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>sungirl129/CYJV1<file_sep>/src/main/java/com/cyj/dao/mybatis/OrderDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.OrderDao; import com.cyj.model.OrderModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class OrderDaoImpl implements OrderDao{ @Resource private SqlSession sqlSession; public int insertOrder(OrderModel model) { return sqlSession.getMapper(OrderDao.class).insertOrder(model); } public List<OrderModel> getAllOrderByState(int state) { return sqlSession.getMapper(OrderDao.class).getAllOrderByState(0); } public List<OrderModel> getOnePageOrderByState(@Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(OrderDao.class).getOnePageOrderByState(state, offset, pageSize); } public OrderModel findModelById(int id) { return sqlSession.getMapper(OrderDao.class).findModelById(id); } public int updateAcceptNumber(@Param("acceptNumber")int acceptNumber,@Param("id")int id) { return sqlSession.getMapper(OrderDao.class).updateAcceptNumber(acceptNumber,id); } public int updatePayedMoney(@Param("payedMoney") double payedMoney, @Param("id") int id) { return sqlSession.getMapper(OrderDao.class).updatePayedMoney(payedMoney, id); } public int updateState(@Param("state") int state, @Param("id") int id) { return sqlSession.getMapper(OrderDao.class).updateState(state, id); } public OrderModel findModelByApplicationId(int applicationId) { return sqlSession.getMapper(OrderDao.class).findModelByApplicationId(applicationId); } public List<OrderModel> getItemBySupplierIdAndState(@Param("supplierId") int supplierId, @Param("state") int state) { return sqlSession.getMapper(OrderDao.class).getItemBySupplierIdAndState(supplierId, state); } @Override public List<OrderModel> getConditionItemBySupplierIdAndState(@Param("supplierId") int supplierId, @Param("goodsId") int goodsId, @Param("state") int state) { return sqlSession.getMapper(OrderDao.class).getConditionItemBySupplierIdAndState(supplierId, goodsId, state); } @Override public List<OrderModel> getOnePageOrderBySupplierIdandState(@Param("supplierId") int supplierId, @Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(OrderDao.class).getOnePageOrderBySupplierIdandState(supplierId, state, offset, pageSize); } @Override public List<OrderModel> getOnePageConditionOrderBySupplierIdandState(@Param("supplierId") int supplierId, @Param("goodsId") int goodsId, @Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(OrderDao.class).getOnePageConditionOrderBySupplierIdandState(supplierId, goodsId, state, offset, pageSize); } @Override public int updateReturnedNumber(@Param("returnedNumber") int returnedNumber, @Param("id") int id) { return sqlSession.getMapper(OrderDao.class).updateReturnedNumber(returnedNumber, id); } } <file_sep>/src/main/java/com/cyj/dao/mybatis/AdminDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.AdminDao; import com.cyj.model.AdminModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; /** * Created by Administrator on 2017/3/31. */ @Repository public class AdminDaoImpl implements AdminDao{ @Resource private SqlSession sqlSession; public AdminModel findModelById(int id) { return sqlSession.getMapper(AdminDao.class).findModelById(id); } public AdminModel findModelByNT(String NT) { return sqlSession.getMapper(AdminDao.class).findModelByNT(NT); } public int updatePassword(@Param("password") String password, @Param("NT") String NT) { return sqlSession.getMapper(AdminDao.class).updatePassword(password, NT); } } <file_sep>/src/main/java/com/cyj/model/OrderModel.java package com.cyj.model; import java.sql.Timestamp; /** * Created by Administrator on 2017/4/5. */ public class OrderModel { private int id; private int applicationId; private int goodsId; private int supplierId; private Timestamp validDate; private int acceptNumber; private int returnedNumber; private double payedMoney; private int orderState; public int getReturnedNumber() { return returnedNumber; } public void setReturnedNumber(int returnedNumber) { this.returnedNumber = returnedNumber; } public int getGoodsId() { return goodsId; } public void setGoodsId(int goodsId) { this.goodsId = goodsId; } public int getSupplierId() { return supplierId; } public void setSupplierId(int supplierId) { this.supplierId = supplierId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getApplicationId() { return applicationId; } public void setApplicationId(int applicationId) { this.applicationId = applicationId; } public Timestamp getValidDate() { return validDate; } public void setValidDate(Timestamp validDate) { this.validDate = validDate; } public int getAcceptNumber() { return acceptNumber; } public void setAcceptNumber(int acceptNumber) { this.acceptNumber = acceptNumber; } public double getPayedMoney() { return payedMoney; } public void setPayedMoney(double payedMoney) { this.payedMoney = payedMoney; } public int getOrderState() { return orderState; } public void setOrderState(int orderState) { this.orderState = orderState; } } <file_sep>/src/test/com/cyj/service/SupplierServiceTest.java package com.cyj.service; import com.cyj.model.SupplierModel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * Created by Administrator on 2017/4/5. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class SupplierServiceTest { @Resource private SupplierService supplierService; @Test public void insertSupplier() throws Exception { SupplierModel model = new SupplierModel(); model.setCorporation("1"); model.setAddress("js1"); model.setName("cyj1"); model.setTel("111"); model.setEmail("<EMAIL>"); model.setUsername("1"); model.setPassword("1"); model.setCredit(1); boolean flag = supplierService.insertSupplier(model); System.out.println(flag); } }<file_sep>/src/main/java/com/cyj/excel/readme.md ## Excel 导入导出说明 *https://poi.apache.org/* ### SimpleImportStatus SimpleImportStatus是一个模板类,用于保存数据导入的结果: - boolean success 导入是否成功 - int totalCount 导入数据的总数 - int successCount 导入数据成功数 - int failCount 导入数据失败数 - List<T> batchAddList 导入的数据 - List<String> msg 导入时信息 - String errorMsg 错误信息,success为true时为空 ### SheetRowConversion SheetRowConversion是一个接口,导入导出的model需要实现这个接口 ``` java public interface SheetRowConversion { SheetRowConversion convertToModel(Row row); Row convertToRow(Row row); } ``` 例子: ``` java public class Stock implements SheetRowConversion { public static final String[] HEADER = new String[]{"名称","单位", "规格","备注","现有库存","最大库存","最小库存"}; private StockModel stockModel; private GoodsModel goodsModel; public StockModel getStockModel() { return stockModel; } public void setStockModel(StockModel stockModel) { this.stockModel = stockModel; } public GoodsModel getGoodsModel() { return goodsModel; } public void setGoodsModel(GoodsModel goodsModel) { this.goodsModel = goodsModel; } @Override public String toString() { return "Stock{" + "stockModel=" + stockModel + ", goodsModel=" + goodsModel + '}'; } @Override public SheetRowConversion convertToModel(Row row) { return null; } @Override public Row convertToRow(Row row) { Cell gnameCell = row.createCell(0); gnameCell.setCellValue(this.goodsModel.getGname()); Cell unitCell = row.createCell(1); unitCell.setCellValue(this.goodsModel.getUnit()); Cell specCell = row.createCell(2); specCell.setCellValue(this.goodsModel.getSpec()); Cell noteCell = row.createCell(3); noteCell.setCellValue(this.goodsModel.getNote()); this.stockModel.getNowNumber(); Cell nowCell = row.createCell(4); nowCell.setCellValue(this.stockModel.getNowNumber()); Cell minCell = row.createCell(5); minCell.setCellValue(this.stockModel.getMinStore()); Cell maxCell = row.createCell(6); maxCell.setCellValue(this.stockModel.getMaxStore()); return row; } } ``` ### SheetHandler SheetHandler是最主要的一个类,负责实际的导入导出,有以下两个函数: - public static <T extends SheetRowConversion> SimpleImportStatus<T> importSheet(File file,Class clazz,boolean isHeader) 导入函数,参数为(导出的文件名、转化的类的Class,是否有头部),其中文件兼容.xls(2003excel版本) 、.xls(2007excel版本); clazz为T的类类型,需要实现SheetRowConversion接口; 函数遍历表格的所有行,利用反射实例化具体的类T: ``` java T t = (T) clazz.newInstance(); t.convertToModel(row); ``` 将结果存放在SimpleImportStatus实例中。 - public static <T extends SheetRowConversion> void exportSheet(File file,List<String>header,List<T>data) 导出函数,参数为导出后的文件名,表格头部,以及数据。T需要实现SheetRowConversion接口; <file_sep>/src/main/java/com/cyj/dao/mybatis/ApplicationDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.ApplicationDao; import com.cyj.model.ApplicationModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class ApplicationDaoImpl implements ApplicationDao{ @Resource private SqlSession sqlSession; public List<ApplicationModel> getApplicationTotalCountByValidAndState(@Param("valid") int valid, @Param("state") int state) { return sqlSession.getMapper(ApplicationDao.class).getApplicationTotalCountByValidAndState(valid, state); } public List<ApplicationModel> getOnePageUncheckedApplication(@Param("valid")int valid, @Param("state")int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(ApplicationDao.class).getOnePageUncheckedApplication(valid, state, offset, pageSize); } public int setValid(@Param("valid")int valid, @Param("id")int id) { return sqlSession.getMapper(ApplicationDao.class).setValid(valid, id); } public ApplicationModel findModelById(int id) { return sqlSession.getMapper(ApplicationDao.class).findModelById(id); } public int insertItem(ApplicationModel applicationModel) { return sqlSession.getMapper(ApplicationDao.class).insertItem(applicationModel); } public List<ApplicationModel> viewMyApplicationByState(@Param("supplierId") int supplierId, @Param("state") int state) { return sqlSession.getMapper(ApplicationDao.class).viewMyApplicationByState(supplierId, state); } @Override public List<ApplicationModel> viewMyApplicationByStateValid(@Param("supplierId") int supplierId, @Param("state") int state, @Param("valid") int valid) { return sqlSession.getMapper(ApplicationDao.class).viewMyApplicationByStateValid(supplierId, state, valid); } public List<ApplicationModel> viewOnePageMyApplicationByState(@Param("supplierId") int supplierId, @Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(ApplicationDao.class).viewOnePageMyApplicationByState(supplierId, state, offset, pageSize); } public List<ApplicationModel> getItemBySupplierIdAndValid(@Param("supplierId") int supplierId, @Param("valid") int valid) { return sqlSession.getMapper(ApplicationDao.class).getItemBySupplierIdAndValid(supplierId, valid); } @Override public List<ApplicationModel> viewOnePageMyApplicationByValid(@Param("supplierId") int supplierId, @Param("valid") int valid, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(ApplicationDao.class).viewOnePageMyApplicationByValid(supplierId, valid, offset, pageSize); } } <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>com.cyj.spring</groupId> <artifactId>Springmvc</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Springmvc Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jfree</groupId> <artifactId>jfreechart</artifactId> <version>1.0.13</version> </dependency> <dependency> <groupId>jfree</groupId> <artifactId>jcommon</artifactId> <version>1.0.16</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.16</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <!--<dependency>--> <!--<groupId>org.python</groupId>--> <!--<artifactId>jython</artifactId>--> <!--<version>2.7.0</version>--> <!--</dependency>--> <dependency> <groupId>gov.nist.math</groupId> <artifactId>jama</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.jdmp</groupId> <artifactId>jdmp-core</artifactId> <version>0.3.0</version> </dependency> <dependency> <groupId>org.jdmp</groupId> <artifactId>jdmp-gui</artifactId> <version>0.3.0</version> </dependency> </dependencies> <build> <finalName>Springmvc</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> <properties> <servlet.version>3.1.0</servlet.version> <jsp.version>2.2.1-b03</jsp.version> </properties> </project> <file_sep>/src/test/com/cyj/service/ScheduleServiceTest.java package com.cyj.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * Created by Administrator on 2017/4/30. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class ScheduleServiceTest { @Resource private ScheduleService scheduleService; @Test public void viewScheduleByGnameYear() throws Exception { // // int[] num = scheduleService.viewScheduleByGnameYear(4,2017); // for(int i = 0; i < 12; i++) { // System.out.println(num[i]); // } } }<file_sep>/src/main/java/com/cyj/service/RejectedService.java package com.cyj.service; import com.cyj.dao.RejectedDao; import com.cyj.model.RejectedModel; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.sql.Timestamp; /** * Created by Administrator on 2017/4/11. */ @Service public class RejectedService { @Resource private RejectedDao rejectedDao; public boolean insertItem(RejectedModel rejectedModel) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); rejectedModel.setReturnedDate(timestamp); return (rejectedDao.insertItem(rejectedModel) == 1); } public boolean insertItem(int orderId, int returnedNumber) { RejectedModel rejectedModel = new RejectedModel(); rejectedModel.setArriveId(orderId); rejectedModel.setReturnedQuantity(returnedNumber); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); rejectedModel.setReturnedDate(timestamp); return insertItem(rejectedModel); } } <file_sep>/src/main/java/com/cyj/service/SupplierService.java package com.cyj.service; import com.cyj.dao.SupplierDao; import com.cyj.model.SupplierModel; import com.cyj.tools.PageUtil; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/3. */ @Service public class SupplierService { @Resource private SupplierDao supplierDao; public SupplierModel findModelById(int id) { return supplierDao.findModelById(id); } public SupplierModel getModelByUsername(String username) { return supplierDao.findModelByUsername(username); } public boolean supplierValid(String username, String password) { SupplierModel supplierModel = supplierDao.findModelByUsername(username); String psw = supplierModel.getPassword(); if(psw.equals(password)) { return true; } else { return false; } } public boolean insertSupplier(SupplierModel supplierModel) { int r = supplierDao.insertSupplier(supplierModel); if(r == 1) { return true; } else { return false; } } public int getSupplierTotalCount() { List<SupplierModel> list = supplierDao.getAllSupplier(); return list.size(); } public PageUtil getOnePageSupplierInfo(int pageNum, int pageSize) { int totalCount = getSupplierTotalCount(); int offset = (pageNum - 1) * pageSize; List<SupplierModel> list = supplierDao.getOnePageSupplier(offset, pageSize); PageUtil page = new PageUtil(pageSize, totalCount); page.setData(list); page.setPageNumber(pageNum); return page; } public boolean modifySupplier(SupplierModel model) { return (supplierDao.updateSupplier(model) == 1); } public boolean deleteSupplier(int id) { return (supplierDao.deleteSupplier(id) == 1); } public boolean changePassword(String password, int id) { return (supplierDao.updatePassword(password, id) == 1); } } <file_sep>/src/test/com/cyj/service/StockServiceTest.java package com.cyj.service; import com.cyj.dao.StockDao; import com.cyj.model.GoodsModel; import com.cyj.model.StockModel; import com.cyj.tools.PageUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.*; /** * Created by Administrator on 2017/4/5. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class StockServiceTest { @Resource private StockService stockService; @Resource private StockDao stockDao; }<file_sep>/src/test/com/cyj/service/OrderServiceTest.java package com.cyj.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * Created by Administrator on 2017/5/15. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class OrderServiceTest { @Resource private OrderService orderService; @Test public void supplyNumberEqualsArriveNumber() throws Exception { boolean flag = orderService.SupplyNumberEqualsArriveNumber(16); System.out.println(flag); } }<file_sep>/src/main/java/com/cyj/tools/PageUtil.java package com.cyj.tools; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/1/15. */ public class PageUtil { // 总页数 private int totalPage; // 总记录(条数) private int totalCount; // 当前页码(1,2,3……) private int pageNumber; // 每页显示条数 private int pageSize; // 当前页数据集合 private List data; // 数据行数 private int rowNum = 0; /** * 构造方法,传递每页条数和总记录数 */ public PageUtil() { } //总记录数和每页显示记录数构造函数 public PageUtil(int pageSize, int totalCount) { this.pageSize = pageSize; this.totalCount = totalCount; if (this.totalCount % this.pageSize == 0) { // 计算总页数 this.totalPage = this.totalCount / this.pageSize; } else { this.totalPage = this.totalCount / this.pageSize + 1; } } public PageUtil(List list,int pageSize,int pageNum,int rowNum){ this.totalCount = list.size(); this.pageSize = pageSize; this.pageNumber = pageNum; this.totalPage = this.totalCount / this.pageSize; if(this.totalCount%this.pageSize!=0) this.totalPage++; int begin = Math.max(0,(pageNum-1)*pageSize); int end = Math.min(totalCount,pageNum*pageSize); this.data = list.subList(begin,end); this.setRowNum(rowNum); } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List getData() { return data; } public void setData(List data) { if(rowNum!=0) this.data = getRowList(data,rowNum); else this.data = data; } public void setRowNum(int rowNum) { this.rowNum = rowNum; if(this.data != null && this.rowNum != 0) this.data = getRowList(data,rowNum); } public static List<List<?> > getRowList(List<?> list,int rowNum){ List<List<?>> rowList = new ArrayList<List<?>>(); for(int i = 0,j = rowNum; i < list.size(); i += rowNum, j += rowNum){ if(j > list.size()) { j = list.size(); } rowList.add(list.subList(i,j)); } return rowList; } public int getRowNum() { return rowNum; } } <file_sep>/src/main/java/com/cyj/model/StatisticsModel.java package com.cyj.model; /** * Created by Administrator on 2017/5/7. */ public class StatisticsModel { private int id; private int goodsId; private int year; private int month; private int purchaseNumber; private int applyNumber; private int state; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getGoodsId() { return goodsId; } public void setGoodsId(int goodsId) { this.goodsId = goodsId; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getPurchaseNumber() { return purchaseNumber; } public void setPurchaseNumber(int purchaseNumber) { this.purchaseNumber = purchaseNumber; } public int getApplyNumber() { return applyNumber; } public void setApplyNumber(int applyNumber) { this.applyNumber = applyNumber; } public int getState() { return state; } public void setState(int state) { this.state = state; } } <file_sep>/src/main/java/com/cyj/dao/mybatis/StatisticsDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.StatisticsDao; import com.cyj.model.StatisticsModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/5/7. */ @Repository public class StatisticsDaoImpl implements StatisticsDao{ @Resource private SqlSession sqlSession; public StatisticsModel findModelById(int id) { return sqlSession.getMapper(StatisticsDao.class).findModelById(id); } public int insertItem(StatisticsModel model) { return sqlSession.getMapper(StatisticsDao.class).insertItem(model); } public StatisticsModel findModelByGoodsIdAndTime(@Param("gid") int gid, @Param("year") int year, @Param("month") int month) { return sqlSession.getMapper(StatisticsDao.class).findModelByGoodsIdAndTime(gid, year, month); } public int updatePurchaseNumber(@Param("purchaseNumber") int purchaseNumber, @Param("id") int id) { return sqlSession.getMapper(StatisticsDao.class).updatePurchaseNumber(purchaseNumber, id); } public int updateApplyNumber(@Param("applyNumber") int applyNumber, @Param("id") int id) { return sqlSession.getMapper(StatisticsDao.class).updateApplyNumber(applyNumber, id); } public List<StatisticsModel> getModelsByGidAndYear(@Param("gid") int gid, @Param("year") int year) { return sqlSession.getMapper(StatisticsDao.class).getModelsByGidAndYear(gid, year); } } <file_sep>/src/main/java/com/cyj/dao/ExchangeDao.java package com.cyj.dao; import com.cyj.model.ExchangeModel; /** * Created by Administrator on 2017/5/12. */ public interface ExchangeDao { int insertItem(ExchangeModel exchangeModel); } <file_sep>/src/main/java/com/cyj/dao/ScheduleDao.java package com.cyj.dao; import com.cyj.model.ScheduleModel; import org.apache.ibatis.annotations.Param; import java.sql.Timestamp; import java.util.List; /** * Created by Administrator on 2017/4/8. */ public interface ScheduleDao { ScheduleModel getUnpublishedModelByGoodsId(int id); int updateBuyNumber(@Param("buyNumber") int buyNumber, @Param("timestamp")Timestamp timestamp, @Param("id")int id); ScheduleModel findModelById(int id); int insertScheduleModel(ScheduleModel scheduleModel); List<ScheduleModel> getUnpublishScheduleTotalCount(@Param("isPublish")int isPublish, @Param("state")int state); List<ScheduleModel> getOnePageUnpublish(@Param("isPublish") int isPublish, @Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize); int publishChangeScheduleState(@Param("scheduleId")int scheduleId); int addPublishDate(@Param("publishDate")Timestamp publishDate, @Param("id")int id); int cancelPublish(int scheduleId); List<ScheduleModel> viewScheduleByGnameYear(@Param("goodsId") int goodsId, @Param("year1")int year1); } <file_sep>/src/main/java/com/cyj/model/ArriveModel.java package com.cyj.model; import java.sql.Timestamp; /** * Created by Administrator on 2017/4/5. */ public class ArriveModel { private int id; private int orderId; private int arriveNumber; private int goodsState; private int badNumber; private Timestamp arriveDate; private int processWay; private int exchangeNumber; private String strGoodsState; private int returnedNumber; private String strProcessWay; public int getReturnedNumber() { return returnedNumber; } public void setReturnedNumber(int returnedNumber) { this.returnedNumber = returnedNumber; } public String getStrProcessWay() { return strProcessWay; } public void setStrProcessWay(String strProcessWay) { this.strProcessWay = strProcessWay; } public String getStrGoodsState() { return strGoodsState; } public void setStrGoodsState(String strGoodsState) { this.strGoodsState = strGoodsState; } public int getProcessWay() { return processWay; } public void setProcessWay(int processWay) { this.processWay = processWay; } public int getExchangeNumber() { return exchangeNumber; } public void setExchangeNumber(int exchangeNumber) { this.exchangeNumber = exchangeNumber; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getArriveNumber() { return arriveNumber; } public void setArriveNumber(int arriveNumber) { this.arriveNumber = arriveNumber; } public int getGoodsState() { return goodsState; } public void setGoodsState(int goodsState) { this.goodsState = goodsState; } public int getBadNumber() { return badNumber; } public void setBadNumber(int badNumber) { this.badNumber = badNumber; } public Timestamp getArriveDate() { return arriveDate; } public void setArriveDate(Timestamp arriveDate) { this.arriveDate = arriveDate; } } <file_sep>/src/main/java/com/cyj/excel/SheetHandler.java package com.cyj.excel; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SheetHandler { /** * @Param file 导入的文件 * @Param clazz T 的 class * @Param isHeader 是否有头部 * */ public static <T extends SheetRowConversion> SimpleImportStatus<T> importSheet(File file,Class clazz,boolean isHeader) throws IOException, InvalidFormatException { SimpleImportStatus<T> simpleImportStatus = new SimpleImportStatus<T>(); List<T> batchAddList = new ArrayList<T>(); List<String> msg = new ArrayList<>(); int successCount = 0; int errorCount = 0; int totalCount = 0; try { Workbook workbook = WorkbookFactory.create(file); Sheet sheet = workbook.getSheetAt(0); totalCount = sheet.getLastRowNum(); int begin = sheet.getFirstRowNum(); if(isHeader) begin += 1; for (int i = begin; i <= sheet.getLastRowNum(); i++) { try { Row row = sheet.getRow(i); T t = (T) clazz.newInstance(); t.convertToModel(row); batchAddList.add(t); successCount++; msg.add("第"+i+"条数据导入成功:"+t.toString()); }catch (Exception e){ e.printStackTrace(); msg.add("第"+i+"条数据导入出错:"+e.getMessage()); errorCount++; } } simpleImportStatus.setTotalCount(totalCount); simpleImportStatus.setBatchAddList(batchAddList); simpleImportStatus.setFailCount(errorCount); simpleImportStatus.setSuccessCount(successCount); simpleImportStatus.setMsg(msg); simpleImportStatus.setSuccess(true); } catch (Exception e) { e.printStackTrace(); simpleImportStatus.setErrorMsg("系统出错:"+e.getMessage()); simpleImportStatus.setSuccess(false); } return simpleImportStatus; } public static <T extends SheetRowConversion> void exportSheet(File file,List<String>header,List<T>data) throws Exception { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(); Row headerRow = sheet.createRow(0); headerRow = setDefaultHeaderRow(workbook,headerRow,header); CellStyle cellStyle = getDefaultBodyStyle(workbook); if(data!=null&&data.size()!=0){ for(int i=0;i<data.size();i++){ Row row = sheet.createRow(i+1); row.setRowStyle(cellStyle); T t = data.get(i); row = t.convertToRow(row); } } try(FileOutputStream fileOutputStream = new FileOutputStream(file)){ workbook.write(fileOutputStream); } } public static CellStyle getDefaultBodyStyle(Workbook workbook){ CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderLeft(BorderStyle.THIN); return cellStyle; } public static CellStyle getDefaultBodyDateStyle(Workbook workbook){ CellStyle cellStyle = getDefaultBodyStyle(workbook); CreationHelper createHelper = workbook.getCreationHelper(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm")); return cellStyle; } private static Row setDefaultHeaderRow(Workbook workbook,Row headerRow,List<String>header) { CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); cellStyle.setFillBackgroundColor((short) 10); cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setBorderLeft(BorderStyle.THIN); for(int i=0;i<header.size();i++){ Cell cell = headerRow.createCell(i); cell.setCellValue(header.get(i)); cell.setCellStyle(cellStyle); } return headerRow; } public static String getStringValueFromCell(Cell cell){ if(cell==null) return ""; switch (cell.getCellType()){ case Cell.CELL_TYPE_BLANK: return ""; case Cell.CELL_TYPE_BOOLEAN:return String.valueOf(cell.getBooleanCellValue()); case Cell.CELL_TYPE_ERROR: return ""; case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_FORMULA:return cell.getCellFormula(); case Cell.CELL_TYPE_NUMERIC:return String.valueOf(cell.getNumericCellValue()); default: return ""; } } public static Timestamp getTimestampValueFromCell(Cell cell){ try{ Date value = cell.getDateCellValue(); return new Timestamp(value.getTime()); }catch(Exception e){ e.printStackTrace(); return null; } } public static double getNumericValueFromCell(Cell cell){ try { double a = cell.getNumericCellValue(); return (int) a; }catch (Exception e){ e.getMessage(); return 0; } } } <file_sep>/src/main/java/com/cyj/dao/mybatis/PayDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.PayDao; import com.cyj.model.PayModel; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class PayDaoImpl implements PayDao{ @Resource private SqlSession sqlSession; public List<PayModel> viewPayInfoByOrderId(int orderId) { return sqlSession.getMapper(PayDao.class).viewPayInfoByOrderId(orderId); } public int insertItem(PayModel payModel) { return sqlSession.getMapper(PayDao.class).insertItem(payModel); } } <file_sep>/src/main/java/com/cyj/dao/ApplicationDao.java package com.cyj.dao; import com.cyj.model.ApplicationModel; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by Administrator on 2017/4/8. */ public interface ApplicationDao { List<ApplicationModel> getApplicationTotalCountByValidAndState(@Param("valid")int valid, @Param("state")int state); List<ApplicationModel> getOnePageUncheckedApplication(@Param("valid")int valid, @Param("state")int state, @Param("offset")int offset, @Param("pageSize")int pageSize); int setValid(@Param("valid")int valid, @Param("id")int id); ApplicationModel findModelById(int id); int insertItem(ApplicationModel applicationModel); List<ApplicationModel> viewMyApplicationByState(@Param("supplierId")int supplierId, @Param("state")int state); List<ApplicationModel> viewMyApplicationByStateValid(@Param("supplierId")int supplierId, @Param("state")int state, @Param("valid")int valid); List<ApplicationModel> viewOnePageMyApplicationByState(@Param("supplierId")int supplierId, @Param("state")int state, @Param("offset")int offset, @Param("pageSize")int pageSize); List<ApplicationModel> getItemBySupplierIdAndValid(@Param("supplierId") int supplierId, @Param("valid") int valid); List<ApplicationModel> viewOnePageMyApplicationByValid(@Param("supplierId") int supplierId, @Param("valid") int valid, @Param("offset")int offset, @Param("pageSize")int pageSize); } <file_sep>/src/main/java/com/cyj/filter/SupplierFilter.java package com.cyj.filter; import com.cyj.model.SupplierModel; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by Administrator on 2017/3/9. */ public class SupplierFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); // String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); SupplierModel model = (SupplierModel)session.getAttribute("supplier"); if(model == null) { response.sendRedirect( "/"); } else { filterChain.doFilter(servletRequest, servletResponse); } } public void destroy() { } } <file_sep>/src/main/java/com/cyj/service/ExchangeService.java package com.cyj.service; import com.cyj.dao.ExchangeDao; import com.cyj.model.ExchangeModel; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * Created by Administrator on 2017/5/14. */ @Service public class ExchangeService { @Resource private ExchangeDao exchangeDao; public boolean insertItem(ExchangeModel exchangeModel) { return (exchangeDao.insertItem(exchangeModel) == 1); } public boolean insertItem(int orderId, int arriveId, int changeNum) { ExchangeModel exchangeModel = new ExchangeModel(); exchangeModel.setOrderId(orderId); exchangeModel.setArriveId(arriveId); exchangeModel.setExchangeNumber(changeNum); return insertItem(exchangeModel); } } <file_sep>/src/main/java/com/cyj/dao/mybatis/ArriveDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.ArriveDao; import com.cyj.model.ArriveModel; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class ArriveDaoImpl implements ArriveDao{ @Resource private SqlSession sqlSession; public List<ArriveModel> getModelListByOrderId(int orderId) { return sqlSession.getMapper(ArriveDao.class).getModelListByOrderId(orderId); } public int insertArriveItem(ArriveModel arriveModel) { return sqlSession.getMapper(ArriveDao.class).insertArriveItem(arriveModel); } } <file_sep>/src/main/java/com/cyj/model/ScheduleModel.java package com.cyj.model; import com.cyj.excel.SheetHandler; import com.cyj.excel.SheetRowConversion; import org.apache.poi.ss.usermodel.Row; import java.sql.Timestamp; /** * Created by Administrator on 2017/4/5. */ public class ScheduleModel implements SheetRowConversion { public static final String[] HEADER = new String[]{"名称","数量"}; private int id; private int goodsId; private int buyNumber; private int isPublish; private int scheduleState; private Timestamp scheduleDate; private Timestamp publishDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getGoodsId() { return goodsId; } public void setGoodsId(int goodsId) { this.goodsId = goodsId; } public int getBuyNumber() { return buyNumber; } public void setBuyNumber(int buyNumber) { this.buyNumber = buyNumber; } public int getIsPublish() { return isPublish; } public void setIsPublish(int isPublish) { this.isPublish = isPublish; } public int getScheduleState() { return scheduleState; } public void setScheduleState(int scheduleState) { this.scheduleState = scheduleState; } public Timestamp getScheduleDate() { return scheduleDate; } public void setScheduleDate(Timestamp scheduleDate) { this.scheduleDate = scheduleDate; } public Timestamp getPublishDate() { return publishDate; } public void setPublishDate(Timestamp publishDate) { this.publishDate = publishDate; } /** * 导入:商品名称 * */ private String gname; public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } /** * 导入 * */ @Override public SheetRowConversion convertToModel(Row row) { this.gname = SheetHandler.getStringValueFromCell(row.getCell(0)); this.buyNumber = (int) SheetHandler.getNumericValueFromCell(row.getCell(1)); return this; } @Override public Row convertToRow(Row row) { return null; } } <file_sep>/src/main/java/com/cyj/dao/SupplierDao.java package com.cyj.dao; import com.cyj.model.SupplierModel; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by Administrator on 2017/4/3. */ public interface SupplierDao { SupplierModel findModelById(int id); SupplierModel findModelByUsername(String username); int insertSupplier(SupplierModel supplierModel); List<SupplierModel> getAllSupplier(); List<SupplierModel> getOnePageSupplier(@Param("offset")int offset,@Param("pageSize")int pageSize); int updateSupplier(SupplierModel supplierModel); int deleteSupplier(int id); int updatePassword(@Param("password") String password, @Param("id") int id); } <file_sep>/src/main/java/com/cyj/model/ApplicationModel.java package com.cyj.model; import java.sql.Timestamp; /** * Created by Administrator on 2017/4/5. */ public class ApplicationModel { private int id; private int publishId; private int scheduleId; private int supplierId; private int goodsId; private int supplyNumber; private double price; private int valid; private int applicationState; private Timestamp applicationDate; private String strValid; public String getStrValid() { return strValid; } public void setStrValid(String strValid) { this.strValid = strValid; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPublishId() { return publishId; } public void setPublishId(int publishId) { this.publishId = publishId; } public int getScheduleId() { return scheduleId; } public void setScheduleId(int scheduleId) { this.scheduleId = scheduleId; } public int getSupplierId() { return supplierId; } public void setSupplierId(int supplierId) { this.supplierId = supplierId; } public int getGoodsId() { return goodsId; } public void setGoodsId(int goodsId) { this.goodsId = goodsId; } public int getSupplyNumber() { return supplyNumber; } public void setSupplyNumber(int supplyNumber) { this.supplyNumber = supplyNumber; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getValid() { return valid; } public void setValid(int valid) { this.valid = valid; } public int getApplicationState() { return applicationState; } public void setApplicationState(int applicationState) { this.applicationState = applicationState; } public Timestamp getApplicationDate() { return applicationDate; } public void setApplicationDate(Timestamp applicationDate) { this.applicationDate = applicationDate; } } <file_sep>/src/main/java/com/cyj/dao/mybatis/PublishDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.PublishDao; import com.cyj.model.PublishModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class PublishDaoImpl implements PublishDao{ @Resource private SqlSession sqlSession; public PublishModel findModelById(int id) { return sqlSession.getMapper(PublishDao.class).findModelById(id); } public PublishModel getPublishModelByGoodsId(int id) { return sqlSession.getMapper(PublishDao.class).getPublishModelByGoodsId(id); } public int changePublishNumber(PublishModel model) { return sqlSession.getMapper(PublishDao.class).changePublishNumber(model); } public int insertPublishItem(PublishModel model) { return sqlSession.getMapper(PublishDao.class).insertPublishItem(model); } public List<PublishModel> getPublishTotalCountByState(int state) { return sqlSession.getMapper(PublishDao.class).getPublishTotalCountByState(state); } public List<PublishModel> getOnePagePublishByState(@Param("state") int state, @Param("offset") int offset, @Param("pageSize") int pageSize) { return sqlSession.getMapper(PublishDao.class).getOnePagePublishByState(state, offset, pageSize); } public int cacelPublish(int pid) { return sqlSession.getMapper(PublishDao.class).cacelPublish(pid); } public int changeApplyNumber(@Param("applyNumber") int applyNumber, @Param("id") int id) { return sqlSession.getMapper(PublishDao.class).changeApplyNumber(applyNumber, id); } public int changeState(@Param("state") int state, @Param("id") int id) { return sqlSession.getMapper(PublishDao.class).changeState(state, id); } public int deleteItem(int id) { return sqlSession.getMapper(PublishDao.class).deleteItem(id); } } <file_sep>/src/main/java/com/cyj/dao/mybatis/ScheduleDaoImpl.java package com.cyj.dao.mybatis; import com.cyj.dao.ScheduleDao; import com.cyj.model.ScheduleModel; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.Timestamp; import java.util.List; /** * Created by Administrator on 2017/4/8. */ @Repository public class ScheduleDaoImpl implements ScheduleDao{ @Resource private SqlSession sqlSession; public ScheduleModel getUnpublishedModelByGoodsId(int id) { return sqlSession.getMapper(ScheduleDao.class).getUnpublishedModelByGoodsId(id); } public int updateBuyNumber(@Param("buyNumber") int buyNumber, @Param("timestamp") Timestamp timestamp, @Param("id") int id) { return sqlSession.getMapper(ScheduleDao.class).updateBuyNumber(buyNumber,timestamp,id); } public ScheduleModel findModelById(int id) { return sqlSession.getMapper(ScheduleDao.class).findModelById(id); } public int insertScheduleModel(ScheduleModel scheduleModel) { return sqlSession.getMapper(ScheduleDao.class).insertScheduleModel(scheduleModel); } public List<ScheduleModel> getUnpublishScheduleTotalCount(@Param("isPublish")int isPublish, @Param("state")int state) { return sqlSession.getMapper(ScheduleDao.class).getUnpublishScheduleTotalCount(isPublish, state); } public List<ScheduleModel> getOnePageUnpublish(@Param("isPublish") int isPublish, @Param("state") int state, @Param("offset")int offset, @Param("pageSize")int pageSize) { return sqlSession.getMapper(ScheduleDao.class).getOnePageUnpublish(isPublish, state, offset, pageSize); } public int publishChangeScheduleState(@Param("scheduleId") int scheduleId) { return sqlSession.getMapper(ScheduleDao.class).publishChangeScheduleState(scheduleId); } public int addPublishDate(@Param("publishDate") Timestamp publishDate, @Param("id") int id) { return sqlSession.getMapper(ScheduleDao.class).addPublishDate(publishDate, id); } public int cancelPublish(int scheduleId) { return sqlSession.getMapper(ScheduleDao.class).cancelPublish(scheduleId); } public List<ScheduleModel> viewScheduleByGnameYear(@Param("goodsId") int goodsId, @Param("year1") int year1) { return sqlSession.getMapper(ScheduleDao.class).viewScheduleByGnameYear(goodsId, year1); } } <file_sep>/src/main/java/com/cyj/service/StockService.java package com.cyj.service; import com.cyj.dao.StockDao; import com.cyj.model.GoodsModel; import com.cyj.model.StockModel; import com.cyj.model.show.Stock; import com.cyj.tools.PageUtil; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.*; /** * Created by Administrator on 2017/4/5. */ @Service public class StockService { @Resource private StockDao stockDao; //得到货物类别数量 public int getTotalGoodsNumber() { List<GoodsModel> TotalList = stockDao.getStockTotalItem(); int totalCount = TotalList.size(); return totalCount; } //显示一页货物信息 public List<GoodsModel> getOnePageGoodsInfo(int pageNum, int pageSize) { int offset = (pageNum - 1) * pageSize; return stockDao.getOnePageGoodsInfo(offset, pageSize); } public StockModel findStockModelByGoodsId(int id) { return stockDao.findStockModelByGoodsId(id); } public GoodsModel findGoodsModelByGoodsId(int id) { return stockDao.findGoodsModelByGoodsId(id); } public int findGoodsIdByGname(String name) { GoodsModel goodsModel = stockDao.findGoodsModelByGname(name); return goodsModel.getId(); } public List<Stock> search(String gname,String unit,int stockL,int stockR){ if(gname!=null&&gname.equals("")) gname = null; if(unit!=null&&unit.equals("")) unit = null; return stockDao.search(unit,gname,stockL,stockR); } }
aab17d1e547be99029828ec312248826529583cd
[ "Markdown", "Java", "Maven POM" ]
30
Java
sungirl129/CYJV1
5e69c9d568c41cb93fc5c6a67ad745a990da8db8
48f3f80dec5f00e9e54f1ac6550b8cbc59ae3ed4
refs/heads/master
<repo_name>ajay399/color<file_sep>/script.js console.log("welcome To Color Picker, I am <NAME>!"); const myFunction=()=>{ var header = document.getElementById("myHeader"); var sticky = header.offsetTop; if (window.pageYOffset > sticky) { header.classList.add("sticky"); } else { header.classList.remove("sticky"); } } const CopyCode=(text)=>{ var tempInput = document.createElement("input"); tempInput.style = "position: absolute; left: -1000px; top: -1000px"; tempInput.value = text.trim(); document.body.appendChild(tempInput); tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); } window.onscroll = ()=> {myFunction()}; var colorName = document.getElementsByClassName("colorName"); for (var i = 0 ; i < colorName.length; i++) { colorName[i].addEventListener("click", function() { var text=this.innerHTML; var NewText="Copied!"; CopyCode(text); this.innerHTML=NewText; var oldText=this; setTimeout(function(){ oldText.innerHTML=text; }, 3000); }, false); }
7c8c330bc2a471e58c2f2fdf0646f6b6fe6a40c9
[ "JavaScript" ]
1
JavaScript
ajay399/color
ad69668d9b6b1aa71daf751924ce9a4efa20b1a8
185d02e4ff6fd6d23ce81d4bb80d705d327f186e
refs/heads/main
<repo_name>peteturnham/leaflet-challenge<file_sep>/static/js/config.js // API key const API_KEY = "<KEY>"; <file_sep>/static/js/logic.js //initial map var map = L.map("mapid", { center: [37.09, -95.71], zoom: 5 }); // Create the tile layer that will be the background of our map var lightmap = L.tileLayer("https://api.mapbox.com/styles/v1/mapbox/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", { attribution: "Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>", maxZoom: 18, id: "light-v10", accessToken: API_KEY }); // Add our 'lightmap' tile layer to the map lightmap.addTo(map); // Create a legend to display information about our map var info = L.control({ position: "bottomright" }); // When the layer control is added, insert a div with the class of "legend" info.onAdd = function() { var div = L.DomUtil.create("div", "legend"); var limits = ['-10-10', '10-10', '30-50', '50-70', '70-90', '90+']; var colors = ["green", 'yellowgreen', 'gold', 'orange', 'salmon', 'red']; var labels = []; var legendInfo = "<h1>Earthquake Legend Key</h1>" + "<div> color scale = depth of earthquake"; div.innerHTML = legendInfo; limits.forEach(function(limit, index) { labels.push("<li style=\"background-color: " + colors[index] + "\"></li>"); }); div.innerHTML += "<ul>" + labels.join("") + "</ul>"; return div; }; // Add the info legend to the map info.addTo(map); //------------------------------------------------------------------------------------------------------ const url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson' d3.json(url).then(function(data) { for (var i = 0; i < data.features.length; i++) { // array of objects var feature = data.features[i]; var mag = [feature.properties.mag] var depth = [feature.geometry.coordinates[2]] console.log(mag); // conditional for depth var color = ""; if (depth > -10 && depth < 10) { color = "green"; } else if (depth >= 10 && depth < 30) { color = "yellowgreen"; } else if (depth >= 30 && depth < 50) { color = "gold"; } else if (depth >= 50 && depth < 70) { color = "orange"; } else if (depth >= 70 && depth < 90) { color = "salmon"; } else { color = "red"; } L.circle([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], { Opacity: 0.5, fillOpacity: 0.75, radius: mag * 2500, color: color, fillColor: color }).bindPopup("<h3>" + feature.properties.place + "</h3><hr><p>" + new Date(feature.properties.time) + "</p>").addTo(map); }})
3914aefb42c8bbeadd347a890f673fc76480ca51
[ "JavaScript" ]
2
JavaScript
peteturnham/leaflet-challenge
42ef682a992d459a403c97a1b915084873f3dec6
4efb0df37f61bc1cdb51cba942f0659e1e207bde
refs/heads/master
<file_sep>import java.io.*; import java.util.Scanner; public class UseThreshold { private String fileName; private double realNumberThreshold; public UseThreshold(){ fileName = "number1.txt"; realNumberThreshold = 5; } public UseThreshold(String fileName,double realNumberThreshold){ this.fileName = fileName; this.realNumberThreshold = realNumberThreshold; } public String getFileName() { return fileName; } public double getRealNumberThreshold() { return realNumberThreshold; } public String setFileName(String fileName) { this.fileName = fileName; return fileName; } public int setRealNumberThreshold(int realNumberThreshold) { this.realNumberThreshold = realNumberThreshold; return realNumberThreshold; } public int getCount() throws IOException { int counter = 0; File file = new File(fileName); Scanner scan = new Scanner(file); while(scan.hasNextDouble()) { if (scan.nextDouble()> realNumberThreshold) { counter++; } } System.out.println(counter); return counter; } public double getSum() throws IOException { double sum = 0; File file = new File(fileName); Scanner scan = new Scanner(file); while(scan.hasNextDouble()) { double kek = scan.nextDouble(); if (kek> realNumberThreshold) { sum = sum + kek; } } System.out.println(sum); return sum; } public double getMax() throws IOException { double max = 0; File file = new File(fileName); Scanner scan = new Scanner(file); while(scan.hasNextDouble()) { double kek = scan.nextDouble(); if (kek> realNumberThreshold && kek>max) { max = kek; } } System.out.println(max); return max; } public String toString() { System.out.println("Filename: " + fileName + "\nThreshold: " + realNumberThreshold); return "Filename: " + fileName + "\nThreshold: " + realNumberThreshold; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File("numbers1.text"); Scanner key = new Scanner(file); while (key.hasNextInt()) System.out.println(key.nextLine()); } } <file_sep># FileReadingTest Java files that read from a text file and check the data inside of it, in this case, numbers
b804e9bedbdd390a63b88e52b19a86c23230ed39
[ "Markdown", "Java" ]
2
Java
SasukeSC/FileReadingTest
9820981062c70d3e1cef7ea47187bb226d1de28b
5bb51d4e87d6a93f081e50e2b74595bd401e3657
refs/heads/master
<repo_name>arpercussion/ov-phonegap-build<file_sep>/src/main/java/com/obscured/phonegap/build/models/App.java package com.obscured.phonegap.build.models; import com.fasterxml.jackson.annotation.JsonProperty; public class App { @JsonProperty("id") private Integer id; @JsonProperty("title") private String title; @JsonProperty("package") private String _package; @JsonProperty("version") private String version; @JsonProperty("build_count") private Integer buildCount; @JsonProperty("private") private Boolean _private; @JsonProperty("phonegap_version") private String phonegapVersion; @JsonProperty("hydrates") private Boolean hydrates; @JsonProperty("share") private Boolean share; @JsonProperty("last_build") private String lastBuild; @JsonProperty("description") private String description; @JsonProperty("repo") private String repo; @JsonProperty("tag") private String tag; @JsonProperty("debug") private Boolean debug; @JsonProperty("head") private String head; @JsonProperty("link") private String link; @JsonProperty("plugins") private String plugins; @JsonProperty("completed") private Boolean completed; @JsonProperty("role") private String role; @JsonProperty("icon") private Icon icon; @JsonProperty("status") private Status status; @JsonProperty("phonegap_versions") private PhonegapVersions phonegapVersions; @JsonProperty("download") private Download download; @JsonProperty("error") private Error error; @JsonProperty("install_url") private String installUrl; @JsonProperty("share_url") private String shareUrl; @JsonProperty("keys") private Keys keys; @JsonProperty("logs") private Logs logs; @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("package") public String getPackage() { return _package; } @JsonProperty("package") public void setPackage(String _package) { this._package = _package; } @JsonProperty("version") public String getVersion() { return version; } @JsonProperty("version") public void setVersion(String version) { this.version = version; } @JsonProperty("build_count") public Integer getBuildCount() { return buildCount; } @JsonProperty("build_count") public void setBuildCount(Integer buildCount) { this.buildCount = buildCount; } @JsonProperty("private") public Boolean getPrivate() { return _private; } @JsonProperty("private") public void setPrivate(Boolean _private) { this._private = _private; } @JsonProperty("phonegap_version") public String getPhonegapVersion() { return phonegapVersion; } @JsonProperty("phonegap_version") public void setPhonegapVersion(String phonegapVersion) { this.phonegapVersion = phonegapVersion; } @JsonProperty("hydrates") public Boolean getHydrates() { return hydrates; } @JsonProperty("hydrates") public void setHydrates(Boolean hydrates) { this.hydrates = hydrates; } @JsonProperty("share") public Boolean getShare() { return share; } @JsonProperty("share") public void setShare(Boolean share) { this.share = share; } @JsonProperty("last_build") public String getLastBuild() { return lastBuild; } @JsonProperty("last_build") public void setLastBuild(String lastBuild) { this.lastBuild = lastBuild; } @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String description) { this.description = description; } @JsonProperty("repo") public String getRepo() { return repo; } @JsonProperty("repo") public void setRepo(String repo) { this.repo = repo; } @JsonProperty("tag") public String getTag() { return tag; } @JsonProperty("tag") public void setTag(String tag) { this.tag = tag; } @JsonProperty("debug") public Boolean getDebug() { return debug; } @JsonProperty("debug") public void setDebug(Boolean debug) { this.debug = debug; } @JsonProperty("head") public String getHead() { return head; } @JsonProperty("head") public void setHead(String head) { this.head = head; } @JsonProperty("link") public String getLink() { return link; } @JsonProperty("link") public void setLink(String link) { this.link = link; } @JsonProperty("plugins") public String getPlugins() { return plugins; } @JsonProperty("plugins") public void setPlugins(String plugins) { this.plugins = plugins; } @JsonProperty("completed") public Boolean getCompleted() { return completed; } @JsonProperty("completed") public void setCompleted(Boolean completed) { this.completed = completed; } @JsonProperty("role") public String getRole() { return role; } @JsonProperty("role") public void setRole(String role) { this.role = role; } @JsonProperty("icon") public Icon getIcon() { return icon; } @JsonProperty("icon") public void setIcon(Icon icon) { this.icon = icon; } @JsonProperty("status") public Status getStatus() { return status; } @JsonProperty("status") public void setStatus(Status status) { this.status = status; } @JsonProperty("phonegap_versions") public PhonegapVersions getPhonegapVersions() { return phonegapVersions; } @JsonProperty("phonegap_versions") public void setPhonegapVersions(PhonegapVersions phonegapVersions) { this.phonegapVersions = phonegapVersions; } @JsonProperty("download") public Download getDownload() { return download; } @JsonProperty("download") public void setDownload(Download download) { this.download = download; } @JsonProperty("error") public Error getError() { return error; } @JsonProperty("error") public void setError(Error error) { this.error = error; } @JsonProperty("install_url") public String getInstallUrl() { return installUrl; } @JsonProperty("install_url") public void setInstallUrl(String installUrl) { this.installUrl = installUrl; } @JsonProperty("share_url") public String getShareUrl() { return shareUrl; } @JsonProperty("share_url") public void setShareUrl(String shareUrl) { this.shareUrl = shareUrl; } @JsonProperty("keys") public Keys getKeys() { return keys; } @JsonProperty("keys") public void setKeys(Keys keys) { this.keys = keys; } @JsonProperty("logs") public Logs getLogs() { return logs; } @JsonProperty("logs") public void setLogs(Logs logs) { this.logs = logs; } } <file_sep>/src/main/java/com/obscured/phonegap/build/common/Utils.java package com.obscured.phonegap.build.common; import java.util.AbstractMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Utils { public static Map<String, String> OptionsToMap(String[] opts) { Map<String, String> map = IntStream.range(0, opts.length / 2) .mapToObj(m -> new AbstractMap.SimpleEntry<>(2 * m, 2 * m + 1)) .collect(Collectors.toMap( k -> opts[k.getKey()], v -> opts[v.getValue()])); return map; } } <file_sep>/src/main/java/com/obscured/phonegap/build/models/PhonegapVersions.java package com.obscured.phonegap.build.models; import com.fasterxml.jackson.annotation.JsonProperty; public class PhonegapVersions { @JsonProperty("android") private String android; @JsonProperty("ios") private String ios; @JsonProperty("winphone") private String winphone; @JsonProperty("windows") private String windows; @JsonProperty("android") public String getAndroid() { return android; } @JsonProperty("android") public void setAndroid(String android) { this.android = android; } @JsonProperty("ios") public String getIos() { return ios; } @JsonProperty("ios") public void setIos(String ios) { this.ios = ios; } @JsonProperty("winphone") public String getWinphone() { return winphone; } @JsonProperty("winphone") public void setWinphone(String winphone) { this.winphone = winphone; } @JsonProperty("windows") public String getWindows() { return windows; } @JsonProperty("windows") public void setWindows(String windows) { this.windows = windows; } } <file_sep>/src/test/java/com/obscured/phonegap/build/CliTest.java package com.obscured.phonegap.build; import org.junit.Test; public class CliTest { @Test public void main() throws Exception { } }<file_sep>/src/main/java/com/obscured/phonegap/build/Cli.java package com.obscured.phonegap.build; import com.obscured.phonegap.build.common.PhonegapAction; import com.obscured.phonegap.build.common.Utils; import com.obscured.phonegap.build.common.Wrapper; import com.obscured.phonegap.build.models.App; import org.apache.commons.cli.*; import java.util.Map; public class Cli { private static Options options; private static CommandLine cmd; public static void main(String[] args) throws Exception { buildOptions(args); processOptions(); } private static void buildOptions(String[] args) throws ParseException { options = new Options(); Option help = Option.builder("h") .longOpt("help") .desc("Print this message") .build(); Option user = Option.builder("u") .hasArg() .longOpt("user") .desc("The username for authorization to the Phonegap Build") .build(); Option password = Option.builder("p") .hasArg() .longOpt("password") .desc("The password for authorization to the Phonegap Build") .build(); Option token = Option.builder("t") .hasArg() .longOpt("token") .desc("The token for authorization to the Phonegap Build") .build(); Option opt = Option.builder("D") .argName("property=value") .hasArgs() .numberOfArgs(2) .valueSeparator('=') .desc("Use value for given property") .build(); options.addOption(help); options.addOption(user); options.addOption(password); options.addOption(token); options.addOption(opt); CommandLineParser parser = new DefaultParser(); cmd = parser.parse(options, args); } private static void processOptions() { if (cmd.hasOption("h")) { printHelp(); } else if (cmd.hasOption("D")) { String[] values = cmd.getOptionValues("D"); Map<String, String> opts = Utils.OptionsToMap(values); opts.put("user", cmd.getOptionValue("u")); opts.put("password", cmd.getOptionValue("p")); handleOptions(opts); } else { System.out.println("No options were supplied"); } } private static void handleOptions(Map<String, String> opts) { // for now only option is update if (opts.containsKey("user") && opts.containsKey("password") && opts.containsKey("id") && opts.containsKey("action") && opts.get("action").equalsIgnoreCase(PhonegapAction.UpdateAppById.toString())) { Wrapper wrapper = new Wrapper(opts.get("user"), opts.get("password")); App app = wrapper.updateRepoApp(opts.get("id")); if (app != null) { System.out.println(String.format("App %s is currently being updated", app.getId())); } else { System.out.println(String.format("App %s was not updated", opts.get("id"))); } } else { System.out.println("Please supply required options. Currently only update action is handled"); } } private static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("cli", options); } } <file_sep>/README.md # ov-phonegap-build phonegap build api
b4b1d5fdfc7f293c6ef71166c39a190895c5260f
[ "Markdown", "Java" ]
6
Java
arpercussion/ov-phonegap-build
941c18547af96cdc5a4903a8d706d1f8d8b17e5e
6a2b93ff5b3586d5b20bb0ee4328d5873583703d
refs/heads/main
<file_sep># Backend MisiónTic 2022 - Proyecto Ciclo 3 Se requiere analizar, diseñar y construir una aplicación de software que permita realizar el seguimiento de las ventas de un producto y/o servicio de IMMAX TECH empresa de tecnologia, creada para este proyecto. Para realizar el seguimiento de las ventas es necesario construir interfaces de usuario que permitan: el ingreso a la aplicación, registro de productos, maestro de productos, registro de venta, maestro de las ventas y maestro de usuarios. En este repositorio se encuentra las distintas configuraciones, imagenes, herramientas y programas empleados para el desarrollo del Backend de la pagina web de IMMAX TECH. --- INTEGRANTES: Profesor: <NAME>. Tutor: <NAME>. Autores: <NAME>. <NAME>. <NAME>. <file_sep>import {ObjectId} from 'mongodb'; import { getDB } from '../../db/db.js'; const queryAllEquipos = async (callback) => { const baseDeDatos = getDB(); await baseDeDatos.collection('Equipos').find({}).limit(50).toArray(callback); }; const crearEquipos = async (datosEquipos, callback) => { if ( Object.keys(datosEquipos).includes('referencia') && Object.keys(datosEquipos).includes('nombre') && Object.keys(datosEquipos).includes('marca') && Object.keys(datosEquipos).includes('modelo') ) { const baseDeDatos = getDB(); // implementar código para crear vehículo en la BD await baseDeDatos.collection('Equipos').insertOne(datosEquipos, callback); } else { return 'error'; } }; const consultarEquipos = async (id, callback) => { const baseDeDatos = getDB(); await baseDeDatos.collection('Equipos').findOne({ _id: new ObjectId(id) }, callback); }; const editarEquipos = async (id, edicion, callback) => { const filtroEquipos = { _id: new ObjectId(id) }; const operacion = { $set: edicion, }; const baseDeDatos = getDB(); await baseDeDatos .collection('Equipos') .findOneAndUpdate(filtroEquipos, operacion, { upsert: true, returnOriginal: true }, callback); }; const eliminarEquipos = async (id, callback) => { const filtroEquipos = { _id: new ObjectId(id) }; const baseDeDatos = getDB(); await baseDeDatos.collection('Equipos').deleteOne(filtroEquipos, callback); }; export { queryAllEquipos, crearEquipos, consultarEquipos, editarEquipos, eliminarEquipos }; const queryAllUsers = async (callback) => { const baseDeDatos = getDB(); console.log('query'); await baseDeDatos.collection('usuario').find({}).limit(50).toArray(callback); }; const crearUsuario = async (datosUsuario, callback) => { const baseDeDatos = getDB(); await baseDeDatos.collection('usuario').insertOne(datosUsuario, callback); }; const consultarUsuario = async (id, callback) => { const baseDeDatos = getDB(); await baseDeDatos.collection('usuario').findOne({ _id: new ObjectId(id) }, callback); }; const editarUsuario = async (id, edicion, callback) => { const filtroUsuario = { _id: new ObjectId(id) }; const operacion = { $set: edicion, }; const baseDeDatos = getDB(); await baseDeDatos .collection('usuario') .findOneAndUpdate(filtroUsuario, operacion, { upsert: true, returnOriginal: true }, callback); }; const eliminarUsuario = async (id, callback) => { const filtroUsuario = { _id: new ObjectId(id) }; const baseDeDatos = getDB(); await baseDeDatos.collection('usuario').deleteOne(filtroUsuario, callback); }; export { queryAllUsers, crearUsuario, consultarUsuario, editarUsuario, eliminarUsuario };
a170d7735ed824146c7d7ec465e268a74b1c2155
[ "Markdown", "JavaScript" ]
2
Markdown
IMMAX-TECH/Backend
33bb65455bfac425bdb8d8951f5bcc82eb905b47
91740bec051f87192b02ff985a3b7abdceae9cb9
refs/heads/master
<file_sep>const NUM_PEOPLE = 100; const INFECTION_DISTANCE = 10; const START_NUM_INFECTED = 5; const PERSON_SIZE = 5; const ITERATIONS_PER_CLICK = 5; const ITERATION_PER_SECOND = 5; const INFECTION_PROBABILITY = 0.2; const SHOW_INFECTION_RING = true; const MAX_MOVEMENT_DISTANCE = 20; const VISUALISE = true; let people = []; let infectionCount = START_NUM_INFECTED; let counter; let jsonOP = {0: START_NUM_INFECTED}; let d = 0; let OP; function setup() { createCanvas(400, 400); for (let i = 0; i < NUM_PEOPLE; i++) { people.push({ x: random(0, width), y: random(0, height), infected: i < START_NUM_INFECTED }); } people[0].infected = true; counter = createDiv(); op = createDiv(); frameRate(ITERATION_PER_SECOND); } function draw() { if (infectionCount != NUM_PEOPLE) { runIter(); if (VISUALISE) { background(220); for (let i = 0; i < NUM_PEOPLE; i++) { fill(255) if (people[i].infected) { if (SHOW_INFECTION_RING) { fill(0,0,0,0); circle(people[i].x, people[i].y, INFECTION_DISTANCE + PERSON_SIZE); } fill(255,0,0); } circle(people[i].x, people[i].y, PERSON_SIZE); } } } counter.html("<h1>" + infectionCount + "</h1>"); op.html("<textarea>" + JSON.stringify(jsonOP) + "</textarea>"); } function runIter() { for (let k = 0; k < ITERATIONS_PER_CLICK; k++) { for (let i = 0; i < NUM_PEOPLE; i++) { people[i].x = min(width, max(0, people[i].x + random(-1 * MAX_MOVEMENT_DISTANCE, MAX_MOVEMENT_DISTANCE))); people[i].y = min(height, max(0, people[i].y + random(-1 * MAX_MOVEMENT_DISTANCE, MAX_MOVEMENT_DISTANCE))); } for (let i = 0; i < NUM_PEOPLE; i++) { for (let j = 0; j < NUM_PEOPLE; j++) { if (i != j) { if (pow(people[i].x - people[j].x, 2) + pow(people[i].y - people[j].y, 2) - 2 * PERSON_SIZE <= pow(INFECTION_DISTANCE, 2)) { if ((people[i].infected || people[j].infected) && Math.round(random(1, 1/INFECTION_PROBABILITY)) == 1) { if (! (people[i].infected && people[j].infected)) { infectionCount += 1; } people[i].infected = true; people[j].infected = true; } } } } } } jsonOP[++d] = infectionCount; }<file_sep># Some interesting projects, often simulations or fun maths
874ffe04cd70ac56139814374885e990d1a73300
[ "JavaScript", "Markdown" ]
2
JavaScript
IlleQuiProgrammat/Small-Projects
7e499947255e1cb61c87fd8238df3879ca61fa45
413c4ff9bf569b954da4794cc422b7704feea263
refs/heads/main
<file_sep>const express = require("express"); const app = express(); const pokemon = require("./models/pokemon.json"); app.get("/", (req, res) => { res.send("Welcome 99 Pokemon"); }); app.get("/:verb/:adj/:noun", (req, res) => { const { verb, adj, noun } = req.params; res.send( `Congratulations on starting a new project called ${verb}-${adj}-${noun}` ); }); app.get("/bugs", (req, res) => { let { number_of_bugs } = req.params; number_of_bugs = 101; res.send( `99 little bugs in the code <br/> 99 little bugs <br/> <a href="/bugs/${number_of_bugs}">Pull one down <br/> Patch it around </a>` ); }); app.get("/bugs/:number_of_bugs", (req, res) => { let { number_of_bugs } = req.params; if (number_of_bugs < 200) { res.send(`${number_of_bugs} little bugs in the code <br/> ${number_of_bugs} little bugs <br/> <a href="/bugs/${ Number(number_of_bugs) + 2 }">Pull one down, patch it around </a>`); } else { res.send(`Too many bugs!! Start over!`); } }); // gives the entire object for the API app.get("/pokemon", (req, res) => { res.json(pokemon); }); app.get("/pokemon/search?", (req, res) => { const { name } = req.query; res.json( pokemon.filter((pokemonName) => { return pokemonName.name.toLowerCase() === name.toLowerCase(); }) ); }); app.get("/pokemon/:indexOfArray", (req, res) => { const { indexOfArray } = req.params; if (pokemon[indexOfArray]) { res.json(pokemon[indexOfArray]); } else { res.status(404).send(`Sorry, no pokemon found at ${indexOfArray}`); } }); app.get("/pokemon-pretty/", (req, res) => { res.send(); }); app.get("/pokemon-pretty/:indexOfArray", (req, res) => { const { indexOfArray } = req.params; if (pokemon[indexOfArray]) { res.send(`<h1>${pokemon[indexOfArray].name}</h1> <img src="${pokemon[indexOfArray].img}"/>`); } else { res.status(404).send(`Sorry, no pokemon found at ${indexOfArray}`); } }); module.exports = app; // req.query: directly access the parsed query string parameters // req.params: directly access the parsed route parameters from the path
ed60b842fcf6ae24b785a74b052260bf714a8db2
[ "JavaScript" ]
1
JavaScript
mphall77/99-pokemon-express
fcf5129696d41f6a4abb9b5e51d1443611bf039a
6e59564a15768a6459c11a5cf5978284b749a1fc
refs/heads/master
<file_sep>/** * Gulpfile for task running * @author <NAME> <@thekaanon> */ var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var fs = require('fs'); var configFile = process.cwd() + '/webpack.config.js'; if (!fs.existsSync(configFile)) { console.error('No webpack config found'); return; } var webpackConfig = require(configFile); gulp.task('webpack:build', function(callback) { webpackConfig.plugins = (webpackConfig.plugins || []).concat( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: 'production' } }), new webpack.optimize.UglifyJsPlugin() ); var compiler = webpack(webpackConfig); webpack(webpackConfig).run(function(err, stats) { if (err) { throw new gutil.PluginError('webpack:build', err); } gutil.log('[webpack:build]', stats.toString({ colors: true })); callback(); }); }); gulp.task('webpack:watch', function() { webpack(webpackConfig).watch(100, function (err, stats) { if (err) { throw new gutil.PluginError('webpack:watch', err); } gutil.log('[webpack:build]', stats.toString({ colors: true })); }); }); <file_sep># colorficial Javascript Class for determining color names Color utility. Provides functionality to determine the name of a color. Also provides hue, saturation, value, lightness (or brightness) and can be exported as a css declaration. ## Full Documentation and Demo http://kaanon.github.io/colorficial/ ## Installation `bower install colorficial` `npm install --save colorficial` ## Usage ### Instantiation ```javascript // Client Side with Bower var Color = require('../../bower_components/colorficial/dist/color'); // Server Side with node.js var Color = require('colorficial'); var c = new Color(255,100,100); //red, green, blue var c = new Color([255,100,100]); // [red, green, blue] var c = new Color('#FF9922'); var c = new Color({r: 255, g: 100, b: 100}); var c = new Color({red: 255, green: 100, blue: 100}); ``` ### Name Methods ```javascript var c = new Color([11, 170, 181]); c.name(); // blue c.names(); // ["blue","green"] c.is('red'); // false c.is('blue'); // true c.isLight(); // true (if brightness > 200) c.isLight(100); // true (if brightness > 100); c.isDark(); // true (if brightness < 85) c.isDark(100); // true (if brightness < 100); ``` ### Color Attributes ```javascript var c = new Color([11, 170, 181]); c.red; // 11 c.green; // 170 c.blue // 181 c.hue // 183.88 (measured between 0&deg; and 360&deg;) c.brightness // 37.65 (measured between 0 and 100) c.lightness // 37.65 (synonym of brightness) c.saturation // 88.54 (measured between 0 and 100) c.value // 88.54 (measured between 0 and 100) ``` ### Utility Methods ```javascript var c = new Color([11, 170, 181]); c.css(); // "rgb(11,170,181)" c.css(0.5); // "rgba(11,170,181,0.5)" c.cssHSL(); // "hsl(11,170,181,0.5)" c.cssHSV(); // "hsv(11,170,181,0.5)" c.toJSON(); // { red: 11, green: 170, blue: 181 } c.toArray(); // [ 11, 170, 181 ] c.toString() // "[11, 170, 181]" ``` ## Supported Colors - red - orange - brown - yellow - green - blue - indigo - violet - pink - gray - black - white ## Gotchas Teal (blue/green) and dark pink are pretty 💩. Still working on that. ## TODO - bower support - npm support - more color names (extendable?) ## License [MIT](http://opensource.org/licenses/MIT) © [<NAME>](http://kaanon.com) <file_sep>'use strict'; /** * Color Manipulation class * @author <NAME> <<EMAIL>> * @class Color * @description Find out information about a particular color * @example var c = new Color([100,200,150]); * * * TODO: compare color objects * TODO: support hex in constructor */ class Color { /** * Create the object * @param {varies} opts description on color * var c = new Color(255,100,100); * var c = new Color([255,100,100]); * var c = new Color('#FF9922'); * var c = new Color({r: 255, g: 100, b: 100}) * var c = new Color({red: 255, green: 100, blue: 100}) */ constructor(opts) { var red, green, blue; // If passing in a hex string if(toString.call(opts) === "[object String]" && opts.length >= 6){ var hex = opts.substr(0,1) === '#' ? opts.substr(1) : opts; red = "0x" + hex.substr(0,2); green = "0x" + hex.substr(2,2); blue = "0x" + hex.substr(4,2); } // If passing in an array: else if(Array.isArray(opts) && opts.length === 3){ red = opts[0]; green = opts[1]; blue = opts[2]; } // if passing in else if (arguments.length === 3){ red = arguments[0]; green = arguments[1]; blue = arguments[2]; } else if (opts.r){ red = opts.r; green = opts.g; blue = opts.b; } else if (opts.red){ red = opts.red; green = opts.green; blue = opts.blue; } else { throw new TypeError('Invalid Initialization Options'); } this.red = parseInt(red); this.green = parseInt(green); this.blue = parseInt(blue); // Make sure we are within the known color space if(this.red > 255 || this.green > 255 || this.blue > 255){ throw new TypeError('Invalid Colorspace'); } } get hue(){ if(!this._hue){ this.__initializeHSLV(); } return this._hue; } get saturation(){ if(!this._saturation){ this.__initializeHSLV(); } return this._saturation; } get lightness(){ if(!this._lightness){ this.__initializeHSLV(); } return this._lightness; } get brightness(){ return this.lightness; } get value(){ if(!this._value){ this.__initializeHSLV(); } return this._value; } get X(){ if(!this._x){ this.__initializeXYZ(); } return this._x; } get Y(){ if(!this._y){ this.__initializeXYZ(); } return this._y; } get Z(){ if(!this._z){ this.__initializeXYZ(); } return this._z; } get luminance(){ return this.Y; } name(){ var colorMap = this.getColorMap(), matchedColors = this.getMatchedColors(); if(matchedColors.length === 1){ return matchedColors[0]; } else if(matchedColors.length > 1){ // If more than one color matches, sort by the distance from the reference // Return the color name that is closest to the reference color var that = this; var distances = matchedColors.map(function(name){ return { name: name, distance: that.distance(colorMap[name].reference) } }); distances.sort(function(a,b){ if (a.distance > b.distance) { return 1; } if (a.distance < b.distance) { return -1; } // a must be equal to b return 0; }); return distances[0].name; } return null; } names(){ return this.getMatchedColors(); } getMatchedColors(){ var colorMap = this.getColorMap(), matchedColors = []; for(var colorName in colorMap){ if( this.is(colorName)){ matchedColors.push(colorName); } } return matchedColors; } /** * Returns the value to be used in a css declaration * @method css * @param {float} opacity From 0 - 1 * @return {string} */ css(opacity){ var values = this.toArray(), name = 'rgb('; if(opacity){ name = 'rgba('; values.push(opacity); } return name + values.join(', ') + ')'; } /** * Returns the value to be used in a css declaration * @method cssHSL * @return {string} */ cssHSL(){ var name = 'hsl(', values = [this.hue, this.saturation, this.lightness]; return name + values.join(', ') + ')'; } /** * Returns the value to be used in a css declaration * @method cssHSV * @return {string} */ cssHSV(){ var name = 'hsv(', values = [this.hue, this.saturation, this.value]; return name + values.join(', ') + ')'; } /** * Distance between this color and another color * @method distance * @param {array} rgb [red, green, blue] * @return {number} */ distance(rgb){ var xyz1 = this.__rgb_to_xyz(this.red, this.green, this.blue), xyz2 = this.__rgb_to_xyz.apply(this,rgb), lab1 = this.__xyz_to_lab.apply(this, xyz1), lab2 = this.__xyz_to_lab.apply(this, xyz2), difference = this.__de_1994(lab1, lab2); return difference; } /** * http://www.emanueleferonato.com/2009/08/28/color-differences-algorithm/ * http://www.emanueleferonato.com/2009/09/08/color-difference-algorithm-part-2/ * @method __rgb_to_xyz * @param {[type]} red [description] * @param {[type]} green [description] * @param {[type]} blue [description] * @return {[type]} */ __rgb_to_xyz(r, g, b){ var _red = r/255, _green = g/255, _blue = b/255, x,y,z; if(_red>0.04045){ _red = (_red+0.055)/1.055; _red = Math.pow(_red,2.4); } else{ _red = _red/12.92; } if(_green>0.04045){ _green = (_green+0.055)/1.055; _green = Math.pow(_green,2.4); } else{ _green = _green/12.92; } if(_blue>0.04045){ _blue = (_blue+0.055)/1.055; _blue = Math.pow(_blue,2.4); } else{ _blue = _blue/12.92; } _red *= 100; _green *= 100; _blue *= 100; x = _red * 0.4124 + _green * 0.3576 + _blue * 0.1805; y = _red * 0.2126 + _green * 0.7152 + _blue * 0.0722; z = _red * 0.0193 + _green * 0.1192 + _blue * 0.9505; return [x,y,z]; } __xyz_to_lab(x, y, z){ var _x = x/95.047, _y = y/100, _z = z/108.883, l, a, b; if(_x>0.008856){ _x = Math.pow(_x,1/3); } else{ _x = 7.787*_x + 16/116; } if(_y>0.008856){ _y = Math.pow(_y,1/3); } else{ _y = (7.787*_y) + (16/116); } if(_z>0.008856){ _z = Math.pow(_z,1/3); } else{ _z = 7.787*_z + 16/116; } l= 116*_y -16; a= 500*(_x-_y); b= 200*(_y-_z); return [l, a, b]; } __de_1994( lab1, lab2){ var c1 = Math.sqrt(lab1[1]*lab1[1]+lab1[2]*lab1[2]), c2 = Math.sqrt(lab2[1]*lab2[1]+lab2[2]*lab2[2]), dc = c1-c2, dl = lab1[0]-lab2[0], da = lab1[1]-lab2[1], db = lab1[2]-lab2[2], dh = Math.sqrt((da*da)+(db*db)-(dc*dc)), first = dl, second = dc/(1+0.045*c1), third = dh/(1+0.015*c1); return Math.sqrt(first*first+second*second+third*third); } toString() { return this.css(); } isLight(divider = 45){ return (this.luminance > divider); }; isDark(divider = 45){ return (this.luminance <= divider); }; isSkinTone(brown = [139,69,19]){ if (this.saturation < 60 && this.mostlyRed() && this.distance(brown) < 35 ){ return true; } return false; } isRed(variance){ var colorMap = this.getColorMap(), ret = true; ret = (this.hue <= colorMap.red.maxHue || this.hue > colorMap.pink.maxHue ); delete(colorMap.red.maxHue); return ret && this._matchesCriterion(colorMap.red); } isGray(variance = 30){ var colorMap = this.getColorMap(), ret = true; ret = ( ( Math.abs(this.red - this.blue) < variance) && ( Math.abs(this.red - this.green) < variance) && ( Math.abs(this.blue - this.green) < variance) ); return ret && this._matchesCriterion(colorMap.gray); } getColorMap(){ return { red: { reference: [255,0,0], maxHue: 10, // minBrightness: 30, minSaturation: 10 }, brown: { reference: [112, 42, 11], minHue: 5, maxHue: 50, // maxSaturation: 84, // minBrightness: 18 }, orange: { reference: [253, 82, 13], minHue: 10, maxHue: 39, minSaturation: 71, minBrightness: 40 }, yellow: { reference: [255,255,0], minHue: 40, maxHue: 68, // minSaturation: 50, // minBrightness: 45 }, green: { reference: [0,255,0], minHue: 58.5, maxHue: 170, // minSaturation: 10, minBrightness: 7 }, blue: { reference: [0,0,255], minHue: 167, maxHue: 250 }, indigo: { reference: [0,0,255], minHue: 220, maxHue: 250, minSaturation: 60, maxBrightness: 35 }, violet: { reference: [164, 100, 223], minHue: 220, maxHue: 323, minSaturation: 13, // minBrightness: 10 }, pink: { reference: [250,50,150], minHue: 295, maxHue: 334, // minSaturation: 80 }, white: { reference: [255,255,255], maxSaturation: 5, minBrightness: 95 }, black: { reference: [0,0,0], maxSaturation: 5, maxBrightness: 5 }, gray: { reference: [204,204,204], minBrightness: 10, maxBrightness: 98 } }; } is(compare){ var colorMap = this.getColorMap(); if(compare === 'gray'){ return this.isGray(); } if(compare === 'red'){ return this.isRed(); } if(colorMap[compare]){ var criterion = colorMap[compare]; return this._matchesCriterion(criterion); } // TODO: make this work // else if (typeof compare === 'Color'){ // return this.distance(compare) < variance; // } return false; } _matchesCriterion(criterion){ var ret = true; if(criterion.minHue){ ret = ret && this.hue >= criterion.minHue; } if(criterion.maxHue){ ret = ret && this.hue <= criterion.maxHue; } if(criterion.maxValue){ ret = ret && this.value < criterion.maxValue; } if(criterion.minValue){ ret = ret && this.value >= criterion.minValue; } if(criterion.maxBrightness){ ret = ret && this.brightness <= criterion.maxBrightness; } if(criterion.minBrightness){ ret = ret && this.brightness >= criterion.minBrightness; } if(criterion.maxSaturation){ ret = ret && this.saturation <= criterion.maxSaturation; } if(criterion.minSaturation){ ret = ret && this.saturation >= criterion.minSaturation; } return ret; } //Reference: http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c __initializeHSLV(){ var r = this.red / 255, g = this.green / 255, b = this.blue /255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; var v = max; if(max == min){ h = s = 0; // achromatic }else{ var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; h *= 3.6; } this._hue = parseFloat( (h * 100).toFixed(2) ); this._saturation = parseFloat( (s * 100).toFixed(2) ); this._lightness = parseFloat( (l * 100).toFixed(2) ); this._brightness = parseFloat( ((this.red*299)+(this.green*587)+(this.blue*114))/1000 ); this._value = parseFloat( v ); } __initializeXYZ(){ var xyz = this.rgb_to_xyz(this.red, this.green, this.blue) this._x = xyz[0] this._y = xyz[1] this._z = xyz[2] } toJSON(){ return { red: this.red, green:this.green, blue: this.blue,}; } toArray(){ return [this.red,this.green,this.blue]; } toString(){ return '[' + [this.red,this.green,this.blue].join(', ') + ']'; } }; module.exports = Color; if(typeof window !== 'undefined'){ window.Color = Color; }
31661020a754b5dfe2da02181b50db627df44cd6
[ "JavaScript", "Markdown" ]
3
JavaScript
kaanon/colorficial
2dfe49fcd465bfc8cd1cda79d146184dac4d7e8a
2b6b59ae320de4e33d19a74e3a666e1e586a3921
refs/heads/master
<file_sep> using UnityEngine; public class EndTrigger : MonoBehaviour { public AudioClip saw2; public GameManager gameManager; public void Start() { GetComponent<AudioSource>().clip = saw2 ; } public void OnTriggerEnter() { GetComponent<AudioSource>().Play(); gameManager.CompleteLevel(); } } <file_sep># WatchOut- A PC game developed in Unity to entertain ourselves by dodging ingame obstacles.
071bc59c9d6d355d2d7fd8a9546f294693c6921e
[ "Markdown", "C#" ]
2
C#
splitcabbage/WatchOut-
406866dd40c521460b46ed5cd358b0b936c8e7a8
c6b26d8b6f1e620e86ff199919def049c5301e43
refs/heads/master
<repo_name>sakura0702/AppOcorrenciasv2.0<file_sep>/app/src/main/java/appocorrencias/com/appocorrencias/ClassesSA/OcorrenciasRegistradas.java package appocorrencias.com.appocorrencias.ClassesSA; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by Jeanderson on 22/04/2017. */ public class OcorrenciasRegistradas { public int Id_ocorrencias; public String Descricao; public String Tipocrime; public String CPF; public static List<OcorrenciasRegistradas> lista; public static Random random = new Random(); public int getId_ocorrencias() { return Id_ocorrencias; } public void setId_ocorrencias(int id_ocorrencias) { Id_ocorrencias = id_ocorrencias; } public String getCPF() { return CPF; } public void setCPF(String CPF) { this.CPF = CPF; } public String getTipocrime() { return Tipocrime; } public void setTipocrime(String tipocrime) { Tipocrime = tipocrime; } public String getDescricao() { return Descricao; } public void setDescricao(String descricao) { Descricao = descricao; } public OcorrenciasRegistradas(int id_ocorrencias,String descricao,String tipocrime,String cpf){ Id_ocorrencias = id_ocorrencias; Descricao = descricao; Tipocrime = tipocrime; CPF = cpf; } public static ArrayList<OcorrenciasRegistradas> criarocorrencias (){ ArrayList<OcorrenciasRegistradas> cursosList = new ArrayList(); cursosList.add(0,new OcorrenciasRegistradas(random.nextInt(1000),"Jaqueta amarela, calça preta, boné verde","ROUBO","431313868")); cursosList.add(1,new OcorrenciasRegistradas(random.nextInt(1000),"Jaque<NAME>, calça preta, boné verde","ASSALTO","431313868")); cursosList.add(2,new OcorrenciasRegistradas(random.nextInt(1000),"J<NAME>, calça preta, boné verde","ASSALTO","431313868")); cursosList.add(3,new OcorrenciasRegistradas(random.nextInt(1000),"J<NAME>, calça preta, boné verde","ROUBO","431313868")); cursosList.add(4,new OcorrenciasRegistradas(random.nextInt(1000),"J<NAME>, calça preta, boné verde","ASSALTO","431313868")); return cursosList; } public String toString(){ return "Número Ocorrencia "+Id_ocorrencias+"\n Descricao:"+Descricao+" " +" \n Tipo Ocorrencia: "+Tipocrime; } } <file_sep>/app/src/main/java/appocorrencias/com/appocorrencias/Activitys/Cadastrar_Usuario.java package appocorrencias.com.appocorrencias.Activitys; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.IOException; import appocorrencias.com.appocorrencias.ClassesSA.Buscar_Cep; import appocorrencias.com.appocorrencias.ClassesSA.ProcessaSocket; import appocorrencias.com.appocorrencias.R; import br.com.jansenfelipe.androidmask.MaskEditTextChangedListener; public class Cadastrar_Usuario extends AppCompatActivity { //Variavel para gerar log private static final String TAG = "LOG"; //Variaveis globais private Button btnCadastarUsuario; private Button btnBuscar; private EditText Nome,CPF,Telefone,Email,Senha,Rua, Bairro, Cidade, Numero, CEP, UF; //Variaveis para conversão e referencia nula private String convCpf,convTelefone,convCep,email,senha,numero,rua,bairro,cidade,uf,nome; //Váriaveis para serem utilizadas no envio do cadastro protected String cadastro1,cadastroNome,cadastroRua,cadastroBairro,cadastroCidade; //Dados para o envio do socket. ProcessaSocket processa = new ProcessaSocket(); boolean retorno; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastrar_usuario); //Button cadastrar btnCadastarUsuario = (Button) findViewById(R.id.CadastrarUsuário); btnBuscar = (Button) findViewById(R.id.btnBuscar); //Váriaveis para o cadastro Nome = (EditText) findViewById(R.id.edtNome); CPF = (EditText) findViewById(R.id.edtCPF); Senha = (EditText) findViewById(R.id.edtSenha); Email = (EditText) findViewById(R.id.edtEmail); Rua = (EditText) findViewById(R.id.edtRua); Telefone = (EditText) findViewById(R.id.edtTelefone); CEP = (EditText) findViewById(R.id.edtCep); Bairro = (EditText) findViewById(R.id.edtBairro); Cidade = (EditText) findViewById(R.id.edtCidade); UF = (EditText) findViewById(R.id.edtUF); Numero = (EditText) findViewById(R.id.edtNumero); // Inserindo Mascaras. MaskEditTextChangedListener maskCPF = new MaskEditTextChangedListener("###.###.###-##", CPF); MaskEditTextChangedListener maskTelefone = new MaskEditTextChangedListener("(##)#####-####", Telefone); MaskEditTextChangedListener maskCEP = new MaskEditTextChangedListener("#####-###", CEP); CPF.addTextChangedListener(maskCPF); Telefone.addTextChangedListener(maskTelefone); CEP.addTextChangedListener(maskCEP); } // Método para buscar Cep public void evBuscarCep(View v) throws IOException { convCep = CEP.getText().toString().replaceAll("[^0123456789]", ""); Buscar_Cep busca = new Buscar_Cep(); String Status = busca.getEndereco(convCep); if(Status.equals("erro")){ Toast.makeText(this, "Erro na Conexão", Toast.LENGTH_SHORT).show(); } else { Rua.setText(busca.getEndereco(convCep)); Bairro.setText(busca.getBairro(convCep)); Cidade.setText(busca.getCidade(convCep)); UF.setText(busca.getUF(convCep)); rua = busca.getEndereco(convCep); bairro = busca.getBairro(convCep); cidade = busca.getCidade(convCep); uf = busca.getUF(convCep); } } //Cadastrar usuário no servidor public void evCadastrarUsuario(View v) throws IOException { //Tirando a mascara dos campos convCpf = CPF.getText().toString().replaceAll("[^0123456789]", ""); convTelefone = Telefone.getText().toString().replaceAll("[^0123456789]", ""); convCep = CEP.getText().toString().replaceAll("[^0123456789]", ""); //Retirando referencia null email = Email.getText().toString(); senha = Senha.getText().toString(); numero = Numero.getText().toString(); nome = Nome.getText().toString(); Log.i(TAG, "Cadastrar...."+convCpf); if (convCpf.isEmpty()) { CPF.setError("Faltou preencher CPF "); CPF.setFocusable(true); CPF.requestFocus(); } else { if (validarCPF(convCpf)) { CPF.setError("CPF Inválido"); CPF.setFocusable(true); CPF.requestFocus(); } else { if (!validarEmail(email)) { Email.setError("Faltou preencher E-mail"); Email.setFocusable(true); Email.requestFocus(); } else { if (convCep.isEmpty()) { CEP.setError("CEP Inválido"); CEP.setFocusable(true); CEP.requestFocus(); } else { String retorno = processa.cadastrarUsuario(convCpf, senha, email, convTelefone, convCep, UF, numero, rua, bairro, cidade, nome); if (retorno.equals("erro")) { Toast.makeText(this, "Erro na Conexão com o Servidor", Toast.LENGTH_SHORT).show(); } else { if (retorno.equals("true")) { Toast.makeText(this, "Cadastro feito com sucesso", Toast.LENGTH_SHORT).show(); setContentView(R.layout.activity_main); this.startActivity(new Intent(this, MainActivity.class)); } else { CPF.setError("CPF Já Cadastrado"); CPF.setFocusable(true); CPF.requestFocus(); } } } } } } } //Método para Validar CPF public static boolean validarCPF(String CPF) { if (CPF.equals("00000000000") || CPF.equals("11111111111") || CPF.equals("22222222222") || CPF.equals("33333333333") || CPF.equals("44444444444") || CPF.equals("55555555555") || CPF.equals("66666666666") || CPF.equals("77777777777") || CPF.equals("88888888888") || CPF.equals("99999999999")) { return true; } Log.i(TAG, "Validando...."+CPF); char dig10, dig11; int sm, i, r, num, peso; try { sm = 0; peso = 10; for (i = 0; i < 9; i++) { num = (int) (CPF.charAt(i) - 48); sm = sm + (num * peso); peso = peso - 1; } r = 11 - (sm % 11); if ((r == 10) || (r == 11)) dig10 = '0'; else dig10 = (char) (r + 48); sm = 0; peso = 11; for (i = 0; i < 10; i++) { num = (int) (CPF.charAt(i) - 48); sm = sm + (num * peso); peso = peso - 1; } r = 11 - (sm % 11); if ((r == 10) || (r == 11)) dig11 = '0'; else dig11 = (char) (r + 48); if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10))) return (false); else return (true); } catch (Exception erro) { return (true); } } //Método para validar Email public final static boolean validarEmail(String txtEmail) { if (TextUtils.isEmpty(txtEmail)) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(txtEmail).matches(); } } @Override public void onBackPressed() { super.onBackPressed(); setContentView(R.layout.activity_main); this.startActivity(new Intent(this,MainActivity.class)); } }
4e5783bfee07d0ec4dcde472c03321d118c66775
[ "Java" ]
2
Java
sakura0702/AppOcorrenciasv2.0
e61fe69e05b514ad2bcf36e8378d47e61c9bda81
a13e86bb2068266e64e99ebdb3cd82aca24a3ca0
refs/heads/master
<repo_name>Chiffilin/Lab5.0<file_sep>/README.md # Lab5.0 Easy LvL Вариант №1 Задание: создать текстовый файл с произвольной информацией. Организовать просмотр содержимого файла. Организовать чтение и обработку данных из файла в соответсвии с идивидуальным заданием. Сохранить полученные результаты в новый текстовый файл. "Человек": фамилия;имя;отчество;пол;национальность;рост;вес;дата рождения(год,месяц,число);номер телефона;домашний адрес. Вывести сведения о самом молодом человеке. <file_sep>/Lab5.0/Lab5.0.cpp #include <iostream> #include <fstream> using namespace std; struct Date { short day; short month; short year; bool isCorrect(); }; bool Date::isCorrect() { bool result = false; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: { if ((day <= 31) && (day > 0)) result = true; break; } case 4: case 6: case 9: case 11: { if ((day <= 30) && (day > 0)) result = true; break; } case 2: { if (year % 4 != 0) { if ((day <= 28) && (day > 0)) result = true; } else if (year % 400 == 0) { if ((day <= 29) && (day > 0)) result = true; } else if ((year % 100 == 0) && (year % 400 != 0)) { if ((day == 28) && (day > 0)) result = true; } else if ((year % 4 == 0) && (year % 100 != 0)) if ((day <= 29) && (day > 0)) result = true; break; } default: result = false; } return result; } struct Human { char Surname[64]; //Фамилия char Name[64]; //Имя char Middlename[64]; //Отчетсво char Gender[64]; //Пол char Nationality[64]; //Национальность int Height; //Рост int Weight; //Вес Date birthday; int number; //Номер char adress[128]; //Адрес }; int main() { setlocale(LC_ALL, "RUS"); const int N = 1; Human group[N]; ofstream F; F.open("D:\\games\\Human.txt", ios::out); for (int i = 0; i < N; i++) { cout << "\n............Human..[" << i + 1 << "]........" << endl; cout << "\nВведите Фамилию: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin.getline(group[i].Surname, 64); cout << "\nВвдеите Имя: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin.getline(group[i].Name, 64); cout << "\nВведите Отчество: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin.getline(group[i].Middlename, 64); cout << "\nВведите Пол: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin.getline(group[i].Gender, 64); cout << "\nВведите Национальность: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin.getline(group[i].Nationality, 64); cout << "\nВведите Рост: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin >> group[i].Height; cout << "\nВведите Вес: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin >> group[i].Weight; do { cout << "\nВведите Дату Рождения: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin >> group[i].birthday.day >> group[i].birthday.month >> group[i].birthday.year; } while (!group[i].birthday.isCorrect()); cin.clear(); cout << "\nВведите Номер Телефона: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin >> group[i].number; cout << "\nВведите Дом. Адрес: "; cin.ignore(std::cin.rdbuf()->in_avail()); cin >> group[i].adress; } for (int i = 0; i < N; i++) { cout << "\n...............DATA......................" << endl; cout << "\nФИО: " << group[i].Surname << " " << group[i].Name << " " << group[i].Middlename; cout << "\nПол: " << group[i].Gender; cout << "\nНациональность: " << group[i].Nationality; cout << "\nРост: " << group[i].Height; cout << "\nВес: " << group[i].Weight; cout << "\nДата Рождения: " << group[i].birthday.day << "." << group[i].birthday.month << "." << group[i].birthday.year; cout << "\nНомер Телефона: " << group[i].number; cout << "\nДом. Адрес: " << group[i].adress << endl; } for (int i = 0; i < N; i++) { F << "ФИО: " << group[i].Surname << " " << group[i].Name << " " << group[i].Middlename << "\n" <<"Пол: "<< group[i].Gender << "\n" <<"Национальность: "<< group[i].Nationality << "\n" <<"Рост: "<< group[i].Height << "\n" <<"Вес: "<< group[i].Weight << "\n" <<"Дата Рождения: "<< group[i].birthday.day << "." << group[i].birthday.month << "." << group[i].birthday.year << "\n" <<"Номер Телефона: "<< group[i].number << "\n" <<"Дом. Адрес:"<< group[i].adress << "\n" << endl; } F.close(); system("pause"); return 0; }
2cfe949145d17c4880c3905156edf32f45d42055
[ "Markdown", "C++" ]
2
Markdown
Chiffilin/Lab5.0
c940e31990fb333cdbc9c75a8aa4608af53e9f4c
7efcec18eede3c1899fcc61d32a1f149e9778809
refs/heads/master
<repo_name>tioluwani94/testing-branch-port<file_sep>/test.js console.log("I'm in test"); <file_sep>/hello.js console.log("I'm in hello");
159c55b62fc2fe603f794abd5bb85ad0bc1c4f50
[ "JavaScript" ]
2
JavaScript
tioluwani94/testing-branch-port
5a48e4cefd5d74bf9031f4170babe957cc867362
4d0b776752161b9016bc34d078cbf077e7548d3e
refs/heads/master
<file_sep>const Sequelize = require('sequelize'); const mongoose = require('mongoose'); const sequelize = new Sequelize('research', 'postgres', 'postgres', { host: 'localhost', dialect: 'postgres', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, operatorsAliases: false }); const mysql = new Sequelize('tasks', 'root', 'toor', { host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, operatorsAliases: false }); mongoose.connect('mongodb://localhost/tasks'); const Project = sequelize.define("project", { id: { type: Sequelize.UUID, primaryKey: true }, name: { type: Sequelize.STRING, allowNull: false } }); const Task = mysql.define("task", { id: { type: Sequelize.UUID, primaryKey: true }, title: { type: Sequelize.STRING, allowNull: false }, description: { type: Sequelize.STRING, allowNull: true }, projectId: { type: Sequelize.UUID, allowNull: false } }); const Worklog = mongoose.model("worklog", { id: mongoose.Schema.Types.String, description: mongoose.Schema.Types.String, hours: mongoose.Schema.Types.Number, date: mongoose.Schema.Types.Date, taskId: mongoose.Schema.Types.String }); module.exports = { db: [sequelize, mysql, mongoose], Project, Task, Worklog };<file_sep>const { Project, Task, Worklog } = require('./database'); const uuid = require('uuid-v4'); const resolvers = { Query: { findAllProjects () { return Project.findAll(); }, countProjects () { return Project.count(); }, findAllTasks (_, { projectId }) { return Task.findAll({ where: { projectId }}); }, findAllWorklogs (_, { taskId }) { return Worklog.find({ taskId }); } }, Mutation: { newProject (_, { name }) { const project = Project.create({ id: uuid(), name: name }); return project; }, deleteProject (_, { id }) { Project.destroy({ where: { id } }); return id; }, updateProject (_, { project }) { Project.update(project, { where: { id: project.id } }); return project; }, newTask (_, { task }) { task.id = uuid() const newTask = Task.create(task); return newTask; }, deleteTask (_, { id }) { Task.destroy({ where: { id }}); return id; }, updateTask (_, { task }) { Task.update(task, { where: { id: task.id } }); return task; }, newWorklog (_, { worklog }) { worklog.id = uuid() const newWorklog = Worklog.create(worklog); return newWorklog; }, deleteWorklog (_, { id }) { Worklog.remove({ id }); return id; }, updateWorklog (_, { worklog }) { Worklog.update({ id: worklog.id }, worklog, { upsert: true }); return worklog; } }, Project: { tasks (project) { return Task.findAll({ where: { projectId: project.id }}); } }, Task: { worklogs (task) { return Worklog.find({ taskId: task.id }); } } }; module.exports = resolvers;<file_sep>const typeDefs = ` type Query { findAllProjects: [Project]! countProjects: Int! findAllTasks(projectId: String!): [Task]! findAllWorklogs(taskId: String!): [Worklog]! } type Mutation { newProject(name: String!): Project! deleteProject(id: String!): String! updateProject(project: ProjectInput!): Project! newTask(task: TaskInput!): Task! deleteTask(id: String!): String! updateTask(task: TaskInput): Task! newWorklog(worklog: WorklogInput!): Worklog! deleteWorklog(id: String!): String! updateWorklog(worklog: WorklogInput): Worklog! } type Project { id: String! name: String! tasks: [Task]! } input ProjectInput { id: String! name: String! } type Task { id: String! title: String! description: String! projectId: String! worklogs: [Worklog]! } input TaskInput { id: String title: String! description: String! projectId: String! } type Worklog { id: String! description: String! hours: Float! date: Date! taskId: String! } input WorklogInput { id: String description: String! hours: Float! date: Date! taskId: String! } type Schema { query: Query mutation: Mutation } scalar Date `; module.exports = typeDefs;
9df17c44068dc2b592be247313fdd8b12a3068b6
[ "JavaScript" ]
3
JavaScript
silas-ss/graphql-apollo-server
0cec7de82821959f66e3fa96b62e75ac10de8b25
a6f78f9594143dceef18085f763369fd93651401
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class jurusan extends Model { protected $table = 'jurusans'; protected $fillable = array('nama_jurusan'); public $timestamp = true; public function kelas() { return $this->hasMany('App\kelas', 'id_kelas'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class siswa extends Model { protected $table = 'siswas'; protected $fillable = array('nis', 'nama','email','password','id_kelas','jk' ,'tempat_lahir','tanggal_lahir','alamat','id_user'); public $timestamp = true; public function kelas() { return $this->belongsTo('App\kelas', 'id_kelas'); } public function absensi_siswa() { return $this->hasOne('App\absensi_siswa', 'id_siswa'); } public function User() { return $this->belongsTo('App\User', 'id_user'); } } // class siswaa extends Authenticatable // { // use Notifiable; // protected $guard ='siswa'; // /** // * The attributes that are mass assignable. // * // * @var array // */ // protected $fillable = [ // 'name', 'email', 'password', // ]; // /** // * The attributes that should be hidden for arrays. // * // * @var array // */ // protected $hidden = [ // 'password', 'remember_token', // ]; // }<file_sep><?php use Illuminate\Database\Seeder; use App\Role; use App\User; class UsersSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //membuat role admin $adminRole =new Role(); $adminRole ->name ="admin"; $adminRole ->display_name ="Admin"; $adminRole ->save(); //membuat role member $memberRole =new Role(); $memberRole ->name ="member"; $memberRole ->display_name ="Member"; $memberRole ->save(); $petugasRole =new Role(); $petugasRole ->name ="petugas"; $petugasRole ->display_name ="Petugas"; $petugasRole ->save(); $siswaRole =new Role(); $siswaRole ->name ="siswa"; $siswaRole ->display_name ="Siswa"; $siswaRole ->save(); $guruRole =new Role(); $guruRole ->name ="guru"; $guruRole ->display_name ="Guru"; $guruRole ->save(); $Admin =new User(); $Admin ->name ="Admin"; $Admin ->email ="<EMAIL>"; $Admin ->password =bcrypt('<PASSWORD>'); $Admin ->save(); $Admin ->attachRole($adminRole); $member =new User(); $member ->name ="<NAME>"; $member ->email ="<EMAIL>"; $member ->password =bcrypt('<PASSWORD>'); $member ->save(); $member ->attachRole($memberRole); $member =new User(); $member ->name ="<NAME>"; $member ->email ="<EMAIL>"; $member ->password =bcrypt('<PASSWORD>'); $member ->save(); $member ->attachRole($memberRole); $member =new User(); $member ->name ="<NAME>"; $member ->email ="<EMAIL>"; $member ->password =bcrypt('<PASSWORD>'); $member ->save(); $member ->attachRole($memberRole); $member =new User(); $member ->name ="yogi"; $member ->email ="<EMAIL>"; $member ->password =<PASSWORD>('<PASSWORD>'); $member ->save(); $member ->attachRole($memberRole); $petugas =new User(); $petugas ->name ="sample petugas"; $petugas ->email ="<EMAIL>"; $petugas ->password =bcrypt('<PASSWORD>'); $petugas ->save(); $petugas ->attachRole($petugasRole); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class absensi_guru extends Model { protected $table = 'absensi_gurus'; protected $fillable = array('id_guru', 'tanggal', 'keterangan','nama_petugas','id_user'); public $timestamp = true; public function guru() { return $this->belongsTo('App\guru', 'id_guru'); } // public function petugas_piket() { // return $this->belongsTo('App\petugas_piket', 'id_PetugasPiket'); // } public function User() { return $this->belongsTo('App\User', 'id_user'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class guru extends Model { protected $table = 'gurus'; protected $fillable = array('nik', 'nama','jk','tempat_lahir','tanggal_lahir','alamat','id_user'); public function absensi_guru() { return $this->hasOne('App\absensi_guru', 'id_guru'); } public function User() { return $this->belongsTo('App\User', 'id_user'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\siswa; use App\kelas; class AuthController extends Controller { public function getLogin() { return view('login'); } public function postLogin(Request $request) { // dd(\Auth::attempt(['email'=>$request->email, 'password'=> $request->password]) // ); if(\Auth::attempt([ 'email'=>$request->emailSiswa, 'password'=> $request->passwordSiswa ])){ return redirect('/'); }else{ return 'salah Masuk'; } } public function getRegister() { return view('register'); } public function postRegister(Request $request) { $siswa = siswa::all(); $kelas = kelas::all(); return view('siswa.create',compact('kelas','siswa')); siswa::create([ 'nis' => $request->nis, 'nama' => $request->nama, 'id_kelas' => $request->id_kelas, 'email' => $request->email, 'password' => <PASSWORD>($<PASSWORD>), 'jk' => $request->jk, 'tempat_lahir' => $request->tempat_lahir, 'tanggal_lahir' => $request->tanggal_lahir, 'alamat' => $request->alamat, ]); return redirect()->back(); } }<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Kyslik\ColumnSortable\Sortable; class absensi_siswa extends Model { protected $table = 'absensi_siswas'; use Sortable; protected $fillable = array('id_siswa','id_kelas', 'tanggal', 'keterangan','nama_petugas','id_user'); protected $sortable = array('id_siswa', 'id_kelas','tanggal','keterangan','nama_petugas','id_user'); public $timestamp = true; public function siswa() { return $this->belongsTo('App\siswa', 'id_siswa'); } public function petugas_piket() { return $this->belongsTo('App\petugas_piket', 'id_PetugasPiket'); } public function kelas() { return $this->belongsTo('App\kelas', 'id_kelas'); } public function User() { return $this->belongsTo('App\User', 'id_user'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\petugas_piket; class PetugasPiketController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $petugas_piket = petugas_piket::all(); return view('PetugasPiket.index',compact('petugas_piket')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('PetugasPiket.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request,[ 'id_siswa' => 'required|max:255', 'id_kelas' => 'required|max:255', 'tanggal' => 'required|max:255', 'keterangan' => 'required|max:255', 'id_PetugasPiket' => 'required|max:255', ]); $petugas_piket = new petugas_piket; $petugas_piket->id_siswa = $request->id_siswa; $petugas_piket->id_kelas = $request->id_kelas; $petugas_piket->tanggal = $request->tanggal; $petugas_piket->keterangan = $request->keterangan ; $petugas_piket->id_PetugasPiket = $request->tgl_lahir; // dd($petugas_piket); $petugas_piket->save(); return redirect()->route('petugas_piket.index'); } /** * Display the specified resource. * * @param \App\petugas_piket $petugas_piket * @return \Illuminate\Http\Response */ public function show($id) { $petugas_piket = petugas_piket::findOrFail($id); return view('petugas_piket.show',compact('petugas_piket')); } /** * Show the form for editing the specified resource. * * @param \App\petugas_piket $petugas_piket * @return \Illuminate\Http\Response */ public function edit($id) { // memanggil data petugas_piket berdasrkan id di halaman petugas_piket edit $petugas_piket = petugas_piket::findOrFail($id); return view('petugas_piket.edit',compact('petugas_piket')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\petugas_piket $petugas_piket * @return \Illuminate\Http\Response */ public function update(Request $request,$id) { $this->validate($request,[ 'id_siswa' => 'required|max:255', 'id_kelas' => 'required|max:255', 'tanggal' => 'required|max:255', 'keterangan' => 'required|max:255', 'id_PetugasPiket' => 'required|max:255', ]); $petugas_piket =petugas_piket::findOrFail($id); $petugas_piket->id_siswa = $request->id_siswa; $petugas_piket->id_kelas = $request->id_kelas; $petugas_piket->tanggal = $request->tanggal; $petugas_piket->keterangan = $request->keterangan ; $petugas_piket->id_PetugasPiket = $request->id_PetugasPiket; // dd($petugas_piket); $petugas_piket->save(); return redirect()->route('petugas_piket.index'); } /** * Remove the specified resource from storage. * * @param \App\petugas_piket $petugas_piket * @return \Illuminate\Http\Response */ public function destroy($id) { // delete data beradasarkan id $petugas_piket = petugas_piket::findOrFail($id); $petugas_piket->delete(); return redirect()->route('petugas_piket.index'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\rekap; use App\kelas; use App\absensi_siswa; use App\absensi_guru; use App\User; use Auth; class RekapController extends Controller { public function index() { $kelas = Kelas::all(); $absensi_siswa = absensi_siswa::all(); return view('rekap.index', compact('absensi_siswa','kelas')); } public function index2(Request $request) { // $a = $request->a; $b = $request->b; $kelas = $request->c; $jumlahIzin= absensi_siswa::whereBetween('tanggal', [$a, $b]) ->where('id_kelas','=',$kelas)->get()->where('keterangan','Izin')->count(); $jumlahSakit= absensi_siswa::whereBetween('tanggal', [$a, $b]) ->where('id_kelas','=',$kelas)->get()->where('keterangan','Sakit')->count(); $jumlahAlfa= absensi_siswa::whereBetween('tanggal', [$a, $b]) ->where('id_kelas','=',$kelas)->get()->where('keterangan','Alfa')->count(); $absensi_siswa = absensi_siswa::whereBetween('tanggal', [$a, $b])->where('id_kelas','=',$kelas)->get(); return view('rekap.index2', compact('absensi_siswa', 'a','b','kelas','jumlahIzin','jumlahAlfa','jumlahSakit')); } public function index3() { $absensi_guru = absensi_guru::all(); return view('rekap.index3', compact('absensi_guru')); } public function index4(Request $request) { // $a = $request->a; $b = $request->b; $absensi_guru = absensi_guru::whereBetween('tanggal', [$a, $b])->get(); return view('rekap.index4', compact('absensi_guru', 'a','b')); } public function publish($id) { // $a = $request->a; $b = $request->b; $absensi_guru = absensi_guru::whereBetween('tanggal', [$a, $b])->get(); return view('rekap.index4', compact('absensi_guru', 'a','b')); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\absensi_siswa; use App\siswa; use App\kelas; use App\petugas_piket; use App\User; use Auth; class AbsensiSiswaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $absensi_siswa = absensi_siswa::all(); $siswa = siswa::all(); $kelas =kelas::all(); $petugas_piket =petugas_piket::all(); $user = user::all(); $jumlahIzin= absensi_siswa::where('keterangan','Izin')->count(); $jumlahSakit= absensi_siswa::where('keterangan','Sakit')->count(); $jumlahAlfa= absensi_siswa::where('keterangan','Alfa')->count(); return view('absensi_siswa.index',compact('absensi_siswa', 'siswa','kelas','petugas_piket','user','jumlahIzin','jumlahSakit','jumlahAlfa')); } public function absen() { $absensi_siswa = Auth::user()->absensi_siswa()->paginate(10); $jumlahIzin= Auth::user()->absensi_siswa()->where('keterangan','Izin')->count(); $jumlahSakit= Auth::user()->absensi_siswa()->where('keterangan','Sakit')->count(); $jumlahAlfa= Auth::user()->absensi_siswa()->where('keterangan','Alfa')->count(); $jumlah_data = count($absensi_siswa['absensi_siswa']); return view('member.absen',compact('absensi_siswa','jumlah_data','jumlahAlfa','jumlahSakit','jumlahIzin')); } // public function kelasAjax($id){ // if ($id==0) { // $absensi_siswa = absensi_siswa::all(); // }else{ // $absensi_siswa = absensi_siswa::where('id_kelas','=',$id)->get(); // } // return $absensi_siswa; // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $absensi_siswa = absensi_siswa::all(); // $siswa = siswa::all(); // $kelas =kelas::all(); // $petugas_piket =petugas_piket::all(); // $user = User::all(); // return view('absensi_siswa.create',compact('absensisiswa', 'siswa','kelas','petugas_piket','user')); } public function store(Request $request) { // $date =date("Y-m-d") tahun-bulan-hari $this->validate($request,[ 'id_siswa' => 'required|max:255', 'id_kelas' => 'required|max:255', 'tanggal' => 'required|max:255|before:tomorrow|after:yesterday', 'keterangan' => 'required|max:255', 'nama_petugas' => 'required|max:255', 'id_user'=>'required|max:255', ]); $absensi_siswa = new absensi_siswa; $absensi_siswa->id_siswa = $request->id_siswa; $absensi_siswa->id_kelas = $request->id_kelas; $absensi_siswa->tanggal = $request->tanggal; $absensi_siswa->nama_petugas = $request->nama_petugas ; $absensi_siswa->keterangan = $request->keterangan ; $absensi_siswa->id_user = $request->id_user; // dd($absensi_siswa); $absensi_siswa->save(); return redirect()->route('absensi_siswa.index'); } /** * Display the specified resource. * * @param \App\absensi_siswa $absensi_siswa * @return \Illuminate\Http\Response */ public function show($id) { $absensi_siswa = absensi_siswa::findOrFail($id); return view('absensi_siswa.show',compact('absensi_siswa')); } /** * Show the form for editing the specified resource. * * @param \App\absensi_siswa $absensi_siswa * @return \Illuminate\Http\Response */ public function edit(absensi_siswa $absensi_siswa) { $absensi_siswa = absensi_siswa::findOrFail($absensi_siswa->id); $petugas_piket = petugas_piket::all(); $selectpetugaspiket = absensi_siswa::findOrFail($absensi_siswa->id)->id_PetugasPiket; $siswa = siswa::all(); $selectsiswa = absensi_siswa::findOrFail($absensi_siswa->id)->id_siswa; $kelas = kelas::all(); $selectkelas = absensi_siswa::findOrFail($absensi_siswa->id)->id_kelas; $user = user::all(); $selectuser = absensi_siswa::findOrFail($absensi_siswa->id)->id_user; return view('absensi_siswa.edit',compact('siswa','absensi_siswa','selectsiswa','petugas_piket','selectpetugaspiket','kelas','selectkelas','user','selectuser')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\absensi_siswa $absensi_siswa * @return \Illuminate\Http\Response */ public function update(Request $request,$id) { $this->validate($request,[ 'id_siswa'=>'required|max:255', 'id_kelas'=>'required|max:255', 'tanggal'=>'required|min:1', 'keterangan'=>'required', 'nama_petugas'=>'required|max:255', 'id_user'=>'required|max:255', ]); $absensi_siswa =absensi_siswa::findOrFail($id); $absensi_siswa->id_siswa = $request->id_siswa; $absensi_siswa->id_kelas = $request->id_kelas; $absensi_siswa->tanggal = $request->tanggal; $absensi_siswa->keterangan = $request->keterangan; $absensi_siswa->nama_petugas = $request->nama_petugas; $absensi_siswa->id_user = $request->id_user; // dd($absensi_siswa); $absensi_siswa->save(); return redirect()->route('absensi_siswa.index'); } /** * Remove the specified resource from storage. * * @param \App\absensi_siswa $absensi_siswa * @return \Illuminate\Http\Response */ public function destroy($id) { // delete data beradasarkan id $absensi_siswa = absensi_siswa::findOrFail($id); $absensi_siswa->delete(); return redirect()->route('absensi_siswa.index'); } public function filter($id) { $siswa = siswa::where('id_kelas', $id)->get(); if($siswa->count() > 0){ echo '<option class="form-controll" >pilih siswa </option>'; foreach ($siswa as $data) { echo '<option class="form-controll" value="'.$data->id.'">'.$data->Nama.'|'.$data->Nis.'</option>'; } }else{ echo '<option class="form-control">Belum Ada Siswa</option>'; } } public function filterUser($id) { $user = siswa::where('id', $id)->get(); if($user->count() > 0){ foreach ($user as $data) { echo '<option class="form-control" value="'.$data->id_user.'" >'.$data->user->name.'</option>'; } }else{ echo '<option class="form-control" >Belum Punya Akun</option>'; } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Siswa; use App\kelas; use App\user; use App\absensi_siswa; use App\Role; use Auth; class SiswaController extends Controller { /** * Create a new controller instance. * * @return void */ public function index() { $siswa = siswa::all(); $kelas = kelas::all(); $user = user::all(); return view('siswa.index',compact('kelas','siswa','user')); } public function absen(absensi_siswa $absensi_siswa) { $absensi_siswa = Auth::siswa()->absensi_siswa()->paginate(10); $jumlahIzin::where('keterangan','Izin')->count(); $jumlahSakit::where('keterangan','Sakit')->count(); $jumlahAlfa::where('keterangan','Alfa')->count(); $jumlah_data = count($absensi_siswa['absensi_siswa']); return view('siswa.absen',compact('absensi_siswa','jumlah_data','jumlahAlfa','jumlahSakit','jumlahIzin')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $siswa = siswa::all(); $kelas = kelas::all(); $user = user::all(); return view('siswa.create',compact('kelas','siswa','user')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request,[ 'Nis' => 'required|max:255|unique:siswas', 'Nama' => 'required|min:3|max:255', 'id_kelas' => 'required|max:255', 'jk' => 'required|max:255', 'tempat_lahir' => 'required|max:255', 'tanggal_lahir' => 'required|max:255', 'alamat' => 'required|max:255', 'id_user' => 'required|max:255', ]); $siswa = new siswa; $siswa->Nis = $request->Nis; $siswa->Nama = $request->Nama; $siswa->id_kelas = $request->id_kelas; $siswa->jk = $request->jk ; $siswa->tempat_lahir = $request->tempat_lahir; $siswa->tanggal_lahir = $request->tanggal_lahir; $siswa->alamat = $request->alamat ; $siswa->id_user = $request->id_user ; // dd($siswa); $siswa->save(); return redirect()->route('siswa.index'); } /** * Display the specified resource. * * @param \App\siswa $siswa * @return \Illuminate\Http\Response */ // protected function Creat(array $data) // { // $siswa = siswa::create([ // 'Nis' => $data['Nis'], // 'Nama' => $data['Nama'], // 'id_kelas' => $data['id_kelas'], // 'jk' => $data['jk'], // 'tempat_lahir' => $data['tempat_lahir'], // 'tanggal_lahir' => $data['Nis'], // 'alamat' => $data['alamat'], // ]); // return $siswa; // $user = User::create([ // 'name' => $data['name'], // 'email' => $data['email'], // 'password' => <PASSWORD>($data['password']), // ]); // $memberRole = Role::Where('name' ,'member')->first(); // $user->attachRole($memberRole); // return $user; // } public function show($id) { $siswa = siswa::findOrFail($id); return view('siswa.show',compact('siswa')); } /** * Show the form for editing the specified resource. * * @param \App\siswa $siswa * @return \Illuminate\Http\Response */ public function edit($id) { // memanggil data siswa berdasrkan id di halaman siswa edit $siswa = siswa::findOrFail($id); $kelas = kelas::all(); $selectkelas = siswa::findOrFail($siswa->id)->id_kelas; return view('siswa.edit',compact('kelas','siswa','selectkelas')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\siswa $siswa * @return \Illuminate\Http\Response */ public function update(Request $request,$id) { $this->validate($request,[ 'Nis' => 'required|max:255', 'Nama' => 'required|max:255', 'id_kelas' => 'required|max:255', 'jk' => 'required|max:255', 'tempat_lahir' => 'required|max:255', 'tanggal_lahir' => 'required|max:255', 'alamat' => 'required|max:255', ]); $siswa =siswa::findOrFail($id); $siswa->Nis = $request->Nis; $siswa->Nama = $request->Nama; $siswa->id_kelas = $request->id_kelas; $siswa->jk = $request->jk ; $siswa->tempat_lahir = $request->tempat_lahir; $siswa->tanggal_lahir = $request->tanggal_lahir; $siswa->alamat = $request->alamat ; // dd($siswa); $siswa->save(); return redirect()->route('siswa.index'); } /** * Remove the specified resource from storage. * * @param \App\siswa $siswa * @return \Illuminate\Http\Response */ public function destroy($id) { // delete data beradasarkan id $siswa = siswa::findOrFail($id); $siswa->delete(); return redirect()->route('siswa.index'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\guru; use App\user; class GuruController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $guru = guru::all(); $user = user::all(); return view('guru.index',compact('guru','user')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('guru.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request,[ 'Nik' => 'required|max:255', 'Nama' => 'required|max:255', 'jk' => 'required|max:255', 'tempat_lahir' => 'required|max:255', 'tanggal_lahir' => 'required|max:255', 'alamat' => 'required|max:255', 'id_user' => 'required|max:255', ]); $guru = new guru; $guru->Nik = $request->Nik; $guru->Nama = $request->Nama; $guru->jk = $request->jk ; $guru->tempat_lahir = $request->tempat_lahir; $guru->tanggal_lahir = $request->tanggal_lahir; $guru->alamat = $request->alamat ; $guru->id_user = $request->id_user ; // dd($guru); $guru->save(); return redirect()->route('guru.index'); } /** * Display the specified resource. * * @param \App\guru $guru * @return \Illuminate\Http\Response */ public function show($id) { $guru = guru::findOrFail($id); return view('guru.show',compact('guru')); } /** * Show the form for editing the specified resource. * * @param \App\guru $guru * @return \Illuminate\Http\Response */ public function edit($id) { // memanggil data guru berdasrkan id di halaman guru edit $guru = guru::findOrFail($id); return view('guru.edit',compact('guru')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\guru $guru * @return \Illuminate\Http\Response */ public function update(Request $request,$id) { $this->validate($request,[ 'Nik' => 'required|max:255', 'Nama' => 'required|max:255', 'jk' => 'required|max:255', 'tempat_lahir' => 'required|max:255', 'tanggal_lahir' => 'required|max:255', 'alamat' => 'required|max:255', ]); $guru =guru::findOrFail($id); $guru->Nik = $request->Nik; $guru->Nama = $request->Nama; $guru->jk = $request->jk ; $guru->tempat_lahir = $request->tempat_lahir; $guru->tanggal_lahir = $request->tanggal_lahir; $guru->alamat = $request->alamat ; // dd($guru); $guru->save(); return redirect()->route('guru.index'); } /** * Remove the specified resource from storage. * * @param \App\guru $guru * @return \Illuminate\Http\Response */ public function destroy($id) { // delete data beradasarkan id $guru = guru::findOrFail($id); $guru->delete(); return redirect()->route('guru.index'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Kyslik\ColumnSortable\Sortable; class kelas extends Model { protected $table = 'kelas'; use Sortable; protected $fillable = array('nama_kelas','id_jurusan'); protected $sortable = array('id', 'nama_kelas','id_jurusan'); public $timestamp = true; public function siswa() { return $this->hasMany('App\siswa', 'id_kelas'); } public function jurusan() { return $this->belongsTo('App\jurusan', 'id_jurusan'); } public function absensi_siswa() { return $this->hasMany('App\absensi_siswa', 'id_kelas'); } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\absensi_guru; use App\guru; use App\petugas_piket; use App\User; use Auth; class AbsensiGuruController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $filterA= gallery::where('id_cabangolahraga'); $absensi_guru = absensi_guru::all(); $guru = guru::all(); $petugas_piket = petugas_piket::all(); $user = User::all(); $jumlahIzin= absensi_guru::where('keterangan','Izin')->count(); $jumlahSakit= absensi_guru::where('keterangan','Sakit')->count(); $jumlahAlfa= absensi_guru::where('keterangan','Alfa')->count(); return view('absensi_guru.index',compact('absensi_guru', 'guru','petugas_piket','user','jumlahIzin','jumlahSakit','jumlahAlfa')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function absen() { $absensi_guru = Auth::user()->absensi_guru()->paginate(10); $jumlahIzin= Auth::user()->absensi_guru()->where('keterangan','Izin')->count(); $jumlahSakit= Auth::user()->absensi_guru()->where('keterangan','Sakit')->count(); $jumlahAlfa= Auth::user()->absensi_guru()->where('keterangan','Alfa')->count(); $jumlah_data = count($absensi_guru['absensi_guru']); return view('guru.absen',compact('absensi_guru','jumlah_data','jumlahAlfa','jumlahSakit','jumlahIzin')); } public function create() { $absensi_guru = absensi_guru::all(); $guru = guru::all(); $petugas_piket = petugas_piket::all(); $user = User::all(); return view('absensi_guru.create',compact('absensi_guru', 'guru','petugas_piket','user')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $absensi_guru = absensi_guru::findOrFail($id); return view('absensi_guru.show', compact('absensi_guru')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(absensi_guru $absensi_guru) { $absensi_guru = absensi_guru::findOrFail($absensi_guru->id); $petugas_piket = petugas_piket::all(); $selectpetugaspiket = absensi_guru::findOrFail($absensi_guru->id)->id_PetugasPiket; $guru = guru::all(); $selectguru = absensi_guru::findOrFail($absensi_guru->id)->id_guru; $user = user::all(); $selectuser = absensi_guru::findOrFail($absensi_guru->id)->id_user; return view('absensi_guru.edit',compact('guru','absensi_guru','selectguru','petugas_piket','selectpetugaspiket','user','selectuser')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'id_guru'=>'required|max:255', 'tanggal'=>'required|min:1', 'keterangan'=>'required', 'id_PetugasPiket'=>'required|max:255', 'id_user'=>'required|max:255', ]); $absensi_guru = absensi_guru::findOrFail($id); $absensi_guru->id_guru = $request->id_guru; $absensi_guru->tanggal = $request->tanggal; $absensi_guru->keterangan = $request->keterangan; $absensi_guru->id_PetugasPiket = $request->id_PetugasPiket; $absensi_guru->id_user = $request->id_user; $absensi_guru->save(); return redirect()->route('absensi_guru.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $absensi_guru = absensi_guru::findOrFail($id); $absensi_guru->delete(); return redirect()->route('absensi_guru.index'); } public function filterUser($id) { $user = guru::where('id', $id)->get(); if($user->count() > 0){ foreach ($user as $data) { echo '<option class="form-control" value="'.$data->id_user.'" >'.$data->user->name.'</option>'; } }else{ echo '<option class="form-control" >Belum Punya Akun</option>'; } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class petugas_piket extends Model { protected $table = 'petugas_pikets'; protected $fillable = array('nama_petugas', 'tanggal'); public $timestamp = true; public function absensi_siswa() { return $this->hasMany('App\absensi_siswa', 'id_PetugasPiket'); } // public function absensi_guru() { // return $this->hasMany('App\absensi_guru', 'id_PetugasPiket'); // } } <file_sep><!-- namespace App\Http\Controllers; use Illuminate\Http\Request; use App\absensi_siswa; use App\siswa; use App\kelas; use App\petugas_piket; class LaporanAbsensiSiswaController extends Controller { public function index() { $laporan_absensi_siswa = absensi_siswa::with('siswa','petugas_piket','kelas')->get(); $kelas =kelas::pluck('nama_kelas','id'); return view('laporan_absensi_siswa.index',compact('laporan_absensi_siswa','kelas')); } public function kelasAjax($id){ if ($id==0) { $laporan_absensi_siswa = absensi_siswa::all(); }else{ $laporan_absensi_siswa = absensi_siswa::where('id_kelas','=',$id)->get(); } return $laporan_absensi_siswa; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $kelas = new kelas; $petugas_piket = new petugas_piket; $siswa = new siswa; $laporan_absensi_siswa = absensi_siswa::with('siswa','petugas_piket','kelas')->get(); return view('laporan_absensi_siswa.create',compact('petugas_piket','siswa','kelas','laporan_absensi_siswa')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request,[ 'id_siswa' => 'required|max:255', 'id_kelas' => 'required|max:255', 'tanggal' => 'required|max:255', 'keterangan' => 'required|max:255', 'id_PetugasPiket' => 'required|max:255', ]); $laporan_absensi_siswa = new absensi_siswa; $laporan_absensi_siswa->id_siswa = $request->id_siswa; $laporan_absensi_siswa->id_kelas = $request->id_kelas; $laporan_absensi_siswa->tanggal = $request->tanggal; $laporan_absensi_siswa->keterangan = $request->keterangan ; $laporan_absensi_siswa->id_PetugasPiket = $request->id_PetugasPiket; // dd($laporan_absensi_siswa); $laporan_absensi_siswa->save(); return redirect()->route('laporan_absensi_siswa.index'); } /** * Display the specified resource. * * @param \App\absensi_siswa $laporan_absensi_siswa * @return \Illuminate\Http\Response */ public function show($id) { $laporan_absensi_siswa = absensi_siswa::findOrFail($id); return view('laporan_absensi_siswa.show',compact('absensi_siswa')); } /** * Show the form for editing the specified resource. * * @param \App\absensi_siswa $laporan_absensi_siswa * @return \Illuminate\Http\Response */ public function edit($id) { // memanggil data absensi_siswa berdasrkan id di halaman absensi_siswa edit $laporan_absensi_siswa = absensi_siswa::findOrFail($id); $kelas = kelas::all(); $siswa = jurusan::all(); return view('laporan_absensi_siswa.edit',compact('absensi_siswa')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\absensi_siswa $laporan_absensi_siswa * @return \Illuminate\Http\Response */ public function update(Request $request,$id) { $this->validate($request,[ 'id_siswa' => 'required|max:255', 'id_kelas' => 'required|max:255', 'tanggal' => 'required|max:255', 'keterangan' => 'required|max:255', 'id_PetugasPiket' => 'required|max:255', ]); $laporan_absensi_siswa =absensi_siswa::findOrFail($id); $laporan_absensi_siswa->id_siswa = $request->id_siswa; $laporan_absensi_siswa->id_kelas = $request->id_kelas; $laporan_absensi_siswa->tanggal = $request->tanggal; $laporan_absensi_siswa->keterangan = $request->keterangan ; $laporan_absensi_siswa->id_PetugasPiket = $request->id_PetugasPiket; // dd($laporan_absensi_siswa); $laporan_absensi_siswa->save(); return redirect()->route('laporan_absensi_siswa.index'); } /** * Remove the specified resource from storage. * * @param \App\absensi_siswa $laporan_absensi_siswa * @return \Illuminate\Http\Response */ public function destroy($id) { // delete data beradasarkan id $laporan_absensi_siswa = absensi_siswa::findOrFail($id); $laporan_absensi_siswa->delete(); return redirect()->route('laporan_absensi_siswa.index'); } } --><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('/LoginMember', 'AuthController@getLogin'); Route::post('/LoginMember', 'AuthController@postLogin')->name('loginMember'); Route::get('/RegisterMember', 'AuthController@getRegister'); // Route::post('/RegisterMember', 'AuthController@postRegister')->name('registerMember'); Route::get('/regis', 'SiswaController@create'); Route::post('/RegisterMember', 'SiswaController@creat')->name('registerMember'); Route::get('/', function () { return view('welcome'); }); Route::get('/home', function () { return view('home'); }); Auth::routes(); // Route::group(['prefix'=>'member' ,'middleware'=>['auth','role:member']], // function (){ // Route::get('/',function(){ // return view('member.index'); // }); // Route::get('/absen', 'AbsensiSiswaController@absen')->name('absen'); // Route::get('/absenGuru', 'AbsensiGuruController@absen'); // Route::get('/siswa', 'SiswaController@siswa'); // Route::get('/index', 'AbsensiSiswaController@index'); // Route::get('/index', 'AbsensiSiswaController@index'); // Route::get('Rekap','RekapController@index3'); // Route::post('/laporanabsensi' , 'AbsensiSiswaController@absen')->name('laporanabsensi'); // }); Route::group(['prefix'=>'admin' ,'middleware'=>['auth','role:admin']], function (){ Route::get('/',function(){ return view('admin.index'); }); // Route::post('/RegisterMember', 'SiswaController@create')->name('RegisterMember'); Route::resource('PetugasPiket','PetugasPiketController'); Route::resource('siswa','SiswaController'); Route::resource('guru','GuruController'); Route::resource('kelas','KelasController'); Route::resource('jurusan','jurusanController'); Route::resource('user','userController'); }); Route::group(['prefix'=>'petugaspiket' ,'middleware'=>['auth','role:petugas']], function (){ Route::get('/',function(){ return view('admin.index'); }); Route::resource('absensi_siswa','AbsensiSiswaController'); Route::resource('absensi_guru','AbsensiGuruController'); Route::resource('Rekap','RekapController'); Route::get('Rekapguru','RekapController@index3')->name('Rekapguru'); Route::post('/laporanabsensi' , 'RekapController@index2')->name('laporanabsensi'); Route::post('/laporanabsensiguru' , 'RekapController@index4')->name('laporanabsensiguru'); Route::get('/filter/kelas/{id}', 'AbsensiSiswaController@filter'); Route::get('/filter/user/{id}', 'AbsensiSiswaController@filterUser'); Route::get('/filter/userGuru/{id}', 'AbsensiGuruController@filterUser'); Route::get('/', function () { return view('welcome'); }); }); Route::group(['prefix'=>'siswa' ,'middleware'=>['auth','role:siswa']], function (){ Route::get('/',function(){ return view('member.index'); }); Route::get('/absen', 'AbsensiSiswaController@absen')->name('absen'); Route::get('/siswa', 'SiswaController@siswa'); Route::get('/index', 'AbsensiSiswaController@index'); Route::get('/index', 'AbsensiSiswaController@index'); Route::get('Rekap','RekapController@index3'); }); Route::group(['prefix'=>'guru' ,'middleware'=>['auth','role:guru']], function (){ Route::get('/',function(){ return view('member.index'); }); Route::get('/absenGuru', 'AbsensiGuruController@absen')->name('absenGuru'); Route::get('/siswa', 'SiswaController@siswa'); Route::get('/index', 'AbsensiSiswaController@index'); Route::get('Rekap','RekapController@index3'); ; }); // Templates Auth::routes();
998f23e72dbf09ccb8ab4fce79dd8fc2de88f9bc
[ "PHP" ]
17
PHP
161710089/piketSchool
fa9e4de9cb6844a6ddc75f87d8eaeeff168085ca
25c1c5a808352f95a91bdffaf15e0457017339a5
refs/heads/master
<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMenusTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('menus', function (Blueprint $table) { $table->increments('id'); $table->string('codigo')->unique(); $table->string('nombre'); $table->text('descripcion'); $table->string('precio'); $table->time('tiempo_preparacion'); $table->enum('status', ['disponible', 'agotado'])->default('disponible'); $table->integer('cantidad')->nullable(); $table->integer('categoria_id')->unsigned(); $table->string('imagen')->default('item-default.jpg'); $table->timestamps(); //Relations $table->foreign('categoria_id')->references('id')->on('categorias') ->onDelete('CASCADE') ->onUpdate('CASCADE'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('menus'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Cliente extends Model { protected $fillable = ['user_id', 'dni', 'nombre', 'apellido', 'telefono', 'direccion']; public function user(){ return $this->belongsTo(User::class); } public function mesas(){ return $this->belongsToMany(Mesa::class); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Menu extends Model { protected $fillable = [ 'codigo', 'nombre', 'descripcion', 'precio', 'tiempo_preparacion', 'status', 'cantidad', 'categoria_id', ]; public function categoria(){ return $this->belongsTo(Categoria::class); } public function pedidos(){ return $this->hasMany(Pedido::class); } } <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('/', function () { return view('auth.login'); })->middleware('guest'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::group(['middleware' => ['auth']], function () { Route::resource('clientes', 'ClientesController')->except(['show']); Route::resource('mesas', 'MesasController'); Route::resource('users', 'UsersController'); Route::resource('menus', 'MenusController'); Route::resource('pedidos', 'PedidosController'); Route::resource('facturas', 'FacturasController'); Route::get('clients/verify/{dni}', 'ClientesController@dni_verify'); Route::post('clients/assoc/mesa', 'ClientesController@assoc_client_board')->name('assoc.client'); Route::get('/charge/menu/{categoria}', 'MenusController@charge_menu'); Route::post('/categoria/store', 'MenusController@categoria_store')->name('menu.categoria.store'); Route::post('menus/new_item', 'MenusController@store')->name('menu.item.store'); Route::post('/save/pedido', 'MenusController@save_pedido'); Route::get('/verify/client/facturar/{dni}/{mesa}', 'FacturasController@verify_client'); Route::post('/crear/factura', 'FacturasController@crear')->name('facturas.crear'); }); <file_sep><?php namespace App\Http\Controllers; use App\Mesa; use Illuminate\Http\Request; class MesasController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $mesas = Mesa::all(); $mesas->load('clientes'); return view('mesas.index', compact('mesas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'nro' => 'required|int|unique:mesas,nro', ], [ 'nro.required' => 'Error, Este campo es requerido', 'nro.int' => 'Error, El tipo de dato no es de tipo numerico', 'nro.unique' => 'Error. El nro de mesa ya existe', ]); Mesa::create([ 'nro' => $request->nro, ]); return redirect()->route('mesas.index')->with('success', 'Mesa Registrada con exito'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Factura extends Model { protected $fillable = ['codigo', 'cliente_id', 'fecha', 'subtotal', 'total']; public function cliente(){ return $this->belongsTo(Cliente::class); } public function pedidos(){ return $this->belongsToMany(Pedido::class); } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RequestClienteStore extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required|email', 'password' => '<PASSWORD>', 'dni' => 'required|min:5|unique:clientes,dni', 'nombre' => 'required', 'apellido' => 'required', 'mesa' => 'int', ]; } public function messages(){ return [ 'email.required' => 'Error, Este campo es requerido', 'email.email' => 'Error, El tipo de dato no es de tipo email', 'password.required' => 'Error. Este campo es requerido', 'password.min' => 'Error. La contraseña debe ser de minimo 6 dígitos', 'dni.required' => 'Error. Este campo es requerido', 'dni.min' => 'Error. Longitud invalida', 'dni.unique' => 'Error. Esta cédula ya existe', 'nombre.required' => 'Error. Este campo es requerido', 'apellido.required' => 'Error. Este campo es requerido', 'mesa.integer' => 'Error. Debe selleccionar una mesa', ]; } } <file_sep>function open_pedido(item){ menus.item = item console.log(this.item) $("#modal_new_pedido").modal('show') } const menus = new Vue({ el: '#main', created(){ this.pre_load_menu() }, data: { route: route, categoria: '', menu: [], item: { categoria: { nombre: '' } }, cantidad_item: '', }, methods: { alert_loader(options){ swal({ title: "Espere un momento!", text: options.text, icon: this.route + "/imagenes/"+options.icon+".gif", button: { text: "Entiendo", value: false, closeModal: false, }, closeOnClickOutside: options.click, closeOnEsc: options.esc, dangerMode: true, timer: 10000, }); }, alert_success(options){ // text, click, esc, time = false swal({ title: "Excelente!", text: options.text, icon: "success", button: { text: "Ok" }, dangerMode: true, closeOnClickOutside: options.click, closeOnEsc: options.esc, timer: options.time, }); }, pre_load_menu(){ this.categoria = $("#categoria").val() let url_charge_menu = this.route + '/charge/menu/' + this.categoria axios.get(url_charge_menu).then(response => { //console.log(response.data) this.menu = response.data.menu }).catch(error => { console.log(error) console.log(error.response) }) }, open_pedido(item){ this.item = item console.log(this.item) $("#modal_new_pedido").modal('show') }, save_pedido(){ let url = this.route + "/save/pedido" axios.post(url, {item: this.item, cantidad: this.cantidad_item}).then(response => { /* console.log(response.status) console.log(response.data) */ toastr.success('Pedido Realizado con exito!', 'Excelente!.') $("#modal_new_pedido").modal('hide') this.pre_load_menu() }).catch(error => { console.log(error) console.log(error.response.status) if(error.response.status == 500){ toastr.error(error.response.data.message, 'Atención!'); } }) } } });<file_sep><?php namespace App\Http\Controllers; use Auth; use App\Menu; use App\Pedido; use App\Categoria; use Illuminate\Http\Request; class MenusController extends Controller { public function index(){ //$menus = Menu::where('status', 'disponible')->get(); $categorias = Categoria::all(); return view('menus.index', compact('categorias')); } public function charge_menu($categoria){ $menu = Menu::where('status', 'disponible')->where('categoria_id', $categoria)->get(); $menu->load('categoria'); return response()->json([ 'menu' => $menu ], 200); } public function categoria_store(Request $request){ $this->validate($request, [ 'nombre' => 'required|unique:categorias,nombre', ], [ 'nombre.unique' => 'Error. Este nombre ya existe', ]); $cat = categoria::where('nombre', strtolower($request->nombre))->first(); if($cat != null){ return back()->with('error', 'La categoria ingresada ya se encuentra registrada!.'); } //dd($request->all()); $categoria = Categoria::create($request->all()); return redirect()->route('menus.index')->with('success', 'Categoria: '.$request->nombre.' registrada con exito!.'); } public function store(Request $request){ $this->validate($request, [ 'codigo' => 'required|unique:menus,codigo', ], [ 'codigo.unique' => 'Error. Este codigo ya existe', ]); $menu = Menu::create([ 'codigo' => $request->codigo, 'nombre' => $request->nombre, 'descripcion' => $request->descripcion, 'precio' => $request->precio, 'tiempo_preparacion' => $request->tiempo_preparacion.':00', 'status' => $request->status, 'cantidad' => $request->cantidad, 'categoria_id' => $request->categoria, ]); return redirect()->route('menus.index')->with('success', 'Item: '.$request->nombre.' registrado con exito!.'); } public function save_pedido(Request $request){ if(count(Auth::user()->cliente->mesas) == 0){ return response()->json([ 'message' => 'Usted no tiene una mesa asignada', ], 500); } else { if(Auth::user()->cliente != null){ $pedido = Pedido::create([ 'nro_orden' => random_int(1000, 100000), 'mesa_id' => Auth::user()->cliente->mesas[0]->id, 'cliente_id' => Auth::user()->cliente->id, 'menu_id' => $request->item['id'], 'cantidad' => $request->cantidad, 'status' => 'en_espera', ]); } return response()->json([ 'message' => 'success' ], 200); } } } <file_sep><?php namespace App\Http\Controllers; use Auth; use App\User; use App\Mesa; use App\Cliente; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Http\Requests\RequestClienteStore; class ClientesController extends Controller { public function index() { $mesas = Mesa::where('status', 'disponible')->get(); $clientes = Cliente::all(); //$clientes->load('user'); //dd($clientes); return view('clientes.index', compact('clientes', 'mesas')); } public function create() { return view('clients.create'); } public function dni_verify($dni){ $cliente = Cliente::where('dni', $dni)->first(); return response()->json(['cliente' => $cliente]); } public function store(RequestClienteStore $request) { //dd($request->all()); $user = User::where('email', $request->email)->first(); if($request->telefono != null){ $this->validate($request, [ 'telefono' => 'unique:clientes,telefono', ], [ 'telefono.unique' => 'Error. Este telefono ya existe', ]); } $mesa = Mesa::findOrFail($request->mesa); if($mesa->clientes->count() > 0){ return back()->with('error', 'La mesa seleccionada no se encuentra disponible'); } if($user == null){ $this->validate($request, [ 'email' => 'unique:users,email', ], [ 'email.unique' => 'Error. Este correo ya existe', ]); $user = User::create([ 'email' => $request->email, 'password' => <PASSWORD>::make($request->password), ]); } else { if($user->cliente != null){ return back()->with('error', 'El email ingresado ya pertenece a un cliente!.'); } } $cliente = Cliente::create([ 'user_id' => $user->id, 'dni' => $request->dni, 'nombre' => $request->nombre, 'apellido' => $request->apellido, 'telefono' => $request->telefono, 'direccion' => $request->direccion, ]); $cliente->mesas()->attach($mesa); $mesa->status = 'ocupada'; $mesa->update(); return redirect()->route('clientes.index')->with('success', 'Cliente Registrado con exito'); } public function assoc_client_board(Request $request) { $this->validate($request, [ 'mesa' => 'int', ], [ 'mesa.integer' => 'Error. Debe selleccionar una mesa', ]); $cliente = Cliente::where('dni', $request->dni)->first(); $mesa = Mesa::findOrFail($request->mesa); $cliente->mesas()->attach($mesa); $mesa->status = 'ocupada'; $mesa->update(); return redirect()->route('clientes.index')->with('success', 'Cliente agregado a la mesa #'.$mesa->nro); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Pedido extends Model { protected $fillable = ['nro_orden', 'mesa_id', 'cliente_id', 'menu_id', 'cantidad', 'status']; public function mesa(){ return $this->belongsTo(Mesa::class); } public function cliente(){ return $this->belongsTo(Cliente::class); } public function menu(){ return $this->belongsTo(Menu::class); } public function facturas(){ return $this->belongsToMany(Factura::class); } } <file_sep><?php namespace App\Http\Controllers; use App\Pedido; use Illuminate\Http\Request; class PedidosController extends Controller { public function index(){ $fecha = date('Y-m-d'); $fecha1 = $fecha.' 00:00:00'; $fecha2 = $fecha.' 23:59:59'; $pedidos = Pedido::whereBetween('created_at', [$fecha1, $fecha2])->orderBy('id', 'asc')->get(); //dd($pedidos); return view('pedidos.index', compact('pedidos')); } } <file_sep><?php namespace App\Http\Controllers; use App\Mesa; use App\Cliente; use App\Factura; use App\Configuracion; use Illuminate\Http\Request; class FacturasController extends Controller { public function index(){ $mesas = Mesa::where('status', 'ocupada')->get(); $facturas = Factura::orderBy('id', 'desc')->get(); return view('facturas.index', compact('facturas', 'mesas')); } public function verify_client($dni, $mesa){ $mesa_obj = null; $pedidos = null; $cliente_obj = Mesa::findOrFail($mesa)->clientes()->where('dni', $dni)->first(); $cliente = Cliente::where('dni', $dni)->first(); if($cliente != null){ $mesa_obj = $cliente->mesas()->find($mesa); if($mesa_obj != null){ $pedidos = $mesa_obj->pedidos() ->where('status', '!=', 'cancelado') ->where('status', '!=', 'pagado') ->where('cliente_id', $cliente->id) ->get(); } //dd($mesa_obj); } return response()->json([ 'mesa' => $mesa_obj, 'cliente' => $cliente_obj, 'pedidos' => $pedidos, ], 200); } public function crear(Request $request){ $dni = $request->dni; $mesa = $request->mesa; $factura_id = 1; $data = $this->verify_client($dni, $mesa)->original; $mesa_obj = $data['mesa']; $cliente = $data['cliente']; $pedidos = $data['pedidos']; $conf = Configuracion::first(); $invoice_code = 'F'.random_int(100, 1000).strtoupper(str_random('1').random_int(100, 1000)); $factura = Factura::orderBy('id', 'desc')->first(); if($factura != null){ $factura_id = $factura->id; } //dd($invoice_code); return view('facturas.create', compact('mesa_obj', 'cliente', 'pedidos', 'conf', 'dni', 'mesa','factura_id', 'invoice_code')); } public function store(Request $request){ $data = $this->verify_client($request->dni, $request->mesa)->original; $mesa_obj = $data['mesa']; $cliente = $data['cliente']; $pedidos = $data['pedidos']; $factura = Factura::create([ 'codigo' => $request->codigo, 'cliente_id' => $cliente->id, 'fecha' => date('Y-m-d h:m'), 'subtotal' => $request->subtotal, 'total' => $request->total ]); $factura->pedidos()->attach($pedidos); foreach ($pedidos as $pedido) { $ped = Pedido::find($pedido->id); $ped->status = 'pagado'; $ped->update; } $cliente->mesas()->detach($mesa_obj); $mesa_obj->status = 'disponible'; $mesa_obj->update(); //dd($factura); return redirect()->route('facturas.index')->with('success', 'Factura y pago creados con exito!.'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Mesa extends Model { protected $fillable = ['nro', 'status']; public function clientes(){ return $this->belongsToMany(Cliente::class); } public function pedidos(){ return $this->hasMany(Pedido::class); } }
f239047b47a10e1448c9d1edae553a29f01f2bff
[ "JavaScript", "PHP" ]
14
PHP
CessareJulius/la_cascada
942832a539feef0bbd5f307cf3f9cb6aa713fb7b
f19b0ce507b7e89587c3170c40597e25e85e3ecd
refs/heads/master
<repo_name>Logarathon1/space-bot<file_sep>/README.md # Interstellar Bot 1973 Submission by Team 'certified bot moment' for the 2020 BAS Hackathon Category: Facebook, supplemental Discord component included All code and art written and created by <NAME> (Discord: Logarathon#6969) This is Interstellar Bot 1973, a bot that simulates the voyage of an exploratory spaceship. The bot runs in real-time, rolling the chance for an encounter to occur every minute, and posting a report of what encounters have occurred to Facebook every hour. Encounters will have various effects on each of the ship's systems and resources, and as time progresses the 'story' of the ship will too. While there is no scripted story that is followed, notable encounters are recorded and can be accessed via the supplemental Discord Bot, as can a report on the status of the vessel Additionally, crew member names can be submitted either via the comments section of a specific Facebook post, or through moderated Discord submissions. Facebook entries are not moderated as they are taken directly from the commenter's profile name. <file_sep>/main.js // // Submission by Team 'certified bot moment' for the 2020 BAS Hackathon // Category: Facebook, supplemental Discord component included // All code and art written and created by <NAME> (Discord: Logarathon#6969) // // This is Interstellar Bot 1973, a bot that simulates the voyage of an exploratory spaceship. // The bot runs in real-time, rolling the chance for an encounter to occur every minute, and // posting a report of what encounters have occurred to Facebook every hour. // // Encounters will have various effects on each of the ship's systems and resources, and as time // progresses the 'story' of the ship will too. While there is no scripted story that is followed, // notable encounters are recorded and can be accessed via the supplemental Discord Bot, as can a // report on the status of the ship. // // Additionally, crew member names can be submitted either via the comments section of a specific // Facebook post, or through moderated Discord submissions. Facebook entries are not moderated as // they are taken directly from the commenter's profile name. // const FB = require('fb') const discord = require ('discord.js'); const fs = require("fs"); const cron = require("node-cron"); //const Jimp = require('jimp'); //const express = require('express'); const path = require('path') // comment this out if you want it to work // or supply your own tokens, i'm not your dad const fbtoken = fs.readFileSync("./fbtoken.txt") const disctoken = fs.readFileSync("./disctoken.txt") const prefix = "io!"; var client = new discord.Client(); client.login (disctoken.toString()); // this file contains all of the space events that can be encountered by the ship // some of the events have conditions that will either be met or not, with the outcome dependant on it // based on a scoring system, events require a certain amount of conditions to be met, if so a success // is given, and if not a failure is given, other events do not have conditions, and will have a fixed // outcome that may or may not reward punish the ship and it's crew var encounters = JSON.parse(fs.readFileSync("./encounters.json")); var shipnames = JSON.parse(fs.readFileSync("./shipnames.json")); var crewnames = JSON.parse(fs.readFileSync("./crewnames.json")); FB.setAccessToken(fbtoken.toString()); FB.api("/101226241694587_102150188268859/comments", function (response) { if (response.error) { console.log(response); } else if (!response.data[0]) { } else if (response && !response.error) { for (i = 0; i < response.data.length; i++) { crewnames.push(response.data[i].from.name) } } }); var encounterSel var toPost = ""; var hourlyData = ""; var inputData; var stdin = process.openStdin(); stdin.addListener ("data", function (d) { // allows encounters to be 'forced' by pressing enter in the console window a few times console.log("input = [" + d.toString().trim() + "]"); inputData = d.toString().trim(); run(); }) cron.schedule('0 * * * *', () => { console.log(getTimeStamp() + '] Post report to FB'); FB.setAccessToken(fbtoken.toString()); // load up crew member names crewnames = JSON.parse(fs.readFileSync("./crewnames.json")); FB.api("/101226241694587_102150188268859/comments", function (response) { if (response.error) { console.log(response); } else if (!response.data[0]) { } else if (response && !response.error) { for (i = 0; i < response.data.length; i++) { response.data[i].from.name crewnames.push(response.data[i].from.name) } } }); // load post data toPost = fs.readFileSync("./to-post.txt").toString() // do all of the hourly stuff hourlyData = ""; // life support tick if ((ship.lifeSupport / 100) < Math.random()) { ship.oxygen--; hourlyData += "\nShip oxygen levels have decreased due to damaged life support" } // oxygen tick if (ship.oxygen < 20) { // kill someone // anyone deadPerson = ship.crew.splice(Math.floor(Math.random() * ship.crew.length), 1) hourlyData += "\n" + deadPerson.rank + " " + deadPerson.name + " has died due to insufficent oxygen levels" } // solar tick if ((ship.solarArray / 50) < Math.random()) { ship.power--; hourlyData += "\nShip power levels have decreased due to damaged solar array" } else if (ship.power < 100){ ship.power++; hourlyData += "\nShip power levels have increased" } // fuel tick if (ship.fuel > 0) { ship.fuel--; ship.speed = Number(Number(ship.speed) + Number((Math.random() * 20 + 10).toFixed(2))).toFixed(2); hourlyData += "\nShip has accelerated, new speed: " + ship.speed + "km/s" } else { ship.sensors--; ship.lifeSupport--; ship.oxygenSensor--; ship.powerSensor--; ship.fuelSensor--; ship.scienceSensor--; ship.solarArray--; ship.scienceDatabase--; ship.shipComputer--; ship.speed = Number(Number(ship.speed) + Number((Math.random() * 20 + 10).toFixed(2))).toFixed(2); hourlyData += "\nShip has accelerated, necessary energy diverted from subsystems, new speed: " + ship.speed + "km/s" } // power tick if ((ship.power / 100) < Math.random()) { switch (Math.floor(Math.random() * 10)) { case 0: ship.sensors--; hourlyData += "\nGeneral sensors have been damaged due to insufficient power" break; case 1: ship.lifeSupport--; hourlyData += "\nLife support has been damaged due to insufficient power" break; case 2: ship.oxygenSensor--; hourlyData += "\nOxygen sensors have been damaged due to insufficient power" break; case 3: ship.powerSensor--; hourlyData += "\nPower sensors have been damaged due to insufficient power" break; case 4: ship.fuelSensor--; hourlyData += "\nFuel sensors have been damaged due to insufficient power" break; case 5: ship.scienceSensor--; hourlyData += "\nScientific sensors have been damaged due to insufficient power" break; case 6: ship.solarArray--; hourlyData += "\nSolar array has been damaged due to insufficient power" break; case 7: ship.scienceDatabase--; hourlyData += "\nScience database have been damaged due to insufficient power" break; case 8: ship.shipComputer--; hourlyData += "\nShip computer has been damaged due to insufficient power" break; case 9: ship.shipIntegrity--; hourlyData += "\nShip integrity has been damaged due to insufficient power" break; } } // post toPost if (toPost) { toPost = "[Mission Report - " + ship.name + " - " + getDistanceStamp() + hourlyData + "\n\nNotable Events:" + toPost; } else { toPost = "[Mission Report - " + ship.name + " - " + getDistanceStamp() + hourlyData + "\n\nNotable Events:" + "\nNo recent events of note"; } console.log(toPost); FB.api('me/photos', 'post', { source: fs.createReadStream('./icon.png'), caption: toPost }, function (res) { if(!res || res.error) { console.log(!res ? 'error occurred' : res.error); return true; } console.log(getTimeStamp() + "Posted Successfully!"); console.log(getTimeStamp() + 'Post Id: ' + res.id); FB.api(res.id + '/comments', 'post', { message: "[Operational Report]\n" + getShipInfo() }, function (comm) { if(!comm || comm.error) { console.log(!comm ? 'error occurred' : comm.error); return true; } console.log(getTimeStamp() + "Comment Posted Successfully!"); }); }); fs.writeFileSync("./ship.json",JSON.stringify(ship)) hourlyData = ""; toPost = ""; fs.writeFileSync("./to-post.txt",toPost) }); cron.schedule('0 1-59 * * * *', () => { console.log(getTimeStamp() + '] Generate info for report'); run(); }); client.on ("ready", () => { console.log ("Bot Online"); client.user.setActivity ("the stars || io!help", {type: "WATCHING"}); }); client.on ("message", (message) => { if (message.author.bot) return; ship = JSON.parse(fs.readFileSync("./ship.json")); var newMessage = message.content if (newMessage.startsWith (prefix)) { newMessage = newMessage.split("!"); switch (newMessage[1]) { case "status": var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Operational Report]") .addField("[" + getDistanceStamp(),getShipInfo()); message.channel.send({embed}); break; case "report": toPost = fs.readFileSync("./to-post.txt").toString(); if (toPost) { var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Mission Report]") .addField("[Notable Events]",toPost); } else { var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Mission Report]") .addField("[Notable Events]","No recent events of note"); } message.channel.send({embed}); break; case "crew": if (newMessage[2]) { if (newMessage[2] <= ship.crew.length && newMessage[2] > 0) { var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Crew Member Report]") .addField("[" + ship.crew[newMessage[2] - 1].name + "]","Position: " + ship.crew[newMessage[2] - 1].rank + "\nAge: " + ship.crew[newMessage[2] - 1].age + "\nNotes: " + ship.crew[newMessage[2] - 1].notes); } else { var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Crew Report]") .addField("[Total Crew Count: " + ship.crew.length + "]","Crew Peformance: " + getCrewPerformance() + "\nEntered number out of bounds: Enter a number between 1 and " + (ship.crew.length) + " inclusive to view a specific crew member"); } } else { var embed = new discord.MessageEmbed() .setTitle(getTimeStamp() + " - " + ship.name + " Crew Report]") .addField("[Total Crew Count: " + ship.crew.length + "]","Crew Peformance: " + getCrewPerformance()); } message.channel.send({embed}); break; case "submit": if (newMessage[2]) { names = JSON.parse(fs.readFileSync("./crewnames-pending.json")) names.push(newMessage[2]) fs.writeFileSync("./crewnames-pending.json",JSON.stringify(names)) var embed = new discord.MessageEmbed() .setTitle("[Interstellar Mission Registration]") .addField("[Submission Received]","Pending moderation and approval"); } else { var embed = new discord.MessageEmbed() .setTitle("[Interstellar Mission Registration]") .addField("[Submission Fail]","Empty Submission"); } message.channel.send({embed}); break; case "shipname": if (newMessage[2]) { names = JSON.parse(fs.readFileSync("./shipnames-pending.json")) names.push(newMessage[2]) fs.writeFileSync("./shipnames-pending.json",JSON.stringify(names)) var embed = new discord.MessageEmbed() .setTitle("[Ship Name Registry]") .addField("[Submission Received]","Pending moderation and approval"); } else { var embed = new discord.MessageEmbed() .setTitle("[Ship Name Registry]") .addField("[Submission Failed]","Empty submission"); } message.channel.send({embed}); break; case "help": var embed = new discord.MessageEmbed() .setTitle("[Interstellar Observer]") .addField("Communications interface for vessel " + ship.name,"Available Commands:") .addField("io!status","Displays current operational status of vessel") .addField("io!report","Displays current mission report") .addField("io!crew","Displays current crew roster, input io!crew![#] for specific member information") .addField("io!submit!<name>","Enter a name into the crew member pool for future selection") .addField("io!shipname!<name>","Enter a name into the ship name pool for future selection") .addField("io!help","Displays this command directory"); message.channel.send({embed}); break; } } }); function run () { // load post data toPost = fs.readFileSync("./to-post.txt").toString(); if (JSON.parse(fs.readFileSync("./in-run.json")) == true) { ship = JSON.parse(fs.readFileSync("./ship.json")); } else { ship = new Ship() toPost += "\n" + getTimeStamp() + "] Launch successful, Interstellar Exploratory Vessel designation " + ship.name + " underway at speed " + ship.speed + "km/s\nTotal crew complement of " + ship.crew.length + ", captained by " + ship.crew[0].name fs.writeFileSync("./ship.json",JSON.stringify(ship)) fs.writeFileSync("./runs/" + ship.name + ".txt","Ship Designation: " + ship.name + toPost) fs.writeFileSync("./in-run.json",JSON.stringify(true)) fs.writeFileSync("./to-post.txt",toPost) } // check if the ship was destroyed by the last encounter if (checkDead() != 0) { toPost += "\n\n" + getTimeStamp() + "] "; switch (checkDead()) { case 1: toPost += "Irrepairable damage to ship sustained, multiple system failures, vessel " + ship.name + " has been destroyed" break; case 2: toPost += "All crew members have perished, vessel " + ship.name + " has been lost" break; } console.log(toPost); runInfo = fs.readFileSync("./runs/" + ship.name + ".txt") runInfo += toAdd; fs.writeFileSync("./runs/" + ship.name + ".txt",runInfo) fs.writeFileSync("./ship.json",JSON.stringify(ship)) toPost = "[Mission Report - " + ship.name + " - " + getDistanceStamp() + toPost; console.log(toPost); FB.api('me/photos', 'post', { source: fs.createReadStream('./icon.png'), caption: toPost }, function (res) { if(!res || res.error) { console.log(!res ? 'error occurred' : res.error); return true; } console.log(getTimeStamp() + "Posted Successfully!"); console.log(getTimeStamp() + 'Post Id: ' + res.id); FB.api(res.id + '/comments', 'post', { message: "[Operational Report]\n" + getShipInfo() }, function (comm) { if(!comm || comm.error) { console.log(!comm ? 'error occurred' : comm.error); return true; } console.log(getTimeStamp() + "Comment Posted Successfully!"); }); }); toPost = ""; ship = new Ship() toPost += "\n" + getTimeStamp() + "] Launch successful, Interstellar Exploratory Vessel designation " + ship.name + " underway at speed " + ship.speed + "km/s\nTotal crew complement of " + ship.crew.length + ", captained by " + ship.crew[0].name fs.writeFileSync("./runs/" + ship.name + ".txt","Ship Designation: " + ship.name + toPost) fs.writeFileSync("./in-run.json",JSON.stringify(true)) } // roll chance for encounter // a 4% chance should work for now, can tweak later if (Math.random() < 0.04) { // if successful, wait between one and fifty five seconds for added randomness var delayTime = Math.floor(Math.random() * 55) console.log(getTimeStamp() + "] Encounter Successful, waiting " + delayTime + " seconds") setTimeout(function () { console.log(getTimeStamp() + "] Encounter would go at this time") // need to generate the encounter here encounterSel = encounters[Math.floor(Math.random() * encounters.length)]; var toAdd = "\n\n" + getTimeStamp() + "] " + encounterSel.encounterText; // check if encounter has a success condition // i hope you like if statements if (encounterSel.condition) { // if so then check if enough conditions are met // resources (oxygen, fuel, power) award score if the required amount is present // systems (all sensors, life support, etc) will roll a chance based on their integrity // science can roll on either chance or quantity depending on the encounter // ship integrity will always roll on both methods var score = 0; // resources if (encounterSel.condition.reqOxygen && ship.oxygen > encounterSel.condition.reqOxygen) { score++; } if (encounterSel.condition.reqFuel && ship.fuel > encounterSel.condition.reqFuel) { score++; } if (encounterSel.condition.reqPower && ship.power > encounterSel.condition.reqPower) { score++; } if (encounterSel.condition.reqScience && ship.scienceDatabase > encounterSel.condition.reqScience) { score++; } if (encounterSel.condition.reqShipIntegrity && ship.shipIntegrity > encounterSel.condition.reqShipIntegrity) { score++; } // systems if (encounterSel.condition.reqLifeSupport && Math.random() < (ship.lifeSupport / 100)) { score++; } if (encounterSel.condition.reqSensors && Math.random() < (ship.sensors / 100)) { score++; } if (encounterSel.condition.reqOxygenSensor && Math.random() < (ship.oxygenSensor / 100)) { score++; } if (encounterSel.condition.reqFuelSensor && Math.random() < (ship.fuelSensor / 100)) { score++; } if (encounterSel.condition.reqPowerSensor && Math.random() < (ship.powerSensor / 100)) { score++; } if (encounterSel.condition.reqScienceSensor && Math.random() < (ship.scienceSensor / 100)) { score++; } if (encounterSel.condition.reqScienceDatabase && Math.random() < (ship.scienceDatabase / 100)) { score++; } if (encounterSel.condition.reqShipComputer && Math.random() < (ship.shipComputer / 100)) { score++; } if (encounterSel.condition.reqSolarArray && Math.random() < (ship.solarArray / 100)) { score++; } if (encounterSel.condition.reqShipIntegrity && Math.random() < (ship.shipIntegrity / 100)) { score++; } if (score >= encounterSel.score) { // success toAdd += encounterSel.success.successText; toPost += toAdd; console.log(toPost); // update resources and systems // i'm sure there's a more efficient way to do this if (encounterSel.success.oxygen) { ship.oxygen += encounterSel.success.oxygen } if (encounterSel.success.fuel) { ship.fuel += encounterSel.success.fuel } if (encounterSel.success.power) { ship.power += encounterSel.success.power } if (encounterSel.success.science) { ship.scienceDatabase += encounterSel.success.science } if (encounterSel.success.speed) { ship.speed = Number(Number(encounterSel.success.speed) + Number(ship.speed)).toFixed(2) } if (encounterSel.success.lifeSupport) { ship.lifeSupport += encounterSel.success.lifeSupport } if (encounterSel.success.sensors) { ship.sensors += encounterSel.success.sensors } if (encounterSel.success.oxygenSensor) { ship.oxygenSensor += encounterSel.success.oxygenSensor } if (encounterSel.success.fuelSensor) { ship.fuelSensor += encounterSel.success.fuelSensor } if (encounterSel.success.powerSensor) { ship.powerSensor += encounterSel.success.powerSensor } if (encounterSel.success.scienceSensor) { ship.scienceSensor += encounterSel.success.scienceSensor } if (encounterSel.success.shipComputer) { ship.shipComputer += encounterSel.success.shipComputer } if (encounterSel.success.shipIntegrity) { ship.shipIntegrity += encounterSel.success.shipIntegrity } if (encounterSel.success.solarArray) { ship.solarArray += encounterSel.success.solarArray } if (encounterSel.success.crew) { if (encounterSel.success.crew < 0) { for (i = 0; i > encounterSel.success.crew; i--) { deadPerson = ship.crew.splice(Math.floor(Math.random() * ship.crew.length), 1) toAdd += "\n<" + deadPerson.rank + " " + deadPerson.name + " deceased>" } } } } else { // fail toAdd += encounterSel.failure.failText; toPost += toAdd; console.log(toPost); // update resources and systems // yes, this is the same code as above if (encounterSel.failure.oxygen) { ship.oxygen += encounterSel.failure.oxygen } if (encounterSel.failure.fuel) { ship.fuel += encounterSel.failure.fuel } if (encounterSel.failure.power) { ship.power += encounterSel.failure.power } if (encounterSel.failure.science) { ship.scienceDatabase += encounterSel.failure.science } if (encounterSel.failure.speed) { ship.speed = Number(Number(encounterSel.failure.speed) + Number(ship.speed)).toFixed(2) } if (encounterSel.failure.lifeSupport) { ship.lifeSupport += encounterSel.failure.lifeSupport } if (encounterSel.failure.sensors) { ship.sensors += encounterSel.failure.sensors } if (encounterSel.failure.oxygenSensor) { ship.oxygenSensor += encounterSel.failure.oxygenSensor } if (encounterSel.failure.fuelSensor) { ship.fuelSensor += encounterSel.failure.fuelSensor } if (encounterSel.failure.powerSensor) { ship.powerSensor += encounterSel.failure.powerSensor } if (encounterSel.failure.scienceSensor) { ship.scienceSensor += encounterSel.failure.scienceSensor } if (encounterSel.failure.shipComputer) { ship.shipComputer += encounterSel.failure.shipComputer } if (encounterSel.failure.shipIntegrity) { ship.shipIntegrity += encounterSel.failure.shipIntegrity } if (encounterSel.failure.solarArray) { ship.solarArray += encounterSel.failure.solarArray } if (encounterSel.failure.crew) { if (encounterSel.failure.crew < 0) { for (i = 0; i > encounterSel.failure.crew; i--) { deadPerson = ship.crew.splice(Math.floor(Math.random() * ship.crew.length), 1) toAdd += "\n<" + deadPerson.rank + " " + deadPerson.name + " deceased>" } } } } // check that resources are not over capacity if (ship.oxygen > 100) { ship.oxygen = 100; } if (ship.power > 100) { ship.power = 100; } if (ship.fuel > 100) { ship.fuel = 100; } if (ship.scienceDatabase > 100) { ship.scienceDatabase = 100; } } else { if (encounterSel.oxygen) { ship.oxygen += encounterSel.oxygen } if (encounterSel.fuel) { ship.fuel += encounterSel.fuel } if (encounterSel.power) { ship.power += encounterSel.power } if (encounterSel.science) { ship.scienceDatabase += encounterSel.science } if (encounterSel.speed) { ship.speed = Number(Number(encounterSel.speed) + Number(ship.speed)) } if (encounterSel.lifeSupport) { ship.lifeSupport += encounterSel.lifeSupport } if (encounterSel.sensors) { ship.sensors += encounterSel.sensors } if (encounterSel.oxygenSensor) { ship.oxygenSensor += encounterSel.oxygenSensor } if (encounterSel.fuelSensor) { ship.fuelSensor += encounterSel.fuelSensor } if (encounterSel.powerSensor) { ship.powerSensor += encounterSel.powerSensor } if (encounterSel.scienceSensor) { ship.scienceSensor += encounterSel.scienceSensor } if (encounterSel.shipComputer) { ship.shipComputer += encounterSel.shipComputer } if (encounterSel.shipIntegrity) { ship.shipIntegrity += encounterSel.shipIntegrity } if (encounterSel.solarArray) { ship.solarArray += encounterSel.solarArray } if (encounterSel.crew) { if (encounterSel.crew < 0) { for (i = 0; i > encounterSel.crew; i--) { deadPerson = ship.crew.splice(Math.floor(Math.random() * ship.crew.length), 1) toAdd += "\n<" + deadPerson.rank + " " + deadPerson.name + " deceased>" } } } if (ship.oxygen > 100) { ship.oxygen = 100; } if (ship.power > 100) { ship.power = 100; } if (ship.fuel > 100) { ship.fuel = 100; } if (ship.scienceDatabase > 100) { ship.scienceDatabase = 100; } toPost += toAdd; console.log(toPost); } runInfo = fs.readFileSync("./runs/" + ship.name + ".txt") runInfo += toAdd; fs.writeFileSync("./to-post.txt",toPost) fs.writeFileSync("./runs/" + ship.name + ".txt",runInfo) fs.writeFileSync("./ship.json",JSON.stringify(ship)) }, delayTime * 1000); } } class Ship { constructor () { // all names will be taken from an external JSON file this.name = shipnames[Math.floor(Math.random() * shipnames.length)] // ship needs various stats to keep balanced // things like oxygen, power, fuel, technical systems like sensors, databases, crew options too // oxygen can only be decreased by encounters, or if the life support system is damaged // oxygen level will only rarely go up // low levels will negatively impact the crew this.oxygen = 100; // life support can be damaged and repaired by random encounters // every hour, life support decided whether the oxygen level decreases or remains constant // at 100, there is a 0% chance to decrease, at 90 there is a 10% chance, at 50 a 50% chance, and so on this.lifeSupport = 100; // fuel can be increased and decreased by encounters // every hour, fuel will decrease by one // when fuel runs out, excess power will be required to run the ship // this means that systems such as life support, sensors, and the databases will each decrease by one per hour this.fuel = 100; // can be increased or decreased via encounters // works similarly to life support, except that it drains from a random system // this can be life support, sensors, database, etc this.power = 100; // general sensors, have an effect on resources gained from certain encounters, specific sensor ability this.sensors = 100; // increases the chance of oxygen being gained from encounters this.oxygenSensor = 100; // increases the chance of fuel being gained from encounters this.fuelSensor = 100; // increases the chance of power being gained from encounters this.powerSensor = 100; // related to the amount of science gained from scientific encounters this.scienceSensor = 100; // increases the yields of resource related encounters, boosts the success chance of some encounters this.scienceDatabase = 20; // the integrity of the ship's computer, at lower levels corruption occurs and can damage ship systems and resources this.shipComputer = 100; // the integrity of the solar array, below 50% power will drain at a rate of 1 per hour this.solarArray = 100; // the integrity of the ship itself, it degrading has a chance to kill the crew // also encompasses propulsion systems // at 0 the ship is destroyed this.shipIntegrity = 100; // the speed of the ship in km/s // used for distance purposes, can be affected by encounters this.speed = (Math.random() * 16 + 8).toFixed(2); // distance travelled in km this.distanceKM = 0; // distance travelled in light years this.distanceLY = 0 // the time of last encounter (initially launch) in seconds, used for distance calculations var date = new Date(); this.previousEncounterTime = date.getTime(); // big list of people, semi-random length this.crew = [] // was having an issue with i not existing, stupid bot var i = 0; var totalCrew = Math.floor(Math.random() * 200 + 100); for (i = 0; i < totalCrew; i++) { if (crewnames.length > 0) { this.crew.push(new Person(crewnames.splice(Math.floor(Math.random() * crewnames.length), 1), i)) } else { this.crew.push(new Person("Crew Member " + (i + 1), i)) } } } } class Person { // makes people constructor (name, rank) { this.name = name if (rank == 0){ this.rank = "Captain" } else if (rank == 1) { this.rank = "Commander" } else if (rank < 4) { this.rank = "Lieutentant Commander" } else if (rank < 8) { this.rank = "Lieutentant" } else if (rank < 16) { this.rank = "Lieutentant JR" } else if (rank < 64) { this.rank = "Ensign" } else { this.rank = "Civilian" } this.age = Math.floor(Math.random() * 55 + 17); this.notes = "Nothing to note" } } function checkDead () { if (ship.integrity < 1) { return 1; } if (ship.crew.length < 1) { return 2; } return 0; } function getShipInfo () { shipInfo = "Current Speed: " + ship.speed + "km/s\n\n" shipInfo += "Total System Status: " + getSystemStatus(getTotalSystemsValue()) + "\n"; shipInfo += "Ship Integrity: " + getSystemStatus(ship.shipIntegrity) + "\n"; shipInfo += "Sensor Grid: " + getSystemStatus((ship.sensors + ship.oxygenSensor + ship.powerSensor + ship.fuelSensor + ship.scienceSensor)/5) + "\n" shipInfo += "Life Support: " + getSystemStatus(ship.lifeSupport) + "\n"; shipInfo += "Solar Array: " + getSystemStatus(ship.solarArray) + "\n"; shipInfo += "Computer Core: " + getSystemStatus(ship.shipComputer) + "\n"; shipInfo += "\n" shipInfo += "Resources Overview\n" shipInfo += "Oxygen = " + ship.oxygen + "%\n" shipInfo += "Power = " + ship.power + "%\n" shipInfo += "Fuel = " + ship.fuel + "%\n" shipInfo += "Scientific Data = " + ship.scienceDatabase + "%\n" shipInfo += "\n" shipInfo += "Crew: " + ship.crew.length + " Members" return shipInfo; } function getSystemStatus (value) { if (value <= 0) { return "Inoperative" } else if (value > 100) { return "Exceeding Expectations" } switch (Math.floor(value / 20)) { case 0: return ("Barely Functional"); break; case 1: return ("Major Issues"); break; case 2: return ("Several Issues"); break; case 3: return ("Minor Issues"); break; case 4: return ("Good Performance"); break; case 5: return ("Peak Efficiency"); break; } } function getTotalSystemsValue () { var systemsValue = (ship.shipIntegrity + ship.lifeSupport + ship.solarArray + ship.shipComputer + (ship.sensors + ship.oxygenSensor + ship.powerSensor + ship.fuelSensor + ship.scienceSensor)/5 ) / 5; return systemsValue; } function getCrewPerformance () { var performanceValue = (ship.shipIntegrity + ship.lifeSupport + ship.solarArray + ship.shipComputer + ship.sensors + ship.oxygenSensor + ship.fuelSensor + ship.powerSensor + ship.scienceSensor + ship.scienceDatabase + ship.oxygen + ship.fuel + ship.power) / 13; switch (Math.floor(performanceValue / 20)) { case 0: return ("Abysmal"); break; case 1: return ("Poor"); break; case 2: return ("Room for Improvement"); break; case 3: return ("Average"); break; case 4: return ("Exceeding Expectations"); break; case 5: return ("Exemplary"); break; } } function getTimeStamp () { // gets the UTC date for logging and posting var d = new Date(); var hours = d.getUTCHours(); if (hours < 10) { hours = "0" + hours.toString() } var minutes = d.getUTCMinutes() if (minutes < 10) { minutes = "0" + minutes.toString() } var seconds = d.getUTCSeconds() if (seconds < 10) { seconds = "0" + seconds.toString() } var days = d.getUTCDate() if (days < 10) { days = "0" + days.toString() } var months = d.getUTCMonth() + 1 if (months < 10) { months = "0" + months.toString() } return("[" + hours + ":" + minutes + ":" + seconds + " " + days + "/" + months + "/" + d.getUTCFullYear()) + " UTC"; } function getDistanceStamp () { // gets and updates the total distance travelled by the ship var d = new Date(); var shipTime = ship.previousEncounterTime; var encounterTime = d.getTime(); var distanceKM = (((encounterTime - shipTime) / 1000) * ship.speed); ship.previousEncounterTime = encounterTime; ship.distanceKM += distanceKM ship.distanceLY += (distanceKM / (9.461 * 10 ** 12)) distanceKM = Number(ship.distanceKM) console.log(ship.distanceKM) distanceLY = Number(ship.distanceLY) console.log(ship.distanceLY) return("" + distanceKM.toFixed(2) + " kilometres (" + (distanceLY).toFixed(4) + " ly) travelled] ") }
17b77f93f15c4eed5b578980279752fee04173d3
[ "Markdown", "JavaScript" ]
2
Markdown
Logarathon1/space-bot
1770df8c64251841da1f3403580fce3dd34b357d
beaa08a4d8c6b7600e419607a087e249b72dd655
refs/heads/master
<repo_name>tanzanita/AgenciaViajes2<file_sep>/src/Viajes.cpp #include "Viajes.h" Viajes::Viajes(lista *listaAtributo) { /*idViaje = listaAtributo->pasarAtributo(); cout<<"idViaje:"<<idViaje<<endl; origen = listaAtributo->pasarAtributo(); cout<<"origen:"<<origen<<endl; destino = listaAtributo->pasarAtributo(); cout<<"destino:"<<destino<<endl; fechaSalida = listaAtributo->pasarAtributo(); cout<<"Fecha salida"<<fechaSalida<<endl; fechaLlegada = listaAtributo->pasarAtributo(); cout<<"Fecha llegada:" <<fechaLlegada<<endl; precio = listaAtributo->pasarAtributo(); cout<<"Preio"<<precio<<endl; numPlazas = listaAtributo->pasarAtributo(); cout<<"NumPlazas:"<<numPlazas<<endl; cout <<" "; */ } <file_sep>/main.cpp /* INSTUTUTO TECNOLÓGICO DE COSTA RICA ESCUELA DE COMPUTACION ESTRUCTURA DE DATOS PRIMER PROYECTO PROGRAMADO: AGENCIA DE VIAJES ESTUDIANTE CAMILA VÍQUEZ ALPIZAR PROFESORA: ING.<NAME> */ #include <iostream> #include <AgenciaViajes.h> using namespace std; int main() { AgenciaViajes agencia; agencia.lecturaArchivosViaje("Viajes.txt"); agencia.MostrarListaViajes(); agencia.lecturaArchivosHotel("Hoteles.txt"); agencia.lecturaArchivosTransporte("Transportes.txt"); agencia.lecturaArchivosOferta("OfertasHoteles.txt"); agencia.Menu(); return 0; } <file_sep>/include/NodoHotel.h #ifndef NODOHOTEL_H #define NODOHOTEL_H #include "AgenciaViajes.h" #include <string> using std::string; class NodoViaje; class NodoTransporte; class NodoHotel { public: //CONTRUCTORES NodoHotel(); NodoHotel(string, string, string, string, string, string, string); //ATRIBUTOS string idViaje; string idHotel; string nombre; string categoria; string ciudad; string precioHabIndividual; string precioHabDoble; //PUNTEROS NodoHotel *sigHotel; NodoHotel *antHotel; NodoViaje *listaViaje; NodoViaje *devolverViaje; NodoTransporte *listaTransporte; //NodoOferta *listaOferta; }; typedef NodoHotel *pnodoHotel; #endif // NODOHOTEL_H <file_sep>/include/Viajes.h #ifndef VIAJES_H #define VIAJES_H #include <iostream> #include "ListaString.h" /*using namespace std; class Viajes { public: Viajes(lista *listaAtributo);//constructor string idViaje; string origen; string destino; string fechaSalida; string fechaLlegada; string precio; string numPlazas; }; */ #endif // VIAJES_H <file_sep>/src/EstructuraNodo.cpp /*#include "EstructuraNodo.h" EstructuraNodo::EstructuraNodo() { //ctor } EstructuraNodo::~EstructuraNodo() { //dtor } */ <file_sep>/src/Hoteles.cpp #include "Hoteles.h" Hoteles::Hoteles() { //ctor } Hoteles::~Hoteles() { //dtor } <file_sep>/include/NodoTransporte.h #ifndef NODOTRANSPORTE_H #define NODOTRANSPORTE_H #include "AgenciaViajes.h" #include <string> using std::string; class NodoHotel; class NodoTransporte { public: //CONSTRUCTORES NodoTransporte(); NodoTransporte(string, string,string,string,string,string,string,string,string,string,string,string,string); //ATRIBUTOS string idViaje; string idHotel; string idTransporte; string tipoTransporte; string origen; string destino; string fechaSalida; string horaSalida; string fechaLlegada; string horaLlegada; string compania; string numPlazas; string precio; //PUNTEROS NodoTransporte *sigTransporte; NodoTransporte *antTransporte; NodoHotel *listaHoteles; }; typedef NodoTransporte *pnodoTransporte; #endif // NODOTRANSPORTE_H <file_sep>/src/NodoViaje.cpp #include "NodoViaje.h" NodoViaje::NodoViaje() { } NodoViaje::NodoViaje(string ideV , string origenViaje , string destinoViaje , string fechaSalidaViaje, string fechaLegadaViaje , string precioViaje , string numPlazasViaje) { idViaje = ideV; origen = origenViaje; destino = destinoViaje; fechaSalida = fechaSalidaViaje; fechaLegada = fechaLegadaViaje; precio = precioViaje; numPlazas = numPlazasViaje; } typedef NodoViaje *pnodoViaje; <file_sep>/src/ListaString.cpp #include "ListaString.h" #include "AgenciaViajes.h" #include <iostream> using std::cout; using std::endl; ListaString::ListaString() { //ctor } ListaString::~ListaString() { //dtor } using namespace std; lista::~lista() { pnodo aux; while(primero) { aux = primero; primero = primero->siguiente; delete aux; } actual = NULL; } void lista::InsertarFinal(string v) { if (ListaVacia()) primero = new nodo(v); else { pnodo aux = primero; while ( aux->siguiente != NULL) aux= aux->siguiente; aux->siguiente=new nodo(v); } } void lista::BorrarFinal() { if (ListaVacia()){ cout << "No hay elementos en la lista:" << endl; }else{ if (primero->siguiente == NULL) { primero= NULL; } else { pnodo aux = primero; while (aux->siguiente->siguiente != NULL) { aux = aux->siguiente; } pnodo temp = aux->siguiente; aux->siguiente= NULL; delete temp; } } } void lista::BorrarInicio() { if (ListaVacia()){ cout << "No hay elementos en la lista:" << endl; }else{ if (primero->siguiente == NULL) { primero= NULL; } else { pnodo aux = primero; primero=primero->siguiente; delete aux; } } } void lista::Mostrar() { nodo *aux; aux = primero; while(aux) { cout << aux->valor << "-> "; aux = aux->siguiente; } cout << endl; } void lista::Siguiente() { if(actual) actual = actual->siguiente; } string lista::Primero() { actual = primero; return actual->valor; } string lista::Ultimo() { actual = primero; if(!ListaVacia()){ while(actual->siguiente){ Siguiente(); } } return actual -> valor; } //Metodo para cargar los atributos /*string lista:: pasarAtributo(){ string elemento; elemento = primero -> valor; if(primero -> siguiente != NULL) primero = primero-> siguiente; return elemento; } */ <file_sep>/include/EstructuraNodo.h #ifndef ESTRUCTURANODO_H #define ESTRUCTURANODO_H class EstructuraNodo { public: EstructuraNodo(); virtual ~EstructuraNodo(); protected: private: }; class nodoViaje { public: nodoViaje(viajes) { valor = viajes; siguiente = NULL; } }; #endif // ESTRUCTURANODO_H <file_sep>/include/Hoteles.h #ifndef HOTELES_H #define HOTELES_H #include <string> using std::string; class Hoteles { public: //Constructores Hoteles(); virtual ~Hoteles(); //Atributos string idViaje; string idHotel; string nombre; string categoria; string ciudad; string precioHabIndividual; string precioHabDoble; //Punteros }; #endif // HOTELES_H <file_sep>/include/NodoViaje.h #ifndef NODOVIAJE_H #define NODOVIAJE_H #include "AgenciaViajes.h" #include <string> using std::string; class NodoHotel; class NodoViaje { public: //Constructores NodoViaje(); NodoViaje(string, string, string, string, string, string, string); //Atributos string idViaje; string origen; string destino; string fechaSalida; string fechaLegada; string precio; string numPlazas; //Punteros NodoViaje *primerViaje; NodoViaje *sigViaje; NodoViaje *antViaje; NodoHotel *listaHotel;//sale de nodo viaje pero apunta a nodo hotel entonves e tipo viaje }; typedef NodoViaje *pnodoViaje; #endif // NODOVIAJE_H <file_sep>/src/NodoTransporte.cpp #include "NodoTransporte.h" #include "AgenciaViajes.h" NodoTransporte::NodoTransporte() { } NodoTransporte::NodoTransporte(string idV ,string idH, string idT ,string tipoTrans, string origenTrans,string destinoTrans,string fechaSalidaTrans,string horaSalidaTrans,string fechaLlegadaTrans ,string horaLlegadaTrans,string companiaTrans,string numPlazasTrans,string preioTrans) { idViaje = idV; idHotel = idH; idTransporte = idT; origen = origenTrans; destino= destinoTrans; fechaSalida = fechaSalidaTrans; horaSalida = horaSalidaTrans; fechaLlegada = fechaLlegadaTrans; horaLlegada= horaLlegadaTrans; compania = companiaTrans; numPlazas = numPlazasTrans; precio = preioTrans; } typedef NodoTransporte *pnodoTrasnporte; <file_sep>/include/AgenciaViajes.h #ifndef AGENCIAVIAJES_H #define AGENCIAVIAJES_H #include "NodoViaje.h" #include "NodoHotel.h" #include "NodoTransporte.h" #include <fstream> using std::fstream; using std::ios; #include <iostream> using std::cout; using std::endl; #include <string> using std::string; class NodoViaje; typedef NodoViaje *pnodoViaje; class AgenciaViajes { public: AgenciaViajes(); virtual ~AgenciaViajes(); void lecturaArchivosViaje(string archivo); void lecturaArchivosHotel(string archivo); void lecturaArchivosTransporte(string archivo); void lecturaArchivosOferta(string archivo); void crearViaje(string, string, string, string , string , string , string); //void crearHotel(string, string, string, string, string, string, string); bool listaViajesVacia(); bool listaHotelVacia(string idV); //void MostrarListaHotel(); void MostrarListaViajes(); //bool ViajeExistente(string idV); //pnodoViaje ViajeEncontrado(string idV); //es propio de la lista void Menu(); pnodoViaje primerViaje; }; #endif // AGENCIAVIAJES_H <file_sep>/src/NodoHotel.cpp #include "NodoHotel.h" NodoHotel::NodoHotel() { } NodoHotel::NodoHotel(string idV, string idH, string nombreHotel, string categoriaHotel,string ciudadHotel, string precioHabIndivHotel, string precioHabDobleHotel) { idViaje = idV ; idHotel = idH ; nombre = nombreHotel; categoria = categoriaHotel; ciudad = ciudadHotel; precioHabIndividual = precioHabIndivHotel; precioHabDoble = precioHabDobleHotel; } typedef NodoHotel *pnodoHotel; <file_sep>/src/AgenciaViajes.cpp #include "AgenciaViajes.h" //#include <iostream> #include <stdio.h> //#include <string> #include <stdlib.h> #include <string.h> #include <fstream> #include <sstream> //#include <windows.h> #include <vector> using std::vector; using namespace std; AgenciaViajes::AgenciaViajes() { primerViaje = NULL; } AgenciaViajes::~AgenciaViajes() { //dtor } //LECTURAS DE ARCHIVOS void AgenciaViajes::lecturaArchivosViaje(string archivo){ fstream ficheroEntrada; string linea; //string archivo; int lenLinea; string atributo; vector<string> elementos(0); char separador = ';'; ficheroEntrada.open(archivo.c_str(),ios::in); //int i2 = 0; if (ficheroEntrada.is_open()){ while (!ficheroEntrada.eof()){ getline(ficheroEntrada,linea); lenLinea = linea.size(); for (int i = 0; i < lenLinea; i++){ if(linea[i] != separador){ atributo = atributo + linea[i]; }else{ elementos.push_back(atributo); atributo = ""; } } elementos.push_back(atributo); //llamada a funcion para validar que los IDE sean unicos //validarElementos(elementos); cout<<"-----------------------------------Viajes-----------------------------------"<<endl; cout<<"----------------------------------------------------------------------------"<<endl; //int idViaje = atoi(elementos[0].c_str());cout<<"ID Viaje: "<<idViaje<<endl; string idViaje = elementos[0];cout<<"ID Viaje: "<<idViaje<<endl; string origenViaje = elementos[1];cout<<"Origen Viaje: "<<origenViaje<<endl; string destinoViaje = elementos[2];cout<<"Destino del viaje:"<<destinoViaje<<endl; string fechaSalida = elementos[3];cout<<"Fecha de salida: "<<fechaSalida<<endl; string fechaLlegada = elementos[4];cout<<"Fecha de llegada: "<<fechaLlegada<<endl; string precioViaje = elementos[5];cout<<"Precio del viaje: "<<precioViaje<<endl; string plazasViaje = elementos[6];cout<<"Numero de plazas: "<<plazasViaje<<endl; //cout<<"----------------------------------------------------------------------------"<<endl; crearViaje(idViaje, origenViaje, destinoViaje,fechaSalida, fechaLlegada, precioViaje, plazasViaje); elementos.clear(); atributo = ""; } ficheroEntrada.close(); }else{ cout << "Fichero inexistente o faltan permisos para abrirlo" << endl; } } void AgenciaViajes::lecturaArchivosHotel(string archivo){ fstream ficheroEntrada; string linea; //string archivo; int lenLinea; string atributo; vector<string> elementos(0); char separador = ';'; ficheroEntrada.open(archivo.c_str(),ios::in); //int i2 = 0; if (ficheroEntrada.is_open()){ while (!ficheroEntrada.eof()){ getline(ficheroEntrada,linea); lenLinea = linea.size(); for (int i = 0; i < lenLinea; i++){ if(linea[i] != separador){ atributo = atributo + linea[i]; }else{ elementos.push_back(atributo); atributo = ""; } } elementos.push_back(atributo); cout<<"-----------------------------------Hoteles-----------------------------------"<<endl; cout<<"----------------------------------------------------------------------------"<<endl; //int idViaje = atoi(elementos[0].c_str());cout<<"ID Viaje: "<<idViaje<<endl; string idViaje = elementos[0];cout<<"ID Viaje: "<<idViaje<<endl; string idHotel = elementos[1];cout<<"ID Hotel: "<<idHotel<<endl; string nombre = elementos[2];cout<<"Nombre: "<<nombre<<endl; string categoria = elementos[3];cout<<"Categoria: "<<categoria<<endl; string ciudad = elementos[4];cout<<"Ciudad: "<<ciudad<<endl; string precioHabIndividual = elementos[5];cout<<"Precio habitacion dobre: "<<precioHabIndividual<<endl; string precioHabDoble = elementos[6];cout<<"Precio habitacionindividual: "<<precioHabDoble<<endl; //crearHotel(idViaje, idHotel, nombre,categoria, ciudad, precioHabIndividual, precioHabDoble); elementos.clear(); atributo = ""; } ficheroEntrada.close(); }else{ cout << "Fichero inexistente o faltan permisos para abrirlo" << endl; } } void AgenciaViajes::lecturaArchivosTransporte(string archivo){ fstream ficheroEntrada; string linea; //string archivo; int lenLinea; string atributo; vector<string> elementos(0); char separador = ';'; ficheroEntrada.open(archivo.c_str(),ios::in); //int i2 = 0; if (ficheroEntrada.is_open()){ while (!ficheroEntrada.eof()){ getline(ficheroEntrada,linea); lenLinea = linea.size(); for (int i = 0; i < lenLinea; i++){ if(linea[i] != separador){ atributo = atributo + linea[i]; }else{ elementos.push_back(atributo); atributo = ""; } } elementos.push_back(atributo); cout<<"-----------------------------------Transporte-----------------------------------"<<endl; cout<<"----------------------------------------------------------------------------"<<endl; //int idViaje = atoi(elementos[0].c_str());cout<<"ID Viaje: "<<idViaje<<endl; string idViaje = elementos[0];cout<<"ID Viaje: "<<idViaje<<endl; string idHotel = elementos[1];cout<<"ID Hotel: "<<idHotel<<endl; string idTransporte = elementos[2];cout<<"ID Trasnporte: "<<idTransporte<<endl; string tipoTranporte = elementos[3];cout<<"Tipo: 1Aereo-2Maritimo-3Terrestre: "<<tipoTranporte<<endl; string origen = elementos[4];cout<<"Origen: "<<origen<<endl; string destino = elementos[5];cout<<"Destino: "<<destino<<endl; string fechaSalida = elementos[6];cout<<"Fecha Salida: : "<<fechaSalida<<endl; string horaSalida = elementos[7];cout<<"Hora Salida: "<<horaSalida<<endl; string fechaLlegada= elementos[8];cout<<"Fecha Legada: "<<fechaLlegada<<endl; string horaLegada = elementos[9];cout<<"Hora Llegada: "<<horaLegada<<endl; string compania = elementos[10];cout<<"Compania: "<<compania<<endl; string numPlazas = elementos[11];cout<<"Numero de Plazas: "<<numPlazas<<endl; string precio = elementos[12];cout<<"Precio: "<<precio<<endl; //crearTransporte(idViaje, idHotel, nombre,categoria, ciudad, precioHabIndividual, precioHabDoble); elementos.clear(); atributo = ""; } ficheroEntrada.close(); }else{ cout << "Fichero inexistente o faltan permisos para abrirlo" << endl; } } void AgenciaViajes::lecturaArchivosOferta(string archivo){ fstream ficheroEntrada; string linea; //string archivo; int lenLinea; string atributo; vector<string> elementos(0); char separador = ';'; ficheroEntrada.open(archivo.c_str(),ios::in); //int i2 = 0; if (ficheroEntrada.is_open()){ while (!ficheroEntrada.eof()){ getline(ficheroEntrada,linea); lenLinea = linea.size(); for (int i = 0; i < lenLinea; i++){ if(linea[i] != separador){ atributo = atributo + linea[i]; }else{ elementos.push_back(atributo); atributo = ""; } } elementos.push_back(atributo); //llamada a funcion para validar que los IDE sean unicos //validarElementos(elementos); cout<<"-----------------------------------Oferta-----------------------------------"<<endl; cout<<"----------------------------------------------------------------------------"<<endl; string idViaje = elementos[0];cout<<"ID Viaje: "<<idViaje<<endl; string idHotel = elementos[1];cout<<"ID Hotel: "<<idHotel<<endl; string precioHabIndiv = elementos[2];cout<<"Precio Habitacion individual:"<<precioHabIndiv<<endl; string precioHabDoble = elementos[3];cout<<"Precio Habitacion doble: "<<precioHabDoble<<endl; cout<<"----------------------------------------------------------------------------"<<endl; cout<<endl; cout<<endl; cout<<endl; elementos.clear(); atributo = ""; } ficheroEntrada.close(); }else{ cout << "Fichero inexistente o faltan permisos para abrirlo" << endl; } } //CREACION DE NODOS void AgenciaViajes::crearViaje(string idV, string origenViaje, string destinoViaje, string fechaSalidaViaje, string fechaLlegadaViaje, string precioViaje, string numPlazasViaje){ pnodoViaje nuevoViaje = new NodoViaje(idV ,origenViaje , destinoViaje ,fechaSalidaViaje,fechaLlegadaViaje ,precioViaje ,numPlazasViaje); if(listaViajesVacia()){ //solo si es vacia yo creo este nodo primerViaje = nuevoViaje; primerViaje->sigViaje = primerViaje; primerViaje->antViaje = primerViaje; }else{ pnodoViaje aux = primerViaje; while(aux->sigViaje != primerViaje){ aux = aux->sigViaje; } aux -> sigViaje = nuevoViaje; nuevoViaje -> antViaje = aux; nuevoViaje -> sigViaje = primerViaje; primerViaje -> antViaje = nuevoViaje; aux->listaHotel =NULL;//asegurarse que el nodo todavia no tiene nada } } /*void AgenciaViajes::crearHotel(string idV, string idH, string nombreHotel, string categoriaHotel, string ciudadHotel, string precioHabIndividualHotel, string precioHabDobleHotel){ pnodoHotel nuevoHotel = new NodoHotel(idV,idH , nombreHotel ,categoriaHotel,ciudadHotel ,precioHabIndividualHotel ,precioHabDobleHotel); pnodoViaje vij = ViajeEncontrado(idV); //uso a nuevo como primero if(listaHotelVacia(idV)){ vij->listaHotel = nuevoHotel; nuevoHotel->devolverViaje = vij; nuevoHotel->sigHotel = NULL; nuevoHotel->antHotel = NULL; }else{ pnodoHotel primerH = vij->listaHotel; pnodoHotel aux = primerH; while(aux->sigHotel != NULL){ aux = aux->sigHotel; } aux->sigHotel = nuevoHotel; aux->sigHotel->antHotel= aux; aux->sigHotel->sigHotel = NULL; aux->sigHotel->devolverViaje=NULL; nuevoHotel=NULL; } } */ //METODOS DE VALIDACIONES DE LISTAS bool AgenciaViajes::listaViajesVacia(){ return primerViaje == NULL; } /*bool AgenciaViajes::listaHotelVacia(int idV){ pnodoViaje vij = ViajeEncontrado(idV); if(vij->listaHotel == NULL){ return true; } return false; } */ //METODOS PARA MOSTRAR void AgenciaViajes :: MostrarListaViajes(){ cout<<"Lista Viajes: "<<endl; cout<<endl; pnodoViaje aux = primerViaje; while(aux->sigViaje != primerViaje){ cout<<aux->idViaje<<";"<<aux->origen<<";"<<aux->destino<<";"<<aux->fechaSalida<<";"<<aux->fechaLegada<<";"<<aux->precio<<";"<<aux->numPlazas<<" -> "; aux = aux->sigViaje; } cout<<aux->idViaje<<";"<<aux->origen<<";"<<aux->destino<<";"<<aux->fechaSalida<<";"<<aux->fechaLegada<<";"<<aux->precio<<";"<<aux->numPlazas<<" -> "; } /*void AgenciaViajes :: MostrarListaHotel(){ cout<<"Lista Hotel: "<<endl; cout<<endl; pnodoHotel aux = listaHotel; //aux = pnodoViaje->listaHotel; while(aux->sigHotel != NULL){ cout<<aux->idHotel<<";"<<aux->idHotel<<";"<<aux->nombre<<";"<<aux->categoria<<";"<<aux->ciudad<<";"<<aux->precioHabIndividual<<";"<<aux->precioHabDoble<<" -> "; aux = aux->sigHotel; } cout<<aux->idViaje<<";"<<aux->idHotel<<";"<<aux->nombre<<";"<<aux->categoria<<";"<<aux->ciudad<<";"<<aux->precioHabIndividual<<";"<<aux->precioHabDoble<<" -> "; } */ /*bool AgenciaViajes::ViajeExistente(int idV) { pnodoViaje aux = primerViaje; while ( aux->sigViaje != primerViaje){ if (aux->idViaje == idV) return true; aux = aux->sigViaje; } if (aux->idViaje == idV) return true; return false; } pnodoViaje AgenciaViajes::ViajeEncontrado(int idV) { pnodoViaje aux = primerViaje; while ( aux -> sigViaje != primerViaje){ if (aux->idViaje == idV) return aux; aux = aux -> sigViaje; } if (aux->idViaje == idV) return aux; return NULL; } */ void AgenciaViajes::Menu(){ cout<<"________________________________________________"<<endl; cout<<"________________________________________________"<<endl; cout<<"AGENCIA DE VIAJES"<<endl; cout<<"BIENVENIDO"<<endl; cout<<"________________________________________________"<<endl; cout<<"Digite la opcion a la que desea ingresar"<<endl; cout<<"________________________________________________"<<endl; cout<<"1.Consultar precio de un producto"<<endl; cout<<"2.Consultar hoteles, viajes y transportes"<<endl; cout<<"3.Consultar el viaje de un cliente"<<endl; cout<<"3.1.Consultar el transporte de un cliente"<<endl; cout<<"3.2.Consultar la resrva de un cliente"<<endl; cout<<"________________________________________________"<<endl; cout<<"________________________________________________"<<endl; } <file_sep>/include/Estructura.h #ifndef ESTRUCTURA_H #define ESTRUCTURA_H class Estructura { public: Estructura(); virtual ~Estructura(); protected: private: }; #endif // ESTRUCTURA_H <file_sep>/src/NodoOferta.cpp #include "NodoOferta.h" NodoOferta::NodoOferta() { //dtor } NodoOferta::NodoOferta(string idClienteOferta, string idHotelOferta, string precioHabIndividualOferta, string precioHabDobleOferta) { idCliente = idClienteOferta ; idHotel = idHotelOferta; precioHabIndiv = precioHabIndividualOferta; precioHabDoble = precioHabDobleOferta; } typedef NodoOferta *pnodoOferta; <file_sep>/include/ListaString.h #ifndef LISTASTRING_H #define LISTASTRING_H #include <string> using std::string; class ListaString { public: ListaString(); virtual ~ListaString(); protected: private: }; class nodo { public: nodo(string v) { valor = v; siguiente = NULL; } nodo(string v, nodo * signodo) { valor = v; siguiente = signodo; } private: string valor; nodo *siguiente; friend class lista; //friend class AgenciaDeViajes; }; typedef nodo *pnodo; class lista { public: lista() { primero = actual = NULL; } ~lista(); void InsertarFinal(string v); bool ListaVacia() { return primero == NULL; } void Mostrar(); void Siguiente(); string Primero(); string Ultimo(); void BorrarFinal(); void BorrarInicio(); pnodo primero; pnodo actual; //string pasarAtributo(); //private: //pnodo primero; //pnodo actual; }; #endif // LISTASTRING_H <file_sep>/include/NodoOferta.h #ifndef NODOOFERTA_H #define NODOOFERTA_H #include "AgenciaViajes.h" class NodoOferta { public: //cONSTRUCTORES NodoOferta(); NodoOferta(string, string, string, string); //ATRIBUTOS string idCliente; string idHotel; string precioHabIndiv; string precioHabDoble; //PUNTEROS NodoOferta *sigOferta; NodoOferta *antOferta; NodoHotel *listaHotele; }; typedef NodoOferta *pnodoOferta; #endif // NODOOFERTA_H
2ab5763d5e614aec84bd90d5e8fc6e7f7f30d116
[ "C++" ]
20
C++
tanzanita/AgenciaViajes2
6bd1c6eefa4db1ea0a88981f1cc476cdced2e007
cc54267568c6657f40caac8a78c63db9981f9bdc
refs/heads/master
<file_sep>package com.example.userMgtService.validator; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.example.userMgtService.model.Reg; import com.example.userMgtService.service.RegService; @Component public class RegFormValidator implements Validator { @Autowired RegService regService ; //@Autowired //@Qualifier("emailValidator") //EmailValidator emailValidator; private Pattern pattern; private Matcher matcher; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; @Override public boolean supports(Class<?> clazz) { return Reg.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { Reg reg = (Reg) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "NotEmpty.regForm.firstName"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "NotEmpty.regForm.lastName"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "DOB", "NotEmpty.regForm.DOB"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "NotEmpty.regForm.gender"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "NotEmpty.regForm.userName"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "<PASSWORD>"); // email validation in spring if (!(reg.getUserName() != null && reg.getUserName().isEmpty())) { pattern = Pattern.compile(EMAIL_PATTERN); matcher = pattern.matcher(reg.getUserName()); if (!matcher.matches()) { errors.rejectValue("userName", "regForm.userName.incorrect"); } } if (reg.getFirstName() == null) { errors.rejectValue("firstName", "NotEmpty.regForm.firstName"); } if (reg.getLastName() == null) { errors.rejectValue("lastName", "NotEmpty.regForm.lastName"); } if (reg.getDOB() == null) { errors.rejectValue("DOB", "NotEmpty.regForm.DOB"); } if (reg.getGender() == null) { errors.rejectValue("gender", "NotEmpty.regForm.gender"); } if (reg.getUserName() == null) { errors.rejectValue("userName", "NotEmpty.regForm.userName"); } if (reg.getPassword() == null) { errors.rejectValue("password", "<PASSWORD>"); } } }<file_sep>package com.example.accountMgtService.Contoller; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.accountMgtService.model.SellingOrder; import com.example.accountMgtService.service.AccountService; @RestController @CrossOrigin(origins = "http://localhost:4200") @RequestMapping("/api/v1") //@RequestMapping("/services") //@RestController public class AccountMgtContoller { @Autowired AccountService accountService ; //@PostMapping("/bill") //public SellingOrder saveProduct(@RequestBody SellingOrder sellingOrder) { // return accountService.save(sellingOrder); // } //@GetMapping("/bill") //public Optional<SellingOrder> findById(Long id) { // return accountRepository.findById(id); //} //@RequestMapping("/accountMgtService/{pId}") //@GetMapping("/bill/{pId}") //public Optional<SellingOrder> getProduct(@PathVariable Long pId) { // return accountService.getByPid(pId); //} //@RequestMapping("/accountMgtService/{id}") //@GetMapping("/bill/{id}") //public Optional<SellingOrder> getProduct(@PathVariable Long id) { // return accountService.getById(id); //} @GetMapping("/bill/{id}") public ResponseEntity<Optional<SellingOrder>> getProduct(@PathVariable(value = "id") Long id) { Optional<SellingOrder> sellingOrder= accountService.getById(id); return ResponseEntity.ok().body(sellingOrder); } } <file_sep>package com.example.userMgtService.model; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="User Not Found") public class UserNotFoundException extends RuntimeException { private static final long serialVersionUID = -2581975292273282583L; String exception ; public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } } <file_sep>package com.example.userMgtService.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.userMgtService.dao.UserRepository; import com.example.userMgtService.model.Reg; //import com.fasterxml.jackson.databind.util.JSONPObject; @Service @Transactional public class RegServiceImpl implements RegService { @Autowired UserRepository userRepository; //Checking login details @Override public Reg checkLogin(String userName, String password) { return userRepository.checkLogin(userName, password); } @Override public void save(Reg reg) { //reg.setPassword(<PASSWORD>Encoder.encode(reg.getPassword())); userRepository.save(reg); } @Override public Optional<Reg> findByID(long id) { return userRepository.findById(id) ; } @Override public Reg checkUser(String userName) { return userRepository.checkUser(userName); } //@Override //public void save(RoleType roleType) { // userRepository.save(roleType); //} @Override public void saveOrUpdate(Reg reg) { if (findByID(reg.getId()) == null){ userRepository.save(reg); } else { userRepository.update(reg); } } @Override public Object getAllUnRegUsers() { // TODO Auto-generated method stub return null; } @Override public Reg findByID(Long id) { // TODO Auto-generated method stub return null; } } <file_sep>package com.example.userMgtService.validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.example.userMgtService.model.Reg; import com.example.userMgtService.service.RegService; @Component public class LoginformValidator implements Validator { @Autowired RegService regService ; public boolean supports(Class<?> clazz) { return Reg.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { Reg reg = (Reg) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "NotEmpty.loginForm.userName"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "<PASSWORD>"); if (reg.getUserName() == null) { errors.rejectValue("userName", "NotEmpty.loginForm.userName"); } if (reg.getPassword() == null) { errors.rejectValue("password", "<PASSWORD>"); } } }<file_sep>package com.example.userMgtService.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.example.userMgtService.model.Reg; import com.example.userMgtService.model.UserNotFoundException; import com.example.userMgtService.service.RegService; import com.example.userMgtService.validator.LoginformValidator; import com.example.userMgtService.validator.RegFormValidator; @Controller @Transactional public class MainController { @Autowired RegService regService ; @Autowired RegFormValidator regFormValidator ; @Autowired LoginformValidator loginformValidator; @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(regFormValidator); } @InitBinder protected void initBinder1(WebDataBinder binder) { binder.setValidator(loginformValidator); } //DisplayLogin form // @RequestMapping(value = "/", method = RequestMethod.GET) // public String showLoginForm(Model model) { //Reg reg = new Reg(); //model.addAttribute("loginForm", reg); //return "LoginForm"; //} //Check login details and give access to the system based on privileges @RequestMapping(value = "/login/add" ,method = RequestMethod.POST) public String processForm(@ModelAttribute("loginForm") @Validated Reg reg, BindingResult result, HttpSession httpSession , Model model,final RedirectAttributes redirectAttributes ) { if (result.hasErrors()) { return "LoginForm"; } else { Reg userExists = regService.checkLogin(reg.getUserName(),reg.getPassword()); if(userExists ==null){ throw new UserNotFoundException(); } else { httpSession.setAttribute("reg", userExists); model.addAttribute("reg",userExists); @SuppressWarnings("unused") //Get the type of User String userType = reg.getRole_Type(); return "showReg"; } } } //Displaying an error message when logging details were not matched @ExceptionHandler(UserNotFoundException.class) public ModelAndView handleStudentNotFoundException(UserNotFoundException ex) { Map<String, String> model = new HashMap<String, String>(); model.put("exception", ex.toString()); return new ModelAndView("error", model); } @RequestMapping(value = "/reg", method = RequestMethod.GET) public String showREgForm(Model model) { Reg reg = new Reg(); model.addAttribute("regForm", reg); return "RegForm"; } //@RequestMapping(value = "/reg/add", method = RequestMethod.POST) // public String saveReg(@ModelAttribute("regForm") @Validated Reg reg ,BindingResult result, Model model , // final RedirectAttributes redirectAttributes ) { // if (result.hasErrors()) { // return "RegForm"; // } else { // model.addAttribute("firstName", reg.getFirstName()); // model.addAttribute("lastName",reg.getLastName()); // model.addAttribute("DOB",reg.getDOB()); // model.addAttribute("gender", reg.getGender()); // model.addAttribute("userName",reg.getUserName()); //model.addAttribute("password", reg.getPassword()); //regService.save(reg); //return "redirect:/reg/add/" + reg.getId() ; //} //} @RequestMapping(value = "/reg/add", method = RequestMethod.POST) public String saveReg(@ModelAttribute("regForm") @Validated Reg reg ,BindingResult result,HttpSession httpSession, Model model , final RedirectAttributes redirectAttributes ) { if (result.hasErrors()) { return "RegForm"; } else{ Reg userNameExists = regService.checkUser(reg.getUserName()); if(userNameExists != null){ httpSession.setAttribute("reg", userNameExists); model.addAttribute("reg",userNameExists); return "userError"; } else{ // model.addAttribute("firstName", reg.getFirstName()); // model.addAttribute("lastName",reg.getLastName()); // model.addAttribute("DOB",reg.getDOB()); // model.addAttribute("gender", reg.getGender()); // model.addAttribute("userName",reg.getUserName()); // model.addAttribute("password", <PASSWORD>()); // regService.save(reg); regService.saveOrUpdate(reg); return "redirect:/reg/add/" + reg.getId() ; } } } @RequestMapping(value = "/reg/add/{id}", method = RequestMethod.GET) public String showFilledREg(@PathVariable("id") Long id, Model model) { Reg reg =regService.findByID(id); model.addAttribute("reg",reg); return "InitialRegShow"; } @RequestMapping(value = "/login/add/{id}", method = RequestMethod.GET) public String showRegUser(@PathVariable("id") Long id, Model model) { Reg reg =regService.findByID(id); model.addAttribute("reg",reg); return "showReg"; } // show update form @RequestMapping(value = "/login/add/{id}/update", method = RequestMethod.GET) public String showUpdateUserForm(@PathVariable("id") Long id, Model model) { Reg reg = regService.findByID(id); model.addAttribute("regForm", reg); return "RegForm"; } //list page // @RequestMapping(value = "/login/users", method = RequestMethod.GET) //public String AllUsersForm(Model model) { // model.addAttribute("users", regService.findAll()); // return "list"; //} //delete user //@RequestMapping(value = "/login/users/{id}/delete", method = RequestMethod.POST) //public void deleteUser(@PathVariable("id") int id, //final RedirectAttributes redirectAttributes) { //regService.delete(id); //} // show update formToday //@RequestMapping(value = "/login/add/{id}/update", method = RequestMethod.GET) // public String showUpdateUserForm(@PathVariable("id") int id, Model model) { // Reg reg = regService.findByID(id); // model.addAttribute("regForm", reg); //return "RegForm"; //} // save update form //@RequestMapping(value = "/login/add/{id}/update/save", method = RequestMethod.POST) // public void saveUpdateUserForm(@PathVariable("id") int id, @Validated Reg regUser) { //Reg reg = regService.findByID(id); //reg.setContactNo(regUser.getContactNo()); //reg.setOrgName(regUser.getOrgName()); //regService.update(reg); //} //show update form //@RequestMapping(value = "/add/{id}/update/save", method = RequestMethod.POST) // public void saveUpdateUserForm(@PathVariable("id") int id , @ModelAttribute("updateForm") Reg reg2 ,BindingResult result,HttpSession httpSession, Model model , // final RedirectAttributes redirectAttributes ) { //Reg reg = regService.findByID(id); //reg.setPassword(<PASSWORD>()); //reg.setUserName(reg2.getUserName()); //reg.setGender(reg2.getGender()); //reg.setDOB(reg2.getDOB()); //reg.setLastName(reg2.getLastName()); //reg.setFirstName(reg2.getFirstName()); // regService.save(reg); //} //Processing logging out from the system @RequestMapping(value = "/login/out" ,method = RequestMethod.GET) public String processOUT( @ModelAttribute("loginForm") Reg reg, BindingResult result,HttpSession httpSession , Model model ) { @SuppressWarnings("unused") Reg userExistshttpSession = (Reg)httpSession.getAttribute("reg"); //((HttpSession) userExistshttpSession).invalidate(); httpSession.invalidate(); return "redirect:/"; } @RequestMapping(value = "/login/ViewReports", method = RequestMethod.GET) public ModelAndView showReport1( Model model) { return new ModelAndView ("StockReport"); } @RequestMapping(value = "/login/add/AllowPermission", method = RequestMethod.GET) public String showUnPermitted( Model model) { model.addAttribute("UnPermissionList", regService.getAllUnRegUsers()); return "Permission"; } }
4b49e2fe618d3201d796ce45c7cd8ebaf5846587
[ "Java" ]
6
Java
MedisDineshika/BackEnd
45bfbc3c5cbb9ffac4923e3b46449041222a3d6d
60f4f6d367f65e7da4e6d51526d8b5a51b4e85be
refs/heads/master
<repo_name>kou164nkn/typing-game<file_sep>/typeGame.go package typeGame import ( "bufio" "context" "fmt" "io" "math/rand" "time" ) var word = []string{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"} var defaultTime = 15 type Game struct { input io.Reader output io.Writer quiz []string score int timeLimit int } func New(r io.Reader, w io.Writer) *Game { g := Game{ input: r, output: w, quiz: word, timeLimit: defaultTime, } return &g } func (g *Game) Do() { ich := initial(g.input) ctx, cancel := context.WithTimeout(context.Background(), time.Duration(g.timeLimit)*time.Second) defer cancel() g.score = 0 len := len(g.quiz) rand.Seed(time.Now().UnixNano()) fmt.Fprintln(g.output, "Game start!") for { q := g.quiz[rand.Intn(len)] fmt.Fprintln(g.output, q) select { case <-ctx.Done(): goto ENDGAME case a := <-ich: if q == a { fmt.Fprintln(g.output, "Correct!") g.score++ } else { fmt.Fprintln(g.output, "Wrong...") } } } ENDGAME: fmt.Fprintln(g.output, "Finished!") fmt.Fprintf(g.output, "Your score: %d\n", g.score) } func initial(r io.Reader) <-chan string { ch := make(chan string) go func() { defer close(ch) scanner := bufio.NewScanner(r) for scanner.Scan() { ch <- scanner.Text() } }() return ch } <file_sep>/Makefile .PHONY: build build: go build ./cmd/tgame .PHONY: test test: go test -v -race -cover<file_sep>/typeGame_test.go package typeGame_test import ( "io" "os" "reflect" "strings" "testing" typeGame "github.com/kou164nkn/typing-game" ) func TestNew(t *testing.T) { t.Parallel() cases := map[string]struct { inputMethod io.Reader expect *typeGame.Game }{ "cli_mode": {os.Stdin, typeGame.NewTestGame(os.Stdin, os.Stdout, nil, 15)}, } for name, tt := range cases { t.Run(name, func(t *testing.T) { actual := typeGame.New(tt.inputMethod, os.Stdout) if !reflect.DeepEqual(actual, tt.expect) { t.Errorf("New want %v but got %v", tt.expect, actual) } }) } } func TestDo(t *testing.T) { t.Parallel() cases := map[string]struct { testQuiz []string testTime int answer string expectScore int }{ "no_answer": {[]string{"sample"}, 1, "", 0}, "2_correct": {[]string{"sample"}, 1, "sample\nwrong\nsample", 2}, } for name, tt := range cases { g := typeGame.NewTestGame(strings.NewReader(tt.answer), io.Discard, tt.testQuiz, tt.testTime) t.Run(name, func(t *testing.T) { g.Do() if g.Score() != tt.expectScore { t.Errorf("Expect score is %d but %d", tt.expectScore, g.Score()) } }) } } <file_sep>/go.mod module github.com/kou164nkn/typing-game go 1.16 <file_sep>/cmd/tgame/main.go package main import ( "os" typeGame "github.com/kou164nkn/typing-game" ) func main() { g := typeGame.New(os.Stdin, os.Stdout) g.Do() } <file_sep>/export_test.go package typeGame import "io" func NewTestGame(i io.Reader, o io.Writer, q []string, t int) *Game { if len(q) == 0 { q = word } return &Game{input: i, output: o, quiz: q, score: 0, timeLimit: t} } func (g *Game) Score() int { return g.score }
73f74970e621d941c3efc47a93c782b2f4ed9205
[ "Makefile", "Go Module", "Go" ]
6
Go
kou164nkn/typing-game
9af79039bd43383afa03a26bf957cc70a8602c41
06c5d2c5d7562443c96326318c9827d61fc4e0df
refs/heads/master
<repo_name>PoonamRanawat/cv-angular2<file_sep>/src/app/project/questionnaire-tab/questionnaire/questionnaire.component.ts import {Component, OnInit} from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; @Component({ selector: 'cfm-questionnaire', templateUrl: './questionnaire.component.html', animations: [ trigger('slideInOut', [ state('out', style({ width: 0, overflow: 'hidden' })), transition('in => out', animate('200ms ease-in-out')), transition('out => in', animate('200ms ease-in-out')) ]), ] }) export class QuestionnaireComponent implements OnInit { leftMenuState: string = 'in'; rightMenuState: string = 'in'; constructor() { } ngOnInit() { } toggleLeftMenu() { this.leftMenuState = this.leftMenuState === 'out' ? 'in' : 'out'; } toggleRightMenu() { this.rightMenuState = this.rightMenuState === 'out' ? 'in' : 'out'; } } <file_sep>/src/app/core/menu.service.ts // @todo: This file is having hardcoded values, replace it later when we have API in place. import {Injectable} from '@angular/core'; import {Menu} from './menu'; import {ApiService} from './api.service'; @Injectable() export class MenuService { menus: any; activeMenus: any; flag = false; constructor(private apiService: ApiService) { this.menus = { alerts: [], languages: [], user: [], left: [], quick: [] }; this.activeMenus = { alerts: 0, languages: 0, user: 0, left: 0, quick: 0 }; } /** * Get different menu on basis of location. * * @param location * @returns {any} */ getMenuConfig(location: string): any { if (!this.menus[location]) { return null } return this.menus[location]; } /** * Add menu values. * * @param location * @param newConfig */ add(location: string, newConfig: Menu): void { if (this.menus[location]) { this.menus[location].push(newConfig); newConfig.position = this.menus[location].length - 1; } } /** * Insert value in a particular menu. * * @param location * @param position * @param newConfig */ insert(location: string, position: number, newConfig: Menu): void { if (this.menus[location]) { this.menus[location].splice(position, 0, newConfig); newConfig.position = position; } } /** * Delete the particular menu * * @param location */ delete(location: string) { if (this.menus[location]) { this.menus[location] = []; } } /** * Update the menu config * * @param location * @param config */ update(location: string, config: any) { if (this.menus[location] && config.position >= 0 && config.position < this.menus[location].length) { Object.assign(this.menus[location][config.position], config); } } /** * Set active value of a menu item * * @param location * @param index */ setActive(location: string, index: number) { if (this.menus[location] && index >= 0 && index < this.menus[location].length) { this.activeMenus[location] = index; } } /** * Get active menu item. * * @param location * @returns {any} */ getActive(location: string): Menu { if (this.menus[location]) { const idx = this.activeMenus[location]; if (idx >= 0 && idx < this.menus[location].length) { return this.menus[location][idx]; } else if (this.menus[location].length > 0) { return this.menus[location][0]; } return null; } } /** * Set side menu toggle flag * * @param value */ setToggleClass(value: boolean): void { this.flag = value; } /** * Get side menu toggle flag * * @returns {boolean} */ getToggleClass(): boolean { return this.flag; } /** * Get notifications * * @returns {Observable<R|T>} */ getNotifications() { return this.apiService.getMethod('notificationhistory'); } } <file_sep>/src/app/project/project-routing.module.ts import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {ProjectComponent} from './project.component'; import {ProjectFormComponent} from './project-form/project-form.component'; import {QuestionnaireTabComponent} from './questionnaire-tab/questionnaire-tab.component'; const routes: Routes = [ {path: '', component: ProjectComponent}, {path: 'add', component: ProjectFormComponent}, {path: 'questionnaire', component: QuestionnaireTabComponent} ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProjectRoutingModule { } <file_sep>/src/app/project/questionnaire-tab/questionnaire/page-list-slider/page-list/page-list.component.ts import { Component, OnInit } from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {ToastsManager} from 'ng2-toastr'; import {PageService} from '../../../../page.service' @Component({ selector: 'cfm-page-list', templateUrl: './page-list.component.html', styles: [] }) export class PageListComponent implements OnInit { pageListCollapse = true; private projectId: number; pageList = []; constructor(private route: ActivatedRoute, private pageService: PageService, public toastr: ToastsManager) { } ngOnInit() { this.route.params.subscribe((params: any) => { this.projectId = +params['id']; }); this.pageListData(this.projectId); } /** * Toggle page list * */ togglePageList() { this.pageListCollapse = !this.pageListCollapse; } /** * Get page List * * @param id * return object */ pageListData(id: number) { this.pageService.getPageList(id).subscribe( result => { this.pageList = result['Data']; }, error => { this.toastr.error(error); } ); } } <file_sep>/src/app/core/security.service.ts import {Injectable} from '@angular/core'; import {User} from './user'; @Injectable() export class SecurityService { currentUser: User; constructor() { } /** * Has access * * @param action * @param resource * @returns {boolean} */ hasAccess(action, resource): boolean { return true; } } <file_sep>/src/app/project/project-form/project-form.component.ts import {Component, OnInit, OnDestroy} from '@angular/core'; import {ConfigService} from '../../core/config.service'; import * as _ from 'lodash'; import {ProjectService} from '../../core/project.service'; import {ActivatedRoute, Router} from '@angular/router'; import {ToastsManager} from 'ng2-toastr/ng2-toastr'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'cfm-project-form', templateUrl: './project-form.component.html' }) export class ProjectFormComponent implements OnInit, OnDestroy { projectForm: FormGroup; projectId: number; types: any; modes = []; scoreSettingAvailable: any; private sub: any; private modesSelected = []; constructor(private configService: ConfigService, private projectService: ProjectService, private route: ActivatedRoute, public toastr: ToastsManager, private formBuilder: FormBuilder, private router: Router) { this.projectForm = formBuilder.group({ 'Name': [null, Validators.required], 'Description': [null], 'QuestionnaireTypeId': [null, Validators.required], 'IsScoringAllowed': [false], 'Modes': [[], Validators.required] }); } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.projectId = +params['id']; if (this.projectId) { this.getProjectDetails(); //Disable the project type field in edit mode this.projectForm.get('QuestionnaireTypeId').disable(); } }); this.types = this.configService.getConfigProperty()['QuestionnaireTypes']; } ngOnDestroy() { this.sub.unsubscribe(); } /** * Add new project * * @param data */ onSubmit(data): void { data['Modes'] = this.prepareModeData(); if (this.projectId) { data['Id'] = this.projectId; this.projectService.updateProject(data).subscribe( result => { this.toastr.success(result['Message']); this.reloadProjects(); }, error => { this.toastr.error(JSON.parse(error._body).Message); } ) } else { this.projectService.createProject(data).subscribe( result => { this.toastr.success(result['Message']); this.reloadProjects(); this.router.navigateByUrl(`/project/${result['Data']['Id']}`); }, error => { this.toastr.error(JSON.parse(error._body).Message); } ) } } /** * Reload the new projects */ reloadProjects() { this.projectService.setProjects(); this.projectService.reloadProjects(true); } /** * Prepare mode data for API * * @returns {Array} */ prepareModeData() { if (this.projectId && this.modesSelected.length === 0) { return this.projectForm.get('Modes').value; } let modeData = []; if (this.modes && this.modesSelected) { for (let i = 0; i < this.modes.length; i++) { modeData.push({ 'ModeName': this.modes[i]['Name'], 'Status': (this.modesSelected.indexOf(this.modes[i]['Name']) !== -1) }); } } return modeData; } /** * Get project type dependent fields. * * @param value */ getDependentFields(value: number): void { const valueIndex = _.findIndex(this.types, (o) => { return o['ID'] === +value; }); this.modes = this.types[valueIndex]['Modes']; this.scoreSettingAvailable = (!!this.types[valueIndex]['Scoring']); this.projectForm.get('Modes').setValue(''); } /** * Push modes into mode data properties * * @param value */ selectModeCheckbox(value: string): void { (this.modesSelected.indexOf(value) === -1) ? this.modesSelected.push(value) : this.modesSelected.splice(this.modesSelected.indexOf(value), 1); if (this.modesSelected.length === 0) { this.projectForm.get('Modes').setValue(''); } } /** * Get project details */ getProjectDetails() { this.projectService.getProjectData(this.projectId).subscribe( result => { this.getDependentFields(result['Data']['QuestionnaireTypeId']); this.projectForm.setValue({ Name: result['Data']['Name'], Description: result['Data']['Description'], QuestionnaireTypeId: result['Data']['QuestionnaireTypeId'], IsScoringAllowed: result['Data']['IsScoringAllowed'], Modes: result['Data']['Modes'] }); }, error => { this.toastr.error(error); } ); } /** * Check if mode is selected * * @param modeName * @returns {any} */ isModeSelected(modeName: string): boolean { const modesValue = this.projectForm.get('Modes').value; if (modesValue.length) { const valueIndex = _.findIndex(this.projectForm.get('Modes').value, (o) => { return o['ModeName'] === modeName; }); if (valueIndex >= 0) { return modesValue[valueIndex]['Status']; } } return false; } } <file_sep>/src/app/project/questionnaire-tab/questionnaire/settings-slider/page-settings/page-settings.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'cfm-page-settings', templateUrl: './page-settings.component.html', styles: [] }) export class PageSettingsComponent implements OnInit { pageSettingsCollapse = false; constructor() { } ngOnInit() { } /** * Toggle page settings * */ togglePageSetting() { this.pageSettingsCollapse = !this.pageSettingsCollapse; } } <file_sep>/src/app/app.component.ts import {Component, ViewContainerRef, OnInit} from '@angular/core'; import {Router, NavigationStart} from '@angular/router'; import {MenuService} from './core/menu.service'; import {ToastsManager} from 'ng2-toastr/ng2-toastr'; import {Menu} from './core/menu'; @Component({ selector: 'cfm-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { flag: boolean; constructor(public toastr: ToastsManager, vcr: ViewContainerRef, private menuService: MenuService, private router: Router) { this.toastr.setRootViewContainerRef(vcr); // Opening the side menu on page change. router.events.forEach((event) => { if (event instanceof NavigationStart) { this.sideMenuToggle(false); } }); } ngOnInit() { // @todo: Change this with menu API. Right now it is hardcoded values. this.menuService.add('languages', { position: 1, Name: 'English', Exec: (selected: Menu) => { }, Children: null, IconClass: null, IconSource: './assets/global/img/flags/us.png', showInMenu: true, Route: '', }); this.menuService.add('languages', { position: 1, Name: 'French', Exec: (selected: Menu) => { }, Children: null, IconClass: null, IconSource: './assets/global/img/flags/fr.png', showInMenu: true, Route: '' }); this.menuService.add('languages', { position: 1, Name: 'German', Exec: (selected: Menu) => { }, Children: null, IconClass: null, IconSource: './assets/global/img/flags/de.png', showInMenu: true, Route: '' }); this.menuService.add('languages', { position: 1, Name: 'Russian', Exec: (selected: Menu) => { }, Children: null, IconClass: null, IconSource: './assets/global/img/flags/ru.png', showInMenu: true, Route: '' }); this.menuService.add('quick', { position: 1, Name: 'Quick Menu 1', Exec: (selected: Menu) => { }, Children: null, IconClass: 'icon-magnifier', IconSource: null, showInMenu: true, Route: '/dashboard' }); this.menuService.add('quick', { position: 1, Name: 'Quick Menu 2', Exec: (selected: Menu) => { }, Children: null, IconClass: 'icon-magnifier', IconSource: null, showInMenu: true, Route: '/dashboard' }); } /** * Side menu toggle * * @param value */ sideMenuToggle(value: boolean): void { this.menuService.setToggleClass(value); this.flag = this.menuService.getToggleClass(); } } <file_sep>/src/app/core/project.service.ts //@todo: This file is having hardcoded values, replace it later when we have API in place. import {Injectable} from '@angular/core'; import * as _ from 'lodash'; import {ApiService} from './api.service'; import {Observable} from 'rxjs'; import {Subject} from 'rxjs/Subject'; @Injectable() export class ProjectService { projects: any; private subject = new Subject<boolean>(); constructor(private apiService: ApiService) { } /** * Set the status to reload the projects * * @param reloadProjects */ reloadProjects(reloadProjects: boolean) { this.subject.next(reloadProjects); } /** * Send the status to reload the projects * * @returns {Observable<boolean>} */ getReloadedProjects(): Observable<any> { return this.subject.asObservable(); } /** * Set projects */ setProjects() { this.projects = this.apiService.getMethod('project'); } /** * Get projects * @returns {any} */ getProjects() { if (!this.projects) { this.setProjects(); } return this.projects; } /** * Get project details * * @param projectId */ getProjectData(projectId: number) { return this.apiService.getMethod(`questionnaire?id=${projectId}`); } /** * Create new project * * @param body * @returns {Observable<R|T>} */ createProject(body: Object) { return this.apiService.postMethod('project/create', body); } /** * Update project * * @param body * @returns {Observable<R|T>} */ updateProject(body: Object) { return this.apiService.putMethod('questionnaire/update', body); } /** * Delete project * * @param projectId * @returns {Observable<R|T>} */ deleteProject(projectId: number) { return this.apiService.deleteMethod(`questionnaire/delete?id=${projectId}`); } }<file_sep>/src/app/project/questionnaire-tab/questionnaire/settings-slider/answer-settings/answer-settings.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'cfm-answer-settings', templateUrl: './answer-settings.component.html', styles: [] }) export class AnswerSettingsComponent implements OnInit { answerSettingsCollapse = false; constructor() { } ngOnInit() { } /** * Toggle answer settings * */ toggleAnswerSetting() { this.answerSettingsCollapse = !this.answerSettingsCollapse; } } <file_sep>/src/app/shared/quick-menu/quick-menu.component.ts import {Component, OnInit} from '@angular/core'; import {MenuService} from '../../core/menu.service'; @Component({ selector: 'cfm-quick-menu', templateUrl: './quick-menu.component.html', }) export class QuickMenuComponent implements OnInit { menuItems: any; private menuToggle = false; constructor(private menuService: MenuService) { } ngOnInit() { this.menuItems = this.menuService.getMenuConfig('quick'); } /** * Quick menu toggle */ onClickMenuToggle() { this.menuToggle = !this.menuToggle; } /** * Close quick menu */ closeMenu() { this.menuToggle = false; } } <file_sep>/src/app/shared/side-bar/sub-menu/sub-menu.component.ts import {Component, OnInit, Input} from '@angular/core'; @Component({ selector: '[cfm-sub-menu]', templateUrl: './sub-menu.component.html' }) export class SubMenuComponent implements OnInit { @Input('cfm-sub-menu') subMenu: any; openChildItems: Array<boolean> = []; constructor() { } ngOnInit() { } } <file_sep>/src/app/app.module.ts import {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AppComponent} from './app.component'; import {CoreModule} from './core/core.module'; import {AppRoutingModule} from './app-routing.module'; import {ProjectModule} from './project/project.module'; import {PageNotFoundComponent} from './not-found.component'; import {ToastModule} from 'ng2-toastr/ng2-toastr'; import {HeaderComponent} from './shared/header/header.component'; import {FooterComponent} from './shared/footer/footer.component'; import {SideBarComponent} from './shared/side-bar/side-bar.component'; import {BrowserModule} from '@angular/platform-browser'; import {BsDropdownModule} from 'ngx-bootstrap'; import {HashLocationStrategy, LocationStrategy} from '@angular/common'; import {SubMenuComponent} from './shared/side-bar/sub-menu/sub-menu.component'; import {QuickMenuComponent} from './shared/quick-menu/quick-menu.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MomentModule} from 'angular2-moment'; @NgModule({ declarations: [ AppComponent, PageNotFoundComponent, HeaderComponent, FooterComponent, SideBarComponent, SubMenuComponent, QuickMenuComponent ], imports: [ BrowserModule, CoreModule, RouterModule, BrowserAnimationsModule, AppRoutingModule, BsDropdownModule.forRoot(), ToastModule.forRoot(), ProjectModule, MomentModule ], providers: [ {provide: LocationStrategy, useClass: HashLocationStrategy} ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/core/menu.ts export interface Menu { showInMenu: boolean; position: number; Name: string; Exec: (selected: Menu) => void; Route: string; Children: Menu[]; IconClass: string; IconSource: string; } <file_sep>/src/app/core/user.ts export class User { FullName: string; AccountName: string; ProfilePicture: string; } <file_sep>/src/app/project/project.module.ts import {NgModule} from '@angular/core'; import {ProjectComponent} from './project.component'; import {ProjectFormComponent} from './project-form/project-form.component'; import {ProjectRoutingModule} from './project-routing.module'; import {AccordionModule, ModalModule, TabsModule, TooltipModule} from 'ngx-bootstrap'; import {JWBootstrapSwitchModule} from 'jw-bootstrap-switch-ng2'; import {SharedModule} from '../shared/shared.module'; import {DeleteProjectComponent} from './delete-project/delete-project.component'; import {QuestionnaireTabComponent} from './questionnaire-tab/questionnaire-tab.component'; import {AddPageComponent} from './add-page/add-page.component'; import {PageListSliderComponent} from './questionnaire-tab/questionnaire/page-list-slider/page-list-slider.component'; import {PageThumbnailComponent} from './questionnaire-tab/questionnaire/page-list-slider/page-list/page-thumbnail/page-thumbnail.component'; import {QuestionnaireComponent} from './questionnaire-tab/questionnaire/questionnaire.component'; import {PageListComponent} from './questionnaire-tab/questionnaire/page-list-slider/page-list/page-list.component'; import {GroupTreeComponent} from './questionnaire-tab/questionnaire/page-list-slider/group-tree/group-tree.component'; import {QuestionnaireTopMenuComponent} from './questionnaire-tab/questionnaire/questionnaire-top-menu/questionnaire-top-menu.component'; import {SettingsSliderComponent} from './questionnaire-tab/questionnaire/settings-slider/settings-slider.component'; import {PageSettingsComponent} from './questionnaire-tab/questionnaire/settings-slider/page-settings/page-settings.component'; import {QuestionSettingsComponent} from './questionnaire-tab/questionnaire/settings-slider/question-settings/question-settings.component'; import {AnswerSettingsComponent} from './questionnaire-tab/questionnaire/settings-slider/answer-settings/answer-settings.component'; import {QuestionnaireMainComponent} from './questionnaire-tab/questionnaire/questionnaire-main/questionnaire-main.component'; import { DeletePageComponent } from './questionnaire-tab/questionnaire/page-list-slider/page-list/page-thumbnail/delete-page/delete-page.component'; import {TreeModule} from 'angular-tree-component'; import {PageService} from './page.service'; @NgModule({ imports: [ SharedModule, ProjectRoutingModule, AccordionModule, JWBootstrapSwitchModule, ModalModule, TabsModule.forRoot(), TooltipModule.forRoot(), TreeModule ], declarations: [ ProjectComponent, ProjectFormComponent, DeleteProjectComponent, QuestionnaireTabComponent, AddPageComponent, PageListSliderComponent, PageThumbnailComponent, QuestionnaireComponent, PageListComponent, GroupTreeComponent, QuestionnaireTopMenuComponent, SettingsSliderComponent, PageSettingsComponent, QuestionSettingsComponent, AnswerSettingsComponent, QuestionnaireMainComponent, DeletePageComponent ], providers: [PageService], }) export class ProjectModule { } <file_sep>/src/app/core/core.module.ts import {NgModule, SkipSelf, Optional} from '@angular/core'; import {CommonModule} from '@angular/common'; import {MenuService} from './menu.service'; import {throwIfAlreadyLoaded} from './module-import-guard'; import {ConfigService} from './config.service'; import {ProjectService} from "./project.service"; import {ApiService} from './api.service'; import {HttpModule} from '@angular/http'; @NgModule({ imports: [ CommonModule, HttpModule ], declarations: [], exports: [], providers: [ MenuService, ConfigService, ProjectService, ApiService ] }) export class CoreModule { constructor(@Optional() @SkipSelf() parentModule: CoreModule) { throwIfAlreadyLoaded(parentModule, 'CoreModule'); } } <file_sep>/src/app/project/add-page/add-page.ts export class AddPage { constructor(public pageName: string = '', public pageType: string = '', public questionType: string = '') { } } <file_sep>/src/app/project/page.service.ts import {Injectable} from '@angular/core'; import {ApiService} from '../core/api.service'; @Injectable() export class PageService { constructor(private apiService: ApiService) { } /** * Create Paqe * * @param body * @returns {Observable<R|T>} */ createPage(body: Object) { return this.apiService.postMethod('page', body); } /** * Get page list By Id * * @param questionnaireId * @returns {Observable<R|T>} */ getPageList(questionnaireId: number) { return this.apiService.getMethod(`page/GetPagesByQuestionnaireId?questionnaireId=${questionnaireId}`); } /** * Copy a page * * @param {number} pageId */ copyPage(pageId: number) { // todo: type in the API URL // return this.apiService.postMethod('', pageId); console.log('Copy API URL will come here page.service.ts ' + pageId); } } <file_sep>/src/app/project/questionnaire-tab/questionnaire/page-list-slider/page-list/page-thumbnail/page-thumbnail.component.ts import {Component, OnInit, Input} from '@angular/core'; import {PageService} from '../../../../../page.service' @Component({ selector: 'cfm-page-thumbnail', templateUrl: './page-thumbnail.component.html', styles: [] }) export class PageThumbnailComponent implements OnInit { @Input() pageId: number; @Input() pageName: string; constructor(private pageService: PageService) { } ngOnInit() { } /** * creates a copy of selected page */ copyPage(pageId: number) { // copy page API will come here and pageId will be passed in. this.pageService.copyPage(pageId); } } <file_sep>/src/app/app.config.ts import {environment} from '../environments/environment'; let config = { 'apiUrl': 'http://192.168.2.188:8080/api/' }; if (environment.production) { config = { 'apiUrl': 'http://192.168.2.188:8080/api/' }; } export const APP_CONFIG = config;<file_sep>/src/app/shared/side-bar/side-bar.component.ts import {Component, OnInit} from '@angular/core'; import {MenuService} from '../../core/menu.service'; import {ProjectService} from '../../core/project.service'; import {Menu} from '../../core/menu'; import {ToastsManager} from 'ng2-toastr'; @Component({ selector: 'cfm-side-bar', templateUrl: './side-bar.component.html' }) export class SideBarComponent implements OnInit { sidebarToggleFlag: boolean; isActive: number; isOpen = false; opened: Array<boolean> = []; menuItems: any; projects = []; projectMenuItems = []; constructor(public menuService: MenuService, private projectService: ProjectService, public toastr: ToastsManager) { this.projectService.getReloadedProjects().subscribe(reloadMenuItems => { this.getProjects(reloadMenuItems); }); } ngOnInit() { this.menuItems = this.menuService.getMenuConfig('left'); this.sidebarToggleFlag = this.menuService.getToggleClass(); //Sidebar menu this.menuService.add('left', { position: 1, Name: 'Home', Exec: (selected: Menu) => { }, Children: null, IconClass: 'icon-home', IconSource: null, showInMenu: true, Route: '/' }); this.getProjects(); } /** * Activate the sidebar menu item * * @param index */ activateMenuItem(index: number): void { this.isActive = index; this.isOpen = !this.isOpen; } /** * Get projects * * @param updateProjectMenuItems */ getProjects(updateProjectMenuItems = false): void { this.projectService.getProjects().subscribe( result => { this.projects = result['Data']; this.prepareProjectMenuItems(updateProjectMenuItems); }, error => { this.toastr.error(error); } ); } /** * Prepare project menu items * * @param updateProjectMenuItems */ prepareProjectMenuItems(updateProjectMenuItems = false): void { if (updateProjectMenuItems) { this.projectMenuItems = []; } for (let i = 0; i < this.projects.length; i++) { this.projectMenuItems.push({ position: 1, Name: this.projects[i]['Name'], Exec: (selected: Menu) => { }, Children: [{ position: 1, Name: 'Questionnaire', Exec: (selected: Menu) => { }, Children: null, IconClass: 'icon-puzzle', IconSource: null, showInMenu: true, Route: `/project/${this.projects[i]['QuestionnaireId']}/questionnaire` }], IconClass: 'icon-puzzle', IconSource: null, showInMenu: true, Route: `/project/${this.projects[i]['QuestionnaireId']}` }); } const projectMenu = { position: 1, Name: 'Data collection', Exec: (selected: Menu) => { }, Children: this.projectMenuItems, IconClass: 'icon-settings', IconSource: null, showInMenu: true, Route: '' }; updateProjectMenuItems ? this.menuService.update('left', projectMenu) : this.menuService.add('left', projectMenu); } } <file_sep>/src/app/core/api.service.ts import {Injectable} from '@angular/core'; import {Http, Response, Headers, RequestOptions} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {APP_CONFIG} from '../app.config'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/throw'; @Injectable() export class ApiService { constructor(private http: Http) { } /** * GET api call. * * @param url */ getMethod(url: string) { return this.http.get(APP_CONFIG.apiUrl + url, this.getOptions()) .map((res: Response) => res.json()) .catch(this.handleError); } /** * POST api call. * * @param url * @param body */ postMethod(url: string, body: Object) { return this.http.post(APP_CONFIG.apiUrl + url, body, this.getOptions()) .map((response: Response) => response.json()).catch(this.handleError); } /** * POST api call. * * @param url * @param body */ putMethod(url: string, body: Object) { return this.http.put(APP_CONFIG.apiUrl + url, body, this.getOptions()) .map((response: Response) => response.json()).catch(this.handleError); } /** * Delete api call. * * @param url */ deleteMethod(url: string) { return this.http.delete(APP_CONFIG.apiUrl + url, this.getOptions()) .map((response: Response) => response.json()).catch(this.handleError); } /** * Get request headers * * @returns {RequestOptions} */ private getOptions() { const headers = new Headers({ 'Content-Type': 'application/json', }); return new RequestOptions({headers: headers}); } /** * Check the error message. * * @param error * @returns {ErrorObservable} */ private handleError(error: Response | any) { console.error(error); return Observable.throw(error); } } <file_sep>/src/app/project/delete-project/delete-project.component.ts import {Component, OnInit, ViewChild, Input, Output, EventEmitter} from '@angular/core'; import {ModalDirective} from 'ngx-bootstrap/modal'; import {ProjectService} from '../../core/project.service'; import {ToastsManager} from 'ng2-toastr'; import {Router} from '@angular/router'; @Component({ selector: 'cfm-delete-project', templateUrl: './delete-project.component.html', styles: [] }) export class DeleteProjectComponent implements OnInit { @ViewChild('deleteProjectModal') public modal: ModalDirective; @Input('projectId') public projectId: number; @Output() reloadProjects = new EventEmitter(); constructor(private projectService: ProjectService, public toastr: ToastsManager, private router: Router) { } ngOnInit() { } /** * Show modal */ showDeleteProjectModal(): void { this.modal.show(); } /** * Hide modal */ hideDeleteProjectModal(): void { this.modal.hide(); } /** * Delete Project */ deleteProject(): void { this.projectService.deleteProject(this.projectId).subscribe( result => { this.toastr.success(result['Message']); this.reloadProjects.next(); this.hideDeleteProjectModal(); this.router.navigateByUrl('/'); }, error => { this.toastr.error(error); } ); } } <file_sep>/src/app/core/config.service.ts //@todo: This file is having hardcoded values, replace it later when we have API in place. import {Injectable} from '@angular/core'; import {config} from './config'; import * as _ from 'lodash'; @Injectable() export class ConfigService { constructor() { } /** * Get configuration properties * * @returns {any} */ getConfigProperty(): any { return config['Project'][0]; } /** * Get configuration properties By modeType * * @returns {any} */ getConfigPropertyByModeId(modeId: number): any { const valueIndex = _.findIndex(config['Project'][0]['QuestionnaireTypes'], (o) => { return o['ID'] === modeId; }); return config['Project'][0]['QuestionnaireTypes'][valueIndex]; } } <file_sep>/src/app/project/questionnaire-tab/questionnaire/page-list-slider/page-list/page-thumbnail/delete-page/delete-page.component.ts import {Component, OnInit, ViewChild} from '@angular/core'; import {ModalDirective} from 'ngx-bootstrap/modal'; @Component({ selector: 'cfm-delete-page', templateUrl: './delete-page.component.html', styles: [] }) export class DeletePageComponent implements OnInit { @ViewChild('deletePageModal') public modal: ModalDirective; pageId: number; constructor() { } ngOnInit() { } /** * Show delete page modal * @param pageId */ showDeletePageModal(pageId: number): void { this.pageId = pageId; this.modal.show(); } /** * Hide modal */ hideDeletePageModal(): void { this.modal.hide(); } /** * Delete page */ deletePage(): void { console.log('Delete Page API will come here PageId = ' + this.pageId); this.hideDeletePageModal(); } } <file_sep>/src/app/project/projectSettings.ts /** * Created by swapnilr on 7/6/2017. */ export class ProjectSettings { name: string; description: string; type: string; mode: [{name: string, value: false}]; score: boolean; constructor() { } } <file_sep>/src/app/shared/header/header.component.ts import {Component, OnInit, Output, EventEmitter} from '@angular/core'; import {MenuService} from '../../core/menu.service'; import {ProjectService} from '../../core/project.service'; import {Menu} from '../../core/menu'; @Component({ selector: 'cfm-header', templateUrl: './header.component.html' }) export class HeaderComponent implements OnInit { notifications: any; languages: any; notificationData: any; private sideBarToggle = true; @Output() addToggleClass: EventEmitter<boolean> = new EventEmitter<boolean>(); constructor(private menuService: MenuService, private projectService: ProjectService) { this.projectService.getReloadedProjects().subscribe(reloadMenuItems => { this.getNotifications(reloadMenuItems); }); } ngOnInit() { this.getNotifications(); this.notifications = this.menuService.getMenuConfig('alerts'); this.languages = this.menuService.getMenuConfig('languages'); } /** * Add toggle to side menu */ addToggleClassSideMenu(): void { this.sideBarToggle = !this.sideBarToggle; this.addToggleClass.emit(!this.sideBarToggle); } /** * Get notifications * * @param reloadMenuItems */ getNotifications(reloadMenuItems = false): void { this.menuService.getNotifications().subscribe( result => { this.notificationData = result['Data']; this.prepareNotificationMenuItems(reloadMenuItems); }, error => { console.log(error); } ) } /** * Prepare notifications menu items * * @param reloadMenuItems */ prepareNotificationMenuItems(reloadMenuItems = false): void { if (reloadMenuItems) { this.menuService.delete('alerts'); } for (let notification of this.notificationData) { this.menuService.add('alerts', { position: 1, Name: notification['Message'], Exec: (selected: Menu) => { }, Children: null, IconClass: 'fa fa-plus', IconSource: notification['CreatedOn'], showInMenu: true, Route: '' }); } this.notifications = this.menuService.getMenuConfig('alerts'); } } <file_sep>/src/app/project/add-page/add-page.component.ts import {Component, OnInit, ViewChild} from '@angular/core'; import {NgForm} from '@angular/forms'; import {ActivatedRoute} from '@angular/router'; import {ModalDirective} from 'ngx-bootstrap/modal'; import {AddPage} from './add-page'; import {ConfigService} from '../../core/config.service'; import {ProjectService} from '../../core/project.service' import * as _ from 'lodash'; import {ToastsManager} from 'ng2-toastr'; import {PageService} from '../page.service' @Component({ selector: 'cfm-add-page', templateUrl: './add-page.component.html', styles: [] }) export class AddPageComponent implements OnInit { modeType: number; projectId: number; model: AddPage = new AddPage(); pageTypes = []; questionType = []; subPageType = []; @ViewChild('addPageForm') form: any; @ViewChild('addPageModal') public modal: ModalDirective; constructor(private route: ActivatedRoute, private configService: ConfigService, private projectService: ProjectService, public toastr: ToastsManager, private pageService: PageService, ) { } ngOnInit() { this.route.params.subscribe((params: any) => { this.projectId = +params['id']; }); } /** * Show modal */ showAddPageModal(): void { this.modal.show(); } /** * Hide modal */ hideAddPageModal(): void { this.modal.hide(); } /** * Create Page * * @param addPageForm */ addPage(form: NgForm): void { if (!form.valid) { return; } const createPage = { 'Id': 0, 'Name': form.value.pagename, 'PageTypeId': form.value.pageType, 'SubPageTypeId': (form.value.subPage) ? form.value.subPage : null, 'QuestionTypeId': (form.value.question) ? form.value.question : null, 'QuestionnaireId': this.projectId }; this.pageService.createPage(createPage).subscribe( result => { this.toastr.success(result['Message']); this.hideAddPageModal(); }, error => { this.toastr.error(JSON.parse(error._body).Message); } ) } /** * Get question and subPageType type By page type. * * @param value */ getDependentQuestionType(value: number): void { const valueIndex = _.findIndex(this.pageTypes, (o) => { return o['ID'] === +value; }); this.subPageType = this.pageTypes[valueIndex]['SubPageTypes'] ? this.pageTypes[valueIndex]['SubPageTypes'] : []; this.questionType = this.pageTypes[valueIndex]['QuestionTypes'] ? this.pageTypes[valueIndex]['QuestionTypes'] : []; } } <file_sep>/src/app/project/questionnaire-tab/questionnaire/settings-slider/question-settings/question-settings.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'cfm-question-settings', templateUrl: './question-settings.component.html', styles: [] }) export class QuestionSettingsComponent implements OnInit { questionSettingsCollapse = false; constructor() { } ngOnInit() { } /** * Toggle question settings * */ toggleQuestionSetting() { this.questionSettingsCollapse = !this.questionSettingsCollapse; } }
d4385e7564adff4bb195fa24016c7f386ce9957f
[ "TypeScript" ]
30
TypeScript
PoonamRanawat/cv-angular2
91218e283aa0299fe48c5c336606350938fe287e
8da9131c1c95d621ef9bda8cd6898d0829e15833
refs/heads/main
<file_sep>function makeGetCustomer({ customerDb }) { // * Get Customer Use Case return async function getCustomer({ email } = {}) { if (!email) { throw new Error("Email should be supplied"); } const customer = await customerDb.findCustomerByEmail({ email }); return customer; }; } module.exports = makeGetCustomer; <file_sep>function makeCreateAuth({ registerAuthUc }) { // * Register Authentication Credentials return async function registerAuth(httpRequest) { const headers = { "Content-Type": "application/json" }; let statusCode = 201; let body = {}; // * { username, password } const { ...authInfo } = httpRequest.body; try { const { email, role } = await registerAuthUc(authInfo); body = { registered: { email, role } }; } catch (error) { statusCode = 400; body = { error: error.message }; } return { headers, statusCode, body, }; }; } module.exports = makeCreateAuth; <file_sep>function makeCreateCustomer({ createCustomerUc }) { // * Create Customer Controller return async function createCustomer(httpRequest) { const headers = { "Content-Type": "application/json" }; let statusCode = 201; let body = {}; const { ...customerInfo } = httpRequest.body; try { const result = await createCustomerUc(customerInfo); body = { createdCustomer: result }; } catch (error) { statusCode = 400; body = { error: error.message }; } return { headers, statusCode, body, }; }; } module.exports = makeCreateCustomer; <file_sep>const makeCustomer = require("./index") describe('customer', () => { const validCustomerInput = { "email": "<EMAIL>", "firstname": "Edzer", "lastname": "Padilla", "country": "Philippines", "zip": "1230AA", "city": "Makati", "street": "S. Javier Street", "houseNumber": "Unit 404" } // * validation tests it('must have an email', () => { let testCustomerInput = { ...validCustomerInput } testCustomerInput.email = null expect(() => makeCustomer(testCustomerInput)).toThrow() }) // * getters tests it('must get valid email', () => { const customer = makeCustomer(validCustomerInput) expect(customer.getEmail()).toBe('<EMAIL>') }) // * setters tests })<file_sep>function makeGetCustomer({ getCustomerUc }) { // * Get Customer Controller return async function createSubscription(httpRequest) { const headers = { "Content-Type": "application/json" }; let statusCode = 400; let body = {}; const { email } = httpRequest.params; try { body = await getCustomerUc({ email }); if (!body) { statusCode = 404; } } catch (error) { body = { error: error.message }; } return { headers, statusCode, body, }; }; } module.exports = makeGetCustomer; <file_sep>"# kaguya" <file_sep>module.exports = { setupFiles: [ 'dotenv/config' ], reporters: ['default', 'jest-junit'], coverageReporters: ['text', 'cobertura'] } <file_sep>const { Pool } = require("pg"); const makeCustomerDb = require("./customer"); const { PG_USER, PG_PASS, PG_HOST, PG_DB, PG_PORT, PG_SSL } = process.env; const pool = new Pool({ user: PG_USER, password: <PASSWORD>, host: PG_HOST, database: PG_DB, port: PG_PORT, ssl: PG_SSL, }); pool.on("error", (err) => { console.error("Unexpected error on client", err); process.exit(-1); }); async function makeDb() { return pool; } async function destroyDb() { await pool.end(); } customerDb = makeCustomerDb({ makeDb }); module.exports = { customerDb }; <file_sep>const AUTH_TABLE = "auth"; function makeAuth({ makeDb }) { return Object.freeze({ registerAuth, findAuthByEmail, }); // * register a user - password authentication async function registerAuth({ ...authInfo }) { const client = await makeDb(); const result = await client.saveDoc(AUTH_TABLE, authInfo); return result; } // * find credentials by email async function findAuthByEmail({ email }) { const client = await makeDb(); const result = await client[AUTH_TABLE].findDoc({ email }); if (result.length === 0) { return null; } return result[0]; } } module.exports = makeAuth; <file_sep>const schema = { type: "object", properties: { email: { type: "string", format: "email" }, password: { type: ["string"], minLength: 8, maxLength: 32 }, role: { type: ["string"], enum: ["customer", "admin"], default: "customer", }, }, required: ["email", "password"], additionalProperties: false, }; module.exports = ({ validateData, encrypt, compare, createAuthToken, validateAuthToken, }) => { return async function makeAuth(auth) { // * used schema instead of nested if-else statements const errorMessage = validateData(schema, auth); if (errorMessage) { throw new Error(errorMessage); } let encryptedPassword = await encrypt(auth.password); return Object.freeze({ getEmail: () => auth.email, getEncryptedPassword: () => encryptedPassword, isPasswordMatched: async (encryptedPassword) => await compare(auth.password, encryptedPassword), getRole: () => auth.role, // * JWT token getAuthToken: () => createAuthToken({ email: auth.email, role, }), isAuthTokenValid: (authToken) => validateAuthToken(authToken), }); }; }; <file_sep>const customerUseCases = require("./customer"); const authUseCases = require("./auth"); module.exports = { customerUseCases, authUseCases }; <file_sep>const massive = require("massive"); const makeCustomerDb = require("./customer"); const makeAuthDb = require("./auth"); const { PG_USER, PG_PASS, PG_HOST, PG_DB, PG_PORT, PG_SSL } = process.env; let client = null; async function makeDb() { if (!client) { client = await massive( { user: PG_USER, password: <PASSWORD>, host: PG_HOST, database: PG_DB, port: PG_PORT, ssl: PG_SSL === "true", }, { documentPkType: "uuid", } ); } return client; } const customerDb = makeCustomerDb({ makeDb }); const authDb = makeAuthDb({ makeDb }); module.exports = { customerDb, authDb }; <file_sep>const schema = { type: "object", properties: { email: { type: "string", format: "email" }, firstname: { type: ["string"], minLength: 2, maxLength: 32 }, lastname: { type: ["string"], minLength: 2, maxLength: 32 }, country: { type: "string", minLength: 2, maxLength: 32 }, zip: { type: "string", pattern: '^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-zA-Z]{2}$' }, city: { type: "string", minLength: 2, maxLength: 32 }, street: { type: "string", minLength: 2, maxLength: 32 }, houseNumber: { type: "string", minLength: 2, maxLength: 32 }, state: {type: "string", enum: ['inactive', 'active'], default: 'inactive'} }, required: ["email", "firstname", "lastname", "country", "zip", "city", "street", "houseNumber"], additionalProperties: false, }; module.exports = ({ validateData }) => { return function makeCustomer(customer = {}) { // * used schema instead of nested if-else statements const errorMessage = validateData(schema, customer); if (errorMessage) { throw new Error(errorMessage); } return Object.freeze({ getEmail: () => customer.email, getFirstName: () => customer.firstname, getLastName: () => customer.lastname, getCountry: () => customer.country, getZip: () => customer.zip, getCity: () => customer.city, getStreet: () => customer.street, getHouseNumber: () => customer.houseNumber, getState: () => customer.state, setActive: () => customer.state = "active", setInactive: () => customer.state = "inactive" }); }; };<file_sep>const { makeCustomer } = require("../../entities"); function makeCreateCustomer({ customerDb, validateAddress }) { // * Create Customer Use Case return async function createCustomer(customerInfo) { const customer = makeCustomer(customerInfo); const existingCustomer = await customerDb.findCustomerByEmail({ email: customer.getEmail(), }); if (existingCustomer) { return existingCustomer; } const result = validateAddress({ country: customer.getCountry(), zip: customer.getZip(), city: customer.getCity(), street: customer.getStreet(), houseNumber: customer.getHouseNumber(), }); if (!result) { throw new Error("Address must be valid"); } const createdCustomer = await customerDb.createCustomer({ email: customer.getEmail(), firstname: customer.getFirstName(), lastname: customer.getLastName(), state: customer.getState(), billingAddress: { country: customer.getCountry(), zip: customer.getZip(), city: customer.getCity(), street: customer.getStreet(), houseNumber: customer.getHouseNumber(), }, }); return createdCustomer; }; } module.exports = makeCreateCustomer; <file_sep>const { customerDb } = require("../../data-access"); const makeCreateCustomer = require("./createCustomer"); const makeGetCustomer = require("./getCustomer"); // Create UC from factory const validateAddress = ({}) => {return true} const createCustomerUc = makeCreateCustomer({ customerDb, validateAddress }); const getCustomerUc = makeGetCustomer({ customerDb }); const customerUseCases = Object.freeze({ createCustomerUc, getCustomerUc }); module.exports = customerUseCases <file_sep>const Ajv = require("ajv").default; const addFormats = require("ajv-formats"); const bcrypt = require("bcrypt"); var jwt = require("jsonwebtoken"); const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true }); addFormats(ajv, ["email"]); const { AUTH_TOKEN_SECRET } = process.env; const SALT_ROUNDS = 10; function validateData(schema, data) { const validate = ajv.compile(schema); const result = validate(data); if (!result) { return `${validate.errors[0].dataPath} ${validate.errors[0].message}`; } else { return null; } } async function encrypt(password) { const salt = await bcrypt.genSalt(SALT_ROUNDS); const hashed = await bcrypt.hash(password, salt); return hashed; } async function compare(password, encryptedPassword) { const isMatched = await bcrypt.compare(password, encryptedPassword); return isMatched; } function createAuthToken({ email, role, country = "NL" }) { const token = jwt.sign( { email, role, country, }, AUTH_TOKEN_SECRET, { expiresIn: "7d" } // * 7 days session expiration ); return token; } function validateAuthToken(authToken) { let decoded = jwt.verify(authToken, AUTH_TOKEN_SECRET); return decoded; } // * Entities const buildMakeAuth = require("./auth"); // * Inject dependencies const makeAuth = buildMakeAuth({ validateData, encrypt, compare, createAuthToken, validateAuthToken, }); module.exports = makeAuth; <file_sep>const CUSTOMER_TABLE = "customer"; function makeCustomer({ makeDb }) { return Object.freeze({ createCustomer, findCustomerByEmail, }); async function createCustomer({ ...customerInfo }) { const client = await makeDb(); const result = await client.saveDoc(CUSTOMER_TABLE, customerInfo); return result; } async function findCustomerByEmail({ email }) { const client = await makeDb(); const result = await client[CUSTOMER_TABLE].findDoc({ email }); if (result.length === 0) { return null; } return result[0]; } } module.exports = makeCustomer; <file_sep>const { makeAuth } = require("../../entities"); function makeRegisterAuth({ authDb }) { // * Register Credential Use Case return async function registerAuth(authInfo) { const auth = await makeAuth(authInfo); // * Authentication email is already existin const existingAuth = await authDb.findAuthByEmail({ email: auth.getEmail(), }); if (existingAuth) { return existingAuth; } const result = authDb.registerAuth({ email: auth.getEmail(), password: <PASSWORD>(), role: auth.getRole(), }); return result; }; } module.exports = makeRegisterAuth; <file_sep>const { makeAuth } = require("../../entities"); function makeLoginAuth({ authDb }) { // * Login Authentication Use Case return async function loginAuth(authInfo) { const auth = await makeAuth(authInfo); // * Authentication email is already existing const existingAuth = await authDb.findAuthByEmail({ email: auth.getEmail(), }); if (!existingAuth) { throw new Error("No matching email found"); } // * Check if passwords will match const result = await auth.isPasswordMatched(existingAuth.password); if (!result) { throw new Error("Password did not matched"); } const authToken = auth.getAuthToken(); return authToken; }; } module.exports = makeLoginAuth; <file_sep>const { authDb } = require("../../data-access"); const makeRegisterAuth = require("./registerAuth"); const makeLoginAuth = require("./loginAuth"); // Create UC from factory const md5 = ({}) => { return true; }; const registerAuthUc = makeRegisterAuth({ authDb, md5 }); const loginAuthUc = makeLoginAuth({ authDb, md5 }); const authUseCases = Object.freeze({ registerAuthUc, loginAuthUc, }); module.exports = authUseCases; <file_sep>function createExpressAdapter(controller) { return (request, response) => { const httpRequest = { body: request.body, query: request.query, params: request.params, ip: request.ip, method: request.method, path: request.path, headers: { "Content-Type": request.get("Content-Type"), Referer: request.get("referer"), "User-Agent": request.get("User-Agent"), }, }; controller(httpRequest) .then(({ headers, statusCode, body }) => { if (headers) { response.set(headers); } response.type("json"); response.status(statusCode).send(body); }) .catch((e) => { console.log(e) response.status(500).send({ error: "An unkown error occurred." }) } ); }; } module.exports = createExpressAdapter; <file_sep>const { Router } = require("express"); const requestAdapter = require("../adapters/createExpressAdapter"); const { authController } = require("../controllers"); const { registerAuth, loginAuth } = authController; const router = Router(); module.exports = () => { router.post("/register", requestAdapter(registerAuth)); router.post("/login", requestAdapter(loginAuth)); return router; }; <file_sep>const { customerUseCases } = require("../../usecases"); const makeGetCustomer = require("./getCustomer"); const makeCreateCustomer = require("./createCustomer"); const { getCustomerUc, createCustomerUc } = customerUseCases; // * Create the Controllers const createCustomer = makeCreateCustomer({ createCustomerUc }); const getCustomer = makeGetCustomer({ getCustomerUc }); const customerController = Object.freeze({ getCustomer, createCustomer }); module.exports = customerController
9294078ad0be51a7c690259ecdcbb0cd113694b9
[ "JavaScript", "Markdown" ]
23
JavaScript
dzerium/kaguya
d1afa65687f6c29ffc42336bcd0da8d584c0c11f
a612506646022db919c35505c42daaac3f27bf19
refs/heads/master
<repo_name>leokret/oministack-week-10<file_sep>/README.md # oministack-week-10 Rocketseat study (Semana oministack 10) # How to startup yarn or npm install to install project yarn dev or npm run dev to run project <file_sep>/backend/src/routes.js const { Router } = require('express') const DevController = require('./controllers/DevController') const SearchController = require('./controllers/SearchController') const routes = Router() routes.get('/dev', DevController.index) routes.get('/dev/search', SearchController.index) routes.post('/dev', DevController.store) module.exports = routes
6e5e4ef5163975330ef8a6d6441b957d0732c0d9
[ "Markdown", "JavaScript" ]
2
Markdown
leokret/oministack-week-10
04374360ab9e7652e528a30fedc68525cef5bf70
9409cf258667e633b90fec8232e5737f8048d210
refs/heads/main
<repo_name>Udit-8/TrackIt<file_sep>/README.md # TrackIt Android App to track students travelling in school bus
b819bdfee407d3654d5d19f35008e704534a19f2
[ "Markdown" ]
1
Markdown
Udit-8/TrackIt
15988c83031de6e14e948bd54d00442fc5ecdd07
130b9a62aa4b6c453d516f92924bf8ff516e28e2
refs/heads/master
<file_sep>require 'spec_helper' describe "books/show" do before(:each) do @book = assign(:book, stub_model(Book, :name => "Name", :full_title => "Full Title", :author => "Author", :publisher => "Publisher", :version => "9.99", :isbn => "Isbn", :original_price => "Original Price", :sale_price => "Sale Price", :cover_pic => "Cover Pic", :tags => "Tags", :popularity => 1, :description => "MyText", :in_stock => 2, :style => "Style", :publication_city => "Publication City" )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers rendered.should match(/Name/) rendered.should match(/Full Title/) rendered.should match(/Author/) rendered.should match(/Publisher/) rendered.should match(/9.99/) rendered.should match(/Isbn/) rendered.should match(/Original Price/) rendered.should match(/Sale Price/) rendered.should match(/Cover Pic/) rendered.should match(/Tags/) rendered.should match(/1/) rendered.should match(/MyText/) rendered.should match(/2/) rendered.should match(/Style/) rendered.should match(/Publication City/) end end <file_sep># Be sure to restart your server when you modify this file. BookSheriff::Application.config.session_store :cookie_store, key: '_book_sheriff_session' <file_sep>require 'spec_helper' describe "books/new" do before(:each) do assign(:book, stub_model(Book, :name => "MyString", :full_title => "MyString", :author => "MyString", :publisher => "MyString", :version => "9.99", :isbn => "MyString", :original_price => "MyString", :sale_price => "MyString", :cover_pic => "MyString", :tags => "MyString", :popularity => 1, :description => "MyText", :in_stock => 1, :style => "MyString", :publication_city => "MyString" ).as_new_record) end it "renders new book form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", books_path, "post" do assert_select "input#book_name[name=?]", "book[name]" assert_select "input#book_full_title[name=?]", "book[full_title]" assert_select "input#book_author[name=?]", "book[author]" assert_select "input#book_publisher[name=?]", "book[publisher]" assert_select "input#book_version[name=?]", "book[version]" assert_select "input#book_isbn[name=?]", "book[isbn]" assert_select "input#book_original_price[name=?]", "book[original_price]" assert_select "input#book_sale_price[name=?]", "book[sale_price]" assert_select "input#book_cover_pic[name=?]", "book[cover_pic]" assert_select "input#book_tags[name=?]", "book[tags]" assert_select "input#book_popularity[name=?]", "book[popularity]" assert_select "textarea#book_description[name=?]", "book[description]" assert_select "input#book_in_stock[name=?]", "book[in_stock]" assert_select "input#book_style[name=?]", "book[style]" assert_select "input#book_publication_city[name=?]", "book[publication_city]" end end end <file_sep>require 'spec_helper' describe "books/index" do before(:each) do assign(:books, [ stub_model(Book, :name => "Name", :full_title => "Full Title", :author => "Author", :publisher => "Publisher", :version => "9.99", :isbn => "Isbn", :original_price => "Original Price", :sale_price => "Sale Price", :cover_pic => "Cover Pic", :tags => "Tags", :popularity => 1, :description => "MyText", :in_stock => 2, :style => "Style", :publication_city => "Publication City" ), stub_model(Book, :name => "Name", :full_title => "Full Title", :author => "Author", :publisher => "Publisher", :version => "9.99", :isbn => "Isbn", :original_price => "Original Price", :sale_price => "Sale Price", :cover_pic => "Cover Pic", :tags => "Tags", :popularity => 1, :description => "MyText", :in_stock => 2, :style => "Style", :publication_city => "Publication City" ) ]) end it "renders a list of books" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Name".to_s, :count => 2 assert_select "tr>td", :text => "Full Title".to_s, :count => 2 assert_select "tr>td", :text => "Author".to_s, :count => 2 assert_select "tr>td", :text => "Publisher".to_s, :count => 2 assert_select "tr>td", :text => "9.99".to_s, :count => 2 assert_select "tr>td", :text => "Isbn".to_s, :count => 2 assert_select "tr>td", :text => "Original Price".to_s, :count => 2 assert_select "tr>td", :text => "Sale Price".to_s, :count => 2 assert_select "tr>td", :text => "Cover Pic".to_s, :count => 2 assert_select "tr>td", :text => "Tags".to_s, :count => 2 assert_select "tr>td", :text => 1.to_s, :count => 2 assert_select "tr>td", :text => "MyText".to_s, :count => 2 assert_select "tr>td", :text => 2.to_s, :count => 2 assert_select "tr>td", :text => "Style".to_s, :count => 2 assert_select "tr>td", :text => "Publication City".to_s, :count => 2 end end <file_sep>json.array!(@books) do |book| json.extract! book, :name, :full_title, :author, :publisher, :version, :isbn, :date_published, :original_price, :sale_price, :cover_pic, :tags, :popularity, :time_added, :description, :in_stock, :style, :publication_city json.url book_url(book, format: :json) end<file_sep># BookSheriff Web Application: Written by <NAME> <<EMAIL>> This is the application for the [*BookSheriff Website*](http://thebooksheriff.com/) by [<NAME>](http://and0ne808.wix.com/andrew/) Testing to see if it all works<file_sep>class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :name t.string :full_title t.string :author t.string :publisher t.decimal :version t.string :isbn t.date :date_published t.string :original_price t.string :sale_price t.string :cover_pic t.string :tags t.integer :popularity t.timestamp :time_added t.text :description t.integer :in_stock t.string :style t.string :publication_city t.timestamps end end end
7f2190d053911c8ce2daa68ee4d6caa2f830ad73
[ "Markdown", "Ruby" ]
7
Ruby
and0ne808/book_sheriff
6bf017a46ae34110e5e6ab45ee7bec50097a57f3
e6d1294afcb39f198fa6791729df6f0de91820c8
refs/heads/master
<file_sep>#!/bin/bash is_root_user(){ [ $(id -u) -eq 0 ] } is_root_user echo "s" <file_sep>#!/bin/bash var=$(cat /etc/passwd | cut -d: -f1) maxl=0 max='' minl=111 min='' for x in $var do if [ ${#x} -gt $maxl ]; then maxl=${#x} max=$x fi if [ ${#x} -lt $minl ] ; then minl=${#x} min=$x fi done echo $max echo $min <file_sep>#include <iostream> using namespace std; int main() { int tab[5]={4,2,3,5,1}; int max=0; int min=tab[0]; for(int i=0; i<5; i++) {if(max<=tab[i]) {max=tab[i]; } else{ if(min>=tab[i]) min=tab[i]; } } cout<<"max = "<<max<<endl; cout<<"min = "<<min; return 0; } <file_sep>#!/bin/bash create_jail(){ d=$1 echo "create_jail(): d is set to $d" } d=/apache.jail echo "Before to $d" create_jail "/home/apache/jail" echo "After to $d" <file_sep>#include <iostream> using namespace std; int main() {int tab[7]; int i=0; int j=0; for(int i=0; i<7; i++) { cin>>tab[i]; } for(int i=0; i<7; i++) {for(int j=0; j<6-i; j++) {if(tab[j]>=tab[j+1]) swap(tab[j],tab[j+1]); } } for(int i=0; i<7; i++) { cout<<tab[i]<<" "; } return 0; } <file_sep>#!/bin/bash for FILE in *.sh do echo $var done <file_sep>#!/bin/bash d=/apache.jail create_jail(){ local d=$1 echo "create_jail(): d is set to $d" } echo "Before to $d" create_jail "/home/apache/jail" echo "After to $d" <file_sep>#!/bin/bash sleep echo "argument nr 1: $1" echo "argument nr 2: $2" echo "argument nr 3: $3" <file_sep>#!/bin/bash # Variables domain="CyberCoBIz" out="" function to_lower() { local str="$@" local output output=$(tr '[A-Z]' '[a-z]'<<<"${str}") echo $output } to_lower "THiS iS A TeSt" out=$(to_lower ${domain}) echo "Domain name : $out" <file_sep># Warsztat-programisty <file_sep>#!/bin/bash if echo $tab="xyz" then echo $var else echo $x fi <file_sep>#!/bin/bash while true do DATE=`date '+%Y-%d-%m% H: %M"%s'` echo $DATE sleep 2s done <file_sep>#include<iostream> using namespace std; int main() { int i; int index; int size =10; int t[size]={10,7,19,5,14,3,22,23,17,1}; int mn; int j; j=0; index = 0; for(j=0; j<size; j++) {mn=t[0+j]; index=j; for(i=0+j; i<size; i++) { if(t[i]<mn) { mn=t[i]; index = i; } } t[index] = t[0+j]; t[0+j] = mn; } for(i=0; i<size; i++) cout<<t[i]<< endl; return 0; } <file_sep>#!/bin/bash var=$(cat /etc/passwd | cut -d: -f1) for x in $var do echo ${#x} done <file_sep>#!/bin/bash while [ echo $zmienna < 3 ] do echo $1 zmienna = 2 done <file_sep>#include <stdio.h> int main() { int r=3; printf("Pole kola = %d",r*r); printf("Pi"); return 0; } <file_sep>#include <iostream> using namespace std; int main() {int tab[9]={3,2,4,5,1,10,23,7,11}; int piv=tab[4] return 0; } <file_sep>#!/bin/bash cut /etc/passwd | cut -d: -f1; <file_sep>#!/bin/bash var=$(cat | cut -d: -f1) for file in $(ls ~); do if [ -r $file ] ; then echo '1. wysiwietlic?' fi done <file_sep>#!/bin/bash # dynbox.sh - Yes/No box demo dialog --title "Delete file" \ --backtitle "Linux Shell Script Tutorial" \ \"/tmp/foo.txt\"?" 7 60 respone=$? case $response in 0) echo "File Deleted.";; 1) echo "not Deleted.";; 255) echo "[ESC]";; esac <file_sep>#include <stdio.h> int main() { int a=0; int h=0; printf("wpisz podstawe "); scanf("%d" , &a); printf("wpisz wysokosc "); scanf("%d" , &h); printf("Pole trojkata = %d",a*h/2); printf("Warsztat"); return 0; }
91206e52c23c9f23210c4b0a8df9e455789958b2
[ "Markdown", "C", "C++", "Shell" ]
21
Shell
Bartonio/Warsztat-programisty
1236c48c65a7d108c03dbcb2c7053ccfb6be9568
683ba58c910c9eb1cbe6fb4c94bea8f47f1e4d80
refs/heads/master
<file_sep>import datetime import logging import select import socket import threading import time import traceback import queue import win32com.client logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Change the formatting ch = logging.StreamHandler() fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') ch.setFormatter(fmt) logger.addHandler(ch) running = True def list_to_string(l): return ','.join(map(str, l)) class LabViewApp(): """ Represents a LabView application """ def __init__(self, application, vi): self.app = win32com.client.Dispatch(application) self.vi = self.app.GetViReference(vi) def get_data(self, name): return self.vi.GetControlValue(name) def set_data(self, control_name, control_data, Async=False): if type(control_data) in (tuple, list): self.vi.SetControlValue('SetControl', (control_name, '', control_data)) else: self.vi.SetControlValue('SetControl', (control_name, control_data, [[], []])) if not Async: while self.vi.GetControlValue('SetControl')[0] != '': time.sleep(0.1) class QueueThread(threading.Thread): """ Processes commands in the queue. """ def __init__(self, name, work_queue, lock): threading.Thread.__init__(self, name=name) self.work_queue = work_queue self.lock = lock def run(self): global running logger.info('Starting main queue thread') # We have to call CoInitialize to get the COM working with threads win32com.client.pythoncom.CoInitialize() # Connect to the fridge software self.tc = LabViewApp('DRTempControl.Application', 'DR TempControl.exe\TC.vi') self.fp = LabViewApp('DRFrontPanel.Application', 'DR FrontPanel.exe\FP.vi') while running: self.lock.acquire() if not self.work_queue.empty(): sock, data = self.work_queue.get() self.lock.release() self.handle_command(sock, data) else: self.lock.release() time.sleep(0.1) logger.info('Exiting queue thread, socket thread will exit within 60s') def handle_command(self, sock, command): """ Parses an incoming command and sends the response back. """ response = '' try: if command.startswith('all_temperatures'): response = list_to_string(self.tc.get_data('T')) elif command.startswith('all_currents'): response = list_to_string(self.tc.get_data('I')) elif command.startswith('all_resistances'): response = list_to_string(self.tc.get_data('R')) elif command.startswith('temperature'): response = str(self.tc.get_data('T')[int(command[-1])]) elif command.startswith('current'): response = str(self.tc.get_data('I')[int(command[-1])]) elif command.startswith('resistance'): response = str(self.tc.get_data('R')[int(command[-1])]) elif command.startswith('pressure'): response = str(self.fp.get_data('P{}'.format(command[-1]))) else: logger.error('Command ' + command + ' not recognized') response = 'command not recognized' except (win32com.client.pythoncom.com_error, Exception) as e: logger.error(traceback.format_exc()) logger.error(e) response = 'error executing command, see server log' addr = sock.getpeername() try: logger.info(str(addr) + ': Sending: ' + response) sock.send(response.encode()) except Exception as e: logger.error(str(addr) + ': Error sending response:') logger.error(str(e)) finally: logger.info(str(addr) + ': Closing connection') sock.shutdown(socket.SHUT_RDWR) sock.close() class SocketThread(threading.Thread): """ Accepts connections and puts commands into the queue. """ def __init__(self, name, work_queue, lock): threading.Thread.__init__(self, name=name) self.work_queue = work_queue self.lock = lock def run(self): global running logger.info('Starting socket thread') start_time = datetime.datetime.now() recv_buffer = 4096 addr = '0.0.0.0' port = 5611 connections = [] server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((addr, port)) server_socket.listen(5) logger.info('Listening at ' + str((addr, port))) connections.append(server_socket) while running: read_socks, write_socks, error_socks = select.select(connections, [], [], 60) for sock in read_socks: if sock == server_socket: # Accept a new incoming connection new_socket, addr = server_socket.accept() connections.append(new_socket) logger.info(str(addr) + ': Accepted connection request') else: try: # Recieve a command and append it to the work queue data = sock.recv(recv_buffer).decode().rstrip().lower() if data: addr = sock.getpeername() logger.info(str(addr) + ': Recieved: ' + data) if data == 'stop': running = False elif data == 'server_status': uptime = str(datetime.datetime.now() - start_time) response = 'Uptime: {}, connections: {}'.format( uptime, len(connections) - 1) sock.send(response.encode()) sock.shutdown(socket.SHUT_RDWR) else: with self.lock: self.work_queue.put((sock, data)) connections.remove(sock) except Exception as e: logger.info(str(e)) sock.close() connections.remove(sock) logger.info('Closing server socket and exiting thread') server_socket.close() if __name__ == '__main__': lock = threading.Lock() work_queue = queue.Queue(100) queue_thread = QueueThread('queue_thread', work_queue, lock) queue_thread.start() socket_thread = SocketThread('socket_thread', work_queue, lock) socket_thread.start() queue_thread.join() socket_thread.join() <file_sep>from instrument import Instrument import types import socket import errno class Leiden_fridge(Instrument): def __init__(self, name, address, port): Instrument.__init__(self, name) self._socket = None self._address = address self._port = port self._ensure_connection = EnsureConnection(self) self._channels = range(10) self._pressures = range(1, 8) self._currents = range(3) self.add_parameter('pressure', flags=Instrument.FLAG_GET, type=types.FloatType, channels=self._pressures, units='') self.add_parameter('current', flags=Instrument.FLAG_GET, type=types.FloatType, channels=self._currents, units='A') self.add_parameter('resistance', flags=Instrument.FLAG_GET, type=types.FloatType, channels=self._channels, units='Ohm') self.add_parameter('temperature', flags=Instrument.FLAG_GET, type=types.FloatType, channels=self._channels, units='K') self.reset() def _connect(self): if self._socket is not None: self._disconnect() try: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._address, self._port)) except socket.error as serr: print(serr) self._socket.close() self._socket = None def _disconnect(self): if self._socket is None: return self._socket.shutdown(socket.SHUT_RDWR) self._socket.close() self._socket = None def _send(self, data): self._socket.send(data) def _recv(self, buffer_size=1400): return self._socket.recv(buffer_size) def ask(self, cmd): with self._ensure_connection: self._send(cmd) return self._recv() def reset(self): pass def do_get_pressure(self, channel): return self.ask('pressure{}'.format(channel)) def do_get_current(self, channel): return self.ask('temperature{}'.format(channel)) def do_get_resistance(self, channel): return self.ask('temperature{}'.format(channel)) def do_get_temperature(self, channel): return self.ask('temperature{}'.format(channel)) def get_server_status(self): return self.ask('server_status') def get_all(): pass class EnsureConnection: def __init__(self, instrument): self.instrument = instrument def __enter__(self): """Make sure we connect when entering the context.""" if self.instrument._socket is None: self.instrument._connect() def __exit__(self, type, value, tb): """Possibly disconnect on exiting the context.""" self.instrument._disconnect() <file_sep>import LCApp # Connect to Temp Control and Front Panel applications # For compiled executables: TC = LCApp.LVApp("DRTempControl.Application","DR TempControl.exe\TC.vi") FP = LCApp.LVApp("DRFrontPanel.Application","DR FrontPanel.exe\FP.vi") # For VI's: #TC = LCApp.LVApp("LabView.Application","E:\Dropbox\Labview\LC Software\TempControl\TC.vi") #Substitute with correct path to VI's #FP = LCApp.LVApp("LabView.Application","E:\Dropbox\Labview\LC Software\Front Panel\FP.vi") # List of currents for automatic mode IList = ((0.0, 0.0, 10000.0, 7), (0.0, 0.0, 10000.0, 8.0), (0.0, 0.0, 10000.0, 9.0), (0.0, 0.0, 10000.0, 10.0), (0.0, 0.0, 10000.0, 11.0), (0.0, 0.0, 10000.0, 12.0), (0.0, 0.0, 10000.0, 14.0), (0.0, 0.0, 10000.0, 16.0), (0.0, 0.0, 10000.0, 18.0), (0.0, 0.0, 10000.0, 20.0), (0.0, 0.0, 10000.0, 25.0), (0.0, 0.0, 10000.0, 30.0), (0.0, 0.0, 10000.0, 35.0), (0.0, 0.0, 10000.0, 40.0), (0.0, 0.0, 10000.0, 50.0), (0.0, 0.0, 12000.0, 60.0), (0.0, 0.0, 12000.0, 70.0), (0.0, 0.0, 12000.0, 80.0), (0.0, 0.0, 12000.0, 90.0), (0.0, 0.0, 12000.0, 100.0), (0.0, 0.0, 14000.0, 110.0), (0.0, 0.0, 14000.0, 120.0), (0.0, 0.0, 14000.0, 140.0), (0.0, 0.0, 14000.0, 160.0), (0.0, 0.0, 15000.0, 200.0), (0.0, 0.0, 15000.0, 250.0), (0.0, 0.0, 15000.0, 300.0), (0.0, 0.0, 15000.0, 350.0), (0.0, 0.0, 15000.0, 400.0), (0.0, 0.0, 15000.0, 500.0), (0.0, 0.0, 15000.0, 600.0), (0.0, 0.0, 15000.0, 700.0), (0.0, 0.0, 10000.0, 0.0)) # Reading data from VI's print TC.GetData("AVS names") print TC.GetData("R") print TC.GetData("T") print TC.GetData("I") print TC.GetData("I3") print FP.GetData("FP Data") print FP.GetData("MG Data") print FP.GetData("PT Data") print FP.GetData("LEDs") print FP.GetData("Flow") print FP.GetData("P5") # Writing data - see LVApp.SetData() comments for details TC.SetData("C_I3.I",100) # Set 100 uA on CS channel 3 TC.SetData("C_I3.Toggle ON/OFF",True) # Toggle CS channel 3 ON/OFF TC.SetData("I_list",IList) # Write array to automatic mode currents list FP.SetData("Button",58) # Toggle S4 pump ON/OFF # It is possible to get names of all controls in the program: # print TC.GetData('ControlNames') # print FP.GetData('ControlNames') <file_sep>import socket if __name__ == '__main__': host = '127.0.0.1' port = 5611 sock = socket.socket() sock.connect((host, port)) # message = 'stop' sock.send(message.encode()) data = sock.recv(1024).decode() #print('recieved ' + data) sock.send('STOP'.encode()) sock.close() <file_sep>from qcodes import IPInstrument class LeidenFridge(IPInstrument): """ Driver that talks to the Leiden fridge software via an intermediate server script. """ def __init__(self, name, address, port, timeout=20, **kwargs): super().__init__(name, address=address, port=port, timeout=timeout, persistent=False) for i in range(10): self.add_parameter(name='temperature{}'.format(i), get_cmd='temperature{}'.format(i), get_parser=float) for i in range(3): self.add_parameter(name='current{}'.format(i), get_cmd='current{}'.format(i), get_parser=float) for i in range(10): self.add_parameter(name='resistance{}'.format(i), get_cmd='resistance{}'.format(i), get_parser=float) self.add_parameter(name='server_status', get_cmd='server_status') self.connect_message() def connect_message(self): pass def get_idn(self): pass <file_sep>import win32com.client import time class LVApp: def __init__(self, AppName, ViName): self.App = win32com.client.Dispatch(AppName) self.Vi = self.App.GetViReference(ViName) # Reading data from VI's is straight forward def GetData(self, ControlName): return self.Vi.GetControlValue(ControlName) # Writing data to VI's is more complicated. # It is possible to write data by simply using SetControlValue(<Name>), but that does not trigger ValueChanged event # in LabView program. Since a lot of things are happening inside the event structure, it breaks TC and FP programs. # Instead there is a special cluster called "SetControl". It has three fields: "Name", "Scalar" and "Array". # To write data to any control put it's name in "Name" field and value in either "Scalar" or "Array" field depending on # data type. Do not write data in both "Scalar" and "Array" fields as the LabView program will ignore the command. Put # empty string '' or empty list [[], []] in the unused field. # It is possible to write data to individual controls in clusters by <ClusterName>.<ControlName> notation. It will # trigger the ValueChanged event for that control and not the cluster. # After the program reads the "SetControl" structure it will empty it to flag that it's been processed. Checking if # the cluster is empty allows synchronous operation def SetData(self, ControlName, ControlData, Async = False): if type(ControlData) in (tuple, list): self.Vi.SetControlValue('SetControl', (ControlName, '', ControlData)) else: self.Vi.SetControlValue('SetControl', (ControlName, ControlData, [[], []])) if not Async: while self.Vi.GetControlValue('SetControl')[0] != '': time.sleep(0.1)
b07bb8dee505cc4cc730c0491d7f24c5589604e3
[ "Python" ]
6
Python
Rubenknex/fridge_server
a8e8707664e6483f4521e92c0d37e1f6dd3f1d91
97888fcb16d6a7d00e5e265fec577cda571cb60f
refs/heads/master
<repo_name>smile2snail/Parking-Game<file_sep>/script.js $(document).ready(function(){ var index=1; $(".car").click(function(){ if(index%6==1){ $(this).animate({top:"350px"},600) } else if(index%6==2){ $(this).animate({top:"262.5px"},600) } else if(index%6==3){ $(this).animate({top:"175px"},600) } else if(index%6==4){ $(this).animate({top:"87.5px"},600) } else if(index%6==5){ $(this).animate({top:"0px"},600) } else{ $(this).animate({top:"-60px"},600) alert("You Reach the Dead End!") } index++; }); $(".Park").click(function(){ if(index%6==5){ alert("Congratulations! You park your car successfully!"); $(".car").animate({left:"0px"},600); index=2; $(".car").animate({top:"350px",left:"350px"},600) } else{ alert("You Crash into another car!") index=2; $(".car").animate({top:"350px",left:"350px"},600) } }); })
d042422f1567de9867d515e299acbd77286e6c32
[ "JavaScript" ]
1
JavaScript
smile2snail/Parking-Game
2b3bb45c2ccf1ef4cc70bd11306fc71ddea04118
e00f76c5fd07ed5980ec7f9ef086be0953c2bcc7
refs/heads/master
<repo_name>luizgcancian/spring-annotations<file_sep>/src/com/luiz/springdemo/AnnotationTesting.java package com.luiz.springdemo; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationTesting { public static void main(String[] args) { // reading the spring config file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //get the bean from the spring container TennisCoach theCoach = (TennisCoach) context.getBean("tennisCoach",Coach.class); // Using method of the bean System.out.println(theCoach.getYourSalary()); //Closing the app context.close(); } } <file_sep>/src/com/luiz/springdemo/HighSalary.java package com.luiz.springdemo; import org.springframework.stereotype.Component; @Component public class HighSalary implements Salary { @Override public String getSalary() { return "you have a good salary"; } } <file_sep>/src/com/luiz/springdemo/TennisCoach.java package com.luiz.springdemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class TennisCoach implements Coach { /* // Field Injection// @Autowired @Qualifier("lowSalary") */ private Salary salary; @Value("${foo.team}") private String team; public String getTeam() { return team; } @Autowired public TennisCoach(@Qualifier("lowSalary")Salary salary) { this.salary = salary; } // Setter Injection // /* @Autowired public void setSalary(Salary salary) { this.salary = salary; } */ @Override public String getDailyWorkout() { return "doing tennis stuff"; } @Override public String getYourSalary() { return salary.getSalary(); } } <file_sep>/src/sport.properties foo.team = Sao Paulo Futebol Clube
0dc03f957cc91b8b6140b7813ce60f1aca1cd56f
[ "Java", "INI" ]
4
Java
luizgcancian/spring-annotations
f65af04a2aaa8ff8f5cb41b0271c9260fa0accb8
f69cf4612c967638e77dbf06099c592183ac3c65
refs/heads/master
<repo_name>09747670/Apico_-Intensive<file_sep>/main.js function createElement(tagName, style, data) { let element = document.createElement(tagName); if (style !== undefined) { element = React.createStyle(element, style); } if (Array.isArray(data)) { data.map((el) => element.append(el)); } else if (data !== undefined) { element.textContent = data; } return element; } const createStyle = (element, style) => { for (const [name, st] of Object.entries(style)) { if (typeof st === 'object' && st !== null) { for (const [k, v] of Object.entries(st)) { element[name][k] = v; } } else { element[name] = st; } } return element; }; function render (value, element) { element.append(value); }; const React = { createElement, createStyle, render, }; const app = React.createElement( 'div', { style: { backgroundColor: 'red' } }, [ React.createElement('span', undefined, 'Hello world'), React.createElement('br'), 'This is just a text node', React.createElement('div', { textContent: 'Text content' }), ], ); console.log(app); React.render(app, document.getElementById('app'));
abc04d148b1f46f792d6ea5204b15c770215e2ca
[ "JavaScript" ]
1
JavaScript
09747670/Apico_-Intensive
42604e8a9e05867e39ea3f58562459d1b08964aa
fd1a3e2c2292a0acdca71baae6c8bcf56d1b913c
refs/heads/master
<file_sep>package com.zhaoia; /* * mail to <EMAIL> to ask for appkey secretcode * * zhaoia development guide document : http://www.zhaoia.com/apidoc/zhaoia_api_doc.pdf * * more detail in http://www.zhaoia.com/api * * alse see http://www.zhaoia.com/test_api */ public class Const { // mail to <EMAIL> to ask for appkey secretcode // static final public String AppKey = ""; static final public String SecretCode = ""; // // static final public String SearchURL = "http://192.168.1.101:3000/service/get_product_lists/"; static final public int NFID = 0xff; static final public String Site = "http://www.zhaoia.com"; static public int WIDTH = 0; static public int HEIGHT = 0; } <file_sep>package com.zhaoia; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; public class Anim { static public Animation trans( int w, long t, double f, long offset ){ Animation anim = new TranslateAnimation((float)w, 0, 0, 0); anim.setDuration(t); anim.setInterpolator( new DecelerateInterpolator((float)f) ); anim.setFillAfter(true); anim.setStartOffset(offset); return anim; } static public Animation alpha(double from, long t, double f, long offset){ Animation anim = new AlphaAnimation((float)from,1.0f); anim.setDuration(t); anim.setInterpolator( new AccelerateInterpolator((float)f) ); anim.setFillAfter(true); anim.setStartOffset(offset); return anim; } }
a8a741033ab0d2b933f58387d2848a4d6ab83bb1
[ "Java" ]
2
Java
zhaoia/AndroidZhao
2c18a556d5ff42c16f302600aed48093c593a876
3d06696d5ea2db6e4e8235554ca4937b115d767f
refs/heads/master
<repo_name>eduardoalbuquerque/estudo-spring<file_sep>/src/main/java/br/com/solucitiva/projetoestudospring/domain/service/CidadeService.java package br.com.solucitiva.projetoestudospring.domain.service; import java.util.List; import org.springframework.stereotype.Service; import br.com.solucitiva.projetoestudospring.domain.model.Cidade; import br.com.solucitiva.projetoestudospring.domain.repository.CidadeRepository; @Service public class CidadeService { private CidadeRepository cidadeRepository; public CidadeService(CidadeRepository cidadeRepository) { this.cidadeRepository = cidadeRepository; } public List<Cidade> listar(){ return cidadeRepository.listar(); } }
d1f3d7368b4a0f292009fb670bd36ea3378769ac
[ "Java" ]
1
Java
eduardoalbuquerque/estudo-spring
2323d4a7e834efae14ec73e639c7345d1d5edf59
b2e98f43b7dddfc87a84aaac11038be5eb66e956
refs/heads/master
<repo_name>SysSynBio/al3c<file_sep>/macs/macs_darwin_x86-64.so.cpp #include<unistd.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <limits.h> #include <sstream> #include "../include/al3c.hpp" struct param_t { float MigrationRate_AfrToEur, MigrationRate_AfrToAsn, MigrationRate_EurToAsn, EffectivePopulationSize_Afr, GrowthRate_Eur, GrowthRate_Asn, PastEvent_AfrToEurProportion; }; struct param_summary_t { float MigrationRate_AfrToEur_Variance, MigrationRate_AfrToAsn_Variance, MigrationRate_EurToAsn_Variance, EffectivePopulationSize_Afr_Variance, GrowthRate_Eur_Variance, GrowthRate_Asn_Variance, PastEvent_AfrToEurProportion_Variance; }; void user_t::prior() { param->MigrationRate_AfrToEur=u01()*0.4+0.84; // Unif[0.84,1.24] param->MigrationRate_AfrToAsn=u01()*0.32+0.16; // Unif[0.16,0.48] param->MigrationRate_EurToAsn=u01()*0.84+0.72; // Unif[0.72,1.56] param->EffectivePopulationSize_Afr=u01()*0.2994+1.319; // Unif[1.319, 1.6184] param->GrowthRate_Eur=u01()*0.31+0.28; // Unif[0.28, 0.59] param->GrowthRate_Asn=u01()*0.45+0.30; // Unif[0.30, 0.75] param->PastEvent_AfrToEurProportion=u01()*2.8+4.8; // Unif[4.8,7.6] }; float user_t::prior_density() { if (0.84<=param->MigrationRate_AfrToEur && param->MigrationRate_AfrToEur<=1.24 && 0.16<=param->MigrationRate_AfrToAsn && param->MigrationRate_AfrToAsn<=0.48 && 0.72<=param->MigrationRate_EurToAsn && param->MigrationRate_EurToAsn<=1.56 && 1.319<=param->EffectivePopulationSize_Afr && param->EffectivePopulationSize_Afr<=1.6184 && 0.28<=param->GrowthRate_Eur && param->GrowthRate_Eur<=0.59 && 0.3<=param->GrowthRate_Asn && param->GrowthRate_Asn<=0.75 && 4.8<=param->PastEvent_AfrToEurProportion && param->PastEvent_AfrToEurProportion<=7.6) return 1; else return 0; return 1; } void user_t::perturb() { param->MigrationRate_AfrToEur+=(u01()-0.5f)*sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12); param->MigrationRate_AfrToAsn+=(u01()-0.5f)*sqrt(2*param_summary->MigrationRate_AfrToAsn_Variance*12); param->MigrationRate_EurToAsn+=(u01()-0.5f)*sqrt(2*param_summary->MigrationRate_EurToAsn_Variance*12); param->EffectivePopulationSize_Afr+=(u01()-0.5f)*sqrt(2*param_summary->EffectivePopulationSize_Afr_Variance*12); param->GrowthRate_Eur+=(u01()-0.5f)*sqrt(2*param_summary->GrowthRate_Eur_Variance*12); param->GrowthRate_Asn+=(u01()-0.5f)*sqrt(2*param_summary->GrowthRate_Asn_Variance*12); param->PastEvent_AfrToEurProportion+=(u01()-0.5f)*sqrt(2*param_summary->PastEvent_AfrToEurProportion_Variance*12); } float user_t::perturb_density(param_t *old_param) { /* if ( fabs(param->MigrationRate_AfrToEur - old_param->MigrationRate_AfrToEur) > sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12)/2.f ) return 0.f; if ( fabs(param->MigrationRate_AfrToAsn - old_param->MigrationRate_AfrToAsn) > sqrt(2*param_summary->MigrationRate_AfrToAsn_Variance*12)/2.f ) return 0.f; if ( fabs(param->MigrationRate_EurToAsn - old_param->MigrationRate_AfrToEur) > sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12)/2.f ) return 0.f; if ( fabs(param->EffectivePopulationSize_Afr - old_param->MigrationRate_AfrToEur) > sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12)/2.f ) return 0.f; if ( fabs(param->GrowthRate_Eur - old_param->MigrationRate_AfrToEur) > sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12)/2.f ) return 0.f; if ( fabs(param->GrowthRate_Asn - old_param->MigrationRate_AfrToEur) > sqrt(2*param_summary->MigrationRate_AfrToEur_Variance*12)/2.f ) return 0.f; if ( fabs(param->PastEvent_AfrToEurProportion - old_param->PastEvent_AfrToEurProportion) > sqrt(2*param_summary->PastEvent_AfrToEurProportion_Variance*12)/2.f ) return 0.f; */ return 1.f; } void user_t::simulate() { //const int MAX_PATH_LEN=10000; //char cwd[MAX_PATH_LEN]; //getcwd(cwd,MAX_PATH_LEN); ostringstream cmd; uint seed=u01()*UINT_MAX; // run this command: // It is assumed that MaCS is in the search path // ./macs <parameters> | allele_spectrum | cut -f3- | sed 1d cmd<<"macs/macs_darwin_x86-64 718 100000 -s "<<seed<<" -t .001 -I 3 176 170 372 0 -m 2 1 "<<param->MigrationRate_AfrToEur<<" -m 3 1 "<<param->MigrationRate_AfrToAsn<<" -m 3 2 "<<param->MigrationRate_EurToAsn<<" -n 1 "<<param->EffectivePopulationSize_Afr<<" -g 2 "<<param->GrowthRate_Eur<<" -g 3 "<<param->GrowthRate_Asn<<" -eg .0230000 2 0 -eg .0230001 3 0 -ej .0230002 3 2 -em .0230003 2 1 "<<param->PastEvent_AfrToEurProportion<<" -en .0230004 2 0.1861 -ej .051 2 1 -en .148 1 0.731 -r 0.0006 2>/dev/null | macs/allele_spectrum_darwin_x86-64 | cut -f3- | sed 1d"; exec_cmd(cmd.str().c_str()); } float user_t::distance() { float r=0; for (uint n=0;n<N;n++) for (uint d=0;d<D;d++) r+=pow(S[n][d]-O[n][d],2); return sqrt(r); } void user_summary_t::summarize(){ float m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->MigrationRate_AfrToEur; m2+=params[a]->MigrationRate_AfrToEur*params[a]->MigrationRate_AfrToEur; } m1/=(float)A; m2/=(float)A; summary->MigrationRate_AfrToEur_Variance=m2-m1*m1; m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->MigrationRate_AfrToAsn; m2+=params[a]->MigrationRate_AfrToAsn*params[a]->MigrationRate_AfrToAsn; } m1/=(float)A; m2/=(float)A; summary->MigrationRate_AfrToAsn_Variance=m2-m1*m1; m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->MigrationRate_EurToAsn; m2+=params[a]->MigrationRate_EurToAsn*params[a]->MigrationRate_EurToAsn; } m1/=(float)A; m2/=(float)A; summary->MigrationRate_EurToAsn_Variance=m2-m1*m1; m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->EffectivePopulationSize_Afr; m2+=params[a]->EffectivePopulationSize_Afr*params[a]->EffectivePopulationSize_Afr; } m1/=(float)A; m2/=(float)A; summary->EffectivePopulationSize_Afr_Variance=m2-m1*m1; m1=0, m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->GrowthRate_Eur; m2+=params[a]->GrowthRate_Eur*params[a]->GrowthRate_Eur; } m1/=(float)A; m2/=(float)A; summary->GrowthRate_Eur_Variance=m2-m1*m1; m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->GrowthRate_Asn; m2+=params[a]->GrowthRate_Asn*params[a]->GrowthRate_Asn; } m1/=(float)A; m2/=(float)A; summary->GrowthRate_Asn_Variance=m2-m1*m1; m1=0,m2=0; for (uint a=0;a<A;a++) { m1+=params[a]->PastEvent_AfrToEurProportion; m2+=params[a]->PastEvent_AfrToEurProportion*params[a]->PastEvent_AfrToEurProportion; } m1/=(float)A; m2/=(float)A; summary->PastEvent_AfrToEurProportion_Variance=m2-m1*m1; } void user_t::print(ofstream& output, bool header) { if (header) { output<<"#distance weight MigrationRate_AfrToEur MigrationRate_AfrToAsn MigrationRate_EurToAsn EffectivePopulationSize_Afr GrowthRate_Eur GrowthRate_Asn PastEvent_AfrToEurProportion\n"; return; } output<<"d="<<(*d)<<"\tw="<<(*w) <<"\t"<<param->MigrationRate_AfrToEur <<"\t"<<param->MigrationRate_AfrToAsn <<"\t"<<param->MigrationRate_EurToAsn <<"\t"<<param->EffectivePopulationSize_Afr <<"\t"<<param->GrowthRate_Eur <<"\t"<<param->GrowthRate_Asn <<"\t"<<param->PastEvent_AfrToEurProportion<<"\n"; for (uint n=0;n<N;n++) { output<<"#"; for (uint d=0;d<D;d++) output<<"\t"<<S[n][d]; output<<"\n"; } } <file_sep>/src/signal.cpp #include <signal.h> void signal_callback_handler(int signum) { SIGNUM=signum; if (np==0) cerr<<"Received signal '"<<SIGNUM<<"', stand by while we finish this generation..."<<endl; } <file_sep>/src/u01.cpp #define SFMT_MEXP 19937 #include "SFMT/SFMT.h" #include "SFMT/SFMT.c" #define SFMT_MEXP 19937 #define RANDOM_SEED 1 //be careful: without this, you may run on repeat after a while! #define RND_BUFFER 16777216 #define SKEW_SEEDS 256 #define LEFT_OPEN 1 // U(0,1] #define RIGHT_OPEN 2 // U[0,1) #define BOTH_OPEN 3 // U(0,1) uint64_t u01n; uint32_t *rnd_array=NULL; sfmt_t sfmt; uint32_t *skew_seed(bool random) { uint32_t *seed=new uint32_t[SKEW_SEEDS]; time_t tick; uint j=0; for (uint i=0;i<SKEW_SEEDS;i++) { if (random) { tick=clock(); for(j=0;(uint)clock()==tick;j++) ; } seed[i]= j%256;// only use lower 8 bits.. } return seed; } float u01(char c) { float f; repeat: u01n++; if (u01n%RND_BUFFER==1) { if (rnd_array==NULL) { if (np==0) { cerr<<"+------------------------------------------------------------------------------+\n"; cerr<<"| Invoking SIMD-oriented Fast Mersenne Twister (SFMT) |\n"; cerr<<"| Copyright 2006,2007 <NAME>, <NAME> and Hiroshima University |\n"; cerr<<"| Copyright 2012 <NAME>, <NAME>, Hiroshima University and |\n"; cerr<<"| The University of Tokyo. All rights reserved. |\n"; cerr<<"+------------------------------------------------------------------------------+"<<endl; } rnd_array=new uint32_t[RND_BUFFER]; uint32_t *seeds=skew_seed(RANDOM_SEED); sfmt_init_by_array(&sfmt, seeds, SKEW_SEEDS); delete [] seeds; } sfmt_fill_array32(&sfmt, rnd_array, RND_BUFFER); u01n=1; } f=rnd_array[u01n-1]/(float)UINT32_MAX; switch (c) { case LEFT_OPEN: if (f==0) goto repeat; else return f; case RIGHT_OPEN: if (f==1) goto repeat; else return f; case BOTH_OPEN: if (f==0 || f==1) goto repeat; else return f; default: return f; } } float u01() { //this is a function overload... will give in [0,1] interval. return u01(0); } <file_sep>/Makefile include make.inc UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Darwin) MPIFLAGS += -stdlib=libstdc++ -lstdc++ endif all: bin/al3c static_darwin: bin/al3c_darwin_x86-64 static_linux: bin/al3c_linux_x86-64 bin/al3c: src/main.cpp src/SMC.cpp src/signal.cpp src/u01.cpp src/weight.cpp include/al3c.hpp make.inc $(MPI) $(MPIFLAGS) $(MPIINCLUDEFLAGS) -o bin/al3c $(MPILIBFLAGS) $< ##make sure MPI .dylibs are removed for this to compile statically... bin/al3c_darwin_x86-64: src/main.cpp src/SMC.cpp src/signal.cpp src/u01.cpp src/weight.cpp include/al3c.hpp make.inc $(MPI) $(MPIFLAGS) $(MPIINCLUDEFLAGS) -o bin/al3c_darwin_x86-64 $(MPILIBFLAGS) $< bin/al3c_linux_x86-64: src/main.cpp src/SMC.cpp src/signal.cpp src/u01.cpp src/weight.cpp include/al3c.hpp make.inc mpiicpc -Wall -O2 -static_mpi -o bin/al3c_linux_x86-64 -ldl $< clean: -rm bin/al3c bin/al3c_linux_x86-64
eac37dfec0523d139927563519bc76c9b5492d82
[ "Makefile", "C++" ]
4
C++
SysSynBio/al3c
cd9ade263e0b9eb61bedf65981de1d5669afc234
a20ea3915441d092d5e09a501f7dabe6e85ccf86
refs/heads/master
<repo_name>MrityunjayBhardwaj/16-Bit_Processor_in_Python<file_sep>/Processor/processor_16bit.py from math import floor from math import ceil # Creating the gates from Scratch: # the focus is both in the Interface level and implementation level # Transistors: def num2loc(n): return [floor(n/(4096)),floor(n/512),floor(n/64),floor(n/8),(n%8) ] pass def num2locN(n,k): # n = number in decimal # r = number of ram parts # k = ram size loc = [] w = k/8 while w >= 8: loc.append(floor(n/(w))) w = w/8 loc.append(n%8) return loc def bin2dec(bin): val =0; for i in range(len(bin)): val += bin[(len(bin)-1)-i]*(2**i); return val MasterClock = 1 class Transistor: """ Transistors are the basic building block of any electrical appliances that we see today... you can learn more about transistors here:- https://en.wikipedia.org/wiki/Transistor and video explaination: https://www.youtube.com/watch?v=VBDoT8o4q00 as you can see transistors consist of 3 pins 2 input pins and 1 output pins. so input : POWER supply (Source) GATE (main on and off Switch) Out: Output (Drain) which gives us 0 and 1 according to our inputs. """ # transistor id: transistor_id = -1 def __init__(self,Switch,Power=1): # Bydefault source is always set to 1 i.e, power suppply is always on! #00 = 0 10 = 0 01= 0 11 = 1 self.switch = Switch self.power = Power self.output_value = self.power*self.switch Transistor.transistor_id += 1 def output(self): # TT : 00 = 0 01 = 0 10 = 0 11 = 1 return self.output_value def __repr__(self): return ('{self.__class__.__name__}'); class NAND(): """ Truth_Table 00 = 1 01 = 1 10 = 1 11 = 0 """ nand_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): # Creating 2 transisors: self.tr_s0_0 = Transistor(Switch_0,Power) self.tr_s1_1 = Transistor(Switch_1,self.tr_s0_0.output()) self.output_value = (1-self.tr_s1_1.output())*Power NAND.nand_id += 1 def output(self): # because the source of tr_1 is (__connected-to__ ) the output of tr_0. return self.output_value class NOT: """ Truth_Table 0 = 1 1 = 0 """ not_gt_id= -1 def __init__(self,Switch,Power=1): self.NAND_s_s_0 = NAND(Switch,Switch,Power) self.output_value = self.NAND_s_s_0.output() def output(self): return self.output_value class AND(): """ Truth_Table 00 = 0 01 = 0 10 = 0 11 = 1 """ and_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): self.NAND_s0_s1_0 = NAND(Switch_0,Switch_1,Power) self.NOT_0_1 = NOT(self.NAND_s0_s1_0.output(),Power) self.output_value = self.NOT_0_1.output() AND.and_id += 1 def output(self): # because the source of tr_1 is (__connected-to__ ) the output of tr_0. return self.output_value class OR(): """ Truth_Table 00 = 0 01 = 1 10 = 1 11 = 1 """ or_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): # Creating 2 transisors: self.NOT_s0_0 = NOT(Switch_0,Power) self.NOT_s1_1 = NOT(Switch_1,Power) self.NAND_0_1_2 = NAND(self.NOT_s0_0.output(),self.NOT_s1_1.output(),Power) self.output_value = self.NAND_0_1_2.output() OR.or_id += 1 def output(self): return self.output_value class NOR(): """ Truth_Table 00 = 1 01 = 0 10 = 0 11 = 0 """ nor_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): # Creating 2 transisors: self.NOT_s0_0 = NOT (Switch_0,Power) self.NOT_s1_1 = NOT (Switch_1,Power) self.NAND_0_1_2 = NAND(self.NOT_s0_0.output(),self.NOT_s1_1.output(),Power) self.NOT_2_3 = NOT(self.NAND_0_1_2.output(),Power) self.output_value = self.NOT_2_3.output() NOR.nor_id += 1 def output(self): return self.output_value class XOR(): """ Truth_Table 00 = 0 01 = 1 10 = 1 11 = 0 """ xor_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): # Creating 2 transisors: self.NAND_s0_s1_0 = NAND(Switch_0,Switch_1,Power) self.NAND_s0_0_1 = NAND(Switch_0,self.NAND_s0_s1_0.output(),Power) self.NAND_0_s1_2 = NAND(self.NAND_s0_s1_0.output(),Switch_1,Power) self.NAND_2_1_3 = NAND(self.NAND_0_s1_2.output(),self.NAND_s0_0_1.output(),Power) self.output_value = self.NAND_2_1_3.output() XOR.xor_id += 1 def output(self): return self.output_value class XNOR(): """ Truth_Table 00 = 1 01 = 0 10 = 0 11 = 1 """ xnor_id = -1 def __init__(self,Switch_0,Switch_1,Power=1): # Creating 2 transisors: self.NAND_s0_s1_0 = NAND(Switch_0,Switch_1,Power) self.NAND_s0_0_1 = NAND(Switch_0,self.NAND_s0_s1_0.output(),Power) self.NAND_0_s1_2 = NAND(self.NAND_s0_s1_0.output(),Switch_1,Power) self.NAND_2_1_3 = NAND(self.NAND_0_s1_2.output(),self.NAND_s0_0_1.output(),Power) self.NOR_3_4 = NOT(self.NAND_2_1_3.output(),Power) self.output_value = self.NOR_3_4.output() XNOR.xnor_id += 1 def output(self): return self.output_value class MUX(): """ Take 2 inputs and one switch, which decide which input should be taken as output Truth_Table Input Selection_bit Output A | B 0 0 0 0 0 1 0 0 1 0 0 1 1 1 0 1 0 0 1 0 0 1 1 1 1 0 1 0 1 1 1 1 """ mux_id = -1 def __init__(self,Input_0,Input_1,Selection_bit,Power=1): self.NOT_sb_0 = NOT(Selection_bit,Power) self.AND_sb_i1_1 = AND(Selection_bit,Input_1,Power) self.AND_sb_i0_2 = AND(self.NOT_sb_0.output(),Input_0,Power) self.OR_1_2_3 = OR(self.AND_sb_i1_1.output(),self.AND_sb_i0_2.output()) self.output_value = self.OR_1_2_3.output() MUX.mux_id += 1 def output(self): return self.output_value class DMUX(): """ DMUX is the complement of MUX i.e, it takes 1 input and 1 switch which decide to which output this input should go Truth_Table S out 0 = input_0 1 = input_1 """ dmux_id = -1 def __init__(self,Input,Selection_bit,Power=1): # Creating 2 transisors: self.NOT_sb_0 = NOT(Selection_bit,Power) self.AND_sb_i_1 = AND(Selection_bit,Input,Power) self.AND_0_i_2 = AND(self.NOT_sb_0.output(),Input,Power) self.output_value = [self.AND_0_i_2.output(),self.AND_sb_i_1.output()] DMUX.dmux_id += 1 def output(self): return self.output_value # 16 Bit Variants: class Mux16(): """ this mux takes 16bit data as input and give 16bit as well it has 1 switcher for indepth MUX: http://www.zeepedia.com/read.php%3F2-input_4-bit_multiplexer_8_16-input_multiplexer_logic_function_generator_digital_logic_design%26b%3D9%26c%3D18 """ mux16_id = -1 def __init__(self,Input_a,Input_b,Selection_bit,Power=1): # Using the basic multiplexer layout for all the bits #self.NOT_0 = NOT(Selection_bit,Power) #self.NAND_1 = NAND(Input_0,Selection_bit,Power) #self.NAND_2 = NAND(self.NOT_0.output(),Input_1,Power) #self.NAND_3 = NAND(self.NAND_1.output(),self.NAND_2.output(),Power) # Using AND OR gates self.output_value = [] Selection_bit = 1- Selection_bit self.AND_P_S_0 = AND(Power,Selection_bit) self.NOT_S_1 = NOT(Selection_bit) self.AND_1_P_2 = AND(self.NOT_S_1.output(),Power) self.AND_0_Ia0_3 = AND(self.AND_P_S_0.output(),Input_a[0]) self.AND_2_Ib0_4 = AND(self.AND_1_P_2.output(),Input_b[0]) self.OR_3_4_5 = OR(self.AND_0_Ia0_3.output(),self.AND_2_Ib0_4.output()) self.output_value.append(self.OR_3_4_5.output()) self.AND_0_Ia1_6 = AND(self.AND_P_S_0.output(),Input_a[1]) self.AND_2_Ib1_7 = AND(self.AND_1_P_2.output(),Input_b[1]) self.OR_6_7_8 = OR(self.AND_0_Ia1_6.output(),self.AND_2_Ib1_7 .output()) self.output_value.append(self.OR_6_7_8.output()) self.AND_0_Ia2_9 = AND(self.AND_P_S_0.output(),Input_a[2]) self.AND_2_Ib2_10 = AND(self.AND_1_P_2.output(),Input_b[2]) self.OR_9_10_11 = OR(self.AND_0_Ia2_9.output(),self.AND_2_Ib2_10 .output()) self.output_value.append(self.OR_9_10_11.output()) self.AND_0_Ia3_12 = AND(self.AND_P_S_0.output(),Input_a[3]) self.AND_2_Ib3_13 = AND(self.AND_1_P_2.output(),Input_b[3]) self.OR_12_13_14 = OR(self.AND_0_Ia3_12.output(),self.AND_2_Ib3_13 .output()) self.output_value.append(self.OR_12_13_14.output()) self.AND_0_Ia4_15 = AND(self.AND_P_S_0.output(),Input_a[4]) self.AND_2_Ib4_16 = AND(self.AND_1_P_2.output(),Input_b[4]) self.OR_15_16_17 = OR(self.AND_0_Ia4_15.output(),self.AND_2_Ib4_16 .output()) self.output_value.append(self.OR_15_16_17.output()) self.AND_0_Ia5_18 = AND(self.AND_P_S_0.output(),Input_a[5]) self.AND_2_Ib5_19 = AND(self.AND_1_P_2.output(),Input_b[5]) self.OR_18_19_20 = OR(self.AND_0_Ia5_18.output(),self.AND_2_Ib5_19 .output()) self.output_value.append(self.OR_18_19_20.output()) self.AND_0_Ia6_21 = AND(self.AND_P_S_0.output(),Input_a[6]) self.AND_2_Ib6_22 = AND(self.AND_1_P_2.output(),Input_b[6]) self.OR_21_22_23 = OR(self.AND_0_Ia6_21.output(),self.AND_2_Ib6_22 .output()) self.output_value.append(self.OR_21_22_23.output()) self.AND_0_Ia7_24 = AND(self.AND_P_S_0.output(),Input_a[7]) self.AND_2_Ib7_25 = AND(self.AND_1_P_2.output(),Input_b[7]) self.OR_24_25_26 = OR(self.AND_0_Ia7_24.output(),self.AND_2_Ib7_25 .output()) self.output_value.append(self.OR_24_25_26.output()) self.AND_0_Ia8_27 = AND(self.AND_P_S_0.output(),Input_a[8]) self.AND_2_Ib8_28 = AND(self.AND_1_P_2.output(),Input_b[8]) self.OR_27_28_29 = OR(self.AND_0_Ia8_27.output(),self.AND_2_Ib8_28 .output()) self.output_value.append(self.OR_27_28_29.output()) self.AND_0_Ia9_30 = AND(self.AND_P_S_0.output(),Input_a[9]) self.AND_2_Ib9_31 = AND(self.AND_1_P_2.output(),Input_b[9]) self.OR_30_31_32 = OR(self.AND_0_Ia9_30.output(),self.AND_2_Ib9_31 .output()) self.output_value.append(self.OR_30_31_32.output()) self.AND_0_Ia10_33 = AND(self.AND_P_S_0.output(),Input_a[10]) self.AND_2_Ib10_34 = AND(self.AND_1_P_2.output(),Input_b[10]) self.OR_33_34_35 = OR(self.AND_0_Ia10_33.output(),self.AND_2_Ib10_34 .output()) self.output_value.append(self.OR_33_34_35.output()) self.AND_0_Ia11_36 = AND(self.AND_P_S_0.output(),Input_a[11]) self.AND_2_Ib11_37 = AND(self.AND_1_P_2.output(),Input_b[11]) self.OR_36_37_38 = OR(self.AND_0_Ia11_36.output(),self.AND_2_Ib11_37 .output()) self.output_value.append(self.OR_36_37_38.output()) self.AND_0_Ia12_39 = AND(self.AND_P_S_0.output(),Input_a[12]) self.AND_2_Ib12_40 = AND(self.AND_1_P_2.output(),Input_b[12]) self.OR_39_40_41 = OR(self.AND_0_Ia12_39.output(),self.AND_2_Ib12_40 .output()) self.output_value.append(self.OR_39_40_41.output()) self.AND_0_Ia13_42 = AND(self.AND_P_S_0.output(),Input_a[13]) self.AND_2_Ib13_43 = AND(self.AND_1_P_2.output(),Input_b[13]) self.OR_42_43_44 = OR(self.AND_0_Ia13_42.output(),self.AND_2_Ib13_43 .output()) self.output_value.append(self.OR_42_43_44.output()) self.AND_0_Ia14_45 = AND(self.AND_P_S_0.output(),Input_a[14]) self.AND_2_Ib14_46 = AND(self.AND_1_P_2.output(),Input_b[14]) self.OR_45_46_47 = OR(self.AND_0_Ia14_45.output(),self.AND_2_Ib14_46 .output()) self.output_value.append(self.OR_45_46_47.output()) self.AND_0_Ia15_48 = AND(self.AND_P_S_0.output(),Input_a[15]) self.AND_2_Ib15_49 = AND(self.AND_1_P_2.output(),Input_b[15]) self.OR_48_49_50 = OR(self.AND_0_Ia15_48.output(),self.AND_2_Ib15_49 .output()) self.output_value.append(self.OR_48_49_50.output()) Mux16.mux16_id += 1 # print("this is inp:",Input_b) def output(self): # print("this is self.output_value:",self.output_value) return self.output_value class And16(): """ Truth_Table 00 = 0 01 = 0 10 = 0 11 = 1 """ and16_id = -1 def __init__(self,input_a,input_b,Power=1): self.output_value = [] self.AND_0 = AND(input_a[0],input_b[0],Power) self.output_value.append(self.AND_0.output()) self.AND_1 = AND(input_a[1],input_b[1],Power) self.output_value.append(self.AND_1.output()) self.AND_2 = AND(input_a[2],input_b[2],Power) self.output_value.append(self.AND_2.output()) self.AND_3 = AND(input_a[3],input_b[3],Power) self.output_value.append(self.AND_3.output()) self.AND_4 = AND(input_a[4],input_b[4],Power) self.output_value.append(self.AND_4.output()) self.AND_5 = AND(input_a[5],input_b[5],Power) self.output_value.append(self.AND_5.output()) self.AND_6 = AND(input_a[6],input_b[6],Power) self.output_value.append(self.AND_6.output()) self.AND_7 = AND(input_a[7],input_b[7],Power) self.output_value.append(self.AND_7.output()) self.AND_8 = AND(input_a[8],input_b[8],Power) self.output_value.append(self.AND_8.output()) self.AND_9 = AND(input_a[9],input_b[9],Power) self.output_value.append(self.AND_9.output()) self.AND_10 = AND(input_a[10],input_b[10],Power) self.output_value.append(self.AND_10.output()) self.AND_11 = AND(input_a[11],input_b[11],Power) self.output_value.append(self.AND_11.output()) self.AND_12 = AND(input_a[12],input_b[12],Power) self.output_value.append(self.AND_12.output()) self.AND_13 = AND(input_a[13],input_b[13],Power) self.output_value.append(self.AND_13.output()) self.AND_14 = AND(input_a[14],input_b[14],Power) self.output_value.append(self.AND_14.output()) self.AND_15 = AND(input_a[15],input_b[15],Power) self.output_value.append(self.AND_15.output()) self.and16_id += 1 def output(self): # because the source of tr_1 is (__connected-to__) the output of tr_0. return self.output_value class Or16: def __init__(self,input_a,input_b,Power): self.output_value = [] self.OR_0 = OR(input_a[0],input_b[0],Power) self.output_value.append(self.OR_0.output()) self.OR_1 = OR(input_a[1],input_b[1],Power) self.output_value.append(self.OR_1.output()) self.OR_2 = OR(input_a[2],input_b[2],Power) self.output_value.append(self.OR_2.output()) self.OR_3 = OR(input_a[3],input_b[3],Power) self.output_value.append(self.OR_3.output()) self.OR_4 = OR(input_a[4],input_b[4],Power) self.output_value.append(self.OR_4.output()) self.OR_5 = OR(input_a[5],input_b[5],Power) self.output_value.append(self.OR_5.output()) self.OR_6 = OR(input_a[6],input_b[6],Power) self.output_value.append(self.OR_6.output()) self.OR_7 = OR(input_a[7],input_b[7],Power) self.output_value.append(self.OR_7.output()) self.OR_8 = OR(input_a[8],input_b[8],Power) self.output_value.append(self.OR_8.output()) self.OR_9 = OR(input_a[9],input_b[9],Power) self.output_value.append(self.OR_9.output()) self.OR_10 = OR(input_a[10],input_b[10],Power) self.output_value.append(self.OR_10.output()) self.OR_11 = OR(input_a[11],input_b[11],Power) self.output_value.append(self.OR_11.output()) self.OR_12 = OR(input_a[12],input_b[12],Power) self.output_value.append(self.OR_12.output()) self.OR_13 = OR(input_a[13],input_b[13],Power) self.output_value.append(self.OR_13.output()) self.OR_14 = OR(input_a[14],input_b[14],Power) self.output_value.append(self.OR_14.output()) self.OR_15 = OR(input_a[15],input_b[15],Power) self.output_value.append(self.OR_15.output()) def output(self): return self.output_value class Not16: def __init__(self,Input,Power=1): self.output_value = [] self.NOT_0 = NOT(Input[0],Power) self.output_value.append(self.NOT_0.output()) self.NOT_1 = NOT(Input[1],Power) self.output_value.append(self.NOT_1.output()) self.NOT_2 = NOT(Input[2],Power) self.output_value.append(self.NOT_2.output()) self.NOT_3 = NOT(Input[3],Power) self.output_value.append(self.NOT_3.output()) self.NOT_4 = NOT(Input[4],Power) self.output_value.append(self.NOT_4.output()) self.NOT_5 = NOT(Input[5],Power) self.output_value.append(self.NOT_5.output()) self.NOT_6 = NOT(Input[6],Power) self.output_value.append(self.NOT_6.output()) self.NOT_7 = NOT(Input[7],Power) self.output_value.append(self.NOT_7.output()) self.NOT_8 = NOT(Input[8],Power) self.output_value.append(self.NOT_8.output()) self.NOT_9 = NOT(Input[9],Power) self.output_value.append(self.NOT_9.output()) self.NOT_10 = NOT(Input[10],Power) self.output_value.append(self.NOT_10.output()) self.NOT_11 = NOT(Input[11],Power) self.output_value.append(self.NOT_11.output()) self.NOT_12 = NOT(Input[12],Power) self.output_value.append(self.NOT_12.output()) self.NOT_13 = NOT(Input[13],Power) self.output_value.append(self.NOT_13.output()) self.NOT_14 = NOT(Input[14],Power) self.output_value.append(self.NOT_14.output()) self.NOT_15 = NOT(Input[15],Power) self.output_value.append(self.NOT_15.output()) def output(self): return self.output_value # Creating multi-way version of digital Logic Gates class Or8Way: """ in: in[8] out: out if any input bit is 1 then it return 1 otherwise 0 """ or8way_id = -1 def __init__(self,Input,Power=1): self.output_value = 0 self.OR_I0_I1_0 = OR(Input[0],Input[1],Power) self.OR_I2_I3_1 = OR(Input[2],Input[3],Power) self.OR_I4_I5_2 = OR(Input[4],Input[5],Power) self.OR_I6_I7_3 = OR(Input[6],Input[7],Power) self.OR_0_1_4 = OR(self.OR_I0_I1_0.output(),self.OR_I2_I3_1.output()) self.OR_2_3_5 = OR(self.OR_I4_I5_2.output(),self.OR_I6_I7_3.output()) self.OR_4_5_6 = OR(self.OR_0_1_4.output(),self.OR_2_3_5.output()) self.output_value = self.OR_4_5_6.output() Or8Way.or8way_id +=1 def output(self): return self.output_value class Mux4Way16: """ in: a[16],b[16],c[16],d[16] Selection_bit = s[2] out: out[16] func: Select one output out of 4 inputs using selection bit TT: s[1] s[0] out 0 0 a 0 1 b 1 0 c 1 1 d """ mux4way16_id = -1 def __init__(self,input_a,input_b,input_c,input_d,S,Power=1): self.MUX_Ia_Ib_S0_0 = Mux16(input_a,input_b,S[1],Power) self.MUX_Ic_Id_S0_1 = Mux16(input_c,input_d,S[1],Power) self.MUX_0_1_S1_2 = Mux16(self.MUX_Ia_Ib_S0_0.output(),self.MUX_Ic_Id_S0_1.output(),S[0],Power) self.output_value = self.MUX_0_1_S1_2.output() Mux4Way16.mux4way16_id +=1 def output(self): return self.output_value class Mux8Way16: """ in: a[16],b[16],c[16],d[16],e[16],f[16],g[16],h[16] Selection_bits = s[3] out: out[16] func: Select one output,out of 8 inputs using selection bit TT: s[2] s[1] s[0] out 0 0 0 a 0 0 1 b 0 1 0 c 0 1 1 d 1 0 0 e 1 0 1 f 1 1 0 g 1 1 1 h """ mux8way16_id = -1 def __init__(self,input_a,input_b,input_c,input_d,input_e,input_f,input_g,input_h,S,Power=1): self.MUX4way_Ia_Ib_Ic_Id_S01_0 = Mux4Way16(input_a,input_b,input_c,input_d,[S[1],S[2]],Power) self.MUX4way_Ie_If_Ig_Ih_S01_1 = Mux4Way16(input_e,input_f,input_g,input_h,[S[1],S[2]],Power) # print("\nfrom mux8: ",self.MUX4way_Ia_Ib_Ic_Id_S01_0.output(),self.MUX4way_Ie_If_Ig_Ih_S01_1.output()) self.MUX_0_1_2 = Mux16(self.MUX4way_Ia_Ib_Ic_Id_S01_0.output(),self.MUX4way_Ie_If_Ig_Ih_S01_1.output(),S[0],Power) self.output_value = self.MUX_0_1_2.output() Mux8Way16.mux8way16_id +=1 def output(self): return self.output_value class Dmux4Way: """ in: inp Selection_bits = s[2] out: a,b,c,d func: It channels one 1-bit input into 8 1-bit output using Selection bits """ dmux4way_id = -1 def __init__(self,Input,S,Power=1): self.DMUX_I_S0_0 = DMUX(Input,S[1],Power) # print("DMUX: ",self.DMUX_I_S0_0.output()) self.NOT_S_2 = NOT(S[1],Power) # Always return 0 self.MUX_00_01_3 = MUX(self.DMUX_I_S0_0.output()[0],self.DMUX_I_S0_0.output()[1],self.NOT_S_2.output()) self.MUX_00_3_S1_4 = MUX(self.DMUX_I_S0_0.output()[0],self.MUX_00_01_3.output(),S[0],Power) self.MUX_01_3_S1_5 = MUX(self.DMUX_I_S0_0.output()[1],self.MUX_00_01_3.output(),S[0],Power) self.MUX_3_00_S1_6 = MUX(self.MUX_00_01_3.output(),self.DMUX_I_S0_0.output()[0],S[0],Power) self.MUX_3_01_S1_7 = MUX(self.MUX_00_01_3.output(),self.DMUX_I_S0_0.output()[1],S[0],Power) self.output_value = [self.MUX_00_3_S1_4.output(),self.MUX_01_3_S1_5.output(),self.MUX_3_00_S1_6.output(),self.MUX_3_01_S1_7.output()] Dmux4Way.dmux4way_id +=1 def output(self): return self.output_value class DMux8Way: """ in: inp Selection_bits = [3] out:a,b,c,d,e,f,g,h func: It channels one 1-bit input into 8 1-bit output using Selection bits """ dmux8way_id = -1 def __init__(self,Input,S,Power=1): self.Dmux4Way_I_S01_0 = Dmux4Way(Input,[S[1],S[2]],Power) self.dummyBit_1 = 0 # creating 4 bits of empty data [0,0,0,0] self.Dmux4Way_I_S01_2 = Dmux4Way(self.dummyBit_1,[S[1],S[2]],Power) # first 4 bits(a,b,c,d) selection using s[2] self.MUX_00_20_S2_3 = MUX(self.Dmux4Way_I_S01_0.output()[0],self.Dmux4Way_I_S01_2.output()[0],S[0],Power) self.MUX_01_21_S2_4 = MUX(self.Dmux4Way_I_S01_0.output()[1],self.Dmux4Way_I_S01_2.output()[1],S[0],Power) self.MUX_02_22_S2_5 = MUX(self.Dmux4Way_I_S01_0.output()[2],self.Dmux4Way_I_S01_2.output()[2],S[0],Power) self.MUX_03_23_S2_6 = MUX(self.Dmux4Way_I_S01_0.output()[3],self.Dmux4Way_I_S01_2.output()[3],S[0],Power) # last 4 bits (e,f,g,h) self.MUX_20_00_S2_7 = MUX(self.Dmux4Way_I_S01_2.output()[0],self.Dmux4Way_I_S01_0.output()[0],S[0],Power) self.MUX_21_01_S2_8 = MUX(self.Dmux4Way_I_S01_2.output()[1],self.Dmux4Way_I_S01_0.output()[1],S[0],Power) self.MUX_22_02_S2_9 = MUX(self.Dmux4Way_I_S01_2.output()[2],self.Dmux4Way_I_S01_0.output()[2],S[0],Power) self.MUX_23_03_S2_10 = MUX(self.Dmux4Way_I_S01_2.output()[3],self.Dmux4Way_I_S01_0.output()[3],S[0],Power) #output = [a,b,c,d,e,f,g,h] self.output_value = [self.MUX_00_20_S2_3.output(),self.MUX_01_21_S2_4.output(),self.MUX_02_22_S2_5.output(),self.MUX_03_23_S2_6.output(),self.MUX_20_00_S2_7.output(),self.MUX_21_01_S2_8.output(),self.MUX_22_02_S2_9.output(),self.MUX_23_03_S2_10.output()] # id DMux8Way.dmux8way_id +=1 def output(self): return self.output_value # now creating ADDERS!!! # half-adder class HalfAdder: """ in: a,b out: [sum,carry] func: add a and b and store the carry bit TT: a b sum carry 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1 ComponentUsed: XOR and AND gate """ halfadder_id = -1 def __init__(self,input_a,input_b,Power=1): self.xor_ia_ib_0 = XOR(input_a,input_b,Power) self.and_ia_ib_1 = AND(input_a,input_b,Power) self.output_value = [self.xor_ia_ib_0.output(),self.and_ia_ib_1.output()] HalfAdder.halfadder_id +=1 def output(self): return self.output_value #full Adder class FullAdder: """ in: a,b,c(carry bit from previous place addition) out: [sum,carrybit] func: add a and b and also take the carry bit from prebious operation into account for calculation TT: a b c sum carry 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 1 1 0 0 1 0 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 1 0 1 1 0 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 """ fulladder_id = -1 def __init__(self,input_a,input_b,c,Power=1): self.halfadder_ia_ib_0 = HalfAdder(input_a,input_b,Power) self.halfadder_c_00_1 = HalfAdder(c,self.halfadder_ia_ib_0.output()[0],Power) self.or_11_01 = OR(self.halfadder_ia_ib_0.output()[1],self.halfadder_c_00_1.output()[1],Power) self.output_value = [self.halfadder_c_00_1.output()[0],self.or_11_01.output()] FullAdder.fulladder_id +=1 def output(self): return self.output_value class Adder16: """ """ adder16_id = -1 def __init__(self,input_a,input_b,Power): self.output_value = [] self.halfadder_ia15_ib15_0 = HalfAdder(input_a[15],input_b[15],Power) self.output_value.append(self.halfadder_ia15_ib15_0.output()[0]) # self.fulladder_ia14_ib14_01_1 = FullAdder(input_a[14],input_b[14],self.halfadder_ia15_ib15_0.output()[1],Power) # self.output_value.append(self.fulladder_ia1_ib1_01_1.output()[0]) self.fulladder_ia14_ib14_01_1 = FullAdder(input_a[14],input_b[14],self.halfadder_ia15_ib15_0.output()[1],Power) self.output_value.append(self.fulladder_ia14_ib14_01_1.output()[0]) self.fulladder_ia13_ib13_11_2 = FullAdder(input_a[13],input_b[13],self.fulladder_ia14_ib14_01_1.output()[1],Power) self.output_value.append(self.fulladder_ia13_ib13_11_2.output()[0]) self.fulladder_ia12_ib12_21_3 = FullAdder(input_a[12],input_b[12],self.fulladder_ia13_ib13_11_2.output()[1],Power) self.output_value.append(self.fulladder_ia12_ib12_21_3.output()[0]) self.fulladder_ia11_ib11_31_4 = FullAdder(input_a[11],input_b[11],self.fulladder_ia12_ib12_21_3.output()[1],Power) self.output_value.append(self.fulladder_ia11_ib11_31_4.output()[0]) self.fulladder_ia10_ib10_41_5 = FullAdder(input_a[10],input_b[10],self.fulladder_ia11_ib11_31_4.output()[1],Power) self.output_value.append(self.fulladder_ia10_ib10_41_5.output()[0]) self.fulladder_ia9_ib9_51_6 = FullAdder(input_a[9],input_b[9],self.fulladder_ia10_ib10_41_5.output()[1],Power) self.output_value.append(self.fulladder_ia9_ib9_51_6.output()[0]) self.fulladder_ia8_ib8_61_7 = FullAdder(input_a[8],input_b[8],self.fulladder_ia9_ib9_51_6.output()[1],Power) self.output_value.append(self.fulladder_ia8_ib8_61_7.output()[0]) self.fulladder_ia7_ib7_71_8 = FullAdder(input_a[7],input_b[7],self.fulladder_ia8_ib8_61_7.output()[1],Power) self.output_value.append(self.fulladder_ia7_ib7_71_8.output()[0]) self.fulladder_ia6_ib6_81_9 = FullAdder(input_a[6],input_b[6],self.fulladder_ia7_ib7_71_8.output()[1],Power) self.output_value.append(self.fulladder_ia6_ib6_81_9.output()[0]) self.fulladder_ia5_ib5_91_10 = FullAdder(input_a[5],input_b[5],self.fulladder_ia6_ib6_81_9.output()[1],Power) self.output_value.append(self.fulladder_ia5_ib5_91_10.output()[0]) self.fulladder_ia4_ib4_101_11 = FullAdder(input_a[4],input_b[4],self.fulladder_ia5_ib5_91_10.output()[1],Power) self.output_value.append(self.fulladder_ia4_ib4_101_11.output()[0]) self.fulladder_ia3_ib3_111_12 = FullAdder(input_a[3],input_b[3],self.fulladder_ia4_ib4_101_11.output()[1],Power) self.output_value.append(self.fulladder_ia3_ib3_111_12.output()[0]) self.fulladder_ia2_ib2_121_13 = FullAdder(input_a[2],input_b[2],self.fulladder_ia3_ib3_111_12.output()[1],Power) self.output_value.append(self.fulladder_ia2_ib2_121_13.output()[0]) self.fulladder_ia1_ib1_131_14 = FullAdder(input_a[1],input_b[1],self.fulladder_ia2_ib2_121_13.output()[1],Power) self.output_value.append(self.fulladder_ia1_ib1_131_14.output()[0]) self.fulladder_ia0_ib0_141_15 = FullAdder(input_a[0],input_b[0],self.fulladder_ia1_ib1_131_14.output()[1],Power) self.output_value.append(self.fulladder_ia0_ib0_141_15.output()[0]) # Reversing the order of the output i.e, make it Stack tmp0 = [self.output_value[(len(self.output_value)-1)-i] for i in range(len(self.output_value))] self.output_value = tmp0 def output(self): return self.output_value class Inc16: #increment the input value by one bit def __init__(self,Input,Power=1): inc_val_0 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] self.adder16_i_0_1 = Adder16(Input,inc_val_0,Power); self.output_value = self.adder16_i_0_1.output(); def output(self): return self.output_value class Neg16: """ in: x[16] out: out[16] func: Converting x into -x using this formula : 1 + (((2^n) -1)-x) basically we are finding the 2's complement version of the input x. which helps us to represent the negetive version of our input x """ neg_num16_id = -1 def __init__(self,Input,Power=1): # self.output_value = [] #Converting input into its complements using Not16 self.not16_I_0 = Not16(Input,Power) #Creating 1 in 16bit format self.tempvalue__1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] # now adding both the outputs to get our final value in 2's complement format self.adder16_0_1_2 = Adder16(self.not16_I_0.output(),self.tempvalue__1,Power) self.output_value = self.adder16_0_1_2.output() Neg16.neg_num16_id += 1 def output(self): return self.output_value # FInally Creating ARITHMATIC LOGICAL UNIT class ALU: """ in: x[16] y[16] zx // zero the x nx // negate the x zy // zero the y ny // negate the u f // 1 = add 0 = and no // negate the output out: out[16] zr // 1 iff out == 0 ng // 1 iff out < 0 func: if zx then x = 0 // 16-bit zero Constant if nx then x = !x // bit-wise negation if zy then y = 0 // 16-bit zero constant if ny then y = !y // bit-wise negation if f then out = x+y else out = x &y if no then out = !out //bit-wise negation if out=0 then zr=1 else zr=0 // 16-bit eq. comparison if out<0 then ng=1 else ng=0 // 16-bit neg. comparison """ alu_id = -1 # althought usually there is only one alu in a cpu but to follow the convension we are giving it an id def __init__(self,input_x,input_y,zx,nx,zy,ny,f,no,Power=1): # Creating a const zero self.constZero__0 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] #if zx then x = 0 // 16-bit zero Constant self.mux16_ix_0_zx_1 = Mux16(input_x,self.constZero__0,zx,Power) #if nx then x = !x // bit-wise negation # print("if zx: ",self.mux16_ix_0_zx_1.output()) #Creating !x self.not16_1_2 = Not16(self.mux16_ix_0_zx_1.output(),Power) self.mux16_1_2_nx_3 = Mux16(self.mux16_ix_0_zx_1.output(),self.not16_1_2.output(),nx,Power) # print("if nx: ",self.mux16_1_2_nx_3.output()) #if zy then y = 0 // 16-bit zero constant self.mux16_iy_0_zy_4 = Mux16(input_y,self.constZero__0,zy,Power) # print("if zy: ",self.mux16_iy_0_zy_4.output()) #if ny then y = !y // bit-wise negation self.not16_4_5 = Not16(self.mux16_iy_0_zy_4.output(),Power) self.mux16_4_5_ny_6 = Mux16(self.mux16_iy_0_zy_4.output(),self.not16_4_5.output(),ny,Power) # print("if ny: ",self.mux16_4_5_ny_6.output()) #if f then out = x+y #else out = x &y self.adder16_3_6_7 = Adder16(self.mux16_1_2_nx_3.output(),self.mux16_4_5_ny_6.output(),Power) # print("adder: ",self.adder16_3_6_7.output()) self.and16_3_6_8 = And16(self.mux16_1_2_nx_3.output(),self.mux16_4_5_ny_6.output(),Power) # print("and16 : ",self.and16_3_6_8.output()) self.mux16_7_8_f_9 = Mux16(self.and16_3_6_8.output(),self.adder16_3_6_7.output(),f,Power) # print("if f ",self.mux16_7_8_f_9.output()) #if no then out = !out //bit-wise negation self.not16_9_10 = Not16(self.mux16_7_8_f_9.output(),Power) self.mux16_9_10_no_11 = Mux16(self.mux16_7_8_f_9.output(),self.not16_9_10.output(),no,Power) self.out = self.mux16_9_10_no_11.output() # print("self.out",self.out); #if out=0 then zr=1 else zr=0 // 16-bit eq. comparison self.or8way_ixfrom0to7_12 = Or8Way([self.out[0],self.out[1],self.out[2],self.out[3],self.out[4],self.out[5],self.out[6],self.out[7]],Power) self.or8way_ixfrom8to15_13 = Or8Way([self.out[8],self.out[9],self.out[10],self.out[11],self.out[12],self.out[13],self.out[14],self.out[15]],Power) self.or_12_13_14 = OR(self.or8way_ixfrom0to7_12.output(),self.or8way_ixfrom8to15_13.output(),Power) # now this operation gives us 0 if out==1 otherwise 1 if out ==0 self.not_14_15 = NOT(self.or_12_13_14.output(),Power) self.zr = self.not_14_15.output() #if out<0 then ng=1 else ng=0 // 16-bit neg. comparison # take the most significant bit(i.e, index0 because we are going from right to left) of output and if that is 1 then its negetive(i.e,ng =1) otherwise its not i.e,ng = 0 self.ng = self.out[0] # now putting it all together as a final output of ALU in dictonary format. self.output_value = {"out":self.out,"zr":self.zr,"ng":self.ng} ALU.alu_id += 1 def output(self): return self.output_value class SRFF(): #THIS IS JUST THE TEMPORARY VERSION OF SRFF USING IF... I Will Create the final logic Later # tm1 == time minus one. i.e, previous time step def __init__(self,S,R,tm1_Q0=None,Power=1): #initializing self.tm1_Q0_1 = None self.tm1_Q1_2 = None # if we dont know t-1 input i.e, when we just starting our computer # just think about the scenerio what if both tm1_Q0 and tm1_Q1 were '0' if (tm1_Q0==None) : if(S==1): tm1_Q0 = 0; if(S==0): tm1_Q0 = 1; self.output_value = [0,0] else: # Always outputing the previously evaluated value. # and because its the first state of existence of this SRFF then just output tm1_Q0 and tm1_Q1 self.tm1_Q0_1 = tm1_Q0 self.tm1_Q1_2 = 1-tm1_Q0 # because Q1 will always be opposite of Q1 self.output_value = [self.tm1_Q0_1,self.tm1_Q1_2] self.eval_val = [self.tm1_Q0_1,self.tm1_Q1_2] #evaluated value from the current inputs and the eval_value is going to be the output_value for the next time step # if( S==0 and R==0 ):self.eval_val = [self.tm1_Q0_1,self.tm1_Q1_2]#then dont change the values if( S==0 and R==1 ):self.eval_val = [1,0] if( S==1 and R==0 ):self.eval_val = [0,1] # if( S==1 and R==1 ):self.eval_val = [None,None] #Now for the next time the output is going to be the currently evaluated value. self.tm1_Q0_1 = self.eval_val[0] self.tm1_Q1_2 = self.eval_val[1] def update(self,S,R,Power=1): #Call update whenever updating the time. # for the current time step the ouput is going to be the previously evaluated value self.output_value = [self.tm1_Q0_1,self.tm1_Q1_2] self.eval_val = [self.tm1_Q0_1,self.tm1_Q1_2] # if( S==0 and R==0 ): if( S==0 and R==1 ):self.eval_val = [1,0] if( S==1 and R==0 ):self.eval_val = [0,1] # if( S==1 and R==1 ):self.eval_val = [None,None] #Now for the next time the output is going to be the currently evaluated value. self.tm1_Q0_1 = self.eval_val[0] self.tm1_Q1_2 = self.eval_val[1] def output(self): return self.output_value class Clocked_DFF: """ Clocked D Flip Flop state[t] = function(state[t-1]) i.e, the output of current time unit is the evaluated value of the previous time unit """ def __init__(self,data,clock,Power=1): self.not_d_0 = NOT(data,Power) self.nand_d_c_1 = NAND(data,clock,Power) self.nand_c_1_2 = NAND(clock,self.not_d_0.output(),Power) #Now Using SR FlipFlop \\\\\\\\\\\\\\\\\\\\\\\\\\\\USING "SRFF" temporarly///////////////////////////////////// self.srff_1_2_3 = SRFF(self.nand_d_c_1.output(),self.nand_c_1_2.output(),tm1_Q0=None,Power=Power) self.output_value = self.srff_1_2_3.output() def update(self,data,clock,Power=1): self.not_d_0 = NOT(data,Power) self.nand_d_c_1 = NAND(data,clock,Power) self.nand_c_1_2 = NAND(clock,self.not_d_0.output(),Power) #Now Using SR FlipFlop.update to update the values according to the new inputs self.srff_1_2_3.update(self.nand_d_c_1.output(),self.nand_c_1_2.output(),Power) self.output_value = self.srff_1_2_3.output() def output(self): return self.output_value class Reg1Bit: """ if the load bit is on then the new input_1 is going to be inserted in DFF otherwise, Input_0 (i.e, output of t-1) is going to persist """ def __init__(self,Input_1,Load,Power=1): Input_0 = 0; # if we know the value of (t-1) then we can use that to calculate the current time output self.mux_i0_i1_l_0 = MUX(Input_0,Input_1,Load,Power) # print("self.mux_ ",self.mux_i0_i1_l_0.output()); self.dff_0_1 = Clocked_DFF(self.mux_i0_i1_l_0.output(),1,Power) self.register_state = self.dff_0_1.output()[0] # now for the next t-step this output is going to be the currently evaluated value #if i look at the output of the system it will show me the out of the previous time step self.output_value = self.register_state # for current t-step the out is going to be the output in t-1 t-step which is describe by Input_1 # print("self.output_value ",self.output_value) def update(self,Input,Load,Power=1): if (self.register_state == None): self.register_state = 0; # using the output of the previous time step as a second input for this time step self.mux_i0_i1_l_0 = MUX(self.register_state,Input,Load,Power) self.dff_0_1.update(self.mux_i0_i1_l_0.output(),Load,Power) # print("\n self.dff_0_1.update() ",self.dff_0_1.output()); # for current t-step the out is going to be the output in t-1 t-step which is describe by Input_1 self.register_state = self.dff_0_1.output()[0] # the ouput is only Q not Q` self.output_value = self.register_state def output(self): return self.output_value class Reg16: #16-bit Register # TODO: Change the name Reg1Bit_i1"x"_l_0 def __init__(self,Input,Load,Power=1): self.output_value = [] Input_0 = [0]*16; self.Reg1Bit_i0_l_0 = Reg1Bit(Input[0],Load,Power) self.output_value.append(self.Reg1Bit_i0_l_0.output()) self.Reg1Bit_i1_l_1 = Reg1Bit(Input[1],Load,Power) self.output_value.append(self.Reg1Bit_i1_l_1.output()) self.Reg1Bit_i2_l_2 = Reg1Bit(Input[2],Load,Power) self.output_value.append(self.Reg1Bit_i2_l_2.output()) self.Reg1Bit_i3_l_3 = Reg1Bit(Input[3],Load,Power) self.output_value.append(self.Reg1Bit_i3_l_3.output()) self.Reg1Bit_i4_l_4 = Reg1Bit(Input[4],Load,Power) self.output_value.append(self.Reg1Bit_i4_l_4.output()) self.Reg1Bit_i5_l_5 = Reg1Bit(Input[5],Load,Power) self.output_value.append(self.Reg1Bit_i5_l_5.output()) self.Reg1Bit_i6_l_6 = Reg1Bit(Input[6],Load,Power) self.output_value.append(self.Reg1Bit_i6_l_6.output()) self.Reg1Bit_i7_l_7 = Reg1Bit(Input[7],Load,Power) self.output_value.append(self.Reg1Bit_i7_l_7.output()) self.Reg1Bit_i8_l_8 = Reg1Bit(Input[8],Load,Power) self.output_value.append(self.Reg1Bit_i8_l_8.output()) self.Reg1Bit_i9_l_9 = Reg1Bit(Input[9],Load,Power) self.output_value.append(self.Reg1Bit_i9_l_9.output()) self.Reg1Bit_i10_l_10 = Reg1Bit(Input[10],Load,Power) self.output_value.append(self.Reg1Bit_i10_l_10.output()) self.Reg1Bit_i11_l_11 = Reg1Bit(Input[11],Load,Power) self.output_value.append(self.Reg1Bit_i11_l_11.output()) self.Reg1Bit_i12_l_12 = Reg1Bit(Input[12],Load,Power) self.output_value.append(self.Reg1Bit_i12_l_12.output()) self.Reg1Bit_i13_l_13 = Reg1Bit(Input[13],Load,Power) self.output_value.append(self.Reg1Bit_i13_l_13.output()) self.Reg1Bit_i14_l_14 = Reg1Bit(Input[14],Load,Power) self.output_value.append(self.Reg1Bit_i14_l_14.output()) self.Reg1Bit_i15_l_15 = Reg1Bit(Input[15],Load,Power) self.output_value.append(self.Reg1Bit_i15_l_15.output()) # print("Reg16: ",self.output_value); def update(self,Input,Load,Power): # Input because Input_0 is the output of t-1 so we are going to reference that # updating the individual Register and feeding the values inside output # Here ofcourse i am using the previously created Register object so dont match the arguments with the names. self.Reg1Bit_i0_l_0.update(Input[0],Load,Power) self.output_value[0] = self.Reg1Bit_i0_l_0.output() self.Reg1Bit_i1_l_1.update(Input[1],Load,Power) self.output_value[1] = self.Reg1Bit_i1_l_1.output() self.Reg1Bit_i2_l_2.update(Input[2],Load,Power) self.output_value[2] = self.Reg1Bit_i2_l_2.output() self.Reg1Bit_i3_l_3.update(Input[3],Load,Power) self.output_value[3] = self.Reg1Bit_i3_l_3.output() self.Reg1Bit_i4_l_4.update(Input[4],Load,Power) self.output_value[4] = self.Reg1Bit_i4_l_4.output() self.Reg1Bit_i5_l_5.update(Input[5],Load,Power) self.output_value[5] = self.Reg1Bit_i5_l_5.output() self.Reg1Bit_i6_l_6.update(Input[6],Load,Power) self.output_value[6] = self.Reg1Bit_i6_l_6.output() self.Reg1Bit_i7_l_7.update(Input[7],Load,Power) self.output_value[7] = self.Reg1Bit_i7_l_7.output() self.Reg1Bit_i8_l_8.update(Input[8],Load,Power) self.output_value[8] = self.Reg1Bit_i8_l_8.output() self.Reg1Bit_i9_l_9.update(Input[9],Load,Power) self.output_value[9] = self.Reg1Bit_i9_l_9.output() self.Reg1Bit_i10_l_10.update(Input[10],Load,Power) self.output_value[10] = self.Reg1Bit_i10_l_10.output() self.Reg1Bit_i11_l_11.update(Input[11],Load,Power) self.output_value[11] = self.Reg1Bit_i11_l_11.output() self.Reg1Bit_i12_l_12.update(Input[12],Load,Power) self.output_value[12] = self.Reg1Bit_i12_l_12.output() self.Reg1Bit_i13_l_13.update(Input[13],Load,Power) self.output_value[13] = self.Reg1Bit_i13_l_13.output() self.Reg1Bit_i14_l_14.update(Input[14],Load,Power) self.output_value[14] = self.Reg1Bit_i14_l_14.output() self.Reg1Bit_i15_l_15.update(Input[15],Load,Power) self.output_value[15] = self.Reg1Bit_i15_l_15.output() def output(self): return self.output_value # Counter class ProgramCounter: # Program Counter # in[16] : input_number,load_bit and increment # out[16] # Note: it will give the currently evaluated value in the next time step def __init__(self,Input,load,inc,reset,Power=1): #initializing with 0 bit self.zero16_0 = [0]*16 self.value_1 = self.zero16_0 #current counter value ###### #if load == 1 self.mux16_0_i_l_2 = Mux16(self.value_1,Input,load,Power).output()# choose value_0 or incremented value depending on add bit #if reset == 1 self.mux16_2_0_r_3 = Mux16(self.mux16_0_i_l_2,self.zero16_0,reset,Power).output() self.inc16_3_4 = Inc16(self.mux16_2_0_r_3,Power).output() self.mux16_3_4_5 = Mux16(self.mux16_2_0_r_3,self.inc16_3_4,inc,Power) self.eval_out = self.mux16_3_4_5.output() # output evaluate at current time step self.output_value = self.value_1 self.value_1 = self.eval_out def update(self,Input=None,load=0,inc=1,reset=0,Power=1): #if load == 1 self.mux16_0_i_l_2 = Mux16(self.value_1,Input,load,Power).output()# choose value_0 or incremented value depending on add bit #if reset == 1 self.mux16_2_0_r_3 = Mux16(self.mux16_0_i_l_2,self.zero16_0,reset,Power).output() self.inc16_3_4 = Inc16(self.mux16_2_0_r_3,Power).output() self.mux16_3_4_5 = Mux16(self.mux16_2_0_r_3,self.inc16_3_4,inc,Power) self.eval_out = self.mux16_3_4_5.output() # output evaluate at current time step self.output_value = self.value_1 self.value_1 = self.eval_out # self.output_value = self.eval_out # giving the output of previous operation # self.eval_out = self.inc16_3_4.output() # output evaluate at current time step def output(self): return self.output_value ## Next IS RAM!!! Bitches!!! :D class RAM8: """ Input = 16 bit address = 3 bit """ #AWESOME!!! def __init__(self,Input,address,load,Power=1): self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("RAM8-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.reg16_i_30_7 = Reg16(Input,self.dmux_10_a2_3[0],Power) self.reg16_i_31_8 = Reg16(Input,self.dmux_10_a2_3[1],Power) self.output_value.append(self.reg16_i_30_7.output()) self.output_value.append(self.reg16_i_31_8.output()) self.reg16_i_40_9 = Reg16(Input,self.dmux_11_a2_4[0],Power) self.reg16_i_41_10 = Reg16(Input,self.dmux_11_a2_4[1],Power) self.output_value.append(self.reg16_i_40_9.output()) self.output_value.append(self.reg16_i_41_10.output()) self.reg16_i_50_11 = Reg16(Input,self.dmux_20_a2_5[0],Power) self.reg16_i_51_12 = Reg16(Input,self.dmux_20_a2_5[1],Power) self.output_value.append(self.reg16_i_50_11.output()) self.output_value.append(self.reg16_i_51_12.output()) self.reg16_i_60_13 = Reg16(Input,self.dmux_21_a2_6[0],Power) self.reg16_i_61_14 = Reg16(Input,self.dmux_21_a2_6[1],Power) self.output_value.append(self.reg16_i_60_13.output()) self.output_value.append(self.reg16_i_61_14.output()) def update(self,Input,address,load,Power=1): self.output_value = [] # reinitializing the output_value self.final_load_path = []; self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration(i.e, which register is going to get the input) for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # feeding the final configuration of load bits to the registers self.reg16_i_30_7.update(Input,self.dmux_10_a2_3[0],Power) self.reg16_i_31_8.update(Input,self.dmux_10_a2_3[1],Power) self.output_value.append(self.reg16_i_30_7.output()) self.output_value.append(self.reg16_i_31_8.output()) self.reg16_i_40_9.update(Input,self.dmux_11_a2_4[0],Power) self.reg16_i_41_10.update(Input,self.dmux_11_a2_4[1],Power) self.output_value.append(self.reg16_i_40_9.output()) self.output_value.append(self.reg16_i_41_10.output()) self.reg16_i_50_11.update(Input,self.dmux_20_a2_5[0],Power) self.reg16_i_51_12.update(Input,self.dmux_20_a2_5[1],Power) self.output_value.append(self.reg16_i_50_11.output()) self.output_value.append(self.reg16_i_51_12.output()) self.reg16_i_60_13.update(Input,self.dmux_21_a2_6[0],Power) self.reg16_i_61_14.update(Input,self.dmux_21_a2_6[1],Power) self.output_value.append(self.reg16_i_60_13.output()) self.output_value.append(self.reg16_i_61_14.output()) def output(self): return self.output_value class RAM64: def __init__(self,Input,address,load,Power=1): # r64 consist of 8 RAM8 i.e, 3 more address bits self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("INIT: RAM64-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5]] self.ram8_i_7_30_8 = RAM8(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram8_i_7_30_8.output()) self.ram8_i_7_31_9 = RAM8(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram8_i_7_31_9.output()) self.ram8_i_7_40_10 = RAM8(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram8_i_7_40_10.output()) self.ram8_i_7_41_11 = RAM8(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram8_i_7_41_11.output()) self.ram8_i_7_50_12 = RAM8(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram8_i_7_50_12.output()) self.ram8_i_7_51_13 = RAM8(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram8_i_7_51_13.output()) self.ram8_i_7_60_14 = RAM8(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram8_i_7_60_14.output()) self.ram8_i_7_61_15 = RAM8(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram8_i_7_61_15.output()) def update(self,Input,address,load,Power=1): # r64 consist of 8 RAM8 i.e, 3 more address bits self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("\n UPDATE: RAM64-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5]] self.ram8_i_7_30_8.update(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram8_i_7_30_8.output()) self.ram8_i_7_31_9.update(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram8_i_7_31_9.output()) self.ram8_i_7_40_10.update(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram8_i_7_40_10.output()) self.ram8_i_7_41_11.update(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram8_i_7_41_11.output()) self.ram8_i_7_50_12.update(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram8_i_7_50_12.output()) self.ram8_i_7_51_13.update(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram8_i_7_51_13.output()) self.ram8_i_7_60_14.update(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram8_i_7_60_14.output()) self.ram8_i_7_61_15.update(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram8_i_7_61_15.output()) # print("output: ",self.output_value,"\n\n") def output(self): return self.output_value # also need to create ram512 ram4K and ram16K class RAM512: def __init__(self,Input,address,load,Power=1): # r512 consist of 8 RAM64 i.e, 3 more address bits so total of 9 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("INIT: RAM512-> final_load_path\n\n",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8]] self.ram64_i_7_30_8 = RAM64(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram64_i_7_30_8.output()) self.ram64_i_7_31_9 = RAM64(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram64_i_7_31_9.output()) self.ram64_i_7_40_10 = RAM64(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram64_i_7_40_10.output()) self.ram64_i_7_41_11 = RAM64(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram64_i_7_41_11.output()) self.ram64_i_7_50_12 = RAM64(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram64_i_7_50_12.output()) self.ram64_i_7_51_13 = RAM64(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram64_i_7_51_13.output()) self.ram64_i_7_60_14 = RAM64(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram64_i_7_60_14.output()) self.ram64_i_7_61_15 = RAM64(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram64_i_7_61_15.output()) # print("INIT: output: ",self.output_value) def update(self,Input,address,load,Power=1): # r512 consist of 8 RAM64 i.e, 3 more address bits so total of 9 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("UPDATE: RAM64-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8]] self.ram64_i_7_30_8.update(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram64_i_7_30_8.output()) self.ram64_i_7_31_9.update(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram64_i_7_31_9.output()) self.ram64_i_7_40_10.update(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram64_i_7_40_10.output()) self.ram64_i_7_41_11.update(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram64_i_7_41_11.output()) self.ram64_i_7_50_12.update(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram64_i_7_50_12.output()) self.ram64_i_7_51_13.update(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram64_i_7_51_13.output()) self.ram64_i_7_60_14.update(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram64_i_7_60_14.output()) self.ram64_i_7_61_15.update(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram64_i_7_61_15.output()) # print("UPDATE: RAM512 -> output: ",self.output_value[5][6]) def output(self): return self.output_value class RAM4K: def __init__(self,Input,address,load,Power=1): # r512 consist of 8 RAM512 i.e, 3 more address bits so total of 12 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("INIT: RAM4K-> final_load_path\n\n",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11]] self.ram512_i_7_30_8 = RAM512(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram512_i_7_30_8.output()) self.ram512_i_7_31_9 = RAM512(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram512_i_7_31_9.output()) self.ram512_i_7_40_10 = RAM512(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram512_i_7_40_10.output()) self.ram512_i_7_41_11 = RAM512(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram512_i_7_41_11.output()) self.ram512_i_7_50_12 = RAM512(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram512_i_7_50_12.output()) self.ram512_i_7_51_13 = RAM512(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram512_i_7_51_13.output()) self.ram512_i_7_60_14 = RAM512(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram512_i_7_60_14.output()) self.ram512_i_7_61_15 = RAM512(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram512_i_7_61_15.output()) # print("INIT: output: ",self.output_value) def update(self,Input,address,load,Power=1): # r512 consist of 8 RAM512 i.e, 3 more address bits so total of 12 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("UPDATE: RAM4K-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11]] self.ram512_i_7_30_8.update(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram512_i_7_30_8.output()) self.ram512_i_7_31_9.update(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram512_i_7_31_9.output()) self.ram512_i_7_40_10.update(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram512_i_7_40_10.output()) self.ram512_i_7_41_11.update(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram512_i_7_41_11.output()) self.ram512_i_7_50_12.update(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram512_i_7_50_12.output()) self.ram512_i_7_51_13.update(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram512_i_7_51_13.output()) self.ram512_i_7_60_14.update(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram512_i_7_60_14.output()) self.ram512_i_7_61_15.update(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram512_i_7_61_15.output()) # print("UPDATE: RAM512 -> output: ",self.output_value[5][6]) def output(self): return self.output_value class RAM16K: def __init__(self,Input,address,load,Power=1): # r16K consist of 4 RAM4K i.e, 2 more address bits so total of 14 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # print("INIT: RAM16K-> final_load_path\n\n",self.dmux_00_a1_1,self.dmux_01_a1_2) self.final_load_path.append(self.dmux_00_a1_1) self.final_load_path.append(self.dmux_01_a1_2) # print("INIT: RAM316K-> final_load_path\n\n",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[2],address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11],address[12],address[13]] # self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11],address[12],address[13],address[14]] self.ram4k_i_7_10_8 = RAM4K(Input,self.spliced_address_7,self.dmux_00_a1_1[0]) self.output_value.append(self.ram4k_i_7_10_8.output()) self.ram4k_i_7_11_9 = RAM4K(Input,self.spliced_address_7,self.dmux_00_a1_1[1]) self.output_value.append(self.ram4k_i_7_11_9.output()) self.ram4k_i_7_20_10 = RAM4K(Input,self.spliced_address_7,self.dmux_01_a1_2[0]) self.output_value.append(self.ram4k_i_7_20_10.output()) self.ram4k_i_7_21_11 = RAM4K(Input,self.spliced_address_7,self.dmux_01_a1_2[1]) self.output_value.append(self.ram4k_i_7_21_11.output()) def update(self,Input,address,load,Power=1): # r16K consist of 4 RAM4K i.e, 2 more address bits so total of 14 bits of address if (load): print("\nfromRAM loading value :",Input,"address: ",address,"\n"); self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # print("INIT: RAM16K-> final_load_path\n\n",self.dmux_00_a1_1,self.dmux_01_a1_2) self.spliced_address_7 = [address[2],address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11],address[12],address[13]] self.final_load_path.append(self.dmux_00_a1_1) self.final_load_path.append(self.dmux_01_a1_2) self.ram4k_i_7_10_8.update(Input,self.spliced_address_7,self.dmux_00_a1_1[0]) self.output_value.append(self.ram4k_i_7_10_8.output()) self.ram4k_i_7_11_9.update(Input,self.spliced_address_7,self.dmux_00_a1_1[1]) self.output_value.append(self.ram4k_i_7_11_9.output()) self.ram4k_i_7_20_10.update(Input,self.spliced_address_7,self.dmux_01_a1_2[0]) self.output_value.append(self.ram4k_i_7_20_10.output()) self.ram4k_i_7_21_11.update(Input,self.spliced_address_7,self.dmux_01_a1_2[1]) self.output_value.append(self.ram4k_i_7_21_11.output()) def output(self): return self.output_value class ROM32K: def __init__(self,Input,address,load,Power=1): # r32K consist of 8 RAM4K i.e, 3 more address bits so total of 15 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() # print("INIT: RAM32K-> final_load_path\n\n",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11],address[12],address[13],address[14]] self.ram4k_i_7_30_8 = RAM4K(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram4k_i_7_30_8.output()) self.ram4k_i_7_31_9 = RAM4K(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram4k_i_7_31_9.output()) self.ram4k_i_7_40_10 = RAM4K(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram4k_i_7_40_10.output()) self.ram4k_i_7_41_11 = RAM4K(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram4k_i_7_41_11.output()) self.ram4k_i_7_50_12 = RAM4K(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram4k_i_7_50_12.output()) self.ram4k_i_7_51_13 = RAM4K(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram4k_i_7_51_13.output()) self.ram4k_i_7_60_14 = RAM4K(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram4k_i_7_60_14.output()) self.ram4k_i_7_61_15 = RAM4K(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram4k_i_7_61_15.output()) # print("INIT: output: ",self.output_value) def update(self,Input,address,load,Power=1): # r32K consist of 8 RAM4K i.e, 3 more address bits so total of 15 bits of address self.final_load_path = [] self.output_value = [] self.dmux_l_a0_0 = DMUX(load,address[0],Power).output() self.dmux_00_a1_1 = DMUX(self.dmux_l_a0_0[0],address[1],Power).output() self.dmux_01_a1_2 = DMUX(self.dmux_l_a0_0[1],address[1],Power).output() self.final_load_path.append(self.dmux_00_a1_1) self.final_load_path.append(self.dmux_00_a1_2) # this section gives the final switch configuration for all 8 register files self.dmux_10_a2_3 = DMUX(self.dmux_00_a1_1[0],address[2],Power).output() self.final_load_path.append(self.dmux_10_a2_3) self.dmux_11_a2_4 = DMUX(self.dmux_00_a1_1[1],address[2],Power).output() self.final_load_path.append(self.dmux_11_a2_4) self.dmux_20_a2_5 = DMUX(self.dmux_01_a1_2[0],address[2],Power).output() self.final_load_path.append(self.dmux_20_a2_5) self.dmux_21_a2_6 = DMUX(self.dmux_01_a1_2[1],address[2],Power).output() self.final_load_path.append(self.dmux_21_a2_6) # print("UPDATE: RAM32K-> final_load_path",self.final_load_path) # feeding the final configuration of load bits to the registers self.spliced_address_7 = [address[3],address[4],address[5],address[6],address[7],address[8],address[9],address[10],address[11],address[12],address[13],address[14]] self.ram4k_i_7_30_8.update(Input,self.spliced_address_7,self.dmux_10_a2_3[0]) self.output_value.append(self.ram4k_i_7_30_8.output()) self.ram4k_i_7_31_9.update(Input,self.spliced_address_7,self.dmux_10_a2_3[1]) self.output_value.append(self.ram4k_i_7_31_9.output()) self.ram4k_i_7_40_10.update(Input,self.spliced_address_7,self.dmux_11_a2_4[0]) self.output_value.append(self.ram4k_i_7_40_10.output()) self.ram4k_i_7_41_11.update(Input,self.spliced_address_7,self.dmux_11_a2_4[1]) self.output_value.append(self.ram4k_i_7_41_11.output()) self.ram4k_i_7_50_12.update(Input,self.spliced_address_7,self.dmux_20_a2_5[0]) self.output_value.append(self.ram4k_i_7_50_12.output()) self.ram4k_i_7_51_13.update(Input,self.spliced_address_7,self.dmux_20_a2_5[1]) self.output_value.append(self.ram4k_i_7_51_13.output()) self.ram4k_i_7_60_14.update(Input,self.spliced_address_7,self.dmux_21_a2_6[0]) self.output_value.append(self.ram4k_i_7_60_14.output()) self.ram4k_i_7_61_15.update(Input,self.spliced_address_7,self.dmux_21_a2_6[1]) self.output_value.append(self.ram4k_i_7_61_15.output()) # print("UPDATE: RAM16K -> output: ",self.output_value[5][6]) def output(self): return self.output_value #TODO : think about what naming convention to follow when using class arguments as inputs #Fuckin Finall Creating CPU!!! # CENTRAL PROCESSING UNIT!!!!! class CPU: def __init__(self,Iin,Min,reset,Power=1): self.output_value = []; """ input: Min = Data from DataMemory (16) Iin = Instructions from InstructionMemory (16) reset (1) output: Data To Data Memory:- Mout (16) Mwrite (1) Maddress(15) Data To Instruction Memory:- pc (15) """ # Maybe add Decoder later ( using Data Buses.) # So the input is going to be an array array # FOR A INSTRUCTION # //////_________\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ self.ALUout_tm1_0 = [0]*16; # Although there is no output of alu tm1 beacuse this init is the first time there is. # think of it as a data bus Iin[1 to 15] self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; # FOR C INSTRUCTION self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output()] #Jump Bits # NOTE: Maybe We have to seperate all of the components "AND(x,y).output" into seprate variable... but first we need to concrete our Style Guide for this code. #Calculating Comp Bits (only Appy to C instructions) self.Ctrlbit[0] = Iin[0] # first opcode tells weather its a A instruction or C instruction. self.Ctrlbit[1] = AND(Iin[0],Iin[10]).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() self.Ctrlbit[1] = OR(NOT(Iin[0]).output(),self.Ctrlbit[1]).output() # if it is an A instruction then always set it to 1 else use the evaluated value of ctrlbit[1] self.mux16_1_0_c0_3 = Mux16(self.Input_1,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # NOTE: when we initialize any register its initial output will go None which is not good for the further circuit insertion so we have to find a better way to do it ..... maybe set the initial output of registerst to 0? # A_register self.Reg16_3_c1_5 = Reg16(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) print("A register: ",self.Reg16_3_c1_5.output()); # D_register self.Reg16_0_c2_6 = Reg16(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1) # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.output_value.append(outM) self.ALUout_tm1_0 = outM # the output of this ALU will used as input in t+1 timestep; #out : writeM writeM = self.Ctrlbit[5] self.output_value.append(writeM) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() """ self.Ctrlbit[5] = OR(\ OR(\ AND(\ AND(Iin[0],Iin[13]).output(),\ NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]).output()).output()\ ,\ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] \ )\ ).output()\ , \ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] )\ ).output() """ self.programcounter_5_r_c5_9 = ProgramCounter(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) # out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) def update(self,Iin,Min,reset,Power=1): #INITIALIZATION self.output_value = [] # for A instructions self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output(), ] #Jump Bits # if (Iin[0] == 0)1 else self.Ctrlbit[1] #Calculating Comp Bits self.Ctrlbit[0] = Iin[0] # first opcode tells weather its a A instruction or C instruction. self.Ctrlbit[1] = OR( (NOT(Iin[0]).output()) , (AND(Iin[0],Iin[10]).output()) ).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() #NOTE: self.Ctrlbit[6] required the output of ALU to calcuate the value, so we will do it later on, when we got the ALU output self.mux16_0_1_c0_3 = Mux16(Iin,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) print("-------------------inside CPU------------------") ####################################### # all the sequential logic Gates should be "Ticked" samultaniously :D # A-register self.Reg16_3_c1_5.update(self.mux16_0_1_c0_3.output(),self.Ctrlbit[1],Power=1) # D-register self.Reg16_0_c2_6.update(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1)#using the t-1 A-register. # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.ALUout_tm1_0 = outM; print("\nA_register:",self.Reg16_3_c1_5.output()); print("D_register:",self.Reg16_0_c2_6.output()); print("\n\n###########################################################") print("D_input:",self.Reg16_0_c2_6.output()); print("M/A_input:",self.mux16_5_m_c3_7.output()); print("ALU_out:",outM); print("zr: ",self.alu_6_7_c4_8.output()["zr"],"ng: ",self.alu_6_7_c4_8.output()["ng"]) print("###########################################################\n") print("-------------------outside CPU------------------") self.output_value.append(outM) #out : writeM self.output_value.append(self.Ctrlbit[5]) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() print("self.CTRLBIT[6]",self.Ctrlbit[6]) if (self.Ctrlbit[6] == 1): print("ksadjflksjdlkfjaslkdjfasdfskfjaskdjfklsjdflkjsdlkjfklasjlkfjlksdajflksjadlfjslkadjfklsdjfklasjkdfjskladjfklasjdkflaskdjflksjadkfjalskdjflkasjdlkfjsaldkfjlaksdjflksajdfkasjdlkfjaslkdjlfksajdlfkajsldkfjaslkfjlsjfskldjflskadfjlskdfjlksdjflsdkj") self.programcounter_5_r_c5_9.update(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) #out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) # print("\n self.mux16_0_1_c0_3: ",self.mux16_0_1_c0_3.output(),self.Ctrlbit[1]); # A_register TODO: always add the value inside A regester when we have A instruction. # self.Reg16_3_c1_5.update([0]*16,0,Power=1); # print("\n\nA register: ",self.Reg16_3_c1_5.output()) # # D_register # self.Reg16_0_c2_6.update([0]*16,0,Power=1) # print("D register: ",self.Reg16_0_c2_6.output(),"\n\n") def output(self): return self.output_value; # PUTTING IT ALL TOGETHER!!!! FINALLY CREATING A COMPUTER!!!!!! class CPU2: def __init__(self,Iin,Min,reset,Power=1): self.output_value = []; """ input: Min = Data from DataMemory (16) Iin = Instructions from InstructionMemory (16) reset (1) output: Data To Data Memory:- Mout (16) Mwrite (1) Maddress(15) Data To Instruction Memory:- pc (15) """ # Maybe add Decoder later ( using Data Buses.) # So the input is going to be an array array # FOR A INSTRUCTION # //////_________\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ self.ALUout_tm1_0 = [0]*16; # Although there is no output of alu tm1 beacuse this init is the first time there is. # think of it as a data bus Iin[1 to 15] self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; # FOR C INSTRUCTION self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output()] #Jump Bits # NOTE: Maybe We have to seperate all of the components "AND(x,y).output" into seprate variable... but first we need to concrete our Style Guide for this code. #Calculating Comp Bits (only Appy to C instructions) self.Ctrlbit[0] = AND(Iin[0],Iin[10]).output() # first opcode tells weather its a A instruction or C instruction. self.Ctrlbit[1] = AND(Iin[0],Iin[10]).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() self.Ctrlbit[1] = OR(NOT(Iin[0]).output(),self.Ctrlbit[1]).output() # if it is an A instruction then always set it to 1 else use the evaluated value of ctrlbit[1] self.mux16_1_0_c0_3 = Mux16(self.Input_1,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # A_register self.Reg16_3_c1_5 = Reg16(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) print("A register: ",self.Reg16_3_c1_5.output()); # D_register self.Reg16_0_c2_6 = Reg16(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) # M/A register self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1) # self.mux16_5_m_c3_7 = Mux16([0]*16,Min,self.Ctrlbit[3],Power=1) print("M/Aout: ",self.mux16_5_m_c3_7.output()) # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.output_value.append(outM) self.ALUout_tm1_0 = outM # the output of this ALU will used as input in t+1 timestep; #out : writeM writeM = self.Ctrlbit[5] self.output_value.append(writeM) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() """ self.Ctrlbit[5] = OR(\ OR(\ AND(\ AND(Iin[0],Iin[13]).output(),\ NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]).output()).output()\ ,\ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] \ )\ ).output()\ , \ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] )\ ).output() """ self.programcounter_5_r_c5_9 = ProgramCounter(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) # updating the programcounter in the init because as we know the output of the program counter will take effect @ t+1 but we are ignoring the first time step of initializing and going straight to t=1 # self.programcounter_5_r_c5_9.update() # out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) def update(self,Iin,Min,reset,Power=1): #INITIALIZATION self.output_value = [] print("cpu_inI: ",Iin,Iin[0],"cpu_inM: ",Min); # for A instructions self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output(), ] #Jump Bits # if (Iin[0] == 0)1 else self.Ctrlbit[1] #Calculating Comp Bits self.Ctrlbit[0] = AND(Iin[0],Iin[10]).output() self.Ctrlbit[1] = OR( (NOT(Iin[0]).output()) , (AND(Iin[0],Iin[10]).output()) ).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] for A-register load bit self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() # for D-register load bit self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction for M/A Mux self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() #NOTE: self.Ctrlbit[6] required the output of ALU to calcuate the value, so we will do it later on, when we got the ALU output self.Ctrlbit[1] = OR(NOT(Iin[0]).output(),self.Ctrlbit[1]).output() # if it is an A instruction then always set it to 1 else use the evaluated value of ctrlbit[1] self.mux16_1_0_c0_3 = Mux16(self.Input_1,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # # A_register # self.Reg16_3_c1_5.update(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) # M/A register self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1) self.mux16_0_1_c0_3 = Mux16(Iin,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # A_register self.Reg16_3_c1_5.update(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) print("-------------------inside CPU------------------") ####################################### # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.ALUout_tm1_0 = outM; # D_register self.Reg16_0_c2_6.update(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) print("\nA_register:",self.Reg16_3_c1_5.output()); print("D_register:",self.Reg16_0_c2_6.output()); print("\n\n###########################################################") print("D_input:",self.Reg16_0_c2_6.output()); print("M/A_input:",self.mux16_5_m_c3_7.output()); print("ALU input: ",self.Ctrlbit[4],"ALU_out:",outM); print("zr: ",self.alu_6_7_c4_8.output()["zr"],"ng: ",self.alu_6_7_c4_8.output()["ng"]) print("###########################################################\n") print("-------------------outside CPU------------------") self.output_value.append(outM) #out : writeM self.output_value.append(self.Ctrlbit[5]) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() print("self.CTRLBIT[6]",self.Ctrlbit[6]) if (self.Ctrlbit[6] == 1): print("ksadjflksjdlkfjaslkdjfasdfskfjaskdjfklsjdflkjsdlkjfklasjlkfjlksdajflksjadlfjslkadjfklsdjfklasjkdfjskladjfklasjdkflaskdjflksjadkfjalskdjflkasjdlkfjsaldkfjlaksdjflksajdfkasjdlkfjaslkdjlfksajdlfkajsldkfjaslkfjlsjfskldjflskadfjlskdfjlksdjflsdkj") self.programcounter_5_r_c5_9.update(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) #out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) # print("\n self.mux16_0_1_c0_3: ",self.mux16_0_1_c0_3.output(),self.Ctrlbit[1]); # A_register TODO: always add the value inside A regester when we have A instruction. # self.Reg16_3_c1_5.update([0]*16,0,Power=1); # print("\n\nA register: ",self.Reg16_3_c1_5.output()) # # D_register # self.Reg16_0_c2_6.update([0]*16,0,Power=1) # print("D register: ",self.Reg16_0_c2_6.output(),"\n\n") def output(self): return self.output_value; class CPU3: def __init__(self,Iin,Min,reset,Power=1): self.output_value = []; """ input: Min = Data from DataMemory (16) Iin = Instructions from InstructionMemory (16) reset (1) output: Data To Data Memory:- Mout (16) Mwrite (1) Maddress(15) Data To Instruction Memory:- pc (15) """ # Maybe add Decoder later ( using Data Buses.) # So the input is going to be an array array # FOR A INSTRUCTION # //////_________\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ self.ALUout_tm1_0 = [0]*16; # Although there is no output of alu tm1 beacuse this init is the first time there is. # think of it as a data bus Iin[1 to 15] self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; # FOR C INSTRUCTION self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output()] #Jump Bits # NOTE: Maybe We have to seperate all of the components "AND(x,y).output" into seprate variable... but first we need to concrete our Style Guide for this code. #Calculating Comp Bits (only Appy to C instructions) self.Ctrlbit[0] = AND(Iin[0],Iin[10]).output() # first opcode tells weather its a A instruction or C instruction. self.Ctrlbit[1] = AND(Iin[0],Iin[10]).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() self.Ctrlbit[1] = OR(NOT(Iin[0]).output(),self.Ctrlbit[1]).output() # if it is an A instruction then always set it to 1 else use the evaluated value of ctrlbit[1] self.mux16_1_0_c0_3 = Mux16(self.Input_1,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # A_register self.Reg16_3_c1_5 = Reg16(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) print("A register: ",self.Reg16_3_c1_5.output()); # D_register self.Reg16_0_c2_6 = Reg16(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) # M/A register self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1) # self.mux16_5_m_c3_7 = Mux16([0]*16,Min,self.Ctrlbit[3],Power=1) print("M/Aout: ",self.mux16_5_m_c3_7.output()) # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.output_value.append(outM) self.ALUout_tm1_0 = outM # the output of this ALU will used as input in t+1 timestep; #out : writeM writeM = self.Ctrlbit[5] self.output_value.append(writeM) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() """ self.Ctrlbit[5] = OR(\ OR(\ AND(\ AND(Iin[0],Iin[13]).output(),\ NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]).output()).output()\ ,\ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] \ )\ ).output()\ , \ AND(\ AND(Iin[0],Iin[13]).output(),\ self.alu_6_7_c4_8.output()["zr"] )\ ).output() """ self.programcounter_5_r_c5_9 = ProgramCounter(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) # updating the programcounter in the init because as we know the output of the program counter will take effect @ t+1 but we are ignoring the first time step of initializing and going straight to t=1 # self.programcounter_5_r_c5_9.update() # out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) def update(self,Iin,Min,reset,Power=1): #INITIALIZATION self.output_value = [] print("cpu_inI: ",Iin,Iin[0],"cpu_inM: ",Min); # for A instructions self.Input_1 = [0,Iin[1],Iin[2],Iin[3],Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9],Iin[10],Iin[11],Iin[12],Iin[13],Iin[14],Iin[15]]; self.Ctrlbit = [0,0,0,0,0,0,0] self.Jump = [AND(Iin[0],Iin[13]).output(), AND(Iin[0],Iin[14]).output(), AND(Iin[0],Iin[15]).output(), ] #Jump Bits # if (Iin[0] == 0)1 else self.Ctrlbit[1] #Calculating Comp Bits self.Ctrlbit[0] = AND(Iin[0],Iin[10]).output() self.Ctrlbit[1] = OR( (NOT(Iin[0]).output()) , (AND(Iin[0],Iin[10]).output()) ).output() # if (Iin[0]) Ctrlbit[1] = Iin[10] for A-register load bit self.Ctrlbit[2] = AND(Iin[0],Iin[11]).output() # for D-register load bit self.Ctrlbit[3] = AND(Iin[0],Iin[3]).output() # "a" bit of C instruction for M/A Mux self.Ctrlbit[4] = [AND(Iin[0],Iin[4]).output(), AND(Iin[0],Iin[5]).output(), AND(Iin[0],Iin[6]).output(), AND(Iin[0],Iin[7]).output(), AND(Iin[0],Iin[8]).output(), AND(Iin[0],Iin[9]).output(), ] #All the computation bits will go in ALU self.Ctrlbit[5] = AND(Iin[0],Iin[12]).output() #NOTE: self.Ctrlbit[6] required the output of ALU to calcuate the value, so we will do it later on, when we got the ALU output self.Ctrlbit[1] = OR(NOT(Iin[0]).output(),self.Ctrlbit[1]).output() # if it is an A instruction then always set it to 1 else use the evaluated value of ctrlbit[1] # # A_register # self.Reg16_3_c1_5.update(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) # M/A register self.mux16_5_m_c3_7 = Mux16(self.Reg16_3_c1_5.output(),Min,self.Ctrlbit[3],Power=1) # Printing t-1 outputs print("-------------------inside CPU------------------") print("\n\n###########################################################") print("D_input:",self.Reg16_0_c2_6.output()); print("M/A_input:",self.mux16_5_m_c3_7.output()); print("ALU input: ",self.Ctrlbit[4],"ALU_out:",self.ALUout_tm1_0); # print("zr: ",self.ALUout_tm1_0.output()["zr"],"ng: ",self.ALUout_tm1_0.output()["ng"]) print("###########################################################\n") ####################################### # Using ALU out[0] = evaluated value; out[1] = zr and out[2] = ng self.alu_6_7_c4_8 = ALU(self.Reg16_0_c2_6.output(), self.mux16_5_m_c3_7.output(), zx=self.Ctrlbit[4][0], nx=self.Ctrlbit[4][1], zy=self.Ctrlbit[4][2], ny=self.Ctrlbit[4][3], f=self.Ctrlbit[4][4], no=self.Ctrlbit[4][5], Power=1) #out : outM outM = self.alu_6_7_c4_8.output()["out"] self.ALUout_tm1_0 = outM; self.mux16_1_0_c0_3 = Mux16(self.Input_1,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) self.mux16_0_1_c0_3 = Mux16(Iin,self.ALUout_tm1_0,self.Ctrlbit[0],Power=1) # A_register self.Reg16_3_c1_5.update(self.mux16_1_0_c0_3.output(),self.Ctrlbit[1],Power=1) # D_register self.Reg16_0_c2_6.update(self.ALUout_tm1_0,self.Ctrlbit[2],Power=1) print("\nA_register:",self.Reg16_3_c1_5.output()); print("D_register:",self.Reg16_0_c2_6.output()); print("-------------------outside CPU------------------") self.output_value.append(outM) #out : writeM self.output_value.append(self.Ctrlbit[5]) #out : addressM addressM = self.Reg16_3_c1_5.output() self.output_value.append(addressM) # Calculating the load bit of the program counter using Jump bits and the outputs of the ALU self.and_j1_82_9 = AND(self.Jump[0],self.alu_6_7_c4_8.output()["ng"]) self.and_j2_81_10 = AND(self.Jump[1],self.alu_6_7_c4_8.output()["zr"]) self.nor_81_82_11 = NOR(self.alu_6_7_c4_8.output()["zr"],self.alu_6_7_c4_8.output()["ng"]) self.and_j3_10_12 = AND(self.Jump[2],self.nor_81_82_11.output()) self.or_10_12_13 = OR(self.and_j2_81_10.output(),self.and_j3_10_12.output()) self.or_9_13_14 = OR(self.and_j1_82_9.output(),self.or_10_12_13.output()) self.Ctrlbit[6] = self.or_9_13_14.output() print("self.CTRLBIT[6]",self.Ctrlbit[6]) if (self.Ctrlbit[6] == 1): print("ksadjflksjdlkfjaslkdjfasdfskfjaskdjfklsjdflkjsdlkjfklasjlkfjlksdajflksjadlfjslkadjfklsdjfklasjkdfjskladjfklasjdkflaskdjflksjadkfjalskdjflkasjdlkfjsaldkfjlaksdjflksajdfkasjdlkfjaslkdjlfksajdlfkajsldkfjaslkfjlsjfskldjflskadfjlskdfjlksdjflsdkj") self.programcounter_5_r_c5_9.update(self.Reg16_3_c1_5.output(),self.Ctrlbit[6],NOT(self.Ctrlbit[6]).output(),reset,Power=1) #out : PC self.output_value.append(self.programcounter_5_r_c5_9.output()) # print("\n self.mux16_0_1_c0_3: ",self.mux16_0_1_c0_3.output(),self.Ctrlbit[1]); # A_register TODO: always add the value inside A regester when we have A instruction. # self.Reg16_3_c1_5.update([0]*16,0,Power=1); # print("\n\nA register: ",self.Reg16_3_c1_5.output()) # # D_register # self.Reg16_0_c2_6.update([0]*16,0,Power=1) # print("D register: ",self.Reg16_0_c2_6.output(),"\n\n") def output(self): return self.output_value; class CPUfromhdl: # out: outM[16],writeM,addressM[15],pc[15] def __init__(self,Iin , Min,reset =0,Power=1): self.output_values = [] self.ALUout = [0]*16 # we dont know ALUout just yet so we create a dummy ALUout self.Ainstruction = NOT(Iin[15],Power=1).output() self.Cinstruction = NOT(self.Ainstruction,Power=1).output() self.ALUtoA = AND(self.Cinstruction,Iin[10]).output() # C-instruction and destination to A-register? self.Aregin = Mux16(Iin,self.ALUout,self.ALUtoA).output() #for A register self.loadA = OR(self.Ainstruction,self.ALUtoA).output() self.Aregister = Reg16(self.Aregin,self.loadA) self.Aout = self.Aregister.output() #for A/M Multiplexer self.AMout = Mux16(self.Aout,Min,Iin[3]).output() #for D register self.loadD = AND(self.Cinstruction,Iin[11]).output() self.Dregister = Reg16(self.ALUout,self.loadD) self.Dout = self.Dregister.output() #ALU self.MyALU = ALU(self.Dout,self.AMout,Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9]).output() self.ALUout = self.MyALU["out"] self.ZRout = self.MyALU["zr"] self.NGout = self.MyALU["ng"] #Set outputs for Writing memory self.CpuOut_outM = self.ALUout; self.CpuOut_writeM = Iin[12]; self.CpuOut_addressM = self.Aout; # i.e, A register #calculate ProgramCounter output jeq = AND(self.ZRout,Iin[14],Power=1).output() jlt = AND(self.NGout,Iin[13],Power=1).output() zeroOrNeg = OR(self.ZRout,self.NGout).output() positive = NOT(zeroOrNeg).output() jgt = AND(positive,Iin[15]).output() jle = OR(jeq,jlt).output(); jumpToA = OR(jle,jgt).output() PCload = AND(self.Cinstruction,jumpToA).output() PCinc = NOT(PCload).output() self.pc = ProgramCounter(self.Aout,PCload,PCinc,reset); self.CpuOut_pc = self.pc.output() self.output_values = [self.CpuOut_outM,self.CpuOut_writeM,self.CpuOut_addressM,self.CpuOut_pc] def update(self,Iin,Min,reset=0,Power=1): self.output_values = [] self.Ainstruction = NOT(Iin[0],Power=1).output() self.Cinstruction = NOT(self.Ainstruction,Power=1).output() self.ALUtoA = AND(self.Cinstruction,Iin[10]).output() # C-instruction and destination to A-register? self.Aregin = Mux16(Iin,self.ALUout,self.ALUtoA).output() #for A register self.loadA = OR(self.Ainstruction,self.ALUtoA).output() self.Aregister.update(self.Aregin,self.loadA,Power) #_# self.Aout = self.Aregister.output() #for A/M Multiplexer self.AMout = Mux16(self.Aout,Min,Iin[3]).output() #for D register self.loadD = AND(self.Cinstruction,Iin[11]).output() self.Dregister.update(self.ALUout,self.loadD,Power) #_# self.Dout = self.Dregister.output() print("==============inside CPU================") print("A-register: ",self.Aout) print("D-register: ",self.Dout) print("M/A input : ",self.AMout) print("ALUout: ",self.ALUout) print("=========================================") #ALU self.MyALU = ALU(self.Dout,self.AMout,Iin[4],Iin[5],Iin[6],Iin[7],Iin[8],Iin[9]).output() self.ALUout = self.MyALU["out"] self.ZRout = self.MyALU["zr"] self.NGout = self.MyALU["ng"] #Set outputs for Writing memory self.CpuOut_outM = self.ALUout; self.CpuOut_writeM = Iin[12]; self.CpuOut_addressM = self.Aout; # i.e, A register #calculate ProgramCounter output from ALUouts jeq = AND(self.ZRout,Iin[14],Power=1).output() jlt = AND(self.NGout,Iin[13],Power=1).output() zeroOrNeg = OR(self.ZRout,self.NGout).output() positive = NOT(zeroOrNeg).output() jgt = AND(positive,Iin[15]).output() jle = OR(jeq,jlt).output(); jumpToA = OR(jle,jgt).output() PCload = AND(self.Cinstruction,jumpToA).output() PCinc = NOT(PCload).output() self.pc.update(self.Aout,PCload,PCinc,reset,Power) self.CpuOut_pc = self.pc.output() self.output_values = [self.CpuOut_outM,self.CpuOut_writeM,self.CpuOut_addressM,self.CpuOut_pc] def output(self): return self.output_values; class Computer: def __init__(self,progPath,reset=0,Power=1): #Input: it takes A file of Assembly Code from external file. and Feed it in ROM program = open(progPath,"rt"); # Converting file lines to bits array Instructions = [] #program Lines for line in program: Iin = []; for bit in line: if (bit != "\n"): Iin.append(int(bit)) Instructions.append(Iin); #temp: Adding Vacent space Instructions.append([0]*16) Instructions.append([0]*16) Instructions.append([0]*16) Instructions.append([0]*16) Instructions.append([0]*16) Instructions.append([0]*16) # Adding all the Instruction into Array representation # output of CPU in t-1 time step is takens for calcuating the input of this time step self.cpu_outM = [0]*16; self.cpu_addressM = [0]*15 # 15bit address(because we are using ram16K which need 14 bits of address and 1 bit is useless because most significant bit gives info about its sign) self.cpu_writeM = 0; self.cpu_pc = [0]*15; # input of this time step CPU self.cpu_inM = [0]*16; self.cpu_inI = [0]*16; self.reset = reset; addNbit = self.cpu_addressM[1:] self.output_value = [self.cpu_outM,self.cpu_addressM,self.cpu_writeM,self.cpu_pc] self.ROM = Instructions # AKA Instruction Memory # consist of array of instructions # add empty instructions for i in range(5): self.ROM.append([0]*16) self.RAM = RAM512(self.cpu_outM,addNbit,self.cpu_writeM,Power=1) # AKA Data Memory self.reset = reset; #Computer's reset Button # Fetching the current Instruction of CPU to Process self.index_of_current_instruction = bin2dec(self.cpu_pc) # self.cpu_inI = self.ROM[self.index_of_current_instruction] self.cpu_inI = [0]*16 # extract only 14bits because we are using RAM16 and in the output the first bit is reserved for number sign i.e, 0 == negitive and 1 == positive address = num2locN(bin2dec(addNbit),512); # self.cpu_inM = self.RAM.output()[address[0]][address[1]][address[2]][address[3]][address[4]] # value inside RAM self.cpu_inM = self.RAM.output()[address[0]][address[1]][address[2]] # value inside RAM print("CPU IN: this is FROM COMPUTER","self.cpu_inI: ",self.cpu_inI,"self.cpu_inM: ",self.cpu_inM) #Central Processing Unit self.CPU = CPUfromhdl(self.cpu_inI,self.cpu_inM,self.reset) # self.CPU.update(self.cpu_inI,self.cpu_inM,self.reset) self.Computer_counter = 0; print("self.cpu_outM ", self.cpu_outM) print("self.cpu_writeM ", self.cpu_writeM) print("self.cpu_addressM ", self.cpu_addressM) print("self.cpu_pc ", self.cpu_pc) def update(self,reset=0,Power=1): self.reset = reset # Updating the values using the CPU from t-1 cpu output self.cpu_outM = self.CPU.output()[0] self.cpu_writeM = self.CPU.output()[1] self.cpu_addressM = self.CPU.output()[2] self.cpu_pc = self.CPU.output()[3] self.output_value = [self.cpu_outM,self.cpu_addressM,self.cpu_writeM,self.cpu_pc] print("\n\n------------------------------------------------------------------------\n") print("Computer_counter: ",self.Computer_counter,"\n") print("self.cpu_outM ", self.cpu_outM) print("self.cpu_writeM ", self.cpu_writeM) print("self.cpu_addressM ", self.cpu_addressM) print("self.cpu_pc ", self.cpu_pc) # Using the output of CPU t-1 to calcualte the inputs for current step's cpu # Fetching the current Instruction of CPU to Process self.index_of_current_instruction = bin2dec(self.cpu_pc) self.cpu_inI = self.ROM[self.index_of_current_instruction] print("self.indexof current_instruction: ",self.index_of_current_instruction) # For RAM Update:- # addNbit = self.cpu_addressM[1:] # for 14bits of address for RAM16 addNbit = self.cpu_addressM[7:] address = num2locN(bin2dec(addNbit),512) print("address: ",bin2dec(addNbit),len(addNbit),addNbit,"\t",address) self.RAM.update(self.cpu_outM,addNbit,self.cpu_writeM,Power) # value inside RAM[self.outaddM] # self.RAM.update([0]*16,[0]*15,0,Power) # self.cpu_inM = self.RAM.output()[address[0]][address[1]][address[2]][address[3]][address[4]] # value inside RAM16K self.cpu_inM = self.RAM.output()[address[0]][address[1]][address[2]] # value inside RAM512 # Print address print("printing RAM") for i in range(20): val = num2locN(i,512) ramout = self.RAM.output()[val[0]][val[1]][val[2]] print(i,ramout) print() print("Cpu_inI: ",self.cpu_inI,"Cpu_inM: ",self.cpu_inM) self.CPU.update(self.cpu_inI,self.cpu_inM,self.reset) self.Computer_counter += 1 print("\n--------------------------END-------------------------------------------") print("-----------------------x-x-x-x-x----------------------------------------\n") def output(self): return self.output_value program2 ="Assembler/program/executable/program2.out"; MyComputer = Computer(progPath=program2,reset=0,Power=1) for i in range(20): MyComputer.update() print("\n output:",MyComputer.output()) <file_sep>/Processor/Test_processor.py import unittest import processor_16bit # import numpy as np import random import math def gen_num(maxbit): return [(int)(random.random()*1.5) for i in range(maxbit)] def to_binary(val): retval = "" for i in val: retval += str(i) return retval def bin2dec(bin): val =0; for i in range(len(bin)): val += bin[(len(bin)-1)-i]*(2**i); return val def dec2bin(n,k): initbin = bin(n).replace("0b","") b = [ int(initbin[i]) if i >= 0 else 0 for i in range(len(initbin)-k,len(initbin))] return b def andt(i1,i2): return [ i1[i] and i2[i] for i in range(len(i1))] def ort(i1,i2): return [ i1[i] or i2[i] for i in range(len(i1))] def nott(inp): return [1-inp[i] for i in range(len(inp))] class TestCalc(unittest.TestCase): def test_transistor(self): #{in = switch = 0/1 power = 1} {out = 0/1} test_result = Gates_refactored.Transistor(0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.Transistor(1).output() self.assertEqual(test_result,1) # Testing POWER input: # if Power is 0 then the output should be 0 test_result = Gates_refactored.Transistor(1,0).output() self.assertEqual(test_result,0) def test_NAND(self): test_result = Gates_refactored.NAND(0,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.NAND(0,1,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.NAND(1,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.NAND(1,1,1).output() self.assertEqual(test_result,0) # Testing POWER input: test_result = Gates_refactored.NAND(1,0,0).output() self.assertEqual(test_result,0) def test_NOT(self): test_result = Gates_refactored.NOT(0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.NOT(1,1).output() self.assertEqual(test_result,0) # Testing Power input: test_result = Gates_refactored.NOT(1,0).output() self.assertEqual(test_result,0) def test_AND(self): test_result = Gates_refactored.AND(0,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.AND(0,1,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.AND(1,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.AND(1,1,1).output() self.assertEqual(test_result,1) # Testing POWER input: test_result = Gates_refactored.AND(1,1,0).output() self.assertEqual(test_result,0) def test_OR(self): test_result = Gates_refactored.OR(0,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.OR(0,1,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.OR(1,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.OR(1,1,1).output() self.assertEqual(test_result,1) # Testing POWER input: test_result = Gates_refactored.OR(1,1,0).output() self.assertEqual(test_result,0) def test_NOR(self): test_result = Gates_refactored.NOR(0,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.NOR(0,1,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.NOR(1,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.NOR(1,1,1).output() self.assertEqual(test_result,0) # Testing POWER input: test_result = Gates_refactored.NOR(0,0,0).output() self.assertEqual(test_result,0) def test_XOR(self): test_result = Gates_refactored.XOR(0,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.XOR(0,1,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.XOR(1,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.XOR(1,1,1).output() self.assertEqual(test_result,0) # Testing POWER input: test_result = Gates_refactored.XOR(1,0,0).output() self.assertEqual(test_result,0) def test_XNOR(self): test_result = Gates_refactored.XNOR(0,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.XNOR(0,1,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.XNOR(1,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.XNOR(1,1,1).output() self.assertEqual(test_result,1) # Testing POWER input: test_result = Gates_refactored.XNOR(0,0,0).output() self.assertEqual(test_result,0) def test_MUX(self): test_result = Gates_refactored.MUX(0,0,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.MUX(0,1,0,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.MUX(1,0,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.MUX(1,1,0,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.MUX(0,0,1,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.MUX(0,1,1,1).output() self.assertEqual(test_result,1) test_result = Gates_refactored.MUX(1,0,1,1).output() self.assertEqual(test_result,0) test_result = Gates_refactored.MUX(1,1,1,1).output() self.assertEqual(test_result,1) #Testing POWER input: test_result = Gates_refactored.MUX(1,1,1,0).output() self.assertEqual(test_result,0) def test_DMUX(self): test_result = Gates_refactored.DMUX(0,0,1).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.DMUX(0,1,1).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.DMUX(1,0,1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.DMUX(1,1,1).output() self.assertEqual(test_result,[0,1]) # Testing Power input; test_result = Gates_refactored.DMUX(1,0,0).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.DMUX(1,1,0).output() self.assertEqual(test_result,[0,0]) # Testing 16 Bit Variants def test_MUX16(self): test_result = Gates_refactored.Mux16([0,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1],0,1).output() self.assertEqual(test_result,[0,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1]) test_result = Gates_refactored.Mux16([0,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1],1,1).output() self.assertEqual(test_result,[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1]) #Testing Power input; test_result = Gates_refactored.Mux16([0,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],0,0).output() self.assertEqual(test_result,[0]*16) test_result = Gates_refactored.Mux16([0,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1],1,0).output() self.assertEqual(test_result,[0]*16) def test_AND16(self): # generating random inputs for the tests inputs = [gen_num(16),gen_num(16)] # print("\n\n inputs:",inputs,"\n\n") test_result = Gates_refactored.And16(inputs[0],inputs[1],Power=1).output() # comparing the results using built-in "and" operator self.assertEqual(test_result,andt(inputs[0],inputs[1])); test_result = Gates_refactored.And16(inputs[1],inputs[0],Power=1).output() #same but reversed inputs self.assertEqual(test_result,andt(inputs[0],inputs[1])); #testing Power input: test_result = Gates_refactored.And16(inputs[1],inputs[0],Power=0).output() self.assertEqual(test_result,[0]*16) def test_OR16(self): inputs = [gen_num(16),gen_num(16)] test_result = Gates_refactored.Or16(inputs[0],inputs[1],Power=1).output() self.assertEqual(test_result,ort(inputs[0],inputs[1])) test_result = Gates_refactored.Or16(inputs[1],inputs[0],Power=1).output() self.assertEqual(test_result,ort(inputs[0],inputs[1])) #testing Power input: test_result = Gates_refactored.Or16(inputs[1],inputs[0],Power=0).output() self.assertEqual(test_result,[0]*16) def test_NOT16(self): inp = gen_num(16) test_result = Gates_refactored.Not16(inp,1).output() self.assertEqual(test_result,nott(inp)) test_result = Gates_refactored.Not16(inp,1).output() self.assertEqual(test_result,nott(inp)) #testing Power input: test_result = Gates_refactored.Not16(inp,0).output() self.assertEqual(test_result,[0]*16) # NOw testing a to n Ways Gates/devices: def test_or8way(self): inp = gen_num(8) test_result = Gates_refactored.Or8Way(inp,Power=1).output() # print("testResult: ",test_result,"\ninp: ",inp) self.assertEqual(test_result,max(inp)) #Regenerating new random input just for test inp = gen_num(8) test_result = Gates_refactored.Or8Way(inp,Power=1).output() self.assertEqual(test_result,max(inp)) #testing Power input: test_result = Gates_refactored.Or8Way(inp,Power=0).output() self.assertEqual(test_result,0) def test_mux4way16(self): inp = [gen_num(16),gen_num(16),gen_num(16),gen_num(16),] test_result = Gates_refactored.Mux4Way16(inp[0],inp[1],inp[2],inp[3],S=[0,0],Power=1).output() self.assertEqual(test_result,inp[0]) test_result = Gates_refactored.Mux4Way16(inp[0],inp[1],inp[2],inp[3],S=[0,1],Power=1).output() # print("\n inp: ",inp,"\n\ntest_result ",test_result) self.assertEqual(test_result,inp[1]) test_result = Gates_refactored.Mux4Way16(inp[0],inp[1],inp[2],inp[3],S=[1,0],Power=1).output() self.assertEqual(test_result,inp[2]) test_result = Gates_refactored.Mux4Way16(inp[0],inp[1],inp[2],inp[3],S=[1,1],Power=1).output() self.assertEqual(test_result,inp[3]) #Testing Power input: test_result = Gates_refactored.Mux4Way16(inp[0],inp[1],inp[2],inp[3],S=[0,0],Power=0).output() self.assertEqual(test_result,[0]*16) def test_Mux8Way16(self): inp = [gen_num(16),gen_num(16),gen_num(16),gen_num(16),gen_num(16),gen_num(16),gen_num(16),gen_num(16),] test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[0,0,0],Power=1).output() self.assertEqual(test_result,inp[0]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[0,0,1],Power=1).output() self.assertEqual(test_result,inp[1]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[0,1,0],Power=1).output() self.assertEqual(test_result,inp[2]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[0,1,1],Power=1).output() self.assertEqual(test_result,inp[3]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[1,0,0],Power=1).output() self.assertEqual(test_result,inp[4]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[1,0,1],Power=1).output() self.assertEqual(test_result,inp[5]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[1,1,0],Power=1).output() self.assertEqual(test_result,inp[6]) test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[1,1,1],Power=1).output() self.assertEqual(test_result,inp[7]) #Testing Power input: test_result = Gates_refactored.Mux8Way16(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],S=[0,0,1],Power=0).output() self.assertEqual(test_result,[0]*16) def test_Dmux4Way(self): test_result = Gates_refactored.Dmux4Way(Input=1,S=[0,0],Power=1).output() self.assertEqual(test_result,[1,0,0,0]) test_result = Gates_refactored.Dmux4Way(Input=1,S=[0,1],Power=1).output() self.assertEqual(test_result,[0,1,0,0]) test_result = Gates_refactored.Dmux4Way(Input=1,S=[1,0],Power=1).output() self.assertEqual(test_result,[0,0,1,0]) test_result = Gates_refactored.Dmux4Way(Input=1,S=[1,1],Power=1).output() self.assertEqual(test_result,[0,0,0,1]) #Testing 0 as input: test_result = Gates_refactored.Dmux4Way(Input=0,S=[1,0],Power=1).output() self.assertEqual(test_result,[0,0,0,0]) #Testing Power input: test_result = Gates_refactored.Dmux4Way(Input=1,S=[0,0],Power=0).output() self.assertEqual(test_result,[0,0,0,0]) def test_Dmux8Way(self): test_result = Gates_refactored.DMux8Way(Input=1,S=[0,0,0],Power=1).output() self.assertEqual(test_result,[1,0,0,0,0,0,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[0,0,1],Power=1).output() self.assertEqual(test_result,[0,1,0,0,0,0,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[0,1,0],Power=1).output() self.assertEqual(test_result,[0,0,1,0,0,0,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[0,1,1],Power=1).output() self.assertEqual(test_result,[0,0,0,1,0,0,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[1,0,0],Power=1).output() self.assertEqual(test_result,[0,0,0,0,1,0,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[1,0,1],Power=1).output() self.assertEqual(test_result,[0,0,0,0,0,1,0,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[1,1,0],Power=1).output() self.assertEqual(test_result,[0,0,0,0,0,0,1,0]) test_result = Gates_refactored.DMux8Way(Input=1,S=[1,1,1],Power=1).output() self.assertEqual(test_result,[0,0,0,0,0,0,0,1]) #Testing Power input: test_result = Gates_refactored.DMux8Way(Input=1,S=[0,0,0],Power=0).output() self.assertEqual(test_result,[0,0,0,0,0,0,0,0]) # Testing ADDERS: def test_halfAdders(self): test_result = Gates_refactored.HalfAdder(input_a=0,input_b=0,Power=1).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.HalfAdder(input_a=0,input_b=1,Power=1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.HalfAdder(input_a=1,input_b=0,Power=1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.HalfAdder(input_a=1,input_b=1,Power=1).output() self.assertEqual(test_result,[0,1]) #Testing Power input: test_result = Gates_refactored.HalfAdder(input_a=0,input_b=1,Power=0).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.HalfAdder(input_a=1,input_b=1,Power=0).output() self.assertEqual(test_result,[0,0]) def test_FullAdder(self): test_result = Gates_refactored.FullAdder(input_a=0,input_b=0,c=0,Power=1).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.FullAdder(input_a=0,input_b=1,c=0,Power=1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.FullAdder(input_a=1,input_b=0,c=0,Power=1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.FullAdder(input_a=1,input_b=1,c=0,Power=1).output() self.assertEqual(test_result,[0,1]) #Testing Carry Bit test_result = Gates_refactored.FullAdder(input_a=0,input_b=0,c=1,Power=1).output() self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.FullAdder(input_a=0,input_b=1,c=1,Power=1).output() self.assertEqual(test_result,[0,1]) test_result = Gates_refactored.FullAdder(input_a=1,input_b=0,c=1,Power=1).output() self.assertEqual(test_result,[0,1]) test_result = Gates_refactored.FullAdder(input_a=1,input_b=1,c=1,Power=1).output() self.assertEqual(test_result,[1,1]) #Testing Power input: test_result = Gates_refactored.FullAdder(input_a=1,input_b=0,c=0,Power=0).output() self.assertEqual(test_result,[0,0]) test_result = Gates_refactored.FullAdder(input_a=0,input_b=1,c=1,Power=0).output() self.assertEqual(test_result,[0,0]) def test_Adder16(self): rndinp_a = gen_num(16) rndinp_b = gen_num(16) rndinp_a = [0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0] #22850 rndinp_b = [0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1] #8881 ans_aplusb = [0,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1] # answer a+b = 22850 + 8881 = 31731 test_result = Gates_refactored.Adder16(input_a=rndinp_a,input_b=rndinp_b,Power=1).output() self.assertEqual(test_result,ans_aplusb) # testing for operation with numrical overflow :- rndinp_a = [1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0] #41410 rndinp_b = [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0] #51504 ans_aplusb = [0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0] #correct answer upto max bit length # answer a+b = 41410 + 51504 = 92914 # true ans: 010110101011110010 # our ans: 0110101011110010 test_result = Gates_refactored.Adder16(input_a=rndinp_a,input_b=rndinp_b,Power=1).output() self.assertEqual(test_result,ans_aplusb) # testing Power input: # generating random input rndinp_a = gen_num(16) rndinp_b = gen_num(16) test_result = Gates_refactored.Adder16(input_a=rndinp_a,input_b=rndinp_b,Power=0).output() self.assertEqual(test_result,[0]*16) def test_Neg16(self): inp = [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1] # 13 # as we know in 2's compliment it is negetive 13 ans = [1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1] # 2^16 - 13 = 65536 - 13 = 65523 # ans = [0,0,0,1,0,1,1,0,1,0,1,1,1,0,0,0] test_result = Gates_refactored.Neg16(inp,Power=1).output() self.assertEqual(test_result,ans) # inp = [1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,0] # ans = nott(inp) #using premade function for testing not gate # test_result = Gates_refactored.Neg16(inp,Power=1).output() # self.assertEqual(test_result,ans) # testing Power input: test_result = Gates_refactored.Neg16(inp,Power=0).output() self.assertEqual(test_result,[0]*16) # finally testing ALU def test_ALU(slef): pass # Testing Memory def test_SRFlipFlop(self): test_result = Gates_refactored.SRFF(S=1,R=0,tm1_Q0=0,Power=1).output() self.assertEqual(test_result,[0,1]) # test_result = Gates_refactored.SRFlipFlop(S=0,R=1,tm1_Q0=0,Power=1).output() # self.assertEqual(test_result,[1,0]) test_result = Gates_refactored.SRFF(S=0,R=0,tm1_Q0=0,Power=1).output() self.assertEqual(test_result,[0,1]) test_result = Gates_refactored.SRFF(S=1,R=1,tm1_Q0=0,Power=1).output() self.assertEqual(test_result,[0,1]) test_result = Gates_refactored.SRFF(S=0,R=1,tm1_Q0=0,Power=1).output() self.assertEqual(test_result,[0,1]) # testing by changing the time step # TIME = 0 test_result = Gates_refactored.SRFF(S=0,R=1,tm1_Q0=0,Power=1) #TIME = 1 | updating State test_result.update(S=1,R=0) self.assertEqual(test_result.output(),[1,0]) #TIME = 2 | updating State test_result.update(S=0,R=0) self.assertEqual(test_result.output(),[0,1]) #TIME = 3 | updating State test_result.update(S=1,R=1) self.assertEqual(test_result.output(),[0,1]); #TIME = 4 | updating State test_result.update(S=1,R=0) self.assertEqual(test_result.output(),[0,1]); #TIME = 5 | updating State test_result.update(S=0,R=1) #Note: once it is haulted because of S=1 R=1 it can never recover back. so the output will always # going to be 0. self.assertEqual(test_result.output(),[0,1]); # When the previous States is S=1 R=0 # instance_Sfirst = Gates_refactored.SRFlipFlop(S=1,R=0,Power=1) # instance_Sfirst.update(S=1,R=0) # test_result = instance_Sfirst.output() # self.assertEqual(test_result,[0,1]) # instance_Sfirst = Gates_refactored.SRFlipFlop(S=1,R=0,Power=1) # instance_Sfirst.update(S=1,R=1) # test_result = instance_Sfirst.output() # self.assertEqual(test_result,[0,1]) #When the previous State is S=0 R=1 # instance_Rfirst = Gates_refactored.SRFlipFlop(S=0,R=1,Power=1) # instance_Rfirst.update(S=0,R=1) # test_result = instance_Rfirst.output() # self.assertEqual(test_result,[1,0]) # instance_Rfirst = Gates_refactored.SRFlipFlop(S=0,R=1,Power=1) # instance_Rfirst.update(S=1,R=1) # test_result = instance_Rfirst.output() # self.assertEqual(test_result,[1,0]) # #When the previous State is S=0 R=0 # instance_Nofirst = Gates_refactored.SRFlipFlop(S=0,R=0,Power=1) # instance_Nofirst.update(S=1,R=0) # test_result = instance_Nofirst.output() # self.assertEqual(test_result,[1,1]) #testing Power input: # test_result = Gates_refactored.SRFlipFlop(S=0,R=1,Power=0).output() # self.assertEqual(test_result,[0,0]) # def Test_RAM8(self): # test_result = Gates_refactored.RAM8(S=1,R=1,tm1_Q0=0,Power=1).output() # self.assertEqual(test_result,[0,1]) def test_ClockedDFF(self): # Working Perfectly! :D # now even when we turn off the clock the data still remain intact. which we can use in next time step #CLK HIGH test_result = Gates_refactored.Clocked_DFF(data=0,clock=1,Power=1) self.assertEqual(test_result.output(),[0,0]) #CLK HIGH test_result.update(data=1,clock=1,Power=1) self.assertEqual(test_result.output(),[0,1]) test_result.update(data=1,clock=0,Power=1) self.assertEqual(test_result.output(),[1,0]) # # if the clock is down then there is no output hence "0" test_result.update(data=0,clock=0,Power=1) self.assertEqual(test_result.output(),[1,0]) #CLK HIGH test_result.update(data=0,clock=1,Power=1) self.assertEqual(test_result.output(),[1,0]) test_result.update(data=1,clock=0,Power=1) self.assertEqual(test_result.output(),[0,1]) #CLK HIGH test_result.update(data=1,clock=1,Power=1) self.assertEqual(test_result.output(),[0,1]) def test_Reg1Bit(self): #LOAD test_result = Gates_refactored.Reg1Bit(Input_1=1,Load=1,Power=1); self.assertEqual(test_result.output(),0); #value is loaded in the register test_result.update(Input=0,Load=0,Power=1); self.assertEqual(test_result.output(),1) #LOAD test_result.update(Input=0,Load=1,Power=1); self.assertEqual(test_result.output(),1) test_result.update(Input=0,Load=0,Power=1); self.assertEqual(test_result.output(),0) def test_Reg16(self): test_result = Gates_refactored.Reg16(Input=[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],Load=1,Power=1) self.assertEqual(test_result.output(),[0]*16); test_result.update(Input=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1],Load=0,Power=1); self.assertEqual(test_result.output(),[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]); test_result.update(Input=[0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1],Load=0,Power=1) self.assertEqual(test_result.output(),[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]); def test_Program_Counter(self): test_result = Gates_refactored.ProgramCounter(Input=[0]*16,load=0,inc=1,reset=0,Power=1); self.assertEqual(test_result.output(),[0]*16) # print("program_counter: ",test_result.value_1) tmpInput = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0] test_result.update(Input=tmpInput,load=1,inc=0,reset=0,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]) # print("inside PC: ",test_result.mux16_3_4_r_5.output()); test_result.update(Input=tmpInput,load=0,inc=1,reset=0,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]) test_result.update(Input=tmpInput,load=0,inc=0,reset=1,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1]) test_result.update(Input=tmpInput,load=1,inc=0,reset=0,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]) test_result.update(Input=tmpInput,load=0,inc=1,reset=1,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]) test_result.update(Input=tmpInput,load=1,inc=1,reset=0,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]) test_result.update(Input=tmpInput,load=1,inc=1,reset=1,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1]) test_result.update(Input=tmpInput,load=1,inc=0,reset=0,Power=1) self.assertEqual(test_result.output(),[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]) def test_RAM8(self): test_result = Gates_refactored.RAM8(Input=[0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1],address=[0,1,1],load=1,Power=1) test_result.update(Input=[1]*16,address=[0,0,1],load=0,Power=1) test_result.update(Input=[0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1],address=[0,0,0],load=1,Power=1) test_result.update(Input=[0]*16,address=[0,0,0],load=0,Power=1) # print("RAM8: ",test_result.output()) # self.assertEqual(test_result.output(),[0]*16) def test_RAM64(self): # IT FUCKIN WORKS!! test_result = Gates_refactored.RAM64(Input=[0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0],address=[0,0,0,0,1,1],load=1,Power=1) test_result.update(Input=[1]*16,address=[1,1,1,1,1,1],load=1,Power=1) test_result.update(Input=[1]*16,address=[0,0,0,1,1,1],load=0,Power=1) test_result.update(Input=[0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0],address=[1,1,1,1,1,1],load=1,Power=1) test_result.update(Input=[0]*16,address=[0,0,0,0,1,0],load=0,Power=1) print("RAM64: ",test_result.output()[7][7]) # self.assertEqual(test_result.output(),[0]*16) pass def test_RAM512(self): RAMindex = 5 add2put = dec2bin(RAMindex,9) print("dec2bin: ",add2put) test_result = Gates_refactored.RAM512(Input=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],address=[0,0,0,0,0,0,0,0,0],load=0,Power=1) test_result.update(Input=[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],address=add2put,load=1,Power=1) test_result.update(Input=[1]*16,address=[0,0,0,0,0,0,1,1,1],load=0,Power=1) print("RAM512: ",len(test_result.output()[0][0][0])); for i in range(18): address = Gates_refactored.num2locN(i,512) print("this is RAM512: ",test_result.output()[address[0]][address[1]][address[2]]) # test_result.update(Input=[0]*16,address=[0,0,0],load=0,Power=1) # self.assertEqual(test_result.output(),[0]*16) pass def test_RAM16K(self): # test_result = Gates_refactored.RAM16K(Input=[1]*16,address = [0]*15,load=1); # test_result.update(Input=[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],address=[1]*15,load=1,Power=1) pass # print("RAM16K: ",len(test_result.output()[0]),(test_result.output()[0][0][0][0])); def test_ALU(self): # input_1 = [0,0,1,1,1,1,0,1,0,1,0,0,0,1,0,1] # input_2 = [0,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0] # print("dec2bin: ",dec2bin(17,16) ); # addit = Gates_refactored.Adder16(input_1,input_2,Power=1); # print("add: ",addit.output()); # ctrl_bits = [0,1,0,1,1,1] # test_result = Gates_refactored.ALU(input_1,input_2,ctrl_bits[0],ctrl_bits[1],ctrl_bits[2],ctrl_bits[3],ctrl_bits[4],ctrl_bits[5]) # print("dec:" ,bin2dec(test_result.output()["out"])) # print(test_result.output()); pass def test_CPU(self): # # read instruction from program # program = open("Assembler/program2.out","rt"); # # Converting file lines to bits array # plines = [] #program Lines # for line in program: # Iin = []; # for bit in line: # if (bit != "\n"): # Iin.append(int(bit)) # plines.append(Iin); # Iin = plines[0];# Current Instruction # Min = [0]*16; # reset = 0; # print(Iin); # test_result = Gates_refactored.CPU(Iin,Min,reset=0) # print("\nCENTRAL PROCESSING UNIT OUTPUT:",test_result.output(),"\n"); # Iin = plines[1]; # # Min = # test_result.update(Iin,Min,reset); # print("\nCENTRAL PROCESSING UNIT OUTPUT:",test_result.output(),"\n"); # test_result.update(Iin,Min,reset); # print("\nCENTRAL PROCESSING UNIT OUTPUT:",test_result.output(),"\n"); # def test_Computer(self): # pass #Testing Computer!!:- # test_result = Gates_refactored.Computer(); # print(test_result.output()) # test_result.update(); # print(test_result.output()) # test_result.update(); # print(test_result.output()) # test_result.update(); # print(test_result.output()) # test_result.update(); # print(test_result.output()) # test_result = 0 pass def int2binary(n): pass if __name__ =='__main__': unittest.main() # Gates_refactored.Reg1Bit(Input_1=1,Load=1,Power=1); <file_sep>/Assembler/Assembler.py """ TODO: insert a file preprocess it. """ import re import sys Symbol_table = { "@R0": 0, "@R1": 1, "@R2": 2, "@R3": 3, "@R4": 4, "@R5": 5, "@R6": 6, "@R7": 7, "@R8": 8, "@R9": 9, "@R10": 10, "@R11": 11, "@R12": 12, "@R13": 13, "@R14": 14, "@R15": 15, "SP" : 0, "LCL" : 1, "ARG" : 2, "THIS": 3, "THAT": 4, "SCREEN":16384, "KBD" : 24576 } # print(Symbol_table.get("KBD")) comp_table = { "0" : [0 ,1,0,1,0,1,0], "1" : [0 ,1,1,1,1,1,1], "-1" : [0 ,0,0,1,1,0,0], "D" : [0 ,0,0,1,1,0,0], "A" : [0 ,1,1,0,0,0,0], "M" : [ 1 ,1,1,0,0,0,0], "!D" : [0 ,0,0,1,1,0,1], "!A" : [0 ,1,1,0,0,0,1], "!M" : [ 1 ,1,1,0,0,0,1], "-A" : [0 ,1,1,0,0,1,1], "-M" : [ 1 ,1,1,0,0,1,1], "D+1" : [0 ,0,1,1,1,1,1], "A+1" : [0 ,1,1,0,1,1,1], "M+1" : [ 1 ,1,1,0,1,1,1], "D-1" : [0 ,0,0,1,1,1,0], "A-1" : [0 ,1,1,0,0,1,0], "M-1" : [ 1 ,1,1,0,0,1,0], "D+A" : [0 ,0,0,0,0,1,0], "D+M" : [ 1 ,0,0,0,0,1,0], "D-A" : [0 ,0,1,0,0,1,1], "D-M" : [ 1 ,0,1,0,0,1,1], "A-D" : [0 ,0,0,0,1,1,1], "M-D" : [ 1 ,0,0,0,1,1,1], "D&A" : [0 ,0,0,0,0,0,0], "D&M" : [ 1 ,0,0,0,0,0,0], "D|A" : [0 ,0,1,0,1,0,1], "D|M" : [ 1 ,0,1,0,1,0,1], } dest_table = { "null" : [0,0,0], "M" : [0,0,1], "D" : [0,1,0], "MD" : [0,1,1], "A" : [1,0,0], "AM" : [1,0,1], "AD" : [1,1,0], "AMD" : [1,1,1], } jump_table = { "null" : [0,0,0], "JGT" : [0,0,1], "JEQ" : [0,1,0], "JGE" : [0,1,1], "JLT" : [1,0,0], "JNE" : [1,0,1], "JLE" : [1,1,0], "JMP" : [1,1,1], } def dec2bin(n): initbin = bin(n).replace("0b","") b = [ int(initbin[i]) if i >= 0 else 0 for i in range(len(initbin)-16,len(initbin))] return b def main(): #Open The File f = open(str(sys.argv[1]),"rt"); # rt = read text # print(f.read()) # Processing this file p1 = [re.compile('\/\/').split(line) for line in f] p2 = [l[0] for l in p1] p3 = []; for line in p2: if(re.search(r'\w',line) != None): p3.append(line.replace(" ","").replace("\n","")); # NOTE: FIRST PASS # NOTE: ADD LABELS in the Symbol Table and remove lables from the lines(because they are useless while interpreting the asm code) lineNum = 0; for line in p3: if( re.search(r'\(',line) != None): currLabel = line.replace("(","").replace(")","") # check if its alreadly inside the symbols table if (Symbol_table.get(currLabel) == None): # then add it in the dictonary Symbol_table[currLabel] = lineNum; del p3[lineNum] lineNum+=1 #NOTE: SECOND PASS #NOTE: Now splitting the instructions for parsing. # for A instruction BinaryProgram = [None]*len(p3) # Converting Variables to Register Number(16++) var_index = 16 #because 0-15 are researved Registers lineNum =0 for line in p3: if( re.search(r'@\D',line) != None): currVariable = line.replace("@","") if (Symbol_table.get(currVariable) == None): # add this new Variable in Symbol_table Symbol_table[currVariable] = var_index p3[lineNum] = "@"+str(var_index) var_index +=1 else: p3[lineNum] = "@"+str(Symbol_table.get(currVariable)) lineNum +=1 # Write the preprocessed File out = open(str(sys.argv[1]).replace(".asm","")+".pre","w") for line in p3: out.write(str(line)+"\n") # STAGE 2 Creating Symbol table # NOW, Split the instruction to destination,comp,jump i=0 p3split = [None]*len(p3) for line in p3: tmp = re.split(r'\=',line) tmp1 = re.split(r'\;',tmp[len(tmp) - 1]) finalbits = tmp;# if len(tmp) > 1 and len(tmp1) == 1 # A instruction split if (len(tmp)== 1 and len(tmp1)== 1): finalbits = [line.replace("@","")] # C instruction split if (len(tmp)== 1 and len(tmp1) > 1): finalbits = ["null",tmp1[0],tmp1[1]] if (len(tmp)> 1 and len(tmp1) == 1): finalbits = [tmp[0],tmp[1],"null"] if (len(tmp)> 1 and len(tmp1) > 1) : finalbits = [tmp[0],tmp1[0],tmp1[1]] p3split[i] = finalbits i +=1 # print(p3split) # Now, finally Converting it to Binary using Symbol_table for i in range(0,len(p3split)): line = p3split[i] if (len(line) > 1):# filter out A instructions # print(line) dest = line[0] comp = line[1] jump = line[2] w = dest_table[dest] x = comp_table[comp] y = jump_table[jump] BinaryProgram[i] = [1,1,1,x[0],x[1],x[2],x[3],x[4],x[5],x[6],w[0],w[1],w[2],y[0],y[1],y[2]] continue print(line) BinaryProgram[i] = dec2bin(int(line[0])) p3 = BinaryProgram # print(BinaryProgram) print(Symbol_table) # Write out file out = open(str(sys.argv[1]).replace(".asm","")+".out","w") for line in p3: for i in line: out.write(str(i)) out.write("\n") pass if __name__ == '__main__': main()
16e0756f34e99694c09cc7c1bbdebd233d1482c6
[ "Python" ]
3
Python
MrityunjayBhardwaj/16-Bit_Processor_in_Python
9c487ea1d30c78c57ed5c8ba7b69bace17ebc510
ec6690c22f989d5fb7fe8425e8e139db137ae72a
refs/heads/main
<repo_name>florianvazelle/automate-twitch<file_sep>/src/pages/ContentScript/index.ts console.log('helloworld from content script'); /** * @name observe * @param {string} selector - CSS selector, which represents the path to the element to observe * @param {MutationCallback} callback - Callback function to execute when mutations are observed * @returns {MutationObserver|null} */ function observe(selector: string, callback: MutationCallback): MutationObserver | null { // Options for the observer (which mutations to observe) const config = { childList: true, subtree: true }; // Select the node that will be observed for mutations const targetNode = document.querySelector(selector); if (targetNode) { // Create an observer instance linked to the callback function const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); callback([], observer); return observer; } return null; } function start({}, observer: MutationObserver) { const selector = '.community-points-summary > .tw-full-height.tw-relative.tw-z-above > .tw-transition:first-child'; const callback = () => { const identifiableTarget = document.querySelector('.claimable-bonus__icon') if (identifiableTarget) { const bonusButton = identifiableTarget.closest('button') if (bonusButton) bonusButton.click(); } }; const bonusObserver = observe(selector, callback); if (bonusObserver) { observer.disconnect(); } } var oldHref = document.location.href; var observer: MutationObserver | null; observe('body', () => { if (oldHref != document.location.href) { if (observer) { observer.disconnect(); } oldHref = document.location.href; observer = observe('body', start); } }); observer = observe('body', start); export {}; <file_sep>/README.md # Automate Twitch Automate the collection of [channel points](https://help.twitch.tv/s/article/channel-points-guide) on Twitch. You can install the latest version manually, from the [Firefox Add-ons web site.](https://addons.mozilla.org/en-US/firefox/addon/automate-twitch/) ## Usage 1. Download and load the Add-on in your browser. 2. Go to the `twitch.tv` page of the stream you want to see. 3. Make sure you are logged in and it's go. ## Dependency Ensure you have [Node.js](https://nodejs.org) 10 or later installed. ## Development 1. Run `npm install` to install dependencies. 2. To watch file changes in development, run `npm run dev:<chrome|firefox|opera>`. 3. And load extension in browser - ### Chrome - Go to the browser address bar and type `chrome://extensions` - Check the `Developer Mode` button to enable it. - Click on the `Load Unpacked Extension…` button. - Select your extension’s extracted directory. - ### Firefox - Load the Add-on via `about:debugging` as temporary Add-on. - Choose the `manifest.json` file in the extracted directory - ### Opera - Load the extension via `opera:extensions` - Check the `Developer Mode` and load as unpacked from extension’s extracted directory. ## Production - `npm run build` builds the extension for all the browsers to `extension/BROWSER` directory respectively.
5c8ba60028642ae44d774fd967751c0f629eb933
[ "Markdown", "TypeScript" ]
2
TypeScript
florianvazelle/automate-twitch
a2deeaf6c4c170c1ac76fe24140945a9899192b0
ce4bddef2936d90a52cfdd085385be8a669ecb95
refs/heads/master
<repo_name>badaljain/LeetcodeQuestions<file_sep>/LongestSubstringWithoutRepeatingCharacters.java package LeetcodePrograms; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; /** * Created by rkhurana on 7/15/18. */ public class LongestSubstringWithoutRepeatingCharacters { public static int longestSubstringWithoutRepeatingCharacter(String s){ HashMap<Character,Integer> map = new HashMap<>(); int maxLength=0; int currentLength = 0; for(int i = 0; i < s.length(); i++ ){ if(map.containsKey(s.charAt(i))){ i=map.get(s.charAt(i)); currentLength = 0; map.clear(); } else{ map.put(s.charAt(i), i); currentLength++; if(currentLength > maxLength) maxLength = currentLength; } } return maxLength; } //below method will take O(n) complexity public int lengthOfLongestSubstring2(String s) { if (s.length()==0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max=0; for (int i=0, j=0; i<s.length(); ++i){ if (map.containsKey(s.charAt(i))){ j = Math.max(j,map.get(s.charAt(i))+1); } map.put(s.charAt(i),i); max = Math.max(max,i-j+1); } return max; } // can do the above same thing using ascii solution public int lengthOfLongestSubstring3(String s) { int len = s.length(),max=0; int [] chars = new int[128]; for(int i=0,j=0;i<len;i++){ j = Math.max(j,chars[s.charAt(i)]); max = Math.max(max,i-j+1); chars[s.charAt(i)]=i+1; } return max; } public int lengthOfLongestSubstring4(String s) { int len = s.length(); HashSet<Character> set = new HashSet<>(); int i=0,j=0,max = 0; while(i<len&&j<len){ if(!set.contains(s.charAt(i))){ set.add(s.charAt(i++)); max = Math.max(max,i-j); } else{ set.remove(s.charAt(j++)); } } return max; } public static void main(String [] args){ System.out.println(LongestContinousSubstring2("abcabcdbb")); } public static String LongestContinousSubstring2(String str){ int low = 0 ; //List<String> list = new ArrayList<String>(); String result=""; if(str.length() == 0) return ""; HashMap<Character,Integer> map = new HashMap<>(); for(int i=0 ; i < str.length() ; i++){ if(map.get(str.charAt(i))!= null){ if( i - low> result.length()){ result = str.substring(low,i); } low = Math.max(map.get(str.charAt(i)) +1,low); } map.put(str.charAt(i),i); } return result; } //if you want all the strings (list) of the same size to be printed public static List<String> LongestContinousSubstringList(String str){ int low = 0 ; List<String> list = new ArrayList<String>(); if(str.length() == 0) return list; String result =""; HashMap<Character,Integer> map = new HashMap<>(); for(int i=0 ; i < str.length() ; i++){ if(map.get(str.charAt(i))!= null){ if( (i) - low > result.length()){ list.clear(); //result = str.substring(low,i); list.add(str.substring(low,i)); } else if((i) - low == result.length()){ list.add(str.substring(low,i)); } low = Math.max(map.get(str.charAt(i)) +1,low); } map.put(str.charAt(i),i); } return list; } } <file_sep>/JumpGame.java package LeetcodePrograms; /** * Created by rkhurana on 1/29/19. */ public class JumpGame { public static int jump (int A[]){ if(A.length <=1 ) return 0; int ladder = A[0]; //keep track of the ladder at each step int stairs = A[0]; //keep track of stairs at each step int jump = 1; for(int level = 1; level < A.length ; level++){ if(level == A.length - 1) return jump; if(level + A[level] > ladder) ladder = level + A[level]; //build up the ladder stairs--; //use up the stairs if(stairs ==0){ jump++; stairs = ladder - level; } } return jump; } public static void main(String []args){ int a[]={2,3,1,1,4}; System.out.print(jump(a)); } }
67071b4e6393de10b8549236753fc36036e0df6a
[ "Java" ]
2
Java
badaljain/LeetcodeQuestions
b7bb53456605699aaf99fee1cc135473324fcfda
a79bf4f3fc12c4ad6854e959f778e0daf7e531d3
refs/heads/master
<file_sep>#ifndef AIDP_APP_METRICS_HPP_ #define AIDP_APP_METRICS_HPP_ #include <adbase/Utility.hpp> #include <adbase/Logging.hpp> #include <adbase/Metrics.hpp> #include <adbase/Lua.hpp> #include <unordered_map> #include "AdbaseConfig.hpp" namespace app { class Metrics : public std::enable_shared_from_this<Metrics> { public: Metrics(); ~Metrics(); void bindClass(adbase::lua::Engine* engine); std::weak_ptr<Metrics> getMetrics(); std::weak_ptr<adbase::metrics::Counter> buildCounter(const std::string& moduleName, const std::string& metricName); std::weak_ptr<adbase::metrics::Meters> buildMeters(const std::string& moduleName, const std::string& metricName); std::weak_ptr<adbase::metrics::Histograms> buildHistograms(const std::string& moduleName, const std::string& metricName, uint32_t interval); std::weak_ptr<adbase::metrics::Timers> buildTimers(const std::string& moduleName, const std::string& metricName, uint32_t interval); std::weak_ptr<adbase::metrics::Timer> getTimer(); private: const std::string getKey(const std::string& moduleName, const std::string& metricName); }; } #endif <file_sep>#include "Http.hpp" // {{{ Http::Http() Http::Http(AdServerContext* context, adbase::http::Server* http) : _context(context), _http(http) { } // }}} // {{{ Http::~Http() Http::~Http() { ADSERVER_HTTP_STOP(Server); ADSERVER_HTTP_STOP(Index); } // }}} // {{{ void Http::addController() void Http::addController() { ADSERVER_HTTP_ADD_CONTROLLER(Server); ADSERVER_HTTP_ADD_CONTROLLER(Index); } // }}} // {{{ std::unordered_map<std::string, std::string> Http::rewrite() std::unordered_map<std::string, std::string> Http::rewrite() { std::unordered_map<std::string, std::string> urls; return urls; } // }}} <file_sep>#include "ConsumerOut.hpp" #include "App/Message.hpp" namespace aims { namespace kafka { // {{{ ConsumerOut::ConsumerOut() ConsumerOut::ConsumerOut(AimsContext* context) : _context(context) { } // }}} // {{{ ConsumerOut::~ConsumerOut() ConsumerOut::~ConsumerOut() { } // }}} // {{{ void ConsumerOut::pull() bool ConsumerOut::pull(const std::string& topicName, int partId, uint64_t offset, const adbase::Buffer& data) { app::MessageItem item; item.partId = partId; item.offset = offset; item.message = data; item.topicName = topicName; item.tryNum = 0; if (_context->message != nullptr) { return _context->message->push(item); } return false; } // }}} // {{{ void ConsumerOut::stat() void ConsumerOut::stat(adbase::kafka::ConsumerBatch*, const std::string& stats) { LOG_INFO << "Stats:" << stats.substr(0, 1024); } // }}} } } <file_sep>#include "Storage.hpp" namespace app { // {{{ Storage::Storage() Storage::Storage(AdbaseConfig* configure): _configure(configure) { } // }}} // {{{ Storage::~Storage() Storage::~Storage() { } // }}} // {{{ void Storage::init() void Storage::init() { adbase::metrics::Metrics::buildGauges("storage", "incrmap.size", 1000, [this](){ std::lock_guard<std::mutex> lk(_mut); return _incrMap.size(); }); adbase::metrics::Metrics::buildGauges("storage", "keyvalmap.size", 1000, [this](){ std::lock_guard<std::mutex> lk(_mut); return _keyValMap.size(); }); adbase::metrics::Metrics::buildGauges("storage", "ttlmap.size", 1000, [this](){ std::lock_guard<std::mutex> lk(_mut); return _ttlMap.size(); }); } // }}} // {{{ void Storage::clear() void Storage::clear() { std::lock_guard<std::mutex> lk(_mut); adbase::Timestamp current = adbase::Timestamp::now(); std::list<std::string> deleteKeys; for (auto &t : _ttlMap) { if (t.second < current) { continue; } deleteKeys.push_back(t.first); } for (auto &t : deleteKeys) { if (_keyValMap.find(t) != _keyValMap.end()) { _keyValMap.erase(t); } if (_ttlMap.find(t) != _ttlMap.end()) { _ttlMap.erase(t); } } } // }}} // {{{ void Storage::bindClass() void Storage::bindClass(adbase::lua::Engine* engine) { adbase::lua::BindingClass<Storage> storage("storage", "aidp", engine->getLuaState()); adbase::lua::BindingNamespace storageCs = storage.getOwnerNamespace(); typedef std::function<std::weak_ptr<Storage>()> GetStorage; GetStorage storageFn = std::bind(&Storage::getStorage, this); storageCs.addMethod("storage", storageFn); storage.addMethod<bool, Storage, std::string, std::string>("set", &Storage::set); storage.addMethod<bool, Storage, std::string, std::string, int>("set", &Storage::set); storage.addMethod("incr", &Storage::incr); storage.addMethod("decr", &Storage::decr); storage.addMethod("get", &Storage::get); storage.addMethod("exists", &Storage::exists); storage.addMethod("del", &Storage::deleteKey); } // }}} // {{{ std::weak_ptr<Storage> Storage::getStorage() std::weak_ptr<Storage> Storage::getStorage() { return shared_from_this(); } // }}} // {{{ bool Storage::set() bool Storage::set(const std::string key, const std::string value) { std::lock_guard<std::mutex> lk(_mut); _keyValMap[key] = value; return true; } // }}} // {{{ bool Storage::set() bool Storage::set(const std::string key, const std::string value, int ttl) { std::lock_guard<std::mutex> lk(_mut); _keyValMap[key] = value; _ttlMap[key] = adbase::addTime(adbase::Timestamp::now(), ttl); return true; } // }}} // {{{ int64_t Storage::incr() int64_t Storage::incr(const std::string key, int step) { std::lock_guard<std::mutex> lk(_mut); if (_incrMap.find(key) == _incrMap.end()) { _incrMap[key] = step; } else { _incrMap[key] += step; } return _incrMap[key]; } // }}} // {{{ int64_t Storage::decr() int64_t Storage::decr(const std::string key, int step) { std::lock_guard<std::mutex> lk(_mut); if (_incrMap.find(key) == _incrMap.end()) { _incrMap[key] = -step; } else { _incrMap[key] -= step; } return _incrMap[key]; } // }}} // {{{ const std::string Storage::get() const std::string Storage::get(const std::string key) { std::lock_guard<std::mutex> lk(_mut); if (_keyValMap.find(key) != _keyValMap.end()) { return _keyValMap[key]; } if (_incrMap.find(key) != _incrMap.end()) { return std::to_string(_incrMap[key]); } return ""; } // }}} // {{{ bool Storage::exists() bool Storage::exists(const std::string key) { std::lock_guard<std::mutex> lk(_mut); if (_keyValMap.find(key) != _keyValMap.end()) { return true; } if (_incrMap.find(key) != _incrMap.end()) { return true; } return false; } // }}} // {{{ bool Storage::deleteKey() bool Storage::deleteKey(const std::string key) { std::lock_guard<std::mutex> lk(_mut); if (_keyValMap.find(key) != _keyValMap.end()) { _keyValMap.erase(key); } if (_ttlMap.find(key) != _ttlMap.end()) { _ttlMap.erase(key); } if (_incrMap.find(key) != _incrMap.end()) { _incrMap.erase(key); } return true; } // }}} } <file_sep># AIDP (Data Process) [中文文档](README_CN.md) AIDP is responsible for a series of messages such as message queue consumption. After getting the message, the specific processing is handled by Lua script. The developer can customize the processing of the consumption queue, and the framework provides http server service. You can use the Lua script to customize the http API Interface, and then consumption message logic and http server between the framework provides a simple Key-Val storage structure for data sharing. The figure is the structure of the AIDP data processing framework: ![structure](docs/images/aidp_struct.png) AIDP invoke flow: ![data process flow](docs/images/aidp_struct_pro.png) ### Why use lua script customize ? Most of the application scenarios for the message queue are back-end with a consumer module for data processing, the final data stored in a DB, and finally through the RPC interface for the user use. Some application scenarios data process logic may be particularly simple, but most of the language is very complicated for Kafka's consumption (Kafka consumption logic) When the specific data process logic to increase the development costs, AIDP through C++ this general development model abstract package, in order to increase the custom through the embedded Lua scripting language. To complete the custom part of the logic. AIDP is a compromise between development difficulty, cost and flexibility. Can meet a large number of data processing demand ### Quick Start #### RPM install RPM currently support centos7.x version, other versions will be uploaded, there are other system version of the demand can add the issue #### Complie install First, install AIDP depend package adbase, Installation method refer : https://nmred.gitbooks.io/adbase/content/en/basic/install.html Second, complie and install aidp ``` git clone git@github.com:weiboad/aidp.git cd aidp ./cmake.sh cd build make make install ``` #### Example For example, using aidp get kafka cluster topic `test` data write to the local disk, and statistics the number of messages, the final number of messages through the http api interface can be obtained. In the installed aidp directory modify the configuration `conf/system.ini`, configure kafka consumption calls lua script path, by modifying `consumer` section `scriptName` field. Set up on the lua script can be configured to handle the script as follows: ```lua -- -- -- This sctipt process message write to the local disk and statistics the number of messages store in local storage -- -- local obj = aidp.message.get() local filename = os.date('%Y-%m-%d-%H') .. '.log' local files = {}; -- get storage object local storage = aidp.storage() for k,v in pairs(obj) do if #v == 3 then if files[v[2]] == nil then files[v[2]] = io.open(v[2]..filename, 'a+'); files[v[2]]:setvbuf('full') end files[v[2]]:write(v[3]..'\n') -- store number of message in local storage storage:incr(v[2] .. ':message_size', 1) end end for k,v in pairs(files) do v:flush() v:close() end ``` Modify the configuration file `http` section `scriptName` field set http interface call lua script path, lua script processing logic as follows: ```lua -- get a topic number of has process message local request = aidp.http.request(); local topic_name = request:get_query('t') local response = aidp.http.response(); local storage = aidp.storage() response:set_content(topic_name .. ':message_size ' .. storage:get(topic_name .. ':message_size')); ``` Start aidp service: ``` cd /usr/local/adinf/aidp/bin ./aidp -c ../conf/system.ini ``` ### Message Consumer The message consumption module is responsible for getting the message from Kafka and invoking the Lua consumption script after getting the message. The Lua script can invoke the `aidp.message.get()` function to get the message #### aidp.message.get Get kafka message Params:None Scope:Only the message consumption script valid Return:Data structure is follow: ```lua -- { -- { -- id, -- topicName, -- messageBody -- }, -- { -- id, -- topicName, -- messageBody -- }, -- { -- id, -- topicName, -- messageBody -- } -- } ``` ```lua --This sctipt process message write to the local disk -- -- get message local obj = aidp.message.get() local filename = os.date('%Y-%m-%d-%H') .. '.log' local files = {}; local storage = aidp.storage() for k,v in pairs(obj) do if #v == 3 then if files[v[2]] == nil then files[v[2]] = io.open(v[2]..filename, 'a+'); files[v[2]]:setvbuf('full') end files[v[2]]:write(v[3]..'\n') storage:incr(v[2] .. ':message_size', 1) end end for k,v in pairs(files) do v:flush() v:close() end ``` ### Http Server Provide HTTP interface Lua custom development, for the Lua side to provide Request, Response object, through the Request to obtain the request data, and through the Lua script. The final response data will be customized through the Response interface, Request and Response object methods only in the Http Server processing script is valid for the Message consumer processing script is invalid #### Request | Method | Method Type | Description | |-----|-----|-----| | aidp.http.request() | Static | Construct request object | | request:get_uri() | Object Method | Get request URI | | request:get_remote_address() | Object Method | Get remote address | | request:get_post_data() | Object Method | Get origin post data | | request:get_post([key]) | Object Method | Get POST Form-Data type data | | request:get_query(key) | Object Method | Get GET method data | | request:get_header(key) | Object Method | Get Header val | | request:get_location() | Object Method | Get location | | request:get_method() | Object Method | Get request method, will return enum type METHOD_GET、METHOD_POST、METHOD_OTHER | #### Response | Method | Method Type | Description | |-----|-----|-----| | aidp.http.response() | Static | Construct response object | | response:set_header(key, val) | Object Method | Set response header, if already exists will cover header | | response:add_header(key, val) | Object Method | Add response header | | response:set_content(body) | Object Method | Set response body | | response:append_content(body) | Object Method | Append response body | | response:get_code() | Object Method | Get response http code | | response:set_body_size(size) | Object Method | Set response body size | #### Sample ```lua local request = aidp.http.request(); local topic_name = request:get_query('t') local response = aidp.http.response(); local storage = aidp.storage() response:set_content(topic_name .. ':message_size ' .. storage:get(topic_name .. ':message_size')); ``` ### Simple Storage Storage provides a simple stand-alone storage similar to Redis's key-val structure, helping to implement some data cache storage logic. The following Lua Api is common in the Http lua script and the Message Consumer valid. | Method | Method Type | Description | |-----|-----|-----| | aidp.storage() | Static | Construct storage object | | storage:set(key, val, [ttl]) | Object Method | Set the data in the storage, if set ttl is expired after the key will be recovered, ttl units is second | | storage:incr(key, step) | Object Method | Increment val step | | storage:decr(key, step) | Object Method | Decrement val step | | storage:get(key) | Object Method | Get value | | storage:exists(key) | Object Method | Get whether a key exists | | storage:del(key) | Object Method | Delete a key | <file_sep>#ifndef AIDP_APP_STORAGE_HPP_ #define AIDP_APP_STORAGE_HPP_ #include <adbase/Utility.hpp> #include <adbase/Logging.hpp> #include <adbase/Metrics.hpp> #include <adbase/Lua.hpp> #include <unordered_map> #include <mutex> #include "AdbaseConfig.hpp" namespace app { class Storage : public std::enable_shared_from_this<Storage> { public: Storage(AdbaseConfig* configure); ~Storage(); void init(); // key - value bool set(const std::string key, const std::string value); bool set(const std::string key, const std::string value, int ttl); int64_t incr(const std::string key, int step); int64_t decr(const std::string key, int step); const std::string get(const std::string key); bool deleteKey(const std::string key); bool exists(const std::string key); void clear(); void bindClass(adbase::lua::Engine* engine); std::weak_ptr<Storage> getStorage(); private: AdbaseConfig *_configure; mutable std::mutex _mut; std::unordered_map<std::string, int> _incrMap; std::unordered_map<std::string, std::string> _keyValMap; std::unordered_map<std::string, adbase::Timestamp> _ttlMap; }; } #endif <file_sep>cmake_minimum_required(VERSION 2.6) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src) INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/thridpart) LINK_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) SET(CMAKE_SOURCE_DIR .) SET(CMAKE_MODULE_PATH ${CMAKE_ROOT}/Modules ${CMAKE_SOURCE_DIR}/cmake/Modules ${PROJECT_SOURCE_DIR}/Modules) configure_file ( "${PROJECT_SOURCE_DIR}/src/Version.hpp.in" "${PROJECT_SOURCE_DIR}/src/Version.hpp" ) SET(AIDP_SRC aidp.cpp BootStrap.cpp App.cpp AdServer.cpp Http.cpp Http/HttpInterface.cpp Http/Server.cpp Http/Index.cpp McProcessor.cpp HeadProcessor.cpp Aims.cpp Aims/Kafka/ConsumerOut.cpp Timer.cpp App/Message.cpp App/Storage.cpp App/Metrics.cpp ) ADD_EXECUTABLE(aidp ${AIDP_SRC}) # adbase FIND_PACKAGE( libadbase REQUIRED) MARK_AS_ADVANCED( LIBADBASE_INCLUDE_DIR LIBADBASE_LIBRARIES ) IF (LIBADBASE_INCLUDE_DIR AND LIBADBASE_LIBRARIES) MESSAGE(STATUS "Found libadbase libraries") INCLUDE_DIRECTORIES(${LIBADBASE_INCLUDE_DIR}) MESSAGE( ${LIBADBASE_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBADBASE_LIBRARIES} ) ELSE (LIBADBASE_INCLUDE_DIR AND LIBADBASE_LIBRARIES) MESSAGE(FATAL_ERROR "Failed to find libadbase libraries") ENDIF (LIBADBASE_INCLUDE_DIR AND LIBADBASE_LIBRARIES) # adbase_kafka FIND_PACKAGE( libadbase_kafka REQUIRED) MARK_AS_ADVANCED( LIBADBASE_KAFKA_INCLUDE_DIR LIBADBASE_KAFKA_LIBRARIES ) IF (LIBADBASE_KAFKA_INCLUDE_DIR AND LIBADBASE_KAFKA_LIBRARIES) MESSAGE(STATUS "Found libadbase_kafka libraries") INCLUDE_DIRECTORIES(${LIBADBASE_KAFKA_INCLUDE_DIR}) MESSAGE( ${LIBADBASE_KAFKA_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBADBASE_KAFKA_LIBRARIES} ) ELSE (LIBADBASE_KAFKA_INCLUDE_DIR AND LIBADBASE_KAFKA_LIBRARIES) MESSAGE(FATAL_ERROR "Failed to find libadbase_kafka libraries") ENDIF (LIBADBASE_KAFKA_INCLUDE_DIR AND LIBADBASE_KAFKA_LIBRARIES) # rdkafka++ FIND_PACKAGE( librdkafka REQUIRED) MARK_AS_ADVANCED( LIBRDKAFKA_INCLUDE_DIR LIBRDKAFKA_LIBRARIES ) IF (LIBRDKAFKA_INCLUDE_DIR AND LIBRDKAFKA_LIBRARIES) MESSAGE(STATUS "Found librdkafka libraries") INCLUDE_DIRECTORIES(${LIBRDKAFKA_INCLUDE_DIR}) MESSAGE( ${LIBRDKAFKA_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBRDKAFKA_CPP_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBRDKAFKA_LIBRARIES} ) ELSE (LIBRDKAFKA_INCLUDE_DIR AND LIBRDKAFKA_LIBRARIES) MESSAGE(FATAL_ERROR "Failed to find librdkafka libraries") ENDIF (LIBRDKAFKA_INCLUDE_DIR AND LIBRDKAFKA_LIBRARIES) # adbase_lua FIND_PACKAGE( libadbase_lua REQUIRED) MARK_AS_ADVANCED( LIBADBASE_LUA_INCLUDE_DIR LIBADBASE_LUA_LIBRARIES ) IF (LIBADBASE_LUA_INCLUDE_DIR AND LIBADBASE_LUA_LIBRARIES) MESSAGE(STATUS "Found libadbase_kafka libraries") INCLUDE_DIRECTORIES(${LIBADBASE_LUA_INCLUDE_DIR}) MESSAGE( ${LIBADBASE_LUA_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBADBASE_LUA_LIBRARIES} ) ELSE (LIBADBASE_LUA_INCLUDE_DIR AND LIBADBASE_LUA_LIBRARIES) MESSAGE(FATAL_ERROR "Failed to find libadbase_lua libraries") ENDIF (LIBADBASE_LUA_INCLUDE_DIR AND LIBADBASE_LUA_LIBRARIES) # liblua FIND_PACKAGE( liblua REQUIRED) MARK_AS_ADVANCED( LIBLUA_INCLUDE_DIR LIBLUA_LIBRARIES ) IF (LIBLUA_INCLUDE_DIR AND LIBLUA_LIBRARIES) MESSAGE(STATUS "Found liblua libraries") INCLUDE_DIRECTORIES(${LIBLUA_INCLUDE_DIR}) MESSAGE( ${LIBLUA_LIBRARIES} ) TARGET_LINK_LIBRARIES(aidp ${LIBLUA_LIBRARIES} ) ELSE (LIBLUA_INCLUDE_DIR AND LIBLUA_LIBRARIES) MESSAGE(FATAL_ERROR "Failed to find liblua libraries") ENDIF (LIBLUA_INCLUDE_DIR AND LIBLUA_LIBRARIES) # pthread #FIND_PACKAGE( libpthread REQUIRED) #MARK_AS_ADVANCED( #LIBPTHREAD_INCLUDE_DIR #LIBPTHREAD_LIBRARIES #) #IF (LIBPTHREAD_INCLUDE_DIR AND LIBPTHREAD_LIBRARIES) # MESSAGE(STATUS "Found libpthread libraries") # INCLUDE_DIRECTORIES(${LIBPTHREAD_INCLUDE_DIR}) # MESSAGE( ${LIBPTHREAD_LIBRARIES} ) # TARGET_LINK_LIBRARIES(aidp ${LIBPTHREAD_LIBRARIES} ) #ELSE (LIBPTHREAD_INCLUDE_DIR AND LIBPTHREAD_LIBRARIES) # MESSAGE(FATAL_ERROR "Failed to find libpthread libraries") #ENDIF (LIBPTHREAD_INCLUDE_DIR AND LIBPTHREAD_LIBRARIES) TARGET_LINK_LIBRARIES(aidp libevent.a pthread rt dl libz.a) INSTALL(TARGETS aidp RUNTIME DESTINATION bin) <file_sep>#include "Message.hpp" #include "Storage.hpp" #include "Metrics.hpp" #include <fstream> #include <adbase/Lua.hpp> namespace app { thread_local std::unique_ptr<adbase::lua::Engine> messageLuaEngine; thread_local std::unordered_map<std::string, MessageItem> messageLuaMessages; thread_local size_t messageLuaMessagesSize; // {{{ Message::Message() Message::Message(AdbaseConfig* configure, Storage* storage, Metrics* metrics): _configure(configure), _storage(storage), _metrics(metrics), _isRunning(false) { } // }}} // {{{ Message::~Message() Message::~Message() { for(auto &t : _queues) { if (t.second != nullptr) { delete t.second; t.second = nullptr; } } } // }}} // {{{ void Message::start() void Message::start() { _threadNumber = _configure->consumerThreadNumber; _isRunning = true; _luaProcessTimer = adbase::metrics::Metrics::buildTimers("message", "process", 60000); for (int i = 0; i < _configure->consumerThreadNumber; i++) { _queues[i] = new MessageQueue; std::unordered_map<std::string, std::string> tags; tags["queue_id"] = std::to_string(i); adbase::metrics::Metrics::buildGaugesWithTag("message", "queue.size", tags, 1000, [this, i](){ return _queues[i]->getSize(); }); ThreadPtr callThread(new std::thread(std::bind(&Message::call, this, std::placeholders::_1), i), &Message::deleteThread); LOG_DEBUG << "Create call lua thread success"; Threads.push_back(std::move(callThread)); } std::string messageName = _configure->messageDir + "/message_error"; _logger = std::shared_ptr<adbase::AsyncLogging>(new adbase::AsyncLogging(messageName, _configure->messageRollSize)); _logger->start(); } // }}} // {{{ void Message::stop() void Message::stop() { for (auto &t : _queues) { MessageItem newItem; newItem.mask = 0x01; newItem.partId = 0; newItem.offset = 0; newItem.tryNum = 0; t.second->push(newItem); } _isRunning = false; std::unique_lock<std::mutex> lk(_mut); _dataCond.wait(lk, [this]{return (_threadNumber == 0);}); } // }}} // {{{ void Message::reload() void Message::reload() { } // }}} // {{{ void Message::call() void Message::call(int i) { // 初始化 lua 引擎 initLua(); std::unordered_map<std::string, std::string> tags; tags["map_id"] = std::to_string(i); adbase::metrics::Metrics::buildGaugesWithTag("message", "lua.message.map", tags, 1000, [this, i](){ return messageLuaMessagesSize; }); int batchNum = _configure->consumerBatchNumber; while(_isRunning) { MessageItem item; _queues[i]->waitPop(item); if (item.mask == 0x01) { break; } addLuaMessage(item); if (static_cast<int>(_queues[i]->getSize()) > batchNum) { bool ret = false; bool exit = false; do { MessageItem itemBatch; ret = _queues[i]->tryPop(itemBatch); if (item.mask == 0x01) { exit = true; continue; } if (!ret) { break; } addLuaMessage(itemBatch); batchNum--; } while(batchNum > 0); if (exit) { break; } } callMessage(); } for (auto &t : messageLuaMessages) { saveMessage(t.second); } while(_queues[i]->getSize()) { MessageItem item; bool ret = _queues[i]->tryPop(item); if (!ret) { break; } saveMessage(item); } std::unique_lock<std::mutex> lk(_mut); _threadNumber--; _dataCond.notify_all(); } // }}} // {{{ void Message::initLua() void Message::initLua() { std::unique_ptr<adbase::lua::Engine> engine(new adbase::lua::Engine()); messageLuaEngine = std::move(engine); messageLuaEngine->init(); messageLuaEngine->addSearchPath(_configure->luaScriptPath, true); adbase::lua::BindingClass<app::Message> clazz("message", "aidp", messageLuaEngine->getLuaState()); typedef std::function<MessageToLua()> GetMessageFn; GetMessageFn getMessageFn = std::bind(&app::Message::getMessage, this); clazz.addMethod("get", getMessageFn); typedef std::function<int (std::list<std::string>)> RollBackMessageFn; RollBackMessageFn rollbackFn = std::bind(&app::Message::rollback, this, std::placeholders::_1); clazz.addMethod("rollback", rollbackFn); _storage->bindClass(messageLuaEngine.get()); _metrics->bindClass(messageLuaEngine.get()); } // }}} // {{{ void Message::callMessage() void Message::callMessage() { adbase::metrics::Timer timer; timer.start(); bool isCall = messageLuaEngine->runFile(_configure->consumerScriptName.c_str()); if (!isCall) { for (auto &t : messageLuaMessages) { saveMessage(t.second); } } messageLuaMessages.clear(); messageLuaMessagesSize = messageLuaMessages.size(); double time = timer.stop(); if (_luaProcessTimer != nullptr) { _luaProcessTimer->setTimer(time); } } // }}} // {{{ MessageToLua Message::getMessage() MessageToLua Message::getMessage() { MessageToLua ret; for (auto &t : messageLuaMessages) { std::list<std::string> item; std::string id = convertKey(t.second); adbase::Buffer tmp = t.second.message; std::string message = tmp.retrieveAllAsString(); item.push_back(id); item.push_back(t.second.topicName); item.push_back(message); ret.push_back(item); } return ret; } // }}} // {{{ int Message::rollback() int Message::rollback(std::list<std::string> ids) { int count = 0; for (auto &t : ids) { if (messageLuaMessages.find(t) != messageLuaMessages.end()) { MessageItem item = messageLuaMessages[t]; saveMessage(item); count++; } } messageLuaMessagesSize = messageLuaMessages.size(); return count; } // }}} // {{{ bool Message::push() bool Message::push(MessageItem& item) { int processQueueNum = item.partId % _configure->consumerThreadNumber; if (item.message.readableBytes()) { _queues[processQueueNum]->push(item); } return true; } // }}} // {{{ bool Message::queueCheck() bool Message::queueCheck() { for(auto &t : _queues) { if (static_cast<int>(t.second->getSize()) > _configure->consumerMaxNumber) { return false; } } return true; } // }}} // {{{ void Message::deleteThread() void Message::deleteThread(std::thread *t) { t->join(); delete t; } // }}} // {{{ void Message::addLuaMessage() void Message::addLuaMessage(MessageItem& item) { messageLuaMessages[convertKey(item)] = item; messageLuaMessagesSize = messageLuaMessages.size(); } // }}} // {{{ const std::string Message::convertKey() const std::string Message::convertKey(MessageItem& item) { std::string key = std::to_string(item.partId) + "_" + std::to_string(item.offset) + "_" + item.topicName; return key; } // }}} // {{{ void Message::serialize() void Message::serialize(adbase::Buffer& buffer, MessageItem& item) { buffer.appendInt32(item.partId); buffer.appendInt32(item.tryNum); buffer.appendInt32(static_cast<uint32_t>(item.topicName.size())); buffer.append(item.topicName); size_t messageSize = item.message.readableBytes(); buffer.appendInt32(static_cast<uint32_t>(messageSize)); buffer.append(item.message.peek(), messageSize); } // }}} // {{{ void Message::saveMessage() void Message::saveMessage(MessageItem& item) { if (item.tryNum < _configure->consumerTryNumber) { int processQueueNum = item.partId % _configure->consumerThreadNumber; item.tryNum = item.tryNum + 1; _queues[processQueueNum]->push(item); } else { adbase::Buffer buffer; serialize(buffer, item); if (_logger) { _logger->append(buffer.peek(), static_cast<int>(buffer.readableBytes())); } if (_errorMessageMeter.find(item.topicName) == _errorMessageMeter.end()) { std::unordered_map<std::string, std::string> tags; tags["topic_name"] = item.topicName; _errorMessageMeter[item.topicName] = adbase::metrics::Metrics::buildMetersWithTag("message", "error", tags); } if (_errorMessageMeter[item.topicName] != nullptr) { _errorMessageMeter[item.topicName]->mark(); } } } // }}} } <file_sep>#include "Metrics.hpp" namespace app { thread_local std::unordered_map<std::string, std::shared_ptr<adbase::metrics::Counter>> metricsCounters; thread_local std::unordered_map<std::string, std::shared_ptr<adbase::metrics::Meters>> metricsMeters; thread_local std::unordered_map<std::string, std::shared_ptr<adbase::metrics::Histograms>> metricsHistograms; thread_local std::unordered_map<std::string, std::shared_ptr<adbase::metrics::Timers>> metricsTimers; thread_local std::shared_ptr<adbase::metrics::Timer> metricsTimer; // {{{ Metrics::Metrics() Metrics::Metrics() { } // }}} // {{{ Metrics::~Metrics() Metrics::~Metrics() { } // }}} // {{{ void Metrics::bindClass() void Metrics::bindClass(adbase::lua::Engine* engine) { // metrics adbase::lua::BindingClass<Metrics> metrics("metrics", "aidp", engine->getLuaState()); adbase::lua::BindingNamespace metricsCs = metrics.getOwnerNamespace(); typedef std::function<std::weak_ptr<Metrics>()> GetMetrics; GetMetrics metricsFn = std::bind(&Metrics::getMetrics, this); metricsCs.addMethod("metrics", metricsFn); metrics.addMethod("counter", &Metrics::buildCounter); metrics.addMethod("meters", &Metrics::buildMeters); metrics.addMethod("histograms", &Metrics::buildHistograms); metrics.addMethod("timers", &Metrics::buildTimers); metrics.addMethod("timer", &Metrics::getTimer); // counter adbase::lua::BindingClass<adbase::metrics::Counter> counter("counter", "aidp", engine->getLuaState()); counter.addMethod("module_name", &adbase::metrics::Counter::getModuleName); counter.addMethod("metric_name", &adbase::metrics::Counter::getMetricName); counter.addMethod("add", &adbase::metrics::Counter::add); counter.addMethod("dec", &adbase::metrics::Counter::dec); // meters adbase::lua::BindingClass<adbase::metrics::Meters> meters("meters", "aidp", engine->getLuaState()); meters.addMethod("module_name", &adbase::metrics::Meters::getModuleName); meters.addMethod("metric_name", &adbase::metrics::Meters::getMetricName); meters.addMethod("mark", &adbase::metrics::Meters::mark); meters.addMethod("get_count", &adbase::metrics::Meters::getCounter); LOG_INFO << "TOP:" << lua_gettop(engine->getLuaState()); // histograms adbase::lua::BindingClass<adbase::metrics::Histograms> histograms("histograms", "aidp", engine->getLuaState()); histograms.addMethod("module_name", &adbase::metrics::Histograms::getModuleName); histograms.addMethod("metric_name", &adbase::metrics::Histograms::getMetricName); histograms.addMethod("update", &adbase::metrics::Histograms::update); // timers adbase::lua::BindingClass<adbase::metrics::Timers> timers("timers", "aidp", engine->getLuaState()); timers.addMethod("module_name", &adbase::metrics::Timers::getModuleName); timers.addMethod("metric_name", &adbase::metrics::Timers::getMetricName); timers.addMethod("set_timer", &adbase::metrics::Timers::setTimer); // timer adbase::lua::BindingClass<adbase::metrics::Timer> timer("timer", "aidp", engine->getLuaState()); timer.addMethod("start", &adbase::metrics::Timer::start); timer.addMethod("stop", &adbase::metrics::Timer::stop); } // }}} // {{{ std::weak_ptr<Metrics> Metrics::getMetrics() std::weak_ptr<Metrics> Metrics::getMetrics() { return shared_from_this(); } // }}} // {{{ std::weak_ptr<adbase::metrics::Timer> Metrics::getTimer() std::weak_ptr<adbase::metrics::Timer> Metrics::getTimer() { if (metricsTimer == false) { metricsTimer = std::shared_ptr<adbase::metrics::Timer>(new adbase::metrics::Timer()); } return metricsTimer; } // }}} // {{{ std::weak_ptr<adbase::metrics::Counter> Metrics::buildCounter() std::weak_ptr<adbase::metrics::Counter> Metrics::buildCounter(const std::string& moduleName, const std::string& metricName) { adbase::metrics::Counter* counter = adbase::metrics::Metrics::buildCounter(moduleName, metricName); auto sharedCounter = std::shared_ptr<adbase::metrics::Counter>(counter, [](adbase::metrics::Counter*) { LOG_INFO << "delete Counter";}); std::string key = getKey(moduleName, metricName); metricsCounters[key] = sharedCounter; return metricsCounters[key]; } // }}} // {{{ std::weak_ptr<adbase::metrics::Meters> Metrics::buildMeters() std::weak_ptr<adbase::metrics::Meters> Metrics::buildMeters(const std::string& moduleName, const std::string& metricName) { adbase::metrics::Meters* meters = adbase::metrics::Metrics::buildMeters(moduleName, metricName); auto sharedMeters = std::shared_ptr<adbase::metrics::Meters>(meters, [](adbase::metrics::Meters*) { LOG_INFO << "delete meters";}); std::string key = getKey(moduleName, metricName); metricsMeters[key] = sharedMeters; return metricsMeters[key]; } // }}} // {{{ std::weak_ptr<adbase::metrics::Histograms> Metrics::buildHistograms() std::weak_ptr<adbase::metrics::Histograms> Metrics::buildHistograms(const std::string& moduleName, const std::string& metricName, uint32_t interval) { adbase::metrics::Histograms* histograms = adbase::metrics::Metrics::buildHistograms(moduleName, metricName, interval); auto sharedHistograms = std::shared_ptr<adbase::metrics::Histograms>(histograms, [](adbase::metrics::Histograms*) { LOG_INFO << "delete histograms";}); std::string key = getKey(moduleName, metricName); metricsHistograms[key] = sharedHistograms; return metricsHistograms[key]; } // }}} // {{{ std::weak_ptr<adbase::metrics::Timers> Metrics::buildHistograms() std::weak_ptr<adbase::metrics::Timers> Metrics::buildTimers(const std::string& moduleName, const std::string& metricName, uint32_t interval) { adbase::metrics::Timers* timers = adbase::metrics::Metrics::buildTimers(moduleName, metricName, interval); auto sharedTimers = std::shared_ptr<adbase::metrics::Timers>(timers, [](adbase::metrics::Timers*) { LOG_INFO << "delete timers";}); std::string key = getKey(moduleName, metricName); metricsTimers[key] = sharedTimers; return metricsTimers[key]; } // }}} // {{{ const std::string Metrics::getKey() const std::string Metrics::getKey(const std::string& moduleName, const std::string& metricName) { std::string result = moduleName; result.append(1, 26); result.append(metricName); return result; } // }}} } <file_sep>#ifndef AIDP_APP_MESSAGE_HPP_ #define AIDP_APP_MESSAGE_HPP_ #include <adbase/Utility.hpp> #include <adbase/Logging.hpp> #include <adbase/Lua.hpp> #include <adbase/Metrics.hpp> #include <unordered_map> #include <condition_variable> #include <mutex> #include <thread> #include <list> #include <limits.h> #include "AdbaseConfig.hpp" namespace app { class Storage; class Metrics; // message queue typedef struct MessageItem { int partId; int mask; // 0x00 normal, 0x01 stop uint64_t offset; int tryNum; std::string topicName; adbase::Buffer message; } MessageItem; typedef adbase::Queue<MessageItem> MessageQueue; typedef std::list<std::list<std::string>> MessageToLua; class Message { public: Message(AdbaseConfig* configure, Storage* storage, Metrics* metrics); ~Message(); void start(); void stop(); void reload(); void call(int i); MessageToLua getMessage(); int rollback(std::list<std::string> ids); bool push(MessageItem& item); bool queueCheck(); static void deleteThread(std::thread *t); private: mutable std::mutex _mut; std::condition_variable _dataCond; typedef std::unique_ptr<std::thread, decltype(&Message::deleteThread)> ThreadPtr; typedef std::vector<ThreadPtr> ThreadPool; ThreadPool Threads; int _threadNumber; AdbaseConfig *_configure; Storage* _storage; Metrics* _metrics; bool _isRunning; std::unordered_map<int, MessageQueue*> _queues; std::shared_ptr<adbase::AsyncLogging> _logger; std::unordered_map<std::string, adbase::metrics::Meters*> _errorMessageMeter; adbase::metrics::Timers* _luaProcessTimer; void callMessage(); void initLua(); void addLuaMessage(MessageItem& item); const std::string convertKey(MessageItem& item); void serialize(adbase::Buffer& buffer, MessageItem& item); void saveMessage(MessageItem& item); }; } #endif <file_sep>[project] ADINF_PROJECT_NAME=aidp ADINF_PROJECT_SUMMARY=Weibo adinf kafka consumer using lua script ADINF_PROJECT_URL=http://adinf.weiboad.org ADINF_PROJECT_VENDOR=nmred <<EMAIL>> ADINF_PROJECT_PACKAGER=nmred <<EMAIL>> [module] adserver=yes timer=yes kafkac=yes kafkap=no logging=yes [params] timers=default http_controllers=Index kafka_consumers=Out kafka_consumers_topics=test kafka_consumers_groups=test_group_id kafka_producers=In kafka_producers_topics=in [files] src/main.cpp=src/@ADINF_PROJECT_NAME@.cpp rpm/main.spec.in=rpm/@ADINF_PROJECT_NAME@.spec.in [execs] cmake.sh=1 build_rpm.in=1 <file_sep>#ifndef AIDP_APP_HPP_ #define AIDP_APP_HPP_ #include <adbase/Config.hpp> #include <adbase/Lua.hpp> #include "AdbaseConfig.hpp" #include "Aims.hpp" #include "App/Message.hpp" #include "App/Storage.hpp" #include "App/Metrics.hpp" class App { public: App(AdbaseConfig* config); ~App(); void reload(); void run(); void stop(); void checkQueue(); void setAdServerContext(AdServerContext* context); void setTimerContext(TimerContext* context); void setAimsContext(AimsContext* context); void loadConfig(adbase::IniConfig& config); uint64_t getSeqId(); void setAims(std::shared_ptr<Aims>& aims); private: AdbaseConfig* _configure; std::shared_ptr<app::Storage> _storage; std::shared_ptr<app::Message> _message; std::shared_ptr<app::Metrics> _metrics; std::shared_ptr<Aims> _aims; mutable std::mutex _mut; void bindLuaMessage(); }; #endif <file_sep>/// 该程序自动生成,禁止修改 #ifndef AIDP_VERSION_HPP_ #define AIDP_VERSION_HPP_ #define VERSION "1.0.0" #define SOVERSION "1" #define GIT_DIRTY "758" #define GIT_SHA1 "a3a4ad7c" #define BUILD_ID "bpdev-1503035195" #define BUILD_TYPE "Release" #endif <file_sep>local request = aidp.http.request(); local topic_name = request:get_query('t') local response = aidp.http.response(); local storage = aidp.storage() response:set_content(topic_name .. ':message_size ' .. storage:get(topic_name .. ':message_size')); <file_sep>#ifndef AIDP_ADBASE_CONFIG_HPP_ #define AIDP_ADBASE_CONFIG_HPP_ #include <string> #include <adbase/Net.hpp> #include <adbase/Metrics.hpp> #include <adbase/Lua.hpp> // {{{ macros #ifndef DECLARE_KAFKA_CONSUMER_CONFIG #define DECLARE_KAFKA_CONSUMER_CONFIG(name) \ std::string topicNameConsumer##name;\ std::string groupId##name;\ std::string brokerListConsumer##name;\ std::string kafkaDebug##name;\ std::string statInterval##name; #endif #ifndef DECLARE_KAFKA_PRODUCER_CONFIG #define DECLARE_KAFKA_PRODUCER_CONFIG(name) \ std::string topicNameProducer##name;\ std::string brokerListProducer##name;\ std::string debug##name;\ int queueLength##name; #endif #ifndef DECLARE_TIMER_CONFIG #define DECLARE_TIMER_CONFIG(name) \ int interval##name; #endif // }}} typedef struct adbaseConfig { bool daemon; std::string pidFile; int appid; int macid; int mallocTrimPad; int mallocTrimInterval; // logging config std::string logsDir; size_t logRollSize; int logLevel; bool isAsync; bool isStartMc; bool isStartHead; bool isStartHttp; std::string httpHost; int httpPort; int httpTimeout; int httpThreadNum; std::string httpDefaultController; std::string httpDefaultAction; std::string httpServerName; std::string httpAccessLogDir; int httpAccesslogRollSize; std::string httpScriptName; std::string headHost; int headPort; std::string headServerName; int headThreadNum; std::string mcHost; int mcPort; std::string mcServerName; int mcThreadNum; DECLARE_KAFKA_CONSUMER_CONFIG(Out); DECLARE_TIMER_CONFIG(ClearStorage); bool luaDebug; std::string luaScriptPath; std::string consumerScriptName; int consumerBatchNumber; int consumerThreadNumber; int consumerMaxNumber; int consumerTryNumber; int messageRollSize; std::string messageDir; } AdbaseConfig; class App; namespace app { class Message; class Storage; class Metrics; } typedef struct adserverContext { AdbaseConfig* config; adbase::EventBasePtr mainEventBase; App* app; adbase::metrics::Metrics* metrics; // 前后端交互数据指针添加到下面 app::Storage* storage; app::Metrics* appMetrics; } AdServerContext; typedef struct aimsContext { AdbaseConfig* config; App* app; // 消息队列交互上下文 app::Message* message; app::Storage* storage; app::Metrics* appMetrics; } AimsContext; typedef struct timerContext { AdbaseConfig* config; adbase::EventBasePtr mainEventBase; App* app; // 定时器交互上下文 app::Storage* storage; app::Metrics* appMetrics; } TimerContext; #endif <file_sep>#include <adbase/Utility.hpp> #include <adbase/Logging.hpp> #include <adbase/Lua.hpp> #include "App.hpp" //{{{ macros #define LOAD_TIMER_CONFIG(name) do {\ _configure->interval##name = config.getOptionUint32("timer", "interval"#name);\ } while(0) #define LOAD_KAFKA_CONSUMER_CONFIG(name, sectionName) do {\ _configure->topicNameConsumer##name = config.getOption("kafkac_"#sectionName, "topicName"#name);\ _configure->groupId##name = config.getOption("kafkac_"#sectionName, "groupId"#name);\ _configure->brokerListConsumer##name = config.getOption("kafkac_"#sectionName, "brokerList"#name);\ _configure->kafkaDebug##name = config.getOption("kafkac_"#sectionName, "kafkaDebug"#name);\ _configure->statInterval##name = config.getOption("kafkac_"#sectionName, "statInterval"#name);\ } while(0) //}}} // {{{ App::App() App::App(AdbaseConfig* config) : _configure(config) { } // }}} // {{{ App::~App() App::~App() { } // }}} // {{{ void App::run() void App::run() { _storage = std::shared_ptr<app::Storage>(new app::Storage(_configure)); _storage->init(); _metrics = std::shared_ptr<app::Metrics>(new app::Metrics()); _message = std::shared_ptr<app::Message>(new app::Message(_configure, _storage.get(), _metrics.get())); _message->start(); } // }}} // {{{ void App::reload() void App::reload() { // 重新加载 message _message->reload(); } // }}} // {{{ void App::stop() void App::stop() { _message->stop(); } // }}} // {{{ void App::checkQueue() void App::checkQueue() { if (!_message->queueCheck()) { if (_aims) { _aims->pause(); } } else { if (_aims) { _aims->resume(); } } } // }}} // {{{ void App::setAdServerContext() void App::setAdServerContext(AdServerContext* context) { context->app = this; context->storage = _storage.get(); context->appMetrics = _metrics.get(); } // }}} // {{{ void App::setAimsContext() void App::setAimsContext(AimsContext* context) { context->app = this; context->message = _message.get(); context->storage = _storage.get(); context->appMetrics = _metrics.get(); } // }}} // {{{ void App::setTimerContext() void App::setTimerContext(TimerContext* context) { context->app = this; context->storage = _storage.get(); context->appMetrics = _metrics.get(); } // }}} // {{{ void App::setAims() void App::setAims(std::shared_ptr<Aims>& aims) { _aims = aims; } // }}} //{{{ void App::loadConfig() void App::loadConfig(adbase::IniConfig& config) { _configure->mallocTrimInterval = config.getOptionUint32("system", "mallocTrimInterval"); _configure->mallocTrimPad = config.getOptionUint32("system", "mallocTrimPad"); _configure->luaDebug = config.getOptionBool("lua", "debug"); _configure->luaScriptPath = config.getOption("lua", "scriptPath"); _configure->consumerScriptName = config.getOption("consumer", "scriptName"); _configure->consumerBatchNumber = config.getOptionUint32("consumer", "batchNumber"); _configure->consumerThreadNumber = config.getOptionUint32("consumer", "threadNumber"); _configure->consumerMaxNumber = config.getOptionUint32("consumer", "maxNumber"); _configure->consumerTryNumber = config.getOptionUint32("consumer", "tryNumber"); _configure->messageDir = config.getOption("consumer", "messageDir"); _configure->messageRollSize = config.getOptionUint32("consumer", "messageRollSize"); _configure->httpScriptName = config.getOption("http", "scriptName"); LOAD_KAFKA_CONSUMER_CONFIG(Out, out); LOAD_TIMER_CONFIG(ClearStorage); } //}}} //{{{ uint64_t App::getSeqId() uint64_t App::getSeqId() { std::lock_guard<std::mutex> lk(_mut); adbase::Sequence seq; return seq.getSeqId(static_cast<uint16_t>(_configure->macid), static_cast<uint16_t>(_configure->appid)); } //}}} <file_sep>#include "Aims.hpp" // {{{ Aims::Aims() Aims::Aims(AimsContext* context) : _context(context) { _configure = _context->config; } // }}} // {{{ Aims::~Aims() Aims::~Aims() { } // }}} // {{{ void Aims::run() void Aims::run() { // 初始化 server init(); _kafka->start(); _state = RUNNING; } // }}} // {{{ void Aims::reload() void Aims::reload() { std::vector<std::string> topicNames = adbase::explode(_configure->topicNameConsumerOut, ',', true); _kafka->setTopics(topicNames); } // }}} // {{{ void Aims::init() void Aims::init() { initKafkaConsumer(); } // }}} // {{{ void Aims::stop() void Aims::stop() { if (_kafka != nullptr) { _kafka->stop(); delete _kafka; } if (_kafkaConsumerCallbackOut != nullptr) { delete _kafkaConsumerCallbackOut; _kafkaConsumerCallbackOut = nullptr; } } // }}} // {{{ void Aims::pause() void Aims::pause() { if (_state == RUNNING) { _kafka->pause(); _state = PAUSE; } } // }}} // {{{ void Aims::resume() void Aims::resume() { if (_state == PAUSE) { _kafka->resume(); _state = RUNNING; } } // }}} // {{{ void Aims::initKafkaConsumer() void Aims::initKafkaConsumer() { _kafkaConsumerCallbackOut = new aims::kafka::ConsumerOut(_context); std::vector<std::string> topicNames = adbase::explode(_configure->topicNameConsumerOut, ',', true); LOG_INFO << "Topic list:" << _configure->topicNameConsumerOut; _kafka = new adbase::kafka::ConsumerBatch(topicNames, _configure->groupIdOut, _configure->brokerListConsumerOut); _kafka->setMessageHandler(std::bind(&aims::kafka::ConsumerOut::pull, _kafkaConsumerCallbackOut, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); _kafka->setStatCallback(std::bind(&aims::kafka::ConsumerOut::stat, _kafkaConsumerCallbackOut, std::placeholders::_1, std::placeholders::_2)); _kafka->setKafkaDebug(_configure->kafkaDebugOut); _kafka->setKafkaStatInterval(_configure->statIntervalOut); } // }}} <file_sep>-- -- -- 该脚本实现将 kafka 中的数据落地到文件中,并且统计落地消息数 -- -- local obj = aidp.message.get() local filename = os.date('%Y-%m-%d-%H') .. '.log' local files = {}; local storage = aidp.storage() for k,v in pairs(obj) do if #v == 3 then if files[v[2]] == nil then files[v[2]] = io.open(v[2]..filename, 'a+'); files[v[2]]:setvbuf('full') end files[v[2]]:write(v[3]..'\n') storage:incr(v[2] .. ':message_size', 1) end end for k,v in pairs(files) do v:flush() v:close() end <file_sep>#ifndef AIDP_HTTP_INDEX_HPP_ #define AIDP_HTTP_INDEX_HPP_ #include <adbase/Lua.hpp> #include "HttpInterface.hpp" namespace adserver { namespace http { class Index : HttpInterface { public: Index(AdServerContext* context); void registerLocation(adbase::http::Server* http); void index(adbase::http::Request* request, adbase::http::Response* response, void*); std::weak_ptr<adbase::http::Request>& getRequest(); std::weak_ptr<adbase::http::Response>& getResponse(); private: void bindLuaClass(adbase::lua::Engine* engine); }; } } #endif <file_sep>#ifndef AIDP_AIMS_KAFKA_CONSUMER_OUTHPP_ #define AIDP_AIMS_KAFKA_CONSUMER_OUTHPP_ #include <adbase/Kafka.hpp> #include <adbase/Logging.hpp> #include "AdbaseConfig.hpp" namespace aims { namespace kafka { class ConsumerOut { public: ConsumerOut(AimsContext* context); ~ConsumerOut(); bool pull(const std::string& topicName, int partId, uint64_t offset, const adbase::Buffer& data); void stat(adbase::kafka::ConsumerBatch* consumer, const std::string& stats); private: AimsContext* _context; }; } } #endif <file_sep># AIDP (Data Process) AIDP 负责消息队列消费等一系列逻辑,在获取到消息后具体的处理交由 Lua 脚本处理,开发者可以定制消费队列的处理,并且本框架提供了 Http Server 服务,可以使用 Lua 脚本定制 Http API 接口,再消费消息逻辑和 Http Server 间本框架提供了简单的 Key-Val 存储结构做数据共享。如图是该数据处理框架的结构: ![结构图](docs/images/aidp_struct.png) AIDP 处理调用流程: ![数据处理流程](docs/images/aidp_struct_pro.png) ### Why? 对于消息队列的大部分应用场景是后端有一个消费模块进行数据处理,将最终的数据存储到一个地方,最终通过 RPC 接口供使用方使用。有的应用场景业务逻辑可能特别的简单,但是大部分语言对于 Kafka 的消费实现都很复杂(Kafka 消费逻辑决定)使得在开发具体业务逻辑的时候增加开发成本,AIDP 通过 C++ 将这一通用开发模型进行抽象封装,为了增加定制性通过嵌入 Lua 脚本语言来完成定制化部分的逻辑。AIDP 是在开发难度、成本与灵活性之间权衡的折中方案。可以满足大量的数据处理需求 ### Quick Start #### RPM 安装 RPM 目前支持 centos7.x 版本,其他版本陆续会上传, 有其他系统版本的需求可以提 issue #### 编译安装 1. 安装 adbase, 参见:https://nmred.gitbooks.io/adbase/content/zh/basic/install.html 2. 安装 aidp ``` - git clone <EMAIL>:weiboad/aidp.git - cd aidp - ./cmake.sh - cd build - make - make install ``` #### Example 例如使用 aidp 将 kafka 集群中 topic test 落地到本地,并且统计消息的个数,最终消息个数通过 http api 接口可以获取 在安装好的 aidp 中修改配置 `conf/system.ini` ,配置 kafka 消费调用的 lua 脚本,通过修改 [consumer] -> scriptName 配置配置上 lua 脚本即可, 处理脚本如下: ```lua -- -- -- 该脚本实现将 kafka 中的数据落地到文件中,并且统计落地消息数 -- -- local obj = aidp.message.get() local filename = os.date('%Y-%m-%d-%H') .. '.log' local files = {}; -- 实例化存储 local storage = aidp.storage() for k,v in pairs(obj) do if #v == 3 then if files[v[2]] == nil then files[v[2]] = io.open(v[2]..filename, 'a+'); files[v[2]]:setvbuf('full') end files[v[2]]:write(v[3]..'\n') -- 存储计数 storage:incr(v[2] .. ':message_size', 1) end end for k,v in pairs(files) do v:flush() v:close() end ``` 修改配置文件 [http]->scriptName 设置 http 接口调用的 lua 脚本,lua脚本处理内容如下: ```lua -- 获取某个 topic 当前消费的数量 local request = aidp.http.request(); local topic_name = request:get_query('t') local response = aidp.http.response(); local storage = aidp.storage() response:set_content(topic_name .. ':message_size ' .. storage:get(topic_name .. ':message_size')); ``` 启动 aidp ``` cd /usr/local/adinf/aidp/bin ./aidp -c ../conf/system.ini ``` ### Message Consumer 消息消费模块负责从 Kafka 中获取消息,在获取到消息后会调用 Lua 消费脚本,Lua 脚本中可以调用 `aidp.message.get()` 这个函数获取消息,做相应的处理, 例如: #### aidp.message.get Lua 脚本获取 kafka 消息的接口 参数:无 作用范围:仅 Message Consumer 脚本有效 返回: ```lua -- 返回多条消息: -- { -- { -- id, -- topicName, -- messageBody -- }, -- { -- id, -- topicName, -- messageBody -- }, -- { -- id, -- topicName, -- messageBody -- } -- } ``` ```lua -- 将 Kafka 消息写入到本地文件中 -- 获取消息 local obj = aidp.message.get() local filename = os.date('%Y-%m-%d-%H') .. '.log' local files = {}; local storage = aidp.storage() for k,v in pairs(obj) do if #v == 3 then if files[v[2]] == nil then files[v[2]] = io.open(v[2]..filename, 'a+'); files[v[2]]:setvbuf('full') end files[v[2]]:write(v[3]..'\n') storage:incr(v[2] .. ':message_size', 1) end end for k,v in pairs(files) do v:flush() v:close() end ``` ### Http Server 提供 HTTP 接口 Lua 定制开发,对于 Lua 端提供 Request、Response 对象,通过 Request 获取请求数据,并且通过 Lua 脚本处理将最终的响应数据通过 Response 接口定制,Request 和 Response 相关的接口仅仅在 Http Server 处理脚本上有效,对于 Message consumer 处理脚本无效 #### Request | 方法 | 类型 | 描述 | |-----|-----|-----| | aidp.http.request() | 静态构造函数 | 构造 request 对象 | | request:get_uri() | 对象方法 | 获取请求 URI | | request:get_remote_address() | 对象方法 | 获取请求远程的 IP 地址 | | request:get_post_data() | 对象方法 | 获取 POST 请求的原始数据 | | request:get_post([key]) | 对象方法 | 获取 POST Form-Data 类型的数据 | | request:get_query(key) | 对象方法 | 获取 GET 数据 | | request:get_header(key) | 对象方法 | 获取 Header 数据 | | request:get_location() | 对象方法 | 获取 Location 数据 | | request:get_method() | 对象方法 | 获取请求类型, 返回枚举 METHOD_GET、METHOD_POST、METHOD_OTHER | #### Response | 方法 | 类型 | 描述 | |-----|-----|-----| | aidp.http.response() | 静态构造函数 | 构造 response 对象 | | response:set_header(key, val) | 对象方法 | 设置响应 header, 如果存在则覆盖原有的 header | | response:(key, val) | 对象方法 | 设置响应 header, 如果存在则覆盖原有的 header | | response:add_header(key, val) | 对象方法 | 添加响应 header | | response:add_header(key, val) | 对象方法 | 添加响应 header | | response:set_content(body) | 对象方法 | 设置响应 body | | response:append_content(body) | 对象方法 | 追加响应 body | | response:get_code() | 对象方法 | 获取响应的 HTTP 状态码 | | response:set_body_size(size) | 对象方法 | 设置 body 体大小 | #### Sample ```lua local request = aidp.http.request(); local topic_name = request:get_query('t') local response = aidp.http.response(); local storage = aidp.storage() response:set_content(topic_name .. ':message_size ' .. storage:get(topic_name .. ':message_size')); ``` ### Simple Storage 存储提供了类似于 Redis 的 key-val 结构的简单的单机存储,辅助实现一些数据缓存存储逻辑 如下 Lua Api 在 Http lua 脚本和 Message Consumer 中通用 | 方法 | 类型 | 描述 | |-----|-----|-----| | aidp.storage() | 静态构造函数 | 构造 storage 对象 | | storage:set(key, val, [ttl]) | 对象方法 | 在存储中设置数据, 如果设置 ttl 则到期后该key 会被回收掉,ttl 单位为秒 | | storage:incr(key, step) | 对象方法 | 对某个值累加 step | | storage:decr(key, step) | 对象方法 | 对某个值累减 step | | storage:get(key) | 对象方法 | 获取数据 | | storage:exists(key) | 对象方法 | 判断某个 key 是否存在 | | storage:del(key) | 对象方法 | 删除某个 key | <file_sep>MESSAGE(STATUS "Using bundled Findlibadbase_lua.cmake...") FIND_PATH( LIBADBASE_LUA_INCLUDE_DIR Lua.hpp /usr/local/include/adbase /usr/include/ ) FIND_LIBRARY( LIBADBASE_LUA_LIBRARIES NAMES libadbase_lua.a PATHS /usr/lib/ /usr/local/lib/ /usr/lib64 /usr/local/lib64 ) <file_sep>#include "Index.hpp" #include "App/Storage.hpp" #include "App/Metrics.hpp" #include <adbase/Logging.hpp> namespace adserver { namespace http { thread_local std::weak_ptr<adbase::http::Request> tmpRequest; thread_local std::weak_ptr<adbase::http::Response> tmpResponse; // {{{ Index::Index() Index::Index(AdServerContext* context) : HttpInterface(context) { } // }}} // {{{ void Index::registerLocation() void Index::registerLocation(adbase::http::Server* http) { ADSERVER_HTTP_ADD_API(http, Index, index) } // }}} // {{{ void Index::index() void Index::index(adbase::http::Request* request, adbase::http::Response* response, void*) { thread_local adbase::lua::Engine* httpLuaEngine = nullptr; if (httpLuaEngine == nullptr) { httpLuaEngine = new adbase::lua::Engine(); httpLuaEngine->init(); httpLuaEngine->addSearchPath(_context->config->luaScriptPath, true); bindLuaClass(httpLuaEngine); LOG_INFO << "Http Lua engine init...."; } auto sharedRequest = std::shared_ptr<adbase::http::Request>(request, [](adbase::http::Request*) { LOG_INFO << "delete Request";}); auto sharedResponse = std::shared_ptr<adbase::http::Response>(response, [](adbase::http::Response*) { LOG_INFO << "delete Response";}); tmpRequest = sharedRequest; tmpResponse = sharedResponse; responseHeader(response); response->setContent(""); httpLuaEngine->runFile(_context->config->httpScriptName.c_str()); //responseJson(response, "{\"msg\": \"hello xxxx adinf\"}", 0, ""); sharedResponse.reset(); sharedRequest.reset(); response->sendReply(); } // }}} // {{{ void Index::getRequest() std::weak_ptr<adbase::http::Request>& Index::getRequest() { LOG_INFO << "return request...."; return tmpRequest; } // }}} // {{{ void Index::getResponse() std::weak_ptr<adbase::http::Response>& Index::getResponse() { return tmpResponse; } // }}} // {{{ void Index::bindLuaClass() void Index::bindLuaClass(adbase::lua::Engine* engine) { adbase::lua::BindingClass<adbase::http::Request> request("request", "aidp.http", engine->getLuaState()); adbase::lua::BindingNamespace requestCs = request.getOwnerNamespace(); typedef std::function<std::weak_ptr<adbase::http::Request>()> GetRequest; GetRequest requestFn = std::bind(&adserver::http::Index::getRequest, this); requestCs.addMethod("request", requestFn); request.addMethod("get_uri", &adbase::http::Request::getUri); request.addMethod("get_remote_address", &adbase::http::Request::getRemoteAddress); request.addMethod("get_post_data", &adbase::http::Request::getPostData); request.addMethod("get_post", &adbase::http::Request::getPost); request.addMethod("get_query", &adbase::http::Request::getQuery); request.addMethod("get_header", &adbase::http::Request::getHeader); request.addMethod("get_location", &adbase::http::Request::getLocation); request.addMethod("get_method", &adbase::http::Request::getMethod); request.addConst("METHOD_GET", adbase::http::Request::httpMethod::METHOD_GET); request.addConst("METHOD_POST", adbase::http::Request::httpMethod::METHOD_POST); request.addConst("METHOD_OTHER", adbase::http::Request::httpMethod::METHOD_OTHER); // bind response adbase::lua::BindingClass<adbase::http::Response> response("response", "aidp.http", engine->getLuaState()); adbase::lua::BindingNamespace responseCs = response.getOwnerNamespace(); typedef std::function<std::weak_ptr<adbase::http::Response>()> GetResponse; GetResponse responseFn = std::bind(&adserver::http::Index::getResponse, this); responseCs.addMethod("response", responseFn); // 构造函数 response.addMethod("set_header", &adbase::http::Response::setHeader); response.addMethod("add_header", &adbase::http::Response::addHeader); response.addMethod<void, adbase::http::Response, const char*, size_t>("set_content", &adbase::http::Response::setContent); response.addMethod<void, adbase::http::Response, const std::string&>("set_content", &adbase::http::Response::setContent); response.addMethod<void, adbase::http::Response, const char*, size_t, bool>("append_content", &adbase::http::Response::appendContent); response.addMethod<void, adbase::http::Response, const std::string&, bool>("append_content", &adbase::http::Response::appendContent); response.addMethod("send_reply", &adbase::http::Response::sendReply); response.addMethod("get_code", &adbase::http::Response::getCode); response.addMethod("set_body_size", &adbase::http::Response::getBodySize); _context->storage->bindClass(engine); _context->appMetrics->bindClass(engine); } // }}} } } <file_sep>local obj = aidp.message.get() local filename = 'test' .. os.date('%Y-%m-%d-%H') .. '.log' local file = io.open(filename, 'a+') file:setvbuf('full') for k,v in pairs(obj) do if #v == 2 then print(v[2]) file:write(v[2]..'\n') end end file:flush() file:close() <file_sep>[system] appid=0 macid=0 daemon=no pidFile=./aidp.pid ; malloc trim 128kb mallocTrimPad=131072 ; malloc trim interval ; 5s mallocTrimInterval=1000 [logging] logsDir=logs/ ; 日志分卷大小 logRollSize=52428800 ; 1: LOG_TRACE 2: LOG_DEBUG 3: LOG_INFO logLevel=3 isAsync=no [adserver] ; 是否启动 mc server mc=no ; 是否启动 http server http=yes ; 是否启动 head server head=no [mc] host=0.0.0.0 port=10011 threadNum=4 serverName=mc-server [http] host=0.0.0.0 port=10053 timeout=3 threadNum=1 serverName=adinf-adserver accessLogDir=logs/ accesslogRollSize=52428800 defaultController=index defaultAction=index scriptName=http.lua [head] host=0.0.0.0 port=10012 threadNum=4 serverName=head-server [kafkac_out] ; 支持同时消费多个 topic, 多个用逗号分隔 topicNameOut=test groupIdOut=test_group_id brokerListOut=127.0.0.1:9192 kafkaDebugOut=none statIntervalOut=60000 [timer] ; 单位ms intervalClearStorage=1000 [lua] ; 如果是 debug 模式脚本执行将每次重新加载 debug=no scriptPath=/usr/home/zhongxiu/code/lua [consumer] scriptName=../../example/dusty.lua batchNumber=1000 messageDir=./message/ messageRollSize=52428800 threadNumber=8 tryNumber=10 maxNumber=10000 <file_sep>#ifndef AIDP_AIMS_HPP_ #define AIDP_AIMS_HPP_ #include <adbase/Utility.hpp> #include <adbase/Logging.hpp> #include <adbase/Kafka.hpp> #include "AdbaseConfig.hpp" #include "Aims/Kafka/ConsumerOut.hpp" class Aims { public: Aims(AimsContext* context); ~Aims(); void run(); void stop(); void reload(); void pause(); void resume(); private: /// 传输上下文指针 AimsContext* _context; AdbaseConfig* _configure; bool _isResume = true; bool _isPause = true; void init(); void initKafkaConsumer(); aims::kafka::ConsumerOut* _kafkaConsumerCallbackOut = nullptr; adbase::kafka::ConsumerBatch* _kafka; enum runState { STOP = 0, RUNNING = 1, PAUSE = 2, }; runState _state = STOP; }; #endif
519a3f7ff93c85a85dad6361dc6ab7a9aba890b9
[ "CMake", "Lua", "Markdown", "INI", "C++" ]
26
C++
W3SS/aidp
8bf7d0cbd580d892922e3f772690b39fd2b0203b
eccef8405e21069482ba0c38dfb92ac7184cc1f0
refs/heads/master
<repo_name>tkobayas/kiegroup-examples<file_sep>/Ex-kie-drools-archetype/README.txt ## Project generated by kie-drools-archetype for example) ``` mvn archetype:generate -DarchetypeGroupId=org.kie -DarchetypeArtifactId=kie-drools-archetype -DarchetypeVersion=7.61.0.Final -DgroupId=com.sample -DartifactId=basic-kjar -Dversion=1.0-SNAPSHOT -Dpackage=com.sample ``` <file_sep>/Ex-spreadsheet-boolean-7.58/src/main/java/com/sample/MyFact2.java package com.sample; public class MyFact2 { private int a; private int b; private String c; public MyFact2() { super(); // TODO Auto-generated constructor stub } public MyFact2(int a, int b, String c) { super(); this.a = a; this.b = b; this.c = c; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } } <file_sep>/Ex-basic-drl-7.38/src/main/java/com/sample/DroolsTest.java package com.sample; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { public static void main(String[] args) { KieServices ks = KieServices.Factory.get(); KieContainer kcontainer = ks.getKieClasspathContainer(); KieBase kbase = kcontainer.getKieBase(); KieSession ksession = kbase.newKieSession(); ksession.insert(new Person("John", 35)); ksession.fireAllRules(); ksession.dispose(); } } <file_sep>/Ex-drools-webapp-7.36/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sample</groupId> <artifactId>drools-webapp-example</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <drools.version>7.36.0.Final</drools.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin> <version.jboss.bom.eap>7.1.0.GA</version.jboss.bom.eap> <version.surefire.plugin>2.10</version.surefire.plugin> <version.war.plugin>2.1.1</version.war.plugin> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.jboss.bom</groupId> <artifactId>jboss-eap-javaee7-with-tools</artifactId> <version>${version.jboss.bom.eap}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <repositories> <repository> <id>jboss-public-repository-group</id> <name>JBoss Public Repository Group</name> <url>http://repository.jboss.org/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>daily</updatePolicy> </snapshots> </repository> <repository> <id>rh-all</id> <url>https://maven.repository.redhat.com/ga</url> <releases> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencies> <!-- Import the Servlet API, we use provided scope as the API is included in JBoss EAP --> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.1_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-core</artifactId> <version>${drools.version}</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>${drools.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>${version.war.plugin}</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <!-- JBoss AS plugin to deploy war --> <!-- <plugin> --> <!-- <groupId>org.jboss.as.plugins</groupId> --> <!-- <artifactId>jboss-as-maven-plugin</artifactId> --> <!-- <version>${version.jboss.maven.plugin}</version> --> <!-- </plugin> --> <!-- WildFly plug-in to deploy the WAR --> <plugin> <groupId>org.wildfly.plugins</groupId> <artifactId>wildfly-maven-plugin</artifactId> <version>${version.wildfly.maven.plugin}</version> </plugin> </plugins> </build> </project> <file_sep>/Ex-business-application-7.69/Ex-kie-server-client-7.69/src/main/java/com/sample/Constants.java package com.sample; public class Constants { public static final String USERNAME = "kieserver"; public static final String PASSWORD = "<PASSWORD>!"; public static final String BASE_URL = "http://localhost:8090/rest/server"; public static final String GROUP_ID = "com.company"; public static final String ARTIFACT_ID = "business-application-kjar"; public static final String VERSION = "1.0-SNAPSHOT"; public static final String CONTAINER_ID = "business-application-kjar-1_0-SNAPSHOT"; // public static final String GROUP_ID = "com.myspace"; // public static final String ARTIFACT_ID = "myproj"; // public static final String VERSION = "1.0.0-SNAPSHOT"; // public static final String CONTAINER_ID = "myproj_1.0.0-SNAPSHOT"; } <file_sep>/Ex-ruleunit-spring-boot-2-executable-8.37.0-SNAPSHOT/src/test/java/com/example/demo/DemoApplicationIntegrationTest.java package com.example.demo; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DemoApplicationIntegrationTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void testGetFoo() { // send a GET request to the "/foo" endpoint ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/hello", String.class); // assert that the response status code is OK Assertions.assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } } <file_sep>/Ex-ruleunit-spring-boot-2-executable-8.37.0-SNAPSHOT/README.txt RuleUnit example in Spring Boot 2 executable jar. Requires JDK 11. mvn clean install java -jar target/ruleunit-spring-boot-2.7.10-SNAPSHOT.jar curl http://localhost:8080/hello <file_sep>/Ex-old-API-7.70/src/main/java/com/sample/DroolsTest.java package com.sample; import java.util.Collection; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.KnowledgeBaseFactory; import org.kie.api.KieServices; import org.kie.api.definition.KiePackage; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; public class DroolsTest { public static void main(String[] args) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); Resource resource1 = KieServices.Factory.get().getResources().newClassPathResource("Sample.drl", DroolsTest.class); kbuilder.add(resource1, ResourceType.DRL); Collection<KiePackage> knowledgePackages = kbuilder.getKnowledgePackages(); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addPackages(knowledgePackages); KieSession ksession = kbase.newKieSession(); ksession.insert(new Person("John", 35)); ksession.insert(new Person("Paul", 33)); ksession.fireAllRules(); ksession.dispose(); } } <file_sep>/Ex-kie-server-controller-ws-client-7.69/README.txt Just for test purpose. Not meaningful as a practical example. <file_sep>/Ex-dmn-7.38/src/main/java/com/sample/DMNTest.java package com.sample; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.dmn.api.core.DMNContext; import org.kie.dmn.api.core.DMNModel; import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.DMNRuntime; import org.kie.dmn.core.api.DMNFactory; import org.kie.dmn.core.compiler.RuntimeTypeCheckOption; import org.kie.dmn.core.impl.DMNRuntimeImpl; import org.kie.dmn.core.util.KieHelper; /** * This is a sample class to launch a rule. */ public class DMNTest { public static final void main(String[] args) { final KieServices ks = KieServices.Factory.get(); final KieContainer kieContainer = KieHelper.getKieContainer( ks.newReleaseId("com.sample", "dmn-example-" + UUID.randomUUID(), "1.0"), ks.getResources().newClassPathResource("Traffic_Violation.dmn", DMNTest.class)); DMNRuntime dmnRuntime = kieContainer.newKieSession().getKieRuntime(DMNRuntime.class); ((DMNRuntimeImpl) dmnRuntime).setOption(new RuntimeTypeCheckOption(true)); final DMNModel dmnModel = dmnRuntime.getModel("https://github.com/kiegroup/drools/kie-dmn/_A4BCA8B8-CF08-433F-93B2-A2598F19ECFF", "Traffic Violation"); final DMNContext context = DMNFactory.newContext(); Map<String, Object> driverMap = new HashMap<>(); driverMap.put("Name", "John"); driverMap.put("Age", 34); driverMap.put("State", "Texas"); driverMap.put("City", "Austin"); driverMap.put("Points", 20); context.set("Driver", driverMap); Map<String, Object> violationMap = new HashMap<>(); violationMap.put("Code", "AAA"); violationMap.put("Date", LocalDate.now()); violationMap.put("Type", "speed"); violationMap.put("Speed Limit", 100); violationMap.put("Actual Speed", 120); context.set("Violation", violationMap); final DMNResult dmnResult = dmnRuntime.evaluateAll(dmnModel, context); System.out.println(dmnResult); } } <file_sep>/Ex-cep-window-length-8.32/src/test/java/com/sample/DroolsTest.java package com.sample; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.concurrent.TimeUnit; import org.drools.core.common.EventFactHandle; import org.drools.core.time.impl.PseudoClockScheduler; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.time.SessionClock; public class DroolsTest { @Test public void testCep() { try { KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); KieSession kSession = kContainer.newKieSession("ksession1"); PseudoClockScheduler clock = (PseudoClockScheduler) kSession.<SessionClock> getSessionClock(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS"); clock.setStartupTime(sdf.parse("30-05-2016 10:00:00.000").getTime()); Message message1 = new Message(1, "AAA"); kSession.insert(message1); clock.advanceTime(200, TimeUnit.DAYS); Message message2 = new Message(2, "BBB"); kSession.insert(message2); clock.advanceTime(30, TimeUnit.DAYS); Message message3 = new Message(3, "CCC"); kSession.insert(message3); clock.advanceTime(200, TimeUnit.DAYS); Message message4 = new Message(4, "DDD"); kSession.insert(message4); clock.advanceTime(80, TimeUnit.DAYS); Message message5 = new Message(5, "EEE"); kSession.insert(message5); kSession.fireAllRules(); // The kSession.getObjects() and kSession.getFactHandles() return a Collection, not sorted System.out.println(); System.out.println("------ retained events(not sorted)"); Collection<FactHandle> factHandles = kSession.getFactHandles(); for (FactHandle factHandle : factHandles) { EventFactHandle eventFactHandle = (EventFactHandle) factHandle; System.out.println(new Date(eventFactHandle.getStartTimestamp()) + " -> " + eventFactHandle.getObject()); } } catch (Throwable t) { t.printStackTrace(); } } } <file_sep>/Ex-kie-server-client-global-by-listener-7.56/src/main/java/com/sample/Constants.java package com.sample; public class Constants { public static final String BASE_URL = "http://localhost:8080/kie-server/services/rest/server"; // public static final String GROUP_ID = "org.kie.example"; // public static final String ARTIFACT_ID = "project3"; // public static final String VERSION = "5.0.0"; // public static final String CONTAINER_ID = "project3_5.0.0"; public static final String GROUP_ID = "com.myspace"; public static final String ARTIFACT_ID = "myproj"; public static final String VERSION = "1.0.0-SNAPSHOT"; public static final String CONTAINER_ID = "myproj_1.0.0-SNAPSHOT"; } <file_sep>/Ex-spreadsheet-boolean-7.58/src/main/java/com/sample/MyFact1.java package com.sample; public class MyFact1 { private boolean a; private boolean b; private boolean c; public MyFact1() { super(); // TODO Auto-generated constructor stub } public MyFact1(boolean a, boolean b, boolean c) { super(); this.a = a; this.b = b; this.c = c; } public boolean isA() { return a; } public void setA(boolean a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } <file_sep>/Ex-KieFileSystem-em-persist-kjar-7.55/src/test/java/com/sample/LoadUrlResourceTest.java package com.sample; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.drools.core.io.impl.UrlResource; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; import org.kie.api.builder.KieRepository; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; public class LoadUrlResourceTest { private KieServices kieService = KieServices.Factory.get(); private KieContainer kieContainer; // private final String URL = "file:///home/tkobayas/usr/git/tkobayas/kiegroup-examples/Ex-KieFileSystem-em-persist-kjar-7.55/output/basic-kjar-em-55-kfs-1.0.0.jar"; private final String URL = new File("output/basic-kjar-em-55-kfs-1.0.0.jar").toURI().toString(); @Test public void testRules() throws Exception { // System.setProperty("drools.projectClassLoader.enableStoreFirst", "false"); System.out.println("URL : " + URL); initialiseNewKieContainer(URL, null); } private void initialiseNewKieContainer(String url, List<String> logCollector) throws Exception { boolean printLog = false; if (logCollector == null) { logCollector = new ArrayList<String>(); printLog = true; } String log = "\n********** [ INITIALISATION LOG DETAILS ]**********"; logCollector.add(log); Date startTime = new Date(); Date totalStartTime = new Date(); /** * Geting the Instance of KieRepository */ KieRepository kr = kieService.getRepository(); logCollector.add("\n1. Time taken to get the KieRepository from kieService.getRepository() =" + ((new Date()).getTime() - startTime.getTime()) + "ms"); UrlResource urlResource = (UrlResource) kieService.getResources().newUrlResource(url); // urlResource.setUsername(this.REPO_USER_ID); // urlResource.setPassword(this.REPO_PASSWORD); // urlResource.setBasicAuthentication("enabled"); /** * Getting the Input Stream of in-memory downloaded KJAR. */ InputStream is = null; try { startTime = new Date(); is = urlResource.getInputStream(); logCollector.add("\n2. Time taken to download the KJAR from URL [" + url + "]=" + ((new Date()).getTime() - startTime.getTime()) + "ms"); } catch (IOException e) { throw e; } /** * Getting the Kie Module from KJAR Input Stream */ startTime = new Date(); KieModule kModule = kr.addKieModule(kieService.getResources().newInputStreamResource(is)); logCollector.add("\n3. Time taken to get the Kie module from in-memory downloaded KJAR InputStream =" + ((new Date()).getTime() - startTime.getTime()) + "ms"); ReleaseId releaseId = kModule.getReleaseId(); /** * Creating the KIE Container from releaseId */ startTime = new Date(); kieContainer = kieService.newKieContainer(releaseId); logCollector.add("\n4. Time taken to get the KIE Container from KieService.newKieContainer(" + releaseId + ") =" + ((new Date()).getTime() - startTime.getTime()) + "ms"); System.out.println("****************************** getKieBase"); startTime = new Date(); KieBase kbase = kieContainer.getKieBase("defaultKieBase"); logCollector.add("\n5. Time taken to get the KIE Base from KieContainer.getKieBase(defaultKieBase) = " + ((new Date()).getTime() - startTime.getTime()) + "ms"); logCollector.add(" ----------------------------------------------------------------------------------------------------------------------------------------------"); logCollector.add("\n6. Total Time taken to initalise the KIE Container From New KJAR =" + ((new Date()).getTime() - totalStartTime.getTime()) + "ms"); logCollector.add("************************************************************************************************************************************************************"); if (printLog) { for (String logString : logCollector) { System.out.println(logString); } } System.out.println("rules size = " + kbase.getKiePackage("com.sample").getRules().size()); // KieSession kSession = null; // try { // kSession = kbase.newKieSession(); // List<String> resultList = new ArrayList<>(); // kSession.setGlobal("resultList", resultList); // Person john = new Person("john", 25); // kSession.insert(john); // kSession.fireAllRules(); // System.out.println(resultList); // } finally { // kSession.dispose(); // } } } <file_sep>/Ex-KieFileSystem-7.38/src/main/java/com/sample/DroolsTest.java package com.sample; import java.io.File; import java.io.FileInputStream; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { public static void main(String[] args) throws Exception { // KieServices is the entry point of APIs KieServices ks = KieServices.Factory.get(); // KieFileSystem is responsible for gathering resources KieFileSystem kfs = ks.newKieFileSystem(); // You can add your DRL files as InputStream here kfs.write("src/main/resources/com/sample/Sample1.drl", ks.getResources().newInputStreamResource(new FileInputStream(new File("work/Sample1.drl")))); kfs.write("src/main/resources/com/sample/12345.drl", ks.getResources().newInputStreamResource(new FileInputStream(new File("work/Sample2.drl")))); // You need to specify a unique ReleaseId per KieContainer (= the unit which you store a set of DRL files) // ReleaseId consists of "GroupId" + "ArtifactId" + "Version". The same idea of Maven artifact. ReleaseId releaseId = ks.newReleaseId("com.sample", "my-sample-a", "1.0.0"); kfs.generateAndWritePomXML(releaseId); // Now resources are built and stored into an internal repository ks.newKieBuilder(kfs).buildAll(); // You can get a KieContainer with the ReleaseId KieContainer kcontainer = ks.newKieContainer(releaseId); // KieContainer can create a KieBase KieBase kbase = kcontainer.getKieBase(); // KieBase can create a KieSession KieSession ksession = kbase.newKieSession(); ksession.insert(new Person("John", 35)); ksession.fireAllRules(); ksession.dispose(); } } <file_sep>/Ex-kie-server-process-kjar-7.58/src/main/java/com/sample/LoanApplication.java package com.sample; public class LoanApplication { private Person applicant; private int amount; private boolean approved = false; public LoanApplication() {} public LoanApplication(Person applicant, int amount) { this.applicant = applicant; this.amount = amount; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public Person getApplicant() { return applicant; } public void setApplicant(Person applicant) { this.applicant = applicant; } } <file_sep>/Ex-global-LHS-nest-7.61/src/main/java/com/sample/MyGlobal.java package com.sample; public class MyGlobal { private int ageA; private int ageB; private int ageC; public MyGlobal() { } public MyGlobal(int ageA, int ageB, int ageC) { this.ageA = ageA; this.ageB = ageB; this.ageC = ageC; } public int getAgeA() { return ageA; } public void setAgeA(int ageA) { this.ageA = ageA; } public int getAgeB() { return ageB; } public void setAgeB(int ageB) { this.ageB = ageB; } public int getAgeC() { return ageC; } public void setAgeC(int ageC) { this.ageC = ageC; } } <file_sep>/Ex-kie-server-client-global-by-listener-7.56/src/test/java/com/sample/StatefulWithListenerTest.java package com.sample; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.myspace.myproj.Person; import junit.framework.TestCase; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; import org.kie.api.command.KieCommands; import org.kie.api.runtime.ExecutionResults; import org.kie.server.api.model.ServiceResponse; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesFactory; import org.kie.server.client.RuleServicesClient; import static com.sample.Constants.BASE_URL; import static com.sample.Constants.CONTAINER_ID; public class StatefulWithListenerTest extends TestCase { private static final String USERNAME = "kieserver"; private static final String PASSWORD = "<PASSWORD>!"; private static final String KSESSION_NAME = "myStatefulKsession"; private static final String GLOBAL_IDENTIFIER = "results"; // private static final MarshallingFormat FORMAT = MarshallingFormat.JSON; // private static final MarshallingFormat FORMAT = MarshallingFormat.JAXB; @Test public void testProcess() { // You will always use the same Stateful ksession with lookup="myStatefulKsession" which you configured in kmodule.xml // set global setup(); // results = [] // 1st run Person p1 = new Person(); p1.setName("John"); p1.setAge(20); runClient(p1); // 2nd run Person p2 = new Person(); p2.setName("Paul"); p2.setAge(10); runClient(p2); // don't forget dispose dispose(); } private void setup() { System.out.println("-----------------------------------"); System.out.println("Setup Global 'results' by listner triggered by a String"); RuleServicesClient ruleClient = getRuleClient(); List<Command<?>> commands = new ArrayList<Command<?>>(); KieCommands commandsFactory = KieServices.Factory.get().getCommands(); commands.add(commandsFactory.newInsert("reset", "fact-reset")); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands); // lookup default stateful ksession ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution); System.out.println(response); List results = (List) response.getResult().getValue(GLOBAL_IDENTIFIER); System.out.println("results = " + results); } private RuleServicesClient getRuleClient() { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, USERNAME, PASSWORD); HashSet<Class<?>> classes = new HashSet<Class<?>>(); classes.add(Person.class); config.addExtraClasses(classes); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); RuleServicesClient ruleClient = client.getServicesClient(RuleServicesClient.class); return ruleClient; } private void runClient(Person person) { System.out.println("-----------------------------------"); System.out.println("Send : " + person); RuleServicesClient ruleClient = getRuleClient(); List<Command<?>> commands = new ArrayList<Command<?>>(); KieCommands commandsFactory = KieServices.Factory.get().getCommands(); commands.add(commandsFactory.newInsert(person, "fact-" + person.getName())); commands.add(commandsFactory.newFireAllRules("fire-result")); commands.add(commandsFactory.newGetGlobal(GLOBAL_IDENTIFIER)); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands); // lookup default stateful ksession ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution); System.out.println(response); List results = (List) response.getResult().getValue(GLOBAL_IDENTIFIER); System.out.println("results = " + results); } private void dispose() { System.out.println("-----------------------------------"); System.out.println("Dispose"); RuleServicesClient ruleClient = getRuleClient(); List<Command<?>> commands = new ArrayList<Command<?>>(); KieCommands commandsFactory = KieServices.Factory.get().getCommands(); commands.add(commandsFactory.newDispose()); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands); ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution); System.out.println(response); } } <file_sep>/Ex-KieFileSystem-reuse-kfs-8.35/src/test/java/com/sample/DroolsTest.java package com.sample; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { private KieFileSystem kfs; @Test public void testRules() throws Exception { // KieServices is the entry point of APIs KieServices ks = KieServices.Factory.get(); // kfs will be shared across 1st and 2nd run kfs = ks.newKieFileSystem(); // You need to specify a unique ReleaseId per KieContainer (= the unit which you store a set of DRL files) // ReleaseId consists of "GroupId" + "ArtifactId" + "Version". The same idea of Maven artifact. ReleaseId releaseId = ks.newReleaseId("com.sample", "my-sample-a", "1.0.0"); buildInitialResources(releaseId, new File("work/Sample1.drl"), new File("work/Sample2.drl")); // You can get a KieContainer with the ReleaseId KieContainer kcontainer = ks.newKieContainer(releaseId); System.out.println("=== 1st run : " + releaseId); KieSession ksession1 = kcontainer.newKieSession(); try { ksession1.insert(new Person("John", 35)); ksession1.fireAllRules(); } finally { ksession1.dispose(); } System.out.println("//================== Update Sample1.drl"); // If you add or modify the resources and build a new KieContainer, make sure that it has a new ReleaseId (usually, version increment). ReleaseId newReleaseId = ks.newReleaseId("com.sample", "my-sample-a", "1.0.1"); // Update Sample1.drl, but keep other files (Sample2.drl) buildResourceByUpdatingRule(newReleaseId, "Sample1.drl", new File("work/Sample1_updated.drl")); KieContainer newKcontainer = ks.newKieContainer(newReleaseId); System.out.println("=== 2nd run : " + newReleaseId); KieSession ksession2 = newKcontainer.newKieSession(); try { ksession2.insert(new Person("George", 32)); ksession2.fireAllRules(); } finally { ksession2.dispose(); } } private void buildInitialResources(ReleaseId releaseId, File... files) { KieServices ks = KieServices.Factory.get(); for (File file : files) { // You can add your DRL files as InputStream here try { kfs.write("src/main/resources/com/sample/" + file.getName(), ks.getResources().newInputStreamResource(new FileInputStream(file))); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } kfs.generateAndWritePomXML(releaseId); // Now resources are built and stored into an internal repository with the releaseId ks.newKieBuilder(kfs).buildAll(); } private void buildResourceByUpdatingRule(ReleaseId newReleaseId, String updatedFileName, File newFile) { KieServices ks = KieServices.Factory.get(); // Update a DRL file try { kfs.write("src/main/resources/com/sample/" + updatedFileName, ks.getResources().newInputStreamResource(new FileInputStream(newFile))); } catch (FileNotFoundException e) { throw new RuntimeException(e); } kfs.generateAndWritePomXML(newReleaseId); // Now resources are built and stored into an internal repository with the releaseId ks.newKieBuilder(kfs).buildAll(); } } <file_sep>/Ex-many-drl-7.54/src/main/java/com/sample/RuleGen.java package com.sample; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class RuleGen { public static void main(String[] args) throws Exception { StringBuilder builder = new StringBuilder(); builder.append("package com.sample\n"); builder.append("import com.sample.*\n\n"); builder.append("global java.util.List resultList;\n\n"); int ruleNum = 2000; for (int i = 0; i < ruleNum; i++) { builder.append("rule \"rule" + i + "\"\n"); builder.append(" when\n"); builder.append(" $p : Person( age >= " + i*5 + " && age < " + (i+1)*5 + " )\n"); builder.append(" then\n"); builder.append(" resultList.add( kcontext.getRule().getName() + \" : \" + $p );\n"); builder.append("end\n"); builder.append("\n"); } Path path = Paths.get("src/main/resources/com/sample/Sample.drl"); Files.write(path, builder.toString().getBytes(), StandardOpenOption.CREATE); System.out.println("finish"); } } <file_sep>/Ex-kie-server-client-global-by-listener-7.56/src/main/java/com/sample/KieRestClientBasic.java package com.sample; import static com.sample.Constants.BASE_URL; import org.kie.server.api.model.KieServerInfo; import org.kie.server.api.model.ServiceResponse; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesFactory; public class KieRestClientBasic { public static void main(String[] args) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, "kieserver", "kieserver1!"); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); ServiceResponse<KieServerInfo> response = client.getServerInfo(); System.out.println(response.getResult()); } } <file_sep>/Ex-kie-server-process-client-7.61/src/test/java/com/sample/FindStartCompleteTaskTest.java package com.sample; import java.util.List; import junit.framework.TestCase; import org.kie.server.client.UserTaskServicesClient; import static com.sample.Constants.CONTAINER_ID; import static com.sample.Constants.USERNAME; public class FindStartCompleteTaskTest extends TestCase { public void testRest() throws Exception { UserTaskServicesClient taskClient = KieServerRestUtils.getUserTaskServicesClient(); List<org.kie.server.api.model.instance.TaskSummary> taskList; taskList = taskClient.findTasksAssignedAsPotentialOwner(USERNAME, 0, 100); for (org.kie.server.api.model.instance.TaskSummary taskSummary : taskList) { System.out.println("taskSummary.getId() = " + taskSummary.getId() + ", staus = " + taskSummary.getStatus()); long taskId = taskSummary.getId(); if (taskSummary.getStatus().equals("Reserved")) { taskClient.startTask(CONTAINER_ID, taskId, USERNAME); } taskClient.completeTask(CONTAINER_ID, taskId, USERNAME, null); } } } <file_sep>/Ex-kie-server-xstream-extension-nil-converter-7.48.0.Final-redhat-00004/src/main/java/org/example/kie/server/xstream/extension/NilableConverter.java package org.example.kie.server.xstream.extension; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NilableConverter implements Converter { private static final Logger LOG = LoggerFactory.getLogger(NilableConverter.class); @Override public boolean canConvert(Class type) { return String.class.equals(type); } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { // This method is not actually called because AbstractReflectionConverter.doMarshal() checks null earlier (line.152) if (source == null) { writer.addAttribute("nil", "true"); } else { writer.setValue(source.toString()); } } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { String value = ""; // default value if ("true".equals(reader.getAttribute("nil"))) { value = null; } else { value = reader.getValue(); } return value; } } <file_sep>/Ex-ruleunit-spring-boot-3-executable-8.37.0-SNAPSHOT/README.txt RuleUnit example in Spring Boot 3 executable jar. Requires JDK 17. mvn clean install java -jar target/ruleunit-spring-boot-3.0.5-SNAPSHOT.jar curl http://localhost:8080/hello <file_sep>/Ex-kie-server-warmup-listener-7.48.0.Final-redhat-00006/my-kie-server-warmup-listener/src/main/java/org/example/kie/server/warmup/MyKieServerWarmupEventListener.java package org.example.kie.server.warmup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import org.kie.api.builder.model.KieSessionModel.KieSessionType; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; import org.kie.api.runtime.ExecutionResults; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; import org.kie.internal.command.CommandFactory; import org.kie.server.api.model.KieContainerResource; import org.kie.server.api.model.KieServerConfigItem; import org.kie.server.services.api.KieContainerInstance; import org.kie.server.services.api.KieServer; import org.kie.server.services.api.KieServerEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyKieServerWarmupEventListener implements KieServerEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(MyKieServerWarmupEventListener.class); public static final String KIE_WARMUP_LISTENER_STRATEGY = "org.example.kie.server.warmup.strategy"; @Override public void beforeServerStarted(KieServer kieServer) {} @Override public void afterServerStarted(KieServer kieServer) {} @Override public void beforeServerStopped(KieServer kieServer) {} @Override public void afterServerStopped(KieServer kieServer) {} @Override public void beforeContainerStarted(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void afterContainerStarted(KieServer kieServer, KieContainerInstance containerInstance) { // To set the KIE_WARMUP_LISTENER_STRATEGY value, see CreateContainerWithWarmupTrue.java in Ex-kie-server-client-7.48.0.Final-redhat-00006 // If you comment-out this part, you can always trigger warm-up. KieContainerResource resource = containerInstance.getResource(); Optional<KieServerConfigItem> optItem = resource.getConfigItems().stream() .filter(item -> item.getName().equals(KIE_WARMUP_LISTENER_STRATEGY)) .findFirst(); if (!optItem.isPresent()) { LOGGER.info("{} is not enabled : ", KIE_WARMUP_LISTENER_STRATEGY); return; } String strategy = optItem.get().getValue(); LOGGER.info("start warmup : " + strategy); long start = System.currentTimeMillis(); try { switch (strategy) { case "internal-fire-only": internalWarmupFireOnly(containerInstance); break; case "internal-full": // in order to use internalWarmupFull, you need to edit the method to insert expected fact objects internalWarmupFull(containerInstance); break; default: break; } } catch (Exception e) { LOGGER.warn("warmup failed. You can ignore the error and use the deployed container", e); } LOGGER.info("afterContainerStarted : elapsed time = {}ms", System.currentTimeMillis() - start); } private void internalWarmupFireOnly(KieContainerInstance containerInstance) { LOGGER.info(" internalWarmupFireOnly"); KieContainer kieContainer = containerInstance.getKieContainer(); Collection<String> kieBaseNames = kieContainer.getKieBaseNames(); // warmup all kieSessions kieBaseNames.stream() .flatMap(kieBaseName -> kieContainer.getKieSessionNamesInKieBase(kieBaseName).stream()) .forEach(kieSessionName -> { LOGGER.info("warmup : kieSessionName = {}", kieSessionName); KieSessionType type = kieContainer.getKieSessionModel(kieSessionName).getType(); if (type == KieSessionType.STATEFUL) { KieSession kieSession = kieContainer.newKieSession(kieSessionName); kieSession.fireAllRules(); kieSession.dispose(); } else { StatelessKieSession statelessKieSession = kieContainer.newStatelessKieSession(kieSessionName); final List<Command> cmds = new ArrayList<Command>(); cmds.add(CommandFactory.newFireAllRules()); BatchExecutionCommand batchExecutionCommand = CommandFactory.newBatchExecution(cmds); final ExecutionResults batchResult = (ExecutionResults) statelessKieSession.execute(batchExecutionCommand); } }); } private void internalWarmupFull(KieContainerInstance containerInstance) { LOGGER.info(" internalWarmupFull"); KieContainer kieContainer = containerInstance.getKieContainer(); // you need to get the class via kieContainer's classloader. Unless, the fact wouldn't match the rule Object person = null; Class<?> personClass = null; try { personClass = Class.forName("com.sample.Person", true, kieContainer.getClassLoader()); if (personClass != null) { Constructor<?> constructor = personClass.getConstructor(String.class, int.class); person = constructor.newInstance("George", 18); LOGGER.info(" obj = {}", person); } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } // Note that these warm-up codes are tailer for each kieSession StatelessKieSession statelessKieSession = kieContainer.newStatelessKieSession("myStatelessKsession"); List<Command> cmds = new ArrayList<Command>(); cmds.add(CommandFactory.newInsert(Integer.valueOf(20), "integer-fact")); // You need to know what facts should be inserted cmds.add(CommandFactory.newFireAllRules()); BatchExecutionCommand batchExecutionCommand = CommandFactory.newBatchExecution(cmds); ExecutionResults batchResult = (ExecutionResults) statelessKieSession.execute(batchExecutionCommand); LOGGER.info(" batchResult = {}", batchResult); statelessKieSession = kieContainer.newStatelessKieSession("myStatelessKsession2"); cmds = new ArrayList<Command>(); cmds.add(CommandFactory.newInsert(person, "person-fact")); // You need to know what facts should be inserted cmds.add(CommandFactory.newFireAllRules()); batchExecutionCommand = CommandFactory.newBatchExecution(cmds); batchResult = (ExecutionResults) statelessKieSession.execute(batchExecutionCommand); LOGGER.info(" batchResult = {}", batchResult); } @Override public void beforeContainerStopped(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void afterContainerStopped(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void beforeContainerActivated(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void afterContainerActivated(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void beforeContainerDeactivated(KieServer kieServer, KieContainerInstance containerInstance) {} @Override public void afterContainerDeactivated(KieServer kieServer, KieContainerInstance containerInstance) {} } <file_sep>/not-supported/Ex-RuleUnit-7.36/README.md ## RuleUnit in pure Drools 7.x is not recommended/supported. It's used only for Kogito as of now. ## This example just explains how it works with pure Drools in status quo<file_sep>/Ex-kie-server-xstream-extension-nil-converter-7.48.0.Final-redhat-00004/src/main/java/org/example/kie/server/xstream/extension/NilableReflectionConverter.java package org.example.kie.server.xstream.extension; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NilableReflectionConverter extends ReflectionConverter { private static final Logger LOG = LoggerFactory.getLogger(NilableReflectionConverter.class); public NilableReflectionConverter(Mapper mapper, ReflectionProvider reflectionProvider) { super(mapper, reflectionProvider); } public boolean canConvert(Class type) { return type != null && type.getCanonicalName().equals("com.sample.Person") && canAccess(type); } @Override protected void doMarshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) { super.doMarshal(source, writer, context); addNilFields(source, writer); } private void addNilFields(Object source, HierarchicalStreamWriter writer) { Class clazz = source.getClass(); try { BeanInfo info = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals("class")) { continue; } try { Method readMethod = propertyDescriptor.getReadMethod(); Object value = readMethod.invoke(source); if (value == null) { writer.startNode(propertyDescriptor.getName()); writer.addAttribute("nil", "true"); writer.endNode(); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.warn("failed to get {}", propertyDescriptor.getName(), e); } } } catch (IntrospectionException e) { LOG.warn("failed to introspect {}", clazz.getName(), e); } } // No need to override doUnmarshal() because NilableConverter.unmarshal() does the job } <file_sep>/Ex-kie-server-warmup-listener-7.48.0.Final-redhat-00006/README.txt ## kie-server-warmup-listener You can implement KieServerEventListener to do some "warm-up" task right after kjar deployment so that kie-server can make the first response quicker. ### How to use Environment: RHDM/RHPAM 7.10.1 - Build my-kie-server-warmup-listener $ mvn clean install - Copy target/my-kie-server-warmup-listener-7.48.0.Final-redhat-00006.jar to ~/jboss/standalone/deployments/kie-server.war/WEB-INF/lib/ - Start RHDM/RHPAM - Build Ex-kie-server-kjar-7.48.0.Final-redhat-00006 $ mvn clean install - Call CreateContainerWithInternalFireOnlyWarmup in Ex-kie-server-client-7.48.0.Final-redhat-00006 - You will see logs like this ``` 19:00:35,080 INFO [org.kie.server.services.impl.KieServerImpl] (default task-2) Container kie-server-kjar-example_1.0.0 (for release id com.sample:kie-server-kjar-example:1.0.0) successfully started 19:00:35,081 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) start warmup : internal-fire-only 19:00:35,081 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) internalWarmupFireOnly 19:00:35,081 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) warmup : kieSessionName = myStatelessKsession 19:00:35,083 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) warmup : kieSessionName = myStatefulKsession 19:00:35,084 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) warmup : kieSessionName = myStatelessKsession2 19:00:35,085 INFO [stdout] (default task-2) init 19:00:35,086 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) warmup : kieSessionName = myStatefulKsession2 19:00:35,087 INFO [stdout] (default task-2) init 19:00:35,087 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) afterContainerStarted : elapsed time = 6ms ``` Then, next request (StatelessTestInteger.java, StatelessTestPerson) will be (slightly) quicker. - Call DisposeContainer in Ex-kie-server-client-7.48.0.Final-redhat-00006 to dispose the container - Call CreateContainerWithInternalFullWarmup in Ex-kie-server-client-7.48.0.Final-redhat-00006 - You will see logs like this ``` 19:02:40,480 INFO [org.kie.server.services.impl.KieServerImpl] (default task-2) Container kie-server-kjar-example_1.0.0 (for release id com.sample:kie-server-kjar-example:1.0.0) successfully started 19:02:40,482 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) start warmup : internal-full 19:02:40,482 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) internalWarmupFull 19:02:40,482 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) obj = com.sample.Person@470da4b7 19:02:40,543 INFO [stdout] (default task-2) Ha ha ha 19:02:40,543 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) batchResult = org.drools.core.runtime.impl.ExecutionResultImpl@6bfcbcc1 19:02:40,548 INFO [stdout] (default task-2) init 19:02:40,549 INFO [stdout] (default task-2) Hello, George 19:02:40,549 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) batchResult = org.drools.core.runtime.impl.ExecutionResultImpl@2ed58d46 19:02:40,549 INFO [org.example.kie.server.warmup.MyKieServerWarmupEventListener] (default task-2) afterContainerStarted : elapsed time = 67ms ``` Then, next request (StatelessTestInteger.java, StatelessTestPerson) will be much quicker. ---- my-kie-server-warmup-listener is an example implementation. MyKieServerWarmupEventListener is automatically enlisted in kie-server by `META-INF/services/org.kie.server.services.api.KieServerEventListener` MyKieServerWarmupEventListener.internalWarmupFireOnly() executes FireAllRules only. MyKieServerWarmupEventListener.internalWarmupFull() inserts expected facts and executes FireAllRules so that it gives better warm-up. Notice that MyKieServerWarmupEventListener.internalWarmupFull() should know that there are 2 StatelessKieSession "myStatelessKsession" "myStatelessKsession2" are defined in a kjar (expecting to test with Ex-kie-server-kjar-7.48.0.Final-redhat-00006). MyKieServerWarmupEventListenerVariant.java contains other approaches (kie-server-client REST call). But not actually called. Just as a hint for implementation. <file_sep>/Ex-spreadsheet-watch-7.60/src/main/java/com/sample/CommissionStructure.java package com.sample; public enum CommissionStructure { ADJUSTED, STANDARD } <file_sep>/Ex-KieFileSystem-multi-KieContainer-em-8.29/src/test/java/com/sample/DroolsTest.java package com.sample; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.drools.model.codegen.ExecutableModelProject; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { private final KieServices ks = KieServices.Factory.get(); private final ReleaseId releaseIdCustomerA1 = ks.newReleaseId("com.sample", "my-sample-customer-a", "1.0.0"); private final ReleaseId releaseIdCustomerB1 = ks.newReleaseId("com.sample", "my-sample-customer-b", "1.0.0"); private final ReleaseId releaseIdCustomerA2 = ks.newReleaseId("com.sample", "my-sample-customer-a", "2.0.0"); @Test public void differentArtifactIdsAndVersions() throws Exception { System.out.println("===== differentArtifactIdsAndVersions"); System.out.println("--- Create CustomerA version 1 KieContainer"); List<File> fileListA1 = new ArrayList<>(); fileListA1.add(new File("work/CommonRule-1.drl")); fileListA1.add(new File("work/CustomerA-1.drl")); createKieContainer(releaseIdCustomerA1, fileListA1); System.out.println("--- Create CustomerB version 1 KieContainer"); List<File> fileListB1 = new ArrayList<>(); fileListB1.add(new File("work/CommonRule-1.drl")); fileListB1.add(new File("work/CustomerB-1.drl")); createKieContainer(releaseIdCustomerB1, fileListB1); System.out.println("--- Use CustomerA version 1 KieContainer"); KieContainer kcontainerA1 = ks.newKieContainer(releaseIdCustomerA1); KieSession ksessionA1 = kcontainerA1.newKieSession(); try { ksessionA1.insert(new Person("John", 35)); ksessionA1.fireAllRules(); } finally { ksessionA1.dispose(); } System.out.println("--- Use CustomerB version 1 KieContainer"); KieContainer kcontainerB1 = ks.newKieContainer(releaseIdCustomerB1); KieSession ksessionB1 = kcontainerB1.newKieSession(); try { ksessionB1.insert(new Person("John", 35)); ksessionB1.fireAllRules(); } finally { ksessionB1.dispose(); } System.out.println("--- Create CustomerA version 2 KieContainer"); List<File> fileListA2 = new ArrayList<>(); fileListA2.add(new File("work/CommonRule-1.drl")); fileListA2.add(new File("work/CustomerA-2.drl")); createKieContainer(releaseIdCustomerA2, fileListA2); System.out.println("--- Use CustomerA version 2 KieContainer"); KieContainer kcontainerA2 = ks.newKieContainer(releaseIdCustomerA2); KieSession ksessionA2 = kcontainerA2.newKieSession(); try { ksessionA2.insert(new Person("John", 35)); ksessionA2.fireAllRules(); } finally { ksessionA2.dispose(); } } private void createKieContainer(ReleaseId releaseId, List<File> fileList) { KieServices ks = KieServices.Factory.get(); // KieFileSystem is responsible for gathering resources KieFileSystem kfs = ks.newKieFileSystem(); for (File file : fileList) { // You can add your DRL files as InputStream here try { kfs.write("src/main/resources/com/sample/" + file.getName(), ks.getResources().newInputStreamResource(new FileInputStream(file))); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } kfs.generateAndWritePomXML(releaseId); // Now resources are built and stored into an internal repository ks.newKieBuilder(kfs).buildAll(ExecutableModelProject.class); } } <file_sep>/Ex-kie-server-process-client-7.58/src/test/java/com/sample/KieServerRestUtils.java package com.sample; import static com.sample.Constants.BASE_URL; import java.util.ArrayList; import java.util.List; import org.kie.server.api.KieServerConstants; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesFactory; import org.kie.server.client.ProcessServicesClient; import org.kie.server.client.QueryServicesClient; import org.kie.server.client.RuleServicesClient; import org.kie.server.client.UserTaskServicesClient; public class KieServerRestUtils { private static final String DEFAULT_USERNAME = "kieserver"; private static final String DEFAULT_PASSWORD = "<PASSWORD>!"; public static KieServicesClient getKieServicesClient(String username, String password) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, username, password); List<String> capabilities = new ArrayList<String>(); capabilities.add(KieServerConstants.CAPABILITY_BPM); config.setCapabilities(capabilities); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); return client; } public static UserTaskServicesClient getUserTaskServicesClient() { return getUserTaskServicesClient(DEFAULT_USERNAME, DEFAULT_PASSWORD); } public static UserTaskServicesClient getUserTaskServicesClient(String username, String password) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, username, password); List<String> capabilities = new ArrayList<String>(); capabilities.add(KieServerConstants.CAPABILITY_BPM); config.setCapabilities(capabilities); config.setTimeout(600000); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); UserTaskServicesClient userTaskServiceClient = client.getServicesClient(UserTaskServicesClient.class); return userTaskServiceClient; } public static QueryServicesClient getQueryServicesClient() { return getQueryServicesClient(DEFAULT_USERNAME, DEFAULT_PASSWORD); } public static QueryServicesClient getQueryServicesClient(String username, String password) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, username, password); List<String> capabilities = new ArrayList<String>(); capabilities.add(KieServerConstants.CAPABILITY_BPM); config.setCapabilities(capabilities); // config.setMarshallingFormat(MarshallingFormat.JSON); config.setMarshallingFormat(MarshallingFormat.JAXB); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); QueryServicesClient queryServiceClient = client.getServicesClient(QueryServicesClient.class); return queryServiceClient; } public static ProcessServicesClient getProcessServicesClient() { return getProcessServicesClient(DEFAULT_USERNAME, DEFAULT_PASSWORD); } public static ProcessServicesClient getProcessServicesClient(String username, String password) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, username, password); List<String> capabilities = new ArrayList<String>(); capabilities.add(KieServerConstants.CAPABILITY_BPM); config.setCapabilities(capabilities); config.setMarshallingFormat(MarshallingFormat.JSON); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); ProcessServicesClient processServiceClient = client.getServicesClient(ProcessServicesClient.class); return processServiceClient; } public static RuleServicesClient getRuleServicesClient() { return getRuleServicesClient(DEFAULT_USERNAME, DEFAULT_PASSWORD); } public static RuleServicesClient getRuleServicesClient(String username, String password) { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, username, password); List<String> capabilities = new ArrayList<String>(); capabilities.add(KieServerConstants.CAPABILITY_BRM); capabilities.add(KieServerConstants.CAPABILITY_BPM); config.setCapabilities(capabilities); config.setTimeout(60000); KieServicesClient client = KieServicesFactory.newKieServicesClient(config); RuleServicesClient ruleServiceClient = client.getServicesClient(RuleServicesClient.class); return ruleServiceClient; } } <file_sep>/Ex-kie-server-xstream-extension-nil-converter-7.48.0.Final-redhat-00004/src/test/java/com/sample/RoundTripTest.java package com.sample; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.kie.server.api.marshalling.Marshaller; import org.kie.server.api.marshalling.MarshallerFactory; import org.kie.server.api.marshalling.MarshallingFormat; public class RoundTripTest { @Test public void roundTrip() { Set<Class<?>> extraClasses = new HashSet<Class<?>>(); extraClasses.add(Person.class); Marshaller marshaller = MarshallerFactory.getMarshaller(extraClasses, MarshallingFormat.XSTREAM, getClass().getClassLoader()); Person person = new Person(null, 35); String payload = marshaller.marshall(person); System.out.println("--- payload"); System.out.println(payload); Person person2 = marshaller.unmarshall(payload, Person.class); System.out.println(); System.out.println("--- unmarshalled value"); System.out.println(person2); } } <file_sep>/not-supported/Ex-RuleUnit-7.36/src/main/java/com/sample/DroolsTest.java package com.sample; import org.drools.ruleunit.DataSource; import org.drools.ruleunit.RuleUnit; import org.drools.ruleunit.RuleUnitExecutor; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; /** * * RuleUnit in pure Drools 7.x is not recommended/supported. It's used only for Kogito as of now. * This example just explains how it works with pure Drools in status quo * */ public class DroolsTest { public static void main(String[] args) { KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); // Create a `RuleUnitExecutor` class and bind it to the KIE base: KieBase kbase = kContainer.getKieBase(); RuleUnitExecutor executor = RuleUnitExecutor.create().bind(kbase); DataSource<Person> persons = DataSource.create(new Person("John", 42), new Person("Jane", 44), new Person("Sally", 4)); // Create the `AdultUnit` rule unit using the `persons` data source and run the executor: RuleUnit adultUnit = new AdultUnit(persons, 18); executor.run(adultUnit); // Can re-use // System.out.println("---"); // persons.insert(new Person( "Paul", 40 )); // executor.run(adultUnit); executor.dispose(); } } <file_sep>/Ex-global-by-listener-7.61/src/main/java/com/sample/GlobalSetUpListener.java package com.sample; import java.util.ArrayList; import java.util.List; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; import org.kie.api.event.rule.RuleRuntimeEventListener; import org.kie.api.runtime.KieSession; public class GlobalSetUpListener implements RuleRuntimeEventListener { @Override public void objectDeleted(ObjectDeletedEvent arg0) { // TODO Auto-generated method stub } @Override public void objectInserted(ObjectInsertedEvent event) { System.out.println(event); Object obj = event.getObject(); if (obj instanceof String && "reset".equals(obj)) { System.out.println("RESET!!"); KieSession ksession = (KieSession)event.getKieRuntime(); List<String> resultList = new ArrayList<>(); ksession.setGlobal("resultList", resultList); } } @Override public void objectUpdated(ObjectUpdatedEvent arg0) { // TODO Auto-generated method stub } } <file_sep>/Ex-template-7.74/src/test/java/com/sample/DroolsTest.java package com.sample; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.drools.decisiontable.ExternalSpreadsheetCompiler; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.ReleaseId; import org.kie.api.definition.KiePackage; import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { @Test public void testTemplate() { // first, generate a drl using template and values final ExternalSpreadsheetCompiler converter = new ExternalSpreadsheetCompiler(); final KieServices ks = KieServices.Factory.get(); final Resource valueTable = ks.getResources().newClassPathResource("sample_cheese.xls", DroolsTest.class); final Resource template = ks.getResources().newClassPathResource("sample_cheese.drt", DroolsTest.class); String drl = null; try { // the data we are interested in starts at row 2, column 2 (i.e. B2) drl = converter.compile(valueTable.getInputStream(), template.getInputStream(), 2, 2); } catch (IOException e) { throw new IllegalArgumentException("Could not read spreadsheet or rules stream.", e); } // build the generated drl final Resource drlResource = ks.getResources().newReaderResource(new StringReader(drl)); drlResource.setTargetPath("src/main/resources/rule.drl"); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write("src/main/resources/com/sample/rule.drl", drlResource); ReleaseId releaseId = ks.newReleaseId("com.sample", "my-sample-a", "1.0.0"); kfs.generateAndWritePomXML(releaseId); ks.newKieBuilder(kfs).buildAll(); KieContainer kcontainer = ks.newKieContainer(releaseId); KieBase kbase = kcontainer.getKieBase(); final Collection<KiePackage> pkgs = kbase.getKiePackages(); System.out.println("pkgs = " + pkgs); final KieSession ksession = kbase.newKieSession(); ksession.insert(new Cheese("stilton")); ksession.insert(new Person("michael", 42)); final List<String> list = new ArrayList<String>(); ksession.setGlobal("list", list); ksession.fireAllRules(); System.out.println("list = " + list.toString()); ksession.dispose(); } } <file_sep>/Ex-drools-webapp-7.36/README.md ### Build ~~~ $ mvn clean package ~~~ or ~~~ $ mvn clean install ~~~ ### Access the application The application will be running at <http://localhost:8080/drools-test/hello> You can specify "user" as a query parameter like: ~~~ $ curl http://localhost:8080/drools-test/hello?user=drools ~~~ For example: ~~~ $ curl http://localhost:8080/drools-test/hello <html> <head> <title>DroolsExampleServlet</title> </head> <body> <h1> message = Goodbye cruel world </h1> </body> </html> ~~~ ~~~ $ curl http://localhost:8080/drools-test/hello?user=drools <html> <head> <title>DroolsExampleServlet</title> </head> <body> <h1> message = Goodbye cruel drools </h1> </body> </html> ~~~ And you can see the log messages like the following in server.log: ~~~ 15:57:44,022 INFO [com.sample.DroolsExampleServlet] (default task-1) doGet() is invoked 15:57:44,030 INFO [stdout] (default task-1) KieSession[2] : Hello, world 15:57:44,034 INFO [stdout] (default task-1) KieSession[2] : Goodbye cruel world 15:57:51,216 INFO [com.sample.DroolsExampleServlet] (default task-1) doGet() is invoked 15:57:51,221 INFO [stdout] (default task-1) KieSession[3] : Hello, drools 15:57:51,230 INFO [stdout] (default task-1) KieSession[3] : Goodbye cruel drools ~~~ <file_sep>/Ex-kie-server-client-7.38/src/test/java/com/sample/DMNTest.java package com.sample; import static com.sample.Constants.BASE_URL; import static com.sample.Constants.CONTAINER_ID; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; import org.kie.api.command.KieCommands; import org.kie.api.runtime.ExecutionResults; import org.kie.dmn.api.core.DMNContext; import org.kie.dmn.api.core.DMNDecisionResult; import org.kie.dmn.api.core.DMNResult; import org.kie.server.api.model.ServiceResponse; import org.kie.server.client.DMNServicesClient; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesFactory; import org.kie.server.client.RuleServicesClient; public class DMNTest extends TestCase { private static final String USERNAME = "kieserver"; private static final String PASSWORD = "<PASSWORD>!"; private static final String KSESSION_NAME = "myStatelessKsession"; private static final String GLOBAL_IDENTIFIER = "results"; // private static final MarshallingFormat FORMAT = MarshallingFormat.JSON; // private static final MarshallingFormat FORMAT = MarshallingFormat.JAXB; @Test public void testProcess() { KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(BASE_URL, USERNAME, PASSWORD); // config.setMarshallingFormat(FORMAT); // HashSet<Class<?>> classes = new HashSet<Class<?>>(); // classes.add(Person.class); // // config.addExtraClasses(classes); KieServicesClient kieServicesClient = KieServicesFactory.newKieServicesClient(config); DMNServicesClient dmnClient = kieServicesClient.getServicesClient(DMNServicesClient.class); DMNContext dmnContext = dmnClient.newContext(); Map<String, Object> driverMap = new HashMap<>(); driverMap.put("Points", 2); dmnContext.set("Driver", driverMap); Map<String, Object> violationMap = new HashMap<>(); violationMap.put("Type", "speed"); violationMap.put("Actual Speed", 120); violationMap.put("Speed Limit", 100); dmnContext.set("Violation", violationMap); ServiceResponse<DMNResult> serverResp = dmnClient.evaluateAll(CONTAINER_ID, "https://github.com/kiegroup/drools/kie-dmn/_A4BCA8B8-CF08-433F-93B2-A2598F19ECFF", "Traffic Violation", dmnContext); DMNResult dmnResult = serverResp.getResult(); for (DMNDecisionResult dr : dmnResult.getDecisionResults()) { System.out.println( "Decision: '" + dr.getDecisionName() + "', " + "Result: " + dr.getResult()); } } } <file_sep>/Ex-metric-8.34/src/test/java/com/sample/JoinTest.java package com.sample; import java.util.ArrayList; import java.util.List; import org.drools.core.reteoo.ReteDumper; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import static org.junit.Assert.assertEquals; public class JoinTest { private final int NUM_CUSTOMER = 10; private final int NUM_ORDER_PER_CUSTOMER = 100; @Test public void testJoin() { System.setProperty("drools.metric.logger.enabled", "true"); System.setProperty("drools.metric.logger.threshold", "500"); // microseconds KieServices ks = KieServices.Factory.get(); KieContainer kcontainer = ks.getKieClasspathContainer(); KieBase kbase = kcontainer.getKieBase(); KieSession ksession = kbase.newKieSession(); List<List<Order>> result = new ArrayList<>(); ksession.setGlobal("result", result); // convenient static methods System.out.println("======= dumpRete output"); ReteDumper.dumpRete(kbase); System.out.println("======="); System.out.println(); System.out.println("======= dumpAssociatedRulesRete output"); ReteDumper.dumpAssociatedRulesRete(kbase); System.out.println("======="); System.out.println(); for (int i = 0; i < NUM_CUSTOMER; i++) { Customer cust = new Customer("Customer" + i); ksession.insert(cust); for (int j = 0; j < NUM_ORDER_PER_CUSTOMER; j++) { long id = (i * NUM_ORDER_PER_CUSTOMER) + j; int price = j * 10; Order order = new Order(id, cust, "Item" + j, price); ksession.insert(order); } } System.out.println("-----------"); long start = System.currentTimeMillis(); ksession.fireAllRules(); System.out.println(" -> elapsed time (ms) : " + (System.currentTimeMillis() - start)); ksession.dispose(); System.out.println("result.size() = " + result.size()); assertEquals(100, result.size()); } } <file_sep>/Ex-kogito-syntax-spreadsheet-experiment-7.58/README.txt This project is just to explain how to convert assets in kogito-examples to standard Drools assets. Basically, you don't need to understand this approach. If you use standard Drools, just refer to standard Drools examples or test cases. <file_sep>/Ex-kjar-dep-test-7.48/src/test/java/com/sample/DroolsTest.java package com.sample; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class DroolsTest { @Test public void testContainer() { try { KieServices ks = KieServices.Factory.get(); ReleaseId releaseId = ks.newReleaseId("com.sample", "kjar-dep-parent", "1.0.0-SNAPSHOT"); KieContainer kContainer = ks.newKieContainer(releaseId); KieSession kSession = kContainer.newKieSession(); Person john = new Person("john", 20); kSession.insert(john); kSession.fireAllRules(); kSession.dispose(); } catch (Throwable t) { t.printStackTrace(); } } } <file_sep>/Ex-ruleunit-add-8.32/src/main/java/org/example/ExampleUnit.java package org.example; import org.drools.ruleunits.api.DataSource; import org.drools.ruleunits.api.DataStore; import org.drools.ruleunits.api.RuleUnitData; public class ExampleUnit implements RuleUnitData { private final DataStore<Variable> variables; private final DataStore<String> strings; public ExampleUnit() { this(DataSource.createStore(), DataSource.createStore()); } public ExampleUnit(DataStore<Variable> variables, DataStore<String> strings) { this.variables = variables; this.strings = strings; } public DataStore<Variable> getVariables() { return variables; } public DataStore<String> getStrings() { return strings; } }
cf07f2eee4c7f857626e0b203604d03d05c0cabd
[ "Markdown", "Java", "Text", "Maven POM" ]
41
Text
tkobayas/kiegroup-examples
885848c86fc97c7926e73d4d9a75b6b698f6e784
62e7677cb83bcd9e844b780bac09106d0cd693bd
refs/heads/master
<repo_name>DharmeshKheni/button-to-Image<file_sep>/imageTesting/ViewController.swift // // ViewController.swift // imageTesting // // Created by Anil on 02/02/15. // Copyright (c) 2015 Variya Soft Solutions. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func btn1(sender: AnyObject) { let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as ImageViewController secondViewController.imageString = "1.png" self.navigationController?.pushViewController(secondViewController, animated: true) } @IBAction func btn2(sender: AnyObject) { let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as ImageViewController secondViewController.imageString = "2.png" self.navigationController?.pushViewController(secondViewController, animated: true) } @IBAction func btn3(sender: AnyObject) { let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as ImageViewController secondViewController.imageString = "3.png" self.navigationController?.pushViewController(secondViewController, animated: true) } @IBAction func btn4(sender: AnyObject) { let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as ImageViewController secondViewController.imageString = "4.png" self.navigationController?.pushViewController(secondViewController, animated: true) } @IBAction func btn5(sender: AnyObject) { let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as ImageViewController secondViewController.imageString = "5.png" self.navigationController?.pushViewController(secondViewController, animated: true) } } <file_sep>/imageTesting/ImageViewController.swift // // ImageViewController.swift // imageTesting // // Created by Anil on 02/02/15. // Copyright (c) 2015 Variya Soft Solutions. All rights reserved. // import UIKit class ImageViewController: UIViewController { var imageString = String() @IBOutlet weak var imgView: UIImageView! override func viewDidLoad() { super.viewDidLoad() var image = UIImage(named: imageString) self.imgView.image = image } }
3b32f77df702c13c6ab85f21ddd4abdc65d9b9f4
[ "Swift" ]
2
Swift
DharmeshKheni/button-to-Image
77c451f4cd2161934830fab3705ff6a896f2c0fe
6fe320fba327ab44ccd2bb48c76df4b26571b4e6
refs/heads/main
<file_sep>export interface ImportantDayInterface { id: string; title: string; type: string; address?: string; time?: string; description?: string; budget?: string; date?: string; } <file_sep>export * from './important-day.service'; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MaterialModule } from '../material/material.module'; import { RouterModule } from '@angular/router'; import { IMPORTANT_ROUTES } from './important.routing'; import { DayComponent } from './components/day/day.component'; import { DayEditComponent } from './components/day-edit/day-edit.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ DayComponent, DayEditComponent ], imports: [ CommonModule, RouterModule.forChild(IMPORTANT_ROUTES), MaterialModule, ReactiveFormsModule ] }) export class ImportantDayModule { } <file_sep>export * from './important-day.interface'; <file_sep>import { Routes } from '@angular/router'; export const APP_ROUTES: Routes = [ { path: '', redirectTo: 'day', pathMatch: 'full' }, { path: 'day', loadChildren: () => import('./modules/important-day/important-day.module.js') .then(m => m.ImportantDayModule), }, { path: '**', redirectTo: 'day', pathMatch: 'full' } ]; <file_sep>export enum ImportantDayEnum { HOLIDAY = 'holidays', EVENT = 'event', OTHER_DAY = 'other-day' } <file_sep>import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MatSelectChange } from '@angular/material/select'; import { ImportantDayEnum } from '../../../../core/enums'; import { ActivatedRoute } from '@angular/router'; import { ImportantDayService } from '../../../../core/services/important-day.service'; import { first } from 'rxjs/operators'; import { ImportantDayInterface } from '../../../../core/models'; import { MatSnackBar } from '@angular/material/snack-bar'; interface RouterParams { mode: string; id: string; } @Component({ selector: 'app-day-edit', templateUrl: './day-edit.component.html', styleUrls: ['./day-edit.component.scss'] }) export class DayEditComponent implements OnInit { form: FormGroup; private routeParams: RouterParams; private importantDay: ImportantDayInterface; get f(): any { return this.form.controls; } ngOnInit(): void { this.routeParams = this.activatedRoute.snapshot.params as RouterParams; if (this.routeParams.mode === 'edit') { return this.getImportantDay(); } this.initForm(ImportantDayEnum.HOLIDAY); } onSubmit(): void { if (this.routeParams.mode === 'edit' && this.importantDay) { this.importantDayService.update(this.form.value) .pipe(first()) .subscribe(() => this.snackBar.open('Данные успешно обновлены')); } else { this.importantDayService.add(this.form.value) .pipe(first()) .subscribe(() => this.snackBar.open('Данные успешно сохранены')); } console.log(this.form.value); } initForm(type: string): void { const form: any = { id: new Date().getTime().toString(), title: [this.form ? this.form.get('title').value : '', Validators.required], type: [type, Validators.required], date: this.routeParams.mode === 'add' ? this.routeParams.id : this.importantDay.date, }; if (type === ImportantDayEnum.EVENT) { form.address = ['', Validators.required]; form.time = ['', Validators.required]; } else if (type === ImportantDayEnum.OTHER_DAY) { form.description = ['', Validators.required]; } else { form.budget = ['', Validators.required]; } this.form = this.fb.group(form); } private getImportantDay(): void { this.importantDayService.getOne(this.routeParams.id) .pipe(first()) .subscribe((res: ImportantDayInterface) => { this.importantDay = res; this.initForm(res ? res.type : ImportantDayEnum.HOLIDAY); this.form.patchValue(res); }); } constructor( private fb: FormBuilder, private activatedRoute: ActivatedRoute, private importantDayService: ImportantDayService, private snackBar: MatSnackBar ) { } } <file_sep>import { Component, OnDestroy, OnInit } from '@angular/core'; import { ImportantDayService } from '../../../../core/services/important-day.service'; import { Observable, Subject } from 'rxjs'; import { ImportantDayInterface } from '../../../../core/models'; import { FormControl, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { first, takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-day', templateUrl: './day.component.html', styleUrls: ['./day.component.scss'] }) export class DayComponent implements OnInit, OnDestroy { date = new FormControl(new Date(), Validators.required); importantDays: ImportantDayInterface[]; private destroy$ = new Subject(); ngOnInit(): void { this.getImplementDays(this.date.value.toISOString()); this.date.valueChanges .pipe(takeUntil(this.destroy$)) .subscribe((value: Date) => this.getImplementDays(value.toISOString())); } ngOnDestroy(): void { this.destroy$.next(true); this.destroy$.unsubscribe(); } addEvent(): void { const date = new Date(this.date.value); date.setHours(0, 0, 0, 0); this.router.navigate(['/day', 'add', date.toISOString()]); } edit(item: ImportantDayInterface): void { this.router.navigate(['/day', 'edit', item.id]); } delete(item: ImportantDayInterface, index: number): void { this.importantDayService.delete(item.id) .pipe(first()) .subscribe((res) => this.importantDays.splice(index, 1)); } private getImplementDays(date: string): void { this.importantDayService.getAll(date) .pipe(first()) .subscribe((res: ImportantDayInterface[]) => this.importantDays = res); } constructor( private importantDayService: ImportantDayService, private router: Router ) { } } <file_sep>import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { ImportantDayInterface } from '../models'; @Injectable({ providedIn: 'root' }) export class ImportantDayService { private storageName = 'importantDays'; getAll(date: string): Observable<ImportantDayInterface[]> { const parseDate = date.substring(0, date.indexOf('T')); const items = this.getItems(); return of(items) .pipe( map(importantDays => { return importantDays.filter(item => item.date.includes(parseDate)); }) ); } getOne(id: string): Observable<ImportantDayInterface> { const items = this.getItems(); const findImportantDay = items.find(item => item.id === id); return of(findImportantDay); } add(data: ImportantDayInterface): Observable<ImportantDayInterface> { const items = this.getItems(); items.push(data); localStorage.setItem(this.storageName, JSON.stringify(items)); return of(data); } update(data: ImportantDayInterface): Observable<ImportantDayInterface> { const items = this.getItems(); const findImportantDayIndex = items.findIndex(item => item.id === data.id); items[findImportantDayIndex] = data; localStorage.setItem(this.storageName, JSON.stringify(items)); return of(data); } delete(id: string): Observable<boolean> { const items = this.getItems(); localStorage.setItem(this.storageName, JSON.stringify( items.filter(item => item.id !== id) )); return of(true); } private getItems(): ImportantDayInterface[] { return JSON.parse(localStorage.getItem(this.storageName) || '[]'); } constructor() { } } <file_sep>import { Routes } from '@angular/router'; import { DayComponent } from './components/day/day.component'; import { DayEditComponent } from './components/day-edit/day-edit.component'; export const IMPORTANT_ROUTES: Routes = [ { path: '', component: DayComponent }, { path: ':mode/:id', component: DayEditComponent } ]; <file_sep>export * from './important-day.enum';
918fd88236a96db2aacb8097922ce99496e02828
[ "TypeScript" ]
11
TypeScript
Abdumannon26/important-day
5072e9cc59e10f8a89f7a2e0346942cce26fdc8c
5f52856f331381f49fb9a1f0446e20aae1e569a8
refs/heads/master
<repo_name>karamk-immalle/Shape<file_sep>/WpfApplication8/MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication8 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void drawButton_Click(object sender, RoutedEventArgs e) { //Rectangle rect = new Rectangle(); //rect.Stroke = new SolidColorBrush(Colors.Black); //rect.Width = 100; //rect.Height = 70; //rect.Margin = new Thickness(10, 10, 10, 0); //canvas.Children.Add(rect); Circle circle = new Circle(40, 40); Square squarel = new Square(180, 180); List<Shape> group = new List<Shape>(); group.Add(circle); group.Add(squarel); foreach (Shape shape in group) { shape.DisplayOn(canvas); } } } }
4a72a77b8e25548cd5b0ba79b53aa93088d977be
[ "C#" ]
1
C#
karamk-immalle/Shape
1f2033bf2ce36f8f8ece717cffab4677a402a84a
775060a82adc2014af6a079c80adbb85c8bfab50
refs/heads/master
<repo_name>ss-hoon/Data-Structure<file_sep>/스택/StackArray.cpp #include <iostream> #define MAX_SIZE 100 using namespace std; class Stack { private: int top; // 스택의 top int stack[MAX_SIZE]; // stack 배열 public: Stack() { // Stack 생성자 top = -1; // top 변수를 -1로 초기화 } void push(int data) { // push(stack에 값을 input) 함수 if (top >= MAX_SIZE - 1) cout << "Stack is Full" << endl; else stack[++top] = data; } int pop() { // pop(stack의 top부분 값 반환) 함수 if (top == -1) { cout << "Stack is Empty" << endl; return 0; } else return stack[top--]; } void peek() { // peek(stack의 top부분 출력) 함수 if (top == -1) cout << "Stack is Empty" << endl; else cout << stack[top] << endl; } }; int main() { Stack stack; stack.push(1); stack.push(2); stack.peek(); cout << stack.pop() << endl; stack.peek(); return 0; }<file_sep>/연결리스트/LinkedList.cpp #include <iostream> #include <cstdlib> using namespace std; struct Node { int data; // Node 내부의 data 값 struct Node * link; // List의 다음 노드를 가리킬 Node 포인터 }; class LinkedList { private: Node * head; // LinkedList의 첫 노드 포인터 Node * tail; // LinkedList의 마지막 노드 포인터 int ListSize; // LinkedList의 전체 노드 개수 public: LinkedList() { // LinkedList 클래스의 생성자 (head, tail 포인터와 ListSize 변수를 초기화 해준다) head = tail = NULL; ListSize = 0; } // ----------------------------- insert 함수 ----------------------------- // parameter가 1개일 때는 맨 마지막 노드를 삽입 // parameter가 2개일 때는 두 번째 parameter의 위치에 노드를 삽입 void insert(int data) { // LinkedList의 맨 마지막 노드에 새로운 노드를 연결시키는 insert 함수 Node * newNode = (Node*)malloc(sizeof(Node)); // 새로운 노드의 메모리 공간을 확보 (동적할당) newNode->data = data; // parameter의 data값을 새로 할당한 newNode의 data 필드에 input newNode->link = NULL; // newNode의 포인터를 아무것도 가리키지 않게 한다 if (head == NULL) head = tail = newNode; // head 포인터가 아무것도 가리키지 않는 경우 LinkedList에는 아무것도 없으므로 head, tail 포인터를 새로 할당한 newNode를 가리키게 한다 else { tail->link = newNode; // tail이 가리키는 노드의 link 포인터를 새로 할당한 newNode를 가리키게 한다 tail = newNode; // tail이 newNode를 가리키게 한다 } ListSize++; // ListSize를 1 증가시킨다 } void insert(int data, int position) { // LinkedList의 postion 위치에 새로운 노드를 연결시키는 insert 함수 Node * temp_front = head; // Node형을 가리키는 포인터를 하나 선언해서 head 포인터가 현재 가리키고 있는 노드를 가리키게 한다 Node * temp_next; Node * newNode = (Node*)malloc(sizeof(Node)); // 새로운 노드의 메모리 공간을 확보 (동적할당) newNode->data = data; // parameter의 data값을 새로 할당한 newNode의 data 필드에 input if (position > ListSize + 1) { // 현재 LinkedList 노드의 총 개수 + 1보다 position이 큰 경우 return (노드를 삽입하면 현재 ListSize의 + 1개가 되기 때문) cout << "위치를 다시 설정해주세요" << endl; return; } if (head == NULL) { // 현재 LinkedList에 아무것도 없는 경우 newNode->link = NULL; // newNode의 link 포인터를 아무것도 가리키지 않게 한 후 head = tail = newNode; // head, tail 포인터를 newNode를 가리키게 한다 } else { // 현재 LinkedList에 하나 이상의 노드가 있는 경우 for (int index = 1; index < position - 1; index++) temp_front = temp_front->link; // 반복문과 노드의 link 포인터를 통해 삽입하려는 위치의 앞까지 temp를 이동시킨다 if (position == 1) { // 삽입하려는 노드의 위치가 맨 처음일 경우 newNode->link = head; // newNode의 link 포인터가 head가 가리키는 노드를 가리키게 한 후 head = newNode; // head가 newNode를 가리키게 한다 } else if (temp_front->link == NULL) { // 삽입하려는 노드의 위치가 맨 마지막일 경우 newNode->link = NULL; // newNode의 link 포인터를 아무것도 가리키지 않게 한 후 temp_front->link = newNode; // 앞서 반복문을 통해 이동한 temp_front의 link 포인터를 newNode를 가리키게 한다 tail = newNode; // tail이 newNode를 가리키게 한다 } else { // 삽입하려는 노드의 위치가 중간일 경우 temp_next = temp_front->link; // temp_next 포인터는 삽입하려는 위치의 다음 노드를 가리킨다 newNode->link = temp_next; // newNode의 link 포인터를 temp_next가 가리키는 노드를 가리키게 한다 temp_front->link = newNode; // temp_front가 가리키는 노드의 link 포인터를 newNode를 가리키게 한다 } } ListSize++; // ListSize를 1 증가시킨다 } // --------------------------------------------------------------------- // ----------------------------- erase 함수 ----------------------------- // parameter가 0개일 때는 맨마지막 노드를 삭제 // parameter가 1개일 때는 parameter 위치의 노드를 삭제 void erase() { // LinkedList의 맨 마지막 노드를 삭제하는 erase 함수 if (head == NULL) { // LinkedList의 노드가 없을 경우 cout << "삭제할 노드가 없습니다" << endl; return; } else if (head->link == NULL) { // LinkedList의 노드가 1개일 경우 Node * temp = head; // temp 포인터를 head가 가리키는 노드를 가리키게 한 후 free(temp); // 새로운 노드를 만들기 위해 동적으로 할당했던 힙 영역의 메모리를 다시 반환 head = tail = NULL; // head, tail 포인터를 아무것도 가리키지 않게 한다 } else { Node * temp_front; Node * temp_next = tail; for (temp_front = head; temp_front->link != tail; temp_front = temp_front->link); // temp_front 포인터를 LinkedList 맨 마지막 노드의 앞 노드를 가리키게 한다 free(temp_next); // LinkedList 마지막 노드 메모리 공간을 반환 temp_front->link = NULL; // temp_front의 link 포인터를 아무것도 가리키지 않게 한다 tail = temp_front; // tail 포인터를 temp_front가 가리키는 노드를 가리키게 한다 } ListSize--; // ListSize를 1 감소시킨다 } void erase(int position) { // LinkedList의 position 위치의 노드를 삭제하는 erase 함수 if (position > ListSize) { // 현재 LinkedList 노드의 총 개수보다 position이 큰 경우 return cout << "위치를 다시 설정해주세요" << endl; return; } if (head == NULL) { // LinkedList에 노드가 없을 경우 cout << "삭제할 노드가 없습니다" << endl; return; } else { // LinkedList에 노드가 있을 경우 Node * temp_front = head; Node * temp_next; for (int index = 1; index < position - 1; index++) temp_front = temp_front->link; // 반복문과 노드의 link 포인터를 통해 삽입하려는 위치의 앞까지 temp_front를 이동시킨다 if (position == 1) { // 삭제하려는 노드의 위치가 맨 처음 노드일 경우 ex) 리스트가 1-2-3일 경우 1을 삭제하는 경우 head = temp_front->link; // head 포인터가 temp_front의 link 포인터가 가리키는 노드를 가리키게 한 후 ex) head 포인터가 2를 가리키게 한다 free(temp_front); // temp_front가 가리키는 노드의 메모리를 반환한다 ex) 1을 메모리 반환한다 } else if (temp_front->link == tail) { // 삭제하려는 노드의 위치가 맨 마지막 노드일 경우 ex) 리스트가 1-2-3일 경우 3을 삭제하는 경우 temp_next = tail; // temp_next 포인터가 맨 마지막 노드를 가리키게 한다 ex) temp_next 포인터가 3을 가리키게 한다 temp_front->link = NULL; // temp_front의 link 포인터가 아무것도 가리키지 않게 한다 ex) 2에서 3으로 가는 연결을 끊는다 tail = temp_front; // tail 포인터가 temp_front가 가리키는 노드를 가리키게 한 후 ex) tail을 2를 가리키게 한다 free(temp_next); // temp_next가 가리키는 노드의 메모리를 반환한다 ex) 3을 메모리 반환한다 } else { // 삭제하려는 노드의 위치가 중간일 경우 ex) 리스트가 1-2-3일 경우 2를 삭제하는 경우 temp_next = temp_front->link; // temp_next 포인터가 temp_front의 link 포인터가 가리키는 노드를 가리키게 한다 ex) temp_next 포인터가 2를 가리키게 함 temp_front->link = temp_next->link; // temp_front의 link 포인터가 temp_next의 link 포인터를 가리키게 한 후 ex) 1을 3과 연결시킨다 free(temp_next); //temp_next가 가리키는 노드의 메모리를 반환한다 ex) 2를 메모리 반환한다 } } ListSize--; // ListSize를 1 감소시킨다 } // --------------------------------------------------------------------- int size() { // LinkedList의 노드 총 개수를 반환한다 return ListSize; } void print() { for (Node * temp = head; temp != tail->link; temp = temp->link) cout << temp->data << " "; // LinkedList를 순회하면서 data 값을 출력한다 cout << endl; } }; int main() { LinkedList list; list.insert(8, 1); list.insert(1); list.print(); list.insert(2); list.print(); list.insert(3, 2); list.print(); list.insert(4, 3); list.print(); list.erase(2); list.print(); list.erase(); list.print(); cout << "현재 LinkedList의 노드 총 개수는 " << list.size() << "개입니다." << endl; }<file_sep>/트리/traversal.cpp #include <iostream> #include <stack> using namespace std; typedef struct treeNode { treeNode * left; char data; treeNode * right; }treeNode; class Tree { private: int size; treeNode * root; public: Tree(char X) { // 트리 초기화 생성자 treeNode * node = new treeNode; node->data = X; node->left = NULL; node->right = NULL; root = node; size = 1; } treeNode * getRoot() { // root 노드 위치 반환 return root; } void makeTree(char X) { // 노드 추가 함수 stack<char> st; int location = size + 1; treeNode * temp = root; treeNode * newNode = new treeNode; newNode->data = X; newNode->left = NULL; newNode->right = NULL; while (location != 1) { // 완전 이진트리를 만들기 위한 전처리 작업 if (location % 2 == 0) st.push('L'); else st.push('R'); location /= 2; } while (st.size() != 1) { // 추가하려는 위치까지 이동 if (st.top() == 'L') temp = temp->left; else temp = temp->right; st.pop(); } // 해당 위치에 추가 if (st.top() == 'L') temp->left = newNode; else temp->right = newNode; size++; // 트리 전체 사이즈 증가 } void preorder(treeNode * node) { // 전위 순회 출력 if (node != NULL) { cout << node->data << " "; preorder(node->left); preorder(node->right); } } void inorder(treeNode * node) { // 중위 순회 출력 if (node != NULL) { inorder(node->left); cout << node->data << " "; inorder(node->right); } } void postorder(treeNode * node) { // 후위 순회 출력 if (node != NULL) { postorder(node->left); postorder(node->right); cout << node->data << " "; } } }; int main() { Tree tree('A'); tree.makeTree('B'); tree.makeTree('C'); tree.makeTree('D'); tree.makeTree('E'); tree.makeTree('F'); tree.makeTree('G'); tree.makeTree('H'); tree.makeTree('I'); cout << "Preorder -> "; tree.preorder(tree.getRoot()); cout << endl; cout << "Inorder -> "; tree.inorder(tree.getRoot()); cout << endl; cout << "Postorder -> "; tree.postorder(tree.getRoot()); cout << endl; return 0; }<file_sep>/트리/insert_delete.cpp #include <iostream> using namespace std; typedef struct treeNode { treeNode * left; int data; treeNode * right; }treeNode; class Tree { private: int size; treeNode * root; public: Tree(int X) { // 트리 초기화 생성자 treeNode * node = new treeNode; node->data = X; node->left = NULL; node->right = NULL; root = node; size = 1; } treeNode * getRoot() { // root 노드 위치 반환 return root; } treeNode * insertTree(treeNode * p, int X) { // 노드 추가 함수 if (p == NULL) { treeNode * newNode = new treeNode; newNode->data = X; newNode->left = NULL; newNode->right = NULL; size++; // 트리 전체 사이즈 증가 cout << X << " 노드가 추가되었습니다." << endl; return newNode; } else if (p->data > X) p->left = insertTree(p->left, X); else if (p->data < X) p->right = insertTree(p->right, X); else cout << "해당 키가 있습니다." << endl; return p; } void deleteTree(int X) { // 노드 삭제 함수 treeNode * parent = NULL; treeNode * child = root; while (child != NULL && child->data != X) { // 삭제하려는 노드 탐색 parent = child; if (child->data > X) child = child->left; else child = child->right; } if (child == NULL) { // 삭제하려는 노드가 없을 경우 cout << "해당 노드가 없습니다." << endl; return; } if (child->left == NULL && child->right == NULL) { // 삭제하려는 노드가 단말노드인 경우 if (parent != NULL) { // 삭제하려는 노드가 루트 노드가 아닌 경우 if (parent->left == child) parent->left = NULL; else parent->right = NULL; } else root = NULL; // 삭제하려는 노드가 루트 노드인 경우 } else if (child->left == NULL || child->right == NULL) { // 삭제하려는 노드가 하나의 자식노드를 가진 경우 treeNode * grandChild; if (child->left == NULL) grandChild = child->right; else grandChild = child->left; if (parent != NULL) { // 삭제하려는 노드가 루트 노드가 아닌 경우 if (parent->left == child) parent->left = grandChild; else parent->right = grandChild; } else root = grandChild; // 삭제하려는 노드가 루트 노드인 경우 } else { // 삭제하려는 노드가 두 자식노드를 가진 경우(왼쪽 자식노드의 맨 오른쪽 노드로 대체) treeNode * temp_parent = child; treeNode * temp_child = child->left; while (temp_child->right != NULL) { temp_parent = temp_child; temp_child = temp_child->right; } if (temp_parent->left == temp_child) temp_parent->left = temp_child->left; else temp_parent->right = temp_child->left; child->data = temp_child->data; child = temp_child; } delete child; } void preorder(treeNode * node) { // 전위 순회 출력 if (node != NULL) { cout << node->data << " "; preorder(node->left); preorder(node->right); } } void inorder(treeNode * node) { // 중위 순회 출력 if (node != NULL) { inorder(node->left); cout << node->data << " "; inorder(node->right); } } void postorder(treeNode * node) { // 후위 순회 출력 if (node != NULL) { postorder(node->left); postorder(node->right); cout << node->data << " "; } } }; int main() { Tree tree(20); tree.insertTree(tree.getRoot(), 30); tree.insertTree(tree.getRoot(), 8); tree.insertTree(tree.getRoot(), 15); tree.insertTree(tree.getRoot(), 4); tree.insertTree(tree.getRoot(), 13); tree.deleteTree(20); tree.deleteTree(13); tree.deleteTree(8); return 0; }<file_sep>/스택/StackArray.java class Stack{ int top; // 스택의 top int[] stack; // stack 배열 int stack_maxSize; // stack 최대 크기 Stack(int size){ // Stack 생성자 top = -1; stack = new int[size]; stack_maxSize = size; } public void push(int data){ // push 메소드 if(top >= stack_maxSize - 1){ System.out.println("Stack is Full"); } else { stack[++top] = data; } } public int pop(){ // pop 메소드 if(top == -1){ System.out.println("Stack is Empty"); return 0; } else { return stack[top--]; } } public void peek(){ // peek 메소드 if(top == -1){ System.out.println("Stack is Empty"); } else { System.out.println(stack[top]); } } } public class StackArray{ public static void main(String[] args){ Stack st = new Stack(100); st.push(1); st.push(2); st.peek(); System.out.println(st.pop()); st.peek(); } }
2b53ba2a4b8fe4e9fe945dfcc663ec76f3e5d31c
[ "Java", "C++" ]
5
C++
ss-hoon/Data-Structure
34b4266d2515902ed48e8f1780b7501870d6bb69
32b75b7ada3712d1dcc3c64a3cf797125450862c
refs/heads/master
<repo_name>krand/macos-reminder<file_sep>/terminal-notifier.app/Contents/MacOS/terminal-notifier #!/usr/bin/env bash terminal-notifier "$@" <file_sep>/README.md # macos-reminder ## Installation 1. Install https://github.com/julienXX/terminal-notifier 2. Enable ```launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist``` to make `at` command work 3. copy terminal-notifier to your Applications/ folder 4. chmod +x /Applications/Aterminal-notifier/Contents/MacOS/terminal-notifier 4. copy function to .zshrc 5. Check notification settings ## Usage ```$remindme <msg> <minutes>``` ```$remindme <msg> <hours>h``` <file_sep>/.zshrc function remindme() { local TIME_UNIT="minute" local TIME_VAL="$2" if [[ $TIME_VAL =~ "^([0-9]+)h$" ]]; then TIME_UNIT="hour" TIME_VAL=${match[1]} fi if [[ $TIME_VAL == "" ]]; then TIME_VAL="30" fi if [[ $TIME_VAL != "1" ]]; then TIME_UNIT=$TIME_UNIT"s" fi echo "open -a /Applications/terminal-notifier.app --args -title 'REMINDER:' -message '☝🏻$1' -sound default -sender com.apple.Terminal" | at now + $TIME_VAL $TIME_UNIT }
bea81d1a3f6a1eb81e7fd37def20737ef590c6df
[ "Markdown", "Shell" ]
3
Shell
krand/macos-reminder
3f0d857aa176ebb3d31c7cf890d863bfbafe10dc
f4f25dfa0cdd5695924c35752be4bd705e81b1b4
refs/heads/main
<file_sep>export interface Plant { id: string name: string about: string water_tips: string photo: string environments: string[] frequency: { times: number repeat_every: string } dateTimeNotification: Date hour: string } export type Environment = { key: string title: string } export type StoragePlant = { [id: string]: { data: Plant notificationId: string } } <file_sep>export default { heading: 'Jost600', text: 'Jost400', complement: 'Jost400', }
26e3f567f7640a0818490c3d832f8a3c80c51e32
[ "TypeScript" ]
2
TypeScript
MelkdeSousa/plantmanager
f42cfbb653baaab7e76c6e525097dd348cc3739f
784976f5147267deb8479d180e14d1f8c01f85f2
refs/heads/master
<file_sep>class App def call(env) perform_request [status, headers, body] end private def perform_request sleep rand(1..3) end def status 200 end def headers { 'Content-Type' => 'text/plain' } end def body ["Welcome aboard!\n"] end end
6a08c180ce6344d92e4b7bcc2f9fbf03e785d252
[ "Ruby" ]
1
Ruby
IljaBekirov/rack
ef251dc5ca09ac59a76b4f4d272801fce40d0b5c
fc81bbc658928cb3aa0f2300fc608b2f6cd05027
refs/heads/master
<repo_name>projet-javascript-4IW1/pokedex<file_sep>/app.js import {PokeRoutes} from './router.js'; import {Json} from './jsonmodule.js'; window.onload=function(){ function Pokemon(name,abilities,type,weakness,thumbnailImage,number,height,weight){ //private properties var name = name ? name : null; var abilities = abilities ? abilities : []; var type = type ? type : []; var weakness = weakness ? weakness : []; var thumbnailImage = thumbnailImage ? thumbnailImage : null; var number = number ? number : null; var height = height ? height : null; var weight = weight ? weight : null; this.getName = function(){ return name; } this.getAbilities = function(){ return abilities.join(' - '); } this.getType = function(){ return type.join(' - '); } this.getWeakness = function(){ return weakness.join(' - '); } this.getThumbnailImage = function(){ return thumbnailImage; } this.getNumber = function(){ return number; } this.getHeight = function(){ return height; } this.getWeight = function(){ return weight; } } let element; let button; let button_afficher; let afficherListe = function(){ let ul = document.createElement('ul'); ul.setAttribute('id','pokemonList'); document.getElementById('root').appendChild(ul); Json.getJSON('https://raw.githubusercontent.com/cheeaun/repokemon/master/data/pokemon-list.json', function(err, data) { if (err !== null) { alert('Impossible : ' + err); } else { data.forEach( pokemon => { let li = document.createElement('li'); li.setAttribute('class','item'); ul.appendChild(li); let div = document.createElement('div'); li.appendChild(div); let label = document.createElement('label'); let image = document.createElement('img'); div.appendChild(label); let name = document.createTextNode("Nom : " + prop_access(pokemon,"data.name")); image.setAttribute("src", prop_access(pokemon,"data.ThumbnailImage")); image.setAttribute("width", "150"); image.setAttribute("height", "150"); image.setAttribute("alt", prop_access(pokemon,"data.name")); label.appendChild(name); div.appendChild(image); li.addEventListener('click', function (e) { e.preventDefault(); let pokemon_obj = new Pokemon(pokemon['name'],pokemon['abilities'],pokemon['type'],pokemon['weakness'],pokemon['ThumbnailImage'],pokemon['number'],pokemon['height'],pokemon['weight']); history.pushState(`/${pokemon['id']}`, '', `/${pokemon['id']}`); PokeRoutes.createCard(pokemon_obj); }) }); } }); }; let searchListe = function(){ if(document.getElementById("pokemonList")){ document.getElementById("pokemonList").remove(); } let ul = document.createElement('ul'); ul.setAttribute('id','pokemonList'); document.getElementById('root').appendChild(ul); let criteria = document.getElementById('searchCrit').value; let string_verif = type_check_v1(document.getElementById('searchbar').value,"string"); if(string_verif){ let search = document.getElementById('searchbar').value; if(document.getElementById('alert')){ document.getElementById('alert').remove(); } Json.getJSON('https://raw.githubusercontent.com/cheeaun/repokemon/master/data/pokemon-list.json', function(err, data) { console.log(data); if (err !== null) { alert('Impossible : ' + err); } else { // let pokemons = []; data.forEach( pokemon => { let criteriavalidation = false; let re = new RegExp(tolower(search), 'gi'); if((criteria == "type" || criteria == "weakness") && tolower(prop_access(pokemon,"data."+criteria)).indexOf(tolower(search)) >= 0){ criteriavalidation = true; } else if(criteria == "name" && tolower(prop_access(pokemon,"data.name")).match(re)) { criteriavalidation = true; } if(search !== null && criteriavalidation == true){ let li = document.createElement('li'); li.setAttribute('class','item'); ul.appendChild(li); let div = document.createElement('div'); li.appendChild(div); let label = document.createElement('label'); let image = document.createElement('img'); div.appendChild(label); let name = document.createTextNode("Nom : " + prop_access(pokemon,"data.name")); image.setAttribute("src", prop_access(pokemon,"data.ThumbnailImage")); image.setAttribute("width", "150"); image.setAttribute("height", "150"); image.setAttribute("alt", prop_access(pokemon,"data.name")); label.appendChild(name); div.appendChild(image); li.addEventListener('click', function (e) { e.preventDefault(); let pokemon_obj = new Pokemon(pokemon['name'],pokemon['abilities'],pokemon['type'],pokemon['weakness'],pokemon['ThumbnailImage'],pokemon['number'],pokemon['height'],pokemon['weight']); history.pushState(`/${pokemon['id']}`, '', `/${pokemon['id']}`); PokeRoutes.createCard(pokemon_obj); }); } }); } }); } else { alert("Vous devez entrer une chaine de caractère."); } }; let path = location.pathname; switch (path) { case '/': Affichage.affichageHome(); affichageEventHome(); break; case '/all': Affichage.affichageHome(); afficherListe(); break; default: console.log('here'); PokeRoutes.getInfo(path).then(result => { let pokemon_obj = new Pokemon(result['name'],result['abilities'],result['type'],result['weakness'],result['ThumbnailImage'],result['number'],result['height'],result['weight']); PokeRoutes.createCard(pokemon_obj); } , reject => new Error(reject)) } window.onpopstate = (e) => { console.log(e.state); if(e.state === null) { location.href = '/'; } if(e.state === 'all'){ afficherListe(); } else { PokeRoutes.getInfo(e.state).then(result => { let pokemon_obj = new Pokemon(result['name'],result['abilities'],result['type'],result['weakness'],result['ThumbnailImage'],result['number'],result['height'],result['weight']); PokeRoutes.createCard(pokemon_obj); } , reject => new Error(reject)) } }; function prop_access(object, path) { if (typeof path != "string"){ return object; } if(typeof object != 'object' || object == null) { console.log(path + ' not exist'); return; } if (path === null || path === '') { return object; } let props = path.split('.'); let property = object; props.forEach(function (prop) { if(!property.hasOwnProperty(prop)) { // console.log(path + ' not exist'); return; } property = property[prop]; }); return property; } function tolower(string) { if (string.length === 0) return string; if (typeof string == "object") { for (let i = 0; i < string.length; i++) { string[i] = string[i].toLowerCase(); } return string; } if (typeof string !== "string") return ""; // array = string.split(" "); return string.toLowerCase(); } function type_check_v1(data, type) { switch(typeof data) { case "number": case "string": case "boolean": case "undefined": case "function": return type === typeof data; case "object": switch(type) { case "null": return data === null; case "array": return Array.isArray(data); default: return data !== null && !Array.isArray(data); } } return false; } function affichageEventHome(){ document.getElementsByTagName("input")[0].setAttribute("id", "searchbar"); document.getElementById("searchbar").placeholder = "Rechercher..."; document.getElementById("show_button").addEventListener("click", function(){ history.pushState('all', '', '/all'); afficherListe(); }); document.getElementById("searchbar").addEventListener("keyup", function(){ searchListe(); }); document.getElementById("search_button").addEventListener("click", function(){ searchListe(); }); }; }; let Affichage = { affichageHome:function(){ let menu = document.createElement("div"); menu.setAttribute("class","menu"); let titre = document.createElement("h3"); let img = document.createElement('img'); img.setAttribute("class","logo"); img.src = 'img/image.png'; let content_h3 = document.createTextNode("Bienvenue sur le POKEDECK"); let button = document.createElement("button"); let button_afficher = document.createElement("button"); let content_button_afficher = document.createTextNode("Afficher tout les pokemons"); button_afficher.setAttribute("class","style-button"); button_afficher.setAttribute("id","show_button"); button.setAttribute("class","style-button-search"); button.setAttribute("id","search_button"); let br = document.createElement("br"); let br2 = document.createElement("br"); let div_search = document.createElement("div"); let searchbar = document.createElement("input"); let selectbar = document.createElement("select"); selectbar.id = "searchCrit"; let list = ["name","type","weakness"]; for (let i = 0; i < list.length; i++) { let option = document.createElement("option"); option.value = list[i]; option.text = list[i]; selectbar.appendChild(option); } titre.appendChild(content_h3); button_afficher.appendChild(content_button_afficher); let element = document.getElementById("root"); element.appendChild(menu); menu.appendChild(img); menu.appendChild(titre); menu.appendChild(button_afficher); menu.appendChild(br); menu.appendChild(br2); menu.appendChild(div_search); div_search.appendChild(searchbar); div_search.appendChild(selectbar); div_search.appendChild(button); } } export { Affichage };<file_sep>/README.md # pokedex Application en JS Natif permettant d'afficher des pokemons
8fbab24d3f4de00f0e464d250eb0cae863cae601
[ "JavaScript", "Markdown" ]
2
JavaScript
projet-javascript-4IW1/pokedex
4c1eaeca36facab6240ce8f292fca016f10f03cc
5ae0e96ce03c4b0aff8e7032b6bb501c1a337821
refs/heads/master
<repo_name>anfauglit/set<file_sep>/rndset.c #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 10 #define RANGE 100 typedef struct { size_t size; int* set; } set; int main (void) { set* gen_set (size_t, int); void print_set (set*); void destr_set (set*); srand(time(NULL)); set* setA = gen_set(SIZE, RANGE); set** setF; setF = malloc (sizeof (set*) * SIZE); for (int i = 0; i < SIZE; ++i) { setF[i] = gen_set(SIZE + i, RANGE); } for (int i = 0; i < SIZE; ++i) { print_set(setF[i]); puts(""); } destr_set(setA); return 0; } set* gen_set (size_t size, int range) { set* _set = malloc(sizeof (set)); int* setA = malloc(sizeof (int) * size); for (int i = 0; i < size; ++i) setA[i] = rand() % range; *_set = (set) {size, setA}; return _set; } void destr_set (set* setA) { free(setA->set); free(setA); } void print_set (set* set) { for (int i = 0; i < set->size; ++i) printf("%3i", set->set[i]); }
bd68d3e230c1e10488bcf41619df4427138e58d5
[ "C" ]
1
C
anfauglit/set
77634c783dd9345d7a9e4fc0cce440190dd06a97
427ee842e0893e99a0c163902e0696de371fe3ab
refs/heads/master
<repo_name>YenR/ReactTutorial<file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function Square(props) { return ( <button className ={props.className} onClick={props.onClick}> {props.value} </button> ); } class Board extends React.Component { // normal square renderSquare(i) { return (<Square className={"square"} key={i.toString()} value={this.props.squares[i]} onClick = {() => this.props.onClick(i)} />); } // highlighted as part of the winning squares renderHighlightedSquare(i) { return (<Square className={"square_highlighted"} key={i.toString()} value={this.props.squares[i]} onClick = {() => this.props.onClick(i)} />); } render() { //improved code, functionally same as below but with extendable loops return ( <div key ={'mainboard'}> { [0,1,2].map( (i) => { return( <div className="board-row" key={'board' + i}> { [0,1,2].map( (j) => { let squareID = (i*3+j); // the 3 is still hardcoded if(calculateWinner(this.props.squares) && winningTile(this.props.squares, squareID)) { //console.log('square ' + squareID + ' is a winning square') return this.renderHighlightedSquare(squareID); } return this.renderSquare(squareID); }) } </div> ); }) } </div> ); // return ( // <div> // <div className="board-row"> // {this.renderSquare(0)} // {this.renderSquare(1)} // {this.renderSquare(2)} // </div> // <div className="board-row"> // {this.renderSquare(3)} // {this.renderSquare(4)} // {this.renderSquare(5)} // </div> // <div className="board-row"> // {this.renderSquare(6)} // {this.renderSquare(7)} // {this.renderSquare(8)} // </div> // </div> // ); } } class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ squares: Array(9).fill(null), }], xIsNext: true, stepNumber: 0, toggle: false, } } jumpTo(step) { this.setState({ stepNumber: step, xIsNext: (step%2)===0, }) } handleClick(i) { const history = this.state.history.slice(0, this.state.stepNumber +1); const current = history[history.length - 1]; const squares = current.squares.slice(); if(calculateWinner(squares) || squares[i]) return; squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState( { history: history.concat([{ squares: squares, }]), stepNumber: history.length, xIsNext: !this.state.xIsNext, }); } /** * toggles between sorting history in descending or ascending order */ clickToggle() { this.setState({toggle: !this.state.toggle}); //console.log("toggled to: " + this.state.toggle); } render() { const history = this.state.history; const current = history[this.state.stepNumber]; const winner = calculateWinner(current.squares); const draw = calculateDraw(current.squares); const moves = history.map((step, move) => { // Description of button including move number, square that was changed and inserted symbol const desc = move ? 'Go to move #' + move + ' ' + findChange(history[move].squares, history[move-1].squares) + ((move%2)===0 ? ' O' : ' X') : 'Go to game start'; return ( <li key={move}> <button onClick={() => this.jumpTo(move)} style={ // if currently active step, make button text bold (move === this.state.stepNumber) ? { fontWeight: 'bold' } : { fontWeight: 'normal' } }> {desc} </button> </li> ); }); const toggleButton = <button onClick={() => this.clickToggle()}>{ "Move Sorting Order: " + (this.state.toggle ? "Ascending" : "Descending")} </button>; if(this.state.toggle) moves.reverse(); let status; if(winner) { status = 'Winner: ' + winner; } else if (draw) { status = "Draw"; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); } return ( <div className="game"> <div className="game-board"> <Board squares = {current.squares} onClick = {(i) => this.handleClick(i)} /> </div> <div className="game-info"> <div>{status}</div> <div>{toggleButton}</div> <ol>{ moves }</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); /** * finds the first possible change between two board states * given board states should preferably only differ in one square * returns '(???)' if no differences were found * @param squares1 first board state * @param squares2 second board state, does not matter if actually occurred before or after the first one * @returns {string} coordinates of the occurred change in format (x,y) */ function findChange(squares1, squares2) { for(var i=0; i<9; i++) { if(squares1[i] !== squares2[i]) return iToCoords(i); } //console.log('' + i + ', ' + squares1[0] + ', ' + squares2[0]) return '(???)'; } /** * translates a given number i to coordinates in String format (x,y) * @param i board tile id to be identified as coordinates (0 <= i <= 8) * @returns {string} translated into format (x,y) with (1 <= x,y <= 3) */ function iToCoords(i) { let y; if(i<3) y = 0; else if(i<6) y = 1; else y = 2; return '(' + (i-3*y+1) + ', ' + (y+1) + ')' } /** * checks whether or not the square with the given number i is part of a winning line * based on the calculateWinner function below * @param squares the field of squares, should be in won condition * @param i the number of the field to be tested * @returns {boolean} true if field i was responsible for the win, false otherwise */ function winningTile(squares, i) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let j = 0; j < lines.length; j++) { const [a, b, c] = lines[j]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { if(i === a || i === b || i === c) return true; } } return false; } /** * returns true if the game is a draw (no more moves and no winner) * @param squares current board state */ function calculateDraw(squares) { for(let i of squares) { if(!i) return false; } if(calculateWinner(squares)) // redundant but for call safety return false; //console.log("draw detected"); return true; } /** * borrowed function from tutorial * @param squares * @returns {null|*} */ function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; }
2255ab74a9b8f67591fb005d3141da864a332284
[ "JavaScript" ]
1
JavaScript
YenR/ReactTutorial
6cd79ec7571b07e43a276fae0b574de6e6062c6f
5c79354c41cc9f690f03dbbbff40cc080be7d3d8
refs/heads/master
<file_sep>package br.com.blz.testjava.http.data.request; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class WarehouseRequest { @NotNull private String locality; //Deveria ser um Enum? @NotNull(message = "quantity is required") @Min(value = 0, message = "quantity must be a positive number") private Integer quantity; @NotNull(message = "warehouse type is required") private WarehouseTypeRequest type; } <file_sep>package br.com.blz.testjava.http.data.response; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ProductResponse { private Long sku; private String name; private InventoryResponse inventory; @JsonProperty(value = "isMarketable") private Boolean marketable; } <file_sep>package br.com.blz.testjava.usecase.data; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Product { @NotNull @Min(1) private Long sku; @NotNull @Size(min = 3) private String name; @NotNull private Inventory inventory; @NotNull private Boolean marketable; } <file_sep>package br.com.blz.testjava.usecase.converter; import br.com.blz.testjava.base.interfaces.RequestConverter; import br.com.blz.testjava.base.interfaces.ResponseConverter; import br.com.blz.testjava.gateway.documents.ProductDocument; import br.com.blz.testjava.usecase.data.Product; public interface ProductUseCaseConverter extends RequestConverter<Product, ProductDocument>, ResponseConverter<ProductDocument, Product> { } <file_sep>package br.com.blz.testjava.usecase.impl; import br.com.blz.testjava.base.exceptions.DocumentNotExistsException; import br.com.blz.testjava.gateway.documents.ProductDocument; import br.com.blz.testjava.gateway.repository.ProductRepository; import br.com.blz.testjava.usecase.ProductUseCase; import br.com.blz.testjava.usecase.converter.ProductUseCaseConverter; import br.com.blz.testjava.usecase.data.Inventory; import br.com.blz.testjava.usecase.data.Product; import br.com.blz.testjava.usecase.data.Warehouse; import lombok.RequiredArgsConstructor; import org.springframework.cglib.core.CollectionUtils; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.Validation; import java.util.Collections; import java.util.List; import java.util.Objects; import static java.util.Objects.*; import static java.util.Objects.requireNonNull; @Component @RequiredArgsConstructor public class ProductUseCaseImpl implements ProductUseCase { private final static String INVENTORY_IS_REQUIRED = "Inventory is Required"; private final static String WAREHOUSE_IS_REQUIRED = "Warehouse is Required"; private final ProductUseCaseConverter converter; private final ProductRepository repository; @Override public Product getBySku(Long sku) { ProductDocument document = repository.getById(sku); Product product = converter.toResponse(document); handlerInventoryQuantityAndMarketable(product); return product; } @Override public Product create(@Validated Product product) { ProductDocument documentToCreate = converter.toRequest(product); ProductDocument createdDocument = repository.create(documentToCreate); Product createdProduct = converter.toResponse(createdDocument); handlerInventoryQuantityAndMarketable(createdProduct); return createdProduct; } @Override public Product update(Long sku,@Validated Product product) { product.setSku(sku); ProductDocument documentToUpdate = converter.toRequest(product); ProductDocument createdDocument = repository.update(documentToUpdate); Product updatedProduct = converter.toResponse(createdDocument); handlerInventoryQuantityAndMarketable(updatedProduct); return updatedProduct; } @Override public void delete(Long sku) { repository.delete(sku); } private void handlerInventoryQuantityAndMarketable(Product product){ if(nonNull(product)){ calculeInventoryQuantity(product); defineFlagMarketable(product); } } private void calculeInventoryQuantity(Product product) { Inventory inventory = product.getInventory(); List<Warehouse> warehouses = inventory.getWarehouses(); if(!warehouses.isEmpty()){ Integer totalAmount = warehouses.stream().map(Warehouse::getQuantity) .reduce(0, Integer::sum); inventory.setQuantity(totalAmount); } } private void defineFlagMarketable(Product product) { Inventory inventory = product.getInventory(); Integer inventoryQuantity = inventory.getQuantity(); product.setMarketable(nonNull(inventoryQuantity) && inventoryQuantity > 0 ); } } <file_sep>package br.com.blz.testjava.http; import br.com.blz.testjava.http.converter.ProductHttpConverter; import br.com.blz.testjava.http.data.request.ProductRequest; import br.com.blz.testjava.http.data.response.ProductResponse; import br.com.blz.testjava.usecase.ProductUseCase; import br.com.blz.testjava.usecase.data.Product; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping(path = "/products" ) @RequiredArgsConstructor public class ProductController { private final ProductHttpConverter converter; private final ProductUseCase useCase; @GetMapping(path = "/{sku}", produces = MediaType.APPLICATION_JSON_VALUE) public ProductResponse getProductBySku(@PathVariable Long sku){ Product product = useCase.getBySku(sku); return converter.toResponse(product); } @PostMapping( produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ProductResponse createProduct(@Valid @Validated @RequestBody ProductRequest request){ Product convertedProduct = converter.toRequest(request); Product createdProduct = useCase.create(convertedProduct); return converter.toResponse(createdProduct); } @PutMapping(path = "/{sku}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ProductResponse updateProduct(@PathVariable Long sku, @Validated @RequestBody ProductRequest request){ Product convertedProduct = converter.toRequest(request); Product updatedProduct = useCase.update(sku, convertedProduct); return converter.toResponse(updatedProduct); } @DeleteMapping(path = "/{sku}", produces = MediaType.APPLICATION_JSON_VALUE) public void deleteProduct(@PathVariable Long sku){ useCase.delete(sku); } } <file_sep>package br.com.blz.testjava.usecase.converter.impl; import br.com.blz.testjava.gateway.documents.InventoryDocument; import br.com.blz.testjava.gateway.documents.ProductDocument; import br.com.blz.testjava.gateway.documents.WarehouseDocument; import br.com.blz.testjava.gateway.documents.WarehouseTypeDocument; import br.com.blz.testjava.usecase.converter.ProductUseCaseConverter; import br.com.blz.testjava.usecase.data.Inventory; import br.com.blz.testjava.usecase.data.Product; import br.com.blz.testjava.usecase.data.Warehouse; import br.com.blz.testjava.usecase.data.WarehouseType; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; import static java.util.Objects.requireNonNull; import static org.springframework.beans.BeanUtils.copyProperties; @Component public class ProductUseCaseConverterImpl implements ProductUseCaseConverter { @Override public ProductDocument toRequest(Product product) { if(nonNull(product)){ ProductDocument document = new ProductDocument(); InventoryDocument inventoryDocument = new InventoryDocument(); List<WarehouseDocument> warehouseDocuments = new ArrayList<>(); inventoryDocument.setWarehouses(warehouseDocuments); document.setInventory(inventoryDocument); copyProperties(product, document); //copyProperties(product.getInventory(), inventoryDocument); product.getInventory().getWarehouses().forEach(warehouse ->{ WarehouseDocument warehouseDocument = new WarehouseDocument(); copyProperties(warehouse, warehouseDocument); warehouseDocument.setType(WarehouseTypeDocument.valueOf(warehouse.getType().name())); warehouseDocuments.add(warehouseDocument); }); return document; } return null; } @Override public Product toResponse(ProductDocument productDocument) { if(nonNull(productDocument)){ Product product = new Product(); Inventory inventory = new Inventory(); List<Warehouse> warehouses = new ArrayList<>(); inventory.setWarehouses(warehouses); product.setInventory(inventory); copyProperties(productDocument, product); copyProperties(productDocument.getInventory(), inventory, "warehouses"); productDocument.getInventory().getWarehouses().forEach(warehouseDocument -> { Warehouse warehouse = new Warehouse(); copyProperties(warehouseDocument, warehouse); warehouse.setType(WarehouseType.valueOf(warehouseDocument.getType().name())); warehouses.add(warehouse); }); return product; } return null; } } <file_sep>package br.com.blz.testjava.http.converter; import br.com.blz.testjava.base.interfaces.RequestConverter; import br.com.blz.testjava.base.interfaces.ResponseConverter; import br.com.blz.testjava.http.data.request.ProductRequest; import br.com.blz.testjava.http.data.response.ProductResponse; import br.com.blz.testjava.usecase.data.Product; public interface ProductHttpConverter extends RequestConverter<ProductRequest, Product>, ResponseConverter<Product, ProductResponse> { } <file_sep>package br.com.blz.testjava.base.interfaces; public interface BaseRepository<ID, Document> { Document getById(ID id); Document create(Document document); Document update(Document document); void delete(ID id); } <file_sep>package br.com.blz.testjava.base.config; import br.com.blz.testjava.base.exceptions.DocumentAlreadyExistsException; import br.com.blz.testjava.base.exceptions.DocumentNotExistsException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; @ControllerAdvice public class HandlerExceptionController { //TODO tratar erros @ExceptionHandler(value = {DocumentNotExistsException.class, DocumentAlreadyExistsException.class}) public ResponseEntity<ExceptionResponse> handlerNotExistsException(RuntimeException ex){ return new ResponseEntity<>(ExceptionResponse.builder() .message(ex.getMessage()) .error(sanitizeError(HttpStatus.BAD_REQUEST.toString())) .status(HttpStatus.BAD_REQUEST.value()) .build(), HttpStatus.BAD_REQUEST); } private String sanitizeError(String value){ return value.replaceAll("[0-9]", "") .replace("_", " ").trim(); } } <file_sep>package br.com.blz.testjava.usecase; import br.com.blz.testjava.usecase.data.Product; public interface ProductUseCase { Product getBySku(Long sku); Product create(Product product); Product update(Long sku, Product product); void delete(Long sku); } <file_sep>package br.com.blz.testjava.base.interfaces; public interface RequestConverter<From, To> { To toRequest(From from); } <file_sep>package br.com.blz.testjava.base.exceptions; public class DocumentNotExistsException extends RuntimeException { public DocumentNotExistsException(String id) { super(String.format("The Document: %s not exists", id)); } } <file_sep>package br.com.blz.testjava.base.exceptions; public class DocumentAlreadyExistsException extends RuntimeException { public DocumentAlreadyExistsException(String id) { super(String.format("The Document: %s already exists", id)); } }
9c55e37f02355fadc96d830095928940e66cfafc
[ "Java" ]
14
Java
rafaellemes/test-java
7a0cadb368df52d2ff1b3be73a58bdfff2b1b1bc
2b21dd605808f6273c2831296a2efdb86870360b
refs/heads/master
<repo_name>PenutReaper/GlazeEditor<file_sep>/README.md # GlazeEditor Glaze Editor, for modifying Black Ice save files. This is super prototype so you may encounter issues. Please let me know if anything does go wrong. ## Note While editing save files, affix names must be capitalised correctly. This is the only time in which capitalisation matters and I'll probably get round to fixing it later. <file_sep>/Core/Core/FileParser.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace Core { class FileParser { string RawSave; public gEquipment Equip = new gEquipment(); public gInventory Inv = new gInventory(); public gPlayerInfo Info = new gPlayerInfo(); public FileParser(string rawSave) => RawSave = rawSave; public void Parse() { JObject saveData = (JObject)JsonConvert.DeserializeObject(RawSave.Substring(0, RawSave.LastIndexOf("}")+1)); Info.Hash = RawSave.Substring(RawSave.LastIndexOf("}")); Info.Credits = (int) saveData.GetValue("Credits"); Info.Hardcore = (bool) saveData.GetValue("Hardcore"); Info.Level = (int) saveData.GetValue("Level"); Info.Name = (string) saveData.GetValue("Name"); Info.NewCharacter = (bool) saveData.GetValue("NewCharacter"); Info.PerkPoints = (int) saveData.GetValue("PerkPoints"); foreach (JProperty perk in saveData.GetValue("Perks").Children()) { Affix toAdd; if (Enum.TryParse<Affix>(perk.Name, out toAdd)) { Info.Perks.Add((toAdd, float.Parse((string)perk.Value))); } } Info.TalentPoints = (int) saveData.GetValue("TalentPoints"); foreach (JProperty perk in saveData.GetValue("Talents").Children()) { Affix toAdd; if (Enum.TryParse<Affix>(perk.Name, out toAdd)) { Info.Talents.Add((toAdd, float.Parse((string)perk.Value))); } } Info.XP = (int) saveData.GetValue("XP"); //The actual item information is a few levels deep, so we have to do this to get at it JObject e_setup = (JObject)saveData.GetValue("Equipment"); JArray e_setup2 = (JArray)e_setup.GetValue("$values"); foreach (JObject item in e_setup2) { gItem new_item = new gItem(); new_item._type = (string)item.GetValue("$type"); new_item._name = (string)item.GetValue("Name"); new_item._cooldown = (float)item.GetValue("Cooldown"); new_item._effect = (float)item.GetValue("Effect"); new_item._favorite = (bool)item.GetValue("Favorite"); new_item._flavorText = (string)item.GetValue("FlavorText"); new_item._icon = (IconIndex)Enum.Parse(typeof(IconIndex), (string)item.GetValue("Icon")); new_item._itemLevel = (int)item.GetValue("ItemLevel"); new_item._levelRequirement = (int)item.GetValue("LevelRequirement"); new_item._ramConsumed = (int)item.GetValue("RamConsumed"); new_item._rarity = (RarityType)Enum.Parse(typeof(RarityType), (string)item.GetValue("Rarity")); new_item._specialProperties = (string)item.GetValue("SpecialProperties"); new_item._value = (int)item.GetValue("Value"); //new_item._affixes new_item._affixes = new List<(Affix, float)>(); foreach (JProperty affix in item.GetValue("Affixes")) { Affix toAdd; if (Enum.TryParse<Affix>(affix.Name, out toAdd)) { new_item._affixes.Add((toAdd, float.Parse((string)affix.Value))); } } if (item.GetValue("ProjectileType") != null) { gWeapon new_wep = new gWeapon(new_item); new_wep._minDamage = (int)item.GetValue("MinDamage"); new_wep._maxDamage = (int)item.GetValue("MaxDamage"); new_wep._projectileType = (PayloadIndex)Enum.Parse(typeof(PayloadIndex), (string)item.GetValue("ProjectileType")); new_wep._projectileSpeed = (int)item.GetValue("ProjectileSpeed"); new_wep._range = (int)item.GetValue("Range"); new_wep._accuracy = (int)item.GetValue("Accuracy"); new_wep._projectileCount = (int)item.GetValue("ProjectileCount"); new_wep._pitch = (float)item.GetValue("Pitch"); new_wep._weaponSound = (LaserSoundIndex)Enum.Parse(typeof(LaserSoundIndex), (string)item.GetValue("WeaponSound")); new_wep._damageFalloff = (bool)item.GetValue("DamageFalloff"); JObject spread = (JObject)item.GetValue("WeaponSpread"); new_wep._spread = new List<(string, float)> { ("MaxSpread", (float)spread.GetValue("MaxSpread")), ("SpreadPerShot", (float)spread.GetValue("SpreadPerShot")), ("SecondsToNormal", (float)spread.GetValue("SecondsToNormal")) }; new_wep._weaponModel = (WeaponModelIndex)Enum.Parse(typeof(WeaponModelIndex), (string)item.GetValue("WeaponModel")); Equip.Items.Add(new_wep); } else if (item.GetValue("EnemyToSpawn") != null) { gMinion new_min = new gMinion(new_item); new_min._minDamage = (int)item.GetValue("MinDamage"); new_min._maxDamage = (int)item.GetValue("MaxDamage"); new_min._enemyToSpawn = (EnemyIndex)Enum.Parse(typeof(EnemyIndex), (string)item.GetValue("EnemyToSpawn")); new_min._health = (int)item.GetValue("Health"); } else { Equip.Items.Add(new_item); } } //The actual item information is a few levels deep, so we have to do this to get at it JObject i_setup = (JObject)saveData.GetValue("Inventory"); JArray i_setup2 = (JArray)e_setup.GetValue("$values"); foreach (JObject item in i_setup2) { gItem new_item = new gItem(); new_item._type = (string)item.GetValue("$type"); new_item._name = (string)item.GetValue("Name"); new_item._cooldown = (float)item.GetValue("Cooldown"); new_item._effect = (float)item.GetValue("Effect"); new_item._favorite = (bool)item.GetValue("Favorite"); new_item._flavorText = (string)item.GetValue("FlavorText"); new_item._icon = (IconIndex)Enum.Parse(typeof(IconIndex), (string)item.GetValue("Icon")); new_item._itemLevel = (int)item.GetValue("ItemLevel"); new_item._levelRequirement = (int)item.GetValue("LevelRequirement"); new_item._ramConsumed = (int)item.GetValue("RamConsumed"); new_item._rarity = (RarityType)Enum.Parse(typeof(RarityType), (string)item.GetValue("Rarity")); new_item._specialProperties = (string)item.GetValue("SpecialProperties"); new_item._value = (int)item.GetValue("Value"); //new_item._affixes new_item._affixes = new List<(Affix, float)>(); foreach (JProperty affix in item.GetValue("Affixes")) { Affix toAdd; if (Enum.TryParse<Affix>(affix.Name, out toAdd)) { new_item._affixes.Add((toAdd, float.Parse((string)affix.Value))); } } Inv.Items.Add(new_item); } Info.Cheater = (bool)saveData.GetValue("Cheater"); Info.HighestServerHacked = (int)saveData.GetValue("HighestServerHacked"); Info.TimeSinceLastLevel = (float)saveData.GetValue("TimeSinceLastLevel"); JObject state = (JObject)saveData.GetValue("WorldState"); Info.WorldState = new List<(string, int)> { ("Door_Portcullis", (int?) state.GetValue("Door_Portcullis") ?? 0) , ("Door_Finality1", (int?) state.GetValue("Door_Finality1") ?? 0) }; } } } <file_sep>/Core/Core/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; namespace Core { class Program { static void Main(string[] args) { List<SaveFile> EditableData = new List<SaveFile>(); List<FileInfo> Saves = GetSaveFiles(); FileParser parser; foreach (FileInfo Save in Saves) { SaveFile curFile = new SaveFile(); string RawSave = ReadSave(Save); parser = new FileParser(RawSave); parser.Parse(); curFile.SetInfo(parser.Info); curFile.SetEquipment(parser.Equip); curFile.SetInventory(parser.Inv); EditableData.Add(curFile); } bool exit = false; int command_mode = 0; while (!exit) { Console.Clear(); string inp = ""; string output = ""; if (command_mode == 0) { Console.WriteLine("Display, Edit or Save:"); inp = Console.ReadLine().Trim().ToLower(); switch (inp) { case "display": command_mode = 1; break; case "edit": command_mode = 2; break; case "save": command_mode = 3; break; default: output = "Invalid Input, Press Enter to Continue"; break; } } else if (command_mode == 1) { Console.WriteLine("Param to Display"); inp = Console.ReadLine().Trim().ToLower(); switch (inp) { case "name": output = $"Player Name: {EditableData[0].player_info.Name}"; break; case "level": output = $"Player Level: {EditableData[0].player_info.Level}"; break; case "credits": output = $"Credits: {EditableData[0].player_info.Credits}"; break; case "xp": output = $"XP: {EditableData[0].player_info.XP}"; break; case "perks": foreach ((Affix name, float level) perk in EditableData[0].player_info.Perks) { output += $"{perk.name}: {perk.level}{Environment.NewLine}"; } break; case "perkpoints": output = $"PerkPoints: {EditableData[0].player_info.PerkPoints}"; break; case "hardcore": output = $"Hardcore: {EditableData[0].player_info.Hardcore}"; break; case "newcharacter": output = $"NewCharacter: {EditableData[0].player_info.NewCharacter}"; break; case "talents": foreach ((Affix name, float level) talents in EditableData[0].player_info.Talents) { output += $"{talents.name}: {talents.level}{Environment.NewLine}"; } break; case "talentpoints": output = $"levelPoints: {EditableData[0].player_info.TalentPoints}"; break; default: output = "Invalid Input, Press Enter to Continue"; break; } Console.WriteLine(output); Console.Read(); command_mode = 0; } else if (command_mode == 2) { Console.WriteLine("Param to Modify:"); inp = Console.ReadLine().Trim().ToLower(); switch (inp) { case "name": Console.Clear(); Console.WriteLine("Enter New Value For Name"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Name = inp; break; case "level": Console.Clear(); Console.WriteLine("Enter New Value For Level"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Level = int.Parse(inp); break; case "credits": Console.Clear(); Console.WriteLine("Enter New Value For Credits"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Credits = int.Parse(inp); break; case "xp": Console.Clear(); Console.WriteLine("Enter New Value For XP"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.XP = int.Parse(inp); break; case "perks": Console.Clear(); foreach ((Affix name, float level) perk in EditableData[0].player_info.Perks) { output += $"{perk.name}: {perk.level}{Environment.NewLine}"; } Console.WriteLine(output); output = ""; Console.WriteLine("Choose Perk to Edit: "); inp = Console.ReadLine().Trim(); Affix toEdit; bool foundAffix = false; if (Enum.TryParse(inp, out toEdit)) { for (int i = 0; i < EditableData[0].player_info.Perks.Count; i++) { (Affix name, float level) perk; perk.name = EditableData[0].player_info.Perks[i].Item1; perk.level = EditableData[0].player_info.Perks[i].Item2; if (perk.name == toEdit) { Console.WriteLine($"Enter New Value For {perk.name}"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Perks[i] = Tuple.Create(perk.name, float.Parse(inp)).ToValueTuple(); foundAffix = true; } } if (!foundAffix) { Console.WriteLine("Perk Not Found"); Console.Read(); } } break; case "perkpoints": Console.Clear(); Console.WriteLine("Enter New Value For PerkPoints"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.PerkPoints = int.Parse(inp); break; case "hardcore": Console.Clear(); Console.WriteLine("Enter New Value For Hardcore"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Hardcore = bool.Parse(inp); break; case "newcharacter": Console.Clear(); Console.WriteLine("Enter New Value For NewCharacter"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.NewCharacter = bool.Parse(inp); break; case "talents": Console.Clear(); foreach ((Affix name, float level) perk in EditableData[0].player_info.Talents) { output += $"{perk.name}: {perk.level}{Environment.NewLine}"; } Console.WriteLine(output); output = ""; Console.WriteLine("Choose Talent to Edit: "); inp = Console.ReadLine().Trim(); Affix toEdit2; bool foundAffix2 = false; if (Enum.TryParse(inp, out toEdit2)) { for (int i = 0; i < EditableData[0].player_info.Talents.Count; i++) { (Affix name, float level) perk; perk.name = EditableData[0].player_info.Talents[i].Item1; perk.level = EditableData[0].player_info.Talents[i].Item2; if (perk.name == toEdit2) { Console.WriteLine($"Enter New Value For {perk.name}"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.Talents[i] = Tuple.Create(perk.name, float.Parse(inp)).ToValueTuple(); foundAffix2 = true; } } if (!foundAffix2) { Console.WriteLine("Talent Not Found"); Console.Read(); } } break; case "talentpoints": Console.Clear(); Console.WriteLine("Enter New Value For TalentPoints"); inp = Console.ReadLine().Trim(); EditableData[0].player_info.TalentPoints = int.Parse(inp); break; default: output = "Invalid Input, Press Enter to Continue"; command_mode = 0; break; } command_mode = 0; } else if (command_mode == 3) { for (int i = 0; i < EditableData.Count; i++) { SaveFile cur_file = EditableData[i]; using (StreamWriter sw = new StreamWriter($@"{Directory.GetCurrentDirectory()}\Black Ice_Data\Saves\PlayerData{i}.save")) { sw.WriteLine("{"); sw.WriteLine($" \"$type\": \"PlayerSaveProxy, Assembly-CSharp\","); sw.WriteLine($" \"Name\": \"{cur_file.player_info.Name}\","); sw.WriteLine($" \"XP\": {cur_file.player_info.XP},"); sw.WriteLine($" \"Level\": {cur_file.player_info.Level},"); sw.WriteLine($" \"TalentPoints\": {cur_file.player_info.TalentPoints},"); sw.WriteLine($" \"Talents\": {{"); sw.WriteLine($" \"$type\": \"System.Collections.Generic.Dictionary`2[[Affix, Assembly-CSharp],[System.Single, mscorlib]], mscorlib\","); for (int x = 0; x < cur_file.player_info.Talents.Count; x++) { (Affix name, float level) tal = ( cur_file.player_info.Talents[x].Item1, cur_file.player_info.Talents[x].Item2); int max = cur_file.player_info.Talents.Count - 1; string do_comma = x < max ? "," : ""; sw.WriteLine($" \"{tal.name}\": {tal.level.ToString("0.0")}{do_comma}"); } sw.WriteLine(" },"); sw.WriteLine($" \"PerkPoints\": {cur_file.player_info.PerkPoints},"); sw.WriteLine($" \"Perks\": {{"); sw.WriteLine($" \"$type\": \"System.Collections.Generic.Dictionary`2[[Affix, Assembly-CSharp],[System.Single, mscorlib]], mscorlib\","); for (int x = 0; x < cur_file.player_info.Perks.Count; x++) { (Affix name, float level) perk = ( cur_file.player_info.Perks[x].Item1, cur_file.player_info.Perks[x].Item2); int max = cur_file.player_info.Perks.Count - 1; string do_comma = x < max ? "," : ""; sw.WriteLine($" \"{perk.name}\": {perk.level.ToString("0.0")}{do_comma}"); } sw.WriteLine(" },"); sw.WriteLine($" \"Hardcore\": {cur_file.player_info.Hardcore.ToString().ToLower()},"); sw.WriteLine($" \"NewCharacter\": {cur_file.player_info.NewCharacter.ToString().ToLower()},"); sw.WriteLine($" \"Credits\": {cur_file.player_info.Credits},"); sw.WriteLine($" \"Equipment\": {{"); sw.WriteLine($" \"$type\": \"Item[], Assembly-CSharp\","); sw.WriteLine($" \"$values\": ["); i = writeEquipment(i, cur_file, sw); sw.WriteLine($" ] {Environment.NewLine} }},"); sw.WriteLine($" \"Inventory\": {{"); sw.WriteLine($" \"$type\": \"Item[], Assembly-CSharp\","); sw.WriteLine($" \"$values\": ["); i = writeInventory(i, cur_file, sw); sw.WriteLine($" ] {Environment.NewLine} }},"); sw.WriteLine($" \"Cheater\": {cur_file.player_info.Cheater.ToString().ToLower()},"); sw.WriteLine($" \"HighestServerHacked\": {cur_file.player_info.HighestServerHacked},"); sw.WriteLine($" \"TimeSinceLastLevel\": {cur_file.player_info.TimeSinceLastLevel},"); sw.WriteLine($" \"WorldState\": {{"); sw.WriteLine($" \"$type\": \"System.Collections.Generic.Dictionary`2[[WorldState, Assembly - CSharp],[System.Int32, mscorlib]], mscorlib\","); sw.WriteLine($" \"Door_Portcullis\": {cur_file.player_info.WorldState[0].Item2},"); sw.WriteLine($" \"Door_Finality1\": {cur_file.player_info.WorldState[1].Item2}"); sw.WriteLine($" }}"); sw.Write($"{cur_file.player_info.Hash}"); command_mode = 0; exit = true; } } } } } private static int writeInventory(int i, SaveFile cur_file, StreamWriter sw) { for (int x = 0; x < 45; x++) { try { gItem cur_item = cur_file.player_inventory.Items[x]; string comma = x < 44 ? "," : ""; sw.WriteLine(" {"); if (cur_item is gWeapon) { gWeapon cur_wep = (gWeapon)cur_item; sw.WriteLine($" \"MinDamage\": {cur_wep._minDamage},"); sw.WriteLine($" \"MaxDamage\": {cur_wep._maxDamage},"); sw.WriteLine($" \"ProjectileType\": {(int)cur_wep._projectileType},"); sw.WriteLine($" \"ProjectileSpeed\": {cur_wep._projectileSpeed},"); sw.WriteLine($" \"Range\": {cur_wep._range},"); sw.WriteLine($" \"Accuracy\": {cur_wep._accuracy},"); sw.WriteLine($" \"ProjectileCount\": {cur_wep._projectileCount},"); sw.WriteLine($" \"Pitch\": {cur_wep._pitch},"); sw.WriteLine($" \"WeaponSound\": {(int)cur_wep._weaponSound},"); sw.WriteLine($" \"DamageFalloff\": {cur_wep._accuracy.ToString().ToLower()},"); sw.WriteLine($" \"WeaponSpread\": {{"); sw.WriteLine($" \"$type\": \"WeaponSpread, Assembly - CSharp\","); sw.WriteLine($" \"MaxSpread\": {cur_wep._spread[0].Item2},"); sw.WriteLine($" \"SpreadPerShot\": {cur_wep._spread[1].Item2},"); sw.WriteLine($" \"SecondsToNormal\": {cur_wep._spread[2].Item2}"); sw.WriteLine($" }},"); sw.WriteLine($" \"WeaponModel\": {(int)cur_wep._weaponModel},"); } if (cur_item is gMinion) { gMinion cur_min = (gMinion)cur_item; sw.WriteLine($" \"MinDamage\": {cur_min._minDamage},"); sw.WriteLine($" \"MaxDamage\": {cur_min._maxDamage},"); sw.WriteLine($" \"EnemyToSpawn\": {(int)cur_min._enemyToSpawn},"); sw.WriteLine($" \"Health\": {cur_min._health},"); } sw.WriteLine($" \"$type\": \"{cur_item._type}\","); sw.WriteLine($" \"Name\": \"{cur_item._name}\","); sw.WriteLine($" \"Value\": {cur_item._value},"); sw.WriteLine($" \"Affixes\": {{"); for (int a = 0; a < cur_item._affixes.Count; a++) { (Affix name, float level) perk = ( cur_item._affixes[a].Item1, cur_item._affixes[a].Item2); int max = cur_item._affixes.Count - 1; string do_comma = a < max ? "," : ""; sw.WriteLine($" \"{perk.name}\": {perk.level.ToString("0.0")}{do_comma}"); } sw.WriteLine($" }},"); sw.WriteLine($" \"Icon\": {(int)cur_item._icon},"); sw.WriteLine($" \"RamConsumed\": {cur_item._ramConsumed},"); sw.WriteLine($" \"Effect\": {cur_item._effect},"); sw.WriteLine($" \"Cooldown\": {cur_item._cooldown},"); sw.WriteLine($" \"LevelRequirement\": {cur_item._levelRequirement},"); sw.WriteLine($" \"ItemLevel\": {cur_item._itemLevel},"); sw.WriteLine($" \"SpecialProperties\": \"{cur_item._specialProperties.Trim()}\","); sw.WriteLine($" \"Favorite\": {cur_item._favorite.ToString().ToLower()},"); sw.WriteLine($" \"FlavorText\": \"{cur_item._flavorText.Trim()}\""); sw.WriteLine($" }}{ comma } "); } catch { string comma = x < 44 ? "," : ""; sw.WriteLine($" null{comma}"); } } return i; } private static int writeEquipment(int i, SaveFile cur_file, StreamWriter sw) { for (int x = 0; x < 9; x++) { try { gItem cur_item = cur_file.player_equipment.Items[x]; string comma = x < 8 ? "," : ""; sw.WriteLine(" {"); if (cur_item is gWeapon) { gWeapon cur_wep = (gWeapon)cur_item; sw.WriteLine($" \"MinDamage\": {cur_wep._minDamage},"); sw.WriteLine($" \"MaxDamage\": {cur_wep._maxDamage},"); sw.WriteLine($" \"ProjectileType\": {(int)cur_wep._projectileType},"); sw.WriteLine($" \"ProjectileSpeed\": {cur_wep._projectileSpeed},"); sw.WriteLine($" \"Range\": {cur_wep._range},"); sw.WriteLine($" \"Accuracy\": {cur_wep._accuracy},"); sw.WriteLine($" \"ProjectileCount\": {cur_wep._projectileCount},"); sw.WriteLine($" \"Pitch\": {cur_wep._pitch},"); sw.WriteLine($" \"WeaponSound\": {(int)cur_wep._weaponSound},"); sw.WriteLine($" \"DamageFalloff\": {cur_wep._accuracy.ToString().ToLower()},"); sw.WriteLine($" \"WeaponSpread\": {{"); sw.WriteLine($" \"$type\": \"WeaponSpread, Assembly - CSharp\","); sw.WriteLine($" \"MaxSpread\": {cur_wep._spread[0].Item2},"); sw.WriteLine($" \"SpreadPerShot\": {cur_wep._spread[1].Item2},"); sw.WriteLine($" \"SecondsToNormal\": {cur_wep._spread[2].Item2}"); sw.WriteLine($" }},"); sw.WriteLine($" \"WeaponModel\": {(int)cur_wep._weaponModel},"); } if (cur_item is gMinion) { gMinion cur_min = (gMinion)cur_item; sw.WriteLine($" \"MinDamage\": {cur_min._minDamage},"); sw.WriteLine($" \"MaxDamage\": {cur_min._maxDamage},"); sw.WriteLine($" \"EnemyToSpawn\": {(int)cur_min._enemyToSpawn},"); sw.WriteLine($" \"Health\": {cur_min._health},"); } sw.WriteLine($" \"$type\": \"{cur_item._type}\","); sw.WriteLine($" \"Name\": \"{cur_item._name}\","); sw.WriteLine($" \"Value\": {cur_item._value},"); sw.WriteLine($" \"Rarity\": {(int)cur_item._rarity},"); sw.WriteLine($" \"Affixes\": {{"); for (int a = 0; a < cur_item._affixes.Count; a++) { (Affix name, float level) perk = ( cur_item._affixes[a].Item1, cur_item._affixes[a].Item2); int max = cur_item._affixes.Count - 1; string do_comma = a < max ? "," : ""; sw.WriteLine($" \"{perk.name}\": {perk.level.ToString("0.0")}{do_comma}"); } sw.WriteLine($" }},"); sw.WriteLine($" \"Icon\": {(int)cur_item._icon},"); sw.WriteLine($" \"RamConsumed\": {cur_item._ramConsumed},"); sw.WriteLine($" \"Effect\": {cur_item._effect},"); sw.WriteLine($" \"Cooldown\": {cur_item._cooldown},"); sw.WriteLine($" \"LevelRequirement\": {cur_item._levelRequirement},"); sw.WriteLine($" \"ItemLevel\": {cur_item._itemLevel},"); sw.WriteLine($" \"SpecialProperties\": \"{cur_item._specialProperties.Trim()}\","); sw.WriteLine($" \"Favorite\": {cur_item._favorite.ToString().ToLower()},"); sw.WriteLine($" \"FlavorText\": \"{cur_item._flavorText.Trim()}\""); sw.WriteLine($" }}{ comma } "); } catch { string comma = x < 8 ? "," : ""; sw.WriteLine($" null{comma}"); } } return i; } private static List<FileInfo> GetSaveFiles() { DirectoryInfo SaveDir = new DirectoryInfo($@"{Directory.GetCurrentDirectory()}\Black Ice_Data\Saves"); FileInfo[] Files = SaveDir.GetFiles(); List<FileInfo> Saves = RemoveNonPlayerSaves(Files); return Saves; } private static List<FileInfo> RemoveNonPlayerSaves(FileInfo[] saves) { List<FileInfo> TempSaves = new List<FileInfo>(); for (int i = 0; i < saves.Count(); i++) { if (saves[i].Extension == ".save" && saves[i].Name.Contains("PlayerData")) { TempSaves.Add(saves[i]); } } return TempSaves; } private static string ReadSave(FileInfo save) => File.ReadAllText($"{save.FullName}"); } class SaveFile { public gPlayerInfo player_info { get; set; } public gEquipment player_equipment { get; set; } public gInventory player_inventory { get; set; } public void SetInventory(gInventory newInv) => player_inventory = newInv; public void SetEquipment(gEquipment newEquip) => player_equipment = newEquip; public void SetInfo(gPlayerInfo newInfo) => player_info = newInfo; } class gPlayerInfo { public List<(Affix, float)> Talents = new List<(Affix, float)>(); public List<(Affix, float)> Perks = new List<(Affix, float)>(); public int TalentPoints; public int PerkPoints; public int Level; public int XP; public string Name; public bool Hardcore; public bool NewCharacter; public int Credits; public bool Cheater; public int HighestServerHacked; public float TimeSinceLastLevel; public List<(string, int)> WorldState = new List<(string, int)>(); public string Hash; } class gInventory { public List<gItem> Items = new List<gItem>(); } class gEquipment { public List<gItem> Items = new List<gItem>(); } class gMinion : gItem { public EnemyIndex _enemyToSpawn; public int _minDamage = 1; public int _maxDamage = 1; public int _health = 1; public gMinion(gItem base_item) { _type = base_item._type; _name = base_item._name; _value = base_item._value; _rarity = base_item._rarity; _affixes = base_item._affixes; _icon = base_item._icon; _ramConsumed = base_item._ramConsumed; _effect = base_item._effect; _cooldown = base_item._cooldown; _levelRequirement = base_item._levelRequirement; _itemLevel = base_item._itemLevel; _specialProperties = base_item._specialProperties; _favorite = base_item._favorite; _flavorText = base_item._flavorText; } } class gWeapon : gItem { public int _minDamage = 1; public int _maxDamage = 1; public PayloadIndex _projectileType; public int _projectileSpeed = 80; public int _range = 30; public int _accuracy = 90; public int _projectileCount = 1; public float _pitch = 1f; public LaserSoundIndex _weaponSound; public bool _damageFalloff; public List<(string, float)> _spread = new List<(string, float)>(); public WeaponModelIndex _weaponModel; public gWeapon(gItem base_item) { _type = base_item._type; _name = base_item._name; _value = base_item._value; _rarity = base_item._rarity; _affixes = base_item._affixes; _icon = base_item._icon; _ramConsumed = base_item._ramConsumed; _effect = base_item._effect; _cooldown = base_item._cooldown; _levelRequirement = base_item._levelRequirement; _itemLevel = base_item._itemLevel; _specialProperties = base_item._specialProperties; _favorite = base_item._favorite; _flavorText = base_item._flavorText; } } class gItem { public string _type; public string _name; public int _value; public RarityType _rarity; public List<(Affix, float)> _affixes; public IconIndex _icon = IconIndex.Laser; public int _ramConsumed; public float _effect = 1f; public float _cooldown = 0.1f; public int _levelRequirement; public int _itemLevel = 1; public string _specialProperties = string.Empty; public bool _favorite; public string _flavorText = string.Empty; public gItem() { } public gItem(string type, string name, int value, RarityType rarity, List<(Affix, float)> affixes, IconIndex icon, int ramConsumed, float effect, float cooldown, int levelRequirement, int itemLevel, string specialProperties, bool favorite, string flavorText) { _type = type; _name = name; _value = value; _rarity = rarity; _affixes = affixes; _icon = icon; _ramConsumed = ramConsumed; _effect = effect; _cooldown = cooldown; _levelRequirement = levelRequirement; _itemLevel = itemLevel; _specialProperties = specialProperties; _favorite = favorite; _flavorText = flavorText; } } } <file_sep>/Core/Core/GameEnums.cs using System.Collections.Generic; namespace Core { public enum Affix { HackSpeed, HackTimeFlat, HackRange, MovementSpeed, LootFind, RAM, RAMPerSecond = 7, MaxHealth, AttackSpeed, Accuracy, CritChance, CritMultiplier, WeaponDamagePercentage, WeaponDamageFlat, WeaponRange, Thorns, Defense = 22, RAMPerSecondPercentage = 24, MaxHealthPercentage, RecoilReduction = 42, SpreadReduction, LevelRequirementReduced = 26, ChanceToPierce = 17, Drunk, Knockback, Homing, ChanceToRicochet, ChanceToColorize = 23, ChanceToBurn = 45, ChanceToFreeze, ChanceToSlow, PercentRAM = 6, ChanceToTeleport = 27, XPPercentage, PerkSniperHoming, PerkLowHPDamageBonus, PerkMineMovementSpeed, PerkLasgunPiercing, PerkMoreDiscs, PerkDrunkenMaster, PerkStandingStillDamageBonus, PerkMovingForwardDamageBonus, PerkColorizeConverts, PerkGITSfishDoubler, PerkAimbotProjectiles, PerkThornsPower, PerkShotgunDoubleBarrel, PerkMachineGun = 44 } public enum PayloadIndex { Laser, PlasmaBall, GreenLaserEnemy, Missile, LasgunLaser, Hammer, Disc, Fireball, FireLasgunLaser, Frostbolt, Slowbolt, SlowingLasgunLaser, Railgun, RainbowShot, Mine, EnemyLasgunLaser, SpiderMine, FireEnemyLasgunLaser, SlowingEnemyLasgunLaser, BouncyBall, Dodgeball, BouncyFireball, DiscoDeathball, GreenLaser, OrangeLaser, BlueLaser, PurpleLaser, SlowBall } public enum RarityType { Common, Uncommon, Rare, Epic, Unique, Any, UncommonOrBetter, RareOrBetter, EpicOrBetter, NotUnique } public enum WeaponModelIndex { MachineGun, Shotgun, Sniper, Lasgun, Shotgun2, MachineGun2, Bubblegun, RayPistol, RocketLauncher, TeslaCannon, Healgun, Prismgun, Disc, Shotgun3, Cat, Dodgeball } public enum LaserSoundIndex { Laser, Railgun, BouncyBall, PlasmaBall, Disc, Lasgun, Mine, EnemyLaser, Missile, Dodgeball, Frostbolt, Fireball, RainbowShot, SilverHammer, FireBouncyBall } public enum AbilityIcon { Laser, Knockback, Spider, Jump, Sprint, Hack, Mine, Sniper, Shotgun } public enum IconIndex { EmptySlot, Laser, Icebreaker, Mod, Spider, PlasmaBall, Missile, Jump, Sprint, Scope, Heal, Mine, Disc, Fireball, Frostbolt, RainbowShot, EMP, Railgun, Lasgun, Text, Lasbreaker, Popup, Aimbot, GITSfish, ActiveSlot, HackOLantern, Scorpion, Cat, BouncyBall, Dodgeball, DiscoDeathball, Hammer, SubIcon_Machinegun, SubIcon_Shotgun, SubIcon_Sniper, Lock, Teleport, HealOverTime, Frostbiter, IceAKill, Kokinator, Oersted, Porta, REM, Scorchporation, Meatball, SpiderMine, Valentyn, SubIcon_Spiral, JumpOrig } public enum EnemyIndex { Spider, Probe, Hopper, Shark, Crab, Scorpion, Cat, CrabMustache, CrabSD, Snail, Mom } }
9495cd8fb265af90e3c7e2d4e94c2db5ac82f15c
[ "Markdown", "C#" ]
4
Markdown
PenutReaper/GlazeEditor
c1ea73bec81c7ccab82916b7d6a7bd41f17481d9
308e142ea0862212812b1042e4c6713d4075f530
refs/heads/master
<repo_name>z2australia/ch2-1<file_sep>/test.py import json from collections import defaultdict from collections import Counter from numpy.random import randn import numpy as np import os import matplotlib.pyplot as plt from pandas import DataFrame, Series import pandas as pd path = 'usagov_bitly_data2012-03-16-1331923249.txt' def get_counts(sequence): counts = {} for x in sequence: if x in counts: counts[x] += 1 else: counts[x] = 1 return counts def get_counts2(sequence): counts = defaultdict(int) # values will initialize to 0 for x in sequence: counts[x] += 1 return counts records = [json.loads(line) for line in open(path)] records[0]['tz'] print(records[0]['tz']) time_zones = [rec['tz'] for rec in records if 'tz' in rec] counts = get_counts(time_zones) print(counts['America/New_York']) print(len(time_zones)) counts = Counter(time_zones) print(counts.most_common(10)) frame = DataFrame(records) tz_counts = frame['tz'].value_counts() tz_counts[:10] clean_tz = frame['tz'].fillna('Missing') clean_tz[clean_tz == ''] = 'Unknown' tz_counts = clean_tz.value_counts() print(tz_counts[:10]) plt.figure(figsize=(13, 4)) np.set_printoptions(precision=4) tz_counts[:10].plot(kind='barh', rot=0) plt.show()
51e0b9f28f2dbc9dee5a10fc4bb85efda35ebf0b
[ "Python" ]
1
Python
z2australia/ch2-1
3db1dfdf6f1b52d708993b1581c505a5f068c8f4
b5dffc80449d408858b3878fa898b3d833000e3b
refs/heads/master
<file_sep>import logging import sys from typing import List, Optional import click import coloredlogs import spacy from spacy.language import Language from spacy.tokens import Doc, Span, Token as SpacyToken from spacyThrift import SpacyThrift from spacyThrift.ttypes import Token from thrift.transport import TSocket, TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer class Handler: def __init__(self, tagging_nlp: Language, ner_nlp: Optional[Language] = None) -> None: self.tagging_nlp = tagging_nlp self.ner_nlp = ner_nlp @classmethod def _lemma(cls, token: SpacyToken): if token.lemma_ != "-PRON-": return token.lemma_.lower().strip() else: return token.lower_ def tag(self, sentence: str) -> List[Token]: document = self.tagging_nlp(sentence) # type: Doc return [ Token(element.orth_, element.tag_, self._lemma(element)) for element in document # type: SpacyToken ] def ner(self, sentence: str) -> List[Token]: if not self.ner_nlp: return None document = self.ner_nlp(sentence) # type: Doc return [ Token(element.orth_, element.tag_, self._lemma(element), '-'.join([element.ent_iob_, element.ent_type_]) if element.ent_type_ else None) for element in document # type: SpacyToken ] @click.command() @click.option('--port', default=9090) @click.option('--language', default='en') @click.option('--ner', is_flag=True) def serve(port: int, language: str, ner: bool) -> None: coloredlogs.install(stream=sys.stderr, level=logging.INFO, fmt='%(asctime)s %(name)s %(levelname)s %(message)s') logging.info("Loading ...") tagging_nlp = spacy.load(language, disable=['ner']) # type: Language tagging_nlp.remove_pipe('parser') logging.info("Tagging pipeline: %s", ', '.join(tagging_nlp.pipe_names)) ner_nlp = None if ner: ner_nlp = spacy.load(language) # type: Language logging.info("NER pipeline: %s", ', '.join(ner_nlp.pipe_names)) handler = Handler(tagging_nlp, ner_nlp) processor = SpacyThrift.Processor(handler) server_socket = TSocket.TServerSocket(port=port) transport_factory = TTransport.TBufferedTransportFactory() protocol_factory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TThreadedServer(processor, server_socket, transport_factory, protocol_factory) logging.info("Serving on port %d ...", port) server.serve() if __name__ == '__main__': serve() <file_sep>.PHONY: generate generate: thrift -r --gen py --out . spacy.thrift <file_sep># spacy-thrift [spaCy](https://github.com/explosion/spaCy) as a service using [Thrift](https://thrift.apache.org) ## Usage Download spaCy's parser model for English: - `python3 -m spacy download en` Run the service: - `python3 -m spacyThrift.service` Pass the `--ner` option to perform named-entity recognition. ## Development - The Thrift code can be updated using: `make generate` - If a new version of Thrift is used, also ensure the version is specified in `requirements.txt`
2d75a0fae93624b3fbbc7b222bcded898fad0b4f
[ "Markdown", "Python", "Makefile" ]
3
Python
BigRLab/spacy-thrift
9b45caca91ae7ceb1e790c5467f994c6b2d9ecef
c866b3422c7f20a601e83ec543ac733273bd2422
refs/heads/master
<repo_name>cocos-laboratory/wechat-minigame<file_sep>/assets/Script/Helloworld.ts import wechat from './wechat' const { ccclass, property } = cc._decorator; @ccclass export default class Helloworld extends cc.Component { @property(cc.Sprite) display: cc.Sprite = null tex: cc.Texture2D = new cc.Texture2D() private _isShow: boolean = false onClick() { this._isShow = !this._isShow // 发消息给子域 wx.postMessage({ message: this._isShow ? 'Show' : 'Hide' }) } setUserCloudStorage() { wx.setUserCloudStorage({ KVDataList: [{ score: 1000 }], success(res) { cc.log('wx.setUserCloudStorage success', res) }, fail(e) { cc.log('wx.setUserCloudStorage fail', e) } }) } start() { wx.setKeepScreenOn({ keepScreenOn: true }) wx.login({ success: function () { wx.getUserInfo({ success(res) { cc.log(res) } }) } }) wx.onShareAppMessage(() => { return { title: '转发标题' } }) } _updateSubDomainCanvas() { if (!this.tex) { return } this.tex.initWithElement(window['sharedCanvas']) this.tex.handleLoadedTexture() this.display.spriteFrame = new cc.SpriteFrame(this.tex) } update() { this._updateSubDomainCanvas(); } share() { wechat.shareApp() } } <file_sep>/assets/Script/wechat.ts export default { shareApp () { return wx.shareAppMessage({ title: 'share test', fail(e) { cc.log(e) }, success(res) { cc.log(res) } }) } }<file_sep>/README.md # hello-world 调试该项目的时候,一定要使用真实的appid。使用cc自带的appid会提示没有调用api的权限。
52635a755e8218cb529dd6150a6951e65317034c
[ "Markdown", "TypeScript" ]
3
TypeScript
cocos-laboratory/wechat-minigame
d45949b194adfe3f2f0b620c3d5e42c73141c32b
de485eff0310cb871d2bf7a655ef59aabae7c95c
refs/heads/master
<repo_name>mpizarroc/TestMigrationEF<file_sep>/TestMigrationEF.Data/Class1.cs using System; namespace TestMigrationEF.Data { public class Class1 { } } <file_sep>/TestMigrationEF/Program.cs using Microsoft.EntityFrameworkCore; using System; namespace TestMigrationEF { class Program { static void Main(string[] args) { using (var context = new AppContext()) { context.Database.Migrate(); Console.WriteLine("Database has been migrated"); } } } } <file_sep>/README.md # TestMigrationEF Prueba de migracion automaticas con .net core y entityFramework core
e522fbde2e832381d39c5ab3d1cd3b1c57599e21
[ "Markdown", "C#" ]
3
C#
mpizarroc/TestMigrationEF
c7519946d08721a541911574cca2547fc2315f71
b6e6f76963b284966604a3dd425290c90465d4c6
refs/heads/master
<file_sep>#ifndef LAMP_HPP #define LAMP_HPP #include "RFTransmitter.hpp" class Lamp : public RFTransmitter { bool _isTurnedOn; int brightnessLevel; public: explicit Lamp(uint8_t); bool isTurnedOn(); void turnOn(unsigned long, unsigned int); void turnOff(unsigned long, unsigned int); void setPowerState(bool); int getBrightness(); void setBrightness(int, unsigned long, unsigned int); }; #endif <file_sep>#ifndef SENSOR_HPP #define SENSOR_HPP #include "Arduino.h" class Sensor { uint8_t pin; public: Sensor(uint8_t pin, uint8_t mode); explicit Sensor(uint8_t pin); protected: uint8_t getPin() const; }; #endif <file_sep>#ifndef IR_DEVICE_HPP #define IR_DEVICE_HPP namespace IRDevice { enum Model { SAMSUNG }; }; // namespace IRDevice #endif <file_sep>#include "Lamp.hpp" Lamp::Lamp(uint8_t pin) : RFTransmitter(pin) { _isTurnedOn = false; brightnessLevel = 100; } bool Lamp::isTurnedOn() { return _isTurnedOn; } void Lamp::turnOn(unsigned long code, unsigned int length) { RFTransmitter::sendCode(code, length); setPowerState(true); } void Lamp::turnOff(unsigned long code, unsigned int length) { RFTransmitter::sendCode(code, length); setPowerState(false); } void Lamp::setPowerState(bool isTurnedOn) { _isTurnedOn = isTurnedOn; } void Lamp::setBrightness(int level, unsigned long code, unsigned int length) { RFTransmitter::sendCode(code, length); brightnessLevel = level; } int Lamp::getBrightness() { return brightnessLevel; } <file_sep>#ifndef LCD_HPP #define LCD_HPP #include <LiquidCrystal_I2C.h> #include <Wire.h> class LCD { LiquidCrystal_I2C *lcd; int sdaPin, scaPin; public: LCD(int sdaPin, int scaPin, uint8_t columns, uint8_t rows); LCD *init(); LCD *print(const String &text); LCD *print(float value); LCD *moveCursorTo(uint8_t column, uint8_t row); LCD *clear(); }; #endif <file_sep>#include "IRReceiver.hpp" IRReceiver::IRReceiver(uint8_t pin) : Sensor(pin) { ir = new IRrecv(pin, CAPTURE_BUFFER_SIZE, TIMEOUT, true); ir->enableIRIn(); } std::tuple<uint64_t, String> IRReceiver::capture() { std::tuple<uint64_t, String> data; if (ir->decode(&results)) { decodedData = resultToSourceCode(&results); data = std::tuple<uint64_t, String>(results.value, decodedData); ir->resume(); } else { data = std::tuple<uint64_t, String>(0ULL, "UNKNOWN"); } return data; } String IRReceiver::getDecodedData() const { return decodedData; } <file_sep>#include "LCD.hpp" /* Typical config #define LCD_SDA_PIN 14 #define LCD_SCL_PIN 12 #define LCD_COLUMNS 16 #define LCD_ROWS 2 */ LCD::LCD(int _sdaPin, int _scaPin, uint8_t columns, uint8_t rows) : sdaPin(_sdaPin), scaPin(_scaPin) { lcd = new LiquidCrystal_I2C(0x27, columns, rows); } LCD *LCD::init() { Wire.begin(sdaPin, scaPin); lcd->init(); lcd->backlight(); lcd->print("Ready"); return this; } LCD *LCD::print(float value) { return print(String(value)); } LCD *LCD::print(const String& text) { lcd->print(text); return this; } LCD *LCD::clear() { lcd->clear(); return this; } LCD *LCD::moveCursorTo(uint8_t column, uint8_t row) { lcd->setCursor(column, row); return this; } <file_sep>#ifndef MOTION_SENSOR_HPP #define MOTION_SENSOR_HPP #include "Sensor.hpp" class MotionSensor : public Sensor { public: explicit MotionSensor(uint8_t); bool isMovementDetected(); }; #endif <file_sep>#include "RFReceiver.hpp" RFReceiver::RFReceiver(uint8_t pin) : Sensor(pin) { receiver = RCSwitch(); enable(); } unsigned long RFReceiver::listen() { unsigned long code = 0; if (receiver.available()) { Serial.print("Received "); code = receiver.getReceivedValue(); Serial.print(code); Serial.print(" / "); Serial.print(receiver.getReceivedBitlength()); Serial.print("bit "); Serial.print("Protocol: "); Serial.println(receiver.getReceivedProtocol()); receiver.resetAvailable(); } return code; } void RFReceiver::disable() { receiver.disableReceive(); } void RFReceiver::enable() { receiver.enableReceive(getPin()); } <file_sep>#ifndef LIGHT_SENSOR_HPP #define LIGHT_SENSOR_HPP #include <BH1750FVI.h> #include <Wire.h> class LightSensor { static const unsigned int CONNECTION_ATTEMPT_DELAY; static const unsigned int CONNECTION_TIMEOUT; BH1750FVI *lightSensor; bool isConnected; public: LightSensor(uint8_t, uint8_t); float measureLightLevel(); bool isAvailable(); }; #endif <file_sep>#ifndef IR_TRANSMITTER_H #define IR_TRANSMITTER_H #include <IRsend.h> #include "IRDevice.hpp" #include "Sensor.hpp" class IRTransmitter : public Sensor { IRsend *ir; public: explicit IRTransmitter(uint8_t); void send(IRDevice::Model, uint64_t); }; #endif <file_sep># Arduino Sensors' Wrappers Library This library simplifies working with common devices like button, LED, motion sensor, RF receiver / transmitter, etc. ## Installation Just follow the recommended [PlatformIO instructions](https://platformio.org/lib/show/6374/arduino-sensors-wrappers/installation). In case of any manual updates, you have to clone this repository, make modifications and copy corresponding sources into ./lib/arduino-sensors-wrappers (assuming you're using PlatformIO) or Arduino/libraries/arduino-sensors-wrappers (in case of Arduino usage) folder. ## Usage Check [examples](https://github.com/sskorol/arduino-sensors-wrappers/tree/master/examples) for details. <file_sep>#ifndef RF_TRANSMITTER_HPP #define RF_TRANSMITTER_HPP #include <RCSwitch.h> #include "Sensor.hpp" class RFTransmitter : public Sensor { RCSwitch transmitter; public: explicit RFTransmitter(uint8_t); void sendCode(unsigned long, unsigned int); void switchProtocol(int); void enable(); void disable(); }; #endif <file_sep>#ifndef IR_RECEIVER_H #define IR_RECEIVER_H #include <IRrecv.h> #include <IRutils.h> #include <tuple> #include "Sensor.hpp" #define CAPTURE_BUFFER_SIZE 1024 #define TIMEOUT 15U class IRReceiver : public Sensor { IRrecv *ir; decode_results results; String decodedData; public: explicit IRReceiver(uint8_t); std::tuple<uint64_t, String> capture(); String getDecodedData() const; }; #endif <file_sep>#include "Button.hpp" #include "LED.hpp" #define BAUD_RATE 115200 #define BUTTON_PIN D1 #define LED_PIN D2 #define DEBOUNCING_INTERVAL 5 Button button = Button(BUTTON_PIN, DEBOUNCING_INTERVAL); LED led = LED(LED_PIN); void setup() { Serial.begin(BAUD_RATE); } void loop() { if (button.isPressed()) { led.changeState(!led.isTurnedOn()); } } <file_sep>#ifndef BUTTON_HPP #define BUTTON_HPP #include "ContactSensor.hpp" class Button : public ContactSensor { public: Button(uint8_t, uint16_t); bool isPressed(); }; #endif <file_sep>#include "SamsungAirConditioner.hpp" SamsungAirConditioner::SamsungAirConditioner(uint8_t pin, bool inverted) { ac = new IRSamsungAc(pin, inverted); ac->begin(); } SamsungAirConditioner *SamsungAirConditioner::turnOn() { ac->on(); ac->sendOn(); return this; } SamsungAirConditioner *SamsungAirConditioner::turnOff() { ac->off(); ac->sendOff(); return this; } bool SamsungAirConditioner::isTurnedOn() { return ac->getPower(); } SamsungAirConditioner *SamsungAirConditioner::adjustTemperature(uint8_t value) { return adjustTemperature(value, false); } SamsungAirConditioner *SamsungAirConditioner::adjustTemperature(uint8_t value, bool shouldSend) { ac->setTemp(value); if (shouldSend) { sendCommands(); } return this; } uint8_t SamsungAirConditioner::getTemperature() { return ac->getTemp(); } SamsungAirConditioner *SamsungAirConditioner::adjustFanSpeed(uint8_t value) { return adjustFanSpeed(value, false); } SamsungAirConditioner *SamsungAirConditioner::adjustFanSpeed(uint8_t value, bool shouldSend) { ac->setFan(value); if (shouldSend) { sendCommands(); } return this; } uint8_t SamsungAirConditioner::getFanSpeed() { return ac->getFan(); } SamsungAirConditioner *SamsungAirConditioner::adjustWorkMode(uint8_t value) { return adjustWorkMode(value, false); } SamsungAirConditioner *SamsungAirConditioner::adjustWorkMode(uint8_t value, bool shouldSend) { ac->setMode(value); if (shouldSend) { sendCommands(); } return this; } uint8_t SamsungAirConditioner::getWorkMode() { return ac->getMode(); } SamsungAirConditioner *SamsungAirConditioner::adjustSwingMode(bool state) { return adjustSwingMode(state, false); } SamsungAirConditioner *SamsungAirConditioner::adjustSwingMode(bool state, bool shouldSend) { ac->setSwing(state); if (shouldSend) { sendCommands(); } return this; } bool SamsungAirConditioner::isSwingModeOn() { return ac->getSwing(); } SamsungAirConditioner *SamsungAirConditioner::sendCommands() { ac->send(); return this; } SamsungAirConditioner *SamsungAirConditioner::printState() { Serial.println("Samsung A/C remote is in the following state:"); Serial.printf(" %s\n", ac->toString().c_str()); return this; } <file_sep>#ifndef RF_RECEIVER_HPP #define RF_RECEIVER_HPP #include "Sensor.hpp" #include "RCSwitch.h" class RFReceiver : public Sensor { RCSwitch receiver; public: explicit RFReceiver(uint8_t); unsigned long listen(); void enable(); void disable(); }; #endif <file_sep>#include "Button.hpp" Button::Button(uint8_t pin, uint16_t debouncingInterval) : ContactSensor(pin, debouncingInterval) {} bool Button::isPressed() { return ContactSensor::isUpdated() && ContactSensor::getState() == LOW; } <file_sep>#include "RFTransmitter.hpp" RFTransmitter::RFTransmitter(uint8_t pin) : Sensor(pin) { transmitter = RCSwitch(); enable(); } void RFTransmitter::sendCode(unsigned long code, unsigned int length) { transmitter.send(code, length); } void RFTransmitter::switchProtocol(int number) { transmitter.setProtocol(number); } void RFTransmitter::enable() { transmitter.enableTransmit(getPin()); } void RFTransmitter::disable() { transmitter.disableTransmit(); } <file_sep>#ifndef LED_HPP #define LED_HPP #include "Sensor.hpp" class LED : public Sensor { int state; public: explicit LED(uint8_t); void changeState(uint8_t); void turnOn(); void turnOff(); boolean isTurnedOn(); }; #endif <file_sep>#ifndef SAMSUNG_AIR_CONDITIONER_HPP #define SAMSUNG_AIR_CONDITIONER_HPP #include <IRremoteESP8266.h> #include <IRsend.h> #include <ir_Samsung.h> class SamsungAirConditioner { IRSamsungAc *ac; public: explicit SamsungAirConditioner(uint8_t pin, bool inverted = false); SamsungAirConditioner *turnOn(); SamsungAirConditioner *turnOff(); bool isTurnedOn(); SamsungAirConditioner *adjustTemperature(uint8_t); SamsungAirConditioner *adjustTemperature(uint8_t, bool); uint8_t getTemperature(); SamsungAirConditioner *adjustFanSpeed(uint8_t); SamsungAirConditioner *adjustFanSpeed(uint8_t, bool); uint8_t getFanSpeed(); SamsungAirConditioner *adjustWorkMode(uint8_t); SamsungAirConditioner *adjustWorkMode(uint8_t, bool); uint8_t getWorkMode(); SamsungAirConditioner *adjustSwingMode(bool); SamsungAirConditioner *adjustSwingMode(bool, bool); bool isSwingModeOn(); SamsungAirConditioner *sendCommands(); SamsungAirConditioner *printState(); }; #endif <file_sep>#include "ContactSensor.hpp" ContactSensor::ContactSensor(uint8_t pin, uint16_t debouncingInterval) : Sensor(pin, INPUT_PULLUP) { debouncer = Bounce(); debouncer.attach(pin); debouncer.interval(debouncingInterval); } int ContactSensor::getState() { return debouncer.read(); } bool ContactSensor::isUpdated() { return debouncer.update(); } <file_sep>#include "IRTransmitter.hpp" using namespace IRDevice; IRTransmitter::IRTransmitter(uint8_t pin) : Sensor(pin) { ir = new IRsend(pin); ir->begin(); } void IRTransmitter::send(Model deviceModel, uint64_t code) { switch (deviceModel) { case Model::SAMSUNG: ir->sendSAMSUNG(code, SAMSUNG_BITS, 1); break; } } <file_sep>#include "Sensor.hpp" Sensor::Sensor(uint8_t _pin, uint8_t mode) : pin(_pin) { pinMode(pin, mode); } Sensor::Sensor(uint8_t _pin) : pin(_pin) {} uint8_t Sensor::getPin() const { return pin; } <file_sep>name=arduino-sensors-wrappers version=0.0.7 author=<NAME> <<EMAIL>> maintainer=<NAME> <<EMAIL>> sentence=A set of wrappers for easier sensors management. paragraph=arduino-sensor-wrappers provides a set of wrappers to simplify development routings while working with different sensors. category=Sensors url=https://github.com/sskorol/arduino-sensors-wrappers architectures=* repository=https://github.com/sskorol/arduino-sensors-wrappers.git license=Apache-2.0 <file_sep>#ifndef CONTACT_SENSOR_HPP #define CONTACT_SENSOR_HPP #include "Sensor.hpp" #include <Bounce2.h> class ContactSensor : public Sensor { Bounce debouncer; public: ContactSensor(uint8_t, uint16_t); int getState(); bool isUpdated(); }; #endif <file_sep>#include "LED.hpp" LED::LED(uint8_t pin) : Sensor(pin, OUTPUT) { state = LOW; } void LED::changeState(uint8_t _state) { state = _state; digitalWrite(getPin(), state); } void LED::turnOn() { changeState(HIGH); } void LED::turnOff() { changeState(LOW); } boolean LED::isTurnedOn() { return state == HIGH; } <file_sep>#include "MotionSensor.hpp" MotionSensor::MotionSensor(uint8_t pin) : Sensor(pin, INPUT) {} bool MotionSensor::isMovementDetected() { return digitalRead(getPin()) == HIGH; } <file_sep>#include "LightSensor.hpp" const unsigned int LightSensor::CONNECTION_ATTEMPT_DELAY = 500; const unsigned int LightSensor::CONNECTION_TIMEOUT = 5000; LightSensor::LightSensor(uint8_t sdaPin, uint8_t sclPin) { Serial.print("\nConnecting to BH1750FVI"); lightSensor = new BH1750FVI(BH1750_DEFAULT_I2CADDR, BH1750_CONTINUOUS_HIGH_RES_MODE_2, BH1750_SENSITIVITY_DEFAULT, BH1750_ACCURACY_DEFAULT); unsigned int elapsedTime = 0; while (!lightSensor->begin(sdaPin, sclPin) && elapsedTime < CONNECTION_TIMEOUT) { delay(CONNECTION_ATTEMPT_DELAY); elapsedTime += CONNECTION_ATTEMPT_DELAY; Serial.print("."); } isConnected = elapsedTime < CONNECTION_TIMEOUT; if (isConnected) { Serial.println("\nBH1750FVI connected"); } else { Serial.println("\nUnable to connect to BH1750FVI"); } } float LightSensor::measureLightLevel() { return isConnected ? lightSensor->readLightLevel() : 0.0f; } bool LightSensor::isAvailable() { return isConnected; }
0993963cc8c25b3397de00b5bea484deed68be04
[ "Markdown", "C++", "INI" ]
30
C++
sskorol/arduino-sensors-wrappers
5ac720c87f7f5822598f35ea43f8764cfe2b6ef1
153c5554122882b4e4c024002d09c00c70666710
refs/heads/master
<file_sep>Simple menu base created for anyone who wants to learn to code in C++ and/or wants to mod RDR2 themselves :) Menu_Constructor.h has all the functions that draw/handle the menu be sure to add your submenus to Submenus enum in enums.h .asi builds to project directory, though I suggest changing build directory to Red Dead Redemption 2 directory for easier building/testing Project -> Properties - > Configuration Properties -> General -> Output Directory Any questions message me on Discord - Raon Hook#1220 (p.s menu base written, designed and tested In about an hour by myself because someone asked In discord, so don't judge too hard lmao)<file_sep>/* THIS FILE IS A PART OF RDR 2 SCRIPT HOOK SDK http://dev-c.com (C) <NAME> 2019 */ #pragma once enum Submenus { Closed, Main_Menu, Submenu1, Submenu2, DogSpawner_Menu, }; <file_sep>#pragma once #include "types.h" #include "natives.h" Hash joaat(const char* string) { return GAMEPLAY::GET_HASH_KEY(string); } void DrawSprite(const char* category, const char* sprite, float x, float y, float scalex, float scaley, float rotation, int r, int g, int b, int a) { float fX = x + scalex / 2; float fY = y + scaley / 2; if (!TEXTURE::HAS_STREAMED_TEXTURE_DICT_LOADED(sprite)) TEXTURE::REQUEST_STREAMED_TEXTURE_DICT(sprite, 0); GRAPHICS::DRAW_SPRITE(category, sprite, fX, fY, scalex, scaley, rotation, r, g, b, a, 1); TEXTURE::SET_STREAMED_TEXTURE_DICT_AS_NO_LONGER_NEEDED(category); } void draw_Text(const char* text, float x, float y, int r, int g, int b, int a, bool centered = false, float sx = 0.342f, float sy = 0.342f) { UI::SET_TEXT_COLOR_RGBA(r, g, b, a); UI::SET_TEXT_SCALE(sx, sy); UI::SET_TEXT_CENTRE(centered); const char* literalString = GAMEPLAY::CREATE_STRING(10, "LITERAL_STRING", text); UI::DRAW_TEXT(literalString, x, y); } void drawRect(float x, float y, float width, float height, int r, int g, int b, int a) { float fX = x + width / 2; float fY = y + height / 2; GRAPHICS::DRAW_RECT(fX, fY, width, height, r, g, b, a, true); } void PrintSubtitle(const char* text) { const char* literalString = GAMEPLAY::CREATE_STRING(10, "LITERAL_STRING", text); UILOG::_0xFA233F8FE190514C(literalString); UILOG::_0xE9990552DEC71600(); UILOG::_0xDFF0D417277B41F8(); } <file_sep>//Simple RDR2 Menu Base by <NAME> #include "inc/types.h" #include "inc/natives.h" #include "inc/Menu_Constructor.h" #include "inc/enums.h" #include "inc/Game_Functions.h" void TeleportForward() { Vector3 pos = ENTITY::GET_ENTITY_COORDS(PLAYER::PLAYER_PED_ID(), 0, 0); float heading = ENTITY::GET_ENTITY_HEADING(PLAYER::PLAYER_PED_ID()); pos.x += sin(-heading * (PI / 180)) * 10; pos.y += cos(heading * (PI / 180)) * 10; ENTITY::SET_ENTITY_COORDS(PLAYER::PLAYER_PED_ID(), pos.x, pos.y, pos.z, 1, 0, 1, 0); } float playerScale = 1; void SetPlayerScale() { PED::_0x25ACFC650B65C538(PLAYER::PLAYER_PED_ID(), playerScale); } int stringoptionint = 0; const char* strings[6] = { "string 1", "string 2", "string 3", "string 4", "string 5", "string 6" }; struct pedModelInfo { const char* model; const char* name; }; pedModelInfo Dogs[] = { {"A_C_DOGAMERICANFOXHOUND_01", "American Foxhound"}, {"A_C_DOGAUSTRALIANSHEPERD_01", "Australian Shepherd"}, {"A_C_DOGBLUETICKCOONHOUND_01", "Bluetick Coonhound"}, {"A_C_DOGCATAHOULACUR_01", "Catahoula Cur"}, {"A_C_DOGCHESBAYRETRIEVER_01", "Ches Bay Retriever"}, {"A_C_DOGCOLLIE_01", "Rough Collie"}, {"A_C_DOGHOBO_01", "Hobo"}, {"A_C_DOGHOUND_01", "Hound"}, {"A_C_DOGHUSKY_01", "Husky"}, {"A_C_DOGLAB_01", "Labrador"}, {"A_C_DOGLION_01", "Lion"}, {"A_C_DOGPOODLE_01", "Poodle"}, {"A_C_DOGRUFUS_01", "Rufus"}, {"A_C_DOGSTREET_01", "Street"} }; int CreatePed(Hash model) { if (STREAMING::IS_MODEL_IN_CDIMAGE(model)) { STREAMING::REQUEST_MODEL(model, 0); while (!STREAMING::HAS_MODEL_LOADED(model)) WAIT(0); Vector3 pos = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0, 5, 0); int ped = PED::CREATE_PED(model, pos.x, pos.y, pos.z, 0, 1, 0, 0, 0); PED::SET_PED_VISIBLE(ped, true); return ped; } } bool Godmode = false; void GodmodeTick() { if (Godmode) { PLAYER::SET_PLAYER_INVINCIBLE(0, true); ENTITY::SET_ENTITY_HEALTH(PLAYER::PLAYER_PED_ID(), ENTITY::GET_ENTITY_MAX_HEALTH(PLAYER::PLAYER_PED_ID(), 0), 0); PED::SET_PED_CAN_BE_KNOCKED_OFF_VEHICLE(PLAYER::PLAYER_PED_ID(), false); PED::SET_PED_CAN_RAGDOLL(PLAYER::PLAYER_PED_ID(), false); } } //Add functions that need to be called repeatedly here void FunctionTicks() { GodmodeTick(); } //Menu Loop | Everything gets called within here void main() { FunctionTicks(); ButtonMonitoring(); switch (submenu) { case Main_Menu: addTitle("Main Menu"); addHeader("Menu Base by <NAME>"); addSubmenuOption("Submenu 1", Submenu1, [] { PrintSubtitle("This subtitle was called before the menu changed\nUseful when needing to initialize something beforehand"); }); addBoolOption("Godmode", Godmode, [] {Godmode = !Godmode; }); addBoolOption("Invisibility", !ENTITY::IS_ENTITY_VISIBLE(PLAYER::PLAYER_PED_ID()), [] {ENTITY::SET_ENTITY_VISIBLE(PLAYER::PLAYER_PED_ID(), !ENTITY::IS_ENTITY_VISIBLE(PLAYER::PLAYER_PED_ID())); }); addFloatOption("Set Player Scale", &playerScale, 0.1f, SetPlayerScale); addOption("Teleport Forward", TeleportForward); addStringOption("String Option", strings[stringoptionint], &stringoptionint, ARRAYSIZE(strings) - 1, [] {PrintSubtitle(strings[stringoptionint]); }); break; case Submenu1: addTitle("Submenu 1"); addOption("Option"); addSubmenuOption("Dog Spawner", DogSpawner_Menu); break; case DogSpawner_Menu: addTitle("Dog Spawner"); for (int i = 0; i < ARRAYSIZE(Dogs); i++) //Increase int i until i == element count of Dogs[] { addOption(Dogs[i].name, [] { //Adds an option for every loop and Iterates through Dogs with value of i Hash model = GAMEPLAY::GET_HASH_KEY(Dogs[currentOption - 1].model); //You can't pass i through to the function so you must use currentOption - 1 (must subtract 1, as first option = 1, but element 1 of an array = 0) CreatePed(model); //Creates ped //(If you had added an option before the for loop, you would use currentOption - 2, as optionCount would've Increased by 1) }); } break; } resetVars(); } void scriptMain() { srand(GetTickCount()); while (true) { main(); WAIT(0); } } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: scriptRegister(hModule, scriptMain); break; case DLL_PROCESS_DETACH: scriptUnregister(hModule); break; } return TRUE; } <file_sep>Simple menu base created for anyone who wants to learn to code in C++ and/or wants to mod RDR2 themselves. Menu_Constructor.h has all the functions that draw/handle the menu be sure to add your submenus to Submenus enum in enums.h .asi builds to project directory, though I suggest changing build directory to Red Dead Redemption 2 directory for easier building/testing Project -> Properties - > Configuration Properties -> General -> Output Directory Any questions message me on Discord - Raon Hook#1220 (p.s menu base written, designed and tested In about an hour by myself because someone asked In discord, so don't judge too hard :P) ![Image of Menu Base](https://i.imgur.com/QXCsMcS.png) <file_sep>#pragma once #include "Game_Functions.h" #include "enums.h" int submenu = 0; int submenuLevel; int lastSubmenu[20]; int lastOption[20]; int lastSubmenuMinOptions[20]; int lastSubmenuMaxOptions[20]; int currentOption; int optionCount; int maxOptions = 8; bool optionPress = false; int currentMenuMaxOptions = maxOptions; int currentMenuMinOptions = 1; bool leftPress = false; bool rightPress = false; bool fastLeftPress = false; bool fastRightPress = false; float menuX = 0.052f; bool menuHeader = false; void NULLVOID() {} void CloseMenu() { submenu = Closed; submenuLevel = 0; currentOption = 1; } void changeSubmenu(int newSubmenu) { lastSubmenu[submenuLevel] = submenu; lastOption[submenuLevel] = currentOption; lastSubmenuMinOptions[submenuLevel] = currentMenuMinOptions; lastSubmenuMaxOptions[submenuLevel] = currentMenuMaxOptions; currentOption = 1; currentMenuMinOptions = 1; currentMenuMaxOptions = maxOptions; submenu = newSubmenu; submenuLevel++; optionPress = false; } void addTitle(const char* title) { optionCount = 0; draw_Text(title, menuX + 0.13f, 0.076f, 255, 255, 255, 255, true, 0.5f, 0.5f); drawRect(menuX, 0.073f, 0.260f, 0.104f, 0, 0, 0, 190); DrawSprite("generic_textures", "menu_header_1a", menuX, 0.058f, 0.260f, 0.074f, 0, 255, 255, 255, 255); DrawSprite("generic_textures", "hud_menu_4a", menuX, 0.131f + 0.027f, 0.260f, 0.002f, 0, 255, 255, 255, 255); } void addHeader(const char* header) { menuHeader = true; draw_Text(header, menuX + 0.13f, 0.076f + 0.0575f, 255, 255, 255, 255, true, 0.3f, 0.3f); } float bodyOffset = 0; void addOption(const char* option, void (func)() = NULLVOID) { optionCount++; if (currentOption <= currentMenuMaxOptions && optionCount <= currentMenuMaxOptions && currentOption >= currentMenuMinOptions && optionCount >= currentMenuMinOptions) { draw_Text(option, menuX + 0.007f, 0.131f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 255, 255, 255, 255); drawRect(menuX, 0.124f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.260f, 0.038f, 0, 0, 0, 190); if (currentOption == optionCount) { DrawSprite("generic_textures", "selection_box_bg_1d", menuX, 0.124f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.260f, 0.038f, 0, 255, 0, 0, 190); if (optionPress) func(); } } } void addSubmenuOption(const char* option, int submenu) { addOption(option); if (currentOption <= currentMenuMaxOptions && optionCount <= currentMenuMaxOptions && currentOption >= currentMenuMinOptions && optionCount >= currentMenuMinOptions) { DrawSprite("menu_textures", "selection_arrow_right", menuX + 0.235f, 0.132f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.01125f, 0.02f, 0, 255, 255, 255, 255); if(currentOption == optionCount) if (optionPress) changeSubmenu(submenu); } } void addSubmenuOption(const char* option, int submenu, void (func)()) { addOption(option); if (currentOption <= currentMenuMaxOptions && optionCount <= currentMenuMaxOptions && currentOption >= currentMenuMinOptions && optionCount >= currentMenuMinOptions) { DrawSprite("menu_textures", "selection_arrow_right", menuX + 0.235f, 0.132f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.01125f, 0.02f, 0, 255, 255, 255, 255); if(currentOption == optionCount){ if (optionPress) { func(); changeSubmenu(submenu); } } } } void addBoolOption(const char* option, bool var, void (func)() = NULLVOID) { addOption(option); if (currentOption <= currentMenuMaxOptions && optionCount <= currentMenuMaxOptions && currentOption >= currentMenuMinOptions && optionCount >= currentMenuMinOptions) { if (var) { DrawSprite("generic_textures", "tick_box", menuX + 0.232f, 0.132f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.0140625f, 0.025f, 0, 255, 255, 255, 255); DrawSprite("generic_textures", "tick", menuX + 0.232f, 0.132f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.0140625f, 0.025f, 0, 255, 255, 255, 255); } else { DrawSprite("generic_textures", "tick_box", menuX + 0.232f, 0.132f + (0.038f * ((optionCount - currentMenuMinOptions) + 1)), 0.0140625f, 0.025f, 0, 255, 255, 255, 255); } if (currentOption == optionCount) if (optionPress) func(); } } void addIntOption(const char* option, int* var, int step = 1, bool fastPress = false, int min = -2147483647, int max = 2147483647) { char buffer[64]; snprintf(buffer, 64, "%s < %i >", option, *var); addOption(buffer); if (currentOption == optionCount) { if (fastPress) { if (fastLeftPress) { if (*var == min) *var = max; else *var -= step; } else if (fastRightPress) { if (*var == max) *var = min; else *var += step; } } else { if (leftPress) { if (*var == min) *var = max; else *var -= step; } else if (rightPress) { if (*var == max) *var = min; else *var += step; } } } } void addIntOption(const char* option, int* var, void (func)(), int step = 1, bool fastPress = false, int min = -2147483647, int max = 2147483647) { char buffer[64]; snprintf(buffer, 64, "%s < %i >", option, *var); addOption(buffer); if (currentOption == optionCount) { if (fastPress) { if (fastLeftPress) { if (*var == min) *var = max; else *var -= step; } else if (fastRightPress) { if (*var == max) *var = min; else *var += step; } } else { if (leftPress) { if (*var == min) *var = max; else *var -= step; } else if (rightPress) { if (*var == max) *var = min; else *var += step; } } if (optionPress) func(); } } void addFloatOption(const char* option, float* var, float step, bool fastPress = false, float min = -3.4028235e38, float max = 3.4028235e38) { char buffer[64]; snprintf(buffer, 64, "%s < %.03f >", option, *var); addOption(buffer); if (currentOption == optionCount) { if (fastPress) { if (fastLeftPress) { if (*var == min) *var = max; else *var -= step; } else if (fastRightPress) { if (*var == max) *var = min; else *var += step; } } else { if (leftPress) { if (*var == min) *var = max; else *var -= step; } else if (rightPress) { if (*var == max) *var = min; else *var += step; } } } } void addFloatOption(const char* option, float* var, float step, void (func)(), bool fastPress = false, float min = -3.4028235e38, float max = 3.4028235e38) { char buffer[64]; snprintf(buffer, 64, "%s < %.03f >", option, *var); addOption(buffer); if (currentOption == optionCount) { if (fastPress) { if (fastLeftPress) { if (*var == min) *var = max; else *var -= step; } else if (fastRightPress) { if (*var == max) *var = min; else *var += step; } } else { if (leftPress) { if (*var == min) *var = max; else *var -= step; } else if (rightPress) { if (*var == max) *var = min; else *var += step; } } if (optionPress) func(); } } void addStringOption(const char* option, const char* var, int* intvar, int elementCount, bool fastPress = false) { char buffer[64]; snprintf(buffer, 64, "%s < %s >", option, var); addOption(buffer); if (currentOption == optionCount) { if (fastPress == false) { if (leftPress) { if (*intvar <= 0) *intvar = elementCount; else *intvar -= 1; } else if (rightPress) { if (*intvar >= elementCount) *intvar = 0; else *intvar += 1; } } else { if (fastLeftPress) { if (*intvar <= 0) *intvar = elementCount; else *intvar -= 1; } else if (fastRightPress) { if (*intvar >= elementCount) *intvar = 0; else *intvar += 1; } } } } void addStringOption(const char* option, const char* var, int* intvar, int elementCount, void (func)(), bool fastPress = false) { char buffer[64]; snprintf(buffer, 64, "%s < %s >", option, var); addOption(buffer); if (currentOption == optionCount) { if (fastPress == false) { if (leftPress) { if (*intvar <= 0) *intvar = elementCount; else *intvar -= 1; } else if (rightPress) { if (*intvar >= elementCount) *intvar = 0; else *intvar += 1; } } else { if (fastLeftPress) { if (*intvar <= 0) *intvar = elementCount; else *intvar -= 1; } else if (fastRightPress) { if (*intvar >= elementCount) *intvar = 0; else *intvar += 1; } } if (optionPress) func(); } } void displayOptionIndex() { char buffer[32]; snprintf(buffer, 32, "%i of %i", currentOption, optionCount); if (optionCount >= maxOptions) { draw_Text(buffer, menuX + 0.13f, 0.131f + (0.038f * (maxOptions + 1)), 255, 255, 255, 255, true); drawRect(menuX, 0.124f + (0.038f * (maxOptions + 1)), 0.260f, 0.038f, 0, 0, 0, 190); DrawSprite("generic_textures", "hud_menu_4a", menuX, 0.126f + (0.038f * (maxOptions + 1)), 0.260f, 0.002f, 0, 255, 255, 255, 255); } else { draw_Text(buffer, menuX + 0.13f, 0.131f + (0.038f * (optionCount + 1)), 255, 255, 255, 255, true); drawRect(menuX, 0.124f + (0.038f * (optionCount + 1)), 0.260f, 0.038f, 0, 0, 0, 190); DrawSprite("generic_textures", "hud_menu_4a", menuX, 0.126f + (0.038f * (optionCount + 1)), 0.260f, 0.002f, 0, 255, 255, 255, 255); } } void resetVars() { if (submenu != Closed) { displayOptionIndex(); } optionPress = false; rightPress = false; leftPress = false; fastRightPress = false; fastLeftPress = false; menuHeader = false; } void ButtonMonitoring() { if (submenu == Closed) { if (CONTROLS::IS_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_LT")) || CONTROLS::IS_DISABLED_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_LT"))) { submenu = Main_Menu; submenuLevel = 0; currentOption = 1; currentMenuMinOptions = 1; currentMenuMaxOptions = maxOptions; } } else { if (CONTROLS::IS_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_RDOWN"))) { //Enter optionPress = true; } if (CONTROLS::IS_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_RRIGHT"))) //Backspace { if (submenu == Main_Menu) { CloseMenu(); } else { submenu = lastSubmenu[submenuLevel - 1]; currentOption = lastOption[submenuLevel - 1]; currentMenuMinOptions = lastSubmenuMinOptions[submenuLevel - 1]; currentMenuMaxOptions = lastSubmenuMaxOptions[submenuLevel - 1]; submenuLevel--; } } if (CONTROLS::IS_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_UP"))) //Scroll Up { if (currentOption == 1) { currentOption = optionCount; currentMenuMaxOptions = optionCount; if (optionCount > maxOptions) currentMenuMinOptions = optionCount - maxOptions + 1; else currentMenuMinOptions = 1; } else { currentOption--; if (currentOption < currentMenuMinOptions) { currentMenuMinOptions = currentOption; currentMenuMaxOptions = currentOption + maxOptions - 1; } } } if (CONTROLS::IS_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_DOWN"))) //Scroll Down { if (currentOption == optionCount) { currentOption = 1; currentMenuMinOptions = 1; currentMenuMaxOptions = maxOptions; } else { currentOption++; if (currentOption > currentMenuMaxOptions) { currentMenuMaxOptions = currentOption; currentMenuMinOptions = currentOption - maxOptions + 1; } } } if (CONTROLS::IS_DISABLED_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_LEFT"))) //Scroll Left { leftPress = true; } if (CONTROLS::IS_DISABLED_CONTROL_JUST_PRESSED(0, joaat("INPUT_FRONTEND_RIGHT"))) //Scroll Right { rightPress = true; } if (CONTROLS::IS_DISABLED_CONTROL_PRESSED(0, joaat("INPUT_FRONTEND_LEFT"))) { fastLeftPress = true; } if (CONTROLS::IS_DISABLED_CONTROL_PRESSED(0, joaat("INPUT_FRONTEND_RIGHT"))) { fastRightPress = true; } } }
dcd89df007f17e366d7aa9ee75743f05934c16af
[ "Markdown", "C", "Text", "C++" ]
6
Text
Adam058/RDR2-Menu-Base
6d76ab0f934df898761dfc92fd646d4083d230c0
b261c10c12840b233d8941fec0420d6a5dd1d39a
refs/heads/main
<file_sep>--- --- <!-- See annual summary data saved as `card_summary.csv` within this directory (`fishery`). --> <!-- TODO: MORE NARRATIVE HERE for table summary (1) explain with comments each code chunk (2) narrative: wording about pre-ALDS & ALDS, free & then charge (3) narrative: note about pre-ALDS not having DNF category (4) narrative: number table and then reference number; explain field names (5) decide whether or not to include species fate (6) decide whether or not to save output to .csv file --> ```{r todo-list, eval=FALSE} # TODO: address below # See Notes-FishingCode.txt # Useage level codes (2013-current)*: # U = used card (& caught fish) # NU = did not use card (i.e., did not fish) # UNS = used card (but did not catch fish; i.e., got skunked) # *in 2012 codes were only U or NU # TODO: address for 2013 and greater, som anglers entering on-line reported # fishing but did not report catch (use proper internet selection for fishing) # TODO: include 2 columns of catch (one with using codes u, nu, uns) and the # other straight from the Catch dataframe # TODO: consolidate species_fate and annual_length (similar) but some length # data in the latter might be nice to preserve # TODO: add narrative # TODO: save appropriate data ``` <!-- Cards issued (purchased) --> ```{r purchased} # Card data are bifurcated (i.e., pre-ALDS, ALDS), so it is a bit cumbersome to # combine into concise output issued and returned data # below is the summary for cards issued or purchased (year dependent) # head(Card[["ArchTally"]]) # head(Card[["AldsPurchased"]]) col_names <- c("Year", "Issued") p07_11 <- aggregate( formula = Counts ~ CardYear, data = Card[["ArchTally"]], FUN = sum, subset = TallyDesc %in% "CardsIssued" ) colnames(p07_11) <- col_names pAlds <- aggregate( formula = LicenseID ~ ItemYear, data = Card[["AldsPurchased"]], FUN = length, subset = StatusCodeDesc %in% "Active" & !duplicated(LicenseID) ) colnames(pAlds) <- col_names purchased <- rbind(p07_11, data.frame(Year = 2011, Issued = 112000), pAlds) # clean up rm(p07_11, pAlds, col_names) ``` <!-- Cards returned --> ```{r ret-0711} dnf_nocatch_0711 <- aggregate( formula = Counts ~ CardYear + TallyDesc, data = Card[["ArchTally"]], FUN = sum, na.rm = TRUE, subset = !(TallyDesc %in% "CardsIssued") ) ``` ```{r ret-alds} # head(Card[["AldsReturned"]]) card_catch_2012 <- with(data = Card$AnglerCatch, expr = { # sum(Year %in% 2012 & !duplicated(AnglerID)) sum(!duplicated(AnglerID[Year %in% 2012])) }) # !duplicated(LicenseID) needed below nodup <- !duplicated(Card[["AldsReturned"]][["LicenseID"]]) ret_type_alds <- with(data = Card[["AldsReturned"]][nodup, ], expr = { # nodup <- !duplicated(LicenseID) res <- table(ItemYear, Code, useNA = "ifany") tot_used <- sum(res["2012", c("U", "UNS")]) res["2012", "UNS"] <- tot_used - card_catch_2012 res["2012", "U"] <- card_catch_2012 res }) # clean up rm(nodup, card_catch_2012) ``` ```{r ret-catch} # gets annual number of cards returned with catch; basically it's a count of the # unique anglers who reported catching at least one sturgeon ret_catch <- aggregate( formula = AnglerID ~ Year, data = Card[["AnglerCatch"]], FUN = function(x) sum(!duplicated(x)) ) colnames(ret_catch) <- c("Year", "Catch") ``` <!-- below adds more fields to annual summary --> ```{r dnf-fnc} # purchased$NoEffort <- NULL # purchased$NoCatch <- NULL # purchased$Catch <- NULL # combine older & ALDS data for did not fish & fished no catch dnf_fnc <- with(data = dnf_nocatch_0711, expr = { b_dnf <- TallyDesc %in% "DidNotFish" b_fnc <- TallyDesc %in% "NoCatch" # NU = did not fish; UNS = fished no catch dnf <- c(Counts[b_dnf], unname(ret_type_alds[, "NU"])) fnc <- c(Counts[b_fnc], unname(ret_type_alds[, "UNS"])) # because CDFW did not collect these data 2007-2010 dnf[1:3] <- NA_integer_ # matrix for ease of combining with purchased data matrix( data = c(dnf, fnc), ncol = 2, dimnames = list(NULL, c("NoEffort", "NoCatch")) ) }) # clean up rm(dnf_nocatch_0711) ``` ```{r card-summary} # to create the card sumary by combining purchased data with reported data card_summary <- data.frame( # purchased[purchased[["Year"]] <= current_card_year, ], purchased, dnf_fnc ) card_summary <- merge( x = card_summary, y = ret_catch, by = "Year", all = TRUE ) i <- match( card_summary[["Year"]], table = as.numeric(dimnames(ret_type_alds)[[1]]) ) card_summary$CatchAlds <- ret_type_alds[i, "U"] # clean up rm(i, purchased, dnf_fnc, ret_type_alds, ret_catch) ``` ```{r return-rate} rate_not_ret <- with(data = card_summary, expr = { eff <- NoEffort eff[is.na(eff)] <- 0 yr <- Year <= 2011 ctc <- vector(mode = "numeric", length = length(yr)) ctc[yr] <- Catch[yr] ctc[!yr] <- CatchAlds[!yr] ret <- eff + NoCatch + ctc list(RR = (ret / Issued) * 100, Not = Issued - ret) }) card_summary$ReturnRate <- rate_not_ret[["RR"]] card_summary$NotReturned <- rate_not_ret[["Not"]] ``` ```{r reporting-source} reporting_source <- aggregate( formula = CustomerID ~ ItemYear + CustomerSourceCode, data = Card[["AldsReturned"]], FUN = length ) colnames(reporting_source) <- c("Year", "Source", "Count") # add reporting source fields to card_summary b_cc <- reporting_source[["Source"]] %in% "CC" i <- match(card_summary[["Year"]], table = reporting_source[["Year"]]) card_summary$CC <- reporting_source[b_cc, "Count"][i] card_summary$IS <- reporting_source[!b_cc, "Count"][i] # clean up rm(reporting_source, b_cc, i) ``` <!-- may not include below in display --> ```{r species-fate, eval=FALSE} # chunk merges card_summary with species fate, and for now (09-Apr-2020) I've # decided not to include this, likely it'll be presented elsewhere in the report species_fate <- aggregate( formula = AnglerID ~ Year + Species + Fate, data = Card[["AnglerCatch"]], FUN = length ) # for ease of display species_fate <- xtabs( formula = AnglerID ~ Year + paste(Species, Fate, sep = "_"), data = species_fate ) # for mering with card_summary species_fate <- data.frame( Year = as.numeric(dimnames(species_fate)[[1]]), GST = species_fate[, "Green_"], WSTr = species_fate[, "White_released"], WSTk = species_fate[, "White_kept"], Unkr = species_fate[, "Unk_released"], row.names = NULL ) card_summary <- merge( x = card_summary, y = species_fate, by = "Year", all = TRUE ) # clean up rm(species_fate) ``` <file_sep># ****************************************************************************** # Created: 11-Apr-2016 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file produces abundance at sturgeon age, particularly age-15 - # one of the metrics of the CVPIA. For this process, we currently # use age-length key WSTALKEY (the extant age-length key used by CDFW) # and abundance estimates by way of harvest (Card) and harvest rate # mark-recapture. # ****************************************************************************** # TODO (<NAME>, 15-Apr-2016): for lf dist decide whether or not to subset on # ShedTag != Yes or Maybe & try to reconcile catch with WSTALKEY.xls (2006-2009) # using various subsetting (i.e., understand where numbers are coming from) # TODO (<NAME>, 15-Apr-2016): # Background -------------------------------------------------------------- # we assign ages using age-length keys (alk) # (1) alk developed with data from mostly 1970s (can be found in WSTALKEY.xls) # (2) alk developed by USFWS who have aged sturgeon (some collected from CDFW # operations) starting in 2014 # we need to start first with a WST length frequency distribution then get age # frequency. # add more here... # File Paths -------------------------------------------------------------- # data_import <- "C:/Data/jdubois/RDataConnections/Sturgeon" # Libraries and Source Files ---------------------------------------------- library(ggplot2) # library(reshape) # library(reshape2) source(file = "../../RDataConnections/Sturgeon/OtherData.R") source(file = "../../RDataConnections/Sturgeon/TaggingData.R") source(file = "../../RSourcedCode/methods_len_freq.R") source(file = "../../RSourcedCode/methods_age_freq.R") source(file = "../../RSourcedCode/functions_global_data_subset.R") # source(file = "source_stu_mark-recap.R") # load .rds abundance data (NOTE: .rds file is saved in Analysis-AltAbundance, # so run code therein to refresh this .rds file - last refreshed 15-Apr-2016) AltAbundance <- readRDS("Analysis-AbundByAge/AltAbund.rds") # Workspace Clean Up ------------------------------------------------------ # rm() # Variables --------------------------------------------------------------- # establish l-f breaks for WSTALKEY; note this alk uses TL not FL #wst_alkey_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) wst_alkey_breaks <- c(wst_alkey$Bins, Inf) # Length frequency: all sizes white sturgeon ------------------------------ # For now, lf below includes recaptured WST & WST recorded as shedding tag. Use # below in subset to further dial in lf dist for a particular subset of WST # & !(ShedTag %in% c("Yes", "Maybe")) # get length frequency distribution (from 2006-present for convenience) # including all WST (regardless of size or shed tag) but not recaptured WST wst_lf <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & RelYear > 2005 & # below removes recaptured WST StuType %in% c("Tag", "NoTag") ) # just FIO wst_lf$Breaks wst_lf$Bins wst_lf$Freq # Length frequency: white sturgeon >= 85 cm TL ---------------------------- # NOTE: subsetting on >= 85 cm TL for use in getting at age-15 abundance. Alt # abundance currently calculated using minimum WST length of >= 85 cm TL # get length frequency distribution (from 2006-present for convenience) # including only WST >= 85 cm TL & *not* including recaptured WST (for now, this # includes fish recorded as shedding tag) wst_lf_85 <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & # RelYear > 2005 & TL >= 85 & RelYear %in% c(2007:2014) & TL >= 85 & # below removes recaptured WST StuType %in% c("Tag", "NoTag") ) # just FIO wst_lf_85$Breaks wst_lf_85$Bins wst_lf_85$Freq colSums(wst_lf_85$Freq) # plot(wst_lf, lens = TL, fillBar = LenCat) + facet_grid(facets = RelYear ~ .) # Length frequency: white sturgeon slot sized ----------------------------- # to compare abundance at age-15 when calculated using >= 85 cm TL sized fish or # when using (as in this section) fish within the current slot limit # get lf dist for fish within slot (117-168 cm TL) wst_lf_slot <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & # RelYear > 2005 & TL %in% 117:168 & RelYear %in% c(2007:2014) & TL %in% 117:168 & # below removes recaptured WST StuType %in% c("Tag", "NoTag") ) # just FIO wst_lf_slot$Breaks wst_lf_slot$Bins wst_lf_slot$Freq colSums(wst_lf_slot$Freq) # Age length key: create from other sources ------------------------------- # other sources in this case being 2014 USFWS data GetRandomRows(wst_usfws_age_len) # create usfws al key wst_alk_usfws <- MakeALKey( dat = wst_usfws_age_len, len = TotalLength, age = Age, lenBreaks = wst_lf$Breaks, breakLabs = wst_lf$Bins, dia = TRUE ) # convert wst_alk_usfws bins to integer for analytics to follow wst_alk_usfws$Bins <- as.integer(as.character(wst_alk_usfws$Bins)) # confirm typeof(wst_alk_usfws$Bins) # Age frequency: all sizes white sturgeon --------------------------------- # using different al keys get age frequency distribution for WST # age frequency using extant CDFW age-length key GetAgeFreq( lfTable = wst_lf$Freq, alk = wst_alkey, prop = FALSE ) # age frequency using 2014(?) USFWS age-length key GetAgeFreq( lfTable = wst_lf$Freq, alk = wst_alk_usfws, prop = FALSE ) # Age frequency: white sturgeon >= 85 cm TL ------------------------------- # using different al keys get age frequency distribution for WST; for this # purpose we get proportions of total (by year) for each age rather than count # age frequency using extant CDFW age-length key wst_af_cdfw <- GetAgeFreq( lfTable = wst_lf_85$Freq, alk = wst_alkey, prop = TRUE ) # idea is to then multiply abundance by age freq proportions. wst_af_cdfw[ , -1] * 100000 # age frequency using 2014(?) USFWS age-length key wst_af_usfws <- GetAgeFreq( lfTable = wst_lf_85$Freq, alk = wst_alk_usfws, prop = TRUE ) wst_af_usfws[ , -1] * 100000 # Age frequency: white sturgeon slot size --------------------------------- # age frequency using extant CDFW age-length key wst_af_cdfw_slot <- GetAgeFreq( lfTable = wst_lf_slot$Freq, alk = wst_alkey, prop = TRUE ) # age frequency using data collected by USFWS wst_af_usfws_slot <- GetAgeFreq( lfTable = wst_lf_slot$Freq, alk = wst_alk_usfws, prop = TRUE ) # Abundance: at age ------------------------------------------------------- AltAbundance # as alt abundance is segregated based on length category (sub, leg, ovr) we # need to sum all values to get overall abundance annual_abun <- aggregate( formula = N ~ Year, data = AltAbundance, FUN = sum ) # age-15 abundance using fish >= 85 cm TL & CDFW age-length key GetAbunAtAge( abun = annual_abun, af = wst_af_cdfw, age = 15 ) # age-15 abundance using fish >= 85 cm TL & USFWS age-length key GetAbunAtAge( abun = annual_abun, af = wst_af_usfws, age = 15 ) # age-15 abundance using slot-sized fish & CDFW age-length key GetAbunAtAge( abun = AltAbundance[AltAbundance$LenCat %in% "leg", c("Year", "N")], af = wst_af_cdfw_slot, age = 15 ) # age-15 abundance using slot-sized fish & USFWS age-length key GetAbunAtAge( abun = AltAbundance[AltAbundance$LenCat %in% "leg", c("Year", "N")], af = wst_af_usfws_slot, age = 15 ) # some testing below can be deleted as we really cannot do abundance for all # ages - sturgeon aren't fully recruited to out gear until ~ age-9 wst_af_cdfw[-c(1, 10), -1] * annual_abun$N wifi[4:9] <- lapply(wifi[4:9], A) wst_af_cdfw[-c(1, 10), -1] <- wst_af_cdfw[-c(1, 10), -1] * annual_abun$N wst_af_usfws[-c(1, 10), -1] * annual_abun$N # # TESTING: can be deleted at some point ----------------------------------- with(SturgeonAll[SturgeonAll$Species %in% "White" & #SturgeonAll$StuType %in% c("Tag", "NoTag") & !is.na(SturgeonAll$TL),], expr = { table(RelYear, ShedTag, useNA = "ifany") }) SturgeonAll[SturgeonAll$RelYear %in% 2006 & SturgeonAll$ShedTag %in% c("Yes", "Maybe"),] SturgeonAll[SturgeonAll$TagNum %in% "FF1191", ] <file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics") ``` ```{r libraries} # source(file = "~/RSourcedCode/methods_desc_stats.R") library(dplyr) ``` ```{r load-data} SturgeonCpfv <- readRDS(file = "data/cpfv/SturgeonCpfv.rds") count_all <- nrow(SturgeonCpfv) ``` ```{r somevars} # chunk creates variables needed in analytics or fig caption years_text <- paste0(range(SturgeonCpfv[["LogYear"]]), collapse = "-") # only blocks east of GG Bridge blocks_sfe <- c(300:308, 488, 489) # # for this report only White Sturgeon (assume 470 is mostly white) # species <- c("470", "472") # all & white - for summary only # # # for applying descriptive stats; fields for which stats are applied appear at # # right commented out # cols_desc_stats <- list( # c("Year", "Period", "NumMonths", "NumDays", "N"), # date # "NVals", # vessel count # "ValsAsString", # species code # "Sum", # num kept # "Sum", # num hours fished # "Sum", # num anglers # "Sum" # num angler hours # ) # # # column names for final annual summary output (dataframe) # new_col_names <- c( # "Year", "Period", "Months", "Days", "Trips", #"Vessels", # "SpecCode", "Catch", "Hours", "Anglers", "AnglerHours" # ) # # # column names in dat on which we wish to perform descriptive stats per # # `cols_desc_stats` # mls_names <- c( # "LogDate", "VesselID", "SpeciesCode", "NumberKept", # "HoursFished", "NumberOfFishers", "AnglerHours" # ) ``` ```{r subset-data} SturgeonCpfv <- subset(SturgeonCpfv, Block %in% blocks_sfe) count_sub <- nrow(SturgeonCpfv) ``` ```{r get-summary} cpfv <- SturgeonCpfv %>% filter(Block %in% blocks_sfe & NumberKept > 0) %>% group_by(LogYear) %>% summarise( Catch = sum(NumberKept), # AngHours = sum(AnglerHours, na.rm = TRUE) NumAnglers = sum(NumberOfFishers) ) # adding catch per unit effort (CPUE) field (multiplying by 100 for convenience # of working with larger numbers rather than decimals) # summary_mls$CPUE <- (summary_mls$Catch / summary_mls$AngHours) * 100 xlsx::write.xlsx( cpfv, file = "WhiteStuESRData.xlsx", sheetName = "cpfv"#, # col.names = TRUE, # row.names = FALSE ) ``` ```{r} png(filename = "cpfv.png", width = 1024, height = 768, pointsize = 25) # png(filename = "cpfv.png", width = 6, height = 4, res = 72, pointsize = 25) # c(bottom, left, top, right) par(mar = c(3.5, 4, 1, 4) + 0.1, bty = "u") plot( x = cpfv[["LogYear"]], y = cpfv[["NumAnglers"]], type = "h", lwd = 10, lend = 2, col = "grey75", ylim = c(0, max(cpfv[["NumAnglers"]])), ylab = "Number of anglers (x 1000)", xlab = NA, yaxt = "n", xaxt = "n" ) # range(cpfv[["NumAnglers"]]) # signif(c(seq(0, 3805, 500) / 1000), digits = 3) axis( side = 2, at = seq(0, 3805, 500), labels = format(seq(0, 3805, 500) / 1000), las = 1 # lwd.ticks = , # hadj = ) par(new = TRUE) plot( x = cpfv[["LogYear"]], y = cpfv[["Catch"]], type = "b", cex = 1.1, col = "steelblue", axes = FALSE, ylab = NA, xlab = NA ) # range(cpfv[["Catch"]]) # seq(100, 1000, 100) axis( side = 4, at = seq(100, 1000, 100), labels = (seq(100, 1000, 100)) / 100, las = 2 # lwd.ticks = , # hadj = ) mtext(text = "Catch (x 100)", side = 4, line = 2.5) mtext(text = "Year", side = 1, line = 2) axis( side = 1, at = (1980:2017)[(1980:2017) %% 5 == 0], labels = (1980:2017)[(1980:2017) %% 5 == 0], tck = -0.03, padj = -0.5 # las = 2 # lwd.ticks = 5 # hadj = ) axis( side = 1, at = 1980:2017, labels = NA, tck = -0.01 ) # grid() legend(x = 2000, y = 975, # fill = c("grey75", "steelblue"), col = c("grey75", "steelblue"), pch = c(15, 1), legend = c("Anglers", "Catch"), pt.cex = 1.5, ncol = 2, box.col = "grey90", border = NA) dev.off() ``` ```{r} plot( x = range(cpfv$LogYear), y = c(0, max(cpfv[, c("Catch", "NumAnglers")])), type = "n" ) lines( x = cpfv[["LogYear"]], y = cpfv[["NumAnglers"]], type = "h", lwd = 10, lend = 2, col = "grey75" ) par(new = T) lines( x = cpfv[["LogYear"]], y = cpfv[["Catch"]], type = "b", # lwd = 10, # lend = 2, col = "steelblue", ylim = c(75, 1000), bty = "n" ) # range(cpfv[["Catch"]]) ``` <file_sep>--- title: "White Sturgeon Age-Length Key: A Comparison of Datasets" author: "CA Department of Fish and Wildlife" date: "May 9, 2016" output: html_document: default github_document: html_preview: true toc: true fig_height: 6 fig_width: 8 --- ```{r setup, include=FALSE} knitr::opts_chunk$set( echo = FALSE, warning = FALSE, message = FALSE ) ``` ```{r File Paths and Libraries} # file paths for absolute reference to source code and data connection data_dir <- "C:/Data/jdubois/RDataConnections/Sturgeon/" data_non_db_dir <- "C:/Data/jdubois/RProjects/1_NonDbData" # creates file path to file containing CDFW age-length data file_age_len <- paste(data_non_db_dir, "WstAgeLenData.txt", sep = "/") # load libraries as needed library(ggplot2) library(dplyr) library(knitr) library(tidyr) # library(htmlwidgets) # library(DT) #library(reshape2) #library(scales) ``` ```{r Data, results='hide', cache=TRUE} source(file = paste0(data_dir, "OtherData.R"), echo = TRUE) # source(file = paste0(data_dir, "TaggingData.R"), echo = TRUE) # loads CDFW age-length data (circa mid 1970s) old_al_data <- read.table( file = file_age_len, header = TRUE, sep = "\t", # colClasses = c( # "character", "integer", "POSIXct", "double", # "double", rep("integer", 7), "double", # "integer" # ), col.names = c( "ID", "Species", "Date", "FL", "TL", "Sex", "CapMethod", "Location", "Age", "YearClass", "Check", "Age_1", "TLen", "NewAge" ), stringsAsFactors = FALSE ) # re-format date & add year variable for convenience old_al_data$Date <- as.Date(old_al_data$Date, format = "%m/%d/%y") old_al_data$Year <- as.numeric(format(old_al_data$Date, "%Y")) ``` ```{r Source Code} # the source directory source_dir <- "C:/Data/jdubois/RSourcedCode" # sources needed functions and methods source(file = paste(source_dir, "methods_len_freq.R", sep = "/")) source(file = "source_al_key.R") source(file = paste(source_dir, "methods_age_freq.R", sep = "/")) # source(file = paste(source_dir, "functions_global_data_subset.R", sep = "/")) # source(file = paste(source_dir, "functions_global_desc_stats.R", sep = "/")) # some cleanup # rm(data_dir, source_dir, data_non_db_dir, file_age_len) rm(data_dir, data_non_db_dir, file_age_len) ``` ### Introduction Herein we compare extant age-length data (1973-1976, CDFW) with recently-collected and recently-aged age-length data (2012-present, USFWS). Current data collection and ageing is ongoing, so consider this comparison very preliminary. Further, herein is a comparison of sorts of the extant data to itself. We (CDFW) recently discovered (in electronic form) the age-length data behind our extant age-length key (see WSTALKEY.xls). Recreating the age-length key, we discovered certain (minor) discrepancies. Assuming, of course, we have all the data (and this is a safe assumption +/- a couple data points), the minor discrepancies may be from manual manipulation not (yet) evident in the .xls file or any metadata. In spite of this, we are confident the 1973-1976 data herein are represented in [Kohlhorst et al. (1980)](ftp://ftp.dfg.ca.gov/Adult_Sturgeon_and_Striped_Bass/White%20sturgeon%20age%20and%20growth%201980.pdf). ### General summary: CDFW Data (1973-1976) * All data are for White Sturgeon * Number of records: `r nrow(old_al_data)` * Number of columns: `r ncol(old_al_data)`; "Year" field added for convenience * In counts per year (summary below), years 1998 and 2014 are likely entry errors * Errant data (i.e., data where year > 1976) shown for reference only * Data in fields "Age" and "Age_1" are identical * Data in fields "TL" and "TLen" are identical ```{r SummaryCDFW} # display data structure str(old_al_data) # count of records per year table(CountPerYear = old_al_data$Year, useNA = "ifany") # display records (n=4) where year is a typo (?) old_al_data[old_al_data$Year > 1976, ] # fields are the same # identical(old_al_data$Age, old_al_data$Age_1) # identical(old_al_data$TL, old_al_data$TLen) ``` ### General summary: USFWS Data (2012-ongoing) * All data are for White Sturgeon * Number of records: `r nrow(wst_usfws_age_len)` * Number of columns: `r ncol(wst_usfws_age_len)` * Fish sampled during CDFW mark-recapture study & during sturgeon fishing derby ```{r SummaryUSFWS} # display data structure str(wst_usfws_age_len) # count of records per year table(wst_usfws_age_len$Source, useNA = "ifany") ``` ### Length Frequency Distribution Here we look at the length frequency distributions for both data sets. For the purposes of comparison, we used total length (TL, in centimeters) and binned lengths `r paste0("from ", min(wst_alkey$Bins), " to ", max(wst_alkey$Bins), "+", " by 5 cm")`. See overall stats (for TL) in table below. ```{r LFDist} # establish l-f breaks for WSTALKEY; note this alk uses TL not FL # wst_alkey_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) wst_alkey_breaks <- c(wst_alkey$Bins, Inf) # splitting variables added for convenience of using GetLenFreq() on dataframe old_al_data$DateSource <- "CDFW" wst_usfws_age_len$DateSource <- "USFWS" # create lf dist for 1973-1976 data - using DateSource to "split" data on # although DateSource is all CDFW. Using .dataframe method to enable plotting. lf_cdfw_old <- GetLenFreq( old_al_data, colX = TL, by = "DateSource", breaks = wst_alkey_breaks, intBins = FALSE ) # create lf dist for USFWS data - using DateSource to "split" data on although # DateSource is all USFWS. Using .dataframe method to enable plotting. lf_usfws <- GetLenFreq( wst_usfws_age_len, colX = TotalLength, by = "DateSource", breaks = wst_alkey_breaks, intBins = FALSE ) # desc stats for both cdfw and usfws data kable( rbind( lf_cdfw_old$DescStats, lf_usfws$DescStats )[, c(1, 2, 5:8)], format = "markdown", col.names = c( "Source", "Count", "Mean", "Median", "Min", "Max" ) ) ``` Below, we plot length frequency distributions for CDFW (top) and USFWS (bottom). ```{r LfDistPlots} # plot cdfw lf plot( lf = lf_cdfw_old, lens = TL, fillBar = NULL, type = "POT", addMed = FALSE, addN = TRUE ) + theme_stu_al_key # plot usfws lf plot( lf = lf_usfws, lens = TotalLength, type = "POT", addMed = FALSE, addN = TRUE )+ theme_stu_al_key ``` ### Age Frequency Distribution ```{r AFDist} # variables used for min, max output and to develop x-axis labeling in plots # below age_range_cdfw <- range(old_al_data$Age) age_range_usfws <- range(wst_usfws_age_len$Age) max_age <- max(age_range_cdfw[2], age_range_usfws[2]) ``` Age data for CDFW ranged `r paste0(age_range_cdfw, collapse = "-")` and for USFWS `r paste0(age_range_usfws, collapse = "-")`. Plots below display age frequency distribution (CDFW - top, USFWS - bottom). Note: different y-axis & USFWS plot begins at age-3. ```{r AFDistPlots} # variables for plotting (_x_axis for custom breaks) age_x_axis_2 <- scale_x_continuous( breaks = seq(from = 0, to = max_age, by = 2), expand = c(0.01, 0) ) age_y_axis_2 <- scale_y_continuous(expand = c(0.01, 0)) # plot CDFW age frequency ggplot(data = old_al_data, mapping = aes(x = Age)) + geom_histogram(binwidth = 1, closed = "left") + age_x_axis_2 + age_y_axis_2 + ylab("Count") + theme_stu_al_key # plot USFWS age frequency ggplot(data = wst_usfws_age_len, mapping = aes(x = Age)) + geom_histogram(binwidth = 1, closed = "left") + age_x_axis_2 + age_y_axis_2 + ylab("Count") + theme_stu_al_key # using age to develop al key - need to combine all fish > age-22 to age-22 # (this is per design of WSTALKEY) # old_al_data$Age[old_al_data$Age > 22] <- 22 # clean up rm(age_x_axis_2, age_y_axis_2) ``` ### Mean Length at Age Presented below are mean lengths at each age (CDFW - top, USFWS - bottom). Along with means (Avg) are standard deviation (SD) and standard error (SE). ```{r MeanLenAtAge} # not the best way - but works for now...methods_lf has GetDescStats but I want # to use the one in _global_desc_stats.R, so loading here for this purpose source(file = paste(source_dir, "functions_global_desc_stats.R", sep = "/")) # CDFW - create mean length at age output mean_len_age_cdfw <- old_al_data %>% group_by(Age) %>% select(Age, TL) %>% do(GetDescStats(.$TL)) # USFWS - create mean length at age output mean_len_age_usfws <- wst_usfws_age_len %>% group_by(Age) %>% select(Age, TotalLength) %>% do(GetDescStats(.$TotalLength)) # CDFW kable( as.data.frame(mean_len_age_cdfw), format = "markdown", digits = 3 ) # USFWS kable( as.data.frame(mean_len_age_usfws), format = "markdown", digits = 3 ) # clean up rm(source_dir) ``` ### Growth Curve: von Bertalanffy Growth Curve Applied [Kohlhorst et al. (1980)](ftp://ftp.dfg.ca.gov/Adult_Sturgeon_and_Striped_Bass/White%20sturgeon%20age%20and%20growth%201980.pdf) applied the von Bertalanffy formula (below) to the 1973-1976 data. Here we repeat the application of this formula to the 1973-1976 data, plus we apply the formula to USFWS data. Note: here we use all ages. Kohlhorst et al. (1980) used ages 0-21. R code included below for reference. $l_t = L_∞ * (1 - e^{-k * (age - t_0)})$ where: $l_t$ = length (cm TL) at a given age $L_∞$ = asymptotic length (or length at age infinity) $k$ = curvature parameter (how quickly fish gets to $L_∞$) $t_0$ = age at which fish has 0 length [von Bertalanffy reference](http://www.fao.org/docrep/w5449e/w5449e05.htm) ```{r vonBert, echo=TRUE} # Here we apply the von Bertalanffy model to CDFW data and to USFWS data. # Summary output assigned to variable for use later in this report and in # plotting. VB algorithm fitted using R's nls() function, which requires # starting values (see list argument for 'start' parameter). For reference see # page 663 of "The R Book" (Crawley 2007) # The nls() function requires starting values. Values were choses based on # Kohlhorst et al. 1980 values. # for simplicity... # a = L_sub_inf (200) # b = k (0.05) # c = t_sub_0 (0) # CDFW mod_vb_cdfw <- nls( formula = TLen ~ a * (1 - (exp(-b * (Age - c)))), data = old_al_data, start = list(a = 200, b = 0.05, c = 0) ) # USFWS mod_vb_usfws <- nls( formula = TotalLength ~ a * (1 - (exp(-b * (Age - c)))), data = wst_usfws_age_len, start = list(a = 200, b = 0.05, c = 0) ) # get summary of each model mod_vb_cdfw_sum <- summary(mod_vb_cdfw) mod_vb_usfws_sum <- summary(mod_vb_usfws) ``` Results of the non-linear least squares model `nls()` are given below (CDFW - top, USFWS - bottom). Though displayed as 0, CDFW results are significant to p < 0.001. ```{r VBCoeff Display} kable( mod_vb_cdfw_sum$coefficients, format = "markdown", format.args = list(scientific = FALSE), row.names = TRUE ) kable( mod_vb_usfws_sum$coefficients, format = "markdown", format.args = list(scientific = FALSE), row.names = TRUE ) ``` ```{r XaxisAge} # setting breaks for x-axis for more convenience and more uniformed look age_x_axis <- scale_x_continuous( minor_breaks = seq(from = 0, to = max_age, by = 1), expand = c(0.02, 0) ) ``` Here we plot the von Bertalanffy model output. Points are mean total length (cm) at age. ```{r PlotVb} # set up formula for y-axis in geom_line() - using sprintf() for convenience & # automation vb_yval_cdfw <- sprintf( "%f * (1 - exp(-%f * (Age - %f)))", mod_vb_cdfw_sum$coefficients["a", "Estimate"], mod_vb_cdfw_sum$coefficients["b", "Estimate"], mod_vb_cdfw_sum$coefficients["c", "Estimate"] ) vb_yval_usfws <- sprintf( "%f * (1 - exp(-%f * (Age - %f)))", mod_vb_usfws_sum$coefficients["a", "Estimate"], mod_vb_usfws_sum$coefficients["b", "Estimate"], mod_vb_usfws_sum$coefficients["c", "Estimate"] ) # plot with mean length at age and fitted vb curve ggplot() + geom_line( mapping = aes_string(x = "Age", y = vb_yval_usfws, colour = '"USFWS"'), data = wst_usfws_age_len, size = 2, alpha = 3/5 ) + geom_line( mapping = aes_string(x = "Age", y = vb_yval_cdfw, colour = '"CDFW"'), data = old_al_data, size = 2, alpha = 3/5 ) + stat_summary( mapping = aes(x = Age, y = TotalLength, colour = "USFWS"), data = wst_usfws_age_len, fun.y = mean, geom = "point", size = 3 ) + stat_summary( mapping = aes(x = Age, y = TLen, colour = "CDFW"), data = old_al_data, fun.y = mean, geom = "point", size = 3 ) + scale_color_manual( "", values = c(USFWS = "salmon", CDFW = "steelblue") ) + age_x_axis + labs(y = "Mean total length (cm)") + theme_stu_al_key # checking ages 0:100 - not run # ggplot(data = data.frame(Age = 0:100)) + # geom_line( # mapping = aes_string(x = "Age", y = vb_yval_cdfw, colour = '"CDFW"'), # size = 2, alpha = 3/5 # ) + # geom_line( # mapping = aes_string(x = "Age", y = vb_yval_usfws, colour = '"USFWS"'), # size = 2, alpha = 3/5 # ) ``` ### Other Plots: raw data Below we plot total length (cm) as a function of age, with loess line added for reference (see blue line). Points are raw data (CDFW - top figure, USFWS - bottom figure) and are shaded according to degree of overlap. ```{r RawDataPlots} # plots of cdfw age-length data & usfws age-length data; plotting to show raw # data & trend without fitting data to any one model (see loess line) ggplot(data = old_al_data, mapping = aes(x = Age, y = TLen)) + geom_smooth(se = FALSE, size = 2) + geom_point(alpha = 1/5, size = 3) + age_x_axis + theme_stu_al_key ggplot(data = wst_usfws_age_len, mapping = aes(x = Age, y = TotalLength)) + geom_smooth(se = FALSE, size = 2) + geom_point(alpha = 1/5, size = 3) + age_x_axis + theme_stu_al_key ``` ### CDFW 1970s Data: summary count for some variables Below are summary outputs for CDFW data (1973-1976). We are in the process of finding metadata for the codes. Likely, though, for "Sex" 1 = male, 2 = female. ```{r GeneralInfo} table(CaptureMethod = old_al_data$CapMethod, useNA = "ifany") table(Location = old_al_data$Location, useNA = "ifany") table(Sex = old_al_data$Sex, useNA = "ifany") ``` ### CDFW 1970s Data: understanding the raw data Prior to recent endeavors of ageing sturgeon (i.e., collaboration between CDFW & USFWS), we (CDFW) used the age-length key developed from the 1973-1976 data (see WSTALKEY.xls, tab 'A') to age sturgeon. Recently we found the raw data behind this age-length key. However, in trying to recreate the age-length key with this raw data, we discovered some discrepancies. Twenty of the 34 length bins are identical, leaving 14 with (what I'll call) minor deviations. See "ugly" output below for differences by each length bin. Row 3 of $Data is difference between second row (key of newly found age-length data) and first row (extant key). Row 4 is percent changes as calculated below, where *i* denotes each row. If $IsEqual is TRUE, then keys match for that row. ${change} = \frac{new_i - extant_i}{extant_i} * {100}$ ```{r OldALKey} # create age-length key from "found" electronic age-length key data # using age to develop al key - need to combine all fish > age-22 to age-22 # (this is per design of WSTALKEY) old_al_data$Age[old_al_data$Age > 22] <- 22 new_old_alkey <- MakeALKey( dat = old_al_data, len = TL, age = Age, lenBreaks = wst_alkey_breaks, breakLabs = wst_alkey_breaks[-35] ) # convert wst_alk_usfws bins to integer for analytics to follow new_old_alkey$Bins <- as.integer(as.character(new_old_alkey$Bins)) ``` ```{r DisplayALK, eval=FALSE} kable( wst_alkey, format = "markdown", digits = 4 ) kable( new_old_alkey, format = "markdown", digits = 4 ) ``` ```{r Differences, comment=""} # variable for looping through sapply below rows <- 1:nrow(wst_alkey) names(rows) <- paste0("Bin", wst_alkey[, 1]) # to compare each line (bin) of wst_alkey with the newly-created alkey lst_diff <- sapply(X = rows, FUN = function(x) { # bind each line of the old and new alkey res <- rbind( wst_alkey[x, ], round(new_old_alkey[x, ], digits = 4) ) # calculate difference and percent change for comparison (setting old key as # "first" value); see http://www.percent-change.com/index.php difference <- res[2, ] - res[1, ] percent_change <- ((res[2, ] - res[1, ]) / res[1, ]) * 100 # combine for convenient output res <- rbind(res, difference, percent_change) # reset row numbers rownames(res) <- 1:nrow(res) # function output list( Data = res[, -1], # Data = res, # Diff = difference, # PerChange = percent_change, IsEqual = all(res[1, ] - res[2, ] == 0) ) }, simplify = FALSE) # ideally would yield number equivalent to number of bins (n=34) but only yields # 20, so 14 bins of newly-created alkey to not "align" with extant WSTALKEY # sum( # sapply(X = rows, FUN = function(x) { # lst_diff[[x]]$IsEqual # }) # ) lst_diff ``` To examine differences in the age-length keys, we ran fake data through both, and then compared the difference in frequency at age. Difference measured in direction wst_alkey - alkey from length & age data found in 1973-1976 file (n = 1222). Fake length data was randomly generated, but this is fine since we are interested in the differences and not absolute counts at age. The red line in the plot is set at y = 0, blue lines at 0.025 & -0.025. ```{r TestKeys} # mean(old_al_data$TL) # range(old_al_data$TL) # sd(old_al_data$TL) # TODO: look at rnorm instead of sample() # TODO: look at more than just rnorm - as true lf dist is # likely not normally distributed # TODO: create function to help with showing prop_diff on # varying sample size # generate fake length data; Year variable required in GetLenFreq() tl_fake <- data.frame( Year = 2016, # TL = sample(21:200, size = 100000, replace = TRUE), TL = rnorm(n = 300, mean = 97, sd = 33.1), stringsAsFactors = FALSE ) # using wst length breaks, get length frequency lf_fake <- GetLenFreq( tl_fake, colX = TL, by = "Year", breaks = wst_alkey_breaks, intBins = TRUE ) # get age frequency using the two age-length keys af_fake_1 <- GetAgeFreq(lfTable = lf_fake$Freq, alk = wst_alkey) af_fake_2 <- GetAgeFreq(lfTable = lf_fake$Freq, alk = new_old_alkey) ``` ```{r PlotTestKeys} diff_count <- unlist(af_fake_2[, -1] - af_fake_1[, -1]) prop_change <- diff_count / unlist(af_fake_1[, -1]) # plot differences as extant - newly created plot( colnames(af_fake_1[, -1]), # unlist(af_fake_1[, -1] - af_fake_2[, -1]), prop_change, # diff_count, pch = 20, xlab = "Age", ylab = "Proportional change" ) abline(h = 0, col = 2) abline(h = 0.025, col = 4, lty = 2, lwd = 0.25) abline(h = -0.025, col = 4, lty = 2, lwd = 0.25) ``` <a href="#top">back to top</a> *** Report ran: `r Sys.time()` End of report <file_sep>--- title: | | White Sturgeon Abundance Estimates | from Harvest and Harvest Rate author: "CDFW" date: '' output: pdf_document: default html_document: default github_document: default header-includes: \usepackage{float} \usepackage{caption} \captionsetup[figure]{labelformat = empty} --- ```{r setup, include=FALSE} knitr::opts_chunk$set( echo = FALSE, warning = FALSE, message = FALSE, fig.pos = 'H' ) knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics/") ``` ```{r libraries} library(ggplot2) library(knitr) # library(reshape2) ``` ```{r data} # load all .rds data from card & tagging directories # list.files(path = "data/card", pattern = ".rds$") # list.files(path = "data/tagging", pattern = ".rds$") # sourcing functions here to load data - likely will not use these functions # elsewhere in this file source(file = "source/functions_load_files.R") LoadRdsFiles(dirName = "data/card") LoadRdsFiles(dirName = "data/tagging") SlotChanges <- read.csv( file = "data/SlotChanges.csv", header = TRUE, stringsAsFactors = FALSE ) # clean up - functions for loading not needed rm(list = ls.str(mode = "function")) ``` ```{r source-files} # source(file = "source/source_stu_hr.R") source(file = "source/source_stu_mark-recap.R") source(file = "source/functions_global_general.R") source(file = "source/functions_global_record_count.R") source(file = "source/functions_global_data_subset.R") # source(file = "source/functions_cc_survival_rate.R") # source(file = "source/methods_len_freq.R") # source(file = "source/methods_age_freq.R") # source(file = "source/source_stu_cc.R") source(file = "source/source_alt_abundance.R") ``` ```{r combine-card} # this section combines the ALDS and archived (2007-2011) data card_alds <- subset( SturgeonAlds, select = -MonthF ) # adds Document (or Card) number - needed for reconciliation with tag return # data card_alds <- merge( card_alds, RetCardsAlds[, c("LicenseReportID", "DocumentNumber")], by = "LicenseReportID" ) # adding date field for rbind()ing with 07 data card_alds$DateOfCapture <- as.POSIXct( paste( card_alds$ItemYear, card_alds$Month, card_alds$Day, sep = "-" ), format = "%Y-%m-%d" ) get_alds_cols <- c( "DocumentNumber", "ItemYear", "DateOfCapture", "LocCode", "SturgeonType", "Fate", "Length", "RewardDisk", "TL_cm", "FL_cm" ) # subsetting & ordering for rbind()ing below # card_alds <- card_alds[, c(11, 3, 12, 6, 9, 10, 7, 8)] card_alds <- card_alds[, get_alds_cols] # card_arch <- subset( # Sturgeon0711#, # # select = -c(SturgeonID, CorR) # # select = -c(CorR) # ) # alias to avoid changing code below - fields SturgeonID, CorR are not in # Sturgeon0711 so subsetting is not needed (28-Apr-2017) card_arch <- Sturgeon0711 # set column names equal for rbind()ing colnames(card_arch) <- colnames(card_alds) card_all <- rbind( card_arch, card_alds ) # clean up rm(card_arch, card_alds, get_alds_cols) ``` ```{r stats} # adding year field for convenience Effort$RelYear <- as.numeric(format(Effort$RelDate, "%Y")) # rescue locations from April 2011 which we don't want for this analysis drop_locations <- c("Fremont Weir", "Tisdale Bypass") # get start, mid, and end dates dates <- ApplyFunToDf( Effort, !(Location %in% drop_locations) & RelYear > 2005, splitVars = "RelYear", FUN = TaggingDates ) # get length category stats for White Sturgeon from 2006-present (added # 05-Apr-2016 total length cutoff in keeping with IEP article "Estimating Annual # Abundance of White Sturgeon 85-116 and ≥ 169 Centimeters Total Length") lc_stats <- ApplyFunToDf( SturgeonAll, Species %in% "White" & RelYear > 2005 & TL >= 85, splitVars = "RelYear", FUN = GetLcStats ) # clean up rm(drop_locations) ``` ```{r abundance, comment=''} # calculate alternative abundance estimates for White Sturgeon from # 2007-present; output is a list so use GetAltAbundance() for cleaner display of # abundance estimates with CIs alt_abundance <- CalcAltAbundance( datHarvest = GetWstCount(datCard = card_all, dates = dates), datLcStats = lc_stats ) # for convenience - variable used within narrative max_year <- max(as.numeric(alt_abundance$Harvest$RelYear)) # tabular display of annual stats (e.g., harvest rate, tag returns) along with # abundance estimates with Wald-type CIs and log-normal based CIs stats_abund <- GetAltAbundance(dat = alt_abundance) ``` ### Background Herein are estimates of White Sturgeon abundance calculated using harvest (from Sturgeon Report Card) and harvest rate (from mark-recapture data). For more information and details regarding development of this method, please click [Abundance](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=43532). We estimate abundance directly for legal-sized White Sturgeon, which from 2007 to present is 117-168 cm TL (centimeters total length; though from 2013 to present the equivalent is measured in fork length: 102-152 cm FL). Using proportions of catch and ratios, we estimate abundance for both sub-legal and over-legal sized White Sturgeon. Note: any previous estimates have been updated using most-current (i.e., from `r Sys.Date()`) Report Card and mark-recapture data. ### Assigning Length Category We assigned White Sturgeon --- caught during our mark-recapture field work --- to a length category of either 'sub' (sub-legal), 'leg' (legal), or 'ovr' (over-legal) based on measured length (total or fork) and data in the table below. The slot limit was instituted in 1990, thus sub-legal fish are below the slot limit and over-legal fish are above the slot limit. For this purpose, we use data in the last two rows of the table below. ```{r slot} # changing Inf to NA for table display SlotChanges[1, 5] <- NA # outpout slot table for info on how LenCat was set kable( SlotChanges, format = "pandoc", align = 'c', row.names = FALSE, col.names = c( "From Year", "To Year", "Species", "Min Length (cm)", "Max Length (cm)", "Length Type" ), caption = "Table of legal-size ranges for sturgeon from 1954 to present. Note: in 2013 it became illegal to take Green Sturgeon. Species W = White & G = Green" ) # reseting to Inf SlotChanges[1, 5] <- Inf ``` For this purpose, we did not model length frequency distributions (as in [Gingras and DuBois 2015](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=114809)). Proportions and ratios were derived from non-modeled (i.e., straight) catch (see table below, where 'N' denotes count and 'P' denotes proportion). "SubToLeg" and "OvrToLeg" are ratios derived from the appropriate proportions. Also, per methodology described in [Gingras and DuBois 2015](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=114809), we limited White Sturgeon length to $\geqslant$ 85 cm TL. For example, in 2007 393 White Sturgeon were categorized as "sub," with n=34 < 85 cm TL. This yields NSub = 359. Notes: 1. NAll = NSub + NLeg + NOvr 2. NUnk = number unknown 3. Proportions (P) calculated as N(Sub or Leg or Ovr) / NAll ```{r proportions} #\u2265 = ≥ # display count and proportions table kable( lc_stats, format = "pandoc", col.names = c( "Year", "NSub", "NLeg", "NOvr", "NAll", "NUnk", "PSub", "PLeg", "POvr", "SubToLeg", "OvrToLeg" ), caption = paste0( "Count and proportion of White Stureon ", "from mark-recapture data, ", "where length limited to >= 85 cm TL" ) ) ``` ### Harvest Since 2007, anglers fishing for sturgeon in California waters are required to report catch on a Sturgeon Fishing Report Card (Card). Annually, the Card provides --- among other information --- numbers of White Sturgeon kept (or harvest, ${H}$). Per developed methodology, we count harvest for three periods (start, middle, end) based on beginning and ending dates of our field season (August-October). The rationale is to use harvest more in line with harvest rate (the estimates of which use first-year tag returns). Because we have found harvest does not vary much by period (see table below), for abundance estimates we used harvest from the 'start' period. Notes: 1. Each period has a 'from' and 'to' date (denoting one year) within which harvest is counted. 2. Harvest for 2006 not over a complete year, as Card not instituted until 2007. 3. Harvest for `r max_year` is preliminary, as data from `r max_year + 1` Card not available until early `r max_year + 2`. 4. Harvest data are in BDSturgeonReportCard database (2007-2011) & ALDS (on-line) database (2012-present) ```{r harvest} # display harvest dataframe kable( alt_abundance$Harvest, format = "pandoc", #align = 'c', row.names = FALSE, col.names = c( "Year", "Period", "From", "To", "Harvest" ), caption = "Harvest of White Sturgeon as reported on Cards from 2006-present. Harvest for 2006 included FIO and is partial, as Card not instituted until 2007.", format.args = list(big.mark = ',') ) ``` ### Harvest Rate We estimate harvest rate ($\hat{h}$) annually using angler tag returns (Ret or returns) and CDFW tag releases (Rel or releases). To minimize bias, we only use first-year tag returns (i.e., tagged fished caught within one year of release; denoted ${_f}$ in equation below). Below are harvest rate estimates for White Sturgeon legal-sized when tagged. The returns and releases presented in the table are for this demographic. Period, dates (from & to), and harvest included in table for convenience. $\hat{h} = \frac{Ret_f}{Rel}$ Notes: 1. Rate for 2006 provided for information only. 2. Rate for `r max_year` is preliminary and will change with future data (returns). 3. Returns (Ret) includes tags physically returned to us by angler and tag reported on Cards but not physically returned (Ret & Rel data are in BDSturgeonTagging database) 4. We release reward tags (current values: $50; $100; $150) but do not consider reward here (i.e., for the harvest rate estimate). See [Gingras and DuBois 2014](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=74460) for further information regarding bias in annual harvest rate estimates. ```{r harvest-rate} # display harvest rate dataframe kable( stats_abund$AnnualStats, format = "pandoc", digits = 3, #align = 'c', row.names = FALSE, col.names = c( "Year", "Period", "From", "To", "Harvest", "Ret", "Rel", "Rate" ), caption = "Harvest rate estimates of White Sturgeon legal-sized when tagged (2006-present). Note: rates for 2016 will change with further data.", format.args = list(big.mark = ',') ) ``` ### Abundance Estimates Below are (alternative) abundance estimates ($\hat{N}$) for White Sturgeon for the three length categories. Provided herewith are standard error (SE), Wald-type confidence intervals (CI), and log-normal confidence intervals (lower = LNLB, upper = LNUB). (Confidence interval algorithms provided courtesy of <NAME> & <NAME> of USFWS.) **Abundance equations** $\hat{N}_{leg} = \frac{H}{\hat{h}}$ $\hat{N}_{sub} = \hat{N}_{leg} * SubToLeg$ $\hat{N}_{ovr} = \hat{N}_{leg} * OvrToLeg$ **Standard error and variance** ${SE}({\hat{N}_{leg}}) = \frac{H}{\sqrt{\hat{h}^{3} * {Rel}}}$ ${VAR}({\hat{N}_{leg}}) = {SE}({\hat{N}_{leg}})^2$ ${SE}({\hat{N}_{sub}}) = \sqrt{{VAR}({\hat{N}_{leg}}) * SubToLeg}$ ${SE}({\hat{N}_{ovr}}) = \sqrt{{VAR}({\hat{N}_{leg}}) * OvrToLeg}$ **Wald-type confidence interval (CI)** ${CI}(\hat{N}) = {\pm}{Z} * {SE}(\hat{N})$ **Log-normal confidence intervals (lower & upper bounds)** ${LNLB}(\hat{N}) = \hat{N} * exp({-Z} * {\frac{SE(\hat{N})}{\hat{N}}})$ ${LNUB}(\hat{N}) = \hat{N} * exp({Z} * {\frac{SE(\hat{N})}{\hat{N}}})$ ```{r abundance-tabular} # for display purpose in table below stats_abund$Abundance$Year <- as.character(stats_abund$Abundance$Year) # display abundance estimates kable( stats_abund$Abundance, format = "pandoc", digits = 0, #align = 'c', row.names = FALSE, col.names = c( "Year", "Category", "N", "SE", "CI", "LNLB", "LNUB" ), caption = "Annual White Sturgeon abundance estimates by size category", format.args = list(big.mark = ',') ) # resetting numeric for plotting stats_abund$Abundance$Year <- as.numeric(stats_abund$Abundance$Year) ``` \pagebreak Plot of abundance estimates with log-normal confidence intervals. Note: estimates for `r max(stats_abund$Abundance$Year)` available ~`r max(stats_abund$Abundance$Year) + 2`. ```{r graphics, fig.height=7, fig.width=5, fig.align='center', fig.cap="White Sturgeon abundance estimates from harvest and harvest rate with log-normal confidence intervals; note: separate y-axis for each category"} stats_abund$Abundance$LenCat <- factor( stats_abund$Abundance$LenCat, levels = c(sub = "sub", leg = "leg", ovr = "ovr") ) year_range <- range(stats_abund$Abundance$Year) # possilbe plotting option (change data source) plt <- ggplot( data = stats_abund$Abundance[stats_abund$Abundance$Year < year_range[2], ], mapping = aes(x = as.character(Year), y = N) ) plt + geom_bar(stat = "identity", fill = "black") + #facet_wrap(facets = ~LenCat, scales = "free_y", ncol = 1) facet_grid(facets = LenCat ~ ., scales = "free_y") + geom_errorbar( mapping = aes(ymax = LNUB, ymin = LNLB), colour = "steelblue", size = 0.5, width = 0.1 ) + scale_y_continuous( name = "Abundance (x 1000)", #name = quote(Abundance * 10^3), labels = function(x) x / 1000, expand = c(0.02, 0) ) + xlab("Year") # scale_y_continuous( # minor_breaks = 5, # labels = function(x) x / 1000 # ) + #ylab("Abundance (x 1000)") ``` *** Report ran: `r Sys.time()` End of report<file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set( root.dir = "~/RProjects/SturgeonPopMetrics/", global.par = FALSE ) # fig.align needed for fig label to appear in `markdown` knitr::opts_chunk$set(echo = FALSE, fig.align = "left") ``` <!-- chunks for data loading, data clean up, & global variables --> ```{r data-log-date} data_log <- readLines("data/card/data-log")[1] ptrn <- "\\d{4}\\-\\d{2}\\-\\d{2}\\s{1}\\d{2}\\:\\d{2}\\:\\d{2}" dte <- gregexpr(pattern = ptrn, text = data_log) srt <- dte[[1]][1] stp <- attr(dte[[1]], which = "match.length") dte <- substr(data_log, start = srt, stop = srt + (stp - 1)) # clean up rm(srt, stp, data_log, ptrn) ``` ```{r load-libraries} # `sportfish` currently available on GitHub library(sportfish) # library(package) ``` ```{r global-par} # source(file = "presentations/.base-par.R") ``` ```{r load-data, results='hide'} # load all `.rds` files from directory `data/card`; to keep the workspace clean # load these files into a new environment called `Card` # the data directory for bay study data_dir <- "data/card" # list.files(path = data_dir, pattern = ".rds") Card <- new.env() ReadRDSFiles(fileDir = data_dir, envir = Card) # clean up rm(data_dir) ``` ```{r variables} # variables created here for use throughout file # boolean for extracting within data green sturgeon records only b_gst <- Card[["AnglerCatch"]][["Species"]] %in% "Green" # for narrative or analytics when needed years <- unique(Card[["AnglerCatch"]][["Year"]]) # to display tables for current Card year only current_card_year <- 2019 # for narrative when referrencing current calendar year current_year <- as.numeric(format(Sys.Date(), format = "%Y")) # list to loop through desired species-fate groupings lst_stu <- list( GST = c("Green", ""), WSTk = c("White", "kept"), WSTr = c("White", "released") ) # for use in annual analytics by location codes loc_lvls <- names(table(Card[["AnglerCatch"]][["LocCode"]])) # for proper identification of angler-reported reward tag Card[["AnglerCatch"]]$CheckTag <- t(vapply( Card[["AnglerCatch"]][["RewardDisk"]], FUN = CheckCardTag, FUN.VALUE = character(2L) )) # for consistency & clean output dimnames(Card[["AnglerCatch"]][["CheckTag"]])[[1]] <- seq_len(length.out = nrow(Card[["AnglerCatch"]])) ``` ```{r gst-kept, eval=FALSE, message=FALSE} # In 2009, one angler (perhaps erroneously) reported keeping a Green Sturgeon. # For simplicity, we'll set fate to blank (i.e., empty character as "") for all # Green Sturgeon. i_gst_kept <- with(data = Card[["AnglerCatch"]], expr = { which(Fate %in% "kept" & Species %in% "Green") }) g_cols <- c("Year", "CaptureDate", "LocCode", "Species", "Fate", "FL_cm") knitr::kable( Card[["AnglerCatch"]][i_gst_kept, g_cols], format = "pandoc", row.names = FALSE ) # clean up rm(g_cols) ``` ```{r gst-remove-fate, results='hide'} Card[["AnglerCatch"]][["Fate"]][b_gst] <- "" # clean up # rm(b_gst, i_gst_kept) rm(b_gst) ``` <!-- include child files --> ```{r _1summary, child="annual_card_files/_1summary.Rmd"} ``` ```{r _2catch, child="annual_card_files/_2catch.Rmd"} ``` ```{r _3catch-angler, child="annual_card_files/_3catch-angler.Rmd"} ``` ```{r _4catch-season, child="annual_card_files/_4catch-season.Rmd", warning=FALSE} ``` <!-- caption automation here --> ```{r caption-periods} # to get year ranges for table & figure captions pd_cs <- paste0(range(card_summary[["Year"]]), collapse = "-") pd_ct <- paste0(range(catch[["Year"]]), collapse = "-") pd_ca <- paste0(range(catch_angler_year[["Year"]]), collapse = "-") pd_tabs <- c(pd_cs, pd_ct, rep(pd_ca, times = 2), rep(pd_ct, times = 4)) ``` ```{r captions} # to create figure & table captions FigCap <- Caption(label = "Figure", sep = ".") TabCap <- Caption(label = "Table", sep = ".") caps <- ReadCaptionFile(file = "fishery/annual_card_files/captions") caps_names <- names(caps) ntabs <- sum(grepl(pattern = "^table", x = caps_names)) nfigs <- sum(grepl(pattern = "^figure", x = caps_names)) # for ease of use within narrative fcn <- FigCap$Num tcn <- TabCap$Num figures <- Map(f = function(nm, i, p) { nm <- paste0(nm, i) substitute( expr = FigCap$Show(cap = a, period = pd), env = list(a = caps[[nm]], pd = p) ) }, nm = "figure", i = seq_len(nfigs), p = pd_ct) tables <- Map(f = function(nm, i, p) { nm <- paste0(nm, i) substitute( expr = TabCap$Show(cap = a, period = pd), env = list(a = caps[[nm]], pd = p) ) }, nm = "table", i = seq_len(ntabs), p = pd_tabs) # section clean up rm(caps, caps_names, ntabs, nfigs) ``` <!-- begin narrative below --> ## Introduction Herein provides a summary of California Sturgeon Report Card (Card) data. Since 2007, the Card has been required of any angler fishing for sturgeon. It is part of a suite of sport fishing regulations intended to protect California’s year-round White Sturgeon fishery while increasing protections for the federally-threatened Green Sturgeon population and adding resiliency to the conservation-dependent White Sturgeon population. Card data are complementary to on-going research and monitoring conducted by the California Department of Fish and Wildlife (CDFW) and other entities. The Card includes fields for angler contact information (pre-printed), retained White Sturgeon, and released sturgeon. To aid CDFW’s efforts to reduce illegal commercialization of sturgeon and to enforce the daily and annual bag limits on White Sturgeon, each Card also includes detachable single-use serially numbered Card-specific tags to be placed on retained White Sturgeon. Anglers must record the day, month, and location for any sturgeon they catch and keep or catch and release. Anglers also must record sturgeon length if kept. Though not required, many anglers record length for sturgeon released. A 'Reward Disk' field is available should the angler catch a sturgeon with a CDFW-affixed disc tag. **NOTES** (1) Card data are not static, and summaries may change as new data become available. The current summary year (typically one year behind current calendar year) is most affected by this. This summary report is updated periodically as new data are collected. The most recent data extraction was `r format(as.POSIXct(dte), format = "%d-%b-%Y @ %H:%M")`. (2) Reporting for current valid Card (year `r current_year`) is not due until 31-Jan-`r current_year + 1`. Consider this when viewing any summary herein for `r current_year`. (3) From 2007-2017, CDFW produced single-year Card summary reports. These reports are available at https://wildlife.ca.gov/Conservation/Delta/Sturgeon-Study/Bibliography, find title *'YYYY' Sturgeon Fishing Report Card: Preliminary Data Report*, though updated annual summaries are found herein. The CDFW's Sportfish Unit will no longer produce single-year summaries. (4) The Card was first made available 01-Mar-2007. Some anglers reported data for Jan 2007 & Feb 2007; however, catch data are a bit 'thin' for this period compared to the norm. Keep this in mind when interpreting summaries herein. (5) Card location descriptions as written are long. For conciseness, locations *codes* are displayed in figures and tables herein. For reference, please see table in section 'Card Location Codes and Descriptions.' (6) 'disk' or 'disc' are used interchangeably when referring to the external tag CDFW affixes to White Sturgeon. The Card uses 'disk'. *CDFW contact*: [<NAME>](mailto:<EMAIL>) ## Distribution and Return The Card has been distributed through the Automated License Data System (ALDS) since 2012. From 2007 through 2012, the Card was issued free of charge. A fee of ~\$8 was set in 2013. Initially, Cards were categorized as catch or no catch, but in 2010 a 'did not fish' check box was included (Table `r tcn()`). The ALDS affords anglers on-line reporting. There has been a steady increase of anglers making use of such accommodation (Table `r tcn()`, see 'IS' or Internet submission). Further, there has been an increase overall in reporting ('ReportingRate'), though it seems to have reached a plateau (Table `r tcn()`; ~`r max(card_summary[["ReturnRate"]]) %/% 1`%). Table `r tcn()` field names explained below for reference. - left-most column: calendar year for which Card was issued (sold) - **Issued**: number of Cards issued (or sold post 2012) - **NoEffort**: number of anglers reporting 'did not fish' (available from 2010) - **NoCatch**: number of anglers reporting 'fished, no catch' - **Catch**: number of anglers reporting catching one or more sturgeon - **ReturnRate**: sum of NoEffort, NoCatch, Catch divided by Issued - **NotReturned**: number of Cards not returned - **CC**: Control Center - Card entered by CDFW staff - **IS**: Internet Submission - Card entered (reported) on-line by angler *`r eval(tables[[1]])`* ```{r disp-card-summary} br <- card_summary[["Year"]] <= current_card_year # bc <- !(colnames(card_summary) %in% "CatchAlds") bc <- !(colnames(card_summary) %in% c("Year", "CatchAlds")) row.names(card_summary) <- card_summary[["Year"]] # removed br to show current calendar year (17-Apr-2020) knitr::kable( # card_summary[br, bc], card_summary[, bc], format = "pandoc", digits = 2, row.names = TRUE, format.args = list(big.mark = ",") ) # chunk clean up rm(br, bc) ``` ## Reported Catch ```{r wst-catch-avg-narrative} # TODO: put safegaurd in here for current calendar year catch that may not be # complete & could greatly lower the average; same with GST too (22-Apr-2020) catch_nar <- (rowMeans(vapply(catch[["WST"]], FUN = function(d) { d[, "Tot"] }, FUN.VALUE = numeric(2L))) %/% 100) * 100 catch_nar <- format(catch_nar, big.mark = ",") ``` Anglers must report sturgeon catch, whether kept or released. Anglers may keep only White Sturgeon, with bag limits of one daily and three annually. On average, each year anglers keep about `r catch_nar[["kept"]]` White Sturgeon (Figure `r fcn()`). Anglers catch and release an annual average of about `r catch_nar[["released"]]` White Sturgeon (Figure `r fcn()`). ```{r plot-wst-catch} # plotting WST catch: uses `catch` dataframe # to set plot margins for desired display par( oma = c(1, 1, 0.5, 0.25), mar = c(1.5, 1.5, 1.25, 0.25)#, # mgp = c(2.5, 0.6, 0), # cex.axis = 1.0, # cex.lab = 1.5, # tcl = -0.3 ) # to set max y-value for plot limits max_catch_year <- vapply( catch[["WST"]], FUN = function(d) max(d[, "Tot"]), FUN.VALUE = numeric(1L) ) # empty plot based on total WST catch for all years p_catch <- Plot(x = range(years), y = c(0, max(max_catch_year))) p_catch$grid(xRng = TRUE) # add bars to plot p_catch_bars <- Map(f = function(d, y) { # for dodging (offsetting) kept & released off <- 0.18 # total WST kept points( x = y - off, y = d["kept", "Tot"], type = "h", col = "orange2", lwd = 15, lend = 1 ) # total WST released points( x = y + off, y = d["released", "Tot"], type = "h", col = "steelblue", lwd = 15, lend = 1 ) # X marking number released WST measured points( x = y + off, y = d["released", "Meas"], col = "grey20", pch = 4, cex = 0.75 ) }, catch[["WST"]], catch[["Year"]]) # end Map # to display axes ticks & labels Axis(p_catch, side = 1, cexAxis = 1, labelAdj = 0.3, interval = 2) yax <- Axis(p_catch, side = 2, cexAxis = 1, labelAdj = 0.3, format = TRUE) mtext(text = "Year", side = 1, line = 1.2, cex = 1) mtext(text = yax$AxisTitle(var = "Count"), side = 2, line = 1.2, cex = 1) # just to include note on plot's bottom right corner mtext( text = "(x notes number measured)", side = 1, line = 1.1, cex = 0.75, adj = 0.9, col = "grey30", font = 3 ) # to inform viewer about colored bars legend( x = p_catch[["xrng"]][[2]], y = p_catch[["yrng"]][[2]] * 1.13, legend = c("kept", "released"), fill = c("orange2", "steelblue"), xjust = 1, xpd = TRUE, border = NA, bty = "n", ncol = 2 ) # chunk clean up rm(yax, p_catch_bars, max_catch_year) ``` *`r eval(figures[[1]])`* ```{r gst-catch-avg-narrative} # see TODO in `wst-catch-avg-narrative` catch_gst_nar <- (mean(catch[["GST"]][,"Tot"]) %/% 10) * 10 ``` Green Sturgeon are bycatch in the White Sturgeon fishery. Anglers may not keep a Green Sturgeon and annually release on average about `r catch_gst_nar` (Figure `r fcn()`). ```{r plot-gst-catch} # to set plot margins for desired display par( oma = c(1, 1, 0.25, 0.25), mar = c(1.5, 1.5, 0.25, 0.25)#, # mgp = c(2.5, 0.6, 0), # cex.axis = 1.0, # cex.lab = 1.5, # tcl = -0.3 ) p_gst <- Plot(x = catch[["Year"]], y = catch[["GST"]][, "Tot"], y0 = TRUE) points(p_gst, type = "h", lwd = 30, col = "steelblue", xRng = TRUE) # X marking number released WST measured points( x = p_gst$data()[["x"]], y = catch[["GST"]][, "Meas"], col = "grey20", pch = 4, cex = 0.75 ) # to display axes ticks & labels Axis(p_gst, side = 1, cexAxis = 1, labelAdj = 0.3, interval = 2) yax <- Axis(p_gst, side = 2, cexAxis = 1, labelAdj = 0.3, format = TRUE) mtext(text = "Year", side = 1, line = 1.2, cex = 1) mtext(text = yax$AxisTitle(var = "Count"), side = 2, line = 1.3, cex = 1) # just to include note on plot's bottom right corner mtext( text = "(x notes number measured)", side = 1, line = 1.1, cex = 0.75, adj = 0.9, col = "grey30", font = 3 ) # chunk clean up rm(yax) ``` *`r eval(figures[[2]])`* The Card provides species check boxes (White or Green) for fish released with no reward disk present. No such check boxes exist for fish released with reward disk present, given a correctly recorded disk tag number provides trace back to CDFW release data. Annually, on average, about `r mean(catch[["Unk"]]) %/% 1` sturgeon cannot be identified to species given the available information. ```{r disp-unk, eval=FALSE} # maybe, but might just work into narrative somehow catch[c("Year", "Unk")] ``` ## Catch per Angler Roughly &frac23; to &frac34; of anglers who report catching sturgeon catch only 1 or 2 White Sturgeon per year (includes both kept and released; Table `r tcn()`). Few anglers (<4%) catch 15 or more, and each year at least one angler reports catching many White Sturgeon (Table `r tcn()`, field 'Max'). *`r eval(tables[[2]])`* ```{r disp-catch-per-angler} # chunk displays WST catch per angler, where catch has been binned by 2 (e.g., # 1-2 represents anglers who caught 1-2 WST [either kept or released]) # Max = MaxPerSingleAngler col_names <- c(dimnames(catch[["PerAnglerBinned"]])[[2]], "Max") # call to data.frame needed to ensure proper formatting knitr::kable( data.frame( # catch[["PerAnglerBinned"]], prop.table(catch[["PerAnglerBinned"]], margin = 1), catch[["MaxWSTPerAngler"]] ), format = "markdown", digits = 2, row.names = TRUE, col.names = col_names ) # chunk clean up rm(col_names) ``` #### 2013-present In the ALDS-era and post-2012, Card reporting has consistently offered three categories: did not fish; fished no catch; and fished (& caught). This facilitates analyzing catch for the angling population expending effort (i.e., to not include 'did not fish' anglers). ```{r gst-frac-anglers-narratvie} # for average, sets to 1000 number of reporting anglers; this avoid including # values where very few anglers have reported # TODO: decided whether or not 1000 anglers is a good limit, then maybe # implement for entire doc n_anglers <- 1000L b <- catch_angler_year[["GST"]][, "Anglers"] >= n_anglers avg <- mean(catch_angler_year[["GST"]][b, "Frac"]) gst_frac_narrative <- sprintf(fmt = "%.1f%% (%.3f)", avg * 100, avg) # section clean up rm(b, avg) ``` Annually, on average about `r gst_frac_narrative` of anglers (n &ge; `r n_anglers` reporting) who fish catch and release at least one Green Sturgeon (Table `r tcn()`). Some anglers do catch and release more than one Green Sturgeon annually (Table `r tcn()`, see 'Max' field). *`r eval(tables[[3]])`* ```{r disp-gst-2013_now} # Anglers = number who reported & who went fishing # AngGST = number anglers who caught a GST # Count = total # GST caught per year # MaxAngler = max # GST per single angler # Frac = fraction of anglers reporting having fished who caught a GST # (includes those who got skunked but not those who did not fish) # DNF = did not fish # catch_angler_year[["GST"]] knitr::kable( # catch_angler_year[["GST"]][, c("Anglers", "Frac", "MaxAngler")], catch_angler_year[["GST"]][, c("AngGST", "Frac", "MaxAngler")], format = "markdown", digits = 4, row.names = TRUE, format.args = list(big.mark = ","), col.names = c("Anglers", "Fraction", "Max") ) ``` ```{r wst-frac-anglers-narratvie} n_anglers <- 1000L b <- catch_angler_year[["ReportWSTk"]][, "Anglers"] >= n_anglers avg <- mean(catch_angler_year[["ReportWSTk"]][b, "1"]) wst_frac_narrative <- sprintf(fmt = "%.0f%% (%.2f)", avg * 100, avg) wst_dnf_narrative <- range(catch_angler_year[["ReportWSTk"]][b, 6]) * 100 # wst_dnf_narrative %/% 0.01 wst_dnf_narrative <- sprintf( fmt = "%.0f%%-%.0f%%", wst_dnf_narrative[[1]], wst_dnf_narrative[[2]] ) # section clean up rm(b, avg) ``` Of reporting anglers (n &ge; `r n_anglers`, including 'did not fish'), about `r wst_frac_narrative` on average keep one White Sturgeon. Fewer still keep the limit of three (Table `r tcn()`). Roughly `r wst_dnf_narrative` anglers reported 'did not fish.' *`r eval(tables[[4]])`* ```{r disp-wstk-frac-anglers} # catch_angler_year[["ReportWSTk"]] knitr::kable( catch_angler_year[["ReportWSTk"]], #* 100, format = "markdown", digits = 4, row.names = TRUE, format.args = list(big.mark = ","), col.names = c( "Anglers", "None", "Kept-1", "Kept-2", "Kept-3", "NoEffort" ) ) ``` ```{r cnr-narrative} n_anglers <- 1000L b <- catch_angler_year[["CatchRelease"]][, "Anglers"] >= n_anglers cnr_frac <- range(catch_angler_year[["CatchRelease"]][b, "Frac"]) cnr_narrative <- sprintf( fmt = "%.1f%% and %.1f%%", cnr_frac[[1]] * 100, cnr_frac[[2]] * 100 ) cnr_yr_narrative <- paste0( range(catch_angler_year[b, "Year"]), collapse = "-" ) # section cleanup rm(cnr_frac, b) ``` To derive the number of anglers who actively practice catch-n-release only is not possible given available data. However, of the reporting anglers who fished, between `r cnr_narrative` released sturgeon yet retained none (`r cnr_yr_narrative`, years with &ge; `r n_anglers` reporting). ```{r plot-mosaic, eval=FALSE} # a possibiliy for displaying this kind of info might be more informative than # the table above (13-Apr-2020) plot(catch_angler_year[["WSTkept"]][["2019"]]) ``` ## Length Anglers must report length for White Sturgeon kept. Anglers are not required to report length of released fish, but some do, typically in the species check box. Anglers report inches, as required by regulations, and herein lengths were converted to centimeters fork length (FL). Occasionally, an angler will report a suspiciously small length (i.e., &le; 10). Likely, here the angler is using short hand for catch (i.e., number caught). So, any "length" &le; 10 is flagged and set to `NA` for analytical purposes (Table `r tcn()`). *`r eval(tables[[5]])`* ```{r disp-length-check} knitr::kable(catch[["LenCheck"]], format = "markdown") ``` #### Green Sturgeon Of the reported valid lengths, most Green Sturgeon are less than 100 cm (~40 inches; Figure `r fcn()`). The orange box represents the interquartile range (25%-75%). ```{r plot-gst-len} par( oma = c(0.5, 0.5, 0.25, 0.25), mar = c(2, 2.5, 0.25, 0.25) ) p_gst_len <- Plot( data = Card[["AnglerCatch"]], x = Year, y = FL_cm, subset = Species %in% "Green" ) p_gst_len$grid(xRng = TRUE) points( formula = y ~ jitter(x), data = p_gst_len$data(), pch = 1, col = rgb(red = 0, green = 0, blue = 0, alpha = 0.5) ) rect( xleft = catch[["Year"]] - 0.25, ybottom = catch[["GSTLenQuant"]][, "p25"], xright = catch[["Year"]] + 0.25, ytop = catch[["GSTLenQuant"]][, "p75"], col = "transparent", # density = NA, border = "orange2", lwd = 2 ) Axis(p_gst_len, side = 1, labelAdj = 0.3, interval = 2) Axis(p_gst_len, side = 2, labelAdj = 0.4) mtext(text = "Year", side = 1, line = 1.3) mtext(text = "Fork length (cm)", side = 2, line = 2) ``` *`r eval(figures[[3]])`* #### White Sturgeon (released) Length distributions indicate annual median values below 102 cm FL, the lower bound for the slot (Figure `r fcn()`, see 'x' on figure). From 2013-2019, it appears anglers were catching more sub-slot sized fish, measuring more sub-slot sized fish, or a combination of both (Figure `r fcn()`, see progressively darker points below the slot). Anglers released White Sturgeon that could have been retained. ```{r plot-wstr-len} par( oma = c(0.5, 0.75, 0.25, 0.25), mar = c(2, 2.75, 0.25, 0.25) ) p_wstr_len <- Plot( data = Card[["AnglerCatch"]], x = Year, y = FL_cm, subset = Species %in% "White" & Fate %in% "released" ) p_wstr_len$grid(xRng = TRUE) rect( xleft = min(catch[["Year"]]) - 0.3, ybottom = 102, xright = max(catch[["Year"]]) + 0.3, ytop = 152, col = "transparent", lwd = 2, # density = NA, # border = rgb(red = 0, green = 0, blue = 0.9, alpha = 0.2)#, border = "steelblue4" ) points( formula = y ~ jitter(x), data = p_wstr_len$data(), pch = 1, cex = 0.5, col = rgb(red = 0, green = 0, blue = 0, alpha = 0.1) # col = grey(level = 0.5, 0.2) ) rect( xleft = catch[["Year"]] - 0.25, ybottom = catch[["WSTrLenQuant"]][, "p25"], xright = catch[["Year"]] + 0.25, ytop = catch[["WSTrLenQuant"]][, "p75"], col = "transparent", # density = NA, border = "orange2", lwd = 2 ) # to display median as 'x' points( x = catch[["Year"]], y = catch[["WSTrLenQuant"]][, "p50"], pch = 4, lwd = 2, col = "orange2" ) Axis(p_gst_len, side = 1, labelAdj = 0.3, interval = 2) Axis(p_gst_len, side = 2, labelAdj = 0.4) mtext(text = "Year", side = 1, line = 1.3) mtext(text = "Fork length (cm)", side = 2, line = 2.1) ``` *`r eval(figures[[4]])`* #### White Sturgeon (kept) Length quartiles 25%, 50%, and 75% show in certain years anglers harvested more fish closer in length to the upper slot limit and other years more fish closer in length to the low slot limit (Figure `r fcn()`). This might indicate a year class (or classes) growing into and out of the slot limit (102-152 cm FL or 40-60 in FL). ```{r plot-wstk-len-med} # 14-Apr-2020: will go with percentile plot here to show median & 25% + 75%; # increase in median length then a decrease par( oma = c(0.5, 0.75, 0.25, 0.25), mar = c(2, 2.75, 0.25, 0.25) ) p_wstk_len <- Plot( x = range(catch[["Year"]]), y = range(catch[["WSTkLenQuant"]]) ) p_wstk_len$grid(xRng = TRUE) rect( xleft = catch[["Year"]] - 0.25, ybottom = catch[["WSTkLenQuant"]][, "p25"], xright = catch[["Year"]] + 0.25, ytop = catch[["WSTkLenQuant"]][, "p75"], col = "transparent", # density = NA, border = "orange2", lwd = 2 ) points( x = catch[["Year"]], y = catch[["WSTkLenQuant"]][, "p50"], pch = 4, lwd = 2, col = "orange2" ) Axis(p_wstk_len, side = 1, labelAdj = 0.3, interval = 2) Axis(p_wstk_len, side = 2, labelAdj = 0.4) mtext(text = "Year", side = 1, line = 1.3) mtext(text = "Fork length (cm)", side = 2, line = 2.1) ``` *`r eval(figures[[5]])`* ```{r plot-len-wstk-mean, eval=FALSE} # possible plot below but likely going with box plot above - might be easier to # explain & may be a bit more informative than mean +/- SD (14-Apr-2020) p_wstk_len <- Plot( x = catch[["Year"]], y = catch[["WSTkLenStats"]][, "Avg"], yerr = sqrt(catch[["WSTkLenStats"]][, "Var"]), adjUsr = 0.5 ) p_wstk_len$grid(xRng = TRUE) lines(p_wstk_len, col = "grey25", lwd = 1.5) points( p_wstk_len, cex = 1.25, col = "white", pch = 21, bg = "grey25", grid = FALSE ) points( x = p_wstk_len$data()[["x"]], y = catch[["WSTkLenStats"]][, "Med"], pch = 4, lwd = 2, col = "orange2" ) ``` ```{r len-freq-old, eval=FALSE, warning=FALSE} # plot(Frequency(Card$AnglerCatch$FL_cm, binWidth = 5)) # test <- aggregate( # formula = FL_cm ~ Year + Species + Fate, # data = Card[["AnglerCatch"]], # # FUN = function(x) unlist(Frequency(x, binWidth = 5)), # FUN = Frequency, # binWidth = 5, # subset = !(Species %in% "Unk") # ) # # test <- lapply( # split(Card$AnglerCatch$FL_cm, f = Card$AnglerCatch$Year), # FUN = Frequency, # binWidth = 5 # ) # loop through lf for species+fate combo freq_stu <- vapply(lst_stu, FUN = function(x) { d <- subset( Card[["AnglerCatch"]], subset = Species %in% x[1] & Fate %in% x[2] ) # not in love with this but for now it'll work, 'kept' has fish will beyond # the legal ranges, so this is an attempt to scale to within (somewhat) of # legal range so plot is not full of white space left & right of bars if (x[2] %in% "kept") d <- subset(d, subset = FL_cm >= 100 & FL_cm <= 155) xrng <- range(d[["FL_cm"]], na.rm = TRUE) s <- split(d[["FL_cm"]], f = d[["Year"]]) lapply(s, FUN = Frequency, binWidth = 5, xRange = xrng) }, FUN.VALUE = as.list(years)) # combine output with years for ease of other analytics & plotting freq <- data.frame(Year = years, freq_stu[, names(lst_stu)]) # clean up rm(freq_stu) ``` ```{r plot-len_freq, eval=FALSE, fig.height=8, fig.width=6} # could delete after 09-Apr-2020 # TODO: # (1) "un-hardcode" creation of layout matrix # (2) use `wstk_lf_plots` output in creation of y-axis title # (3) use `max_den` as arg to Map function paramter, not inside function # establish matrix for plot layout # using data to create matrix; will always have 3 columns clms <- 3L rows <- ceiling(nrow(freq) / clms) mat_data <- (1:nrow(freq))[1:(rows * clms)] # layout cannot have NA values mat_data[is.na(mat_data)] <- 0 # creat the layout for plotting mat_layout <- matrix(data = mat_data, nrow = rows, ncol = clms, byrow = TRUE) nf <- layout(mat = mat_layout) # to put x-axis ticks on bottom three plots max_mat_layout <- sort(mat_layout, decreasing = TRUE)[clms:1] # remove 0s (if any) for proper sorting in next steps mat_layout[mat_layout == 0] <- NA_integer_ # uncomment to show layout as grid with number in each cell # layout.show(nf) # for adding ticks & tick labels to appropriate plots in trellis layout ytl <- sort(mat_layout) %in% mat_layout[, 1] # xtl <- sort(mat_layout) %in% mat_layout[nrow(mat_layout), ] xtl <- sort(mat_layout) %in% max_mat_layout # for consistent y-axis limits between years max_den <- vapply(freq[["WSTk"]], FUN = function(x) { max(x[["density"]]) }, FUN.VALUE = numeric(1L), USE.NAMES = FALSE) # for keeping bottom & left spaces to display axes title par(oma = c(4, 5, 1, 1), cex.axis = 1.5, family = "sans") # use `freq` to create annaul plots & arrange 3 x 4 wstk_lf_plots <- Map(function(fd, lbl, x, y) { par(mar = c(0.1, 0.5, 1.5, 0.1), mgp = c(1, 0.5, 0)) plot( fd, med = TRUE, xTL = x, yTL = y, xTitle = FALSE, yTitle = FALSE, addN = FALSE, maxY = max(max_den) ) mtext( text = bquote(n == .(fd$xstats()[["N"]]) ~ " | " ~ .(lbl)), side = 3, # cex = 0.75, adj = 0, family = "sans", # for Arial ps = 10 ) # output goes here }, freq[["WSTk"]], names(freq[["WSTk"]]), xtl, ytl) # reset for adding axes title below layout(mat = 1) # y-axis title mtext( text = expression(paste("Density x ", 10^-2)), side = 2, # adj = 0.5, # padj = 0.25, line = 3, las = 3 ) # x-axis title mtext(text = "Length bins (cm FL)", side = 1, line = 2.5, las = 1) ``` ```{r plots-wstk, eval=FALSE} # possible plot ideas boxplot( formula = FL_cm ~ Year, data = Card$AnglerCatch, subset = Species %in% "White" & Fate %in% "kept" & FL_cm %in% 90:160 ) ``` ## Catch by Location & Month Card data make possible some spatial and temporal analyses. Though spatially the data are coarse, limited to larger geographic sections and not specific way-points. This section explores such analytics for all White Sturgeon (kept & released). #### Location: Ranking Top 5 for White Sturgeon Suisun Bay (code 18) consistently yields the greatest fraction of White Sturgeon catch, 2008 excepted (Table `r tcn()`; 20%-40%). In fact, Suisun Bay is typically 5+ points higher than the second-ranked location. Sacramento River: Rio Vista to Chipps Island (code 04) is also a top spot for White Sturgeon catch (Table `r tcn()`). *`r eval(tables[[6]])`* ```{r disp-loc-top5} knitr::kable( catch[["LocWSTTop5"]], format = "markdown", row.names = TRUE, col.names = c( "First", "Second", "Third", "Fourth", "Fifth" ) ) ``` #### Month: White Sturgeon Though the White Sturgeon fishery is open year-round, there appears to be a natural seasonality (Table `r tcn()`). Catch as a fraction of total caught is lowest late spring through summer (Table `r tcn()`). Unlike location, no single month stands out as exceptional; winter and spring months hover around 15%. *`r eval(tables[[7]])`* ```{r disp-catch-wst-mon} # numbers are percent of total WST catch knitr::kable( t(vapply(catch[["PerMonth"]], FUN = function(d) { r <- prop.table(d[2:13, "White"]) * 100 names(r) <- month.abb r }, FUN.VALUE = numeric(12L))), format = "markdown", digits = 1, row.names = TRUE ) ``` ```{r wst-all-months-all-years} wst_all_months <- Reduce(f = intersect, x = catch[["LocsYrRndWST"]]) wst_all_months_loc_nums <- which(loc_lvls %in% wst_all_months) wst_all_months_narrative <- paste0( sprintf(fmt = "%s(%s)", wst_all_months, wst_all_months_loc_nums), collapse = "; " ) ``` ```{r wst-max-catch-loc-month-narrative} i <- which.max(catch[["WSTMonthLocMax"]][["Freq"]]) wst_max_catch_loc_month_narrative <- sprintf( fmt = "%s %s at location %s(%s), n=%s", month.abb[as.numeric(catch[["WSTMonthLocMax"]][i, "Month"])], dimnames(catch[["WSTMonthLocMax"]])[[1]][i], catch[["WSTMonthLocMax"]][i, "LocCode"], catch[["WSTMonthLocMax"]][i, "LocNum"], catch[["WSTMonthLocMax"]][i, "Freq"] ) # section clean up rm(i) ``` Anglers have reported catching one or more White Sturgeon each month every year for the following locations: `r wst_all_months_narrative` (Figure `r fcn()`; y-axis is number in parentheses - see section *Card Location Code* for y-axis number & corresponding Card code). To date, the highest White Sturgeon catch was observed `r wst_max_catch_loc_month_narrative`. ```{r plot-wst-loc-month, fig.width=6, fig.asp=1.5} # for proper ordering of plots & layout; a `0` does not plot so `n + 1` will be # the last plot n <- length(catch[["Year"]]) ncols <- 3 nrows <- ceiling(n / ncols) lvls <- seq_len(ncols * nrows) lvls[lvls > n] <- 0 mat <- matrix(data = lvls, nrow = nrows, ncol = ncols, byrow = TRUE) par(oma = c(3, 3, 0.5, 0.75)) lo <- layout(mat = rbind(n + 1, mat), heights = c(0.5, 1)) # layout.show(n = lo) p_wst_loc_month <- Map(f = function(d, y) { par(mar = c(0.25, 0.25, 1, 0.25)) p <- Plot( x = range(d[["X"]]), y = range(d[["Y"]]), adjUsr = 1 ) rect( xleft = d[["X"]] - 0.5, ybottom = d[["Y"]] - 0.5 , xright = d[["X"]] + 0.5, ytop = d[["Y"]] + 0.5, col = d[["clrs"]], border = NA ) # p$usr if (y %% 3 == 0) { par(mgp = c(3, 0.4, 0)) tk <- unique(d[["Y"]]) axis( side = 2, at = tk, labels = NA, tcl = -0.1, col = "transparent", col.ticks = "grey50", col.axis = "grey50" ) axis( side = 2, at = tk[tk %% 5 == 0], labels = tk[tk %% 5 == 0], tcl = -0.3, col = "transparent", col.ticks = "grey50", col.axis = "grey50", las = 1 ) # Axis(p, side = 2, labelAdj = 0.4, interval = 2) } axis( side = 1, at = unique(d[["X"]]), labels = NA, tcl = -0.1, col = "transparent", col.ticks = "grey50", col.axis = "grey50" ) # note: using this approach works for now but as current calendar year data # come online this may not produce the desired results (17-Apr-2020) if (y >= (current_card_year - 2)) Axis(p, side = 1, labelAdj = 0.3) mtext( text = y, side = 3, line = 0, adj = 1, cex = 0.75, col = "grey30", font = 3 # italics ) out <- d[c("bins", "clrs")] out[!duplicated(out), ] }, catch[["MonthLocWST"]], catch[["Year"]]) # for tile (heatmap) legend bins_clrs <- do.call(what = rbind, args = p_wst_loc_month) bins_clrs <- bins_clrs[!duplicated(bins_clrs), ] bins_clrs <- bins_clrs[order(bins_clrs[["bins"]]), ] clrs_mon_loc_wst <- subset( bins_clrs, subset = !clrs %in% "grey75", select = clrs, drop = TRUE ) clrs_count <- length(clrs_mon_loc_wst) bins_mon_loc_wst <- seq( from = 0, to = max_bin_mon_loc_wst, length.out = clrs_count ) par(mar = c(1.5, 1.5, 3.5, 2.5)) p_clr_bar <- Plot( x = bins_mon_loc_wst, y = rep(1, times = clrs_count), adjUsr = 0.05 ) p_clr_bar$grid(xRng = TRUE) Axis(p_clr_bar, side = 3, labelAdj = 0.3, interval = 75) mtext(text = "catch - color bar", side = 3, line = 2, cex = 0.75, font = 3) mtext( text = "grey = NA", side = 3, line = 2, adj = 0, col = "grey50", cex = 0.75, font = 3 # italic ) segments( x0 = bins_mon_loc_wst[-clrs_count], x1 = c(1, bins_mon_loc_wst[-(1:2)]), y0 = 1, col = clrs_mon_loc_wst, lwd = 100, lend = 1 ) # reset for adding axes label lo <- layout(mat = 1) # layout.show(lo) par(oma = c(1, 1, 0.5, 0.75), mar = c(0.25, 0.25, 1, 0.25), bg = "white") mtext(text = "Location (number)", side = 2, line = -0.05, outer = TRUE) mtext(text = "Month (Jan-Dec)", side = 1, line = -0.5) # chunk clean up rm( n, ncols, nrows, lvls, mat, lo, bins_clrs, clrs_count, bins_mon_loc_wst, p_clr_bar, clrs_mon_loc_wst ) ``` *`r eval(figures[[6]])`* ## Angler Tag Returns ```{r tags-digits-only} # count number of tags reported as digits only (either not enough or too many to # make a positve match or educated guess); coded here for narrative below tags_digits_only <- sum(catch[["DiscSummary"]][, "someDigits"]) # below counts number of years in which an angler caught & reported > 1 tag (may # be interesting but won't use right now - 15-Apr-2020) # sum(catch[["DiscSummary"]][, "nAngTwoPlusTags"] > 0) ``` In 2010, CDFW added a field for reporting the disc tag number, if present. Some anglers recorded such information starting in 2009 despite such field's absence (Table `r tcn()`). Ideally, an angler should report the entire alpha-numeric (e.g., HH1234). The prefix denotes the reward value (e.g., 'HH' = \$100). A complete tag number makes easier the task of precisely retrieving CDFW release data. Many anglers do their best, but not every reported disc tag is complete (Table `r tcn()`). CDFW staff use angler-reported disc tags to augment mark-recapture data, perhaps improving population metrics accuracy. Table field names are explained below for reference. - **Anglers**: number of anglers reporting a disc tag or possible disc tag - **Good Tag**: count of complete disc tags (angler correctly reported disc tag) - **No Prefix**: count of disc tags reported without alpha (i.e., missing prefix); likely a valid disc tag but more sleuthing is required - **Prefix 'ST'**: count of disc tags reported as 5-digits, no prefix. CDFW released \$20 disc tags with 'ST' followed by 5 digits. So these are likely \$20 tags but more sleuthing is required. - **Reward Only**: count of likely disc tags but no number available. Angler reported reward value only (e.g., \$50.00). - **Zip Only**: count of likely disc tags but no number available. Angler reported Stockton zip code (CDFW Stockton address printed opposite side of disc tag number). To date, anglers have reported `r tags_digits_only` disc tags as digits only. However, digits are too few or too many to make a positive match with CDFW release data. *`r eval(tables[[8]])`* ```{r disp-count-tags} # to limit fields displayed; !b fields are not needed b <- colnames(catch[["DiscSummary"]]) %in% c("someDigits", "nAngTwoPlusTags") # display (years 2007 & 2008 did not require space for disc tags) knitr::kable( catch[["DiscSummary"]][years > 2008, !b], format = "markdown", row.names = TRUE, col.names = c( "Anglers", "Good Tag", "No Prefix", "Prefix 'ST'", "Reward Only", "Zip Code" ) ) # chunk clean up rm(b, tags_digits_only) ``` ```{r angler-demo, eval=FALSE} # possible angler demographics with(Card$AldsPurchased, expr = { table(CustomerID, ItemYear) > 0 }) ``` <!-- save files as desired --> ```{r save-annual_sum, eval=FALSE} write.csv( annual_length, file = "fishery/card_sp_length.csv", row.names = FALSE ) write.csv( card_summary, file = "fishery/card_summary.csv", row.names = FALSE, na = "" ) write.csv( catch_angler, file = "fishery/catch_angler.csv", row.names = FALSE, na = "" ) write.csv( catch_meas, file = "fishery/catch_meas.csv", row.names = FALSE, na = "" ) ``` ## Card Location Codes & Descriptions Card locations are included below for reference. Field 'Number' is not on printed Card and is merely included here for simplifying y-axis in Figure `r fcn() - 1`. Card codes 2-9 may appear on Card with leading 0 (e.g., 03). ```{r loc-codes} loc_codes <- read.csv( file = "fishery/annual_card_files/LocationCodes.csv", header = TRUE, stringsAsFactors = FALSE ) knitr::kable( loc_codes, format = "markdown", row.names = FALSE, align = c('c', 'c', 'l'), col.names = c("Number", "Card Code", "Card Description") ) ``` --- CDFW, Sportfish Unit **updated**: `r format(Sys.time(), format = "%d-%b-%Y @ %H:%M")` <file_sep>--- title: "White Sturgeon Age-15 Abundance Estimates" author: "California Department of Fish and Wildlife" date: "April 19, 2016" output: html_document --- ```{r File Paths and Libraries, echo=FALSE, warning=FALSE} # file paths for absolute reference to source code and data connection data_dir <- "C:/Data/jdubois/RDataConnections/Sturgeon/" # load libraries as needed library(ggplot2) library(knitr) # library(htmlwidgets) # library(DT) #library(reshape2) #library(scales) ``` ```{r Data, echo=FALSE, warning=FALSE, results='hide', message=FALSE, cache=TRUE} source(file = paste0(data_dir, "OtherData.R"), echo = TRUE) source(file = paste0(data_dir, "TaggingData.R"), echo = TRUE) # load .rds abundance data (NOTE: .rds file is saved in Analysis-AltAbundance, # so run code therein to refresh this .rds file - last refreshed 15-Apr-2016) AltAbundance <- readRDS("AltAbund.rds") ``` ```{r Source Code, echo=FALSE, warning=FALSE, message=FALSE} # the source directory source_dir <- "C:/Data/jdubois/RSourcedCode" # sources needed functions and methods source(file = paste(source_dir, "methods_len_freq.R", sep = "/")) source(file = paste(source_dir, "methods_age_freq.R", sep = "/")) source(file = paste(source_dir, "functions_global_data_subset.R", sep = "/")) source(file = "source_stu_abund_age.R") # some cleanup rm(data_dir, source_dir) ``` ```{r Variables, echo=FALSE} # establish l-f breaks for WSTALKEY; note this alk uses TL not FL #wst_alkey_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) wst_alkey_breaks <- c(wst_alkey$Bins, Inf) ``` ### Background The abundance of age-15 White Sturgeon is a key metric in the CPVIA's doubling goal. Historically, we (California Department of Fish and Wildlife, CDFW) have estimated age-15 abundance using mark-recapture data and the fraction of age-15 fish as calculated using an extant age-length key. Herein we present age-15 White Sturgeon abundance using: * Estimates of abundance using harvest and harvest rate * More recent age-length data (from US Fish and Wildlife Service, USFWS) ### Methods & Results We obtained length frequency distributions for White Sturgeon ≥ 85 cm TL from 2007-2014 (Fig. 1). (Minimum length of 85 cm TL set per investigations cited [here](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=114809).) Using age-length keys from CDFW (extant key) and one produced from recently-collected (~2014) USFWS age-length data, we obtained age frequency distributions for the same period (Fig. 2). We estimated overall abundance (N) for White Sturgeon by summing the sub-legal (sub), legal (leg), and over-legal (ovr) abundance estimates as calculated per [CDFW unpublished](../Analysis-AltAbundance/StuAltAbundance.html). Using the fraction of age-15 White Sturgeon (AF~15~, as provided by the age frequency distributions), we calculated the abundance of age-15 fish (N~15~) using the equation below. ${N}_{15} = {N}*{AF}_{15}$ ### Figures & Tabular Data ```{r LF Dist, echo=FALSE} # NOTE: subsetting on >= 85 cm TL for use in getting at age-15 abundance. Alt # abundance currently calculated using minimum WST length of >= 85 cm TL # get length frequency distribution (from 2007-2014 in harmony with available # alt abundance estimates as of 19-Apr-2016); including only WST >= 85 cm TL & # *not* including recaptured WST (for now, this includes fish recorded as # shedding tag) wst_lf_85 <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & RelYear %in% 2007:2014 & TL >= 85 & # below removes recaptured WST StuType %in% c("Tag", "NoTag") ) # to compare abundance at age-15 when calculated using >= 85 cm TL sized fish or # when using (as in this section) fish within the current slot limit # get lf dist for fish within slot (117-168 cm TL) wst_lf_slot <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & RelYear %in% 2007:2014 & TL %in% 117:168 & # below removes recaptured WST StuType %in% c("Tag", "NoTag") ) ``` ```{r LF Plot, echo=FALSE, warning=FALSE, fig.height=8, fig.width=6, fig.cap="Fig. 1 White Sturgeon length frequency distributions 2007-2014. Length data from CDFW mark-recapture study. Blue vertical bar indicates median length. Length bins by 5 cm."} # converting to factor for order when plotting wst_lf_85$Data$LenCat <- factor( wst_lf_85$Data$LenCat, levels = c("sub", "leg", "ovr") ) # plots length frequency distribution 2007-2014 plot( lf = wst_lf_85, lens = TL, fillBar = LenCat, type = "POT", addMed = TRUE, addN = TRUE ) + facet_grid(facets = RelYear ~ .) + coord_cartesian(xlim = c(81, 186)) + scale_fill_manual( name = "", values = c(sub = "grey50", leg= "black", ovr = "steelblue") ) + xlab("Length bins (cm TL)") + theme_stu_lf ``` <br><br> ```{r Make ALKey, echo=FALSE} # in this section we create an age-length key from USFWS data wst_alk_usfws <- MakeALKey( dat = wst_usfws_age_len, len = TotalLength, age = Age, lenBreaks = wst_lf_85$Breaks, breakLabs = wst_lf_85$Bins, dia = FALSE ) # convert wst_alk_usfws bins to integer for analytics to follow wst_alk_usfws$Bins <- as.integer(as.character(wst_alk_usfws$Bins)) # confirm (if necessary) # typeof(wst_alk_usfws$Bins) ``` ```{r AF Dist, echo=FALSE} # using different al keys get age frequency distribution for WST; for this # purpose we get proportions of total (by year) for each age rather than count # age frequency using extant CDFW age-length key wst_af_cdfw <- GetAgeFreq( lfTable = wst_lf_85$Freq, alk = wst_alkey, prop = TRUE ) # reshape for rbind()ing below (for now it seemed that reshaping was the best & # quickest solutions for creating plot comparing af dist from these 2 al keys) wst_af_cdfw_melt <- reshape2::melt( wst_af_cdfw, id.vars = "RelYear", variable.name = "Age", value.name = "Freq" ) # adding source column for identity wst_af_cdfw_melt$Source <- "CDFW" # age frequency using 2014(?) USFWS age-length key wst_af_usfws <- GetAgeFreq( lfTable = wst_lf_85$Freq, alk = wst_alk_usfws, prop = TRUE ) # reshape for rbind()ing below wst_af_usfws_melt <- reshape2::melt( wst_af_usfws, id.vars = "RelYear", variable.name = "Age", value.name = "Freq" ) # adding source column for identity wst_af_usfws_melt$Source <- "USFWS" # age frequency using extant CDFW age-length key wst_af_cdfw_slot <- GetAgeFreq( lfTable = wst_lf_slot$Freq, alk = wst_alkey, prop = TRUE ) # reshape for rbind()ing below (for now it seemed that reshaping was the best & # quickest solutions for creating plot comparing af dist from these 2 al keys) wst_af_cdfw_slot_melt <- reshape2::melt( wst_af_cdfw_slot, id.vars = "RelYear", variable.name = "Age", value.name = "Freq" ) # adding source column for identity wst_af_cdfw_slot_melt$Source <- "CDFW" # age frequency using data collected by USFWS wst_af_usfws_slot <- GetAgeFreq( lfTable = wst_lf_slot$Freq, alk = wst_alk_usfws, prop = TRUE ) # reshape for rbind()ing below wst_af_usfws_slot_melt <- reshape2::melt( wst_af_usfws_slot, id.vars = "RelYear", variable.name = "Age", value.name = "Freq" ) # adding source column for identity wst_af_usfws_slot_melt$Source <- "USFWS" # combine for plotting wst_af <- rbind(wst_af_cdfw_melt, wst_af_usfws_melt) wst_af_slot <- rbind(wst_af_cdfw_slot_melt, wst_af_usfws_slot_melt) # clean up rm( wst_af_cdfw_melt, wst_af_usfws_melt, wst_af_cdfw_slot_melt, wst_af_usfws_slot_melt ) ``` ```{r AF Plot, echo=FALSE, fig.height=6, fig.width=8, fig.cap="Fig 2. White Sturgeon age frequency distributions 2007-2014 using two separate age-length keys - for fish >= 85 cm TL"} # head(wst_af) # converting for ease of displaying x-axis ticks wst_af$Age <- as.numeric(as.character(wst_af$Age)) # ifelse(test = wst_af$Age %in% 15, yes = "red", no = "black") # display age frequency distribution ggplot(data = wst_af, mapping = aes(x = Age, y = Freq)) + # geom_bar(stat = "identity", fill = "black") + geom_bar( stat = "identity", fill = "black" ) + facet_grid(RelYear ~ Source) + scale_x_continuous( minor_breaks = seq(from = 0, to = 23, by = 1), expand = c(0.01, 0) ) + ylab("Fraction of total") + theme_stu_lf ``` <br> ```{r AF Plot2, echo=FALSE, fig.height=6, fig.width=8, fig.cap="Fig 3. White Sturgeon age frequency distributions 2007-2014 using two separate age-length keys - for slot sized fish only"} # converting for ease of displaying x-axis ticks wst_af_slot$Age <- as.numeric(as.character(wst_af_slot$Age)) # display age frequency distribution ggplot( data = wst_af_slot, mapping = aes(x = Age, y = Freq)) + # geom_bar(stat = "identity", fill = "black") + geom_bar( stat = "identity", fill = "black" ) + facet_grid(RelYear ~ Source) + scale_x_continuous( minor_breaks = seq(from = 0, to = 23, by = 1), expand = c(0.01, 0) ) + ylab("Fraction of total") + theme_stu_lf ``` ```{r Abund Age, echo=FALSE} # AltAbundance # get overall N (sub + leg + ovr) annual_abun <- aggregate( formula = N ~ Year, data = AltAbundance, FUN = sum ) # abundance for age 15 using cdfw af abund_15_cdfw <- GetAbunAtAge( abun = annual_abun, af = wst_af_cdfw, age = 15 ) abund_15_cdfw$Source <- "CDFW" abund_15_cdfw$Cat <- "all" # abundance for age 15 using usfws af abund_15_usfws <- GetAbunAtAge( abun = annual_abun, af = wst_af_usfws, age = 15 ) abund_15_usfws$Source <- "USFWS" abund_15_usfws$Cat <- "all" # age-15 abundance using slot-sized fish & CDFW age-length key abund_15_slot_cdfw <- GetAbunAtAge( abun = AltAbundance[AltAbundance$LenCat %in% "leg", c("Year", "N")], af = wst_af_cdfw_slot, age = 15 ) abund_15_slot_cdfw$Source <- "CDFW" abund_15_slot_cdfw$Cat <- "slot" # age-15 abundance using slot-sized fish & USFWS age-length key abund_15_slot_usfws <- GetAbunAtAge( abun = AltAbundance[AltAbundance$LenCat %in% "leg", c("Year", "N")], af = wst_af_usfws_slot, age = 15 ) abund_15_slot_usfws$Source <- "USFWS" abund_15_slot_usfws$Cat <- "slot" # combine for ease of plotting abund_15 <- rbind( abund_15_cdfw, abund_15_usfws, abund_15_slot_cdfw[!is.na(abund_15_slot_cdfw$n_Age15), ], abund_15_slot_usfws[!is.na(abund_15_slot_usfws$n_Age15), ] ) ``` <br><br> <caption> Tabular display of White Sturgeon age-15 abundance (CDFW - top 2, USFWS - bottom 2). Fraction data from age-length frequency distributions. (all = using fish ≥ 85 cm TL; slot = using fish 117-168 cm TL) </caption> ```{r Tab Abund, echo=FALSE} col_name_display <- c( "Year", "N (Total)", "Fraction", "N (Age 15)", "Length Category" ) # capt <- "Age 15 abundance using %s age-length data" # display tabular age-15 abundance kable( abund_15_cdfw[ , -5], format = "markdown", row.names = FALSE, # padding = 5, col.names = col_name_display#, # caption = sprintf(capt, "CDFW")#, # format.args = list(big.mark = ',') ) kable( abund_15_slot_cdfw[!is.na(abund_15_slot_cdfw$n_Age15), -5], format = "markdown", row.names = FALSE, # padding = 5, col.names = col_name_display#, # caption = sprintf(capt, "CDFW")#, # format.args = list(big.mark = ',') ) kable( abund_15_usfws[ , -5], format = "markdown", row.names = FALSE, col.names = col_name_display#, # caption = sprintf(capt, "USFWS") ) kable( abund_15_slot_usfws[!is.na(abund_15_slot_usfws$n_Age15), -5], format = "markdown", row.names = FALSE, col.names = col_name_display#, # caption = sprintf(capt, "USFWS") ) ``` <br> ```{r Plot Abun, echo=FALSE, fig.height=6, fig.width=8, fig.cap="Fig 4. White Sturgeon age-15 abundance 2007-2014 calculated from two different age-length sources"} ggplot( data = abund_15, mapping = aes( x = as.character(Year), y = n_Age15 ) ) + geom_bar( mapping = aes(fill = Cat), stat = "identity", position = "dodge" ) + scale_y_continuous( labels = function(x) x / 1000, expand = c(0.01, 0) ) + scale_x_discrete( expand = c(0.01, 0) ) + scale_fill_manual( name = "", values = c(all = "black", slot = "grey50") ) + labs( x = "Year", y = "Abundance - Age 15 (x 1000)" ) + facet_grid(facets = . ~ Source) + theme_stu_lf ``` <a href="#top">back to top</a> *** Report ran: `r Sys.time()` End of report<file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics") knitr::opts_chunk$set(echo = FALSE) ``` ```{r libraries} # library() ``` ```{r load-data} indices <- read.csv(file = "abundance/AllIndices.csv") ``` ```{r somevars} ``` Young of year index from Bay Study data. For metadata and calculations see [Fish 2010](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=26542) ```{r} par(mar = c(3.0, 4, 1, 1) + 0.1, bty = "u") plot( formula = WSTBS ~ Year, data = indices, type = "b", las = 1, ylab = "Index", xaxt = "n", xlab = NA ) axis( side = 1, at = (1980:2016)[(1980:2016) %% 5 == 0], labels = (1980:2016)[(1980:2016) %% 5 == 0], tck = -0.03, padj = -0.5 ) axis( side = 1, at = 1980:2016, labels = NA, tck = -0.01 ) mtext(text = "Year", side = 1, line = 1.5) ``` <file_sep># sturgeon_population_metrics <file_sep>--- title: "White Sturgeon Survival Rate" author: "CDFW" date: '' output: github_document: default html_document: fig_caption: yes keep_md: no --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, warning = FALSE) knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics/") ``` ```{r libraries} library(ggplot2) # library(reshape2) # library(knitr) ``` ```{r data} # tagging data SturgeonAll <- readRDS(file = "data/tagging/SturgeonAll.rds") AnglerTagReturn <- readRDS(file = "data/tagging/AnglerTagReturn.rds") # read in USFWS age-length data FedAgeLen <- readRDS(file = "data/al_key/FedAgeLen.rds") # read in CDFW extant age-length key WstAlkey <- read.csv( file = "data/al_key/WstAlkey.csv", header = TRUE, col.names = c("Bins", paste0('age', 0:22)) ) ``` ```{r source-files} source(file = "source/source_stu_hr.R") source(file = "source/source_stu_mark-recap.R") source(file = "source/functions_global_general.R") source(file = "source/functions_global_record_count.R") source(file = "source/functions_global_data_subset.R") source(file = "source/functions_survival_rate.R") source(file = "source/methods_len_freq.R") source(file = "source/methods_age_freq.R") source(file = "source/source_stu_cc.R") ``` ```{r variables} # establish l-f breaks for WSTALKEY; note this alk uses TL not FL # wst_alkey_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) wst_alkey_breaks <- c(WstAlkey$Bins, Inf) ``` ```{r wst_lf} lf_wstalkey <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & RelYear >= 1998 ) # for now does include rescue fish of 2011 table( lf_wstalkey$Data$RelYear, lf_wstalkey$Data$Location, useNA = "ifany" ) ``` ```{r wst_af1} # using extant CDFW to get age-length distribution af_wst <- GetAgeFreq(lf = lf_wstalkey$Freq, alk = WstAlkey) af_wst_melt <- reshape2::melt( af_wst, id.vars = "RelYear", variable.name = "Age" ) # for ease of plotting af_wst_melt$Age <- as.numeric( sub(pattern = "age", replacement = "", x = af_wst_melt$Age) ) ``` ```{r surv_rate1} # get survival rate (catch curve method) by release year lst_cc_ouptut <- lapply( split(af_wst_melt, f = af_wst_melt[["RelYear"]]), FUN = SurvivalRateCC, age = Age, catch = value, ageRange = 9:22 ) # convert list output to dataframe & then unlist each column (for use in # plotting below) cc_output <- ListToDataFrame(lst_cc_ouptut) cc_output[] <- lapply(cc_output, FUN = unlist) # for use in plotting below & eventual display in report colnames(cc_output)[which(colnames(cc_output) %in% "V1")] <- "RelYear" ``` ```{r cc_plot1} # ggplot(data = af_wst_melt, mapping = aes(x = Age, y = value)) + # geom_bar(stat = "identity") + # facet_wrap(facets = ~RelYear, ncol = 2) ggplot(data = af_wst_melt, mapping = aes(x = Age, y = value)) + geom_abline( mapping = aes(slope = Slope, intercept = Intercept), data = cc_output, alpha = 2/5 ) + geom_point(size = 1, colour = "steelblue") + facet_wrap(facets = ~RelYear, ncol = 3, scales = "free_y") + scale_y_log10() ``` ```{r table_sr1} knitr::kable(cc_output, format = "pandoc") ``` ```{r surv_rateMR} SurvivalRateMR( mark = SturgeonAll, recap = AnglerTagReturn, years = 1998:2016, sizeSubset = LenCat %in% "leg" ) ``` <file_sep>White Sturgeon Length Frequency ================ CDFW Tagging ------- ![](WSTLengthFreq_files/figure-markdown_github/WstLfTag-1.png) Note: red (dashed) vertical line in plots indicates median length. Card ---- #### Released White Sturgeon ![](WSTLengthFreq_files/figure-markdown_github/WstLfCardr-1.png) #### Kept White Sturgeon (plot needs formatting on x-axis) ![](WSTLengthFreq_files/figure-markdown_github/WstLfCardk-1.png) <file_sep> path <- "U:/Public/SportFish/EnhancedStatusReport/WhiteStuESRData.xlsx" dat <- readxl::read_xlsx(path = path, sheet = "abundance") library(sportfish) vars <- with(data = dat, expr = { boolPet <- Year >= 1979 & Year <= 2006 boolDFW <- Year >= 2007 rangeX <- c(1979, 2018) rangeY <- range( Petersen[boolPet] + PetersenCI[boolPet], Petersen[boolPet] - PetersenCI[boolPet], na.rm = TRUE ) list( boolPet = boolPet, boolDFW = boolDFW, rangeX = rangeX, rangeY = rangeY ) }) par( # bg = "white", # fg = "black", # col = "grey70", # mar: c(bottom, left, top, right) # mar = c(4, 4, 1, 1) + 0.1 mar = c(5, 6, 1, 1), cex.axis = 1.5, cex.lab = 1.5, col.axis = "grey40", col.lab = "black", las = 1, bty = "n", mgp = c(3, 0.75, 0), tcl = -0.3, lend = 1 ) plot( x = vars[["rangeX"]], y = vars[["rangeY"]], type = "n", xaxt = "n", yaxt = "n", xlab = "Year", ylab = NA, xlim = vars[["rangeX"]] + c(0.5, -0.5) ) # par("xaxp")[1:2] par(xaxp = c(1979, 2018, diff(vars[["rangeX"]]))) y_axis_ticks <- axTicks(side = 2) custom_y <- AxisFormat(y_axis_ticks) grid(lwd = 1000, col = "grey90") grid(lty = 1, col = "white", lwd = 1) par("xaxp") segments( x0 = dat[vars[["boolPet"]], "Year", drop = TRUE], y0 = unlist(dat[vars[["boolPet"]], "Petersen"] - dat[vars[["boolPet"]], "PetersenCI"]), y1 = unlist(dat[vars[["boolPet"]], "Petersen"] + dat[vars[["boolPet"]], "PetersenCI"]) ) segments( x0 = dat[vars[["boolDFW"]], "Year", drop = TRUE], y0 = unlist(dat[vars[["boolDFW"]], "CDFW"] - dat[vars[["boolDFW"]], "CDFW-CI"]), y1 = unlist(dat[vars[["boolDFW"]], "CDFW"] + dat[vars[["boolDFW"]], "CDFW-CI"]) ) points( formula = Petersen ~ Year, data = dat, subset = vars[["boolPet"]], pch = 21, bg = "white" ) points( formula = CDFW ~ Year, data = dat, subset = vars[["boolDFW"]], pch = 22, bg = "grey20" ) axis( side = 1, at = (1979:2018)[(1979:2018) %% 5 == 0], labels = (1979:2018)[(1979:2018) %% 5 == 0], tcl = -0.3, col = "transparent", col.ticks = "grey30" ) axis( side = 2, at = axTicks(side = 2), labels = custom_y[["Labels"]], tcl = -0.3, col = "transparent", col.ticks = "grey30", las = 1 ) mtext(text = custom_y$AxisTitle("Abundance (N) "), side = 2, line = 2, las = 3, cex = 1.5) legend( ncol = 2, x = 1980, y = 510000, legend = c("Petersen", "CDFW"), pch = c(21, 22), pt.bg = c("white", "grey20"), xpd = TRUE, bty = "n" ) <file_sep>--- --- ```{r catch-angler} # 02-Apr-2020: in ALDS-era (or at least from 2013 on) we can get count of # anglers who did not fish, fished not catch, and fished catch; here we explore # how to get per angler the number WSTkept, WSTreleased, and GST; for did not # fish = NA, for fished no catch = all 0; for fished & catch then get numbers # from `Card$AnglerCatch` # ****************************************************************************** # TODO: check for duplicate records in `Card[["AldsReturned"]]` # table(vapply(catch_angler[["Data"]], FUN = nrow, FUN.VALUE = numeric(1L))) # # ckval <- vapply(catch_angler[["Data"]], FUN = nrow, FUN.VALUE = numeric(1L)) # # catch_angler[checkval == 2, c("CustomerID", "ItemYear")] # Card[["AldsReturned"]][["LicenseID"]] # ****************************************************************************** catch_angler <- Split( data = Card[["AldsReturned"]], subset = ItemYear >= 2013, vars = c(Code, CustomerID, ItemYear), splitVars = c(CustomerID, ItemYear), drop = TRUE ) # for desired data type catch_angler$ItemYear <- as.numeric(catch_angler[["ItemYear"]]) ``` ```{r catch-angler-summary} # TODO: chunk runs a bit slowly, but this should be OK for now, may tinker a bit # at a later date to improve speed (02-Apr-2020) # summarizes annual catch data by each angler catch_angler$Catch <- t(vapply(catch_angler[["Data"]], FUN = function(d) { code <- d[["Code"]] n <- length(code) # for function output out <- c(numeric(length = 4L), n) names(out) <- c("WSTk", "WSTr", "GST", "Unk", "NRec") out_na <- out out_na[out == 0] <- NA # end function if angler did not catch sturgeon ("U"); if skunked ("UNS"), # return all 0s; if did not fish ("NU") return all NA's if (!any(code %in% "U")) { if (any(code %in% "UNS")) return(out) if (any(code %in% "NU")) return(out_na) } # if n > 1, need to remove dups; could do if statement but this seems OK for # now; b is boolean for subsetting data `d` b <- !duplicated(d[c("CustomerID", "ItemYear")]) # finds catch records by angler & year bb <- Card[["AnglerCatch"]][["AnglerID"]] %in% d[b, "CustomerID"] & Card[["AnglerCatch"]][["Year"]] %in% d[b, "ItemYear"] # subsets on specific catch records dd <- Card[["AnglerCatch"]][bb, c("Species", "Fate")] # to summarize sturgeon catch out[["WSTk"]] <- sum(dd[[1]] %in% "White" & dd[[2]] %in% "kept") out[["WSTr"]] <- sum(dd[[1]] %in% "White" & dd[[2]] %in% "released") out[["GST"]] <- sum(dd[[1]] %in% "Green") out[["Unk"]] <- sum(dd[[1]] %in% "Unk") # return out with catch numbers out }, FUN.VALUE = numeric(5L))) # end vapply ``` <!-- annual summary using `catch_angler` --> ```{r catch-angler-year} catch_angler_year <- Split( data = catch_angler, # subset = , vars = Catch, splitVars = ItemYear ) # for simplified column names colnames(catch_angler_year) <- c("Year", "Data") # to simplify working with matrix rather than Catch as dataframe with one field # (a matrix with WSTk, WSTr, etc.) catch_angler_year$Data <- lapply( catch_angler_year[["Data"]], FUN = function(x) x[["Catch"]] ) # for desired datatype catch_angler_year$Year <- as.numeric(catch_angler_year[["Year"]]) ``` ```{r no-catch} # tabulates did not fish (DNF) & fished no catch (FNC) # NOTE: FNC values herein are higher than `card_summary` values; reason is that # some anglers reported fishing & catching but then did not enter catch (or # forgot or selected incorrectlty fished and catch); then `out` in # `catch-angler-summary` chunk contains all 0s indicating no catch; DNF is # unaffected # TODO: put some identifier on the anlgers reporting fish+catch but then did not # report any catch (03-Apr-2020) catch_angler_year$NoCatch <- t( vapply(catch_angler_year[["Data"]], FUN = function(d) { d <- d[, c("WSTk", "WSTr", "GST", "Unk")] # d must be a matrix (array) with 2+ dimensions to pass to `rowSums` b <- is.null(dim(d)) dnf <- if (b) sum(is.na(d)) else rowSums(is.na(d)) fnc <- if (b) sum(d %in% 0) else rowSums(d == 0, na.rm = TRUE) c(DNF = sum(dnf == 4), FNC = sum(fnc == 4)) }, FUN.VALUE = numeric(2L)) ) ``` ```{r wst-kept} # by WST kept (0, 1, 2, or 3) tabulates angler count by sturgeon (WST, GST, or # UNK) released as 0, 1, 2, 3, 4, & 5+ # TODO: output format is OK but summary from here might be challenging (at least # in terms of displaying all years); look for ways to change output or possibly # plot some data (03-Apr-2020) catch_angler_year$WSTkept <- lapply( catch_angler_year[["Data"]], FUN = function(d) { others <- c("WSTr", "GST", "Unk") # d must be a matrix (array) with 2+ dimensions to pass to `rowSums` b <- is.null(dim(d[, others])) o <- if (b) sum(d[, others]) else rowSums(d[, others]) lbls <- c(paste0(0:4), "5+") o <- cut(o, breaks = c(0:5, Inf), labels = lbls, right = FALSE) table(o, d[, "WSTk"], dnn = NULL) } ) ``` ```{r catch-angler-gst} # by removing NA we get data on anglers who reported & who went fishing (may # have gotten skunked, but they did fish) # Anglers = number who reported & who went fishing # AngGST = number anglers who caught a GST # Count = total # GST caught per year # MaxAngler = max # GST per single angler # Frac = fraction of anglers reporting having fished who caught a GST # (includes those who got skunked but not those who did not fish) # DNF = did not fish catch_angler_year$GST <- t(vapply( catch_angler_year[["Data"]], FUN = function(d) { g <- Filter(f = Negate(is.na), x = d[, "GST"]) r <- mean(g > 0) nf <- sum(is.na(d[, "GST"])) c( Anglers = length(g), AngGST = length(g) * r, Count = sum(g), MaxAngler = max(g), Frac = r, DNF = nf ) }, FUN.VALUE = numeric(6L) )) ``` ```{r catch-release} # 13-Apr-2020: changed it to get fraction rather than sum; using `==0` & `na.rm # = TRUE` will not include 'did-not-fish' anglers catch_angler_year$CatchRelease <- t(vapply( catch_angler_year[["Data"]], FUN = function(d) { others <- c("WSTr", "GST", "Unk") # d must be a matrix (array) with 2+ dimensions to pass to `rowSums` b <- is.null(dim(d[, others])) o <- if (b) sum(d[, others]) else rowSums(d[, others]) # sum(d[, "WSTk"] %in% 0 & o > 0) c( Anglers = nrow(d), Frac = mean(d[, "WSTk"] == 0 & o > 0, na.rm = TRUE) ) }, FUN.VALUE = numeric(2L) )) ``` ```{r reporting-wst-kept} # of reporting anglers - fraction who kept 0, 1, 2, 3 WST & who did not fish catch_angler_year$ReportWSTk <- t(vapply( catch_angler_year[["Data"]], FUN = function(d) { k <- factor(d[, "WSTk"], levels = c(0:3, NA), exclude = NULL) c(Anglers = nrow(d), prop.table(table(k))) }, FUN.VALUE = numeric(6L) )) ``` <file_sep>--- --- <!-- To get a sense of spatial and temporal catch, we added a 'Season' field to angler catch data. We group seasons as follows: winter = Dec, Jan, Feb; spring = Mar, Apr, May; summer = Jun, Jul, Aug; and fall = Sep, Oct, Nov. To maintain chronology and because winter crosses each calendar year, we 'pushed' Dec into the next Card year. For example, Dec 2008 is grouped with Jan 2009 & Feb 2009 to make winter 2009. As such, winter 2007 (Dec 2006, Jan 2007, & Feb 2007) is data "light" because the Card did not really come on-line until March 2007. Consider this fact when viewing annual summaries for winter 2007. --> <!-- Here we display but 5 rows of the `nrow(catch_yr_loc)` annual summary of seasonal and geographic (location) catch. For `Species`, 'k' denotes kept and 'r' denotes released. Seasons are abbreviated 'uk', 'wi', 'sp', 'su', and 'fa' (unknown, winter, spring, summer, fall). `Total` is total annual catch per location, and `NumAngl` and `NumMeas` are number of anglers and number (of fish) measured. We use (converted) fork length (in centimeters) and provide mean and standard deviation (sd) when number measured greater than 0. --> <!-- catch per season, creates new dataframe from `catch` --> ```{r catch-season} # NOTE: seasonal catch where Dec is in previous year so for example 2019 data # would be Dec 2018, Jan 2019, Feb 2019 for winter, etc. # NOTE: this solution is good but now it's not the same "group" of anglers as # now Dec & Jan+Feb are two different Card years; something to mention in the # narrative (10-Apr-2020) # ************************************************ # add Season field to catch data where # winter (wi): Dec (previous year), Jan, Feb # spring (sp): Mar, Apr, May # summer (su): Jun, Jul, Aug # fall (fa): Sep, Oct, Nov # ************************************************ # allows for understanding catch based on season & location # creates lookup for Month field lkp_season <- setNames( object = c( rep("wi", times = 2), rep("sp", times = 3), rep("su", times = 3), rep("fa", times = 3), "wi" ), nm = c(paste0(0, 1:9), 10:12) ) # to add 'Season' field to catch dataframe; where Month is not supplied (i.e., # NA) Season is 'uk' or unknown; we make field a factor for ordering as in # `labels` below Card$AnglerCatch$Season <- factor( lkp_season[Card[["AnglerCatch"]][["Month"]]], levels = c(NA, "wi", "sp", "su", "fa"), labels = c("uk", "wi", "sp", "su", "fa"), exclude = NULL ) # needed for grouping & then splitting Card[["AnglerCatch"]]$MonthNum <- as.numeric(Card[["AnglerCatch"]][["Month"]]) Card[["AnglerCatch"]]$GroupYear <- GroupYear( Card[["AnglerCatch"]], year = Year, mon = MonthNum, startMon = 12, direction = "backward" ) catch_season <- Split( data = Card[["AnglerCatch"]], # vars = -GroupYear, splitVars = GroupYear ) # for convenient data type & colnames (grouped year advanced by 1 for # realignment back to Card year) catch_season$GroupYear <- as.numeric(catch_season[["GroupYear"]]) + 1 colnames(catch_season) <- c("Year", "Data") # can remove these columns from main data as these fields are now in # catch_season[["Data]] Card[["AnglerCatch"]]$MonthNum <- NULL Card[["AnglerCatch"]]$GroupYear <- NULL ``` ```{r catch-season-wstk} catch_season$WSTk <- lapply( catch_season[["Data"]], FUN = function(d, lvls = loc_lvls) { # for all codes present within each 'Split' d$LocCode <- factor(d[["LocCode"]], levels = lvls) r <- Split( data = d, subset = Species %in% "White" & Fate %in% "kept", vars = c(FL_cm, Season, AnglerID), splitVars = LocCode, drop = FALSE ) # cycle through each location code to get count by seaso o <- vapply(r[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) l <- Filter(f = Negate(is.na), x = dd[["FL_cm"]]) c( Ang = a, table(dd[["Season"]]), Tot = nrow(dd), Meas = length(l), MnFL = mean(l), SdFL = sd(l) ) }, FUN.VALUE = numeric(10L)) # end vapply t(o) } ) # end lapply ``` ```{r catch-season-wstr} catch_season$WSTr <- lapply( catch_season[["Data"]], FUN = function(d, lvls = loc_lvls) { # for all codes present within each 'Split' d$LocCode <- factor(d[["LocCode"]], levels = lvls) r <- Split( data = d, subset = Species %in% "White" & Fate %in% "released", vars = c(FL_cm, Season, AnglerID), splitVars = LocCode, drop = FALSE ) # cycle through each location code to get count by seaso o <- vapply(r[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) l <- Filter(f = Negate(is.na), x = dd[["FL_cm"]]) c( Ang = a, table(dd[["Season"]]), Tot = nrow(dd), Meas = length(l), MnFL = mean(l), SdFL = sd(l) ) }, FUN.VALUE = numeric(10L)) # end vapply t(o) } ) # end lapply ``` ```{r catch-season-gst} catch_season$GST <- lapply( catch_season[["Data"]], FUN = function(d, lvls = loc_lvls) { # for all codes present within each 'Split' d$LocCode <- factor(d[["LocCode"]], levels = lvls) r <- Split( data = d, subset = Species %in% "Green", vars = c(FL_cm, Season, AnglerID), splitVars = LocCode, drop = FALSE ) # cycle through each location code to get count by seaso o <- vapply(r[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) l <- Filter(f = Negate(is.na), x = dd[["FL_cm"]]) c( Ang = a, table(dd[["Season"]]), Tot = nrow(dd), Meas = length(l), MnFL = mean(l), SdFL = sd(l) ) }, FUN.VALUE = numeric(10L)) # end vapply t(o) } ) # end lapply ``` ```{r plot-wstr-spb, eval=FALSE} # plot seasonal catch of released White Sturgeon for San Pablo Bay (SPB). Data # points indicated by 2-character seasonal abbreviation. # for yaxis range rng <- vapply(catch_season[["WSTr"]], FUN = function(d) { range(d["16", c("wi", "sp", "su", "fa")]) }, FUN.VALUE = numeric(2L)) # for empty plot p_season_wstr <- Plot( x = range(catch_season[["Year"]]), y = range(rng) ) p_season_wstr$grid(xRng = TRUE) # points or text for noting number released by season Map(f = function(y, d) { yy <- d["16", c("wi", "sp", "su", "fa")] # to mitigate overplotting dodge <- c(-0.2, -0.1, 0.1, 0.2) text( # x = rep(y, length = 4), x = y + dodge, y = yy, labels = names(yy), col = rgb(red = 0, green = 0, blue = 0, alpha = 0.8) ) # points( # x = y + dodge, # y = yy, # col = 1:4 # ) }, catch_season[["Year"]], catch_season[["WSTr"]]) # add tick labels (need to add axis labels too) Axis(p_season_wstr, side = 1, labelAdj = 0.3, interval = 2) Axis(p_season_wstr, side = 2, labelAdj = 0.4) mtext( text = "White Sturgeon released by Season, San Pablo Bay", side = 3, line = 0, adj = 0, col = "grey25" ) # chunk clean up rm(rng) ``` ```{r plot-wstk-loc-04_18, eval=FALSE} # plot winter catch of kept White Sturgeon comparing locations Suisun Bay (18) # and Sacramento River (Rio Vista to Chipps Island; 04). Data points indicated # by 2-character location code. # for yaxis range rng <- vapply(catch_season[["WSTk"]], FUN = function(d) { range(d[c("04", "18"), "wi"]) }, FUN.VALUE = numeric(2L)) # for empty plot p_season_wstk <- Plot( x = range(catch_season[["Year"]]), y = range(rng) ) p_season_wstr$grid(xRng = TRUE) # points or text for noting number released by season Map(f = function(y, d) { yy <- d[c("04", "18"), "wi"] # to mitigate overplotting dodge <- c(-0.1, 0.1) text( # x = rep(y, length = 4), x = y + dodge, y = yy, labels = names(yy), col = rgb(red = 0, green = 0, blue = 0, alpha = 0.8) ) # points( # x = y + dodge, # y = yy, # col = 1:2 # ) }, catch_season[["Year"]], catch_season[["WSTk"]]) # add tick labels (need to add axis labels too) Axis(p_season_wstk, side = 1, labelAdj = 0.3, interval = 2) Axis(p_season_wstk, side = 2, labelAdj = 0.4) mtext( text = "White Sturgeon kept Winter Season", side = 3, line = 0, adj = 0, col = "grey25" ) # chunk clean up rm(rng) ``` <file_sep> # non-CRAN package installation ------------------------------------------- # need to install from github not source for `spopmodel` to be recognized for # publishing app; uncomment below & run after making any changes to `spopmodel` # devtools::install_github(repo = "jasondubois/spopmodel") # libraries --------------------------------------------------------------- library(shiny) library(spopmodel) # server & application ---------------------------------------------------- server <- function(input, output) { par_set <- par( mar = c(3, 3, 0.75, 0.25), oma = c(0.25, 0.25, 0.25, 0.25), mgp = c(1.75, 0.5, 0) ) # data source ----------------------------------------------------------- # retrieve data from user's selection; d will now be trammel_catch from # `spopmodel` - may need some try-catch block if unable to retrieve dd <- get(isolate(expr = { input$data_source })) d <- reactive({ # dd <- get(input$data_source) bool_gte190 <- dd[["FL"]] >= 190 bool_ageNA <- is.na(dd[["Age"]]) dd[bool_gte190 & bool_ageNA, "Age"] <- 19 # clean up (not needed) rm(bool_gte190, bool_ageNA) # range_fl <- range(dd[["FL"]]) range_fl <- c(50, 220) # if (input$selectivity %in% "no") return(head(dd)) if (input$selectivity %in% "no") return(dd) # otherwise apply Millar's selectivity model split_fl_mesh <- split(dd[["FL"]], f = dd[["MeshSize"]]) freq <- lapply( split_fl_mesh, FUN = Frequency, binWidth = 5, xRange = range_fl ) # expand length bins by counts freq_exp <- lapply(freq, FUN = function(x) { n <- length(x[["breaks"]]) # tms <- x[["counts"]] # tms[tms <= 0 | is.na(tms)] <- 1 rep(x[["breaks"]][-n], times = x[["counts"]]) # rep(x[["breaks"]][-n], times = tms) }) # for repeating mesh size in dataframe needed for ApplyNetFit n <- vapply(freq_exp, FUN = length, FUN.VALUE = numeric(1L)) # creates dataframe needed by ApplyNetFit() & bins lengths as above; if not # needing binned lengths, then just use trammel_net as data supplied to # ApplyNetFit(); Blackburn applied gear selectivity models on length binned # by 5 cm mesh_data_temp <- data.frame( Mesh = rep(as.numeric(names(freq_exp)), times = n), FL = unlist(freq_exp, use.names = FALSE), stringsAsFactors = FALSE ) apply_net_fit <- ApplyNetFit( data = mesh_data_temp, len = FL, mesh = Mesh, relPower = c(1, 1, 2) ) # lowest deviance is desired model_deviance <- DeviancePlots(apply_net_fit) deviance_values <- vapply(model_deviance, FUN = function(x) { x["Deviance", ] }, FUN.VALUE = numeric(1L)) # model_chosen <- names(which.min(deviance_values)); for now hard code to be # in-line with <NAME>'s chosen model (22-Jul-2020) model_chosen <- "binorm.sca" # print(deviance_values) rr <- RelativeRetention(apply_net_fit, standardize = FALSE)[[model_chosen]] # print(mesh_data_temp) # for overall relative retention not just by mesh size rr_row_sums <- rowSums(rr[["Data"]][2:4]) rr_stand <- rr_row_sums / max(rr_row_sums) # print(rr_stand) # print(table(mesh_data_temp[["FL"]])) # <NAME> relative retention values from `size_selective_data.xlsx`, # tab `bi.norm`, column F sb <- c( 0.49157779, 0.57460823, 0.65848795, 0.73990818, 0.81535366, 0.88137855, 0.93489596, 0.97344113, 0.99537404, 1.00000000, 0.98759057, 0.95931149, 0.91706928, 0.86330595, 0.80077257, 0.73230331, 0.66062285, 0.58819520, 0.51712572, 0.44910702, 0.38541133, 0.32691128, 0.27412252, 0.22725779, 0.18628429, # 0.15098010, 0.12098581, 0.09585021, 0.07506861, 0.05811487, 0.15098010, 0.12098581, 0.07506861, 0.04446646, 0.01854676 ) freq_bin <- rowSums(rr[["Freq"]]) freq_adj <- freq_bin / rr_stand # freq_adj <- freq_bin / sb # print(cbind(rr[["Data"]][[1]], freq_bin, sb)) # print(rr_stand) # names(freq_adj) <- rr[["Data"]][[1]] # to get expanded data for additional processing outside this function res <- with(data = dd, expr = { Age[is.na(Age)] <- -1 # bw <- spopmodel:::BinWidth(w = 5) out <- aggregate( MeshSize, by = list(Age = Age, FL = FL), FUN = length, drop = TRUE ) out$Bins <- spopmodel:::CreateLenBins( len = out[["FL"]], # lenBreaks = bw(out[["FL"]]), lenBreaks = seq(from = range_fl[1], to = range_fl[2], by = 5), numericBin = TRUE ) splt <- split(out[["x"]], f = out["Bins"]) out$Prop <- unlist(lapply(splt, FUN = prop.table), use.names = FALSE) out }) res$Age[res[["Age"]] %in% -1] <- NA # i <- match(res$Bins, table = names(freq_adj)) i <- match(res$Bins, table = rr[["Data"]][[1]]) # res$Adj <- freq_adj[i] # new_n <- ceiling(freq_adj[i] * res[["Prop"]]) new_n <- floor(freq_adj[i] * res[["Prop"]]) # print(new_n) # new_n[is.na(new_n)] <- 1 res <- lapply(res, FUN = rep, times = new_n) res <- as.data.frame(res)[c("Age", "FL")] # range_fl <- range(dd[["FL"]]) # len_breaks <- seq(from = range_fl[1], to = range_fl[2], by = 5) # # breaks are all identical for three mesh sizes # alk <- MakeALKey( # data = dd, # len = FL, # age = Age, # lenBreaks = freq[["6"]][["breaks"]] # ) # clean up rm(n, mesh_data_temp) # colSums(alk * freq_adj, na.rm = TRUE) %/% 1 # list( # freq[["6"]][["breaks"]], # rr[["Data"]] # ) # table(mesh_data_temp$FL, useNA = "ifany") # dim(alk) # rr[["Data"]] # freq_bin # freq_adj # list( # vapply(dd, FUN = function(x) { # mean(is.na(x)) # }, FUN.VALUE = numeric(1L)), # vapply(res, FUN = function(x) { # mean(is.na(x)) # }, FUN.VALUE = numeric(1L)) # ) res }) # end d() # for now testing in summary but will need new tab # output$summary <- renderPrint(expr = { print(d()) }) # default age for very large fish --------------------------------------- # assigns age 19 to any fish greater than 190 cm FL with no age; there are # very few fish like this in this dataset & doing this helps when applying # AgeEach() or age-length key (i.e., no un-aged length bins) # bool_gte190 <- d()[["FL"]] >= 190 # bool_ageNA <- is.na(d()[["Age"]]) # d()[bool_gte190 & bool_ageNA, "Age"] <- 19 # # # clean up (not needed) # rm(bool_gte190, bool_ageNA) # option to apply gear selectivity models ------------------------------- # for now moved to `data source` # length frequency ------------------------------------------------------ len_freq <- reactive({ Frequency(d()[["FL"]], binWidth = 5, xRange = c(50, 220)) }) # output$distPlot <- renderPlot(expr = { plot(len_freq(), xlab = "Length") }) # output$summary <- renderPrint(expr = { print(len_freq()) }) # age frequency --------------------------------------------------------- ages <- reactive({ AgeEach( data = d(), len = FL, age = Age, lenBreaks = len_freq()[["breaks"]] ) }) # end ages # age_freq <- reactive( {table(ages()[["Ages"]], dnn = NULL)} ) age_freq <- reactive({ if (input$sb == "no") return(table(ages()[["Ages"]], dnn = NULL)) # Blackburn's data from: size_selective_data.xlsx | tab Abundance | column B r <- c( 45.23, 52.95, 127.91, 121.55, 164.19, 181.24, 136.04, 71.53, 52.50, 33.52, 91.78, 55.50, 105.02, 7.04, 90.93, 20.66, 65.64 ) names(r) <- 3:19 r }) # end age_freq # plot age frequency output$ageFreqPlot <- renderPlot(expr = { par(par_set) y <- as.vector(age_freq()) plot( x = as.numeric(names(age_freq())), y = y, type = "h", col = "grey50", lwd = 5, lend = 1, las = 1, ylab = "Frequency", xlab = "Age", ylim = c(0, max(y)) ) # end plot mtext( text = sprintf(fmt = "n=%.0f", sum(y)), side = 1, line = 1.5, adj = 1, font = 3 ) }) # end output$ageFreqPlot # mean length at age ---------------------------------------------------- # get mean-length-at-age given lengths with assigned ages mean_len_age <- reactive({ # mean-length-at-age using data from d() r <- aggregate(d()[["FL"]], by = d()["Age"], FUN = mean) colnames(r)[2] <- "MeanFL" if (input$sb == "no") return(r) # Blackburn's data from: size_selective_data.xlsx | tab Abundance | column F data.frame( Age = 3:19, MeanFL = c( 63.09090909, 65.23684211, 76.8, 77.56756757, 84.17088608, 89.98882682, 99.47727273, 102.1911765, 117.0652174, 124.64, 136.7916667, 148.0416667, 152.0857143, 167, 168.65, 182.3333333, 187.75 ) ) }) # end mean_len_age # plot mean length-at-age (laa) output$laaPlot <- renderPlot(expr = { par(par_set) plot( x = mean_len_age()[["Age"]], y = mean_len_age()[["MeanFL"]], pch = "+", col = "darkred", las = 1, ylab = "Length (cm FL)", xlab = "Age" ) # end plot # for possible display of n if not using SB data # if (input$sb == "no") { # n_age <- length(d()[["Age"]]) # mtext(text = n_age) # } # for display of harvestable age range relating to length - # will take some massaging (24-Jul-2020) # segments( # x0 = c(0, 10), # y0 = c(mean_len_age()[["MeanFL"]][[8]], mean_len_age()[["MeanFL"]][[8]]), # x1 = c(10, 10), # y1 = c(mean_len_age()[["MeanFL"]][[8]], 0), # col = 2 # ) }) # end output$laaPlot # age distribution ------------------------------------------------------ # establishes age distribution given input from params age_distribution <- reactive({ AgeDist( ageFreq = age_freq(), abund = input$abund, fracFemale = input$frac ) }) # for later analyses est_abundance <- reactive({ age_distribution()[["EstAgeAbund"]] }) # for now testing in summary but will need new tab # output$summary <- renderPrint(expr = { print(age_distribution()) }) # predict age-1 & age-2 abundance --------------------------------------- # log-linear abundance to predict age 1-2 abundance mod <- reactive({ y <- log(as.vector(est_abundance())) x <- as.numeric(names(est_abundance())) list(mod = lm(y ~ x), x = x, y = y) }) # to plot linear regression model used to predict ages 1 & 2 output$predage12Plot <- renderPlot(expr = { plot( x = mod()$x, y = mod()$y, type = "b", col = "grey60", xlab = "Age", ylab = "log(EstAbund)", panel.first = abline(mod()$mod, col = "blue") ) }) # end predage12Plot # female abundance ------------------------------------------------------ females <- reactive({ age1_2 <- exp(predict(object = mod()$mod, newdata = list(x = c(1, 2)))) c( age1_2 * age_distribution()[["FracFemale"]], age_distribution()[["CountFemByAge"]] ) }) # to plot female abundance with predicted ages 1 & 2 output$femAbunPlot <- renderPlot(expr = { par(par_set) y <- females() # Blackburn's data from: corrected_transient_midfecund_current.R # variable `initial_age_dist` | ages 1-19 y2 <- c( 3242.553, 2013.134, 762.9124, 892.9627, 2157.2744, 2050.1174, 2769.1556, 3056.7626, 2294.4497, 1206.4047, 885.4213, 565.3075, 1548.0006, 935.9705, 1771.2220, 118.7429, 1533.6657, 348.5073, 1107.0916 ) # colors for bars in plot to denote predicted cols <- c( # predicted from lm rep("steelblue", times = 2), # derived from age data rep("grey50", times = length(y)) ) # to plot female abundance by ages 1-19(or max age) plot( x = as.numeric(names(females())), y = y, type = "h", col = cols, lwd = 5, lend = 1, las = 1, xlab = "Age", ylab = "N", ylim = c(0, max(y, y2)) ) # to show SB's points used in final model output points( x = as.numeric(names(females())), y = y2, col = "black", pch = "+", cex = 1.2 ) # to display total N for females mtext( text = sprintf(fmt = "N[%s]=%.0f", "\u2640", sum(y)), side = 1, line = 1.5, adj = 1, font = 3 ) }) # end femAbunPlot # spawning probability -------------------------------------------------- # subset of age > 9 bool_mlaa_gt9 <- reactive( {mean_len_age()[["Age"]] > 9} ) # issues the glm warning - should be handled or suppressed prob_spawn2 <- reactive({ cnames <- c("Age", "Prob", "Err") # if (input$sb == "yes") { # p <- prob_spawn # colnames(p) <- cnames # return(p) # } p_spawn <- SpawningProb( len = mean_len_age()[bool_mlaa_gt9(), "MeanFL"], age = mean_len_age()[bool_mlaa_gt9(), "Age"], mature = input$mature ) # output rbind( data.frame(Age = 0:9, Prob = 0, Err = 0), p_spawn[, cnames] ) }) # for now testing in summary but will need new tab # output$summary <- renderPrint(expr = { print(prob_spawn2()) }) # clean up (no longer needed) # rm(bool_mlaa_gt9) # age distribution (complete) ------------------------------------------- # Devore's (et al. 1995) equation to calculate number of eggs based on fork # length eggs_female <- reactive({ 0.072 * (mean_len_age()[bool_mlaa_gt9(), "MeanFL"])^2.94 }) # end eggs_female age0 <- reactive({ r <- prob_spawn2()[11:20, "Prob"] * females()[10:19] * eggs_female() r <- sum(r) if (input$sb == "no") return(r) # add 38,832,615 to get SB's number or close to her value 219387277 r + 38832615 }) # end age0 age_dist2 <- reactive({ r <- data.frame( Age = as.numeric(c(0, names(females()))), Freq = c(age0(), unname(females())), # Freq = c(input$agezero, unname(females())), row.names = NULL ) if (input$sb == "no") return(r) r[2, "Freq"] <- r[2, "Freq"] + 1092.843 r }) # end age_dist2 # to compare SB's age distribution with those calculated herein output$ageDistCompare <- renderPlot(expr = { par(par_set) # par(mar = par_set$mar + c(0, 0, 1.5, 0)) # to plot female abundance by ages 1-19(or max age) plot( x = age_dist[["freq"]][-1], y = age_dist2()[["Freq"]][-1], xlab = "SB's used age dist", ylab = "Age dist (here)" ) abline(a = 0, b = 1, col = 2) # # to display age-0s; given the magnitude - better to display in upper # margin than on plot mtext( text = sprintf( fmt = "Age-0: SB used %s || calc here %s", format(age_dist[["freq"]][1], big.mark = ","), format(age_dist2()[["Freq"]][1], big.mark = ",") ), side = 3, line = 0, adj = 0.5, cex = 0.85, font = 1 ) }) # end ageDistCompare # egg count ------------------------------------------------------------- # egg count age-10 to age-19 num_eggs <- reactive({ mean_len <- mean_len_age()[bool_mlaa_gt9(), "MeanFL"] age_at_len <- mean_len_age()[bool_mlaa_gt9(), "Age"] ec <- EggCount(len = mean_len, age = age_at_len) rbind( data.frame(Age = 0:9, Count = 0, Err = 0), ec[, c("Age", "Count", "Err")] ) }) # to compare SB's age distribution with those calculated herein output$numEggCompare <- renderPlot(expr = { par(par_set) # par(mar = par_set$mar - c(0, 0, 1.5, 0)) b <- number_eggs[["age"]] > 9 # to compare number of eggs plot( x = number_eggs[b, "count"], y = num_eggs()[b, "Count"], xlab = "SB's used number eggs", ylab = "Number eggs (here)" ) # to show ages next to each data point text( x = number_eggs[b, "count"], y = num_eggs()[b, "Count"], labels = number_eggs[b, "age"], cex = 0.9, col = "grey15", adj = c(0.5, 1.25) ) abline(a = 0, b = 1, col = 2) }) # end numEggCompare # cumulative survival rate ---------------------------------------------- # to show survival rate applied to age-0 produces age structure output$cumSurvRate <- renderPlot(expr = { par(par_set) # to compare number of eggs plot( x = 1:20, y = cumprod(prob_survival[["prob"]]) * age0(), xlab = "Age", ylab = "Number survive to next year" ) }) # end cumSurvRate # survival probability -------------------------------------------------- # for use in simulations (next steps) prob_surv <- reactive({ SurvivalProb( ages = prob_survival[["age"]], sRate = prob_survival[1:3, "prob"], sRateErr = prob_survival[1:3, "se"], mu = seq(from = 0, to = 0.30, by = 0.01), # agesMu = c(input$ageharvest[1], input$ageharvest[2]), agesMu = input$ageharvest[1]:input$ageharvest[2], estS = input$surv, estMu = input$harv, methodSB = TRUE ) }) # test <- reactive({input$ageharvest[1]:input$ageharvest[2]}) # # output$summary <- renderPrint(expr = { print(prob_surv()) }) # model ----------------------------------------------------------------- # works but need to rename variable mod_out <- eventReactive( eventExpr = { input$action }, # valueExpr = { input$abund } valueExpr = { sims_prob_spawn <- Simulations( data = prob_spawn2(), prob = Prob, std = Err, iters = input$sims, type = "spawning" ) sims_num_eggs <- Simulations( data = num_eggs(), prob = Count, std = Err, iters = input$sims, type = "numeggs" ) sims_prob_surv <- mapply( FUN = Simulations, prob_surv(), MoreArgs = list( prob = "Prob", std = "Err", recruitment = input$recruit, iters = input$sims, type = "survival" ), SIMPLIFY = FALSE ) sims_fecund <- sims_num_eggs * sims_prob_spawn * input$frac # hard-coding indices susceptible to problems if data change final_age <- lapply(prob_surv(), FUN = "[", 20, 2:3) mu_levels <- setNames( object = names(sims_prob_surv), nm = names(sims_prob_surv) ) pop_proj <- lapply(mu_levels, FUN = function(x) { PopProjections( fSims = sims_fecund, sSims = sims_prob_surv[[x]], mn = final_age[[x]][["Prob"]], sdev = final_age[[x]][["Err"]], ageFreq = age_dist2()[["Freq"]], # ageFreq = age_dist[["freq"]], period = 20 # period = 40 ) }) lambda_mu <- lapply(mu_levels, FUN = function(x) { mu <- as.numeric(sub(pattern = "mu_", replacement = "", x = x)) out <- Lambda( popChanges = pop_proj[[x]]["pop.changes", ], selectCI = as.numeric(input$ci) ) out[["MuLevel"]] <- mu out }) lambda_mu <- do.call(what = rbind, args = lambda_mu) rownames(lambda_mu) <- NULL lambda_mu } ) # output$summary <- renderPrint(expr = { # # print(prob_spawn2()[11:20, "Prob"] * females()[10:19] * eggs_female()) # # print(females()) # print(num_eggs()) # # print(females()) # # print(mean_len_age()[bool_mlaa_gt9(), "MeanFL"]) # # print(prob_spawn2()) # # print(prob_spawn2()[11:20, "Prob"]) # # print( mean_len_age()[bool_mlaa_gt9(), "MeanFL"]) # }) output$mortparams <- renderPrint(expr = { print(spopmodel:::FishingParams(S = input$surv, mu = input$harv)) # print(input$ci) # print(mod_out()) }) output$modelPlot <- renderPlot(expr = { par(par_set) plot( x = mod_out()[["MuLevel"]], y = mod_out()[["MeanLambda"]], col = "orange2", lty = 1, lwd = 2, type = "n", ylim = c(0.8, 1.2), xlab = "Exploitation", ylab = "Population growth rate" ) # polygon() # x & y values for drawing polygon as lower & upper bounds poly_list <- list( x = c( mod_out()[["MuLevel"]][1], mod_out()[["MuLevel"]], rev(mod_out()[["MuLevel"]][-1]) ), y = c( mod_out()[["QuantLow"]][1], mod_out()[["QuantUpp"]], rev(mod_out()[["QuantLow"]][-1]) ) ) polygon(poly_list, col = "grey90", border = NA) lines( x = mod_out()[["MuLevel"]], y = mod_out()[["MeanLambda"]], col = "orange2", lty = 1, lwd = 2 ) abline(h = 1, col = adjustcolor(col = "steelblue", alpha.f = 0.5)) # mtext(text = paste0(est_abundance(), collapse = " | "), side = 3) # mtext(text = nrow(d()), side = 3, line = 0, adj = 1) }) } # end server # shinyApp(ui = htmlTemplate("model/www/index.html"), server = server) shinyApp(ui = htmlTemplate("www/index.html"), server = server) <file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics") ``` ```{r libraries} library(dplyr) library(spopmodel) ``` ```{r load-data} SturgeonAll <- readRDS(file = "data/tagging/SturgeonAll.rds") AnglerTagReturn <- readRDS(file = "data/tagging/AnglerTagReturn.rds") ``` ```{r somevars} ``` ```{r} # head(SturgeonAll) # number legal-sized (at tagging) WST tagged wst_tagged <- SturgeonAll %>% filter( Species %in% "White" & StuType %in% "Tag" & LenCat %in% "leg" & RelYear > 1997 & TagVal > 0 ) %>% group_by(RelYear, TagVal) %>% summarise(NumRel = n()) ``` ```{r} head(AnglerTagReturn) angler_returns <- AnglerTagReturn %>% filter( Species %in% "White" & RetYear %in% 1 & LenCat %in% "leg" & RelYear > 1997 & TagVal > 0 ) %>% group_by(RelYear, TagVal) %>% summarise(NumRet = n()) ``` ```{r} head(wst_tagged) head(angler_returns) rel_ret <- merge( x = wst_tagged, y = angler_returns, all = TRUE, by = c("RelYear", "TagVal") ) rel_ret$NumRet[is.na(rel_ret$NumRet)] <- 0 ``` ```{r} rel_ret[rel_ret$RelYear %in% 2001, ] barplot(height = rel_ret$NumRet, col = 1:3) ReportingRate() # Exploitation ``` ```{r eval=FALSE} par(mar = c(3.0, 4, 1, 1) + 0.1, bty = "u") plot( formula = WSTBS ~ Year, data = indices, type = "b", las = 1, ylab = "Index", xaxt = "n", xlab = NA ) axis( side = 1, at = (1980:2016)[(1980:2016) %% 5 == 0], labels = (1980:2016)[(1980:2016) %% 5 == 0], tck = -0.03, padj = -0.5 ) axis( side = 1, at = 1980:2016, labels = NA, tck = -0.01 ) mtext(text = "Year", side = 1, line = 1.5) ``` <file_sep>###tagging-season report script ###By <NAME> ###11/4/2020 ###Hobbs attempting to recreat the tagging-season.Rmd in tidy-R # sportfish currently available on GitHub library(sportfish) library(tidyr) library(here) ###setting graphics par( # bg = "white", # fg = "black", # col = "grey70", # mar: c(bottom, left, top, right) # mar = c(4, 4, 1, 1) + 0.1 # mar = c(5, 6, 1, 1), # cex.axis = 1.5, # cex.lab = 1.5, col.axis = "grey40", col.lab = "black", # las = 1, bty = "n", mgp = c(3, 0.75, 0), tcl = -0.3, lend = 1 ) ###load the data, data are stored as .rds files here ###U:\SportFish\Staff Files\JDuBois\0_RProjects\SturgeonPopMetrics\data\tagging <file_sep>--- output: html_document --- ```{r setup, include=FALSE} knitr::opts_knit$set( root.dir = "~/RProjects/SturgeonPopMetrics/", global.par = TRUE ) ``` ```{r global-par} par( mar = c(2.75, 2.5, 1.5, 0.5), oma = c(0.5, 0.5, 0.5, 0.5), mgp = c(1.75, 0.5, 0) ) ``` ```{r load-data} # SB's data from 'size_selective_data.xlsx', tab 'Fl'; changing column names to # remove inported prefixed 'X', though not sure it matters for this excercise sbdata <- read.csv(file = "model/SBData.csv", header = TRUE) colnames(sbdata) <- c("FL", 6:8) ``` ```{r variables} # could use either; S. Blackburn rounded to one decimal # msize <- c(6, 7, 8) * 2.54 msize <- c(15.2, 17.8, 20.3) # represents fishing power of net by mesh size (8" mesh fished at twice the # effort as typical net config is 8"-6"-7"-8") rpwr <- c(1, 1, 2) ``` ## Starting Values starting values for net fit model ```{r starting-values} # SB's starting values (X0) for gear selectivity model; origin unknown & I am # not sure these values make sense based on length-frequency modes; starting # values I thought should be based somewhat on existing data; find these values # in file 'SELECT.R' from SB X00 <- c(40, 6, 10, 10, 1) # using functions developed in `spopmodel` to get starting values for comparison # to SB's; here we select values for the 'binorm.sca' model X01 <- spopmodel:::GetX0( svals = spopmodel:::StartVals( len = spopmodel::trammel_catch[["FL"]], mesh = spopmodel::trammel_catch[["MeshSize"]] ) )[["binorm.sca"]] # could try other starting values: somewhat arbitrary based on lf distribution # X01 <- c(75, 15.5, 140, 20.5, 0.62) ``` Display of starting values generated from average of modes by mesh size. Values are markedly different from those used by SB. ```{r display-sbX01} X01 ``` ## Model Fit Note: SB used default for net fishing strength, which assumes equal effort. ```{r model-fit} # use Millar's NetFit function to apply 'binorm.sca' model to data; SB chose # 'binorm.sca' for the sturgeon model; gear selectivity model with lowest # deviance is often the one chosen fit0 <- spopmodel:::NetFit( Data = sbdata, Meshsize = msize, x0 = X00, rtype = "binorm.sca" ) # same model but now using different starting values + relative power of 1, 1, 2 fit1 <- spopmodel:::NetFit( Data = sbdata, Meshsize = msize, x0 = X01, rtype = "binorm.sca", rel.power = rpwr ) # interestingly, below does not work when including un-equal effort, well it # works but results are head scratching (e.g., large negative deviance) fit0_rpwr <- spopmodel:::NetFit( Data = sbdata, Meshsize = msize, x0 = X00, rtype = "binorm.sca", rel.power = rpwr ) ``` ```{r rel-retention} # get relative retention from model fit; will standardize in next chunk rr0 <- spopmodel::RelativeRetention(fit0, standardize = FALSE) rr1 <- spopmodel::RelativeRetention(fit1, standardize = FALSE) ``` ```{r rr-standardized} # for standardization summing relative retention by length bin & then dividing # by max value (method used by SB) rr0_tot <- rowSums(rr0[["Data"]][2:4]) rr1_tot <- rowSums(rr1[["Data"]][2:4]) # to compare relative retention values using different arguments supplied to # NetFit() rr0_stand <- rr0_tot / max(rr0_tot) rr1_stand <- rr1_tot / max(rr1_tot) ``` ```{r plot-rel-retention} # for x-values commonly used for line plotting xx <- rr0[["Data"]][["FL"]] # for line size & colors lwd <- 4L col0 <- adjustcolor(col = "steelblue", alpha.f = 0.5) col1 <- adjustcolor(col = "orange2", alpha.f = 0.5) plot( x = xx, y = seq(from = 0, to = 1, length.out = 34), type = "n", xlab = "FL bin", ylab = "Relative retention" ) lines( x = xx, y = rr0_stand, col = col0, lwd = lwd ) lines( x = xx, y = rr1_stand, col = col1, lwd = lwd ) legend( x = max(xx), y = 1.15, legend = c("SB", "Alt"), col = c(col0, col1), lwd = lwd, xpd = TRUE, xjust = 1, ncol = 2, bty = "n" ) ``` Now adjust catch using relative retention values, and then plot. Grey line is raw length frequency distribution (i.e., no gear selectivity applied). ```{r plot-adj-catch} colNoAdj <- adjustcolor(col = "grey50", alpha.f = 0.5) plot( x = range(xx), y = c(0, 212), type = "n", xlab = "FL bin", ylab = "Count" ) lines( x = xx, y = rowSums(rr0[["Freq"]] / rr0_stand), col = col0, lwd = lwd ) lines( x = xx, y = rowSums(rr1[["Freq"]] / rr1_stand), col = col1, lwd = lwd ) lines( x = xx, y = rowSums(sbdata[2:4]), col = colNoAdj, lwd = lwd ) legend( x = max(xx), y = 245, legend = c("SB", "Alt", "NoAdj"), col = c(col0, col1, colNoAdj), lwd = lwd, xpd = TRUE, xjust = 1, ncol = 3, bty = "n" ) ``` --- CDFW Sportfish `r Sys.Date()` <file_sep>--- title: "White Sturgeon Harvest Rate Estimates" author: "CDFW" date: '' output: pdf_document: df_print: kable fig_caption: yes keep_tex: no fig_height: 5 fig_width: 6 html_document: fig_caption: yes keep_md: no html_notebook: default md_document: variant: markdown_github github_document: default header-includes: \usepackage{float} geometry: margin=0.5in fontsize: 10pt --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, warning = FALSE, fig.pos = "H") knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics/") ``` ```{r libraries} library(ggplot2) library(reshape2) library(knitr) library(rmarkdown) ``` ```{r data} AnglerTagReturn <- readRDS(file = "data/tagging/AnglerTagReturn.rds") SturgeonAll <- readRDS(file = "data/tagging/SturgeonAll.rds") SlotChanges <- read.csv(file = "data/SlotChanges.csv", header = TRUE) ``` ```{r source-files} source(file = "source/source_stu_hr.R") source(file = "source/source_stu_mark-recap.R") source(file = "source/functions_global_general.R") source(file = "source/functions_global_record_count.R") source(file = "source/functions_global_data_subset.R") ``` ```{r harvest-rate} wst_hr_list <- GetStuHrEst(LenCat %in% "leg", RelYear >= 1998, TagNum != "") estimate_years <- paste0(wst_hr_list$HR$Year, collapse = ", ") # below are other variables for use in plotting ******************************** # melting data for scatter plots and barplots of HR.All vs HR.$ rates hr_melt <- reshape2::melt( data = wst_hr_list$HR[, 1:6], id.vars = c("Year", "HR.All") ) # variables used in plotting (scatterplot) year_range <- range(hr_melt$Year) x_breaks <- seq(from = year_range[1], to = year_range[2], by = 2) strip_labs <- c( HR.All = "Harvest rate", HR.20 = "$20", HR.50 = "$50", HR.100 = "$100" ) # for making point red color of the most current (& preliminary) estimate row_max_year <- which.max(wst_hr_list$HR$Year) mark_prelim_point <- c(rep("black", row_max_year - 1), "red") # for scaling x axis x_axis_scale <- scale_x_continuous(breaks = x_breaks, expand = c(0.02, 0)) ``` ##Introduction Simply, we calculate harvest rate as number angler tag returns (returns) divided by number of tags released (releases). However, we implement some constraints on both data streams. We typically are interested in estimates for a particular subset of the population (for example, legal sized fish). Thus, we would restrict release data to a specific size range (e.g., legal size when tagged). Likewise, with tag returns using only tag returns from fish within the specified size range. For returns, we've historically used only 'first-year' returns, or returns where date of capture was within 365 days of release (tag specific). This allows for calculating harvest rate within a single year and mitigates bias due to natural mortality. ##Tag Releases (Marks) Below are number of tags released (since 1998) by reward value and total (`All`, Table 1). For this purpose, we count only fish legal-sized at time of tagging (Table 2). Ideally, we strive to release reward values in equal proportions, but when subsetting on a particular size range it's not always possible. Beginning in 1998, we released tags in $20, $50, and $100 denominations. In 2015, we changed demoniations to $50, $100, and $150. ```{r releases} # display number of tags released in tabular format kable( wst_hr_list$Releases, format = "pandoc", caption = "Count of released tags per year" ) # testing # write.csv(x = wst_hr_list$Releases, "analyses/HarvestRate/Releases.csv") ``` ```{r returns, eval=FALSE} # display number of angler tag returns in tabular format kable(wst_hr_list$Returns, format = "pandoc") ``` ```{r release-plot, eval=FALSE} # display plot of returns and releases ggplot() + # geom_bar( # mapping = aes(x = Year, y = All), # data = wst_hr_list$Releases, # stat = "identity" # ) + geom_bar( mapping = aes(x = Year, y = All), data = wst_hr_list$Returns, stat = "identity", fill = "red" , width = 0.5 ) ``` ##Harvest Rate Estimates (annual) Below are harvest rate estimates (${\mu}$; Ricker 1975) for White Sturgeon for years `r estimate_years`. We estimate harvest rate using data from our mark-rapture (tagging) study ([here for more info](https://www.wildlife.ca.gov/Conservation/Delta/Sturgeon-Study)). Estimates herein consider White Sturgeon **legal-sized** at the time of tagging (Table 2). $\Large{\mu = \frac{R_1}{M}}$ where $R_1$ = angler tag returns within 1 year of tagging $M$ = number of White Sturgeon tagged (marked) within size range (in this case legal-size) Here we estimate harvest rates for each reward value separately and collectively (`All`). We provide 95% confidence limits ($CL_{0.95}$; Ricker 1975, Appendix II) for each annual estimate. ($CL_{0.95}$ potentially will be large given small `M`, for example see 2016.) $\Large{CL_{0.95}=\frac{R_1+1.92\pm1.960\sqrt{R_1 + 1.0}}{M}}$ **Disclaimer**: analytics herein are subject to change pending future data and data QAQC. Contact <EMAIL> for more information. ```{r table1} slot_table <- SlotChanges[, c(1:2, 4:6)] slot_table$MaxLen[is.infinite(slot_table$MaxLen)] <- NA slot_table$MaxYear[which.max(slot_table$MaxYear)] <- "present" # colnames(slot_table) <- c("From", "To", "Min (cm)", "Max (cm)", "Length Type") kable( slot_table, format = "pandoc", row.names = FALSE, caption = "Period (years) of legal-sized (length) limits for White Sturgeon", align = 'c', col.names = c("From", "To", "Min (cm)", "Max (cm)", "Length Type") ) # clean up rm(slot_table) ``` Annual harvest rate for White Sturgeon legal-sized at time of tagging. Numbers at right of point indicate number of tag returns used in calculation of harvest rate. Red dot indicates value may change with futher data (i.e., angler tag returns). Error bars indicate lower and upper $CL_{0.95}$. ```{r HarvRatePlot, fig.width=8, fig.cap="Annual harvest rate for White Sturgeon legal-sized at time of tagging. Numbers at right of point indicate number of tag returns used in calculation of harvest rate.", fig.pos="H"} # using HR.All (the convential method) ggplot(data = wst_hr_list$HR, mapping = aes(x = Year, y = HR.All)) + geom_errorbar(mapping = aes(ymin = LCL.All, ymax = UCL.All), width = 0.15) + geom_point(shape = 21, fill = mark_prelim_point, colour = "white", size = 3) + x_axis_scale + geom_text( mapping = aes(x = Year, y = wst_hr_list$HR$HR.All, label = All), data = wst_hr_list$Returns, nudge_x = 0.30 ) + labs(y = "Harvest rate") ``` ##Harvest Rate Estimates (annual by reward and all) Annual harvest rate for White Sturgeon legal-sized at time of tagging using all tag denominations and by each reward value. For ease of display, $CL_{0.95}$ not shown. ```{r PlotByVal, fig.width=7, fig.cap="Annual harvest rate for White Sturgeon legal-sized at time of tagging using all tag denominations and by each reward value.", fig.pos="H"} # offset overlapping points pd <- position_dodge(width = 0.8) # works but need to work on colors; factor(as.numeric(variable)) needed to keep # order as 20, 50, 100, All ggplot() + geom_bar( mapping = aes(x = Year, y = HR.All, fill = "5"), data = wst_hr_list$HR[, 1:2], stat = "identity" ) + geom_bar( mapping = aes(x = Year, y = value, fill = factor(as.numeric(variable))), data = hr_melt, position = pd, stat = "identity", alpha = 3/5 ) + x_axis_scale + scale_fill_manual( "Type", values = c( '1' = "red", '2' = "green", '3' = "blue", '4' = "orange", '5' = "black" ), labels = c( '1' = "$20", '2' = "$50", '3' = "$100", '4' = "$150", '5' = "All" ) ) + scale_y_continuous(expand = c(0.01, 0)) ``` ```{r table3} # tabular representation of annual harvest rates knitr::kable( wst_hr_list$HR[, 1:6], format = "pandoc", caption = "Harvest rates " ) ``` ##Harvest Rate Comparisons Comparing harvest rate (`HR.All`) to harvest rate by dollar value ($20, $50, and $100). Note: not enough data yet to include $150 tags. Dashed line is slope = 1, intercept = 0. ```{r hr-correlation} hr_melt <- subset(hr_melt, subset = variable != "HR.150") hr_melt$variable <- droplevels(hr_melt$variable) # set up dataframe of correlation coeff and p values cor_list <- sapply(X = split(hr_melt, hr_melt$variable), FUN = function(x) { # get correlation results res <- cor.test(x$HR.All, x$value) # select only correlation and p-value for output cor_est <- round(as.numeric(res["estimate"]), 2) p_value <- round(as.numeric(res["p.value"]), 3) # variables for plotting cor and p-vale on plot x_val <- min(hr_melt$HR.All, na.rm = TRUE) y_val <- max(hr_melt$value, na.rm = TRUE) # function output data.frame(cor_est, p_value, x_val, y_val, row.names = 1) }, simplify = FALSE) cor_dat <- ListToDf(cor_list) colnames(cor_dat) <- c("Rate", "variable", "Cor", "Pval", "Xval", "Yval") cor_dat$variable <- factor( paste(cor_dat$Rate, cor_dat$variable, sep = "."), levels = c("HR.20", "HR.50", "HR.100") ) ``` ```{r ScatterMatrix, fig.asp=1.5, fig.cap="Scatterplot comparing harvest rate by value with harvest rate (all)", fig.pos="H"} # like this one better add r (corr coeff) ggplot(data = hr_melt, mapping = aes(x = HR.All, y = value)) + geom_abline(intercept = 0, slope = 1, linetype = 2, alpha = 4/5) + geom_point(size = 2, colour = "black", shape = 21, fill = "transparent") + geom_text( mapping = aes( x = Xval, y = Yval, label = paste0("r = ", Cor, "\n", "p = ", Pval) ), family = "mono", data = cor_dat, hjust= 0, vjust = 1 ) + facet_grid( facets = variable ~ ., labeller = labeller( variable = c(HR.20 = "$20", HR.50 = "$50", HR.100 = "$100") ) ) + labs(x = "Harvest rate", y = "Rate by value") ``` --- ran report: `r Sys.time()` CDFW - Sportfish Unit <file_sep> White Sturgeon Abundance Estimates  from Harvest and Harvest Rate ================ CDFW ### Background Herein are estimates of White Sturgeon abundance calculated using harvest (from Sturgeon Report Card) and harvest rate (from mark-recapture data). For more information and details regarding development of this method, please click [Abundance](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=43532). We estimate abundance directly for legal-sized White Sturgeon, which from 2007 to present is 117-168 cm TL (centimeters total length; though from 2013 to present the equivalent is measured in fork length: 102-152 cm FL). Using proportions of catch and ratios, we estimate abundance for both sub-legal and over-legal sized White Sturgeon. Note: any previous estimates have been updated using most-current (i.e., from 2018-04-09) Report Card and mark-recapture data. ### Assigning Length Category We assigned White Sturgeon --- caught during our mark-recapture field work --- to a length category of either 'sub' (sub-legal), 'leg' (legal), or 'ovr' (over-legal) based on measured length (total or fork) and data in the table below. The slot limit was instituted in 1990, thus sub-legal fish are below the slot limit and over-legal fish are above the slot limit. For this purpose, we use data in the last two rows of the table below. | From Year | To Year | Species | Min Length (cm) | Max Length (cm) | Length Type | |:---------:|:-------:|:-------:|:---------------:|:---------------:|:-----------:| | 1954 | 1989 | W,G | 102 | NA | total | | 1990 | 1990 | W,G | 107 | 183 | total | | 1991 | 1991 | W,G | 112 | 183 | total | | 1992 | 2006 | W,G | 117 | 183 | total | | 2007 | 2012 | W | 117 | 168 | total | | 2013 | 2018 | W | 102 | 152 | fork | For this purpose, we did not model length frequency distributions (as in [Gingras and DuBois 2015](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=114809)). Proportions and ratios were derived from non-modeled (i.e., straight) catch (see table below, where 'N' denotes count and 'P' denotes proportion). "SubToLeg" and "OvrToLeg" are ratios derived from the appropriate proportions. Also, per methodology described in [Gingras and DuBois 2015](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=114809), we limited White Sturgeon length to ≥ 85 cm TL. For example, in 2007 393 White Sturgeon were categorized as "sub," with n=34 &lt; 85 cm TL. This yields NSub = 359. Notes: 1. NAll = NSub + NLeg + NOvr 2. NUnk = number unknown 3. Proportions (P) calculated as N(Sub or Leg or Ovr) / NAll | Year | NSub| NLeg| NOvr| NAll| NUnk| PSub| PLeg| POvr| SubToLeg| OvrToLeg| |:-----|-----:|-----:|-----:|-----:|-----:|----------:|----------:|----------:|----------:|----------:| | 2006 | 300| 423| 22| 745| 0| 0.4026846| 0.5677852| 0.0295302| 0.7092199| 0.0520095| | 2007 | 359| 398| 66| 823| 0| 0.4362090| 0.4835966| 0.0801944| 0.9020101| 0.1658291| | 2008 | 206| 331| 62| 599| 0| 0.3439065| 0.5525876| 0.1035058| 0.6223565| 0.1873112| | 2009 | 197| 293| 27| 517| 0| 0.3810445| 0.5667311| 0.0522244| 0.6723549| 0.0921502| | 2010 | 109| 193| 41| 343| 0| 0.3177843| 0.5626822| 0.1195335| 0.5647668| 0.2124352| | 2011 | 251| 303| 58| 612| 0| 0.4101307| 0.4950980| 0.0947712| 0.8283828| 0.1914191| | 2012 | 145| 100| 28| 273| 0| 0.5311355| 0.3663004| 0.1025641| 1.4500000| 0.2800000| | 2013 | 90| 57| 23| 170| 0| 0.5294118| 0.3352941| 0.1352941| 1.5789474| 0.4035088| | 2014 | 300| 120| 24| 444| 0| 0.6756757| 0.2702703| 0.0540541| 2.5000000| 0.2000000| | 2015 | 153| 113| 19| 285| 0| 0.5368421| 0.3964912| 0.0666667| 1.3539823| 0.1681416| | 2016 | 56| 37| 7| 100| 0| 0.5600000| 0.3700000| 0.0700000| 1.5135135| 0.1891892| | 2017 | 199| 156| 37| 392| 0| 0.5076531| 0.3979592| 0.0943878| 1.2756410| 0.2371795| ### Harvest Since 2007, anglers fishing for sturgeon in California waters are required to report catch on a Sturgeon Fishing Report Card (Card). Annually, the Card provides --- among other information --- numbers of White Sturgeon kept (or harvest, *H*). Per developed methodology, we count harvest for three periods (start, middle, end) based on beginning and ending dates of our field season (August-October). The rationale is to use harvest more in line with harvest rate (the estimates of which use first-year tag returns). Because we have found harvest does not vary much by period (see table below), for abundance estimates we used harvest from the 'start' period. Notes: 1. Each period has a 'from' and 'to' date (denoting one year) within which harvest is counted. 2. Harvest for 2006 not over a complete year, as Card not instituted until 2007. 3. Harvest for 2017 is preliminary, as data from 2018 Card not available until early 2019. 4. Harvest data are in BDSturgeonReportCard database (2007-2011) & ALDS (on-line) database (2012-present) | Year | Period | From | To | Harvest| |:-----|:-------|:-----------|:-----------|--------:| | 2006 | Start | 2006-08-02 | 2007-08-01 | 741| | 2007 | Start | 2007-08-03 | 2008-08-01 | 1,935| | 2008 | Start | 2008-08-11 | 2009-08-10 | 1,921| | 2009 | Start | 2009-08-10 | 2010-08-09 | 1,430| | 2010 | Start | 2010-08-04 | 2011-08-03 | 1,869| | 2011 | Start | 2011-08-01 | 2012-07-30 | 1,802| | 2012 | Start | 2012-08-01 | 2013-07-31 | 1,923| | 2013 | Start | 2013-08-07 | 2014-08-06 | 2,291| | 2014 | Start | 2014-08-06 | 2015-08-05 | 2,449| | 2015 | Start | 2015-08-06 | 2016-08-04 | 2,134| | 2016 | Start | 2016-09-14 | 2017-09-13 | 2,462| | 2017 | Start | 2017-08-10 | 2018-08-09 | 1,444| | 2006 | Mid | 2006-09-16 | 2007-09-15 | 787| | 2007 | Mid | 2007-09-14 | 2008-09-12 | 1,922| | 2008 | Mid | 2008-09-20 | 2009-09-19 | 1,934| | 2009 | Mid | 2009-09-18 | 2010-09-17 | 1,431| | 2010 | Mid | 2010-09-15 | 2011-09-14 | 1,863| | 2011 | Mid | 2011-09-13 | 2012-09-11 | 1,794| | 2012 | Mid | 2012-09-15 | 2013-09-14 | 1,930| | 2013 | Mid | 2013-09-15 | 2014-09-14 | 2,288| | 2014 | Mid | 2014-09-14 | 2015-09-13 | 2,461| | 2015 | Mid | 2015-09-14 | 2016-09-12 | 2,146| | 2016 | Mid | 2016-10-06 | 2017-10-05 | 2,430| | 2017 | Mid | 2017-09-18 | 2018-09-17 | 1,386| | 2006 | End | 2006-10-30 | 2007-10-29 | 969| | 2007 | End | 2007-10-25 | 2008-10-23 | 1,833| | 2008 | End | 2008-10-29 | 2009-10-28 | 1,952| | 2009 | End | 2009-10-27 | 2010-10-26 | 1,395| | 2010 | End | 2010-10-27 | 2011-10-26 | 1,928| | 2011 | End | 2011-10-25 | 2012-10-23 | 1,747| | 2012 | End | 2012-10-30 | 2013-10-29 | 1,952| | 2013 | End | 2013-10-23 | 2014-10-22 | 2,266| | 2014 | End | 2014-10-22 | 2015-10-21 | 2,441| | 2015 | End | 2015-10-22 | 2016-10-20 | 2,286| | 2016 | End | 2016-10-27 | 2017-10-26 | 2,466| | 2017 | End | 2017-10-26 | 2018-10-25 | 1,135| ### Harvest Rate We estimate harvest rate ($\\hat{h}$) annually using angler tag returns (Ret or returns) and CDFW tag releases (Rel or releases). To minimize bias, we only use first-year tag returns (i.e., tagged fished caught within one year of release; denoted **<sub>*f*</sub> in equation below). Below are harvest rate estimates for White Sturgeon legal-sized when tagged. The returns and releases presented in the table are for this demographic. Period, dates (from & to), and harvest included in table for convenience. $\\hat{h} = \\frac{Ret\_f}{Rel}$ Notes: 1. Rate for 2006 provided for information only. 2. Rate for 2017 is preliminary and will change with future data (returns). 3. Returns (Ret) includes tags physically returned to us by angler and tag reported on Cards but not physically returned (Ret & Rel data are in BDSturgeonTagging database) 4. We release reward tags (current values: $50; $100; $150) but do not consider reward here (i.e., for the harvest rate estimate). See [Gingras and DuBois 2014](https://nrm.dfg.ca.gov/FileHandler.ashx?DocumentId=74460) for further information regarding bias in annual harvest rate estimates. | Year | Period | From | To | Harvest| Ret| Rel| Rate| |:-----|:-------|:-----------|:-----------|--------:|----:|----:|------:| | 2006 | Start | 2006-08-02 | 2007-08-01 | 741| 17| 420| 0.040| | 2007 | Start | 2007-08-03 | 2008-08-01 | 1,935| 13| 387| 0.034| | 2008 | Start | 2008-08-11 | 2009-08-10 | 1,921| 15| 329| 0.046| | 2009 | Start | 2009-08-10 | 2010-08-09 | 1,430| 10| 292| 0.034| | 2010 | Start | 2010-08-04 | 2011-08-03 | 1,869| 10| 192| 0.052| | 2011 | Start | 2011-08-01 | 2012-07-30 | 1,802| 16| 301| 0.053| | 2012 | Start | 2012-08-01 | 2013-07-31 | 1,923| 7| 100| 0.070| | 2013 | Start | 2013-08-07 | 2014-08-06 | 2,291| 3| 57| 0.053| | 2014 | Start | 2014-08-06 | 2015-08-05 | 2,449| 6| 120| 0.050| | 2015 | Start | 2015-08-06 | 2016-08-04 | 2,134| 8| 112| 0.071| | 2016 | Start | 2016-09-14 | 2017-09-13 | 2,462| 4| 37| 0.108| | 2017 | Start | 2017-08-10 | 2018-08-09 | 1,444| 7| 151| 0.046| ### Abundance Estimates Below are (alternative) abundance estimates ($\\hat{N}$) for White Sturgeon for the three length categories. Provided herewith are standard error (SE), Wald-type confidence intervals (CI), and log-normal confidence intervals (lower = LNLB, upper = LNUB). (Confidence interval algorithms provided courtesy of <NAME> & L. Mitchell of USFWS.) **Abundance equations** $\\hat{N}\_{leg} = \\frac{H}{\\hat{h}}$ $\\hat{N}\_{sub} = \\hat{N}\_{leg} \* SubToLeg$ $\\hat{N}\_{ovr} = \\hat{N}\_{leg} \* OvrToLeg$ **Standard error and variance** ${SE}({\\hat{N}\_{leg}}) = \\frac{H}{\\sqrt{\\hat{h}^{3} \* {Rel}}}$ ${VAR}({\\hat{N}\_{leg}}) = {SE}({\\hat{N}\_{leg}})^2$ ${SE}({\\hat{N}\_{sub}}) = \\sqrt{{VAR}({\\hat{N}\_{leg}}) \* SubToLeg}$ ${SE}({\\hat{N}\_{ovr}}) = \\sqrt{{VAR}({\\hat{N}\_{leg}}) \* OvrToLeg}$ **Wald-type confidence interval (CI)** ${CI}(\\hat{N}) = {\\pm}{Z} \* {SE}(\\hat{N})$ **Log-normal confidence intervals (lower & upper bounds)** ${LNLB}(\\hat{N}) = \\hat{N} \* exp({-Z} \* {\\frac{SE(\\hat{N})}{\\hat{N}}})$ ${LNUB}(\\hat{N}) = \\hat{N} \* exp({Z} \* {\\frac{SE(\\hat{N})}{\\hat{N}}})$ | Year | Category | N| SE| CI| LNLB| LNUB| |:-----|:---------|--------:|-------:|-------:|-------:|--------:| | 2007 | sub | 51,959| 15,173| 29,739| 29,315| 92,094| | 2008 | sub | 26,222| 8,582| 16,821| 13,806| 49,804| | 2009 | sub | 28,075| 10,827| 21,221| 13,184| 59,785| | 2010 | sub | 20,267| 8,528| 16,714| 8,884| 46,234| | 2011 | sub | 28,082| 7,714| 15,118| 16,392| 48,110| | 2012 | sub | 39,834| 12,503| 24,506| 21,531| 73,693| | 2013 | sub | 68,730| 31,579| 61,894| 27,928| 169,140| | 2014 | sub | 122,450| 31,616| 61,967| 73,821| 203,113| | 2015 | sub | 40,452| 12,291| 24,090| 22,300| 73,378| | 2016 | sub | 34,468| 14,009| 27,456| 15,541| 76,447| | 2017 | sub | NA| NA| NA| NA| NA| | 2007 | leg | 57,603| 15,976| 31,313| 33,448| 99,204| | 2008 | leg | 42,134| 10,879| 21,322| 25,401| 69,889| | 2009 | leg | 41,756| 13,204| 25,880| 22,467| 77,605| | 2010 | leg | 35,885| 11,348| 22,241| 19,308| 66,694| | 2011 | leg | 33,900| 8,475| 16,611| 20,768| 55,335| | 2012 | leg | 27,471| 10,383| 20,351| 13,097| 57,624| | 2013 | leg | 43,529| 25,131| 49,257| 14,039| 134,965| | 2014 | leg | 48,980| 19,996| 39,191| 22,005| 109,024| | 2015 | leg | 29,876| 10,563| 20,703| 14,941| 59,740| | 2016 | leg | 22,774| 11,387| 22,318| 8,547| 60,678| | 2017 | leg | NA| NA| NA| NA| NA| | 2007 | ovr | 9,552| 6,506| 12,751| 2,514| 36,295| | 2008 | ovr | 7,892| 4,708| 9,228| 2,451| 25,410| | 2009 | ovr | 3,848| 4,008| 7,856| 499| 29,644| | 2010 | ovr | 7,623| 5,230| 10,251| 1,987| 29,251| | 2011 | ovr | 6,489| 3,708| 7,267| 2,117| 19,887| | 2012 | ovr | 7,692| 5,494| 10,769| 1,897| 31,192| | 2013 | ovr | 17,564| 15,964| 31,289| 2,958| 104,300| | 2014 | ovr | 9,796| 8,942| 17,527| 1,637| 58,625| | 2015 | ovr | 5,023| 4,331| 8,489| 927| 27,222| | 2016 | ovr | 4,308| 4,953| 9,707| 453| 41,003| | 2017 | ovr | NA| NA| NA| NA| NA| Plot of abundance estimates with log-normal confidence intervals. Note: estimates for 2017 available ~2019. <img src="StuAltAbundance_files/figure-markdown_github-ascii_identifiers/graphics-1.png" alt="White Sturgeon abundance estimates from harvest and harvest rate with log-normal confidence intervals; note: separate y-axis for each category" /> <p class="caption"> White Sturgeon abundance estimates from harvest and harvest rate with log-normal confidence intervals; note: separate y-axis for each category </p> ------------------------------------------------------------------------ Report ran: 2018-04-09 11:36:42 End of report <file_sep># ****************************************************************************** # Created: 17-Mar-2016 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file creates all items associated with age frequency # distributions of white sturgeon collected during CDFW tagging # operations and then using age distributions to create catch curves # to estimate survival; note: not performed on green sturgeon because # tagging operations don't encounter many green sturgeon # ****************************************************************************** # TODO (<NAME>, 17-Mar-2016): # Background -------------------------------------------------------------- # we assign ages using age-length keys (alk) # (1) alk developed with data from mostly 1970s (can be found in WSTALKEY.xls) # (2) alk developed by USFWS who have aged sturgeon (some collected from CDFW # operations) starting in 2014 # we need to start first with a length frequency distribution # File Paths -------------------------------------------------------------- #data_import <- "C:/Data/jdubois/RDataConnections/Sturgeon" # Libraries and Source Files ---------------------------------------------- library(ggplot2) library(reshape) #library(reshape2) #library() source(file = "../../RDataConnections/Sturgeon/OtherData.R") source(file = "../../RDataConnections/Sturgeon/TaggingData.R") source(file = "../../RSourcedCode/methods_len_freq.R") source(file = "../../RSourcedCode/methods_age_freq.R") source(file = "Analysis-CatchCurve/source_stu_cc.R") #source(file = "source_stu_mark-recap.R") #source(file = "../../RSourcedCode/functions_len_freq.R") # Workspace Clean Up ------------------------------------------------------ #rm() # Variables --------------------------------------------------------------- # establish l-f breaks for WSTALKEY; note this alk uses TL not FL #wst_alkey_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) wst_alkey_breaks <- c(wst_alkey$Bins, Inf) # Length frequency -------------------------------------------------------- lf_wstalkey <- GetLenFreq( dat = SturgeonAll, colX = TL, by = "RelYear", breaks = wst_alkey_breaks, #seqBy = 5, intBins = TRUE, subset = Species %in% "White" & RelYear > 2005 ) # for now does include rescue fish of 2011 table( lf_wstalkey$Data$RelYear, lf_wstalkey$Data$Location, useNA = "ifany" ) # Age frequency ----------------------------------------------------------- af_wst <- GetAgeFreq(lf = lf_wstalkey$Freq, alk = wst_alkey) rowSums(af_wst[, -1]) data.frame( V1 = af_wst[, 1], n = round(rowSums(af_wst[, -1]), digits = 0), stringsAsFactors = FALSE ) af_wst_melt <- melt(af_wst, id.vars = "RelYear", variable_name = "Age") n_fish <- aggregate(value ~ RelYear, data = af_wst_melt, FUN = function(x) { round(sum(x), digits = 0) }) # Age frequency: plot ----------------------------------------------------- ggplot(data = af_wst_melt, mapping = aes(x = Age, y = value)) + geom_bar(stat = "identity") + facet_wrap(facets = ~RelYear, ncol = 2) # Catch curve ------------------------------------------------------------- ggplot(data = af_wst_melt, mapping = aes(x = Age, y = value)) + geom_point() + facet_wrap(facets = ~RelYear, ncol = 2, scales = "free_y") + scale_y_log10() lm(log10(value) ~ as.numeric(as.character(Age)), data = af_wst_melt) <file_sep>--- --- ```{r catch} # chunk splits catch by year for use in annual analytics; helpful & controls the # number of dataframes in global environment; will add list columns to `catch` # as needed catch <- Split( data = Card[["AnglerCatch"]], # subset = , vars = -Year, splitVars = Year ) # for desired data type catch$Year <- as.numeric(catch[["Year"]]) ``` <!-- numbers --> ```{r catch-wst} # splits by fate (kept or released) catch$WST <- lapply(catch[["Data"]], FUN = function(d) { s <- Split( data = d, subset = Species %in% "White", vars = Length, splitVars = Fate ) t(vapply(s[["Data"]], FUN = function(dd) { l <- dd[["Length"]] r <- is.na(l) | l == 0 q <- l > 0 & l <= 10 & !is.na(l) c(Meas = sum(!r), NotMeas = sum(r), Tot = length(l), QL = sum(q)) },FUN.VALUE = numeric(4L))) }) ``` ```{r catch-gst} catch$GST <- t(vapply(catch[["Data"]], FUN = function(d) { b <- d[["Species"]] %in% "Green" l <- d[b, "Length"] r <- is.na(l) | l == 0 q <- l > 0 & l <= 10 & !is.na(l) c(Meas = sum(!r), NotMeas = sum(r), Tot = length(l), QL = sum(q)) }, FUN.VALUE = numeric(4L))) ``` ```{r catch-unk} catch$Unk <- vapply(catch[["Data"]], FUN = function(d) { sum(d[["Species"]] %in% "Unk") }, FUN.VALUE = numeric(1L)) ``` <!-- length --> ```{r fl-quantiles} # calculates 25%, 50%, & 75% quantiles for length (fork length in cm); doing it # separately by species for ease of using in plots catch$GSTLenQuant <- t(vapply(catch[["Data"]], FUN = function(d) { p <- c(p25 = 0.25, p50 = 0.50, p75 = 0.75) b <- d[["Species"]] %in% "Green" o <- quantile( d[b, "FL_cm"], probs = p, na.rm = TRUE, names = FALSE ) names(o) <- names(p) o }, FUN.VALUE = numeric(3L))) catch$WSTrLenQuant <- t(vapply(catch[["Data"]], FUN = function(d) { p <- c(p25 = 0.25, p50 = 0.50, p75 = 0.75) b <- d[["Species"]] %in% "White" & d[["Fate"]] %in% "released" o <- quantile( d[b, "FL_cm"], probs = p, na.rm = TRUE, names = FALSE ) names(o) <- names(p) o }, FUN.VALUE = numeric(3L))) catch$WSTkLenQuant <- t(vapply(catch[["Data"]], FUN = function(d) { p <- c(p25 = 0.25, p50 = 0.50, p75 = 0.75) b <- d[["Species"]] %in% "White" & d[["Fate"]] %in% "kept" o <- quantile( d[b, "FL_cm"], probs = p, na.rm = TRUE, names = FALSE ) names(o) <- names(p) o }, FUN.VALUE = numeric(3L))) ``` ```{r fl-wstk, warning=FALSE} # TODO: for kept WST (09-Apr-2020) but may add for GST & WSTr catch$WSTkLenStats <- t(vapply(catch[["Data"]], FUN = function(d) { b <- d[["Species"]] %in% "White" & d[["Fate"]] %in% "kept" unlist(DescStat(d[b, "FL_cm"])) }, FUN.VALUE = numeric(7L))) ``` ```{r len-in-queston} catch$LenCheck <- t(vapply(catch[["Data"]], FUN = function(d) { p <- c("White", "Green") s <- factor(d[["Species"]], levels = p, exclude = "Unk") l <- split(d[["Length"]], f = s) vapply(l, FUN = function(x) { sum(x > 0 & x <= 10 & !is.na(x)) }, FUN.VALUE = numeric(1L)) }, FUN.VALUE = numeric(2L))) ``` <!-- length frequency --> ```{r len-freq} ``` ```{r plot-lf-test, eval=FALSE} # TODO: for now (13-Jun-2019) not going to use this plot but herein has # potential for creating a 'time series' of histograms, which might be useful # for observing trends or patterns with len-freq distributions; process herein # --- like most other chunks herein --- would benefit from a custom function or # functions written within sportfish package # source(file = "presentations/.base-par.R") par( # mar = c(5, 6, 1, 1), cex.axis = 1.5, cex.lab = 1.5, col.axis = "grey40", col.lab = "black", las = 1, bty = "n", # mgp = c(3, 0.75, 0), tcl = -0.3, lend = 2 ) # nf <- layout(mat = matrix(data = 1:12, nrow = 4, ncol = 3, byrow = TRUE)) nf <- layout( mat = matrix(data = 1:12, nrow = 1, ncol = 12, byrow = TRUE), widths = 1, heights = 1 ) # layout.show(nf) # Map(plot, freq$GST, xlab = "") # use xlim in hist() to get consistent x-axis over all years # 07-May-2019 max_den <- vapply(freq[["WSTr"]], FUN = function(x) { max(x[["density"]]) }, FUN.VALUE = numeric(1L), USE.NAMES = FALSE) par(oma = c(4, 5, 1, 1)) # lapply(freq[["WSTr"]], FUN = function(fd) { # # # par(mai = c(0.1, 0.1, 0.1, 0.1)) # # par(mgp = c(1, 0.5, 0)) # par(mar = c(0.1, 0.1, 0.1, 0.1), mgp = c(1, 0.5, 0)) # # # plot(fd, xlab = "", xaxt = "n") # # # do.call(rbind, fd) # # fd # # med <- fd$xstats()[["Med"]] # mult <- 1000 # # plot( # fd$density, # fd$mids, # type = "s", # yaxt = "n", # xaxt = "n", # # main = "2007", # xlim = c(0, max(max_den)), # panel.first = abline(h = med, col = 2), # # xlab = expression(paste("Density x", 1e-3)) # ) #, # # # list(Dens = range(fd$density), Mids = range(fd$mids)) # xtck <- axTicks(side = 1) # axis(side = 1, at = xtck[c(T, F)], labels = (xtck * mult)[c(T, F)]) # axis(side = 1, at = xtck, labels = NA) # mtext(text = "2007", side = 3, cex = 0.75) # # # xtck # }) test <- Map(function(fd, lbl, y) { # par(mai = c(0.1, 0.1, 0.1, 0.1)) # par(mgp = c(1, 0.5, 0)) par(mar = c(0.1, 0.1, 0.1, 0.1), mgp = c(1, 0.5, 0)) # plot(fd, xlab = "", xaxt = "n") # do.call(rbind, fd) # fd med <- fd$xstats()[["Med"]] mult <- 1000 tp <- "n" if (y) tp <- "s" plot( fd$density, fd$mids, type = "s", lwd = 1.5, col = "steelblue", yaxt = "n", xaxt = "n", # main = "2007", xlim = c(0, max(max_den)), # panel.first = abline(h = med, col = 2) panel.first = grid(lwd = 1000, col = "grey90") # xlab = expression(paste("Density x", 1e-3)) ) #, abline( h = med, col = rgb(red = 0.4, green = 0.1, blue = 0.1, alpha = 0.4), lwd =2 ) if (y) axis( side = 2, at = axTicks(side = 2), labels = axTicks(side = 2), col = "transparent", col.ticks = "black" ) # list(Dens = range(fd$density), Mids = range(fd$mids)) xtck <- axTicks(side = 1) axis( side = 1, at = xtck[c(T, F)], labels = (xtck * mult)[c(T, F)], col = "transparent", col.ticks = "black" ) axis( side = 1, at = xtck, labels = NA, col = "transparent", col.ticks = "black" ) mtext(text = lbl, side = 3, cex = 0.75) invisible(med) }, freq[["WSTr"]], names(freq[["WSTr"]]), c(T, rep(F, times = 11))) # par(mar = c(5.1, 4.1, 4.1, 2.1)) layout(mat = 1) mtext( text = expression(paste("Density x", 10^-4)), side = 1, adj = 0.5, padj = 0.25, line = 2.5 ) mtext(text = "Bins", side = 2, line = 4, las = 3) # freq$GST$`2007`$xstats()[["Med"]] # plot(freq$GST$`2007`, ylim = c(0, .1), xaxt = "n") # # par()$mgp # # plot(freq$WSTr$`2007`$density, freq$WSTr$`2007`$mids, type = "s") # abline(h = 100, col = 2) ``` <!-- per angler --> ```{r catch-per-angler} # chunk creats dataframe of WST recorded (either kept or released) per each # angler; also adds max recorded by angler catch$PerAngler <- lapply(catch[["Data"]], FUN = function(d) { aggregate( d[["Species"]], by = d["AnglerID"], FUN = function(x) sum(x %in% "White") ) }) catch$MaxWSTPerAngler <- vapply( catch[["PerAngler"]], FUN = function(d) max(d[["x"]]), FUN.VALUE = numeric(1L) ) ``` ```{r catch-max-gst-per-angler} # chunk creats dataframe of WST recorded (either kept or released) per each # angler; also adds max recorded by angler catch$MaxGSTPerAngler <- vapply(catch[["Data"]], FUN = function(d) { g <- aggregate( d[["Species"]], by = d["AnglerID"], FUN = function(x) sum(x %in% "Green") ) max(g[["x"]]) }, FUN.VALUE = numeric(1L)) ``` ```{r catch-per-angler-binned} # chunk creates table based on catch per angler bins by 1 (e.g., 1-2; 3-4) until # 14, then last bin is 15+ (can rescale if needed but this is good for now) catch$PerAnglerBinned <- t(vapply(catch[["PerAngler"]], FUN = function(d) { brks <- c(seq(from = 1, to = 15, by = 2), Inf) lbls <- paste(brks, brks + 1, sep = "-") lbls <- c(lbls[1:7], "15+") bins <- cut( d[["x"]], breaks = brks, labels = lbls, include.lowest = FALSE, right = FALSE ) table(bins) }, FUN.VALUE = numeric(8L))) ``` <!-- per month --> ```{r catch-per-month} # chunk adds catch-per-month to catch dataframe catch$PerMonth <- lapply(catch[["Data"]], FUN = function(d) { l <- sub(pattern = " ", replacement = 0, format(1:12)) # ng = not given m <- factor( d[["Month"]], levels = c(NA, l), labels = c("ng", l), exclude = NULL ) s <- factor(d[["Species"]], levels = c("White", "Green", "Unk")) mm <- split(m, f = s) vapply(mm, FUN = table, FUN.VALUE = numeric(13L)) }) ``` <!-- per month & location --> ```{r catch-table-mon-loc-wst} # creates a frequency table to catch max catch overall used to bin catch in next # step for producing heat map (15-Apr-2020) catch$TbMonLocWST <- lapply(catch[["Data"]], FUN = function(d, lvl = loc_lvls) { b <- d[["Species"]] %in% "White" #& # d[["Fate"]] %in% "released" m <- factor(d[b, "Month"], levels = c(paste0(0, 1:9), 10:12)) l <- factor(d[b, "LocCode"], levels = lvl, exclude = "unk") # to get frequency table(l, m, dnn = NULL) }) max_catch_mon_loc_wst <- vapply( catch[["TbMonLocWST"]], FUN = max, FUN.VALUE = numeric(1L) ) # ****************************************************************************** # possible programming for getting upper value for binning but not needed now # 15-Apr-2020 # any(nchar(max_catch_mon_loc_wst) > 3) # nchar(max_catch_mon_loc_wst) # if (!all(nchar(max_catch_mon_loc_wst) == 3)) { # stop("`max_catch_mon_loc_wst`", call. = FALSE) # } # ****************************************************************************** # for sequence in color breaks used in next chunk max_bin_mon_loc_wst <- max(ceiling(max_catch_mon_loc_wst / 100) * 100) ``` ```{r locs-year-round-wst} # locatation with year-round WST catch catch$LocsYrRndWST <- lapply(catch[["TbMonLocWST"]], FUN = function(d) { v <- rowSums(d > 0) b <- v %in% 12 sort(names(v[b])) }) # to check which locations appear every year # Reduce(f = intersect, x = catch[["LocsYrRndWST"]]) # sort(table(unlist(catch[["LocsYrRndWST"]])), decreasing = TRUE) ``` ```{r catch-month-loc-wst} # process # (1) subset by species (if White, then kept or released) # (2) factor months for proper ordering & inclusion on every year # (3) factor location code 1A, 1B, 1C from 2010 on, 1 not used after 2009 # (4) exclude "unk" from location, but include count per year # (5) because each line in catch data is a single fish, get frequency # per location & month, and then bin frequency into no more than 10 bins # (6) converting step 5 to dataframe might be cumbersome but it might be the # most convenient in terms of plotting heat map # (7) at any rate will need to create fields for bins, and then alpha for # transparency in rgb() - use steelblue color # (8) bin starting with 0, and then set 0 color to white or grey99 or... # (9) plot each year with location on y-axis & month on x-axis # table(Card[["AnglerCatch"]][c("LocCode", "Year")]) catch$MonthLocWST <- Map(f = function(r, y, maxBin = max_bin_mon_loc_wst) { # already done in previous chunk # b <- d[["Species"]] %in% "White" #& # # d[["Fate"]] %in% "released" # # m <- factor(d[b, "Month"], levels = c(paste0(0, 1:9), 10:12)) # l <- factor(d[b, "LocCode"], levels = lvl, exclude = "unk") # # # to get frequency # r <- table(l, m, dnn = NULL) # return(max(r)) r <- as.data.frame(r, stringsAsFactors = TRUE) r$X <- as.numeric(as.character(r[["Var2"]])) r$Y <- unclass(r[["Var1"]]) # bin frequency for color in plot brks <- seq(from = 0, to = maxBin, length.out = 9) r$bins <- cut(r[["Freq"]], breaks = brks, right = FALSE) r$clrs <- rgb( red = 0.27, green = 0.50, blue = 0.70, alpha = as.numeric(r[["bins"]]) / 10 ) # r$clrs[r[["Freq"]] %in% 0] <- "grey99" r$clrs[r[["Freq"]] %in% 0] <- rgb( red = 0.99, green = 0.54, blue = 0, alpha = 0.3 ) # clr_na <- rgb(red = 0.99, green = 0.54, blue = 0, alpha = 0.2) clr_na <- "grey75" if (y < 2010) r$clrs[r[["Var1"]] %in% paste0("01", LETTERS[1:3])] <- clr_na else r$clrs[r[["Var1"]] %in% "01"] <- clr_na r }, catch[["TbMonLocWST"]], catch[["Year"]]) # end Map ``` ```{r wst-month-loc-max-year} # gets maximum catch per year by location & month catch$WSTMonthLocMax <- t(vapply(catch[["MonthLocWST"]], FUN = function(d) { i <- which.max(d[["Freq"]]) m <- as.character(d[i, "Var2"]) l <- as.character(d[i, "Var1"]) lc <- as.integer(d[i, "Var1"]) list(Month = m, LocCode = l, LocNum = lc, Freq = d[i, "Freq"]) }, FUN.VALUE = as.list(1:4))) # for ease of extracting data (e.g., max frequency) catch$WSTMonthLocMax <- as.data.frame(catch$WSTMonthLocMax) catch$WSTMonthLocMax[] <- lapply(catch$WSTMonthLocMax, FUN = unlist) ``` <!-- per location by species --> ```{r catch-loc-species, warning=FALSE} # like tables 5-7 in old report: getting angler count & total catch per location # along with number measures & some length stats; might be a neater way to do # this but for now this should work (07-Apr-2020) # green sturgeon catch$LocGST <- lapply(catch[["Data"]], FUN = function(d, lvl = loc_lvls) { d$LocCodeF <- factor(d[["LocCode"]], levels = lvl) s <- Split( data = d, subset = Species %in% "Green", # vars = , splitVars = LocCodeF, drop = FALSE ) out <- vapply(s[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) n <- nrow(dd) l <- DescStat(dd[["FL_cm"]]) c( NumAnglers = a, TotalCatch = n, NumMeas = l[["N"]], MeanLen = l[["Avg"]], SDLen = sqrt(l[["Var"]]) ) }, FUN.VALUE = numeric(5L)) t(out) }) # white sturgeon kept catch$LocWSTk <- lapply(catch[["Data"]], FUN = function(d, lvl = loc_lvls) { d$LocCodeF <- factor(d[["LocCode"]], levels = lvl) s <- Split( data = d, subset = Species %in% "White" & Fate %in% "kept", # vars = , splitVars = LocCodeF, drop = FALSE ) out <- vapply(s[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) n <- nrow(dd) l <- DescStat(dd[["FL_cm"]]) c( NumAnglers = a, TotalCatch = n, NumMeas = l[["N"]], MeanLen = l[["Avg"]], SDLen = sqrt(l[["Var"]]) ) }, FUN.VALUE = numeric(5L)) t(out) }) # white sturgeon released catch$LocWSTr <- lapply(catch[["Data"]], FUN = function(d, lvl = loc_lvls) { d$LocCodeF <- factor(d[["LocCode"]], levels = lvl) s <- Split( data = d, subset = Species %in% "White" & Fate %in% "released", # vars = , splitVars = LocCodeF, drop = FALSE ) out <- vapply(s[["Data"]], FUN = function(dd) { a <- length(unique(dd[["AnglerID"]])) n <- nrow(dd) l <- DescStat(dd[["FL_cm"]]) c( NumAnglers = a, TotalCatch = n, NumMeas = l[["N"]], MeanLen = l[["Avg"]], SDLen = sqrt(l[["Var"]]) ) }, FUN.VALUE = numeric(5L)) t(out) }) ``` <!-- top 5 WST catch location --> ```{r catch-loc-wst} # provides a top 5 ranking by location of percent of total WST catch catch$LocWSTTop5 <- t(vapply(catch[["Data"]], FUN = function(d) { b <- d[["Species"]] %in% "White" # res <- sort(table(d[b, "LocCode"]), decreasing = TRUE)[1:5] res <- prop.table(table(d[b, "LocCode"])) res <- sort(res, decreasing = TRUE)[1:5] sprintf(fmt = "%s (%.0f)", names(res), res * 100) }, FUN.VALUE = character(5L))) ``` ```{r catch-loc-sorted, eval=FALSE} # an idea for output not run currently (09-Apr-2020) but used in previous # reports, may resurrect at some point catch_loc <- aggregate( formula = LocCode ~ Year, data = Card[["AnglerCatch"]], FUN = function(x) { r <- table(x, dnn = NULL) b <- r <= 50 res <- c(sort(r[!b], decreasing = TRUE), AOL = sum(r[b])) list( Count = res, PerTot = res / sum(res), NumAOL = sum(b), LocAOL = names(r)[b], TotCatch = sum(r) ) } ) ``` <!-- rewark disk field summaries --> ```{r catch-disc-check} catch$DiscFreq <- lapply(catch[["Data"]], FUN = function(d) { table(d[["CheckTag"]][, "Desc"]) }) ``` ```{r catch-disk-angler} lvls_tag_desc <- c( "goodTag", "missingPrefix", "prefixed-ST", "rewardOnly", "zipCodeOnly", "someDigits" ) catch$DiscFreqAngler <- lapply( catch[["Data"]], FUN = function(d, lvls = lvls_tag_desc) { b <- d[["CheckTag"]][, "Desc"] %in% lvls k <- factor(d[b, "CheckTag"][, "Desc"], levels = lvls) table(d[b, "AnglerID"], k, dnn = NULL) } ) catch$DiscSummary <- t(vapply(catch[["DiscFreqAngler"]], FUN = function(d) { c( nAnglers = dim(d)[[1]], colSums(d), nAngTwoPlusTags = sum(rowSums(d) > 1) ) }, FUN.VALUE = numeric(8L))) # clean up rm(lvls_tag_desc) ``` <file_sep>--- --- ```{r setup, include=FALSE} #knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics/") knitr::opts_knit$set(root.dir = "U:/SportFish/Staff Files/JDuBois/0_RProjects/SturgeonPopMetrics/") now <- Sys.Date() ``` ## Introduction <!-- Herein, we calculate White Sturgeon absolute abundance using CDFW mark-recaptured data. Also, <GREEN STURGEON??> --> ## Libraries We load the `sportfish` package, currently available on GitHub. For now (`r now`), this is the only package required. ```{r load-libraries} library(sportfish) # library(package) ``` ## Load Data We load all `.rds` files from directory `data/tagging`. To keep our workspace clean, we load these files into a new environment called `Tagging`. ```{r load-data} # the data directory for bay study data_dir <- "data/tagging" # list.files(path = data_dir, pattern = ".rds") Tagging <- new.env() ReadRDSFiles(fileDir = data_dir, envir = Tagging) notes <- readLines(file.path(data_dir, "data-log"), n = 2) notes <- paste0(notes[1], notes[2]) # clean up rm(data_dir) ``` **Note**: `r notes`. ## Variables Here we create some variables we'll use throughout this process. We create them here and now for convenience. ```{r variables} ``` ```{r split-tagging} # head(Tagging[["Sturgeon"]]) catch <- Split(data = Tagging[["Sturgeon"]], splitVars = RelYear) # for desired data type catch$RelYear <- as.numeric(catch[["RelYear"]]) ``` ## Tag (Mark) ```{r tag-count} # to get count of White Sturgeon disc-tagged by desired category # NLeg = legal sized at time of tagging # NSlt = within current slot (102-152 cm FL); may be variations due to # conversions & rounding # NRng = between 100 & 200 cm TL (range we typically disc tag) catch$TagCount <- t(vapply(catch[["Data"]], FUN = function(d) { b <- d[["Species"]] %in% "White" & d[["StuType"]] %in% "Tag" tl <- Filter(f = Negate(is.na), x = d[b, "TL"]) nall <- sum(b) nleg <- sum(d[b, "LenCat"] %in% "leg") nslt <- sum(d[b, "InSlot"], na.rm = TRUE) nrng <- sum(tl >= 100 & tl <= 200) c(NAll = nall, NLeg = nleg, NSlt = nslt, NRng = nrng) }, numeric(4L))) # end vapply ``` ## Catch ```{r catch-cutoff-mat} catch$CutoffMat <- CatchCutoffMatrix( relYear = unique(Tagging[["Sturgeon"]][["RelYear"]]), minLen = c(rep(102, length = 9), 107, 112, rep(117, length = 20)), maxLen = c(rep(NA, length = 9), rep(183, length = 10), rep(168, length = 12)), vb = GetVBGM(Linf = 261.2, K = 0.04027, t0 = -3.638) ) ``` ```{r length-count} catch$LenCount <- lapply(catch[["Data"]], FUN = function(d) { b <- d[["Species"]] %in% "White" y <- unique(d[["RelYear"]]) clc <- CatchLengthCutoff(catch[["CutoffMat"]], year = y) f <- clc[["CountCatch"]] f(l = d[b, "TL"]) }) # if what = rbind then perform column sums, if what = cbind perform row sums; # otherwise can use count_lens as a list to process catch per release year # do.call(what = cbind, args = catch[["LenCount"]]) ``` ```{r catch-c} # to get CC (i.e., `C` in MC / R) for each release (tagging) year; not sure if # removal of NA is needed at this point (05-Aug-2020) catch$CC <- lapply(catch[["RelYear"]], FUN = function(y) { o <- vapply(catch[["LenCount"]], FUN = function(x) { x[names(x) %in% as.character(y)] }, FUN.VALUE = numeric(1L)) # end vapply # Filter(f = Negate(is.na), x = o) o }) # end outer lapply ``` ## Recaptures ```{r recaps} # CountRecap # GetStuRecap # class(Tagging$TagRecaptures$Data$B4010) # CountRecap(recaps[["CrossTab"]], n = 10) # dim(recaps$GetMatrixData()) # list to define recapture type (rtype); minDAL is minimum days at large, where # 30 days ensures adequate mixing with non-tagged populations; can add other # items to the list as desired (05-Aug-2020) # defaults: species = 'w', lencat = NULL, minDAL = -1L rtype <- list( All = c(lencat = NULL, minDAL = -1L), Leg = c(lencat = 'l', minDAL = 30) ) # to get summary of recaps from raw data recap_summary <- lapply(rtype, FUN = function(...) { ApplyStuRecap(Tagging[["TagRecaptures"]][["Data"]], ...) }) # annual (release year) recap count by recapture year recaps <- lapply(recap_summary, FUN = function(r) { # to apply table() which gets count by recapture year mat <- r$GetMatrixData() lapply(catch[["RelYear"]], FUN = function(y) { b <- mat[, "RelY"] %in% y table(mat[b, "RecY"]) }) # end inner lapply }) # end out lapply ``` ## Petersen Estimates ```{r petersen-ests} # to calculate Petersen Estimates (abundance [N]) based on catch & recapture # collected with each tagging season & number of tags release per year; because # C is established based on what was legal at time of tagging, these PEs are for # legal-at-time-of-tagging sized fish (06-Aug-2020) catch$PetEst <- Map(f = function(m, cc, rr) { # cc <- Filter(f = Negate(is.na), x = cc) # to select recap for appropriate year related to catch b1 <- names(cc) %in% names(rr) # to remove same year (within season) value where C is NA (i.e., no annual # estimate made for same-year sampling) b2 <- !is.na(cc) # sets up vector of 0s to hold appropriate recapture value r <- vector(mode = "integer", length = length(cc)) r[b1] <- rr # to set up alpha a <- 0.05 # for the three variations on Petersen Estimate (pe) # (1) peA: N calculated for each year following sampling year # (2) peC: N calculated cumulatively for C & R # (3) peT: N calculated based on total (to date) C & R list( peA = PetersenEst(m, CC = cc[b2], RR = r[b2], alpha = a), peC = PetersenEst(m, CC = cumsum(cc[b2]), RR = cumsum(r[b2]), alpha = a), peT = PetersenEst(m, CC = sum(cc[b2]), RR = sum(r[b2]), alpha = a) ) }, m = catch[["TagCount"]][, "NLeg"], cc = catch[["CC"]], rr = recaps[["Leg"]]) # end Map (PetersenEst) ``` ```{r display-pe} catch[["PetEst"]] ``` --- CDFW, SportFish Unit `r Sys.time()` <file_sep># ****************************************************************************** # Created: 28-Mar-2016 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file calculates alternative abundance estimates for White # Sturgeon (WST) using harvest (from Card data) and harvest rate # estimate (from mark-recapture data). # # Two aspects of this process are as follows: # (1) Getting Card data for various period rather than by calendar year # (2) Getting harvest rate for legal-sized WST # ****************************************************************************** # Information ------------------------------------------------------------- # Steps provided herein calculate alternative abundance estimates of White # Sturgeon (WST; alternative to mark-recapture estimates per the Petersen method). # The alternative method uses harvest from Card data and harvest rate from # mark-recapture data. # Estimates are calculated directly for legal-sized WST (leg) & indirectly for # sub-legal WST (sub) and over-legal WST (ovr). The indirect approach uses # ratios of proportions of each category (sub, leg, ovr) from mark-recapture # (tagging) data collected (typically) August-October each year. Using tagging # data, we categorized each WST (as sub, leg, ovr) based on length at tagging. # Proportions for each category were calculated based on the total (sub + leg + # ovr) not including WST with no length (i.e., those that could not be placed # into a size category). NOTE: for this exercise, we have made no adjustment to # catch based on gear selectvity. Proportions of sub, leg, & ovr are based on # straight catch. # Libraries and Source Files ---------------------------------------------- library(ggplot2) #library(reshape2) # loads all Card Data (ALDS from 2012 to present & 2007-2011); loads all tagging # data of releases and angler tag returns - needed for reconciliaton process source(file = "../../RDataConnections/Sturgeon/CardData07.R", echo = TRUE) source(file = "../../RDataConnections/Sturgeon/TaggingData.R", echo = TRUE) source(file = "../../RDataConnections/Sturgeon/CardDataAlds.R", echo = TRUE) source(file = "../../RSourcedCode/functions_global_general.R") source(file = "Analysis-AltAbundance/source_alt_abundance.R") # Step 1: combine ALDS and archived data ---------------------------------- # this section combines the ALDS and archived (2007-2011) data card_alds <- subset( StuCardAll, select = -MonthF ) # adds Document (or Card) number - needed for reconciliation with tag return # data card_alds <- merge( card_alds, ReturnedCards[, c("LicenseReportID", "DocumentNumber")], by = "LicenseReportID" ) # adding date field for rbind()ing with 07 data card_alds$DateOfCapture <- as.POSIXct( paste( card_alds$ItemYear, card_alds$Month, card_alds$Day, sep = "-" ), format = "%Y-%m-%d" ) # subsetting & ordering for rbind()ing below card_alds <- card_alds[, c(11, 3, 12, 6, 9, 10, 7, 8)] card_arch <- subset( SturgeonsCards07, select = -c(SturgeonID, CorR) ) # set column names equal for rbind()ing colnames(card_arch) <- colnames(card_alds) card_all <- rbind( card_arch, card_alds ) # clean up rm(card_arch, card_alds) # Step 2: get needed stats for estimates ---------------------------------- # adding year field for convenience Effort$RelYear <- as.numeric(format(Effort$RelDate, "%Y")) # rescue locations from April 2011 which we don't want for this analysis drop_locations <- c("Fremont Weir", "Tisdale Bypass") # get start, mid, and end dates dates <- ApplyFunToDf( Effort, !(Location %in% drop_locations) & RelYear > 2005, splitVars = "RelYear", FUN = TaggingDates ) # get length category stats for White Sturgeon from 2006-present (added # 05-Apr-2016 total length cutoff in keeping with IEP article "Estimating Annual # Abundance of White Sturgeon 85-116 and ≥ 169 Centimeters Total Length") lc_stats <- ApplyFunToDf( SturgeonAll, Species %in% "White" & RelYear > 2005 & TL >= 85, splitVars = "RelYear", FUN = GetLcStats ) # clean up rm(drop_locations) # Step 3: calculate abundance estimates ----------------------------------- # calculate alternative abundance estimates for White Sturgeon from # 2007-present; output is a list so use GetAltAbundance() for cleaner display of # abundance estimates with CIs alt_abundance <- CalcAltAbundance( datHarvest = GetWstCount(datCard = card_all, dates = dates), datLcStats = lc_stats ) # tabular display of annual stats (e.g., harvest rate, tag returns) along with # abundance estimates with Wald-type CIs and log-normal based CIs GetAltAbundance(dat = alt_abundance) # save abundance for Analysis-AbundByAge (must be re-saved when data is updated # (i.e., ~ annually)) saveRDS( object = GetAltAbundance(dat = alt_abundance)$Abundance, file = "Analysis-AbundByAge/AltAbund.rds" ) # write.csv( # alt_abundance$HR, # file = "Analysis-AltAbundance/HRAll.csv" # ) # Plotting: abundance with confidence intervals --------------------------- # possilbe plotting option (change data source) # ggplot(data = abnd$Abundance, mapping = aes(x = Year, y = N)) + # geom_bar( # mapping = aes(fill = LenCat), # position = "dodge", # stat = "identity" # ) <file_sep>C:\Users\JaHobbs\OneDrive - California Department of Fish and Wildlife\IEP_Planning_Folder\Surveys\sportfish\sturgeon\SturgeonPopMetrics CDFW Sturgeon Population Estimates by <NAME> copied from this directory on 11/25/20 by <NAME> U:\SportFish\Staff Files\JDuBois\0_RProjects\SturgeonPopMetrics <file_sep># ****************************************************************************** # Created: 31-May-2017 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file contains code to calculate WST Petersen Abundance Estimates # as (M*C)/R. Code herein may eventually be moved to a .Rmd file for # ease of display and presentation on GitHub. # ****************************************************************************** # NOTE: to date (01-Jun-2017) we have not recaptured a WST from release years # 2012 or 2013 or 2015; number of tags released in these years was low, so that # may play into it # TODO (01-Jun-2017): # (2) for Recaps - decide on whether or not to include true within-season # recaptures (twsr) along with old # (3) for Recaps - subset on length category (LenCat) or InSlot at release # (4) figure out how to join C and R datasets according to proper year # load data --------------------------------------------------------------- SturgeonAll <- readRDS(file = "data/tagging/SturgeonAll.rds") # libraries and source files ---------------------------------------------- # library(package) source(file = "source/functions_pop_estimate.R") source(file = "source/source_recaptures.R") # variables: used throughout file ----------------------------------------- # section contains variable used within this file # von Bertalanffy growth curve parameters (from Kohlhorst 1980) vb_params <- list(Linf = 261.2, k = -0.04027, t0 = 3.638) # create von Bertalanffy matrix to be used in assessing number of sturgeon # captured that would have been legal sized in year Y given capture in Y+t, # where t >= 1 # can set arguments as desired or set useDefault to TRUE to get # data/WSTVonBertMatrix.csv WSTVonBertMatrix <- CreateVbMatrix( relYear = c(2016:2005, 2002:2001, 1998), minLen = 117, maxLen = c(rep(168, times = 10), rep(183, 5)), vbParams = vb_params ) # gets matrix in data/WSTVonBertMatrix.csv # WSTVonBertMatrix <- CreateVbMatrix(useDefault = TRUE) # assessing recapture data ------------------------------------------------ # likely inaccurate (partial tag 2486 recaptured in 2014 cannot be positively # matched to release tag) Recaps[Recaps$DAL > 6000, ] # removing tag RecTag 2486 - it was recaptured & only part of the tag number was # recorded or could be read; tag was recaptured in 2014 & tag 2486 was released # in 1968, making this a highly unlikely recap. So we remove this tag here. Recaps <- subset(Recaps, subset = !(RecTag %in% "2486")) # recaptures: cross-tab rel year x recap year ----------------------------- # subsetting DAL < 6000 removes the partial tag recovered in 2014 (tag 2486), # which matches with an impossible (given the length) 1968 release; might want # to think about removing this tag earlier in the process recap_xtab <- xtabs( ~ Rel.RelYear + RecYear, data = Recaps, subset = RecapType %in% c("old") ) # for convenience when displaying names(dimnames(recap_xtab)) <- c("Rel", "Rec") # dim(recap_xtab) # dimnames(recap_xtab) # recaptures: dataframe from cross-tab ------------------------------------ recap_long <- as.data.frame(recap_xtab, stringsAsFactors = FALSE) # to get recaptures per release year (rel or Rel) recap_long_split_rel <- split(recap_long, f = recap_long[["Rel"]]) # number of recaptures per release year with N & cutoff year (year in which we # are not including anymore Rs or Cs); nZero = maximum allowable consecutive 0 # (that is how many years will allow without a recap) -- adjust as needed; # alternatively you can set a fixed number of year with setN & then nZero # parameter is ignored lst_recap_count <- lapply(recap_long_split_rel, FUN = GetRecapCount, nZero = 2) # for better viewing do.call(rbind, lst_recap_count) vapply(lst_recap_count, FUN = function(x) x[["Value"]], FUN.VALUE = numeric(1L)) # clean up section # rm() # captures: calculating C in [M*C]/R -------------------------------------- # TODO: add coding for C (catch) values # create matrix of catch, where colums are RelYear in WSTVonBertMatrix mat_catch <- CatchMatrix( dat = SturgeonAll, len = TL, splitVar = RelYear, Species %in% "White" & !(RelYear %in% 1955), vbMatrix = WSTVonBertMatrix, params = vb_params ) # 12-May-2017: tested function & output is accurate; differences between these # outputs and those of the past (e.g., 2011) may be due in part to how I was # subsettig the data in previous years. Am comfortable now functions herein are # producing accurate results - <NAME> lst_catch <- apply(mat_catch[["CountMatrix"]], 2, FUN = GetFinalC, limitN = 5) # marks: getting number of tagged fish ------------------------------------ # TODO: create function to get M and then combine all 3 in (M*C)/R <file_sep># ****************************************************************************** # Created: 16-Mar-2016 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file creates all items associated with length frequency # distributions of sturgeon collected during CDFW tagging operations # ****************************************************************************** # TODO (J. DuBois, 17-Mar-2016): format wst l-f plot; try to move facet labels # to y2 axis allowing more room for data; continue to format theme in source # file # File Paths -------------------------------------------------------------- #data_import <- "C:/Data/jdubois/RDataConnections/Sturgeon" # Libraries and Source Files ---------------------------------------------- library(ggplot2) #library(reshape2) #library() source(file = "../../RDataConnections/Sturgeon/TaggingData.R") source(file = "../../RSourcedCode/methods_len_freq.R") source(file = "Analysis-LengthFreq/source_stu_lf.R") #source(file = "source_stu_mark-recap.R") #source(file = "../../RSourcedCode/functions_len_freq.R") # Workspace Clean Up ------------------------------------------------------ #rm() # Variables --------------------------------------------------------------- # FIO about length range and count sapply(X = split(SturgeonAll, SturgeonAll[, c("RelYear", "Species")], drop = TRUE), FUN = function(x) { range(x$FL, na.rm = TRUE) }, simplify = FALSE) # FIO with(data = SturgeonAll, expr = { length(FL[FL %in% c(145:149) & !is.na(FL) & RelYear %in% 2006 & Species %in% "White"]) }) # set min release year for l-f dist (tabular and plot) rel_year <- 2005 # set length breaks #wst_fl_breaks <- SeqBreaks(from = 35, to = 180, by = 5, includeInf = TRUE) #gst_fl_breaks <- SeqBreaks(from = 45, to = 180, by = 3, includeInf = TRUE) # other options for length breaks #wst_fl_breaks <- c(0, seq(from = 55, to = 180, by = 6), Inf) #wst_fl_breaks2 <- c(seq(from = 35, to = 200, by = 5)) #gst_fl_breaks <- c(seq(from = 45, to = 180, by = 3), 197) #wst_tl_breaks <- c(seq(from = 21, to = 186, by = 5), Inf) # WSTALKEY # Analytics: annual length frequency -------------------------------------- lf_wst <- GetLenFreq( dat = SturgeonAll, colX = FL, by = "RelYear", breaks = NULL, seqBy = 5, intBins = FALSE, subset = Species %in% "White" & RelYear > 2005 ) lf_wst$DescStats lf_gst <- GetLenFreq( dat = SturgeonAll, colX = FL, by = "RelYear", breaks = NULL, seqBy = 5, intBins = FALSE, subset = Species %in% "Green" & RelYear > 2005 ) lf_gst$DescStats # Plotting: white stureon length frequency -------------------------------- # converting to factor for fill(ing) in plot below lf_wst$Data$InSlot <- factor( lf_wst$Data$InSlot , levels = c(1, 0) ) # displaying tabular data FIO print(lf_wst$FreqFraction, digits = 4, quote = FALSE) lf_wst$MaxPercent # create plot (using fraction of total - POT) lf_wst_plot <- plot( lf = lf_wst, lens = FL, fillBar = InSlot, type = "POT", addMed = TRUE, addN = TRUE ) # formatting plot and arranging facets (RelYear) lf_wst_plot + facet_wrap(facets = ~RelYear, ncol = 2) + #, switch = "y" scale_fill_manual( "In Slot", values = c('1' = "black", '0' = "grey50"), labels = c('1' = 'Y', '0' = 'N') ) + xlab("Fork length (cm)") #+ #theme_stu_lf # Plotting: green stureon length frequency -------------------------------- # gst l-f likely not all that useful as we just don't catch many gst and catch # varies wildly from year-to-year # create gst length frequency plot lf_gst_plot <- plot( lf = lf_gst, lens = FL, fillBar = NULL, type = "POT", addMed = TRUE, addN = TRUE ) # formatting and facetting lf_gst_plot + facet_wrap(facets = ~RelYear, ncol = 2) + #, switch = "y" xlab("Fork length (cm)") #+ #theme_stu_lf <file_sep> ## Age-0 Recruitment annual number of age-0 fish (produced from the model based on potential number of eggs per year per female per age class) ## Recruitment period (in years) of successful age-classes (e.g., 5 denotes successful recruitment once every 5 years) ## Annual Survival Rate (ASR) annual survival rate for segment not affected by harvest; model assumes a constant rate for this segment; value usually calculated via catch curve or Chapman-Robson methods ## ASR Standard Error (or Deviation) some measure of variance on ASR ## Abundance absolute abundance estimates typically derived from mark-recapture and report card data ## Annual Harvest Rate for segment harvested annually and calculated using mark-recapture data, where recaptures are angler tag returns; value should be adjusted for non-response using appropriate methods ## Harvestable Ages ages affected by harvest; because harvest regulations are set on length, one must use some conversion between age and length; current regs allow harvest of 40-60 inches fork length (or roughly ages 10-15 given current age-at-length growth model) ## Fraction Females segment (or fraction) of population that is female ## Maturity fraction of mature females spawning annually ## Data age & length data that drives the model; for now this is CDFW-collected data from 2014-2016 ## Simulations the model is stochastic, so this sets the number of simulations or model iterations ## Confidence Interval sets the desired confidence interval (CI) for lambda (population growth rate); for now CIs based on sample quantiles ## Gear Selectivity ## Period <file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics") knitr::opts_chunk$set(echo = FALSE) ``` ```{r libraries, warning=FALSE, message=FALSE, echo=FALSE} # source(file = "~/RSourcedCode/methods_desc_stats.R") library(dplyr) ``` ```{r load-data, echo=FALSE} SturgeonAlds <- readRDS(file = "data/card/SturgeonAlds.rds") Sturgeon0711 <- readRDS(file = "data/card/Sturgeon0711.rds") RetCardsAlds <- readRDS(file = "data/card/RetCardsAlds.rds") PurCardsAlds <- readRDS(file = "data/card/PurCardsAlds.rds") count_alds <- nrow(SturgeonAlds) count_0711 <- nrow(Sturgeon0711) # summary(SturgeonAlds) # summary(Sturgeon0711) ``` ```{r somevars, echo=FALSE} col_names <- c( "Id", "Year", "Month", "LocCode", "Fate", "Length", "TagNum", "FL_cm", "TL_cm" ) ``` ```{r data-subset, echo=FALSE} # subset data on white stu & prepare for rbind()ing # usefule for seasonal summary Sturgeon0711$Month <- as.numeric(format(Sturgeon0711[["DateOfCapture"]], "%m")) arch_wst <- subset( Sturgeon0711, subset = Species %in% "White", select = c( CardNum, Year, Month, LocationCode, Fate, Length, TagNum, FL_cm, TL_cm ) ) colnames(arch_wst) <- col_names alds_wst <- subset( SturgeonAlds, subset = SturgeonType %in% "White", select = c( CustomerID, ItemYear, Month, LocCode, Fate, Length, RewardDisk, FL_cm, TL_cm ) ) colnames(alds_wst) <- col_names card <- rbind(arch_wst, alds_wst) rm(arch_wst, alds_wst) ``` Summary data about number of White Sturgeon kept and released each year. ```{r} catch <- aggregate( formula = Id ~ Year + Fate, data = card, FUN = length ) catch$Fate <- factor(catch$Fate, levels = c("kept", "released")) colnames(catch) <- c("Year", "Fate", "NumOfWst") anglers <- aggregate( formula = Id ~ Year, data = card, FUN = function(x) length(unique(x)) ) colnames(anglers) <- c("Year", "NumOfAnglers") as.data.frame(catch) as.data.frame(anglers) ``` Plot of data above. ```{r echo=FALSE} # plot(Id ~ Year, data = anglers) par(mar = c(3.5, 4, 1, 4) + 0.1, bty = "u") plot( x = anglers[["Year"]], y = anglers[["NumOfAnglers"]], type = "h", lwd = 10, lend = 2, col = "grey75", ylim = c(0, max(anglers[["NumOfAnglers"]])), ylab = "Number of anglers (x 1000)", xlab = NA, yaxt = "n", xaxt = "n" ) # range(anglers[["Id"]]) axis( side = 2, at = seq(0, 3000, 500), labels = format(seq(0, 3000, 500) / 1000), las = 1 ) par(new = TRUE) # catch <- catch[order(catch[["Year"]]), ] # points(Id ~ Year, data = catch, type = "b", subset = Fate %in% "kept", ylim = c(0, 6000)) # points(Id ~ Year, data = catch, type = "b", subset = Fate %in% "released", ylim = c(0, 6000)) bool <- catch[["Fate"]] %in% "released" plot( x = catch[["Year"]], y = catch[["NumOfWst"]], type = "n", # col = as.numeric(catch[["Fate"]]), # lty = as.numeric(catch[["Fate"]]), axes = FALSE, ylab = NA, xlab = NA ) # range(catch[["Id"]]) pts <- lapply(c("kept", "released"), FUN = function(x) { color <- c(kept = "steelblue", released = "darkorange") points( formula = NumOfWst ~ Year, data = catch, subset = Fate %in% x, type = "b", col = color[x], cex = 1.1 ) }) axis( side = 4, at = seq(1400, 6200, 700), labels = ( seq(1400, 6200, 700)) / 100, las = 2 # lwd.ticks = , # hadj = ) mtext(text = "Catch (x 100)", side = 4, line = 2.5) mtext(text = "Year", side = 1, line = 2) axis( side = 1, at = (2007:2017)[(2007:2017) %% 2 == 1], labels = (2007:2017)[(2007:2017) %% 2 == 1], tck = -0.03, padj = -0.5 # las = 2 # lwd.ticks = 5 # hadj = ) axis( side = 1, at = 2007:2017, labels = NA, tck = -0.01 ) legend(#x = 2009, #y = 6300, "topleft", # fill = c("grey75", "steelblue"), col = c("grey75", "steelblue", "darkorange"), pch = c(15, 1, 1), legend = c("anglers", "kept", "released"), pt.cex = 1.5, ncol = 3, box.col = "grey90", border = NA) ``` Some angler demographics...these data only available from 2012 to present. Count of cards issued (or purchased beginning 2013) by year and gender along with median age. ```{r angler-info, echo=FALSE} angler_info <- PurCardsAlds %>% group_by(ItemYear, Gender = factor(Gender, levels = c('M', 'F'))) %>% filter(!duplicated(CustomerID) & ItemYear < 2018) %>% summarise( Count = n(), MeadianAge = median(2018 - BirthYear) ) as.data.frame(angler_info) ``` Fraction of top 5 counties by year. County = where angler resides. Fractions don't vary much annually and majority of sturgeon anglers is local (to the Delta - Estuary). ```{r county-info, echo=FALSE} # years <- setNames(object = 2012:2017, nm = 2012:2017) county_info <- vapply(years, FUN = function(y) { d <- PurCardsAlds[PurCardsAlds[["ItemYear"]] %in% y, ] d <- d[!duplicated(d[["CustomerID"]]), ] county <- prop.table(table(d[["County"]], useNA = "ifany")) sort(county, decreasing = TRUE)[1:5] }, FUN.VALUE = numeric(5L)) t(county_info) ``` More anglers now appear to be submitting on-line compared to when ALDS came on-line in 2012. IS = Internet submission (by angler) CC = Control Center (by CDFW staff) ```{r alds-returns, echo=FALSE} # head(RetCardsAlds) # # table(RetCardsAlds[["Code"]], useNA = "ifany") # table(RetCardsAlds[["CustomerSourceCode"]], useNA = "ifany") ret_cards_alds <- RetCardsAlds %>% filter(ItemYear < 2018) %>% group_by(ItemYear, CustomerSourceCode) %>% summarise(Count = n()) as.data.frame(ret_cards_alds) ``` <file_sep># ****************************************************************************** # Created: 04-May-2016 # Author: <NAME> # Contact: <EMAIL> # Purpose: This file is for demonstrating how previous biologists developed the # age-length key for WST (as in WSTALKEY.xls). I found data that looks # to be that used to develop this key and herein will explore this data # to confirm or dismiss my hunch. # ****************************************************************************** # load libraries library(ggplot2) library(dplyr) # Load data --------------------------------------------------------------- # get age-length (al) data from yesteryear (saved as a .txt file because saving # to .csv was raising some error for reasons unknown) old_al_data <- read.table( file = "../1_NonDbData/WstAgeLenData.txt", header = TRUE, sep = "\t", # colClasses = c( # "character", "integer", "POSIXct", "double", # "double", rep("integer", 7), "double", # "integer" # ), col.names = c( "ID", "Species", "Date", "FL", "TL", "Sex", "CapMethod", "Location", "Age", "YearClass", "Check", "Age_1", "TLen", "NewAge" ), stringsAsFactors = FALSE ) # Checking some data ------------------------------------------------------ str(old_al_data) range(old_al_data$Date) table(old_al_data$Loc, useNA = "ifany") # change variable as needed # fields are the same identical(old_al_data$Age, old_al_data$Age_1) identical(old_al_data$TL, old_al_data$TLen) # fields NOT the same identical(old_al_data$Age, old_al_data$NewAge) # using age to develop al key - need to combine all fish > age-22 to age-22 # (this is per design of WSTALKEY) old_al_data$Age[old_al_data$Age > 22] <- 22 # check - should now be FALSE identical(old_al_data$Age, old_al_data$Age_1) # trying conversion to observe effect # old_al_data$TL <- round(old_al_data$TL, digits = 0) # old_al_data$TL <- as.integer(old_al_data$TL) # old_al_data$TL <- old_al_data$TL - 0.01 # Create al key with extant (1973-1976) data ------------------------------ wst_alkey_check <- MakeALKey( dat = old_al_data, len = TL, age = Age, lenBreaks = wst_alkey_breaks, breakLabs = wst_alkey_breaks[-35], dia = FALSE ) # convert wst_alk_usfws bins to integer for analytics to follow wst_alkey_check$Bins <- as.integer(as.character(wst_alkey_check$Bins)) # compare with WSTALKEY (tab 'A' in WSTALKEY.xls) - as of now still yielding # FALSE even with rounding to appropriate number of digits identical( x = wst_alkey, y = round(wst_alkey_check, 4) ) wst_alkey - round(wst_alkey_check, 4) # Analysis of ALKEY differences: bin by bin ------------------------------- # for looping through sapply below rows <- 1:nrow(wst_alkey) # to compare each line (bin) of wst_alkey with the newly-created alkey lst_diff <- sapply(X = rows, FUN = function(x) { res <- rbind( wst_alkey[x, ], round(wst_alkey_check[x, ], digits = 4) ) res <- rbind(res, res[1, ] - res[2, ]) list( Data = res, Good = all(res[1, ] - res[2, ] == 0) ) }, simplify = FALSE) # ideally would yield number equivalent to number of bins (n=34) but only yields # 20, so 14 bins of newly-created alkey to not "align" with extant WSTALKEY sum( sapply(X = rows, FUN = function(x) { lst_diff[[x]]$Good }) ) # Mean length at age ------------------------------------------------------ mean_len_age <- old_al_data %>% group_by(Age) %>% select(Age, TL) %>% do(GetDescStats(.$TL)) # More analysis of differences -------------------------------------------- old_al_data[old_al_data$TLen >=176 & old_al_data$TLen <= 180.3000, ] old_al_data[old_al_data$TLen >=76 & old_al_data$TLen <= 80, ] old_al_data[old_al_data$TLen >=181, ] test <- old_al_data[old_al_data$TLen >=101 & old_al_data$TLen <= 105, ] old_al_data[old_al_data$Age %in% 18, ] table( cut( old_al_data$TL, breaks = wst_alkey_breaks, include.lowest = FALSE, right = FALSE ), old_al_data$Age, useNA = "ifany" ) old_al_data$TL[old_al_data$TL %% 1 > 0] length(old_al_data$ID[old_al_data$ID < 0]) # more tinkering table( format( as.Date( old_al_data$Date, format = "%m/%d/%y" ), "%Y" ), useNA = "ifany" ) # experimenting with cut() function cut( c(25.9, 26), breaks = wst_alkey_breaks - 0.1, include.lowest = FALSE, right = F ) # Plotting: exploratory --------------------------------------------------- ggplot(data = old_al_data, mapping = aes(x = Age, y = TL, group = Age)) + geom_boxplot() #+ # facet_grid(facets = Location ~ .) ggplot(data = old_al_data, mapping = aes(x = YearClass, y = Check)) + geom_point() ggplot(data = old_al_data, mapping = aes(x = TL)) + # geom_histogram(breaks = wst_alkey_breaks[-35]) geom_histogram(binwidth = 5) ggplot(data = old_al_data, mapping = aes(x = Age, y = TL)) + geom_smooth() + stat_summary(fun.y = mean, geom = "point") + geom_line(mapping = aes(y = 261.2 * (1 - exp(-0.04027 * (Age + 3.638)))), colour = "red") plot(261.2 * (1 - exp(-0.04027 * (0:100 + 3.638)))) # Fitting von Bertalanffy curve ------------------------------------------- # Kohlhorst et al. (1980) fitted White Sturgeon age-length data (collected # 1973-1976) to the von Bertalanffy growth curve. Below, I will attempt to # recreate the model fit to better understand the model parameters. # (1) using non-linear least squares (nls) # (2) von Bertalanffy growth curve (vbgc) = # len_inf * (1 - (exp(-k * (ages - t0)))) mod_vb_cdfw <- nls( formula = TLen ~ a * (1 - (exp(-b * (Age - c)))), data = old_al_data, start = list( a = 200, b = 0.05, c = 0 ) ) summary(mod_vb_cdfw) mod_vb_usfws <- nls( formula = TotalLength ~ a * (1 - (exp(-b * (Age - c)))), data = wst_usfws_age_len, start = list( a = 200, b = 0.05, c = 0 ) ) summary(mod_vb_usfws) plot(mod_vb_usfws$m$resid()) ggplot(data = old_al_data, mapping = aes(x = Age, y = TLen, group = Age)) + geom_point(alpha = 1/5, size = 3)# + # geom_boxplot() <file_sep>--- --- ```{r setup, include=FALSE} knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics") knitr::opts_chunk$set(echo = FALSE) ``` ```{r libraries} # library() ``` ```{r load-data} AltAbund <- readRDS(file = "abundance/AltAbund.rds") Petersen <- readRDS(file = "abundance/Petersen.rds") ``` ```{r somevars} ``` ```{r} Petersen <- within(data = Petersen, expr = { Abund <- (NumTagged * (FinalC + 1)) / (Recap + 1) }) alt_n <- with(data = AltAbund$Abundance, expr = { b <- LenCat == "leg" N[b] }) ``` ```{r} Petersen$AltN <- c(rep(NA, times = 18), alt_n) ``` ```{r} xlsx::write.xlsx(Petersen, file = "abundance/test.xlsx", showNA = FALSE) ``` <file_sep> ----- ----- <!-- chunks for data loading, data clean up, & global variables --> <!-- include child files --> <!-- See annual summary data saved as `card_summary.csv` within this directory (`fishery`). --> <!-- TODO: MORE NARRATIVE HERE for table summary (1) explain with comments each code chunk (2) narrative: wording about pre-ALDS & ALDS, free & then charge (3) narrative: note about pre-ALDS not having DNF category (4) narrative: number table and then reference number; explain field names (5) decide whether or not to include species fate (6) decide whether or not to save output to .csv file --> <!-- Cards issued (purchased) --> <!-- Cards returned --> <!-- below adds more fields to annual summary --> <!-- may not include below in display --> <!-- numbers --> <!-- length --> <!-- length frequency --> <!-- per angler --> <!-- per month --> <!-- per month & location --> <!-- per location by species --> <!-- top 5 WST catch location --> <!-- rewark disk field summaries --> <!-- annual summary using `catch_angler` --> <!-- To get a sense of spatial and temporal catch, we added a 'Season' field to angler catch data. We group seasons as follows: winter = Dec, Jan, Feb; spring = Mar, Apr, May; summer = Jun, Jul, Aug; and fall = Sep, Oct, Nov. To maintain chronology and because winter crosses each calendar year, we 'pushed' Dec into the next Card year. For example, Dec 2008 is grouped with Jan 2009 & Feb 2009 to make winter 2009. As such, winter 2007 (Dec 2006, Jan 2007, & Feb 2007) is data "light" because the Card did not really come on-line until March 2007. Consider this fact when viewing annual summaries for winter 2007. --> <!-- Here we display but 5 rows of the `nrow(catch_yr_loc)` annual summary of seasonal and geographic (location) catch. For `Species`, 'k' denotes kept and 'r' denotes released. Seasons are abbreviated 'uk', 'wi', 'sp', 'su', and 'fa' (unknown, winter, spring, summer, fall). `Total` is total annual catch per location, and `NumAngl` and `NumMeas` are number of anglers and number (of fish) measured. We use (converted) fork length (in centimeters) and provide mean and standard deviation (sd) when number measured greater than 0. --> <!-- catch per season, creates new dataframe from `catch` --> <!-- caption automation here --> <!-- begin narrative below --> ## Introduction Herein provides a summary of California Sturgeon Report Card (Card) data. Since 2007, the Card has been required of any angler fishing for sturgeon. It is part of a suite of sport fishing regulations intended to protect California’s year-round White Sturgeon fishery while increasing protections for the federally-threatened Green Sturgeon population and adding resiliency to the conservation-dependent White Sturgeon population. Card data are complementary to on-going research and monitoring conducted by the California Department of Fish and Wildlife (CDFW) and other entities. The Card includes fields for angler contact information (pre-printed), retained White Sturgeon, and released sturgeon. To aid CDFW’s efforts to reduce illegal commercialization of sturgeon and to enforce the daily and annual bag limits on White Sturgeon, each Card also includes detachable single-use serially numbered Card-specific tags to be placed on retained White Sturgeon. Anglers must record the day, month, and location for any sturgeon they catch and keep or catch and release. Anglers also must record sturgeon length if kept. Though not required, many anglers record length for sturgeon released. A ‘Reward Disk’ field is available should the angler catch a sturgeon with a CDFW-affixed disc tag. **NOTES** 1) Card data are not static, and summaries may change as new data become available. The current summary year (typically one year behind current calendar year) is most affected by this. This summary report is updated periodically as new data are collected. The most recent data extraction was 03-Jun-2020 @ 11:54. 2) Reporting for current valid Card (year 2020) is not due until 31-Jan-2021. Consider this when viewing any summary herein for 2020. 3) From 2007-2017, CDFW produced single-year Card summary reports. These reports are available at <https://wildlife.ca.gov/Conservation/Delta/Sturgeon-Study/Bibliography>, find title *‘YYYY’ Sturgeon Fishing Report Card: Preliminary Data Report*, though updated annual summaries are found herein. The CDFW’s Sportfish Unit will no longer produce single-year summaries. 4) The Card was first made available 01-Mar-2007. Some anglers reported data for Jan 2007 & Feb 2007; however, catch data are a bit ‘thin’ for this period compared to the norm. Keep this in mind when interpreting summaries herein. 5) Card location descriptions as written are long. For conciseness, locations *codes* are displayed in figures and tables herein. For reference, please see table in section ‘Card Location Codes and Descriptions.’ 6) ‘disk’ or ‘disc’ are used interchangeably when referring to the external tag CDFW affixes to White Sturgeon. The Card uses ‘disk’. *CDFW contact*: [<NAME>](mailto:<EMAIL>) ## Distribution and Return The Card has been distributed through the Automated License Data System (ALDS) since 2012. From 2007 through 2012, the Card was issued free of charge. A fee of \~$8 was set in 2013. Initially, Cards were categorized as catch or no catch, but in 2010 a ‘did not fish’ check box was included (Table 1). The ALDS affords anglers on-line reporting. There has been a steady increase of anglers making use of such accommodation (Table 1, see ‘IS’ or Internet submission). Further, there has been an increase overall in reporting (‘ReportingRate’), though it seems to have reached a plateau (Table 1; \~33%). Table 1 field names explained below for reference. - left-most column: calendar year for which Card was issued (sold) - **Issued**: number of Cards issued (or sold post 2012) - **NoEffort**: number of anglers reporting ‘did not fish’ (available from 2010) - **NoCatch**: number of anglers reporting ‘fished, no catch’ - **Catch**: number of anglers reporting catching one or more sturgeon - **ReturnRate**: sum of NoEffort, NoCatch, Catch divided by Issued - **NotReturned**: number of Cards not returned - **CC**: Control Center - Card entered by CDFW staff - **IS**: Internet Submission - Card entered (reported) on-line by angler *Table 1. 2007-2020 Card distribution, return, and return rate. Did not fish (‘NoEffort’) not an option 2007-2009. Automated License Data System implemented 2012, making possible Internet submission (IS).* | | Issued | NoEffort | NoCatch | Catch | ReturnRate | NotReturned | CC | IS | | ---- | ------: | -------: | ------: | ----: | ---------: | ----------: | -----: | -----: | | 2007 | 37,680 | NA | 5,064 | 1,855 | 18.36 | 30,761 | NA | NA | | 2008 | 53,777 | NA | 5,281 | 2,048 | 13.63 | 46,448 | NA | NA | | 2009 | 72,499 | NA | 6,350 | 2,208 | 11.80 | 63,941 | NA | NA | | 2010 | 66,357 | 1,482 | 4,275 | 1,758 | 11.33 | 58,842 | NA | NA | | 2011 | 112,000 | 4,374 | 5,765 | 2,274 | 11.08 | 99,587 | NA | NA | | 2012 | 112,800 | 5,382 | 5,203 | 2,052 | 11.20 | 100,163 | 10,797 | 1,844 | | 2013 | 50,915 | 3,130 | 5,213 | 2,290 | 20.90 | 40,273 | 6,850 | 3,792 | | 2014 | 49,260 | 3,258 | 6,173 | 2,645 | 24.51 | 37,184 | 5,984 | 6,094 | | 2015 | 48,337 | 4,423 | 7,052 | 2,870 | 29.75 | 33,955 | 5,525 | 8,858 | | 2016 | 47,617 | 6,129 | 6,682 | 2,997 | 32.92 | 31,943 | 4,494 | 11,181 | | 2017 | 44,374 | 4,715 | 7,236 | 2,814 | 33.52 | 29,502 | 3,658 | 11,223 | | 2018 | 44,146 | 4,858 | 6,968 | 2,398 | 32.55 | 29,778 | 2,870 | 11,498 | | 2019 | 40,844 | 4,574 | 6,126 | 1,742 | 30.84 | 28,248 | 2,133 | 10,463 | | 2020 | 35,986 | 0 | 1 | NA | 0.00 | 35,985 | 1 | NA | ## Reported Catch Anglers must report sturgeon catch, whether kept or released. Anglers may keep only White Sturgeon, with bag limits of one daily and three annually. On average, each year anglers keep about 2,000 White Sturgeon (Figure 1). Anglers catch and release an annual average of about 4,600 White Sturgeon (Figure 1). <img src="annual_card_files/figure-gfm/plot-wst-catch-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 1. 2007-2019 Annual White Sturgeon catch (kept & released) from reported Cards. ‘x’ denotes number measured (released) and orange bars represent number kept (nearly all of which are measured as required by regulations).* Green Sturgeon are bycatch in the White Sturgeon fishery. Anglers may not keep a Green Sturgeon and annually release on average about 190 (Figure 2). <img src="annual_card_files/figure-gfm/plot-gst-catch-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 2. 2007-2019 Annual Green Sturgeon bycatch from reported Cards. ‘x’ denotes number measured.* The Card provides species check boxes (White or Green) for fish released with no reward disk present. No such check boxes exist for fish released with reward disk present, given a correctly recorded disk tag number provides trace back to CDFW release data. Annually, on average, about 40 sturgeon cannot be identified to species given the available information. ## Catch per Angler Roughly ⅔ to ¾ of anglers who report catching sturgeon catch only 1 or 2 White Sturgeon per year (includes both kept and released; Table 2). Few anglers (\<4%) catch 15 or more, and each year at least one angler reports catching many White Sturgeon (Table 2, field ‘Max’). *Table 2. 2007-2019 Annual White Sturgeon catch (kept or released) by angler. Displayed number is fraction of total anglers who report catching one or more sturgeon. Does not include anglers who reported ‘fished no catch’ or ‘did not fish.’ Column headings denote binned sturgeon catch, with ‘Max’ showing highest annual catch for one angler.* | | 1-2 | 3-4 | 5-6 | 7-8 | 9-10 | 11-12 | 13-14 | 15+ | Max | | :--- | ---: | ---: | ---: | ---: | ---: | ----: | ----: | ---: | --: | | 2007 | 0.67 | 0.15 | 0.06 | 0.03 | 0.02 | 0.01 | 0.01 | 0.04 | 39 | | 2008 | 0.66 | 0.17 | 0.06 | 0.03 | 0.02 | 0.01 | 0.01 | 0.04 | 39 | | 2009 | 0.67 | 0.14 | 0.07 | 0.03 | 0.02 | 0.01 | 0.01 | 0.04 | 143 | | 2010 | 0.66 | 0.16 | 0.07 | 0.03 | 0.03 | 0.01 | 0.01 | 0.04 | 53 | | 2011 | 0.68 | 0.17 | 0.05 | 0.03 | 0.02 | 0.01 | 0.01 | 0.02 | 82 | | 2012 | 0.69 | 0.15 | 0.06 | 0.03 | 0.02 | 0.01 | 0.00 | 0.03 | 32 | | 2013 | 0.71 | 0.15 | 0.06 | 0.03 | 0.01 | 0.01 | 0.01 | 0.02 | 84 | | 2014 | 0.72 | 0.15 | 0.05 | 0.02 | 0.02 | 0.01 | 0.01 | 0.02 | 49 | | 2015 | 0.69 | 0.15 | 0.06 | 0.03 | 0.02 | 0.01 | 0.01 | 0.03 | 44 | | 2016 | 0.73 | 0.14 | 0.05 | 0.03 | 0.01 | 0.01 | 0.01 | 0.02 | 39 | | 2017 | 0.71 | 0.15 | 0.05 | 0.03 | 0.01 | 0.01 | 0.01 | 0.02 | 40 | | 2018 | 0.73 | 0.15 | 0.04 | 0.02 | 0.02 | 0.01 | 0.01 | 0.02 | 41 | | 2019 | 0.75 | 0.13 | 0.04 | 0.02 | 0.02 | 0.01 | 0.01 | 0.02 | 33 | #### 2013-present In the ALDS-era and post-2012, Card reporting has consistently offered three categories: did not fish; fished no catch; and fished (& caught). This facilitates analyzing catch for the angling population expending effort (i.e., to not include ‘did not fish’ anglers). Annually, on average about 1.4% (0.014) of anglers (n ≥ 1000 reporting) who fish catch and release at least one Green Sturgeon (Table 3). Some anglers do catch and release more than one Green Sturgeon annually (Table 3, see ‘Max’ field). *Table 3. 2013-2020 Annual fraction of all reporting anglers who caught and then released one or more Green Sturgeon. ‘Max’ denotes maximum annual catch for one angler.* | | Anglers | Fraction | Max | | :--- | ------: | -------: | --: | | 2013 | 120 | 0.0160 | 7 | | 2014 | 137 | 0.0155 | 7 | | 2015 | 151 | 0.0152 | 5 | | 2016 | 157 | 0.0164 | 5 | | 2017 | 154 | 0.0152 | 8 | | 2018 | 141 | 0.0148 | 15 | | 2019 | 60 | 0.0075 | 3 | | 2020 | 0 | 0.0000 | 0 | Of reporting anglers (n ≥ 1000, including ‘did not fish’), about 9% (0.09) on average keep one White Sturgeon. Fewer still keep the limit of three (Table 4). Roughly 27%-39% anglers reported ‘did not fish.’ *Table 4. 2013-2020 Annual fraction of all reporting anglers who kept 0 (none), 1, 2, or 3 White Sturgeon per Card (calendar) year. ‘NoEffort’ denotes anglers reporting ‘did not fish.’* | | Anglers | None | Kept-1 | Kept-2 | Kept-3 | NoEffort | | :--- | ------: | -----: | -----: | -----: | -----: | -------: | | 2013 | 10,642 | 0.5631 | 0.1031 | 0.0307 | 0.0089 | 0.2941 | | 2014 | 12,074 | 0.5826 | 0.1091 | 0.0320 | 0.0065 | 0.2698 | | 2015 | 14,382 | 0.5633 | 0.0968 | 0.0264 | 0.0060 | 0.3075 | | 2016 | 15,674 | 0.4872 | 0.0868 | 0.0263 | 0.0086 | 0.3910 | | 2017 | 14,872 | 0.5439 | 0.0992 | 0.0299 | 0.0100 | 0.3170 | | 2018 | 14,368 | 0.5470 | 0.0864 | 0.0217 | 0.0067 | 0.3381 | | 2019 | 12,596 | 0.5407 | 0.0744 | 0.0176 | 0.0041 | 0.3631 | | 2020 | 1 | 1.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | To derive the number of anglers who actively practice catch-n-release only is not possible given available data. However, of the reporting anglers who fished, between 6.6% and 10.1% released sturgeon yet retained none (2013-2019, years with ≥ 1000 reporting). ## Length Anglers must report length for White Sturgeon kept. Anglers are not required to report length of released fish, but some do, typically in the species check box. Anglers report inches, as required by regulations, and herein lengths were converted to centimeters fork length (FL). Occasionally, an angler will report a suspiciously small length (i.e., ≤ 10). Likely, here the angler is using short hand for catch (i.e., number caught). So, any “length” ≤ 10 is flagged and set to `NA` for analytical purposes (Table 5). *Table 5. 2007-2019 Annual count of reported ‘lengths’ by species CDFW identified as suspect (i.e., too small). For White Sturgeon, this includes kept and released fish, but most are released.* | | White | Green | | :--- | ----: | ----: | | 2007 | 2 | 0 | | 2008 | 0 | 0 | | 2009 | 5 | 0 | | 2010 | 1 | 0 | | 2011 | 1 | 0 | | 2012 | 1 | 0 | | 2013 | 2 | 1 | | 2014 | 6 | 1 | | 2015 | 3 | 1 | | 2016 | 15 | 1 | | 2017 | 13 | 0 | | 2018 | 5 | 0 | | 2019 | 11 | 0 | #### Green Sturgeon Of the reported valid lengths, most Green Sturgeon are less than 100 cm (\~40 inches; Figure 3). The orange box represents the interquartile range (25%-75%). <img src="annual_card_files/figure-gfm/plot-gst-len-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 3. 2007-2019 Reported Green Sturgeon lengths (converted from inches to centimeters). Bottom and top of orange box denotes 25th and 75th percentile. Note: noise added to x-axis to lessen over-plotting.* #### White Sturgeon (released) Length distributions indicate annual median values below 102 cm FL, the lower bound for the slot (Figure 4, see ‘x’ on figure). From 2013-2019, it appears anglers were catching more sub-slot sized fish, measuring more sub-slot sized fish, or a combination of both (Figure 4, see progressively darker points below the slot). Anglers released White Sturgeon that could have been retained. <img src="annual_card_files/figure-gfm/plot-wstr-len-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 4. 2007-2019 Reported released White Sturgeon lengths (converted from inches to centimeters). Bottom and top of orange box denotes 25th and 75th percentile, ‘x’ denotes median. Blue box denotes current slot limit 102-152 cm FL (40-60 inches FL). Note: noise added to x-axis to lessen over-plotting.* #### White Sturgeon (kept) Length quartiles 25%, 50%, and 75% show in certain years anglers harvested more fish closer in length to the upper slot limit and other years more fish closer in length to the low slot limit (Figure 5). This might indicate a year class (or classes) growing into and out of the slot limit (102-152 cm FL or 40-60 in FL). <img src="annual_card_files/figure-gfm/plot-wstk-len-med-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 5. 2007-2019 Reported kept White Sturgeon lengths (converted from inches to centimeters). Bottom and top of orange box denotes 25th and 75th percentile. ‘x’ denotes median.* ## Catch by Location & Month Card data make possible some spatial and temporal analyses. Though spatially the data are coarse, limited to larger geographic sections and not specific way-points. This section explores such analytics for all White Sturgeon (kept & released). #### Location: Ranking Top 5 for White Sturgeon Suisun Bay (code 18) consistently yields the greatest fraction of White Sturgeon catch, 2008 excepted (Table 6; 20%-40%). In fact, Suisun Bay is typically 5+ points higher than the second-ranked location. Sacramento River: Rio Vista to Chipps Island (code 04) is also a top spot for White Sturgeon catch (Table 6). *Table 6. 2007-2019 Annual top 5 ranking of locations with highest White Sturgeon catch. Number is location code (in parentheses denotes percent of total).* | | First | Second | Third | Fourth | Fifth | | :--- | :------ | :------ | :------ | :------ | :----- | | 2007 | 18 (23) | 04 (17) | 09 (12) | 16 (7) | 03 (7) | | 2008 | 04 (21) | 18 (20) | 09 (10) | 03 (9) | 16 (6) | | 2009 | 18 (28) | 04 (18) | 09 (9) | 03 (7) | 14 (6) | | 2010 | 18 (25) | 04 (20) | 10 (7) | 16 (6) | 17 (6) | | 2011 | 18 (22) | 04 (15) | 16 (14) | 10 (10) | 03 (9) | | 2012 | 18 (25) | 04 (16) | 03 (10) | 10 (7) | 09 (7) | | 2013 | 18 (26) | 04 (17) | 03 (11) | 09 (10) | 16 (7) | | 2014 | 18 (28) | 04 (15) | 03 (11) | 09 (10) | 10 (7) | | 2015 | 18 (30) | 04 (16) | 09 (12) | 03 (8) | 16 (6) | | 2016 | 18 (29) | 04 (17) | 09 (13) | 10 (7) | 03 (6) | | 2017 | 18 (34) | 16 (16) | 09 (11) | 04 (11) | 19 (8) | | 2018 | 18 (40) | 09 (11) | 04 (10) | 16 (8) | 19 (7) | | 2019 | 18 (37) | 09 (12) | 16 (11) | 10 (8) | 04 (7) | #### Month: White Sturgeon Though the White Sturgeon fishery is open year-round, there appears to be a natural seasonality (Table 7). Catch as a fraction of total caught is lowest late spring through summer (Table 7). Unlike location, no single month stands out as exceptional; winter and spring months hover around 15%. *Table 7. 2007-2019 Annual White Sturgeon catch by month. Number represents percent of total annual catch. Note: Card not required until 01-Mar-2007, so 2007 Jan & Feb data not representative of full fishing effort.* | | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | | :--- | ---: | ---: | ---: | ---: | --: | --: | --: | --: | --: | ---: | ---: | ---: | | 2007 | 1.4 | 2.2 | 18.4 | 11.8 | 7.1 | 3.2 | 2.3 | 2.1 | 4.5 | 12.1 | 17.6 | 17.4 | | 2008 | 9.6 | 14.6 | 15.9 | 11.0 | 7.1 | 3.8 | 1.6 | 1.7 | 2.1 | 6.4 | 13.0 | 13.2 | | 2009 | 13.1 | 15.4 | 16.5 | 11.3 | 5.9 | 3.1 | 2.3 | 2.0 | 2.8 | 6.8 | 10.3 | 10.6 | | 2010 | 13.6 | 14.9 | 16.0 | 10.6 | 5.5 | 2.6 | 2.6 | 1.9 | 2.7 | 6.7 | 11.0 | 11.8 | | 2011 | 12.1 | 13.1 | 11.9 | 12.6 | 8.3 | 7.5 | 3.6 | 1.8 | 2.9 | 5.6 | 10.3 | 10.2 | | 2012 | 12.2 | 13.1 | 12.4 | 14.4 | 6.6 | 4.4 | 2.0 | 1.4 | 2.4 | 7.3 | 11.9 | 11.9 | | 2013 | 10.1 | 15.0 | 17.8 | 11.3 | 4.7 | 3.3 | 1.6 | 1.3 | 1.8 | 7.4 | 12.6 | 13.2 | | 2014 | 12.0 | 17.4 | 18.1 | 10.9 | 5.0 | 2.4 | 1.7 | 0.9 | 1.5 | 5.0 | 10.4 | 14.8 | | 2015 | 17.8 | 18.8 | 19.1 | 7.4 | 3.9 | 2.1 | 0.8 | 1.4 | 1.4 | 5.1 | 9.5 | 12.6 | | 2016 | 12.7 | 18.4 | 12.4 | 10.3 | 3.5 | 1.4 | 1.0 | 0.8 | 3.2 | 8.3 | 16.1 | 12.0 | | 2017 | 9.6 | 11.8 | 13.4 | 9.0 | 4.7 | 2.2 | 1.4 | 1.2 | 2.3 | 10.6 | 16.4 | 17.5 | | 2018 | 13.0 | 14.6 | 15.2 | 9.9 | 4.8 | 2.4 | 1.9 | 1.4 | 3.3 | 7.7 | 13.5 | 12.2 | | 2019 | 11.8 | 11.4 | 16.1 | 12.2 | 4.2 | 3.9 | 2.1 | 1.4 | 2.3 | 6.9 | 14.4 | 13.5 | Anglers have reported catching one or more White Sturgeon each month every year for the following locations: 04(7); 09(12); 18(21) (Figure 6; y-axis is number in parentheses - see section *Card Location Code* for y-axis number & corresponding Card code). To date, the highest White Sturgeon catch was observed Nov 2017 at location 18(21), n=559. <img src="annual_card_files/figure-gfm/plot-wst-loc-month-1.png" style="display: block; margin: auto auto auto 0;" /> *Figure 6. 2007-2019 Heatmap (or tile plot) showing reported White Sturgeon catch by location and by month. Grey shading denotes location not an option on Card, and orange shading denotes zero reported catch.* ## Angler Tag Returns In 2010, CDFW added a field for reporting the disc tag number, if present. Some anglers recorded such information starting in 2009 despite such field’s absence (Table 8). Ideally, an angler should report the entire alpha-numeric (e.g., HH1234). The prefix denotes the reward value (e.g., ‘HH’ = $100). A complete tag number makes easier the task of precisely retrieving CDFW release data. Many anglers do their best, but not every reported disc tag is complete (Table 8). CDFW staff use angler-reported disc tags to augment mark-recapture data, perhaps improving population metrics accuracy. Table field names are explained below for reference. - **Anglers**: number of anglers reporting a disc tag or possible disc tag - **Good Tag**: count of complete disc tags (angler correctly reported disc tag) - **No Prefix**: count of disc tags reported without alpha (i.e., missing prefix); likely a valid disc tag but more sleuthing is required - **Prefix ‘ST’**: count of disc tags reported as 5-digits, no prefix. CDFW released $20 disc tags with ‘ST’ followed by 5 digits. So these are likely $20 tags but more sleuthing is required. - **Reward Only**: count of likely disc tags but no number available. Angler reported reward value only (e.g., $50.00). - **Zip Only**: count of likely disc tags but no number available. Angler reported Stockton zip code (CDFW Stockton address printed opposite side of disc tag number). To date, anglers have reported 29 disc tags as digits only. However, digits are too few or too many to make a positive match with CDFW release data. *Table 8. 2007-2019 Annual count of anglers who reported catching a disc-tagged sturgeon and number of tags based on completeness of reported disc number.* | | Anglers | Good Tag | No Prefix | Prefix ‘ST’ | Reward Only | Zip Code | | :--- | ------: | -------: | --------: | ----------: | ----------: | -------: | | 2009 | 5 | 3 | 0 | 1 | 0 | 0 | | 2010 | 34 | 23 | 11 | 2 | 0 | 0 | | 2011 | 37 | 27 | 9 | 3 | 0 | 0 | | 2012 | 34 | 23 | 3 | 5 | 0 | 0 | | 2013 | 30 | 24 | 4 | 3 | 0 | 1 | | 2014 | 40 | 26 | 8 | 1 | 1 | 2 | | 2015 | 36 | 21 | 7 | 0 | 2 | 1 | | 2016 | 22 | 18 | 1 | 0 | 0 | 0 | | 2017 | 28 | 23 | 1 | 1 | 1 | 0 | | 2018 | 29 | 21 | 0 | 2 | 0 | 1 | | 2019 | 10 | 9 | 0 | 0 | 0 | 0 | <!-- save files as desired --> ## Card Location Codes & Descriptions Card locations are included below for reference. Field ‘Number’ is not on printed Card and is merely included here for simplifying y-axis in Figure 6. Card codes 2-9 may appear on Card with leading 0 (e.g., 03). | Number | Card Code | Card Description | | :----: | :-------: | :------------------------------------------------ | | 1 | 1 | Sacramento River: Red Bluff to Colusa (2007-2009) | | 2 | 01A | Sacramento River: Upstream of Red Bluff | | 3 | 01B | Sacramento River: Red Bluff to Hwy 32 bridge | | 4 | 01C | Sacramento River: Hwy 32 bridge to Colusa | | 5 | 2 | Sacramento River: Colusa to Knights Landing | | 6 | 3 | Sacramento River: Knights Landing to Rio Vista | | 7 | 4 | Sacramento River: Rio Vista to Chipps Island | | 8 | 5 | Feather River | | 9 | 6 | American River | | 10 | 7 | Sacramento Deepwater Ship Channel | | 11 | 8 | Yolo Bypass | | 12 | 9 | Montezuma Slough | | 13 | 10 | Napa River | | 14 | 11 | Petaluma River | | 15 | 12 | San Joaquin River: Upstream of HWY 140 bridge | | 16 | 13 | San Joaquin River: HWY 140 bridge to Stockton | | 17 | 14 | San Joaquin River: Stockton to Sherman Lake | | 18 | 15 | Old River | | 19 | 16 | San Pablo Bay | | 20 | 17 | <NAME> | | 21 | 18 | Suisun Bay | | 22 | 19 | Grizzly Bay | | 23 | 20 | San Francisco Bay: North of HWY 80 | | 24 | 21 | San Francisco Bay: South of HWY 80 | | 25 | 22 | Pacific Ocean: North of Golden Gate Bridge | | 26 | 23 | Pacific Ocean: Golden Gate Bridge to Point Sur | | 27 | 24 | Pacific Ocean: Point Sur to San Diego | | 28 | 25 | Any reservoir or lake | | 29 | 26 | Klamath River | ----- CDFW, Sportfish Unit **updated**: 15-Jun-2020 @ 11:11 <file_sep>--- title: "White Sturgeon Length Frequency" author: "CDFW" date: '' output: html_document: fig_caption: yes keep_md: no github_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, warning = FALSE) knitr::opts_knit$set(root.dir = "~/RProjects/SturgeonPopMetrics/") ``` ```{r libraries} library(ggplot2) # library(reshape2) # library(knitr) ``` ```{r data} # tagging data SturgeonAll <- readRDS(file = "data/tagging/SturgeonAll.rds") # card data SturgeonAlds <- readRDS(file = "data/card/SturgeonAlds.rds") Sturgeon0711 <- readRDS(file = "data/card/Sturgeon0711.rds") ``` ```{r source-files} source(file = "source/source_stu_hr.R") source(file = "source/source_stu_mark-recap.R") source(file = "source/functions_global_general.R") source(file = "source/functions_global_record_count.R") source(file = "source/functions_global_data_subset.R") source(file = "source/methods_len_freq.R") ``` ```{r plot-vars} # variables for plotting consistency fill_inslot <- scale_fill_manual( "In Slot", values = c('1' = "black", '0' = "grey50"), labels = c('1' = 'Y', '0' = 'N') ) ``` ## Tagging ```{r lf_wst_tag} lf_wst_tag <- GetLenFreq( SturgeonAll, colX = FL, by = "RelYear", subset = RelYear >= 2005 & Species %in% "White" ) ``` ```{r WstLfTag, fig.asp=2} plot( lf_wst_tag, lens = FL, type = "POT", fillBar = InSlot, addMed = TRUE, addN = TRUE ) + facet_grid(facets = RelYear ~ .) + fill_inslot + xlab("Length bins (cm FL)") ``` Note: red (dashed) vertical line in plots indicates median length. ## Card ```{r card_combine} # combining pre-alds & alds data in order to plot complete timeseries of lf # head(Sturgeon0711) # head(SturgeonAlds) bool1 <- Sturgeon0711$Species %in% "White" & Sturgeon0711$Length >= 10 & !is.na(Sturgeon0711$Length) bool2 <- SturgeonAlds$SturgeonType %in% "White" & SturgeonAlds$Length >= 10 & !is.na(SturgeonAlds$Length) temp_0711 <- Sturgeon0711[bool1, c("Year", "Species", "Fate", "FL_cm")] temp_alds <- SturgeonAlds[bool2, c("ItemYear", "SturgeonType", "Fate", "FL_cm")] colnames(temp_alds) <- c("Year", "Species", "Fate", "FL_cm") wst_card <- rbind(temp_0711, temp_alds) rm(bool1, bool2, temp_0711, temp_alds) ``` ```{r add-variable} # adding variable to wst_card to shade bars in plot wst_card$InSlot <- 0 wst_card$InSlot[wst_card$FL_cm >= 102 & wst_card$FL_cm <= 152] <- 1 ``` ```{r lf_wst_card_r} lf_wst_card_r <- GetLenFreq( wst_card, colX = FL_cm, by = "Year", breaks = seq(20, 230, 5), subset = Fate %in% "released" #& FL_cm < 230 ) ``` ```{r lf_wst_card_k} lf_wst_card_k <- GetLenFreq( wst_card, colX = FL_cm, by = "Year", subset = Fate %in% "kept" #& FL_cm < 230 ) ``` #### Released White Sturgeon ```{r WstLfCardr, fig.asp=2} plot( lf_wst_card_r, lens = FL_cm, type = "POT", fillBar = InSlot, addMed = TRUE, addN = TRUE ) + facet_grid(facets = Year ~ .) + fill_inslot + xlab("Length bins (cm FL)") ``` #### Kept White Sturgeon (plot needs formatting on x-axis) ```{r WstLfCardk} plot(lf_wst_card_k, lens = FL_cm, type = "POT", addMed = TRUE, addN = TRUE) + facet_grid(facets = Year ~ .) + xlab("Length bins (cm FL)") #+ # coord_cartesian(xlim = c(101, 156)) ```
7c0913417ebe129975efaa187b45040f62f540fd
[ "Markdown", "Text", "R", "RMarkdown" ]
33
RMarkdown
szjhobbs/sturgeon_population_metrics
d04d68560798db110cf5dd9155e8f81b47d65430
8dc1db7b6bcbcf551626f81f8579c00cc9e5d15f
refs/heads/master
<file_sep># ~/.bashrc: executed by bash(1) for non-login shells. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) # for examples export EDITOR="vim" # If not running interactively, don't do anything [ -z "$PS1" ] && return # don't put duplicate lines in the history. See bash(1) for more options # ... or force ignoredups and ignorespace HISTCONTROL=ignoredups:ignorespace # append to the history file, don't overwrite it shopt -s histappend # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # make less more friendly for non-text input files, see lesspipe(1) [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" # set variable identifying the chroot you work in (used in the prompt below) if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot) fi # set a fancy prompt (non-color, unless we know we "want" color) case "$TERM" in xterm-color) color_prompt=yes;; esac # uncomment for a colored prompt, if the terminal has the capability; turned # off by default to not distract the user: the focus in a terminal window # should be on the output of commands, not on the prompt force_color_prompt=yes if [ -n "$force_color_prompt" ]; then if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then # We have color support; assume it's compliant with Ecma-48 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such # a case would tend to support setf rather than setaf.) color_prompt=yes else color_prompt= fi fi if [ "$color_prompt" = yes ]; then #PS1='${debian_chroot:+($debian_chroot)}\[\e[01;34m\]\u\[\e[01;34m\]::\[\e[11;37m\]\h\[\e[01;30m\]:\[\e[01;34m\]\w\[\e[11;37m\]# #\[\e[11;37m\]>>> \[\e[0m\]' PS1="\[\e[00;32m\]\u\[\e[0m\]\[\e[00;33m\]@\[\e[0m\]\[\e[00;34m\]\h\[\e[0m\]\[\e[00;37m\][\[\e[0m\]\[\e[00;33m\]\w\[\e[0m\]\[\e[00;37m\]]\[\e[0m\]\[\e[00;32m\]\\$\[\e[0m\]" #PS1="\n\[\e[30;1m\](\[\e[36;1m\]\u@\h\[\e[30;1m\])-(\[\e[34;0m\]\j\[\e[30;1m\])-(\[\e[32;1m\]\@ \d\[\e[30;1m\])->\[\e[30;1m\]\n(\[\e[34;1m\]\w\[\e[30;1m\])-(\[\e[34;1m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\e[30;1m\])--> \[\e[0m\]" else PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' fi unset color_prompt force_color_prompt # If this is an xterm set the title to user@host:dir case "$TERM" in xterm*|rxvt*) #PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" PS1="\[\e[00;32m\]\u\[\e[0m\]\[\e[00;33m\]@\[\e[0m\]\[\e[00;34m\]\h\[\e[0m\]\[\e[00;37m\][\[\e[0m\]\[\e[00;33m\]\w\[\e[0m\]\[\e[00;37m\]]\[\e[0m\]\[\e[00;32m\]\\$\[\e[0m\]" ;; *) ;; esac # enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' #USER ALIAS #alias my='mysql -u maioral -p --auto-rehash' #alias ic='cd /safe/icarus/configurations && django && cd ../' #alias ol='cd /safe/olympus/configurations && django && cd ../' #alias ar='cd /safe/ares/configurations && django && cd ../' #alias ml='cd /home/rspena/fmq/mathlibs' alias clean='clear;clear;' alias reload='clear;clear;exec bash -l;' #USER HOME ALIAS alias work='cd /home/fabiov/workspace' alias home='cd /home/fabiov' #alias test='cd /home/edu/workspaces/testing' #GAMEDEV ALIAS alias repos='cd /home/fabiov/workspace/repos' #alias gm='cd /home/edu/workspaces/repos/impriart/source/games' #alias fmq='cd /home/edu/workspaces/impriart_motor' #alias imp='cd /home/edu/workspaces/impriart_motor' #alias impriart='cd /home/edu/workspaces/repos/impriart/source' #alias drivers='cd /home/edu/workspaces/RepoDrivers/Software/LibDrivers/' #alias drv='cd /home/edu/workspaces/RepoDrivers/Software/LibDrivers/' #GIT ALIAS alias gg='git gui' alias gc='git checkout' alias gss='git stash save' alias gsp='git stash pop' alias gs='git status' alias gb='git branch' alias gp='git pull' alias gk='gitk --all' alias gr='git reset --hard HEAD~0' alias gl="git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --" #QX ALIAS #alias qxx='172.20.2.234' #alias qxxconnect='ssh machine@172.20.2.234' #Microchip Tools export PATH=$PATH:"/opt/microchip/xc32/v1.31/bin" export PATH=$PATH:"/opt/microchip/xc16/v1.21/bin" export PATH=$PATH:"/opt/microchip/xc8/v1.30/bin" export PATH=$PATH:"/opt/microchip/xc8/v1.33/bin" export PATH=$PATH:"/opt/microchip/xc16/v1.22/bin" export PATH=$PATH:"/opt/microchip/xc32/v1.33/bin" #alias logs='gnome-terminal -e "python /safe/icarus/scripts/openlogs.py all"' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert #alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' #alias terminator="terminator 2>/dev/null" # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if [ -f /etc/bash_completion ] && ! shopt -oq posix; then . /etc/bash_completion fi export LESS="-R" eval "$(lesspipe)" #---------------------------------------------------------------------------+ # => colour chart | #---------------------------------------------------------------------------+ # Reset Color_Off="\[\033[0m\]" # Text Reset # Regular Colors Black="\[\033[0;30m\]" # Black Red="\[\033[0;31m\]" # Red Green="\[\033[0;32m\]" # Green Yellow="\[\033[0;33m\]" # Yellow Blue="\[\033[0;34m\]" # Blue # Bold BBlack="\[\033[1;30m\]" # Black BRed="\[\033[1;31m\]" # Red BGreen="\[\033[1;32m\]" # Green BYellow="\[\033[1;33m\]" # Yellow BBlue="\[\033[1;34m\]" # Blue # Bold High Intensty BIBlack="\[\033[1;90m\]" # Black BIRed="\[\033[1;91m\]" # Red BIGreen="\[\033[1;92m\]" # Green BIYellow="\[\033[1;93m\]" # Yellow BIBlue="\[\033[1;94m\]" # Blue # Various variables you might want for your PS1 prompt instead LoggedUser="\u" PathShort="\w" PathFull="\W" NewLine="\n" #export PS1='$([ "$(id -u)" == "0" ] && echo "'${BRed}'" || echo "'${BBlue}'")'"[ "${LoggedUser}" ]"${Color_Off}'$(git branch &>/dev/null;\ export PS1='$([ "$(id -u)" == "0" ] && echo "'${BRed}'" || echo "'${BBlue}'")'"\[\e[00;32m\]\u\[\e[0m\]\[\e[00;33m\]@\[\e[0m\]\[\e[00;34m\]\h\[\e[0m\]\[\e[00;37m\][\[\e[0m\]\[\e[00;33m\]\w\[\e[0m\]\[\e[00;37m\]]\[\e[0m\]\[\e[00;32m\]\\$\[\e[0m\]"${Color_Off}'$(git branch &>/dev/null;\ if [ $? -eq 0 ]; then \ echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \ if [ "$?" -eq "0" ]; then \ # @4 - Clean repository - nothing to commit echo "'${BGreen}'\n"$(__git_ps1 " (%s)"); \ else \ # @5 - Changes to working tree echo "'${BIRed}'\n"$(__git_ps1 " {%s}"); \ fi) '${Red}" "${Color_Off}'\n$ "; \ else \ # @2 - Prompt when not in GIT repo echo "'${Green}" "${Color_Off}'"; \ fi)' mymake() { pathpat="(/[^/]*)+:[0-9]+" ccred=$(echo -e "\033[0;31m") ccyellow=$(echo -e "\033[0;33m") ccend=$(echo -e "\033[0m") /usr/bin/make "$@" 2>&1 | sed -E -e "/[Ee]rror[: ]/ s%$pathpat%$ccred&$ccend%g" -e "/[Ww]arning[: ]/ s%$pathpat%$ccyellow&$ccend%g" return ${PIPESTATUS[0]} } #fortune cookies #~/.myScripts/cowscript #Node NVM #source ~/.nvm/nvm.sh #nvm use 0.12.4 > /dev/null 2>&1 #nodeVersion=`nvm current` #Node Webkit #alias nw='~/.nw/nw' #Electron #alias electron='~/.electron/electron' #electronVersion=` electron --version` #gcc g++ #gccVersion=`gcc -v 2>&1 | tail -1 | cut -d " " -f 3` #gppVersion=`g++ -v 2>&1 | tail -1 | cut -d " " -f 3` #gccArm #8.2.1 #export PATH="/opt/armGcc/gcc-arm-none-eabi-8-2018-q4-major/bin:$PATH" #4.7.4 #export PATH="/opt/armGcc/gcc-arm-none-eabi-4_7-2013q2/bin:$PATH" #alias arm-gcc='arm-none-eabi-gcc' #alias arm-g++='arm-none-eabi-g++' #arm-gcc arm-g++ #armGccVersion=`arm-none-eabi-gcc -v 2>&1 | tail -1 | cut -d " " -f 3` #armGppVersion=`arm-none-eabi-g++ -v 2>&1 | tail -1 | cut -d " " -f 3` #openOCDVersion=`openocd -v 2>&1 | head -1 | cut -d " " -f 4| cut -c1-10` #python #pythonVersion=`python -c 'import platform; print(platform.python_version())'` #IP's #wifiIp=`ifconfig wlp2s0 |grep 'netmask' |awk '/inet/ {print $2}'` #adapterIp=`ifconfig enp0s31f6 |grep 'netmask' |awk '/inet/ {print $2}'` #dockIp=`ifconfig enx3ce1a1240fce |grep 'netmask' |awk '/inet/ {print $2}'` #Print Versions: #echo -e '\033[1;34m' Now using: #echo -e '\033[1;37m' \* node: $nodeVersion\\t'\033[1;93m' \* electron: $electronVersion\\t'\033[1;91m'\* python: $pythonVersion #echo -e '\033[1;92m' \* gcc: $gccVersion\\t\\t'\033[1;90m' \* g++: $gppVersion #echo -e '\033[0;92m' \* arm-gcc: $armGccVersion\\t'\033[0;90m' \* arm-g++: $armGppVersion\\t'\033[1;91m'\* OpenOCD: $openOCDVersion #Print IP's #ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://' #echo -e '\033[1;34m' IP: `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'` #echo -e '\033[1;34m' IP\'s: #echo -e '\033[1;37m' \* Wifi: $wifiIp\\t'\033[1;93m' \* Dock: $dockIp '\033[1;91m'\\t\* Adapter: $adapterIp\\t'\033[1;92m' #echo -en "\e[0m" #unetbootin #export PATH=$PATH:/opt/SourceryCodeBenchLite/bin/ #export PATH=$PATH:/opt/unetbootin/ #alias unetbootin='sudo /opt/unetbootin/unetbootin-linux64-661.bin' export PATH="/home/fabiov/workspace/Scripts/:$PATH" #GCC compiler to ledstrips firmware export PATH="/opt/gcc-arm-none-eabi-4_7-2013q2/bin:$PATH" #GCC compliler for botoneira #export PATH="/opt/gcc-arm-none-eabi-8-2019-q3-update/bin:$PATH"
707ab3fe11f8e8b36b92ed9304a8c2c46e914ea6
[ "Shell" ]
1
Shell
FabioVasconcelos22/.bashrc_personal
4ee7e828985f893a3284e032434bb04b744517c9
0fa7e4dddbf10cd80e600da979822f3eb1eac84c
refs/heads/master
<repo_name>ZarinaAlice/Airbnb<file_sep>/js/script.js $(document).ready(function() { $(".custom-navigation").hide(); $(".navbar-toggle").click(function(){ $(".custom-navigation").animate({width: "toggle"}, 1000); }); $(".clear-navigation").click(function(){ $(".custom-navigation").animate({width:"toggle"}, 1000); }); }); <file_sep>/README.md # Readme This is my version of Airbnb and this is how it looks like [zarina.mthd.kz](http://zarina.mthd.kz) Still working on improvements :)
384fd866000957ab8ad6a657d246d4d583867863
[ "JavaScript", "Markdown" ]
2
JavaScript
ZarinaAlice/Airbnb
85b733daaee21952c33b1383634366484494bf72
6903d9b5887ef818db9526c8511856e9662db48d
refs/heads/master
<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ var count =6 do{ println("count: $count") if(count%2==0){ println("Number is even: $count") } count++ }while(count <= 5) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun main(args:Array<String>){ var map= hashMapOf(1 to "Hosanna", 2 to "Gabe-Oji") map.put(3, "Tommy") println(map.get(3)) println(map[3]) var ar = arrayOf(1,10,22,11) println(ar[0]) // var list = listOf(11, 22, 33, 22) // list[0]=22 list immutable, cannot change value var list = mutableListOf(11, 22, 33, 22) list[0]=22 for(item in list){ println(item) } }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ for(count1 in 1..5){ println("count1:$count1") for(count2 in 1..7){ println("count2: $count2") } println("loop nested done") } println("loop done") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun main (args:Array<String>){ var setElement = setOf(1,2,3,1,44,55,55) for(element in setElement){ println(element) } var setElementM = mutableSetOf(1,2,3,1,44,55,55) setElementM.add(77) for(element in setElementM){ println(element) } }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ for(count in 1..10){ if(count == 4) { continue } println("count: $count") } println("first loop done") for(count2 in 1..10){ if(count2 == 4) { break } println("count2: $count2") } println("second loop done") loop@ for(count3 in 1..10){ for(count4 in 1..5){ println("count3: $count3") if(count4 == 4) { break@loop } } } println("third loop done") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ var fullname="<NAME>" //global var fun display():Unit{ println(fullname) // print("name:" +name) } fun main(args:Array<String>){ var name="Hosanna" //local var println(fullname) print("name: "+name) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ /* Operations rules | Priorities rules 1- () 2- ^ 3- * , / 4- + , - 5- = */ fun main(args:Array<String>){ var number1:Int=10 var number2:Int=10 var number3:Int=5 var sum:Int? sum = (number1+number2)*number3-3; print("sum: $sum") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ var n1=10 var n2=20 // var max /*if(n1>n2){ max = n1; }else{ max=n2; }*/ var max = if(n1>n2) n1 else n2 println("max: $max") //When var age=30 var isYoung= when(age){ 30-> true else->false } println("is young: $isYoung") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ print("enter your grade: ") var grade= readLine()!!.toDouble(); if(grade>=90){ if(grade < 93){ println("You are in A- level") }else{ println("You are in A+ level") } } }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun main(args:Array<String>){ var map = HashMap<Int, String>() map.put(1, "Hosanna") map.put(2, "Gabe") map.put(3, "Moninseh") println(map.get(2)) map.put(2, "Gabe-OJi") for(k in map.keys){ println(map.get(k)) } }<file_sep>import java.util.* /** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ //input print("Enter your DOB: ") var DOB:Int= readLine()!!.toInt() //process var year=Calendar.getInstance().get(Calendar.YEAR) var age = year - DOB //output println("Your age is $age years") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ var n:Int=9 println(n>=0 && n<10) var n2:Int=55 println(n2==10 || n<100) var IsMarried:Boolean=true print(!IsMarried) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ // var name: String // name=null cannot assign null value var name: String? name=null print(name!!) //? meaans var can accept null values //!! means this value has to have a value otherwise throw exceptions }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ var number1:Int = 10 var number2:Int? var number2Str:String = "12" number2=number2Str.toInt() var number2Float:Float? number2Float=number2Str.toFloat() println("number1: "+ number1) println("number2: "+ number2) var xpi:Double=3.14 println("xpi: " + xpi) var IntPi:Int=xpi.toInt() println("IntPi: "+ IntPi) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/3/2020. */ fun main (args:Array<String>){ var x = 10; var y = 12; var name = "Ped" var age = 28 // var myName:String = 12; declaring data type explicitly rejects other types var dep:String? //? means variable is accepting null values dep="Software Engineering" var experience: String //declared variables must have a data type or be initialized println("name : "+name) println("age : "+age) println("dept: " +dep) var pi:Double = 3.14159 var gravity:Float = 9.8f var weight:Int = 85 }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/7/2020. */ fun main(args:Array<String>){ var title ="Welcome to Abuja" print(title) println("title:" +title) println("title: $title") var name="Hosanna " + "Gabe-Oji" println("name: $name") println("Second Char: "+title[5]) println("title to uppercase: "+title.toUpperCase()) println("title to lowercase: "+title.toLowerCase()) println("title split:: "+title.split(" ")) println("title: "+title.trim()) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun main(args:Array<String>){ var arrayInt=Array<Int>(5){0} arrayInt[3] = 55 println("Array[3]="+ arrayInt[3]) println("--All Element by object--") for(element in arrayInt){ println(element) } println("--All Element by index--") for(index in 0..4){ println("index: $index value: " +arrayInt[index]) } var arrayStr=Array<String>(4){""} for(index in 0..3){ println("arrayStr[ "+index+ " ]=") arrayStr[index] = readLine()!! } for(index in 0..3){ println("arrayStr[ "+index+ " ]=" +arrayStr[index]) } }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/3/2020. */ // This is main function fun main(args:Array<String>){ //Enter Username print("Enter name:") var name = readLine(); print("Enter Age: ") var age:Int = readLine()!!.toInt() //Add non null asserted call print("Enter department: ") var dept:String? dept = readLine() print("Enter pi: ") var pi:Double= readLine()!!.toDouble() /*Print output to allow users to see the variable values */ println("**** output *****") println("name: "+name) println("age: "+age) println("department: "+dept) println("PI: "+pi) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/3/2020. */ fun main(args: Array<String>){ println("Hi Ped, ") print("Welcome to Kotlin") print(3) } <file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ println("---- Math calculator -----") print("Enter number 1:") var number1:Float= readLine()!!.toFloat() print("Enter number 2:") var number2:Float= readLine()!!.toFloat() var sum:Float? sum=number1+number2 print("sum:"+sum) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ print("enter your grade: ") var grade= readLine()!!.toDouble(); if(grade>=90){ grade=grade+3 println("You are in A level") }else if (grade >=80 && grade <90){ println("You are in B level") } else if(grade >=70 && grade <80){ println("You are in C level") } else{ println("You fail") } } <file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun sum(n1:Int, n2:Int):Int{ return n1+n2 } fun sum(n1:Int, n2:Int, n3:Int):Int{ return n1+n2+n3 } fun sum(n1:Int, n2:Int, n3:Int, n4:Int):Int{ return n1+n2+n3+n4 } fun main(args:Array<String>){ println(sum(10,11)) println(sum(10,11, 15)) println(sum(10,11, 15, 19)) }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/3/2020. */ fun main(args:Array<String>){ var name = "Ped" name = "Hosanna" // var is read and write val github = "Pedestal19" // val is read only after first write // github = "dummy" // val cannot be reassigned // define variables has var if they are not going to change }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun sum(n1:Double, n2:Double):Double{ var sum = n1+n2 return sum } fun display(n:Int=0): Unit{ println("n: $n") } fun displayNoInput(): Unit{ println("Welcome to display") } fun main(args:Array<String>){ var r = sum(10.4, 14.8) println("r: $r") r = sum(5.0, 80.0) println("r: $r") r = sum(12.5, 17.5) println("r: $r") display(10) display() }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/8/2020. */ fun main(args:Array<String>){ var arraylist= ArrayList<String>() arraylist.add("Tommy") arraylist.add("Tom") arraylist.add("Doggy") arraylist.add("Ford") arraylist.add("one") println("First name: " +arraylist.get(0)) arraylist.set(0, "Hozay") println("all element by object") for(item in arraylist){ println(item) } println(" all element by index") for(index in 0..arraylist.size-1){ println(arraylist.get(index)) } //Search if(arraylist.contains("Hozay")){ print("name is found") } else{ println("name is not found") } }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ for(item in 1..10){ if(item==2) println("count: $item") } println("loop done") }<file_sep>/** * Author: <NAME>. *Project: Kotlin_Demo. *Date: 3/4/2020. */ fun main(args:Array<String>){ var x=30; when(x){ 1,2-> print("Value is 1 or 2") in 10..30-> print("Value is in 10-30 range") !in 10..30-> print("Value is not in 10-30 range") else ->{ println("value is out of range") } } }
3bd399fecead8d19704dd20ccb12c6c03bc6a616
[ "Kotlin" ]
27
Kotlin
Pedestal19/Kotlin_Demo
4e749f2f4990c1eccd8e5d03124e51770ba65235
d6866307c755c121ac8b383b0b7b774cebc27712
refs/heads/master
<repo_name>ulissesg/Heap_Sort_Tree<file_sep>/main.cpp //<NAME> - 2019 #include<stdio.h> #include <stdlib.h> void imprimeVetor (int *v){ for (int i = 0; i< 10; i++){ printf("-%d\n", v[i]); } } void troca(int *v1, int *v2){ int aux = *v1; *v1 = *v2; *v2 = aux; } void Heapify(int *Arv, int i, int n){ int left = 2*(i+1)-1; int right = 2*(i+1); int maior; if ((left <= n) && (Arv[left] > Arv[i])){ maior = left; }else{ maior = i; } if ((right <= n) && (Arv[right] > Arv[maior])){ maior = right; } if (maior != i){ troca(&(Arv[i]), &(Arv[maior])); Heapify(Arv, maior, n); } } void criarHeap(int *Arv, int n){ for(int i = (n / 2); i >= 0; i--){ Heapify(Arv, i, n); } } void Heapsort(int *Arv, int n){ criarHeap(Arv, n); for (int i = n-1; i > 0; i--){ troca(&(Arv[0]), &(Arv[i])); Heapify(Arv, 0, i-1); } } int main(){ int vetor[10]; for(int i = 0; i<10; i++){ vetor[i] = i; } Heapsort(vetor, 10); imprimeVetor(vetor); } <file_sep>/README.md # Heap Sort Tree Code of a Heap Sort Tree, made for algorithm and data structure class, in the first half of 2019.
a647d13a96cb12fd4302574bbf94f0f9b35ca12f
[ "Markdown", "C++" ]
2
C++
ulissesg/Heap_Sort_Tree
206a877e48713a9737beb2fd09e1eee18bc1b44a
0abd345c59b4dd8f5dec99b0c0cb9617779c4c8c
refs/heads/master
<file_sep># TTGO-T-Beam-GPS TTGO T-Beam GPS example ## Howto Flash it to your board using Arduino IDE (see my [TTGO-T-Beam-Blinking example](https://github.com/luckynrslevin/TTGO-T-Beam-Blinking) for details). Connect to via serial console to your board, e.g. on mac you can use screen: ``` TERM=xterm screen -L -h 5000 /dev/tty.SLAB_USBtoUART 115200 ``` Maybe you have to replace the tty device name in case your's is different. ## Output Until a proper GPS signal is found you will see "Positioning" message with an increasing counter: ``` Positioning(1) Positioning(2) Positioning(3) Positioning(4) ... ``` as soon as a valid GPS signal is available it will change to display the coordinates: ``` UTC:17:1:55 LNG:-73.9837 LAT:40.7405 satellites:4 ... UTC:17:2:20 LNG:-73.9893 LAT:40.7419 satellites:6 ... ``` <file_sep>#include <Wire.h> #include <axp20x.h> #include <TinyGPS++.h> #define UBLOX_GPS_OBJECT() TinyGPSPlus gps #define GPS_BAUD_RATE 9600 #define GPS_RX_PIN 34 #define GPS_TX_PIN 12 #define I2C_SDA 21 #define I2C_SCL 22 #define AXP192_SLAVE_ADDRESS 0x34 UBLOX_GPS_OBJECT(); AXP20X_Class axp; bool axp192_found = false; char buff[5][256]; uint64_t gpsSec = 0; void scanI2Cdevice(void) { byte err, addr; int nDevices = 0; for (addr = 1; addr < 127; addr++) { Wire.beginTransmission(addr); err = Wire.endTransmission(); if (err == 0) { Serial.print("I2C device found at address 0x"); if (addr < 16) Serial.print("0"); Serial.print(addr, HEX); Serial.println(" !"); nDevices++; if (addr == AXP192_SLAVE_ADDRESS) { axp192_found = true; Serial.println("axp192 PMU found"); } } else if (err == 4) { Serial.print("Unknow error at address 0x"); if (addr < 16) Serial.print("0"); Serial.println(addr, HEX); } } if (nDevices == 0) Serial.println("No I2C devices found\n"); else Serial.println("done\n"); } void setup() { Serial.begin(115200); delay(5000); Wire.begin(I2C_SDA, I2C_SCL); scanI2Cdevice(); if (axp192_found) { if (!axp.begin(Wire, AXP192_SLAVE_ADDRESS)) { Serial.println("AXP192 Begin PASS"); // power on ESP32 & GPS axp.setPowerOutPut(AXP192_LDO3, AXP202_ON); axp.setPowerOutPut(AXP192_DCDC1, AXP202_ON); axp.setDCDC1Voltage(3300); //esp32 core VDD 3v3 axp.setLDO3Voltage(3300); //GPS VDD 3v3 Serial.printf("DCDC1: %s\n", axp.isDCDC1Enable() ? "ENABLE" : "DISABLE"); Serial.printf("DCDC2: %s\n", axp.isDCDC2Enable() ? "ENABLE" : "DISABLE"); Serial.printf("LDO2: %s\n", axp.isLDO2Enable() ? "ENABLE" : "DISABLE"); Serial.printf("LDO3: %s\n", axp.isLDO3Enable() ? "ENABLE" : "DISABLE"); Serial.printf("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE"); Serial.printf("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE"); // Set mode of blue onboard LED (OFF, ON, Blinking 1Hz, Blinking 4 Hz) // axp.setChgLEDMode(AXP20X_LED_OFF); //axp.setChgLEDMode(AXP20X_LED_LOW_LEVEL); axp.setChgLEDMode(AXP20X_LED_BLINK_1HZ); //axp.setChgLEDMode(AXP20X_LED_BLINK_4HZ); } else { Serial.println("AXP192 Begin FAIL"); } } else { Serial.println("AXP192 not found"); } Serial1.begin(GPS_BAUD_RATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN); } void loop() { // put your main code here, to run repeatedly static uint64_t gpsMap = 0; while (Serial1.available()) gps.encode(Serial1.read()); if (millis() > 5000 && gps.charsProcessed() < 10) { snprintf(buff[0], sizeof(buff[0]), "T-Beam GPS"); snprintf(buff[1], sizeof(buff[1]), "No GPS detected"); Serial.println(buff[1]); return; } if (!gps.location.isValid()) { if (millis() - gpsMap > 1000) { snprintf(buff[0], sizeof(buff[0]), "T-Beam GPS"); snprintf(buff[1], sizeof(buff[1]), "Positioning(%llu)", gpsSec++); Serial.println(buff[1]); gpsMap = millis(); } } else { if (millis() - gpsMap > 1000) { snprintf(buff[0], sizeof(buff[0]), "UTC:%d:%d:%d", gps.time.hour(), gps.time.minute(), gps.time.second()); snprintf(buff[1], sizeof(buff[1]), "LNG:%.4f", gps.location.lng()); snprintf(buff[2], sizeof(buff[2]), "LAT:%.4f", gps.location.lat()); snprintf(buff[3], sizeof(buff[3]), "satellites:%u", gps.satellites.value()); Serial.println(buff[0]); Serial.println(buff[1]); Serial.println(buff[2]); Serial.println(buff[3]); gpsMap = millis(); } } }
3dafa1f46f3ce30b3b72d6a27253fb034bc32358
[ "Markdown", "C++" ]
2
Markdown
hiddenvs/TTGO-T-Beam-GPS
0f0a95dc9e6287ccd9d9fb47cc82fa6a1c290643
950658fb39aa79bfdb2bc9dce282df67e69c150a
refs/heads/master
<repo_name>Rus1mir/spring_mvc_2_2_2<file_sep>/src/main/java/web/service/CarService.java package web.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import web.dao.CarDao; import web.model.Car; import java.util.List; import java.util.stream.Collectors; @Service public class CarService { @Autowired private CarDao carDao; public List<Car> getCars(int quantity) { return carDao.getCars().stream().limit(quantity).collect(Collectors.toList()); } }
111309840f187518a674409cb19cdd60954a9ff4
[ "Java" ]
1
Java
Rus1mir/spring_mvc_2_2_2
1ef59d9e6e8e80d03a69398b9d6ce3e62de40bed
63df905e42d84d1b4e2a4a2fcbc6019cefc3eae6
refs/heads/master
<file_sep>import os import time import numpy as np import cv2 from matplotlib import pyplot as plt np.random.seed(1337) import keras from keras.layers import Conv2D, Flatten, MaxPooling2D, Dropout, Dense from keras.layers.normalization import BatchNormalization from keras.models import Sequential from keras.models import load_model from keras.utils import np_utils from keras.utils import to_categorical from keras.preprocessing.image import ImageDataGenerator from sklearn.metrics import precision_score from sklearn.metrics import recall_score from google.colab import drive drive.mount('/content/drive') train_datagen = ImageDataGenerator( rescale=1./255, width_shift_range = 0.3, height_shift_range = 0.3, shear_range=0.2, zoom_range=0.2) val_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( '/content/drive/My Drive/Colab Notebooks/tsr_car_automation/Large_data/train', target_size=(64, 64), class_mode='categorical', color_mode = "grayscale") validation_generator = val_datagen.flow_from_directory( '/content/drive/My Drive/Colab Notebooks/tsr_car_automation/Large_data/val', target_size=(64, 64), class_mode='categorical', color_mode = "grayscale") model = Sequential() model.add(Conv2D(64, kernel_size=(3,3), activation="relu", name = "convlayer1", input_shape = (64,64,1))) model.add(BatchNormalization()) model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', name = "convlayer2")) model.add(MaxPooling2D(pool_size=(2, 2), name = "mp1")) model.add(BatchNormalization()) model.add(Conv2D(128, kernel_size=(3, 3), activation='relu', name = "convlayer3")) model.add(MaxPooling2D(pool_size=(2, 2), name = "mp2")) model.add(BatchNormalization()) model.add(Conv2D(128, kernel_size=(3, 3), activation='relu', name = "convlayer4")) model.add(MaxPooling2D(pool_size=(2, 2), name = "mp3")) model.add(BatchNormalization()) model.add(Conv2D(256, kernel_size=(3, 3), activation='relu', name = "convlayer5")) model.add(MaxPooling2D(pool_size=(2, 2), name = "mp4")) model.add(BatchNormalization()) model.add(Flatten(name = "flatten")) model.add(Dense(units = 27, activation='relu', name = "dense1")) model.add(Dropout(0.5)) model.add(Dense(units = 9, activation='relu', name = "dense2")) model.add(Dropout(0.5)) model.add(Dense(units = 3, activation = "softmax", name = "dense3")) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) example = model.fit_generator( train_generator, epochs=25, validation_data=validation_generator, shuffle = True) model.evaluate_generator(validation_generator) ''' Plotting accuracy v epoch ''' print(example.history.keys()) plt.plot(example.history['acc']) plt.plot(example.history['val_acc']) plt.xlabel('epochs') plt.ylabel('accuracy') plt.legend(['train', 'val'], loc = 'upper left') plt.show() ''' Save weights and model ''' model.save_weights('/content/drive/My Drive/Colab Notebooks/weights_final.h5') model.save('/content/drive/My Drive/Colab Notebooks/model_final.h5') ''' Compute Precision, Recall ''' val_images = [] val_labels = [] name = os.listdir('/content/drive/My Drive/Colab Notebooks/Large_data/forward_val') for i in range(len(name)): img = cv2.imread('/content/drive/My Drive/Colab Notebooks/Large_data/forward_val/' + name[i],0) img = cv2.resize(img,(64,64)) val_images.append(img) val_labels.append(0) name = os.listdir('/content/drive/My Drive/Colab Notebooks/Large_data/left_val') for i in range(len(name)): img = cv2.imread('/content/drive/My Drive/Colab Notebooks/Large_data/left_val/' + name[i],0) img = cv2.resize(img,(64,64)) val_images.append(img) val_labels.append(1) name = os.listdir('/content/drive/My Drive/Colab Notebooks/Large_data/right_val') for i in range(len(name)): img = cv2.imread('/content/drive/My Drive/Colab Notebooks/Large_data/right_val/' + name[i],0) img = cv2.resize(img,(64,64)) val_images.append(img) val_labels.append(2) val_images = np.array(val_images) val_images = val_images/255.0 val_images = np.expand_dims(val_images,3) val_labels = np.array(val_labels) #print(val_labels) yhat_probs = model.predict(val_images, verbose=0) yhat_classes = model.predict_classes(val_images, verbose=0) precision = precision_score(val_labels, yhat_classes, average = 'macro') recall = recall_score(val_labels, yhat_classes, average = "macro") print(precision,recall) ''' Prediction on traffic sign obtained from the demo gif. ''' from google.colab.patches import cv2_imshow import math avoid_repeat_sign = 0; final = [] cap = cv2.VideoCapture('/content/drive/My Drive/Colab Notebooks/demo.gif') while True: det_img = [] ret, frame = cap.read() if(not(ret)): break img_sign = cv2.resize(frame, (400,400)) img_hsv = cv2.cvtColor(img_sign, cv2.COLOR_BGR2HSV) min_hsv_blue = np.array([90,100,50]) max_hsv_blue = np.array([120,255,255]) threshold1 = cv2.inRange(img_hsv, min_hsv_blue, max_hsv_blue) thres = cv2.dilate(threshold1,(5,5)) thres = cv2.dilate(thres,(5,5)) thres = cv2.erode(thres,(5,5)) thres = cv2.erode(thres,(5,5)) conts,_ = cv2.findContours(thres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) E = 0 for i in conts: area = cv2.contourArea(i) if(area>100 and avoid_repeat_sign==0): M = cv2.moments(i) _,(ma,mb),_ = cv2.fitEllipse(i) E = M['m00']/(math.pi*(ma/2)*(mb/2)) if(E>0.95): avoid_repeat_sign = 2 x,y,w,h = cv2.boundingRect(i) det_img = img_sign[y:y+h,x:x+w] final.append(det_img) avoid_repeat_sign = max(--avoid_repeat_sign, 0) cv2.destroyAllWindows() cap.release() for img in final: cv2_imshow(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.resize(img,(64,64)) img = np.array(img) img = img/255.0 img = np.expand_dims(img,3) img.resize((1,64,64,1)) print(model.predict_classes(img))<file_sep>import cv2 import matplotlib.pyplot as plt import numpy as np import math avoid_repeat_sign = 0; detected_sign_image = []; #image to be recognised stored here cap = cv2.VideoCapture("F:/IEEE_Project_2019/data_collection/demo.gif") while True: #reading video frame ret,frame = cap.read() if(not(ret)): break img_sign = cv2.resize(frame,(400,400)) #color thresholding img_hsv = cv2.cvtColor(img_sign , cv2.COLOR_BGR2HSV) min_hsv_blue = np.array([90,100,50]) max_hsv_blue = np.array([120,255,255]) threshold1 = cv2.inRange(img_hsv , min_hsv_blue , max_hsv_blue) ''' #code for detecting red rim sign(out of scope for now) min_hsv_red1 = np.array([170,0,0]) max_hsv_red1 = np.array([190,255,255]) threshold2 = cv2.inRange(img_hsv , min_hsv_red1 , max_hsv_red1) min_hsv_red2 = np.array([0,100,100]) max_hsv_red2 = np.array([10,255,255]) threshold3 = cv2.inRange(img_hsv , min_hsv_red2 , max_hsv_red2) threshold = cv2.bitwise_or(threshold1, threshold2 , threshold3) ''' # Morphological operation thres = cv2.dilate(threshold1,(5,5)) thres = cv2.dilate(thres,(5,5)) thres = cv2.erode(thres,(5,5)) thres = cv2.erode(thres,(5,5)) #Traffic sign detection _,cnts,_ = cv2.findContours(thres,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) E=0 for i in cnts: area = cv2.contourArea(i) if(area>1000 and avoid_repeat_sign == 0): M = cv2.moments(i) _,(ma,mb),_ = cv2.fitEllipse(i) E = M['m00']/(math.pi*(ma/2)*(mb/2)) if(E>0.95): avoid_repeat_sign = 20 # no sign would be detected for next 20 frame x,y,w,h = cv2.boundingRect(i) detected_sign_image = img_sign[y:y+h,x:x+w] cv2.rectangle(img_sign, (x,y), (x+w,y+h), (0,255,255), 3) avoid_repeat_sign = max(--avoid_repeat_sign , 0) cv2.imshow('sign',img_sign) cv2.waitKey(50) cv2.destroyAllWindows() cap.release() <file_sep>import os import numpy as np import cv2 from matplotlib import pyplot as plt import tensorflow as tf import pickle import math np.random.seed(1337) import keras from keras.preprocessing.image import ImageDataGenerator from keras.applications.mobilenet import MobileNet from keras.callbacks import ReduceLROnPlateau from google.colab import drive drive.mount('/content/drive') train_datagen = ImageDataGenerator( rescale=1./255, width_shift_range = 0.3, height_shift_range = 0.3, shear_range=0.2, zoom_range=0.2) val_datagen = ImageDataGenerator(rescale=1./255) """ ***Change PATH*** """ train_generator = train_datagen.flow_from_directory( '/content/drive/My Drive/Colab Notebooks/tsr_car_automation/Large_data/train', target_size=(64, 64), class_mode='categorical', color_mode = "grayscale") validation_generator = val_datagen.flow_from_directory( '/content/drive/My Drive/Colab Notebooks/tsr_car_automation/Large_data/val', target_size=(64, 64), class_mode='categorical', color_mode = "grayscale") """ Define model. Reduced MobileNet Architecture """ def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha,depth_multiplier=1, strides=(1, 1), block_id=1): x = inputs x = keras.layers.DepthwiseConv2D((3, 3),padding='same' if strides == (1, 1) else 'valid',depth_multiplier=depth_multiplier,strides=strides,use_bias=True,name='conv_dw_%d' % block_id)(x) x = keras.layers.BatchNormalization(name='conv_dw_%d_bn' % block_id)(x) x = keras.layers.ReLU(6., name='conv_dw_%d_relu' % block_id)(x) x = keras.layers.Conv2D(pointwise_conv_filters, (1, 1),padding='same',use_bias=False,strides=(1, 1),name='conv_pw_%d' % block_id)(x) x = keras.layers.BatchNormalization(name='conv_pw_%d_bn' % block_id)(x) return keras.layers.ReLU(6., name='conv_pw_%d_relu' % block_id)(x) def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)): x = inputs x = keras.layers.ZeroPadding2D(padding=((0, 1), (0, 1)), name='conv1_pad')(inputs) x = keras.layers.Conv2D(filters, kernel,padding='valid',use_bias=False,strides=strides,name='conv1')(x) x = keras.layers.BatchNormalization(name='conv1_bn')(x) return keras.layers.ReLU(6., name='conv1_relu')(x) def MobileNet(alpha=1.0,depth_multiplier=1,dropout=1e-3,classes=3): #rows = 64 #cols = 64 img_input = keras.layers.Input((64,64,1)) x = img_input x = _conv_block(x, 32, alpha, strides=(2, 2)) x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1) x = _depthwise_conv_block(x, 128, alpha, depth_multiplier,strides=(2, 2), block_id=2) x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3) x = _depthwise_conv_block(x, 256, alpha, depth_multiplier,strides=(2, 2), block_id=4) x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5) x = _depthwise_conv_block(x, 512, alpha, depth_multiplier,strides=(2, 2), block_id=6) x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7) shape = (1, 1, int(512 * alpha)) x = keras.layers.GlobalAveragePooling2D()(x) x = keras.layers.Reshape(shape, name='reshape_1')(x) x = keras.layers.Dropout(dropout, name='dropout')(x) x = keras.layers.Conv2D(classes, (1, 1),padding='same',name='conv_preds')(x) x = keras.layers.Reshape((classes,), name='reshape_2')(x) output = keras.layers.Activation('softmax', name='act_softmax')(x) model = keras.models.Model(img_input, output) return model model = MobileNet() adam = keras.optimizers.Adam(lr = 0.001) model.compile(optimizer = "adam" , loss = "categorical_crossentropy" , metrics = ["acc"]) #model.summary() """ Train model. """ reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.001) example = model.fit_generator( train_generator, epochs=100, validation_data=validation_generator, shuffle = True, callbacks = [reduce_lr]) """ Test model on test set """ name = os.listdir('/content/drive/My Drive/Colab Notebooks/Large_data/Test') test_images = [] for i in range(len(name)): img = cv2.imread('/content/drive/My Drive/Colab Notebooks/Large_data/Test/' + name[i],0) img = cv2.resize(img,(64,64)) test_images.append(img) #print('Test' + str(i)) test_images = np.array(test_images) test_images = test_images/255.0 test_images = np.expand_dims(test_images,3) final = model.predict(test_images) print(final) pred = [] for i in final: pred.append(np.argmax(i)) print(pred) """ Plot metrics """ print(example.history.keys()) plt.plot(example.history['acc']) plt.plot(example.history['val_acc']) plt.xlabel('epochs') plt.ylabel('accuracy') plt.legend(['train', 'val'], loc = 'upper left') plt.show() path = '/content/drive/My Drive/Colab Notebooks/rmn1' #the path of the directory in which you have to save model test_path = '/content/drive/My Drive/Colab Notebooks/Large_data/Test' #directory where test images are present model.save(path + 'model.h5') tflite_converter = tf.lite.TFLiteConverter.from_keras_model_file(path + 'model.h5') tflite_model = tflite_converter.convert() open(path + 'model_lite.tflite','wb').write(tflite_model) with open('/content/drive/My Drive/Colab Notebooks/trainHistoryDict', 'wb') as f: pickle.dump(example.history, f) """ Get the traffic sign from the gif/video. """ avoid_repeat_sign = 0; final = [] cap = cv2.VideoCapture('/content/drive/My Drive/Colab Notebooks/demo.gif') while True: det_img = [] ret, frame = cap.read() if(not(ret)): break img_sign = cv2.resize(frame, (400,400)) img_hsv = cv2.cvtColor(img_sign, cv2.COLOR_BGR2HSV) min_hsv_blue = np.array([90,100,50]) max_hsv_blue = np.array([120,255,255]) threshold1 = cv2.inRange(img_hsv, min_hsv_blue, max_hsv_blue) thres = cv2.dilate(threshold1,(5,5)) thres = cv2.dilate(thres,(5,5)) thres = cv2.erode(thres,(5,5)) thres = cv2.erode(thres,(5,5)) conts,_ = cv2.findContours(thres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) E = 0 for i in conts: area = cv2.contourArea(i) if(area>100 and avoid_repeat_sign==0): M = cv2.moments(i) _,(ma,mb),_ = cv2.fitEllipse(i) E = M['m00']/(math.pi*(ma/2)*(mb/2)) if(E>0.95): avoid_repeat_sign = 2 x,y,w,h = cv2.boundingRect(i) det_img = img_sign[y:y+h,x:x+w] final.append(det_img) avoid_repeat_sign = max(--avoid_repeat_sign, 0) cv2.destroyAllWindows() cap.release() for img in final: cv2.imshow('img',img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.resize(img,(64,64)) img = np.array(img) img = img/255.0 img = np.expand_dims(img,3) img.resize((1,64,64,1)) print(np.argmax(model.predict(img))) """ For RPi integration. """ tflite_interpreter = tf.lite.Interpreter(model_path = path + 'model_lite.tflite') tflite_interpreter.allocate_tensors() input_tensor_index = tflite_interpreter.get_input_details()[0]['index'] output = tflite_interpreter.tensor(tflite_interpreter.get_output_details()[0]['index']) prediction = [] for img in final: cv2.imshow('img',img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.resize(img,(64,64)) img = np.array(img) img = img/255.0 img = np.expand_dims(img,3).astype(np.float32) img.resize((1,64,64,1)) tflite_interpreter.set_tensor(input_tensor_index,img) tflite_interpreter.invoke() pred = np.argmax(output()[0]) prediction.append(pred) print(prediction)<file_sep>import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread("E:\Computer Vision\Images\sign.png",1) hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) lower = np.array([0,0,0]) upper = np.array([15,250,255]) lower1 = np.array([165,0,0]) upper1 = np.array([179,250,255]) mask1 = cv2.inRange(hsv,lower,upper) mask2 = cv2.inRange(hsv,lower1,upper1) mask = mask1+mask2 #OR operation out = cv2.bitwise_and(img,img,mask = mask) gray = cv2.cvtColor(out,cv2.COLOR_BGR2GRAY) med = cv2.medianBlur(gray,5) #removing noise hough = cv2.HoughCircles(med,cv2.HOUGH_GRADIENT,8,img.shape[0]/64,param1=200,param2 = 150,minRadius=2,maxRadius=300) if hough is not None: for i in hough[0, :]: cv2.circle(out, (i[0], i[1]), i[2], (255, 255, 0), 2) cv2.imshow("final",out) cv2.waitKey() cv2.destroyAllWindows()<file_sep>""" Reduced MobileNet Model. """ import keras def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha,depth_multiplier=1, strides=(1, 1), block_id=1): x = inputs x = keras.layers.DepthwiseConv2D((3, 3),padding='same' if strides == (1, 1) else 'valid',depth_multiplier=depth_multiplier,strides=strides,use_bias=True,name='conv_dw_%d' % block_id)(x) x = keras.layers.BatchNormalization(name='conv_dw_%d_bn' % block_id)(x) x = keras.layers.ReLU(6., name='conv_dw_%d_relu' % block_id)(x) x = keras.layers.Conv2D(pointwise_conv_filters, (1, 1),padding='same',use_bias=False,strides=(1, 1),name='conv_pw_%d' % block_id)(x) x = keras.layers.BatchNormalization(name='conv_pw_%d_bn' % block_id)(x) return keras.layers.ReLU(6., name='conv_pw_%d_relu' % block_id)(x) def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)): x = inputs x = keras.layers.ZeroPadding2D(padding=((0, 1), (0, 1)), name='conv1_pad')(inputs) x = keras.layers.Conv2D(filters, kernel,padding='valid',use_bias=False,strides=strides,name='conv1')(x) x = keras.layers.BatchNormalization(name='conv1_bn')(x) return keras.layers.ReLU(6., name='conv1_relu')(x) def MobileNet(alpha=1.0,depth_multiplier=1,dropout=1e-3,classes=3): #rows = 64 #cols = 64 img_input = keras.layers.Input((64,64,1)) x = img_input x = _conv_block(x, 32, alpha, strides=(2, 2)) x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1) x = _depthwise_conv_block(x, 128, alpha, depth_multiplier,strides=(2, 2), block_id=2) x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3) x = _depthwise_conv_block(x, 256, alpha, depth_multiplier,strides=(2, 2), block_id=4) x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5) x = _depthwise_conv_block(x, 512, alpha, depth_multiplier,strides=(2, 2), block_id=6) x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7) shape = (1, 1, int(512 * alpha)) x = keras.layers.GlobalAveragePooling2D()(x) x = keras.layers.Reshape(shape, name='reshape_1')(x) x = keras.layers.Dropout(dropout, name='dropout')(x) x = keras.layers.Conv2D(classes, (1, 1),padding='same',name='conv_preds')(x) x = keras.layers.Reshape((classes,), name='reshape_2')(x) output = keras.layers.Activation('softmax', name='act_softmax')(x) model = keras.models.Model(img_input, output) return model<file_sep>The dataset used for training is provided [here](https://drive.google.com/drive/folders/1cxvK8ZMuypgPHGeZ3Uf8jfn7M-O2-M3j?usp=sharing)<file_sep>#Implementing hough transform on a video(gif) import cv2 import numpy as np cap = cv2.VideoCapture("E:\Computer Vision\Images\demo.gif") while True: ret, frame = cap.read() if ret == True: gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) gauss = cv2.GaussianBlur(gray,(3,3),0,0) hough = cv2.HoughCircles(gauss,cv2.HOUGH_GRADIENT,1,80,param1=200,param2 = 28,minRadius=4,maxRadius=25) if hough is not None: hough = np.uint16(np.around(hough)) for i in hough[0, :]: cv2.circle(frame, (i[0], i[1]), i[2], (255, 255, 0), 2) cv2.imshow("out",frame) if cv2.waitKey(50) & 0xFF == ord('q'): break else: break cap.release() cv2.destroyAllWindows()
c5e535fc0041ff97e7b12b2b24901b3d57ba44b7
[ "Markdown", "Python" ]
7
Python
IEEE-NITK/TSR_based_car_automation
fd09e5bc13766721dc1eed53f532146ae76987a2
c846308d591d48eafd1e70d00e6c22bed7ddc028
refs/heads/master
<file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Entities.Sprites; using Phantoms.Helpers; using System; using System.Collections.Generic; namespace Phantoms.Entities.Ghostly { public class PhantomExpression { public enum Expression { Cry, Love, Bored, Sing } private static Texture2D _expressionSheet; private static Texture2D ExpressionSheet { get { return GetTexture(); } } private Body body; private Phantom phantom; private AnimatedSprite Animation { get { return ((AnimatedSprite)body.Sprite); } } public bool IsExpressing { get { return Animation.IsPlaying; } } public Expression Main { get; private set; } public PhantomExpression(Phantom phantom) { Initialize(phantom); } public void ExpressPhantom() { ExpressPhantom(GetExpressionName(Main)); } public void ExpressPhantom(Expression expression) { ExpressPhantom(GetExpressionName(expression)); } public void ExpressPhantom(string expression) { if (IsExpressing) return; Animation.Stop(); Animation.Change(expression); UpdatePosition(); Animation.Play(); } public string GetCurrentExpressionName() { if (!IsExpressing) return ""; return Animation.CurrentName; } public void UpdatePosition() { Vector2 position = new Vector2(phantom.Position.X + (phantom.Width * .5f), phantom.Position.Y - (body.Height * .75f)); body.MoveTo(position, setFacingDirection: false, keepOnScreenBounds: false); } public void Update(GameTime gameTime) { Animation.Update(gameTime); } public void StopExpressing() { if (IsExpressing) Animation.Stop(); } public void Draw(SpriteBatch spriteBatch) { body.Draw(spriteBatch); } private string GetExpressionName(Expression expression) { switch (expression) { case Expression.Cry: return "Cry"; case Expression.Love: return "Love"; case Expression.Bored: return "Bored"; case Expression.Sing: return "Sing"; default: throw new Exception("ops"); } } private void Initialize(Phantom phantom) { Dictionary<string, Frame[]> expressionsFrames = new Dictionary<string, Frame[]>(); expressionsFrames.Add("Cry", GetCryFrames()); expressionsFrames.Add("Love", GetLoveFrames()); expressionsFrames.Add("Bored", GetBoredFrames()); expressionsFrames.Add("Sing", GetSingFrames()); AnimatedSprite animation = null; int ciclesCount = 0; animation = new AnimatedSprite(ExpressionSheet, expressionsFrames, onFrameChange: (sender, e) => { int totalCicles = animation.CurrentName == "Love" || animation.CurrentName == "Sing" ? 3 : 1; if (e.HasCompletedCicle) ciclesCount++; if (ciclesCount >= totalCicles) { ciclesCount = 0; animation.Stop(); } }, autoPlay: false); Array values = Enum.GetValues(typeof(Expression)); Random random = new Random(); Main = (Expression)values.GetValue(random.Next(values.Length)); body = new Body(Vector2.Zero, animation, scale: 3f); body.SetOrigin(.5f); this.phantom = phantom; } private Frame[] GetCryFrames() { return new Frame[] { new Frame() { Name = "cry_1", Source = new Rectangle(0, 12, 7, 7), Duration = 100 }, new Frame() { Name = "cry_2", Source = new Rectangle(7, 12, 7, 7), Duration = 100 }, new Frame() { Name = "cry_3", Source = new Rectangle(14, 12, 7, 7), Duration = 100 }, new Frame() { Name = "cry_3", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_4", Source = new Rectangle(21, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_5", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_6", Source = new Rectangle(21, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_7", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_8", Source = new Rectangle(28, 12, 7, 7), Duration = 100 }, new Frame() { Name = "cry_9", Source = new Rectangle(35, 12, 7, 7), Duration = 100 }, new Frame() { Name = "cry_10", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_11", Source = new Rectangle(21, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_12", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_13", Source = new Rectangle(21, 12, 7, 7), Duration = 200 }, new Frame() { Name = "cry_14", Source = new Rectangle(0, 12, 7, 7), Duration = 200 }, }; } private Frame[] GetLoveFrames() { return new Frame[] { new Frame() { Name = "love_1", Source = new Rectangle(0, 0, 7, 6), Duration = 250 }, new Frame() { Name = "love_2", Source = new Rectangle(14, 0, 7, 6), Duration = 250 } }; } private Frame[] GetBoredFrames() { return new Frame[] { new Frame() { Name = "bored_1", Source = new Rectangle(42, 11, 8, 8), Duration = 500 }, new Frame() { Name = "bored_2", Source = new Rectangle(50, 11, 8, 8), Duration = 250 }, new Frame() { Name = "bored_3", Source = new Rectangle(42, 11, 8, 8), Duration = 500 }, new Frame() { Name = "bored_4", Source = new Rectangle(58, 11, 8, 8), Duration = 1000 } }; } private Frame[] GetSingFrames() { return new Frame[] { new Frame() { Name = "sing_1", Source = new Rectangle(28, 0, 5, 9), Duration = 250 }, new Frame() { Name = "sing_2", Source = new Rectangle(33, 0, 5, 9), Duration = 250 }, new Frame() { Name = "sing_3", Source = new Rectangle(38, 0, 5, 9), Duration = 125 }, new Frame() { Name = "sing_4", Source = new Rectangle(43, 0, 5, 9), Duration = 125 }, new Frame() { Name = "sing_5", Source = new Rectangle(48, 0, 5, 9), Duration = 125 }, new Frame() { Name = "sing_6", Source = new Rectangle(53, 0, 5, 9), Duration = 125 } }; } private static Texture2D GetTexture() { if (_expressionSheet == null) _expressionSheet = Loader.LoadTexture("phantom_expressions_sheet"); return _expressionSheet; } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Entities.Sprites; using Phantoms.Inputs; using Phantoms.Interfaces; using System.Collections.Generic; namespace Phantoms.Entities.Ghostly { public class Phantom : Body { private readonly IInput input = new KeyboardInput(); protected PhantomExpression expression; protected AnimatedSprite Animation { get { return (Sprite as AnimatedSprite); } } public float Speed { get { return .6f; } } public bool HasDisappeared { get { return !isActive; } private set { isActive = !value; } } public bool IsDisappearing { get; private set; } public bool IsTeleporting { get; private set; } public bool IsBot { get; protected set; } public string CurrentPlace { get; set; } public Phantom(AnimatedSprite animation, Vector2 position) : base(position, sprite: animation, scale: 5f) { expression = new PhantomExpression(this); } public Phantom(Texture2D spriteSheet, Vector2 position) : base(position, sprite: GetAnimationDefault(spriteSheet), scale: 5f) { expression = new PhantomExpression(this); } public static Phantom New(Texture2D spriteSheet, Vector2 position) { return new Phantom(GetAnimationDefault(spriteSheet), position); } protected static AnimatedSprite GetAnimationDefault(Texture2D spriteSheet) { Dictionary<string, Frame[]> animationFrames = new Dictionary<string, Frame[]>(); animationFrames.Add("Idle", new Frame[] { new Frame() { Name = "idle", Source = new Rectangle(22, 0, 11, 11), Duration = 500 } }); animationFrames.Add("Walk", new Frame[] { new Frame() { Name = "walk_1", Source = new Rectangle(0, 0, 11, 11), Duration = 100 }, new Frame() { Name = "walk_2", Source = new Rectangle(11, 0, 11, 11), Duration = 100 } }); return new AnimatedSprite(spriteSheet, animationFrames); } public override void Update(GameTime gameTime) { if (HasDisappeared) return; base.Update(gameTime); if (expression.IsExpressing && !IsDisappearing) expression.Update(gameTime); if (IsBot || IsDisappearing || IsTeleporting) return; input.Update(); Vector2 direction = input.DirectionalPressing(); Animation.Change(direction == Vector2.Zero ? "Idle" : "Walk"); Move(direction * (Speed * Scale * Global.ScreenScale)); if (input.ActivateExpressionOne()) expression.ExpressPhantom(PhantomExpression.Expression.Bored); else if (input.ActivateExpressionTwo()) expression.ExpressPhantom(PhantomExpression.Expression.Cry); else if (input.ActivateExpressionThree()) expression.ExpressPhantom(PhantomExpression.Expression.Love); else if (input.ActivateExpressionFour()) expression.ExpressPhantom(PhantomExpression.Expression.Sing); if (input.InteractionJustPressed() && !IsTeleporting) { if (CollidesWith(MainGame.World.Vortex)) BeginTeleport(); else expression.ExpressPhantom(); } } public void Move(Vector2 movement) { if (IsBot) MoveTo(movement); else MoveAndSlide(movement); if (expression.IsExpressing) expression.UpdatePosition(); } protected void BeginTeleport() { IsTeleporting = true; if (expression.IsExpressing) expression.StopExpressing(); Animation.Pause(); SetOrigin(.5f); Spin(FacingDirection); FadeOut(); Shrink(onResizeEnded: (sender, e) => Teleport()); } protected void Teleport() { if (!IsBot) { MainGame.World.TeleportPlayerTo(MainGame.World.Vortex.Destiny); CurrentPlace = MainGame.World.PlaceName; } IsTeleporting = false; Scale = ScaleDefault; StopFade(); StopSpin(); Sprite.Opacity = 1f; Sprite.Rotation = 0; SetOrigin(0); Animation.Play(); } public string GetCurrentExpressionName() { return expression.GetCurrentExpressionName(); } public void Disappear() { Animation.Pause(); IsDisappearing = true; expression.StopExpressing(); FadeOut(onFadeEnded: (sender, e) => HasDisappeared = true); } public override void Draw(SpriteBatch spriteBatch) { if (!IsVisible) return; if (expression.IsExpressing && !IsTeleporting) expression.Draw(spriteBatch); base.Draw(spriteBatch); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Interfaces; using System; namespace Phantoms.Entities.Sprites { public class Sprite { private Texture2D spriteStrip; public virtual Rectangle Source { get; set; } public virtual int Width { get { return spriteStrip.Width; } } public virtual int Height { get { return spriteStrip.Height; } } public float Rotation { get; set; } public float Opacity { get; set; } public Vector2 Origin { get; set; } public Sprite(Texture2D spriteStrip, Rectangle source = default(Rectangle), float opacity = 1f, Vector2 origin = default(Vector2), float rotation = 0) { this.spriteStrip = spriteStrip; Source = source == default(Rectangle) ? new Rectangle(0, 0, Width, Height) : source; Opacity = opacity; Origin = origin; Rotation = rotation; } public void Tint(Color tint) { Color[] pixels = new Color[spriteStrip.Width * spriteStrip.Height]; spriteStrip.GetData(pixels); for (int i = 0; i < pixels.Length; i++) { byte r = (byte)MathHelper.Clamp(((tint.R - 255) + pixels[i].R), 0, 255); byte g = (byte)MathHelper.Clamp(((tint.G - 255) + pixels[i].G), 0, 255); byte b = (byte)MathHelper.Clamp(((tint.B - 255) + pixels[i].B), 0, 255); pixels[i] = new Color(r, g, b, pixels[i].A); } Texture2D tintedTexture = new Texture2D(spriteStrip.GraphicsDevice, spriteStrip.Width, spriteStrip.Height); tintedTexture.SetData(pixels); spriteStrip = tintedTexture; } public void Draw(SpriteBatch spriteBatch, Vector2 position, Color color = default(Color), float scale = 1, SpriteEffects effect = SpriteEffects.None, float layerDepth = 0) { color = color == default(Color) ? Color.White : color; spriteBatch.Draw(spriteStrip, position, Source, color * Opacity, Rotation, Origin, scale * Global.ScreenScale, effect, layerDepth); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Phantoms.Abstracts; using Phantoms.Data; using Phantoms.Entities; using Phantoms.Entities.Ghostly; using Phantoms.Entities.Sprites; using Phantoms.Helpers; using Phantoms.Manipulators; using Phantoms.Sounds; using System; using System.Collections.Generic; namespace Phantoms.Scenes { public class World : Cyclic { public enum Local { Paradise, GasStation, Lake, LittleHouse, BrownGrass } public string PlaceName { get; private set; } public Body Place { get; private set; } public Vortex Vortex { get; private set; } public Phantom Player { get; private set; } public PhantomBotLog PlayerLog { get; private set; } public List<PhantomBot> PhantomBots { get; private set; } public float ElapsedTime { get; set; } public static Local[] ExistingPlaces { get; } = (Local[])Enum.GetValues(typeof(Local)); public World(Phantom player, List<PhantomBot> phantomBots) { Player = player; PhantomBots = phantomBots; Vortex = new Vortex("vortex", Vector2.Zero); Random random = new Random(); Color phantomColor = new Color(random.Next(256), random.Next(256), random.Next(256)); Player.Sprite.Tint(phantomColor); SetPlace(ExistingPlaces[random.Next(ExistingPlaces.Length)]); Player.CurrentPlace = PlaceName; player.MoveTo(new Vector2(random.Next(Camera.AreaWidth - player.Width + 1), random.Next(Camera.AreaHeight - player.Height + 1))); PlayerLog = new PhantomBotLog() { Color = phantomColor, Traces = new List<PhantomTraceLog>() { new PhantomTraceLog() { ElapsedTime = 0, Position = player.Position, Expression = "" } } }; SoundEffect soundTrack = Loader.LoadSound("dominos_revisitado"); SoundTrack.Load(soundTrack, play: true, playOnLoop: false); } public void TeleportPlayerTo(Local local) { SetPlace(local); Player.MoveTo(Vortex.Position, false); } public Local GetCurrentLocal() { switch (PlaceName) { case "Paradise": return Local.Paradise; case "Gas Station": return Local.GasStation; case "Lake": return Local.Lake; case "Little House": return Local.LittleHouse; case "Brown Grass": return Local.BrownGrass; default: throw new Exception("kd esse luga meu xapa"); } } private void SetPlace(Local local) { switch (local) { case Local.Paradise: PlaceName = "Paradise"; Place = new Body(Vector2.Zero, sprite: new Sprite(Loader.LoadTexture("paisagi"))); break; case Local.GasStation: PlaceName = "Gas Station"; Place = new Body(Vector2.Zero, sprite: new Sprite(Loader.LoadTexture("posto"))); break; case Local.Lake: PlaceName = "Lake"; Place = new Body(Vector2.Zero, sprite: new Sprite(Loader.LoadTexture("lago"))); break; case Local.LittleHouse: PlaceName = "Little House"; Place = new Body(Vector2.Zero, sprite: new Sprite(Loader.LoadTexture("casinha"))); break; case Local.BrownGrass: PlaceName = "Brown Grass"; Place = new Body(Vector2.Zero, sprite: new Sprite(Loader.LoadTexture("matagal"))); break; } Camera.AreaWidth = Place.Width; Camera.AreaHeight = Place.Height; Vortex.StopSpin(); Vortex.SetOrigin(0); Vortex.MoveTo(GetVortexPlacePosition(local) * Global.ScreenScale, false); Vortex.SetOrigin(.5f); Vortex.Spin(Global.HorizontalDirection.Left, 2f); Vortex.SetRandomDestiny(GetCurrentLocal()); } private Vector2 GetVortexPlacePosition(Local local) { switch (local) { case Local.Paradise: return new Vector2(1115, 200); case Local.GasStation: return new Vector2(48, 845); case Local.Lake: return new Vector2(606, 169); case Local.LittleHouse: return new Vector2(840, 192); case Local.BrownGrass: return new Vector2(389, 339); default: throw new Exception("kd esse luga meu xapa"); } } public override void Update(GameTime gameTime) { ElapsedTime += gameTime.ElapsedGameTime.Milliseconds; Player.Update(gameTime); Camera.Update(Player); Vortex.Update(gameTime); if (!Player.IsDisappearing) PlayerLog.Traces.Add( new PhantomTraceLog() { ElapsedTime = ElapsedTime, Place = PlaceName, Position = Player.Position / Global.ScreenScale, Expression = Player.GetCurrentExpressionName(), Scale = Player.Scale, Opacity = Player.Sprite.Opacity, Rotation = Player.Sprite.Rotation, Origin = Player.Sprite.Origin }); if (SoundTrack.HasEnded && !Player.IsDisappearing) Player.Disappear(); foreach (PhantomBot phantomBot in PhantomBots) phantomBot.Update(gameTime); } public override void Draw(SpriteBatch spriteBatch) { Place.Draw(spriteBatch); Vortex.Draw(spriteBatch); foreach (PhantomBot phantomBot in PhantomBots) phantomBot.Draw(spriteBatch); Player.Draw(spriteBatch); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Abstracts; using Phantoms.Entities.Sprites; using Phantoms.Manipulators; using System; using static Phantoms.Global; namespace Phantoms.Entities { public class Body : Cyclic { private Rectangle? customCollision; protected bool isActive = true; private Fade fade = null; private Spin spin = null; private Size size = null; public Sprite Sprite { get; private set; } public float Scale { get; set; } public HorizontalDirection FacingDirection { get; set; } public Vector2 Position { get; private set; } public Rectangle Collision { get { Vector2 spriteSource = (Sprite?.Origin ?? Vector2.Zero) * (Scale * ScreenScale); return customCollision ?? new Rectangle((int)(Position.X - spriteSource.X), (int)(Position.Y - spriteSource.Y), Width, Height); } } public float ScaleDefault { get; private set; } public int Width { get { return (int)((Sprite?.Width ?? 0) * (Scale * ScreenScale)); } } public int Height { get { return (int)((Sprite?.Height ?? 0) * (Scale * ScreenScale)); } } public bool IsFading { get { return fade != null; } } public bool IsSpinning { get; private set; } public bool IsVisible { get; set; } public Body(Vector2 position, Sprite sprite = null, HorizontalDirection facingDirection = HorizontalDirection.Right, float scale = 1f, Rectangle? customCollision = null) { IsVisible = true; Sprite = sprite; FacingDirection = facingDirection; Scale = scale; ScaleDefault = scale; this.customCollision = customCollision; MoveTo(position); } public void ReplaceSprite(Sprite sprite, Rectangle? customCollision = null) { Sprite = sprite; this.customCollision = customCollision; } public void MoveTo(Vector2 position, bool setFacingDirection = true, bool keepOnScreenBounds = true) { if (Position.X != position.X && setFacingDirection) { float horizontalDifference = position.X - Position.X; FacingDirection = horizontalDifference < 0 ? HorizontalDirection.Left : HorizontalDirection.Right; } if (keepOnScreenBounds) { position.X = MathHelper.Clamp(position.X, 0, Camera.AreaWidth - Width); position.Y = MathHelper.Clamp(position.Y, 0, Camera.AreaHeight - Height); } Position = position; } public void MoveTo(int x, int y, bool setFacingDirection = true, bool keepOnScreenBounds = true) { MoveTo(new Vector2(x, y), setFacingDirection, keepOnScreenBounds); } public void MoveHorizontally(int x, bool setFacingDirection = true, bool keepOnScreenBounds = true) { MoveTo(new Vector2(x, Position.Y), setFacingDirection, keepOnScreenBounds); } public void MoveVertically(int y, bool setFacingDirection = true, bool keepOnScreenBounds = true) { MoveTo(new Vector2(Position.X, y), setFacingDirection, keepOnScreenBounds); } public void MoveAndSlide(int x, int y, bool setFacingDirection = true, bool keepOnScreenBounds = true) { MoveTo(new Vector2(Position.X + x, Position.Y + y), setFacingDirection, keepOnScreenBounds); } public void MoveAndSlide(Vector2 position, bool setFacingDirection = true, bool keepOnScreenBounds = true) { if (position != Vector2.Zero) MoveTo(Position + position, setFacingDirection, keepOnScreenBounds); } public void SetOrigin(float origin, bool keepInPlace = true) { float totalScale = (Scale * ScreenScale); Vector2 updatedOrigin = origin == 0 ? Vector2.Zero : new Vector2((Width * origin) / totalScale, (Height * origin) / totalScale); if (keepInPlace) MoveAndSlide((updatedOrigin * totalScale) - (Sprite.Origin * totalScale), false); Sprite.Origin = updatedOrigin; } public void SetOrigin(Vector2 origin, bool keepInPlace = true) { if (Sprite == null) return; float totalScale = (Scale * ScreenScale); Sprite.Origin = new Vector2((Width * origin.X) / totalScale, (Height * origin.Y) / totalScale) * -1; if (keepInPlace) MoveAndSlide(Sprite.Origin * totalScale); } public void CustomizeCollision(Rectangle collision) { customCollision = collision; } public void ResetCollisionToSpriteBounds() { customCollision = null; } public void FadeIn(float amount = .01f, EventHandler onFadeEnded = null) { Fade(Math.Abs(amount), 0, 1, onFadeEnded); } public void FadeOut(float amount = .01f, EventHandler onFadeEnded = null) { Fade(-Math.Abs(amount), 1, 0, onFadeEnded); } public void Fade(float amount, float from, float to, EventHandler onFadeEnded = null) { fade = new Fade(Sprite, amount, from, to, (sender, e) => { StopFade(); onFadeEnded?.Invoke(sender, EventArgs.Empty); }); } public void StopFade() { fade = null; } public void StopSpin() { spin = null; } public void StopResize() { size = null; } public void Spin(HorizontalDirection direction, float amount = 5, bool autoSpin = true, EventHandler onCicleCompleted = null) { spin = new Spin(Sprite, amount, direction, autoSpin, onCicleCompleted); } public void Spin(float amount, bool autoSpin = true, EventHandler onCicleCompleted = null) { spin = new Spin(Sprite, amount, autoSpin, onCicleCompleted); } public void Grow(float amount = .01f, float percent = 100, bool goBackToOriginalSizeOnEnded = true, EventHandler onResizeEnded = null) { size = new Size(this); size.Grow(amount, percent, (sender, e) => { StopResize(); onResizeEnded?.Invoke(sender, EventArgs.Empty); }); } public void Shrink(float amount = .01f, float percent = 100, EventHandler onResizeEnded = null) { size = new Size(this); size.Shrink(amount, percent, (sender, e) => { size = null; onResizeEnded?.Invoke(sender, EventArgs.Empty); }); } public bool CollidesWith(Body body) { return Collision.Intersects(body.Collision); } protected void UpdateSize(GameTime gameTime) { size?.Update(gameTime); } protected void UpdateFading(GameTime gameTime) { fade?.Update(gameTime); } protected void UpdateAnimation(GameTime gameTime) { if (Sprite != null && Sprite.GetType() == typeof(AnimatedSprite)) (Sprite as AnimatedSprite).Update(gameTime); } protected void UpdateSpinning(GameTime gameTime) { spin?.Update(gameTime); } public override void Update(GameTime gameTime) { if (!isActive) return; UpdateSize(gameTime); UpdateSpinning(gameTime); UpdateFading(gameTime); UpdateAnimation(gameTime); } public override void Draw(SpriteBatch spriteBatch) { if (!isActive || !IsVisible) return; Sprite?.Draw(spriteBatch, Position, scale: Scale, effect: FacingDirection == HorizontalDirection.Left ? SpriteEffects.FlipHorizontally : SpriteEffects.None); } } } <file_sep># Fantasmas boo <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Data; using Phantoms.Entities.Sprites; using System.Collections.Generic; using System.Linq; namespace Phantoms.Entities.Ghostly { public class PhantomBot : Phantom { private List<PhantomTraceLog> traces; private int currentTraceIndex = 0; public PhantomBot(AnimatedSprite sprite, PhantomBotLog log) : base(sprite, log.Traces.First().Position) { Initialize(log); } public PhantomBot(Texture2D spriteSheet, PhantomBotLog log) : base(spriteSheet, log.Traces.First().Position) { Initialize(log); } private void Initialize(PhantomBotLog log) { IsBot = true; traces = log.Traces; Sprite.Tint(log.Color); } public static PhantomBot New(Texture2D spriteSheet, PhantomBotLog log) { return new PhantomBot(GetAnimationDefault(spriteSheet), log); } public override void Update(GameTime gameTime) { if (traces.Count == 0) { if (!IsDisappearing) Disappear(); else base.Update(gameTime); return; } List<PhantomTraceLog> tracesJumped = new List<PhantomTraceLog>(); PhantomTraceLog nextTrace = traces[currentTraceIndex]; tracesJumped.Add(nextTrace); foreach (PhantomTraceLog trace in traces) { if (trace.ElapsedTime <= MainGame.World.ElapsedTime) { tracesJumped.Add(trace); nextTrace = trace; } else { Vector2 updatedPosition = trace.Position * Global.ScreenScale; Animation.Change(updatedPosition == Position ? "Idle" : "Walk"); Move(updatedPosition); if (!string.IsNullOrEmpty(trace.Expression) && !expression.IsExpressing) expression.ExpressPhantom(trace.Expression); if (string.IsNullOrEmpty(trace.Expression) && expression.IsExpressing) expression.StopExpressing(); Scale = trace.Scale; Sprite.Opacity = trace.Opacity; Sprite.Rotation = trace.Rotation; Sprite.Origin = trace.Origin; CurrentPlace = trace.Place; IsVisible = CurrentPlace == MainGame.World.PlaceName; break; } } traces.RemoveRange(0, tracesJumped.Count); base.Update(gameTime); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Phantoms.Interfaces; using System; using System.Collections.Generic; namespace Phantoms.Inputs { public class KeyboardInput : IInput { public KeyboardState currentKeyboardState; public KeyboardState previousKeyboardState; Keys leftKey; Keys rightKey; Keys upKey; Keys downKey; Keys interactionKey; Keys expressionOneKey; Keys expressionTwoKey; Keys expressionThreeKey; Keys expressionFourKey; public KeyboardInput() { SetDefaultKeysByIndex(); } public void SetDefaultKeysByIndex() { leftKey = Keys.Left; rightKey = Keys.Right; upKey = Keys.Up; downKey = Keys.Down; interactionKey = Keys.Space; Dictionary<int, Keys> expressions = new Dictionary<int, Keys>(); List<Keys> expressionsOptions = new List<Keys>() { Keys.D1, Keys.D2, Keys.D3, Keys.D4 }; Random random = new Random(); for (int i = 0; i < 4; i++) { Keys expression = expressionsOptions[random.Next(expressionsOptions.Count)]; expressions.Add(i, expression); expressionsOptions.Remove(expression); } expressionOneKey = expressions[0]; expressionTwoKey = expressions[1]; expressionThreeKey = expressions[2]; expressionFourKey = expressions[3]; } public void Update() { previousKeyboardState = currentKeyboardState; currentKeyboardState = Keyboard.GetState(); } public Vector2 DirectionalPressing() { float x = currentKeyboardState.IsKeyDown(leftKey) ? -1 : currentKeyboardState.IsKeyDown(rightKey) ? 1 : 0; float y = currentKeyboardState.IsKeyDown(upKey) ? -1 : currentKeyboardState.IsKeyDown(downKey) ? 1 : 0; return new Vector2(x, y); } public bool InteractionJustPressed() { return previousKeyboardState.IsKeyUp(interactionKey) && currentKeyboardState.IsKeyDown(interactionKey); } public bool ActivateExpressionOne() { return previousKeyboardState.IsKeyUp(expressionOneKey) && currentKeyboardState.IsKeyDown(expressionOneKey); } public bool ActivateExpressionTwo() { return previousKeyboardState.IsKeyUp(expressionTwoKey) && currentKeyboardState.IsKeyDown(expressionTwoKey); } public bool ActivateExpressionThree() { return previousKeyboardState.IsKeyUp(expressionThreeKey) && currentKeyboardState.IsKeyDown(expressionThreeKey); } public bool ActivateExpressionFour() { return previousKeyboardState.IsKeyUp(expressionFourKey) && currentKeyboardState.IsKeyDown(expressionFourKey); } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Phantoms.Data; using Phantoms.Entities.Ghostly; using Phantoms.Helpers; using Phantoms.Manipulators; using Phantoms.Scenes; using System; using System.Collections.Generic; namespace Phantoms { /// <summary> /// This is the main type for your game. /// </summary> public class MainGame : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public static World World { get; set; } public MainGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Loader.Initialize(Content); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); AdjustScreen(true); Texture2D phantomTexture = Loader.LoadTexture("fantasminha_white"); Phantom player = Phantom.New(phantomTexture, Vector2.Zero); List<PhantomBotLog> botLogs = Loader.LoadDeserializedJsonFile<List<PhantomBotLog>>("phatom_bots"); List<PhantomBot> phantomBots = new List<PhantomBot>(); foreach (PhantomBotLog botLog in botLogs) phantomBots.Add(PhantomBot.New(phantomTexture, botLog)); World = new World(player, phantomBots); } public void ToggleFullScreen() { graphics.IsFullScreen = !graphics.IsFullScreen; AdjustScreen(); } public void AdjustScreen(bool isFullScreen) { graphics.IsFullScreen = isFullScreen; AdjustScreen(); } private void AdjustScreen() { if (graphics.IsFullScreen) { Global.ScreenWidth = GraphicsDevice.DisplayMode.Width; Global.ScreenHeight = GraphicsDevice.DisplayMode.Height; graphics.PreferredBackBufferWidth = Global.ScreenWidth; graphics.PreferredBackBufferHeight = Global.ScreenHeight; graphics.ApplyChanges(); decimal scaleX = (decimal)Global.ScreenWidth / GraphicsDeviceManager.DefaultBackBufferWidth; decimal scaleY = (decimal)Global.ScreenHeight / GraphicsDeviceManager.DefaultBackBufferHeight; Global.ScreenScale = (int)Math.Ceiling(scaleX > scaleY ? scaleX : scaleY); } else { Global.ScreenWidth = GraphicsDeviceManager.DefaultBackBufferWidth; Global.ScreenHeight = GraphicsDeviceManager.DefaultBackBufferHeight; Global.ScreenScale = 1f; } Camera.AreaWidth = World?.Place.Width ?? 0; Camera.AreaHeight = World?.Place.Height ?? 0; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape) || World.Player.HasDisappeared) { if (World.Player.HasDisappeared) { List<PhantomBotLog> botLogs = Loader.LoadDeserializedJsonFile<List<PhantomBotLog>>("phatom_bots"); botLogs.Add(World.PlayerLog); if (botLogs.Count > 9) botLogs.RemoveRange(0, botLogs.Count - 9); Loader.SaveJsonFile("phatom_bots", botLogs); } Exit(); } World.Update(gameTime); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, Camera.ViewMatrix); World.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } } <file_sep>using Microsoft.Xna.Framework.Audio; using System; namespace Phantoms.Sounds { public static class SoundTrack { static SoundEffectInstance song; public static bool HasEnded { get { return song.State == SoundState.Stopped; } } public static TimeSpan Duration { get; private set; } public static void Load(SoundEffect song, bool play = false, bool playOnLoop = true) { SoundTrack.song = song.CreateInstance(); Duration = song.Duration; if (play) Play(playOnLoop); } public static void Play(bool playOnLoop = true) { song.IsLooped = playOnLoop; song.Play(); } } } <file_sep>using Microsoft.Xna.Framework; using Phantoms.Entities.Sprites; using System; namespace Phantoms.Manipulators { public class Fade { private float amount; private float limit; private Sprite fadingSprite; private event EventHandler onFadeEnded; public bool HasEnded { get; private set; } public Fade(Sprite fadingSprite, float amount, float from, float to, EventHandler onFadeEnded = null) { this.fadingSprite = fadingSprite; this.amount = amount; fadingSprite.Opacity = from; limit = to; this.onFadeEnded = onFadeEnded; } public void Update(GameTime gameTime) { fadingSprite.Opacity += amount; if ((Math.Sign(amount) < 0 && fadingSprite.Opacity <= limit) || (Math.Sign(amount) > 0 && fadingSprite.Opacity >= limit)) { fadingSprite.Opacity = limit; HasEnded = true; onFadeEnded?.Invoke(this, EventArgs.Empty); } } } } <file_sep>using Microsoft.Xna.Framework; namespace Phantoms.Interfaces { public interface IInput { void Update(); Vector2 DirectionalPressing(); bool InteractionJustPressed(); bool ActivateExpressionOne(); bool ActivateExpressionTwo(); bool ActivateExpressionThree(); bool ActivateExpressionFour(); } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Phantoms.Entities.Sprites; using Phantoms.Helpers; using Phantoms.Scenes; using System; using System.Collections.Generic; using System.Linq; namespace Phantoms.Entities { public class Vortex : Body { public World.Local Destiny { get; set; } public Vortex(Texture2D spriteSheet, Vector2 position) : base(position, sprite: GetAnimationDefault(spriteSheet)) { } public Vortex(string textureName, Vector2 position) : base(position, sprite: GetAnimationDefault(Loader.LoadTexture(textureName))) { } protected static AnimatedSprite GetAnimationDefault(Texture2D spriteSheet) { Dictionary<string, Frame[]> animationFrames = new Dictionary<string, Frame[]>(); animationFrames.Add("Default", new Frame[] { new Frame() { Name = "spin_1", Source = new Rectangle(0, 0, 90, 84), Duration = 100 }, new Frame() { Name = "spin_2", Source = new Rectangle(90, 0, 90, 84), Duration = 100 }, new Frame() { Name = "spin_3", Source = new Rectangle(180, 0, 90, 84), Duration = 100 } }); return new AnimatedSprite(spriteSheet, animationFrames); } public void SetRandomDestiny(World.Local currentPlace) { Random random = new Random(); IEnumerable<World.Local> avaiablePlaces = (from w in World.ExistingPlaces where w != currentPlace select w); Destiny = avaiablePlaces.ElementAt(random.Next(avaiablePlaces.Count())); } } } <file_sep>using Microsoft.Xna.Framework; using System.Collections.Generic; namespace Phantoms.Data { public class PhantomBotLog { public Color Color { get; set; } public List<PhantomTraceLog> Traces { get; set; } } public class PhantomTraceLog { public float ElapsedTime { get; set; } public string Place { get; set; } public string Expression { get; set; } public float Scale { get; set; } public float Opacity { get; set; } public float Rotation { get; set; } public Vector2 Position { get; set; } public Vector2 Origin { get; set; } } } <file_sep>using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Phantoms.Interfaces { public interface IVisual { int Width { get; } int Height { get; } void Draw(SpriteBatch spriteBatch, Vector2 position, Color color = default(Color), float rotation = 0, Vector2 origin = default(Vector2), float scale = 1, SpriteEffects effect = SpriteEffects.None, float layerDepth = 0, float opacity = 1f); } }
23056fd2530ee206b1e1811c96ac3fb52ad38237
[ "Markdown", "C#" ]
15
C#
marcelomesmo/Fantasmas
20c3ab4aabc050e9972599565f7fde7526d6d87f
b3503d62de606c5764abe65dd430e9b27590a35a
refs/heads/master
<file_sep> <h1><b>Snake Game </b></h1> <b>CREATED BY </b> : Nithin.P <EMAIL> http://facebook.com/nithin.nithinp <b> Description </b> : This is a Snake Game coded by me in python using pygame module. You need python and pygame module installed to run this code. <b>License </b> : This Source Code is free to use for educational purpose only. <b>Instructions </b> : <ul> <li> Use 'UP' key to change direction of snake to 'UP' </li> <li> Use 'DOWN' key to change direction of snake to 'DOWN' </li> <li> Use 'LEFT' key to change direction of snake to 'LEFT' </li> <li>Use 'RIGHT' key to change direction of snake to 'RIGHT' </li> </ul> <file_sep> ############################################################################## # # # Snake Game # # # # # # CREATED BY : Nithin.P # # <EMAIL> # # http://facebook.com/nithin.nithinp # # # # Description : This is Snake Game coded by me # # in python using pygame module. # # # # License : This Source Code is free to use # # for educational purpose only. # # # # Instructions : Use 'UP' key to change direction of snake to 'UP' # # Use 'DOWN' key to change direction of snake to 'DOWN' # # Use 'LEFT' key to change direction of snake to 'LEFT' # # Use 'RIGHT' key to change direction of snake to 'RIGHT' # # # ############################################################################## import pygame import sys import random # Initial Conditions. white=(255,255,255) black=(0,0,0) green=(0,255,0) red=(255,0,0) blue=(0,0,255) gray=(128,128,128) size=[720,630] cube_size=30 snake=[{'i_cord' : 5,'j_cord' : 7},{'i_cord' : 5,'j_cord' : 8},{'i_cord' : 5,'j_cord' : 9},{'i_cord' : 5,'j_cord' : 10}] new_food=True food=None time1=pygame.time.get_ticks() direction='right' game_over=False score=0 paused_game=False time_limit=300 # Increase this time limit to decrease speed of snake # Function to reset the game. def reset_game() : global snake global new_food global food global time1 global direction global game_over global score snake=[{'i_cord' : 5,'j_cord' : 7},{'i_cord' : 5,'j_cord' : 8},{'i_cord' : 5,'j_cord' : 9},{'i_cord' : 5,'j_cord' : 10}] new_food=True food=None time1=pygame.time.get_ticks() direction='right' game_over=False score=0 # Function to wait for any key press. def wait_for_any_key() : while True : for event in pygame.event.get() : if event.type==pygame.QUIT : sys.exit() pygame.quit() if event.type == pygame.KEYDOWN : return True # Function to print press any key. def print_press_any_key() : global paused_game font=pygame.font.Font(None,30) if paused_game : text = font.render("Press Escape key to continue", True, gray) else : text = font.render("Press any key to continue", True, gray) rect = text.get_rect() rect.centerx=size[0]-150 rect.centery=size[1]-50 screen.blit(text, rect) # Function to print 'Paused'. def print_paused_game() : font=pygame.font.Font(None,230) overText = font.render('Paused', True, white) overRect = overText.get_rect() overRect.centerx=(size[0]/2) overRect.centery=(size[1]/2) screen.blit(overText, overRect) print_press_any_key() # Function to draw initial screen. def draw_initial_screen() : play() draw_screen() font=pygame.font.Font(None,220) gameText = font.render("Nithin's", True, white) overText = font.render('Snake', True, white) over1Text = font.render('Game', True, white) gameRect = gameText.get_rect() overRect = overText.get_rect() over1Rect = over1Text.get_rect() gameRect.centerx=(size[0]/2) gameRect.centery=(size[1]/2)-150 overRect.centerx=(size[0]/2) overRect.centery=(size[1]/2) over1Rect.centerx=(size[0]/2) over1Rect.centery=(size[1]/2+150) screen.blit(gameText, gameRect) screen.blit(overText, overRect) screen.blit(over1Text, over1Rect) print_press_any_key() pygame.display.update() # Function print Game Over. def print_game_over() : font=pygame.font.Font(None,270) font1=pygame.font.Font(None,50) gameText = font.render('Game', True, white) overText = font.render('Over', True, white) sc="Your Score : "+str(score) scoreText = font1.render(sc, True, white) gameRect = gameText.get_rect() overRect = overText.get_rect() scoreRect = scoreText.get_rect() gameRect.centerx=(size[0]/2) gameRect.centery=(size[1]/2)-120 overRect.centerx=(size[0]/2) overRect.centery=(size[1]/2)+30 scoreRect.centerx=(size[0]/2) scoreRect.centery=(size[1]/2)+150 screen.blit(gameText, gameRect) screen.blit(overText, overRect) screen.blit(scoreText, scoreRect) # Function create new food location. def create_new_food_location() : tmp=[] for i in range(19) : for j in range(24) : t={'i_cord' : i,'j_cord' : j} if t not in snake : tmp.append(t) loc=(int(random.random()*100000000))%len(tmp) food=tmp[loc] return food # Function to draw game screen. def draw_screen() : screen.fill(black) i=0 while i<(size[0]) : pygame.draw.line(screen,gray,(i,60),(i,size[1])) i+=cube_size i=60 while i<(size[1]) : pygame.draw.line(screen,gray,(0,i),(size[0],i)) i+=cube_size font=pygame.font.Font(None,30) score1='Score : '+str(score) scoreText=font.render(score1,True,white) scoreRect=scoreText.get_rect() scoreRect.centerx=int(size[0]/2) scoreRect.centery=30 screen.blit(scoreText,scoreRect) for part in snake : left=(part['j_cord']*cube_size)+1 up=(part['i_cord']*cube_size)+60+1 pygame.draw.rect(screen,red,(left,up,(cube_size-1),(cube_size-1))) left=(food['j_cord']*cube_size)+1 up=(food['i_cord']*cube_size)+60+1 pygame.draw.rect(screen,green,(left,up,(cube_size-1),(cube_size-1))) # Main play function. def play() : global game_over global food global snake global new_food global time1 global score if new_food : food=create_new_food_location() new_food=False #print food if pygame.time.get_ticks() > (time1+time_limit) : new_snake_head={'i_cord' : 0,'j_cord' : 0} # Create new snake head. if direction=='right' : new_snake_head['i_cord']=snake[(len(snake)-1)]['i_cord'] new_snake_head['j_cord']=snake[(len(snake)-1)]['j_cord']+1 if direction=='left' : new_snake_head['i_cord']=snake[(len(snake)-1)]['i_cord'] new_snake_head['j_cord']=snake[(len(snake)-1)]['j_cord']-1 if direction=='up' : new_snake_head['i_cord']=snake[(len(snake)-1)]['i_cord']-1 new_snake_head['j_cord']=snake[(len(snake)-1)]['j_cord'] if direction=='down' : new_snake_head['i_cord']=snake[(len(snake)-1)]['i_cord']+1 new_snake_head['j_cord']=snake[(len(snake)-1)]['j_cord'] if new_snake_head==food : # Snake catches food. snake.append(new_snake_head) new_food=True score+=1 else : if new_snake_head['i_cord']<0 or new_snake_head['i_cord']>=19 or new_snake_head['j_cord']<0 or new_snake_head['j_cord']>=24 : # new_new_snake_head exceeds screem size. game_over=True if new_snake_head in snake : # new_new_snake_head strikes with snake body. game_over=True if game_over==False : snake.append(new_snake_head) snake.remove(snake[0]) time1=pygame.time.get_ticks() # Initial screen. pygame.init() screen=pygame.display.set_mode(size,0,32) pygame.display.set_caption("Nithin's Snake Game") draw_initial_screen() while True : if wait_for_any_key() : break # Main game loop while True : for event in pygame.event.get() : if event.type==pygame.QUIT : if paused_game : sys.exit() pygame.quit() game_over=True print_game_over() pygame.display.update() time3=pygame.time.get_ticks() while pygame.time.get_ticks() < (time3+1000) : pygame.time.get_ticks() sys.exit() pygame.quit() if event.type == pygame.KEYDOWN : if event.key == pygame.K_ESCAPE : if paused_game==False : paused_game=True print_paused_game() pygame.display.update() else : paused_game=False if event.key == pygame.K_LEFT : # Change direction of snake to Left. if direction!='right' : direction='left' if event.key == pygame.K_RIGHT : # Change direction of snake to RIGHT. if direction!='left' : direction='right' if event.key == pygame.K_DOWN : # Change direction of snake to DOWN. if direction!='up' : direction='down' if event.key == pygame.K_UP : # Change direction of snake to UP. if direction!='down' : direction='up' if game_over==True : print_game_over() pygame.display.update() if wait_for_any_key() : reset_game() elif paused_game==False : play() draw_screen() pygame.display.update()
e79db8eb831cc2313818c089bad3fb216d181e4e
[ "Markdown", "Python" ]
2
Markdown
nithinp/snake-game
15954ed243059744e91a9d9f3e8b0065b6ed0506
b9007d69a0712b21c8cc7effd3f63aea89f10566
refs/heads/master
<file_sep>#!/usr/bin/python import thread import time import random from threading import Lock # Define a function for the thread def philosopher_eat( philosopher ): while 1: philosopher.eat() forks = [Lock(), Lock(), Lock(), Lock(), Lock()] class Waiter: def __init__(self, name, forks): self.name = name self.forks = forks def canEat(self, fork1, fork2): return fork1.acquire(False) and fork2.acquire(False) def release(self, fork1, fork2): fork1.release() fork2.release() class Philosopher: def __init__(self, name, waiter, fork1, fork2): self.name = name self.count = 0 self.waiter = waiter self.fork1 = fork1 self.fork2 = fork2 def eat(self): #time.sleep(random.random()/100) print self.name + " trying to eat (" + str(self.count) + ")" waiter.canEat(self.fork1, self.fork2) print self.name + " eating" self.count +=1 #time.sleep(random.random()/100) waiter.release(self.fork1, self.fork2) print self.name + " finished eating" waiter = Waiter("Waiter", forks) philosophers = [ Philosopher("A", waiter, forks[0], forks[1]), Philosopher(" B", waiter, forks[1], forks[2]), Philosopher(" C", waiter, forks[2], forks[3]), Philosopher(" D", waiter, forks[3], forks[4]), Philosopher(" E", waiter, forks[4], forks[0]), ] # Create two threads as follows for philosopher in philosophers: thread.start_new_thread( philosopher_eat, (philosopher, ) ) while 1: pass <file_sep># Challenge Dining philosophers # Run kotlinc -script dining.kts or java Dining.java <file_sep>#!/usr/bin/python import thread import time import random from threading import Lock # Define a function for the thread def philosopher_eat( philosopher ): while 1: philosopher.eat() forks = [Lock(), Lock(), Lock(), Lock(), Lock()] class Philosopher: def __init__(self, name, fork1, fork2): self.name = name self.count = 0 self.fork1 = fork1 self.fork2 = fork2 def eat(self): #time.sleep(random.random()/100) print self.name + " trying to eat(" + str(self.count) + ")" self.fork1.acquire() #time.sleep(random.random()/1000) second_fork = self.fork2.acquire(False) if not second_fork: self.fork1.release() print self.name + " couldn't eat" time.sleep(random.random()/100) return print self.name + " eating" self.count +=1 #time.sleep(random.random()/100) self.fork1.release() #time.sleep(random.random()/1000) self.fork2.release() print self.name + " finished eating" philosophers = [ Philosopher("A", forks[0], forks[1]), Philosopher(" B", forks[1], forks[2]), Philosopher(" C", forks[2], forks[3]), Philosopher(" D", forks[3], forks[4]), Philosopher(" E", forks[4], forks[0]), ] # Create two threads as follows for philosopher in philosophers: thread.start_new_thread( philosopher_eat, (philosopher, ) ) while 1: pass<file_sep>class Philospher(val index: Int, val left: Any, val right: Any) { var count = 0 val diner = Thread { while(true) { println("$index think : $count") synchronized(left) { synchronized(right) { println("$index eat : ${count++}") } } } } var eat = { diner.start() } fun isEating() : Boolean { return diner.isAlive() } } val size = 4 val forks = (0..size).map { Object() } val forksPlus = forks + listOf(forks[0]) val philosphers = (0..size).map { i -> Philospher(i, forks[i], forksPlus[i+1]) } println("Start ...") philosphers.forEach {it -> it.eat()} println("... all eating") var eating = true while (eating) { Thread.sleep(1_000) var count = philosphers.count {it -> it.isEating()} eating = count != 0 if (eating) println("... ${count} count still eating") } println("... end")<file_sep>public class Dining { public static void main(String[] args) { System.out.println("Hello"); new Philosophers().eat(); } static class Philosophers { void eat() { System.out.println("Eating"); } } }
0abc9159879984f3999ba5caa3ba4342a9998ba8
[ "Markdown", "Java", "Python", "Kotlin" ]
5
Python
ianhomer/try-dining
8320b6f1fc091e45838c6ec0532a2230bacaad14
4bfc9d3e70c6e989244c6eb4ec0460ddf9682a78
refs/heads/master
<repo_name>RupinSamria/Temperature-Alert-VIA-telegram-bot<file_sep>/README.md # Temperature-Alert-VIA-telegram-bot<file_sep>/Conf.py bolt_api_key = "" # Bolt Cloud API Key device_id = "" # Bolt Device ID telegram_chat_id = "@XXXX" # channel ID of Telegram channel. telegram_bot_id = "botXXXX" # bot ID of Telegram Bot. threshold = 250 # Threshold beyond which the alert should be sent
96993552c947263d6c42589b49bed87191a5b7f2
[ "Markdown", "Python" ]
2
Markdown
RupinSamria/Temperature-Alert-VIA-telegram-bot
10f939f6f6a08a73b534a40cb244c30c53b35c3e
8ccb88b983bef2e7a047469f2286aff0a0a1371f
refs/heads/master
<repo_name>MSchlumpf/lab2<file_sep>/logmap.cxx #include<iostream> using namespace std; int main(){ int N=100; double r=0.1; double x=0.5; for(r=0.1;r<4;r+=0.01){ x=0.5; for(int i=0;i<N;i++){ x=x*r*(1-x); if (i>19){ cout << r <<" "<< x <<endl;} } } return 0; }
2a560a135ce02b69f9c17bf1a9bdb488d61f8676
[ "C++" ]
1
C++
MSchlumpf/lab2
cfa3e268241951a087a4e4582e3ea7b8e5d3a10c
9dbce77fd7e02e5f466e448dbe2ebb14f6692c35
refs/heads/master
<file_sep>package com.hujian.interfaces; /** * @description: * @author: hujian * @create: 2021-01-28 22:35 */ public class HelloServiceImpl implements HelloService{ @Override public String sayHello(String username) { return username; } } <file_sep>package com.hujian.api.Protocol.netty.client; import com.hujian.api.Invocation; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.concurrent.CountDownLatch; /** * @description: 处理器 * @author: hujian * @create: 2021-01-28 22:32 */ public class ClientHandle extends SimpleChannelInboundHandler<String> { String result = ""; CountDownLatch countDownLatch = new CountDownLatch(1); @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { result = msg; System.out.println(result); countDownLatch.countDown(); } public String getResult(Invocation invocation, Bootstrap bootstrap){ try { countDownLatch.wait(); } catch (InterruptedException e) { e.printStackTrace(); } //重置 countDownLatch = new CountDownLatch(1); return result; } } <file_sep>package com.hujian.basic.service; import com.hujian.interfaces.BasicService; import org.apache.dubbo.config.annotation.Service; /** * @description: * @author: hujian * @create: 2021-02-01 21:33 */ @Service public class BasicServiceImpl implements BasicService { @Override public String sayHello(String name) { return "hello "+name; } } <file_sep>package com.hujian.provider; /** * @description: 服务提供者 * @author: hujian * @create: 2021-01-28 21:29 */ public class Provider { } <file_sep>package com.hujian.api; import com.hujian.interfaces.HelloService; import com.hujian.interfaces.proxy.ProxyFactory; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * @description: 传输的封装类 * @author: hujian * @create: 2021-01-28 21:37 */ @Getter @Setter @AllArgsConstructor public class Invocation { private String interfaceName; private String methodName; private Class[] paramTypes; private Object[] params; public static void main(String[] args) { HelloService proxy = (HelloService)ProxyFactory.getProxy(HelloService.class); String m = proxy.sayHello("hujian"); System.out.println(m); } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hujian</groupId> <artifactId>dubbo</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>dubbo-simulate</module> <module>dubbo-demo</module> <module>dubbo-basic-using</module> </modules> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <dubbo.version>2.7.5</dubbo.version> <spring-boot.version>2.3.6.RELEASE</spring-boot.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency> <!-- <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> </dependency>--> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-api</artifactId> <version>1.0.10</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.10</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.10</version> </dependency> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Apache Dubbo --> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-dependencies-bom</artifactId> <version>${dubbo.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo</artifactId> <version>${dubbo.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> </project><file_sep>package com.hujian.api.Protocol; import com.hujian.api.Invocation; public interface Protocol { void send(String host,int port,Invocation invocation); void start(); }
5f26e240a4c2bef3f1e6c134aae6f645c3707eab
[ "Java", "Maven POM" ]
7
Java
lymzcq1993/dubbo
ea255c1292d9dbea25c7fd7cdbb5bd15bf48ba1e
49bee61d75eebc69b59bdc660290949e5e23dbb0
refs/heads/master
<file_sep>package com.example.mangaglide; import android.app.Fragment; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.ExecutionException; public class List_liked_manga extends Fragment { private TextView tv; private File f; private LinearLayout frame; private final String filename = "myfile"; private String s = ""; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_list_liked_manga, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); frame = view.findViewById(R.id.list_frame); frame.removeAllViews(); f = new File(getActivity().getFilesDir(), filename); try { BufferedReader br = new BufferedReader(new FileReader(f)); String line; HashMap<String, String> file_content = ((MainActivity) getActivity()).getFile_content(); while ((line = br.readLine()) != null) { TextView c = new TextView(this.getContext()); c.setText("------------------------------------------------------------------------------------------------------------"); c.setTextColor(Color.WHITE); TextView b = new TextView(this.getContext()); b.setTextSize(22); b.setText(file_content.get(line)); b.setTextColor(Color.WHITE); b.setClickable(true); final String r = line; line = br.readLine(); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("what is the link i clicked" + r); ((MainActivity) getActivity()).setOnClik_manga(r); //blog truyen or mangaka int index1 = r.indexOf("mangakakalot"); int index2 = r.indexOf("manganelo"); int site = -3; if(index1 == -1 && index2 == -1){ site = 0; }else{ site = 1; } String[] urls = new String[]{r}; try { Manga_info manga = new GET_Manga_info(List_liked_manga.this.getActivity(), site).execute(urls).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }); frame.addView(c); frame.addView(b); } br.close(); } catch (IOException e) { //You'll need to add proper error handling here } } } <file_sep>package com.example.mangaglide; import android.os.AsyncTask; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; public class Querry_Manga extends AsyncTask<String, Void, ArrayList<Link_info>> { private final String prefix1 = "https://m.blogtruyen.com"; private final String prefix2 = ""; private int max_querry_item = 10; private int site; public Querry_Manga(int which){ site = which; } @Override protected ArrayList<Link_info> doInBackground(String... urls) { ArrayList<Link_info> list = new ArrayList<>(); final StringBuilder builder = new StringBuilder(); if(site == 0){ //blog truyen try { Document doc = Jsoup.connect(urls[0]).get(); String title = doc.title(); Elements links = doc.select("table"); Element table = links.first(); if(table != null){ Element table_body = table.child(0); int i = 0; for (Element link : table_body.children()) { Element l = link.getElementsByTag("a").first(); Link_info q = new Link_info(l.attr("title"), prefix1 + l.attr("href")); list.add(q); i++; if(i == max_querry_item) break; } }else{ return null; } } catch (IOException e) { builder.append("Error : ").append(e.getMessage()).append("\n"); } } if(site == 1){ //mangakaka try { Document doc = Jsoup.connect(urls[0]).get(); String title = doc.title(); Element links = doc.select(".panel_story_list").first(); if(links != null){ int i = 0; for (Element link : links.children()) { Element h = link.select(".story_name").first(); Element l = h.child(0); Link_info q = new Link_info(l.text(), l.attr("href")); list.add(q); i++; if(i == max_querry_item) break; } }else{ return null; } } catch (IOException e) { builder.append("Error : ").append(e.getMessage()).append("\n"); } } return list; } } <file_sep>package com.example.mangaglide; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.os.PersistableBundle; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import java.util.ArrayList; public class Reading extends FragmentActivity { private ArrayList<String> all_url; private int current; private final String SIMPLE_FRAGMENT_TAG = "myfragmenttag"; public ArrayList<String> getAll_url() { return all_url; } public int getCurrent() { return current; } public void setCurrent(int current) { this.current += current; } @Override protected void onCreate(Bundle savedInstanceState) { //1 super.onCreate(savedInstanceState); setContentView(R.layout.activity_reader); Intent intent = getIntent(); Bundle b = intent.getExtras(); if(b != null){ all_url = b.getStringArrayList("ALLURLs"); current = Integer.parseInt(b.getString("CURRENT_INDEX")); } FragmentManager manager = getFragmentManager(); //first time go here FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); Manga homeFragment = new Manga(); fragmentTransaction.add(R.id.Frame, homeFragment, SIMPLE_FRAGMENT_TAG); fragmentTransaction.commit(); } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { current = outState.getInt("current"); all_url = outState.getStringArrayList("allurls"); super.onSaveInstanceState(outState, outPersistentState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { savedInstanceState.putStringArrayList("allurls", all_url); savedInstanceState.putInt("current", current); super.onRestoreInstanceState(savedInstanceState); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void onBackPressed() { //have to pass the data on this method Intent intent = new Intent(); intent.putExtra("Return", current); setResult(RESULT_OK, intent); System.out.println("Return message is" + current); finish(); super.onBackPressed(); } } <file_sep>package com.example.mangaglide; import android.app.Fragment; import android.media.Image; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.ListPreloader; import com.bumptech.glide.RequestBuilder; import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader; import com.bumptech.glide.util.FixedPreloadSizeProvider; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; public class Manga extends Fragment { private final int imageWidthPixels = 1024; private final int imageHeightPixels = 768; private ImageURLInterface myUrls; private LinearLayoutManager layoutManager; private ArrayList<String> all_url; private ImageView iv; private RecyclerView recyclerView; private int current; private String[] url; private boolean index; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //2 return inflater.inflate(R.layout.manga_layout, container, false); } public ImageView getIv() { return iv; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { //3 all_url = ((Reading) this.getActivity()).getAll_url(); current = ((Reading) this.getActivity()).getCurrent(); url = new String[1]; url[0] = all_url.get(all_url.size() - 1 - current); int index1 = url[0].indexOf("mangakakalot"); int index2 = url[0].indexOf("manganelo"); index = index1 == -1 && index2 == -1; if(index){ url[0] = url[0].substring(0,8) + url[0].substring(10); } System.out.println("get url" + url[0]); myUrls = ImageURLInterface.create(url[0]); //default image iv = view.findViewById(R.id.empty_view); iv.setImageResource(R.drawable.error); iv.setClickable(true); iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("you picked"); getActivity().getFragmentManager().beginTransaction().remove(Manga.this).commit(); } }); setup(); } private void setup(){ //set up recycler view ListPreloader.PreloadSizeProvider sizeProvider = new FixedPreloadSizeProvider(imageWidthPixels, imageHeightPixels); ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider(); RecyclerViewPreloader<Image> preloader = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, sizeProvider, 20); recyclerView = this.getView().findViewById(R.id.rv_images); recyclerView.addOnScrollListener(preloader); //set layout layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); DividerItemDecoration itemDecorator = new DividerItemDecoration(Objects.requireNonNull(getContext()), DividerItemDecoration.VERTICAL); //5dp space between item itemDecorator.setDrawable(getActivity().getDrawable(R.drawable.divider)); recyclerView.addItemDecoration(itemDecorator); recyclerView.setAdapter(new ImageAdapter(myUrls, this, recyclerView)); } private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider{ @NonNull @Override public List getPreloadItems(int position) { String url = myUrls.get(position); if (TextUtils.isEmpty(url)) { return Collections.emptyList(); } return Collections.singletonList(url); } @Nullable @Override public RequestBuilder<?> getPreloadRequestBuilder(@NonNull Object item) { return Glide.with(Manga.this).load(item).override(imageWidthPixels, imageHeightPixels); } } @Override public void onDestroy() { super.onDestroy(); getActivity().finish(); } public String next(){ String url_next = ""; if (current + 1 < all_url.size()){ int next = current + 1; url_next = all_url.get(all_url.size() - 1 - next); if(index) { url_next = url_next.substring(0, 8) + url_next.substring(10); } } return url_next; } public String prev(){ String url_prev = ""; if (current > 0){ int prev = current - 1; url_prev = all_url.get(all_url.size() - 1 - prev); if(index){ url_prev = url_prev.substring(0,8) + url_prev.substring(10); } } return url_prev; } public void setMyUrls(ImageURLInterface myUrls) { this.myUrls = myUrls; } public void setCurrent(int current) { this.current += current; ((Reading) getActivity()).setCurrent(current); } public LinearLayoutManager getLayoutManager() { return layoutManager; } }
8297cc1a507f52606474d032eb9b55fd332e5e87
[ "Java" ]
4
Java
kdle15/Glide_Mangaanga
6ebaf1d9e01d58d9d8e7bcb6f38d91268caf40be
e7afee1048062cdda234bac53a34eb6f4b7520e8
refs/heads/master
<repo_name>kachontep/sensu-elasticsearch<file_sep>/elastic.rb require 'rubygems' if RUBY_VERSION < '1.9.0' require 'elasticsearch' require 'patron' require 'json' require 'date' require 'oj' module Sensu::Extension class Elastic < Handler def name 'elastic' end def description 'outputs metrics to ES' end def post_init @esclient = Elasticsearch::Client.new host: settings['elastic']['host'], timeout: settings['elastic']['timeout'] @index = settings['elastic']['index'] @type = settings['elastic']['type'] # Use symbol as json keys Oj.default_options = { :symbol_keys => true } end def run(event) begin event = Oj.load(event) end rescue => e @logger.error("ES: Error setting up event object - #{e.backtrace.to_s}") end begin timestamp = event[:client][:timestamp] iso_timestamp = Time.parse(Time.at(timestamp.to_i).to_s).iso8601 data = event.merge({ client: { timestamp: iso_timestamp } }) rescue => e @logger.error("ES: Error parsing output lines - #{e.backtrace.to_s}") end begin @esclient.create index: @index, type: @type, body: data rescue => e @logger.error("ES: Error indexing event - #{e.backtrace.to_s}") end yield("ES: Handler finished", 0) end end end
a11ef4e7f9108ff3c9e3a1e837f48caf5412fc80
[ "Ruby" ]
1
Ruby
kachontep/sensu-elasticsearch
fecb0ba41d0fb9fa4bca9d0767f73eed7a462741
70e184b82e1f5be4faa3bb19ab834b1ff63cdcfe
refs/heads/master
<file_sep>import { Character, battle} from "../src/RPG"; import { Item } from "../src/Item"; import { Ability } from "../src/Abilities"; describe("Nori",function () { var cultist = new Character("Susan","Gorberson", "Sewn-<NAME>", 3, 3, 5, 5, 1, 4); var nori = new Character("Nori", "Ishi", "Entrepeneur extroardinaire", 6, 9, 4, 5, 3, 3); var francois = new Character("Francois", "Thompson", "Fist your sister", 10,10,10,10,10,10); var swipe = new Ability("Swipe", "Physical", "target.cHP -= self.mAtk;"); nori.actions.push(swipe); nori.StPr(); cultist.StPr(); var knux = new Item("Spiked Knuckles"); knux.atk = 5; cultist.GainItem(knux); cultist.Equip(cultist.inventory[0]); it("has all Character Sheet fields filled",function(){ expect(nori.firstName && nori.lastName).toBeDefined(); }); it("has starting stats at or above the minimums", function () { expect(nori.might).toBeGreaterThanOrEqual(1); expect(nori.spryness).toBeGreaterThanOrEqual(1); expect(nori.judgment).toBeGreaterThanOrEqual(1); expect(nori.magnetism).toBeGreaterThanOrEqual(1); expect(nori.fortune).toBeGreaterThanOrEqual(1); }); it("is or was at valid stat sum upon generation", function(){ if(nori.generating){ var horse = nori.might + nori.spryness + nori.echo + nori.judgment + nori.magnetism + nori.fortune; expect(horse).toBe(30); } }); francois.StPr(); console.log(nori); console.log(nori.cHP, cultist.cHP); // console.log(battle(nori, cultist)); var battleresult = battle(nori, cultist); it("beat the Cultist!", function(){ expect(battleresult).toBe("<NAME> wins!"); }); it("has the spiked knuckles!",function(){ expect(nori.inventory[0].name).toBe("Spiked Knuckles"); }); var baseatk = nori.atk; console.log(baseatk); nori.Equip(nori.inventory[0]); it("gained the benefit of the Spiked Knuckles!",function(){ expect(nori.atk).toBe(baseatk+5); }); var battleresult2 = battle(nori,francois); it("Cannot win against francois!", function(){ expect(battleresult2).toBe("<NAME> wins!"); }); });<file_sep> export class Ability { constructor(name, type, effect) { this.name = name; this.type = type; this.effect = effect; } Execute(self, target) { eval(this.effect); } } <file_sep>import $ from 'jquery'; import 'bootstrap'; export class Character { constructor( firstName, lastName, altname, might, spryness, judgment, echo, magnetism, fortune ) { this.firstName = firstName; this.lastName = lastName; this.altname = altname; this.might = might; this.spryness = spryness; this.judgment = judgment; this.echo = echo; this.magnetism = magnetism; this.fortune = fortune; this.mightMin = 1; this.sprynessMin = 1; this.judgmentMin = 1; this.echoMin = 1; this.magnetismMin = 1; this.fortuneMin = 1; this.generating = true; this.leveling = false; // this.head; // this.torso; // this.arms; // this.legs; // this.feet; this.mainhand; this.offhand; // this.accessory; // this.abilities; this.actions = []; this.cHP = 0; this.atk = 0; this.rAtk = 0; this.mAtk = 0; this.defense = 0; this.luck = 0; this.speed = 0; this.turnprog = 0; this.level = 1; this.drops = []; this.inventory = []; this.invid = 0; } //process stats levelUp() { this.leveling = true; this.StPr(); this.level++; console.log(`${this.firstName} reached level ${this.level}! `); } StPr() { if (this.leveling == true) { this.might = Math.round(this.might * 1.25); this.spryness = Math.round(this.spryness * 1.25); this.judgment = Math.round(this.judgment * 1.25); this.echo = Math.round(this.echo * 1.25); this.magnetism = Math.round(this.magnetism * 1.25); this.fortune = Math.round(this.fortune * 1.25); } this.tHp = (this.might * 1.5); //when you level up you receive the difference in health (WIP) this.cHP = this.tHp; //melee attacks are calculated using might and spryness. //How fast you can swing is secondary to your ability to Follow Through on your attack. this.atk = (this.might * 1.5) + (this.spryness * .5); console.log(`Current Attack: ${this.atk}`); if (this.mainhand != null) { this.atk += this.mainhand.atk; console.log(`Current Attack WITH WEAPON: ${this.atk}`); } //ranged attacks are based on the stability of your hands (pulling the drawstring, accounting for recoil), // plus your ability to load your equipment efficiently (the quickness of your hands) this.rAtk = (this.spryness * 1.5) + (this.might * .5); //magic attacks are equal parts being able to remember an incantation //and the raw intellect of being able to process said spells in the first place. //Magnetism is essential to making sure your pronunciation is convincing //to the entities you draw power from. this.mAtk = ((this.judgment + this.echo) / 2) + (this.magnetism * .5); //judgment decides which parts your character decides to defend, //spryness decides how fast your character is to defend vital areas //might decides how much raw force your character can take generally this.defense = (this.judgment / 2) + (this.spryness + this.might / 2); //Luck is the opportunities you find //and the ability you have to recognize those opportunities for what they are. this.luck = (this.judgment + this.fortune / 2); this.speed = (this.spryness * 1.5) + (this.fortune * 1.5) / 2; this.turnprog = 0; this.generating = false; this.leveling = false; } Equip(item) { item.id = null; this.mainhand = item; this.inventory.splice(item.id - 1, item.id - 1); this.invid--; this.StPr(); } Unequip(item) { if(item != null){ item.id = this.invid; this.invid++; this.inventory.push(item); this.mainhand = null; this.StPr(); } } GainItem(item) { item.id = this.invid; this.invid++; this.inventory.push(item); } LoseItem(item) { this.inventory.splice(item.id - 1, item.id - 10); this.invid--; } // SheetPrint(){ // this.StPr(); // var printing = ""; // printing+="<div id='confirmname'>" + this.firstName + " '" + this.altname + "' "+ this.lastName + "</div>"; // printing+=""; // console.log(printing); // $("#charsheet").append(printing); // } } export function battle(char1, char2) { var turnTime = 100; console.log(char1); console.log(char2); console.log("running"); while (char1.cHP > 0 && char2.cHP > 0) { char1.turnprog += char1.speed; char2.turnprog += char2.speed; console.log(`${char1.firstName} turn progress: ${char1.turnprog} \n ${char2.firstName} turn progress: ${char2.turnprog}`); console.log(char1.cHP); console.log(char2.cHP); if (char1.turnprog >= turnTime) { console.log(char1.firstName + " attacks!"); char2.cHP -= char1.mAtk; char1.turnprog -= turnTime; } if (char2.turnprog >= turnTime) { console.log(char2.firstName + " attacks!"); char1.cHP -= char1.mAtk; char2.turnprog -= turnTime; } if (char2.cHP <= 0) { char1.levelUp(); char2.Unequip(char2.mainhand); char2.inventory.forEach(function (item) { char2.LoseItem(item); console.log(`${char2.firstName} lost ${item.name}!`); char1.GainItem(item); console.log(`${char1.firstName} gained ${item.name}!`); }); return `${char1.firstName} ${char1.lastName} wins!`; } else if (char1.cHP <= 0) { char2.levelUp(); char1.Unequip(char2.mainhand); char1.inventory.forEach(function (item) { char1.LoseItem(item); console.log(`${char1.firstName} lost ${item.name}!`); char2.GainItem(item); console.log(`${char2.firstName} gained ${item.name}!`); }); return `${char2.firstName} ${char2.lastName} wins!`; } } }<file_sep>import $ from 'jquery'; import 'bootstrap'; import { Character } from './RPG'; import './styles.css'; $(document).ready(function(){ var charbank = []; $("#charsheet").hide(); charbank.push(new Character($("#firstName").val(), $("#lastName").val(), $("#altname").val(), $("#might").val(), $("#spryness").val(), $("#judgment").val(), $("#echo").val(), $("#magnetism").val(), $("#fortune").val())); $("#createsend").submit(function(){ event.preventDefault(); var main = new Character($("#firstName").val(), $("#lastName").val(), $("#altname").val(), $("#might").val(), $("#spryness").val(), $("#judgment").val(), $("#echo").val(), $("#magnetism").val(), $("#fortune").val()); console.log(main); $("#createsend").hide(); $("#charsheet").show(); main.SheetPrint(); }); });
00c48e44cb3c2ae86fcda919be31eff12b9ee6e9
[ "JavaScript" ]
4
JavaScript
Riverface/RPG
80b80648b56510ed5093795704ba8edac2a43181
0fb09d73462323428eb1a79896cc64ebbe72a92b
refs/heads/master
<repo_name>leQu/NeuralDojo<file_sep>/snakedemo/world.js class World { constructor(gridsize, numberOfSnakes) { this.snakes = [] this.gridsize = gridsize for (let i = 0; i < numberOfSnakes; i++) { this.snakes.push(new Snake(this.gridsize, new SnakeBrain())) } } done() { return this.snakes.every(s => !s.alive) } breed(legendRatio) { let gradedSnakes = this.snakes.map(s => [s.fitness(), s]).sort((a, b) => b[0] - a[0]) let fitnessSum = gradedSnakes.reduce((sum, s) => sum + s[0], 0) const randomSnake = () => { let selectPoint = random(fitnessSum) let sum = 0 for (let i = 0; i < gradedSnakes.length; i++) { sum += gradedSnakes[i][0] if (selectPoint < sum) { return gradedSnakes[i][1] } } } let legendCount = Math.max(1, (legendRatio * this.snakes.length) | 0) this.snakes = gradedSnakes.map((gs, i) => { if (i < legendCount) { // Legends be more legend return new Snake(this.gridsize, gs[1].brain, 0.99 * (gs[1].legend + 1)) } if (gs[1].legend > 0) { // Let old legends survive return new Snake(this.gridsize, gs[1].brain, 0.99 * (gs[1].legend - 1)) } if (i < gradedSnakes.length - legendCount) { // Make children return randomSnake().makeChild(randomSnake()) } // Let some new blood in return new Snake(this.gridsize, new SnakeBrain()) }) } update() { for (let s of this.snakes) { s.update() } } show(number) { let alive = this.snakes.filter(s => s.alive) if (alive.length > number) { alive.slice(0, number).forEach(s => s.show()) return } number -= alive.length let dead = this.snakes.filter(s => !s.alive) dead.slice(0, number).forEach(s => s.show()) alive.forEach(s => s.show()) } }
aabc33ba30d8ec47f1dbeec85ae36685659e1caf
[ "JavaScript" ]
1
JavaScript
leQu/NeuralDojo
72386fcef2656dcf715cdb82f04ee9165d24cd22
ce932b9f36b21da9d38c7da34dd93c60ce1111a3
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe SatelliteRecordController, type: :controller do end <file_sep># Satellite Tracker README ## Description Satellite Tracker is an endpoint that listen's to Nestio's satellite API and creates separate API end-points for /stats and /health. Nestio's satellite API posts satellite altitude (km) and time of update every 10 seconds. The Satellite Tracker /stats end-point returns the minimum, maximum, and average altitudes from Nestio's API from the last 5 minutes (i.e. if the /stats API request was made at 5:55:25, the stats would include records from Nestio's API going back to 5:50:20) in a json object. The Satellite Tracker /health end-point returns a description of the altitude of the satellite. If the altitude has been below 160 km for the past minute (i.e. if the request was made at 5:55:25, the satellite would have been below 160 km since 5:55:20), the end-point returns "WARNING: RAPID ORBITAL DECAY IMMINENT". Once the average altitude of the satellite returns to 160km or above, the end-point returns "Sustained Low Earth Orbit Resumed" for a minute. Otherwise, the /health end-point returns "Altitude is A-OK". Satellite Tracker works by making calls to the Nestio API every 10 seconds and saving the data as a record saved to a Postgres database table called satellite_records with variables time_updated, altitude, average, and minute_below. On each API call any records beyond the 5 minutes of records needed to calculate the data for the /stats endpoint are deleted. The only rails model used is the model in the table, Satellite Record. There are two service object used to fetch data (Satellite Data Fetcher) and report data (Satellite Reporter). ## Specifications ### Rails * Version: 5.1.5 * Gems/Dependencies: pg, rest-client, json, whenever ### Postgresql * Version 9.6 ## Installation and Implementation Instructions In order to run the application, fork the repo or clone using the following: git clone https://github.com/pawlkris/satellite-tracker.git Navigate to the main directory on your local drive. Run ```whenever --update-crontab``` in the terminal command line to start the cron job to pull data from Nestio's satellite API. The cron job is set to run on the developer server. You can make modifications to the cron job in the schedule.rb file (root/config/schedule.rb) Run ```rails s``` in the terminal command line to run the rails server on http://localhost:3000 Get requests to http://localhost:3000/stats will yield /stats data and http://localhost:3000/health will yield /health data, which are outlined in the Description section. To stop the cron job, enter ```crontab -r``` in the terminal command line. You can run tests by running ```rspec``` in the command line. Tests can be found in the root/rspec/models folder. <file_sep>class SatelliteReporter def initialize @last_record = SatelliteRecord.last @average = @last_record.average @max = SatelliteRecord.all.max_by(&:altitude).altitude @min = SatelliteRecord.all.min_by(&:altitude).altitude @last_seven = SatelliteRecord.all.last(7) end def stats {average: @average, maximum: @max, minimum: @min} end def health if @last_record.minute_below==true return {message: 'WARNING: RAPID ORBITAL DECAY IMMINENT'} elsif @last_seven.find{|record| record.minute_below==true} && @last_seven.find{|record| record.average > 160} return {message: "Sustained Low Earth Orbit Resumed"} else return {message: "Altitude is A-OK"} end end end <file_sep>class SatelliteRecord < ApplicationRecord before_create :set_average before_create :set_minute_below def set_average self.average = SatelliteRecord.average(self.altitude) end def set_minute_below self.minute_below = SatelliteRecord.minute_below?(self) end def self.average(current) altitudes_for_average = SatelliteRecord.last(30).map{|record| record.altitude} altitudes_for_average.push(current) average = altitudes_for_average.sum/altitudes_for_average.length end def self.minute_below?(current) length = self.all.length if length < 6 return false end self.all.last(6).push(current).all?{|x|x.average < 160} end end <file_sep>namespace :chron do desc 'Fetch api record data' task :fetch => :environment do 6.times do |x| if SatelliteRecord.all.length == 31 SatelliteRecord.first.delete end new_sat = SatelliteDataFetcher.fetch sleep 10 end end end <file_sep>class SatelliteDataFetcher API_URL = "nestio.space/api/satellite/data" HEADERS = {Accept:'application/json'} def self.fetch response = JSON.parse(RestClient.get(API_URL, HEADERS)) data = SatelliteDataFetcher.parse_response(response) SatelliteRecord.create(data) end def self.parse_response(response) altitude = response["altitude"] last_updated = DateTime.strptime(response["last_updated"],"%Y-%m-%dT%H:%M:%S") { altitude: altitude, last_updated: last_updated } end end <file_sep>require 'rails_helper' RSpec.describe SatelliteReporter, type: :model do describe "SatelliteReporter.health" do it "returns 'WARNING: RAPID ORBITAL DECAY IMMINENT' when previous 7 records' averages are below 160, thus making the last record's minute_below status true" do 7.times {|i| SatelliteRecord.create(altitude: 120, last_updated:"2018-03-13 13:16:00")} SatelliteRecord.create(altitude: 120.757129951577, last_updated:"2018-03-13 13:16:00") reporter = SatelliteReporter.new expect(reporter.health).to eq({:message=>"WARNING: RAPID ORBITAL DECAY IMMINENT"} ) end it "returns 'WARNING: RAPID ORBITAL DECAY IMMINENT' when previous 6 records' averages are below 160" do 6.times {|i| SatelliteRecord.create(altitude: 120, last_updated:"2018-03-13 13:16:00")} SatelliteRecord.create(altitude: 120.757129951577, last_updated:"2018-03-13 13:16:00") reporter = SatelliteReporter.new expect(reporter.health).to eq({:message=>"WARNING: RAPID ORBITAL DECAY IMMINENT"} ) end it "returns 'Sustained Low Earth Orbit Resumed' when at least one of the past seven records' altitudes is above 160 at least one record's minute_below? status is true" do 7.times{|i| SatelliteRecord.create(altitude: 158.757129951577, last_updated:"2018-03-13 13:16:00")} 1.times{|i| SatelliteRecord.create(altitude: 250.757129951577, last_updated:"2018-03-13 13:16:00")} reporter = SatelliteReporter.new expect(reporter.health).to eq({:message=>"Sustained Low Earth Orbit Resumed"}) end it "returns 'Altitude is A-OK' when one average is below 160, but others are above and no records have minute below equal to true" do sat_info = {altitude: 166.757129951577, last_updated:"2018-03-13 13:16:00"} SatelliteRecord.create(altitude: 120.757129951577, last_updated:"2018-03-13 13:16:00") 6.times {|i| SatelliteRecord.create(sat_info)} reporter = SatelliteReporter.new expect(reporter.health).to eq({:message=>"Altitude is A-OK"} ) end end end <file_sep>class AddMinuteBelowToSatelliteRecords < ActiveRecord::Migration[5.1] def change add_column :satellite_records, :minute_below, :boolean, default:false end end <file_sep>class CreateSatelliteRecords < ActiveRecord::Migration[5.1] def change create_table :satellite_records do |t| t.float :altitude t.float :average t.datetime :last_updated t.timestamps end end end <file_sep>require 'rails_helper' RSpec.describe SatelliteRecord, type: :model do describe "SatelliteRecord.minute_below?" do it "returns true when last six records have average altitude below 160" do 6.times {|i| SatelliteRecord.create(altitude: 120, last_updated:"2018-03-13 13:16:00")} expect(SatelliteRecord.minute_below?(SatelliteRecord.last)).to eq(true) end it "returns false when fewer than six records exist" do 4.times {|i| SatelliteRecord.create(altitude: 120, last_updated:"2018-03-13 13:16:00")} expect(SatelliteRecord.minute_below?(SatelliteRecord.last)).to eq(false) end it "returns false when at least one of six records have average altitude above 160" do 6.times {|i| SatelliteRecord.create(altitude: 158, last_updated:"2018-03-13 13:16:00")} SatelliteRecord.create(altitude: 300, last_updated:"2018-03-13 13:16:00") expect(SatelliteRecord.minute_below?(SatelliteRecord.last)).to eq(false) end end describe "SatelliteRecord.average" do it "returns average of previous 30 records plus input of the current record (0:00 to 5:00)" do 30.times {|i| SatelliteRecord.create(altitude: 1, last_updated:"2018-03-13 13:16:00")} expect(SatelliteRecord.average(32)).to eq(2) end it "returns the correct average if there are fewer than 30 records" do 10.times {|i| SatelliteRecord.create(altitude: 1, last_updated:"2018-03-13 13:16:00")} expect(SatelliteRecord.average(12)).to eq(2) end end end <file_sep>class SatelliteRecordController < ApplicationController def stats reporter = SatelliteReporter.new stats = reporter.stats render json: stats end def health reporter = SatelliteReporter.new health = reporter.health render json: health end end
6277937bdb025abd9e56b329ff65facdcfcf546f
[ "Markdown", "Ruby" ]
11
Ruby
pawlkris/satellite-tracker
ace703cc06ec7c5e118727697cfdca7faa25d485
2fab0933b6ae8ea9e2ebb8eb4ddf7e57979bd87d
refs/heads/master
<file_sep>/*global $*/ /*global window*/ /*global location*/ /*global document*/ /*global event*/ //$ = jQuery $(document).ready(function () { "use strict"; //by declaring DOM elements into variables, can be used as objects var $figcaption = $("figcaption"), $figure = $("figure"), $hamburgerMenu = $("#on-click-menu-list"), $hamburgerOpen = $(".open"), $hamburgerClose = $(".close"), $backToTop = $(".back-to-top"); //figure-figcaption $figcaption.css({ opacity: "0" }); $figure.on("mouseenter", function () { $(event.currentTarget).children("figcaption").animate({ opacity: "1" }, "slow"); }).on("mouseleave", function () { $(event.currentTarget).children("figcaption").animate({ opacity: "0" }, "fast"); }); //refershing window on resize $(window).on("resize", function () { location.reload(); }); //targeting the window width if (window.matchMedia("(max-width: 1024px)").matches) { //hamburger-hamburgerMenu $hamburgerMenu.hide(); $hamburgerClose.hide(); $hamburgerOpen.on("click", function () { $hamburgerMenu.slideDown(); $hamburgerClose.fadeIn(400); $hamburgerOpen.hide(); }); $hamburgerClose.on("click", function () { $hamburgerMenu.slideUp(); $hamburgerClose.hide(); $hamburgerOpen.fadeIn(); }); } $backToTop.hide(); $(window).on("scroll", function () { //hiding the navigation on scroll position if ($(document).scrollTop() > 80) { $("nav").fadeOut(); } else { $("nav").fadeIn(); } //showing the back-to-top on scroll position if ($(this).scrollTop() > 400) { $backToTop.fadeIn(800); } else { $backToTop.fadeOut(); } //scroll animation on click $backToTop.on("click", function () { $("html, body").stop().animate({scrollTop:0}, 1000); return false; }); }); }); <file_sep># BicycleEcommerceSite [Live Preview](https://tarunjuluru.github.io/BicycleEcommerceSite/)
d78cd3d48d47777bbccdc9ba449220af898719eb
[ "JavaScript", "Markdown" ]
2
JavaScript
TarunJuluru/BicycleEcommerceSite
7be23f10ae29a9e5f375da46ed2805d633e9bef2
e237b44a3cdd9970d65b7a59e33a5a8b4690a650
refs/heads/master
<file_sep>#!/bin/bash #===================================================================# # System Required: CentOS 7 # #===================================================================# # #一键脚本 # # # 设置字体颜色函数 function blue(){ echo -e "\033[34m\033[01m $1 \033[0m" } function green(){ echo -e "\033[32m\033[01m $1 \033[0m" } function greenbg(){ echo -e "\033[43;42m\033[01m $1 \033[0m" } function red(){ echo -e "\033[31m\033[01m $1 \033[0m" } function redbg(){ echo -e "\033[37;41m\033[01m $1 \033[0m" } function yellow(){ echo -e "\033[33m\033[01m $1 \033[0m" } function white(){ echo -e "\033[37m\033[01m $1 \033[0m" } # # @安装docker install_docker() { docker version > /dev/null || curl -fsSL get.docker.com | bash service docker restart systemctl enable docker } install_docker_compose() { curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose } # 单独检测docker是否安装,否则执行安装docker。 check_docker() { if [ -x "$(command -v docker)" ]; then echo "docker is installed" # command else echo "Install docker" # command install_docker fi } check_docker_compose() { if [ -x "$(command -v docker-compose)" ]; then echo "docker-compose is installed" # command else echo "Install docker-compose" # command install_docker_compose fi } # check docker # 以上步骤完成基础环境配置。 echo "恭喜,您已完成基础环境安装,可执行安装程序。" restart_qiaohu(){ cd /opt/qiaohu docker-compose restart } # 输出结果 notice(){ green "==================================================" green "主程序已搭建完毕,让我们来完成最后几步,之后就可以访问了" green "==================================================" white "以下内容必须一步步操作" sleep 2s greenbg "正在重启qiaohu" restart_qiaohu white "正在导入数据库操作" sleep 10s docker-compose exec mysql bash <<EOF mysql -uroot -p$rootpwd sq_qiaohu < /opt/qiaohu.sql exit EOF #docker exec qizhimysql mysql -uroot -p$rootpwd sq_qiaohu < /opt/qiaohu/docker/database/qiaohu.sql sleep 10s greenbg "数据库导入完成" greenbg "正在重启qiaohu" restart_qiaohu sleep 5s } # 开始安装qiaohu install_main(){ blue "获取配置文件" mkdir -p /opt/qiaohu && cd /opt/ white "请仔细填写参数,部署完毕会反馈已填写信息" green "访问端口:如果想通过域名访问,请设置80端口,其余端口可随意设置" read -e -p "请输入访问端口(默认端口80):" port [[ -z "${port}" ]] && port="80" green "设置数据库ROOT密码" read -e -p "请输入ROOT密码(默认<PASSWORD>):" rootpwd [[ -z "${rootpwd}" ]] && rootpwd="<PASSWORD>" docker network create qizhi-net qiaohu_master notice } # 初始化qiaohu程序 qiaohu_master(){ rm -rf /opt/qiaohu && cd /opt yum install -y git git clone -b master https://git.china-qizhi.com/zhangjian/qiaohu.git cd /opt/qiaohu sed -i "s/"8000:80/"$port:80/" /opt/qiaohu/docker-compose.yml sed -i "s/数据库密码/$rootpwd/" /opt/qiaohu/docker-compose.yml sed -i "s/数据库密码/$rootpwd/" /opt/qiaohu/projects/DB.php sed -i "s/数据库密码/$rootpwd/" /opt/qiaohu/projects/DB2.php sed -i "s/数据库密码/$rootpwd/" /opt/qiaohu/projects/Tiyan/protected/config/dbconfig.php sed -i "s/数据库密码/$rootpwd/" /opt/qiaohu/projects/Api/protected/config/dbconfig.php chmod -R 777 /opt/qiaohu/projects/_Core/runtime greenbg "本地初始化完成" cd /opt/qiaohu redbg "开始启动服务,首次启动会拉取镜像,请耐心等待" docker-compose up -d } # 停止服务 stop_qiaohu(){ cd /opt/qiaohu docker-compose kill } # 重启服务 restart_qiaohu(){ cd /opt/qiaohu docker-compose restart } # 卸载 remove_all(){ cd /opt/qiaohu docker-compose down echo -e "\033[32m已完成卸载\033[0m" } #开始菜单 start_menu(){ clear greenbg "===============================================================" greenbg "简介:网站一键安装脚本 " greenbg "系统:Centos7、Ubuntu等 " greenbg "===============================================================" echo yellow "使用前提:脚本会自动安装docker,国外服务器搭建只需1min~2min" yellow "国内服务器下载镜像稍慢,请耐心等待" blue "备注:非80端口可以用caddy反代,自动申请ssl证书,到期自动续期" echo white "—————————————程序安装——————————————" white "1.安装qiaohu" white "—————————————杂项管理——————————————" white "2.停止qiaohu" white "3.重启qiaohu" white "4.卸载qiaohu" white "5.清除本地缓存(仅限卸载后操作)" white "—————————————域名访问——————————————" white "6.Caddy域名反代一键脚本(可以实现非80端口使用域名直接访问)" blue "0.退出脚本" echo echo read -p "请输入数字:" num case "$num" in 1) check_docker check_docker_compose install_main ;; 2) stop_qiaohu green "qiaohu程序已停止运行" ;; 3) restart_qiaohu green "qiaohu程序已重启完毕" ;; 4) remove_all ;; 5) rm -fr /opt/qiaohu green "清除完毕" ;; 6) bash <(curl -L -s https://raw.githubusercontent.com/doney0318/webdocker/master/caddy.sh) ;; 0) exit 1 ;; *) clear echo "请输入正确数字" sleep 5s start_menu ;; esac } start_menu <file_sep>#!/bin/bash #===================================================================# # System Required: CentOS 7 # #===================================================================# # #一键脚本 # # # 设置字体颜色函数 function red(){ echo -e "\033[31m\033[01m $1 \033[0m" } function redbg(){ echo -e "\033[37;41m\033[01m $1 \033[0m" } function yellow(){ echo -e "\033[33m\033[01m $1 \033[0m" } function white(){ echo -e "\033[37m\033[01m $1 \033[0m" } # # @安装docker install_docker() { docker version > /dev/null || curl -fsSL get.docker.com | bash service docker restart systemctl enable docker } install_docker_compose() { curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose } # 单独检测docker是否安装,否则执行安装docker。 check_docker() { if [ -x "$(command -v docker)" ]; then echo "docker is installed" # command else echo "Install docker" # command install_docker fi } check_docker_compose() { if [ -x "$(command -v docker-compose)" ]; then echo "docker-compose is installed" # command else echo "Install docker-compose" # command install_docker_compose fi } # check docker # 以上步骤完成基础环境配置。 echo "恭喜,您已完成基础环境安装,可执行安装程序。" restart_meedu(){ cd /opt/web docker-compose restart } # 输出结果 notice(){ yellow "==================================================" yellow "主程序已搭建完毕,让我们来完成最后几步,之后就可以访问了" yellow "==================================================" white "以下内容必须一步步操作" greenbg "等待数据库完成初始化,等待约10s" sleep 12s yellow "创建软链接" docker-compose exec app php artisan storage:link sleep 3s yellow "安装数据表" docker-compose exec app php artisan migrate sleep 10s yellow "初始化系统权限" docker-compose exec app php artisan install role sleep 8s yellow "初始化后台菜单" docker-compose exec app php artisan install backend_menu sleep 6s yellow "生成安装锁" docker-compose exec app php artisan install:lock yellow "定时任务" echo "* * * * * cd /opt/meedu && docker-compose exec app php artisan schedule:run >> /dev/null 2>&1" >> /var/spool/cron/root service crond reload yellow "开启队列监听器" yum install -y python-setuptools easy_install supervisor cat > /etc/supervisor/conf.d/meedu.conf <<-EOF [program:meedu] process_name=%(program_name)s_%(process_num)02d command=cd /opt/meedu && docker-compose exec php artisan queue:work --sleep=3 --tries=3 autostart=true autorestart=true user=root numprocs=4 redirect_stderr=true stdout_logfile=opt/meedu/storage/logs/supervisor.log EOF greenbg "队列监听配置完成。开始重启" supervisorctl reread supervisorctl update supervisorctl start meedu:* greenbg "正在重启meedu" restart_meedu sleep 10s } notice2(){ greenbg "初始化管理员" docker-compose exec app php artisan install administrator #初始化管理员,安装提示输入管理员的账号和密码 green "==================================================" green "搭建成功,现在您可以直接访问了" green "---------------------------" green " 首页地址: http://ip:$port" green " 后台地址:http://ip:$port/backend/login" green " 网页数据位置: /opt/meedu/data" green "---------------------------" white "其他信息" white "已配置的端口:$port 数据库root密码:<PASSWORD> " green "==================================================" } notice3(){ greenbg "初始化管理员" docker-compose exec app php artisan install administrator #初始化管理员,安装提示输入管理员的账号和密码 green "==================================================" green "搭建成功,现在您可以直接访问了" green "---------------------------" green " 首页地址: http://ip:$port" green " 管理员后台地址:http://ip:$port/backend/login" green " 主机数据绝对路径: /opt/meedu" green " 源码编辑器 http://ip:899 编辑器内路径/var/www/meedu" green "---------------------------" white "其他信息" white "已配置的端口:$port 数据库root密码:<PASSWORD> " green "==================================================" } # 开始安装meedu install_main(){ blue "获取配置文件" mkdir -p /opt/meedu && cd /opt/meedu rm -f docker-compose.yml wget https://raw.githubusercontent.com/doney0318/webdocker/master/docker-compose.yml blue "配置文件获取成功" sleep 2s white "请仔细填写参数,部署完毕会反馈已填写信息" green "访问端口:如果想通过域名访问,请设置80端口,其余端口可随意设置" read -e -p "请输入访问端口(默认端口2020):" port [[ -z "${port}" ]] && port="2020" green "设置数据库ROOT密码" read -e -p "请输入ROOT密码(默认baiyue.one):" rootpwd [[ -z "${rootpwd}" ]] && rootpwd="<PASSWORD>" green "请选择安装版本" yellow "1.[meedu1.0](稳定版-此版不支持源码编辑)" yellow "2.[meedu20190412](开发版)" yellow "3.[meedu-dev](开发版,同步meedu官网最新git分支-支持源码编辑)" echo read -e -p "请输入数字[1~3](默认1):" vnum [[ -z "${vnum}" ]] && vnum="1" if [[ "${vnum}" == "1" ]]; then greenbg "开始安装meedu1.0版本" sed -i "s/数据库密码/$rootpwd/g" /opt/meedu/docker-compose.yml sed -i "s/版本号/1.0/g" /opt/meedu/docker-compose.yml sed -i "s/"访问端口/"$port/g" /opt/meedu/docker-compose.yml greenbg "已完成配置部署" greenbg "程序将下载镜像,请耐心等待下载完成" cd /opt/meedu greenbg "首次启动会拉取镜像,国内速度比较慢,请耐心等待完成" docker-compose up -d notice notice2 elif [[ "${vnum}" == "2" ]]; then greenbg "开始安装meedu20190412版本" sed -i "s/数据库密码/$rootpwd/g" /opt/meedu/docker-compose.yml sed -i "s/版本号/20190412/g" /opt/meedu/docker-compose.yml sed -i "s/"访问端口/"$port/g" /opt/meedu/docker-compose.yml greenbg "已完成配置部署" greenbg "程序将下载镜像,请耐心等待下载完成" cd /opt/meedu greenbg "首次启动会拉取镜像,国内速度比较慢,请耐心等待完成" docker-compose up -d notice notice2 elif [[ "${vnum}" == "3" ]]; then white "项目正在路上。。。" meedu_master notice notice3 fi } # 初始化meedu程序 meedu_master(){ rm -rf /opt/meedu && cd /opt git clone -b master https://github.com/Qsnh/meedu.git cd /opt/meedu rm -f docker-compose.yml git clone -b docker https://github.com/Baiyuetribe/meedu.git && mv meedu/* . && rm -rf meedu sed -i "s/baiyue.one/$rootpwd/g" docker-compose.yml sed -i "7s/"80:80/"$port:80/" docker-compose.yml sed -i "s/127.0.0.1/mysql/g" .env.example sed -i "s/DB_PASSWORD=<PASSWORD>/DB_PASSWORD=$rootpwd/g" .env.example cp .env.example .env chmod -R a+w+r storage chmod -R a+w+r bootstrap/cache greenbg "本地初始化完成" cd /opt/meedu redbg "开始启动服务,首次启动会拉取镜像,请耐心等待" docker-compose up -d } # 停止服务 stop_meedu(){ cd /opt/meedu docker-compose kill } # 重启服务 restart_meedu(){ cd /opt/meedu docker-compose restart } # 卸载 remove_all(){ cd /opt/meedu docker-compose down echo -e "\033[32m已完成卸载\033[0m" } #开始菜单 start_menu(){ clear echo "" yellow "===============================================================" yellow "简介:网站一键安装脚本 " yellow "系统:Centos7、Ubuntu等 " yellow "===============================================================" echo yellow "使用前提:脚本会自动安装docker,国外服务器搭建只需1min~2min" yellow "国内服务器下载镜像稍慢,请耐心等待" white "备注:非80端口可以用caddy反代,自动申请ssl证书,到期自动续期" echo white "—————————————程序安装——————————————" white "1.安装meedu" white "—————————————杂项管理——————————————" white "2.停止meedu" white "3.重启meedu" white "4.卸载meedu" white "5.清除本地缓存(仅限卸载后操作)" white "—————————————域名访问——————————————" white "6.Caddy域名反代一键脚本(可以实现非80端口使用域名直接访问)" white "0.退出脚本" echo echo read -p "请输入数字:" num case "$num" in 1) check_docker check_docker_compose install_main ;; 2) stop_meedu green "meedu程序已停止运行" ;; 3) restart_meedu green "meedu程序已重启完毕" ;; 4) remove_all ;; 5) rm -fr /opt/meedu green "清除完毕" ;; 6) bash <(curl -L -s https://raw.githubusercontent.com/Baiyuetribe/codes/master/caddy/caddy.sh) ;; 0) exit 1 ;; *) clear echo "请输入正确数字" sleep 5s start_menu ;; esac } start_menu <file_sep>#!/bin/bash #===================================================================# # System Required: CentOS 7 # #===================================================================# # #一键脚本 # # 设置字体颜色函数 function blue(){ echo -e "\033[34m\033[01m $1 \033[0m" } function green(){ echo -e "\033[32m\033[01m $1 \033[0m" } function greenbg(){ echo -e "\033[43;42m\033[01m $1 \033[0m" } function red(){ echo -e "\033[31m\033[01m $1 \033[0m" } function redbg(){ echo -e "\033[37;41m\033[01m $1 \033[0m" } function yellow(){ echo -e "\033[33m\033[01m $1 \033[0m" } function white(){ echo -e "\033[37m\033[01m $1 \033[0m" } # # @安装docker install_docker() { docker version > /dev/null || curl -fsSL get.docker.com | bash service docker restart systemctl enable docker } install_docker_compose() { curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose } # 单独检测docker是否安装,否则执行安装docker。 check_docker() { if [ -x "$(command -v docker)" ]; then echo "docker is installed" # command else echo "Install docker" # command install_docker fi } check_docker_compose() { if [ -x "$(command -v docker-compose)" ]; then echo "docker-compose is installed" # command else echo "Install docker-compose" # command install_docker_compose fi } # check docker # 以上步骤完成基础环境配置。 echo "恭喜,您已完成基础环境安装,可执行安装程序。" restart_nginx(){ cd /opt/nginx docker-compose restart } # 输出结果 notice2(){ greenbg "初始化管理员" green "==================================================" green "搭建成功,现在您可以直接访问了" green "---------------------------" green " 首页地址: http://ip:$port" green " 后台地址:http://ip:$port/" green " 网页数据位置: /opt/nginx/www" green "---------------------------" white "其他信息" white "已配置的端口:$port 数据库root密码:<PASSWORD> " green "==================================================" } notice3(){ green "==================================================" green "搭建成功,现在您可以直接访问了" green "---------------------------" green " 首页地址: http://ip:$port" green " 主机数据绝对路径: /opt/nginx" green "---------------------------" white "其他信息" white "已配置的端口:$port 数据库root密码:<PASSWORD> " white "phpMyAdmin: http://ip:8080" white "phpRedisAdmin: http://ip:8081" green "==================================================" } # 环境配置 config_nginx(){ blue "获取配置文件" mkdir -p /opt/nginx && cd /opt/nginx yum install git -y git clone https://github.com/doney0318/dnmp.git mv dnmp/* . rm -rf dnmp blue "配置文件获取成功" sleep 2s white "请仔细填写参数,部署完毕会反馈已填写信息" green "访问端口:如果想通过域名访问,请设置80端口,其余端口可随意设置" read -e -p "请输入访问端口(默认端口80):" port [[ -z "${port}" ]] && port="80" green "设置数据库ROOT密码" read -e -p "请输入ROOT密码(默认123456):" rootpwd [[ -z "${rootpwd}" ]] && rootpwd="<PASSWORD>" green "环境配置中" cp env.sample .env cp docker-compose-sample.yml docker-compose.yml sed -i "s/NGINX_HTTP_HOST_PORT=80/NGINX_HTTP_HOST_PORT=$port/g" /opt/nginx/.env sed -i "s/MYSQL_ROOT_PASSWORD=<PASSWORD>/MYSQL_ROOT_PASSWORD=$rootpwd/g" /opt/nginx/.env green "已完成配置部署" } # 程序安装 install_main(){ if [[ -d "/opt/nginx" ]]; then white "配置文件已存在" cd /opt/nginx else white "配置文件不存在" blue "获取配置文件" mkdir -p /opt/nginx && cd /opt/nginx yum install git -y git clone https://github.com/doney0318/dnmp.git mv dnmp/* . rm -rf dnmp blue "配置文件获取成功" sleep 2s white "请仔细填写参数,部署完毕会反馈已填写信息" green "访问端口:如果想通过域名访问,请设置80端口,其余端口可随意设置" read -e -p "请输入访问端口(默认端口80):" port [[ -z "${port}" ]] && port="80" green "设置数据库ROOT密码" read -e -p "请输入ROOT密码(默认123456):" rootpwd [[ -z "${rootpwd}" ]] && rootpwd="<PASSWORD>" green "环境配置中" cp env.sample .env cp docker-compose-sample.yml docker-compose.yml sed -i "s/NGINX_HTTP_HOST_PORT=80/NGINX_HTTP_HOST_PORT=$port/g" /opt/nginx/.env sed -i "s/MYSQL_ROOT_PASSWORD=<PASSWORD>/MYSQL_ROOT_PASSWORD=$rootpwd/g" /opt/nginx/.env green "已完成配置部署" fi green "程序将下载镜像,请耐心等待下载完成" green "首次启动会拉取镜像,国内速度比较慢,请耐心等待完成" docker-compose up -d notice3 } # 项目加载 nginx_master(){ green "请选择需要安装的项目" yellow "1.[nginx1](项目一)" yellow "2.[nginx2](项目二)" read -e -p "请输入数字[1~2](默认1):" vnum [[ -z "${vnum}" ]] && vnum="1" if [[ "${vnum}" == "1" ]]; then white "开始加载项目一" white "施工中" elif [[ "${vnum}" == "2" ]]; then white "开始加载项目二" white "施工中" fi redbg "拉取镜像中,请耐心等待" } # 停止服务 stop_nginx(){ cd /opt/nginx docker-compose kill } # 重启服务 restart_nginx(){ cd /opt/nginx docker-compose restart } # 卸载 remove_all(){ cd /opt/nginx docker-compose down echo -e "\033[32m已完成卸载\033[0m" } #开始菜单 start_menu(){ clear echo "" greenbg "===============================================================" greenbg "简介:网站一键安装脚本" greenbg "系统:Centos7" greenbg "===============================================================" echo white "—————————————环境设置——————————————" white "1.环境设置" white "—————————————程序安装——————————————" white "2.安装nginx" white "—————————————项目加载——————————————" white "3.项目加载" white "—————————————杂项管理——————————————" white "4.停止nginx" white "5.重启nginx" white "6.卸载nginx" white "7.清除本地缓存(仅限卸载后操作)" blue "0.退出脚本" echo read -p "请输入数字:" num case "$num" in 1) config_nginx green "环境参数设置完毕" ;; 2) check_docker check_docker_compose install_main ;; 3) nginx_master ;; 4) stop_nginx green "程序已停止运行" ;; 5) restart_nginx green "程序已重启完毕" ;; 6) remove_all ;; 7) rm -fr /opt/nginx green "清除完毕" ;; 0) exit 1 ;; *) clear echo "请输入正确数字" sleep 5s start_menu ;; esac } start_menu <file_sep>## 一键安装脚本(适配centos7) ``` bash <(curl -L -s https://raw.githubusercontent.com/doney0318/webdocker/master/docker.sh) ``` ## 版本介绍 ## 功能介绍 一键增加虚拟内存 ``` wget https://raw.githubusercontent.com/doney0318/webdocker/master/swap.sh && bash swap.sh ```
09a8b45f49ebf1eca4a5be1472b328d58e5a1bbc
[ "Markdown", "Shell" ]
4
Shell
doney0318/webdocker
045cd0855dbbc7a9404479d20b39c7c21b0605e7
c6370479a500903b93e1183485320e5aab1fdfe0
refs/heads/master
<file_sep># imports from flask import Flask, render_template, make_response, request import os import sys import pathlib import datetime as dt import urllib.request import boto3 # for the data processing import pandas as pd # for connection to SQL database #from sqlalchemy import create_engine # Local imports #sys.path.insert(0, str(pathlib.Path(__file__).parent)) from datalink import download_jsongz_data, get_updated_city_list, get_city_coord, load_appconfig, init_config_file from db_access import fetch_records_table_for_coord, engine app = Flask(__name__) # Let's use Amazon S3 s3engine = boto3.client('s3') #city_list = get_updated_city_list(form_location=os.environ['WG_CONFIG_PATH']) # update using the list of records stored on local disk #app.config['CITY_LIST'] = city_list @app.route('/') @app.route('/index') def index(): citiesLST = [] display_country = 'CZ' for item in config['CITY_LIST']: if item['country'] == display_country: if item['retrieve']==True: citiesLST.append(item['name']) return render_template('list_of_cities.html', cities = citiesLST, country=display_country) #return render_template('index.html') @app.route('/<country>') def show_cities(country): citiesLST = [] for item in config['CITY_LIST']: if item['country'] == country: citiesLST.append(item['name']) return render_template('list_of_cities.html', cities = citiesLST, country=country) @app.route('/list_of_countries') def show_countries(): countryLST = [] for item in config['CITY_LIST']: country=item['country'] if not country in countryLST: countryLST.append(country) else: pass return render_template('list_of_countries.html',title='List of countries', countries=countryLST) @app.route('/query') def show_city(): """ display the stored weather records for given city """ timestamp = request.args.get('timestamp') country=request.args.get('country') city=request.args.get('city') coord = get_city_coord(city,country,config['CITY_LIST']) records_pd = fetch_records_table_for_coord(engine,coord) # list of records downloaded for this city if type(records_pd)!=type(None): record_filenames = list(records_pd['data_storage_link'].values ) bucket_name = os.environ['WG_S3BUCKET_NAME'] #record_links = [urllib.parse.urljoin (DS_link,record_filename) for record_filename in record_filenames ] record_timestamps = list(records_pd.index.values) record_dates = [dt.datetime.fromtimestamp(int(ts)) for ts in record_timestamps] # formated for display in the web pages # select apropriate timestamp to display: if timestamp==None: record_idx = -1 else: record_idx = record_timestamps.index(timestamp) record_filename = record_filenames[record_idx] record_dict = download_jsongz_data(s3engine, bucket_name, object_name=record_filename) info_date = dt.datetime.fromtimestamp(record_dict['current']['dt']).isoformat() weather_info_table = pd.json_normalize(record_dict['current']).loc[:,'sunrise':'wind_deg'].to_html(index=False) forecast_table = pd.json_normalize(record_dict['hourly']).loc[:,'dt':'wind_deg'] tsIndex = [dt.datetime.fromtimestamp(ts) for ts in forecast_table['dt'].values] forecast_table['dt'] = tsIndex forecast_table.set_index('dt',inplace=True) forecast_info_table = forecast_table.to_html(index=True) response = render_template('city.html', country=country, name=city, other_records=zip(record_dates,record_timestamps), weather_info=weather_info_table, forecast_info = forecast_info_table, info_date=info_date) else: response = render_template('city_not_found.html', country=country, name=city, ) return response #background process happening without any refreshing @app.route('/background_process_test') def background_process_test(): print ("Downloading the data from the OpenWeatherService") response = urllib.urlopen('https://wordpress.org/plugins/about/readme.txt') data = response.read() print(data) return ("nothing") @app.route("/graphics/<city>(<country>).png") def plot_param(city,country,plot_parameter='main.temp'): """ placeholder function to put graphics generation code """ response = '' return response if __name__ == '__main__': config = load_appconfig(s3engine,os.environ['WG_CONFIG_PATH']) if config == None: # initialize the config file local_data_folder=os.environ['WG_LOCAL_DATA_STORE'] config_path=os.environ['WG_CONFIG_PATH'] init_config_file(s3engine,local_data_folder, config_path, count_limit=int(os.environ['WG_CITY_COUNT_LIMIT'])) config = load_appconfig(s3engine,os.environ['WG_CONFIG_PATH']) app.run(debug=True, host='0.0.0.0') <file_sep>from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter def plot_param(city,country,plot_parameter='main.temp'): from modules.datalink import extract_json_data city_found = False # indicator whether the city was found among cities in the given country graph_filename = 'blank.png' # filename of the weather prediciton graph hourly_14 = extract_json_data('data/hourly_14.json.gz') for item in hourly_14: if item['city']['country'] == country: if item['city']['name'] == city: city_found = True forecast_date = dt.datetime.fromtimestamp(item['time']).isoformat() # forecast date break hourly_14_city_df = pd.json_normalize(item['data']) tsIndex = [dt.datetime.fromtimestamp(ts) for ts in pd.to_datetime(hourly_14_city_df['dt']).values] hourly_14_city_df['timestamp'] =tsIndex hourly_14_city_df.set_index('timestamp',inplace=True); # extract the data to plot temps = hourly_14_city_df[plot_parameter] t = temps.index s = temps.values # create the figure fig=Figure() ax=fig.add_subplot(111) ax.plot_date(t, s,'-') fig.autofmt_xdate(rotation=45) ax.set(xlabel='dates', ylabel=plot_parameter, title=('weather forecast ISO date: %s' % forecast_date)) ax.grid() # generate the picture data canvas=FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' #fig.savefig("graphics/test.png") return response <file_sep>FROM ubuntu:18.04 MAINTAINER <NAME> RUN apt-get update -y && \ apt-get install -y python3-pip python3-dev && \ apt-get install -y nginx uwsgi uwsgi-plugin-python3 COPY ./requirements.txt /requirements.txt COPY ./nginx.conf /etc/nginx/nginx.conf COPY ./proxy.conf /etc/nginx/proxy.conf COPY ./fastcgi.conf /etc/nginx/fastcgi.conf COPY ./mime.types /etc/nginx/mime.types WORKDIR / RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt COPY . / RUN adduser --disabled-password --gecos '' nginx\ && chown -R nginx:nginx /app \ && chmod 777 /run/ -R \ && chmod 777 /root/ -R ENTRYPOINT [ "/bin/bash", "/launch.sh"] <file_sep>import io import os import sys import pathlib import pandas as pd # for config saving and data download import urllib import gzip, json import datetime as dt import logging from botocore.exceptions import ClientError def extract_json_data(jsonfilename): with gzip.GzipFile(jsonfilename, 'r') as fin: #print('enc', json.detect_encoding(fin.read())) data = [json.loads(line,encoding='utf-8') for line in fin.readlines()] #data = json.loads(fin.read().decode('utf-8'),encoding='utf-8') return data def download_jsongz_data(s3engine, bucket_name, object_name): """retrieve data form a object in the S3 bucket inputs: bot3.client('s3') instance :param file_name: File to upload :param bucket: Bucket name to upload to :param object_name: S3 object name. :return: True if file was uploaded, else False """ # Download the file try: with io.BytesIO() as f: response = s3engine.download_fileobj(bucket_name, object_name,f) print (response) f.seek(0, 0) with gzip.open(f, 'r') as jf: data = json.loads(jf.read(),encoding='utf-8') except ClientError as e: logging.error(e) data = None return data def upload_jsongz_data(s3engine, bucket_name, object_name, data): """ helper for uploading the JSON serialized python objects to the S3 server inputs : S3engine: instance of boto3.client object_name: what should be the filename of the serialized object on the server returns: None """ #remote_link = "https://muyavskybleu.s3.amazonaws.com/config/test_config.json.gz" try: data_json = gzip.compress (json.dumps(data).encode('utf-8')) with io.BytesIO(data_json) as f: s3engine.upload_fileobj(f, bucket_name, object_name) except ClientError as e: logging.error(e) return def save_appconfig(S3engine,filename, config): """ helper for saving the app config inputs : file: filename for saving the configuration config: configuration object returns: None """ remote_link = os.environ['WG_CONFIG_PATH'] kyblik = os.environ['WG_S3BUCKET_NAME'] print('saving config to file:', remote_link) upload_jsongz_data(S3engine, bucket_name=kyblik, object_name=remote_link, data=config) return def load_appconfig(S3engine,filename, config=None): """ helper for loading the app config loads the dictionary from the file and updates a config, or creates new config inputs : file: filename for saving the configuration config: configuration object returns: None """ remote_link = os.environ['WG_CONFIG_PATH'] kyblik = os.environ['WG_S3BUCKET_NAME'] new_config=download_jsongz_data(S3engine, bucket_name=kyblik, object_name=remote_link) if type(config) == type(None): response = new_config else: config.update(new_config) response = None return response def init_config_file(S3engine, local_data_folder, config_path, count_limit=3): # setup the application configuration config = dict() DATA_STORE = local_data_folder # this will point to the folder in the compute server in the cloud cities_Fname = os.path.join(DATA_STORE, 'weather_14.json.gz') # where the list of cities for initialization is stored country_retireve = 'CZ' # download data for cities in this country config['DATA_STORE'] = DATA_STORE config['OPENWEATHER_ONECALL_URL'] = 'https://api.openweathermap.org/data/2.5/onecall?' config['OPENWEATHER_QUERY'] = {'lat':None, 'lon':None, 'units':'metric'} config['CITY_LIST'] = [item['city'] for item in extract_json_data(cities_Fname)] # list of cities, links to their records and retrieval status # configure retrieval of weather information (staticaly, for all CZ cities from the list) limit = count_limit # for testing purposes, download only 3 cities for city in config['CITY_LIST']: if (city['country'] == country_retireve) and (limit>=0): city['retrieve'] = True #city['retrieval_interval(s)'] = 3600 limit -=1 print(city['name']) else: city['retrieve'] = False # save the config in a json file save_appconfig(S3engine,config_path,config) return def get_updated_city_list(s3engine, form_location): # reload config new_config = load_appconfig(s3engine,form_location) return new_config['CITY_LIST'] def get_city_latlon (city,country,city_list): lat=None lon=None for item in city_list: if item['country'] == country: if item['name'] == city: city_found = True lat=item['coord']['lat'] lon=item['coord']['lon'] break return (lat,lon) def get_city_coord (city,country,city_list): response = None for item in city_list: if item['country'] == country: if item['name'] == city: city_found = True response = item['coord'] break return response def query_for_city(city,country,url,query_template,city_list): (lat, lon) = get_city_latlon(city,country,city_list) query_dict = {} for key in query_template: query_dict[key] = query_template[key] if key == 'lat': query_dict[key] = lat if key == 'lon': query_dict[key] = lon queryS = url+"&".join([('%s=%s'% (qid,val)) for (qid, val) in query_dict.items()]) return queryS def get_dict_from_data(record_fname): with open(record_fname) as jf: data = [json.loads(line,encoding='utf-8') for line in jf.readlines()] return data def fetch_records_table_for_coord(engine,coord,units='metric'): """ fetches metadata with links to the stored files, and related information """ table_name = format_SQLtable_name(coord,units) response = None if table_exists (engine,coord,units): query = ("SELECT * FROM %s;" % table_name) response = pd.read_sql(query,engine,index_col='timestamp') return response def get_dict_from_data_http(record_fname): """ retrieves stored file from S3 """ with urllib.request.urlopen(record_fname) as jf: data = [json.loads(line,encoding='utf-8') for line in jf.readlines()] return data<file_sep># WeatherGirl-frontend Sample web app that displays historical weather information gathered form OpenWeatherMap.com. It is written in Python and uses Amazon Web Services (one S3 bucket and MySQL database hosted on RDS) cloud infrastructure. The app looks-up the database to get list of filenames that contain weather information related to a specified geolocation (city, country). It then displays the data from JSON files retrieved from the S3 bucket. The application source code is ready for deployment in form of docker container. ## Prerequisites: The app serves as a web UI to display data stored in the cloud infrastructure. The app must have access to the respective services, namely the S3 bucket and the mysql database server. Another app [WeatherGirl-backend](https://github.com/daveraees/WeatherGirl-backend) can be used to retrieve the weather info files from OpenWeatherMap and store the data files in the S3 bucket. ## Dependency requirements for running the server: ### libraries - The app was tested and runs with python 3.7 - Libraries are specified in the file requirements.txt ### environment variables: Before running the app itself from source code, or building of container, please make sure the following environmental variables are configured - WG_S3BUCKET_NAME=appbucket # name of the file storage server S3 buckeet - WG_CONFIG_PATH=path/to/config/wg_config.json.gz # this file must be accessible also to the backend app, that uses it to execute the weather infro downloads - WG_LOCAL_DATA_STORE=app/data # where small temporary file can be stored. No requirements for accessibility from other services - WG_DATABASE_ENDPOINT=mysqlDB.example.com - WG_DATABASE_USER="mysql_read_access_username" - WG_DATABASE_PASS="<PASSWORD>" - WG_DATABASE_PORT: 3306 - WG_DATABASE_NAME: 'cities' - WG_CITY_COUNT_LIMIT=60 # maximum number of cities that can be marked for download by the backend app. ## Usage: running the web server locally from the source code in the root directory of the local git repository: $ python3 ./app/app.py This will start the web server. The app will try to download the configuration file. If the config download fail, it will create new config, using the city locaiton database in file app/data/weather_14.json.gz The files docker-compose.yml and Dockerfile contain instructions needed to build a docker image. <file_sep><html> <body> <h1>City named "{{ name }}" not found in weather records for country ({{ country }})!</h1> <p><a href='/'>Return to the homepage</a> </body> </html>
e9c37a2e7062aefb36d393cdb40d866f63bba208
[ "Markdown", "HTML", "Python", "Dockerfile" ]
6
Python
daveraees/WeatherGirl-frontend
42e1d623cdc9a481854553bdce4b4ddc00861fc5
79ee0ab82e7eff5ab36105209d760072bf4f4108
refs/heads/main
<repo_name>Diezia/mis-custom-hooks<file_sep>/useCounter.js import { useState } from "react" export const useCounter = ( initialCounter = 0, minValue = 0, maxValue = 100000 ) => { // Agregarle uno o dos parámetros para que se pueda indicar (desde el componente que llama a useCounter) el número máximo y el número mínimo que puede tomar el counter const [counter, setCounter] = useState(initialCounter) // console.log("entre en el useCounter") const increment = () => { // console.log("increment"); maxValue > counter && setCounter( counter + 1 ) } const decrement = () => { // console.log("decrement"); minValue < counter && setCounter( counter - 1 ) } const reset = () => { // console.log("reset"); setCounter( initialCounter ) } const random = () => { // console.log("random"); const rand = minValue + Math.random() * (maxValue - minValue); const randint = Math.floor( rand ) setCounter( randint ); } return({ counter, increment, decrement, reset, random }) }
319a204c5f56e31ef2bc4a232a2067c087b7717c
[ "JavaScript" ]
1
JavaScript
Diezia/mis-custom-hooks
4b9bf1829d9dd1140b783062d02e73e06fab60e5
f4547f894729c381af13559ed6eb55de220f1c02
refs/heads/main
<file_sep>## Interfaces Inteligentes ### Práctica 3: Delegados, eventos 1. Agregar dos objetos en la escena: A y B. Cuando el jugador colisiona con un objeto de tipo B, el objeto A volcará en consola un mensaje. Cuando toca el objeto A se incrementará un contador en el objeto B: Para el primer enunciado "Cuando el jugador colisiona con un objeto de tipo B, el objeto A volcará en consola un mensaje" scripts usados: *objectA, delegateHandler* [![Image from Gyazo](https://i.gyazo.com/43331d996bd059535a2d5c59964c94b7.gif)](https://gyazo.com/43331d996bd059535a2d5c59964c94b7) > (Se imprime 4 veces ya que existes cuatro instancias del objecto A en el momento de ejecución) Cuando toca el objeto A se incrementará un contador en el objeto B: [![Image from Gyazo](https://i.gyazo.com/2289d39f12ab1e80d04cd296493e3aba.gif)](https://gyazo.com/2289d39f12ab1e80d04cd296493e3aba) > Un pequeño fail en el primer intento de chocar jeje ---- 2. Implementar un controlador de escena usando el patrón delegado que gestione las siguientes acciones: ○ Si el jugador dispara, los objetos de tipo A que estén a una distancia media serán desplazados y los que estén a una distancia pequeña serán destruidos. Los umbrales que marcan los límites se deben configurar en el inspector: [![Image from Gyazo](https://i.gyazo.com/2bf1da290cff3a5326f5e07b416cdfa0.gif)](https://gyazo.com/2bf1da290cff3a5326f5e07b416cdfa0) ○ Si el jugador choca con objetos de tipo B, todos los de ese tipo sufrirán alguna transformación o algún cambio en su apariencia y decrementarán el poder del jugador: [![Image from Gyazo](https://i.gyazo.com/0728494bdd8b042225e072fd8ca929bc.gif)](https://gyazo.com/0728494bdd8b042225e072fd8ca929bc) --- 3. En la escena habrá ubicados un tipo de objetos que al ser recolectados por el jugador harán que ciertos obstáculos se desplacen desbloqueando algún espacio: [![Image from Gyazo](https://i.gyazo.com/879c964810e5844d90cbaa9949826a79.gif)](https://gyazo.com/879c964810e5844d90cbaa9949826a79) ---- 4. Incorporar un elemento que sirva para encender o apagar un foco utilizando el teclado: [![Image from Gyazo](https://i.gyazo.com/10cca6ef65dfd9d80b3101fd7b1d2505.gif)](https://gyazo.com/10cca6ef65dfd9d80b3101fd7b1d2505) <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class objectB : MonoBehaviour { public DelegateHandler handler; public int collisionCounter; public float distanceToPlayer; // Start is called before the first frame update void Start() { collisionCounter = 0; handler.col += Counter; } // Update is called once per frame void Update() { } void Counter() { collisionCounter++; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerCollision : MonoBehaviour { public MainSceneController mainController; // Start is called before the first frame update void Start() { mainController.bimp += ChangeSize; } // Update is called once per frame void Update() { } void OnCollisionEnter(Collision collision) { if (collision.collider.tag == "Player") { mainController.ChangeSizeTrigger(); } } void ChangeSize() { // Efecto en objectos B GetComponent<Transform>().localScale += new Vector3(10, 10, 10); GetComponent<Rigidbody>().mass *= 1000; // Efecto en jugador (negativo) GameObject.Find("shadowElEriso").GetComponent<MoveBehaviour>().runSpeed = 0.3f; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GateMovement : MonoBehaviour { public MainSceneController mainController; public bool slide; public float slideSpeed; // Start is called before the first frame update void Start() { mainController.gate += SlideDown; slide = false; slideSpeed = 50; } // Update is called once per frame void Update() { if (slide == true) { if (GetComponent<Transform>().localPosition.y > -54) { transform.Translate(Vector3.down * slideSpeed * Time.deltaTime, Space.World); } } } void SlideDown() { slide = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class objectA : MonoBehaviour { // Start is called before the first frame update public DelegateHandler CollisionHandler; public MainSceneController SceneController; public float distanceToPlayer; void Start() { CollisionHandler.col += PrintMessage; SceneController.pshot += PlayerShot; } // Update is called once per frame void Update() { } void PrintMessage() { Debug.Log("¡El jugador ha impactado con el objeto B!"); } void PlayerShot() { distanceToPlayer = Vector3.Distance(GameObject.Find("shadowElEriso").transform.position, transform.position); if(distanceToPlayer < SceneController.ShortRange) { Debug.Log("Object A " + name + " at short range (" + distanceToPlayer+ ")"); SceneController.pshot -= PlayerShot; Destroy(gameObject, 0); } else if(distanceToPlayer < SceneController.MediumRange) { Debug.Log("Object A " + name + " at medium range (" + distanceToPlayer+ ")"); // how much the character should be knocked back float magnitude = 2000 * distanceToPlayer; // calculate force vector var force = transform.position - GameObject.Find("shadowElEriso").transform.position; // normalize force vector to get direction only and trim magnitude force.Normalize(); gameObject.GetComponent<Rigidbody>().AddForce(force * magnitude); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController : MonoBehaviour { public Transform tf; public float velocity; public Vector3 movement; // Start is called before the first frame update void Start() { tf = GetComponent<Transform>(); velocity = 6.0f; } // Update is called once per frame void Update() { float xAxis = 0; float zAxis = 0; if (Input.GetKey("w")) { xAxis += 1; } if (Input.GetKey("a")) { zAxis += 1; } if (Input.GetKey("s")) { xAxis -= 1; } if (Input.GetKey("d")) { zAxis -= 1; } movement = new Vector3(xAxis * velocity, 0, zAxis * velocity); tf.Translate(movement * Time.deltaTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainSceneController : MonoBehaviour { public delegate void PlayerShot(); public event PlayerShot pshot; public delegate void BImpact(); public event BImpact bimp; public delegate void ItemCollection(); public event ItemCollection gate; public float ShortRange = 5; public float MediumRange = 10; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown("r")) { if(pshot != null) { pshot(); } } } public void ChangeSizeTrigger() { bimp(); } public void GateTrigger() { gate(); } }
6ea19fa25a6a74a8413ad9b80de009d66b45dde0
[ "Markdown", "C#" ]
7
Markdown
jacedleon/P3-II
8472879f55966725f655d70d3bfe00cfedf5649b
1a31877b3cde156bd6e596c6301a488cdb10d5bd
refs/heads/master
<repo_name>stenzek/YGameEngine<file_sep>/Engine/Source/MathLib/StreamOperators.cpp #include "MathLib/StreamOperators.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #include "MathLib/Quaternion.h" #include "MathLib/AABox.h" #include "MathLib/Sphere.h" #include "YBaseLib/BinaryReader.h" #include "YBaseLib/BinaryWriter.h" BinaryReader &operator>>(BinaryReader &binaryReader, Vector2f &value) { return binaryReader >> value.x >> value.y; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector3f &value) { return binaryReader >> value.x >> value.y >> value.z; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector4f &value) { return binaryReader >> value.x >> value.y >> value.z >> value.w; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector2i &value) { return binaryReader >> value.x >> value.y; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector3i &value) { return binaryReader >> value.x >> value.y >> value.z; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector4i &value) { return binaryReader >> value.x >> value.y >> value.z >> value.w; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector2u &value) { return binaryReader >> value.x >> value.y; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector3u &value) { return binaryReader >> value.x >> value.y >> value.z; } BinaryReader &operator>>(BinaryReader &binaryReader, Vector4u &value) { return binaryReader >> value.x >> value.y >> value.z >> value.w; } BinaryReader &operator>>(BinaryReader &binaryReader, Quaternion &value) { float x, y, z, w; BinaryReader &ret = binaryReader >> x >> y >> z >> w; value.Set(x, y, z, w); return ret; } BinaryReader &operator>>(BinaryReader &binaryReader, AABox &value) { Vector3f minBounds, maxBounds; BinaryReader &ret = binaryReader >> minBounds >> maxBounds; value.SetBounds(minBounds, maxBounds); return ret; } BinaryReader &operator>>(BinaryReader &binaryReader, Sphere &value) { Vector3f center; float radius; BinaryReader &ret = binaryReader >> center >> radius; value.SetCenterAndRadius(center, radius); return ret; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2f &value) { return binaryWriter << value.x << value.y; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3f &value) { return binaryWriter << value.x << value.y << value.z; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4f &value) { return binaryWriter << value.x << value.y << value.z << value.w; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2i &value) { return binaryWriter << value.x << value.y; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3i &value) { return binaryWriter << value.x << value.y << value.z; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4i &value) { return binaryWriter << value.x << value.y << value.z << value.w; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2u &value) { return binaryWriter << value.x << value.y; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3u &value) { return binaryWriter << value.x << value.y << value.z; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4u &value) { return binaryWriter << value.x << value.y << value.z << value.w; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Quaternion &value) { return binaryWriter << value.x << value.y << value.z << value.w; } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const AABox &value) { return binaryWriter << value.GetMinBounds() << value.GetMaxBounds(); } BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Sphere &value) { return binaryWriter << value.GetCenter() << value.GetRadius(); } <file_sep>/Engine/Source/Core/TypeRegistry.h #pragma once #include "Core/Common.h" #include "YBaseLib/PODArray.h" #include "YBaseLib/CString.h" #include "YBaseLib/MemArray.h" #define INVALID_TYPE_INDEX 0xFFFFFFFF template<class T> class TypeRegistry { public: struct RegisteredTypeInfo { T *pTypeInfo; const char *TypeName; uint32 InheritanceDepth; }; public: TypeRegistry() {} ~TypeRegistry() {} uint32 RegisterTypeInfo(T *pTypeInfo, const char *TypeName, uint32 InheritanceDepth) { uint32 Index; DebugAssert(pTypeInfo != NULL); for (Index = 0; Index < m_arrTypes.GetSize(); Index++) { if (m_arrTypes[Index].pTypeInfo == pTypeInfo) Panic("Attempting to register type multiple times."); } for (Index = 0; Index < m_arrTypes.GetSize(); Index++) { if (m_arrTypes[Index].pTypeInfo == NULL) { m_arrTypes[Index].pTypeInfo = pTypeInfo; m_arrTypes[Index].TypeName = TypeName; m_arrTypes[Index].InheritanceDepth = InheritanceDepth; break; } } if (Index == m_arrTypes.GetSize()) { RegisteredTypeInfo t; t.pTypeInfo = pTypeInfo; t.TypeName = TypeName; t.InheritanceDepth = InheritanceDepth; m_arrTypes.Add(t); } CalculateMaxInheritanceDepth(); return Index; } void UnregisterTypeInfo(T *pTypeInfo) { uint32 i; for (i = 0; i < m_arrTypes.GetSize(); i++) { if (m_arrTypes[i].pTypeInfo == pTypeInfo) { m_arrTypes[i].pTypeInfo = NULL; m_arrTypes[i].TypeName = NULL; m_arrTypes[i].InheritanceDepth = 0; break; } } } const uint32 GetNumTypes() const { return m_arrTypes.GetSize(); } const uint32 GetMaxInheritanceDepth() const { return m_iMaxInheritanceDepth; } const RegisteredTypeInfo &GetRegisteredTypeInfoByIndex(uint32 TypeIndex) const { return m_arrTypes.GetElement(TypeIndex); } const T *GetTypeInfoByIndex(uint32 TypeIndex) const { return m_arrTypes.GetElement(TypeIndex).pTypeInfo; } const T *GetTypeInfoByName(const char *TypeName) const { for (uint32 i = 0; i < m_arrTypes.GetSize(); i++) { if (m_arrTypes[i].pTypeInfo != NULL && !Y_stricmp(m_arrTypes[i].TypeName, TypeName)) return m_arrTypes[i].pTypeInfo; } return NULL; } private: typedef MemArray<RegisteredTypeInfo> TypeArray; TypeArray m_arrTypes; uint32 m_iMaxInheritanceDepth; void CalculateMaxInheritanceDepth() { uint32 i; m_iMaxInheritanceDepth = 0; for (i = 0; i < m_arrTypes.GetSize(); i++) { if (m_arrTypes[i].pTypeInfo != NULL) m_iMaxInheritanceDepth = Max(m_iMaxInheritanceDepth, m_arrTypes[i].InheritanceDepth); } } }; <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUDevice.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUBuffer.h" #include "D3D11Renderer/D3D11GPUOutputBuffer.h" #include "Engine/EngineCVars.h" Log_SetChannel(D3D11GPUDevice); D3D11GPUDevice::D3D11GPUDevice(IDXGIFactory *pDXGIFactory, IDXGIAdapter *pDXGIAdapter, ID3D11Device *pD3DDevice, ID3D11Device1 *pD3DDevice1, D3D_FEATURE_LEVEL D3DFeatureLevel, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, DXGI_FORMAT windowBackBufferFormat, DXGI_FORMAT windowDepthStencilFormat) : m_pDXGIFactory(pDXGIFactory) , m_pDXGIAdapter(pDXGIAdapter) , m_pD3DDevice(pD3DDevice) , m_pD3DDevice1(pD3DDevice1) , m_D3DFeatureLevel(D3DFeatureLevel) , m_featureLevel(featureLevel) , m_texturePlatform(texturePlatform) , m_swapChainBackBufferFormat(windowBackBufferFormat) , m_swapChainDepthStencilBufferFormat(windowDepthStencilFormat) { if (m_pDXGIFactory != nullptr) m_pDXGIFactory->AddRef(); if (m_pDXGIAdapter != nullptr) m_pDXGIAdapter->AddRef(); if (m_pD3DDevice != nullptr) m_pD3DDevice->AddRef(); if (m_pD3DDevice1 != nullptr) m_pD3DDevice1->AddRef(); } D3D11GPUDevice::~D3D11GPUDevice() { SAFE_RELEASE(m_pD3DDevice1); SAFE_RELEASE(m_pD3DDevice); SAFE_RELEASE(m_pDXGIAdapter); SAFE_RELEASE(m_pDXGIFactory); #ifdef Y_BUILD_CONFIG_DEBUG // dump remaining objects { HMODULE hDXGIDebugModule = GetModuleHandleA("dxgidebug.dll"); if (hDXGIDebugModule != NULL) { HRESULT(WINAPI *pDXGIGetDebugInterface)(REFIID riid, void **ppDebug); pDXGIGetDebugInterface = (HRESULT(WINAPI *)(REFIID, void **))GetProcAddress(hDXGIDebugModule, "DXGIGetDebugInterface"); if (pDXGIGetDebugInterface != NULL) { IDXGIDebug *pDXGIDebug; if (SUCCEEDED(pDXGIGetDebugInterface(__uuidof(pDXGIDebug), reinterpret_cast<void **>(&pDXGIDebug)))) { Log_DevPrint("=== Begin remaining DXGI and D3D object dump ==="); pDXGIDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL); Log_DevPrint("=== End remaining DXGI and D3D object dump ==="); pDXGIDebug->Release(); } } } } #endif } RENDERER_PLATFORM D3D11GPUDevice::GetPlatform() const { return RENDERER_PLATFORM_D3D11; } RENDERER_FEATURE_LEVEL D3D11GPUDevice::GetFeatureLevel() const { return m_featureLevel; } TEXTURE_PLATFORM D3D11GPUDevice::GetTexturePlatform() const { return m_texturePlatform; } void D3D11GPUDevice::GetCapabilities(RendererCapabilities *pCapabilities) const { pCapabilities->MaxTextureAnisotropy = D3D11_MAX_MAXANISOTROPY; pCapabilities->MaximumVertexBuffers = D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; pCapabilities->MaximumConstantBuffers = D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT; pCapabilities->MaximumTextureUnits = D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; pCapabilities->MaximumSamplers = D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT; pCapabilities->MaximumRenderTargets = D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; pCapabilities->SupportsCommandLists = false; pCapabilities->SupportsMultithreadedResourceCreation = true; pCapabilities->SupportsDrawBaseVertex = true; pCapabilities->SupportsDepthTextures = true; pCapabilities->SupportsTextureArrays = (m_featureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsCubeMapTextureArrays = (m_featureLevel >= D3D_FEATURE_LEVEL_10_1); pCapabilities->SupportsGeometryShaders = (m_featureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsSinglePassCubeMaps = (m_featureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsInstancing = (m_featureLevel >= D3D_FEATURE_LEVEL_10_0); } bool D3D11GPUDevice::CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat /*= NULL*/) const { DXGI_FORMAT DXGIFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(PixelFormat); if (DXGIFormat == DXGI_FORMAT_UNKNOWN) { // use r8g8b8a8 if (CompatibleFormat != NULL) *CompatibleFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; return false; } if (CompatibleFormat != NULL) *CompatibleFormat = PixelFormat; return true; } void D3D11GPUDevice::CorrectProjectionMatrix(float4x4 &projectionMatrix) const { } float D3D11GPUDevice::GetTexelOffset() const { return 0.0f; } void D3D11GPUDevice::BeginResourceBatchUpload() { } void D3D11GPUDevice::EndResourceBatchUpload() { } D3D11SamplerState::D3D11SamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, ID3D11SamplerState *pD3DSamplerState) : GPUSamplerState(pSamplerStateDesc), m_pD3DSamplerState(pD3DSamplerState) { } D3D11SamplerState::~D3D11SamplerState() { m_pD3DSamplerState->Release(); } void D3D11SamplerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11SamplerState); // approximation if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11SamplerState::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DSamplerState, name); } GPUSamplerState *D3D11GPUDevice::CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { ID3D11SamplerState *pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc); if (pD3DSamplerState == NULL) return NULL; D3D11SamplerState *pSamplerState = new D3D11SamplerState(pSamplerStateDesc, pD3DSamplerState); return pSamplerState; } D3D11RasterizerState::D3D11RasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc, ID3D11RasterizerState *pD3DRasterizerState) : GPURasterizerState(pRasterizerStateDesc), m_pD3DRasterizerState(pD3DRasterizerState) { } D3D11RasterizerState::~D3D11RasterizerState() { m_pD3DRasterizerState->Release(); } void D3D11RasterizerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11RasterizerState); // approximation if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11RasterizerState::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DRasterizerState, name); } GPURasterizerState *D3D11GPUDevice::CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) { ID3D11RasterizerState *pD3DRasterizerState = D3D11Helpers::CreateD3D11RasterizerState(m_pD3DDevice, pRasterizerStateDesc); if (pD3DRasterizerState == NULL) return NULL; D3D11RasterizerState *pRasterizerState = new D3D11RasterizerState(pRasterizerStateDesc, pD3DRasterizerState); return pRasterizerState; } D3D11DepthStencilState::D3D11DepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc, ID3D11DepthStencilState *pD3DDepthStencilState) : GPUDepthStencilState(pDepthStencilStateDesc), m_pD3DDepthStencilState(pD3DDepthStencilState) { } D3D11DepthStencilState::~D3D11DepthStencilState() { m_pD3DDepthStencilState->Release(); } void D3D11DepthStencilState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11DepthStencilState); // approximation if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11DepthStencilState::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DDepthStencilState, name); } GPUDepthStencilState *D3D11GPUDevice::CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) { ID3D11DepthStencilState *pD3DDepthStencilState = D3D11Helpers::CreateD3D11DepthStencilState(m_pD3DDevice, pDepthStencilStateDesc); if (pD3DDepthStencilState == NULL) return NULL; D3D11DepthStencilState *pDepthStencilState = new D3D11DepthStencilState(pDepthStencilStateDesc, pD3DDepthStencilState); return pDepthStencilState; } D3D11BlendState::D3D11BlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc, ID3D11BlendState *pD3DBlendState) : GPUBlendState(pBlendStateDesc), m_pD3DBlendState(pD3DBlendState) { } D3D11BlendState::~D3D11BlendState() { m_pD3DBlendState->Release(); } void D3D11BlendState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11BlendState); // approximation if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11BlendState::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DBlendState, name); } GPUBlendState *D3D11GPUDevice::CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) { ID3D11BlendState *pD3DBlendState = D3D11Helpers::CreateD3D11BlendState(m_pD3DDevice, pBlendStateDesc); if (pD3DBlendState == NULL) return NULL; D3D11BlendState *pBlendState = new D3D11BlendState(pBlendStateDesc, pD3DBlendState); return pBlendState; } <file_sep>/Engine/Source/Core/ChunkFileReader.h #pragma once #include "Core/Common.h" class ByteStream; // Uses the standard chunk header format to create a straightforward way to load chunked files. // Only one chunk can be loaded at a time. To avoid memory fragmentation, the size of the largest chunk // will be found on initialization, and a memory block of this size will be allocated. This will be // used for further chunk loading. class ChunkFileReader { public: ChunkFileReader(); ~ChunkFileReader(); bool Initialize(ByteStream *pStream); bool InitializeFromMemory(const byte *pData, uint32 DataSize, bool RequiresOwnCopy); void Close(); // Gets the total size of the file, including chunk headers. uint64 GetTotalSize() const; // Retrieve chunk size. uint32 GetChunkSize(uint32 ChunkIndex) const; // Loads the requested chunk as the current chunk. bool LoadChunk(uint32 ChunkIndex); // Get the currently loaded chunk as a pointer. const byte *GetCurrentChunkPointer() const; uint32 GetCurrentChunkSize() const; // Templated version of the above. template<typename T> const T *GetCurrentChunkTypePointer() const { return (const T *)GetCurrentChunkPointer(); } template<typename T> uint32 GetCurrentChunkTypeCount() const { return (uint32)GetCurrentChunkSize() / sizeof(T); } template<typename T> bool CurrentChunkHasValidCountOfType() const { return (GetCurrentChunkSize() % sizeof(T)) == 0; } template<typename T> bool LoadTypedChunk(uint32 ChunkIndex, const T **pTypePtr, uint32 *pTypeCount) { if (!LoadChunk(ChunkIndex) || GetCurrentChunkTypeCount<T>() == 0 || !CurrentChunkHasValidCountOfType<T>()) return false; *pTypePtr = GetCurrentChunkTypePointer<T>(); *pTypeCount = GetCurrentChunkTypeCount<T>(); return true; } uint32 GetStringCount() const; const char *GetStringByIndex(uint32 StringIndex) const; private: struct Chunk { uint64 Offset; uint32 Size; }; void Reset(); bool InternalInitialize(); bool LoadStrings(uint32 stringDataSize, uint32 expectedStringCount); ByteStream *m_pStream; bool m_bOwnsStream; uint64 m_iBaseOffset; uint64 m_iTotalSize; Chunk *m_pChunks; uint32 m_nChunks; uint32 m_uMaximumChunkSize; uint32 m_iStringCount; char *m_pStringData; const char **m_pStringPointers; byte *m_pChunkData; uint32 m_uCurrentChunkSize; }; <file_sep>/Engine/Source/MathLib/SIMDMatrixf_scalar.h #include "MathLib/Matrixf.h" #include "MathLib/SIMDVectorf.h" struct Matrix2x2f; struct Matrix3x3f; struct Matrix3x4f; struct Matrix4x4f; struct SIMDMatrix3x3f : public Matrix3x3f { SIMDMatrix3x3f() {} // set everything at once SIMDMatrix3x3f(const float E00, const float E01, const float E02, const float E10, const float E11, const float E12, const float E20, const float E21, const float E22) : Matrix3x3f(E00, E01, E02, E10, E11, E12, E20, E21, E22) {} // sets the diagonal to the specified value (1 == identity) SIMDMatrix3x3f(const float Diagonal) : Matrix3x3f(Diagonal) {} // assumes row-major packing order with vectors in columns SIMDMatrix3x3f(const float *p) : Matrix3x3f(p) {} // copy SIMDMatrix3x3f(const SIMDMatrix3x3f &v) : Matrix3x3f(v) {} // downscaling/from floatx SIMDMatrix3x3f(const Matrix3x3f &v) : Matrix3x3f(v) {} // row/field accessors const float operator()(uint32 i, uint32 j) const { return Matrix3x3f::operator()(i, j); } float &operator()(uint32 i, uint32 j) { return Matrix3x3f::operator()(i, j); } // assignment operators SIMDMatrix3x3f &operator=(const SIMDMatrix3x3f &v) { Matrix3x3f::operator=(v); return *this; } SIMDMatrix3x3f &operator=(const float Diagonal) { Matrix3x3f::operator=(Diagonal); return *this; } SIMDMatrix3x3f &operator=(const float *p) { Matrix3x3f::operator=(p); return *this; } SIMDMatrix3x3f &operator=(const Matrix3x3f &v) { Matrix3x3f::operator=(v); return *this; } // various operators SIMDMatrix3x3f &operator*=(const SIMDMatrix3x3f &v) { Matrix3x3f::operator*=(v); return *this; } SIMDMatrix3x3f &operator*=(const float v) { Matrix3x3f::operator*=(v); return *this; } SIMDMatrix3x3f operator*(const SIMDMatrix3x3f &v) const { return Matrix3x3f::operator*(v); } SIMDMatrix3x3f operator*(float v) const { return Matrix3x3f::operator*(v); } SIMDMatrix3x3f operator-() const { return Matrix3x3f::operator-(); } // matrix * vector SIMDVector3f operator*(const SIMDVector3f &v) const { return Matrix3x3f::operator*(v); } // constants static const SIMDMatrix3x3f &Zero, &Identity; }; struct SIMDMatrix4x4f : public Matrix4x4f { SIMDMatrix4x4f() {} // set everything at once SIMDMatrix4x4f(const float E00, const float E01, const float E02, const float E03, const float E10, const float E11, const float E12, const float E13, const float E20, const float E21, const float E22, const float E23, const float E30, const float E31, const float E32, const float E33) : Matrix4x4f(E00, E01, E02, E03, E10, E11, E12, E13, E20, E21, E22, E23, E30, E31, E32, E33) {} // sets the diagonal to the specified value (1 == identity) SIMDMatrix4x4f(const float Diagonal) : Matrix4x4f(Diagonal) {} // assumes row-major packing order with vectors in columns SIMDMatrix4x4f(const float *p) : Matrix4x4f(p) {} // copy SIMDMatrix4x4f(const SIMDMatrix4x4f &v) : Matrix4x4f(v) {} // downscaling/from floatx SIMDMatrix4x4f(const Matrix4x4f &v) : Matrix4x4f(v) {} // row/field accessors const float operator()(uint32 i, uint32 j) const { return Matrix4x4f::operator()(i, j); } float &operator()(uint32 i, uint32 j) { return Matrix4x4f::operator()(i, j); } // assignment operators SIMDMatrix4x4f &operator=(const SIMDMatrix4x4f &v) { Matrix4x4f::operator=(v); return *this; } SIMDMatrix4x4f &operator=(const float Diagonal) { Matrix4x4f::operator=(Diagonal); return *this; } SIMDMatrix4x4f &operator=(const float *p) { Matrix4x4f::operator=(p); return *this; } SIMDMatrix4x4f &operator=(const Matrix4x4f &v) { Matrix4x4f::operator=(v); return *this; } // various operators SIMDMatrix4x4f &operator*=(const SIMDMatrix4x4f &v) { Matrix4x4f::operator*=(v); return *this; } SIMDMatrix4x4f &operator*=(const float v) { Matrix4x4f::operator*=(v); return *this; } SIMDMatrix4x4f operator*(const SIMDMatrix4x4f &v) const { return Matrix4x4f::operator*(v); } SIMDMatrix4x4f operator*(float v) const { return Matrix4x4f::operator*(v); } SIMDMatrix4x4f operator-() const { return Matrix4x4f::operator-(); } // matrix * vector SIMDVector4f operator*(const SIMDVector4f &v) const { return Matrix4x4f::operator*(v); } // constants static const SIMDMatrix4x4f &Zero, &Identity; }; <file_sep>/Engine/Source/MapCompilerStandalone/MapCompiler.cpp #include "Common.h" #include "MapCompiler/MapCompiler.h" #include "Engine/Engine.h" Log_SetChannel(MapCompiler); enum MAP_COMPILER_STAGE { MAP_COMPILER_STAGE_REGIONS, MAP_COMPILER_STAGE_TERRAIN, MAP_COMPILER_STAGE_BLOCK_TERRAIN, MAP_COMPILER_STAGE_COUNT, }; static String s_inputFileName; static String s_outputFileName; static uint32 s_overrideLODLevels; static uint32 s_overrideLoadRadius; static uint32 s_overrideActivationRadius; struct BuildOperation { enum OpType { OpType_GlobalEntities, OpType_Region, OpType_Entities, OpType_Terrain, OpType_Count, }; BuildOperation(OpType type, int32 regionX, int32 regionY) : Type(type), RegionX(regionX), RegionY(regionY) {} OpType Type; int32 RegionX; int32 RegionY; }; static MemArray<BuildOperation> s_buildOperations; static bool ParseRegionCoordinates(const char *coordStr, int32 *pRegionX, int32 *pRegionY) { uint32 coordStrLength = Y_strlen(coordStr); char *tempString = (char *)alloca(coordStrLength + 1); uint32 tempStringLength = 0; uint32 stringPosition = 0; uint32 coordIndex = 0; for (; stringPosition < coordStrLength; stringPosition++) { if (coordStr[stringPosition] == ',') { if (tempStringLength == 0) return false; tempString[tempStringLength] = 0; *pRegionX = StringConverter::StringToInt32(tempString); tempStringLength = 0; coordIndex++; continue; } tempString[tempStringLength++] = coordStr[stringPosition]; } if (coordIndex == 0) return false; tempString[tempStringLength] = 0; *pRegionY = StringConverter::StringToInt32(tempString); return true; } static bool ParseArguments(int argc, char **argv) { #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) // first argument should always be the map name if (argc < 1) { Log_ErrorPrintf("Missing map file name"); return false; } // read map name s_inputFileName = argv[0]; if (!s_inputFileName.EndsWith(".map", false)) { Log_ErrorPrintf("Invalid map file name: '%s' (should end in .map)", s_inputFileName.GetCharArray()); return false; } // build output map name s_outputFileName = s_inputFileName.SubString(0, s_inputFileName.GetLength() - 4); s_outputFileName.AppendString(".cmap"); // fix for os FileSystem::BuildOSPath(s_inputFileName); FileSystem::BuildOSPath(s_outputFileName); // parse parameters for (int i = 1; i < argc; ) { if (CHECK_ARG_PARAM("-OverrideLODLevels")) { s_overrideLODLevels = StringConverter::StringToUInt32(argv[++i]); if (s_overrideLODLevels == 0 || s_overrideLODLevels > 16) { Log_ErrorPrintf("Invalid override lod levels: %u", s_overrideLODLevels); return false; } } else if (CHECK_ARG_PARAM("-OverrideLoadRadius")) { s_overrideLoadRadius = StringConverter::StringToUInt32(argv[++i]); if (s_overrideLoadRadius == 0 || s_overrideLoadRadius > 16) { Log_ErrorPrintf("Invalid override load radius: %u", s_overrideLoadRadius); return false; } } else if (CHECK_ARG_PARAM("-OverrideActivationRadius")) { s_overrideActivationRadius = StringConverter::StringToUInt32(argv[++i]); if (s_overrideActivationRadius == 0 || s_overrideActivationRadius > 16) { Log_ErrorPrintf("Invalid override activation radius: %u", s_overrideActivationRadius); return false; } } else if (CHECK_ARG("-GlobalEntities")) { BuildOperation op(BuildOperation::OpType_Region, 0, 0); s_buildOperations.Add(op); } else if (CHECK_ARG_PARAM("-BuildRegion")) { BuildOperation op(BuildOperation::OpType_Region, 0, 0); if (!ParseRegionCoordinates(argv[++i], &op.RegionX, &op.RegionY)) { Log_ErrorPrintf("Invalid region coordinates: '%s'", argv[i]); return false; } s_buildOperations.Add(op); } else if (CHECK_ARG_PARAM("-BuildRegionTerrain")) { BuildOperation op(BuildOperation::OpType_Terrain, 0, 0); if (!ParseRegionCoordinates(argv[++i], &op.RegionX, &op.RegionY)) { Log_ErrorPrintf("Invalid region coordinates: '%s'", argv[i]); return false; } s_buildOperations.Add(op); } else { Log_ErrorPrintf("Invalid option: %s", argv[i]); return false; } i++; } #undef CHECK_ARG #undef CHECK_ARG_PARAM return true; } int RunMapCompiler(int argc, char **argv) { MapSource *pMapSource = nullptr; MapCompiler *pMapCompiler = nullptr; ByteStream *pReadStream = nullptr; ByteStream *pWriteStream = nullptr; int exitCode = 0; Log::GetInstance().SetConsoleOutputParams(true); Log::GetInstance().SetDebugOutputParams(true); // Clear all stages. if (!ParseArguments(argc, argv)) { Log_ErrorPrintf("Invalid command line arguments."); return false; } // Check input filename. Log_InfoPrintf("Map source file name: %s", s_inputFileName.GetCharArray()); Log_InfoPrintf("Compiled map file name: %s", s_outputFileName.GetCharArray()); // All stages require reading of the map file. { Log_InfoPrint("=============================== Reading Map File =============================="); ConsoleProgressCallbacks progressCallbacks; pMapSource = new MapSource(); if (!pMapSource->Load(s_inputFileName, &progressCallbacks)) { Log_ErrorPrintf("Failed to load map file '%s'", s_inputFileName.GetCharArray()); exitCode = 1; goto CLEANUP_ERROR; } } // Create compiler pMapCompiler = new MapCompiler(pMapSource); // Check if the map file exists if (s_buildOperations.GetSize() > 0 && g_pVirtualFileSystem->FileExists(s_outputFileName)) { Log_InfoPrint("================================ Reading Compiled Map ===================================="); pReadStream = FileSystem::OpenFile(s_outputFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pReadStream == nullptr) { Log_ErrorPrintf("Failed to open compiled map file '%s' for reading", s_outputFileName.GetCharArray()); exitCode = 2; goto CLEANUP_ERROR; } pWriteStream = FileSystem::OpenFile(s_outputFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE | BYTESTREAM_OPEN_SEEKABLE); if (pWriteStream == nullptr) { Log_ErrorPrintf("Failed to open compiled map file '%s' for writing", s_outputFileName.GetCharArray()); exitCode = 2; goto CLEANUP_ERROR; } // init compiler ConsoleProgressCallbacks progressCallbacks; if (!pMapCompiler->StartReuseCompile(pReadStream, pWriteStream, &progressCallbacks)) { Log_ErrorPrintf("Failed to start reuse compile for map file '%s'", s_outputFileName.GetCharArray()); exitCode = 2; goto CLEANUP_ERROR; } } else { Log_InfoPrint("================================ Creating Compiled Map ===================================="); // open file for writing pWriteStream = FileSystem::OpenFile(s_outputFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE | BYTESTREAM_OPEN_SEEKABLE); if (pWriteStream == nullptr) { Log_ErrorPrintf("Failed to open compiled map file '%s' for writing", s_outputFileName.GetCharArray()); exitCode = 2; goto CLEANUP_ERROR; } // init compiler ConsoleProgressCallbacks progressCallbacks; if (!pMapCompiler->StartFreshCompile(pWriteStream, &progressCallbacks)) { Log_ErrorPrintf("Failed to start fresh compile for map file '%s'", s_outputFileName.GetCharArray()); exitCode = 2; goto CLEANUP_ERROR; } // set override lods if (s_overrideLODLevels != 0) { Log_WarningPrintf("Overriding LOD levels: %u. This may take a while.", s_overrideLODLevels); pMapCompiler->SetOverrideRegionLODLevels(s_overrideLODLevels); } if (s_overrideLoadRadius != 0) { Log_WarningPrintf("Overriding region load radius: %u.", s_overrideLoadRadius); pMapCompiler->SetOverrideRegionLoadRadius(s_overrideLoadRadius); } if (s_overrideActivationRadius != 0) { Log_WarningPrintf("Overriding region activation radius: %u.", s_overrideActivationRadius); pMapCompiler->SetOverrideRegionActivationRadius(s_overrideActivationRadius); } } { Log_InfoPrint("============================= Compiling ================================"); ConsoleProgressCallbacks progressCallbacks; if (s_buildOperations.GetSize() > 0) { // issue operations for (uint32 i = 0; i < s_buildOperations.GetSize(); i++) { const BuildOperation &op = s_buildOperations[i]; if (op.Type == BuildOperation::OpType_GlobalEntities) { Log_InfoPrintf("Building global entities..."); if (!pMapCompiler->BuildGlobalEntities(&progressCallbacks)) { Log_ErrorPrintf("Build global entities failed."); exitCode = 3; goto CLEANUP_ERROR; } } else if (op.Type == BuildOperation::OpType_Region) { Log_InfoPrintf("Building region [%i, %i]...", op.RegionX, op.RegionY); if (!pMapCompiler->BuildRegion(op.RegionX, op.RegionY, &progressCallbacks)) { Log_ErrorPrintf("Build region [%i, %i] failed.", op.RegionX, op.RegionY); exitCode = 3; goto CLEANUP_ERROR; } } else if (op.Type == BuildOperation::OpType_Entities) { Log_InfoPrintf("Building region [%i, %i] entities...", op.RegionX, op.RegionY); if (!pMapCompiler->BuildRegionEntities(op.RegionX, op.RegionY, &progressCallbacks)) { Log_ErrorPrintf("Build region [%i, %i] entities failed.", op.RegionX, op.RegionY); exitCode = 3; goto CLEANUP_ERROR; } } else if (op.Type == BuildOperation::OpType_Terrain) { Log_InfoPrintf("Building region [%i, %i] terrain...", op.RegionX, op.RegionY); if (!pMapCompiler->BuildRegionTerrain(op.RegionX, op.RegionY, &progressCallbacks)) { Log_ErrorPrintf("Build region [%i, %i] terrain failed.", op.RegionX, op.RegionY); exitCode = 3; goto CLEANUP_ERROR; } } } } else { // build the whole thing if (!pMapCompiler->BuildAll(-1, &progressCallbacks)) { Log_ErrorPrintf("Build all failed."); exitCode = 3; goto CLEANUP_ERROR; } } } { Log_InfoPrint("============================= Finalizing ======================================"); ConsoleProgressCallbacks progressCallbacks; if (!pMapCompiler->FinalizeCompile(&progressCallbacks)) { Log_ErrorPrintf("Failed to run finalize."); exitCode = 4; goto CLEANUP_ERROR; } } // commit to destination Log_InfoPrint("=========================== Cleaning up ======================================="); delete pMapCompiler; delete pMapSource; if (pReadStream != nullptr) pReadStream->Release(); if (!pWriteStream->Commit()) { pWriteStream->Release(); Log_WarningPrintf("Failed to commit output file"); exitCode = 5; goto END; } pWriteStream->Release(); goto END; CLEANUP_ERROR: Log_InfoPrint("=========================== Cleaning up ======================================="); if (pMapCompiler != nullptr) { pMapCompiler->DiscardCompile(); delete pMapCompiler; } delete pMapSource; if (pWriteStream != nullptr) { pWriteStream->Discard(); pWriteStream->Release(); } if (pReadStream != nullptr) pReadStream->Release(); goto END; END: if (exitCode == 0) Log_InfoPrint("Exiting with success."); else Log_ErrorPrintf("Exiting with error code %d.", exitCode); return exitCode; } int main(int argc, char *argv[]) { // set log flags g_pLog->SetConsoleOutputParams(true); g_pLog->SetDebugOutputParams(true); // parse command line uint32 argsStart = g_pConsole->ParseCommandLine(argc, (const char **)argv); // adjust pointers int newArgc = argc - argsStart; char **newArgv = argv + argsStart; // initialize VFS if (!g_pVirtualFileSystem->Initialize()) { Log_ErrorPrintf("VFS startup failed. Cannot continue."); return false; } // initialize engine if (!g_pEngine->Startup()) { Log_ErrorPrintf("Engine startup failed. Cannot continue."); g_pVirtualFileSystem->Shutdown(); return false; } // register types g_pEngine->RegisterEngineTypes(); // run modules int returnCode = RunMapCompiler(newArgc, newArgv); // shutdown everything g_pEngine->Shutdown(); g_pEngine->UnregisterTypes(); g_pVirtualFileSystem->Shutdown(); return returnCode; } <file_sep>/Engine/Source/ContentConverter/AssimpSkeletalMeshImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiNode; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class SkeletalMeshGenerator; class AssimpSkeletalMeshImporter : public BaseImporter { public: struct Options { String SourcePath; String OutputResourceName; String SkeletonName; bool ImportMaterials; String MaterialDirectory; String MaterialPrefix; String DefaultMaterialName; COORDINATE_SYSTEM CoordinateSystem; bool FlipFaceOrder; String CollisionShapeType; }; public: AssimpSkeletalMeshImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpSkeletalMeshImporter(); static void SetDefaultOptions(Options *pOptions); bool Execute(); private: bool LoadScene(); bool CreateGenerator(); bool CreateMaterials(); bool CreateMesh(); bool ParseNode(const aiNode *pNode); bool PostProcess(); bool CreateCollisionShape(); bool WriteOutput(); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; String m_baseOutputPath; PODArray<uint32> m_materialMapping; SkeletalMeshGenerator *m_pOutputGenerator; }; <file_sep>/DemoGame/Source/DemoGame/BaseDemoGameState.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/BaseDemoGameState.h" #include "Engine/Engine.h" #include "Engine/EngineCVars.h" #include "Engine/InputManager.h" #include "Engine/DynamicWorld.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(BaseDemoGameState); BaseDemoGameState::BaseDemoGameState(DemoGame *pDemoGame) : m_pDemoGame(pDemoGame) , m_uiActive(true) { } BaseDemoGameState::~BaseDemoGameState() { } bool BaseDemoGameState::Initialize() { bool result = false; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, &result]() { result = CreateGPUResources(); }); if (!result) return false; // get window width/height //uint32 windowWidth = m_pDemoGame->GetOutputWindow()->GetWidth(); //uint32 windowHeight = m_pDemoGame->GetOutputWindow()->GetHeight(); return true; } void BaseDemoGameState::Shutdown() { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this]() { ReleaseGPUResources(); }); } bool BaseDemoGameState::CreateGPUResources() { return true; } void BaseDemoGameState::ReleaseGPUResources() { } void BaseDemoGameState::DrawOverlays(float deltaTime) { if (m_uiActive) DrawUI(deltaTime); } void BaseDemoGameState::DrawUI(float deltaTime) { uint32 windowWidth = m_pDemoGame->GetOutputWindow()->GetWidth(); //uint32 windowHeight = m_pDemoGame->GetOutputWindow()->GetHeight(); ImGui::SetNextWindowPos(ImVec2(float(windowWidth - 125), 110)); ImGui::SetNextWindowSize(ImVec2(115, 110)); if (ImGui::Begin("Demo Controls", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { if (ImGui::Button("Toggle UI", ImVec2(100, 20))) { // call on main thread QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { ToggleUI(); }); } if (ImGui::Button("Render Debug", ImVec2(100, 20))) { // call on main thread QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { m_pDemoGame->OpenDebugRenderMenu(); }); } if (ImGui::Button("Exit Demo", ImVec2(100, 20))) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { m_pDemoGame->EndModalGameState(); }); } } ImGui::End(); // light options? } void BaseDemoGameState::OnSwitchedIn() { if (m_uiActive) m_pDemoGame->ActivateImGui(); } void BaseDemoGameState::OnSwitchedOut() { if (m_uiActive) m_pDemoGame->DeactivateImGui(); } void BaseDemoGameState::OnBeforeDelete() { } void BaseDemoGameState::OnWindowResized(uint32 width, uint32 height) { } void BaseDemoGameState::OnWindowFocusGained() { } void BaseDemoGameState::OnWindowFocusLost() { } void BaseDemoGameState::ToggleUI() { //DebugAssert(!Renderer::IsOnRenderThread()); @TODO IsOnMainThread if (m_uiActive) { m_pDemoGame->DeactivateImGui(); m_uiActive = false; OnUIToggled(false); } else { OnUIToggled(true); m_pDemoGame->ActivateImGui(); m_uiActive = true; } } void BaseDemoGameState::OnUIToggled(bool enabled) { } bool BaseDemoGameState::OnWindowEvent(const union SDL_Event *event) { if (!m_pDemoGame->IsImGuiActivated()) { if (event->type == SDL_KEYUP && event->key.keysym.sym == SDLK_ESCAPE) { ToggleUI(); return true; } } return false; } void BaseDemoGameState::OnMainThreadPreFrame(float deltaTime) { } void BaseDemoGameState::OnMainThreadBeginFrame(float deltaTime) { } void BaseDemoGameState::OnMainThreadAsyncTick(float deltaTime) { } void BaseDemoGameState::OnMainThreadTick(float deltaTime) { } void BaseDemoGameState::OnMainThreadEndFrame(float deltaTime) { } void BaseDemoGameState::OnRenderThreadPreFrame(float deltaTime) { } void BaseDemoGameState::OnRenderThreadBeginFrame(float deltaTime) { } void BaseDemoGameState::OnRenderThreadDraw(float deltaTime) { // most will override this // draw overlays m_pDemoGame->GetGUIContext()->PushManualFlush(); DrawOverlays(deltaTime); m_pDemoGame->GetGUIContext()->PopManualFlush(); } void BaseDemoGameState::OnRenderThreadEndFrame(float deltaTime) { } <file_sep>/Editor/Source/Editor/ui_EditorProgressDialog.h /******************************************************************************** ** Form generated from reading UI file 'EditorProgressDialog.ui' ** ** Created by: Qt User Interface Compiler version 5.4.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_EDITORPROGRESSDIALOG_H #define UI_EDITORPROGRESSDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QProgressBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_EditorProgressDialog { public: QGroupBox *m_statusGroupBox; QLabel *m_status; QProgressBar *m_progressBar; QWidget *horizontalLayoutWidget; QHBoxLayout *horizontalLayout; QSpacerItem *horizontalSpacer; QPushButton *m_cancelButton; void setupUi(QDialog *EditorProgressDialog) { if (EditorProgressDialog->objectName().isEmpty()) EditorProgressDialog->setObjectName(QStringLiteral("EditorProgressDialog")); EditorProgressDialog->resize(660, 170); EditorProgressDialog->setModal(true); m_statusGroupBox = new QGroupBox(EditorProgressDialog); m_statusGroupBox->setObjectName(QStringLiteral("m_statusGroupBox")); m_statusGroupBox->setGeometry(QRect(10, 10, 641, 71)); m_status = new QLabel(m_statusGroupBox); m_status->setObjectName(QStringLiteral("m_status")); m_status->setGeometry(QRect(10, 20, 621, 41)); m_status->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop); m_progressBar = new QProgressBar(EditorProgressDialog); m_progressBar->setObjectName(QStringLiteral("m_progressBar")); m_progressBar->setGeometry(QRect(10, 90, 641, 31)); m_progressBar->setValue(24); horizontalLayoutWidget = new QWidget(EditorProgressDialog); horizontalLayoutWidget->setObjectName(QStringLiteral("horizontalLayoutWidget")); horizontalLayoutWidget->setGeometry(QRect(10, 130, 641, 31)); horizontalLayout = new QHBoxLayout(horizontalLayoutWidget); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); m_cancelButton = new QPushButton(horizontalLayoutWidget); m_cancelButton->setObjectName(QStringLiteral("m_cancelButton")); horizontalLayout->addWidget(m_cancelButton); retranslateUi(EditorProgressDialog); QMetaObject::connectSlotsByName(EditorProgressDialog); } // setupUi void retranslateUi(QDialog *EditorProgressDialog) { EditorProgressDialog->setWindowTitle(QApplication::translate("EditorProgressDialog", "Action In Progress...", 0)); m_statusGroupBox->setTitle(QApplication::translate("EditorProgressDialog", "Status", 0)); m_status->setText(QApplication::translate("EditorProgressDialog", "Current Status", 0)); m_cancelButton->setText(QApplication::translate("EditorProgressDialog", "Cancel", 0)); } // retranslateUi }; namespace Ui { class EditorProgressDialog: public Ui_EditorProgressDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_EDITORPROGRESSDIALOG_H <file_sep>/Engine/Source/Renderer/WorldRenderers/SSMShadowMapRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" #include "Renderer/Shaders/ShadowMapShader.h" #include "Renderer/ShaderProgram.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderQueue.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgramSelector.h" #include "Engine/Camera.h" #include "Engine/Material.h" #include "Engine/Profiling.h" Log_SetChannel(SSMShadowMapRenderer); SSMShadowMapRenderer::SSMShadowMapRenderer(uint32 shadowMapResolution /* = 256 */, PIXEL_FORMAT shadowMapFormat /* = PIXEL_FORMAT_D16_UNORM */) : m_shadowMapResolution(shadowMapResolution), m_shadowMapFormat(shadowMapFormat) { m_renderQueue.SetAcceptingLights(false); m_renderQueue.SetAcceptingRenderPassMask(RENDER_PASS_SHADOW_MAP); m_renderQueue.SetAcceptingOccluders(false); m_renderQueue.SetAcceptingDebugObjects(false); } SSMShadowMapRenderer::~SSMShadowMapRenderer() { } bool SSMShadowMapRenderer::AllocateShadowMap(ShadowMapData *pShadowMapData) { // store vars pShadowMapData->IsActive = false; // allocate texture GPU_TEXTURE2D_DESC textureDesc(m_shadowMapResolution, m_shadowMapResolution, m_shadowMapFormat, GPU_TEXTURE_FLAG_SHADER_BINDABLE | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_CLAMP, float4::One, 0, 0, 0, 0, GPU_COMPARISON_FUNC_NEVER); //samplerStateDesc.Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; //samplerStateDesc.ComparisonFunc = RENDERER_COMPARISON_FUNC_LESS_EQUAL; Log_PerfPrintf("SSMShadowMapRenderer::AllocateShadowMap: Creating new %u x %u %s texture", m_shadowMapResolution, m_shadowMapResolution, NameTable_GetNameString(NameTables::PixelFormat, m_shadowMapFormat)); pShadowMapData->pShadowMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc); if (pShadowMapData->pShadowMapTexture == nullptr) return false; GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC dsvDesc(pShadowMapData->pShadowMapTexture, 0); pShadowMapData->pShadowMapDSV = g_pRenderer->CreateDepthStencilBufferView(pShadowMapData->pShadowMapTexture, &dsvDesc); if (pShadowMapData->pShadowMapDSV == nullptr) { pShadowMapData->pShadowMapTexture->Release(); pShadowMapData->pShadowMapTexture = nullptr; return false; } // ok return true; } void SSMShadowMapRenderer::FreeShadowMap(ShadowMapData *pShadowMapData) { pShadowMapData->pShadowMapDSV->Release(); pShadowMapData->pShadowMapTexture->Release(); } static void BuildDirectionalLightCamera(Camera *pShadowCamera, const Camera *pViewCamera, const float3 &lightDirection, float shadowDistance) { const float extraBackup = 20.0f; const float nearClip = 1.0f; // // calc camera up vector // Vector3 lightCameraUpVector; // float lightDirectionDotWorldUp = lightDirection.Dot(float3::UnitZ); // if (lightDirectionDotWorldUp > 0.5f) // lightCameraUpVector = float3::NegativeUnitY; // else if (lightDirectionDotWorldUp < -0.5f) // lightCameraUpVector = float3::UnitY; // else // lightCameraUpVector = float3::UnitZ; //Log_DevPrintf("dir = %s, dotz = %s", StringConverter::Float3ToString(lightDirection).GetCharArray(), StringConverter::FloatToString(lightDirection.Dot(float3::UnitZ)).GetCharArray()); // convert the direction to a rotation from the default direction Quaternion cameraRotation(Quaternion::FromTwoUnitVectors(float3::NegativeUnitZ, lightDirection)); // since our camera normally points down the y axis, rotate it so the default is pointing downwards cameraRotation *= Quaternion::FromEulerAngles(-90.0f, 0.0f, 0.0f); cameraRotation.NormalizeInPlace(); #if 0 // create light aabb in view-space AABox lightViewAABB(float3(-shadowDistance, -shadowDistance, -shadowDistance), float3(shadowDistance, shadowDistance, shadowDistance)); lightViewAABB.ApplyTransform(pViewCamera->GetViewMatrix()); // rotate into light space lightViewAABB.ApplyTransform(cameraRotation.GetFloat3x3()); // calculate the light position float lightDepth = lightViewAABB.GetMaxBounds().z - lightViewAABB.GetMinBounds().z; float3 lightPositionWS(Camera::TransformFromCameraToWorldCoordinateSystem(lightViewAABB.GetCenter())); lightPositionWS += lightDirection * (-lightDepth / 2.0f); // set the window pShadowCamera->SetPosition(lightPositionWS); pShadowCamera->SetRotation(cameraRotation); pShadowCamera->SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); pShadowCamera->SetOrthographicWindow(lightViewAABB.GetMaxBounds().x - lightViewAABB.GetMinBounds().x, lightViewAABB.GetMaxBounds().y - lightViewAABB.GetMinBounds().y); pShadowCamera->SetNearFarPlaneDistances(1.0f, lightDepth); #else // create camera Camera tempCamera(*pViewCamera); tempCamera.SetNearFarPlaneDistances(1.0f, shadowDistance); Sphere frustumBoundingSphere(tempCamera.GetFrustum().GetBoundingSphere()); float backupDist = extraBackup + nearClip + frustumBoundingSphere.GetRadius(); //float windowSize = frustumBoundingSphere.GetRadius() * 2.0f; float windowSize = frustumBoundingSphere.GetRadius(); pShadowCamera->SetPosition(float3(frustumBoundingSphere.GetCenter()) - (lightDirection * backupDist)); //pShadowCamera->LookDirection(lightDirection, lightCameraUpVector); pShadowCamera->SetRotation(cameraRotation); pShadowCamera->SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); pShadowCamera->SetOrthographicWindow(windowSize, windowSize); pShadowCamera->SetNearPlaneDistance(nearClip); pShadowCamera->SetFarPlaneDistance((backupDist + (frustumBoundingSphere.GetRadius() * 2.0f))); #endif pShadowCamera->SetObjectCullDistance(shadowDistance); //pShadowCamera->SetPosition(float3(250, 250, 500.0f)); //pShadowCamera->SetOrthographicWindow(1000, 1000); //lightCamera.SetPosition(float3(0, 0, 500.0f)); //lightCamera.SetWindowSize(1000, 1000); //pShadowCamera->SetFarPlaneDistance(1.0f); //pShadowCamera->SetFarPlaneDistance(500.0f); //pShadowCamera->SetFarPlaneDistance(1000.0f); //pShadowCamera->SetFarPlaneDistance(8000.0f); } void SSMShadowMapRenderer::DrawDirectionalShadowMap(GPUContext *pGPUContext, ShadowMapData *pShadowMapData, const RenderWorld *pRenderWorld, const Camera *pViewCamera, float shadowDistance, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { MICROPROFILE_SCOPEI("SSMShadowMapRenderer", "DrawDirectionalShadowMap", MICROPROFILE_COLOR(200, 0, 0)); // fix shadow distance shadowDistance = Min(shadowDistance, pViewCamera->GetFarPlaneDistance() - pViewCamera->GetNearPlaneDistance()); // build base view parameters Camera lightCamera; BuildDirectionalLightCamera(&lightCamera, pViewCamera, pLight->Direction, shadowDistance); // build viewport RENDERER_VIEWPORT shadowMapViewport(0, 0, m_shadowMapResolution, m_shadowMapResolution, 0.0f, 1.0f); // set and clear the shadow map pGPUContext->SetRenderTargets(0, nullptr, pShadowMapData->pShadowMapDSV); pGPUContext->SetViewport(&shadowMapViewport); pGPUContext->ClearTargets(false, true, false, float4::Zero, 1.0f); // align to texels { float halfShadowMapSize = (float)m_shadowMapResolution * 0.5f; float3 shadowOrigin(lightCamera.GetViewProjectionMatrix().TransformPoint(float3::Zero)); shadowOrigin *= halfShadowMapSize; float2 roundedOrigin(Math::Round(shadowOrigin.x), Math::Round(shadowOrigin.y)); float2 rounding = roundedOrigin - shadowOrigin.xy(); rounding /= halfShadowMapSize; float4x4 roundingMatrix = float4x4::MakeTranslationMatrix(rounding.x, rounding.y, 0.0f); // apply after projection lightCamera.SetProjectionMatrix(roundingMatrix * lightCamera.GetProjectionMatrix()); } // store matrix to shadow map data pShadowMapData->IsActive = true; pShadowMapData->ViewProjectionMatrix = lightCamera.GetViewProjectionMatrix(); g_pRenderer->GetGPUDevice()->CorrectProjectionMatrix(pShadowMapData->ViewProjectionMatrix); // clear render queue m_renderQueue.Clear(); // find renderables { MICROPROFILE_SCOPEI("SSMShadowMapRenderer", "EnumerateRenderables", MICROPROFILE_COLOR(0, 200, 0)); // enumerate everything in frustum pRenderWorld->EnumerateRenderablesInFrustum(lightCamera.GetFrustum(), [this, &lightCamera](const RenderProxy *pRenderProxy) { // add to render queue pRenderProxy->QueueForRender(&lightCamera, &m_renderQueue); }); // sort renderables m_renderQueue.Sort(); } // no renderables? if (m_renderQueue.GetQueueSize() == 0) return; // set render targets, for pipelining we do this before sorting pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pGPUContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // set up view-dependent constants pGPUContext->GetConstants()->SetFromCamera(lightCamera, true); // init selector @TODO global flags ShaderProgramSelector programSelector(0); programSelector.SetBaseShader(OBJECT_TYPEINFO(ShadowMapShader), 0); // opaque // TODO: Use ShaderProgramSelector { RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); MICROPROFILE_SCOPEI("SSMShadowMapRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(255, 100, 0)); MICROPROFILE_SCOPEGPUI("DrawOpaqueObjects", MICROPROFILE_COLOR(255, 100, 0)); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { // Select appropriate shader // For now, only masked materials are drawn with clipping if (pQueueEntry->pMaterial->GetShader()->GetBlendMode() == MATERIAL_BLENDING_MODE_MASKED) { programSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); programSelector.SetMaterial(pQueueEntry->pMaterial); ShaderProgram *pShaderProgram = programSelector.MakeActive(pGPUContext); if (pShaderProgram != nullptr) { pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pGPUContext); } } else { // Otherwise, use shadowmap shader without material programSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); programSelector.SetMaterial(nullptr); ShaderProgram *pShaderProgram = programSelector.MakeActive(pGPUContext); if (pShaderProgram != nullptr) { pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pGPUContext); } } } } // translucent { RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); MICROPROFILE_SCOPEI("SSMShadowMapRenderer", "DrawTranslucentObjects", MICROPROFILE_COLOR(255, 0, 0)); MICROPROFILE_SCOPEGPUI("DrawTranslucentObjects", MICROPROFILE_COLOR(255, 0, 0)); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & RENDER_PASS_SHADOW_MAP) { // For now, only masked materials are drawn with clipping, so just use the regular shader here programSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); programSelector.SetMaterial((pQueueEntry->pMaterial->GetShader()->GetBlendMode() != MATERIAL_BLENDING_MODE_NONE) ? pQueueEntry->pMaterial : nullptr); ShaderProgram *pShaderProgram = programSelector.MakeActive(pGPUContext); if (pShaderProgram != nullptr) { pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pGPUContext); } } } } } void SSMShadowMapRenderer::DrawSpotShadowMap(GPUContext *pGPUContext, ShadowMapData *pShadowMapData, const RenderWorld *pRenderWorld, const Camera *pViewCamera, float shadowDistance, const RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight) { } <file_sep>/Engine/Source/Core/VirtualFileSystem.cpp #include "Core/PrecompiledHeader.h" #include "Core/VirtualFileSystem.h" #include "Core/Console.h" #include "YBaseLib/Platform.h" #include "YBaseLib/Log.h" VirtualFileSystem s_VirtualFileSystem; VirtualFileSystem *g_pVirtualFileSystem = &s_VirtualFileSystem; Log_SetChannel(VirtualFileSystem); // Storing these here should be okay since nobody outside should be setting them.. namespace CVars { CVar vfs_basepath("vfs_basepath", CVAR_FLAG_NO_ARCHIVE | CVAR_FLAG_REQUIRE_APP_RESTART, "", "base path for virtual file system", "string"); CVar vfs_userpath("vfs_userpath", CVAR_FLAG_NO_ARCHIVE | CVAR_FLAG_REQUIRE_APP_RESTART, "", "base user path for virtual file system", "string"); CVar vfs_gamedir("vfs_gamedir", CVAR_FLAG_NO_ARCHIVE | CVAR_FLAG_REQUIRE_APP_RESTART, "BlockGame", "virtual file system game directory name", "string"); CVar vfs_mount_gamedata_rw("vfs_mount_gamedata_rw", CVAR_FLAG_NO_ARCHIVE | CVAR_FLAG_REQUIRE_APP_RESTART, "false", "mount the game data directory read-write (default read-only, only will work with developer directory structure)", "string"); CVar vfs_gitlayout("vfs_gitlayout", CVAR_FLAG_NO_ARCHIVE | CVAR_FLAG_REQUIRE_APP_RESTART, "false", "use repository-style directory structure", "bool"); } class LocalVirtualFileSystemArchive : public VirtualFileSystemArchive { public: LocalVirtualFileSystemArchive(const char *BasePath, bool ReadOnly) { FileSystem::CanonicalizePath(m_strBasePath, BasePath); m_bReadOnly = ReadOnly; } ~LocalVirtualFileSystemArchive() { } const char *GetArchiveTypeName() const { return "LocalVirtualFileSystemArchive"; } inline void BuildFullPath(PathString &fullPath, const char *Path) { // build full path if (Path[0] != '\0') fullPath.Format("%s/%s", m_strBasePath.GetCharArray(), Path); else fullPath = m_strBasePath; } inline void FixPathString(String &Path) { DebugAssert(Path.GetLength() >= m_strBasePath.GetLength()); DebugAssert(Y_strnicmp(Path, m_strBasePath, m_strBasePath.GetLength()) == 0); if (Path.GetLength() == m_strBasePath.GetLength()) { // empty path Path.Clear(); return; } // remove leading backslash Path.Erase(0, m_strBasePath.GetLength() + 1); // convert all backslashes to forward slashes #if FS_OSPATH_SEPERATOR_CHARACTER == '\\' uint32 i; for (i = 0; i < Path.GetLength(); i++) { if (Path[i] == FS_OSPATH_SEPERATOR_CHARACTER) Path[i] = '/'; } #endif } inline void FixPathArray(char *Path) { uint32 pathLen = Y_strlen(Path); DebugAssert(pathLen >= m_strBasePath.GetLength()); DebugAssert(Y_strnicmp(Path, m_strBasePath, m_strBasePath.GetLength()) == 0); if (pathLen == m_strBasePath.GetLength()) { Path[0] = '\0'; return; } pathLen -= m_strBasePath.GetLength() + 1; Y_memmove(Path, Path + m_strBasePath.GetLength() + 1, pathLen); Path[pathLen] = '\0'; // convert all backslashes to forward slashes #if FS_OSPATH_SEPERATOR_CHARACTER == '\\' uint32 i; for (i = 0; i < pathLen; i++) { if (Path[i] == FS_OSPATH_SEPERATOR_CHARACTER) Path[i] = '/'; } #endif } bool FindFiles(const char *Path, const char *Pattern, uint32 Flags, FileSystem::FindResultsArray *pResults) { // build full path PathString fullPath; BuildFullPath(fullPath, Path); // pass it to filesystem class FileSystem::BuildOSPath(fullPath); uint32 i; uint32 curResultsSize = pResults->GetSize(); if (!FileSystem::FindFiles(fullPath.GetCharArray(), Pattern, Flags, pResults)) return false; if (!(Flags & FILESYSTEM_FIND_RELATIVE_PATHS)) { for (i = curResultsSize; i < pResults->GetSize(); i++) FixPathArray(pResults->GetElement(i).FileName); } return true; } bool StatFile(const char *Path, FILESYSTEM_STAT_DATA *pStatData) { // build full path PathString fullPath; BuildFullPath(fullPath, Path); // pass it to filesystem class FileSystem::BuildOSPath(fullPath); return FileSystem::StatFile(fullPath.GetCharArray(), pStatData); } bool GetFileName(String &Destination, const char *FileName) { PathString fullPath; BuildFullPath(fullPath, FileName); FileSystem::BuildOSPath(fullPath); if (!FileSystem::GetFileName(Destination, fullPath)) return false; FixPathString(Destination); return true; } ByteStream *OpenFile(const char *FileName, uint32 Flags) { // special behaviour when writing to files if (Flags & BYTESTREAM_OPEN_WRITE) { // if requesting write, outright deny it if we are mounted read-only if (m_bReadOnly) return NULL; // when creating a new folder, if the parent directory structure does not exist, // we have to create it ourselves here. // not right now.. changed my mind } // build full path PathString fullPath; BuildFullPath(fullPath, FileName); // pass it to filesystem class FileSystem::BuildOSPath(fullPath); return FileSystem::OpenFile(fullPath, Flags); } bool DeleteFile(const char *FileName) { if (m_bReadOnly) return false; PathString fullPath; BuildFullPath(fullPath, FileName); FileSystem::BuildOSPath(fullPath); FILESYSTEM_STAT_DATA statData; if (FileSystem::StatFile(fullPath, &statData) && !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) return FileSystem::DeleteFile(fullPath); else return false; } bool DeleteDirectory(const char *FileName, bool recursive) { if (m_bReadOnly) return false; PathString fullPath; BuildFullPath(fullPath, FileName); FileSystem::BuildOSPath(fullPath); FILESYSTEM_STAT_DATA statData; if (FileSystem::StatFile(fullPath, &statData) && statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY) return FileSystem::DeleteDirectory(fullPath, recursive); else return false; } class ChangeNotifierArchive : public FileSystem::ChangeNotifier { public: ChangeNotifierArchive(const String &basePath, const String &filterPath, FileSystem::ChangeNotifier *pRealNotifier) : FileSystem::ChangeNotifier(basePath, true), m_basePath(basePath), m_filterPath(filterPath), m_pRealNotifier(pRealNotifier) { } virtual ~ChangeNotifierArchive() { delete m_pRealNotifier; } virtual void EnumerateChanges(EnumerateChangesCallback callback, void *pUserData) override { m_pRealNotifier->EnumerateChanges([this, &callback, pUserData](const ChangeInfo *pChangeInfo) { uint32 pathLength = Y_strlen(pChangeInfo->Path); if (pathLength <= (m_basePath.GetLength() + 1)) return; // clone the path and copy it, stripping the base path, and convert any \s to / PathString virtualPath; virtualPath.AppendSubString(pChangeInfo->Path, m_basePath.GetLength() + 1); virtualPath.Replace('\\', '/'); // handle filters if (!m_filterPath.IsEmpty() && !virtualPath.StartsWith(m_filterPath, false)) return; // invoke the callback with the virtual path ChangeInfo newChangeInfo; newChangeInfo.Path = virtualPath; newChangeInfo.Event = pChangeInfo->Event; callback(&newChangeInfo, pUserData); }); } protected: String m_basePath; String m_filterPath; FileSystem::ChangeNotifier *m_pRealNotifier; }; FileSystem::ChangeNotifier *CreateChangeNotifier(const String &directoryPath) { // create a change notifier on the base path FileSystem::ChangeNotifier *pChangeNotifier = FileSystem::CreateChangeNotifier(m_strBasePath, true); if (pChangeNotifier == nullptr) return nullptr; // create our virtual class return new ChangeNotifierArchive(m_strBasePath, directoryPath, pChangeNotifier); } protected: String m_strBasePath; bool m_bReadOnly; }; class ChangeNotifierVFS : public FileSystem::ChangeNotifier { public: ChangeNotifierVFS(FileSystem::ChangeNotifier **ppArchiveNotifiers, uint32 nArchiveNotifiers) : FileSystem::ChangeNotifier(StaticString("VFS Root"), true) { m_ppChangeNotifiers = new FileSystem::ChangeNotifier *[nArchiveNotifiers]; Y_memcpy(m_ppChangeNotifiers, ppArchiveNotifiers, sizeof(FileSystem::ChangeNotifier *) * nArchiveNotifiers); m_nChangeNotifiers = nArchiveNotifiers; } virtual ~ChangeNotifierVFS() { for (uint32 i = 0; i < m_nChangeNotifiers; i++) delete m_ppChangeNotifiers[i]; delete[] m_ppChangeNotifiers; } virtual void EnumerateChanges(EnumerateChangesCallback callback, void *pUserData) override { for (uint32 i = 0; i < m_nChangeNotifiers; i++) m_ppChangeNotifiers[i]->EnumerateChanges(callback, pUserData); } private: FileSystem::ChangeNotifier **m_ppChangeNotifiers; uint32 m_nChangeNotifiers; }; VirtualFileSystem::VirtualFileSystem() { } VirtualFileSystem::~VirtualFileSystem() { } bool VirtualFileSystem::Initialize() { String executablePath; String currentSearchPath; FILESYSTEM_STAT_DATA statData; // parse cvar overrides String basePath = CVars::vfs_basepath.GetString(); String userPath = CVars::vfs_userpath.GetString(); String gameDirectory = CVars::vfs_gamedir.GetString(); bool mountDataDirectoriesReadWrite = CVars::vfs_mount_gamedata_rw.GetBool(); bool shippingDirectoryStructure = true; // log start Log_InfoPrint("Initializing virtual file system..."); // get path to binary if (!Platform::GetProgramFileName(executablePath)) { Log_ErrorPrintf("VirtualFileSystem initialization error: Could not get program file name."); return false; } // log it Log_DevPrintf("Base path: %s", basePath.GetCharArray()); Log_DevPrintf("User path: %s", userPath.GetCharArray()); Log_DevPrintf("Game directory: %s", gameDirectory.GetCharArray()); Log_DevPrintf("Program file name: %s", executablePath.GetCharArray()); #ifndef Y_PLATFORM_HTML5 // check for developer directory structure if (basePath.IsEmpty() || CVars::vfs_gitlayout.GetBool()) { // in developer structure, program is located at <root>/Binaries/<platform> bool validDeveloperStructure = true; // determine base path if (basePath.IsEmpty()) FileSystem::BuildPathRelativeToFile(basePath, executablePath, "../..", true, true); // test for <root>/Engine/Data currentSearchPath.Format("%s/Engine/Data", basePath.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!FileSystem::StatFile(currentSearchPath, &statData) || !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) { // try three levels down, for unix systems launching editor/tools FileSystem::BuildPathRelativeToFile(basePath, executablePath, "../../..", true, true); // test for <root>/Engine/Data again currentSearchPath.Format("%s/Engine/Data", basePath.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!FileSystem::StatFile(currentSearchPath, &statData) || !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) { validDeveloperStructure = false; } } // test for <root>/<gamename>/Data if (validDeveloperStructure) { currentSearchPath.Format("%s/%s/Data", basePath.GetCharArray(), gameDirectory.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!FileSystem::StatFile(currentSearchPath, &statData) || !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) validDeveloperStructure = false; } // ok? if (validDeveloperStructure) { // logging Log_InfoPrintf("VirtualFileSystem: Developer directory structure detected (base path of '%s').", basePath.GetCharArray()); shippingDirectoryStructure = false; // mount engine data currentSearchPath.Format("%s/Engine/Data", basePath.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); AddDirectory(currentSearchPath, 30, !mountDataDirectoriesReadWrite, false); // mount game data currentSearchPath.Format("%s/%s/Data", basePath.GetCharArray(), gameDirectory.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); AddDirectory(currentSearchPath, 20, !mountDataDirectoriesReadWrite, false); } else { // clear base path so code below can derive it basePath.Clear(); } } // load shipping directory structure if (shippingDirectoryStructure) { // find base path if (basePath.IsEmpty()) FileSystem::BuildPathRelativeToFile(basePath, executablePath, "..", true, true); // engine data directory should be at <base data path>/Engine currentSearchPath.Format("%s/Data/Engine", basePath.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!AddDirectory(currentSearchPath, 30, true, false)) { Log_ErrorPrintf("VirtualFileSystem: Could not mount engine data directory (detected as '%s')", currentSearchPath.GetCharArray()); return false; } // game data directory should be at <base data path>/<game name> currentSearchPath.Format("%s/Data/%s", basePath.GetCharArray(), gameDirectory.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!AddDirectory(currentSearchPath, 20, true, false)) { Log_ErrorPrintf("VirtualFileSystem: Could not mount game data directory (detected as '%s')", currentSearchPath.GetCharArray()); return false; } } // mount user data if (shippingDirectoryStructure || !mountDataDirectoriesReadWrite) { // both developer and shipping use the same path at <base directory>/UserData/<game name> // Otherwise, it'll save to My Documents\\<SavePath>, TODO IMPLEMENT THIS (SHGetSpecialFolderPath(NULL, ModulePath, CSIDL_MYDOCUMENTS, FALSE);) bool mountedUserData = false; // set userpath if (userPath.IsEmpty()) { currentSearchPath.Format("%s/UserData", basePath.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); } else { currentSearchPath = userPath; } // check for userdata path presence first if (FileSystem::StatFile(currentSearchPath, &statData) && statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY) { // if the game directory does not exist here, we can create it currentSearchPath.Format("%s/UserData/%s", basePath.GetCharArray(), gameDirectory.GetCharArray()); FileSystem::BuildOSPath(currentSearchPath); if (!FileSystem::StatFile(currentSearchPath, &statData) || !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) { // create the directory Log_InfoPrintf("VirtualFileSystem: Attempting to create user directory for VFS at '%s'...", currentSearchPath.GetCharArray()); if (!FileSystem::CreateDirectory(currentSearchPath, false)) Log_WarningPrintf("VirtualFileSystem: Failed to create user directory in VFS. Path was '%s'.", currentSearchPath.GetCharArray()); } // mount it mountedUserData = AddDirectory(currentSearchPath, 0, false, false); } // worked? if (!mountedUserData) { Log_WarningPrint("Could not determine user path. Enable developer mode with -vfs_mount_gamedata_rw 1 to save to the game directory, or specify a user path on the commandline with -vfs_userpath."); return false; } } #else // Mount html5 archive as a single archive at /data, /userdata AddDirectory("/Data/Engine", 30, true, true); currentSearchPath.Format("/Data/%s", gameDirectory.GetCharArray()); AddDirectory(currentSearchPath, 20, true, true); currentSearchPath.Format("/UserData/%s", gameDirectory.GetCharArray()); AddDirectory(currentSearchPath, 0, false, true); #endif Log_InfoPrintf("VirtualFileSystem initialization completed, %u archives mounted.", m_liArchives.GetSize()); return true; } void VirtualFileSystem::Shutdown() { Log_InfoPrintf("VirtualFileSystem unmounting %u archives...", m_liArchives.GetSize()); for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { itr->SortKey.Clear(); delete itr->pArchiveInterface; } } bool VirtualFileSystem::FindFiles(const char *Path, const char *Pattern, uint32 Flags, FileSystem::FindResultsArray *pResults) { uint32 i, j; bool Result = false; if (!(Flags & FILESYSTEM_FIND_KEEP_ARRAY)) pResults->Clear(); for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { uint32 curResultsSize = pResults->GetSize(); if (itr->pArchiveInterface->FindFiles(Path, Pattern, Flags | FILESYSTEM_FIND_KEEP_ARRAY, pResults)) { // remove any duplicates that snuck in for (i = curResultsSize; i < pResults->GetSize(); ) { for (j = 0; j < curResultsSize; j++) { if (Y_stricmp(pResults->GetElement(i).FileName, pResults->GetElement(j).FileName) == 0) break; } if (j != curResultsSize) pResults->OrderedRemove(i); else i++; } Result = true; } } return Result; } bool VirtualFileSystem::StatFile(const char *Path, FILESYSTEM_STAT_DATA *pStatData) { for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->StatFile(Path, pStatData)) return true; } return false; } bool VirtualFileSystem::FileExists(const char *Path) { FILESYSTEM_STAT_DATA statData; for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->StatFile(Path, &statData) && !(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) return true; } return false; } bool VirtualFileSystem::DirectoryExists(const char *Path) { FILESYSTEM_STAT_DATA statData; for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->StatFile(Path, &statData) && statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY) return true; } return false; } bool VirtualFileSystem::GetFileName(String &Destination, const char *FileName) { for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->GetFileName(Destination, FileName)) return true; } return false; } bool VirtualFileSystem::GetFileName(String &FileName) { return GetFileName(FileName, FileName.GetCharArray()); } ByteStream *VirtualFileSystem::OpenFile(const char *FileName, uint32 Flags) { ByteStream *pStream; for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if ((pStream = itr->pArchiveInterface->OpenFile(FileName, Flags)) != NULL) return pStream; } return NULL; } bool VirtualFileSystem::DeleteFile(const char *FileName) { for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->DeleteFile(FileName)) return true; } return false; } bool VirtualFileSystem::DeleteDirectory(const char *FileName, bool recursive) { for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pArchiveInterface->DeleteDirectory(FileName, recursive)) return true; } return false; } FileSystem::ChangeNotifier *VirtualFileSystem::CreateChangeNotifier(const char *directoryPath /*= nullptr*/) { if (m_liArchives.GetSize() == 0) return nullptr; FileSystem::ChangeNotifier **ppArchiveNotifiers = (FileSystem::ChangeNotifier **)alloca(sizeof(FileSystem::ChangeNotifier *) * m_liArchives.GetSize()); uint32 nArchiveNotifiers = 0; String directoryPathString; if (directoryPath != nullptr) directoryPathString = directoryPath; for (ArchiveList::Iterator itr = m_liArchives.Begin(); !itr.AtEnd(); itr.Forward()) { if ((ppArchiveNotifiers[nArchiveNotifiers] = itr->pArchiveInterface->CreateChangeNotifier(directoryPathString)) != nullptr) nArchiveNotifiers++; } if (nArchiveNotifiers == 0) return nullptr; return new ChangeNotifierVFS(ppArchiveNotifiers, nArchiveNotifiers); } BinaryBlob *VirtualFileSystem::GetFileContents(const char *filename) { ByteStream *pStream = OpenFile(filename, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return nullptr; BinaryBlob *pReturn = BinaryBlob::CreateFromStream(pStream); pStream->Release(); return pReturn; } bool VirtualFileSystem::PutFileContents(const char *filename, const void *pData, uint32 dataSize, bool overwrite /*= true*/, bool createPath /*= true*/) { if (FileExists(filename) && !overwrite) return false; uint32 openFlags = BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE; if (createPath) openFlags |= BYTESTREAM_OPEN_CREATE_PATH; ByteStream *pStream = OpenFile(filename, openFlags); if (pStream == nullptr) return false; if (dataSize > 0 && !pStream->Write2(pData, dataSize)) { pStream->Discard(); pStream->Release(); return false; } else { pStream->Commit(); pStream->Release(); return true; } } bool VirtualFileSystem::AddDirectory(const char *Path, int32 Priority, bool ReadOnly, bool AddNonexistantDirectories) { // we should be able to stat it, if not, don't bother, as the path most likely does not exist FILESYSTEM_STAT_DATA statData; if (!FileSystem::StatFile(Path, &statData)) { // skipping directory check? if (!AddNonexistantDirectories) return false; } else if (!(statData.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)) { // can't add it if it's a file return false; } // create archive LocalVirtualFileSystemArchive *pArchive = new LocalVirtualFileSystemArchive(Path, ReadOnly); AddArchive(pArchive, EmptyString, Priority); Log_InfoPrintf("Mounted local directory '%s' into VFS, at priority %d, with %s permissions.", Path, Priority, ReadOnly ? "read-only" : "read-write"); return true; } void VirtualFileSystem::AddArchive(VirtualFileSystemArchive *pArchiveInterface, const String &SortKey, int32 Priority) { VirtualFileSystemArchiveEntry archiveEntry; archiveEntry.pArchiveInterface = pArchiveInterface; archiveEntry.SortKey = SortKey; archiveEntry.Priority = Priority; ArchiveList::Iterator itr = m_liArchives.Begin(); for (; !itr.AtEnd(); itr.Forward()) { VirtualFileSystemArchiveEntry &Entry = *itr; if (Entry.Priority < Priority) continue; // if priority is equal, use sort key, otherwise priority if (Entry.Priority == Priority && Entry.SortKey.NumericCompareInsensitive(SortKey) < 0) continue; // it is before it, insert before this one m_liArchives.InsertBefore(itr, archiveEntry); return; } // not inserted yet, add to tail m_liArchives.PushBack(archiveEntry); } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2Defines.h #pragma once namespace NameTables { Y_Declare_NameTable(GLESErrors); } extern GLenum g_eGLES2LastError; extern void GLES2Renderer_PrintError(const char *Format, ...); #define GL_CHECKED_SECTION_BEGIN() glGetError(); #define GL_CHECK_ERROR_STATE() ((g_eGLES2LastError = glGetError()) != GL_NO_ERROR) #define GL_PRINT_ERROR(...) GLES2Renderer_PrintError(__VA_ARGS__) namespace OpenGLES2TypeConversion { // shader stuff void GetOpenGLVAOTypeAndSizeForVertexElementType(GPU_VERTEX_ELEMENT_TYPE elementType, bool *pIntegerType, GLenum *pGLType, GLint *pGLSize, GLboolean *pGLNormalized); // state stuff GLenum GetOpenGLComparisonFunc(GPU_COMPARISON_FUNC ComparisonFunc); GLenum GetOpenGLComparisonMode(TEXTURE_FILTER Filter); GLenum GetOpenGLTextureMinFilter(TEXTURE_FILTER Filter, bool hasMips); GLenum GetOpenGLTextureMagFilter(TEXTURE_FILTER Filter); GLenum GetOpenGLTextureWrap(TEXTURE_ADDRESS_MODE AddressMode); GLenum GetOpenGLCullFace(RENDERER_CULL_MODE CullMode); GLenum GetOpenGLStencilOp(RENDERER_STENCIL_OP StencilOp); GLenum GetOpenGLBlendEquation(RENDERER_BLEND_OP BlendOp); GLenum GetOpenGLBlendFunc(RENDERER_BLEND_OPTION BlendFactor); GLenum GetOpenGLTextureTarget(TEXTURE_TYPE textureType); // Convert pixel format to GL texture internalFormat, format, type bool GetOpenGLTextureFormat(PIXEL_FORMAT PixelFormat, GLint *pGLInternalFormat, GLenum *pGLFormat, GLenum *pGLType); } namespace OpenGLES2Helpers { GLenum GetOpenGLTextureTarget(GPUTexture *pGPUTexture); GLuint GetOpenGLTextureId(GPUTexture *pGPUTexture); void BindOpenGLTexture(GPUTexture *pGPUTexture); void GLUniformWrapper(SHADER_PARAMETER_TYPE type, GLuint location, GLuint arraySize, const void *pValue); void SetObjectDebugName(GLenum type, GLuint id, const char *debugName); } <file_sep>/Editor/Source/Editor/SkeletalAnimationEditor/moc_EditorSkeletalAnimationEditor.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorSkeletalAnimationEditor.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorSkeletalAnimationEditor.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorSkeletalAnimationEditor.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorSkeletalAnimationEditor_t { QByteArrayData data[45]; char stringdata[1078]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorSkeletalAnimationEditor_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorSkeletalAnimationEditor_t qt_meta_stringdata_EditorSkeletalAnimationEditor = { { QT_MOC_LITERAL(0, 0, 29), // "EditorSkeletalAnimationEditor" QT_MOC_LITERAL(1, 30, 23), // "OnActionOpenMeshClicked" QT_MOC_LITERAL(2, 54, 0), // "" QT_MOC_LITERAL(3, 55, 23), // "OnActionSaveMeshClicked" QT_MOC_LITERAL(4, 79, 25), // "OnActionSaveMeshAsClicked" QT_MOC_LITERAL(5, 105, 20), // "OnActionCloseClicked" QT_MOC_LITERAL(6, 126, 34), // "OnActionCameraPerspectiveTrig..." QT_MOC_LITERAL(7, 161, 7), // "checked" QT_MOC_LITERAL(8, 169, 30), // "OnActionCameraArcballTriggered" QT_MOC_LITERAL(9, 200, 32), // "OnActionCameraIsometricTriggered" QT_MOC_LITERAL(10, 233, 30), // "OnActionViewWireframeTriggered" QT_MOC_LITERAL(11, 264, 26), // "OnActionViewUnlitTriggered" QT_MOC_LITERAL(12, 291, 24), // "OnActionViewLitTriggered" QT_MOC_LITERAL(13, 316, 32), // "OnActionViewFlagShadowsTriggered" QT_MOC_LITERAL(14, 349, 41), // "OnActionViewFlagWireframeOver..." QT_MOC_LITERAL(15, 391, 32), // "OnActionToolInformationTriggered" QT_MOC_LITERAL(16, 424, 30), // "OnActionToolBoneTrackTriggered" QT_MOC_LITERAL(17, 455, 31), // "OnActionToolRootMotionTriggered" QT_MOC_LITERAL(18, 487, 28), // "OnActionToolClipperTriggered" QT_MOC_LITERAL(19, 516, 37), // "OnActionToolLightManipulatorT..." QT_MOC_LITERAL(20, 554, 22), // "OnScrubberValueChanged" QT_MOC_LITERAL(21, 577, 5), // "value" QT_MOC_LITERAL(22, 583, 22), // "OnHierarchyItemClicked" QT_MOC_LITERAL(23, 606, 16), // "QTreeWidgetItem*" QT_MOC_LITERAL(24, 623, 5), // "pItem" QT_MOC_LITERAL(25, 629, 6), // "column" QT_MOC_LITERAL(26, 636, 37), // "OnInformationPreviewMeshLinkA..." QT_MOC_LITERAL(27, 674, 4), // "link" QT_MOC_LITERAL(28, 679, 35), // "OnClipperSetStartFrameNumberC..." QT_MOC_LITERAL(29, 715, 33), // "OnClipperSetEndFrameNumberCli..." QT_MOC_LITERAL(30, 749, 20), // "OnClipperClipClicked" QT_MOC_LITERAL(31, 770, 24), // "OnSwapChainWidgetResized" QT_MOC_LITERAL(32, 795, 22), // "OnSwapChainWidgetPaint" QT_MOC_LITERAL(33, 818, 30), // "OnSwapChainWidgetKeyboardEvent" QT_MOC_LITERAL(34, 849, 16), // "const QKeyEvent*" QT_MOC_LITERAL(35, 866, 14), // "pKeyboardEvent" QT_MOC_LITERAL(36, 881, 27), // "OnSwapChainWidgetMouseEvent" QT_MOC_LITERAL(37, 909, 18), // "const QMouseEvent*" QT_MOC_LITERAL(38, 928, 11), // "pMouseEvent" QT_MOC_LITERAL(39, 940, 27), // "OnSwapChainWidgetWheelEvent" QT_MOC_LITERAL(40, 968, 18), // "const QWheelEvent*" QT_MOC_LITERAL(41, 987, 11), // "pWheelEvent" QT_MOC_LITERAL(42, 999, 33), // "OnSwapChainWidgetGainedFocusE..." QT_MOC_LITERAL(43, 1033, 25), // "OnFrameExecutionTriggered" QT_MOC_LITERAL(44, 1059, 18) // "timeSinceLastFrame" }, "EditorSkeletalAnimationEditor\0" "OnActionOpenMeshClicked\0\0" "OnActionSaveMeshClicked\0" "OnActionSaveMeshAsClicked\0" "OnActionCloseClicked\0" "OnActionCameraPerspectiveTriggered\0" "checked\0OnActionCameraArcballTriggered\0" "OnActionCameraIsometricTriggered\0" "OnActionViewWireframeTriggered\0" "OnActionViewUnlitTriggered\0" "OnActionViewLitTriggered\0" "OnActionViewFlagShadowsTriggered\0" "OnActionViewFlagWireframeOverlayTriggered\0" "OnActionToolInformationTriggered\0" "OnActionToolBoneTrackTriggered\0" "OnActionToolRootMotionTriggered\0" "OnActionToolClipperTriggered\0" "OnActionToolLightManipulatorTriggered\0" "OnScrubberValueChanged\0value\0" "OnHierarchyItemClicked\0QTreeWidgetItem*\0" "pItem\0column\0OnInformationPreviewMeshLinkActivated\0" "link\0OnClipperSetStartFrameNumberClicked\0" "OnClipperSetEndFrameNumberClicked\0" "OnClipperClipClicked\0OnSwapChainWidgetResized\0" "OnSwapChainWidgetPaint\0" "OnSwapChainWidgetKeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "OnSwapChainWidgetMouseEvent\0" "const QMouseEvent*\0pMouseEvent\0" "OnSwapChainWidgetWheelEvent\0" "const QWheelEvent*\0pWheelEvent\0" "OnSwapChainWidgetGainedFocusEvent\0" "OnFrameExecutionTriggered\0timeSinceLastFrame" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorSkeletalAnimationEditor[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 30, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 164, 2, 0x08 /* Private */, 3, 0, 165, 2, 0x08 /* Private */, 4, 0, 166, 2, 0x08 /* Private */, 5, 0, 167, 2, 0x08 /* Private */, 6, 1, 168, 2, 0x08 /* Private */, 8, 1, 171, 2, 0x08 /* Private */, 9, 1, 174, 2, 0x08 /* Private */, 10, 1, 177, 2, 0x08 /* Private */, 11, 1, 180, 2, 0x08 /* Private */, 12, 1, 183, 2, 0x08 /* Private */, 13, 1, 186, 2, 0x08 /* Private */, 14, 1, 189, 2, 0x08 /* Private */, 15, 1, 192, 2, 0x08 /* Private */, 16, 1, 195, 2, 0x08 /* Private */, 17, 1, 198, 2, 0x08 /* Private */, 18, 1, 201, 2, 0x08 /* Private */, 19, 1, 204, 2, 0x08 /* Private */, 20, 1, 207, 2, 0x08 /* Private */, 22, 2, 210, 2, 0x08 /* Private */, 26, 1, 215, 2, 0x08 /* Private */, 28, 0, 218, 2, 0x08 /* Private */, 29, 0, 219, 2, 0x08 /* Private */, 30, 0, 220, 2, 0x08 /* Private */, 31, 0, 221, 2, 0x08 /* Private */, 32, 0, 222, 2, 0x08 /* Private */, 33, 1, 223, 2, 0x08 /* Private */, 36, 1, 226, 2, 0x08 /* Private */, 39, 1, 229, 2, 0x08 /* Private */, 42, 0, 232, 2, 0x08 /* Private */, 43, 1, 233, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Int, 21, QMetaType::Void, 0x80000000 | 23, QMetaType::Int, 24, 25, QMetaType::Void, QMetaType::QString, 27, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 34, 35, QMetaType::Void, 0x80000000 | 37, 38, QMetaType::Void, 0x80000000 | 40, 41, QMetaType::Void, QMetaType::Void, QMetaType::Float, 44, 0 // eod }; void EditorSkeletalAnimationEditor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorSkeletalAnimationEditor *_t = static_cast<EditorSkeletalAnimationEditor *>(_o); switch (_id) { case 0: _t->OnActionOpenMeshClicked(); break; case 1: _t->OnActionSaveMeshClicked(); break; case 2: _t->OnActionSaveMeshAsClicked(); break; case 3: _t->OnActionCloseClicked(); break; case 4: _t->OnActionCameraPerspectiveTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnActionCameraArcballTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnActionCameraIsometricTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnActionViewWireframeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnActionViewUnlitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->OnActionViewLitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnActionViewFlagShadowsTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 11: _t->OnActionViewFlagWireframeOverlayTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->OnActionToolInformationTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 13: _t->OnActionToolBoneTrackTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 14: _t->OnActionToolRootMotionTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 15: _t->OnActionToolClipperTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 16: _t->OnActionToolLightManipulatorTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 17: _t->OnScrubberValueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 18: _t->OnHierarchyItemClicked((*reinterpret_cast< QTreeWidgetItem*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 19: _t->OnInformationPreviewMeshLinkActivated((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 20: _t->OnClipperSetStartFrameNumberClicked(); break; case 21: _t->OnClipperSetEndFrameNumberClicked(); break; case 22: _t->OnClipperClipClicked(); break; case 23: _t->OnSwapChainWidgetResized(); break; case 24: _t->OnSwapChainWidgetPaint(); break; case 25: _t->OnSwapChainWidgetKeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 26: _t->OnSwapChainWidgetMouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 27: _t->OnSwapChainWidgetWheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 28: _t->OnSwapChainWidgetGainedFocusEvent(); break; case 29: _t->OnFrameExecutionTriggered((*reinterpret_cast< float(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorSkeletalAnimationEditor::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_EditorSkeletalAnimationEditor.data, qt_meta_data_EditorSkeletalAnimationEditor, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorSkeletalAnimationEditor::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorSkeletalAnimationEditor::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorSkeletalAnimationEditor.stringdata)) return static_cast<void*>(const_cast< EditorSkeletalAnimationEditor*>(this)); return QMainWindow::qt_metacast(_clname); } int EditorSkeletalAnimationEditor::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 30) qt_static_metacall(this, _c, _id, _a); _id -= 30; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 30) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 30; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/Engine/ComponentTypeInfo.h #pragma once #include "Engine/Common.h" #include "Core/ObjectTypeInfo.h" class ComponentTypeInfo : public ObjectTypeInfo { public: ComponentTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory); virtual ~ComponentTypeInfo(); // only called once. virtual void RegisterType() override; virtual void UnregisterType() override; }; #define DECLARE_COMPONENT_TYPEINFO(Type, ParentType) \ private: \ static ComponentTypeInfo s_typeInfo; \ static const PROPERTY_DECLARATION s_propertyDeclarations[]; \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ComponentTypeInfo *StaticTypeInfo() { return &s_typeInfo; } \ static ComponentTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } #define DECLARE_COMPONENT_GENERIC_FACTORY(Type) DECLARE_OBJECT_GENERIC_FACTORY(Type) #define DECLARE_COMPONENT_NO_FACTORY(Type) DECLARE_OBJECT_NO_FACTORY(Type) #define DEFINE_COMPONENT_TYPEINFO(Type) \ ComponentTypeInfo Type::s_typeInfo = ComponentTypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::s_propertyDeclarations, Type::StaticFactory()); #define DEFINE_COMPONENT_GENERIC_FACTORY(Type) DEFINE_OBJECT_GENERIC_FACTORY(Type) #define BEGIN_COMPONENT_PROPERTIES(Type) \ const PROPERTY_DECLARATION Type::s_propertyDeclarations[] = { #define END_COMPONENT_PROPERTIES() \ PROPERTY_TABLE_MEMBER(NULL, PROPERTY_TYPE_COUNT, 0, NULL, NULL, NULL, NULL, NULL, NULL) \ }; #define COMPONENT_TYPEINFO(Type) OBJECT_TYPEINFO(Type) #define COMPONENT_TYPEINFO_PTR(Ptr) OBJECT_TYPEINFO_PTR(Type) #define COMPONENT_MUTABLE_TYPEINFO(Type) OBJECT_MUTABLE_TYPEINFO(Type) #define COMPONENT_MUTABLE_TYPEINFO_PTR(Type) OBJECT_MUTABLE_TYPEINFO_PTR(Type) <file_sep>/Editor/Source/Editor/ToolMenuWidget.h #pragma once #include "Editor/Common.h" class ToolMenuWidget : public QWidget { Q_OBJECT public: ToolMenuWidget(QWidget *pParent, Qt::Orientation orientation = Qt::Vertical, bool showLabels = true); virtual ~ToolMenuWidget(); const Qt::Orientation getOrientation() const { return m_orientation; } void setOrientation(Qt::Orientation orientation) { m_orientation = orientation; recreateLayout(); } const bool showLabels() const { return m_showLabels; } void setShowLabels(bool showLabels) { m_showLabels = showLabels; recreateLayout(); } const int buttonMargins() const { return m_buttonMargins; } void setButtonMargins(int buttonMargins) { m_buttonMargins = buttonMargins; recreateLayout(); } void clear(); void addAction(QAction *pAction); void addWidget(QWidget *pWidget); void addSeperator(); void removeAction(QAction *pAction); void removeWidget(QWidget *pWidget); private: struct Item { QAction *pAction; QWidget *pWidget; }; QToolButton *createToolButtonForAction(QAction *pAction); Item *findItemForAction(QAction *pAction); Item *findItemForWidget(QWidget *pWidget); void recreateLayout(); Qt::Orientation m_orientation; bool m_showLabels; QList<Item> m_items; QBoxLayout *m_layout; QSize m_iconSize; int m_buttonMargins; private Q_SLOTS: void OnToolButtonClicked(bool checked); }; <file_sep>/Engine/Source/ContentConverter/AssimpCommon.h #pragma once #include "ContentConverter/Common.h" #include "YBaseLib/ProgressCallbacks.h" #include "assimp/Importer.hpp" #include "assimp/Logger.hpp" #include "assimp/LogStream.hpp" #include "assimp/DefaultLogger.hpp" #include "assimp/scene.h" #include "assimp/postprocess.h" #include "assimp/material.h" namespace AssimpHelpers { float4x4 AssimpMatrix4x4ToFloat4x4(const aiMatrix4x4 &mat); Quaternion AssimpQuaternionToQuaternion(const aiQuaternion &quat); float2 AssimpVector2ToFloat2(const aiVector2D &vec); float3 AssimpVector3ToFloat3(const aiVector3D &vec); uint32 AssimpColor3ToColor(const aiColor3D &vec); uint32 AssimpColor4ToColor(const aiColor4D &vec); aiMatrix4x4 Float4x4ToAssimpMatrix4x4(const float4x4 &mat); class ProgressCallbacksLogStream : public Assimp::LogStream { public: ProgressCallbacksLogStream(ProgressCallbacks *pProgressCallbacks); virtual ~ProgressCallbacksLogStream(); virtual void write(const char* message); private: ProgressCallbacks *m_pProgressCallbacks; }; bool InitializeAssimp(); int GetAssimpStaticMeshImportPostProcessingFlags(); int GetAssimpSkeletonImportPostProcessingFlags(); int GetAssimpSkeletalAnimationImportPostProcessingFlags(); int GetAssimpSkeletalMeshImportPostProcessingFlags(); float4x4 GetAssimpToWorldCoordinateSystemFloat4x4(); aiMatrix4x4 GetAssimpToWorldCoordinateSystemAIMatrix4x4(); } <file_sep>/Engine/Source/ResourceCompilerStandalone/Main.cpp #include "ResourceCompilerInterface/ResourceCompilerInterfaceRemote.h" #include "YBaseLib/Subprocess.h" int main(int argc, char *argv[]) { Log::GetInstance().SetConsoleOutputParams(true); // Handle subprocess stuff if (Subprocess::IsSubprocess()) { ResourceCompilerInterfaceRemote::RemoteProcessLoop(); return 0; } //UNREFERENCED_PARAMETER(argc); //UNREFERENCED_PARAMETER(argv); return 0; } <file_sep>/Engine/Source/BlockEngine/BlockWorldTypes.h #pragma once #include "Engine/Common.h" // engine type forward declarations class BlockPalette; class Entity; // forward declarations of data types class BlockWorld; class BlockWorldSection; class BlockWorldChunk; class BlockWorldChunkRenderProxy; class BlockWorldChunkCollisionShape; // fixed limits #define BLOCK_WORLD_MAX_LOD_LEVELS (3) // block data type typedef uint16 BlockWorldBlockType; typedef uint8 BlockWorldBlockDataType; #define BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT (0x8000U) #define BLOCK_WORLD_BLOCK_DATA_LIGHTING_MASK (0xF) #define BLOCK_WORLD_BLOCK_DATA_LIGHTING_SHIFT (0) #define BLOCK_WORLD_BLOCK_DATA_GET_LIGHTING(data) (((data) >> BLOCK_WORLD_BLOCK_DATA_LIGHTING_SHIFT) & BLOCK_WORLD_BLOCK_DATA_LIGHTING_MASK) #define BLOCK_WORLD_BLOCK_DATA_SET_LIGHTING(data, lighting) (((data) & ~(BLOCK_WORLD_BLOCK_DATA_LIGHTING_MASK << BLOCK_WORLD_BLOCK_DATA_LIGHTING_SHIFT)) | (((lighting) & BLOCK_WORLD_BLOCK_DATA_LIGHTING_MASK) << BLOCK_WORLD_BLOCK_DATA_LIGHTING_SHIFT)) #define BLOCK_WORLD_BLOCK_DATA_ROTATION_MASK (0x3) #define BLOCK_WORLD_BLOCK_DATA_ROTATION_SHIFT (6) #define BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(data) (((data) >> BLOCK_WORLD_BLOCK_DATA_ROTATION_SHIFT) & BLOCK_WORLD_BLOCK_DATA_ROTATION_MASK) #define BLOCK_WORLD_BLOCK_DATA_SET_ROTATION(data, rotation) (((data) & ~(BLOCK_WORLD_BLOCK_DATA_ROTATION_MASK << BLOCK_WORLD_BLOCK_DATA_ROTATION_SHIFT)) | (((rotation) & BLOCK_WORLD_BLOCK_DATA_ROTATION_MASK) << BLOCK_WORLD_BLOCK_DATA_ROTATION_SHIFT)) // rotation enumeration enum BLOCK_WORLD_BLOCK_ROTATION { BLOCK_WORLD_BLOCK_ROTATION_NORTH, BLOCK_WORLD_BLOCK_ROTATION_EAST, BLOCK_WORLD_BLOCK_ROTATION_SOUTH, BLOCK_WORLD_BLOCK_ROTATION_WEST, NUM_BLOCK_WORLD_BLOCK_ROTATIONS, }; // data tracked by block world for entities in the all-inclusive table struct BlockWorldEntityHashTableData { Entity *pEntity; BlockWorldSection *pSection; }; // data tracked by either block world or containing section struct BlockWorldEntityReference { Entity *pEntity; uint32 EntityID; AABox BoundingBox; Sphere BoundingSphere; }; <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUShaderProgram.h #pragma once #include "D3D11Renderer/D3D11Common.h" #include "D3D11Renderer/D3DShaderCacheEntry.h" class D3D11GPUShaderProgram : public GPUShaderProgram { public: struct ConstantBuffer { // @TODO this class could potentially be removed to save a level of indirection String Name; uint32 ParameterIndex; uint32 MinimumSize; uint32 EngineConstantBufferIndex; }; struct Parameter { String Name; SHADER_PARAMETER_TYPE Type; int32 ConstantBufferIndex; uint32 ConstantBufferOffset; uint32 ArraySize; uint32 ArrayStride; D3D_SHADER_BIND_TARGET BindTarget; int32 BindPoint[SHADER_PROGRAM_STAGE_COUNT]; int32 LinkedSamplerIndex; }; public: D3D11GPUShaderProgram(); virtual ~D3D11GPUShaderProgram(); // resource virtuals virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; // create bool Create(D3D11GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, ByteStream *pByteCodeStream); // bind to a context that has no current shader void Bind(D3D11GPUContext *pContext); // switch context to a new shader void Switch(D3D11GPUContext *pContext, D3D11GPUShaderProgram *pCurrentProgram); // unbind from a context, resetting all shader states void Unbind(D3D11GPUContext *pContext); // --- internal query api --- uint32 InternalGetConstantBufferCount() const { return m_constantBuffers.GetSize(); } uint32 InternalGetParameterCount() const { return m_parameters.GetSize(); } const ConstantBuffer *GetConstantBuffer(uint32 Index) const { DebugAssert(Index < m_constantBuffers.GetSize()); return &m_constantBuffers[Index]; } const Parameter *GetParameter(uint32 Index) const { DebugAssert(Index < m_parameters.GetSize()); return &m_parameters[Index]; } // --- internal parameter api --- void InternalSetParameterValue(D3D11GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue); void InternalSetParameterValueArray(D3D11GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements); void InternalSetParameterStruct(D3D11GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize); void InternalSetParameterStructArray(D3D11GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements); void InternalSetParameterResource(D3D11GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState); void InternalBindAutomaticParameters(D3D11GPUContext *pContext); // --- public parameter api --- virtual uint32 GetParameterCount() const override; virtual void GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) override; protected: // arrays typedef Array<ConstantBuffer> ConstantBufferArray; typedef Array<Parameter> ParameterArray; // shader objects ID3D11InputLayout *m_pD3DInputLayout; ID3D11VertexShader *m_pD3DVertexShader; ID3D11HullShader *m_pD3DHullShader; ID3D11DomainShader *m_pD3DDomainShader; ID3D11GeometryShader *m_pD3DGeometryShader; ID3D11PixelShader *m_pD3DPixelShader; ID3D11ComputeShader *m_pD3DComputeShader; // arrays of above ConstantBufferArray m_constantBuffers; ParameterArray m_parameters; // context we are bound to D3D11GPUContext *m_pBoundContext; }; <file_sep>/Engine/Source/ResourceCompiler/SkeletonGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/SkeletalMesh.h" #include "Core/PropertyTable.h" class SkeletonGenerator { public: class Bone { friend class SkeletonGenerator; public: Bone(uint32 index, const char *name, Bone *pParent, const Transform &baseFrameTransform); ~Bone(); const uint32 GetIndex() const { return m_index; } const String &GetName() const { return m_name; } const Bone *GetParent() const { return m_pParent; } const Transform &GetBaseFrameTransform() const { return m_baseFrameTransform; } void SetName(const char *name) { m_name = name; } void SetParent(Bone *pParent) { m_pParent = pParent; } void SetBaseFrameTransform(const Transform &transform) { m_baseFrameTransform = transform; } Bone *GetChild(uint32 i) { return m_children[i]; } uint32 GetChildCount() const { return m_children.GetSize(); } void AddChild(Bone *pBone) { m_children.Add(pBone); } private: uint32 m_index; String m_name; Bone *m_pParent; Transform m_baseFrameTransform; PODArray<Bone *> m_children; DeclareNonCopyable(Bone); }; public: SkeletonGenerator(); ~SkeletonGenerator(); // properties const PropertyTable *GetPropertyTable() const { return &m_properties; } // bones const uint32 GetBoneCount() const { return m_bones.GetSize(); } const Bone *GetBoneByIndex(uint32 i) const { return m_bones[i]; } const Bone *GetBoneByName(const char *name) const; Bone *GetBoneByIndex(uint32 i) { return m_bones[i]; } Bone *GetBoneByName(const char *name); Bone *CreateBone(const char *name, Bone *pParent, const Transform &baseFrameTransform); // Loading interface (from XML) bool LoadFromXML(const char *FileName, ByteStream *pStream); // Output interface bool SaveToXML(ByteStream *pStream) const; bool Compile(ByteStream *pStream) const; private: PropertyTable m_properties; PODArray<Bone *> m_bones; }; <file_sep>/Engine/Source/Engine/DynamicWorld.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/DynamicWorld.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Brush.h" #include "Engine/Entity.h" #include "Renderer/RenderWorld.h" DynamicWorld::DynamicWorld() : World() { } DynamicWorld::~DynamicWorld() { // clean up remaining entites while (m_entities.GetSize() > 0) { EntityData &data = m_entities[m_entities.GetSize() - 1]; Entity *pEntity = data.pEntity; for (uint32 i = 0; i < m_activeEntities.GetSize(); i++) { if (m_activeEntities[i].pEntity == pEntity) { m_activeEntities.FastRemove(i); break; } } for (uint32 i = 0; i < m_activeAsyncEntities.GetSize(); i++) { if (m_activeAsyncEntities[i].pEntity == pEntity) { m_activeAsyncEntities.FastRemove(i); break; } } // as OnRemoveFromWorld could invoke an entity lookup/search, we have to remove the entity from the list *now* m_entities.RemoveBack(); // invoke handler and cleanup pEntity->OnRemoveFromWorld(this); pEntity->Release(); } // and static objects while (m_brushes.GetSize() > 0) { Brush *pObject = m_brushes.PopBack(); pObject->OnRemoveFromWorld(this); pObject->Release(); } } DynamicWorld::EntityData *DynamicWorld::GetEntityData(const Entity *pEntity) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].pEntity == pEntity) return &m_entities[i]; } return nullptr; } void DynamicWorld::AddBrush(Brush *pObject) { DebugAssert(!m_brushes.Contains(pObject)); // add reference pObject->AddRef(); m_brushes.Add(pObject); // invoke added function pObject->OnAddToWorld(this); // update bounds m_worldBoundingBox.Merge(pObject->GetBoundingBox()); m_worldBoundingSphere.Merge(pObject->GetBoundingSphere()); } void DynamicWorld::RemoveBrush(Brush *pObject) { // lookup for (uint32 i = 0; i < m_brushes.GetSize(); i++) { if (m_brushes[i] == pObject) { pObject->OnRemoveFromWorld(this); pObject->Release(); m_brushes.OrderedRemove(i); return; } } // should not get reached Panic("attempted to remove brush from world where it does not exist"); } const Entity *DynamicWorld::GetEntityByID(uint32 EntityId) const { DebugAssert(EntityId != 0); for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID == EntityId) return m_entities[i].pEntity->Cast<Entity>(); } return nullptr; } Entity *DynamicWorld::GetEntityByID(uint32 EntityId) { DebugAssert(EntityId != 0); for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID == EntityId) return m_entities[i].pEntity->Cast<Entity>(); } return nullptr; } void DynamicWorld::AddEntity(Entity *pEntity) { DebugAssert(pEntity->GetEntityID() != 0); DebugAssert(GetEntityByID(pEntity->GetEntityID()) == nullptr); // add reference pEntity->AddRef(); // add to lookup list EntityData data; data.pEntity = pEntity; data.EntityID = pEntity->GetEntityID(); data.BoundingBox = pEntity->GetBoundingBox(); data.BoundingSphere = pEntity->GetBoundingSphere(); m_entities.Add(data); // invoke added function pEntity->OnAddToWorld(this); // update bounds m_worldBoundingBox.Merge(pEntity->GetBoundingBox()); m_worldBoundingSphere.Merge(pEntity->GetBoundingSphere()); } void DynamicWorld::MoveEntity(Entity *pEntity) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { EntityData &data = m_entities[i]; if (data.pEntity == pEntity) { data.BoundingBox = pEntity->GetBoundingBox(); data.BoundingSphere = pEntity->GetBoundingSphere(); m_worldBoundingBox.Merge(pEntity->GetBoundingBox()); m_worldBoundingSphere.Merge(pEntity->GetBoundingSphere()); return; } } Panic("attempted to move entity in world where it does not exist"); } void DynamicWorld::UpdateEntity(Entity *pEntity) { } void DynamicWorld::RemoveEntity(Entity *pEntity) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { EntityData &data = m_entities[i]; if (data.pEntity == pEntity) { // ensure it isn't active for (uint32 j = 0; j < m_activeEntities.GetSize(); j++) { if (m_activeEntities[j].pEntity == pEntity) { m_activeEntities.FastRemove(j); SortActiveEntities(); break; } } for (uint32 j = 0; j < m_activeAsyncEntities.GetSize(); j++) { if (m_activeAsyncEntities[j].pEntity == pEntity) { m_activeAsyncEntities.FastRemove(j); SortActiveAsyncEntities(); break; } } // ensure it isn't queued for removal for (uint32 j = 0; j < m_removeQueue.GetSize(); j++) { if (m_removeQueue[j] == pEntity) { m_removeQueue.FastRemove(j); break; } } // remove from list m_entities.FastRemove(i); // invoke removed function pEntity->OnRemoveFromWorld(this); // remove object pEntity->Release(); return; } } // should not get reached Panic("attempted to remove entity from world where it does not exist"); } void DynamicWorld::BeginFrame(float deltaTime) { World::BeginFrame(deltaTime); } void DynamicWorld::UpdateAsync(float deltaTime) { World::UpdateAsync(deltaTime); } void DynamicWorld::Update(float deltaTime) { World::Update(deltaTime); } void DynamicWorld::EndFrame() { World::EndFrame(); } <file_sep>/Engine/Source/Engine/Common.h #pragma once // profile setup // todo move this elsewhere.... // define to log loading times of resources #define PROFILE_RESOURCEMANAGER_LOAD_TIMES 1 // define to log texture upload times #define PROFILE_TEXTURE_UPLOAD_TIMES 1 // define to log compilation times of shaders #define PROFILE_SHADER_COMPILE_TIMES 1 // define to log terrain quadtree rebuild times #define PROFILE_TERRAIN_QUADTREE_REBUILD_TIMES 1 // BaseLib includes #include "YBaseLib/Assert.h" #include "YBaseLib/Memory.h" #include "YBaseLib/CString.h" #include "YBaseLib/NameTable.h" #include "YBaseLib/Timer.h" #include "YBaseLib/Pair.h" #include "YBaseLib/KeyValuePair.h" #include "YBaseLib/Array.h" #include "YBaseLib/MemArray.h" #include "YBaseLib/AlignedMemArray.h" #include "YBaseLib/PODArray.h" #include "YBaseLib/String.h" #include "YBaseLib/ReferenceCounted.h" #include "YBaseLib/ReferenceCountedHolder.h" #include "YBaseLib/AutoReleasePtr.h" #include "YBaseLib/NonCopyable.h" #include "YBaseLib/LinkedList.h" #include "YBaseLib/HashTable.h" #include "YBaseLib/CIStringHashTable.h" #include "YBaseLib/BinaryReader.h" #include "YBaseLib/BinaryWriter.h" #include "YBaseLib/TextReader.h" #include "YBaseLib/TextWriter.h" #include "YBaseLib/Singleton.h" #include "YBaseLib/StringConverter.h" #include "YBaseLib/Thread.h" #include "YBaseLib/Mutex.h" #include "YBaseLib/MutexLock.h" #include "YBaseLib/RecursiveMutex.h" #include "YBaseLib/RecursiveMutexLock.h" #include "YBaseLib/ReadWriteLock.h" #include "YBaseLib/Barrier.h" #include "YBaseLib/ThreadPool.h" #include "YBaseLib/Timestamp.h" #include "YBaseLib/BinaryBlob.h" #include "YBaseLib/Log.h" #include "YBaseLib/Functor.h" #include "YBaseLib/ProgressCallbacks.h" #include "YBaseLib/Platform.h" #include "YBaseLib/FileSystem.h" #include "YBaseLib/BitSet.h" // MathLib includes #include "MathLib/AABox.h" #include "MathLib/Sphere.h" #include "MathLib/Vectorh.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #include "MathLib/Matrixf.h" #include "MathLib/SIMDVectorf.h" #include "MathLib/SIMDVectori.h" #include "MathLib/SIMDMatrixf.h" #include "MathLib/SIMDMatrixi.h" #include "MathLib/Ray.h" #include "MathLib/Plane.h" #include "MathLib/Quaternion.h" #include "MathLib/Frustum.h" #include "MathLib/Transform.h" #include "MathLib/Interpolator.h" #include "MathLib/StreamOperators.h" #include "MathLib/StringConverters.h" #include "MathLib/HashTraits.h" // Core includes #include "Core/Property.h" #include "Core/PixelFormat.h" #include "Core/Console.h" #include "Core/VirtualFileSystem.h" #include "Core/Object.h" #include "Core/Resource.h" // Alias mathlib types, temporary typedef Vector2f float2; typedef Vector3f float3; typedef Vector4f float4; typedef Vector2i int2; typedef Vector3i int3; typedef Vector4i int4; typedef Vector2u uint2; typedef Vector3u uint3; typedef Vector4u uint4; typedef Matrix3x3f float3x3; typedef Matrix3x4f float3x4; typedef Matrix4x4f float4x4; // Alias in stringconverter namespace StringConverter { static inline float2 StringToFloat2(const char *Source) { return StringToVector2f(Source); } static inline float3 StringToFloat3(const char *Source) { return StringToVector3f(Source); } static inline float4 StringToFloat4(const char *Source) { return StringToVector4f(Source); } static inline void Float2ToString(String &Destination, const float2 &Source) { return Vector2fToString(Destination, Source); } static inline void Float3ToString(String &Destination, const float3 &Source) { return Vector3fToString(Destination, Source); } static inline void Float4ToString(String &Destination, const float4 &Source) { return Vector4fToString(Destination, Source); } static inline int2 StringToInt2(const char *Source) { return StringToVector2i(Source); } static inline int3 StringToInt3(const char *Source) { return StringToVector3i(Source); } static inline int4 StringToInt4(const char *Source) { return StringToVector4i(Source); } static inline uint2 StringToUInt2(const char *Source) { return StringToVector2u(Source); } static inline uint3 StringToUInt3(const char *Source) { return StringToVector3u(Source); } static inline uint4 StringToUInt4(const char *Source) { return StringToVector4u(Source); } static inline void Int2ToString(String &Destination, const int2 &Source) { return Vector2iToString(Destination, Source); } static inline void Int3ToString(String &Destination, const int3 &Source) { return Vector3iToString(Destination, Source); } static inline void Int4ToString(String &Destination, const int4 &Source) { return Vector4iToString(Destination, Source); } static inline void UInt2ToString(String &Destination, const uint2 &Source) { return Vector2uToString(Destination, Source); } static inline void UInt3ToString(String &Destination, const uint3 &Source) { return Vector3uToString(Destination, Source); } static inline void UInt4ToString(String &Destination, const uint4 &Source) { return Vector4uToString(Destination, Source); } static inline TinyString Float2ToString(const float2 &Source) { return Vector2fToString(Source); } static inline TinyString Float3ToString(const float3 &Source) { return Vector3fToString(Source); } static inline TinyString Float4ToString(const float4 &Source) { return Vector4fToString(Source); } static inline TinyString Int2ToString(const int2 &Source) { return Vector2iToString(Source); } static inline TinyString Int3ToString(const int3 &Source) { return Vector3iToString(Source); } static inline TinyString Int4ToString(const int4 &Source) { return Vector4iToString(Source); } static inline TinyString UInt2ToString(const uint2 &Source) { return Vector2uToString(Source); } static inline TinyString UInt3ToString(const uint3 &Source) { return Vector3uToString(Source); } static inline TinyString UInt4ToString(const uint4 &Source) { return Vector4uToString(Source); } } // engine common includes #include "Engine/Defines.h" <file_sep>/Engine/Source/ContentConverter/AssimpSkeletalAnimationImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpSkeletalAnimationImporter.h" #include "ContentConverter/AssimpSkeletonImporter.h" #include "ContentConverter/AssimpCommon.h" #include "ResourceCompiler/SkeletalAnimationGenerator.h" using AssimpHelpers::AssimpVector3ToFloat3; using AssimpHelpers::AssimpQuaternionToQuaternion; AssimpSkeletalAnimationImporter::AssimpSkeletalAnimationImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(NULL), m_pLogStream(NULL), m_pScene(NULL) { } AssimpSkeletalAnimationImporter::~AssimpSkeletalAnimationImporter() { delete m_pLogStream; delete m_pImporter; } void AssimpSkeletalAnimationImporter::SetDefaultOptions(Options *pOptions) { pOptions->CreateSkeleton = false; pOptions->ListOnly = false; pOptions->DefaultAnimationTicksPerSecond = 30.0f; pOptions->OverrideTicksPerSecond = 0.0f; pOptions->AllAnimations = false; pOptions->ClipAnimation = false; pOptions->ClipRangeStart = 0; pOptions->ClipRangeEnd = 0; pOptions->OptimizeAnimation = false; } bool AssimpSkeletalAnimationImporter::Execute() { Timer timer; m_pProgressCallbacks->SetProgressValue(0); m_pProgressCallbacks->SetProgressRange(2); if (m_pOptions->SourcePath.IsEmpty() || m_pOptions->OutputResourceName.IsEmpty() || (m_pOptions->ClipAnimation && (m_pOptions->ClipRangeStart < 1 || m_pOptions->ClipRangeStart > m_pOptions->ClipRangeEnd))) { m_pProgressCallbacks->ModalError("Missing parameters"); return false; } // ensure assimp is initialized if (!AssimpHelpers::InitializeAssimp()) { m_pProgressCallbacks->ModalError("assimp initialization failed"); return false; } m_pProgressCallbacks->PushState(); timer.Reset(); if (!LoadScene()) { m_pProgressCallbacks->ModalError("LoadScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("LoadScene(): %.4f ms", timer.GetTimeMilliseconds()); m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(1); ListAnimations(); if (m_pOptions->ListOnly) return true; if (m_pOptions->CreateSkeleton) { timer.Reset(); if (!CreateSkeleton()) { m_pProgressCallbacks->ModalError("CreateSkeleton() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateSkeleton(): %.4f ms", timer.GetTimeMilliseconds()); } m_pProgressCallbacks->PushState(); timer.Reset(); if (!CreateAnimations()) { m_pProgressCallbacks->ModalError("CreateAnimations() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateAnimations(): %.4f ms", timer.GetTimeMilliseconds()); m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(2); return true; } bool AssimpSkeletalAnimationImporter::CreateSkeleton() { String skeletonName = m_pOptions->SkeletonName; if (skeletonName.IsEmpty()) { skeletonName = m_pOptions->OutputResourceName; m_pProgressCallbacks->DisplayFormattedError("Skeleton name not provided, using '%s'", skeletonName.GetCharArray()); } AssimpSkeletonImporter::Options skeletonImportOptions; skeletonImportOptions.SourcePath = m_pOptions->SourcePath; skeletonImportOptions.OutputResourceName = skeletonName; AssimpSkeletonImporter skeletonImporter(&skeletonImportOptions, m_pProgressCallbacks); m_pProgressCallbacks->DisplayFormattedInformation("Importing skeleton from '%s' to '%s'", m_pOptions->SourcePath.GetCharArray(), skeletonName.GetCharArray()); if (!skeletonImporter.Execute()) { m_pProgressCallbacks->DisplayError("Skeleton import failed."); return false; } return true; } bool AssimpSkeletalAnimationImporter::LoadScene() { m_pProgressCallbacks->SetStatusText("Loading scene..."); // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // get post process flags uint32 postProcessFlags = AssimpHelpers::GetAssimpSkeletalAnimationImportPostProcessingFlags(); // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(postProcessFlags); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } void AssimpSkeletalAnimationImporter::ListAnimations() { for (uint32 i = 0; i < m_pScene->mNumAnimations; i++) { const aiAnimation *pAnimation = m_pScene->mAnimations[i]; m_pProgressCallbacks->DisplayFormattedInformation("Animation '%s': %u channels/bones, %.2f TPS, %.2f duration (%.2f frames)", pAnimation->mName.C_Str(), pAnimation->mNumChannels, pAnimation->mTicksPerSecond, pAnimation->mDuration, pAnimation->mDuration / ((pAnimation->mTicksPerSecond != 0.0f) ? pAnimation->mTicksPerSecond : (double)1.0f)); } } bool AssimpSkeletalAnimationImporter::CreateAnimations() { m_pProgressCallbacks->SetStatusText("Creating animations..."); m_pProgressCallbacks->SetProgressRange((m_pOptions->AllAnimations) ? (uint32)m_pScene->mNumAnimations : (uint32)1); m_pProgressCallbacks->SetProgressValue(0); for (uint32 i = 0; i < m_pScene->mNumAnimations; i++) { const aiAnimation *pAnimation = m_pScene->mAnimations[i]; if (!m_pOptions->AllAnimations) { // use filter name? if (m_pOptions->SingleAnimationName.GetLength() > 0) { if (!m_pOptions->SingleAnimationName.CompareInsensitive(pAnimation->mName.C_Str())) continue; } // convert this animation to the output name return ParseAnimation(pAnimation, m_pOptions->OutputResourceName, m_pOptions->ClipAnimation, m_pOptions->ClipRangeStart, m_pOptions->ClipRangeEnd); } // importing all animations // generate the animation name SmallString cleanedResourceName; if (pAnimation->mName.length == 0) { // auto-generate name cleanedResourceName.Format("animation%u", i); } else { // use name cleanedResourceName.AppendString(pAnimation->mName.C_Str()); FileSystem::SanitizeFileName(cleanedResourceName); } // generate resource name String outputResourceName; outputResourceName.Format("%s/%s%s", m_pOptions->OutputResourceDirectory.GetCharArray(), m_pOptions->OutputResourcePrefix.GetCharArray(), cleanedResourceName.GetCharArray()); // parse it if (!ParseAnimation(m_pScene->mAnimations[i], outputResourceName, m_pOptions->ClipAnimation, m_pOptions->ClipRangeStart, m_pOptions->ClipRangeEnd)) return false; m_pProgressCallbacks->SetProgressValue(i); } return true; } static aiVector3D FindAndInterpolateBoneVector(const double t, const aiVectorKey *pKeys, uint32 nKeys) { DebugAssert(nKeys > 0); if (nKeys == 1) { // use first and only position return pKeys[0].mValue; } // find the key that we reside in with a time of <= t uint32 keyIndex; for (keyIndex = 0; keyIndex < (nKeys - 1); keyIndex++) { if (t < pKeys[keyIndex + 1].mTime) break; } // is this the last key? uint32 nextKeyIndex = keyIndex + 1; if (nextKeyIndex == nKeys) { // use this (last) key return pKeys[keyIndex].mValue; } // this case can happen when t is less than the first key if (t < pKeys[keyIndex].mTime) { // just use the first key return pKeys[keyIndex].mValue; } // get factor const double thisKeyTime = pKeys[keyIndex].mTime; const aiVector3D &thisKeyValue = pKeys[keyIndex].mValue; const double nextKeyTime = pKeys[nextKeyIndex].mTime; const aiVector3D &nextKeyValue = pKeys[nextKeyIndex].mValue; const double factor = (t - thisKeyTime) / (nextKeyTime - thisKeyTime); DebugAssert(factor >= 0.0 && factor <= 1.0); // factor == 0 or 1? if (Math::NearEqual(factor, 0.0, (double)Y_FLT_EPSILON)) return thisKeyValue; else if (Math::NearEqual(factor, 1.0, (double)Y_FLT_EPSILON)) return nextKeyValue; // interpolate between the two return thisKeyValue + ((nextKeyValue - thisKeyValue) * (float)factor); } static aiQuaternion FindAndInterpolateBoneQuaternion(const double t, const aiQuatKey *pKeys, uint32 nKeys) { DebugAssert(nKeys > 0); if (nKeys == 1) { // use first and only position return pKeys[0].mValue; } // find the key that we reside in with a time of <= t uint32 keyIndex; for (keyIndex = 0; keyIndex < (nKeys - 1); keyIndex++) { if (t < pKeys[keyIndex + 1].mTime) break; } // is this the last key? uint32 nextKeyIndex = keyIndex + 1; if (nextKeyIndex == nKeys) { // use this (last) key return pKeys[keyIndex].mValue; } // this case can happen when t is less than the first key if (t < pKeys[keyIndex].mTime) { // just use the first key return pKeys[keyIndex].mValue; } // get factor const double thisKeyTime = pKeys[keyIndex].mTime; const aiQuaternion &thisKeyValue = pKeys[keyIndex].mValue; const double nextKeyTime = pKeys[nextKeyIndex].mTime; const aiQuaternion &nextKeyValue = pKeys[nextKeyIndex].mValue; const double factor = (t - thisKeyTime) / (nextKeyTime - thisKeyTime); DebugAssert(factor >= 0.0 && factor <= 1.0); // factor == 0 or 1? if (Math::NearEqual(factor, 0.0, (double)Y_FLT_EPSILON)) return thisKeyValue; else if (Math::NearEqual(factor, 1.0, (double)Y_FLT_EPSILON)) return nextKeyValue; // interpolate between the two aiQuaternion interpolatedRotation; aiQuaternion::Interpolate(interpolatedRotation, thisKeyValue, nextKeyValue, (float)factor); return interpolatedRotation.Normalize(); } bool AssimpSkeletalAnimationImporter::ParseAnimation(const aiAnimation *pAnimation, const char *outputResourceName, bool clipAnimation /* = false */, uint32 clipKeyFrameStart /* = 0 */, uint32 clipKeyFrameEnd /* = 0 */) { // get duration in ticks double animationDurationInTicks = pAnimation->mDuration; double animationTicksPerSecond = (pAnimation->mTicksPerSecond <= 0.0) ? (double)m_pOptions->DefaultAnimationTicksPerSecond : pAnimation->mTicksPerSecond; if (m_pOptions->OverrideTicksPerSecond > 0.0f) animationTicksPerSecond = (double)m_pOptions->OverrideTicksPerSecond; // determine the number of frames to be generated //double animationFramesGeneratedF = animationDurationInTicks / animationTicksPerSecond; //uint32 maximumKeyFrameCount = (uint32)Math::Truncate((float)animationFramesGeneratedF); //if (!Math::NearEqual(Math::FractionalPart((float)animationFramesGeneratedF), 0.0f, Y_FLT_EPSILON)) //m_pProgressCallbacks->DisplayFormattedWarning("animation '%s' forms incomplete frame count (%f)", pAnimation->mName.C_Str(), animationFramesGeneratedF); // logging m_pProgressCallbacks->SetProgressRange(pAnimation->mNumChannels); m_pProgressCallbacks->SetProgressValue(0); m_pProgressCallbacks->DisplayFormattedInformation("animation '%s' has %u tracks in file", pAnimation->mName.C_Str(), pAnimation->mNumChannels); m_pProgressCallbacks->DisplayFormattedInformation("animation '%s' has a duration of %f ticks, or %f seconds", pAnimation->mName.C_Str(), animationDurationInTicks, animationDurationInTicks / animationTicksPerSecond); //m_pProgressCallbacks->DisplayFormattedInformation("animation '%s' will have a maximum of %u keyframes", pAnimation->mName.C_Str(), maximumKeyFrameCount); // create generator SkeletalAnimationGenerator animationGenerator; animationGenerator.SetSkeletonName(m_pOptions->SkeletonName); // create bone tracks for (uint32 channelIndex = 0; channelIndex < pAnimation->mNumChannels; channelIndex++) { const aiNodeAnim *pNodeAnim = pAnimation->mChannels[channelIndex]; // logging m_pProgressCallbacks->SetProgressValue(channelIndex); m_pProgressCallbacks->SetFormattedStatusText("Processing bone '%s'", pNodeAnim->mNodeName.C_Str()); // determine # of keyframes uint32 keyFrameCount = Max((uint32)pNodeAnim->mNumPositionKeys, Max((uint32)pNodeAnim->mNumRotationKeys, (uint32)pNodeAnim->mNumScalingKeys)); m_pProgressCallbacks->DisplayFormattedInformation("bone '%s' has %u keyframes in file", pNodeAnim->mNodeName.C_Str(), keyFrameCount); // shouldn't happen if (keyFrameCount == 0) { m_pProgressCallbacks->DisplayFormattedWarning("no key frames, ignoring channel"); continue; } // check for dupes, shouldn't happen if (animationGenerator.GetBoneTrackByName(pNodeAnim->mNodeName.C_Str()) != nullptr) { m_pProgressCallbacks->DisplayFormattedError("a track named '%s' already exists", pNodeAnim->mNodeName.C_Str()); continue; } // allocate track SkeletalAnimationGenerator::BoneTrack *boneTrack = new SkeletalAnimationGenerator::BoneTrack(pNodeAnim->mNodeName.C_Str()); // handle case where position count != rotation count != scale count if (keyFrameCount != pNodeAnim->mNumPositionKeys || keyFrameCount != pNodeAnim->mNumRotationKeys || pNodeAnim->mNumScalingKeys != keyFrameCount) m_pProgressCallbacks->DisplayFormattedWarning("position keys %u / rotation keys %u / scale keys %u - mismatched, interpolation will be performed", pNodeAnim->mNumPositionKeys, pNodeAnim->mNumRotationKeys, pNodeAnim->mNumScalingKeys); // handle case where the first timestamp is not zero double subtractTime = 0.0; if (pNodeAnim->mPositionKeys[0].mTime != 0.0) { subtractTime = Max(pNodeAnim->mPositionKeys[0].mTime, subtractTime); m_pProgressCallbacks->DisplayFormattedWarning("first position key has a nonzero time (%.3f), new subtract time = %.3f", pNodeAnim->mPositionKeys[0].mTime, subtractTime); } if (pNodeAnim->mRotationKeys[0].mTime != 0.0) { subtractTime = Max(pNodeAnim->mRotationKeys[0].mTime, subtractTime); m_pProgressCallbacks->DisplayFormattedWarning("first rotation key has a nonzero time (%.3f), new subtract time = %.3f", pNodeAnim->mRotationKeys[0].mTime, subtractTime); } if (pNodeAnim->mScalingKeys[0].mTime != 0.0) { subtractTime = Max(pNodeAnim->mScalingKeys[0].mTime, subtractTime); m_pProgressCallbacks->DisplayFormattedWarning("first scale key has a nonzero time (%.3f), new subtract time = %.3f", pNodeAnim->mScalingKeys[0].mTime, subtractTime); } // collect unique timestamps of keys PODArray<double> keyFrameTimeStamps; keyFrameTimeStamps.Reserve(keyFrameCount + 1); // ensure a zero key gets allocated keyFrameTimeStamps.Add(0.0); // for positions for (uint32 keyIndex = 0; keyIndex < pNodeAnim->mNumPositionKeys; keyIndex++) { double timeStamp = Max(pNodeAnim->mPositionKeys[keyIndex].mTime - subtractTime, 0.0); if (keyFrameTimeStamps.IndexOf(timeStamp) < 0) keyFrameTimeStamps.Add(timeStamp); } // for rotations for (uint32 keyIndex = 0; keyIndex < pNodeAnim->mNumRotationKeys; keyIndex++) { double timeStamp = Max(pNodeAnim->mRotationKeys[keyIndex].mTime - subtractTime, 0.0); if (keyFrameTimeStamps.IndexOf(timeStamp) < 0) keyFrameTimeStamps.Add(timeStamp); } // for scales for (uint32 keyIndex = 0; keyIndex < pNodeAnim->mNumScalingKeys; keyIndex++) { double timeStamp = Max(pNodeAnim->mScalingKeys[keyIndex].mTime - subtractTime, 0.0); if (keyFrameTimeStamps.IndexOf(timeStamp) < 0) keyFrameTimeStamps.Add(timeStamp); } // log the new key frame count keyFrameTimeStamps.SortCB([](double left, double right) { return (left < right) ? -1 : ((left > right) ? 1 : 0); }); m_pProgressCallbacks->DisplayFormattedInformation("after collection, keyframes %u -> %u, min %.2f, max %.2f", keyFrameCount, keyFrameTimeStamps.GetSize(), keyFrameTimeStamps[0], keyFrameTimeStamps[keyFrameTimeStamps.GetSize() - 1]); // create key frames for (uint32 keyFrameIndex = 0; keyFrameIndex < keyFrameTimeStamps.GetSize(); keyFrameIndex++) { // keyframe time in ticks double keyFrameTimeInTicks = keyFrameTimeStamps[keyFrameIndex]; // collect transform aiVector3D keyFramePosition(FindAndInterpolateBoneVector(keyFrameTimeInTicks + subtractTime, pNodeAnim->mPositionKeys, pNodeAnim->mNumPositionKeys)); aiQuaternion keyFrameRotation(FindAndInterpolateBoneQuaternion(keyFrameTimeInTicks + subtractTime, pNodeAnim->mRotationKeys, pNodeAnim->mNumRotationKeys)); aiVector3D keyFrameScale(FindAndInterpolateBoneVector(keyFrameTimeInTicks + subtractTime, pNodeAnim->mScalingKeys, pNodeAnim->mNumScalingKeys)); // find the time in seconds double keyFrameTimeInSeconds = keyFrameTimeInTicks / animationTicksPerSecond; // create key frame boneTrack->AddKeyFrame((float)keyFrameTimeInSeconds, AssimpVector3ToFloat3(keyFramePosition), AssimpQuaternionToQuaternion(keyFrameRotation), AssimpVector3ToFloat3(keyFrameScale)); } // clip the sequence if (clipAnimation) { // calculate clip time range float clipTimeStart = static_cast<float>(static_cast<double>(clipKeyFrameStart - 1) / animationTicksPerSecond); float clipTimeEnd = static_cast<float>(static_cast<double>(clipKeyFrameEnd - 1) / animationTicksPerSecond); boneTrack->ClipKeyFrames(clipTimeStart, clipTimeEnd); // logging m_pProgressCallbacks->DisplayFormattedInformation("channel '%s' clip range %.2f -> %.2f, %u -> %u keyframes", pNodeAnim->mNodeName.C_Str(), clipTimeStart, clipTimeEnd, keyFrameTimeStamps.GetSize(), boneTrack->GetKeyFrameCount()); // discard the track if it has no frames left if (boneTrack->GetKeyFrameCount() == 0) { m_pProgressCallbacks->DisplayFormattedWarning("discarding channel '%s' as it has no key frames after clipping", pNodeAnim->mNodeName.C_Str()); delete boneTrack; continue; } } // add the track animationGenerator.AddBoneTrack(boneTrack); } // optimize the sequence if (m_pOptions->OptimizeAnimation) { m_pProgressCallbacks->PushState(); animationGenerator.Optimize(true); m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(pAnimation->mNumChannels); } // if we didn't get any keyframes abort if (animationGenerator.GetBoneTrackCount() == 0) { m_pProgressCallbacks->DisplayFormattedError("animation '%s' produced no tracks", pAnimation->mName.C_Str()); return false; } m_pProgressCallbacks->SetStatusText("Writing animation..."); // output filename PathString outputResourceFileName; outputResourceFileName.Format("%s.ska.xml", outputResourceName); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputResourceFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not open file '%s'", outputResourceFileName.GetCharArray()); return false; } // save it if (!animationGenerator.SaveToXML(pStream)) { m_pProgressCallbacks->DisplayFormattedError("failed to save xml file '%s'", outputResourceFileName.GetCharArray()); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); return true; } <file_sep>/Engine/Source/Core/Image.h #pragma once #include "Core/Common.h" #include "Core/PixelFormat.h" enum IMAGE_RESIZE_FILTER { IMAGE_RESIZE_FILTER_BOX, IMAGE_RESIZE_FILTER_BILINEAR, IMAGE_RESIZE_FILTER_BICUBIC, IMAGE_RESIZE_FILTER_BSPLINE, IMAGE_RESIZE_FILTER_CATMULLROM, IMAGE_RESIZE_FILTER_LANCZOS3, IMAGE_RESIZE_FILTER_COUNT, }; namespace NameTables { Y_Declare_NameTable(ImageResizeFilter); } class Image { public: Image(); Image(const Image &copy); ~Image(); // Creates a new image with the specified pixel format and dimensions. void Create(PIXEL_FORMAT PixelFormat, uint32 uWidth, uint32 uHeight, uint32 uDepth); // Copies another image. void Copy(const Image &rCopy); bool CopyAndConvertPixelFormat(const Image &rCopy, PIXEL_FORMAT NewFormat); bool CopyAndResize(const Image &rCopy, IMAGE_RESIZE_FILTER resizeFilter, uint32 newWidth, uint32 newHeight, uint32 newDepth); // Resizes this image. bool Resize(IMAGE_RESIZE_FILTER resizeFilter, uint32 newWidth, uint32 newHeight, uint32 newDepth); // Flips the image. Cannot be used on compressed formats. bool FlipVertical(); bool FlipHorizontal(); // Copies part of the contents of another image to this image. bool Blit(uint32 dx, uint32 dy, const Image &sourceImage, uint32 sx, uint32 sy, uint32 width, uint32 height); // operations. these don't work on compressed formats. bool Pad(uint32 top, uint32 right, uint32 bottom, uint32 left, float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f); bool Clip(uint32 startX, uint32 startY, uint32 endX, uint32 endY); // Read/write pixels. bool ReadPixels(void *pBuffer, uint32 cbBuffer, uint32 x, uint32 y, uint32 width, uint32 height) const; bool WritePixels(const void *pBuffer, uint32 cbBuffer, uint32 x, uint32 y, uint32 width, uint32 height); // Retrieve information about the image. bool IsValidImage() const; PIXEL_FORMAT GetPixelFormat() const { return m_ePixelFormat; } uint32 GetWidth() const { return m_uWidth; } uint32 GetHeight() const { return m_uHeight; } uint32 GetDepth() const { return m_uDepth; } // Retrieves pointers to the image data for this image. uint32 GetDataSize() const { return m_uDataSize; } uint32 GetDataRowPitch() const { return m_uDataRowPitch; } uint32 GetDataSlicePitch() const { return m_uDataSlicePitch; } const byte *GetData() const { return m_pData; } byte *GetData() { return m_pData; } // Frees data associated with this image. void Delete(); // Converts the format of this image. bool ConvertPixelFormat(PIXEL_FORMAT NewFormat); // Changes the pixel format of this image without converting any data. Types must have identical bpp. bool SetPixelFormatWithoutConversion(PIXEL_FORMAT newFormat); // overloaded operators Image &operator=(const Image &copy); private: PIXEL_FORMAT m_ePixelFormat; uint32 m_uWidth; uint32 m_uHeight; uint32 m_uDepth; byte *m_pData; uint32 m_uDataSize; uint32 m_uDataRowPitch; uint32 m_uDataSlicePitch; }; <file_sep>/Engine/Source/ResourceCompiler/MaterialGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/MaterialGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/Engine.h" #include "Engine/Texture.h" #include "Engine/DataFormats.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(MaterialShaderGenerator); MaterialGenerator::MaterialGenerator() { } MaterialGenerator::~MaterialGenerator() { } void MaterialGenerator::Create(const char *ShaderName) { m_strShaderName = ShaderName; m_ShaderUniformParameters.Clear(); m_ShaderTextureParameters.Clear(); m_ShaderStaticSwitchParameters.Clear(); } void MaterialGenerator::CreateFromMaterial(const Material *pMaterial) { uint32 i; SmallString tempString; const MaterialShader *pMaterialShader = pMaterial->GetShader(); m_strShaderName = pMaterialShader->GetName(); m_ShaderUniformParameters.Clear(); m_ShaderTextureParameters.Clear(); m_ShaderStaticSwitchParameters.Clear(); for (i = 0; i < pMaterialShader->GetUniformParameterCount(); i++) { const MaterialShader::UniformParameter *pUniformParameter = pMaterialShader->GetUniformParameter(i); const MaterialShader::UniformParameter::Value *pValue = pMaterial->GetShaderUniformParameter(i); // check if default value if (Y_memcmp(pValue, &pUniformParameter->DefaultValue, sizeof(MaterialShader::UniformParameter::Value)) != 0) { // if not, add it ShaderParameterTypeToString(tempString, pUniformParameter->Type, reinterpret_cast<const void *>(pValue)); m_ShaderUniformParameters.Add(ShaderUniformParameter(pUniformParameter->Name, tempString)); } } for (i = 0; i < pMaterialShader->GetTextureParameterCount(); i++) { const MaterialShader::TextureParameter *pTextureParameter = pMaterialShader->GetTextureParameter(i); const MaterialShader::TextureParameter::Value *pValue = pMaterial->GetShaderTextureParameter(i); // check if default value if (pValue->pTexture != NULL) { bool isDefaultValue; if (pTextureParameter->DefaultValue.GetLength() == 0) isDefaultValue = (pValue->pTexture->GetName() != g_pEngine->GetDefaultTextureName(pTextureParameter->Type)); else isDefaultValue = (pValue->pTexture->GetName() != pTextureParameter->DefaultValue); if (!isDefaultValue) m_ShaderTextureParameters.Add(ShaderTextureParameter(pTextureParameter->Name, pValue->pTexture->GetName())); } } for (i = 0; i < pMaterialShader->GetStaticSwitchParameterCount(); i++) { const MaterialShader::StaticSwitchParameter *pStaticSwitchParameter = pMaterialShader->GetStaticSwitchParameter(i); const bool Value = pMaterial->GetShaderStaticSwitchParameter(i); if (Value != pStaticSwitchParameter->DefaultValue) m_ShaderStaticSwitchParameters.Add(ShaderStaticSwitchParameter(pStaticSwitchParameter->Name, Value)); } } bool MaterialGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { xmlReader.PrintError("failed to create XML reader"); return false; } // skip to correct node if (!xmlReader.SkipToElement("material")) { xmlReader.PrintError("failed to skip to material element"); return false; } // start parsing xml if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 materialSelection = xmlReader.Select("shader"); if (materialSelection < 0) return false; switch (materialSelection) { // shader case 0: { // read the name element const char *materialShaderName = xmlReader.FetchAttribute("name"); if (materialShaderName == NULL) { xmlReader.PrintError("material shader name not found"); return false; } // set name m_strShaderName = materialShaderName; // parse parameters if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 shaderSelection = xmlReader.Select("parameters"); if (shaderSelection < 0) return false; switch (shaderSelection) { // parameters case 0: { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 parametersSelection = xmlReader.Select("uniform|texture|staticswitch"); if (parametersSelection < 0) return false; switch (parametersSelection) { // uniform case 0: { const char *uniformName = xmlReader.FetchAttribute("name"); const char *uniformValue = xmlReader.FetchAttribute("value"); if (uniformName == NULL || uniformValue == NULL) { xmlReader.PrintError("incomplete uniform declaration"); return false; } int32 uniformIndex = FindShaderUniformParameter(uniformName); if (uniformIndex >= 0) { xmlReader.PrintWarning("duplicate declared uniform '%s'", uniformName); m_ShaderUniformParameters[uniformIndex].Value = uniformValue; } else { ShaderUniformParameter uniformParameter(uniformName, uniformValue); m_ShaderUniformParameters.Add(uniformParameter); } } break; // texture case 1: { const char *textureName = xmlReader.FetchAttribute("name"); const char *textureValue = xmlReader.FetchAttribute("value"); if (textureName == NULL || textureValue == NULL) { xmlReader.PrintError("incomplete texture declaration"); return false; } int32 textureIndex = FindShaderTextureParameter(textureName); if (textureIndex >= 0) { xmlReader.PrintWarning("duplicate declared texture '%s'", textureName); m_ShaderTextureParameters[textureIndex].Value = textureValue; } else { ShaderTextureParameter textureParameter(textureName, textureValue); m_ShaderTextureParameters.Add(textureParameter); } } break; // staticswitch case 2: { const char *staticSwitchName = xmlReader.FetchAttribute("name"); const char *staticSwitchValue = xmlReader.FetchAttribute("value"); if (staticSwitchName == NULL || staticSwitchValue == NULL) { xmlReader.PrintError("incomplete static switch declaration"); return false; } int32 staticSwitchIndex = FindShaderStaticSwitchParameter(staticSwitchName); if (staticSwitchIndex >= 0) { xmlReader.PrintWarning("duplicate declared static switch '%s'", staticSwitchName); m_ShaderStaticSwitchParameters[staticSwitchIndex].Value = StringConverter::StringToBool(staticSwitchValue); } else { ShaderStaticSwitchParameter staticSwitchParameter(staticSwitchName, StringConverter::StringToBool(staticSwitchValue)); m_ShaderStaticSwitchParameters.Add(staticSwitchParameter); } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "parameters") == 0); break; } else { UnreachableCode(); } } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "shader") == 0); break; } else { UnreachableCode(); } } } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "material") == 0); break; } } } if (m_strShaderName.GetLength() == 0) { Log_ErrorPrintf("Failed to load material '%s': No material shader defined.", FileName); return false; } return true; } bool MaterialGenerator::SaveToXML(ByteStream *pStream) { uint32 i; SmallString tempString; XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("material"); { xmlWriter.StartElement("shader"); xmlWriter.WriteAttribute("name", m_strShaderName.GetCharArray()); { xmlWriter.StartElement("parameters"); { for (i = 0; i < m_ShaderUniformParameters.GetSize(); i++) { const ShaderUniformParameter &uniformParameter = m_ShaderUniformParameters[i]; xmlWriter.StartElement("uniform"); xmlWriter.WriteAttribute("name", uniformParameter.Key); xmlWriter.WriteAttribute("value", uniformParameter.Value); xmlWriter.EndElement(); } for (i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { const ShaderTextureParameter &textureParameter = m_ShaderTextureParameters[i]; xmlWriter.StartElement("texture"); xmlWriter.WriteAttribute("name", textureParameter.Key); xmlWriter.WriteAttribute("value", textureParameter.Value); xmlWriter.EndElement(); } for (i = 0; i < m_ShaderStaticSwitchParameters.GetSize(); i++) { const ShaderStaticSwitchParameter &staticSwitchParameter = m_ShaderStaticSwitchParameters[i]; xmlWriter.StartElement("staticswitch"); xmlWriter.WriteAttribute("name", staticSwitchParameter.Key); StringConverter::BoolToString(tempString, staticSwitchParameter.Value); xmlWriter.WriteAttribute("value", tempString); xmlWriter.EndElement(); } } xmlWriter.EndElement(); } xmlWriter.EndElement(); } xmlWriter.EndElement(); bool errorState = xmlWriter.InErrorState(); xmlWriter.Close(); return !errorState; } int32 MaterialGenerator::FindShaderUniformParameter(const char *Name) { uint32 i; for (i = 0; i < m_ShaderUniformParameters.GetSize(); i++) { if (m_ShaderUniformParameters[i].Key.CompareInsensitive(Name)) return static_cast<int32>(i); } return -1; } int32 MaterialGenerator::FindShaderTextureParameter(const char *Name) { uint32 i; for (i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { if (m_ShaderTextureParameters[i].Key.CompareInsensitive(Name)) return static_cast<int32>(i); } return -1; } int32 MaterialGenerator::FindShaderStaticSwitchParameter(const char *Name) { uint32 i; for (i = 0; i < m_ShaderStaticSwitchParameters.GetSize(); i++) { if (m_ShaderStaticSwitchParameters[i].Key.CompareInsensitive(Name)) return static_cast<int32>(i); } return -1; } void MaterialGenerator::RemoveShaderUniformParameter(uint32 Index) { DebugAssert(Index < m_ShaderUniformParameters.GetSize()); m_ShaderUniformParameters.OrderedRemove(Index); } void MaterialGenerator::RemoveShaderTextureParameter(uint32 Index) { DebugAssert(Index < m_ShaderTextureParameters.GetSize()); m_ShaderTextureParameters.OrderedRemove(Index); } void MaterialGenerator::RemoveShaderStaticSwitchParameter(uint32 Index) { DebugAssert(Index < m_ShaderStaticSwitchParameters.GetSize()); m_ShaderStaticSwitchParameters.OrderedRemove(Index); } bool MaterialGenerator::RemoveShaderUniformParameterByName(const char *Name) { int32 Index = FindShaderUniformParameter(Name); if (Index < 0) return false; m_ShaderUniformParameters.OrderedRemove(static_cast<uint32>(Index)); return true; } bool MaterialGenerator::RemoveShaderTextureParameterByName(const char *Name) { int32 Index = FindShaderTextureParameter(Name); if (Index < 0) return false; m_ShaderTextureParameters.OrderedRemove(static_cast<uint32>(Index)); return true; } bool MaterialGenerator::RemoveShaderStaticSwitchParameterByName(const char *Name) { int32 Index = FindShaderStaticSwitchParameter(Name); if (Index < 0) return false; m_ShaderStaticSwitchParameters.OrderedRemove(static_cast<uint32>(Index)); return true; } void MaterialGenerator::SetShaderUniformParameter(uint32 Index, SHADER_PARAMETER_TYPE Type, const void *pNewValue) { DebugAssert(Index < m_ShaderUniformParameters.GetSize()); ShaderParameterTypeToString(m_ShaderUniformParameters[Index].Value, Type, pNewValue); } void MaterialGenerator::SetShaderUniformParameterString(uint32 Index, const char *NewValue) { DebugAssert(Index < m_ShaderUniformParameters.GetSize()); m_ShaderUniformParameters[Index].Value = NewValue; } void MaterialGenerator::SetShaderTextureParameter(uint32 Index, const Texture *pTexture) { DebugAssert(Index < m_ShaderTextureParameters.GetSize()); m_ShaderTextureParameters[Index].Value = pTexture->GetName(); } void MaterialGenerator::SetShaderTextureParameterString(uint32 Index, const char *NewTextureName) { DebugAssert(Index < m_ShaderTextureParameters.GetSize()); m_ShaderTextureParameters[Index].Value = NewTextureName; } void MaterialGenerator::SetShaderStaticSwitchParameter(uint32 Index, bool On) { DebugAssert(Index < m_ShaderStaticSwitchParameters.GetSize()); m_ShaderStaticSwitchParameters[Index].Value = On; } void MaterialGenerator::SetShaderUniformParameterByName(const char *Name, SHADER_PARAMETER_TYPE Type, const void *pNewValue) { int32 Index = FindShaderUniformParameter(Name); if (Index >= 0) { ShaderParameterTypeToString(m_ShaderUniformParameters[Index].Value, Type, pNewValue); } else { ShaderUniformParameter uniformParameter; uniformParameter.Key = Name; ShaderParameterTypeToString(uniformParameter.Value, Type, pNewValue); m_ShaderUniformParameters.Add(uniformParameter); } } void MaterialGenerator::SetShaderUniformParameterStringByName(const char *Name, const char *NewValue) { int32 Index = FindShaderUniformParameter(Name); if (Index >= 0) m_ShaderUniformParameters[Index].Value = NewValue; else m_ShaderUniformParameters.Add(ShaderUniformParameter(Name, NewValue)); } void MaterialGenerator::SetShaderTextureParameterByName(const char *Name, const Texture *pNewTexture) { int32 Index = FindShaderTextureParameter(Name); if (Index >= 0) m_ShaderTextureParameters[Index].Value = pNewTexture->GetName(); else m_ShaderTextureParameters.Add(ShaderTextureParameter(Name, pNewTexture->GetName())); } void MaterialGenerator::SetShaderTextureParameterStringByName(const char *Name, const char *NewTextureName) { int32 Index = FindShaderTextureParameter(Name); if (Index >= 0) m_ShaderTextureParameters[Index].Value = NewTextureName; else m_ShaderTextureParameters.Add(ShaderTextureParameter(Name, NewTextureName)); } void MaterialGenerator::SetShaderStaticSwitchParameterByName(const char *Name, bool On) { int32 Index = FindShaderStaticSwitchParameter(Name); if (Index >= 0) m_ShaderStaticSwitchParameters[Index].Value = On; else m_ShaderStaticSwitchParameters.Add(ShaderStaticSwitchParameter(Name, On)); } MaterialGenerator &MaterialGenerator::operator=(const MaterialGenerator &copyFrom) { m_strShaderName = copyFrom.m_strShaderName; m_ShaderUniformParameters = copyFrom.m_ShaderUniformParameters; m_ShaderTextureParameters = copyFrom.m_ShaderTextureParameters; m_ShaderStaticSwitchParameters = copyFrom.m_ShaderStaticSwitchParameters; return *this; } // Compiler bool MaterialGenerator::Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pOutputStream) { // Load the material we're using AutoReleasePtr<const MaterialShader> pMaterialShader = pCallbacks->GetCompiledMaterialShader(m_strShaderName); if (pMaterialShader == nullptr) { Log_ErrorPrintf("MaterialGenerator::Compile: Could not load MaterialShader '%s'", m_strShaderName.GetCharArray()); return false; } // Writes in binary BinaryWriter binaryWriter(pOutputStream); // Generate static switch mask. We should really compare against the material for this, due to ordering.. :S // But that would mean having a GetCompiledMaterialShader method.. or reloading the source.. ugh. uint32 staticSwitchMask = 0; for (uint32 i = 0; i < m_ShaderStaticSwitchParameters.GetSize(); i++) { if (m_ShaderStaticSwitchParameters[i].Value) { int32 index = pMaterialShader->FindStaticSwitchParameter(m_ShaderStaticSwitchParameters[i].Key); if (index >= 0) staticSwitchMask |= pMaterialShader->GetStaticSwitchParameter((uint32)index)->Mask; } } // Write header DF_MATERIAL_HEADER header; header.Magic = DF_MATERIAL_HEADER_MAGIC; header.HeaderSize = sizeof(header); header.ShaderNameLength = m_strShaderName.GetLength(); header.UniformParameterCount = pMaterialShader->GetUniformParameterCount(); header.TextureParameterCount = pMaterialShader->GetTextureParameterCount(); header.StaticSwitchMask = staticSwitchMask; binaryWriter.WriteBytes(&header, sizeof(header)); binaryWriter.WriteFixedString(m_strShaderName, header.ShaderNameLength); // Write uniforms - must follow shader ordering for (uint32 i = 0; i < pMaterialShader->GetUniformParameterCount(); i++) { const MaterialShader::UniformParameter *pShaderParameter = pMaterialShader->GetUniformParameter(i); // start with default value MaterialShader::UniformParameter::Value value; Y_memcpy(&value, &pShaderParameter->DefaultValue, sizeof(value)); // Find our version of it for (uint32 j = 0; j < m_ShaderUniformParameters.GetSize(); j++) { const ShaderUniformParameter &ourParameter = m_ShaderUniformParameters[j]; if (ourParameter.Key.CompareInsensitive(pShaderParameter->Name)) { // use this value instead ShaderParameterTypeFromString(pShaderParameter->Type, &value, ourParameter.Value); break; } } // Write it DF_MATERIAL_UNIFORM_PARAMETER outParameter; outParameter.UniformType = (uint32)pShaderParameter->Type; Y_memcpy(&outParameter.UniformValue, &value, sizeof(outParameter.UniformValue)); binaryWriter.WriteBytes(&outParameter, sizeof(outParameter)); } // Write textures for (uint32 i = 0; i < pMaterialShader->GetTextureParameterCount(); i++) { const MaterialShader::TextureParameter *pShaderParameter = pMaterialShader->GetTextureParameter(i); // start with default value String textureName = pShaderParameter->DefaultValue; // Find our version of it for (uint32 j = 0; j < m_ShaderTextureParameters.GetSize(); j++) { const ShaderTextureParameter &ourParameter = m_ShaderTextureParameters[j]; if (ourParameter.Key.CompareInsensitive(pShaderParameter->Name)) { // use this value instead textureName = ourParameter.Value; break; } } // Write it out DF_MATERIAL_TEXTURE_PARAMETER outParameter; outParameter.TextureNameLength = textureName.GetLength(); outParameter.TextureType = (uint32)pShaderParameter->Type; binaryWriter.WriteBytes(&outParameter, sizeof(outParameter)); binaryWriter.WriteFixedString(textureName, outParameter.TextureNameLength); } // Done return !binaryWriter.InErrorState(); } // Interface BinaryBlob *ResourceCompiler::CompileMaterial(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.mtl.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileMaterial: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); MaterialGenerator *pGenerator = new MaterialGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pCallbacks, pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Engine/ScriptObject.h #pragma once #include "Engine/Common.h" #include "Engine/ScriptObjectTypeInfo.h" class ScriptObject : public Object { DECLARE_SCRIPT_OBJECT_TYPEINFO(ScriptObject, Object); DECLARE_OBJECT_NO_FACTORY(ScriptObject); public: ScriptObject(const ScriptObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ScriptObject(); // Script object type info accessor const ScriptObjectTypeInfo *GetScriptObjectTypeInfo() const { return static_cast<const ScriptObjectTypeInfo *>(m_pObjectTypeInfo); } // Do we have a persistent script object reference? bool HasPersistentScriptObjectReference() const { return (m_persistentScriptObjectReference != INVALID_SCRIPT_REFERENCE); } // Gets the persistent script object reference, if it doesn't exist, allocates it. ScriptReferenceType GetPersistentScriptObjectReference() const; // Creates and initializes this object's script environment. bool CreateScriptObject(); // Creates and initializes this object's script environment, running the provided script. bool CreateScriptObject(const byte *pScript, uint32 scriptLength, const char *source = "text chunk"); // Creates and initializes this object's script environment, using an existing environment. bool CreateScriptObject(ScriptReferenceType environmentReference); // Method invoker inline ScriptCallResult CallScriptMethod(const char *methodName) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallObjectMethod(m_persistentScriptObjectReference, methodName, false) : ScriptCallResult_NoObject; } inline ScriptCallResult CallScriptMethodResults(const char *methodName) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallObjectMethod(m_persistentScriptObjectReference, methodName, true) : ScriptCallResult_NoObject; } template<typename... Args> inline ScriptCallResult CallScriptMethod(const char *methodName, Args... args) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallObjectMethod(m_persistentScriptObjectReference, methodName, args..., false) : ScriptCallResult_NoObject; } template<typename... Args> inline ScriptCallResult CallScriptMethodResults(const char *methodName, Args... args) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallObjectMethod(m_persistentScriptObjectReference, methodName, args..., true) : ScriptCallResult_NoObject; } // Threaded method invoker inline ScriptCallResult CallThreadedScriptMethod(ScriptThread **ppThread, const char *methodName) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallThreadedObjectMethod(ppThread, m_persistentScriptObjectReference, methodName, false) : ScriptCallResult_NoObject; } inline ScriptCallResult CallThreadedScriptMethodResults(ScriptThread **ppThread, const char *methodName) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallThreadedObjectMethod(ppThread, m_persistentScriptObjectReference, methodName, true) : ScriptCallResult_NoObject; } template<typename... Args> inline ScriptCallResult CallThreadedScriptMethod(ScriptThread **ppThread, const char *methodName, Args... args) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallThreadedObjectMethod(ppThread, m_persistentScriptObjectReference, methodName, args..., false) : ScriptCallResult_NoObject; } template<typename... Args> inline ScriptCallResult CallThreadedScriptMethodResults(ScriptThread **ppThread, const char *methodName, Args... args) { return (HasPersistentScriptObjectReference()) ? g_pScriptManager->CallThreadedObjectMethod(ppThread, m_persistentScriptObjectReference, methodName, args..., true) : ScriptCallResult_NoObject; } private: ScriptReferenceType m_persistentScriptObjectReference; }; <file_sep>/Engine/Source/Engine/Physics/PhysicsProxy.h #pragma once #include "Engine/Common.h" class btCollisionObject; namespace Physics { class PhysicsWorld; class PhysicsProxy : public ReferenceCounted { public: PhysicsProxy(uint32 entityID); virtual ~PhysicsProxy(); const uint32 GetEntityID() const { return m_entityID; } const AABox &GetBoundingBox() const { return m_boundingBox; } PhysicsWorld *GetPhysicsWorld() const { return m_pPhysicsWorld; } const bool IsInWorld() const { return (m_pPhysicsWorld != nullptr); } void SetEntityID(uint32 entityID) { m_entityID = entityID; } virtual void OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld); virtual void OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld); virtual void OnSynchronize(); // todo: test collision against another object protected: uint32 m_entityID; AABox m_boundingBox; PhysicsWorld *m_pPhysicsWorld; }; } // namespace Physics<file_sep>/Engine/Source/ContentConverter/TextureImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/TextureImporter.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "Engine/Common.h" #include "ResourceCompiler/TextureGenerator.h" TextureImporter::TextureImporter(ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(NULL), m_pGenerator(NULL) { } TextureImporter::~TextureImporter() { delete m_pGenerator; for (uint32 i = 0; i < m_sourceImages.GetSize(); i++) delete m_sourceImages[i]; } void TextureImporter::SetDefaultOptions(TextureImporterOptions *pOptions) { pOptions->AppendTexture = false; pOptions->RebuildTexture = false; pOptions->Type = TEXTURE_TYPE_2D; pOptions->Usage = TEXTURE_USAGE_NONE; pOptions->Filter = TEXTURE_FILTER_ANISOTROPIC; pOptions->AddressU = TEXTURE_ADDRESS_MODE_CLAMP; pOptions->AddressV = TEXTURE_ADDRESS_MODE_CLAMP; pOptions->AddressW = TEXTURE_ADDRESS_MODE_CLAMP; pOptions->ResizeWidth = 0; pOptions->ResizeHeight = 0; pOptions->ResizeFilter = IMAGE_RESIZE_FILTER_LANCZOS3; pOptions->GenerateMipMaps = true; pOptions->SourcePremultipliedAlpha = false; pOptions->EnablePremultipliedAlpha = true; pOptions->EnableTextureCompression = true; pOptions->OutputFormat = PIXEL_FORMAT_UNKNOWN; pOptions->Optimize = false; pOptions->Compile = false; } bool TextureImporter::HasTextureFileExtension(const char *fileName) { const char *extension = Y_strrchr(fileName, '.'); if (extension == NULL) return false; static const char *textureExtensions[] = { "bmp", "jpg", "jpeg", "png", "tga", "dds", }; // remove '.' extension++; // compare against known uint32 i; for (i = 0; i < countof(textureExtensions); i++) { if (Y_stricmp(extension, textureExtensions[i]) == 0) return true; } return false; } bool TextureImporter::Execute(const TextureImporterOptions *pOptions) { Timer timer; bool result = false; if ((!pOptions->RebuildTexture && pOptions->InputFileNames.GetSize() == 0) || (pOptions->InputMaskFileNames.GetSize() > 0 && pOptions->InputMaskFileNames.GetSize() != pOptions->InputFileNames.GetSize()) || pOptions->OutputName.IsEmpty()) { m_pProgressCallbacks->ModalError("One or more required parameters not set."); return false; } if ((pOptions->ResizeWidth == 0 && pOptions->ResizeHeight != 0) || (pOptions->ResizeWidth != 0 && pOptions->ResizeHeight == 0)) { m_pProgressCallbacks->ModalError("Invalid resize dimensions"); return false; } // store options m_pOptions = pOptions; if (!m_pOptions->RebuildTexture && !LoadSources()) { m_pProgressCallbacks->ModalError("LoadSources() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("LoadSources(): %.4f msec", timer.GetTimeMilliseconds()); if ((m_pOptions->AppendTexture | m_pOptions->RebuildTexture)) { timer.Reset(); if (!LoadGenerator()) { m_pProgressCallbacks->ModalError("LoadGenerator() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("LoadGenerator(): %.4f msec", timer.GetTimeMilliseconds()); timer.Reset(); if (m_pOptions->AppendTexture && !AppendImages()) { m_pProgressCallbacks->ModalError("AppendImages() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("AppendImages(): %.4f msec", timer.GetTimeMilliseconds()); } else { timer.Reset(); if (!CreateGenerator()) { m_pProgressCallbacks->ModalError("CreateGenerator() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("CreateGenerator(): %.4f msec", timer.GetTimeMilliseconds()); } timer.Reset(); if (!ResizeAndSetProperties()) { m_pProgressCallbacks->ModalError("ResizeAndSetProperties() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("ResizeAndSetProperties(): %.4f msec", timer.GetTimeMilliseconds()); timer.Reset(); if (m_pOptions->Optimize && !m_pGenerator->Optimize()) { m_pProgressCallbacks->ModalError("Optimize() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("Optimize(): %.4f msec", timer.GetTimeMilliseconds()); timer.Reset(); if (!WriteOutput()) { m_pProgressCallbacks->ModalError("WriteOutput() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("WriteOutput(): %.4f msec", timer.GetTimeMilliseconds()); timer.Reset(); if (m_pOptions->Compile && !WriteCompiledOutput()) { m_pProgressCallbacks->ModalError("WriteCompiledOutput() failed. The log may have more information."); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("WriteCompiledOutput(): %.4f msec", timer.GetTimeMilliseconds()); // flag success result = true; EXIT: m_pOptions = NULL; delete m_pGenerator; m_pGenerator = NULL; for (uint32 i = 0; i < m_sourceImages.GetSize();i++) delete m_sourceImages[i]; m_sourceImages.Clear(); return result; } bool TextureImporter::LoadSources() { PathString osFileName; for (uint32 i = 0; i < m_pOptions->InputFileNames.GetSize(); i++) { FileSystem::CanonicalizePath(osFileName, m_pOptions->InputFileNames[i], true); ByteStream *pStream = FileSystem::OpenFile(osFileName, BYTESTREAM_OPEN_READ); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Failed to open file '%s'", osFileName.GetCharArray()); return false; } ImageCodec *pImageCodec = ImageCodec::GetImageCodecForStream(osFileName, pStream); if (pImageCodec == NULL) { m_pProgressCallbacks->DisplayFormattedError("Failed to find codec for '%s'", osFileName.GetCharArray()); return false; } Image *pSourceImage = new Image(); if (!pImageCodec->DecodeImage(pSourceImage, osFileName, pStream)) { m_pProgressCallbacks->DisplayFormattedError("Failed to decode image '%s'", osFileName.GetCharArray()); delete pSourceImage; return false; } m_pProgressCallbacks->DisplayFormattedInformation("Source loaded: %u x %u x %u [%s]", pSourceImage->GetWidth(), pSourceImage->GetHeight(), pSourceImage->GetDepth(), NameTable_GetNameString(NameTables::PixelFormat, pSourceImage->GetPixelFormat())); pStream->Release(); // uncompress it const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pSourceImage->GetPixelFormat()); if (pPixelFormatInfo->IsBlockCompressed) { m_pProgressCallbacks->DisplayFormattedInformation("Decompressing image from %s to %s", pPixelFormatInfo->Name, PixelFormat_GetPixelFormatInfo(pPixelFormatInfo->UncompressedFormat)->Name); if (!pSourceImage->ConvertPixelFormat(pPixelFormatInfo->UncompressedFormat)) { m_pProgressCallbacks->DisplayFormattedError("Failed to decompress image.", m_pOptions->InputFileNames[i].GetCharArray()); delete pSourceImage; return false; } } if (i > 0 && pSourceImage->GetPixelFormat() != m_sourceImages[0]->GetPixelFormat() && !pSourceImage->ConvertPixelFormat(m_sourceImages[0]->GetPixelFormat())) { m_pProgressCallbacks->DisplayFormattedError("Failed to convert '%s' to common pixel format.", m_pOptions->InputFileNames[i].GetCharArray()); delete pSourceImage; return false; } if (m_pOptions->InputMaskFileNames.GetSize() > 0) { DebugAssert(i < m_pOptions->InputMaskFileNames.GetSize()); FileSystem::CanonicalizePath(osFileName, m_pOptions->InputFileNames[i], true); m_pProgressCallbacks->DisplayFormattedInformation("Adding mask from file '%s'", osFileName.GetCharArray()); pStream = FileSystem::OpenFile(osFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Failed to open mask file '%s'", osFileName.GetCharArray()); delete pSourceImage; return false; } pImageCodec = ImageCodec::GetImageCodecForStream(osFileName, pStream); if (pImageCodec == NULL) { m_pProgressCallbacks->DisplayFormattedError("Failed to find codec for mask file '%s'", osFileName.GetCharArray()); pStream->Release(); delete pSourceImage; return false; } Image maskImage; if (!pImageCodec->DecodeImage(&maskImage, osFileName, pStream)) { m_pProgressCallbacks->DisplayFormattedError("Failed to decode mask file '%s'", osFileName.GetCharArray()); pStream->Release(); delete pSourceImage; return false; } const PIXEL_FORMAT_INFO *pMaskPixelFormatInfo = PixelFormat_GetPixelFormatInfo(maskImage.GetPixelFormat()); m_pProgressCallbacks->DisplayFormattedInformation("Loaded mask file '%s' (%ux%u %s)", osFileName.GetCharArray(), maskImage.GetWidth(), maskImage.GetHeight(), pMaskPixelFormatInfo->Name); pStream->Release(); if (maskImage.GetWidth() != pSourceImage->GetWidth() || maskImage.GetHeight() != pSourceImage->GetHeight()) { m_pProgressCallbacks->DisplayFormattedError("Mask image and source image size mismatch."); delete pSourceImage; return false; } // convert the input pixels to something useful if (!pSourceImage->ConvertPixelFormat(PIXEL_FORMAT_R8G8B8A8_UNORM)) { delete pSourceImage; return false; } // does it have alpha? if (pMaskPixelFormatInfo->HasAlpha) { // convert to something useful if (maskImage.GetPixelFormat() != PIXEL_FORMAT_R8G8B8A8_UNORM && !maskImage.ConvertPixelFormat(PIXEL_FORMAT_R8G8B8A8_UNORM)) { m_pProgressCallbacks->DisplayFormattedError("Failed to convert mask file to RGBA8 format"); delete pSourceImage; return false; } // take the alpha channel from each pixel of the mask and apply it to the source for (uint32 y = 0; y < pSourceImage->GetHeight(); y++) { const byte *pMaskPixels = maskImage.GetData() + (y * maskImage.GetDataRowPitch()); byte *pPixels = pSourceImage->GetData() + (y * pSourceImage->GetDataRowPitch()); for (uint32 x = 0; x < pSourceImage->GetWidth(); x++) { pPixels[3] = pMaskPixels[3]; pMaskPixels += 4; pPixels += 4; } } } else { // convert the image to R8 if (maskImage.GetPixelFormat() != PIXEL_FORMAT_R8_UNORM && !maskImage.ConvertPixelFormat(PIXEL_FORMAT_R8_UNORM)) { m_pProgressCallbacks->DisplayFormattedError("Failed to convert mask file to R8 format"); delete pSourceImage; return false; } // take the red channel from each pixel of the mask and apply it to the source's alpha channel for (uint32 y = 0; y < pSourceImage->GetHeight(); y++) { const byte *pMaskPixels = maskImage.GetData() + (y * maskImage.GetDataRowPitch()); byte *pPixels = pSourceImage->GetData() + (y * pSourceImage->GetDataRowPitch()); for (uint32 x = 0; x < pSourceImage->GetWidth(); x++) { pPixels[3] = pMaskPixels[0]; pMaskPixels++; pPixels += 4; } } } } m_sourceImages.Add(pSourceImage); } // handle resizes { bool differingSizes = false; for (uint32 i = 1; i < m_sourceImages.GetSize(); i++) { if (m_sourceImages[i]->GetWidth() != m_sourceImages[0]->GetWidth() || m_sourceImages[i]->GetHeight() != m_sourceImages[0]->GetHeight()) { differingSizes = true; break; } } if (differingSizes && m_pOptions->ResizeWidth) { m_pProgressCallbacks->DisplayFormattedError("Sizes differ between images and no resize dimensions were specified"); return false; } if (m_pOptions->ResizeWidth != 0) { for (uint32 i = 0; i < m_sourceImages.GetSize(); i++) { Image *pSourceImage = m_sourceImages[i]; if (!pSourceImage->Resize(m_pOptions->ResizeFilter, m_pOptions->ResizeWidth, m_pOptions->ResizeHeight, 1)) { m_pProgressCallbacks->DisplayFormattedError("Resize failed"); return false; } } } } return true; } bool TextureImporter::LoadGenerator() { PathString outputFileName; FileSystem::CanonicalizePath(outputFileName, m_pOptions->OutputName, true); outputFileName.AppendString(".tex.zip"); m_pProgressCallbacks->DisplayFormattedInformation("Loading texture: '%s'", outputFileName.GetCharArray()); ByteStream *pStream = FileSystem::OpenFile(outputFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Failed to open '%s'", outputFileName.GetCharArray()); return false; } m_pGenerator = new TextureGenerator(); if (!m_pGenerator->Load(outputFileName, pStream)) { pStream->Release(); m_pProgressCallbacks->DisplayFormattedError("Failed to load '%s'", outputFileName.GetCharArray()); return false; } pStream->Release(); return true; } bool TextureImporter::CreateGenerator() { TEXTURE_TYPE textureType = m_pOptions->Type; uint32 arraySize = 1; if (textureType == TEXTURE_TYPE_2D && m_sourceImages.GetSize() > 1) { m_pProgressCallbacks->DisplayFormattedInformation("Changing 2D texture to 2D array texture as there is more than one image"); textureType = TEXTURE_TYPE_2D_ARRAY; arraySize = m_sourceImages.GetSize(); } else if (textureType == TEXTURE_TYPE_2D_ARRAY) { // okay, nothing to do arraySize = m_sourceImages.GetSize(); } else if (textureType == TEXTURE_TYPE_CUBE) { if (m_sourceImages.GetSize() != 6) { m_pProgressCallbacks->DisplayFormattedError("Cube map textures must have 6 images"); return false; } arraySize = m_sourceImages.GetSize(); } else if (textureType == TEXTURE_TYPE_CUBE_ARRAY) { if ((m_sourceImages.GetSize() % 6) != 0) { m_pProgressCallbacks->DisplayFormattedError("Cube map textures must have a multiple of 6 images"); return false; } arraySize = m_sourceImages.GetSize(); } // create generator m_pGenerator = new TextureGenerator(); if (!m_pGenerator->Create(textureType, m_sourceImages[0]->GetPixelFormat(), m_sourceImages[0]->GetWidth(), m_sourceImages[0]->GetHeight(), m_sourceImages[0]->GetDepth(), arraySize, m_pOptions->Usage)) { m_pProgressCallbacks->DisplayFormattedError("Failed to create generator"); return false; } for (uint32 i = 0; i < m_sourceImages.GetSize(); i++) { m_pProgressCallbacks->DisplayFormattedInformation("setting image %u %ux%u %s", i, m_sourceImages[i]->GetWidth(), m_sourceImages[i]->GetHeight(), PixelFormat_GetPixelFormatInfo(m_sourceImages[i]->GetPixelFormat())->Name); if (!m_pGenerator->SetImage(i, m_sourceImages[i])) { m_pProgressCallbacks->DisplayFormattedError("Failed to set image %u in generator", i); return false; } } return true; } bool TextureImporter::AppendImages() { // resize to generator size for (uint32 i = 0; i < m_sourceImages.GetSize(); i++) { Image *pSourceImage = m_sourceImages[i]; m_pProgressCallbacks->DisplayFormattedInformation("Appending source image %u...", i); if (pSourceImage->GetPixelFormat() != m_pGenerator->GetPixelFormat()) { m_pProgressCallbacks->DisplayFormattedError("Failed to convert source image %u from %s to %s", i, PixelFormat_GetPixelFormatInfo(pSourceImage->GetPixelFormat())->Name, PixelFormat_GetPixelFormatInfo(m_pGenerator->GetPixelFormat())->Name); return false; } if ((pSourceImage->GetWidth() != m_pGenerator->GetWidth() || pSourceImage->GetHeight() != m_pGenerator->GetHeight()) && !pSourceImage->Resize(m_pOptions->ResizeFilter, m_pGenerator->GetWidth(), m_pGenerator->GetHeight(), 1)) { m_pProgressCallbacks->DisplayFormattedError("Failed to resize source image %u", i); return false; } if (!m_pGenerator->AddImage(pSourceImage)) { m_pProgressCallbacks->DisplayFormattedError("Failed to add source image %u", i); return false; } } return true; } bool TextureImporter::ResizeAndSetProperties() { // set properties m_pGenerator->SetTextureUsage(m_pOptions->Usage); m_pGenerator->SetTextureFilter(m_pOptions->Filter); m_pGenerator->SetTextureAddressModeU(m_pOptions->AddressU); m_pGenerator->SetTextureAddressModeV(m_pOptions->AddressV); m_pGenerator->SetTextureAddressModeW(m_pOptions->AddressW); m_pGenerator->SetMipMapResizeFilter(m_pOptions->ResizeFilter); m_pGenerator->SetGenerateMipmaps(m_pOptions->GenerateMipMaps); m_pGenerator->SetSourcePremultipliedAlpha(m_pOptions->SourcePremultipliedAlpha); m_pGenerator->SetEnablePremultipliedAlpha(m_pOptions->EnablePremultipliedAlpha); m_pGenerator->SetEnableTextureCompression(m_pOptions->EnableTextureCompression); // convert formats if (m_pOptions->OutputFormat != PIXEL_FORMAT_UNKNOWN) { if (!m_pGenerator->ConvertToPixelFormat(m_pOptions->OutputFormat)) { m_pProgressCallbacks->DisplayFormattedError("failed to convert to pixel format %s", PixelFormat_GetPixelFormatInfo(m_pOptions->OutputFormat)->Name); return false; } } // do resize if (m_pOptions->ResizeWidth != 0) { if (m_pGenerator->GetWidth() != m_pOptions->ResizeWidth || m_pGenerator->GetHeight() != m_pOptions->ResizeHeight) { m_pProgressCallbacks->DisplayFormattedInformation("Resizing to %u x %u", m_pOptions->ResizeWidth, m_pOptions->ResizeHeight); if (!m_pGenerator->Resize(m_pOptions->ResizeFilter, m_pOptions->ResizeWidth, m_pOptions->ResizeHeight, 1)) return false; } } return true; } bool TextureImporter::WriteOutput() { PathString outputFileName; FileSystem::CanonicalizePath(outputFileName, m_pOptions->OutputName, true); outputFileName.AppendString(".tex.zip"); m_pProgressCallbacks->DisplayFormattedInformation("Output filename: '%s'", outputFileName.GetCharArray()); ByteStream *pOutputStream; if ((pOutputStream = g_pVirtualFileSystem->OpenFile(outputFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE)) == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open output file '%s'", outputFileName.GetCharArray()); return false; } bool result = m_pGenerator->Save(pOutputStream); if (!result) pOutputStream->Discard(); else pOutputStream->Commit(); pOutputStream->Release(); return result; } bool TextureImporter::WriteCompiledOutput() { PathString outputFileName; FileSystem::CanonicalizePath(outputFileName, m_pOptions->OutputName, true); outputFileName.AppendString(".tex"); m_pProgressCallbacks->DisplayFormattedInformation("Compiled output filename: '%s'", outputFileName.GetCharArray()); ByteStream *pOutputStream; if ((pOutputStream = g_pVirtualFileSystem->OpenFile(outputFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE)) == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open output file '%s'", outputFileName.GetCharArray()); return false; } bool result = m_pGenerator->Compile(pOutputStream); if (!result) pOutputStream->Discard(); else pOutputStream->Commit(); pOutputStream->Release(); return result; } <file_sep>/Engine/Source/Engine/Physics/PhysicsWorld.h #pragma once #include "Engine/Common.h" #include "Engine/Physics/PhysicsProxy.h" class btCollisionObject; class btDiscreteDynamicsWorld; class btDefaultCollisionConfiguration; class btCollisionDispatcher; struct btDbvtBroadphase; class btSequentialImpulseConstraintSolver; class btGhostPairCallback; namespace Physics { class CollisionObject; class PhysicsWorld { public: PhysicsWorld(); ~PhysicsWorld(); // Gravity const float3 &GetGravity() const { return m_gravity; } void SetGravity(const float3 &gravity); // Bullet accessor const btDiscreteDynamicsWorld *GetBulletWorld() const { return m_pBulletWorld; } btDiscreteDynamicsWorld *GetBulletWorld() { return m_pBulletWorld; } // Object manipulation. void AddObject(PhysicsProxy *pPhysicsProxy); void RemoveObject(PhysicsProxy *pPhysicsProxy); void QueueObjectSynchronization(PhysicsProxy *pPhysicsProxy); // Runs a frame (allowed to be called asynchronously) // todo: split to async and sync parts void UpdateAsync(float timeSinceLastUpdate); void Update(float timeSinceLastUpdate); // Ray casting bool RayCast(const Ray &ray) const; bool RayCast(const Ray &ray, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const; // Reverse intersection functions // These test for a reverse (i.e. the object being tested colliding with us) bool TestAABoxIntersection(const AABox &box) const; bool TestAABoxIntersection(const AABox &box, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const; bool TestSphereIntersection(const Sphere &sphere) const; bool TestSphereIntersection(const Sphere &sphere, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const; //bool TestMovingSphereIntersection(const Sphere &) // sweep tests bool SweepBox(const float3 &boxHalfExtents, const float3 &from, const float3 &to, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint, float *pHitFraction) const; bool SweepSphere(const float radius, const float3 &from, const float3 &to, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint, float *pHitFraction) const; // Query functions template<typename T> void EnumerateCollisionObjects(T &Callback) { for (PhysicsProxy *pPhysicsProxy : m_collisionObjects) Callback(pPhysicsProxy); } template<typename T> void EnumerateCollisionObjects(T &Callback) const { for (const PhysicsProxy *pPhysicsProxy : m_collisionObjects) Callback(pPhysicsProxy); } // Finds objects inside the specified axis-aligned box. template<typename T> void EnumerateCollisionObjectsInAABox(const AABox &box, T &Callback) { for (PhysicsProxy *pPhysicsProxy : m_collisionObjects) { if (box.AABoxIntersection(pPhysicsProxy->GetBoundingBox())) Callback(pPhysicsProxy); } } template<typename T> void EnumerateCollisionObjectsInAABox(const AABox &box, T &Callback) const { for (const PhysicsProxy *pPhysicsProxy : m_collisionObjects) { if (box.AABoxIntersection(pPhysicsProxy->GetBoundingBox())) Callback(pPhysicsProxy); } } // apply a radial force void ApplyRadialForce(const float3 &center, float radius, float amount, float falloffRate); // change the aabb of a single object void UpdateSingleObject(CollisionObject *pCollisionObject); // wake objects when a static object changes within a bounding box void WakeObjectsInBox(const AABox &box); private: typedef LinkedList<PhysicsProxy *> CollisionObjectList; typedef PODArray<PhysicsProxy *> CollisionObjectArray; // gravity vector float3 m_gravity; // arrays CollisionObjectArray m_collisionObjects; //CollisionObjectArray m_addQueue; //CollisionObjectArray m_removeQueue; CollisionObjectArray m_synchronizationQueue; // Bullet world btDiscreteDynamicsWorld *m_pBulletWorld; btDefaultCollisionConfiguration *m_pBulletCollisionConfiguration; btCollisionDispatcher *m_pBulletCollisionDispatcher; btDbvtBroadphase *m_pBulletBroadphase; btSequentialImpulseConstraintSolver *m_pBulletSolver; btGhostPairCallback *m_pBulletGhostPairCallback; }; } // namespace Physics <file_sep>/Editor/Source/Editor/MapEditor/EditorMapEditMode.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapEditMode.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/EditorPropertyEditorWidget.h" #include "Editor/EditorHelpers.h" #include "Editor/ToolMenuWidget.h" #include "MapCompiler/MapSource.h" #include "ResourceCompiler/ObjectTemplate.h" Log_SetChannel(EditorMapEditMode); struct ui_EditorMapEditMode { QWidget *root; QAction *actionCheckMap; QAction *actionCompileMap; QAction *actionTestMap; QLabel *regionSize; QLabel *regionCount; QLabel *objectCount; QCheckBox *showSky; QCheckBox *showSun; QCheckBox *useTimeOfDay; QTimeEdit *timeOfDayStartTime; QTimeEdit *timeOfDayEndTime; QDoubleSpinBox *timeOfDayRate; void CreateUI(QWidget *parentWidget) { root = new QWidget(parentWidget); QVBoxLayout *rootLayout = new QVBoxLayout(root); rootLayout->setMargin(0); rootLayout->setSpacing(0); rootLayout->setContentsMargins(0, 0, 0, 0); // actions { actionCheckMap = new QAction(root->tr("Check Map"), root); actionCheckMap->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionCompileMap = new QAction(root->tr("Compile Map"), root); actionCompileMap->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionTestMap = new QAction(root->tr("Test Map"), root); actionTestMap->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); } // fixed toolbar { ToolMenuWidget *fixedToolMenu = new ToolMenuWidget(root); fixedToolMenu->addAction(actionCheckMap); fixedToolMenu->addAction(actionCompileMap); fixedToolMenu->addAction(actionTestMap); rootLayout->addWidget(fixedToolMenu); } // scrollable area { QScrollArea *scrollArea = new QScrollArea(root); QWidget *scrollAreaWidget = new QWidget(scrollArea); scrollArea->setBackgroundRole(QPalette::Background); scrollArea->setFrameStyle(0); scrollArea->setWidgetResizable(true); scrollArea->setWidget(scrollAreaWidget); QVBoxLayout *scrollAreaLayout = new QVBoxLayout(scrollArea); scrollAreaLayout->setMargin(0); scrollAreaLayout->setSpacing(2); scrollAreaLayout->setContentsMargins(0, 0, 0, 0); // summary { QGroupBox *summaryBox = new QGroupBox(root->tr("Summary"), scrollAreaWidget); QFormLayout *summaryLayout = new QFormLayout(summaryBox); regionSize = new QLabel(summaryBox); summaryLayout->addRow(root->tr("Region Size: "), regionSize); regionCount = new QLabel(summaryBox); summaryLayout->addRow(root->tr("Region Count: "), regionCount); objectCount = new QLabel(summaryBox); summaryLayout->addRow(root->tr("Object Count: "), objectCount); summaryBox->setLayout(summaryLayout); scrollAreaLayout->addWidget(summaryBox); } // shows { QGroupBox *showBox = new QGroupBox(root->tr("Visibility"), scrollAreaWidget); QFormLayout *showLayout = new QFormLayout(showBox); showSky = new QCheckBox(root->tr("Sky"), showBox); showLayout->addRow(showSky); showSun = new QCheckBox(root->tr("Sun"), showBox); showLayout->addRow(showSun); showBox->setLayout(showLayout); scrollAreaLayout->addWidget(showBox); } // time of day { QGroupBox *timeOfDayBox = new QGroupBox(root->tr("Time of Day"), scrollAreaWidget); QFormLayout *timeOfDayLayout = new QFormLayout(timeOfDayBox); timeOfDayLayout->setLabelAlignment(Qt::AlignTop); useTimeOfDay = new QCheckBox(root->tr("Enable time of day"), timeOfDayBox); timeOfDayLayout->addRow(useTimeOfDay); timeOfDayStartTime = new QTimeEdit(timeOfDayBox); timeOfDayLayout->addRow(root->tr("Start Time: "), timeOfDayStartTime); timeOfDayEndTime = new QTimeEdit(timeOfDayBox); timeOfDayLayout->addRow(root->tr("End Time: "), timeOfDayEndTime); timeOfDayRate = new QDoubleSpinBox(timeOfDayBox); timeOfDayLayout->addRow(root->tr("Time Rate: "), timeOfDayRate); timeOfDayBox->setLayout(timeOfDayLayout); scrollAreaLayout->addWidget(timeOfDayBox); } // use remaining space scrollAreaLayout->addStretch(1); // finalize scroll area scrollAreaWidget->setLayout(scrollAreaLayout); rootLayout->addWidget(scrollArea, 1); } root->setLayout(rootLayout); } }; QWidget *EditorMapEditMode::CreateUI(QWidget *pParentWidget) { DebugAssert(m_ui == nullptr); m_ui = new ui_EditorMapEditMode(); m_ui->CreateUI(pParentWidget); // bind events // update summary UpdateSummary(); return m_ui->root; } void EditorMapEditMode::OnUIShowSkyChanged(bool checked) { } void EditorMapEditMode::OnUIShowSunChanged(bool checked) { } EditorMapEditMode::EditorMapEditMode(EditorMap *pMap) : EditorEditMode(pMap), m_ui(nullptr) { } EditorMapEditMode::~EditorMapEditMode() { delete m_ui; } void EditorMapEditMode::UpdateSummary() { m_ui->regionSize->setText(ConvertStringToQString(TinyString::FromFormat("%u x %u units", m_pMap->GetMapSource()->GetRegionSize(), m_pMap->GetMapSource()->GetRegionSize()))); m_ui->regionCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(0))); m_ui->objectCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pMap->GetMapSource()->GetEntityCount()))); } void EditorMapEditMode::OnMapPropertyChanged(const char *propertyName, const char *propertyValue) { } bool EditorMapEditMode::Initialize(ProgressCallbacks *pProgressCallbacks) { if (!EditorEditMode::Initialize(pProgressCallbacks)) return false; return true; } void EditorMapEditMode::Activate() { EditorEditMode::Activate(); // initialize the property editor with the map properties EditorPropertyEditorWidget *propertyEditor = m_pMap->GetMapWindow()->GetPropertyEditorWidget(); DebugAssert(m_pMap->GetMapSource()->GetObjectTemplate() != nullptr); propertyEditor->AddPropertiesFromTemplate(m_pMap->GetMapSource()->GetObjectTemplate()->GetPropertyTemplate()); //propertyEditor->SetTitleText(m_pMap->GetMapSource()->GetObjectTemplate()->GetTypeName()); } void EditorMapEditMode::Deactivate() { EditorEditMode::Deactivate(); } void EditorMapEditMode::Update(const float timeSinceLastUpdate) { EditorEditMode::Update(timeSinceLastUpdate); } void EditorMapEditMode::OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) { // this must be a map property! update it in the map... m_pMap->SetMapProperty(propertyName, propertyValue); } void EditorMapEditMode::OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) { EditorEditMode::OnActiveViewportChanged(pOldActiveViewport, pNewActiveViewport); } bool EditorMapEditMode::HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) { return EditorEditMode::HandleViewportKeyboardInputEvent(pViewport, pKeyboardEvent); } bool EditorMapEditMode::HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) { return EditorEditMode::HandleViewportMouseInputEvent(pViewport, pMouseEvent); } bool EditorMapEditMode::HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) { return EditorEditMode::HandleViewportWheelInputEvent(pViewport, pWheelEvent); } void EditorMapEditMode::OnViewportDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterWorld(pViewport); } void EditorMapEditMode::OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawBeforeWorld(pViewport); } void EditorMapEditMode::OnViewportDrawAfterPost(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterPost(pViewport); } void EditorMapEditMode::OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawAfterWorld(pViewport); } void EditorMapEditMode::OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawBeforeWorld(pViewport); } <file_sep>/Engine/Source/ResourceCompiler/SkeletalMeshGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/SkeletalMeshGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "Engine/DataFormats.h" #include "Core/ChunkFileWriter.h" #include "Core/MeshUtilties.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(SkeletalMeshGenerator); static const uint32 MAX_BONES_PER_BATCH = 64; static const uint32 MAX_VERTICES_PER_BATCH = 0xFFFE; SkeletalMeshGenerator::SkeletalMeshGenerator() : m_provideVertexTextureCoordinates(false), m_provideVertexColors(false), m_pCollisionShapeGenerator(nullptr) { } SkeletalMeshGenerator::~SkeletalMeshGenerator() { delete m_pCollisionShapeGenerator; } const int32 SkeletalMeshGenerator::FindBoneIndexByName(const char *boneName) const { for (uint32 i = 0; i < m_bones.GetSize(); i++) { if (m_bones[i].Name.Compare(boneName)) return (int32)i; } return -1; } SkeletalMeshGenerator::Bone *SkeletalMeshGenerator::AddBone(const char *boneName, const Transform &localToBoneTransform) { Assert(FindBoneIndexByName(boneName) == -1); uint32 boneIndex = m_bones.GetSize(); m_bones.Add(Bone(boneIndex, boneName, localToBoneTransform)); return &m_bones[boneIndex]; } const int32 SkeletalMeshGenerator::FindMaterialNameIndex(const char *materialName) const { for (uint32 i = 0; i < m_materialNames.GetSize(); i++) { if (m_materialNames[i].Compare(materialName)) return (int32)i; } return -1; } const uint32 SkeletalMeshGenerator::AddMaterialName(const char *materialName) { for (uint32 i = 0; i < m_materialNames.GetSize(); i++) { if (m_materialNames[i].Compare(materialName)) return i; } uint32 materialNameIndex = m_materialNames.GetSize(); m_materialNames.Add(String(materialName)); return materialNameIndex; } uint32 SkeletalMeshGenerator::AddVertex(const Vertex &vertex) { for (uint32 i = 0; i < SKELETAL_MESH_MAX_BONES_PER_VERTEX; i++) { DebugAssert(vertex.BoneIndices[i] < 0 || (uint32)vertex.BoneIndices[i] < m_bones.GetSize()); } uint32 index = m_vertices.GetSize(); m_vertices.Add(vertex); return index; } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates) { return AddVertex(position, textureCoordinates, float3::UnitX, float3::UnitY, float3::UnitZ); } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &normal) { return AddVertex(position, textureCoordinates, float3::UnitX, float3::UnitY, normal); } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &tangent, const float3 &binormal, const float3 &normal) { Vertex vert; vert.Position = position; vert.TextureCoordinates = textureCoordinates; vert.Tangent = tangent; vert.Binormal = binormal; vert.Normal = normal; for (uint32 i = 0; i < SKELETAL_MESH_MAX_BONES_PER_VERTEX; i++) { vert.BoneIndices[i] = -1; vert.BoneWeights[i] = 0.0f; } uint32 index = m_vertices.GetSize(); m_vertices.Add(vert); return index; } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates, const int32 *pBoneIndices, const float *pBoneWeights) { return AddVertex(position, textureCoordinates, float3::UnitX, float3::UnitY, float3::UnitZ, pBoneIndices, pBoneWeights); } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &normal, const int32 *pBoneIndices, const float *pBoneWeights) { return AddVertex(position, textureCoordinates, float3::UnitX, float3::UnitY, normal, pBoneIndices, pBoneWeights); } uint32 SkeletalMeshGenerator::AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &tangent, const float3 &binormal, const float3 &normal, const int32 *pBoneIndices, const float *pBoneWeights) { Vertex vert; vert.Position = position; vert.TextureCoordinates = textureCoordinates; vert.Tangent = tangent; vert.Binormal = binormal; vert.Normal = normal; Y_memcpy(vert.BoneIndices, pBoneIndices, sizeof(vert.BoneIndices)); Y_memcpy(vert.BoneWeights, pBoneWeights, sizeof(vert.BoneWeights)); for (uint32 i = 0; i < SKELETAL_MESH_MAX_BONES_PER_VERTEX; i++) { DebugAssert(vert.BoneIndices[i] < 0 || (uint32)vert.BoneIndices[i] < m_bones.GetSize()); } uint32 index = m_vertices.GetSize(); m_vertices.Add(vert); return index; } uint32 SkeletalMeshGenerator::AddTriangle(uint32 materialNameIndex, uint64 smoothingGroups, uint32 v0, uint32 v1, uint32 v2) { DebugAssert(materialNameIndex < m_materialNames.GetSize()); Triangle tri; tri.MaterialIndex = materialNameIndex; tri.SmoothingGroups = smoothingGroups; tri.VertexIndices[0] = v0; tri.VertexIndices[1] = v1; tri.VertexIndices[2] = v2; uint32 index = m_triangles.GetSize(); m_triangles.Add(tri); return index; } uint32 SkeletalMeshGenerator::AddTriangle(uint32 materialNameIndex, uint64 smoothingGroups, const uint32 *pIndices) { DebugAssert(materialNameIndex < m_materialNames.GetSize()); Triangle tri; tri.MaterialIndex = materialNameIndex; tri.SmoothingGroups = smoothingGroups; Y_memcpy(tri.VertexIndices, pIndices, sizeof(uint32) * 3); uint32 index = m_triangles.GetSize(); m_triangles.Add(tri); return index; } void SkeletalMeshGenerator::CalculateTangentVectors() { // zero everything for (uint32 i = 0; i < m_vertices.GetSize(); i++) { Vertex &vertex = m_vertices[i]; vertex.Tangent.SetZero(); vertex.Binormal.SetZero(); } // build each triangle's tangent space // todo: smoothing groups for (uint32 i = 0; i < m_triangles.GetSize(); i++) { Triangle &tri = m_triangles[i]; Vertex &v0 = m_vertices[tri.VertexIndices[0]]; Vertex &v1 = m_vertices[tri.VertexIndices[1]]; Vertex &v2 = m_vertices[tri.VertexIndices[2]]; float3 tangent, binormal, normal; MeshUtilites::CalculateTangentSpaceVectors(v0.Position, v1.Position, v2.Position, v0.TextureCoordinates, v1.TextureCoordinates, v2.TextureCoordinates, tangent, binormal, normal); v0.Tangent += tangent; v0.Binormal += binormal; v1.Tangent += tangent; v1.Binormal += binormal; v2.Tangent += tangent; v2.Binormal += binormal; } // normalize everything for (uint32 i = 0; i < m_vertices.GetSize(); i++) { Vertex &vertex = m_vertices[i]; if (vertex.Tangent.SquaredLength() > 0.0f) vertex.Tangent.NormalizeInPlace(); if (vertex.Binormal.SquaredLength() > 0.0f) vertex.Binormal.NormalizeInPlace(); } } void SkeletalMeshGenerator::CalculateTangentVectorsAndNormals() { // zero everything for (uint32 i = 0; i < m_vertices.GetSize(); i++) { Vertex &vertex = m_vertices[i]; vertex.Tangent.SetZero(); vertex.Binormal.SetZero(); vertex.Normal.SetZero(); } // build each triangle's tangent space // todo: smoothing groups for (uint32 i = 0; i < m_triangles.GetSize(); i++) { Triangle &tri = m_triangles[i]; Vertex &v0 = m_vertices[tri.VertexIndices[0]]; Vertex &v1 = m_vertices[tri.VertexIndices[1]]; Vertex &v2 = m_vertices[tri.VertexIndices[2]]; float3 tangent, binormal, normal; MeshUtilites::CalculateTangentSpaceVectors(v0.Position, v1.Position, v2.Position, v0.TextureCoordinates, v1.TextureCoordinates, v2.TextureCoordinates, tangent, binormal, normal); v0.Tangent += tangent; v0.Binormal += binormal; v0.Normal += normal; v1.Tangent += tangent; v1.Binormal += binormal; v1.Normal += normal; v2.Tangent += tangent; v2.Binormal += binormal; v2.Normal += normal; } // normalize everything for (uint32 i = 0; i < m_vertices.GetSize(); i++) { Vertex &vertex = m_vertices[i]; if (vertex.Tangent.SquaredLength() > 0.0f) vertex.Tangent.NormalizeInPlace(); if (vertex.Binormal.SquaredLength() > 0.0f) vertex.Binormal.NormalizeInPlace(); if (vertex.Normal.SquaredLength() > 0.0f) vertex.Normal.NormalizeInPlace(); } } bool SkeletalMeshGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) return false; if (!xmlReader.SkipToElement("skeletal-mesh")) { xmlReader.PrintError("could not skip to skeletal-mesh element."); return false; } // process xml nodes for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 skeletalMeshSelection = xmlReader.Select("skeleton|flags|bones|vertices|triangles|collision-shape"); if (skeletalMeshSelection < 0) return false; switch (skeletalMeshSelection) { // skeleton case 0: { const char *nameStr = xmlReader.FetchAttribute("name"); if (nameStr == nullptr) { xmlReader.PrintError("missing name attribute"); return false; } m_skeletonName = nameStr; } break; // flags case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 flagsSelection = xmlReader.Select("vertex-colors|vertex-texture-coordinates"); if (flagsSelection < 0) return false; switch (flagsSelection) { // vertex-colors case 0: m_provideVertexColors = true; break; // vertex-texture-coordinates case 1: m_provideVertexTextureCoordinates = true; break; default: UnreachableCode(); break; } if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "flags") == 0); break; } else { UnreachableCode(); break; } } } } break; // bones case 2: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 bonesSelection = xmlReader.Select("bone"); if (bonesSelection < 0) return false; const char *boneNameStr = xmlReader.FetchAttribute("name"); const char *boneTransformPositionStr = xmlReader.FetchAttribute("transform-position"); const char *boneTransformRotationStr = xmlReader.FetchAttribute("transform-rotation"); const char *boneTransformScaleStr = xmlReader.FetchAttribute("transform-scale"); if (boneNameStr == NULL || boneTransformPositionStr == NULL || boneTransformRotationStr == NULL || boneTransformScaleStr == NULL) { xmlReader.PrintError("missing bone fields"); return false; } if (FindBoneIndexByName(boneNameStr) >= 0) { xmlReader.PrintError("duplicate bone '%s'", boneNameStr); return false; } float3 boneTransformPosition = StringConverter::StringToFloat3(boneTransformPositionStr); Quaternion boneTransformRotation = StringConverter::StringToQuaternion(boneTransformRotationStr); float3 boneTransformScale = StringConverter::StringToFloat3(boneTransformScaleStr); m_bones.Add(Bone(m_bones.GetSize(), boneNameStr, Transform(boneTransformPosition, boneTransformRotation, boneTransformScale))); if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "bones") == 0); break; } else { xmlReader.PrintError("parse error"); break; } } } } break; // vertices case 3: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 verticesSelection = xmlReader.Select("vertex"); if (verticesSelection < 0) return false; const char *vertexPositionStr = xmlReader.FetchAttribute("position"); const char *vertexTangentStr = xmlReader.FetchAttribute("tangent"); const char *vertexBinormalStr = xmlReader.FetchAttribute("binormal"); const char *vertexNormalStr = xmlReader.FetchAttribute("normal"); const char *vertexTextureCoordinatesStr = xmlReader.FetchAttribute("texture-coordinates"); const char *vertexColorStr = xmlReader.FetchAttribute("color"); if (vertexPositionStr == nullptr || vertexTangentStr == nullptr || vertexBinormalStr == nullptr || vertexNormalStr == nullptr || vertexTextureCoordinatesStr == nullptr || vertexColorStr == nullptr) { xmlReader.PrintError("missing attributes"); return false; } // create vertex Vertex vert; vert.Position = StringConverter::StringToFloat3(vertexPositionStr); vert.Tangent = StringConverter::StringToFloat3(vertexTangentStr); vert.Binormal = StringConverter::StringToFloat3(vertexBinormalStr); vert.Normal = StringConverter::StringToFloat3(vertexNormalStr); vert.TextureCoordinates = StringConverter::StringToFloat2(vertexTextureCoordinatesStr); vert.Color = StringConverter::StringToColor(vertexColorStr); Y_memset(vert.BoneIndices, (byte)-1, sizeof(vert.BoneIndices)); Y_memzero(vert.BoneWeights, sizeof(vert.BoneWeights)); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 vertexSelection = xmlReader.Select("weight"); if (vertexSelection < 0) return false; switch (vertexSelection) { // weight case 0: { const char *boneStr = xmlReader.FetchAttribute("bone"); const char *weightStr = xmlReader.FetchAttribute("weight"); if (boneStr == nullptr || weightStr == nullptr) { xmlReader.PrintError("missing attributes"); return false; } // find free index uint32 weightIndex = 0; for (; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { if (vert.BoneIndices[weightIndex] == -1) break; } if (weightIndex == SKELETAL_MESH_MAX_BONES_PER_VERTEX) { xmlReader.PrintError("too many weights"); return false; } // check bone index int32 boneIndex = FindBoneIndexByName(boneStr); if (boneIndex < 0) { xmlReader.PrintError("unknown bone"); return false; } vert.BoneIndices[weightIndex] = boneIndex; vert.BoneWeights[weightIndex] = StringConverter::StringToFloat(weightStr); if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "vertex") == 0); break; } else { UnreachableCode(); break; } } } // check the sum equals one float weightSum = 0.0f; for (uint32 i = 0; i < SKELETAL_MESH_MAX_BONES_PER_VERTEX; i++) weightSum += vert.BoneWeights[i]; if (!Math::NearEqual(weightSum, 1.0f, Y_FLT_EPSILON)) { xmlReader.PrintWarning("vertex weights do not sum to 1, fixing"); for (uint32 i = 0; i < SKELETAL_MESH_MAX_BONES_PER_VERTEX; i++) vert.BoneWeights[i] *= 1.0f / weightSum; } // add vert m_vertices.Add(vert); } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "vertices") == 0); break; } else { xmlReader.PrintError("parse error"); break; } } } } break; // triangles case 4: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 trianglesSelection = xmlReader.Select("triangle"); if (trianglesSelection < 0) return false; const char *materialNameStr = xmlReader.FetchAttribute("material"); const char *smoothingGroupsStr = xmlReader.FetchAttribute("smoothing-groups"); const char *vertex1Str = xmlReader.FetchAttribute("vertex1"); const char *vertex2Str = xmlReader.FetchAttribute("vertex2"); const char *vertex3Str = xmlReader.FetchAttribute("vertex3"); if (materialNameStr == nullptr || smoothingGroupsStr == nullptr || vertex1Str == nullptr || vertex2Str == nullptr || vertex3Str == nullptr) { xmlReader.PrintError("incomplete triangle"); return false; } int32 materialIndex = FindMaterialNameIndex(materialNameStr); if (materialIndex < 0) materialIndex = AddMaterialName(materialNameStr); uint64 smoothingGroups = StringConverter::StringToUInt64(smoothingGroupsStr); uint32 i0 = StringConverter::StringToUInt32(vertex1Str); uint32 i1 = StringConverter::StringToUInt32(vertex2Str); uint32 i2 = StringConverter::StringToUInt32(vertex3Str); if (i0 > m_vertices.GetSize() || i1 > m_vertices.GetSize() || i2 > m_vertices.GetSize()) { xmlReader.PrintError("one or more indices are out of range"); return false; } Triangle tri; tri.MaterialIndex = materialIndex; tri.SmoothingGroups = smoothingGroups; tri.VertexIndices[0] = i0; tri.VertexIndices[1] = i1; tri.VertexIndices[2] = i2; m_triangles.Add(tri); if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "triangles") == 0); break; } else { xmlReader.PrintError("parse error"); break; } } } } break; // collision-shape case 5: { if (m_pCollisionShapeGenerator != nullptr) { xmlReader.PrintError("collision shape already defined"); return false; } m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(); if (!m_pCollisionShapeGenerator->LoadFromXML(xmlReader)) return false; } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "skeletal-mesh") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } if (m_skeletonName.IsEmpty()) { xmlReader.PrintError("missing skeleton"); return false; } return true; } bool SkeletalMeshGenerator::SaveToXML(ByteStream *pStream) const { XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("skeletal-mesh"); { xmlWriter.StartElement("skeleton"); xmlWriter.WriteAttribute("name", m_skeletonName); xmlWriter.EndElement(); // </skeleton> xmlWriter.StartElement("flags"); { if (m_provideVertexColors) xmlWriter.WriteEmptyElement("vertex-colors"); if (m_provideVertexTextureCoordinates) xmlWriter.WriteEmptyElement("vertex-texture-coordinates"); } xmlWriter.EndElement(); // </flags> xmlWriter.StartElement("bones"); { for (uint32 i = 0; i < m_bones.GetSize(); i++) { const Bone *pBone = &m_bones[i]; xmlWriter.StartElement("bone"); { xmlWriter.WriteAttribute("name", pBone->Name); xmlWriter.WriteAttribute("transform-position", StringConverter::Float3ToString(pBone->LocalToBoneTransform.GetPosition())); xmlWriter.WriteAttribute("transform-rotation", StringConverter::QuaternionToString(pBone->LocalToBoneTransform.GetRotation())); xmlWriter.WriteAttribute("transform-scale", StringConverter::Float3ToString(pBone->LocalToBoneTransform.GetScale())); } xmlWriter.EndElement(); // </bone> } } xmlWriter.EndElement(); // </bones> xmlWriter.StartElement("vertices"); { for (uint32 j = 0; j < m_vertices.GetSize(); j++) { const Vertex *pVertex = &m_vertices[j]; xmlWriter.StartElement("vertex"); { xmlWriter.WriteAttribute("position", StringConverter::Float3ToString(pVertex->Position)); xmlWriter.WriteAttribute("tangent", StringConverter::Float3ToString(pVertex->Tangent)); xmlWriter.WriteAttribute("binormal", StringConverter::Float3ToString(pVertex->Binormal)); xmlWriter.WriteAttribute("normal", StringConverter::Float3ToString(pVertex->Normal)); xmlWriter.WriteAttribute("texture-coordinates", StringConverter::Float2ToString(pVertex->TextureCoordinates)); xmlWriter.WriteAttribute("color", StringConverter::ColorToString(pVertex->Color)); for (uint32 k = 0; k < SKELETAL_MESH_MAX_BONES_PER_VERTEX; k++) { if (pVertex->BoneIndices[k] < 0) continue; DebugAssert((uint32)pVertex->BoneIndices[k] < m_bones.GetSize()); xmlWriter.StartElement("weight"); { xmlWriter.WriteAttribute("bone", m_bones[pVertex->BoneIndices[k]].Name); xmlWriter.WriteAttribute("weight", StringConverter::FloatToString(pVertex->BoneWeights[k])); } xmlWriter.EndElement(); // </weight> } } xmlWriter.EndElement(); // </vertex> } } xmlWriter.EndElement(); // </vertices> xmlWriter.StartElement("triangles"); { for (uint32 j = 0; j < m_triangles.GetSize(); j++) { const Triangle *pTriangle = &m_triangles[j]; xmlWriter.StartElement("triangle"); { xmlWriter.WriteAttribute("material", m_materialNames[pTriangle->MaterialIndex]); xmlWriter.WriteAttribute("smoothing-groups", StringConverter::UInt64ToString(pTriangle->SmoothingGroups)); xmlWriter.WriteAttribute("vertex1", StringConverter::UInt32ToString(pTriangle->VertexIndices[0])); xmlWriter.WriteAttribute("vertex2", StringConverter::UInt32ToString(pTriangle->VertexIndices[1])); xmlWriter.WriteAttribute("vertex3", StringConverter::UInt32ToString(pTriangle->VertexIndices[2])); } xmlWriter.EndElement(); // </triangle> } } xmlWriter.EndElement(); // </triangles> if (m_pCollisionShapeGenerator != nullptr) { xmlWriter.StartElement("collision-shape"); //xmlWriter.WriteAttribute("type", NameTable_GetNameString(Physics::NameTables::CollisionShapeType, m_pCollisionShapeGenerator->GetType())); if (!m_pCollisionShapeGenerator->SaveToXML(xmlWriter)) return false; xmlWriter.EndElement(); // </collision-shape> } } xmlWriter.EndElement(); // </skeletal-mesh> return (!xmlWriter.InErrorState() && !pStream->InErrorState()); } bool SkeletalMeshGenerator::BuildBoxCollisionShape() { // get all vertex positions MemArray<float3> vertexPositions; for (const Vertex &vertex : m_vertices) vertexPositions.Add(vertex.Position); // calculate bounding box of all vertices AABox boundingBox(AABox::FromPoints(vertexPositions.GetBasePointer(), vertexPositions.GetSize())); // create shape delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_BOX); m_pCollisionShapeGenerator->SetBoxCenter(boundingBox.GetCenter()); m_pCollisionShapeGenerator->SetBoxHalfExtents(boundingBox.GetExtents() / 2.0f); return true; } bool SkeletalMeshGenerator::BuildSphereCollisionShape() { // get all vertex positions MemArray<float3> vertexPositions; for (const Vertex &vertex : m_vertices) vertexPositions.Add(vertex.Position); // calculate bounding box of all vertices Sphere boundingSphere(Sphere::FromPoints(vertexPositions.GetBasePointer(), vertexPositions.GetSize())); // create shape delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_SPHERE); m_pCollisionShapeGenerator->SetSphereCenter(boundingSphere.GetCenter()); m_pCollisionShapeGenerator->SetSphereRadius(boundingSphere.GetRadius()); return true; } bool SkeletalMeshGenerator::BuildTriangleMeshCollisionShape() { #if 0 // nuke the old one delete m_pCollisionShapeGenerator; // build new m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH); // use lod const LOD *lod = m_lods[buildFromLOD]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle *triangle = &batch->Triangles[triangleIndex]; m_pCollisionShapeGenerator->AddTriangle(lod->Vertices[triangle->Indices[0]].Position, lod->Vertices[triangle->Indices[1]].Position, lod->Vertices[triangle->Indices[2]].Position); } } #endif return false; } bool SkeletalMeshGenerator::BuildConvexHullCollisionShape() { //InternalBuildTriangleMeshCollisionShape(buildFromLOD); //m_pCollisionShapeGenerator->ConvertToConvexHull(); return false; } bool SkeletalMeshGenerator::Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const { // load the skeleton we're using AutoReleasePtr<const Skeleton> pSkeleton = pCallbacks->GetCompiledSkeleton(m_skeletonName); if (pSkeleton == nullptr) { Log_ErrorPrintf("SkeletalMeshGenerator::Compile: Could not load Skeleton '%s'", m_skeletonName.GetCharArray()); return false; } // calculate mesh flags uint32 meshFlags = 0; if (m_provideVertexTextureCoordinates) meshFlags |= DF_SKELETALMESH_FLAG_USE_TEXTURE_COORDINATES; if (m_provideVertexColors) meshFlags |= DF_SKELETALMESH_FLAG_USE_VERTEX_COLORS; // sanity check if (m_skeletonName.GetLength() == 0 || m_vertices.GetSize() == 0 || m_bones.GetSize() == 0 || m_triangles.GetSize() == 0) { Log_ErrorPrintf("SkeletalMeshGenerator::Compile: Incomplete mesh."); return false; } // map our bone names to the skeleton's bone names PODArray<const Skeleton::Bone *> skeletonBoneNameMapping; for (uint32 boneIndex = 0; boneIndex < m_bones.GetSize(); boneIndex++) { const Bone *pOurBone = &m_bones[boneIndex]; const Skeleton::Bone *pSkeletonBone = pSkeleton->GetBoneByName(pOurBone->Name); if (pSkeletonBone == nullptr) { Log_ErrorPrintf("SkeletalMeshGenerator::Compile: Mesh references bone '%s' not present in skeleton '%s'", pOurBone->Name.GetCharArray(), pSkeleton->GetName().GetCharArray()); return false; } skeletonBoneNameMapping.Add(pSkeletonBone); } // transform all vertices to bone space /*MemArray<Vertex> boneSpaceVertices; boneSpaceVertices.Reserve(m_vertices.GetSize()); for (uint32 vertexIndex = 0; vertexIndex < m_vertices.GetSize(); vertexIndex++) { const Vertex *pVertex = &m_vertices[vertexIndex]; Vertex boneSpaceVertex; boneSpaceVertex.Position = float3::Zero; boneSpaceVertex.Tangent = float3::Zero; boneSpaceVertex.Binormal = float3::Zero; boneSpaceVertex.Normal = float3::Zero; boneSpaceVertex.TextureCoordinates = pVertex->TextureCoordinates; boneSpaceVertex.Color = pVertex->Color; for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { int32 boneIndex = pVertex->BoneIndices[weightIndex]; if (boneIndex >= 0) { DebugAssert((uint32)boneIndex < m_bones.GetSize()); const Bone *pOurBone = &m_bones[boneIndex]; float boneWeight = pVertex->BoneWeights[weightIndex]; // transform to bone space boneSpaceVertex.Position += pOurBone->LocalToBoneTransform.TransformPoint(pVertex->Position) * boneWeight; boneSpaceVertex.Tangent += pOurBone->LocalToBoneTransform.TransformNormal(pVertex->Tangent) * boneWeight; boneSpaceVertex.Binormal += pOurBone->LocalToBoneTransform.TransformNormal(pVertex->Binormal) * boneWeight; boneSpaceVertex.Normal += pOurBone->LocalToBoneTransform.TransformNormal(pVertex->Normal) * boneWeight; // set index + weight boneSpaceVertex.BoneIndices[weightIndex] = skeletonBoneNameMapping[boneIndex]->GetIndex(); boneSpaceVertex.BoneWeights[weightIndex] = boneWeight; } else { boneSpaceVertex.BoneIndices[weightIndex] = -1; boneSpaceVertex.BoneWeights[weightIndex] = 0.0f; } } // normalize normals boneSpaceVertex.Tangent.SafeNormalizeInPlace(); boneSpaceVertex.Binormal.SafeNormalizeInPlace(); boneSpaceVertex.Normal.SafeNormalizeInPlace(); // add to output list boneSpaceVertices.Add(boneSpaceVertex); }*/ // bbox/bsphere AABox boundingBox; Sphere boundingSphere; { // find vertex positions in base frame space MemArray<float3> baseFrameVertexPositions; baseFrameVertexPositions.Reserve(m_vertices.GetSize()); // iterate over vertices for (uint32 vertexIndex = 0; vertexIndex < m_vertices.GetSize(); vertexIndex++) { const Vertex *pVertex = &m_vertices[vertexIndex]; const float3 &localSpacePosition(pVertex->Position); float3 baseFrameSpacePosition(float3::Zero); for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { int32 boneIndex = pVertex->BoneIndices[weightIndex]; if (boneIndex >= 0) { float boneWeight = pVertex->BoneWeights[weightIndex]; const Bone *pBone = &m_bones[boneIndex]; DebugAssert((uint32)boneIndex < skeletonBoneNameMapping.GetSize()); // transform bone space, then to base frame baseFrameSpacePosition += (skeletonBoneNameMapping[boneIndex]->GetAbsoluteBaseFrameTransform().GetTransformMatrix4x4() * pBone->LocalToBoneTransform.GetTransformMatrix4x4()).TransformPoint(localSpacePosition) * boneWeight; } } baseFrameVertexPositions.Add(baseFrameSpacePosition); } // calculate bounding box/sphere boundingBox = AABox::FromPoints(baseFrameVertexPositions.GetBasePointer(), baseFrameVertexPositions.GetSize()); boundingSphere = Sphere::FromPoints(baseFrameVertexPositions.GetBasePointer(), baseFrameVertexPositions.GetSize()); } // build output bones MemArray<DF_SKELETALMESH_BONE> outputBones; outputBones.Reserve(m_bones.GetSize()); for (uint32 boneIndex = 0; boneIndex < m_bones.GetSize(); boneIndex++) { DF_SKELETALMESH_BONE outputBone; outputBone.SkeletonBoneIndex = skeletonBoneNameMapping[boneIndex]->GetIndex(); m_bones[boneIndex].LocalToBoneTransform.GetPosition().Store(outputBone.LocalToBonePosition); m_bones[boneIndex].LocalToBoneTransform.GetRotation().Store(outputBone.LocalToBoneRotation); m_bones[boneIndex].LocalToBoneTransform.GetScale().Store(outputBone.LocalToBoneScale); outputBones.Add(outputBone); } // build output indices and batches MemArray<DF_SKELETALMESH_VERTEX> outputVertices; PODArray<uint16> outputIndices; MemArray<DF_SKELETALMESH_BATCH> outputBatches; PODArray<uint16> outputBoneRefs; PODArray<uint16> currentBoneRefs; PODArray<int32> currentVertexMapping; // copy the triangle list MemArray<Triangle> triangleList(m_triangles); // drain it while (triangleList.GetSize() > 0) { uint32 templateMaterialIndex; uint32 templateWeightCount; // use the first triangle as a template { const Triangle *firstTriangle = &triangleList[0]; templateMaterialIndex = firstTriangle->MaterialIndex; #if 0 // find the number of weights for this triangle uint32 vertexWeightCounts[3]; Y_memzero(vertexWeightCounts, sizeof(vertexWeightCounts)); for (uint32 vertexIndex = 0; vertexIndex < 3; vertexIndex++) { const Vertex *pVertex = &m_vertices[firstTriangle->VertexIndices[vertexIndex]]; for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { if (pVertex->BoneIndices[weightIndex] >= 0) vertexWeightCounts[vertexIndex]++; else break; } } // select the maximum of the three vertices templateWeightCount = Max(vertexWeightCounts[0], Max(vertexWeightCounts[1], vertexWeightCounts[2])); #else templateWeightCount = SKELETAL_MESH_MAX_BONES_PER_VERTEX; #endif } // new batch DF_SKELETALMESH_BATCH batch; batch.MaterialIndex = templateMaterialIndex; batch.BaseBoneRef = outputBoneRefs.GetSize(); batch.BoneRefCount = 0; batch.WeightCount = templateWeightCount; batch.BaseVertex = 0;// outputVertices.GetSize(); batch.VertexCount = 0; batch.StartIndex = outputIndices.GetSize(); batch.IndexCount = 0; // initialize arrays uint32 currentVertexCount = outputVertices.GetSize(); currentBoneRefs.Clear(); currentVertexMapping.Resize(m_vertices.GetSize()); Y_memset(currentVertexMapping.GetBasePointer(), 0xFF, currentVertexMapping.GetStorageSizeInBytes()); // find matching triangles for (uint32 triangleIndex = 0; triangleIndex < triangleList.GetSize(); ) { const Triangle *triangle = &triangleList[triangleIndex]; // check the material index if (triangle->MaterialIndex != templateMaterialIndex) { triangleIndex++; continue; } #if 0 // find the number of weights for this triangle Y_memzero(vertexWeightCounts, sizeof(vertexWeightCounts)); for (uint32 vertexIndex = 0; vertexIndex < 3; vertexIndex++) { const Vertex *pVertex = &m_vertices[triangle->VertexIndices[vertexIndex]]; for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { if (pVertex->BoneIndices[weightIndex] >= 0) vertexWeightCounts[vertexIndex]++; else break; } } // weight count matches? uint32 weightCount = Max(vertexWeightCounts[0], Max(vertexWeightCounts[1], vertexWeightCounts[2])); if (weightCount != templateWeightCount) { triangleIndex++; continue; } #endif // cool, we have a matching triangle // find out how much vertex space we need, and how many bone slots we need uint32 extraVerticesNeeded = 0; uint32 extraBoneSlotsNeeded = 0; for (uint32 vertexIndex = 0; vertexIndex < 3; vertexIndex++) { const uint32 vertexArrayIndex = triangle->VertexIndices[vertexIndex]; const Vertex *pVertex = &m_vertices[vertexArrayIndex]; // has a mapping for this vertex in this batch? if (currentVertexMapping[vertexArrayIndex] == -1) { extraVerticesNeeded++; // has a mapping for each of the bones in this batch? for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { if (pVertex->BoneIndices[weightIndex] >= 0) { if (currentBoneRefs.IndexOf(static_cast<uint16>(pVertex->BoneIndices[weightIndex])) < 0) extraBoneSlotsNeeded++; } } } } // enough space? // this will screw up if the triangle is degenerate (ie two identical vertices), but that shouldn't happen anyway // currently the bone slots (if identical for each 3 vertices) will be 3 times the correct size.. fix me at some point? if ((currentVertexCount + extraVerticesNeeded) > MAX_VERTICES_PER_BATCH || (currentBoneRefs.GetSize() + extraBoneSlotsNeeded) > MAX_BONES_PER_BATCH) { Log_PerfPrintf("Splitting skeletal mesh due to %s overrun", ((currentVertexCount + extraVerticesNeeded) > MAX_VERTICES_PER_BATCH) ? "vertex index" : "bone index"); triangleIndex++; continue; } // this triangle is good to add! // loop through each of the vertices for (uint32 vertexIndex = 0; vertexIndex < 3; vertexIndex++) { const uint32 vertexArrayIndex = triangle->VertexIndices[vertexIndex]; // vertex already done? int32 batchVertexIndex = currentVertexMapping[vertexArrayIndex]; if (batchVertexIndex >= 0) { // add this index DebugAssert(batchVertexIndex < MAX_VERTICES_PER_BATCH); outputIndices.Add(static_cast<uint16>(batchVertexIndex)); batch.IndexCount++; continue; } // have to add the vertex, so copy the common information const Vertex *sourceVertex = &m_vertices[vertexArrayIndex]; DF_SKELETALMESH_VERTEX outVertex; sourceVertex->Position.Store(outVertex.Position); sourceVertex->Tangent.Store(outVertex.Tangent); sourceVertex->Binormal.Store(outVertex.Binormal); sourceVertex->Normal.Store(outVertex.Normal); sourceVertex->TextureCoordinates.Store(outVertex.TextureCoordinates); outVertex.Color = sourceVertex->Color; // set all the bone indices to zero and the weights to zero bool hasWeights = false; Y_memzero(outVertex.BoneIndices, sizeof(outVertex.BoneIndices)); Y_memzero(outVertex.BoneWeights, sizeof(outVertex.BoneWeights)); // now the bones are a bit tricker, we have to re-index them for (uint32 weightIndex = 0; weightIndex < templateWeightCount; weightIndex++) { int32 boneIndex = sourceVertex->BoneIndices[weightIndex]; DebugAssert(boneIndex < 0 || static_cast<uint32>(boneIndex) < m_bones.GetSize()); // if this vertex has no weight for this index, just set the ref index to zero (ie ignore it), there should be at least one ref always. if (boneIndex < 0) continue; // in bone ref array? int32 boneRefIndex = currentBoneRefs.IndexOf(static_cast<uint16>(boneIndex)); if (boneRefIndex >= 0) { // set the reference DebugAssert(boneRefIndex < MAX_BONES_PER_BATCH); outVertex.BoneIndices[weightIndex] = static_cast<uint8>(boneRefIndex); } else { // add it DebugAssert(currentBoneRefs.GetSize() < MAX_BONES_PER_BATCH); outVertex.BoneIndices[weightIndex] = static_cast<uint8>(currentBoneRefs.GetSize()); currentBoneRefs.Add(static_cast<uint16>(boneIndex)); } // and carry the weight across outVertex.BoneWeights[weightIndex] = sourceVertex->BoneWeights[weightIndex]; hasWeights = true; } // handle badly-exported models with no weights if (!hasWeights) { Log_WarningPrintf("SkeletalMeshGenerator::Compile: Batch %u (%s): has a vertex with no weights", outputBatches.GetSize(), m_materialNames[templateMaterialIndex].GetCharArray()); if (currentBoneRefs.IsEmpty()) currentBoneRefs.Add(static_cast<uint16>(0)); outVertex.BoneIndices[0] = 0; outVertex.BoneWeights[0] = 1.0f; } // add the vertex, and set the index DebugAssert(currentVertexCount < MAX_VERTICES_PER_BATCH); batchVertexIndex = static_cast<int32>(currentVertexCount); currentVertexMapping[vertexArrayIndex] = batchVertexIndex; outputVertices.Add(outVertex); currentVertexCount++; outputIndices.Add(static_cast<uint16>(batchVertexIndex)); batch.IndexCount++; } // toss the triangle out triangleList.OrderedRemove(triangleIndex); } // this batch should have some stuff... DebugAssert(currentVertexCount > 0 && batch.IndexCount > 0 && currentBoneRefs.GetSize() > 0); // temp logging Log_DevPrintf("SkeletalMeshGenerator::Compile: Batch %u (%s): %u vertices, %u indices, %u bone refs with %u weights", outputBatches.GetSize(), m_materialNames[templateMaterialIndex].GetCharArray(), currentVertexCount, batch.IndexCount, currentBoneRefs.GetSize(), templateWeightCount); // add the bone refs back to the main list, and update the batch info batch.VertexCount = currentVertexCount; batch.BoneRefCount = currentBoneRefs.GetSize(); outputBoneRefs.AddArray(currentBoneRefs); outputBatches.Add(batch); } // didn't get any batches? if (outputBatches.GetSize() == 0) { Log_ErrorPrintf("SkeletalMeshGenerator::Compile: No batches generated."); return false; } // temp logging Log_DevPrintf("SkeletalMeshGenerator::Compile: Built %u batches", outputBatches.GetSize()); // determine flags uint32 skeletalMeshFlags = 0; if (m_provideVertexTextureCoordinates) skeletalMeshFlags |= DF_SKELETALMESH_FLAG_USE_TEXTURE_COORDINATES; if (m_provideVertexColors) skeletalMeshFlags |= DF_SKELETALMESH_FLAG_USE_VERTEX_COLORS; // build header DF_SKELETALMESH_HEADER fileHeader; fileHeader.Magic = DF_SKELETALMESH_HEADER_MAGIC; fileHeader.HeaderSize = sizeof(fileHeader); fileHeader.Flags = skeletalMeshFlags; boundingBox.GetMinBounds().Store(fileHeader.BoundingBoxMin); boundingBox.GetMaxBounds().Store(fileHeader.BoundingBoxMax); boundingSphere.GetCenter().Store(fileHeader.BoundingSphereCenter); fileHeader.BoundingSphereRadius = boundingSphere.GetRadius(); fileHeader.MaterialCount = m_materialNames.GetSize(); fileHeader.SkeletonBoneCount = pSkeleton->GetBoneCount(); fileHeader.BoneCount = outputBones.GetSize(); fileHeader.BoneRefCount = outputBoneRefs.GetSize(); fileHeader.VertexCount = outputVertices.GetSize(); fileHeader.IndexCount = outputIndices.GetSize(); fileHeader.BatchCount = outputBatches.GetSize(); fileHeader.CollisionShapeType = (m_pCollisionShapeGenerator != nullptr) ? m_pCollisionShapeGenerator->GetType() : Physics::COLLISION_SHAPE_TYPE_NONE; // write header pStream->Write2(&fileHeader, sizeof(fileHeader)); // initialize chunk writer ChunkFileWriter cfw; if (!cfw.Initialize(pStream, DF_SKELETALMESH_CHUNK_COUNT)) return false; // write skeleton cfw.BeginChunk(DF_SKELETALMESH_CHUNK_SKELETON); { DF_SKELETALMESH_SKELETON fileSkeleton; fileSkeleton.SkeletonNameStringIndex = cfw.AddString(m_skeletonName); cfw.WriteChunkData(&fileSkeleton, sizeof(fileSkeleton)); } cfw.EndChunk(); // write bones cfw.BeginChunk(DF_SKELETALMESH_CHUNK_BONES); cfw.WriteChunkData(outputBones.GetBasePointer(), outputBones.GetStorageSizeInBytes()); cfw.EndChunk(); // write bone refs cfw.BeginChunk(DF_SKELETALMESH_CHUNK_BONE_REFS); cfw.WriteChunkData(outputBoneRefs.GetBasePointer(), outputBoneRefs.GetStorageSizeInBytes()); cfw.EndChunk(); // write materials cfw.BeginChunk(DF_SKELETALMESH_CHUNK_MATERIALS); { for (uint32 i = 0; i < m_materialNames.GetSize(); i++) { DF_SKELETALMESH_MATERIAL fileMaterial; fileMaterial.MaterialNameStringIndex = cfw.AddString(m_materialNames[i]); cfw.WriteChunkData(&fileMaterial, sizeof(fileMaterial)); } } cfw.EndChunk(); // write vertices cfw.BeginChunk(DF_SKELETALMESH_CHUNK_VERTICES); cfw.WriteChunkData(outputVertices.GetBasePointer(), outputVertices.GetStorageSizeInBytes()); cfw.EndChunk(); // write indices cfw.BeginChunk(DF_SKELETALMESH_CHUNK_INDICES); cfw.WriteChunkData(outputIndices.GetBasePointer(), outputIndices.GetStorageSizeInBytes()); cfw.EndChunk(); // write batches cfw.BeginChunk(DF_SKELETALMESH_CHUNK_BATCHES); cfw.WriteChunkData(outputBatches.GetBasePointer(), outputBatches.GetStorageSizeInBytes()); cfw.EndChunk(); // for collision shape: if (m_pCollisionShapeGenerator != nullptr) { // transform it with the root bone transform Physics::CollisionShapeGenerator *pCollisionShapeGeneratorCopy = new Physics::CollisionShapeGenerator(); // bit of a hack, but ehh.. for box/sphere we use the post-skeleton-transformed vertices if (m_pCollisionShapeGenerator->GetType() == Physics::COLLISION_SHAPE_TYPE_BOX) { pCollisionShapeGeneratorCopy->SetType(Physics::COLLISION_SHAPE_TYPE_BOX); pCollisionShapeGeneratorCopy->SetBoxCenter(boundingBox.GetCenter()); pCollisionShapeGeneratorCopy->SetBoxHalfExtents(boundingBox.GetExtents() / 2.0f); } else if (m_pCollisionShapeGenerator->GetType() == Physics::COLLISION_SHAPE_TYPE_SPHERE) { pCollisionShapeGeneratorCopy->SetType(Physics::COLLISION_SHAPE_TYPE_SPHERE); pCollisionShapeGeneratorCopy->SetSphereCenter(boundingSphere.GetCenter()); pCollisionShapeGeneratorCopy->SetSphereRadius(boundingSphere.GetRadius()); } else { // transform the shape pCollisionShapeGeneratorCopy->Copy(m_pCollisionShapeGenerator); pCollisionShapeGeneratorCopy->ApplyTransform(pSkeleton->GetRootBone()->GetAbsoluteBaseFrameTransform().GetTransformMatrix4x4()); } // compile it BinaryBlob *pCollisionShapeBlob; if (!pCollisionShapeGeneratorCopy->Compile(&pCollisionShapeBlob)) return false; // write it cfw.BeginChunk(DF_SKELETALMESH_CHUNK_COLLISION_SHAPE); cfw.WriteChunkData(pCollisionShapeBlob->GetDataPointer(), pCollisionShapeBlob->GetDataSize()); cfw.EndChunk(); pCollisionShapeBlob->Release(); } if (!cfw.Close()) return false; return !(pStream->InErrorState()); } // Interface BinaryBlob *ResourceCompiler::CompileSkeletalMesh(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.skm.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileSkeletalMesh: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); SkeletalMeshGenerator *pGenerator = new SkeletalMeshGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pCallbacks, pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Renderer/ShaderComponent.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderComponent.h" DEFINE_SHADER_COMPONENT_INFO(ShaderComponent); BEGIN_SHADER_COMPONENT_PARAMETERS(ShaderComponent) END_SHADER_COMPONENT_PARAMETERS() ShaderComponent::ShaderComponent(const ShaderComponentTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo) { } bool ShaderComponent::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return false; } bool ShaderComponent::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { return false; } <file_sep>/Engine/Source/MathLib/Interpolator.h #pragma once #include "MathLib/Common.h" #include "MathLib/Quaternion.h" #include "YBaseLib/Assert.h" class EasingFunction { public: enum Type { Linear, Quadratic, Cubic, Quart, Quint, Expo, EaseInSine, EaseOutSine, EaseInOutSine, EaseInCirc, EaseOutCirc, EaseInOutCirc, EaseInElastic, EaseOutElastic, EaseInOutElastic, EaseInBack, EaseOutBack, EaseInOutBack, EaseInBounce, EaseOutBounce, EaseInOutBounce, TypeCount, }; static float GetCoefficient(Type type, float p); }; template<typename T> class Interpolator { public: static T CalculateValue(EasingFunction::Type function, const T &start, const T &end, float factor); enum State { State_Forward, State_ForwardPaused, State_Reverse, State_ReversePaused, State_Complete, State_Count, }; public: Interpolator() : m_moveDuration(1.0f), m_pauseDuration(0.0f), m_reverseCycle(false), m_repeatCount(0), m_function(EasingFunction::Linear), m_timeRemaining(0.0f), m_cyclesRemaining(0), m_state(State_Complete) { } Interpolator(const T &startValue, const T &endValue, float moveDuration = 1.0f, float pauseDuration = 0.0f, bool reverseCycle = true, uint32 repeatCount = 0, EasingFunction::Type easingFunction = EasingFunction::Linear) : m_startValue(startValue), m_endValue(endValue), m_moveDuration(moveDuration), m_pauseDuration(pauseDuration), m_reverseCycle(reverseCycle), m_repeatCount(repeatCount), m_function(easingFunction), m_timeRemaining(0.0f), m_cyclesRemaining(repeatCount), m_state(State_Complete), m_currentValue(endValue) { } // start/end values const T &GetStartValue() const { return m_startValue; } void SetStartValue(const T &value) { m_startValue = value; } const T &GetEndValue() const { return m_endValue; } void SetEndValue(const T &value) { m_endValue = value; } void SetValues(const T &start, const T &end) { m_startValue = start; m_endValue = end; m_currentValue = start; } // durations -- in seconds float GetMoveDuration() const { return m_moveDuration; } void SetMoveDuration(float duration) { DebugAssert(duration > 0.0f); m_moveDuration = duration; } float GetPauseDuration() const { return m_pauseDuration; } void SetPauseDuration(float duration) { DebugAssert(duration >= 0.0f); m_pauseDuration = duration; } // enable/disable repeat cycle bool GetReverseCycle() const { return m_reverseCycle; } void SetReverseCycle(bool reverseCycle) { m_reverseCycle = reverseCycle; } // repeat count, 0 = infinite uint32 GetRepeatCount() const { return m_repeatCount; } void SetRepeatCount(uint32 repeatCount) { m_repeatCount = repeatCount; } // function const EasingFunction::Type GetFunction() const { return m_function; } void SetFunction(EasingFunction::Type function) { m_function = function; } // reset/reverse void Reset() { m_timeRemaining = m_moveDuration; m_cyclesRemaining = m_repeatCount; m_state = State_Forward; m_currentValue = m_startValue; } void WarpToEnd() { m_timeRemaining = 0.0f; m_cyclesRemaining = 0; m_state = State_Complete; m_currentValue = m_endValue; } void Reverse() { Swap(m_startValue, m_endValue); Reset(); } // value reader float GetTimeRemaining() const { return m_timeRemaining; } uint32 GetCyclesRemaining() const { return m_cyclesRemaining; } bool IsActive() const { return (m_state != State_Complete); } const T &GetCurrentValue() const { return m_currentValue; } // value updater void Update(float deltaTime) { if (m_state == State_Complete) return; // handle cases (or lag) where deltaTime > timeRemaining while (deltaTime > 0.0f) { float thisDelta = Min(deltaTime, m_timeRemaining); deltaTime -= thisDelta; if (thisDelta >= m_timeRemaining) { // cycle complete if (m_state == State_Forward) { // set to end m_currentValue = m_endValue; // enter pause phase or reverse stage if (m_pauseDuration > 0.0f) { m_state = State_ForwardPaused; m_timeRemaining = m_pauseDuration; } else if (m_reverseCycle) { m_state = State_Reverse; m_timeRemaining = m_moveDuration; } else { m_state = State_Complete; } } else if (m_state == State_ForwardPaused) { // enter either the reverse or complete state if (m_reverseCycle) { m_state = State_Reverse; m_timeRemaining = m_moveDuration; } else { m_state = State_Complete; } } else if (m_state == State_Reverse) { // set to start m_currentValue = m_startValue; // completed a reverse cycle, enter pause or complete if (m_pauseDuration > 0.0f) { m_state = State_ReversePaused; m_timeRemaining = m_pauseDuration; } else { m_state = State_Complete; } } else if (m_state == State_ReversePaused) { // cycle completed m_state = State_Complete; } // was a cycle just completed? if (m_state == State_Complete) { // repeat infinitely or a number of times if (m_repeatCount == 0 || (m_cyclesRemaining > 0 && (--m_cyclesRemaining) > 0)) { // enter forward state again m_state = State_Forward; m_timeRemaining = m_moveDuration; } } } else { // not a complete cycle m_timeRemaining -= thisDelta; // update the value if (m_state == State_Forward) m_currentValue = CalculateValue(m_function, m_startValue, m_endValue, 1.0f - (m_timeRemaining / m_moveDuration)); else if (m_state == State_Reverse) m_currentValue = CalculateValue(m_function, m_endValue, m_startValue, 1.0f - (m_timeRemaining / m_moveDuration)); } } } private: // start/end T m_startValue; T m_endValue; // parameters float m_moveDuration; float m_pauseDuration; bool m_reverseCycle; uint32 m_repeatCount; EasingFunction::Type m_function; // state float m_timeRemaining; uint32 m_cyclesRemaining; State m_state; T m_currentValue; }; // default value calculator, uses overloaded operators template<typename T> inline T Interpolator<T>::CalculateValue(EasingFunction::Type function, const T &start, const T &end, float factor) { float coefficient = EasingFunction::GetCoefficient(function, factor); return start + ((end - start) * coefficient); } // overloaded interpolator for quaternions :: @TODO MOVE TO .cpp please template<> inline Quaternion Interpolator<Quaternion>::CalculateValue(EasingFunction::Type function, const Quaternion &start, const Quaternion &end, float factor) { float coefficient = EasingFunction::GetCoefficient(function, factor); return Quaternion::LinearInterpolate(start, end, coefficient); } <file_sep>/Engine/Source/Engine/SkeletalMesh.h #pragma once #include "Engine/Common.h" #include "Engine/Skeleton.h" #include "Renderer/RendererTypes.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/VertexFactories/SkeletalMeshVertexFactory.h" class Material; class Skeleton; namespace Physics { class CollisionShape; } #define SKELETAL_MESH_MAX_BONES_PER_VERTEX (4) class SkeletalMesh : public Resource { DECLARE_RESOURCE_TYPE_INFO(SkeletalMesh, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(SkeletalMesh); public: struct Bone { uint32 SkeletonBoneIndex; Transform LocalToBoneTransform; }; struct Batch { uint32 MaterialIndex; uint32 WeightCount; uint32 BaseBoneRef; uint32 BoneRefCount; uint32 BaseVertex; uint32 VertexCount; uint32 FirstIndex; uint32 IndexCount; }; public: SkeletalMesh(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); virtual ~SkeletalMesh(); // skeleton const Skeleton *GetSkeleton() const { return m_pSkeleton; } // coordinates are for the base frame const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } // materials const uint32 GetMaterialCount() const { return m_materials.GetSize(); } const Material *GetMaterial(uint32 i) const { return m_materials[i]; } // bones const uint32 GetBoneCount() const { return m_bones.GetSize(); } const Bone *GetBone(uint32 i) const { return &m_bones[i]; } // bone refs const uint32 GetBoneRefCount() const { return m_boneRefs.GetSize(); } const uint16 GetBoneRef(uint32 i) const { return m_boneRefs[i]; } // vertices const uint32 GetVertexCount() const { return m_vertices.GetSize(); } const SkeletalMeshVertexFactory::Vertex *GetVertex(uint32 i) const { return &m_vertices[i]; } // indices const uint32 GetIndexCount() const { return m_indices.GetSize(); } const uint16 GetIndex(uint32 i) const { return m_indices[i]; } // batches const uint32 GetBatchCount() const { return m_batches.GetSize(); } const Batch *GetBatch(uint32 i) const { return &m_batches[i]; } // collision shape const Physics::CollisionShape *GetCollisionShape() const { return m_pCollisionShape; } // initialization bool LoadFromStream(const char *name, ByteStream *pStream); // gpu resources const VertexBufferBindingArray *GetVertexBuffers() const { return &m_vertexBuffers; } const uint32 GetBaseVertexFactoryFlags() const { return m_baseVertexFactoryFlags; } const uint32 GetBufferVertexFactoryFlags() const { return m_bufferVertexFactoryFlags; } GPUBuffer *GetIndexBuffer() const { return m_pIndexBuffer; } bool CreateGPUResources() const; void ReleaseGPUResources() const; bool CheckGPUResources() const; private: const Skeleton *m_pSkeleton; AABox m_boundingBox; Sphere m_boundingSphere; MemArray<Bone> m_bones; PODArray<uint16> m_boneRefs; PODArray<const Material *> m_materials; MemArray<SkeletalMeshVertexFactory::Vertex> m_vertices; MemArray<uint16> m_indices; uint32 m_baseVertexFactoryFlags; MemArray<Batch> m_batches; Physics::CollisionShape *m_pCollisionShape; // gpu data mutable uint32 m_bufferVertexFactoryFlags; mutable VertexBufferBindingArray m_vertexBuffers; mutable GPUBuffer *m_pIndexBuffer; mutable bool m_GPUResourcesCreated; DeclareNonCopyable(SkeletalMesh); }; /* class SkeletalMeshInstanceBoneData { public: SkeletalMeshInstanceBoneData(const SkeletalMesh *pSkeletalMesh); ~SkeletalMeshInstanceBoneData(); const Transform &GetTransform(uint32 i) const { return m_boneTransforms[i]; } void SetTransform(uint32 i, const Transform &transform) { m_boneTransforms[i] = transform; } void InitializeForMesh(const SkeletalMesh *pSkeletalMesh); void ResetToBaseFrame(const SkeletalMesh *pSkeletalMesh); private: MemArray<Transform> m_boneTransforms; }; */ <file_sep>/Editor/Source/Editor/EditorScriptEditor.h #pragma once #include "Editor/Common.h" class EditorScriptEditor : public QMainWindow { Q_OBJECT public: EditorScriptEditor(QWidget *parent); virtual ~EditorScriptEditor(); private: }; <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUOutputBuffer.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUOutputBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" #include "Engine/SDLHeaders.h" Log_SetChannel(OpenGLES2RenderBackend); OpenGLES2GPUOutputBuffer::OpenGLES2GPUOutputBuffer(SDL_Window *pSDLWindow, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType, bool externalWindow) : GPUOutputBuffer(vsyncType) , m_pSDLWindow(pSDLWindow) , m_width(0) , m_height(0) , m_backBufferFormat(backBufferFormat) , m_depthStencilBufferFormat(depthStencilBufferFormat) , m_vsyncType(vsyncType) , m_externalWindow(externalWindow) { // get window dimensions SDL_GetWindowSize(pSDLWindow, (int *)&m_width, (int *)&m_height); } OpenGLES2GPUOutputBuffer::~OpenGLES2GPUOutputBuffer() { // we don't destroy the window (except for external outputs), it's the owner's job to do that. if (m_externalWindow) SDL_DestroyWindow(m_pSDLWindow); } void OpenGLES2GPUOutputBuffer::Resize(uint32 width, uint32 height) { if (width == 0 || height == 0) { // get window dimensions int windowWidth, windowHeight; SDL_GetWindowSize(m_pSDLWindow, &windowWidth, &windowHeight); width = windowWidth; height = windowHeight; } m_width = width; m_height = height; } void OpenGLES2GPUOutputBuffer::SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) { if (m_vsyncType == vsyncType) return; // fixme! m_vsyncType = vsyncType; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GPUOutputBuffer *OpenGLES2GPUDevice::CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) { // create an external sdl window SDL_Window *pSDLWindow = SDL_CreateWindowFrom(reinterpret_cast<const void *>(hWnd)); if (pSDLWindow == nullptr) { Log_ErrorPrintf("OpenGLGPUOutputBuffer::Create: SDL_CreateWindowFrom failed: %s", SDL_GetError()); return nullptr; } // create wrapper return new OpenGLES2GPUOutputBuffer(pSDLWindow, m_outputBackBufferFormat, m_outputDepthStencilFormat, vsyncType, true); } GPUOutputBuffer *OpenGLES2GPUDevice::CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) { // create wrapper return new OpenGLES2GPUOutputBuffer(pSDLWindow, m_outputBackBufferFormat, m_outputDepthStencilFormat, vsyncType, false); } <file_sep>/Engine/Source/Engine/ParticleSystemBuiltinModules.h #pragma once #include "Engine/ParticleSystemModule.h" class ParticleSystemModule_TimeBased : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_TimeBased, ParticleSystemModule); DECLARE_OBJECT_NO_FACTORY(ParticleSystemModule_TimeBased); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_TimeBased); public: ParticleSystemModule_TimeBased(); virtual ~ParticleSystemModule_TimeBased(); const float GetTimeFraction() const { return m_timeFraction; } void SetTimeFraction(float timeFraction) { m_timeFraction = timeFraction; } const EasingFunction::Type GetEasingFunction() const { return (EasingFunction::Type)m_easingFunction; } void SetEasingFunction(EasingFunction::Type easingFunction) { m_easingFunction = easingFunction; } protected: // Helper to get a coefficient for a particle's time, ie fraction of time passed float GetCoefficient(const ParticleData *pParticle) const; // Helper to get the inverse coefficient for a particle's time, ie fraction of time remaining float GetInverseCoefficient(const ParticleData *pParticle) const; float m_timeFraction; uint32 m_easingFunction; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SpawnLifetime : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnLifetime, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnLifetime); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnLifetime); public: ParticleSystemModule_SpawnLifetime(); virtual ~ParticleSystemModule_SpawnLifetime(); const float GetMinTime() const { return m_minTime; } const float GetMaxTime() const { return m_maxTime; } void SetMinTime(float minTime) { m_minTime = minTime; } void SetMaxTime(float maxTime) { m_maxTime = maxTime; } void SetTime(float minTime, float maxTime) { m_minTime = minTime; m_maxTime = maxTime; } // Only affects creation of particles virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; private: float m_minTime; float m_maxTime; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SpawnLocation : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnLocation, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnLocation); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnLocation); public: // Emitter starting location types enum SpawnLocationType { LocationType_Point, LocationType_Box, LocationType_Sphere, LocationType_Cylinder, LocationType_Triangle, LocationType_Count }; public: ParticleSystemModule_SpawnLocation(); virtual ~ParticleSystemModule_SpawnLocation(); // Spawn location const SpawnLocationType GetSpawnLocationType() const { return (SpawnLocationType)m_spawnLocationType; } void SetSpawnLocationPoint(const float3 &point); void SetSpawnLocationBox(const float3 &boxMinBounds, const float3 &boxMaxBounds); void SetSpawnLocationSphere(const float3 &sphereCenter, float sphereRadius); void SetSpawnLocationCylinder(const float3 &cylinderBase, float width, float height, uint32 heightAxis); void SetSpawnLocationTriangle(const float3 &triangleBaseCenter, float height, float depth); // Only affects creation of particles virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; private: // Spawn location setup uint32 m_spawnLocationType; struct { struct { float Position[3]; } Fixed; struct { float MinBounds[3]; float MaxBounds[3]; } Box; struct { float Center[3]; float Radius; } Sphere; struct { float Center[3]; float Width; float Height; uint32 HeightAxis; } Cylinder; struct { float BaseCenter[3]; float Height; float Depth; } Triangle; } m_spawnLocationProperties; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SpawnSize : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnSize, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnSize); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnSize); public: ParticleSystemModule_SpawnSize(); virtual ~ParticleSystemModule_SpawnSize(); float GetMinWidth() const { return m_minWidth; } float GetMaxWidth() const { return m_maxWidth; } float GetMinHeight() const { return m_minHeight; } float GetMaxHeight() const { return m_maxHeight; } void SetMinWidth(float value) { m_minWidth = value; } void SetMaxWidth(float value) { m_maxWidth = value; } void SetMinHeight(float value) { m_minHeight = value; } void SetMaxHeight(float value) { m_maxHeight = value; } void SetWidth(float minWidth, float maxWidth) { m_minWidth = minWidth; m_maxWidth = maxWidth; } void SetHeight(float minHeight, float maxHeight) { m_minHeight = minHeight; m_maxHeight = maxHeight; } virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; private: float m_minWidth; float m_maxWidth; float m_minHeight; float m_maxHeight; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SpawnVelocity : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnVelocity, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnVelocity); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnVelocity); public: // Emitter starting velocity types enum SpawnVelocityType { SpawnVelocityType_Fixed, SpawnVelocityType_Arc, SpawnVelocityType_Random, SpawnVelocityType_RandomFixedAxis, SpawnVelocityType_Count }; public: ParticleSystemModule_SpawnVelocity(); virtual ~ParticleSystemModule_SpawnVelocity(); // Only affects creation of particles virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; // Spawn velocity const SpawnVelocityType GetSpawnVelocityType() const { return (SpawnVelocityType)m_spawnVelocityType; } void SetSpawnVelocityFixed(const float3 &fixedVelocity); void SetSpawnVelocityArc(float minAngle, float maxAngle, float distance, uint32 axis); void SetSpawnVelocityRandom(float minSpeed, float maxSpeed); void SetSpawnVelocityRandomFixedAxis(float minSpeed, float maxSpeed, uint32 axis); private: // Spawn velocity setup uint32 m_spawnVelocityType; struct { struct { float Velocity[3]; } Fixed; struct { float MinAngle; float MaxAngle; float Distance; uint32 Axis; } Arc; struct { float MinSpeed; float MaxSpeed; } Random; struct { float MinSpeed; float MaxSpeed; uint32 Axis; } RandomFixedAxis; } m_spawnVelocityProperties; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SpawnRotation : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnRotation, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnRotation); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnRotation); public: ParticleSystemModule_SpawnRotation(); virtual ~ParticleSystemModule_SpawnRotation(); const float GetMinRotation() const { return m_minRotation; } const float GetMaxRotation() const { return m_maxRotation; } void SetMinRotation(float minRotation) { m_minRotation = minRotation; } void SetMaxRotation(float maxRotation) { m_maxRotation = maxRotation; } void SetRotation(float minRotation, float maxRotation) { m_minRotation = minRotation; m_maxRotation = maxRotation; } // Only affects creation of particles virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; private: float m_minRotation; float m_maxRotation; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_LockToEmitter : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_LockToEmitter, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_LockToEmitter); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_LockToEmitter); public: ParticleSystemModule_LockToEmitter(); virtual ~ParticleSystemModule_LockToEmitter(); const float3 &GetOffsetPosition() const { return m_offsetPosition; } void SetOffsetPosition(const float3 &offsetPosition) { m_offsetPosition = offsetPosition; } virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float3 m_offsetPosition; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_FadeOut : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_FadeOut, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_FadeOut); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_FadeOut); public: ParticleSystemModule_FadeOut(); virtual ~ParticleSystemModule_FadeOut(); virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float m_startFadeTime; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_Flipbook : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_Flipbook, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_Flipbook); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_Flipbook); public: ParticleSystemModule_Flipbook(); virtual ~ParticleSystemModule_Flipbook(); const uint32 GetColumnCount() const { return m_columns; } const uint32 GetRowCount() const { return m_rows; } const float GetFlipInterval() const { return m_flipInterval; } void SetColumnCount(uint32 columns) { m_columns = columns; } void SetRowCount(uint32 rows) { m_rows = rows; } void SetFlipInterval(float flipInterval) { m_flipInterval = flipInterval; } // Initialize the texture coordinates of the particle to the first frame of the flipbook virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; // Update the texture coordinates of the particle to the next frame of the flipbook if enough time has passed virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: // helper function to get the minimum/maximum texture coordinates of a frame float2 GetTextureCoordinateRange() const; float2 GetMinTextureCoordinates(uint32 frameNumber) const; float2 GetMaxTextureCoordinates(uint32 frameNumber) const; // properties uint32 m_columns; uint32 m_rows; float m_flipInterval; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_ColorOverTime : public ParticleSystemModule_TimeBased { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_ColorOverTime, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_ColorOverTime); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_ColorOverTime); public: ParticleSystemModule_ColorOverTime(); virtual ~ParticleSystemModule_ColorOverTime(); const uint32 GetStartColor() const { return m_startColor; } const uint32 GetEndColor() const { return m_endColor; } void SetStartColor(uint32 startColor) { m_startColor = startColor; } void SetEndColor(uint32 endColor) { m_endColor = endColor; } // Initialize the particle to starting color virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; // Update the particle to the correct color virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: uint32 m_startColor; uint32 m_endColor; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_OpacityOverTime : public ParticleSystemModule_TimeBased { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_OpacityOverTime, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_OpacityOverTime); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_OpacityOverTime); public: ParticleSystemModule_OpacityOverTime(); virtual ~ParticleSystemModule_OpacityOverTime(); const float GetStartOpacity() const { return m_startOpacity; } const float GetEndOpacity() const { return m_endOpacity; } void SetStartOpacity(float startOpacity) { m_startOpacity = startOpacity; } void SetEndOpacity(float endOpacity) { m_endOpacity = endOpacity; } // Initialize the particle to starting color virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; // Update the particle to the correct color virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float m_startOpacity; float m_endOpacity; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_SizeOverTime : public ParticleSystemModule_TimeBased { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_SizeOverTime, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SizeOverTime); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_SizeOverTime); public: ParticleSystemModule_SizeOverTime(); virtual ~ParticleSystemModule_SizeOverTime(); float GetStartWidth() const { return m_startWidth; } float GetEndWidth() const { return m_endWidth; } float GetStartHeight() const { return m_startHeight; } float GetEndHeight() const { return m_endHeight; } void SetStartWidth(float value) { m_startWidth = value; } void SetEndWidth(float value) { m_endWidth = value; } void SetStartHeight(float value) { m_startHeight = value; } void SetEndHeight(float value) { m_endHeight = value; } void SetWidth(float startWidth, float endWidth) { m_startWidth = startWidth; m_endWidth = endWidth; } void SetHeight(float startHeight, float endHeight) { m_startHeight = startHeight; m_endHeight = endHeight; } virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float m_startWidth; float m_endWidth; float m_startHeight; float m_endHeight; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_RotationSpeed : public ParticleSystemModule { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_RotationSpeed, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_RotationSpeed); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_RotationSpeed); public: ParticleSystemModule_RotationSpeed(); virtual ~ParticleSystemModule_RotationSpeed(); float GetRotationSpeed() const { return m_rotationSpeed; } void SetRotationSpeed(float rotationSpeed) { m_rotationSpeed = rotationSpeed; } virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float m_rotationSpeed; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ParticleSystemModule_RotationOverTime : public ParticleSystemModule_TimeBased { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule_RotationOverTime, ParticleSystemModule); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_RotationOverTime); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemModule_RotationOverTime); public: ParticleSystemModule_RotationOverTime(); virtual ~ParticleSystemModule_RotationOverTime(); float GetStartRotation() const { return m_startRotation; } float GetEndRotation() const { return m_endRotation; } void SetStartRotation(float rotation) { m_startRotation = rotation; } void SetEndRotation(float rotation) { m_endRotation = rotation; } void SetRotation(float startRotation, float endRotation) { m_startRotation = startRotation; m_endRotation = endRotation; } virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const override; virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const override; private: float m_startRotation; float m_endRotation; }; <file_sep>/Engine/Source/MathLib/AABox.h #pragma once #include "MathLib/Common.h" #include "MathLib/Sphere.h" #include "MathLib/Vectorf.h" class Sphere; class Transform; struct Matrix3x3f; struct Matrix3x4f; struct Matrix4x4f; // this class represents an axis-aligned bounding box class AABox { public: AABox() {} AABox(const Vector3f &position); AABox(const Vector3f &vecLow, const Vector3f &vecHigh); AABox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); AABox(const AABox &rCopy); // changes low+high values regardless of existing value void SetBounds(const AABox &bounds); void SetBounds(const Vector3f &position); void SetBounds(const Vector3f &vecLow, const Vector3f &vecHigh); void SetBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); void SetZero(); // changes low value if this value is lower than it, high value if it is higher void Merge(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); void Merge(const Vector3f &minBounds, const Vector3f &maxBounds); void Merge(const Vector3f &vecPoint); void Merge(const AABox &box); // accessors inline const Vector3f &GetMinBounds() const { return m_minBounds; } inline const Vector3f &GetMaxBounds() const { return m_maxBounds; } // tests whether one AABox contains another // 1 - this contains OtherBox, 0 - neither contain, -1 - OtherBox contains this int32 ContainsAABox(const AABox &rOtherBox) const; // tests whether a point is inside a box bool ContainsPoint(const Vector3f &Point) const; // tests whether two aaboxes instersect each other bool AABoxIntersection(const AABox &aabOther) const; bool AABoxIntersection(const AABox &aabOther, Vector3f &contactNormal, Vector3f &contactPoint) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const; // tests whether an aabox and a sphere intersect each other bool SphereIntersection(const Sphere &sphOther) const; bool SphereIntersection(const Sphere &sphOther, Vector3f &contactNormal, Vector3f &contactPoint) const; // tests whether an aabox and a triangle intersect each other bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const; float TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const; // Get vertices for this box. void GetCornerPoints(Vector3f *pVertices) const; void GetCornerPoints(SIMDVector3f *pVertices) const; // transforms void ApplyTransform(const Transform &transform); void ApplyTransform(const Matrix3x3f &transform); void ApplyTransform(const Matrix3x4f &transform); void ApplyTransform(const Matrix4x4f &transform); // Get transformed bounds. AABox GetTransformed(const Transform &transform) const; AABox GetTransformed(const Matrix3x3f &transform) const; AABox GetTransformed(const Matrix3x4f &transform) const; AABox GetTransformed(const Matrix4x4f &transform) const; // Gets a vector at the centre of the the box. SIMDVector3f GetCenter() const; // Determines the extents of the box. (the size of the box) SIMDVector3f GetExtents() const; // Gets a bounding sphere encompassing this box. Sphere GetSphere() const; // comparison operator bool operator==(const AABox &Other) const; bool operator!=(const AABox &Other) const; // assignment operator AABox &operator=(const AABox &rCopy); // box builders static AABox FromSphere(const Sphere &sphere); static AABox FromPoints(const SIMDVector3f *pPoints, uint32 nPoints); static AABox FromPoints(const Vector3f *pPoints, uint32 nPoints); static AABox Merge(const AABox &left, const AABox &right); // constants static const AABox &Zero; static const AABox &MaxSize; private: Vector3f m_minBounds; Vector3f m_maxBounds; }; <file_sep>/Engine/Source/BlockEngine/BlockAnimation.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockAnimation.h" #include "Engine/Physics/BoxCollisionShape.h" #include "Engine/Physics/RigidBody.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Camera.h" #include "Engine/World.h" #include "Renderer/RenderProxy.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/RenderWorld.h" Log_SetChannel(BlockAnimation); static const float BLOCK_START_FADEOUT_TIME = 1.0f; class BlockAnimationBlockRenderProxy : public RenderProxy { public: struct Batch { Batch() {} Batch(const void *pSourcePtr_, const Material *pMaterial_, uint32 baseVertex, uint32 baseIndex, uint32 firstIndex, uint32 indexCount, const float4x4 &transformMatrix, const AABox &localBoundingBox, const AABox &worldBoundingBox) : pSourcePtr(pSourcePtr_), pMaterial(pMaterial_), BaseVertex(baseVertex), BaseIndex(baseIndex), FirstIndex(firstIndex), IndexCount(indexCount), TransformMatrix(transformMatrix), LocalBoundingBox(localBoundingBox), WorldBoundingBox(worldBoundingBox), TintColor(0xFFFFFFFF) {} const void *pSourcePtr; const Material *pMaterial; uint32 BaseVertex; uint32 BaseIndex; uint32 FirstIndex; uint32 IndexCount; float4x4 TransformMatrix; AABox LocalBoundingBox; AABox WorldBoundingBox; uint32 TintColor; }; public: BlockAnimationBlockRenderProxy(uint32 entityID) : RenderProxy(entityID), m_pIndexBuffer(nullptr) { } ~BlockAnimationBlockRenderProxy() { SAFE_RELEASE(m_pIndexBuffer); m_vertexBuffers.Clear(); } virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override { // add batches uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT | RENDER_PASS_TINT; wantedRenderPasses &= pRenderQueue->GetAcceptingRenderPassMask(); if (wantedRenderPasses == 0) return; // get batches for (uint32 batchIndex = 0; batchIndex < m_batches.GetSize(); batchIndex++) { const Batch *pBatch = &m_batches[batchIndex]; // get view distance float3 boundingBoxCenter(pBatch->WorldBoundingBox.GetCenter()); float viewDistance = pCamera->CalculateDepthToPoint(boundingBoxCenter); if (viewDistance > pCamera->GetObjectCullDistance()) continue; // get pass mask uint32 renderPassMask = pBatch->pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (pBatch->TintColor == 0xFFFFFFFF) renderPassMask &= ~(RENDER_PASS_TINT); else renderPassMask &= ~(RENDER_PASS_SHADOW_MAP); if (renderPassMask != 0) { // create queue entry for base layer RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory); queueEntry.pMaterial = pBatch->pMaterial; queueEntry.BoundingBox = pBatch->WorldBoundingBox; queueEntry.RenderPassMask = renderPassMask; queueEntry.VertexFactoryFlags = 0; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = pBatch->TintColor; queueEntry.UserData[0] = batchIndex; queueEntry.Layer = queueEntry.pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override { const Batch *pBatch = &m_batches[pQueueEntry->UserData[0]]; pCommandList->GetConstants()->SetLocalToWorldMatrix(pBatch->TransformMatrix, true); m_vertexBuffers.BindBuffers(pCommandList); pCommandList->SetIndexBuffer(m_pIndexBuffer, GPU_INDEX_FORMAT_UINT16, 0); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); } virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override { const Batch *pBatch = &m_batches[pQueueEntry->UserData[0]]; pCommandList->DrawIndexed(pBatch->BaseIndex + pBatch->FirstIndex, pBatch->IndexCount, pBatch->BaseVertex); } void UpdateRenderData(MemArray<BlockWorldVertexFactory::Vertex> *pVertices, MemArray<uint16> *pIndices, MemArray<BlockAnimationBlockRenderProxy::Batch> *pBatches, const AABox &boundingBox) { // forward through to render thread QUEUE_RENDERER_LAMBDA_COMMAND([this, pVertices, pIndices, pBatches, boundingBox]() { // create vertex buffer GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, pVertices->GetStorageSizeInBytes()); AutoReleasePtr<GPUBuffer> pVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, pVertices->GetBasePointer()); // create index buffer GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, pIndices->GetStorageSizeInBytes()); AutoReleasePtr<GPUBuffer> pIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, pIndices->GetBasePointer()); // store everything if (pVertexBuffer != nullptr && pIndexBuffer != nullptr) { m_vertexBuffers.SetBuffer(0, pVertexBuffer, 0, sizeof(BlockWorldVertexFactory::Vertex)); SAFE_RELEASE(m_pIndexBuffer); m_pIndexBuffer = pIndexBuffer; m_pIndexBuffer->AddRef(); m_batches.Swap(*pBatches); SetBounds(boundingBox, Sphere::FromAABox(boundingBox)); } // release temporary buffers delete pBatches; delete pIndices; delete pVertices; }); } void UpdateTransforms(const void *pSourcePtr, const float4x4 &newTransform, uint32 tintColor) { float4x4 transformCopy(newTransform); QUEUE_RENDERER_LAMBDA_COMMAND([this, pSourcePtr, transformCopy, tintColor]() { for (Batch &blockBatch : m_batches) { if (blockBatch.pSourcePtr == pSourcePtr) { blockBatch.TransformMatrix = transformCopy; blockBatch.WorldBoundingBox = blockBatch.LocalBoundingBox.GetTransformed(transformCopy); blockBatch.TintColor = tintColor; } } // update overall bounds AABox overallBounds(AABox::Zero); for (uint32 batchIndex = 0; batchIndex < m_batches.GetSize(); batchIndex++) { if (batchIndex == 0) overallBounds = m_batches[batchIndex].WorldBoundingBox; else overallBounds.Merge(m_batches[batchIndex].WorldBoundingBox); } SetBounds(overallBounds, Sphere::FromAABox(overallBounds)); }); } private: VertexBufferBindingArray m_vertexBuffers; GPUBuffer *m_pIndexBuffer; MemArray<Batch> m_batches; }; DEFINE_ENTITY_TYPEINFO(BlockAnimation, 0); BEGIN_ENTITY_PROPERTIES(BlockAnimation) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(BlockAnimation) END_ENTITY_SCRIPT_FUNCTIONS() BlockAnimation::BlockAnimation(const EntityTypeInfo *pTypeInfo /*= &s_typeInfo*/) : Entity(pTypeInfo), m_pBlockPalette(nullptr), m_pBlockWorld(nullptr), m_autoDespawn(false), m_pBlockRenderProxy(nullptr), m_renderDataUpdatePending(false) { } BlockAnimation::~BlockAnimation() { DebugAssert(m_physicsBlocks.IsEmpty()); SAFE_RELEASE(m_pBlockRenderProxy); } BlockAnimation *BlockAnimation::Create(BlockWorld *pBlockWorld, bool autoDespawn /*= true*/) { BlockAnimation *pAnimation = new BlockAnimation(); if (!pAnimation->Initialize(pBlockWorld->AllocateEntityID(), EmptyString)) { pAnimation->Release(); return nullptr; } // automatically put us in world, and register for updates. pAnimation->m_pBlockPalette = pBlockWorld->GetPalette(); pAnimation->m_pBlockWorld = pBlockWorld; pAnimation->m_autoDespawn = autoDespawn; pAnimation->m_pBlockRenderProxy = new BlockAnimationBlockRenderProxy(pAnimation->GetEntityID()); pBlockWorld->AddEntity(pAnimation); pAnimation->RegisterForUpdates(); return pAnimation; } bool BlockAnimation::CreatePhysicsBlock(const float3 &basePosition, BlockWorldBlockType blockValue, const float3 &forceVector, float despawnTime /*= 5.0f*/) { // lookup block info const BlockPalette::BlockType *pBlockType = m_pBlockPalette->GetBlockType(blockValue); if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; // calculate the physics block size float3 physicsBlockExtents(1.0f); // create physics block PhysicsBlock *pPhysicsBlock = new PhysicsBlock(); pPhysicsBlock->SourceValue = blockValue; pPhysicsBlock->LastTransform.Set(basePosition, Quaternion::Identity, float3::One); pPhysicsBlock->TimeRemaining = despawnTime; // create the collision shape AutoReleasePtr<Physics::BoxCollisionShape> pCollisionShape = new Physics::BoxCollisionShape(physicsBlockExtents * 0.5f, physicsBlockExtents * 0.5f); pPhysicsBlock->pCollisionObject = new Physics::RigidBody(m_entityID, pCollisionShape, pPhysicsBlock->LastTransform); m_pWorld->GetPhysicsWorld()->AddObject(pPhysicsBlock->pCollisionObject); // apply the impulse if (forceVector.SquaredLength() > 0.0f) static_cast<Physics::RigidBody *>(pPhysicsBlock->pCollisionObject)->ApplyCentralImpulse(forceVector); // add to physics block list m_physicsBlocks.Add(pPhysicsBlock); m_renderDataUpdatePending = true; return true; } bool BlockAnimation::CreatePhysicsBlock(int32 x, int32 y, int32 z, const float3 &forceVector, bool removeBlock /*= true*/, float despawnTime /*= 5.0f*/) { // retrieve the block value BlockWorldBlockType blockValue = m_pBlockWorld->GetBlockValue(x, y, z); if (blockValue == 0) return false; // calculate base position for this block float3 basePosition((float)x, (float)y, (float)z); // create physics block bool result = CreatePhysicsBlock(basePosition, blockValue, forceVector, despawnTime); // remove the block from the world? if (removeBlock) m_pBlockWorld->SetBlockType(x, y, z, 0); // done return result; } void BlockAnimation::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); DebugAssert(pWorld == m_pBlockWorld); pWorld->GetRenderWorld()->AddRenderable(m_pBlockRenderProxy); } void BlockAnimation::OnRemoveFromWorld(World *pWorld) { DebugAssert(pWorld == m_pBlockWorld); // kill any remaining objects for (PhysicsBlock *pPhysicsBlock : m_physicsBlocks) { m_pWorld->GetPhysicsWorld()->RemoveObject(pPhysicsBlock->pCollisionObject); delete pPhysicsBlock; } m_physicsBlocks.Clear(); pWorld->GetRenderWorld()->RemoveRenderable(m_pBlockRenderProxy); m_pBlockWorld = nullptr; BaseClass::OnRemoveFromWorld(pWorld); } void BlockAnimation::Update(float timeSinceLastUpdate) { BaseClass::Update(timeSinceLastUpdate); // do updates... { // update physics blocks bool recalculateBounds = false; for (uint32 physicsBlockIndex = 0; physicsBlockIndex < m_physicsBlocks.GetSize();) { PhysicsBlock *pPhysicsBlock = m_physicsBlocks[physicsBlockIndex]; // timeout blocks pPhysicsBlock->TimeRemaining -= timeSinceLastUpdate; if (pPhysicsBlock->TimeRemaining <= 0.0f) { m_pWorld->GetPhysicsWorld()->RemoveObject(pPhysicsBlock->pCollisionObject); delete pPhysicsBlock; m_physicsBlocks.FastRemove(physicsBlockIndex); m_renderDataUpdatePending = true; continue; } // pull collision data from the physics objects, if they've changed, update the render proxy if (pPhysicsBlock->pCollisionObject->GetTransform() != pPhysicsBlock->LastTransform || pPhysicsBlock->TimeRemaining < BLOCK_START_FADEOUT_TIME) { uint8 tintColor = 255; if (pPhysicsBlock->TimeRemaining < BLOCK_START_FADEOUT_TIME) { float opacity = Math::Saturate(pPhysicsBlock->TimeRemaining / BLOCK_START_FADEOUT_TIME); tintColor = (uint8)Math::Clamp(Math::Truncate(opacity * 255.0f), 0, 255); } pPhysicsBlock->LastTransform = pPhysicsBlock->pCollisionObject->GetTransform(); m_pBlockRenderProxy->UpdateTransforms(pPhysicsBlock, pPhysicsBlock->LastTransform.GetTransformMatrix4x4(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, tintColor)); recalculateBounds = true; } // next physicsBlockIndex++; continue; } if (recalculateBounds) { AABox newBoundingBox(AABox::Zero); for (uint32 physicsBlockIndex = 0; physicsBlockIndex < m_physicsBlocks.GetSize(); physicsBlockIndex++) { PhysicsBlock *pPhysicsBlock = m_physicsBlocks[physicsBlockIndex]; if (physicsBlockIndex == 0) newBoundingBox = pPhysicsBlock->BoundingBox.GetTransformed(pPhysicsBlock->LastTransform); else newBoundingBox.Merge(pPhysicsBlock->BoundingBox.GetTransformed(pPhysicsBlock->LastTransform)); } SetBounds(newBoundingBox, Sphere::FromAABox(newBoundingBox)); } } // despawn if there's nothing left if (m_physicsBlocks.IsEmpty()) { m_pBlockWorld->QueueRemoveEntity(this); return; } // update render data if (m_renderDataUpdatePending) { m_renderDataUpdatePending = false; RebuildRenderData(); } } void BlockAnimation::RebuildRenderData() { #if 0 // create arrays MemArray<BlockWorldVertexFactory::Vertex> *pVertices = new MemArray<BlockWorldVertexFactory::Vertex>(); MemArray<uint16> *pIndices = new MemArray<uint16>(); MemArray<BlockAnimationBlockRenderProxy::Batch> *pBatches = new MemArray<BlockAnimationBlockRenderProxy::Batch>(); MemArray<BlockWorldMesher::Triangle> blockTriangles; // fill with data AABox animationBoundingBox(AABox::Zero); for (uint32 physicsBlockIndex = 0; physicsBlockIndex < m_physicsBlocks.GetSize(); physicsBlockIndex++) { PhysicsBlock *pPhysicsBlock = m_physicsBlocks[physicsBlockIndex]; uint32 baseVertex = pVertices->GetSize(); uint32 baseIndex = pIndices->GetSize(); // mesh the block blockTriangles.Clear(); if (!BlockWorldMesher::MeshSingleBlock(m_pBlockPalette, pPhysicsBlock->SourceValue, *pVertices, blockTriangles)) continue; // add triangles if (blockTriangles.GetSize() > 0) { // optimize triangle order MeshUtilites::OptimizeIndicesForBatching(&blockTriangles[0].Indices[0], sizeof(BlockWorldMesher::Triangle), &blockTriangles[0].MaterialIndex, sizeof(BlockWorldMesher::Triangle), blockTriangles.GetSize() * 3); // calculate bounding box AABox localBoundingBox(AABox::Zero); for (const BlockWorldMesher::Vertex &vertex : *pVertices) localBoundingBox.Merge(vertex.Position); // move bbox to world space AABox worldBoundingBox(localBoundingBox.GetTransformed(pPhysicsBlock->LastTransform)); // create batches, append indices BlockAnimationBlockRenderProxy::Batch batch(pPhysicsBlock, m_pBlockPalette->GetMaterial(blockTriangles[0].MaterialIndex), baseVertex, baseIndex, 0, 0, pPhysicsBlock->LastTransform.GetTransformMatrix4x4(), localBoundingBox, worldBoundingBox); uint32 lastMaterialIndex = blockTriangles[0].MaterialIndex; for (uint32 triangleIndex = 0; triangleIndex < blockTriangles.GetSize(); triangleIndex++) { const BlockWorldMesher::Triangle &inTriangle = blockTriangles[triangleIndex]; if (inTriangle.MaterialIndex == lastMaterialIndex) { batch.IndexCount += 3; } else { pBatches->Add(batch); lastMaterialIndex = inTriangle.MaterialIndex; batch.pMaterial = m_pBlockPalette->GetMaterial(lastMaterialIndex); batch.FirstIndex = triangleIndex * 3; batch.IndexCount = 3; } uint16 indices[3] = { (uint16)inTriangle.Indices[0], (uint16)inTriangle.Indices[1], (uint16)inTriangle.Indices[2] }; pIndices->AddRange(indices, countof(indices)); } // add last batch pBatches->Add(batch); // update bounds pPhysicsBlock->BoundingBox = localBoundingBox; // update overall bounding box if (physicsBlockIndex != 0) animationBoundingBox = worldBoundingBox; else animationBoundingBox.Merge(worldBoundingBox); } } // pass through to render proxy //Log_DevPrintf("pass to RP %u verts, %u inds, %u batches, bbox {%s}-{%s}", pVertices->GetSize(), pIndices->GetSize(), pBatches->GetSize(), StringConverter::Float3ToString(animationBoundingBox.GetMinBounds()).GetCharArray(), StringConverter::Float3ToString(animationBoundingBox.GetMaxBounds()).GetCharArray()); m_pBlockRenderProxy->UpdateRenderData(pVertices, pIndices, pBatches, animationBoundingBox); SetBounds(animationBoundingBox, Sphere::FromAABox(animationBoundingBox)); #endif } void BlockAnimation::CreateSpawnBlock(const float3 &sourcePosition, int32 x, int32 y, int32 z, BlockWorldBlockType blockValue, float spawnTime /*= 1.0f*/, bool setAfterSpawn /*= true*/) { } <file_sep>/Engine/Source/MathLib/SIMDVectori_sse.h #pragma once #include "Core/Math.h" #include "Core/Memory.h" #include <intrin.h> #if Y_CPU_SSE_LEVEL < 2 #error SSE2 must be enabled. #endif // interoperability between int/vector types struct Vector2i; struct Vector3i; struct Vector4i; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector2i { // constructors inline SIMDVector2i() {} inline SIMDVector2i(int32 x_, int32 y_) { m128i = _mm_set_epi32(0, 0, y_, x_); } inline SIMDVector2i(const int32 *p) { m128i = _mm_set_epi32(0, 0, p[1], p[0]); } inline SIMDVector2i(const SIMDVector2i &v) : m128i(v.m128i) {} SIMDVector2i(const Vector2i &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(int32 x_, int32 y_) { m128i = _mm_set_epi32(0, 0, y_, x_); } void Set(const SIMDVector2i &v) { m128i = v.m128i; } void Set(const Vector2i &v); void SetZero() { m128i = _mm_setzero_si128(); } // new vector inline SIMDVector2i operator+(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_add_epi32(m128i, v.m128i); return r; } inline SIMDVector2i operator-(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_sub_epi32(m128i, v.m128i); return r; } inline SIMDVector2i operator*(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_mul_epi32(m128i, v.m128i); return r; } inline SIMDVector2i operator/(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_set_epi32(0, 0, y / v.y, x / v.x); return r; } inline SIMDVector2i operator%(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_set_epi32(0, 0, y % v.y, x % v.x); return r; } inline SIMDVector2i operator&(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_and_si128(m128i, v.m128i); return r; } inline SIMDVector2i operator|(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_or_si128(m128i, v.m128i); return r; } inline SIMDVector2i operator^(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_xor_si128(m128i, v.m128i); return r; } // scalar operators inline SIMDVector2i operator+(const int32 v) const { SIMDVector2i r; r.m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector2i operator-(const int32 v) const { SIMDVector2i r; r.m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector2i operator*(const int32 v) const { SIMDVector2i r; r.m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector2i operator/(const int32 v) const { SIMDVector2i r; r.m128i = _mm_set_epi32(0, 0, y / v, x / v); return r; } inline SIMDVector2i operator%(const int32 v) const { SIMDVector2i r; r.m128i = _mm_set_epi32(0, 0, y % v, x % v); return r; } inline SIMDVector2i operator&(const int32 v) const { SIMDVector2i r; r.m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector2i operator|(const int32 v) const { SIMDVector2i r; r.m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector2i operator^(const int32 v) const { SIMDVector2i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return r; } // no params inline SIMDVector2i operator~() const { SIMDVector2i r; r.m128i = _mm_andnot_si128(m128i, m128i); return r; } inline SIMDVector2i operator-() const { SIMDVector2i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(0x7FFFFFFF)); return r; } // comparison operators inline bool operator==(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFF) == 0xFF; } inline bool operator!=(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFF) != 0xFF; } inline bool operator<=(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmplt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x33) == 0x33; } inline bool operator>=(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmpgt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x33) == 0x33; } inline bool operator<(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) & 0x33) == 0x33; } inline bool operator>(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) & 0x33) == 0x33; } // modifies this vector inline SIMDVector2i &operator+=(const SIMDVector2i &v) { m128i = _mm_add_epi32(m128i, v.m128i); return *this; } inline SIMDVector2i &operator-=(const SIMDVector2i &v) { m128i = _mm_sub_epi32(m128i, v.m128i); return *this; } inline SIMDVector2i &operator*=(const SIMDVector2i &v) { m128i = _mm_mul_epi32(m128i, v.m128i); return *this; } inline SIMDVector2i &operator/=(const SIMDVector2i &v) { x /= v.x; y /= v.y; return *this; } inline SIMDVector2i &operator%=(const SIMDVector2i &v) { x %= v.x; y %= v.y; return *this; } inline SIMDVector2i &operator&=(const SIMDVector2i &v) { m128i = _mm_and_si128(m128i, v.m128i); return *this; } inline SIMDVector2i &operator|=(const SIMDVector2i &v) { m128i = _mm_or_si128(m128i, v.m128i); return *this; } inline SIMDVector2i &operator^=(const SIMDVector2i &v) { m128i = _mm_xor_si128(m128i, v.m128i); return *this; } // scalar operators inline SIMDVector2i &operator+=(const int32 v) { m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator-=(const int32 v) { m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator*=(const int32 v) { m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator/=(const int32 v) { x /= v; y /= v; return *this; } inline SIMDVector2i &operator%=(const int32 v) { x %= v; y %= v; return *this; } inline SIMDVector2i &operator&=(const int32 v) { m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator|=(const int32 v) { m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator^=(const int32 v) { m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector2i &operator=(const SIMDVector2i &v) { m128i = v.m128i; return *this; } SIMDVector2i &operator=(const Vector2i &v); // index accessors //const int32 &operator[](uint32 i) const { return (&x)[i]; } //int32 &operator[](uint32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // to intx const Vector2i &GetInt2() const { return reinterpret_cast<const Vector2i &>(*this); } Vector2i &GetInt2() { return reinterpret_cast<Vector2i &>(*this); } operator const Vector2i &() const { return reinterpret_cast<const Vector2i &>(*this); } operator Vector2i &() { return reinterpret_cast<Vector2i &>(*this); } // partial comparisons bool AnyLess(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) & 0x3) != 0x0; } bool AnyLessEqual(const SIMDVector2i &v) const { return (x <= v.x || y <= v.y); } bool AnyGreater(const SIMDVector2i &v) const { return (_mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) & 0x3) != 0x0; } bool AnyGreaterEqual(const SIMDVector2i &v) const { return (x >= v.x || y >= v.y); } // modification functions SIMDVector2i Min(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_min_epi32(m128i, v.m128i); return r; } SIMDVector2i Max(const SIMDVector2i &v) const { SIMDVector2i r; r.m128i = _mm_max_epi32(m128i, v.m128i); return r; } SIMDVector2i Clamp(const SIMDVector2i &lBounds, const SIMDVector2i &uBounds) const { SIMDVector2i r; r.m128i = _mm_min_epi32(uBounds.m128i, _mm_max_epi32(lBounds.m128i, m128i)); return r; } SIMDVector2i Abs() const { SIMDVector2i r; r.m128i = _mm_abs_epi32(m128i); return r; } SIMDVector2i Saturate() const { SIMDVector2i r; r.m128i = _mm_min_epi32(_mm_set1_epi32(1), _mm_max_epi32(_mm_setzero_si128(), m128i)); return r; } SIMDVector2i Snap(const SIMDVector2i &v) const { return SIMDVector2i(Math::Snap(x, v.x), Math::Snap(y, v.y)); } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128i m128i; struct { int32 x, y; }; struct { int32 r, g; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector2i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector3i { // constructors inline SIMDVector3i() {} inline SIMDVector3i(int32 x_, int32 y_, int32 z_) { m128i = _mm_set_epi32(0, z_, y_, x_); } inline SIMDVector3i(const int32 *p) { m128i = _mm_set_epi32(0, p[2], p[1], p[0]); } inline SIMDVector3i(const SIMDVector3i &v) : m128i(v.m128i) {} SIMDVector3i(const Vector3i &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(int32 x_, int32 y_, int32 z_) { m128i = _mm_set_epi32(0, z_, y_, x_); } void Set(const SIMDVector2i &v) { m128i = v.m128i; } void Set(const Vector3i &v); void SetZero() { m128i = _mm_setzero_si128(); } // new vector inline SIMDVector3i operator+(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_add_epi32(m128i, v.m128i); return r; } inline SIMDVector3i operator-(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_sub_epi32(m128i, v.m128i); return r; } inline SIMDVector3i operator*(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_mul_epi32(m128i, v.m128i); return r; } inline SIMDVector3i operator/(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_set_epi32(x / v.x, y / v.y, z / v.z, 0); return r; } inline SIMDVector3i operator%(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_set_epi32(x % v.x, y % v.y, z % v.z, 0); return r; } inline SIMDVector3i operator&(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_and_si128(m128i, v.m128i); return r; } inline SIMDVector3i operator|(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_or_si128(m128i, v.m128i); return r; } inline SIMDVector3i operator^(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_xor_si128(m128i, v.m128i); return r; } // scalar operators inline SIMDVector3i operator+(const int32 v) const { SIMDVector3i r; r.m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector3i operator-(const int32 v) const { SIMDVector3i r; r.m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector3i operator*(const int32 v) const { SIMDVector3i r; r.m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector3i operator/(const int32 v) const { SIMDVector3i r; r.m128i = _mm_set_epi32(0, z / v, y / v, x / v); return r; } inline SIMDVector3i operator%(const int32 v) const { SIMDVector3i r; r.m128i = _mm_set_epi32(0, z % v, y % v, x % v); return r; } inline SIMDVector3i operator&(const int32 v) const { SIMDVector3i r; r.m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector3i operator|(const int32 v) const { SIMDVector3i r; r.m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector3i operator^(const int32 v) const { SIMDVector3i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return r; } // no params inline SIMDVector3i operator~() const { SIMDVector3i r; r.m128i = _mm_andnot_si128(m128i, m128i); return r; } inline SIMDVector3i operator-() const { SIMDVector3i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(0x7FFFFFFF)); return r; } // comparison operators inline bool operator==(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFFF) == 0xFFF; } inline bool operator!=(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFFF) != 0xFFF; } inline bool operator<=(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmplt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x333) == 0x333; } inline bool operator>=(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmpgt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x333) == 0x333; } inline bool operator<(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) & 0x333) == 0x333; } inline bool operator>(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) & 0x333) == 0x333; } // modifies this vector inline SIMDVector3i &operator+=(const SIMDVector3i &v) { m128i = _mm_add_epi32(m128i, v.m128i); return *this; } inline SIMDVector3i &operator-=(const SIMDVector3i &v) { m128i = _mm_sub_epi32(m128i, v.m128i); return *this; } inline SIMDVector3i &operator*=(const SIMDVector3i &v) { m128i = _mm_mul_epi32(m128i, v.m128i); return *this; } inline SIMDVector3i &operator/=(const SIMDVector3i &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } inline SIMDVector3i &operator%=(const SIMDVector3i &v) { x %= v.x; y %= v.y; z %= v.z; return *this; } inline SIMDVector3i &operator&=(const SIMDVector3i &v) { m128i = _mm_and_si128(m128i, v.m128i); return *this; } inline SIMDVector3i &operator|=(const SIMDVector3i &v) { m128i = _mm_or_si128(m128i, v.m128i); return *this; } inline SIMDVector3i &operator^=(const SIMDVector3i &v) { m128i = _mm_xor_si128(m128i, v.m128i); return *this; } // scalar operators inline SIMDVector3i &operator+=(const int32 v) { m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator-=(const int32 v) { m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator*=(const int32 v) { m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator/=(const int32 v) { x /= v; y /= v; z /= v; return *this; } inline SIMDVector3i &operator%=(const int32 v) { x %= v; y %= v; z %= v; return *this; } inline SIMDVector3i &operator&=(const int32 v) { m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator|=(const int32 v) { m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator^=(const int32 v) { m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector3i &operator=(const SIMDVector3i &v) { m128i = v.m128i; return *this; } SIMDVector3i &operator=(const Vector3i &v); // index accessors //const int32 &operator[](uint32 i) const { return (&x)[i]; } //int32 &operator[](uint32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // to intx const Vector3i &GetInt3() const { return reinterpret_cast<const Vector3i &>(*this); } Vector3i &GetInt3() { return reinterpret_cast<Vector3i &>(*this); } operator const Vector3i &() const { return reinterpret_cast<const Vector3i &>(*this); } operator Vector3i &() { return reinterpret_cast<Vector3i &>(*this); } // partial comparisons bool AnyLess(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) & 0x7) != 0x0; } bool AnyLessEqual(const SIMDVector3i &v) const { return (x <= v.x || y <= v.y || z <= v.z); } bool AnyGreater(const SIMDVector3i &v) const { return (_mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) & 0x7) != 0x0; } bool AnyGreaterEqual(const SIMDVector3i &v) const { return (x >= v.x || y >= v.y || z <= v.z); } // modification functions SIMDVector3i Min(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_min_epi32(m128i, v.m128i); return r; } SIMDVector3i Max(const SIMDVector3i &v) const { SIMDVector3i r; r.m128i = _mm_max_epi32(m128i, v.m128i); return r; } SIMDVector3i Clamp(const SIMDVector3i &lBounds, const SIMDVector3i &uBounds) const { SIMDVector3i r; r.m128i = _mm_min_epi32(uBounds.m128i, _mm_max_epi32(lBounds.m128i, m128i)); return r; } SIMDVector3i Abs() const { SIMDVector3i r; r.m128i = _mm_abs_epi32(m128i); return r; } SIMDVector3i Saturate() const { SIMDVector3i r; r.m128i = _mm_min_epi32(_mm_set1_epi32(1), _mm_max_epi32(_mm_setzero_si128(), m128i)); return r; } SIMDVector3i Snap(const SIMDVector3i &v) const { return SIMDVector3i(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z)); } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128i m128i; struct { int32 x, y, z; }; struct { int32 r, g, b; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector3i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector4i { // constructors inline SIMDVector4i() {} inline SIMDVector4i(int32 x_, int32 y_, int32 z_, int32 w_) { m128i = _mm_set_epi32(w_, z_, y_, x_); } inline SIMDVector4i(const int32 *p) { m128i = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); } inline SIMDVector4i(const SIMDVector4i &v) : m128i(v.m128i) {} SIMDVector4i(const Vector4i &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(int32 x_, int32 y_, int32 z_, int32 w_) { m128i = _mm_set_epi32(w_, z_, y_, x_); } void Set(const SIMDVector2i &v) { m128i = v.m128i; } void Set(const Vector4i &v); void SetZero() { m128i = _mm_setzero_si128(); } // new vector inline SIMDVector4i operator+(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_add_epi32(m128i, v.m128i); return r; } inline SIMDVector4i operator-(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_sub_epi32(m128i, v.m128i); return r; } inline SIMDVector4i operator*(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_mul_epi32(m128i, v.m128i); return r; } inline SIMDVector4i operator/(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_set_epi32(x / v.x, y / v.y, z / v.z, w / v.w); return r; } inline SIMDVector4i operator%(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_set_epi32(x % v.x, y % v.y, z % v.z, w / v.w); return r; } inline SIMDVector4i operator&(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_and_si128(m128i, v.m128i); return r; } inline SIMDVector4i operator|(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_or_si128(m128i, v.m128i); return r; } inline SIMDVector4i operator^(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_xor_si128(m128i, v.m128i); return r; } // scalar operators inline SIMDVector4i operator+(const int32 v) const { SIMDVector4i r; r.m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector4i operator-(const int32 v) const { SIMDVector4i r; r.m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector4i operator*(const int32 v) const { SIMDVector4i r; r.m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector4i operator/(const int32 v) const { SIMDVector4i r; r.m128i = _mm_set_epi32(w / v, z / v, y / v, x / v); return r; } inline SIMDVector4i operator%(const int32 v) const { SIMDVector4i r; r.m128i = _mm_set_epi32(w % v, z % v, y % v, x % v); return r; } inline SIMDVector4i operator&(const int32 v) const { SIMDVector4i r; r.m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector4i operator|(const int32 v) const { SIMDVector4i r; r.m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return r; } inline SIMDVector4i operator^(const int32 v) const { SIMDVector4i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return r; } // no params inline SIMDVector4i operator~() const { SIMDVector4i r; r.m128i = _mm_andnot_si128(m128i, m128i); return r; } inline SIMDVector4i operator-() const { SIMDVector4i r; r.m128i = _mm_xor_si128(m128i, _mm_set1_epi32(0x7FFFFFFF)); return r; } // comparison operators inline bool operator==(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFFFF) == 0xFFFF; } inline bool operator!=(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_cmpeq_epi32(m128i, v.m128i)) & 0xFFFF) != 0xFFFF; } inline bool operator<=(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmplt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x3333) == 0x3333; } inline bool operator>=(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_xor_si128(_mm_cmpgt_epi32(m128i, v.m128i), _mm_cmpeq_epi32(m128i, v.m128i))) & 0x3333) == 0x3333; } inline bool operator<(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) & 0x3333) == 0x3333; } inline bool operator>(const SIMDVector4i &v) const { return (_mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) & 0x3333) == 0x3333; } // modifies this vector inline SIMDVector4i &operator+=(const SIMDVector4i &v) { m128i = _mm_add_epi32(m128i, v.m128i); return *this; } inline SIMDVector4i &operator-=(const SIMDVector4i &v) { m128i = _mm_sub_epi32(m128i, v.m128i); return *this; } inline SIMDVector4i &operator*=(const SIMDVector4i &v) { m128i = _mm_mul_epi32(m128i, v.m128i); return *this; } inline SIMDVector4i &operator/=(const SIMDVector4i &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } inline SIMDVector4i &operator%=(const SIMDVector4i &v) { x %= v.x; y %= v.y; z %= v.z; w %= v.w; return *this; } inline SIMDVector4i &operator&=(const SIMDVector4i &v) { m128i = _mm_and_si128(m128i, v.m128i); return *this; } inline SIMDVector4i &operator|=(const SIMDVector4i &v) { m128i = _mm_or_si128(m128i, v.m128i); return *this; } inline SIMDVector4i &operator^=(const SIMDVector4i &v) { m128i = _mm_xor_si128(m128i, v.m128i); return *this; } // scalar operators inline SIMDVector4i &operator+=(const int32 v) { m128i = _mm_add_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator-=(const int32 v) { m128i = _mm_sub_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator*=(const int32 v) { m128i = _mm_mul_epi32(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator/=(const int32 v) { x /= v; y /= v; z /= v; w /= v; return *this; } inline SIMDVector4i &operator%=(const int32 v) { x %= v; y %= v; z %= v; w %= v; return *this; } inline SIMDVector4i &operator&=(const int32 v) { m128i = _mm_and_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator|=(const int32 v) { m128i = _mm_or_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator^=(const int32 v) { m128i = _mm_xor_si128(m128i, _mm_set1_epi32(v)); return *this; } inline SIMDVector4i &operator=(const SIMDVector4i &v) { m128i = v.m128i; return *this; } SIMDVector4i &operator=(const Vector4i &v); // index accessors //const int32 &operator[](int32 i) const { return (&x)[i]; } //int32 &operator[](int32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // to floatx const Vector4i &GetFloat4() const { return reinterpret_cast<const Vector4i &>(*this); } Vector4i &GetFloat4() { return reinterpret_cast<Vector4i &>(*this); } operator const Vector4i &() const { return reinterpret_cast<const Vector4i &>(*this); } operator Vector4i &() { return reinterpret_cast<Vector4i &>(*this); } // partial comparisons bool AnyLess(const SIMDVector4i &v) const { return _mm_movemask_epi8(_mm_cmplt_epi32(m128i, v.m128i)) != 0x00; } bool AnyLessEqual(const SIMDVector4i &v) const { return (x <= v.x || y <= v.y || z <= v.z || w <= v.w); } bool AnyGreater(const SIMDVector4i &v) const { return _mm_movemask_epi8(_mm_cmpgt_epi32(m128i, v.m128i)) != 0x00; } bool AnyGreaterEqual(const SIMDVector4i &v) const { return (x >= v.x || y >= v.y || z >= v.z || w >= v.w); } // modification functions SIMDVector4i Min(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_min_epi32(m128i, v.m128i); return r; } SIMDVector4i Max(const SIMDVector4i &v) const { SIMDVector4i r; r.m128i = _mm_max_epi32(m128i, v.m128i); return r; } SIMDVector4i Clamp(const SIMDVector4i &lBounds, const SIMDVector4i &uBounds) const { SIMDVector4i r; r.m128i = _mm_min_epi32(uBounds.m128i, _mm_max_epi32(lBounds.m128i, m128i)); return r; } SIMDVector4i Abs() const { SIMDVector4i r; r.m128i = _mm_abs_epi32(m128i); return r; } SIMDVector4i Saturate() const { SIMDVector4i r; r.m128i = _mm_min_epi32(_mm_set1_epi32(1), _mm_max_epi32(_mm_setzero_si128(), m128i)); return r; } SIMDVector4i Snap(const SIMDVector4i &v) const { return SIMDVector4i(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z), Math::Snap(w, v.w)); } // swap void Swap(SIMDVector4i &v) { __m128i temp = m128i; m128i = v.m128i; v.m128i = temp; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128i m128i; struct { int32 x, y, z, w; }; struct { int32 r, g, b, a; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector4i &Zero, &One, &NegativeOne; }; //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<file_sep>/Editor/Source/Editor/MapEditor/EditorGeometryEditMode.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorGeometryEditMode.h" // TODO: MOVE ME // static void CreateCubeBuilderBrush(BrushSource *pBrushSource, float Radius) // { // uint32 i; // BrushSource::FaceSource *pFaceSources[6]; // // pBrushSource->ClearFaces(); // for (i = 0; i < 6; i++) // { // pFaceSources[i] = new BrushSource::FaceSource(); // pFaceSources[i]->MaterialName = g_pEngine->GetDefaultMaterialName(); // pFaceSources[i]->Vertices.Reserve(4); // pBrushSource->AddFace(pFaceSources[i]); // } // // float halfRadius = Radius * 0.5f; // // // top // pFaceSources[0]->TextureOrigin.Set(-halfRadius, halfRadius, -halfRadius); // pFaceSources[0]->TextureUDirection.Set(1.0f, 0.0f, 0.0f); // pFaceSources[0]->TextureVDirection.Set(0.0f, 0.0f, 1.0f); // pFaceSources[0]->Vertices.Add(Vector3(-halfRadius, halfRadius, -halfRadius)); // pFaceSources[0]->Vertices.Add(Vector3(-halfRadius, halfRadius, halfRadius)); // pFaceSources[0]->Vertices.Add(Vector3(halfRadius, halfRadius, halfRadius)); // pFaceSources[0]->Vertices.Add(Vector3(halfRadius, halfRadius, -halfRadius)); // // // bottom // pFaceSources[1]->TextureOrigin.Set(-halfRadius, -halfRadius, -halfRadius); // pFaceSources[1]->TextureUDirection.Set(1.0f, 0.0f, 0.0f); // pFaceSources[1]->TextureVDirection.Set(0.0f, 0.0f, 1.0f); // pFaceSources[1]->Vertices.Add(Vector3(-halfRadius, -halfRadius, -halfRadius)); // pFaceSources[1]->Vertices.Add(Vector3(halfRadius, -halfRadius, -halfRadius)); // pFaceSources[1]->Vertices.Add(Vector3(halfRadius, -halfRadius, halfRadius)); // pFaceSources[1]->Vertices.Add(Vector3(-halfRadius, -halfRadius, halfRadius)); // // // left side // pFaceSources[2]->TextureOrigin.Set(-halfRadius, halfRadius, -halfRadius); // pFaceSources[2]->TextureUDirection.Set(0.0f, 0.0f, 1.0f); // pFaceSources[2]->TextureVDirection.Set(0.0f, -1.0f, 0.0f); // pFaceSources[2]->Vertices.Add(Vector3(-halfRadius, halfRadius, -halfRadius)); // pFaceSources[2]->Vertices.Add(Vector3(-halfRadius, -halfRadius, -halfRadius)); // pFaceSources[2]->Vertices.Add(Vector3(-halfRadius, -halfRadius, halfRadius)); // pFaceSources[2]->Vertices.Add(Vector3(-halfRadius, halfRadius, halfRadius)); // // // right side // pFaceSources[3]->TextureOrigin.Set(halfRadius, halfRadius, -halfRadius); // pFaceSources[3]->TextureUDirection.Set(0.0f, 0.0f, 1.0f); // pFaceSources[3]->TextureVDirection.Set(0.0f, -1.0f, 0.0f); // pFaceSources[3]->Vertices.Add(Vector3(halfRadius, halfRadius, -halfRadius)); // pFaceSources[3]->Vertices.Add(Vector3(halfRadius, halfRadius, halfRadius)); // pFaceSources[3]->Vertices.Add(Vector3(halfRadius, -halfRadius, halfRadius)); // pFaceSources[3]->Vertices.Add(Vector3(halfRadius, -halfRadius, -halfRadius)); // // // front // pFaceSources[4]->TextureOrigin.Set(-halfRadius, halfRadius, halfRadius); // pFaceSources[4]->TextureUDirection.Set(1.0f, 0.0f, 0.0f); // pFaceSources[4]->TextureVDirection.Set(0.0f, -1.0f, 0.0f); // pFaceSources[4]->Vertices.Add(Vector3(-halfRadius, halfRadius, halfRadius)); // pFaceSources[4]->Vertices.Add(Vector3(-halfRadius, -halfRadius, halfRadius)); // pFaceSources[4]->Vertices.Add(Vector3(halfRadius, -halfRadius, halfRadius)); // pFaceSources[4]->Vertices.Add(Vector3(halfRadius, halfRadius, halfRadius)); // // // back // pFaceSources[5]->TextureOrigin.Set(-halfRadius, halfRadius, -halfRadius); // pFaceSources[5]->TextureUDirection.Set(1.0f, 0.0f, 0.0f); // pFaceSources[5]->TextureVDirection.Set(0.0f, -1.0f, 0.0f); // pFaceSources[5]->Vertices.Add(Vector3(-halfRadius, halfRadius, -halfRadius)); // pFaceSources[5]->Vertices.Add(Vector3(halfRadius, halfRadius, -halfRadius)); // pFaceSources[5]->Vertices.Add(Vector3(halfRadius, -halfRadius, -halfRadius)); // pFaceSources[5]->Vertices.Add(Vector3(-halfRadius, -halfRadius, -halfRadius)); // } EditorGeometryEditMode::EditorGeometryEditMode(EditorMap *pMap) : EditorEditMode(pMap) { } EditorGeometryEditMode::~EditorGeometryEditMode() { // release references to our objects //SAFE_RELEASE(m_pBuilderBrushEntity); //SAFE_RELEASE(m_pBuilderBrush); } void EditorGeometryEditMode::SetBuilderBrushCube(const float &Radius) { } void EditorGeometryEditMode::PerformCSGAdd() { // if (m_pBuilderBrush == NULL) // return; // // // generate new entity id // uint32 mapEntityId = m_pMapSource->GenerateObjectId(); // uint32 worldEntityId = m_pWorld->AllocateEntityId(); // // // create a new brush, cloning the state of the builder brush, and insert it into the csg tree // CSGCompilerBrush *pNewBrush = new CSGCompilerBrush(); // pNewBrush->CopyBrush(m_pBuilderBrush, mapEntityId, CSG_OPERATOR_ADD, "Brush"); // m_pCSGCompiler->AddBrush(pNewBrush, NULL); // // // create the source for the brush, and add it to the map source // EntitySource *pEntitySource = new EntitySource(); // pEntitySource->SetBrushSource(new BrushSource()); // pNewBrush->UpdateSource(pEntitySource); // m_pMapSource->AddEntityDefinition(pEntitySource); // // // create entity // EditorBrushEntity *pEditorBrushEntity = new EditorBrushEntity(worldEntityId, pNewBrush); // m_pWorld->AddEntity(pEditorBrushEntity); // AddEntityIdMapping(mapEntityId, worldEntityId); // pEditorBrushEntity->Release(); // // // free mem // pNewBrush->Release(); // // // redraw // RedrawAllViewports(); } void EditorGeometryEditMode::PerformCSGSubtract() { } void EditorGeometryEditMode::PerformCSGIntersection() { } void EditorGeometryEditMode::PerformCSGDeintersection() { } bool EditorGeometryEditMode::Initialize(ProgressCallbacks *pProgressCallbacks) { if (!EditorEditMode::Initialize(pProgressCallbacks)) return false; // // builder brush // { // m_pBuilderBrush = m_pCSGCompiler->GetBrush(BUILDER_BRUSH_ENTITY_ID); // if (m_pBuilderBrush == NULL) // { // Log_ErrorPrintf("Could not find builder brush in CSG compiler."); // return false; // } // } // // // builder brush entity // { // uint32 worldEntityId = LookupWorldEntityId(BUILDER_BRUSH_ENTITY_ID); // if (worldEntityId == 0) // { // Log_ErrorPrintf("Could not find builder brush entity in mapping table."); // return false; // } // // Entity *pEntity = m_pWorld->GetEntityById(worldEntityId); // if (pEntity == NULL) // { // Log_ErrorPrintf("Could not find builder brush entity in world."); // return false; // } // // m_pBuilderBrushEntity = pEntity->SafeCast<EditorBuilderBrushEntity>(); // if (m_pBuilderBrushEntity == NULL) // { // Log_ErrorPrintf("Builder brush is of incorrect type. (%s)", pEntity->GetTypeInfo()->GetName()); // pEntity->Release(); // return false; // } // } return true; } void EditorGeometryEditMode::Activate() { EditorEditMode::Activate(); } void EditorGeometryEditMode::Deactivate() { EditorEditMode::Deactivate(); } void EditorGeometryEditMode::Update(const float timeSinceLastUpdate) { EditorEditMode::Update(timeSinceLastUpdate); } void EditorGeometryEditMode::OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) { EditorEditMode::OnActiveViewportChanged(pOldActiveViewport, pNewActiveViewport); } bool EditorGeometryEditMode::HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) { return EditorEditMode::HandleViewportKeyboardInputEvent(pViewport, pKeyboardEvent); } bool EditorGeometryEditMode::HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) { return EditorEditMode::HandleViewportMouseInputEvent(pViewport, pMouseEvent); } bool EditorGeometryEditMode::HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) { return EditorEditMode::HandleViewportWheelInputEvent(pViewport, pWheelEvent); } void EditorGeometryEditMode::OnViewportDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterWorld(pViewport); } void EditorGeometryEditMode::OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawBeforeWorld(pViewport); } void EditorGeometryEditMode::OnViewportDrawAfterPost(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterPost(pViewport); } void EditorGeometryEditMode::OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawAfterWorld(pViewport); } void EditorGeometryEditMode::OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawBeforeWorld(pViewport); } <file_sep>/Engine/Source/OpenGLES2Renderer/CMakeLists.txt set(HEADER_FILES OpenGLES2Common.h OpenGLES2ConstantLibrary.h OpenGLES2CVars.h OpenGLES2Defines.h OpenGLES2GPUBuffer.h OpenGLES2GPUContext.h OpenGLES2GPUShaderProgram.h OpenGLES2GPUTexture.h OpenGLES2Renderer.h OpenGLES2RendererOutputBuffer.h ) set(SOURCE_FILES OpenGLES2ConstantLibrary.cpp OpenGLES2CVars.cpp OpenGLES2Defines.cpp OpenGLES2GPUBuffer.cpp OpenGLES2GPUContext.cpp OpenGLES2GPUShaderProgram.cpp OpenGLES2GPUTexture.cpp OpenGLES2Renderer.cpp OpenGLES2RendererOutputBuffer.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${OPENGL_INCLUDE_DIR} ${SDL2_INCLUDE_DIR}) add_library(EngineOpenGLES2Renderer STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineOpenGLES2Renderer EngineMain EngineCore glad ${SDL2_LIBRARY}) <file_sep>/Editor/Source/Editor/MapEditor/EditorMapEditMode.h #include "Editor/MapEditor/EditorEditMode.h" struct ui_EditorMapEditMode; class EditorMapEditMode : public EditorEditMode { Q_OBJECT public: EditorMapEditMode(EditorMap *pMap); ~EditorMapEditMode(); // property change callback void OnMapPropertyChanged(const char *propertyName, const char *propertyValue); // implemented base methods virtual bool Initialize(ProgressCallbacks *pProgressCallbacks) override; virtual QWidget *CreateUI(QWidget *parentWidget) override; virtual void Activate() override; virtual void Deactivate() override; virtual void Update(const float timeSinceLastUpdate) override; virtual void OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) override; virtual void OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) override; virtual void OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterPost(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) override; virtual bool HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) override; virtual bool HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) override; virtual bool HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) override; // update the summary void UpdateSummary(); private: ui_EditorMapEditMode *m_ui; private Q_SLOTS: // ui events void OnUIShowSkyChanged(bool checked); void OnUIShowSunChanged(bool checked); }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUDevice.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" #include "D3D12Renderer/D3D12CommandQueue.h" class D3D12GPUSamplerState : public GPUSamplerState { public: D3D12GPUSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &samplerHandle); virtual ~D3D12GPUSamplerState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12DescriptorHandle &GetSamplerHandle() { return m_samplerHandle; } private: D3D12GPUDevice *m_pDevice; D3D12DescriptorHandle m_samplerHandle; }; class D3D12GPURasterizerState : public GPURasterizerState { public: D3D12GPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc, const D3D12_RASTERIZER_DESC *pD3DRasterizerDesc); virtual ~D3D12GPURasterizerState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12_RASTERIZER_DESC *GetD3DRasterizerStateDesc() { return &m_D3DRasterizerDesc; } private: D3D12_RASTERIZER_DESC m_D3DRasterizerDesc; }; class D3D12GPUDepthStencilState : public GPUDepthStencilState { public: D3D12GPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc, const D3D12_DEPTH_STENCIL_DESC *pD3DDepthStencilDesc); virtual ~D3D12GPUDepthStencilState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12_DEPTH_STENCIL_DESC *GetD3DDepthStencilDesc() { return &m_D3DDepthStencilDesc; } private: D3D12_DEPTH_STENCIL_DESC m_D3DDepthStencilDesc; }; class D3D12GPUBlendState : public GPUBlendState { public: D3D12GPUBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc, const D3D12_BLEND_DESC *pD3DBlendDesc); virtual ~D3D12GPUBlendState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12_BLEND_DESC *GetD3DBlendDesc() { return &m_D3DBlendDesc; } private: D3D12_BLEND_DESC m_D3DBlendDesc; }; class D3D12GPUDevice : public GPUDevice { public: // shared command queue structure struct CopyCommandQueue { CopyCommandQueue() : pCommandQueue(nullptr), pCommandAllocator(nullptr), pCommandList(nullptr) { } ~CopyCommandQueue() { if (pCommandList != nullptr) pCommandQueue->ReleaseCommandList(pCommandList); if (pCommandAllocator != nullptr) pCommandQueue->ReleaseCommandAllocator(pCommandAllocator); delete pCommandQueue; } D3D12CommandQueue *pCommandQueue; ID3D12CommandAllocator *pCommandAllocator; ID3D12GraphicsCommandList *pCommandList; Mutex Lock; }; typedef Array<CopyCommandQueue> CopyCommandQueueArray; // copy queue reference struct CopyQueueReference { CopyQueueReference(D3D12GPUDevice *pDevice); ~CopyQueueReference(); bool HasContext() const; D3D12GPUDevice *pDevice; D3D12CommandQueue *pQueue; ID3D12GraphicsCommandList *pCommandList; bool ContextNeedsRelease; }; public: D3D12GPUDevice(HMODULE hD3D12Module, IDXGIFactory4 *pDXGIFactory, IDXGIAdapter3 *pDXGIAdapter, ID3D12Device *pD3DDevice, D3D_FEATURE_LEVEL D3DFeatureLevel, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, PIXEL_FORMAT outputBackBufferFormat, PIXEL_FORMAT outputDepthStencilFormat, uint32 frameLatency); virtual ~D3D12GPUDevice(); // Accessors. virtual RENDERER_PLATFORM GetPlatform() const override final; virtual RENDERER_FEATURE_LEVEL GetFeatureLevel() const override final; virtual TEXTURE_PLATFORM GetTexturePlatform() const override final; virtual void GetCapabilities(RendererCapabilities *pCapabilities) const override final; virtual bool CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat = nullptr) const override final; virtual void CorrectProjectionMatrix(float4x4 &projectionMatrix) const override final; virtual float GetTexelOffset() const override final; // Creates a swap chain on an existing window. virtual GPUOutputBuffer *CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) override final; virtual GPUOutputBuffer *CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) override final; // Resource creation virtual GPUQuery *CreateQuery(GPU_QUERY_TYPE type) override final; virtual GPUBuffer *CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData = nullptr) override final; virtual GPUTexture1D *CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture1DArray *CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2D *CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2DArray *CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture3D *CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr, const uint32 *pInitialDataSlicePitch = nullptr) override final; virtual GPUTextureCube *CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTextureCubeArray *CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUDepthTexture *CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) override final; virtual GPUSamplerState *CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) override final; virtual GPURenderTargetView *CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilBufferView *CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) override final; virtual GPUComputeView *CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilState *CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) override final; virtual GPURasterizerState *CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) override final; virtual GPUBlendState *CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) override final; virtual GPUShaderProgram *CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) override final; virtual GPUShaderProgram *CreateComputeProgram(ByteStream *pByteCodeStream) override final; // off-thread resource creation virtual void BeginResourceBatchUpload() override final; virtual void EndResourceBatchUpload() override final; // private methods IDXGIFactory3 *GetDXGIFactory() const { return m_pDXGIFactory; } IDXGIAdapter3 *GetDXGIAdapter() const { return m_pDXGIAdapter; } ID3D12Device *GetD3DDevice() const { return m_pD3DDevice; } uint32 GetFrameLatency() const { return m_frameLatency; } // creation interface D3D12GPUContext *InitializeAndCreateContext(); void SetImmediateContext(D3D12GPUContext *pContext); void SetThreadCopyCommandQueue(ID3D12GraphicsCommandList *pCommandList); // legacy root signatures ID3D12RootSignature *GetLegacyGraphicsRootSignature() const { return m_pLegacyGraphicsRootSignature; } ID3D12RootSignature *GetLegacyComputeRootSignature() const { return m_pLegacyComputeRootSignature; } // cpu descriptor heaps D3D12DescriptorHeap *GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE type) { return m_pCPUDescriptorHeaps[type]; } const D3D12DescriptorHandle GetNullCBVDescriptorHandle() { return m_nullCBVDescriptorHandle; } const D3D12DescriptorHandle GetNullSRVDescriptorHandle() { return m_nullSRVDescriptorHandle; } const D3D12DescriptorHandle GetNullSamplerHandle() { return m_nullSamplerHandle; } // shader pipeline state lock ReadWriteLock *GetShaderPipelineStateLock() { return &m_shaderPipelineStateLock; } // default states D3D12GPURasterizerState *GetDefaultRasterizerState() const { return m_pDefaultRasterizerState; } D3D12GPUDepthStencilState *GetDefaultDepthStencilState() const { return m_pDefaultDepthStencilState; } D3D12GPUBlendState *GetDefaultBlendState() const { return m_pDefaultBlendState; } // constant buffer management ID3D12Resource *GetConstantBufferResource(uint32 index); const D3D12DescriptorHandle *GetConstantBufferDescriptor(uint32 index) const; // create a resource barrier on the current command list. NOTE: doesn't flush the copy command list, assumes batching void ResourceBarrier(ID3D12Resource *pResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState); // resource freeing - done on graphics queue void ScheduleResourceForDeletion(ID3D12Pageable *pResource); void ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle); // copy queue accessor void ScheduleCopyResourceForDeletion(ID3D12Pageable *pResource); void GetFreeCopyCommandQueue(); void ReleaseCopyCommandQueue(); // clean up after resources are created off-thread // returns true if there were any transitions bool TransitionPendingResources(D3D12CommandQueue *pCommandQueue); private: bool CreateCommandQueues(uint32 copyCommandQueueCount); bool CreateLegacyRootSignatures(); bool CreateCPUDescriptorHeaps(); bool CreateDefaultStates(); bool CreateConstantStorage(); ID3D12GraphicsCommandList *GetCurrentCopyCommandList(); HMODULE m_hD3D12Module; IDXGIFactory4 *m_pDXGIFactory; IDXGIAdapter3 *m_pDXGIAdapter; ID3D12Device *m_pD3DDevice; ID3D12InfoQueue *m_pD3DInfoQueue; D3D_FEATURE_LEVEL m_D3DFeatureLevel; RENDERER_FEATURE_LEVEL m_featureLevel; TEXTURE_PLATFORM m_texturePlatform; PIXEL_FORMAT m_outputBackBufferFormat; PIXEL_FORMAT m_outputDepthStencilFormat; uint32 m_frameLatency; // graphics command queue D3D12CommandQueue *m_pGraphicsCommandQueue; // copy command queues CopyCommandQueueArray m_copyCommandQueues; // immediate context D3D12GPUContext *m_pImmediateContext; // legacy root signature ID3D12RootSignature *m_pLegacyGraphicsRootSignature; ID3D12RootSignature *m_pLegacyComputeRootSignature; PFN_D3D12_SERIALIZE_ROOT_SIGNATURE m_fnD3D12SerializeRootSignature; // descriptor heaps D3D12DescriptorHeap *m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES]; D3D12DescriptorHandle m_nullCBVDescriptorHandle; D3D12DescriptorHandle m_nullSRVDescriptorHandle; D3D12DescriptorHandle m_nullSamplerHandle; // shader pipeline state lock ReadWriteLock m_shaderPipelineStateLock; // default states D3D12GPURasterizerState *m_pDefaultRasterizerState; D3D12GPUDepthStencilState *m_pDefaultDepthStencilState; D3D12GPUBlendState *m_pDefaultBlendState; // constant buffer storage struct ConstantBufferStorage { ID3D12Resource *pResource; D3D12DescriptorHandle DescriptorHandle; uint32 Size; }; MemArray<ConstantBufferStorage> m_constantBufferStorage; ID3D12Heap *m_pConstantBufferStorageHeap; // resources pending transition struct PendingResourceTransition { ID3D12Resource *pResource; D3D12_RESOURCE_STATES BeforeState; D3D12_RESOURCE_STATES AfterState; }; MemArray<PendingResourceTransition> m_pendingResourceTransitions; Mutex m_pendingResourceTransitionLock; }; <file_sep>/Engine/Source/ResourceCompiler/TextureGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/Texture.h" #include "Core/Image.h" #include "Core/PropertyTable.h" class TextureGenerator { friend class Texture; friend class Texture2D; friend class Texture2DArray; friend class TextureCube; public: class Properties { public: static const char *Usage; static const char *SourceSRGB; static const char *SourcePremultipliedAlpha; static const char *MaxFilter; static const char *AddressU; static const char *AddressV; static const char *AddressW; static const char *BorderColor; static const char *GenerateMipmaps; static const char *MipmapResizeFilter; static const char *NPOTMipmaps; static const char *EnableSRGB; static const char *EnablePremultipliedAlpha; static const char *EnableTextureCompression; }; public: TextureGenerator(); TextureGenerator(const TextureGenerator &copy); ~TextureGenerator(); const TEXTURE_TYPE GetTextureType() const { return m_eTextureType; } const TEXTURE_PLATFORM GetTexturePlatform() const { return m_eTexturePlatform; } const PIXEL_FORMAT GetPixelFormat() const { return m_ePixelFormat; } const uint32 GetMipLevels() const { return m_nMipLevels; } const uint32 GetArraySize() const { return m_nArraySize; } const uint32 GetWidth() const { return m_iWidth; } const uint32 GetHeight() const { return m_iHeight; } const uint32 GetDepth() const { return m_iDepth; } const Image *GetImage(uint32 arrayIndex, uint32 mipIndex) const; bool Create(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 arraySize, TEXTURE_USAGE usage = TEXTURE_USAGE_NONE); bool Create(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 mipLevels, uint32 arraySize, TEXTURE_USAGE usage = TEXTURE_USAGE_NONE); bool Load(const char *fileName, ByteStream *pStream); bool Save(ByteStream *pOutputStream) const; bool Resize(IMAGE_RESIZE_FILTER resizeFilter, uint32 width, uint32 height, uint32 depth); bool Optimize(); bool Compile(ByteStream *pOutputStream, TEXTURE_PLATFORM platform = NUM_TEXTURE_PLATFORMS) const; void SetTexturePlatform(TEXTURE_PLATFORM platform); void SetTextureUsage(TEXTURE_USAGE usage); void SetTextureFilter(TEXTURE_FILTER filter); void SetTextureAddressModeU(TEXTURE_ADDRESS_MODE mode); void SetTextureAddressModeV(TEXTURE_ADDRESS_MODE mode); void SetTextureAddressModeW(TEXTURE_ADDRESS_MODE mode); void SetMipMapResizeFilter(IMAGE_RESIZE_FILTER filter); void SetGenerateMipmaps(bool enabled); void SetSourcePremultipliedAlpha(bool enabled); void SetEnablePremultipliedAlpha(bool enabled); void SetEnableTextureCompression(bool enabled); void SetEnableSRGB(bool enabled); void SetSourceSRGB(bool enabled); bool AddMask(uint32 arrayIndex, const Image *pMaskImage); bool AddImage(const Image *pImage); bool SetImage(uint32 arrayIndex, const Image *pImage); bool SetImage(uint32 arrayIndex, uint32 mipIndex, const Image *pImage); void SetArraySize(uint32 newArraySize); bool AnalyzeImage(); PIXEL_FORMAT GetBestPixelFormat(bool allowCompression) const; bool GenerateMipmaps(); bool ConvertToPremultipliedAlpha(); bool ConvertToPixelFormat(PIXEL_FORMAT newPixelFormat); bool UncompressImage(); bool RemoveAlphaChannel(); bool RemoveAlphaChannelIfOpaque(); bool ConvertBGRToRGB(); bool ConvertToTextureArray(); bool ImportDDS(const char *fileName, ByteStream *pStream); bool ImportFromImage(const char *fileName, ByteStream *pStream); bool ImportFromImage(const Image &image); private: bool InternalCreate(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 mipLevels, uint32 arraySize); void SetDefaultProperties(TEXTURE_USAGE usage); bool InternalCompile(ByteStream *pOutputStream); TEXTURE_TYPE m_eTextureType; TEXTURE_PLATFORM m_eTexturePlatform; PropertyTable m_propertyList; // image details PIXEL_FORMAT m_ePixelFormat; uint32 m_nMipLevels; uint32 m_nArraySize; // discovered via analysis bool m_analyzed; bool m_bHasAlpha; bool m_bHasAlphaLevels; // mirrors "level 0" mip uint32 m_iWidth; uint32 m_iHeight; uint32 m_iDepth; // image array Image *m_pImages; uint32 m_nImages; }; <file_sep>/Editor/Source/Editor/MapEditor/EditorWorldOutlinerWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorWorldOutlinerWidget.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "ResourceCompiler/ObjectTemplate.h" #include "Editor/EditorHelpers.h" EditorWorldOutlinerWidget::EditorWorldOutlinerWidget(QWidget *pParent) : QWidget(pParent), m_pSearchBox(nullptr), m_pTreeView(nullptr), m_model(3), m_pEntityContainer(nullptr), m_pVolumesContainer(nullptr) { // create ui { QSizePolicy expandAndVerticalStretchSizePolicy; expandAndVerticalStretchSizePolicy.setHorizontalPolicy(QSizePolicy::Expanding); expandAndVerticalStretchSizePolicy.setVerticalPolicy(QSizePolicy::Expanding); expandAndVerticalStretchSizePolicy.setVerticalStretch(1); QFormLayout *formLayout = new QFormLayout(this); formLayout->setContentsMargins(2, 2, 2, 2); m_pSearchBox = new QLineEdit(this); m_pSearchBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pSearchBox->setFixedHeight(20); formLayout->addRow(tr("Search: "), m_pSearchBox); m_pTreeView = new QTreeView(this); m_pTreeView->setSizePolicy(expandAndVerticalStretchSizePolicy); formLayout->addRow(m_pTreeView); setLayout(formLayout); } // initialize model columns m_model.SetColumnTitle(0, tr("Name")); m_model.SetColumnTitle(1, tr("Type")); m_model.SetColumnTitle(2, tr("Location")); // initialize model containers m_pEntityContainer = m_model.CreateContainer(tr("Entities")); m_pVolumesContainer = m_model.CreateContainer(tr("Volumes")); // set the model m_pTreeView->setModel(&m_model); // connect events connect(m_pTreeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(OnTreeViewItemClicked(const QModelIndex &))); connect(m_pTreeView, SIGNAL(activated(const QModelIndex &)), this, SLOT(OnTreeViewItemActivated(const QModelIndex &))); } EditorWorldOutlinerWidget::~EditorWorldOutlinerWidget() { m_pTreeView->setModel(nullptr); } void EditorWorldOutlinerWidget::Clear() { m_pEntityContainer->RemoveAllItems(); m_pVolumesContainer->RemoveAllItems(); } void EditorWorldOutlinerWidget::AddEntity(const EditorMapEntity *pEntity) { SimpleTreeModel::Item *pItem = m_pEntityContainer->CreateItem(); pItem->SetText(0, ConvertStringToQString(pEntity->GetEntityData()->GetEntityName())); pItem->SetText(1, ConvertStringToQString(pEntity->GetTemplate()->GetTypeName())); pItem->SetText(2, ConvertStringToQString(StringConverter::Float3ToString(pEntity->GetPosition()))); pItem->SetUserData(const_cast<void *>(reinterpret_cast<const void *>(pEntity))); } void EditorWorldOutlinerWidget::OnEntityPositionChanged(const EditorMapEntity *pEntity) { int itemIndex = m_pEntityContainer->FindItemIndexByUserData(const_cast<void *>(reinterpret_cast<const void *>(pEntity))); DebugAssert(itemIndex >= 0); SimpleTreeModel::Item *pItem = m_pEntityContainer->GetItem(itemIndex); pItem->SetText(2, ConvertStringToQString(StringConverter::Float3ToString(pEntity->GetPosition()))); } void EditorWorldOutlinerWidget::RemoveEntity(const EditorMapEntity *pEntity) { int itemIndex = m_pEntityContainer->FindItemIndexByUserData(const_cast<void *>(reinterpret_cast<const void *>(pEntity))); DebugAssert(itemIndex >= 0); m_pEntityContainer->RemoveItem(itemIndex); } void EditorWorldOutlinerWidget::OnTreeViewItemClicked(const QModelIndex &index) { const SimpleTreeModel::Item *pItem = reinterpret_cast<SimpleTreeModel::Item *>(index.internalPointer()); if (pItem == nullptr) return; if (pItem->GetUserData() != nullptr) { if (pItem->GetParent() == m_pEntityContainer) OnEntitySelected(reinterpret_cast<EditorMapEntity *>(pItem->GetUserData())); //else if (pItem->GetParent() == m_pVolumesContainer) //OnVolumeSelected(); } } void EditorWorldOutlinerWidget::OnTreeViewItemActivated(const QModelIndex &index) { const SimpleTreeModel::Item *pItem = reinterpret_cast<SimpleTreeModel::Item *>(index.internalPointer()); if (pItem == nullptr) return; if (pItem->GetUserData() != nullptr) { if (pItem->GetParent() == m_pEntityContainer) OnEntityActivated(reinterpret_cast<EditorMapEntity *>(pItem->GetUserData())); //else if (pItem->GetParent() == m_pVolumesContainer) //OnVolumeActivated(); } } <file_sep>/Editor/Source/Editor/MapEditor/EditorGeometryEditMode.h #include "Editor/MapEditor/EditorEditMode.h" class EditorGeometryEditMode : public EditorEditMode { Q_OBJECT public: EditorGeometryEditMode(EditorMap *pMap); ~EditorGeometryEditMode(); // csg compiler //const CSGCompiler *GetCSGCompiler() const { return m_pCSGCompiler; } //CSGCompiler *GetCSGCompiler() { return m_pCSGCompiler; } // builder brush constructors void SetBuilderBrushCube(const float &Radius); // csg operations void PerformCSGAdd(); void PerformCSGSubtract(); void PerformCSGIntersection(); void PerformCSGDeintersection(); // implemented base methods virtual bool Initialize(ProgressCallbacks *pProgressCallbacks); virtual void Activate(); virtual void Deactivate(); virtual void Update(const float timeSinceLastUpdate); virtual void OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport); virtual void OnViewportDrawBeforeWorld(EditorMapViewport *pViewport); virtual void OnViewportDrawAfterWorld(EditorMapViewport *pViewport); virtual void OnViewportDrawAfterPost(EditorMapViewport *pViewport); virtual void OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport); virtual void OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport); virtual bool HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) override; virtual bool HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) override; virtual bool HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) override; private: //CSGCompiler *m_pCSGCompiler; // editor entities //CSGCompilerBrush *m_pBuilderBrush; //EditorBuilderBrushEntity *m_pBuilderBrushEntity; }; <file_sep>/Editor/Source/Editor/EditorResourceSelectionDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourceSelectionDialog.h" #include "Editor/EditorResourcePreviewWidget.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Engine/ResourceManager.h" Log_SetChannel(EditorResourceSelectionDialog); EditorResourceSelectionDialog::EditorResourceSelectionDialog(QWidget *pParent /*= NULL*/) : QDialog(pParent, Qt::WindowTitleHint), m_pModel(NULL), m_pReturnValueResourceType(NULL) { CreateUI(); NavigateToDirectory("/", false); } EditorResourceSelectionDialog::~EditorResourceSelectionDialog() { } bool EditorResourceSelectionDialog::NavigateToDirectory(const char *directory, bool addToHistory /* = true */) { if (m_pModel != NULL) { m_pTreeView->setModel(NULL); delete m_pModel; } QString directoryVisual; if (directory == NULL || directory[0] == '\0' || (directory[0] == '/' && directory[1] == '\0')) { m_pModel = new EditorResourceSelectionDialogModel(EmptyString, true, true, 0, this); directoryVisual = "/"; } else { m_pModel = new EditorResourceSelectionDialogModel(directory, true, true, 0, this); directoryVisual = directory; } if (m_resourceFilters.GetSize() > 0) m_pModel->SetResourceFilter(m_resourceFilters.GetBasePointer(), m_resourceFilters.GetSize()); m_pTreeView->setModel(m_pModel); // update the combo box m_pDirectoryComboBox->clear(); // split it at / QString tempPath; QStringList directoryComponents = directoryVisual.split('/', QString::SkipEmptyParts); for (int i = 0; i < directoryComponents.size(); i++) { if (tempPath.length() > 0) tempPath.append('/'); tempPath.append(directoryComponents[i]); m_pDirectoryComboBox->insertItem(0, g_pEditor->GetIconLibrary()->GetListViewDirectoryIcon(), tempPath); } // add the root m_pDirectoryComboBox->addItem(g_pEditor->GetIconLibrary()->GetListViewDirectoryIcon(), "/"); m_pDirectoryComboBox->setCurrentIndex(0); // add to history if (addToHistory) m_history.push(ConvertStringToQString(m_pModel->GetRootPath())); // update button states m_pBackButton->setEnabled((m_history.size() > 0)); m_pUpDirectoryButton->setEnabled((m_pModel->GetRootPath().GetLength() > 0)); // clear any preview m_pPreviewWidget->ClearPreview(); m_pSelectButton->setEnabled(false); m_pReturnValueResourceType = NULL; m_returnValueResourceName = EmptyString; return true; } void EditorResourceSelectionDialog::CreateUI() { QToolButton *pMakeDirectoryButton; QPushButton *pCancelButton; QSplitter *pMiddleSplitter; // setup form setWindowTitle(QStringLiteral("Select Resource")); resize(960, 400); // create ui elements QGridLayout *gridLayout = new QGridLayout(this); QHBoxLayout *hboxLayout = new QHBoxLayout(); { m_pDirectoryComboBox = new QComboBox(this); m_pDirectoryComboBox->setEditable(true); hboxLayout->addWidget(m_pDirectoryComboBox, 1); QHBoxLayout *hboxLayout2 = new QHBoxLayout(); { m_pBackButton = new QToolButton(this); m_pBackButton->setEnabled(false); m_pBackButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("Back", 16)); hboxLayout2->addWidget(m_pBackButton); m_pUpDirectoryButton = new QToolButton(this); m_pUpDirectoryButton->setEnabled(false); m_pUpDirectoryButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("UpDirectory", 16)); hboxLayout2->addWidget(m_pUpDirectoryButton); pMakeDirectoryButton = new QToolButton(this); pMakeDirectoryButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("NewDirectory", 16)); hboxLayout2->addWidget(pMakeDirectoryButton); } hboxLayout->addLayout(hboxLayout2); } gridLayout->addLayout(hboxLayout, 0, 0, 1, 1); //m_pTreeView = new QTreeView(this); //m_pTreeView->setExpandsOnDoubleClick(false); //gridLayout->addWidget(m_pTreeView, 1, 0, 1, 1); pMiddleSplitter = new QSplitter(this); m_pTreeView = new QTreeView(pMiddleSplitter); m_pTreeView->setExpandsOnDoubleClick(false); pMiddleSplitter->addWidget(m_pTreeView); m_pPreviewWidget = new EditorResourcePreviewWidget(pMiddleSplitter); pMiddleSplitter->addWidget(m_pPreviewWidget); gridLayout->addWidget(pMiddleSplitter, 1, 0, 1, 1); hboxLayout = new QHBoxLayout(); { m_pFilterTextLabel = new QLabel(this); hboxLayout->addWidget(m_pFilterTextLabel, 1); QHBoxLayout *hboxLayout2 = new QHBoxLayout(); { m_pSelectButton = new QPushButton(this); m_pSelectButton->setText(tr("Select")); m_pSelectButton->setDefault(true); hboxLayout2->addWidget(m_pSelectButton); pCancelButton = new QPushButton(this); pCancelButton->setText(tr("Cancel")); hboxLayout2->addWidget(pCancelButton); } hboxLayout->addLayout(hboxLayout2); } gridLayout->addLayout(hboxLayout, 2, 0, 1, 1); //m_pPreviewWidget = new EditorResourcePreviewWidget(this); //gridLayout->addWidget(m_pPreviewWidget, 3, 0, 1, 1); ////////////////////////////////////////////////////////////////////////// connect(m_pDirectoryComboBox, SIGNAL(activated(const QString &)), this, SLOT(OnDirectoryComboBoxActivated(const QString &))); connect(m_pBackButton, SIGNAL(clicked()), this, SLOT(OnBackButtonPressed())); connect(m_pUpDirectoryButton, SIGNAL(clicked()), this, SLOT(OnUpDirectoryButtonPressed())); connect(m_pTreeView, SIGNAL(activated(const QModelIndex &)), this, SLOT(OnTreeViewItemActivated(const QModelIndex &))); connect(m_pTreeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(OnTreeViewItemClicked(const QModelIndex &))); connect(m_pSelectButton, SIGNAL(clicked()), this, SLOT(OnSelectButtonClicked())); connect(pCancelButton, SIGNAL(clicked()), this, SLOT(OnCancelButtonClicked())); } void EditorResourceSelectionDialog::OnDirectoryComboBoxActivated(const QString &text) { // clear any leading / String directoryPath(ConvertQStringToString(text)); if (directoryPath.GetLength() > 0 && directoryPath[0] == '/') directoryPath.Erase(0, 1); // navigate to this path NavigateToDirectory(directoryPath); } void EditorResourceSelectionDialog::OnBackButtonPressed() { if (m_history.size() > 0) { String newPath(ConvertQStringToString(m_history.top())); m_history.pop(); NavigateToDirectory(newPath, false); } } void EditorResourceSelectionDialog::OnUpDirectoryButtonPressed() { if (m_pModel->GetRootPath().GetLength() > 0) { int32 pos = m_pModel->GetRootPath().RFind('/'); if (pos >= 0) { PathString newPath; newPath.AppendSubString(m_pModel->GetRootPath(), 0, pos); NavigateToDirectory(newPath); } else { // go to root NavigateToDirectory("/"); } } } void EditorResourceSelectionDialog::OnMakeDirectoryButtonPressed() { } void EditorResourceSelectionDialog::OnTreeViewItemActivated(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_pModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == NULL) return; if (pDirectoryNode->IsDirectory()) { // enter this directory, have to temporarily copy the string though, as navigating will destroy the node PathString directoryPathCopy; directoryPathCopy.AppendString(pDirectoryNode->GetFullName()); NavigateToDirectory(directoryPathCopy); } else { // select this item m_pReturnValueResourceType = pDirectoryNode->GetResourceTypeInfo(); m_returnValueResourceName = pDirectoryNode->GetFullName(); OnSelectButtonClicked(); } } void EditorResourceSelectionDialog::OnTreeViewItemClicked(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_pModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == NULL) return; // resource? if (pDirectoryNode->GetResourceTypeInfo() != NULL) { m_pPreviewWidget->SetPreviewResourceByName(pDirectoryNode->GetResourceTypeInfo(), pDirectoryNode->GetFullName()); m_pSelectButton->setEnabled(true); m_pReturnValueResourceType = pDirectoryNode->GetResourceTypeInfo(); m_returnValueResourceName = pDirectoryNode->GetFullName(); } else { m_pPreviewWidget->ClearPreview(); m_pSelectButton->setEnabled(false); m_pReturnValueResourceType = NULL; m_returnValueResourceName = EmptyString; } } void EditorResourceSelectionDialog::OnSelectButtonClicked() { done(1); } void EditorResourceSelectionDialog::OnCancelButtonClicked() { m_pReturnValueResourceType = NULL; m_returnValueResourceName = EmptyString; done(0); } void EditorResourceSelectionDialog::AddResourceFilter(const ResourceTypeInfo *pResourceTypeInfo) { m_resourceFilters.Add(pResourceTypeInfo); m_pModel->SetResourceFilter(m_resourceFilters.GetBasePointer(), m_resourceFilters.GetSize()); } <file_sep>/Engine/Source/Engine/StaticMesh.h #pragma once #include "Engine/Common.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "Renderer/RenderProxy.h" #include "Renderer/RendererTypes.h" #include "Renderer/VertexBufferBindingArray.h" namespace Physics { class CollisionShape; } class VertexBufferBindingArray; class Material; class ChunkFileReader; class StaticMesh : public Resource { DECLARE_RESOURCE_TYPE_INFO(StaticMesh, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(StaticMesh); public: struct Batch { uint32 MaterialIndex; uint32 StartIndex; uint32 NumIndices; }; class LOD { public: LOD(); ~LOD(); const bool IsLoaded() const { return m_loaded; } const LocalVertexFactory::Vertex *GetVertex(uint32 i) const { return &m_vertices[i]; } const uint32 GetVertexCount() const { return m_vertices.GetSize(); } const uint16 *GetIndices16() const { return reinterpret_cast<const uint16 *>(m_pIndices); } const uint32 *GetIndices32() const { return reinterpret_cast<const uint32 *>(m_pIndices); } const uint32 GetIndexCount() const { return m_indexCount; } const GPU_INDEX_FORMAT GetIndexFormat() const { return m_indexFormat; } const Batch *GetBatch(uint32 i) const { return &m_batches[i]; } const uint32 GetBatchCount() const { return m_batches.GetSize(); } const VertexBufferBindingArray *GetVertexBuffers() const { return &m_vertexBuffers; } GPUBuffer *GetIndexBuffer() const { return m_pIndexBuffer; } bool LoadFromStream(ByteStream *pStream, uint32 vertexFactoryFlags); void Unload(); bool CreateGPUResources() const; void ReleaseGPUResources() const; private: // GPU Data uint32 m_vertexFactoryFlags; MemArray<LocalVertexFactory::Vertex> m_vertices; void *m_pIndices; uint32 m_indexCount; GPU_INDEX_FORMAT m_indexFormat; // Rendering information MemArray<Batch> m_batches; // Data on GPU mutable VertexBufferBindingArray m_vertexBuffers; mutable GPUBuffer *m_pIndexBuffer; // loaded flag bool m_loaded; }; // constructor StaticMesh(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~StaticMesh(); // field accessors const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } const Physics::CollisionShape *GetCollisionShape() const { return m_pCollisionShape; } const uint32 GetVertexFactoryFlags() const { return m_vertexFactoryFlags; } // material access const Material *GetMaterial(uint32 i) const { return m_materials[i]; } const uint32 GetMaterialCount() const { return m_materials.GetSize(); } // lod access const LOD *GetLOD(uint32 i) const { DebugAssert(i < m_LODCount); return &m_pLODs[i]; } uint32 GetLODCount() const { return m_LODCount; } // binary serialization bool Load(const char *FileName, ByteStream *pStream); // resource binding & device resource management bool CreateGPUResources() const; void ReleaseGPUResources() const; bool CheckGPUResources() const; private: AABox m_boundingBox; Sphere m_boundingSphere; uint32 m_vertexFactoryFlags; const Physics::CollisionShape *m_pCollisionShape; PODArray<const Material *> m_materials; PODArray<uint32> m_LODOffsetTable; LOD *m_pLODs; uint32 m_LODCount; mutable bool m_GPUResourcesCreated; }; <file_sep>/Engine/Source/BlockEngine/PrecompiledHeader.cpp #include "BlockEngine/PrecompiledHeader.h" <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphNode.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphNode.h" #include "ResourceCompiler/ShaderGraph.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" //Log_SetChannel(ShaderGraphNode); DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode, Object, "ShaderGraphNode", "Description"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode) END_SHADER_GRAPH_NODE_OUTPUTS() Y_Define_NameTable(NameTables::ShaderGraphTextureSampleUnpackOperation) Y_NameTable_Entry("None", SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NONE) Y_NameTable_Entry("NormalMap", SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NORMAL_MAP) Y_NameTable_End() ShaderGraphNodeInput::ShaderGraphNodeInput() { m_pNode = NULL; m_iInputIndex = 0; m_pInputDesc = NULL; m_pSourceNode = NULL; m_iSourceOutputIndex = 0; m_eSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eFixupSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eValueType = SHADER_PARAMETER_TYPE_COUNT; } ShaderGraphNodeInput::~ShaderGraphNodeInput() { //if (m_pSourceNode != NULL) //m_pSourceNode->Release(); } void ShaderGraphNodeInput::Init(ShaderGraphNode *pNode, uint32 InputIndex, const SHADER_GRAPH_NODE_INPUT *pInputDesc) { m_pNode = pNode; m_iInputIndex = InputIndex; m_pInputDesc = pInputDesc; m_eValueType = pInputDesc->Type; } void ShaderGraphNodeInput::SetExpectedType(SHADER_PARAMETER_TYPE ExpectedType) { DebugAssert(m_pSourceNode == NULL); m_eValueType = ExpectedType; } bool ShaderGraphNodeInput::SetLink(const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { const ShaderGraphNodeOutput *pOutput = pSourceNode->GetOutput(OutputIndex); DebugAssert(pOutput != NULL); SHADER_PARAMETER_TYPE newValueType = GetTypeAfterSwizzle(pOutput->GetValueType(), Swizzle); if (newValueType == SHADER_PARAMETER_TYPE_COUNT) return false; // Check the types are compatible. SHADER_GRAPH_VALUE_SWIZZLE fixupSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; if (m_eValueType != SHADER_PARAMETER_TYPE_COUNT && m_eValueType != newValueType) { // Can we truncate it with a swizzle to be the correct type? if (!CanAutoTruncateType(&fixupSwizzle, m_eValueType, newValueType)) return false; // set fixup swizzle newValueType = GetTypeAfterSwizzle(m_eValueType, m_eFixupSwizzle); DebugAssert(newValueType == m_eValueType); } // unlink current node if present if (m_pSourceNode != NULL) ClearLink(); // link new node DebugAssert(pSourceNode != NULL); m_pSourceNode = pSourceNode; m_iSourceOutputIndex = OutputIndex; m_eSwizzle = Swizzle; m_eFixupSwizzle = fixupSwizzle; m_eValueType = newValueType; //m_pSourceNode->AddRef(); // fire input event if (!m_pNode->OnInputConnectionChange(m_iInputIndex)) { //m_pSourceNode->Release(); m_pSourceNode = NULL; m_iSourceOutputIndex = 0; m_eSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eFixupSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eValueType = m_pInputDesc->Type; return false; } // add output reference m_pSourceNode->GetOutput(OutputIndex)->AddLinkReference(); // link added //Log_DevPrintf("ShaderGraph: Link added '%s':%u (%s) -> '%s':%u (%s)", m_pSourceNode->GetName().GetCharArray(), OutputIndex, m_pSourceNode->GetTypeInfo()->GetName(), //m_pNode->GetName().GetCharArray(), m_iInputIndex, m_pNode->GetTypeInfo()->GetName()); return true; } void ShaderGraphNodeInput::ClearLink() { if (m_pSourceNode != NULL) { m_pSourceNode->GetOutput(m_iSourceOutputIndex)->RemoveLinkReference(); //m_pSourceNode->Release(); m_pSourceNode = NULL; m_iSourceOutputIndex = 0; m_eSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eFixupSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; } } bool ShaderGraphNodeInput::CanSwizzleType(SHADER_PARAMETER_TYPE ValueType, SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { if (Swizzle == SHADER_GRAPH_VALUE_SWIZZLE_NONE) return true; return (GetTypeAfterSwizzle(ValueType, Swizzle) != SHADER_PARAMETER_TYPE_COUNT); } SHADER_PARAMETER_TYPE ShaderGraphNodeInput::GetTypeAfterSwizzle(SHADER_PARAMETER_TYPE ValueType, SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { if (Swizzle == SHADER_GRAPH_VALUE_SWIZZLE_NONE) return ValueType; static const SHADER_PARAMETER_TYPE swizzleTypesInt[4] = { SHADER_PARAMETER_TYPE_INT, SHADER_PARAMETER_TYPE_INT2, SHADER_PARAMETER_TYPE_INT3, SHADER_PARAMETER_TYPE_INT4 }; //static const SHADER_PARAMETER_TYPE swizzleTypesUInt[4] = { SHADER_PARAMETER_TYPE_INT, SHADER_PARAMETER_TYPE_INT2, SHADER_PARAMETER_TYPE_INT3, SHADER_PARAMETER_TYPE_INT4 }; static const SHADER_PARAMETER_TYPE swizzleTypesFloat[4] = { SHADER_PARAMETER_TYPE_FLOAT, SHADER_PARAMETER_TYPE_FLOAT2, SHADER_PARAMETER_TYPE_FLOAT3, SHADER_PARAMETER_TYPE_FLOAT4 }; uint32 valueComponents; uint32 valueComponentType; switch (ValueType) { case SHADER_PARAMETER_TYPE_INT: valueComponents = 1; valueComponentType = SHADER_PARAMETER_TYPE_INT; break; case SHADER_PARAMETER_TYPE_INT2: valueComponents = 2; valueComponentType = SHADER_PARAMETER_TYPE_INT; break; case SHADER_PARAMETER_TYPE_INT3: valueComponents = 3; valueComponentType = SHADER_PARAMETER_TYPE_INT; break; case SHADER_PARAMETER_TYPE_INT4: valueComponents = 4; valueComponentType = SHADER_PARAMETER_TYPE_INT; break; case SHADER_PARAMETER_TYPE_FLOAT: valueComponents = 1; valueComponentType = SHADER_PARAMETER_TYPE_FLOAT; break; case SHADER_PARAMETER_TYPE_FLOAT2: valueComponents = 2; valueComponentType = SHADER_PARAMETER_TYPE_FLOAT; break; case SHADER_PARAMETER_TYPE_FLOAT3: valueComponents = 3; valueComponentType = SHADER_PARAMETER_TYPE_FLOAT; break; case SHADER_PARAMETER_TYPE_FLOAT4: valueComponents = 4; valueComponentType = SHADER_PARAMETER_TYPE_FLOAT; break; default: return SHADER_PARAMETER_TYPE_COUNT; } // get components in swizzle uint32 swizzleComponents = ShaderGraph::GetValueSwizzleComponentCount(Swizzle); if (swizzleComponents == 0) { // no swizzle, or an internal issue return ValueType; } // make sure all the components are in range for (uint32 i = 0; i < swizzleComponents; i++) { if (ShaderGraph::GetValueSwizzleComponent(Swizzle, i) >= valueComponents) return SHADER_PARAMETER_TYPE_COUNT; } // return the corresponding type switch (valueComponentType) { case SHADER_PARAMETER_TYPE_INT: return swizzleTypesInt[swizzleComponents - 1]; case SHADER_PARAMETER_TYPE_FLOAT: return swizzleTypesFloat[swizzleComponents - 1]; } // should not be reached return SHADER_PARAMETER_TYPE_COUNT; } bool ShaderGraphNodeInput::CanAutoTruncateType(SHADER_GRAPH_VALUE_SWIZZLE *pSwizzle, SHADER_PARAMETER_TYPE expectedType, SHADER_PARAMETER_TYPE valueType) { // we can go from a longer vector to a shorter vector, nothing else. switch (expectedType) { case SHADER_PARAMETER_TYPE_FLOAT: { switch (valueType) { case SHADER_PARAMETER_TYPE_FLOAT: case SHADER_PARAMETER_TYPE_FLOAT2: case SHADER_PARAMETER_TYPE_FLOAT3: case SHADER_PARAMETER_TYPE_FLOAT4: *pSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_R; return true; } } break; case SHADER_PARAMETER_TYPE_FLOAT2: { switch (valueType) { case SHADER_PARAMETER_TYPE_FLOAT2: case SHADER_PARAMETER_TYPE_FLOAT3: case SHADER_PARAMETER_TYPE_FLOAT4: *pSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_RG; return true; } } break; case SHADER_PARAMETER_TYPE_FLOAT3: { switch (valueType) { case SHADER_PARAMETER_TYPE_FLOAT3: case SHADER_PARAMETER_TYPE_FLOAT4: *pSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_RGB; return true; } } break; case SHADER_PARAMETER_TYPE_FLOAT4: { switch (valueType) { case SHADER_PARAMETER_TYPE_FLOAT2: case SHADER_PARAMETER_TYPE_FLOAT3: case SHADER_PARAMETER_TYPE_FLOAT4: *pSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_RGBA; return true; } } break; } return false; } bool ShaderGraphNodeInput::SetFixupSwizzle(SHADER_PARAMETER_TYPE expectedOutputType) { DebugAssert(m_pSourceNode != NULL && m_pSourceNode->GetOutput(m_iSourceOutputIndex) != NULL); // get the original type, without any fixup swizzle SHADER_PARAMETER_TYPE originalType = m_pSourceNode->GetOutput(m_iSourceOutputIndex)->GetValueType(); SHADER_PARAMETER_TYPE valueType = GetTypeAfterSwizzle(originalType, m_eSwizzle); // ok? if (valueType != expectedOutputType) { SHADER_GRAPH_VALUE_SWIZZLE truncateSwizzle; if (CanAutoTruncateType(&truncateSwizzle, expectedOutputType, valueType)) { m_eFixupSwizzle = truncateSwizzle; m_eValueType = GetTypeAfterSwizzle(valueType, m_eFixupSwizzle); DebugAssert(m_eValueType == expectedOutputType); return true; } } return false; } void ShaderGraphNodeInput::ClearFixupSwizzle() { DebugAssert(m_pSourceNode != NULL && m_pSourceNode->GetOutput(m_iSourceOutputIndex) != NULL); // get the original type, without any fixup swizzle SHADER_PARAMETER_TYPE originalType = m_pSourceNode->GetOutput(m_iSourceOutputIndex)->GetValueType(); SHADER_PARAMETER_TYPE valueType = GetTypeAfterSwizzle(originalType, m_eSwizzle); // set back m_eFixupSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; m_eValueType = valueType; } ShaderGraphNodeOutput::ShaderGraphNodeOutput() { m_pNode = NULL; m_iOutputIndex = 0; m_pOutputDesc = NULL; m_eValueType = SHADER_PARAMETER_TYPE_COUNT; m_iLinkCount = 0; } ShaderGraphNodeOutput::~ShaderGraphNodeOutput() { DebugAssert(m_iLinkCount == 0); } void ShaderGraphNodeOutput::Init(ShaderGraphNode *pNode, uint32 OutputIndex, const SHADER_GRAPH_NODE_OUTPUT *pOutputDesc) { m_pNode = pNode; m_iOutputIndex = OutputIndex; m_pOutputDesc = pOutputDesc; m_eValueType = pOutputDesc->Type; } void ShaderGraphNodeOutput::SetValueType(SHADER_PARAMETER_TYPE NewValueType) { m_eValueType = NewValueType; } ShaderGraphNode::ShaderGraphNode(const ShaderGraphNodeTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pTypeInfo(pTypeInfo), m_iID(0xFFFFFFFF), m_pInputs(NULL), m_nInputs(pTypeInfo->GetInputCount()), m_pOutputs(NULL), m_nOutputs(pTypeInfo->GetOutputCount()) { uint32 i; // allocate linked nodes if (m_nInputs > 0) { m_pInputs = new ShaderGraphNodeInput[m_nInputs]; for (i = 0; i < m_nInputs; i++) m_pInputs[i].Init(this, i, pTypeInfo->GetInput(i)); } if (m_nOutputs > 0) { m_pOutputs = new ShaderGraphNodeOutput[m_nOutputs]; for (i = 0; i < m_nOutputs; i++) m_pOutputs[i].Init(this, i, pTypeInfo->GetOutput(i)); } // Graph editor position. m_GraphEditorPosition.SetZero(); } ShaderGraphNode::~ShaderGraphNode() { if (m_pInputs != NULL) delete[] m_pInputs; if (m_pOutputs != NULL) delete[] m_pOutputs; } bool ShaderGraphNode::OnInputConnectionChange(uint32 InputIndex) { return true; } bool ShaderGraphNode::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { const char *nodeName = xmlReader.FetchAttribute("name"); if (nodeName == NULL) { xmlReader.PrintError("Could not find name attribute."); return false; } const char *position = xmlReader.FetchAttribute("position"); if (position != NULL) m_GraphEditorPosition = StringConverter::StringToInt2(position); m_strName = nodeName; return true; } void ShaderGraphNode::SaveToXML(XMLWriter &xmlWriter) const { xmlWriter.WriteAttribute("name", m_strName); SmallString tempStr; StringConverter::Int2ToString(tempStr, m_GraphEditorPosition); xmlWriter.WriteAttribute("position", tempStr); } bool ShaderGraphNode::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { return true; } const ShaderGraphNodeTypeInfo *ShaderGraphNode::FindTypeInfoForShortName(const char *shortName) { const ObjectTypeInfo::RegistryType &typeRegistry = ObjectTypeInfo::GetRegistry(); for (uint32 typeIndex = 0; typeIndex < typeRegistry.GetNumTypes(); typeIndex++) { const ObjectTypeInfo *pTypeInfo = typeRegistry.GetTypeInfoByIndex(typeIndex); if (pTypeInfo != nullptr && pTypeInfo->IsDerived(OBJECT_TYPEINFO(ShaderGraphNode))) { const ShaderGraphNodeTypeInfo *pShaderGraphNodeTypeInfo = static_cast<const ShaderGraphNodeTypeInfo *>(pTypeInfo); if (Y_stricmp(pShaderGraphNodeTypeInfo->GetShortName(), shortName) == 0) return pShaderGraphNodeTypeInfo; } } return nullptr; } <file_sep>/Engine/Source/Engine/TerrainSectionCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainSectionCollisionShape.h" #include "Engine/TerrainSection.h" #include "Engine/Physics/BulletHeaders.h" #include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h" Log_SetChannel(TerrainCollisionShape); TerrainSectionCollisionShape::TerrainSectionCollisionShape(const TerrainParameters *pParameters, const TerrainSection *pSectionData) : m_boundingBox(pSectionData->GetBoundingBox()) { m_pSectionData = pSectionData; m_pSectionData->AddRef(); // various lookup tables PHY_ScalarType heightStorageScalarTypes[TERRAIN_HEIGHT_STORAGE_FORMAT_COUNT] = { PHY_UCHAR, // TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8 PHY_SHORT, // TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16 PHY_FLOAT // TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32 }; // store some vars uint32 pointCount = pSectionData->GetPointCount(); float heightScale = (pParameters->HeightStorageFormat == TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32) ? 1.0f : static_cast<float>(pParameters->MaxHeight - pParameters->MinHeight); btVector3 localScaling((btScalar)pParameters->Scale, (btScalar)pParameters->Scale, (btScalar)1); // get height map const void *pHeightMapValues; uint32 heightMapDataSize; uint32 heightMapRowPitch; pSectionData->GetRawHeightMapData(&pHeightMapValues, &heightMapDataSize, &heightMapRowPitch); // create the bullet shape btHeightfieldTerrainShape *pBulletShape = new btHeightfieldTerrainShape(pointCount, pointCount, pHeightMapValues, heightScale, (btScalar)pParameters->MinHeight, (btScalar)pParameters->MaxHeight, 2, heightStorageScalarTypes[pParameters->HeightStorageFormat], false); // set scale pBulletShape->setLocalScaling(localScaling); // set bullet shape m_pBulletShape = pBulletShape; } TerrainSectionCollisionShape::~TerrainSectionCollisionShape() { delete m_pBulletShape; m_pSectionData->Release(); } const Physics::COLLISION_SHAPE_TYPE TerrainSectionCollisionShape::GetType() const { return Physics::COLLISION_SHAPE_TYPE_TERRAIN; } const AABox &TerrainSectionCollisionShape::GetLocalBoundingBox() const { return m_boundingBox; } bool TerrainSectionCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { return false; } bool TerrainSectionCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { return false; } Physics::CollisionShape *TerrainSectionCollisionShape::CreateScaledShape(const float3 &scale) const { Panic("Should never be called."); return nullptr; } void TerrainSectionCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { } void TerrainSectionCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { } btCollisionShape *TerrainSectionCollisionShape::GetBulletShape() const { return m_pBulletShape; } Transform TerrainSectionCollisionShape::GetSectionTransform(const TerrainParameters *pParameters, const TerrainSection *pSectionData) { return Transform(float3(pSectionData->GetBoundingBox().GetCenter().xy(), 0.0f), Quaternion::Identity, float3::One); } <file_sep>/Engine/Source/Core/ClassTable.h #pragma once #include "Core/Common.h" #include "Core/ObjectTypeInfo.h" #include "Core/Property.h" #include "Core/PropertyTable.h" class ByteStream; class ClassTable { public: class TypeMapping { friend class ClassTable; public: const ObjectTypeInfo *GetTypeInfo() const { return m_pTypeInfo; } const PROPERTY_DECLARATION *GetPropertyMapping(uint32 serializedIndex) const { DebugAssert(serializedIndex < m_propertyCount); return m_ppPropertyMapping[serializedIndex]; } const uint32 GetPropertyCount() const { return m_propertyCount; } private: const ObjectTypeInfo *m_pTypeInfo; const PROPERTY_DECLARATION **m_ppPropertyMapping; uint32 m_propertyCount; }; public: ClassTable(); ~ClassTable(); // load a class table bool LoadFromStream(ByteStream *pStream, bool abortOnError = false); bool LoadFromBuffer(const void *pBuffer, uint32 bufferSize, bool abortOnError = false); // save a class table bool SaveToStream(ByteStream *pStream) const; // runtime accessors const TypeMapping *GetTypeMapping(uint32 serializedIndex) const { DebugAssert(serializedIndex < m_typeCount); return &m_pTypeMappings[serializedIndex]; } const int32 GetTypeMappingForType(const ObjectTypeInfo *pTypeInfo) const; const uint32 GetTypeCount() const { return m_typeCount; } // add a type to this class table uint32 AddType(const ObjectTypeInfo *pTypeInfo); // save (serialize) an object bool SerializeObject(const Object *pObject, ByteStream *pStream); // construct (deserialize) an object Object *UnserializeObject(ByteStream *pStream, uint32 typeIndex); private: TypeMapping *m_pTypeMappings; uint32 m_typeCount; }; <file_sep>/Engine/Source/MathLib/SIMDVectorf.h #pragma once #include "MathLib/Common.h" // Float vector classes on SSE+ #if Y_CPU_SSE_LEVEL > 0 #include "MathLib/SIMDVectorf_sse.h" #else #include "MathLib/SIMDVectorf_scalar.h" #endif <file_sep>/Engine/Source/Engine/Physics/KinematicObject.h #pragma once #include "Engine/Physics/CollisionObject.h" class btRigidBody; namespace Physics { class KinematicObject : public CollisionObject { class MotionState; public: KinematicObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform); virtual ~KinematicObject(); // overrides virtual void OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; virtual void OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; protected: // overrides virtual btCollisionObject *GetBulletCollisionObject() const override; virtual void OnCollisionShapeChanged() override; virtual void OnTransformChanged() override; MotionState *m_pMotionState; btRigidBody *m_pBulletRigidBody; }; } // namespace Physics <file_sep>/DemoGame/Source/DemoGame/LaunchpadGameState.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/LaunchpadGameState.h" #include "DemoGame/DemoGame.h" #include "DemoGame/BaseDemoGameState.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(LaunchpadGameState); LaunchpadGameState::LaunchpadGameState(DemoGame *pDemoGame) : m_pDemoGame(pDemoGame) { } LaunchpadGameState::~LaunchpadGameState() { } void LaunchpadGameState::OnSwitchedIn() { if (!m_pDemoGame->IsQuitPending()) { // run new demo //InvokeSkeletalAnimationDemo(); //InvokeDrawCallStressDemo(); } m_pDemoGame->ActivateImGui(); } void LaunchpadGameState::OnSwitchedOut() { m_pDemoGame->DeactivateImGui(); } void LaunchpadGameState::OnBeforeDelete() { } void LaunchpadGameState::OnWindowResized(uint32 width, uint32 height) { } void LaunchpadGameState::OnWindowFocusGained() { } void LaunchpadGameState::OnWindowFocusLost() { } bool LaunchpadGameState::OnWindowEvent(const union SDL_Event *event) { return false; } void LaunchpadGameState::OnMainThreadPreFrame(float deltaTime) { } void LaunchpadGameState::OnMainThreadBeginFrame(float deltaTime) { } void LaunchpadGameState::OnMainThreadAsyncTick(float deltaTime) { } void LaunchpadGameState::OnMainThreadTick(float deltaTime) { } void LaunchpadGameState::OnMainThreadEndFrame(float deltaTime) { } void LaunchpadGameState::OnRenderThreadPreFrame(float deltaTime) { } void LaunchpadGameState::OnRenderThreadBeginFrame(float deltaTime) { // Clear targets. Have to do since no worldrenderer. GPUContext *pGPUContext = m_pDemoGame->GetGPUContext(); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetFullViewport(); pGPUContext->ClearTargets(true, true, true); } void LaunchpadGameState::OnRenderThreadDraw(float deltaTime) { m_pDemoGame->GetGUIContext()->DrawTextAt(16, 16, g_pRenderer->GetFixedResources()->GetDebugFont(), 32, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255), "Demo selector"); bool invoked = false; ImGui::SetNextWindowPos(ImVec2(16, 64), ImGuiSetCond_Always); if (ImGui::Begin("Demo Selector", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { if (ImGui::Button("Skeletal Animation Demo") && !invoked) { invoked = true; QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { InvokeSkeletalAnimationDemo(); }); } if (ImGui::Button("ImGui Demo") && !invoked) { invoked = true; QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { InvokeImGuiDemo(); }); } if (ImGui::Button("Draw Call Stress Demo") && !invoked) { invoked = true; QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { InvokeDrawCallStressDemo(); }); } if (ImGui::Button("Exit") && !invoked) { invoked = true; QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { m_pDemoGame->Quit(); }); } ImGui::End(); } } void LaunchpadGameState::OnRenderThreadEndFrame(float deltaTime) { } bool LaunchpadGameState::RunDemo(BaseDemoGameState *pGameState) { if (!pGameState->Initialize()) { pGameState->Shutdown(); delete pGameState; return false; } m_pDemoGame->BeginModalGameState(pGameState); return true; } <file_sep>/Engine/Source/Renderer/RendererStateBlock.h #pragma once #include "Renderer/Renderer.h" enum GPU_STATE_BLOCK_CAPTURE_FLAG { GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE = (1 << 0), GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE = (1 << 1), GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE = (1 << 2), GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS = (1 << 3), GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS = (1 << 4), GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER = (1 << 5), GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY = (1 << 6), GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS = (1 << 7), GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS = (1 << 8), GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS = (1 << 9), GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS = (1 << 10), }; class RendererStateBlock { public: RendererStateBlock(); ~RendererStateBlock(); void Capture(GPUContext *pGPUDevice, uint32 captureFlags); void Restore(); void Clear(); // void SetSavedRasterizerState(GPURasterizerState *pRasterizerState); // void SetSavedDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef); // void SetSavedBlendState(GPUBlendState *pBlendState, const float4 &blendFactors); // void SetSavedRenderTarget(uint32 index, GPUTexture *pRenderTarget); // void SetSavedRenderTarget(uint32 count, GPUTexture **ppRenderTargets); // void SetSavedDepthStencilBuffer(GPUDepthStencilBuffer *pDepthStencilBuffer); // void SetSavedVertexBuffer(uint32 index, GPUVertexBuffer *pVertexBuffer, uint32 offset, uint32 stride); // void SetSavedVertexBuffers(uint32 count, GPUVertexBuffer **ppVertexBuffers, uint32 *pOffsets, uint32 *pStrides); // void SetSavedIndexBuffer(const GPUIndexBuffer *pIndexBuffer, uint32 offset); // void SetSavedDrawTopology(DRAW_TOPOLOGY topology); // void SetSavedViewport(const VIEWPORT *pViewport); // void SetSavedScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect); private: GPUContext *m_pGPUDevice; uint32 m_iCaptureFlags; // GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE GPURasterizerState *m_pSavedRasterizerState; // GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE GPUDepthStencilState *m_pSavedDepthStencilState; uint8 m_iSavedDepthStencilRef; // GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE GPUBlendState *m_pSavedBlendState; float4 m_SavedBlendStateBlendFactors; // GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS GPURenderTargetView *m_pSavedRenderTargets[GPU_MAX_SIMULTANEOUS_RENDER_TARGETS]; GPUDepthStencilBufferView *m_pSavedDepthStencilBuffer; uint32 m_nSavedRenderTargets; // GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS GPUBuffer *m_pSavedVertexBuffers[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_iSavedVertexBufferOffsets[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_iSavedVertexBufferStrides[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_nSavedVertexBuffers; // GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER GPUBuffer *m_pSavedIndexBuffer; GPU_INDEX_FORMAT m_savedIndexFormat; uint32 m_iSavedIndexBufferOffset; // GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY DRAW_TOPOLOGY m_eSavedDrawTopology; // GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS RENDERER_VIEWPORT m_SavedViewport; // GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS RENDERER_SCISSOR_RECT m_SavedScissorRect; // GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS float4x4 m_SavedWorldMatrix; // GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS float4x4 m_SavedViewMatrix; float4x4 m_SavedProjectionMatrix; float3 m_SavedEyePosition; };<file_sep>/Engine/Source/Engine/TerrainQuadTree.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainQuadTree.h" #include "Engine/TerrainSection.h" #include "Engine/EngineCVars.h" #include "Engine/DataFormats.h" Log_SetChannel(TerrainSectionQuadTree); // todo: optimize by not creating leaf nodes when the height is static // todo: background optimization of quadtree TerrainSectionQuadTree::TerrainSectionQuadTree(const TerrainSection *pSection) : m_pSection(pSection), m_pNodes(NULL), m_nNodes(0) { } TerrainSectionQuadTree::~TerrainSectionQuadTree() { delete[] m_pNodes; } bool TerrainSectionQuadTree::Build(const TerrainParameters *pParameters, const TerrainSection *pSection, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { const uint32 sectionSize = pSection->GetPointCount() - 1; DebugAssert(pParameters->LODCount < TERRAIN_MAX_RENDER_LODS && (sectionSize >> (pParameters->LODCount - 1)) > 0); // determine the number of nodes uint32 levelNodeSizes[TERRAIN_MAX_RENDER_LODS]; uint32 allocatedNodeCount = 0; { uint32 currentNodeSize = sectionSize; for (uint32 i = 0; i < pParameters->LODCount; i++) { DebugAssert(currentNodeSize > 0); levelNodeSizes[i] = currentNodeSize; allocatedNodeCount += Math::Square(sectionSize / currentNodeSize); currentNodeSize /= 2; } } // allocate nodes TerrainQuadTreeNode *pNodes = new TerrainQuadTreeNode[allocatedNodeCount]; uint32 currentNodeIndex = 0; // set up progress pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetStatusText("Creating quadtree nodes..."); pProgressCallbacks->SetProgressRange(allocatedNodeCount); pProgressCallbacks->SetProgressValue(0); // build top level nodes, this will recurse down and fill the other levels BuildTopLevel(pNodes, currentNodeIndex, allocatedNodeCount, pParameters, pSection, pProgressCallbacks); // set to max since some nodes may have been skipped pProgressCallbacks->SetProgressValue(allocatedNodeCount); // write the quadtree out bool writeResult = SaveNodeBuffer(pOutputStream, pNodes, currentNodeIndex, pParameters->LODCount); // clean up delete[] pNodes; return writeResult; } void TerrainSectionQuadTree::BuildTopLevel(TerrainQuadTreeNode *pNodeBuffer, uint32 &currentNodeIndex, uint32 allocatedNodeCount, const TerrainParameters *pParameters, const TerrainSection *pSection, ProgressCallbacks *pProgressCallbacks) { const uint32 pointCount = pSection->GetPointCount(); const uint32 quadCount = pParameters->SectionSize; const float3 &sectionMinBounds = pSection->GetBoundingBox().GetMinBounds(); const float3 &sectionMaxBounds = pSection->GetBoundingBox().GetMaxBounds(); // should have lod0 DebugAssert(pSection->GetStorageLODLevel() == 0); // allocate a node DebugAssert(currentNodeIndex < allocatedNodeCount); TerrainQuadTreeNode *pNode = pNodeBuffer + (currentNodeIndex++); // fill the base details pNode->m_LODLevel = (pParameters->LODCount - 1); pNode->m_startQuadX = 0; pNode->m_startQuadY = 0; pNode->m_nodeSize = quadCount; // extract min/max heights float minHeight = Y_FLT_INFINITE; float maxHeight = -Y_FLT_INFINITE; for (uint32 sy = 0; sy < pointCount; sy++) { for (uint32 sx = 0; sx < pointCount; sx++) { float height = pSection->GetHeightMapValue(sx, sy); if (height != Y_FLT_INFINITE) { minHeight = Min(minHeight, height); maxHeight = Max(maxHeight, height); } } } // if no values were found, set both to be infinite, so this quad never gets rendered if (minHeight == Y_FLT_INFINITE && maxHeight == -Y_FLT_INFINITE) minHeight = maxHeight = Y_FLT_INFINITE; // bounds can be copied directly from the section float3 minBounds(sectionMinBounds.x, sectionMinBounds.y, minHeight); float3 maxBounds(sectionMaxBounds.x, sectionMaxBounds.y, maxHeight); pNode->m_boundingBox.SetBounds(minBounds, maxBounds); pNode->m_boundingSphere = Sphere::FromAABox(pNode->m_boundingBox); // initialize child nodes to null for now Y_memzero(pNode->m_pChildNodes, sizeof(pNode->m_pChildNodes)); pNode->m_isLeafNode = false; pNode->m_isFlat = false; // build children, however if we don't have any heights, don't bother if (pNode->m_LODLevel > 0 && minHeight != Y_FLT_INFINITE && maxHeight != Y_FLT_INFINITE) BuildChildrenRecursive(pNodeBuffer, currentNodeIndex, allocatedNodeCount, pNode, pParameters, pSection, pProgressCallbacks); else pNode->m_isLeafNode = true; } void TerrainSectionQuadTree::BuildChildrenRecursive(TerrainQuadTreeNode *pNodeBuffer, uint32 &currentNodeIndex, uint32 allocatedNodeCount, TerrainQuadTreeNode *pSplittingNode, const TerrainParameters *pParameters, const TerrainSection *pSection, ProgressCallbacks *pProgressCallbacks) { const uint32 scale = pParameters->Scale; const float3 &sectionMinBounds = pSection->GetBoundingBox().GetMinBounds(); // store the starting quads and size uint32 startQuadX = pSplittingNode->m_startQuadX; uint32 startQuadY = pSplittingNode->m_startQuadY; uint32 quadCount = pSplittingNode->m_nodeSize; // determine child node size uint32 childQuadCount = quadCount / 2; // divide the splitting node into 4 children // array order: TL, TR, BL, BR float quadrantMinHeights[4]; float quadrantMaxHeights[4]; uint32 quadrantStartPointsX[4]; uint32 quadrantStartPointsY[4]; bool quadrantVariableHeights[4]; // fill starting points quadrantStartPointsX[0] = startQuadX; // TL quadrantStartPointsY[0] = startQuadY; // TL quadrantStartPointsX[1] = startQuadX + childQuadCount; // TR quadrantStartPointsY[1] = startQuadY; // TR quadrantStartPointsX[2] = startQuadX; // BL quadrantStartPointsY[2] = startQuadY + childQuadCount; // BL quadrantStartPointsX[3] = startQuadX + childQuadCount; // BR quadrantStartPointsY[3] = startQuadY + childQuadCount; // BR // find heights from quadrants for (uint32 i = 0; i < 4; i++) { // find starting and ending points uint32 startPointX = quadrantStartPointsX[i]; uint32 startPointY = quadrantStartPointsY[i]; uint32 endPointX = startPointX + childQuadCount; uint32 endPointY = startPointY + childQuadCount; // retrieve the heights float minHeight = -Y_FLT_INFINITE; float maxHeight = Y_FLT_INFINITE; bool firstHeight = true; bool variableHeight = false; for (uint32 sy = startPointY; sy <= endPointY; sy++) { for (uint32 sx = startPointX; sx <= endPointX; sx++) { float height = pSection->GetHeightMapValue(sx, sy); if (height != Y_FLT_INFINITE) { if (!firstHeight) { if (height != minHeight && height != maxHeight) variableHeight = true; minHeight = Min(minHeight, height); maxHeight = Max(maxHeight, height); } else { minHeight = height; maxHeight = height; firstHeight = false; } } } } // store heights quadrantMinHeights[i] = minHeight; quadrantMaxHeights[i] = maxHeight; quadrantVariableHeights[i] = variableHeight; } // are all quadrant heights the same? if so, there is no point in constructing leaf nodes if (!quadrantVariableHeights[0] && !quadrantVariableHeights[1] && !quadrantVariableHeights[2] && !quadrantVariableHeights[3]) { // flag as leaf node, and exit out pSplittingNode->m_isLeafNode = true; pSplittingNode->m_isFlat = true; return; } // create children for (uint32 i = 0; i < 4; i++) { // if the child has no heights (hole), don't allocate it if (quadrantMinHeights[i] == Y_FLT_INFINITE && quadrantMaxHeights[i] == Y_FLT_INFINITE) continue; // allocate a node DebugAssert(currentNodeIndex < allocatedNodeCount); TerrainQuadTreeNode *pNode = pNodeBuffer + (currentNodeIndex++); // fill basic details pNode->m_LODLevel = pSplittingNode->m_LODLevel - 1; pNode->m_startQuadX = quadrantStartPointsX[i]; pNode->m_startQuadY = quadrantStartPointsY[i]; pNode->m_nodeSize = childQuadCount; // calculate bounding box float3 minBounds(sectionMinBounds.x + (float)(quadrantStartPointsX[i] * scale), sectionMinBounds.y + (float)(quadrantStartPointsY[i] * scale), quadrantMinHeights[i]); float3 maxBounds(minBounds.x + (float)(childQuadCount * scale), minBounds.y + (float)(childQuadCount * scale), quadrantMaxHeights[i]); // store it pNode->m_boundingBox.SetBounds(minBounds, maxBounds); pNode->m_boundingSphere = Sphere::FromAABox(pNode->m_boundingBox); // initialize child nodes to null for now Y_memzero(pNode->m_pChildNodes, sizeof(pNode->m_pChildNodes)); pNode->m_isLeafNode = false; pNode->m_isFlat = false; // if this node is not level 0, subdivide it if (pNode->m_LODLevel > 0) BuildChildrenRecursive(pNodeBuffer, currentNodeIndex, allocatedNodeCount, pNode, pParameters, pSection, pProgressCallbacks); else pNode->m_isLeafNode = true; // store as child node pSplittingNode->m_pChildNodes[i] = pNode; } } bool TerrainSectionQuadTree::SaveNodeBuffer(ByteStream *pStream, TerrainQuadTreeNode *pNodeBuffer, uint32 nodeCount, uint32 LODCount) { // write nodes DF_TERRAIN_QUADTREE_HEADER quadTreeHeader; quadTreeHeader.Magic = DF_TERRAIN_QUADTREE_HEADER_MAGIC; quadTreeHeader.HeaderSize = sizeof(quadTreeHeader); quadTreeHeader.LODCount = LODCount; quadTreeHeader.NodeCount = nodeCount; if (!pStream->Write2(&quadTreeHeader, sizeof(quadTreeHeader))) return false; // write nodes for (uint32 i = 0; i < nodeCount; i++) { const TerrainQuadTreeNode *pNode = pNodeBuffer + i; // write node DF_TERRAIN_QUADTREE_NODE writeNode; writeNode.LODLevel = pNode->m_LODLevel; writeNode.StartQuadX = pNode->m_startQuadX; writeNode.StartQuadY = pNode->m_startQuadY; writeNode.NodeSize = pNode->m_nodeSize; pNode->m_boundingBox.GetMinBounds().Store(writeNode.BoundingBoxMin); pNode->m_boundingBox.GetMaxBounds().Store(writeNode.BoundingBoxMax); pNode->m_boundingSphere.GetCenter().Store(writeNode.BoundingSphereCenter); writeNode.BoundingSphereRadius = pNode->m_boundingSphere.GetRadius(); writeNode.IsLeafNode = (pNode->m_isLeafNode) ? 1 : 0; writeNode.IsFlat = (pNode->m_isFlat) ? 1 : 0; // write children indices for (uint32 j = 0; j < 4; j++) { int32 childIndex; if (pNode->m_pChildNodes[j] != NULL) childIndex = (int32)(pNode->m_pChildNodes[j] - pNodeBuffer); else childIndex = -1; writeNode.ChildNodeIndices[j] = childIndex; } // save it if (!pStream->Write2(&writeNode, sizeof(writeNode))) return false; } return true; } bool TerrainSectionQuadTree::LoadFromStream(ByteStream *pStream) { DF_TERRAIN_QUADTREE_HEADER quadTreeHeader; if (!pStream->Read2(&quadTreeHeader, sizeof(quadTreeHeader)) || quadTreeHeader.Magic != DF_TERRAIN_QUADTREE_HEADER_MAGIC || quadTreeHeader.HeaderSize != sizeof(quadTreeHeader)) { return false; } m_LODCount = quadTreeHeader.LODCount; m_nNodes = quadTreeHeader.NodeCount; DebugAssert(m_nNodes > 0); // allocate nodes m_pNodes = new TerrainQuadTreeNode[m_nNodes]; // read nodes for (uint32 nodeIndex = 0; nodeIndex < m_nNodes; nodeIndex++) { DF_TERRAIN_QUADTREE_NODE readNode; if (!pStream->Read2(&readNode, sizeof(readNode))) return false; TerrainQuadTreeNode *pNode = m_pNodes + nodeIndex; pNode->m_LODLevel = readNode.LODLevel; pNode->m_startQuadX = readNode.StartQuadX; pNode->m_startQuadY = readNode.StartQuadY; pNode->m_nodeSize = readNode.NodeSize; float3 boundingBoxMin(readNode.BoundingBoxMin); float3 boundingBoxMax(readNode.BoundingBoxMax); pNode->m_boundingBox.SetBounds(boundingBoxMin, boundingBoxMax); float3 boundingSphereCenter(readNode.BoundingSphereCenter); pNode->m_boundingSphere.SetCenter(boundingSphereCenter); pNode->m_boundingSphere.SetRadius(readNode.BoundingSphereRadius); pNode->m_isLeafNode = (readNode.IsLeafNode != 0); pNode->m_isFlat = (readNode.IsFlat != 0); for (uint32 j = 0; j < 4; j++) { int32 childIndex = readNode.ChildNodeIndices[j]; if (childIndex < 0) { pNode->m_pChildNodes[j] = NULL; continue; } DebugAssert((uint32)childIndex < m_nNodes); pNode->m_pChildNodes[j] = m_pNodes + childIndex; } } return true; } bool TerrainSectionQuadTree::SaveToStream(ByteStream *pOutputStream) const { // write nodes DF_TERRAIN_QUADTREE_HEADER quadTreeHeader; quadTreeHeader.Magic = DF_TERRAIN_QUADTREE_HEADER_MAGIC; quadTreeHeader.HeaderSize = sizeof(quadTreeHeader); quadTreeHeader.LODCount = m_LODCount; quadTreeHeader.NodeCount = m_nNodes; if (!pOutputStream->Write2(&quadTreeHeader, sizeof(quadTreeHeader))) return false; // write nodes for (uint32 i = 0; i < m_nNodes; i++) { const TerrainQuadTreeNode *pNode = m_pNodes + i; // write node DF_TERRAIN_QUADTREE_NODE writeNode; writeNode.LODLevel = pNode->m_LODLevel; writeNode.StartQuadX = pNode->m_startQuadX; writeNode.StartQuadY = pNode->m_startQuadY; writeNode.NodeSize = pNode->m_nodeSize; pNode->m_boundingBox.GetMinBounds().Store(writeNode.BoundingBoxMin); pNode->m_boundingBox.GetMaxBounds().Store(writeNode.BoundingBoxMax); pNode->m_boundingSphere.GetCenter().Store(writeNode.BoundingSphereCenter); writeNode.BoundingSphereRadius = pNode->m_boundingSphere.GetRadius(); writeNode.IsLeafNode = (pNode->m_isLeafNode) ? 1 : 0; writeNode.IsFlat = (pNode->m_isFlat) ? 1 : 0; // write children indices for (uint32 j = 0; j < 4; j++) { int32 childIndex; if (pNode->m_pChildNodes[j] != NULL) childIndex = (int32)(pNode->m_pChildNodes[j] - m_pNodes); else childIndex = -1; writeNode.ChildNodeIndices[j] = childIndex; } // save it if (!pOutputStream->Write2(&writeNode, sizeof(writeNode))) return false; } return true; } void TerrainSectionQuadTree::UpdateMinMaxHeight(uint32 pointX, uint32 pointY, float newHeight, float oldHeight, bool *pNeedsRebuild) { bool needsRebuild = false; // ignore infinite (hole) heights if (newHeight != Y_FLT_INFINITE) { // update top level node UpdateMinMaxHeightRecursive(m_pNodes, pointX, pointY, newHeight, oldHeight, needsRebuild); } if (pNeedsRebuild != NULL) *pNeedsRebuild = needsRebuild; } void TerrainSectionQuadTree::UpdateMinMaxHeightRecursive(TerrainQuadTreeNode *pNode, uint32 pointX, uint32 pointY, float newHeight, float oldHeight, bool &needsRebuild) { // get current bounds float3 minBounds(pNode->m_boundingBox.GetMinBounds()); float3 maxBounds(pNode->m_boundingBox.GetMaxBounds()); // if the old height was the minimum or maximum height, and it's // changed in the opposite direction, trigger a rebuild // todo: reenable when rebuilding is backgrounded /*if (newHeight != Y_FLT_INFINITE) { if ((minBounds.z == oldHeight && newHeight > oldHeight) || (maxBounds.z == oldHeight && newHeight < oldHeight)) { needsRebuild = true; } } else if (oldHeight != Y_FLT_INFINITE) { // adding a hole if (minBounds.z == oldHeight || maxBounds.z == oldHeight) needsRebuild = true; return; }*/ // update this node bool changed = false; if (newHeight < minBounds.z) { minBounds.z = newHeight; changed = true; } if (newHeight > maxBounds.z) { maxBounds.z = newHeight; changed = true; } if (changed) { // signal a rebuild is needed if this was previously a single height leaf node at a lod > 0 if (pNode->GetLODLevel() > 0 && pNode->IsLeafNode()) needsRebuild = true; pNode->m_boundingBox.SetBounds(minBounds, maxBounds); pNode->m_boundingSphere = Sphere::FromAABox(pNode->m_boundingBox); } // not a leaf node? if (!pNode->IsLeafNode()) { // update children for (uint32 i = 0; i < 4; i++) { TerrainQuadTreeNode *pChildNode = pNode->m_pChildNodes[i]; if (pChildNode != NULL) { if (pointX >= pChildNode->m_startQuadX && pointX <= (pChildNode->m_startQuadX + pChildNode->m_nodeSize) && pointY >= pChildNode->m_startQuadY && pointY <= (pChildNode->m_startQuadY + pChildNode->m_nodeSize)) { UpdateMinMaxHeightRecursive(pChildNode, pointX, pointY, newHeight, oldHeight, needsRebuild); } } } } } TerrainQuadTreeQuery::TerrainQuadTreeQuery() { } TerrainQuadTreeQuery::~TerrainQuadTreeQuery() { } void TerrainQuadTreeQuery::Invoke(const TerrainSection *const *ppSections, uint32 nSections, const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS]) { // clear previous results m_selectedNodes.Clear(); // go over sections for (uint32 i = 0; i < nSections; i++) { const TerrainSection *pSection = ppSections[i]; // get toplevel node of quadtree const TerrainSectionQuadTree *pQuadTree = pSection->GetQuadTree(); const TerrainQuadTreeNode *pTopLevelNode = pQuadTree->GetTopLevelNode(); // get intersection type Frustum::IntersectionType intersectionType = cameraFrustum.AABoxIntersectionType(pTopLevelNode->GetBoundingBox()); if (intersectionType != Frustum::INTERSECTION_TYPE_OUTSIDE) { bool completelyInFrustum = (intersectionType == Frustum::INTERSECTION_TYPE_INTERSECTS); ProcessNode(cameraPosition, cameraFrustum, visibilityRanges, pSection, pTopLevelNode, completelyInFrustum); } } } bool TerrainQuadTreeQuery::ProcessNode(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], const TerrainSection *pSection, const TerrainQuadTreeNode *pNode, bool parentCompletelyInFrustum) { // frustum test it Frustum::IntersectionType intersectionType; if (parentCompletelyInFrustum) { // shortcut when parent is entirely in frustum intersectionType = Frustum::INTERSECTION_TYPE_INSIDE; } else { // have to calculate box and test it intersectionType = cameraFrustum.AABoxIntersectionType(pNode->GetBoundingBox()); } // outside frustum? if (intersectionType == Frustum::INTERSECTION_TYPE_OUTSIDE) { // return true to consume the node, preventing the parent from drawing it return true; } // out of range for this lod level? Sphere cameraSphere(cameraPosition, visibilityRanges[pNode->GetLODLevel()]); if (!pNode->GetBoundingBox().SphereIntersection(cameraSphere)) return false; // has lower levels? uint32 drawFlags = 0; if (pNode->IsLeafNode()) { // at lowest lod level, draw the whole thing //if (pNode->IsFlat()) //drawFlags = DRAW_FLAG_SINGLE_QUAD; //else drawFlags = DrawFlagAll; } else { // out of range for next lod level, if the parent is they all will be cameraSphere.SetRadius(visibilityRanges[pNode->GetLODLevel() - 1]); if (pNode->GetBoundingBox().SphereIntersection(cameraSphere)) { // test each of the children const TerrainQuadTreeNode *pChildNode; bool completelyInFrustum = (intersectionType == Frustum::INTERSECTION_TYPE_INSIDE); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopLeft)) != NULL && !ProcessNode(cameraPosition, cameraFrustum, visibilityRanges, pSection, pChildNode, completelyInFrustum)) { drawFlags |= DrawFlagTopLeft; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopRight)) != NULL && !ProcessNode(cameraPosition, cameraFrustum, visibilityRanges, pSection, pChildNode, completelyInFrustum)) { drawFlags |= DrawFlagTopRight; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomLeft)) != NULL && !ProcessNode(cameraPosition, cameraFrustum, visibilityRanges, pSection, pChildNode, completelyInFrustum)) { drawFlags |= DrawFlagBottomLeft; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomRight)) != NULL && !ProcessNode(cameraPosition, cameraFrustum, visibilityRanges, pSection, pChildNode, completelyInFrustum)) { drawFlags |= DrawFlagBottomRight; } } else { // draw everything at this level drawFlags = DrawFlagAll; } } // drawing this node at all? if (drawFlags != 0) { // add to list SelectedNode selectedNode; selectedNode.pSection = pSection; selectedNode.pNode = pNode; selectedNode.DrawFlags = drawFlags; m_selectedNodes.Add(selectedNode); } // consume node return true; } <file_sep>/Engine/Source/Renderer/Shaders/DeferredShadingShaders.h #pragma once #include "Renderer/ShaderComponent.h" #include "Renderer/WorldRenderer.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" class DeferredGBufferShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredGBufferShader, ShaderComponent); enum { WITH_LIGHTMAP = (1 << 0), WITH_LIGHTBUFFER = (1 << 1), NO_ALBEDO = (1 << 2) }; public: DeferredGBufferShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DeferredDirectionalLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredDirectionalLightShader, ShaderComponent); public: enum FLAGS { WITH_SHADOW_MAP = (1 << 0), SHOW_CASCADES = (1 << 1), USE_HARDWARE_PCF = (1 << 2), SHADOW_FILTER_1X1 = (1 << 3), SHADOW_FILTER_3X3 = (1 << 4), SHADOW_FILTER_5X5 = (1 << 5), SHADOW_BITS_MASK = WITH_SHADOW_MAP | SHOW_CASCADES | USE_HARDWARE_PCF | SHADOW_FILTER_1X1 | SHADOW_FILTER_3X3 | SHADOW_FILTER_5X5 }; public: DeferredDirectionalLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } // get flags based on cvar values static uint32 CalculateShadowFlags(bool enableShadows, bool useHardwareShadowFiltering, RENDERER_SHADOW_FILTER shadowFilter, bool showCascades); // light params static void SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); static void SetShadowParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData); static void SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2); static void CommitParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DeferredPointLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredPointLightShader, ShaderComponent); public: enum FLAGS { WITH_SHADOW_MAP = (1 << 0), USE_HARDWARE_PCF = (1 << 1), SHADOW_BITS_MASK = WITH_SHADOW_MAP | USE_HARDWARE_PCF }; public: DeferredPointLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } // get flags based on cvar values static uint32 CalculateShadowFlags(bool enableShadows, bool useHardwareShadowFiltering); // light params static void SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); static void SetShadowParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData); static void SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DeferredPointLightListShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredPointLightListShader, ShaderComponent); public: static const uint32 MAX_LIGHTS = 256; public: DeferredPointLightListShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, uint32 lightIndex, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); static void SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DeferredTiledPointLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredTiledPointLightShader, ShaderComponent); public: struct Light { Light(const float3 &position, float inverseRange, const float3 &color, float falloffExponent) : Position(position), InverseRange(inverseRange), Color(color), FalloffExponent(falloffExponent) {} float3 Position; float InverseRange; float3 Color; float FalloffExponent; }; static const uint32 MAX_LIGHTS_PER_DISPATCH = 1024; static const uint32 TILE_SIZE = 32; public: DeferredTiledPointLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } // light params static void SetLights(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const Light *pLights, uint32 nLights); static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, uint32 tileCountX, uint32 tileCountY); static void SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2, GPUTexture2D *pLightBuffer); static void CommitParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DeferredFogShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DeferredFogShader, ShaderComponent); enum FLAGS { MODE_LINEAR = (1 << 0), MODE_EXP = (1 << 1), MODE_EXP2 = (1 << 2), }; public: DeferredFogShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static uint32 GetFlagsForMode(RENDERER_FOG_MODE mode); static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, GPUTexture2D *pDepthBuffer); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Engine/Source/BaseGame/PrecompiledHeader.h #pragma once #include "BaseGame/Common.h" <file_sep>/Engine/Source/MathLib/Matrixf.h #pragma once #include "MathLib/Vectorf.h" #include "MathLib/Angle.h" #include "YBaseLib/Assert.h" struct Quaternion; struct Matrix3x3f; struct Matrix3x4f; struct Matrix4x4f; struct Matrix2x2f; struct SIMDMatrix3x3f; struct SIMDMatrix3x4f; struct SIMDMatrix4x4f; struct Matrix3x3f { Matrix3x3f() {} // set everything at once Matrix3x3f(const float E00, const float E01, const float E02, const float E10, const float E11, const float E12, const float E20, const float E21, const float E22); // sets the diagonal to the specified value (1 == identity) Matrix3x3f(const float Diagonal); // assumes row-major packing order with vectors in columns Matrix3x3f(const float *p); Matrix3x3f(const float p[3][3]); // copy Matrix3x3f(const Matrix3x3f &v); // downscaling/from floatx Matrix3x3f(const SIMDMatrix3x3f &v); Matrix3x3f(const SIMDMatrix4x4f &v); Matrix3x3f(const Matrix4x4f &v); // setters void Set(const float E00, const float E01, const float E02, const float E10, const float E11, const float E12, const float E20, const float E21, const float E22); void SetIdentity(); void SetZero(); // column accessors Vector3f GetColumn(uint32 j) const; void SetColumn(uint32 j, const Vector3f &v); // for converting to/from opengl matrices void SetTranspose(const float *pElements); void GetTranspose(float *pElements) const; // new matrix Matrix3x3f Inverse() const; Matrix3x3f Transpose() const; float Determinant() const; // in-place void InvertInPlace(); void TransposeInPlace(); // to floatx SIMDMatrix3x3f GetMatrix3() const; // row/field accessors const Vector3f &operator[](uint32 i) const { DebugAssert(i < 3); return reinterpret_cast<const Vector3f &>(Row[i]); } const Vector3f &GetRow(uint32 i) const { DebugAssert(i < 3); return reinterpret_cast<const Vector3f &>(Row[i]); } const float operator()(uint32 i, uint32 j) const { DebugAssert(i < 3 && j < 3); return Row[i][j]; } Vector3f &operator[](uint32 i) { DebugAssert(i < 3); return reinterpret_cast<Vector3f &>(Row[i]); } void SetRow(uint32 i, const Vector3f &v) { DebugAssert(i < 3); reinterpret_cast<Vector3f &>(Row[i]) = v; } float &operator()(uint32 i, uint32 j) { DebugAssert(i < 3 && j < 3); return Row[i][j]; } // assignment operators Matrix3x3f &operator=(const Matrix3x3f &v); Matrix3x3f &operator=(const float Diagonal); Matrix3x3f &operator=(const float *p); Matrix3x3f &operator=(const SIMDMatrix3x3f &v); // various operators Matrix3x3f &operator+=(const Matrix3x3f &v); Matrix3x3f &operator+=(const float v); Matrix3x3f &operator*=(const Matrix3x3f &v); Matrix3x3f &operator*=(const float v); Matrix3x3f operator+(const Matrix3x3f &v) const; Matrix3x3f operator+(const float v) const; Matrix3x3f operator*(const Matrix3x3f &v) const; Matrix3x3f operator*(float v) const; Matrix3x3f operator-() const; // matrix * vector Vector3f operator*(const Vector3f &v) const; // constants static const Matrix3x3f &Zero, &Identity; public: union { float Elements[9]; float Row[3][3]; struct { float m00, m01, m02; float m10, m11, m12; float m20, m21, m22; }; }; }; struct Matrix4x4f { Matrix4x4f() {} // set everything at once Matrix4x4f(const float E00, const float E01, const float E02, const float E03, const float E10, const float E11, const float E12, const float E13, const float E20, const float E21, const float E22, const float E23, const float E30, const float E31, const float E32, const float E33); // sets the diagonal to the specified value (1 == identity) Matrix4x4f(const float Diagonal); // assumes row-major packing order with vectors in columns Matrix4x4f(const float *p); Matrix4x4f(const float p[4][4]); // copy Matrix4x4f(const Matrix4x4f &v); // downscaling/from floatx Matrix4x4f(const SIMDMatrix4x4f &v); // import from float3x4 Matrix4x4f(const Matrix3x4f &v); // setters void Set(const float E00, const float E01, const float E02, const float E03, const float E10, const float E11, const float E12, const float E13, const float E20, const float E21, const float E22, const float E23, const float E30, const float E31, const float E32, const float E33); void SetIdentity(); void SetZero(); // column accessors Vector4f GetColumn(uint32 j) const; void SetColumn(uint32 j, const Vector4f &v); // for converting to/from opengl matrices void SetTranspose(const float *pElements); void GetTranspose(float *pElements) const; // new matrix Matrix4x4f Inverse() const; Matrix4x4f Transpose() const; float Determinant() const; // in-place void InvertInPlace(); void TransposeInPlace(); // to floatx SIMDMatrix4x4f GetMatrix4f() const; // transform vec3 Vector3f TransformPoint(const Vector3f &point) const; Vector3f TransformNormal(const Vector3f &normal, bool normalize = true) const; // decompose void Decompose(Vector3f &translation, Quaternion &rotation, Vector3f &scale) const; // row/field accessors const Vector4f &operator[](uint32 i) const { DebugAssert(i < 4); return reinterpret_cast<const Vector4f &>(Row[i]); } const Vector4f &GetRow(uint32 i) const { DebugAssert(i < 4); return reinterpret_cast<const Vector4f &>(Row[i]); } const float operator()(uint32 i, uint32 j) const { DebugAssert(i < 4 && j < 4); return Row[i][j]; } Vector4f &operator[](uint32 i) { DebugAssert(i < 4); return reinterpret_cast<Vector4f &>(Row[i]); } void SetRow(uint32 i, const Vector4f &v) { DebugAssert(i < 4); reinterpret_cast<Vector4f &>(Row[i]) = v; } float &operator()(uint32 i, uint32 j) { DebugAssert(i < 4 && j < 4); return Row[i][j]; } // assignment operators Matrix4x4f &operator=(const Matrix4x4f &v); Matrix4x4f &operator=(const float Diagonal); Matrix4x4f &operator=(const float *p); Matrix4x4f &operator=(const SIMDMatrix4x4f &v); // various operators Matrix4x4f &operator+=(const Matrix4x4f &v); Matrix4x4f &operator+=(const float v); Matrix4x4f &operator*=(const Matrix4x4f &v); Matrix4x4f &operator*=(const float v); Matrix4x4f operator+(const Matrix4x4f &v) const; Matrix4x4f operator+(const float v) const; Matrix4x4f operator*(const Matrix4x4f &v) const; Matrix4x4f operator*(float v) const; Matrix4x4f operator-() const; // matrix * vector Vector4f operator*(const Vector4f &v) const; // constants static const Matrix4x4f &Zero, &Identity; // matrix constructors static Matrix4x4f MakeScaleMatrix(float s); static Matrix4x4f MakeScaleMatrix(const Vector3f &s); static Matrix4x4f MakeScaleMatrix(float x, float y, float z); static Matrix4x4f MakeRotationMatrixX(Angle angle); static Matrix4x4f MakeRotationMatrixY(Angle angle); static Matrix4x4f MakeRotationMatrixZ(Angle angle); static Matrix4x4f MakeRotationFromEulerAnglesMatrix(const Vector3f &r); static Matrix4x4f MakeRotationFromEulerAnglesMatrix(Angle x, Angle y, Angle z); static Matrix4x4f MakeTranslationMatrix(const Vector3f &t); static Matrix4x4f MakeTranslationMatrix(float x, float y, float z); static Matrix4x4f MakePerspectiveProjectionMatrix(float fovY, float aspect, float zNear, float zFar); static Matrix4x4f MakeOrthographicProjectionMatrix(float width, float height, float zNear, float zFar); static Matrix4x4f MakeOrthographicOffCenterProjectionMatrix(float left, float right, float bottom, float top, float zNear, float zFar); static Matrix4x4f MakeCoordinateSystemConversionMatrix(COORDINATE_SYSTEM fromSystem, COORDINATE_SYSTEM toSystem, bool *pReverseWinding); static Matrix4x4f MakeLookAtViewMatrix(const Vector3f &eye, const Vector3f &at, const Vector3f &up); static Matrix4x4f MakeCubeViewMatrix(uint32 face); static Matrix4x4f MakeCubeViewMatrix(uint32 face, const Vector3f &position); public: union { float Elements[16]; float Row[4][4]; struct { float m00, m01, m02, m03; float m10, m11, m12, m13; float m20, m21, m22, m23; float m30, m31, m32, m33; }; }; }; // float3x4 matrix has special behaviour when doing multiplication, there is an implicit { 0, 0, 0, 1 } fourth row struct Matrix3x4f { Matrix3x4f() {} // set everything at once Matrix3x4f(const float &E00, const float &E01, const float &E02, const float &E03, const float &E10, const float &E11, const float &E12, const float &E13, const float &E20, const float &E21, const float &E22, const float &E23); // assumes row-major packing order with vectors in columns Matrix3x4f(const float *p); Matrix3x4f(const float p[3][4]); // copy Matrix3x4f(const Matrix3x4f &v); // downscaling/from floatx Matrix3x4f(const SIMDMatrix3x4f &v); // from 4x4 matrix Matrix3x4f(const Matrix4x4f &m); // setters void Set(const float &E00, const float &E01, const float &E02, const float &E03, const float &E10, const float &E11, const float &E12, const float &E13, const float &E20, const float &E21, const float &E22, const float &E23); void SetIdentity(); void SetZero(); // column accessors Vector3f GetColumn(uint32 j) const; void SetColumn(uint32 j, const Vector3f &v); // for converting to/from opengl matrices void SetTranspose(const float *pElements); void GetTranspose(float *pElements) const; // to floatx SIMDMatrix3x4f GetMatrix3x4() const; // transform vec3 Vector3f TransformPoint(const Vector3f &point) const; Vector3f TransformNormal(const Vector3f &normal, bool normalize = true) const; // load/store void Load(const float *pValues); void Store(float *pValues); // row/field accessors const Vector4f &operator[](uint32 i) const { DebugAssert(i < 3); return reinterpret_cast<const Vector4f &>(Row[i]); } const Vector4f &GetRow(uint32 i) const { DebugAssert(i < 3); return reinterpret_cast<const Vector4f &>(Row[i]); } const float &operator()(uint32 i, uint32 j) const { DebugAssert(i < 3 && j < 4); return Row[i][j]; } Vector4f &operator[](uint32 i) { DebugAssert(i < 3); return reinterpret_cast<Vector4f &>(Row[i]); } void SetRow(uint32 i, const Vector4f &v) { DebugAssert(i < 3); reinterpret_cast<Vector4f &>(Row[i]) = v; } float &operator()(uint32 i, uint32 j) { DebugAssert(i < 3 && j < 4); return Row[i][j]; } // assignment operators Matrix3x4f &operator=(const Matrix3x4f &v); Matrix3x4f &operator=(const float *p); Matrix3x4f &operator=(const SIMDMatrix3x4f &v); // various operators Matrix3x4f &operator+=(const Matrix3x4f &v); Matrix3x4f &operator+=(const float v); Matrix3x4f &operator*=(const Matrix3x4f &v); Matrix3x4f &operator*=(const float v); Matrix3x4f operator+(const Matrix3x4f &v) const; Matrix3x4f operator+(const float v) const; Matrix3x4f operator*(const Matrix3x4f &v) const; Matrix3x4f operator*(float v) const; Matrix3x4f operator-() const; // matrix * vector Vector3f operator*(const Vector3f &v) const; // constants static const Matrix3x4f &Zero, &Identity; public: union { float Elements[12]; float Row[3][4]; struct { float m00, m01, m02, m03; float m10, m11, m12, m13; float m20, m21, m22, m23; }; }; }; #define DEFINE_CONST_MATRIX4X4F(name, m00, m01, m02, m03, \ m10, m11, m12, m13, \ m20, m21, m22, m23, \ m30, m31, m32, m33) \ static const float __data_##name[16] = { \ m00, m01, m02, m03, \ m10, m11, m12, m13, \ m20, m21, m22, m23, \ m30, m31, m32, m33 \ }; \ const float4x4 &name = reinterpret_cast<const float4x4 &>(__data_##name); #define DECLARE_CONST_MATRIX4X4F(name) const float4x4 &name; <file_sep>/Editor/Source/Editor/EditorResourceSaveDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourceSaveDialog.h" #include "Editor/EditorResourcePreviewWidget.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Engine/ResourceManager.h" Log_SetChannel(EditorResourceSaveDialog); EditorResourceSaveDialog::EditorResourceSaveDialog(QWidget *pParent, const ResourceTypeInfo *pResourceTypeInfo) : QDialog(pParent, Qt::WindowTitleHint), m_pResourceTypeInfo(pResourceTypeInfo), m_pModel(NULL) { CreateUI(); NavigateToDirectory("/", false); } EditorResourceSaveDialog::~EditorResourceSaveDialog() { } bool EditorResourceSaveDialog::NavigateToDirectory(const char *directory, bool addToHistory /* = true */) { if (m_pModel != NULL) { m_pTreeView->setModel(NULL); delete m_pModel; } QString directoryVisual; if (directory == NULL || directory[0] == '\0' || (directory[0] == '/' && directory[1] == '\0')) { m_pModel = new EditorResourceSelectionDialogModel(EmptyString, true, true, 0, this); directoryVisual = "/"; } else { m_pModel = new EditorResourceSelectionDialogModel(directory, true, true, 0, this); directoryVisual = directory; } m_pModel->SetResourceFilter(&m_pResourceTypeInfo, 1); m_pTreeView->setModel(m_pModel); // update the combo box m_pDirectoryComboBox->clear(); // split it at / QString tempPath; QStringList directoryComponents = directoryVisual.split('/', QString::SkipEmptyParts); for (int i = 0; i < directoryComponents.size(); i++) { if (tempPath.length() > 0) tempPath.append('/'); tempPath.append(directoryComponents[i]); m_pDirectoryComboBox->insertItem(0, g_pEditor->GetIconLibrary()->GetListViewDirectoryIcon(), tempPath); } // add the root m_pDirectoryComboBox->addItem(g_pEditor->GetIconLibrary()->GetListViewDirectoryIcon(), "/"); m_pDirectoryComboBox->setCurrentIndex(0); // add to history if (addToHistory) m_history.push(ConvertStringToQString(m_pModel->GetRootPath())); // update button states m_pBackButton->setEnabled((m_history.size() > 0)); m_pUpDirectoryButton->setEnabled((m_pModel->GetRootPath().GetLength() > 0)); // clear any preview m_pSaveButton->setEnabled(false); return true; } void EditorResourceSaveDialog::CreateUI() { QToolButton *pMakeDirectoryButton; QPushButton *pCancelButton; // setup form setWindowTitle(QStringLiteral("Select Resource")); resize(960, 400); // create ui elements QGridLayout *gridLayout = new QGridLayout(this); QHBoxLayout *hboxLayout = new QHBoxLayout(); { m_pDirectoryComboBox = new QComboBox(this); m_pDirectoryComboBox->setEditable(true); hboxLayout->addWidget(m_pDirectoryComboBox, 1); QHBoxLayout *hboxLayout2 = new QHBoxLayout(); { m_pBackButton = new QToolButton(this); m_pBackButton->setEnabled(false); m_pBackButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("Back", 16)); hboxLayout2->addWidget(m_pBackButton); m_pUpDirectoryButton = new QToolButton(this); m_pUpDirectoryButton->setEnabled(false); m_pUpDirectoryButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("UpDirectory", 16)); hboxLayout2->addWidget(m_pUpDirectoryButton); pMakeDirectoryButton = new QToolButton(this); pMakeDirectoryButton->setIcon(g_pEditor->GetIconLibrary()->GetIconByName("NewDirectory", 16)); hboxLayout2->addWidget(pMakeDirectoryButton); } hboxLayout->addLayout(hboxLayout2); } gridLayout->addLayout(hboxLayout, 0, 0, 1, 1); //m_pTreeView = new QTreeView(this); //m_pTreeView->setExpandsOnDoubleClick(false); //gridLayout->addWidget(m_pTreeView, 1, 0, 1, 1); m_pTreeView = new QTreeView(this); m_pTreeView->setExpandsOnDoubleClick(false); gridLayout->addWidget(m_pTreeView, 1, 0, 1, 1); m_pResourceNameComboBox = new QComboBox(this); m_pResourceNameComboBox->setEditable(true); gridLayout->addWidget(m_pResourceNameComboBox, 2, 0, 1, 1); hboxLayout = new QHBoxLayout(); { m_pFilterTextLabel = new QLabel(this); hboxLayout->addWidget(m_pFilterTextLabel, 1); QHBoxLayout *hboxLayout2 = new QHBoxLayout(); { m_pSaveButton = new QPushButton(this); m_pSaveButton->setText(tr("Save")); m_pSaveButton->setDefault(true); hboxLayout2->addWidget(m_pSaveButton); pCancelButton = new QPushButton(this); pCancelButton->setText(tr("Cancel")); hboxLayout2->addWidget(pCancelButton); } hboxLayout->addLayout(hboxLayout2); } gridLayout->addLayout(hboxLayout, 3, 0, 1, 1); ////////////////////////////////////////////////////////////////////////// connect(m_pDirectoryComboBox, SIGNAL(activated(const QString &)), this, SLOT(OnDirectoryComboBoxActivated(const QString &))); connect(m_pBackButton, SIGNAL(clicked()), this, SLOT(OnBackButtonPressed())); connect(m_pUpDirectoryButton, SIGNAL(clicked()), this, SLOT(OnUpDirectoryButtonPressed())); connect(m_pTreeView, SIGNAL(activated(const QModelIndex &)), this, SLOT(OnTreeViewItemActivated(const QModelIndex &))); connect(m_pTreeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(OnTreeViewItemClicked(const QModelIndex &))); connect(m_pResourceNameComboBox, SIGNAL(editTextChanged(const QString &)), this, SLOT(OnResourceNameEditTextChanged(const QString &))); connect(m_pSaveButton, SIGNAL(clicked()), this, SLOT(OnSaveButtonClicked())); connect(pCancelButton, SIGNAL(clicked()), this, SLOT(OnCancelButtonClicked())); } void EditorResourceSaveDialog::UpdateReturnValue() { QString name = m_pResourceNameComboBox->currentText(); if (name.length() == 0) { m_returnValueResourceName = EmptyString; m_pSaveButton->setEnabled(false); return; } m_returnValueResourceName.Clear(); if (m_pModel->GetRootPath().GetLength() > 0) { m_returnValueResourceName.AppendString(m_pModel->GetRootPath()); m_returnValueResourceName.AppendCharacter('/'); } m_returnValueResourceName.AppendString(ConvertQStringToString(name)); m_pSaveButton->setEnabled(true); } void EditorResourceSaveDialog::OnDirectoryComboBoxActivated(const QString &text) { // clear any leading / String directoryPath(ConvertQStringToString(text)); if (directoryPath.GetLength() > 0 && directoryPath[0] == '/') directoryPath.Erase(0, 1); // navigate to this path NavigateToDirectory(directoryPath); } void EditorResourceSaveDialog::OnBackButtonPressed() { if (m_history.size() > 0) { String newPath(ConvertQStringToString(m_history.top())); m_history.pop(); NavigateToDirectory(newPath, false); } } void EditorResourceSaveDialog::OnUpDirectoryButtonPressed() { if (m_pModel->GetRootPath().GetLength() > 0) { int32 pos = m_pModel->GetRootPath().RFind('/'); if (pos >= 0) { PathString newPath; newPath.AppendSubString(m_pModel->GetRootPath(), 0, pos); NavigateToDirectory(newPath); } else { // go to root NavigateToDirectory("/"); } } } void EditorResourceSaveDialog::OnMakeDirectoryButtonPressed() { } void EditorResourceSaveDialog::OnTreeViewItemActivated(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_pModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == NULL) return; if (pDirectoryNode->IsDirectory()) { // enter this directory, have to temporarily copy the string though, as navigating will destroy the node String directoryPathCopy(pDirectoryNode->GetFullName()); NavigateToDirectory(directoryPathCopy); } else { // select this item OnSaveButtonClicked(); } } void EditorResourceSaveDialog::OnTreeViewItemClicked(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_pModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == NULL) return; // resource? if (pDirectoryNode->GetResourceTypeInfo() != NULL) { // pick up the parent folder names PathString relativeName; relativeName.AppendString(pDirectoryNode->GetDisplayName()); const EditorResourceSelectionDialogModel::DirectoryNode *pParentNode = pDirectoryNode->GetParent(); while (pParentNode->GetParent() != NULL) { relativeName.PrependFormattedString("%s/", pParentNode->GetDisplayName().GetCharArray()); pParentNode = pParentNode->GetParent(); } m_pResourceNameComboBox->setCurrentText(ConvertStringToQString(relativeName)); } } void EditorResourceSaveDialog::OnResourceNameEditTextChanged(const QString &contents) { UpdateReturnValue(); } void EditorResourceSaveDialog::OnSaveButtonClicked() { done(1); } void EditorResourceSaveDialog::OnCancelButtonClicked() { m_pResourceNameComboBox->setCurrentText(QStringLiteral("")); done(0); } <file_sep>/Engine/Source/MapCompiler/MapSourceTerrainData.cpp #include "MapCompiler/MapSourceTerrainData.h" #include "ResourceCompiler/TerrainLayerListGenerator.h" #include "Core/Image.h" #include "YBaseLib/ZipArchive.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(MapSourceTerrainData); MapSourceTerrainData::MapSourceTerrainData(MapSource *pMapSource) : m_pMapSource(pMapSource), m_pLayerListGenerator(nullptr), m_pLayerList(nullptr), m_layerListChanged(false), m_minSectionX(0), m_minSectionY(0), m_maxSectionX(0), m_maxSectionY(0), m_sectionCountX(0), m_sectionCountY(0), m_sectionCount(0), m_availableSectionsChanged(false), m_ppSections(nullptr), m_pEditCallbacks(nullptr) { } MapSourceTerrainData::~MapSourceTerrainData() { for (int32 i = 0; i < m_sectionCount; i++) { if (m_ppSections[i] != nullptr) m_ppSections[i]->Release(); } delete[] m_ppSections; if (m_pLayerList != nullptr) m_pLayerList->Release(); delete m_pLayerListGenerator; } void MapSourceTerrainData::MakeTerrainStorageFileName(String &str, int32 sectionX, int32 sectionY) { str.Format("terrain_sections/%i_%i.dat", sectionX, sectionY); } int32 MapSourceTerrainData::GetSectionArrayIndex(int32 sectionX, int32 sectionY, int32 minSectionX, int32 minSectionY, int32 maxSectionX, int32 maxSectionY) { return ((sectionY - minSectionY) * (maxSectionX - minSectionX)) + (sectionX - minSectionX); } int32 MapSourceTerrainData::GetSectionArrayIndex(int32 sectionX, int32 sectionY) const { DebugAssert(sectionX >= m_minSectionX && sectionX <= m_maxSectionX && sectionY >= m_minSectionY && sectionY <= m_maxSectionY); return ((sectionY - m_minSectionY) * m_sectionCountX) + (sectionX - m_minSectionX); } AABox MapSourceTerrainData::CalculateSectionBoundingBox(int32 sectionX, int32 sectionY) const { return TerrainUtilities::CalculateSectionBoundingBox(&m_parameters, sectionX, sectionY); } AABox MapSourceTerrainData::CalculateTerrainBoundingBox() const { int32 scale = (int32)m_parameters.Scale; int32 sectionSize = (int32)m_parameters.SectionSize; int32 minX = m_minSectionX * sectionSize * scale; int32 minY = m_minSectionY * sectionSize * sectionSize; int32 maxX = (m_maxSectionX + 1) * sectionSize * scale; int32 maxY = (m_maxSectionY + 1) * sectionSize * scale; return AABox((float)minX, (float)minY, (float)m_parameters.MinHeight, (float)maxX, (float)maxY, (float)m_parameters.MaxHeight); } int2 MapSourceTerrainData::CalculateSectionForPoint(int32 globalX, int32 globalY) const { return TerrainUtilities::CalculateSectionForPoint(&m_parameters, globalX, globalY); } int2 MapSourceTerrainData::CalculateSectionForPosition(const float3 &position) const { return TerrainUtilities::CalculateSectionForPosition(&m_parameters, position); } void MapSourceTerrainData::CalculateSectionAndOffsetForPoint(int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, int32 globalX, int32 globalY) const { TerrainUtilities::CalculateSectionAndOffsetForPoint(&m_parameters, pSectionX, pSectionY, pIndexX, pIndexY, globalX, globalY); } void MapSourceTerrainData::CalculateSectionAndOffsetForPosition(int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, const float3 &position) const { TerrainUtilities::CalculateSectionAndOffsetForPosition(&m_parameters, pSectionX, pSectionY, pIndexX, pIndexY, position); } int2 MapSourceTerrainData::CalculatePointForPosition(const float3 &position) const { return TerrainUtilities::CalculatePointForPosition(&m_parameters, position); } float3 MapSourceTerrainData::CalculatePositionForPoint(int32 globalX, int32 globalY) const { return TerrainUtilities::CalculatePositionForPoint(&m_parameters, globalX, globalY); } void MapSourceTerrainData::CalculatePointForSectionAndOffset(int32 *pGlobalX, int32 *pGlobalY, int32 sectionX, int32 sectionY, uint32 offsetX, uint32 offsetY) const { TerrainUtilities::CalculatePointForSectionAndOffset(&m_parameters, pGlobalX, pGlobalY, sectionX, sectionY, offsetX, offsetY); } uint8 MapSourceTerrainData::GetDefaultLayer() const { return (uint8)m_pLayerList->GetFirstLayerIndex(); } bool MapSourceTerrainData::IsSectionAvailable(int32 sectionX, int32 sectionY) const { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return false; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); return m_availableSectionMask.TestBit(sectionIndex); } bool MapSourceTerrainData::IsSectionLoaded(int32 sectionX, int32 sectionY) const { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return false; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); const TerrainSection *pSection = m_ppSections[sectionIndex]; return (pSection != nullptr); } const TerrainSection *MapSourceTerrainData::GetSection(int32 sectionX, int32 sectionY) const { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return NULL; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); return m_ppSections[sectionIndex]; } TerrainSection *MapSourceTerrainData::GetSection(int32 sectionX, int32 sectionY) { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return NULL; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); return m_ppSections[sectionIndex]; } TerrainLayerList *MapSourceTerrainData::CompileLayerList(const TerrainLayerListGenerator *pGenerator, BinaryBlob **ppStoreBlob) { ByteStream *pMemoryStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pMemoryStream)) return nullptr; pMemoryStream->SeekAbsolute(0); TerrainLayerList *pLayerList = new TerrainLayerList(); if (!pLayerList->Load("<in memory>", pMemoryStream)) { pLayerList->Release(); pMemoryStream->Release(); return nullptr; } if (ppStoreBlob != nullptr) { pMemoryStream->SeekAbsolute(0); *ppStoreBlob = BinaryBlob::CreateFromStream(pMemoryStream); } pMemoryStream->Release(); return pLayerList; } bool MapSourceTerrainData::Create(const TerrainParameters *pParameters, const TerrainLayerListGenerator *pLayerListGenerator, ProgressCallbacks *pProgressCallbacks) { DebugAssert(TerrainUtilities::IsValidParameters(pParameters)); // set parameters m_parameters = *pParameters; // compile the layer list { pProgressCallbacks->SetStatusText("Compiling layer list..."); // make a copy TerrainLayerListGenerator *pOurLayerListGenerator = new TerrainLayerListGenerator(); pOurLayerListGenerator->CreateCopy(pLayerListGenerator); // compile it TerrainLayerList *pLayerList; if ((pLayerList = CompileLayerList(pOurLayerListGenerator, nullptr)) == nullptr) { pProgressCallbacks->DisplayError("Failed to compile layer list."); delete pLayerListGenerator; return false; } // new so changed m_pLayerListGenerator = pOurLayerListGenerator; m_pLayerList = pLayerList; m_layerListChanged = true; } // init storage, set up sizes m_minSectionX = 0; m_minSectionY = 0; m_maxSectionX = 0; m_maxSectionY = 0; m_sectionCountX = m_maxSectionX - m_minSectionX + 1; m_sectionCountY = m_maxSectionY - m_minSectionY + 1; m_sectionCount = m_sectionCountX * m_sectionCountY; // allocate bitset m_availableSectionMask.Resize((uint32)m_sectionCount); m_availableSectionMask.Clear(); // and the array m_ppSections = new TerrainSection *[m_sectionCount]; Y_memzero(m_ppSections, sizeof(TerrainSection *)* m_sectionCount); return true; } bool MapSourceTerrainData::Load(ProgressCallbacks *pProgressCallbacks) { // read the xml { AutoReleasePtr<ByteStream> pStream = m_pMapSource->GetMapArchive()->OpenFile("terrain.xml", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == NULL) return false; XMLReader xmlReader; if (!xmlReader.Create(pStream, "terrain.xml")) return false; if (!xmlReader.SkipToElement("terrain")) { xmlReader.PrintError("could not skip to terrain element"); return false; } bool hasParameters = false; bool hasSections = false; for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 terrainSelection = xmlReader.Select("parameters|sections"); if (terrainSelection < 0) return false; switch (terrainSelection) { // parameters case 0: { const char *heightStorageFormatStr = xmlReader.FetchAttribute("height-storage-format"); const char *scaleStr = xmlReader.FetchAttribute("scale"); const char *sectionSizeStr = xmlReader.FetchAttribute("section-size"); const char *renderLODCountStr = xmlReader.FetchAttribute("render-lods"); const char *minHeightStr = xmlReader.FetchAttribute("min-height"); const char *maxHeightStr = xmlReader.FetchAttribute("max-height"); const char *baseHeightStr = xmlReader.FetchAttribute("base-height"); if (heightStorageFormatStr == NULL || scaleStr == NULL || sectionSizeStr == NULL || renderLODCountStr == NULL || minHeightStr == NULL || maxHeightStr == NULL || baseHeightStr == NULL) { xmlReader.PrintError("incomplete terrain parameters"); return false; } m_parameters.Scale = StringConverter::StringToUInt32(scaleStr); m_parameters.SectionSize = StringConverter::StringToUInt32(sectionSizeStr); m_parameters.LODCount = StringConverter::StringToUInt32(renderLODCountStr); m_parameters.MinHeight = StringConverter::StringToInt32(minHeightStr); m_parameters.MaxHeight = StringConverter::StringToInt32(maxHeightStr); m_parameters.BaseHeight = StringConverter::StringToInt32(baseHeightStr); if (!NameTable_TranslateType(NameTables::TerrainHeightStorageFormat, heightStorageFormatStr, &m_parameters.HeightStorageFormat)) { xmlReader.PrintError("invalid height storage format"); return false; } if ((m_pMapSource->GetRegionSize() % (m_parameters.SectionSize * m_parameters.Scale)) != 0 || !TerrainUtilities::IsValidParameters(&m_parameters)) { xmlReader.PrintError("invalid parameters"); return false; } hasParameters = true; } break; // sections case 1: { const char *minXStr = xmlReader.FetchAttribute("min-x"); const char *minYStr = xmlReader.FetchAttribute("min-y"); const char *maxXStr = xmlReader.FetchAttribute("max-x"); const char *maxYStr = xmlReader.FetchAttribute("max-y"); if (minXStr == NULL || minYStr == NULL || maxXStr == NULL || maxYStr == NULL) { xmlReader.PrintError("incomplete sections definition"); return false; } m_minSectionX = StringConverter::StringToInt32(minXStr); m_minSectionY = StringConverter::StringToInt32(minYStr); m_maxSectionX = StringConverter::StringToInt32(maxXStr); m_maxSectionY = StringConverter::StringToInt32(maxYStr); // set up sizes DebugAssert(m_minSectionX <= m_maxSectionX && m_minSectionY <= m_maxSectionY); m_sectionCountX = m_maxSectionX - m_minSectionX + 1; m_sectionCountY = m_maxSectionY - m_minSectionY + 1; m_sectionCount = m_sectionCountX * m_sectionCountY; // allocate bitset m_availableSectionMask.Resize((uint32)m_sectionCount); m_availableSectionMask.Clear(); // and the array m_ppSections = new TerrainSection *[m_sectionCount]; Y_memzero(m_ppSections, sizeof(TerrainSection *)* m_sectionCount); // fill the bitset if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 sectionsSelection = xmlReader.Select("section"); if (sectionsSelection < 0) return false; const char *sectionXStr = xmlReader.FetchAttribute("x"); const char *sectionYStr = xmlReader.FetchAttribute("y"); if (sectionXStr == NULL || sectionYStr == NULL) { xmlReader.PrintError("missing x or y attributes"); return false; } int32 sectionX = StringConverter::StringToInt32(sectionXStr); int32 sectionY = StringConverter::StringToInt32(sectionYStr); int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask.TestBit(arrayIndex)) { xmlReader.PrintError("duplicate defined section (%u, %u)", sectionX, sectionY); return false; } m_availableSectionMask.SetBit(arrayIndex); } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "sections") == 0); break; } } } hasSections = true; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "terrain") == 0); break; } } if (!hasParameters || !hasSections) { xmlReader.PrintError("incomplete terrain xml definition"); return false; } } // load the layer list { AutoReleasePtr<ByteStream> pStream = m_pMapSource->GetMapArchive()->OpenFile("terrain_layers.zip", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == NULL) return false; TerrainLayerListGenerator *pLayerListGenerator = new TerrainLayerListGenerator(); if (!pLayerListGenerator->Load("terrain_layers.zip", pStream, pProgressCallbacks)) { pProgressCallbacks->DisplayError("Failed to load terrain layer list."); delete pLayerListGenerator; return false; } pProgressCallbacks->SetStatusText("Compiling layer list..."); m_pLayerListGenerator = pLayerListGenerator; if ((m_pLayerList = CompileLayerList(pLayerListGenerator, nullptr)) == nullptr) { pProgressCallbacks->DisplayError("Failed to compile terrain layer list."); return false; } } // all done return true; } bool MapSourceTerrainData::Save(ProgressCallbacks *pProgressCallbacks) { PathString fileName; pProgressCallbacks->SetProgressRange(3); pProgressCallbacks->SetProgressValue(0); pProgressCallbacks->PushState(); // for each loaded section, save any changed sections if (m_loadedSections.GetSize() > 0) { pProgressCallbacks->SetStatusText("Saving terrain sections..."); pProgressCallbacks->SetProgressRange(m_loadedSections.GetSize()); pProgressCallbacks->SetProgressValue(0); for (uint32 i = 0; i < m_loadedSections.GetSize(); i++) { const TerrainSection *pSection = m_loadedSections[i]; if (pSection->IsChanged()) { MakeTerrainStorageFileName(fileName, pSection->GetSectionX(), pSection->GetSectionY()); ByteStream *pSectionStream = m_pMapSource->GetMapArchive()->OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pSectionStream == NULL) { Log_WarningPrintf("MapSourceTerrainData::Save: Could not open '%s' for writing.", fileName.GetCharArray()); return false; } if (!pSection->SaveToStream(pSectionStream)) { Log_WarningPrintf("MapSourceTerrainData::Save: Failed to write '%s'.", fileName.GetCharArray()); return false; } pSectionStream->Release(); } pProgressCallbacks->IncrementProgressValue(); } } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(1); pProgressCallbacks->SetStatusText("Saving terrain header..."); // write header xml { ByteStream *pHeaderStream = m_pMapSource->GetMapArchive()->OpenFile("terrain.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pHeaderStream == NULL) return false; XMLWriter xmlWriter; if (!xmlWriter.Create(pHeaderStream)) { pHeaderStream->Release(); return false; } xmlWriter.StartElement("terrain"); { xmlWriter.StartElement("parameters"); { xmlWriter.WriteAttribute("height-storage-format", NameTable_GetNameString(NameTables::TerrainHeightStorageFormat, m_parameters.HeightStorageFormat)); xmlWriter.WriteAttributef("scale", "%u", m_parameters.Scale); xmlWriter.WriteAttributef("section-size", "%u", m_parameters.SectionSize); xmlWriter.WriteAttributef("render-lods", "%u", m_parameters.LODCount); xmlWriter.WriteAttributef("min-height", "%i", m_parameters.MinHeight); xmlWriter.WriteAttributef("max-height", "%i", m_parameters.MaxHeight); xmlWriter.WriteAttributef("base-height", "%i", m_parameters.BaseHeight); } xmlWriter.EndElement(); xmlWriter.StartElement("sections"); { xmlWriter.WriteAttributef("min-x", "%i", m_minSectionX); xmlWriter.WriteAttributef("min-y", "%i", m_minSectionY); xmlWriter.WriteAttributef("max-x", "%i", m_maxSectionX); xmlWriter.WriteAttributef("max-y", "%i", m_maxSectionY); EnumerateAvailableSections([&xmlWriter](int32 sectionX, int32 sectionY) { xmlWriter.StartElement("section"); xmlWriter.WriteAttributef("x", "%i", sectionX); xmlWriter.WriteAttributef("y", "%i", sectionY); xmlWriter.EndElement(); }); } xmlWriter.EndElement(); } xmlWriter.EndElement(); if (xmlWriter.InErrorState() || pHeaderStream->InErrorState()) { xmlWriter.Close(); pHeaderStream->Release(); return false; } xmlWriter.Close(); pHeaderStream->Release(); } pProgressCallbacks->SetProgressValue(2); pProgressCallbacks->SetStatusText("Saving terrain layers..."); // write layers to the archive { ByteStream *pLayersStream = m_pMapSource->GetMapArchive()->OpenFile("terrain_layers.zip", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pLayersStream == NULL) return false; if (!m_pLayerListGenerator->Save(pLayersStream, pProgressCallbacks)) { pProgressCallbacks->DisplayError("Failed to save terrain layers."); return false; } pLayersStream->Release(); } pProgressCallbacks->SetProgressValue(3); // delete any deleted sections from the archive for (uint32 i = 0; i < m_deletedSections.GetSize(); i++) { MakeTerrainStorageFileName(fileName, m_deletedSections[i].x, m_deletedSections[i].y); if (!m_pMapSource->GetMapArchive()->DeleteFile(fileName)) Log_WarningPrintf("MapSourceTerrainStreamingCallbacks::UpdateArchive: Could not remove file '%s' for deleted section.", fileName.GetCharArray()); } m_deletedSections.Clear(); // clear changed flag on any loaded sections for (uint32 i = 0; i < m_loadedSections.GetSize(); i++) { if (m_loadedSections[i]->IsChanged()) m_loadedSections[i]->ClearChangedFlag(); } // clear saved flags m_layerListChanged = false; m_availableSectionsChanged = false; return true; } void MapSourceTerrainData::Delete() { PathString fileName; // unload all sections ignoring any changes UnloadAllSections(true); DebugAssert(m_loadedSections.GetSize() == 0); // delete any deleted sections from the archive for (uint32 i = 0; i < m_deletedSections.GetSize(); i++) { MakeTerrainStorageFileName(fileName, m_deletedSections[i].x, m_deletedSections[i].y); if (!m_pMapSource->GetMapArchive()->DeleteFile(fileName)) Log_WarningPrintf("MapSourceTerrainData::Delete: Could not remove file '%s' for deleted section.", fileName.GetCharArray()); } m_deletedSections.Clear(); // delete any available sections from the archive EnumerateAvailableSections([this, &fileName](int32 sectionX, int32 sectionY) { MakeTerrainStorageFileName(fileName, sectionX, sectionY); // this call may fail, if it was a cached section that was never saved. m_pMapSource->GetMapArchive()->DeleteFile(fileName); }); // clear the available section mask m_availableSectionMask.Clear(); // nuke the header file if (!m_pMapSource->GetMapArchive()->DeleteFile("terrain.xml")) Log_WarningPrintf("MapSourceTerrainData::Delete: Could not remove header file."); // nuke the header file if (!m_pMapSource->GetMapArchive()->DeleteFile("terrain_layers.zip")) Log_WarningPrintf("MapSourceTerrainData::Delete: Could not remove layers file."); } bool MapSourceTerrainData::IsChanged() const { if (m_layerListChanged) return true; if (m_availableSectionsChanged) return true; for (uint32 i = 0; i < m_loadedSections.GetSize(); i++) { if (m_loadedSections[i]->IsChanged()) return true; } return false; } bool MapSourceTerrainData::LoadAllSections(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { pProgressCallbacks->SetStatusText("Loading terrain sections..."); pProgressCallbacks->SetProgressRange(m_sectionCount); pProgressCallbacks->SetProgressValue(0); pProgressCallbacks->SetCancellable(false); for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask.TestBit(arrayIndex) && m_ppSections[arrayIndex] == nullptr) { if (!LoadSection(sectionX, sectionY)) return false; } pProgressCallbacks->IncrementProgressValue(); } } return true; } void MapSourceTerrainData::UnloadAllSections(bool discardChanges /* = false */) { while (m_loadedSections.GetSize() > 0) { if (discardChanges || !m_loadedSections[0]->IsChanged()) UnloadSection(m_loadedSections[0]->GetSectionX(), m_loadedSections[0]->GetSectionY()); } } void MapSourceTerrainData::ResizeSectionArray(int32 newMinSectionX, int32 newMinSectionY, int32 newMaxSectionX, int32 newMaxSectionY) { int32 newSectionCountX = (newMaxSectionX - newMinSectionX) + 1; int32 newSectionCountY = (newMaxSectionY - newMinSectionY) + 1; int32 newSectionCount = newSectionCountX * newSectionCountY; DebugAssert(newMinSectionX <= m_minSectionX && newMinSectionY <= m_minSectionY); DebugAssert(newMaxSectionX >= m_maxSectionX && newMaxSectionY >= m_maxSectionY); DebugAssert(newSectionCountX > 0 && newSectionCountY > 0); // build new bitset and array BitSet32 newAvailableSectionMask(newSectionCount); newAvailableSectionMask.Clear(); TerrainSection **ppNewSectionArray = new TerrainSection *[newSectionCount]; Y_memzero(ppNewSectionArray, sizeof(TerrainSection *) * newSectionCount); // fill new bitset/array for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 oldIndex = ((sectionY - m_minSectionY) * m_sectionCountX) + (sectionX - m_minSectionX); DebugAssert(oldIndex >= 0 && oldIndex < m_sectionCount); if (m_availableSectionMask.TestBit((uint32)oldIndex)) { int32 newIndex = ((sectionY - newMinSectionY) * newSectionCountX) + (sectionX - newMinSectionX); DebugAssert(newIndex >= 0 && newIndex < newSectionCount); newAvailableSectionMask.SetBit((uint32)newIndex); ppNewSectionArray[newIndex] = m_ppSections[oldIndex]; } } } // swap everything over m_minSectionX = newMinSectionX; m_minSectionY = newMinSectionY; m_maxSectionX = newMaxSectionX; m_maxSectionY = newMaxSectionY; m_sectionCountX = newSectionCountX; m_sectionCountY = newSectionCountY; m_sectionCount = newSectionCount; delete[] m_ppSections; m_ppSections = ppNewSectionArray; m_availableSectionMask.Swap(newAvailableSectionMask); } uint32 MapSourceTerrainData::CreateSections(const int2 *pNewSectionIndices, uint32 newSectionCount, float createHeight, uint8 createLayer, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { uint32 sectionSize = m_parameters.SectionSize; uint32 sectionsCreated = 0; // get the min/max new section coordinates int32 minNewSectionX = pNewSectionIndices[0].x; int32 minNewSectionY = pNewSectionIndices[0].y; int32 maxNewSectionX = minNewSectionX; int32 maxNewSectionY = minNewSectionY; for (uint32 i = 1; i < newSectionCount; i++) { int32 sx = pNewSectionIndices[i].x; int32 sy = pNewSectionIndices[i].y; minNewSectionX = Min(minNewSectionX, sx); minNewSectionY = Min(minNewSectionY, sy); maxNewSectionX = Max(maxNewSectionX, sx); maxNewSectionY = Max(maxNewSectionY, sy); } // resize terrain? if (minNewSectionX < m_minSectionX || maxNewSectionX > m_maxSectionX || minNewSectionY < m_minSectionY || maxNewSectionY > m_maxSectionY) { ResizeSectionArray(Min(minNewSectionX, m_minSectionX), Min(minNewSectionY, m_minSectionY), Max(maxNewSectionX, m_maxSectionX), Max(maxNewSectionY, m_maxSectionY)); } // create the sections for (uint32 i = 0; i < newSectionCount; i++) { int32 newSectionX = pNewSectionIndices[i].x; int32 newSectionY = pNewSectionIndices[i].y; if (IsSectionAvailable(newSectionX, newSectionY)) { Log_ErrorPrintf("Refusing to create section [%u, %u] (relative [%i, %i]), already exists", newSectionX, newSectionY, pNewSectionIndices[i].x, pNewSectionIndices[i].y); continue; } if (!EnsureAdjacentSectionsLoaded(newSectionX, newSectionY)) { Log_ErrorPrintf("Refusing to create section [%u, %u], (relative [%i, %i]), could not load adjacent sections", newSectionX, newSectionY, pNewSectionIndices[i].x, pNewSectionIndices[i].y); continue; } // create the section TerrainSection *pSection = new TerrainSection(&m_parameters, newSectionX, newSectionY, 0); pSection->Create(createHeight, createLayer); /* GetSection(newSectionX, newSectionY - 1), // south GetSection(newSectionX + 1, newSectionY - 1), // south-east GetSection(newSectionX + 1, newSectionY)); // east */ // store in lod 0 int32 arrayIndex = GetSectionArrayIndex(newSectionX, newSectionY); DebugAssert(m_ppSections[arrayIndex] == NULL && !m_availableSectionMask.TestBit(arrayIndex)); m_availableSectionMask.SetBit(arrayIndex); m_availableSectionsChanged = true; m_ppSections[arrayIndex] = pSection; m_loadedSections.Add(pSection); sectionsCreated++; // notify callbacks if (m_pEditCallbacks != nullptr) { m_pEditCallbacks->OnSectionCreated(newSectionX, newSectionY); m_pEditCallbacks->OnSectionLoaded(pSection); } // remove from deleted section list int32 deletedSectionIndex = m_deletedSections.IndexOf(int2(newSectionX, newSectionY)); if (deletedSectionIndex >= 0) m_deletedSections.OrderedRemove(deletedSectionIndex); // update adjacent sections // west pixels for (uint32 y = 0; y < sectionSize; y++) { HandleEdgePointsHeightUpdate(pSection, 0, y); HandleEdgePointsWeightUpdate(pSection, 0, y); } // south pixels for (uint32 x = 0; x < sectionSize; x++) { HandleEdgePointsHeightUpdate(pSection, x, 0); HandleEdgePointsWeightUpdate(pSection, x, 0); } // south-west pixels HandleEdgePointsHeightUpdate(pSection, 0, 0); HandleEdgePointsWeightUpdate(pSection, 0, 0); } return sectionsCreated; } void MapSourceTerrainData::DeleteSections(const int2 *pSectionIndices, uint32 sectionCount, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { uint32 sectionSize = m_parameters.SectionSize; int32 baseHeight = m_parameters.BaseHeight; for (uint32 i = 0; i < sectionCount; i++) { int32 sectionX = pSectionIndices[i].x; int32 sectionY = pSectionIndices[i].y; if (!IsSectionAvailable(sectionX, sectionY)) { Log_ErrorPrintf("Refusing to delete section [%u, %u] does not exist", sectionX, sectionY); continue; } // remove heights from adjacent sections if (!EnsureAdjacentSectionsLoaded(sectionX, sectionY)) { Log_ErrorPrintf("Refusing to delete section [%u, %u], could not load adjacent sections", sectionX, sectionY); continue; } // update adjacent sections with base heights TerrainSection *pAdjacentSection; // section to the west pAdjacentSection = GetSection(sectionX - 1, sectionY); if (pAdjacentSection != NULL) { for (uint32 y = 0; y < sectionSize; y++) { pAdjacentSection->SetHeightMapValue(sectionSize, y, (float)baseHeight); pAdjacentSection->ClearSplatMapValues(sectionSize, y); if (m_pEditCallbacks != nullptr) { m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, sectionSize, y); m_pEditCallbacks->OnSectionPointLayersModified(pAdjacentSection, sectionSize, y); } } } // section to the north pAdjacentSection = GetSection(sectionX, sectionY + 1); if (pAdjacentSection != NULL) { for (uint32 x = 0; x < sectionSize; x++) { pAdjacentSection->SetHeightMapValue(x, sectionSize, (float)baseHeight); pAdjacentSection->ClearSplatMapValues(x, sectionSize); if (m_pEditCallbacks != nullptr) { m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, x, sectionSize); m_pEditCallbacks->OnSectionPointLayersModified(pAdjacentSection, x, sectionSize); } } } // section to the north-west pAdjacentSection = GetSection(sectionX - 1, sectionY + 1); if (pAdjacentSection != NULL) { pAdjacentSection->SetHeightMapValue(sectionSize, sectionSize, (float)baseHeight); pAdjacentSection->ClearSplatMapValues(sectionSize, sectionSize); if (m_pEditCallbacks != nullptr) { m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, sectionSize, sectionSize); m_pEditCallbacks->OnSectionPointLayersModified(pAdjacentSection, sectionSize, sectionSize); } } // delete the section uint32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); TerrainSection *pSection = m_ppSections[arrayIndex]; // unload section if (pSection != nullptr) { if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionUnloaded(pSection); pSection->Release(); m_ppSections[arrayIndex] = nullptr; } // execute callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionDeleted(sectionX, sectionY); // set unavailable m_availableSectionMask.UnsetBit(arrayIndex); // store in deleted section list if (m_deletedSections.IndexOf(int2(sectionX, sectionY)) < 0) m_deletedSections.Add(int2(sectionX, sectionY)); } } void MapSourceTerrainData::DeleteAllSections() { for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (!m_availableSectionMask[arrayIndex]) continue; TerrainSection *pSection = m_ppSections[arrayIndex]; // unload section if (pSection != nullptr) { if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionUnloaded(pSection); pSection->Release(); m_ppSections[arrayIndex] = nullptr; } // execute callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionDeleted(sectionX, sectionY); } } // set up sizes m_minSectionX = 0; m_minSectionY = 0; m_maxSectionX = 0; m_maxSectionY = 0; m_sectionCountX = m_maxSectionX - m_minSectionX + 1; m_sectionCountY = m_maxSectionY - m_minSectionY + 1; m_sectionCount = m_sectionCountX * m_sectionCountY; // allocate bitset m_availableSectionMask.Resize((uint32)m_sectionCount); m_availableSectionMask.Clear(); // and the array m_ppSections = new TerrainSection *[m_sectionCount]; Y_memzero(m_ppSections, sizeof(TerrainSection *)* m_sectionCount); } bool MapSourceTerrainData::LoadSection(int32 sectionX, int32 sectionY) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); Assert(m_availableSectionMask.TestBit(arrayIndex)); TerrainSection *pSection = m_ppSections[arrayIndex]; if (pSection != nullptr) return true; // hit the archive for it PathString fileName; MakeTerrainStorageFileName(fileName, sectionX, sectionY); // open the file AutoReleasePtr<ByteStream> pStream = m_pMapSource->GetMapArchive()->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_WarningPrintf("MapSourceTerrainData::LoadSection: Could not open '%s' in archive.", fileName.GetCharArray()); return false; } // create section pSection = new TerrainSection(&m_parameters, sectionX, sectionY, 0); if (!pSection->LoadFromStream(pStream)) { Log_WarningPrintf("MapSourceTerrainData::LoadSection: Terrain load for section (%i, %i) failed.", sectionX, sectionY); return false; } // store section m_ppSections[arrayIndex] = pSection; m_loadedSections.Add(pSection); // execute callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionLoaded(pSection); return true; } void MapSourceTerrainData::UnloadSection(int32 sectionX, int32 sectionY) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(arrayIndex >= 0); // ok, unload it TerrainSection *pSection = m_ppSections[arrayIndex]; int32 loadedSectionIndex = m_loadedSections.IndexOf(pSection); Assert(pSection != nullptr && loadedSectionIndex >= 0); // warn if changed if (pSection->IsChanged()) Log_WarningPrintf("MapSourceTerrainData::UnloadSection: Unloading section %i that has been modified, changes to this section are now lost", sectionX, sectionY); // invoke callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionUnloaded(pSection); // kill the section pSection->Release(); m_loadedSections.FastRemove(loadedSectionIndex); m_ppSections[arrayIndex] = nullptr; } bool MapSourceTerrainData::CreateSection(int32 sectionX, int32 sectionY, float createHeight, uint8 createLayer, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { int2 sectionLocation(sectionX, sectionY); return (CreateSections(&sectionLocation, 1, createHeight, createLayer, pProgressCallbacks) == 1); } void MapSourceTerrainData::DeleteSection(int32 sectionX, int32 sectionY, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { int2 sectionLocation(sectionX, sectionY); DeleteSections(&sectionLocation, 1, pProgressCallbacks); } float MapSourceTerrainData::GetPointHeight(int32 pointX, int32 pointY) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return (float)m_parameters.BaseHeight; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return (float)m_parameters.BaseHeight; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != NULL); } return pSection->GetHeightMapValue(offsetX, offsetY); } float MapSourceTerrainData::GetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return false; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return false; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != NULL); } return pSection->GetSplatMapValue(offsetX, offsetY, layer); } bool MapSourceTerrainData::SetPointHeight(int32 pointX, int32 pointY, float height) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return false; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return false; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != NULL); } // clamp height height = Math::Clamp(height, (float)m_parameters.MinHeight, (float)m_parameters.MaxHeight); // needs to be changed? if (pSection->GetHeightMapValue(offsetX, offsetY) == height) return true; // handle boundary cases, we need to update the neighbour section as well if (offsetX == 0 || offsetY == 0) { if (!EnsureAdjacentSectionsLoaded(sectionX, sectionY)) return false; } // set the height in the section pSection->SetHeightMapValue(offsetX, offsetY, height); // callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointHeightModified(pSection, offsetX, offsetY); // update edge sections HandleEdgePointsHeightUpdate(pSection, offsetX, offsetY); // success return true; } bool MapSourceTerrainData::AddPointHeight(int32 pointX, int32 pointY, float mod) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return false; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return false; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); } return SetPointHeight(pointX, pointY, pSection->GetHeightMapValue(offsetX, offsetY) + mod); } bool MapSourceTerrainData::SetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float weight, bool renormalize /* = true */) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return false; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return false; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); } // check it has to be changed if (pSection->GetSplatMapValue(offsetX, offsetY, layer) == weight) return true; // handle boundary cases, we need to update the neighbour section as well if (offsetX == 0 || offsetY == 0) { if (!EnsureAdjacentSectionsLoaded(sectionX, sectionY)) return false; } // set the height in the section bool hadLayer = pSection->HasSplatMapForLayer(layer); pSection->SetSplatMapValue(offsetX, offsetY, layer, weight, renormalize); // callbacks if (m_pEditCallbacks != nullptr) { if (!hadLayer) m_pEditCallbacks->OnSectionLayersModified(pSection); m_pEditCallbacks->OnSectionPointLayersModified(pSection, offsetX, offsetY); } // update edge points HandleEdgePointsWeightUpdate(pSection, offsetX, offsetY); return true; } bool MapSourceTerrainData::AddPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float amount, bool renormalize /* = true */) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(&sectionX, &sectionY, &offsetX, &offsetY, pointX, pointY); // is a valid section? if (!IsSectionAvailable(sectionX, sectionY)) return false; // ensure this section is loaded TerrainSection *pSection = GetSection(sectionX, sectionY); if (!IsSectionLoaded(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY)) return false; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); } return SetPointLayerWeight(pointX, pointY, layer, Math::Clamp(pSection->GetSplatMapValue(offsetX, offsetY, layer) + amount, 0.0f, 1.0f), renormalize); } bool MapSourceTerrainData::EnsureAdjacentSectionsLoaded(int32 sectionX, int32 sectionY) { DebugAssert(sectionX >= m_minSectionX && sectionX <= m_maxSectionX && sectionY >= m_minSectionY && sectionY <= m_maxSectionY); // self int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX, sectionY)) { return false; } // top-left if (sectionX > m_minSectionX && sectionY < m_maxSectionY) { arrayIndex = GetSectionArrayIndex(sectionX - 1, sectionY + 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX - 1, sectionY + 1)) { return false; } } // top-middle if (sectionY < m_maxSectionY) { arrayIndex = GetSectionArrayIndex(sectionX, sectionY + 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX, sectionY + 1)) { return false; } } // top-right if (sectionX < m_maxSectionX && sectionY < m_maxSectionY) { arrayIndex = GetSectionArrayIndex(sectionX + 1, sectionY + 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX + 1, sectionY + 1)) { return false; } } // middle-left if (sectionX > m_minSectionX) { arrayIndex = GetSectionArrayIndex(sectionX - 1, sectionY); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX - 1, sectionY)) { return false; } } // middle-right if (sectionX < m_maxSectionX) { arrayIndex = GetSectionArrayIndex(sectionX + 1, sectionY); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX + 1, sectionY)) { return false; } } // bottom-left if (sectionX > m_minSectionX && sectionY > m_minSectionY) { arrayIndex = GetSectionArrayIndex(sectionX - 1, sectionY - 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX - 1, sectionY - 1)) { return false; } } // bottom-middle if (sectionY > m_minSectionY) { arrayIndex = GetSectionArrayIndex(sectionX, sectionY - 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX, sectionY - 1)) { return false; } } // bottom-right if (sectionX < m_maxSectionX && sectionY > m_minSectionY) { arrayIndex = GetSectionArrayIndex(sectionX + 1, sectionY - 1); if (m_availableSectionMask[arrayIndex] && m_ppSections[arrayIndex] == nullptr && !LoadSection(sectionX + 1, sectionY - 1)) { return false; } } return true; } bool MapSourceTerrainData::RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint) { // best contacts float bestContactTimeSq = Y_FLT_INFINITE; float3 bestContactPoint; float3 bestContactNormal; #if 1 // get ray bounding box AABox rayBoundingBox(ray.GetAABox()); // get the min/max regions int2 searchSectionMin(CalculateSectionForPosition(rayBoundingBox.GetMinBounds())); int2 searchSectionMax(CalculateSectionForPosition(rayBoundingBox.GetMaxBounds())); // clamp to terrain bounds int32 startSectionX = Math::Clamp(searchSectionMin.x, m_minSectionX, m_maxSectionX); int32 startSectionY = Math::Clamp(searchSectionMin.y, m_minSectionY, m_maxSectionY); int32 endSectionX = Math::Clamp(searchSectionMax.x, m_minSectionX, m_maxSectionX); int32 endSectionY = Math::Clamp(searchSectionMax.y, m_minSectionY, m_maxSectionY); // iterate over these sections for (int32 sectionY = startSectionY; sectionY <= endSectionY; sectionY++) { for (int32 sectionX = startSectionX; sectionX <= endSectionX; sectionX++) { const TerrainSection *pSection = GetSection(sectionX, sectionY); if (pSection == NULL) continue; // use quadtree to break down search pSection->GetQuadTree()->EnumerateNodesIntersectingRay(ray, 0, [this, ray, pSection, &bestContactTimeSq, &bestContactPoint, &bestContactNormal](const TerrainQuadTreeNode *pNode) { // vars const float3 &sectionMinBounds = pSection->GetBoundingBox().GetMinBounds(); uint32 scale = m_parameters.Scale; // get range uint32 startX = pNode->GetStartQuadX(); uint32 startY = pNode->GetStartQuadY(); uint32 endX = startX + pNode->GetNodeSize(); uint32 endY = startY + pNode->GetNodeSize(); float3 v0, v1, v2, v3; float3 triangleContactPoint, triangleContactNormal; float triangleContactTimeSq; // iterate over points for (uint32 ly = startY; ly < endY; ly++) { for (uint32 lx = startX; lx < endX; lx++) { // first triangle v0.Set(sectionMinBounds.x + (float)((lx)* scale), sectionMinBounds.y + (float)((ly + 1) * scale), pSection->GetHeightMapValue(lx, ly + 1)); v1.Set(sectionMinBounds.x + (float)((lx)* scale), sectionMinBounds.y + (float)((ly)* scale), pSection->GetHeightMapValue(lx, ly)); v2.Set(sectionMinBounds.x + (float)((lx + 1) * scale), sectionMinBounds.y + (float)((ly + 1) * scale), pSection->GetHeightMapValue(lx + 1, ly + 1)); // test first triangle if (ray.TriangleIntersection(v0, v1, v2, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } // don't bother testing the other triangle, it's unlikely to hit both? continue; } // fill last vertex v3.Set(sectionMinBounds.x + (float)((lx + 1) * scale), sectionMinBounds.y + (float)((ly)* scale), pSection->GetHeightMapValue(lx + 1, ly)); // test second triangle: note reversed first vertices if (ray.TriangleIntersection(v2, v1, v3, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } } } } }); } } #elif 1 // get the bounding box of the ray AABox rayBoundingBox(ray.GetAABox()); // find the sections this overlaps EnumerateSectionsOverlappingBox(rayBoundingBox, [this, ray, &rayBoundingBox, &bestContactTimeSq, &bestContactPoint, &bestContactNormal](const TerrainSection *pSection) { uint32 unitsPerPoint = m_scale; float fUnitsPerPoint = (float)unitsPerPoint; int32 sectionSizeMinusOne = (int32)m_sectionSize - 1; // ensure the ray actually hits this box (since the box is very coarse) if (!ray.AABoxIntersection(pSection->GetBoundingBox())) return; // possible optimization here: use quadtree-style tests to eliminate triangles early // get region min bounds float3 sectionMinBounds(pSection->GetBoundingBox().GetMinBounds()); // find the overlapping points float3 regionMinPoints((rayBoundingBox.GetMinBounds() - sectionMinBounds) / fUnitsPerPoint); float3 regionMaxPoints((rayBoundingBox.GetMaxBounds() - sectionMinBounds) / fUnitsPerPoint); // quantize them int32 startXi = Math::Truncate(Math::Floor(regionMinPoints.x)); int32 startYi = Math::Truncate(Math::Floor(regionMinPoints.y)); int32 endXi = Math::Truncate(Math::Ceil(regionMaxPoints.x)); int32 endYi = Math::Truncate(Math::Ceil(regionMaxPoints.y)); // fix up range uint32 startX = (uint32)Min(Max(startXi, (int32)0), sectionSizeMinusOne); uint32 startY = (uint32)Min(Max(startYi, (int32)0), sectionSizeMinusOne); uint32 endX = (uint32)Min(Max(endXi, (int32)0), sectionSizeMinusOne); uint32 endY = (uint32)Min(Max(endYi, (int32)0), sectionSizeMinusOne); float3 v0, v1, v2, v3; float3 triangleContactPoint, triangleContactNormal; float triangleContactTimeSq; // iterate over points for (uint32 ly = startY; ly <= endY; ly++) { for (uint32 lx = startX; lx <= endX; lx++) { // first triangle v0.Set(sectionMinBounds.x + (float)((lx)* unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), pSection->GetIndexedHeight(lx, ly + 1)); v1.Set(sectionMinBounds.x + (float)((lx)* unitsPerPoint), sectionMinBounds.y + (float)((ly)* unitsPerPoint), pSection->GetIndexedHeight(lx, ly)); v2.Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), pSection->GetIndexedHeight(lx + 1, ly + 1)); // test first triangle if (ray.TriangleIntersection(v0, v1, v2, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } // don't bother testing the other triangle, it's unlikely to hit both? continue; } // fill last vertex v3.Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly)* unitsPerPoint), pSection->GetIndexedHeight(lx + 1, ly)); // test second triangle: note reversed first vertices if (ray.TriangleIntersection(v2, v1, v3, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } } } } }); #endif if (bestContactTimeSq == Y_FLT_INFINITE) return false; contactNormal = bestContactNormal; contactPoint = bestContactPoint; return true; } bool MapSourceTerrainData::RebuildQuadTree(uint32 newLODCount, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { if (newLODCount != m_parameters.LODCount) { Log_ErrorPrintf("Cannot currently rebuild quadtree with a different lod count"); return false; } return false; } bool MapSourceTerrainData::ImportHeightmap(const Image *pHeightmap, int32 startSectionX, int32 startSectionY, float minHeight, float maxHeight, HeightmapImportScaleType scaleType, uint32 scaleAmount, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { int32 sectionSize = (int32)m_parameters.SectionSize; float heightRange = (maxHeight - minHeight); Log_DevPrintf("import heightmap %u x %u", pHeightmap->GetWidth(), pHeightmap->GetHeight()); if (pHeightmap->GetPixelFormat() != PIXEL_FORMAT_R8_UNORM && pHeightmap->GetPixelFormat() != PIXEL_FORMAT_R16_UNORM && pHeightmap->GetPixelFormat() != PIXEL_FORMAT_R32_FLOAT) { return false; } // delete all visible sections, since there's going to be a lot of height changes, no point uploading them to the gpu one by one DeleteAllSections(); // copy the heightmap and scale it if needed. flip the image vertically, as that's the direction it'll be inserted Image heightmapCopy; heightmapCopy.Copy(*pHeightmap); //heightmapCopy.FlipVertical(); // work out how many sections we need int32 sectionsNeededX = Math::Truncate(Math::Ceil((float)heightmapCopy.GetWidth() / (float)sectionSize)); int32 sectionsNeededY = Math::Truncate(Math::Ceil((float)heightmapCopy.GetHeight() / (float)sectionSize)); // work out starting sections, we position the top-left corner of the heightmap in the top-left section int32 realStartSectionX = startSectionX; int32 realStartSectionY = startSectionY + (sectionsNeededY - 1); // from this, work out the starting global coordinates int32 globalCoordinateStartX, globalCoordinateStartY; CalculatePointForSectionAndOffset(&globalCoordinateStartX, &globalCoordinateStartY, realStartSectionX, realStartSectionY, 0, 0); // create them pProgressCallbacks->SetStatusText("Creating sections..."); pProgressCallbacks->SetProgressRange(sectionsNeededX * sectionsNeededY); pProgressCallbacks->SetProgressValue(0); for (int32 sy = 0; sy < sectionsNeededY; sy++) { for (int32 sx = 0; sx < sectionsNeededX; sx++) { int32 realSectionX = realStartSectionX + sx; int32 realSectionY = realStartSectionY - sy; if (IsSectionAvailable(realSectionX, realSectionY)) { // ensure it's loaded if (!LoadSection(realSectionX, realSectionY) && !IsSectionLoaded(realSectionX, realSectionY)) return false; } else { if (!CreateSection(realSectionX, realSectionY, (float)m_parameters.BaseHeight, GetDefaultLayer())) return false; } pProgressCallbacks->IncrementProgressValue(); } } // fill the values pProgressCallbacks->SetStatusText("Filling data..."); pProgressCallbacks->SetProgressRange(pHeightmap->GetWidth() * pHeightmap->GetHeight()); pProgressCallbacks->SetProgressValue(0); for (int32 pointY = 0; pointY < (int32)pHeightmap->GetHeight(); pointY++) { const byte *pHeightmapDataRow = pHeightmap->GetData() + ((uint32)pointY * pHeightmap->GetDataRowPitch()); for (int32 pointX = 0; pointX < (int32)pHeightmap->GetWidth(); pointX++) { float height = 0.0f; switch (heightmapCopy.GetPixelFormat()) { case PIXEL_FORMAT_R8_UNORM: { uint8 heightmapPixel = *(pHeightmapDataRow++); float valueFraction = (float)heightmapPixel / 255.0f; height = minHeight + (valueFraction * heightRange); } break; case PIXEL_FORMAT_R16_UNORM: { uint16 heightmapPixel = *(uint16 *)pHeightmapDataRow; pHeightmapDataRow += sizeof(uint16); float valueFraction = (float)heightmapPixel / 65535.0f; height = minHeight + (valueFraction * heightRange); } break; case PIXEL_FORMAT_R32_FLOAT: { float heightmapPixel = *(float *)pHeightmapDataRow; pHeightmapDataRow += sizeof(float); height = heightmapPixel; } break; } // int32 realPointX = (startSectionX * sectionSize) + pointX; // int32 realPointY = (startSectionY * sectionSize) + pointY; // m_pTerrainManager->SetPointHeight(realPointX, realPointY, height); // Log_DevPrintf("%i %i -> %f", realPointX, realPointY, height); // int32 writeSectionX = realStartSectionX + (pointX / sectionSize); // int32 writeSectionY = realStartSectionY + (pointY / sectionSize); // int32 writeOffsetX = pointX % sectionSize; // int32 writeOffsetY = pointY % sectionSize; // int32 globalX, globalY; // m_pTerrainManager->CalculatePointForSectionAndOffset(&globalX, &globalY, writeSectionX, writeSectionY, writeOffsetX, writeOffsetY); // m_pTerrainManager->SetPointHeight(globalX, globalY, height); // Log_DevPrintf("%i %i -> %i %i (%i %i :: %i %i) -> %f", pointX, pointY, globalX, globalY, writeSectionX, writeSectionY, writeOffsetX, writeOffsetY, height); // // int32 tsx, tsy; // uint32 tox, toy; // m_pTerrainManager->CalculateSectionAndOffsetForPoint(&tsx, &tsy, &tox, &toy, globalX, globalY); // DebugAssert(tsx == writeSectionX && tsy == writeSectionY); // DebugAssert(tox == writeOffsetX && toy == writeOffsetY); int32 globalPointX = globalCoordinateStartX + pointX; int32 globalPointY = globalCoordinateStartY - pointY; SetPointHeight(globalPointX, globalPointY, height); //Log_DevPrintf("%i %i -> %i %i -> %f", pointX, pointY, globalPointX, globalPointY, height); pProgressCallbacks->IncrementProgressValue(); } } // rebuild quadtrees on affected sections pProgressCallbacks->SetStatusText("Rebuilding quadtree..."); pProgressCallbacks->SetProgressRange(sectionsNeededX * sectionsNeededY); pProgressCallbacks->SetProgressValue(0); for (int32 sy = 0; sy < sectionsNeededY; sy++) { for (int32 sx = 0; sx < sectionsNeededX; sx++) { int32 realSectionX = startSectionX + sx; int32 realSectionY = startSectionY + sy; TerrainSection *pSection = GetSection(realSectionX, realSectionY); DebugAssert(pSection != nullptr); pSection->RebuildQuadTree(); pProgressCallbacks->IncrementProgressValue(); } } return true; } void MapSourceTerrainData::CopySectionPointWeights(const TerrainSection *pSourceSection, uint32 sourceOffsetX, uint32 sourceOffsetY, TerrainSection *pDestinationSection, uint32 destinationOffsetX, uint32 destinationOffsetY) { // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = pSourceSection->GetSplatMapValues(sourceOffsetX, sourceOffsetY, layerIndices, layerWeights, countof(layerIndices)); // clear from the other section pDestinationSection->ClearSplatMapValues(destinationOffsetX, destinationOffsetY); // and copy weights in bool layersModified = false; for (uint32 i = 0; i < nLayers; i++) { if (!pDestinationSection->HasSplatMapForLayer(layerIndices[i])) layersModified = true; pDestinationSection->SetSplatMapValue(destinationOffsetX, destinationOffsetY, layerIndices[i], layerWeights[i], false); } // invoke callbacks if (m_pEditCallbacks != nullptr) { if (layersModified) m_pEditCallbacks->OnSectionLayersModified(pDestinationSection); m_pEditCallbacks->OnSectionPointLayersModified(pDestinationSection, destinationOffsetX, destinationOffsetY); } } void MapSourceTerrainData::HandleEdgePointsHeightUpdate(TerrainSection *pSection, uint32 offsetX, uint32 offsetY) { int32 sectionX = pSection->GetSectionX(); int32 sectionY = pSection->GetSectionY(); float height = pSection->GetHeightMapValue(offsetX, offsetY); // update section to the west if (offsetX == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX - 1, sectionY); if (pAdjacentSection != nullptr && pAdjacentSection->GetHeightMapValue(m_parameters.SectionSize, offsetY) != height) { pAdjacentSection->SetHeightMapValue(m_parameters.SectionSize, offsetY, height); if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, m_parameters.SectionSize, offsetY); } } // update section to the south if (offsetY == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX, sectionY - 1); if (pAdjacentSection != nullptr && pAdjacentSection->GetHeightMapValue(offsetX, m_parameters.SectionSize) != height) { pAdjacentSection->SetHeightMapValue(offsetX, m_parameters.SectionSize, height); if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, offsetX, m_parameters.SectionSize); } } // update section to the southwest if (offsetX == 0 && offsetY == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX - 1, sectionY - 1); if (pAdjacentSection != nullptr && pAdjacentSection->GetHeightMapValue(m_parameters.SectionSize, m_parameters.SectionSize) != height) { pAdjacentSection->SetHeightMapValue(m_parameters.SectionSize, m_parameters.SectionSize, height); if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointHeightModified(pAdjacentSection, m_parameters.SectionSize, m_parameters.SectionSize); } } } void MapSourceTerrainData::HandleEdgePointsWeightUpdate(TerrainSection *pSection, uint32 offsetX, uint32 offsetY) { int32 sectionX = pSection->GetSectionX(); int32 sectionY = pSection->GetSectionY(); // update section to the west if (offsetX == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX - 1, sectionY); if (pAdjacentSection != nullptr) CopySectionPointWeights(pSection, offsetX, offsetY, pAdjacentSection, m_parameters.SectionSize, offsetY); } // update section to the south if (offsetY == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX, sectionY - 1); if (pAdjacentSection != nullptr) CopySectionPointWeights(pSection, offsetX, offsetY, pAdjacentSection, offsetX, m_parameters.SectionSize); } // update section to the southwest if (offsetX == 0 && offsetY == 0) { TerrainSection *pAdjacentSection = GetSection(sectionX - 1, sectionY - 1); if (pAdjacentSection != nullptr) CopySectionPointWeights(pSection, offsetX, offsetY, pAdjacentSection, m_parameters.SectionSize, m_parameters.SectionSize); } } bool MapSourceTerrainData::NormalizePointLayerWeights(TerrainSection *pSection, uint32 offsetX, uint32 offsetY) { // needs adjacent sections for zero offsets if ((offsetX == 0 || offsetY == 0) && !EnsureAdjacentSectionsLoaded(pSection->GetSectionX(), pSection->GetSectionY())) return false; // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = pSection->GetSplatMapValues(offsetX, offsetY, layerIndices, layerWeights, countof(layerIndices)); // get the total length of all weights float weightLength = 0.0f; for (uint32 i = 0; i < nLayers; i++) weightLength += layerWeights[i]; // no weights or zero length? if (nLayers == 0 || Math::NearEqual(weightLength, 0.0f, Y_FLT_EPSILON)) { // zero layers, ugh. set the default layer to full weight pSection->ClearSplatMapValues(offsetX, offsetY); pSection->SetSplatMapValue(offsetX, offsetY, GetDefaultLayer(), 1.0f, false); HandleEdgePointsWeightUpdate(pSection, offsetX, offsetY); return true; } // divide all weights by this length for (uint32 i = 0; i < nLayers; i++) { float newWeight = layerWeights[i] / weightLength; if (layerWeights[i] != newWeight) pSection->SetSplatMapValue(offsetX, offsetY, layerIndices[i], newWeight, false); } // invoke callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointLayersModified(pSection, offsetX, offsetY); // handle edge cases HandleEdgePointsWeightUpdate(pSection, offsetX, offsetY); return true; } bool MapSourceTerrainData::NormalizeSectionLayerWeights(TerrainSection *pSection) { // should have adjacent sections loaded if (!EnsureAdjacentSectionsLoaded(pSection->GetSectionX(), pSection->GetSectionY())) return false; // normalize each point for (uint32 y = 0; y < m_parameters.SectionSize; y++) { for (uint32 x = 0; x < m_parameters.SectionSize; x++) { NormalizePointLayerWeights(pSection, x, y); } } return true; } bool MapSourceTerrainData::RemovePointLayerWeights(TerrainSection *pSection, uint32 offsetX, uint32 offsetY, float threshold /*= 0.1f*/, bool normalizeAfterRemove /*= true*/) { // needs adjacent sections for zero offsets if ((offsetX == 0 || offsetY == 0) && !EnsureAdjacentSectionsLoaded(pSection->GetSectionX(), pSection->GetSectionY())) return false; // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = pSection->GetSplatMapValues(offsetX, offsetY, layerIndices, layerWeights, countof(layerIndices)); // new layer indices/weights uint8 newLayerIndices[TERRAIN_MAX_LAYERS]; float newLayerWeights[TERRAIN_MAX_LAYERS]; float newLayerWeightLength = 0.0f; uint32 nNewLayers = 0; // has layers? if (nLayers > 0) { // process each layer for (uint32 i = 0; i < nLayers; i++) { if (layerWeights[i] >= threshold) { newLayerIndices[nNewLayers] = layerIndices[i]; newLayerWeights[nNewLayers] = layerWeights[i]; newLayerWeightLength += layerWeights[i]; nNewLayers++; } } } // normalize? if (normalizeAfterRemove) { if (nNewLayers == 0 || Math::NearEqual(newLayerWeightLength, 0.0f, Y_FLT_EPSILON)) { // zero layers, ugh. set the default layer to full weight pSection->ClearSplatMapValues(offsetX, offsetY); pSection->SetSplatMapValue(offsetX, offsetY, GetDefaultLayer(), 1.0f, false); HandleEdgePointsWeightUpdate(pSection, offsetX, offsetY); return true; } // normalize each weight for (uint32 i = 0; i < nNewLayers; i++) newLayerWeights[i] = newLayerWeights[i] / newLayerWeightLength; } // set them pSection->ClearSplatMapValues(offsetX, offsetY); for (uint32 i = 0; i < nNewLayers; i++) pSection->SetSplatMapValue(offsetX, offsetY, newLayerIndices[i], newLayerWeights[i], false); // callbacks if (m_pEditCallbacks != nullptr) m_pEditCallbacks->OnSectionPointLayersModified(pSection, offsetX, offsetY); return true; } bool MapSourceTerrainData::RemoveSectionLayerWeights(TerrainSection *pSection, float threshold /* = 0.1f */, bool normalizeAfterRemove /* = true */) { // should have adjacent sections loaded if (!EnsureAdjacentSectionsLoaded(pSection->GetSectionX(), pSection->GetSectionY())) return false; // clear each point for (uint32 y = 0; y < m_parameters.SectionSize; y++) { for (uint32 x = 0; x < m_parameters.SectionSize; x++) { RemoveSectionLayerWeights(pSection, threshold, normalizeAfterRemove); } } return true; } ////////////////////////////////////////////////////////////////////////// bool MapSource::LoadTerrain(ProgressCallbacks *pProgressCallbacks) { FILESYSTEM_STAT_DATA statData; if (!m_pMapArchive->StatFile("terrain.xml", &statData)) return true; MapSourceTerrainData *pTerrainData = new MapSourceTerrainData(this); if (!pTerrainData->Load(pProgressCallbacks)) { delete pTerrainData; return false; } m_pTerrainData = pTerrainData; return true; } bool MapSource::SaveTerrain(ProgressCallbacks *pProgressCallbacks) const { if (m_pTerrainData == NULL) return true; return m_pTerrainData->Save(pProgressCallbacks); } MapSourceTerrainData *MapSource::CreateTerrainData(const TerrainLayerListGenerator *pLayerList, TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat, uint32 scale, uint32 sectionSize, uint32 renderLODCount, int32 minHeight, int32 maxHeight, int32 baseHeight, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pTerrainData == NULL); DebugAssert((m_regionSize % sectionSize * scale) == 0); // create parameters TerrainParameters parameters(heightStorageFormat, minHeight, maxHeight, baseHeight, scale, sectionSize, renderLODCount); if (!TerrainUtilities::IsValidParameters(&parameters)) return nullptr; // create data m_pTerrainData = new MapSourceTerrainData(this); if (!m_pTerrainData->Create(&parameters, pLayerList, pProgressCallbacks)) { delete m_pTerrainData; m_pTerrainData = nullptr; return nullptr; } return m_pTerrainData; } void MapSource::DeleteTerrainData(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pTerrainData != NULL); m_pTerrainData->Delete(); m_pTerrainData = NULL; } /* // set all heights on the top row from the top section for (uint32 x = 0; x < sectionSize; x++) { SetIndexedHeight(x, sectionSize, (pTopSection != NULL) ? pTopSection->GetIndexedHeight(x, 0) : baseHeight); if (pTopSection != NULL) { const uint8 *pRawLayerValues = pTopSection->m_pLayerWeightValues; for (uint32 i = 0; i < pTopSection->m_nUsedLayers; i++) { uint8 value = pRawLayerValues[(i * m_layerWeightValuesStride) + x]; if (value != 0) SetIndexedBaseLayerWeight(x, sectionSize, pTopSection->m_usedLayers[i], (float)value / 255.0f); } } } // set all heights on the right column from the top section for (uint32 y = 0; y < sectionSize; y++) { SetIndexedHeight(sectionSize, y, (pRightSection != NULL) ? pRightSection->GetIndexedHeight(0, y) : baseHeight); if (pRightSection != NULL) { const uint8 *pRawLayerValues = pRightSection->m_pLayerWeightValues; for (uint32 i = 0; i < pRightSection->m_nUsedLayers; i++) { uint8 value = pRawLayerValues[(i * m_layerWeightValuesStride) + (y * m_pointCount) + sectionSize]; if (value != 0) SetIndexedBaseLayerWeight(sectionSize, y, pRightSection->m_usedLayers[i], (float)value / 255.0f); } } } // set corner texel from the origin of the top-right section SetIndexedHeight(sectionSize, sectionSize, (pTopRightSection != NULL) ? pTopRightSection->GetIndexedHeight(0, 0) : baseHeight); if (pTopRightSection != NULL) { const uint8 *pRawLayerValues = pTopRightSection->m_pLayerWeightValues; for (uint32 i = 0; i < pTopRightSection->m_nUsedLayers; i++) { uint8 value = pRawLayerValues[(i * m_layerWeightValuesStride) + (sectionSize * m_pointCount) + sectionSize]; if (value != 0) SetIndexedBaseLayerWeight(sectionSize, sectionSize, pTopRightSection->m_usedLayers[i], (float)value / 255.0f); } } */ <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2ConstantLibrary.h #pragma once #include "OpenGLES2Renderer/OpenGLES2Common.h" class OpenGLES2ConstantLibrary { DeclareNonCopyable(OpenGLES2ConstantLibrary); public: typedef uint32 ConstantID; static const ConstantID ConstantIndexInvalid; static const uint32 BufferOffsetInvalid; struct ConstantInfo { uint32 BufferIndex; uint32 FieldIndex; uint32 ArraySize; SHADER_PARAMETER_TYPE Type; uint32 LocalBufferOffset; uint32 GlobalBufferOffset; }; public: OpenGLES2ConstantLibrary(RENDERER_FEATURE_LEVEL featureLevel); ~OpenGLES2ConstantLibrary(); // Size of global constant storage. const uint32 GetConstantStorageBufferSize() const { return m_allConstantsSize; } // Find the constant id for a given fully-qualified name (InstanceName.VariableName) ConstantID LookupConstantID(const char *fullyQualifiedName) const; // Finds the constant id for a buffer and field index. ConstantID LookupConstantID(uint32 bufferIndex, uint32 fieldIndex) const; // Finds the constant located at buffer and offset. bool FindConstantsAtOffset(uint32 bufferIndex, uint32 startOffset, uint32 endOffset, ConstantID *pFirstConstant, ConstantID *pLastConstant) const; // Get the starting offset for a constant buffer in the global buffer. uint32 GetBufferStartOffset(uint32 bufferIndex) const; // Get constant information. const ConstantInfo *GetConstantInfo(ConstantID constantID) const; // Update the currently-bound program's copy of a constant void UpdateProgramConstant(const byte *pGlobalBuffer, ConstantID constantID, GLuint programLocation) const; private: // generate constant data, starting offsets, and total buffer size void GenerateConstantData(RENDERER_FEATURE_LEVEL featureLevel); // allocate a block of memory of this size per-context uint32 m_allConstantsSize; // constant data MemArray<ConstantInfo> m_constantData; // starting indices of each constant buffer PODArray<ConstantID> m_constantBufferStartingIndices; // starting offset in the global buffer of each constant buffer PODArray<uint32> m_constantBufferStartingOffsets; // hash table mapping fully-qualified names to constant ids CIStringHashTable<ConstantID> m_nameToIDMap; }; <file_sep>/Editor/Source/Editor/MapEditor/EditorCreateTerrainDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorCreateTerrainDialog.h" #include "Editor/EditorHelpers.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" EditorCreateTerrainDialog::EditorCreateTerrainDialog(QWidget *pParent, Qt::WindowFlags windowFlags /*= 0*/) : QDialog(pParent, windowFlags), m_ui(new Ui_EditorCreateTerrainDialog()), m_pLayerList(NULL), m_sectionSize(0), m_unitsPerPoint(0), m_minHeight(0), m_maxHeight(0), m_baseHeight(0), m_createCenterSection(false) { m_ui->setupUi(this); // set state up m_ui->layerListSelection->setResourceTypeInfo(OBJECT_TYPEINFO(TerrainLayerList)); m_ui->sectionSize->setRange(32, 4096); m_ui->sectionSize->setSingleStep(16); m_ui->unitsPerPoint->setRange(1, 64); m_ui->patchSize->setRange(4, 1024); m_ui->heightFormat->addItem("8-Bit Integer"); m_ui->heightFormat->addItem("16-Bit Integer"); m_ui->heightFormat->addItem("32-Bit Float"); // set some defaults //m_ui->layerListSelection->setValue(ConvertStringToQString(g_pEngine->GetDefaultTerrainLayerListName())); m_ui->sectionSize->setValue(1024); m_ui->unitsPerPoint->setValue(4); m_ui->patchSize->setValue(64); m_ui->heightFormat->setCurrentIndex(2); m_ui->minimumHeight->setValue(-16384); m_ui->maximumHeight->setValue(16384); m_ui->textureRepeatInterval->setValue(16); m_ui->createCenterSectionCheckBox->setChecked(true); OnHeightFormatChanged(2); // connect events connect(m_ui->layerListSelection, SIGNAL(valueChanged(const QString &)), this, SLOT(OnLayerListChanged(const QString &))); connect(m_ui->heightFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(OnHeightFormatChanged(int))); connect(m_ui->createButton, SIGNAL(clicked()), this, SLOT(OnCreateButtonTriggered())); connect(m_ui->cancelButton, SIGNAL(clicked()), this, SLOT(OnCancelButtonTriggered())); } EditorCreateTerrainDialog::~EditorCreateTerrainDialog() { if (m_pLayerList != NULL) m_pLayerList->Release(); } bool EditorCreateTerrainDialog::Validate() { if (m_pLayerList != NULL) m_pLayerList->Release(); // todo: update tick buttons along the way m_pLayerList = g_pResourceManager->GetTerrainLayerList(ConvertQStringToString(m_ui->layerListSelection->getValue())); if (m_pLayerList == NULL) { m_ui->createButton->setEnabled(false); return false; } m_sectionSize = (uint32)m_ui->sectionSize->value(); m_unitsPerPoint = (uint32)m_ui->unitsPerPoint->value(); m_quadTreeNodeSize = (uint32)m_ui->patchSize->value(); m_textureRepeatInterval = (uint32)m_ui->textureRepeatInterval->value(); if (/*!TerrainManager::IsValidSectionSize(m_sectionSize, m_quadTreeNodeSize) ||*/ (m_quadTreeNodeSize % m_textureRepeatInterval) != 0) { m_ui->createButton->setEnabled(false); return false; } m_storageFormat = (TERRAIN_HEIGHT_STORAGE_FORMAT)m_ui->heightFormat->currentIndex(); m_minHeight = (int32)m_ui->minimumHeight->value(); m_maxHeight = (int32)m_ui->maximumHeight->value(); m_baseHeight = (int32)m_ui->baseHeight->value(); m_createCenterSection = m_ui->createCenterSectionCheckBox->isChecked(); m_ui->createButton->setEnabled(true); return true; } void EditorCreateTerrainDialog::OnLayerListChanged(const QString &value) { Validate(); } void EditorCreateTerrainDialog::OnHeightFormatChanged(int currentIndex) { static const int32 heightRanges[3][2] = { { -0x7E, 0x7F }, { -0x7FFE, 0x7FFF }, { -0x7FFFF, 0x7FFFF }, }; DebugAssert(currentIndex < countof(heightRanges)); int32 minHeight = heightRanges[currentIndex][0]; int32 maxHeight = heightRanges[currentIndex][1]; m_ui->minimumHeight->setRange(minHeight, maxHeight); m_ui->maximumHeight->setRange(minHeight, maxHeight); m_ui->baseHeight->setRange(minHeight, maxHeight); if (currentIndex == 2) { // float m_ui->minimumHeight->setValue(minHeight); m_ui->minimumHeight->setEnabled(false); m_ui->maximumHeight->setValue(maxHeight); m_ui->maximumHeight->setEnabled(false); } else { // int m_ui->minimumHeight->setEnabled(true); m_ui->maximumHeight->setEnabled(true); } Validate(); } void EditorCreateTerrainDialog::OnCreateButtonTriggered() { if (!Validate()) return; done(1); } void EditorCreateTerrainDialog::OnCancelButtonTriggered() { done(0); } <file_sep>/Engine/Source/Engine/ParticleSystemVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" #include "Engine/ParticleSystemCommon.h" class Camera; class ParticleSystemSpriteVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(ParticleSystemSpriteVertexFactory, VertexFactory); enum Flags { // rendering with per-frame data in dynamic buffer Flag_RenderBasic = (1 << 0), // rendering with position, attributes in vertex buffer and system value to determine edges Flag_RenderInstancedQuads = (1 << 1), // enable world transform Flag_UseWorldTransform = (1 << 1), }; public: static uint32 GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static uint32 GetVerticesPerSprite(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static DRAW_TOPOLOGY GetDrawTopology(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static bool FillVertexBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Camera *pCamera, const ParticleData *pParticles, uint32 nParticles, void *pBuffer, uint32 bufferSize); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); }; <file_sep>/Engine/Source/MathLib/Interpolator.cpp #include "MathLib/Interpolator.h" // adapted from jQueryUI source and http://www.robertpenner.com/easing/ float EasingFunction::GetCoefficient(Type type, float p) { switch (type) { case Linear: return p; case Quadratic: return Math::Pow(p, 2.0f); case Cubic: return Math::Pow(p, 3.0f); case Quart: return Math::Pow(p, 4.0f); case Quint: return Math::Pow(p, 5.0f); case Expo: return Math::Pow(p, 6.0f); case EaseInSine: return 1.0f - Math::Cos(p * Y_HALF_PI); case EaseInCirc: return 1.0f - Math::Sqrt(1.0f - (p * p)); case EaseInElastic: return (p == 0.0f || p == 1.0f) ? p : (-Math::Pow(2.0f, 8.0f * (p - 1.0f)) * Math::Sin(((p - 1.0f) * Math::DegreesToRadians(80.0f) - 7.5f) * (Y_PI / 15.0f))); case EaseInBack: return (p * p * (3.0f * p - 2.0f)); case EaseInBounce: { float pow2; float bounce = 4.0f; while (p < ((pow2 = Math::Pow(2.0f, -bounce)) - 1.0f) / 11.0f); return 1.0f / Math::Pow(4.0f, 3.0f - bounce) - 7.5625f * Math::Pow((pow2 * 3.0f - 2.0f) / 22.0f - p, 2.0f); } case EaseOutSine: case EaseOutCirc: case EaseOutElastic: case EaseOutBack: case EaseOutBounce: return 1.0f - GetCoefficient(static_cast<Type>((int)type - 1), p); case EaseInOutSine: case EaseInOutCirc: case EaseInOutElastic: case EaseInOutBack: case EaseInOutBounce: return (p < 0.5f) ? (GetCoefficient(static_cast<Type>((int)type - 2), p * 2.0f) / 2.0f) : (1.0f - GetCoefficient(static_cast<Type>((int)type - 2), p * -2.0f + 2.0f) / 2.0f); } UnreachableCode(); return p; } <file_sep>/Engine/Source/Renderer/Renderer.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" #include "YBaseLib/TaskQueue.h" // Include helper classes #include "Renderer/VertexFactories/PlainVertexFactory.h" // <--- TODO REMOVE ME #include "Renderer/MiniGUIContext.h" #include "Renderer/ShaderMap.h" // Forward declare classes class Camera; class World; class RenderWorld; class Font; class ShaderProgram; // Declare the render system window handle type #if defined(Y_PLATFORM_WINDOWS) typedef HWND RenderSystemWindowHandle; #else typedef void *RenderSystemWindowHandle; #endif // Required for output window struct SDL_Window; // Capability mask struct RendererCapabilities { uint32 MaxTextureAnisotropy; uint32 MaximumVertexBuffers; uint32 MaximumConstantBuffers; uint32 MaximumTextureUnits; uint32 MaximumSamplers; uint32 MaximumRenderTargets; struct { bool SupportsMultithreadedResourceCreation : 1; bool SupportsCommandLists : 1; bool SupportsDrawBaseVertex : 1; bool SupportsDepthTextures : 1; bool SupportsTextureArrays : 1; bool SupportsCubeMapTextureArrays : 1; bool SupportsGeometryShaders : 1; bool SupportsSinglePassCubeMaps : 1; bool SupportsInstancing : 1; uint32: 1; }; }; // Base class of all gpu resources class GPUResource : public ReferenceCounted { DeclareNonCopyable(GPUResource); public: GPUResource() {} virtual ~GPUResource() {} // Common methods for all resources virtual GPU_RESOURCE_TYPE GetResourceType() const = 0; virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const = 0; virtual void SetDebugName(const char *name) = 0; }; class GPURasterizerState : public GPUResource { public: GPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPURasterizerState() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_RASTERIZER_STATE; } const RENDERER_RASTERIZER_STATE_DESC *GetDesc() const { return &m_desc; } protected: RENDERER_RASTERIZER_STATE_DESC m_desc; private: }; class GPUDepthStencilState : public GPUResource { public: GPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUDepthStencilState() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_DEPTH_STENCIL_STATE; } const RENDERER_DEPTHSTENCIL_STATE_DESC *GetDesc() const { return &m_desc; } protected: RENDERER_DEPTHSTENCIL_STATE_DESC m_desc; private: }; class GPUBlendState : public GPUResource { public: GPUBlendState(const RENDERER_BLEND_STATE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUBlendState() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_BLEND_STATE; } const RENDERER_BLEND_STATE_DESC *GetDesc() const { return &m_desc; } protected: RENDERER_BLEND_STATE_DESC m_desc; private: }; class GPUSamplerState : public GPUResource { public: GPUSamplerState(const GPU_SAMPLER_STATE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUSamplerState() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_SAMPLER_STATE; } const GPU_SAMPLER_STATE_DESC *GetDesc() const { return &m_desc; } protected: GPU_SAMPLER_STATE_DESC m_desc; }; class GPUBuffer : public GPUResource { public: GPUBuffer(const GPU_BUFFER_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUBuffer() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_BUFFER; } const GPU_BUFFER_DESC *GetDesc() const { return &m_desc; } protected: GPU_BUFFER_DESC m_desc; private: }; class GPUTexture : public GPUResource { public: virtual ~GPUTexture() {} virtual TEXTURE_TYPE GetTextureType() const = 0; }; class GPUTexture1D : public GPUTexture { public: GPUTexture1D(const GPU_TEXTURE1D_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTexture1D() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_1D; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURE1D; } const GPU_TEXTURE1D_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURE1D_DESC m_desc; }; class GPUTexture1DArray : public GPUTexture { public: GPUTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTexture1DArray() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_1D_ARRAY; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURE1DARRAY; } const GPU_TEXTURE1DARRAY_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURE1DARRAY_DESC m_desc; }; class GPUTexture2D : public GPUTexture { public: GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTexture2D() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_2D; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURE2D; } const GPU_TEXTURE2D_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURE2D_DESC m_desc; }; class GPUTexture2DArray : public GPUTexture { public: GPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTexture2DArray() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_2D_ARRAY; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURE2DARRAY; } const GPU_TEXTURE2DARRAY_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURE2DARRAY_DESC m_desc; }; class GPUTexture3D : public GPUTexture { public: GPUTexture3D(const GPU_TEXTURE3D_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTexture3D() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_3D; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURE3D; } const GPU_TEXTURE3D_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURE3D_DESC m_desc; }; class GPUTextureCube : public GPUTexture { public: GPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTextureCube() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_CUBE; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURECUBE; } const GPU_TEXTURECUBE_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURECUBE_DESC m_desc; }; class GPUTextureCubeArray : public GPUTexture { public: GPUTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUTextureCubeArray() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_CUBE_ARRAY; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_TEXTURECUBEARRAY; } const GPU_TEXTURECUBEARRAY_DESC *GetDesc() const { return &m_desc; } protected: GPU_TEXTURECUBEARRAY_DESC m_desc; }; class GPUDepthTexture : public GPUTexture { public: GPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); } virtual ~GPUDepthTexture() {} virtual TEXTURE_TYPE GetTextureType() const override { return TEXTURE_TYPE_DEPTH; } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_DEPTH_TEXTURE; } const GPU_DEPTH_TEXTURE_DESC *GetDesc() const { return &m_desc; } protected: GPU_DEPTH_TEXTURE_DESC m_desc; }; class GPURenderTargetView : public GPUResource { public: GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); m_pTexture = pTexture; m_pTexture->AddRef(); } virtual ~GPURenderTargetView() { m_pTexture->Release(); } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_RENDER_TARGET_VIEW; } const GPU_RENDER_TARGET_VIEW_DESC *GetDesc() const { return &m_desc; } GPUTexture *GetTargetTexture() const { return m_pTexture; } protected: GPUTexture *m_pTexture; GPU_RENDER_TARGET_VIEW_DESC m_desc; }; class GPUDepthStencilBufferView : public GPUResource { public: GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); m_pTexture = pTexture; m_pTexture->AddRef(); } virtual ~GPUDepthStencilBufferView() { m_pTexture->Release(); } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_DEPTH_BUFFER_VIEW; } const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *GetDesc() const { return &m_desc; } GPUTexture *GetTargetTexture() const { return m_pTexture; } protected: GPUTexture *m_pTexture; GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC m_desc; }; class GPUComputeView : public GPUResource { public: GPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { Y_memcpy(&m_desc, pDesc, sizeof(m_desc)); m_pResource->AddRef(); } virtual ~GPUComputeView() { m_pResource->Release(); } virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_COMPUTE_VIEW; } const GPU_COMPUTE_VIEW_DESC *GetDesc() const { return &m_desc; } GPUResource *GetTargetResource() const { return m_pResource; } protected: GPUResource *m_pResource; GPU_COMPUTE_VIEW_DESC m_desc; }; class GPUQuery : public GPUResource { public: virtual ~GPUQuery() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_QUERY; } virtual GPU_QUERY_TYPE GetQueryType() const = 0; }; class GPUShaderProgram : public GPUResource { public: GPUShaderProgram() {} virtual ~GPUShaderProgram() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_SHADER_PROGRAM; } // --- parameters --- virtual uint32 GetParameterCount() const = 0; virtual void GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) = 0; }; class GPUShaderPipeline : public GPUShaderProgram { public: GPUShaderPipeline() {} virtual ~GPUShaderPipeline() {} virtual GPU_RESOURCE_TYPE GetResourceType() const override { return GPU_RESOURCE_TYPE_SHADER_PIPELINE; } // TODO: Accessors for states.... }; class GPUOutputBuffer : public ReferenceCounted { DeclareNonCopyable(GPUOutputBuffer); public: GPUOutputBuffer(RENDERER_VSYNC_TYPE vsyncType) : m_vsyncType(vsyncType) {} virtual ~GPUOutputBuffer() {} // Get the dimensions of this swap chain. virtual uint32 GetWidth() const = 0; virtual uint32 GetHeight() const = 0; // Change the vsync type associated with this swap chain. RENDERER_VSYNC_TYPE GetVSyncType() const { return m_vsyncType; } virtual void SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) = 0; protected: RENDERER_VSYNC_TYPE m_vsyncType; }; class RendererOutputWindow : public ReferenceCounted { DeclareNonCopyable(RendererOutputWindow); public: RendererOutputWindow(SDL_Window *pSDLWindow, GPUOutputBuffer *pBuffer, RENDERER_FULLSCREEN_STATE fullscreenState); virtual ~RendererOutputWindow(); // window accessors SDL_Window *GetSDLWindow() const { return m_pSDLWindow; } GPUOutputBuffer *GetOutputBuffer() const { return m_pOutputBuffer; } RENDERER_FULLSCREEN_STATE GetFullscreenState() const { return m_fullscreenState; } void SetFullscreenState(RENDERER_FULLSCREEN_STATE state) { m_fullscreenState = state; } void SetDimensions(uint32 width, uint32 height) { m_width = width; m_height = height; } void SetOutputBuffer(GPUOutputBuffer *pBuffer) { m_pOutputBuffer = pBuffer; } int32 GetPositionX() const { return m_positionX; } int32 GetPositionY() const { return m_positionY; } uint32 GetWidth() const { return m_width; } uint32 GetHeight() const { return m_height; } bool HasFocus() const { return m_hasFocus; } bool IsVisible() const { return m_visible; } const String &GetTitle() const { return m_title; } bool IsMouseGrabbed() const { return m_mouseGrabbed; } bool IsMouseRelativeMovementEnabled() const { return m_mouseRelativeMovement; } // Change the caption of the window void SetWindowTitle(const char *title); // Show/hide the window void SetWindowVisibility(bool visible); // Change the position of the window void SetWindowPosition(int32 x, int32 y); // Changes the window size void SetWindowSize(uint32 width, uint32 height); // Capture the mouse, if it leaves the window it will still receive movement events void SetMouseGrab(bool enabled); // Enable relative mouse movement, when enabled the mouse cursor will be locked to the window and the cursor will be hidden void SetMouseRelativeMovement(bool enabled); protected: SDL_Window *m_pSDLWindow; GPUOutputBuffer *m_pOutputBuffer; RENDERER_FULLSCREEN_STATE m_fullscreenState; int32 m_positionX; int32 m_positionY; uint32 m_width; uint32 m_height; bool m_hasFocus; bool m_visible; String m_title; bool m_mouseGrabbed; bool m_mouseRelativeMovement; }; // constants interface class GPUContextConstants { DeclareNonCopyable(GPUContextConstants); public: GPUContextConstants(GPUDevice *pDevice, GPUCommandList *pCommandList); virtual ~GPUContextConstants(); // Object Constants const float4x4 &GetLocalToWorldMatrix() const { return m_localToWorldMatrix; } void SetLocalToWorldMatrix(const float4x4 &rMatrix, bool Commit = true); void SetMaterialTintColor(const float4 &tintColor, bool Commit = true); // Camera Constants const float4x4 &GetCameraViewMatrix() const { return m_cameraViewMatrix; } const float4x4 &GetCameraProjectionMatrix() const { return m_cameraProjectionMatrix; } const float3 &GetCameraEyePosition() const { return m_cameraEyePosition; } void SetCameraViewMatrix(const float4x4 &rMatrix, bool Commit = true); void SetCameraProjectionMatrix(const float4x4 &rMatrix, bool Commit = true); void SetCameraEyePosition(const float3 &Position, bool Commit = true); void SetFromCamera(const Camera &camera, bool commit = true); // Viewport Constants const float2 &GetViewportOffset() const { return m_viewportOffset; } const float2 &GetViewportSize() const { return m_viewportSize; } void SetViewportOffset(float offsetX, float offsetY, bool commit = true); void SetViewportSize(float width, float height, bool commit = true); // World Constants const float GetWorldTime() const { return m_worldTime; } void SetWorldTime(float worldTime, bool commit = true); // Reset void Reset(); // Commit void CommitChanges(); // Commit the shared program globals constant buffer void CommitGlobalConstantBufferChanges(); private: GPUDevice *m_pDevice; GPUCommandList *m_pCommandList; // Object constants float4x4 m_localToWorldMatrix; float4 m_materialTintColor; // View constants float4x4 m_cameraViewMatrix; float4x4 m_cameraProjectionMatrix; float3 m_cameraEyePosition; // Viewport constants float2 m_viewportOffset; float2 m_viewportSize; // World constants float m_worldTime; // dirty flags bool m_recalculateCombinedMatrices; bool m_recalculateViewportFractions; }; class GPUDevice : public ReferenceCounted { DeclareNonCopyable(GPUDevice); public: GPUDevice() {} virtual ~GPUDevice() {} // Device queries. virtual RENDERER_PLATFORM GetPlatform() const = 0; virtual RENDERER_FEATURE_LEVEL GetFeatureLevel() const = 0; virtual TEXTURE_PLATFORM GetTexturePlatform() const = 0; virtual void GetCapabilities(RendererCapabilities *pCapabilities) const = 0; virtual bool CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat = nullptr) const = 0; virtual void CorrectProjectionMatrix(float4x4 &projectionMatrix) const = 0; virtual float GetTexelOffset() const = 0; // Creates a swap chain on an existing window. virtual GPUOutputBuffer *CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) = 0; virtual GPUOutputBuffer *CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) = 0; // Resource creation virtual GPUDepthStencilState *CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) = 0; virtual GPURasterizerState *CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) = 0; virtual GPUBlendState *CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) = 0; virtual GPUQuery *CreateQuery(GPU_QUERY_TYPE type) = 0; virtual GPUBuffer *CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData = NULL) = 0; virtual GPUTexture1D *CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUTexture1DArray *CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUTexture2D *CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUTexture2DArray *CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUTexture3D *CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL, const uint32 *pInitialDataSlicePitch = NULL) = 0; virtual GPUTextureCube *CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUTextureCubeArray *CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL) = 0; virtual GPUDepthTexture *CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) = 0; virtual GPUSamplerState *CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) = 0; virtual GPURenderTargetView *CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) = 0; virtual GPUDepthStencilBufferView *CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) = 0; virtual GPUComputeView *CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) = 0; virtual GPUShaderProgram *CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) = 0; virtual GPUShaderProgram *CreateComputeProgram(ByteStream *pByteCodeStream) = 0; // CreateGraphicsPipeline // CreateComputePipeline // When creating resources off-thread, there is an implicit flush/wait after each resource creation. This forces a group to be batched together. virtual void BeginResourceBatchUpload() = 0; virtual void EndResourceBatchUpload() = 0; }; class GPUCommandList : public ReferenceCounted { DeclareNonCopyable(GPUCommandList); public: GPUCommandList() {} virtual ~GPUCommandList() {} // State clearing virtual void ClearState(bool clearShaders = true, bool clearBuffers = true, bool clearStates = true, bool clearRenderTargets = true) = 0; // Retrieve RendererVariables interface. virtual GPUContextConstants *GetConstants() = 0; // State Management virtual GPURasterizerState *GetRasterizerState() = 0; virtual void SetRasterizerState(GPURasterizerState *pRasterizerState) = 0; virtual GPUDepthStencilState *GetDepthStencilState() = 0; virtual uint8 GetDepthStencilStateStencilRef() = 0; virtual void SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) = 0; virtual GPUBlendState *GetBlendState() = 0; virtual const float4 &GetBlendStateBlendFactor() = 0; virtual void SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor = float4::One) = 0; // Viewport Management virtual const RENDERER_VIEWPORT *GetViewport() = 0; virtual void SetViewport(const RENDERER_VIEWPORT *pNewViewport) = 0; virtual void SetFullViewport(GPUTexture *pForRenderTarget = nullptr) = 0; // Scissor Rect Management virtual const RENDERER_SCISSOR_RECT *GetScissorRect() = 0; virtual void SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) = 0; // Texture copying virtual bool CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) = 0; virtual bool CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) = 0; // Blit (copy) a texture to the currently bound framebuffer. If this texture is a different size, it'll be resized. This may destroy the shader and target state, so use carefully. virtual void BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter = RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST) = 0; // Mipmap generation, texture must be created with GPU_TEXTURE_FLAG_GENERATE_MIPS virtual void GenerateMips(GPUTexture *pTexture) = 0; // Query accessing virtual bool BeginQuery(GPUQuery *pQuery) = 0; virtual bool EndQuery(GPUQuery *pQuery) = 0; // Predicated drawing virtual void SetPredication(GPUQuery *pQuery) = 0; // RT Clearing virtual void ClearTargets(bool clearColor = true, bool clearDepth = true, bool clearStencil = true, const float4 &clearColorValue = float4::Zero, float clearDepthValue = 1.0f, uint8 clearStencilValue = 0) = 0; virtual void DiscardTargets(bool discardColor = true, bool discardDepth = true, bool discardStencil = true) = 0; // Swap chain changing virtual GPUOutputBuffer *GetOutputBuffer() = 0; virtual void SetOutputBuffer(GPUOutputBuffer *pOutputBuffer) = 0; // Render target changing virtual uint32 GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) = 0; virtual void SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) = 0; // Drawing Setup virtual DRAW_TOPOLOGY GetDrawTopology() = 0; virtual void SetDrawTopology(DRAW_TOPOLOGY Topology) = 0; virtual uint32 GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) = 0; virtual void SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) = 0; virtual void SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) = 0; virtual void GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) = 0; virtual void SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) = 0; // Shader Setup virtual void SetShaderProgram(GPUShaderProgram *pShaderProgram) = 0; virtual void SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) = 0; virtual void SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) = 0; virtual void SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) = 0; virtual void SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) = 0; virtual void SetShaderParameterResource(uint32 index, GPUResource *pResource) = 0; virtual void SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) = 0; // Constant Buffers virtual void WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit = false) = 0; virtual void WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit = false) = 0; virtual void CommitConstantBuffer(uint32 bufferIndex) = 0; // Draw calls virtual void Draw(uint32 firstVertex, uint32 nVertices) = 0; virtual void DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) = 0; virtual void DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) = 0; virtual void DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) = 0; // Draw calls with user-space buffer virtual void DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) = 0; // Compute shaders virtual void Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) = 0; }; class GPUContext : public GPUCommandList { DeclareNonCopyable(GPUContext); public: GPUContext() {} virtual ~GPUContext() {} // Start of frame virtual void BeginFrame() = 0; // Ensure all queued commands are sent to the GPU. virtual void Flush() = 0; // Ensure all commands have been completed by the GPU. virtual void Finish() = 0; // Swap chain manipulation virtual bool GetExclusiveFullScreen() = 0; virtual bool SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) = 0; virtual bool ResizeOutputBuffer(uint32 width = 0, uint32 height = 0) = 0; virtual void PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) = 0; // Command list execution virtual GPUCommandList *CreateCommandList() = 0; virtual bool OpenCommandList(GPUCommandList *pCommandList) = 0; virtual bool CloseCommandList(GPUCommandList *pCommandList) = 0; virtual void ExecuteCommandList(GPUCommandList *pCommandList) = 0; // Buffer mapping/reading/writing virtual bool ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) = 0; virtual bool WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) = 0; virtual bool MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) = 0; virtual void Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) = 0; // Texture reading/writing virtual bool ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) = 0; virtual bool ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) = 0; virtual bool ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) = 0; virtual bool ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) = 0; virtual bool WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) = 0; virtual bool WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) = 0; virtual bool WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; virtual bool WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) = 0; // Query readback virtual GPU_QUERY_GETDATA_RESULT GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) = 0; }; struct RendererInitializationParameters { RendererInitializationParameters() : Platform(RENDERER_PLATFORM_D3D11), EnableThreadedRendering(true) , BackBufferFormat(PIXEL_FORMAT_R8G8B8A8_UNORM), DepthStencilBufferFormat(PIXEL_FORMAT_D24_UNORM_S8_UINT) , HideImplicitSwapChain(false), ImplicitSwapChainCaption("Renderer"), ImplicitSwapChainWidth(800), ImplicitSwapChainHeight(600) , ImplicitSwapChainFullScreen(RENDERER_FULLSCREEN_STATE_WINDOWED), ImplicitSwapChainVSyncType(RENDERER_VSYNC_TYPE_NONE) , GPUFrameLatency(3) { } // Platform to create. RENDERER_PLATFORM Platform; // Override default behaviour of creating a render thread should the cvar be set. bool EnableThreadedRendering; // Pixel format of all on-screen windows. PIXEL_FORMAT BackBufferFormat; PIXEL_FORMAT DepthStencilBufferFormat; // OpenGL at least, requires at least one swap chain be created with the device (implicit swap chain), even if it is not used. // If this is set, the swap chain will be created at a minimum size (to save memory) and the render window will be hidden. // On other APIs that do not require an implicit swap chain, none will be created. bool HideImplicitSwapChain; // If created, this specifies the caption of the implicit swap chain window. const char *ImplicitSwapChainCaption; // If created, this specifies the dimensions of the implicit swap chain window. uint32 ImplicitSwapChainWidth; uint32 ImplicitSwapChainHeight; // If created, whether the implicit swap chain will be created full-screen. RENDERER_FULLSCREEN_STATE ImplicitSwapChainFullScreen; // Implicit swap chain vsync behaviour RENDERER_VSYNC_TYPE ImplicitSwapChainVSyncType; // Frame latency uint32 GPUFrameLatency; }; // Renderer stats class RendererCounters { public: RendererCounters(); ~RendererCounters(); // Counters uint32 GetFrameNumber() const { return m_frameNumber; } uint32 GetDrawCallCounter() const { return m_drawCallCounter; } uint32 GetShaderChangeCounter() const { return m_shaderChangeCounter; } uint32 GetPipelineChangeCounter() const { return m_pipelineChangeCounter; } uint32 GetFramesDroppedCounter() const { return m_framesDroppedCounter; } // Counter updating void IncrementDrawCallCounter() { Y_AtomicIncrement(m_drawCallCounter); } void IncrementShaderChangeCounter() { Y_AtomicIncrement(m_shaderChangeCounter); } void IncrementPipelineChangeCounter() { Y_AtomicIncrement(m_pipelineChangeCounter); } void IncrementFramesDroppedCounter() { Y_AtomicIncrement(m_framesDroppedCounter); } void ResetPerFrameCounters(); // Resource memory management void OnResourceCreated(const GPUResource *pResource); void OnResourceDeleted(const GPUResource *pResource); private: uint32 m_frameNumber; uint32 m_drawCallCounter; uint32 m_shaderChangeCounter; uint32 m_pipelineChangeCounter; uint32 m_framesDroppedCounter; Y_ATOMIC_DECL ptrdiff_t m_resourceCPUMemoryUsage[GPU_RESOURCE_TYPE_COUNT]; Y_ATOMIC_DECL ptrdiff_t m_resourceGPUMemoryUsage[GPU_RESOURCE_TYPE_COUNT]; }; class Renderer { public: class FixedResources { public: struct ScreenQuadVertex { float2 Position; float2 TexCoord; void Set(const float2 &position, const float2 &texcoord) { Position = position; TexCoord = texcoord; } void Set(float x, float y, float u, float v) { Position.Set(x, y); TexCoord.Set(u, v); } }; public: FixedResources(Renderer *pRenderer); ~FixedResources(); bool CreateResources(); void ReleaseResources(); GPURasterizerState *GetRasterizerState(RENDERER_FILL_MODE fillMode = RENDERER_FILL_SOLID, RENDERER_CULL_MODE cullMode = RENDERER_CULL_BACK, bool depthBias = false, bool depthClamping = false, bool scissorTest = false); GPUDepthStencilState *GetDepthStencilState(bool depthTestEnabled = true, bool depthWriteEnabled = true, GPU_COMPARISON_FUNC comparisonFunc = GPU_COMPARISON_FUNC_LESS); GPUBlendState *GetBlendStateNoBlending() const { return m_pBlendStateNoBlending; } GPUBlendState *GetBlendStateNoColorWrites() const { return m_pBlendStateNoColorWrites; } GPUBlendState *GetBlendStateAdditive() const { return m_pBlendStateAdditive; } GPUBlendState *GetBlendStateAlphaBlending() const { return m_pBlendStateAlphaBlending; } GPUBlendState *GetBlendStateAlphaBlendingAdditive() const { return m_pBlendStateAlphaBlendingAdditive; } GPUBlendState *GetBlendStatePremultipliedAlpha() const { return m_pBlendStatePremultipliedAlpha; } GPUBlendState *GetBlendStatePremultipliedAlphaAdditive() const { return m_pBlendStatePremultipliedAlphaAdditive; } GPUBlendState *GetBlendStateBlendFactor() const { return m_pBlendStateBlendFactor; } GPUBlendState *GetBlendStateBlendFactorAdditive() const { return m_pBlendStateBlendFactorAdditive; } GPUBlendState *GetBlendStateBlendFactorPremultipledAlpha() const { return m_pBlendStateBlendFactorPremultipliedAlpha; } GPUBlendState *GetBlendStateBlendFactorApplyBlendFactorAlpha() const { return m_pBlendStateApplyBlendFactorAlpha; } GPUSamplerState *GetPointSamplerState() const { return m_pPointSamplerState; } GPUSamplerState *GetLinearSamplerState() const { return m_pLinearSamplerState; } GPUSamplerState *GetLinearMipSamplerState() const { return m_pLinearMipSamplerState; } const Font *GetDebugFont() const { return m_pDebugFont; } const Texture2D *GetNoiseTexture() const { return m_pNoiseTexture; } const Texture2D *GetRandomTexture() const { return m_pRandomTexture; } ShaderProgram *GetTextureBlitShader() const { return m_pTextureBlitShader; } ShaderProgram *GetTextureBlitLODShader() const { return m_pTextureBlitLODShader; } ShaderProgram *GetDownsampleShader() const { return m_pDownsampleShader; } GPUBuffer *GetFullScreenQuadVertexBuffer() const { return m_pFullScreenQuadVertexBuffer; } ShaderProgram *GetOverlayShaderColoredScreen() const { return m_pOverlayShaderColoredScreen; } ShaderProgram *GetOverlayShaderColoredWorld() const { return m_pOverlayShaderColoredWorld; } ShaderProgram *GetOverlayShaderTexturedScreen() const { return m_pOverlayShaderTexturedScreen; } ShaderProgram *GetOverlayShaderTexturedWorld() const { return m_pOverlayShaderTexturedWorld; } // predefined vertex layouts static const GPU_VERTEX_ELEMENT_DESC *GetPositionOnlyVertexAttributes(); static const uint32 GetPositionOnlyVertexAttributeCount(); static const GPU_VERTEX_ELEMENT_DESC *GetFullScreenQuadVertexAttributes(); static const uint32 GetFullScreenQuadVertexAttributeCount(); private: Renderer *m_pRenderer; // rasterizer // rs[wireframe][culling][depthbias][depthclip][scissor] AtomicPointer<GPURasterizerState> m_pRasterizerStates[RENDERER_FILL_MODE_COUNT][RENDERER_CULL_MODE_COUNT][2][2][2]; // depthstencil // ds[test][writes][comparison] AtomicPointer<GPUDepthStencilState> m_pDepthStencilStates[2][2][GPU_COMPARISON_FUNC_COUNT]; // blending GPUBlendState *m_pBlendStateNoBlending; GPUBlendState *m_pBlendStateNoColorWrites; GPUBlendState *m_pBlendStateAdditive; GPUBlendState *m_pBlendStateAlphaBlending; GPUBlendState *m_pBlendStateAlphaBlendingAdditive; GPUBlendState *m_pBlendStatePremultipliedAlpha; GPUBlendState *m_pBlendStatePremultipliedAlphaAdditive; GPUBlendState *m_pBlendStateBlendFactor; GPUBlendState *m_pBlendStateBlendFactorAdditive; GPUBlendState *m_pBlendStateBlendFactorPremultipliedAlpha; GPUBlendState *m_pBlendStateApplyBlendFactorAlpha; // sampler states GPUSamplerState *m_pPointSamplerState; GPUSamplerState *m_pLinearSamplerState; GPUSamplerState *m_pLinearMipSamplerState; // fixed resources const Font *m_pDebugFont; const Texture2D *m_pNoiseTexture; const Texture2D *m_pRandomTexture; // texture copy shader ShaderProgram *m_pTextureBlitShader; ShaderProgram *m_pTextureBlitLODShader; // downsample shader ShaderProgram *m_pDownsampleShader; // full-screen quad stuff GPUBuffer *m_pFullScreenQuadVertexBuffer; // overlay shader stuff ShaderProgram *m_pOverlayShaderColoredScreen; ShaderProgram *m_pOverlayShaderColoredWorld; ShaderProgram *m_pOverlayShaderTexturedScreen; ShaderProgram *m_pOverlayShaderTexturedWorld; }; public: Renderer(GPUDevice *pDevice, GPUContext *pImmediateContext, RendererOutputWindow *pOutputWindow); virtual ~Renderer(); // Find the default renderer platform for this running platform static RENDERER_PLATFORM GetDefaultPlatform(); // Called at start of application. static bool Create(const RendererInitializationParameters *pCreateParameters); // Shutdown the renderer. void Shutdown(); // draw a fullscreen quad void DrawFullScreenQuad(GPUCommandList *pCommandList); // copy a texture using a shader void BlitTextureUsingShader(GPUCommandList *pCommandList, GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, int32 sourceLevel, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter = RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE blendMode = RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE); // helper for creating an index buffer. buffer is freed with Y_free. static void BuildIndexBufferContents(uint32 sourceVertexCount, const uint32 *pSourceIndices, uint32 nIndicesPerPrimitive, uint32 nPrimitives, uint32 sourceIndicesStride, void **ppOutBuffer, GPU_INDEX_FORMAT *pOutIndexFormat, uint32 *pOutIndexCount); static void FillIndexBufferContents(const uint32 *pSourceIndices, uint32 nIndicesPerPrimitive, uint32 nPrimitives, uint32 sourceIndicesStride, GPU_INDEX_FORMAT indexFormat, void *pDestinationIndices, uint32 cbDestinationIndices); // --- helper methods --- // device queries const RENDERER_PLATFORM GetPlatform() const { return m_eRendererPlatform; } const RENDERER_FEATURE_LEVEL GetFeatureLevel() const { return m_eRendererFeatureLevel; } const TEXTURE_PLATFORM GetTexturePlatform() const { return m_eTexturePlatform; } const RendererCapabilities &GetCapabilities() const { return m_capabilities; } // Accesses the implicit swap chain. RendererOutputWindow *GetImplicitOutputWindow() { return m_pImplicitOutputWindow; } bool ChangeResolution(RENDERER_FULLSCREEN_STATE state, uint32 width = 0, uint32 height = 0, uint32 refreshRate = 0); // device/context access. these will return the value for the current thread, and thus attempting to // call GetGPUDevice() on a thread that has not registered for uploads, or GetGPUContext() on a thread // other than the render thread will cause the process to crash. GPUDevice *GetGPUDevice() const { return m_pDevice; } GPUContext *GetGPUContext() const; // Stats access RendererCounters *GetCounters() { return &m_stats; } // render thread static const Thread::ThreadIdType GetRenderThreadId() { return s_renderThreadId; } static const bool IsOnRenderThread() { return (Thread::GetCurrentThreadId() == s_renderThreadId); } static const bool HasRenderThread() { return (s_renderCommandQueue.GetWorkerThreadCount() != 0); } static TaskQueue *GetCommandQueue() { return &s_renderCommandQueue; } static TaskQueue *GetWorkerCommandQueue() { return &s_renderWorkerCommandQueue; } // accesses shader permutation ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); template<class T> ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return GetShaderProgram(globalShaderFlags, SHADER_COMPONENT_INFO(T), baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags); } template<class SHADERTYPE, class VERTEXFACTORYTYPE> ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return GetShaderProgram(globalShaderFlags, SHADER_COMPONENT_INFO(SHADERTYPE), baseShaderFlags, VERTEX_FACTORY_TYPE_INFO(VERTEXFACTORYTYPE), vertexFactoryFlags, pMaterialShader, materialShaderFlags); } // determine texture dimensions on a gpu texture static uint3 GetTextureDimensions(const GPUTexture *pTexture); // convert pixel coordinates to clip space coordinates static float2 GetClipSpaceCoordinatesForPixelCoordinates(int32 x, int32 y, uint32 windowWidth, uint32 windowHeight); // convert pixel coordinates to texture space coordinates static float2 GetTextureSpaceCoordinatesForPixelCoordinates(int32 x, int32 y, uint32 textureWidth, uint32 textureHeight); // fixed resource accessors. these DO NOT increment the reference count upon retrieval, as they are assumed to be persistent. Renderer::FixedResources *GetFixedResources() { return &m_fixedResources; } // gui context MiniGUIContext *GetGUIContext() { DebugAssert(Renderer::IsOnRenderThread()); return &m_guiContext; } // scissor rect calculators static bool CalculateAABoxScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const AABox &Bounds, const float4x4 &ViewMatrix, int32 RTWidth, int32 RTHeight); static bool CalculatePointLightScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const float3 &LightPosition, const float &LightRange, const float4x4 &ViewMatrix, int32 RTWidth, int32 RTHeight); // wrappers of above functions for current renderer state static bool CalculateAABoxScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const AABox &Bounds); static bool CalculatePointLightScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const float3 &LightPosition, const float &LightRange); // default state static void FillDefaultRasterizerState(RENDERER_RASTERIZER_STATE_DESC *pRasterizerState); static void FillDefaultDepthStencilState(RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState); static void FillDefaultBlendState(RENDERER_BLEND_STATE_DESC *pBlendState); static void FillDefaultSamplerState(GPU_SAMPLER_STATE_DESC *pSamplerState); static void CorrectTextureFilter(GPU_SAMPLER_STATE_DESC *pSamplerState); static bool TextureFilterRequiresMips(TEXTURE_FILTER filter); static uint32 CalculateMipCount(uint32 width, uint32 height = 1, uint32 depth = 1); // determine global shader flags for current environment static uint32 GetGlobalShaderFlagsForCurrentEnvironment(); // Device queries. bool CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat = NULL) const; // Creates a swap chain on a new window. RendererOutputWindow *CreateOutputWindow(const char *windowTitle, uint32 windowWidth, uint32 windowHeight, RENDERER_VSYNC_TYPE vsyncType); // Creates a swap chain on an existing window. GPUOutputBuffer *CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType); GPUOutputBuffer *CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType); // Resource creation GPUDepthStencilState *CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc); GPURasterizerState *CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc); GPUBlendState *CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc); GPUQuery *CreateQuery(GPU_QUERY_TYPE type); GPUBuffer *CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData = NULL); GPUTexture1D *CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUTexture1DArray *CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUTexture2D *CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUTexture2DArray *CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUTexture3D *CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL, const uint32 *pInitialDataSlicePitch = NULL); GPUTextureCube *CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUTextureCubeArray *CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = NULL, const uint32 *pInitialDataPitch = NULL); GPUDepthTexture *CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc); GPUSamplerState *CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc); GPURenderTargetView *CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc); GPUDepthStencilBufferView *CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc); GPUComputeView *CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc); GPUShaderProgram *CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream); GPUShaderProgram *CreateComputeProgram(ByteStream *pByteCodeStream); // CreateGraphicsPipeline // CreateComputePipeline // command list allocator GPUCommandList *AllocateCommandList(); void ReleaseCommandList(GPUCommandList *pCommandList); protected: // allowed to be called by upper classes bool BaseOnStart(); void BaseOnShutdown(); // render thread management static bool StartRenderThread(bool createWorkerThread); static void StopRenderThread(); static Thread::ThreadIdType s_renderThreadId; static TaskQueue s_renderCommandQueue; static TaskQueue s_renderWorkerCommandQueue; // renderer RENDERER_PLATFORM m_eRendererPlatform; RENDERER_FEATURE_LEVEL m_eRendererFeatureLevel; TEXTURE_PLATFORM m_eTexturePlatform; RendererCapabilities m_capabilities; // backend GPUDevice *m_pDevice; GPUContext *m_pImmediateContext; // output window RendererOutputWindow *m_pImplicitOutputWindow; // non-material shader map ShaderMap m_nullMaterialShaderMap; Mutex m_shaderLock; // state manager Renderer::FixedResources m_fixedResources; // gui context - owned by, and usage only by render thread MiniGUIContext m_guiContext; // stats RendererCounters m_stats; // command list pool PODArray<GPUCommandList *> m_freeCommandListPool; uint32 m_outstandingCommandListCount; private: bool InternalDrawPlain(GPUContext *pGPUDevice, const PlainVertexFactory::Vertex *pVertices, uint32 nVertices, uint32 flags); }; extern Renderer *g_pRenderer; // render thread helper macros #define QUEUE_RENDERER_COMMAND(obj) g_pRenderer->GetCommandQueue()->QueueTask(&obj, sizeof(obj)) #define QUEUE_RENDERER_LAMBDA_COMMAND g_pRenderer->GetCommandQueue()->QueueLambdaTask #define QUEUE_BLOCKING_RENDERER_COMMAND(obj) g_pRenderer->GetCommandQueue()->QueueBlockingTask(&obj, sizeof(obj)) #define QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND g_pRenderer->GetCommandQueue()->QueueBlockingLambdaTask #define QUEUE_RENDERER_WORKER_COMMAND(obj) g_pRenderer->GetWorkerCommandQueue()->QueueTask(&obj, sizeof(obj)) #define QUEUE_RENDERER_WORKER_LAMBDA_COMMAND g_pRenderer->GetWorkerCommandQueue()->QueueLambdaTask <file_sep>/Editor/Source/Editor/EditorResourcePreviewGenerator.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourcePreviewGenerator.h" #include "Editor/EditorHelpers.h" #include "Engine/ResourceManager.h" #include "Engine/Material.h" #include "Engine/MaterialShader.h" #include "Engine/Texture.h" #include "Engine/StaticMesh.h" #include "Engine/Font.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/ArcBallCamera.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Renderer/RenderWorld.h" #include "Renderer/Shaders/FullBrightShader.h" #include "Core/Image.h" Log_SetChannel(EditorResourcePreviewGenerator); EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() : m_targetWidth(0), m_targetHeight(0), m_pGPUContext(nullptr), m_pRenderTarget(nullptr), m_pRenderTargetView(nullptr), m_pDepthStencilBuffer(nullptr), m_pDepthStencilBufferView(nullptr), m_pWorldRenderer(nullptr), m_bGPUResourcesCreated(false), m_pOverlayTextFont(nullptr), m_pRenderWorld(new RenderWorld()) { } EditorResourcePreviewGenerator::~EditorResourcePreviewGenerator() { ReleaseGPUResources(); SAFE_RELEASE(m_pOverlayTextFont); m_pRenderWorld->Release(); } bool EditorResourcePreviewGenerator::CreateGPUResources() { if (m_bGPUResourcesCreated) return true; if (m_pWorldRenderer == nullptr) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(EDITOR_RENDER_MODE_FULLBRIGHT, m_pGPUContext, 0, m_targetWidth, m_targetHeight); m_bGPUResourcesCreated = true; return true; } void EditorResourcePreviewGenerator::ReleaseGPUResources() { if (m_pWorldRenderer != NULL) delete m_pWorldRenderer; SAFE_RELEASE(m_pDepthStencilBufferView); SAFE_RELEASE(m_pDepthStencilBuffer); SAFE_RELEASE(m_pRenderTargetView); SAFE_RELEASE(m_pRenderTarget); m_bGPUResourcesCreated = false; } bool EditorResourcePreviewGenerator::SetupRender(Image *pDestinationImage) { if (!m_bGPUResourcesCreated && !CreateGPUResources()) return false; uint32 targetWidth = pDestinationImage->GetWidth(); uint32 targetHeight = pDestinationImage->GetHeight(); DebugAssert(targetWidth > 0 && targetHeight > 0); if (m_targetWidth != targetWidth || m_targetHeight != targetHeight) { SAFE_RELEASE(m_pDepthStencilBufferView); SAFE_RELEASE(m_pDepthStencilBuffer); SAFE_RELEASE(m_pRenderTargetView); SAFE_RELEASE(m_pRenderTarget); m_targetWidth = 0; m_targetHeight = 0; } if (m_pRenderTarget == NULL) { GPU_TEXTURE2D_DESC renderTargetDesc; renderTargetDesc.Width = targetWidth; renderTargetDesc.Height = targetHeight; renderTargetDesc.Format = PIXEL_FORMAT_R8G8B8A8_UNORM; renderTargetDesc.Flags = GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET; renderTargetDesc.MipLevels = 1; GPU_DEPTH_TEXTURE_DESC depthStencilBufferDesc; depthStencilBufferDesc.Width = targetWidth; depthStencilBufferDesc.Height = targetHeight; depthStencilBufferDesc.Format = PIXEL_FORMAT_D16_UNORM; depthStencilBufferDesc.Flags = GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER; if ((m_pRenderTarget = g_pRenderer->CreateTexture2D(&renderTargetDesc, NULL)) == NULL || (m_pDepthStencilBuffer = g_pRenderer->CreateDepthTexture(&depthStencilBufferDesc)) == NULL) { Log_ErrorPrintf("EditorResourcePreviewGenerator::SetupRender: Could not create render target."); SAFE_RELEASE(m_pDepthStencilBuffer); SAFE_RELEASE(m_pRenderTarget); return false; } GPU_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(m_pRenderTarget, 0); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC depthStencilViewDesc(m_pDepthStencilBuffer); if ((g_pRenderer->CreateRenderTargetView(m_pRenderTarget, &renderTargetViewDesc)) == nullptr || (g_pRenderer->CreateDepthStencilBufferView(m_pDepthStencilBuffer, &depthStencilViewDesc)) == nullptr) { Log_ErrorPrintf("EditorResourcePreviewGenerator::SetupRender: Could not create render target view."); SAFE_RELEASE(m_pDepthStencilBufferView); SAFE_RELEASE(m_pDepthStencilBuffer); SAFE_RELEASE(m_pRenderTargetView); SAFE_RELEASE(m_pRenderTarget); return false; } // update dimensions m_targetWidth = targetWidth; m_targetHeight = targetHeight; // create viewport m_viewParameters.Viewport.Set(0, 0, targetWidth, targetHeight, 0.0f, 1.0f); // set in context m_ArcBallCamera.SetPerspectiveAspect((float)targetWidth, (float)targetHeight); m_GUIContext.SetViewportDimensions(targetWidth, targetHeight); } // capture current state m_stateBlock.Capture(m_pGPUContext, GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE | GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE | GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE | GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS | GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS | GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER | GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY | GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS | GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS | GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS | GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS); // setup all targets m_pGPUContext->SetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilBufferView); m_pGPUContext->SetViewport(&m_viewParameters.Viewport); // clear the target m_pGPUContext->ClearTargets(true, true, true, float4(0.0f, 0.0f, 0.0f, 1.0f)); // set camera m_viewParameters.ViewCamera = m_ArcBallCamera; m_viewParameters.ViewCamera.SetObjectCullDistance(m_ArcBallCamera.GetFarPlaneDistance() - m_ArcBallCamera.GetNearPlaneDistance()); m_viewParameters.MaximumShadowViewDistance = m_viewParameters.ViewCamera.GetObjectCullDistance(); // begin scene return true; } bool EditorResourcePreviewGenerator::CompleteRender(Image *pDestinationImage) { // end scene m_pGPUContext->ClearState(true, true, true, true); // restore state m_stateBlock.Restore(); m_stateBlock.Clear(); // do we need to copy to a temporary location first Image temporaryImage; Image *pReadToImage; if (m_pRenderTarget->GetDesc()->Format != pDestinationImage->GetPixelFormat()) { temporaryImage.Create(m_pRenderTarget->GetDesc()->Format, m_targetWidth, m_targetHeight, 1); pReadToImage = &temporaryImage; } else { // can go direct to destination pReadToImage = pDestinationImage; } if (!m_pGPUContext->ReadTexture(m_pRenderTarget, pReadToImage->GetData(), pReadToImage->GetDataRowPitch(), pReadToImage->GetDataSize(), 0, 0, 0, pReadToImage->GetWidth(), pReadToImage->GetHeight())) { Log_ErrorPrintf("EditorResourcePreviewGenerator::CompleteRender: Texture readback failed."); return false; } // conversion necessary? if (pReadToImage != pDestinationImage) { if (!pDestinationImage->CopyAndConvertPixelFormat(temporaryImage, pDestinationImage->GetPixelFormat())) { Log_ErrorPrintf("EditorResourcePreviewGenerator::CompleteRender: Image format conversion failed."); return false; } } return true; } void EditorResourcePreviewGenerator::SetCameraMatricesFor2D() { } void EditorResourcePreviewGenerator::SetCameraMatricesForArcBall() { } void EditorResourcePreviewGenerator::ResetCamera() { } bool EditorResourcePreviewGenerator::GenerateResourcePreview(Image *pDestinationImage, const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName) { AutoReleasePtr<const Resource> pResource = g_pResourceManager->UncachedGetResource(pResourceTypeInfo, resourceName); if (pResource == NULL) return false; return GenerateResourcePreview(pDestinationImage, pResource); } bool EditorResourcePreviewGenerator::GenerateResourcePreview(Image *pDestinationImage, const Resource *pResource) { const ResourceTypeInfo *pResourceTypeInfo = pResource->GetResourceTypeInfo(); if (pResourceTypeInfo == OBJECT_TYPEINFO(Material)) return GenerateMaterialPreview(pDestinationImage, pResource->Cast<Material>()); if (pResourceTypeInfo == OBJECT_TYPEINFO(MaterialShader)) return GenerateMaterialShaderPreview(pDestinationImage, pResource->Cast<MaterialShader>()); if (pResourceTypeInfo == OBJECT_TYPEINFO(Texture2D)) return GenerateTexture2DPreview(pDestinationImage, pResource->Cast<Texture2D>()); if (pResourceTypeInfo == OBJECT_TYPEINFO(StaticMesh)) return GenerateStaticMeshPreview(pDestinationImage, pResource->Cast<StaticMesh>()); if (pResourceTypeInfo == OBJECT_TYPEINFO(BlockPalette)) return GenerateBlockMeshBlockListPreview(pDestinationImage, pResource->Cast<BlockPalette>()); if (pResourceTypeInfo == OBJECT_TYPEINFO(Font)) return GenerateFontDataPreview(pDestinationImage, pResource->Cast<Font>()); return false; } bool EditorResourcePreviewGenerator::GenerateMaterialPreview(Image *pDestinationImage, const Material *pMaterial) { return false; } bool EditorResourcePreviewGenerator::GenerateMaterialShaderPreview(Image *pDestinationImage, const MaterialShader *pMaterialShader) { return false; } bool EditorResourcePreviewGenerator::GenerateTexture2DPreview(Image *pDestinationImage, const Texture2D *pTexture) { if (!SetupRender(pDestinationImage)) return false; // todo: draw checkerboard pattern behind // draw it MINIGUI_RECT rect(0, pDestinationImage->GetWidth() - 1, 0, pDestinationImage->GetHeight() - 1); MINIGUI_UV_RECT uvRect(0.0f, 1.0f, 0.0f, 1.0f); m_GUIContext.SetAlphaBlendingEnabled(false); m_GUIContext.DrawTexturedRect(&rect, &uvRect, pTexture); // complete render return CompleteRender(pDestinationImage); } bool EditorResourcePreviewGenerator::GenerateStaticMeshPreview(Image *pDestinationImage, const StaticMesh *pStaticMesh) { if (!pStaticMesh->CheckGPUResources()) return false; if (!SetupRender(pDestinationImage)) return false; // find mesh dimensions and maximum component float3 meshExtents(pStaticMesh->GetBoundingBox().GetExtents()); float maxComponent = Max(meshExtents.x, Max(meshExtents.y, meshExtents.z)); // create an arcball camera m_ArcBallCamera.Reset(); m_ArcBallCamera.SetEyeDistance(-maxComponent * 2.0f); m_ArcBallCamera.SetFarPlaneDistance(Min(100.0f, maxComponent * 10.0f)); m_ArcBallCamera.SetTarget(pStaticMesh->GetBoundingBox().GetCenter()); // setup renderer m_pGPUContext->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, false); m_pGPUContext->GetConstants()->SetFromCamera(m_ArcBallCamera, false); m_pGPUContext->GetConstants()->CommitChanges(); // draw lod 0 const StaticMesh::LOD *lod = pStaticMesh->GetLOD(0); // bind buffers m_pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); lod->GetVertexBuffers()->BindBuffers(m_pGPUContext); m_pGPUContext->SetIndexBuffer(lod->GetIndexBuffer(), lod->GetIndexFormat(), 0); // draw each batch for (uint32 batchIndex = 0; batchIndex < lod->GetBatchCount(); batchIndex++) { const StaticMesh::Batch *batch = lod->GetBatch(batchIndex); const Material *pMaterial = pStaticMesh->GetMaterial(batch->MaterialIndex); ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, SHADER_COMPONENT_INFO(FullBrightShader), 0, VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory), pStaticMesh->GetVertexFactoryFlags(), pMaterial->GetShader(), pMaterial->GetShaderStaticSwitchMask()); if (pShaderProgram != nullptr) { m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); if (pMaterial->BindDeviceResources(m_pGPUContext, pShaderProgram)) m_pGPUContext->DrawIndexed(batch->StartIndex, batch->NumIndices, 0); } } return CompleteRender(pDestinationImage); } bool EditorResourcePreviewGenerator::GenerateFontDataPreview(Image *pDestinationImage, const Font *pFontData) { return false; } bool EditorResourcePreviewGenerator::GenerateBlockMeshBlockListPreview(Image *pDestinationImage, const BlockPalette *pBlockList) { // render all images, and then merge them to the final image //Image *pBlockImages = new Image[BLOCK_MESH_MAX_BLOCK_TYPES]; //delete[] pBlockImages; return false; } bool EditorResourcePreviewGenerator::GenerateBlockMeshBlockListBlockPreview(Image *pDestinationImage, const BlockPalette *pBlockList, uint32 blockType) { if (!SetupRender(pDestinationImage)) return false; const BlockPalette::BlockType *pBlockType = pBlockList->GetBlockType(blockType); if (pBlockType->IsAllocated) { // get input layout uint32 factoryFlags = BlockMeshVertexFactory::GetVertexFlagsForCurrentRenderer(); // create a temporary mesh, using a 1x1x1 volume BlockVolumeBlockType blockData = (BlockVolumeBlockType)blockType; BlockMeshBuilder meshBuilder; meshBuilder.SetPalette(pBlockList); meshBuilder.SetSize(1, 1, 1); meshBuilder.SetBlockData(&blockData); meshBuilder.SetScale(1.0f); meshBuilder.SetAmbientOcclusionEnabled(false); meshBuilder.SetTranslation(float3(-0.5f, 0.5f, 0.0f)); meshBuilder.GenerateMesh(); // render it if (meshBuilder.GetOutputBatchCount() > 0) { // static view matrix static const float viewMatrixValues[16] = { 1.0000000f, 3.3378265e-009f, 1.0486073e-008f, 0.0082103405f, -1.0661471e-008f, 0.52991974f, 0.84804773f, -0.97877538f, -2.7261406e-009f, -0.84804773f, 0.52991974f, -1.0200906f, 0.0000000f, 0.0000000f, 0.0000000f, 1.0000000 }; float4x4 viewMatrix(viewMatrixValues); float4x4 projectionMatrix(float4x4::MakePerspectiveProjectionMatrix(Math::DegreesToRadians(65.0f), (float)m_targetWidth / (float)m_targetHeight, 0.1f, 100.0f)); // set constants GPUContext *pGPUDevice = m_pGPUContext; GPUContextConstants *pGPUConstants = pGPUDevice->GetConstants(); pGPUConstants->SetLocalToWorldMatrix(float4x4::Identity, false); pGPUConstants->SetCameraViewMatrix(viewMatrix, false); pGPUConstants->SetCameraProjectionMatrix(projectionMatrix, false); pGPUConstants->SetCameraEyePosition(float3(0.0f, -8.0f, 0.0f), false); pGPUConstants->CommitChanges(); // set states pGPUDevice->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pGPUDevice->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); pGPUDevice->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // convert vertices to factory format uint32 vertexSize = BlockMeshVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), factoryFlags); uint32 bufferSize = meshBuilder.GetOutputVertexCount() * vertexSize; byte *pFactoryVertices = new byte[bufferSize]; BlockMeshVertexFactory::FillVertices(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), factoryFlags, meshBuilder.GetOutputVertices().GetBasePointer(), meshBuilder.GetOutputVertexCount(), pFactoryVertices, bufferSize); // allocate indices void *pIndicesData; GPU_INDEX_FORMAT indexFormat; uint32 nIndices; g_pRenderer->BuildIndexBufferContents(meshBuilder.GetOutputVertexCount(), &meshBuilder.GetOutputTriangles().GetElement(0).Indices[0], 3, meshBuilder.GetOutputTriangleCount(), sizeof(BlockMeshBuilder::Triangle), &pIndicesData, &indexFormat, &nIndices); // draw batches for (uint32 batchIndex = 0; batchIndex < meshBuilder.GetOutputBatchCount(); batchIndex++) { const BlockMeshBuilder::Batch &batch = meshBuilder.GetOutputBatches().GetElement(batchIndex); // const void *pIndices = reinterpret_cast<const byte *>(pIndicesData) + (batch.StartIndex * ((indexFormat == GPU_INDEX_FORMAT_UINT32) ? sizeof(uint32) : sizeof(uint16))); // g_pRenderer->DrawMaterialIndexedUserPointer(pGPUDevice, pBlockList->GetMaterial(batch.MaterialIndex), // VERTEX_FACTORY_TYPE_INFO(BlockMeshVertexFactory), factoryFlags, // pFactoryVertices, vertexSize, meshBuilder.GetOutputVertexCount(), // pIndices, // indexFormat, // nIndices); } Y_free(pIndicesData); delete[] pFactoryVertices; } } return CompleteRender(pDestinationImage); } <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUQuery.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUQuery.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" //Log_SetChannel(OpenGLRenderBackend); OpenGLGPUQuery::OpenGLGPUQuery(GPU_QUERY_TYPE type, GLuint id) : m_eType(type) , m_iGLQueryId(id) , m_pOwningContext(nullptr) { } OpenGLGPUQuery::~OpenGLGPUQuery() { DebugAssert(m_pOwningContext == nullptr); if (m_iGLQueryId != 0) glDeleteQueries(1, &m_iGLQueryId); } void OpenGLGPUQuery::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr && m_iGLQueryId != 0) *gpuMemoryUsage = 128; } void OpenGLGPUQuery::SetDebugName(const char *name) { if (m_iGLQueryId != 0) OpenGLHelpers::SetObjectDebugName(GL_QUERY, m_iGLQueryId, name); } GPUQuery *OpenGLGPUDevice::CreateQuery(GPU_QUERY_TYPE Type) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; GLuint glQueryId = 0; switch (Type) { case GPU_QUERY_TYPE_SAMPLES_PASSED: case GPU_QUERY_TYPE_OCCLUSION: case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: case GPU_QUERY_TYPE_TIMESTAMP: { GL_CHECKED_SECTION_BEGIN(); glGenQueries(1, &glQueryId); if (glQueryId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateQuery: glGenQueries failed: "); return nullptr; } } break; case GPU_QUERY_TYPE_FREQUENCY: // fixed at 1000000000.0 break; default: UnreachableCode(); break; } return new OpenGLGPUQuery(Type, glQueryId); } bool OpenGLGPUContext::BeginQuery(GPUQuery *pQuery) { OpenGLGPUQuery *pGLQuery = static_cast<OpenGLGPUQuery *>(pQuery); DebugAssert(pGLQuery->GetOwningContext() == nullptr); pGLQuery->SetOwningContext(this); switch (pQuery->GetQueryType()) { case GPU_QUERY_TYPE_SAMPLES_PASSED: glBeginQuery(GL_SAMPLES_PASSED, pGLQuery->GetGLQueryID()); return true; case GPU_QUERY_TYPE_OCCLUSION: glBeginQuery(GL_ANY_SAMPLES_PASSED, pGLQuery->GetGLQueryID()); return true; case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: glBeginQuery(GL_PRIMITIVES_GENERATED, pGLQuery->GetGLQueryID()); return true; case GPU_QUERY_TYPE_TIMESTAMP: glQueryCounter(pGLQuery->GetGLQueryID(), GL_TIMESTAMP); return true; case GPU_QUERY_TYPE_FREQUENCY: return true; default: UnreachableCode(); return false; } } bool OpenGLGPUContext::EndQuery(GPUQuery *pQuery) { OpenGLGPUQuery *pGLQuery = static_cast<OpenGLGPUQuery *>(pQuery); DebugAssert(pGLQuery->GetOwningContext() == this); pGLQuery->SetOwningContext(nullptr); switch (pQuery->GetQueryType()) { case GPU_QUERY_TYPE_SAMPLES_PASSED: glEndQuery(GL_SAMPLES_PASSED); return true; case GPU_QUERY_TYPE_OCCLUSION: glEndQuery(GL_ANY_SAMPLES_PASSED); return true; case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: glEndQuery(GL_PRIMITIVES_GENERATED); return true; case GPU_QUERY_TYPE_TIMESTAMP: return true; case GPU_QUERY_TYPE_FREQUENCY: return true; default: UnreachableCode(); return false; } } GPU_QUERY_GETDATA_RESULT OpenGLGPUContext::GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) { OpenGLGPUQuery *pGLQuery = static_cast<OpenGLGPUQuery *>(pQuery); DebugAssert(pGLQuery->GetOwningContext() == nullptr); // check result availability if (pGLQuery->GetGLQueryID() != 0) { GLint resultAvailable = GL_FALSE; glGetQueryObjectiv(pGLQuery->GetGLQueryID(), GL_QUERY_RESULT_AVAILABLE, &resultAvailable); if (!resultAvailable) return GPU_QUERY_GETDATA_RESULT_NOT_READY; } switch (pQuery->GetQueryType()) { case GPU_QUERY_TYPE_SAMPLES_PASSED: { // uint64 DebugAssert(cbData >= sizeof(uint64)); glGetQueryObjectui64v(pGLQuery->GetGLQueryID(), GL_SAMPLES_PASSED, reinterpret_cast<GLuint64 *>(pData)); return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_OCCLUSION: { // int -> bool GLint val = 0; glGetQueryObjectiv(pGLQuery->GetGLQueryID(), GL_ANY_SAMPLES_PASSED, &val); DebugAssert(cbData >= sizeof(bool)); *reinterpret_cast<bool *>(pData) = (val != 0); return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: { // uint64 DebugAssert(cbData >= sizeof(uint64)); glGetQueryObjectui64v(pGLQuery->GetGLQueryID(), GL_PRIMITIVES_GENERATED, reinterpret_cast<GLuint64 *>(pData)); return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_TIMESTAMP: { // uint64 DebugAssert(cbData >= sizeof(uint64)); glGetQueryObjectui64v(pGLQuery->GetGLQueryID(), GL_TIMESTAMP, reinterpret_cast<GLuint64 *>(pData)); return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_FREQUENCY: { // uint64 DebugAssert(cbData >= sizeof(uint64)); *reinterpret_cast<uint64 *>(pData) = 1000000000; return GPU_QUERY_GETDATA_RESULT_OK; } default: UnreachableCode(); return GPU_QUERY_GETDATA_RESULT_ERROR; } } void OpenGLGPUContext::SetPredication(GPUQuery *pQuery) { } <file_sep>/Engine/Source/D3D11Renderer/PrecompiledHeader.cpp #include "D3D11Renderer/PrecompiledHeader.h" <file_sep>/Engine/Source/MathLib/Sphere.cpp #include "MathLib/Sphere.h" #include "MathLib/AABox.h" #include "MathLib/CollisionDetection.h" #include "MathLib/Transform.h" #include "MathLib/SIMDVectorf.h" static const float __SphereZero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const float __SphereMaxSize[] = { 0.0f, 0.0f, 0.0f, Y_FLT_MAX }; const Sphere &Sphere::Zero = reinterpret_cast<const Sphere &>(__SphereZero); const Sphere &Sphere::MaxSize = reinterpret_cast<const Sphere &>(__SphereMaxSize); Sphere::Sphere(const Vector3f &centre, float radius) : m_center(centre), m_radius(radius) { } Sphere::Sphere(const Sphere &copy) : m_center(copy.m_center), m_radius(copy.m_radius) { } void Sphere::Merge(const Vector3f &point) { float dist = (SIMDVector3f(point) - SIMDVector3f(m_center)).Length(); m_radius = Max(m_radius, dist); } void Sphere::Merge(const Sphere &sphere) { SIMDVector3f D(SIMDVector3f(sphere.m_center) - SIMDVector3f(m_center)); float d = D.Length(); float i0min = -m_radius; float i0max = m_radius; float i1min = d - sphere.m_radius; float i1max = d + sphere.m_radius; if (i1min >= i0min && i1max <= i0max) { } else if (i0min >= i1min && i0max <= i1max) { m_center = sphere.m_center; m_radius = sphere.m_radius; } else { m_radius = d + m_radius + sphere.m_radius; m_center = SIMDVector3f(m_center) + D * (0.5f * (d + m_radius - sphere.m_radius)) / d; } } Sphere Sphere::Merge(const Sphere &left, const Sphere &right) { Sphere newSphere(left); newSphere.Merge(right); return newSphere; } bool Sphere::AABoxIntersection(const AABox &box) const { return CollisionDetection::SphereIntersectsBox(m_center, m_radius, box.GetMinBounds(), box.GetMaxBounds()); } bool Sphere::AABoxIntersection(const AABox &box, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::SphereIntersectsBox(m_center, m_radius, box.GetMinBounds(), box.GetMaxBounds(), contactNormal, contactPoint); } bool Sphere::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const { return CollisionDetection::SphereIntersectsBox(m_center, m_radius, minBounds, maxBounds); } bool Sphere::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::SphereIntersectsBox(m_center, m_radius, minBounds, maxBounds, contactNormal, contactPoint); } bool Sphere::SphereIntersection(const Sphere &sphere) const { return CollisionDetection::SphereIntersectsSphere(m_center, m_radius, sphere.m_center, sphere.m_radius); } bool Sphere::SphereIntersection(const Sphere &sphere, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::SphereIntersectsSphere(m_center, m_radius, sphere.m_center, sphere.m_radius, contactNormal, contactPoint); } bool Sphere::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); return CollisionDetection::SphereIntersectsTriangle(m_center, m_radius, v0, v1, v2, vec_e0, vec_e1, vec_normal); } bool Sphere::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); return CollisionDetection::SphereIntersectsTriangle(m_center, m_radius, v0, v1, v2, vec_e0, vec_e1, vec_normal, contactNormal, contactPoint); } float Sphere::TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); Vector3f contactNormal, contactPoint; if (CollisionDetection::SphereIntersectsTriangle(m_center, m_radius, v0, v1, v2, vec_e0, vec_e1, vec_normal, contactNormal, contactPoint)) return (SIMDVector3f(contactPoint) - SIMDVector3f(m_center)).Length(); else return Y_FLT_INFINITE; } bool Sphere::operator==(const Sphere &comp) const { return SIMDVector3f(m_center) == SIMDVector3f(comp.m_center) && m_radius == comp.m_radius; } bool Sphere::operator!=(const Sphere &comp) const { return SIMDVector3f(m_center) != SIMDVector3f(comp.m_center) || m_radius != comp.m_radius; } Sphere &Sphere::operator=(const Sphere &copy) { m_center = copy.m_center; m_radius = copy.m_radius; return *this; } Sphere Sphere::FromAABox(const AABox &box) { SIMDVector3f center(box.GetCenter()); float radius = (SIMDVector3f(box.GetMaxBounds()) - center).Length(); return Sphere(center, radius); } Sphere Sphere::FromPoints(const SIMDVector3f *pPoints, uint32 nPoints) { uint32 i; Assert(nPoints > 0); SIMDVector3f center(pPoints[0]); for (i = 1; i < nPoints; i++) center += pPoints[i]; center /= (float)nPoints; float squaredRadius = 0.0f; for (i = 0; i < nPoints; i++) squaredRadius = Max(squaredRadius, (pPoints[i] - center).SquaredLength()); return Sphere(center, Math::Sqrt(squaredRadius)); } Sphere Sphere::FromPoints(const Vector3f *pPoints, uint32 nPoints) { uint32 i; Assert(nPoints > 0); SIMDVector3f center(pPoints[0]); for (i = 1; i < nPoints; i++) center += SIMDVector3f(pPoints[i]); center /= (float)nPoints; float squaredRadius = 0.0f; for (i = 0; i < nPoints; i++) squaredRadius = Max(squaredRadius, (SIMDVector3f(pPoints[i]) - center).SquaredLength()); return Sphere(center, Math::Sqrt(squaredRadius)); } void Sphere::ApplyTransform(const Transform &transform) { // get maximum amount of scale float maxScaleDimension = Max(transform.GetScale().x, Max(transform.GetScale().y, transform.GetScale().z)); // apply translation m_center += transform.GetPosition(); // apply scale m_radius *= maxScaleDimension; } void Sphere::ApplyTransform(const Matrix3x3f &transform) { // get maximum amount of scale float maxScaleDimension = Max(transform(0, 0), Max(transform(1, 1), transform(2, 2))); // apply scale m_radius *= maxScaleDimension; } void Sphere::ApplyTransform(const Matrix3x4f &transform) { // get maximum amount of scale float maxScaleDimension = Max(transform(0, 0), Max(transform(1, 1), transform(2, 2))); // apply translation m_center += transform.GetColumn(3); // apply scale m_radius *= maxScaleDimension; } void Sphere::ApplyTransform(const Matrix4x4f &transform) { // get maximum amount of scale float maxScaleDimension = Max(transform(0, 0), Max(transform(1, 1), transform(2, 2))); // apply translation m_center += transform.GetColumn(3).xyz(); // apply scale m_radius *= maxScaleDimension; } Sphere Sphere::GetTransformed(const Transform &transform) const { Sphere transformed(*this); transformed.ApplyTransform(transform); return transformed; } Sphere Sphere::GetTransformed(const Matrix3x3f &transform) const { Sphere transformed(*this); transformed.ApplyTransform(transform); return transformed; } Sphere Sphere::GetTransformed(const Matrix3x4f &transform) const { Sphere transformed(*this); transformed.ApplyTransform(transform); return transformed; } Sphere Sphere::GetTransformed(const Matrix4x4f &transform) const { Sphere transformed(*this); transformed.ApplyTransform(transform); return transformed; } <file_sep>/Editor/Source/Editor/EditorResourceSelectionWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourceSelectionWidget.h" #include "Editor/EditorResourceSelectionDialog.h" #include "Editor/EditorHelpers.h" EditorResourceSelectionWidget::EditorResourceSelectionWidget(QWidget *pParent /*= NULL*/) : QWidget(pParent) { m_pLineEdit = new QLineEdit(this); m_pBrowseButton = new QPushButton(this); m_pBrowseButton->setText(tr("...")); m_pBrowseButton->setMinimumSize(16, 16); m_pBrowseButton->setMaximumSize(20, 16777215); QHBoxLayout *hbox = new QHBoxLayout(this); hbox->setMargin(0); hbox->setSpacing(0); hbox->addWidget(m_pLineEdit, 1); hbox->addWidget(m_pBrowseButton, 0); setLayout(hbox); connect(m_pLineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(onLineEditEdited(const QString &))); connect(m_pBrowseButton, SIGNAL(clicked()), this, SLOT(onBrowseButtonClicked())); } EditorResourceSelectionWidget::~EditorResourceSelectionWidget() { } void EditorResourceSelectionWidget::setResourceTypeInfo(const ResourceTypeInfo *pResourceTypeInfo) { m_pResourceTypeInfo = pResourceTypeInfo; } void EditorResourceSelectionWidget::setValue(const QString &value) { m_pLineEdit->setText(value); } void EditorResourceSelectionWidget::onBrowseButtonClicked() { EditorResourceSelectionDialog selectionDialog(this); if (m_pResourceTypeInfo != NULL) selectionDialog.AddResourceFilter(m_pResourceTypeInfo); // find the directory of this resource SmallString currentValue; ConvertQStringToString(currentValue, m_pLineEdit->text()); int32 lastSlash = currentValue.RFind('/'); if (lastSlash >= 0) { currentValue.Erase(lastSlash); if (!selectionDialog.NavigateToDirectory(currentValue, false)) selectionDialog.NavigateToDirectory("/", false); } selectionDialog.exec(); if (selectionDialog.GetReturnValueResourceType() != NULL) { QString value(ConvertStringToQString(selectionDialog.GetReturnValueResourceName())); m_pLineEdit->setText(value); valueChanged(value); } } void EditorResourceSelectionWidget::onLineEditEdited(const QString &value) { valueChanged(value); } <file_sep>/Engine/Source/OpenGLRenderer/OpenGLShaderCacheEntry.h #pragma once #pragma pack(push, 4) #define OPENGL_SHADER_CACHE_ENTRY_HEADER (0x474C455332305348ULL) enum OPENGL_SHADER_BIND_TARGET { OPENGL_SHADER_BIND_TARGET_UNIFORM, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT, OPENGL_SHADER_BIND_TARGET_UNIFORM_BUFFER, OPENGL_SHADER_BIND_TARGET_IMAGE_UNIT, OPENGL_SHADER_BIND_TARGET_SHADER_STORAGE_BUFFER, OPENGL_SHADER_BIND_TARGET_COUNT, }; struct OpenGLShaderCacheEntryHeader { uint64 Signature; uint32 Platform; uint32 FeatureLevel; uint32 StageSize[SHADER_PROGRAM_STAGE_COUNT]; uint32 VertexAttributeCount; uint32 UniformBlockCount; uint32 ParameterCount; uint32 FragmentDataCount; uint32 DebugNameLength; // <byte> * StageSize for each stage // OpenGLShaderCacheEntryVertexAttribute * VertexAttributeCount // OpenGLShaderCacheEntryUniformBuffer * UniformBufferCount // OpenGLShaderCacheEntryParameter * ParameterCount // OpenGLShaderCacheEntryFragmentDataOutput * FragmentDataOutputCount // <char> * DebugNameLength // Ignored on GLES2: UniformBufferCount, FragmentDataOutputCount }; struct OpenGLShaderCacheEntryVertexAttribute { uint32 SemanticName; uint32 SemanticIndex; uint32 NameLength; // <char> * NameLength }; struct OpenGLShaderCacheEntryUniformBlock { uint32 NameLength; uint32 Size; uint32 ParameterIndex; bool IsLocal; // <char> * NameLength }; struct OpenGLShaderCacheEntryParameter { uint32 NameLength; uint32 SamplerNameLength; uint32 Type; uint32 ArraySize; uint32 ArrayStride; uint32 BindTarget; int32 UniformBlockIndex; uint32 UniformBlockOffset; // <char> * NameLength // <char> * SamplerNameLength }; struct OpenGLShaderCacheEntryFragmentData { uint32 NameLength; uint32 RenderTargetIndex; // <char> * NameLength }; #pragma pack(pop) <file_sep>/Engine/Source/Core/PixelFormat.cpp #include "Core/PrecompiledHeader.h" #include "Core/PixelFormat.h" #include "YBaseLib/Assert.h" static const PIXEL_FORMAT_INFO g_PixelFormatInfo[PIXEL_FORMAT_COUNT] = { // Name BitsPerPixel IsImageFormat HasAlpha IsBlockCompressed BytesPerBlock BlockSize UncompressedFormat LinearFormat ColorMaskRed ColorMaskGreen ColorMaskBlue ColorMaskAlpha ColorBits DepthBits StencilBits { "PIXEL_FORMAT_R8_UINT", 8, true, false, false, 0, 0, PIXEL_FORMAT_R8_UINT, PIXEL_FORMAT_R8_UINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_R8_SINT", 8, true, false, false, 0, 0, PIXEL_FORMAT_R8_SINT, PIXEL_FORMAT_R8_SINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_R8_UNORM", 8, true, false, false, 0, 0, PIXEL_FORMAT_R8_UNORM, PIXEL_FORMAT_R8_UNORM, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_R8_SNORM", 8, true, false, false, 0, 0, PIXEL_FORMAT_R8_SNORM, PIXEL_FORMAT_R8_SNORM, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_R8G8_UINT", 16, true, false, false, 0, 0, PIXEL_FORMAT_R8G8_UINT, PIXEL_FORMAT_R8G8_UINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R8G8_SINT", 16, true, false, false, 0, 0, PIXEL_FORMAT_R8G8_SINT, PIXEL_FORMAT_R8G8_SINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R8G8_UNORM", 16, true, false, false, 0, 0, PIXEL_FORMAT_R8G8_UNORM, PIXEL_FORMAT_R8G8_UNORM, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R8G8_SNORM", 16, true, false, false, 0, 0, PIXEL_FORMAT_R8G8_SNORM, PIXEL_FORMAT_R8G8_SNORM, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R8G8B8A8_UINT", 32, true, true, false, 0, 0, PIXEL_FORMAT_R8G8B8A8_UINT, PIXEL_FORMAT_R8G8B8A8_UINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_R8G8B8A8_SINT", 32, true, true, false, 0, 0, PIXEL_FORMAT_R8G8B8A8_SINT, PIXEL_FORMAT_R8G8B8A8_SINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_R8G8B8A8_UNORM", 32, true, true, false, 0, 0, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB", 32, true, true, false, 0, 0, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_R8G8B8A8_UNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_R8G8B8A8_SNORM", 32, true, true, false, 0, 0, PIXEL_FORMAT_R8G8B8A8_SNORM, PIXEL_FORMAT_R8G8B8A8_SNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_R9G9B9E5_SHAREDEXP", 32, true, false, false, 0, 0, PIXEL_FORMAT_R9G9B9E5_SHAREDEXP, PIXEL_FORMAT_R9G9B9E5_SHAREDEXP, 0x000001FF, 0x0003FE00, 0x07FC0000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R10G10B10A2_UINT", 32, false, true, false, 0, 0, PIXEL_FORMAT_R10G10B10A2_UINT, PIXEL_FORMAT_R10G10B10A2_UINT, 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000, 30, 0, 0 }, { "PIXEL_FORMAT_R10G10B10A2_UNORM", 32, true, true, false, 0, 0, PIXEL_FORMAT_R10G10B10A2_UNORM, PIXEL_FORMAT_R10G10B10A2_UNORM, 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000, 30, 0, 0 }, { "PIXEL_FORMAT_R11G11B10_FLOAT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R11G11B10_FLOAT, PIXEL_FORMAT_R11G11B10_FLOAT, 0x000007FF, 0x003FF800, 0xFFC00000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16_UINT", 16, true, false, false, 0, 0, PIXEL_FORMAT_R16_UINT, PIXEL_FORMAT_R16_UINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R16_SINT", 16, true, false, false, 0, 0, PIXEL_FORMAT_R16_SINT, PIXEL_FORMAT_R16_SINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R16_UNORM", 16, true, false, false, 0, 0, PIXEL_FORMAT_R16_UNORM, PIXEL_FORMAT_R16_UNORM, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R16_SNORM", 16, true, false, false, 0, 0, PIXEL_FORMAT_R16_SNORM, PIXEL_FORMAT_R16_SNORM, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R16_FLOAT", 16, true, false, false, 0, 0, PIXEL_FORMAT_R16_FLOAT, PIXEL_FORMAT_R16_FLOAT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_R16G16_UINT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R16G16_UINT, PIXEL_FORMAT_R16G16_UINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16G16_SINT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R16G16_SINT, PIXEL_FORMAT_R16G16_SINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16G16_UNORM", 32, true, false, false, 0, 0, PIXEL_FORMAT_R16G16_UNORM, PIXEL_FORMAT_R16G16_UNORM, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16G16_SNORM", 32, true, false, false, 0, 0, PIXEL_FORMAT_R16G16_SNORM, PIXEL_FORMAT_R16G16_SNORM, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16G16_FLOAT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R16G16_FLOAT, PIXEL_FORMAT_R16G16_FLOAT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R16G16B16A16_UINT", 64, true, true, false, 0, 0, PIXEL_FORMAT_R16G16B16A16_UINT, PIXEL_FORMAT_R16G16B16A16_UINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 64, 0, 0 }, { "PIXEL_FORMAT_R16G16B16A16_SINT", 64, true, true, false, 0, 0, PIXEL_FORMAT_R16G16B16A16_SINT, PIXEL_FORMAT_R16G16B16A16_SINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 64, 0, 0 }, { "PIXEL_FORMAT_R16G16B16A16_UNORM", 64, true, true, false, 0, 0, PIXEL_FORMAT_R16G16B16A16_UNORM, PIXEL_FORMAT_R16G16B16A16_UNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 64, 0, 0 }, { "PIXEL_FORMAT_R16G16B16A16_SNORM", 64, true, true, false, 0, 0, PIXEL_FORMAT_R16G16B16A16_SNORM, PIXEL_FORMAT_R16G16B16A16_SNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 64, 0, 0 }, { "PIXEL_FORMAT_R16G16B16A16_FLOAT", 64, true, true, false, 0, 0, PIXEL_FORMAT_R16G16B16A16_FLOAT, PIXEL_FORMAT_R16G16B16A16_FLOAT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 64, 0, 0 }, { "PIXEL_FORMAT_R32_UINT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R32_UINT, PIXEL_FORMAT_R32_UINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R32_SINT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R32_SINT, PIXEL_FORMAT_R32_SINT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R32_FLOAT", 32, true, false, false, 0, 0, PIXEL_FORMAT_R32_FLOAT, PIXEL_FORMAT_R32_FLOAT, 0x000000FF, 0x00000000, 0x00000000, 0x00000000, 32, 0, 0 }, { "PIXEL_FORMAT_R32G32_UINT", 64, true, false, false, 0, 0, PIXEL_FORMAT_R32G32_UINT, PIXEL_FORMAT_R32G32_UINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 64, 0, 0 }, { "PIXEL_FORMAT_R32G32_SINT", 64, true, false, false, 0, 0, PIXEL_FORMAT_R32G32_SINT, PIXEL_FORMAT_R32G32_SINT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 64, 0, 0 }, { "PIXEL_FORMAT_R32G32_FLOAT", 64, true, false, false, 0, 0, PIXEL_FORMAT_R32G32_FLOAT, PIXEL_FORMAT_R32G32_FLOAT, 0x000000FF, 0x0000FF00, 0x00000000, 0x00000000, 64, 0, 0 }, { "PIXEL_FORMAT_R32G32B32_UINT", 96, true, false, false, 0, 0, PIXEL_FORMAT_R32G32B32_UINT, PIXEL_FORMAT_R32G32B32_UINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000, 96, 0, 0 }, { "PIXEL_FORMAT_R32G32B32_SINT", 96, true, false, false, 0, 0, PIXEL_FORMAT_R32G32B32_SINT, PIXEL_FORMAT_R32G32B32_SINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000, 96, 0, 0 }, { "PIXEL_FORMAT_R32G32B32_FLOAT", 96, true, false, false, 0, 0, PIXEL_FORMAT_R32G32B32_FLOAT, PIXEL_FORMAT_R32G32B32_FLOAT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000, 96, 0, 0 }, { "PIXEL_FORMAT_R32G32B32A32_UINT", 128, true, true, false, 0, 0, PIXEL_FORMAT_R32G32B32A32_UINT, PIXEL_FORMAT_R32G32B32A32_UINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 128, 0, 0 }, { "PIXEL_FORMAT_R32G32B32A32_SINT", 128, true, true, false, 0, 0, PIXEL_FORMAT_R32G32B32A32_SINT, PIXEL_FORMAT_R32G32B32A32_SINT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 128, 0, 0 }, { "PIXEL_FORMAT_R32G32B32A32_FLOAT", 128, true, true, false, 0, 0, PIXEL_FORMAT_R32G32B32A32_FLOAT, PIXEL_FORMAT_R32G32B32A32_FLOAT, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, 128, 0, 0 }, { "PIXEL_FORMAT_B8G8R8A8_UNORM", 32, true, true, false, 0, 0, PIXEL_FORMAT_B8G8R8A8_UNORM, PIXEL_FORMAT_B8G8R8A8_UNORM, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB", 32, true, true, false, 0, 0, PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB, PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, 32, 0, 0 }, { "PIXEL_FORMAT_B8G8R8X8_UNORM", 32, true, true, false, 0, 0, PIXEL_FORMAT_B8G8R8X8_UNORM, PIXEL_FORMAT_B8G8R8X8_UNORM, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000, 24, 0, 0 }, { "PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB", 32, true, true, false, 0, 0, PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB, PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000, 24, 0, 0 }, { "PIXEL_FORMAT_B5G6R5_UNORM", 16, true, false, false, 0, 0, PIXEL_FORMAT_B5G6R5_UNORM, PIXEL_FORMAT_B5G6R5_UNORM, 0x0000F800, 0x000007E0, 0x0000001F, 0x00000000, 16, 0, 0 }, { "PIXEL_FORMAT_B5G5R5A1_UNORM", 16, true, true, false, 0, 0, PIXEL_FORMAT_B5G5R5A1_UNORM, PIXEL_FORMAT_B5G5R5A1_UNORM, 0x0000F800, 0x000007C0, 0x0000003E, 0x00000001, 15, 0, 0 }, { "PIXEL_FORMAT_BC1_UNORM", 4, true, true, true, 8, 4, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_BC1_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 4, 0, 0 }, { "PIXEL_FORMAT_BC1_UNORM_SRGB", 4, true, true, true, 8, 4, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_BC1_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 4, 0, 0 }, { "PIXEL_FORMAT_BC2_UNORM", 4, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_BC2_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 4, 0, 0 }, { "PIXEL_FORMAT_BC2_UNORM_SRGB", 4, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_BC2_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 4, 0, 0 }, { "PIXEL_FORMAT_BC3_UNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_BC3_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC3_UNORM_SRGB", 8, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_BC3_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC4_UNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R16_UNORM, PIXEL_FORMAT_BC4_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC4_SNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R16_SNORM, PIXEL_FORMAT_BC4_SNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC5_UNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R16G16_UNORM, PIXEL_FORMAT_BC5_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC5_SNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R16G16_SNORM, PIXEL_FORMAT_BC5_SNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC6H_UF16", 8, false, true, true, 16, 4, PIXEL_FORMAT_R16G16_UNORM, PIXEL_FORMAT_BC6H_UF16, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC6H_SF16", 8, false, true, true, 16, 4, PIXEL_FORMAT_R16G16_SNORM, PIXEL_FORMAT_BC6H_SF16, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC7_UNORM", 8, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_BC7_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_BC7_UNORM_SRGB", 8, true, true, true, 16, 4, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_BC7_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 8, 0, 0 }, { "PIXEL_FORMAT_D16_UNORM", 16, false, false, false, 0, 0, PIXEL_FORMAT_D16_UNORM, PIXEL_FORMAT_D16_UNORM, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 16, 0 }, { "PIXEL_FORMAT_D24_UNORM_S8_UINT", 32, false, false, false, 0, 0, PIXEL_FORMAT_D24_UNORM_S8_UINT, PIXEL_FORMAT_D24_UNORM_S8_UINT, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 24, 8 }, { "PIXEL_FORMAT_D32_FLOAT", 32, false, false, false, 0, 0, PIXEL_FORMAT_D32_FLOAT, PIXEL_FORMAT_D32_FLOAT, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 32, 0 }, { "PIXEL_FORMAT_D32_FLOAT_S8X24_UINT", 64, false, false, false, 0, 0, PIXEL_FORMAT_D32_FLOAT_S8X24_UINT, PIXEL_FORMAT_D32_FLOAT_S8X24_UINT, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 32, 8 }, { "PIXEL_FORMAT_R8G8B8_UNORM", 24, true, false, false, 0, 0, PIXEL_FORMAT_R8G8B8_UNORM, PIXEL_FORMAT_R8G8B8_UNORM, 0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000, 24, 0, 0 }, { "PIXEL_FORMAT_B8G8R8_UNORM", 24, true, false, false, 0, 0, PIXEL_FORMAT_B8G8R8_UNORM, PIXEL_FORMAT_B8G8R8_UNORM, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000, 24, 0, 0 }, }; Y_Define_NameTable(NameTables::PixelFormat) Y_NameTable_VEntry(PIXEL_FORMAT_R8_SINT, "R8_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8_UINT, "R8_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8_UNORM, "R8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R8_SNORM, "R8_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8_SINT, "R8G8_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8_UINT, "R8G8_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8_UNORM, "R8G8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8_SNORM, "R8G8_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8A8_SINT, "R8G8B8A8_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, "R8G8B8A8_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R9G9B9E5_SHAREDEXP, "R9G9B9E5_SHAREDEXP") Y_NameTable_VEntry(PIXEL_FORMAT_R10G10B10A2_UINT, "R10G10B10A2_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R10G10B10A2_UNORM, "R10G10B10A2_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R11G11B10_FLOAT, "R11G11B10_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R16_SINT, "R16_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16_UINT, "R16_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16_UNORM, "R16_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16_SNORM, "R16_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16_FLOAT, "R16_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16_SINT, "R16G16_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16_UINT, "R16G16_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16_UNORM, "R16G16_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16_SNORM, "R16G16_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16_FLOAT, "R16G16_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16B16A16_SINT, "R16G16B16A16_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16B16A16_UINT, "R16G16B16A16_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16B16A16_UNORM, "R16G16B16A16_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16B16A16_SNORM, "R16G16B16A16_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_R16G16B16A16_FLOAT, "R16G16B16A16_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R32_SINT, "R32_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32_UINT, "R32_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32_FLOAT, "R32_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32_SINT, "R32G32_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32_UINT, "R32G32_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32_FLOAT, "R32G32_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32_SINT, "R32G32B32_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32_UINT, "R32G32B32_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32_FLOAT, "R32G32B32_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32A32_SINT, "R32G32B32A32_SINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32A32_UINT, "R32G32B32A32_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_B8G8R8A8_UNORM, "B8G8R8A8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB, "B8G8R8A8_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_B8G8R8X8_UNORM, "B8G8R8X8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB, "B8G8R8X8_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_B5G6R5_UNORM, "B5G6R5_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_B5G5R5A1_UNORM, "B5G5R5A1_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC1_UNORM, "BC1_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC1_UNORM_SRGB, "BC1_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_BC2_UNORM, "BC2_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC2_UNORM_SRGB, "BC2_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_BC3_UNORM, "BC3_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC3_UNORM_SRGB, "BC3_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_BC4_UNORM, "BC4_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC4_SNORM, "BC4_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC5_UNORM, "BC5_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC5_SNORM, "BC5_SNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC6H_UF16, "BC6H_UF16") Y_NameTable_VEntry(PIXEL_FORMAT_BC6H_SF16, "BC6H_SF16") Y_NameTable_VEntry(PIXEL_FORMAT_BC7_UNORM, "BC7_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_BC7_UNORM_SRGB, "BC7_UNORM_SRGB") Y_NameTable_VEntry(PIXEL_FORMAT_D16_UNORM, "D16_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_D24_UNORM_S8_UINT, "D24_UNORM_S8_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_D32_FLOAT, "D32_FLOAT") Y_NameTable_VEntry(PIXEL_FORMAT_D32_FLOAT_S8X24_UINT, "D32_FLOAT_S8X24_UINT") Y_NameTable_VEntry(PIXEL_FORMAT_R8G8B8_UNORM, "R8G8B8_UNORM") Y_NameTable_VEntry(PIXEL_FORMAT_B8G8R8_UNORM, "B8G8R8_UNORM") Y_NameTable_End() const char *PixelFormat_GetPixelFormatName(PIXEL_FORMAT Format) { if (Format == PIXEL_FORMAT_UNKNOWN) return "PIXEL_FORMAT_UNKNOWN"; DebugAssert(Format < PIXEL_FORMAT_COUNT); return g_PixelFormatInfo[Format].Name; } const PIXEL_FORMAT_INFO *PixelFormat_GetPixelFormatInfo(PIXEL_FORMAT Format) { DebugAssert(Format < PIXEL_FORMAT_COUNT); return &g_PixelFormatInfo[Format]; } uint32 PixelFormat_CalculateRowPitch(PIXEL_FORMAT Format, uint32 uWidth) { const PIXEL_FORMAT_INFO *pInfo = PixelFormat_GetPixelFormatInfo(Format); if (pInfo->IsBlockCompressed) { uint32 NumBlocksWide = Max((uint32)1, uWidth / pInfo->BlockSize); return NumBlocksWide * pInfo->BytesPerBlock; } else { // ensure 32bit alignment return ((uWidth * pInfo->BitsPerPixel + 31) / 32) * 4; } } uint32 PixelFormat_CalculateSlicePitch(PIXEL_FORMAT Format, uint32 uWidth, uint32 uHeight) { const PIXEL_FORMAT_INFO *pInfo = PixelFormat_GetPixelFormatInfo(Format); if (pInfo->IsBlockCompressed) { uint32 NumBlocksWide = Max((uint32)1, uWidth / pInfo->BlockSize); uint32 NumBlocksHigh = Max((uint32)1, uHeight / pInfo->BlockSize); return NumBlocksWide * pInfo->BytesPerBlock * NumBlocksHigh; } else { // ensure 32bit alignment return ((uWidth * pInfo->BitsPerPixel + 31) / 32) * 4 * uHeight; } } uint32 PixelFormat_CalculateImageSize(PIXEL_FORMAT Format, uint32 uWidth, uint32 uHeight, uint32 uDepth) { return PixelFormat_CalculateSlicePitch(Format, uWidth, uHeight) * uDepth; } Vector4f PixelFormatHelpers::ConvertRGBAToFloat4(uint32 rgba) { union { uint32 alignedRGBA; uint8 pRGBABytes[4]; }; alignedRGBA = rgba; return Vector4f(float(pRGBABytes[0]) / 255.0f, float(pRGBABytes[1]) / 255.0f, float(pRGBABytes[2]) / 255.0f, float(pRGBABytes[3]) / 255.0f); } uint32 PixelFormatHelpers::ConvertFloat4ToRGBA(const Vector4f &rgba) { return ((uint8)Math::Clamp(Math::Truncate(rgba.r * 255.0f), 0, 255)) | ((uint8)Math::Clamp(Math::Truncate(rgba.g * 255.0f), 0, 255) << 8) | ((uint8)Math::Clamp(Math::Truncate(rgba.b * 255.0f), 0, 255) << 16) | ((uint8)Math::Clamp(Math::Truncate(rgba.a * 255.0f), 0, 255) << 24); } void PixelFormat_FlipImageInPlace(void *pPixels, uint32 rowPitch, uint32 rowCount) { DebugAssert(rowPitch > 0 && rowCount > 0); byte *pRows = (byte *)pPixels; // if greater than 64KB, use a malloced buffer byte *pRowBuffer; byte *pHeapBuffer = NULL; if (rowPitch > 65536) pRowBuffer = pHeapBuffer = (byte *)Y_malloc(rowPitch); else pRowBuffer = (byte *)alloca(rowPitch); // divide the rows by 2, we only need to do this many swaps uint32 flipCount = rowCount / 2; uint32 rowCountMinusOne = rowCount - 1; for (uint32 i = 0; i < flipCount; i++) { byte *pRow1 = pRows + (i * rowPitch); byte *pRow2 = pRows + ((rowCountMinusOne - i) * rowPitch); Y_memcpy(pRowBuffer, pRow1, rowPitch); Y_memcpy(pRow1, pRow2, rowPitch); Y_memcpy(pRow2, pRowBuffer, rowPitch); } // free temp buffer Y_free(pHeapBuffer); } void PixelFormat_FlipImage(void *pDestinationPixels, const void *pPixels, uint32 rowPitch, uint32 rowCount) { DebugAssert(rowPitch > 0 && rowCount > 0); const byte *pSourceRows = (const byte *)pPixels; byte *pDestinationRows = (byte *)pDestinationPixels; // divide the rows by 2, we only need to do this many swaps uint32 flipCount = rowCount / 2; uint32 rowCountMinusOne = rowCount - 1; for (uint32 i = 0; i < flipCount; i++) { const byte *pSourceRow1 = pSourceRows + (i * rowPitch); const byte *pSourceRow2 = pSourceRows + ((rowCountMinusOne - i) * rowPitch); byte *pDestinationRow1 = pDestinationRows + (i * rowPitch); byte *pDestinationRow2 = pDestinationRows + ((rowCountMinusOne - i) * rowPitch); Y_memcpy(pDestinationRow1, pSourceRow2, rowPitch); Y_memcpy(pDestinationRow2, pSourceRow1, rowPitch); } // handle the middle line in odd sized images if (flipCount & 1) { uint32 oddIndex = flipCount + 1; const byte *pSourceRow = pSourceRows + (oddIndex * rowPitch); byte *pDestinationRow = pDestinationRows + (oddIndex * rowPitch); Y_memcpy(pDestinationRow, pSourceRow, rowPitch); } } PIXEL_FORMAT PixelFormatHelpers::GetSRGBFormat(PIXEL_FORMAT format) { switch (format) { case PIXEL_FORMAT_R8G8B8A8_UNORM: return PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB; case PIXEL_FORMAT_B8G8R8A8_UNORM: return PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB; case PIXEL_FORMAT_B8G8R8X8_UNORM: return PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB; case PIXEL_FORMAT_BC1_UNORM: return PIXEL_FORMAT_BC1_UNORM_SRGB; case PIXEL_FORMAT_BC2_UNORM: return PIXEL_FORMAT_BC2_UNORM_SRGB; case PIXEL_FORMAT_BC3_UNORM: return PIXEL_FORMAT_BC3_UNORM_SRGB; case PIXEL_FORMAT_BC7_UNORM: return PIXEL_FORMAT_BC7_UNORM_SRGB; } return PIXEL_FORMAT_UNKNOWN; } PIXEL_FORMAT PixelFormatHelpers::GetLinearFormat(PIXEL_FORMAT format) { return PixelFormat_GetPixelFormatInfo(format)->LinearFormat; } bool PixelFormatHelpers::IsSRGBFormat(PIXEL_FORMAT format) { return PixelFormat_GetPixelFormatInfo(format)->LinearFormat != format; } bool PixelFormatHelpers::IsDepthFormat(PIXEL_FORMAT format) { return (format >= PIXEL_FORMAT_D16_UNORM && format <= PIXEL_FORMAT_D32_FLOAT_S8X24_UINT); } Vector3f PixelFormatHelpers::DecodeNormalFromR8G8B8(uint32 rgb) { union { uint32 alignedRGB; uint8 pRGBBytes[4]; }; alignedRGB = rgb; return (Vector3f(float(pRGBBytes[0]) / 255.0f, float(pRGBBytes[1]) / 255.0f, float(pRGBBytes[2]) / 255.0f) - 0.5f) * 2.0f; } uint32 PixelFormatHelpers::EncodeNormalAsRG8B8B8(const Vector3f &normal) { union { uint32 alignedRGB; uint8 pRGBBytes[4]; }; Vector3f positiveNormal(normal * 0.5f + 0.5f); pRGBBytes[0] = (uint8)Math::Clamp(Math::Truncate(normal.x * 255.0f), 0, 255); pRGBBytes[1] = (uint8)Math::Clamp(Math::Truncate(normal.y * 255.0f), 0, 255); pRGBBytes[2] = (uint8)Math::Clamp(Math::Truncate(normal.z * 255.0f), 0, 255); pRGBBytes[3] = 0; return alignedRGB; } Vector3f PixelFormatHelpers::ConvertLinearToSRGB(const Vector3f &color) { //static const float LINEAR_TO_SRGB_EXPONENT = 1.0f / 2.2f; //return Vector3f(Math::Pow(color.x, LINEAR_TO_SRGB_EXPONENT), Math::Pow(color.y, LINEAR_TO_SRGB_EXPONENT), Math::Pow(color.z, LINEAR_TO_SRGB_EXPONENT)); // https://www.opengl.org/registry/specs/EXT/framebuffer_sRGB.txt Vector3f outColor; for (uint32 i = 0; i < 3; i++) { float cs; float cl = color.ele[i]; if (cl <= 0.0f) cs = 0.0f; else if (cl < 0.0031308f) cs = 12.92f * cl; else if (cl < 1.0f) cs = 1.055f * Math::Pow(cl, 0.41666f) - 0.055f; else cs = 1.0f; outColor.ele[i] = cs; } return outColor; } Vector4f PixelFormatHelpers::ConvertLinearToSRGB(const Vector4f &color) { return Vector4f(ConvertLinearToSRGB(color.xyz()), color.w); } Vector3f PixelFormatHelpers::ConvertSRGBToLinear(const Vector3f &color) { //static const float SRGB_TO_LINEAR_EXPONENT = 2.2f; //return Vector3f(Math::Pow(color.x, SRGB_TO_LINEAR_EXPONENT), Math::Pow(color.y, SRGB_TO_LINEAR_EXPONENT), Math::Pow(color.z, SRGB_TO_LINEAR_EXPONENT)); // https://www.opengl.org/registry/specs/EXT/framebuffer_sRGB.txt Vector3f outColor; for (uint32 i = 0; i < 3; i++) { float cl; float cs = color.ele[i]; if (cs <= 0.04045f) cl = cs / 12.92f; else cl = Math::Pow((cs + 0.055f) / 1.055f, 2.4f); outColor.ele[i] = cl; } return outColor; } Vector4f PixelFormatHelpers::ConvertSRGBToLinear(const Vector4f &color) { return Vector4f(ConvertSRGBToLinear(color.xyz()), color.w); } /* Generator code: import math def toLinear(cs): if (cs <= 0.04045): return cs / 12.92 else: return math.pow((cs + 0.055) / 1.055, 2.4) def toSRGB(cl): if (cl <= 0.0): return 0.0 elif (cl < 0.0031308): return 12.92 * cl elif (cl < 1.0): return 1.055 * pow(cl, 0.41666) - 0.055 else: return 1.0 def printLUT(func): line = "" for i in range(0, 256): if (i > 0 and (i % 32) == 0): print(line) line = "" line += str(int(math.floor(func(i / 255.0) * 255.0))) line += ", " print(line) printLUT(toSRGB) printLUT(toLinear) */ uint32 PixelFormatHelpers::ConvertLinearToSRGB(const uint32 rgba) { //return ConvertFloat4ToRGBA(ConvertLinearToSRGB(ConvertRGBAToFloat4(rgba))); // static const uint8 linearToSRGBLUT[256] = { // 0, 20, 28, 33, 38, 42, 46, 49, 52, 55, 58, 61, 63, 65, 68, 70, 72, 74, 76, 78, 80, 81, 83, 85, 87, 88, 90, 91, 93, 94, 96, 97, // 99, 100, 102, 103, 104, 106, 107, 108, 109, 111, 112, 113, 114, 115, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 135, // 136, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 147, 148, 149, 150, 151, 152, 153, 153, 154, 155, 156, 157, 158, 158, 159, 160, 161, 162, 162, // 163, 164, 165, 165, 166, 167, 168, 168, 169, 170, 171, 171, 172, 173, 174, 174, 175, 176, 176, 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, // 186, 187, 187, 188, 189, 189, 190, 190, 191, 192, 192, 193, 194, 194, 195, 196, 196, 197, 197, 198, 199, 199, 200, 200, 201, 202, 202, 203, 203, 204, 205, 205, // 206, 206, 207, 208, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 214, 215, 216, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 222, 222, 223, 223, // 224, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, // 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255 // }; static const uint8 linearToSRGBLUT[256] = { 0, 12, 21, 28, 33, 38, 42, 46, 49, 52, 55, 58, 61, 63, 66, 68, 70, 73, 75, 77, 79, 81, 82, 84, 86, 88, 89, 91, 93, 94, 96, 97, 99, 100, 102, 103, 104, 106, 107, 109, 110, 111, 112, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 151, 152, 153, 154, 155, 156, 157, 157, 158, 159, 160, 161, 161, 162, 163, 164, 165, 165, 166, 167, 168, 168, 169, 170, 171, 171, 172, 173, 174, 174, 175, 176, 176, 177, 178, 179, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, 194, 195, 196, 196, 197, 197, 198, 199, 199, 200, 201, 201, 202, 202, 203, 204, 204, 205, 205, 206, 206, 207, 208, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 237, 238, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 251, 252, 252, 253, 253, 254, 254, 255 }; union { uint32 alignedRGB; uint8 pRGBBytes[4]; }; alignedRGB = rgba; pRGBBytes[0] = linearToSRGBLUT[pRGBBytes[0]]; pRGBBytes[1] = linearToSRGBLUT[pRGBBytes[1]]; pRGBBytes[2] = linearToSRGBLUT[pRGBBytes[2]]; return alignedRGB; } uint32 PixelFormatHelpers::ConvertSRGBToLinear(const uint32 rgba) { //return ConvertFloat4ToRGBA(ConvertSRGBToLinear(rgba)); // static const uint8 sRGBToLinearLUT[256] = { // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, // 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, // 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28, 29, // 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, // 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 90, // 91, 92, 93, 95, 96, 97, 99, 100, 101, 103, 104, 105, 107, 108, 109, 111, 112, 114, 115, 117, 118, 119, 121, 122, 124, 125, 127, 128, 130, 131, 133, 135, // 136, 138, 139, 141, 142, 144, 146, 147, 149, 151, 152, 154, 156, 157, 159, 161, 162, 164, 166, 168, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189, // 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 244, 246, 248, 250, 252, 255 // }; static const uint8 sRGBToLinearLUT[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252, 255 }; union { uint32 alignedRGB; uint8 pRGBBytes[4]; }; alignedRGB = rgba; pRGBBytes[0] = sRGBToLinearLUT[pRGBBytes[0]]; pRGBBytes[1] = sRGBToLinearLUT[pRGBBytes[1]]; pRGBBytes[2] = sRGBToLinearLUT[pRGBBytes[2]]; return alignedRGB; } <file_sep>/Engine/Source/GameFramework/PositionInterpolatorComponent.h #pragma once #include "Engine/Component.h" class PositionInterpolatorComponent : public Component { DECLARE_COMPONENT_TYPEINFO(PositionInterpolatorComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(PositionInterpolatorComponent); public: PositionInterpolatorComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~PositionInterpolatorComponent(); // Property accessors const float GetMoveDuration() const { return m_moveDuration; } const float GetPauseDuration() const { return m_pauseDuration; } const bool GetReverseCycle() const { return m_reverseCycle; } const uint32 GetRepeatCount() const { return m_repeatCount; } const EasingFunction::Type GetEasingFunction() const { return m_easingFunction; } const bool GetAutoActivate() const { return m_autoActivate; } // Property mutators void SetMoveDuration(float moveDuration); void SetPauseDuration(float pauseDuration); void SetReverseCycle(bool autoReverse); void SetRepeatCount(uint32 repeatCount); void SetEasingFunction(EasingFunction::Type easingFunction); void SetAutoActivate(bool autoActivate); // Creator void Create(const float3 &moveVector = float3::UnitZ, float moveDuration = 1.0f, float pauseDuration = 0.0f, bool reverseCycle = true, uint32 repeatCount = 0, EasingFunction::Type easingFunction = EasingFunction::Linear, bool autoActivate = true); // Reset to the initial state void Reset(); // Activate/resume the mover void Activate(); // Deactivate/pause the mover void Deactivate(); // Events virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; virtual void Update(float timeSinceLastUpdate) override; private: float m_moveDuration; float m_pauseDuration; bool m_reverseCycle; uint32 m_repeatCount; EasingFunction::Type m_easingFunction; bool m_autoActivate; bool m_active; Interpolator<float3> m_interpolator; }; <file_sep>/Engine/Source/MathLib/SIMDMatrixi.h #pragma once #include "MathLib/Common.h" // Integer matrix classes only available with SSE2. //#if Y_CPU_SSE_LEVEL >= 2 //#include "MathLib/SIMDMatrixi_sse.h" //#else #include "MathLib/SIMDMatrixi_scalar.h" //#endif <file_sep>/Engine/Source/Engine/ParticleSystemCommon.h #pragma once #include "Engine/Common.h" // Forward declarations of all relevant classes struct ParticleData; class ParticleSystem; class ParticleSystemEmitter; class ParticleSystemModule; // Strictly contains the data of particle instances, as compact as possible struct ParticleData { // Current information float3 Position; float3 Velocity; float Width; float Height; float Rotation; uint32 Color; float2 MinTextureCoordinates; float2 MaxTextureCoordinates; float LifeSpan; float LifeRemaining; // Light information uint8 LightType; uint8 LightParameter; float LightRange; float LightFalloff; }; <file_sep>/Engine/Source/Engine/Physics/RigidBody.h #pragma once #include "Engine/Physics/CollisionObject.h" #include "Engine/Physics/CollisionShape.h" class btRigidBody; namespace Physics { class RigidBody : public CollisionObject { class MotionState; friend class MotionState; public: typedef void(*UpdateTransformCallbackFunction)(void *pUserData, const Transform &newTransform); public: RigidBody(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform); ~RigidBody(); // getters const bool IsMovable() const { return m_isMovable; } const float GetMass() const { return m_mass; } // setters void SetMass(float mass); // apply a force void ApplyCentralImpulse(const float3 &direction); // clear any forces void ResetForces(); // clear any velocity void ResetVelocity(); // callback from when the rigid body is moved void SetCallbackFunction(UpdateTransformCallbackFunction callback, void *pUserData); // overrides virtual void OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; virtual void OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; virtual void OnSynchronize() override; private: virtual btCollisionObject *GetBulletCollisionObject() const override; virtual void OnCollisionShapeChanged() override; virtual void OnTransformChanged() override; // reset the rigid body, i.e. call when the transform is changed or shape changes void ResetRigidBodyState(); bool m_isMovable; float m_mass; MotionState *m_pMotionState; btRigidBody *m_pBulletRigidBody; UpdateTransformCallbackFunction m_updateTransformCallbackFunction; void *m_pUpdateTransformCallbackUserData; }; } // namespace Physics <file_sep>/Editor/Source/Editor/EditorRendererSwapChainWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorRendererSwapChainWidget.h" #include "Editor/EditorHelpers.h" #include "Renderer/Renderer.h" EditorRendererSwapChainWidget::EditorRendererSwapChainWidget(QWidget *pParent, Qt::WindowFlags flags /* = 0 */) : QWidget(pParent, flags | Qt::MSWindowsOwnDC), m_pSwapChain(NULL) { setAttribute(Qt::WA_PaintOnScreen); setAttribute(Qt::WA_NoSystemBackground); RecreateSwapChain(); } EditorRendererSwapChainWidget::~EditorRendererSwapChainWidget() { SAFE_RELEASE(m_pSwapChain); } GPUOutputBuffer *EditorRendererSwapChainWidget::GetSwapChain() const { if (m_pSwapChain == NULL) const_cast<EditorRendererSwapChainWidget *>(this)->RecreateSwapChain(); return m_pSwapChain; } void EditorRendererSwapChainWidget::DestroySwapChain() { if (m_pSwapChain != NULL) { m_pSwapChain->Release(); m_pSwapChain = NULL; } } void EditorRendererSwapChainWidget::RecreateSwapChain() { if (m_pSwapChain != NULL) m_pSwapChain->Release(); m_pSwapChain = g_pRenderer->CreateOutputBuffer(reinterpret_cast<RenderSystemWindowHandle>(winId()), RENDERER_VSYNC_TYPE_NONE); } QPaintEngine *EditorRendererSwapChainWidget::paintEngine() const { return NULL; } void EditorRendererSwapChainWidget::resizeEvent(QResizeEvent *pEvent) { QWidget::resizeEvent(pEvent); GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); ReferenceCountedHolder<GPUOutputBuffer> pOldBuffer = pGPUContext->GetOutputBuffer(); pGPUContext->SetOutputBuffer(m_pSwapChain); if (m_pSwapChain == NULL || !pGPUContext->ResizeOutputBuffer()) RecreateSwapChain(); pGPUContext->SetOutputBuffer(pOldBuffer); ResizedEvent(); } void EditorRendererSwapChainWidget::paintEvent(QPaintEvent *pEvent) { PaintEvent(); } void EditorRendererSwapChainWidget::focusInEvent(QFocusEvent *pEvent) { QWidget::focusInEvent(pEvent); GainedFocusEvent(); } void EditorRendererSwapChainWidget::focusOutEvent(QFocusEvent *pEvent) { QWidget::focusOutEvent(pEvent); LostFocusEvent(); } void EditorRendererSwapChainWidget::keyPressEvent(QKeyEvent *pKeyEvent) { QWidget::keyPressEvent(pKeyEvent); KeyboardEvent(pKeyEvent); } void EditorRendererSwapChainWidget::keyReleaseEvent(QKeyEvent *pKeyEvent) { QWidget::keyReleaseEvent(pKeyEvent); KeyboardEvent(pKeyEvent); } void EditorRendererSwapChainWidget::mouseMoveEvent(QMouseEvent *pMouseEvent) { QWidget::mouseMoveEvent(pMouseEvent); MouseEvent(pMouseEvent); } void EditorRendererSwapChainWidget::mousePressEvent(QMouseEvent *pMouseEvent) { QWidget::mousePressEvent(pMouseEvent); MouseEvent(pMouseEvent); } void EditorRendererSwapChainWidget::mouseReleaseEvent(QMouseEvent *pMouseEvent) { QWidget::mouseReleaseEvent(pMouseEvent); MouseEvent(pMouseEvent); } void EditorRendererSwapChainWidget::wheelEvent(QWheelEvent *pWheelEvent) { QWidget::wheelEvent(pWheelEvent); WheelEvent(pWheelEvent); } void EditorRendererSwapChainWidget::dropEvent(QDropEvent *pDropEvent) { QWidget::dropEvent(pDropEvent); DropEvent(pDropEvent); } <file_sep>/Engine/Source/Renderer/Shaders/OverlayShader.h #pragma once #include "Renderer/ShaderComponent.h" class GPUTexture; class Texture; class ShaderProgram; class OverlayShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(OverlayShader, ShaderComponent); public: struct Vertex2D { float2 Position; float2 TexCoord; uint32 Color; Vertex2D() {} Vertex2D(const Vertex2D &v) { Y_memcpy(this, &v, sizeof(*this)); } Vertex2D(const float2 &position, const float2 &texcoord, uint32 color) : Position(position), TexCoord(texcoord), Color(color) {} Vertex2D(float x, float y, float u, float v, uint32 color) : Position(x, y), TexCoord(u, v), Color(color) {} void Set(float x, float y, float u, float v, uint32 color) { Position.Set(x, y); TexCoord.Set(u, v); Color = color; } void Set(float x, float y, float u, float v, uint32 r, uint32 g, uint32 b, uint32 a) { Set(x, y, u, v, MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a)); } void Set(float x, float y, float u, float v, float r, float g, float b, float a) { Set(x, y, u, v, PixelFormatHelpers::ConvertFloat4ToRGBA(float4(r, g, b, a))); } void Set(const float2 &position, const float2 &texcoord, uint32 color) { Position = position; TexCoord = texcoord; Color = color; } void Set(const float2 &position, const float2 &texcoord, const float4 &color) { Position = position; TexCoord = texcoord; Color = PixelFormatHelpers::ConvertFloat4ToRGBA(color); } void SetColor(float x, float y, uint32 color) { Set(x, y, 0.0f, 0.0f, color); } void SetColor(float x, float y, uint32 r, uint32 g, uint32 b, uint32 a) { Set(x, y, 0.0f, 0.0f, r, g, b, a); } void SetColor(float x, float y, float r, float g, float b, float a) { Set(x, y, 0.0f, 0.0f, r, g, b, a); } void SetColor(const float2 &position, uint32 color) { Set(position, float2::Zero, color); } void SetColor(const float2 &position, const float4 &color) { Set(position, float2::Zero, color); } void SetUV(float x, float y, float u, float v) { Set(x, y, u, v, 0xFFFFFFFF); } void SetUV(const float2 &position, const float2 &uv) { Set(position, uv, 0xFFFFFFFF); } // skip float comparisons bool operator==(const Vertex2D &v) const { return (Y_memcmp(this, &v, sizeof(*this)) == 0); } bool operator!=(const Vertex2D &v) const { return (Y_memcmp(this, &v, sizeof(*this)) != 0); } }; struct Vertex3D { float3 Position; float2 TexCoord; uint32 Color; Vertex3D() {} Vertex3D(const Vertex3D &v) { Y_memcpy(this, &v, sizeof(*this)); } Vertex3D(const float3 &position, const float2 &texcoord, uint32 color) : Position(position), TexCoord(texcoord), Color(color) {} Vertex3D(float x, float y, float z, float u, float v, uint32 color) : Position(x, y, z), TexCoord(u, v), Color(color) {} void Set(float x, float y, float z, float u, float v, uint32 color) { Position.Set(x, y, z); TexCoord.Set(u, v); Color = color; } void Set(float x, float y, float z, float u, float v, uint32 r, uint32 g, uint32 b, uint32 a) { Set(x, y, z, u, v, MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a)); } void Set(float x, float y, float z, float u, float v, float r, float g, float b, float a) { Set(x, y, z, u, v, PixelFormatHelpers::ConvertFloat4ToRGBA(float4(r, g, b, a))); } void Set(const float3 &position, const float2 &texcoord, uint32 color) { Position = position; TexCoord = texcoord; Color = color; } void Set(const float3 &position, const float2 &texcoord, const float4 &color) { Position = position; TexCoord = texcoord; Color = PixelFormatHelpers::ConvertFloat4ToRGBA(color); } void SetColor(float x, float y, float z, uint32 color) { Set(x, y, z, 0.0f, 0.0f, color); } void SetColor(float x, float y, float z, uint32 r, uint32 g, uint32 b, uint32 a) { Set(x, y, z, 0.0f, 0.0f, r, g, b, a); } void SetColor(float x, float y, float z, float r, float g, float b, float a) { Set(x, y, z, 0.0f, 0.0f, r, g, b, a); } void SetColor(const float3 &position, uint32 color) { Set(position, float2::Zero, color); } void SetColor(const float3 &position, const float4 &color) { Set(position, float2::Zero, color); } void SetUV(float x, float y, float z, float u, float v) { Set(x, y, z, u, v, 0xFFFFFFFF); } void SetUV(const float3 &position, const float2 &uv) { Set(position, uv, 0xFFFFFFFF); } // skip float comparisons bool operator==(const Vertex3D &v) const { return (Y_memcmp(this, &v, sizeof(*this)) == 0); } bool operator!=(const Vertex3D &v) const { return (Y_memcmp(this, &v, sizeof(*this)) != 0); } }; public: enum FLAGS { WITH_3D_VERTEX = (1 << 0), WITH_TEXTURE = (1 << 1), }; public: OverlayShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) {} static void SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture *pTexture); static void SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, Texture *pTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/Core/DDSReader.cpp #include "Core/PrecompiledHeader.h" #include "Core/DDSReader.h" #include "Core/DDSFormat.h" #include "YBaseLib/Log.h" #include "YBaseLib/Math.h" Log_SetChannel(DDSReader); static const PIXEL_FORMAT DDSDXGIFormatToPixelFormat[DDS_DXGI_FORMAT_COUNT] = { PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_UNKNOWN PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32A32_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32A32_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32A32_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32A32_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32B32_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16B16A16_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G32_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32G8X24_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_D32_FLOAT_S8X24_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_X32_TYPELESS_G8X24_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R10G10B10A2_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R10G10B10A2_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R10G10B10A2_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R11G11B10_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8B8A8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8B8A8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8B8A8_UINT PIXEL_FORMAT_R8G8B8A8_SNORM, // DDS_DXGI_FORMAT_R8G8B8A8_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8B8A8_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16G16_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_D32_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R32_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R24G8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_D24_UNORM_S8_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R24_UNORM_X8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_X24_TYPELESS_G8_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_FLOAT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_D16_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R16_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8_UINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8_SINT PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_A8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R1_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R9G9B9E5_SHAREDEXP PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R8G8_B8G8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_G8R8_G8B8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC1_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC1_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC1_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC2_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC2_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC2_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC3_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC3_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC3_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC4_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC4_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC4_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC5_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC5_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC5_SNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B5G6R5_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B5G5R5A1_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8A8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8X8_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8A8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8A8_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8X8_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_B8G8R8X8_UNORM_SRGB PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC6H_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC6H_UF16 PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC6H_SF16 PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC7_TYPELESS PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC7_UNORM PIXEL_FORMAT_UNKNOWN, // DDS_DXGI_FORMAT_BC7_UNORM_SRGB }; DDSReader::DDSReader() { m_pStream = NULL; m_eTextureType = DDS_TEXTURE_TYPE_UNKNOWN; m_iWidth = m_iHeight = m_iDepth = 0; m_nMipLevels = 0; m_iArraySize = 0; m_ePixelFormat = PIXEL_FORMAT_UNKNOWN; m_pMipLevels = NULL; } DDSReader::~DDSReader() { Close(); } DDS_TEXTURE_TYPE DDSReader::GetStreamDDSTextureType(const char *FileName, ByteStream *pStream) { uint32 Magic; DDS_HEADER Header; DDS_TEXTURE_TYPE TextureType = DDS_TEXTURE_TYPE_UNKNOWN; // save current offset uint64 saveStreamOffset = pStream->GetPosition(); // read header if (!pStream->Read2(&Magic, sizeof(Magic)) || Magic != DDS_MAGIC || !pStream->Read2(&Header, sizeof(Header)) || Header.dwSize < sizeof(DDS_HEADER) || (Header.dwSize > sizeof(DDS_HEADER) && !pStream->SeekRelative(Header.dwSize - sizeof(DDS_HEADER)))) { Log_ErrorPrintf("DDSLoader::GetStreamDDSTextureType: \"%s\" Could not read header, or it is invalid.", FileName); goto CLEANUP; } if ((Header.dwFlags & (DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH)) != (DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH)) Log_WarningPrintf("DDSLoader::GetStreamDDSTextureType: \"%s\" Missing some required flags, results may be unpredictible.", FileName); if (Header.dwFlags & (DDSD_PITCH | DDSD_LINEARSIZE)) Log_WarningPrintf("DDSLoader::GetStreamDDSTextureType: \"%s\" Loading images with pitch/linearsize currently unsupported. Image may be corrupted.", FileName); // determine texture type if (Header.dwFlags & DDSD_HEIGHT) { if (Header.dwFlags & DDSD_DEPTH) TextureType = DDS_TEXTURE_TYPE_3D; else if (Header.dwCaps2 & DDSCAPS2_CUBEMAP) TextureType = DDS_TEXTURE_TYPE_CUBE; else TextureType = DDS_TEXTURE_TYPE_2D; } else { TextureType = DDS_TEXTURE_TYPE_1D; } // handle dx10 header if (Header.ddspf.dwFlags == DDS_FOURCC && Header.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', '1', '0')) { DDS_HEADER_DXT10 DX10Header; if (pStream->Read(&DX10Header, sizeof(DX10Header)) != sizeof(DX10Header)) { Log_ErrorPrintf("DDSLoader::GetStreamDDSTextureType: \"%s\" has fourcc DX10 but no DX10 header.", FileName); goto CLEANUP; } // copy from dx10 header if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE1D) TextureType = DDS_TEXTURE_TYPE_1D; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE2D && DX10Header.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE) TextureType = DDS_TEXTURE_TYPE_CUBE; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE2D) TextureType = DDS_TEXTURE_TYPE_2D; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE3D) TextureType = DDS_TEXTURE_TYPE_3D; else { Log_ErrorPrintf("DDSLoader::GetStreamDDSTextureType: \"%s\" invalid resource dimension (%u) in DX10 header.", FileName, DX10Header.resourceDimension); goto CLEANUP; } } CLEANUP: pStream->SeekAbsolute(saveStreamOffset); return TextureType; } bool DDSReader::Open(const char *FileName, ByteStream *pStream) { uint32 Magic; DDS_HEADER Header; uint32 nImages; uint32 currentFilePosition; uint32 fileSize; if (!pStream->Read2(&Magic, sizeof(Magic)) || Magic != DDS_MAGIC || !pStream->Read2(&Header, sizeof(Header)) || Header.dwSize < sizeof(DDS_HEADER) || !pStream->SeekAbsolute(sizeof(Magic) + Header.dwSize)) { Log_ErrorPrintf("DDSLoader::Open: \"%s\" Could not read header, or it is invalid.", FileName); goto FAILURE; } if ((Header.dwFlags & (DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH)) != (DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH)) Log_WarningPrintf("DDSLoader::Open: \"%s\" Missing some required flags, results may be unpredictible.", FileName); if (Header.dwFlags & (DDSD_PITCH | DDSD_LINEARSIZE)) Log_WarningPrintf("DDSLoader::Open: \"%s\" Loading images with pitch/linearsize currently unsupported. Image may be corrupted.", FileName); // determine texture type if (Header.dwFlags & DDSD_HEIGHT) { DebugAssert(!(Header.dwFlags & DDSD_DEPTH)); if (Header.dwFlags & DDSD_DEPTH) m_eTextureType = DDS_TEXTURE_TYPE_3D; else if (Header.dwCaps2 & DDSCAPS2_CUBEMAP) m_eTextureType = DDS_TEXTURE_TYPE_CUBE; else m_eTextureType = DDS_TEXTURE_TYPE_2D; } else { m_eTextureType = DDS_TEXTURE_TYPE_1D; } // determine dimensions m_iWidth = Header.dwWidth; m_iHeight = (m_eTextureType == DDS_TEXTURE_TYPE_1D) ? 1 : Header.dwHeight; m_iDepth = (m_eTextureType != DDS_TEXTURE_TYPE_3D) ? 1 : Header.dwDepth; m_iArraySize = (m_eTextureType == DDS_TEXTURE_TYPE_CUBE) ? 6 : 1; m_nMipLevels = ((Header.dwFlags & DDSD_MIPMAPCOUNT) != 0) ? Header.dwMipMapCount : 1; // determine pixel format m_ePixelFormat = PIXEL_FORMAT_UNKNOWN; if (Header.ddspf.dwFlags == DDS_FOURCC) { if (Header.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '1')) m_ePixelFormat = PIXEL_FORMAT_BC1_UNORM; else if (Header.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '3')) m_ePixelFormat = PIXEL_FORMAT_BC2_UNORM; else if (Header.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '5')) m_ePixelFormat = PIXEL_FORMAT_BC3_UNORM; else if (Header.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', '1', '0')) { DDS_HEADER_DXT10 DX10Header; if (pStream->Read(&DX10Header, sizeof(DX10Header)) != sizeof(DX10Header)) { Log_ErrorPrintf("DDSLoader::Open: \"%s\" has fourcc DX10 but no DX10 header.", FileName); goto FAILURE; } // copy from dx10 header if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE1D) m_eTextureType = DDS_TEXTURE_TYPE_1D; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE2D && DX10Header.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE) m_eTextureType = DDS_TEXTURE_TYPE_CUBE; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE2D) m_eTextureType = DDS_TEXTURE_TYPE_2D; else if (DX10Header.resourceDimension == DDS_RESOURCE_DIMENSION_TEXTURE3D) m_eTextureType = DDS_TEXTURE_TYPE_3D; else { Log_ErrorPrintf("DDSLoader::Open: \"%s\" invalid resource dimension (%u) in DX10 header.", FileName, DX10Header.resourceDimension); goto FAILURE; } m_iArraySize = DX10Header.arraySize; if (DX10Header.dxgiFormat >= DDS_DXGI_FORMAT_COUNT || DDSDXGIFormatToPixelFormat[DX10Header.dxgiFormat] == PIXEL_FORMAT_UNKNOWN) { Log_ErrorPrintf("DDSLoader::Open: \"%s\" invalid dxgi format (%u) in DX10 header.", FileName, DX10Header.dxgiFormat); goto FAILURE; } m_ePixelFormat = DDSDXGIFormatToPixelFormat[DX10Header.dxgiFormat]; } } else { for (uint32 i = 0; i < PIXEL_FORMAT_COUNT; i++) { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo((PIXEL_FORMAT)i); if (pPixelFormatInfo->BitsPerPixel != Header.ddspf.dwRGBBitCount) continue; if (pPixelFormatInfo->ColorMaskAlpha != 0 && pPixelFormatInfo->ColorMaskRed != 0 && pPixelFormatInfo->ColorMaskGreen != 0 && pPixelFormatInfo->ColorMaskBlue != 0 && Header.ddspf.dwFlags == DDS_RGBA) { if (Header.ddspf.dwRBitMask == pPixelFormatInfo->ColorMaskRed && Header.ddspf.dwGBitMask == pPixelFormatInfo->ColorMaskGreen && Header.ddspf.dwBBitMask == pPixelFormatInfo->ColorMaskBlue && Header.ddspf.dwABitMask == pPixelFormatInfo->ColorMaskAlpha) { m_ePixelFormat = (PIXEL_FORMAT)i; break; } } else if (pPixelFormatInfo->ColorMaskAlpha == 0 && pPixelFormatInfo->ColorMaskRed != 0 && pPixelFormatInfo->ColorMaskGreen != 0 && pPixelFormatInfo->ColorMaskBlue != 0 && Header.ddspf.dwFlags == DDS_RGB) { if (Header.ddspf.dwRBitMask == pPixelFormatInfo->ColorMaskRed && Header.ddspf.dwGBitMask == pPixelFormatInfo->ColorMaskGreen && Header.ddspf.dwBBitMask == pPixelFormatInfo->ColorMaskBlue) { m_ePixelFormat = (PIXEL_FORMAT)i; break; } } else if (pPixelFormatInfo->ColorMaskAlpha == 0 && pPixelFormatInfo->ColorMaskRed != 0 && pPixelFormatInfo->ColorMaskGreen == 0 && pPixelFormatInfo->ColorMaskBlue == 0 && Header.ddspf.dwFlags == DDS_LUMINANCE) { if (Header.ddspf.dwRBitMask == pPixelFormatInfo->ColorMaskRed) { m_ePixelFormat = (PIXEL_FORMAT)i; break; } } else if (pPixelFormatInfo->ColorMaskAlpha != 0 && pPixelFormatInfo->ColorMaskRed == 0 && pPixelFormatInfo->ColorMaskGreen == 0 && pPixelFormatInfo->ColorMaskBlue == 0 && Header.ddspf.dwFlags == DDS_ALPHA) { if (Header.ddspf.dwABitMask == pPixelFormatInfo->ColorMaskAlpha) { m_ePixelFormat = (PIXEL_FORMAT)i; break; } } } } if (m_ePixelFormat == PIXEL_FORMAT_UNKNOWN) { Log_ErrorPrintf("DDSLoader::Open: \"%s\" Could not determine pixel format.", FileName); goto FAILURE; } if (!Y_ispow2(m_iWidth) || ((m_eTextureType == DDS_TEXTURE_TYPE_2D || m_eTextureType == DDS_TEXTURE_TYPE_3D || m_eTextureType == DDS_TEXTURE_TYPE_CUBE) && !Y_ispow2(m_iHeight)) || (m_eTextureType == DDS_TEXTURE_TYPE_3D && !Y_ispow2(m_iDepth))) { Log_ErrorPrintf("DDSLoader::Open: \"%s\" Texture dimensions (%u * %u * %u * %u) failed validation.", FileName, m_iWidth, m_iHeight, m_iDepth, m_iArraySize); goto FAILURE; } // check number of miplevels if (m_nMipLevels > 1) { uint32 mw = m_iWidth; uint32 mh = m_iHeight; uint32 md = m_iDepth; uint32 nCalculatedMips = 0; for ( ; ; ) { nCalculatedMips++; if (mw == 1 && mh == 1 && md == 1) break; if (mw > 1) mw /= 2; if (mh > 1) mh /= 2; if (md > 1) md /= 2; } if (nCalculatedMips != m_nMipLevels) { Log_WarningPrintf("DDSLoader::Open: \"%s\" file has an incorrect number of mipmaps (us %u, file %u), disabling all but first.", FileName, nCalculatedMips, m_nMipLevels); m_nMipLevels = 1; } } // allocate miplevels nImages = m_nMipLevels * m_iArraySize; m_pMipLevels = new MipLevelData[nImages]; Y_memzero(m_pMipLevels, sizeof(MipLevelData) * nImages); // fill miplevels currentFilePosition = (uint32)pStream->GetPosition(); fileSize = (uint32)pStream->GetSize(); for (uint32 i = 0; i < m_iArraySize; i++) { uint32 currentMipWidth = m_iWidth; uint32 currentMipHeight = m_iHeight; uint32 currentMipDepth = m_iDepth; for (uint32 j = 0; j < m_nMipLevels; j++) { MipLevelData *pMipLevel = &m_pMipLevels[i * m_nMipLevels + j]; pMipLevel->Size = PixelFormat_CalculateImageSize(m_ePixelFormat, currentMipWidth, currentMipHeight, 1); pMipLevel->Pitch = PixelFormat_CalculateRowPitch(m_ePixelFormat, currentMipWidth); pMipLevel->OffsetInFile = currentFilePosition; pMipLevel->pData = NULL; currentFilePosition += pMipLevel->Size; if (currentFilePosition > fileSize) { Log_WarningPrintf("DDSLoader::Open: \"%s\" image data is larger than file (current offset: %u, file size: %u).", FileName, currentFilePosition, fileSize); goto FAILURE; } if (currentMipWidth > 1) currentMipWidth /= 2; if (currentMipHeight > 1) currentMipHeight /= 2; if (currentMipDepth > 1) currentMipDepth /= 2; } } // set remaining fields m_strFileName = FileName; m_pStream = pStream; pStream->AddRef(); Log_DevPrintf("\"%s\": %u mip levels, %u array textures, mip level 0 is %u x %u x %u", FileName, m_nMipLevels, m_iArraySize, m_iWidth, m_iHeight, m_iDepth); return true; FAILURE: Close(); return false; } bool DDSReader::LoadMipLevel(uint32 MipLevel) { uint32 i; DebugAssert(MipLevel < m_nMipLevels); for (i = 0; i < m_iArraySize; i++) { MipLevelData *pMipLevel = &m_pMipLevels[i * m_nMipLevels + MipLevel]; if (pMipLevel->pData == NULL) { pMipLevel->pData = new byte[pMipLevel->Size]; if (!m_pStream->SeekAbsolute(pMipLevel->OffsetInFile) || !m_pStream->Read2(pMipLevel->pData, pMipLevel->Size)) { Log_ErrorPrintf("DDSLoader::LoadMipLevel: \"%s\" failed to read arrayindex %u miplevel %u.", m_strFileName.GetCharArray(), i, MipLevel); delete[] pMipLevel->pData; pMipLevel->pData = NULL; return false; } } } return true; } bool DDSReader::LoadAllMipLevels() { uint32 i, j; for (i = 0; i < m_iArraySize; i++) { for (j = 0; j < m_nMipLevels; j++) { MipLevelData *pMipLevel = &m_pMipLevels[i * m_nMipLevels + j]; if (pMipLevel->pData == NULL) { pMipLevel->pData = new byte[pMipLevel->Size]; if (!m_pStream->SeekAbsolute(pMipLevel->OffsetInFile) || !m_pStream->Read2(pMipLevel->pData, pMipLevel->Size)) { Log_ErrorPrintf("DDSLoader::LoadAllMipLevels: \"%s\" failed to read arrayindex %u miplevel %u.", m_strFileName.GetCharArray(), i, j); delete[] pMipLevel->pData; pMipLevel->pData = NULL; return false; } } } } return true; } void DDSReader::Close() { FreeMipLevels(); m_strFileName.Clear(); SAFE_RELEASE(m_pStream); m_eTextureType = DDS_TEXTURE_TYPE_UNKNOWN; m_iWidth = m_iHeight = m_iDepth = 0; m_nMipLevels = 0; m_iArraySize = 0; m_ePixelFormat = PIXEL_FORMAT_UNKNOWN; } const DDSReader::MipLevelData *DDSReader::_GetMipLevel(uint32 ArrayIndex, uint32 MipLevel) const { DebugAssert(ArrayIndex < m_iArraySize); return &m_pMipLevels[ArrayIndex * m_nMipLevels + MipLevel]; } void DDSReader::FreeMipLevels() { uint32 i; if (m_pMipLevels != NULL) { for (i = 0; i < m_nMipLevels; i++) { if (m_pMipLevels[i].pData != NULL) delete[] m_pMipLevels[i].pData; } delete[] m_pMipLevels; m_pMipLevels = NULL; } } <file_sep>/Engine/Source/D3D11Renderer/D3D11RenderBackend.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUBuffer.h" #include "D3D11Renderer/D3D11GPUOutputBuffer.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "Engine/EngineCVars.h" #include "Engine/SDLHeaders.h" Log_SetChannel(D3D11Renderer); // d3d11 libraries #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "uxtheme.lib") bool D3D11RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppContext, GPUOutputBuffer **ppOutputBuffer) { HRESULT hResult; // select formats DXGI_FORMAT swapChainBackBufferFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pCreateParameters->BackBufferFormat); DXGI_FORMAT swapChainDepthStencilBufferFormat = (pCreateParameters->DepthStencilBufferFormat != PIXEL_FORMAT_UNKNOWN) ? D3D11TypeConversion::PixelFormatToDXGIFormat(pCreateParameters->DepthStencilBufferFormat) : DXGI_FORMAT_UNKNOWN; if (swapChainBackBufferFormat == DXGI_FORMAT_UNKNOWN || (pCreateParameters->DepthStencilBufferFormat != PIXEL_FORMAT_UNKNOWN && swapChainDepthStencilBufferFormat == DXGI_FORMAT_UNKNOWN)) { Log_ErrorPrintf("D3D11RenderBackend::Create: Invalid swap chain format (%s / %s)", NameTable_GetNameString(NameTables::PixelFormat, pCreateParameters->BackBufferFormat), NameTable_GetNameString(NameTables::PixelFormat, pCreateParameters->DepthStencilBufferFormat)); return false; } // determine driver type D3D_DRIVER_TYPE driverType; if (CVars::r_d3d11_force_ref.GetBool()) driverType = D3D_DRIVER_TYPE_REFERENCE; else if (CVars::r_d3d11_force_warp.GetBool()) driverType = D3D_DRIVER_TYPE_WARP; else driverType = D3D_DRIVER_TYPE_HARDWARE; // feature levels D3D_FEATURE_LEVEL acquiredFeatureLevel; static const D3D_FEATURE_LEVEL requestedFeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; // device flags UINT deviceFlags = 0; if (CVars::r_use_debug_device.GetBool()) { Log_PerfPrintf("Creating a debug Direct3D 11 device, performance will suffer as a result."); deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; } // create the device ID3D11Device *pD3DDevice; ID3D11DeviceContext *pD3DImmediateContext; hResult = D3D11CreateDevice(nullptr, driverType, nullptr, deviceFlags, requestedFeatureLevels, countof(requestedFeatureLevels), D3D11_SDK_VERSION, &pD3DDevice, &acquiredFeatureLevel, &pD3DImmediateContext); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11RenderBackend::Create: Could not create D3D11 device: %08X.", hResult); return false; } // logging Log_DevPrintf("D3D11RenderBackend::Create: Returned a device with feature level %s.", D3D11TypeConversion::D3DFeatureLevelToString(acquiredFeatureLevel)); // test feature levels RENDERER_FEATURE_LEVEL featureLevel; TEXTURE_PLATFORM texturePlatform; if (acquiredFeatureLevel == D3D_FEATURE_LEVEL_10_0 || acquiredFeatureLevel == D3D_FEATURE_LEVEL_10_1) { featureLevel = RENDERER_FEATURE_LEVEL_SM4; texturePlatform = TEXTURE_PLATFORM_DXTC; } else if (acquiredFeatureLevel == D3D_FEATURE_LEVEL_11_0) { featureLevel = RENDERER_FEATURE_LEVEL_SM5; texturePlatform = TEXTURE_PLATFORM_DXTC; } else { Log_ErrorPrintf("D3D11RenderBackend::Create: Returned a device with an unusable feature level: %s (%08X)", D3D11TypeConversion::D3DFeatureLevelToString(acquiredFeatureLevel), acquiredFeatureLevel); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // retrieve handles to DXGI from the created device IDXGIFactory *pDXGIFactory; IDXGIAdapter *pDXGIAdapter; { // get a temporary handle to the dxgi device interface IDXGIDevice *pDXGIDevice; hResult = pD3DDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void **>(&pDXGIDevice)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11RenderBackend::Create: Could not get DXGI device from D3D11 device.", hResult); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // get the adapter from this hResult = pDXGIDevice->GetAdapter(&pDXGIAdapter); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11RenderBackend::Create: Could not get DXGI adapter from device.", hResult); pDXGIAdapter->Release(); pDXGIDevice->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // get the parent of the adapter (factory) hResult = pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void **>(&pDXGIFactory)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11RenderBackend::Create: Could not get DXGI factory from device.", hResult); pDXGIAdapter->Release(); pDXGIDevice->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // dxgi device is no longer needed pDXGIDevice->Release(); } // print device name { // get adapter desc DXGI_ADAPTER_DESC DXGIAdapterDesc; hResult = pDXGIAdapter->GetDesc(&DXGIAdapterDesc); DebugAssert(hResult == S_OK); char deviceName[128]; WideCharToMultiByte(CP_ACP, 0, DXGIAdapterDesc.Description, -1, deviceName, countof(deviceName), NULL, NULL); Log_InfoPrintf("D3D11RenderBackend using DXGI Adapter: %s.", deviceName); Log_InfoPrintf("Texture Platform: %s", NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); } // check for threading support D3D11_FEATURE_DATA_THREADING threadingFeatureData; if (FAILED(hResult = pD3DDevice->CheckFeatureSupport(D3D11_FEATURE_THREADING, &threadingFeatureData, sizeof(threadingFeatureData)))) { Log_ErrorPrintf("D3D11RenderBackend::Create: CheckFeatureSupport(D3D11_FEATURE_THREADING) failed with hResult %08X", hResult); pDXGIFactory->Release(); pDXGIAdapter->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // cap warnings if (threadingFeatureData.DriverConcurrentCreates != TRUE) Log_WarningPrint("Direct3D device driver does not support concurrent resource creation. This may cause some stuttering during streaming."); // get the 11.1 device ID3D11Device1 *pD3DDevice1 = nullptr; if (CVars::r_d3d11_use_11_1.GetBool()) { if (FAILED(hResult = pD3DDevice->QueryInterface(&pD3DDevice1))) Log_WarningPrintf("Failed to retrieve ID3D11Device1 interface with hResult %08X. 11.1 features will not be used.", hResult); else Log_InfoPrintf("Using Direct3D 11.1 features."); } // create device wrapper class D3D11GPUDevice *pGPUDevice = new D3D11GPUDevice(pDXGIFactory, pDXGIAdapter, pD3DDevice, pD3DDevice1, acquiredFeatureLevel, featureLevel, texturePlatform, swapChainBackBufferFormat, swapChainDepthStencilBufferFormat); // create context wrapper class D3D11GPUContext *pGPUContext = new D3D11GPUContext(pGPUDevice, pD3DDevice, pD3DDevice1, pD3DImmediateContext); if (!pGPUContext->Create()) { SAFE_RELEASE(pD3DDevice1); pDXGIFactory->Release(); pDXGIAdapter->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // create implicit swap chain GPUOutputBuffer *pOutputBuffer = nullptr; if (pSDLWindow != nullptr) { // pass through to normal method pOutputBuffer = pGPUDevice->CreateOutputBuffer(pSDLWindow, pCreateParameters->ImplicitSwapChainVSyncType); if (pOutputBuffer == nullptr) { pGPUContext->Release(); pGPUDevice->Release(); SAFE_RELEASE(pD3DDevice1); pDXGIFactory->Release(); pDXGIAdapter->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); return false; } // bind to context pGPUContext->SetOutputBuffer(pOutputBuffer); } // release d3d references SAFE_RELEASE(pD3DDevice1); pDXGIFactory->Release(); pDXGIAdapter->Release(); pD3DImmediateContext->Release(); pD3DDevice->Release(); // set pointers *ppDevice = pGPUDevice; *ppContext = pGPUContext; *ppOutputBuffer = pOutputBuffer; Log_InfoPrint("D3D11 render backend creation successful."); return true; } <file_sep>/Editor/Source/Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.h" #include "Editor/SkeletalAnimationEditor/ui_EditorSkeletalAnimationEditor.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderProxies/SkeletalMeshRenderProxy.h" #include "Renderer/Renderer.h" #include "Engine/ResourceManager.h" #include "Engine/Engine.h" #include "Engine/SkeletalAnimation.h" #include "Engine/SkeletalMesh.h" #include "ResourceCompiler/SkeletalAnimationGenerator.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "Editor/EditorLightSimulator.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorProgressDialog.h" #include "Editor/EditorResourceSaveDialog.h" #include "Editor/EditorResourceSelectionDialog.h" #include "Editor/Editor.h" Log_SetChannel(EditorSkeletalAnimationEditor); EditorSkeletalAnimationEditor::EditorSkeletalAnimationEditor() : m_ui(new Ui_EditorSkeletalAnimationEditor()), m_renderMode(EDITOR_RENDER_MODE_FULLBRIGHT), m_viewportFlags(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS), m_pGenerator(nullptr), m_pSkeleton(nullptr), m_pPreviewMesh(nullptr), m_duration(0.0f), m_previewFrameNumber(0), m_selectedBoneIndex(Y_UINT32_MAX), m_pRenderWorld(new RenderWorld()), m_pLightSimulator(new EditorLightSimulator(0, m_pRenderWorld)), m_pPreviewMeshRenderProxy(nullptr), m_pSwapChain(nullptr), m_pWorldRenderer(nullptr), m_bHardwareResourcesCreated(false), m_bRedrawPending(true), m_lastMousePosition(int2::Zero), m_currentTool(Tool_Information), m_currentState(State_None) { // create ui m_ui->CreateUI(this); m_ui->UpdateUIForCameraMode(m_viewController.GetCameraMode()); m_ui->UpdateUIForRenderMode(m_renderMode); m_ui->UpdateUIForViewportFlags(m_viewportFlags); m_ui->UpdateUIForTool(m_currentTool); // connect events ConnectUIEvents(); // fixup dimensions m_viewController.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); m_guiContext.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); // setup world //m_pCollisionShapePreviewRenderProxy->SetVisibility(false); //m_pRenderWorld->AddRenderable(m_pMeshPreviewRenderProxy); //m_pRenderWorld->AddRenderable(m_pCollisionShapePreviewRenderProxy); } EditorSkeletalAnimationEditor::~EditorSkeletalAnimationEditor() { } void EditorSkeletalAnimationEditor::SetCameraMode(EDITOR_CAMERA_MODE cameraMode) { DebugAssert(cameraMode < EDITOR_CAMERA_MODE_COUNT); m_viewController.SetCameraMode(cameraMode); m_ui->UpdateUIForCameraMode(cameraMode); } void EditorSkeletalAnimationEditor::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } // update state m_renderMode = renderMode; m_ui->UpdateUIForRenderMode(renderMode); delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); FlagForRedraw(); // update ui } void EditorSkeletalAnimationEditor::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorSkeletalAnimationEditor::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorSkeletalAnimationEditor::SetCurrentTool(Tool tool) { m_ui->UpdateUIForTool(tool); if (m_currentTool == tool) return; m_currentTool = tool; // redraw FlagForRedraw(); } bool EditorSkeletalAnimationEditor::Load(const char *animationName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { // find the filename, and open it PathString fileName; fileName.Format("%s.ska.xml", animationName); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { pProgressCallbacks->DisplayFormattedModalError("Could not open file '%s'", fileName.GetCharArray()); return false; } SkeletalAnimationGenerator *pGenerator = new SkeletalAnimationGenerator(); if (!pGenerator->LoadFromXML(fileName, pStream)) { pProgressCallbacks->DisplayFormattedModalError("Could not parse file '%s'", fileName.GetCharArray()); delete pGenerator; return false; } // load skeleton m_pSkeleton = g_pResourceManager->GetSkeleton(pGenerator->GetSkeletonName()); if (m_pSkeleton == nullptr) { pProgressCallbacks->DisplayFormattedModalError("Failed to load referenced skeleton '%s'", m_pGenerator->GetSkeletonName().GetCharArray()); return false; } // allocate transforms m_previewBoneTransforms.Resize(m_pSkeleton->GetBoneCount()); // close anything Close(); // store names m_animationName = animationName; m_animationFileName = fileName; // swap the pointers, and do allocations m_pGenerator = pGenerator; // if (!LoadMaterials()) // { // Close(); // return false; // } // // // create the preview mesh // RefreshPreviewMesh(); // RefreshCollisionShapePreview(); // update everything OnFileNameChanged(); UpdateHierarchy(); UpdateInformationTab(); UpdateTimeDependantVariables(); SetPreviewFrameNumber(0); // load up preview mesh if present from the uncompiled skeleton (if it exists) const String &previewMeshName = m_pGenerator->GetPreviewMeshName(); if (!previewMeshName.IsEmpty()) SetPreviewMeshName(previewMeshName); return true; } bool EditorSkeletalAnimationEditor::Save(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (!IsValidAnimation()) { pProgressCallbacks->DisplayError("The mesh is not valid (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(m_animationFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } return true; } bool EditorSkeletalAnimationEditor::SaveAs(const char *animationName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (!IsValidAnimation()) { pProgressCallbacks->DisplayError("The mesh is not valid (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } PathString newMeshFileName; newMeshFileName.Format("%s.ska.xml", animationName); // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(newMeshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } // update names m_animationName = animationName; m_animationFileName = newMeshFileName; OnFileNameChanged(); return true; } void EditorSkeletalAnimationEditor::Close() { if (m_pGenerator == nullptr) return; m_duration = 0.0f; m_previewFrameNumber = 0; m_selectedBoneIndex = Y_UINT32_MAX; m_frameTimes.Obliterate(); delete m_pGenerator; m_pGenerator = nullptr; if (m_pSkeleton != nullptr) { m_pSkeleton->Release(); m_pSkeleton = nullptr; } m_previewBoneTransforms.Obliterate(); //m_pMeshPreviewRenderProxy->DeleteAllObjects(); } bool EditorSkeletalAnimationEditor::SetPreviewMeshName(const char *meshName) { const SkeletalMesh *pSkeletalMesh = g_pResourceManager->GetSkeletalMesh(meshName); if (pSkeletalMesh == nullptr) return false; SAFE_RELEASE(m_pPreviewMesh); m_pPreviewMesh = pSkeletalMesh; m_pPreviewMesh->AddRef(); if (m_pPreviewMeshRenderProxy != nullptr) { m_pPreviewMeshRenderProxy->SetSkeletalMesh(m_pPreviewMesh); } else { m_pPreviewMeshRenderProxy = new SkeletalMeshRenderProxy(0, m_pPreviewMesh, Transform::Identity, 0); m_pRenderWorld->AddRenderable(m_pPreviewMeshRenderProxy); } UpdateInformationTab(); UpdatePreviewBoneTransforms(); return true; } void EditorSkeletalAnimationEditor::SetPreviewFrameNumber(uint32 frameNumber) { DebugAssert(frameNumber < m_frameTimes.GetSize()); if (m_previewFrameNumber == frameNumber) return; m_previewFrameNumber = frameNumber; BlockSignalsForCall(m_ui->scrubberSlider)->setValue((int)frameNumber + 1); m_ui->scrubberDockWidget->setWindowTitle(ConvertStringToQString(SmallString::FromFormat("Frame %u (%.3fs)", frameNumber + 1, m_frameTimes[frameNumber]))); UpdatePreviewBoneTransforms(); } bool EditorSkeletalAnimationEditor::CreateHardwareResources() { Log_DevPrintf("Creating hardware resources for EditorSkeletalAnimationEditor (%u x %u)", (uint32)m_ui->swapChainWidget->size().width(), (uint32)m_ui->swapChainWidget->size().height()); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == NULL) return false; m_pSwapChain->AddRef(); } // get dimensions uint32 swapChainWidth = m_pSwapChain->GetWidth(); uint32 swapChainHeight = m_pSwapChain->GetHeight(); // update gui context, camera m_guiContext.SetViewportDimensions(swapChainWidth, swapChainHeight); m_guiContext.SetGPUContext(g_pRenderer->GetGPUContext()); m_viewController.SetViewportDimensions(swapChainWidth, swapChainHeight); // create render context if (m_pWorldRenderer == NULL) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); // cancel any pending draws until the windows are arranged and a paint is requested. m_bHardwareResourcesCreated = true; return true; } void EditorSkeletalAnimationEditor::ReleaseHardwareResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; m_pWorldRenderer = NULL; SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_bHardwareResourcesCreated = false; } bool EditorSkeletalAnimationEditor::IsValidAnimation() const { // if (m_pGenerator->GetVertexCount() == 0 || // m_pGenerator->GetTriangleCount() == 0 || // m_pGenerator->GetMaterialCount() == 0 || // m_pGenerator->GetBatchCount() == 0 || // m_pGenerator->GetLODCount() == 0) // { // return false; // } return true; } void EditorSkeletalAnimationEditor::OnFileNameChanged() { // set the material directory to the same directory as the mesh PathString importDirectory; FileSystem::BuildPathRelativeToFile(importDirectory, m_animationFileName, "", false, true); // update the window title setWindowTitle(ConvertStringToQString(String::FromFormat("Skeletal Animation Editor - %s", m_animationName.GetCharArray()))); } void EditorSkeletalAnimationEditor::UpdateTimeDependantVariables() { m_frameTimes.Clear(); m_pGenerator->GenerateKeyFrameTimeList(&m_frameTimes); m_duration = (m_frameTimes.GetSize() > 0) ? m_frameTimes.LastElement() : 0.0f; m_ui->toolInformationFrameCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_frameTimes.GetSize()))); m_ui->toolInformationDuration->setText(ConvertStringToQString(TinyString::FromFormat("%f s", m_duration))); BlockSignalsForCall(m_ui->scrubberSlider)->setMinimum(1); BlockSignalsForCall(m_ui->scrubberSlider)->setMaximum(m_frameTimes.GetSize()); BlockSignalsForCall(m_ui->toolClipperStartFrameNumber)->setMinimum(1); BlockSignalsForCall(m_ui->toolClipperStartFrameNumber)->setMaximum(m_frameTimes.GetSize()); BlockSignalsForCall(m_ui->toolClipperEndFrameNumber)->setMinimum(1); BlockSignalsForCall(m_ui->toolClipperEndFrameNumber)->setMaximum(m_frameTimes.GetSize()); SetPreviewFrameNumber(0); } void EditorSkeletalAnimationEditor::UpdateHierarchyRecursive(const Skeleton::Bone *pBone, QTreeWidgetItem *pParent) { QTreeWidgetItem *pItem; if (pParent != nullptr) pItem = new QTreeWidgetItem(pParent); else pItem = new QTreeWidgetItem(m_ui->hierarchyTreeWidget); pItem->setText(0, EditorHelpers::ConvertStringToQString(pBone->GetName())); if (pParent != nullptr) pParent->addChild(pItem); else m_ui->hierarchyTreeWidget->addTopLevelItem(pItem); for (uint32 childIndex = 0; childIndex < pBone->GetChildBoneCount(); childIndex++) UpdateHierarchyRecursive(pBone->GetChildBone(childIndex), pItem); } void EditorSkeletalAnimationEditor::UpdateHierarchy() { DebugAssert(m_pSkeleton != nullptr); m_ui->hierarchyTreeWidget->clear(); const Skeleton::Bone *pRootBone = m_pSkeleton->GetRootBone(); UpdateHierarchyRecursive(pRootBone, nullptr); } void EditorSkeletalAnimationEditor::UpdatePreviewBoneTransformRecursive(float time, const Skeleton::Bone *pBone, const Transform *pParentBoneTransform) { // get base frame transform Transform boneRelativeTransform(pBone->GetRelativeBaseFrameTransform()); // get track transform const SkeletalAnimationGenerator::BoneTrack *pBoneTrack = m_pGenerator->GetBoneTrackByName(pBone->GetName()); if (pBoneTrack != nullptr) { SkeletalAnimationGenerator::BoneTrack::KeyFrame keyframe; pBoneTrack->InterpolateKeyFrameAtTime(time, &keyframe); boneRelativeTransform.Set(keyframe.GetPosition(), keyframe.GetRotation(), keyframe.GetScale()); } // factor into account the parent transform Transform boneAbsoluteTransform((pParentBoneTransform != nullptr) ? Transform::ConcatenateTransforms(boneRelativeTransform, *pParentBoneTransform) : boneRelativeTransform); // store transform m_previewBoneTransforms[pBone->GetIndex()] = boneAbsoluteTransform; // update preview mesh if (m_pPreviewMesh != nullptr) { for (uint32 meshBoneIndex = 0; meshBoneIndex < m_pPreviewMesh->GetBoneCount(); meshBoneIndex++) { if (m_pPreviewMesh->GetBone(meshBoneIndex)->SkeletonBoneIndex == pBone->GetIndex()) { m_pPreviewMeshRenderProxy->SetBoneTransforms(meshBoneIndex, 1, &boneAbsoluteTransform); break; } } } // handle any children for (uint32 childIndex = 0; childIndex < pBone->GetChildBoneCount(); childIndex++) UpdatePreviewBoneTransformRecursive(time, pBone->GetChildBone(childIndex), &boneAbsoluteTransform); } void EditorSkeletalAnimationEditor::UpdatePreviewBoneTransforms() { float time = m_frameTimes[m_previewFrameNumber]; // calculate from the root bone upwards const Skeleton::Bone *pRootBone = m_pSkeleton->GetRootBone(); UpdatePreviewBoneTransformRecursive(time, pRootBone, nullptr); // redraw FlagForRedraw(); } void EditorSkeletalAnimationEditor::UpdateInformationTab() { m_ui->toolInformationSkeletonName->setText(ConvertStringToQString(m_pSkeleton->GetName())); m_ui->toolInformationBoneTrackCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pGenerator->GetBoneTrackCount()))); m_ui->toolInformationRootMotion->setText((m_pGenerator->GetRootMotionTrack() != nullptr) ? tr("Yes") : tr("No")); m_ui->toolInformationPreviewMesh->setText(ConvertStringToQString(SmallString::FromFormat("<a href=\"select\">%s</a>", (m_pPreviewMesh != nullptr) ? m_pPreviewMesh->GetName().GetCharArray() : "Select..."))); } void EditorSkeletalAnimationEditor::Draw() { // create hardware resources if (!m_bHardwareResourcesCreated && !CreateHardwareResources()) return; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // clear it pGPUContext->SetOutputBuffer(m_pSwapChain); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetViewport(m_viewController.GetViewport()); pGPUContext->ClearTargets(true, true, true); // setup 3d state pGPUContext->GetConstants()->SetFromCamera(m_viewController.GetCamera(), true); // invoke draws DrawGrid(); DrawView(); // bias the projection matrix slightly FIXME pGPUContext->GetConstants()->SetCameraProjectionMatrix(m_viewController.GetCamera().GetBiasedProjectionMatrix(0.01f), true); DrawOverlays(pGPUContext, &m_guiContext); // clear state pGPUContext->ClearState(true, true, true, true); // present pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // clear pending flag m_bRedrawPending = false; } void EditorSkeletalAnimationEditor::DrawGrid() { // draw a grid of 2*the mesh size //float gridSizeX = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().x), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().x)) * 2.0f); //float gridSizeY = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().y), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().y)) * 2.0f); float gridSizeX = 16.0f; float gridSizeY = 16.0f; m_guiContext.Draw3DGrid(float3(-gridSizeX, -gridSizeY, 0.0f), float3(gridSizeX, gridSizeY, 0.0f), float3(1.0f, 1.0f, 1.0f), MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255)); } void EditorSkeletalAnimationEditor::DrawView() { m_pWorldRenderer->DrawWorld(m_pRenderWorld, m_viewController.GetViewParameters(), NULL, NULL); } void EditorSkeletalAnimationEditor::DrawOverlays(GPUContext *pGPUContext, MiniGUIContext *pGUIContext) { // draw the skeleton tree { // for each bone for (uint32 i = 0; i < m_pSkeleton->GetBoneCount(); i++) { const Skeleton::Bone *pParentBone = m_pSkeleton->GetBoneByIndex(i); const Transform &parentBoneTransform = m_previewBoneTransforms[i]; float3 lineSource(parentBoneTransform.TransformPoint(float3::Zero)); // for each bone that has this bone as a parent for (uint32 j = 0; j < m_pSkeleton->GetBoneCount(); j++) { const Skeleton::Bone *pChildBone = m_pSkeleton->GetBoneByIndex(j); if (pChildBone->GetParentBone() == pParentBone) { const Transform &childBoneTransform = m_previewBoneTransforms[j]; // draw a line from source to destination float3 lineDestination(childBoneTransform.TransformPoint(float3::Zero)); pGUIContext->Draw3DLineWidth(lineSource, lineDestination, (m_selectedBoneIndex == pChildBone->GetIndex()) ? MAKE_COLOR_R8G8B8A8_UNORM(240, 240, 0, 255) : MAKE_COLOR_R8G8B8A8_UNORM(240, 240, 240, 255), 2.0f); // and the axes float3 axisOrigin(lineDestination); float3 xAxisPos(childBoneTransform.TransformPoint(float3::UnitX * 0.5f)); float3 yAxisPos(childBoneTransform.TransformPoint(float3::UnitY * 0.5f)); float3 zAxisPos(childBoneTransform.TransformPoint(float3::UnitZ * 0.5f)); pGUIContext->Draw3DLineWidth(axisOrigin, xAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(255, 0, 0, 255), 2.0f); pGUIContext->Draw3DLineWidth(axisOrigin, yAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255), 2.0f); pGUIContext->Draw3DLineWidth(axisOrigin, zAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 255, 255), 2.0f); } } } } } void EditorSkeletalAnimationEditor::OnFrameExecutionTriggered(float timeSinceLastFrame) { // don't do anything if we haven't loaded if (m_pGenerator == nullptr) return; // update camera m_viewController.Update(timeSinceLastFrame); // force draw if requested by camera if (m_viewController.IsChanged()) FlagForRedraw(); // redraw if required if (m_bRedrawPending) Draw(); } void EditorSkeletalAnimationEditor::ConnectUIEvents() { // actions connect(m_ui->actionOpen, SIGNAL(triggered()), this, SLOT(OnActionOpenMeshClicked())); connect(m_ui->actionSave, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshClicked())); connect(m_ui->actionSaveAs, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshAsClicked())); connect(m_ui->actionClose, SIGNAL(triggered()), this, SLOT(OnActionCloseClicked())); connect(m_ui->actionCameraPerspective, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraPerspectiveTriggered(bool))); connect(m_ui->actionCameraArcball, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraArcballTriggered(bool))); connect(m_ui->actionCameraIsometric, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraIsometricTriggered(bool))); connect(m_ui->actionViewWireframe, SIGNAL(triggered(bool)), this, SLOT(OnActionViewWireframeTriggered(bool))); connect(m_ui->actionViewUnlit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewUnlitTriggered(bool))); connect(m_ui->actionViewLit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewLitTriggered(bool))); connect(m_ui->actionViewFlagShadows, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagShadowsTriggered(bool))); connect(m_ui->actionViewFlagWireframeOverlay, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagWireframeOverlayTriggered(bool))); connect(m_ui->actionToolInformation, SIGNAL(triggered(bool)), this, SLOT(OnActionToolInformationTriggered(bool))); connect(m_ui->actionToolBoneTrack, SIGNAL(triggered(bool)), this, SLOT(OnActionToolBoneTrackTriggered(bool))); connect(m_ui->actionToolRootMotion, SIGNAL(triggered(bool)), this, SLOT(OnActionToolRootMotionTriggered(bool))); connect(m_ui->actionToolClipper, SIGNAL(triggered(bool)), this, SLOT(OnActionToolClipperTriggered(bool))); connect(m_ui->actionToolLightManipulator, SIGNAL(triggered(bool)), this, SLOT(OnActionToolLightManipulatorTriggered(bool))); // scrubber connect(m_ui->scrubberSlider, SIGNAL(valueChanged(int)), this, SLOT(OnScrubberValueChanged(int))); // hierarchy connect(m_ui->hierarchyTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(OnHierarchyItemClicked(QTreeWidgetItem *, int))); // information connect(m_ui->toolInformationPreviewMesh, SIGNAL(linkActivated(const QString &)), this, SLOT(OnInformationPreviewMeshLinkActivated(const QString &))); // clipper connect(m_ui->toolClipperSetStartFrameNumber, SIGNAL(clicked()), this, SLOT(OnClipperSetStartFrameNumberClicked())); connect(m_ui->toolClipperSetEndFrameNumber, SIGNAL(clicked()), this, SLOT(OnClipperSetEndFrameNumberClicked())); connect(m_ui->toolClipperClip, SIGNAL(clicked()), this, SLOT(OnClipperClipClicked())); // swapchain connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); connect(m_ui->swapChainWidget, SIGNAL(DropEvent(QDropEvent *)), this, SLOT(OnSwapChainWidgetDropEvent(QDropEvent *))); // frame event connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); } void EditorSkeletalAnimationEditor::closeEvent(QCloseEvent *pCloseEvent) { } void EditorSkeletalAnimationEditor::OnActionOpenMeshClicked() { } void EditorSkeletalAnimationEditor::OnActionSaveMeshClicked() { EditorProgressDialog progressDialog(this); progressDialog.show(); Save(&progressDialog); } void EditorSkeletalAnimationEditor::OnActionSaveMeshAsClicked() { EditorResourceSaveDialog saveDialog(this, OBJECT_TYPEINFO(SkeletalAnimation)); if (saveDialog.exec()) { String newMeshName(saveDialog.GetReturnValueResourceName()); // attempt save EditorProgressDialog progressDialog(this); progressDialog.show(); SaveAs(newMeshName, &progressDialog); } } void EditorSkeletalAnimationEditor::OnActionCloseClicked() { } void EditorSkeletalAnimationEditor::OnInformationPreviewMeshLinkActivated(const QString &link) { EditorResourceSelectionDialog selectionDialog(this); selectionDialog.AddResourceFilter(OBJECT_TYPEINFO(SkeletalMesh)); if (selectionDialog.exec()) SetPreviewMeshName(selectionDialog.GetReturnValueResourceName()); } void EditorSkeletalAnimationEditor::OnHierarchyItemClicked(QTreeWidgetItem *pItem, int column) { const Skeleton::Bone *pBone = m_pSkeleton->GetBoneByName(ConvertQStringToString(pItem->text(0))); if (pBone == nullptr) { Log_DevPrintf("Clear selected bone"); m_selectedBoneIndex = Y_UINT32_MAX; } else { Log_DevPrintf("Set selected bone to %u - %s", pBone->GetIndex(), pBone->GetName().GetCharArray()); m_selectedBoneIndex = pBone->GetIndex(); } FlagForRedraw(); } void EditorSkeletalAnimationEditor::OnScrubberValueChanged(int value) { DebugAssert(value > 0); SetPreviewFrameNumber(value - 1); } void EditorSkeletalAnimationEditor::OnClipperSetStartFrameNumberClicked() { m_ui->toolClipperStartFrameNumber->setValue(m_previewFrameNumber + 1); } void EditorSkeletalAnimationEditor::OnClipperSetEndFrameNumberClicked() { m_ui->toolClipperEndFrameNumber->setValue(m_previewFrameNumber + 1); } void EditorSkeletalAnimationEditor::OnClipperClipClicked() { int32 startFrameNumber = m_ui->toolClipperStartFrameNumber->value() - 1; int32 endFrameNumber = m_ui->toolClipperEndFrameNumber->value() - 1; if (startFrameNumber < 0 || endFrameNumber < 0 || startFrameNumber > endFrameNumber) { QMessageBox::critical(this, tr("Invalid range"), tr("Invalid clip range")); return; } m_pGenerator->ClipAnimation(m_frameTimes[startFrameNumber], m_frameTimes[endFrameNumber]); UpdateTimeDependantVariables(); } void EditorSkeletalAnimationEditor::OnSwapChainWidgetResized() { // skip full recreation if we can just do the resize SAFE_RELEASE(m_pSwapChain); delete m_pWorldRenderer; m_pWorldRenderer = nullptr; m_bHardwareResourcesCreated = false; // flag for redraw FlagForRedraw(); } void EditorSkeletalAnimationEditor::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorSkeletalAnimationEditor::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // pass to camera m_viewController.HandleKeyboardEvent(pKeyboardEvent); } void EditorSkeletalAnimationEditor::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { if (m_currentState == State_None) { } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { //switch (m_currentState) //{ //} } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_currentState == State_None) { // right mouse button enters camera rotation state m_currentState = State_RotateCamera; return; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_currentState == State_RotateCamera) { m_currentState = State_None; return; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pMouseEvent->x(), pMouseEvent->y()); int2 lastMousePosition(m_lastMousePosition); int2 mousePositionDiff(currentMousePosition - lastMousePosition); m_lastMousePosition = currentMousePosition; switch (m_currentState) { case State_RotateCamera: m_viewController.RotateFromMousePosition(mousePositionDiff); FlagForRedraw(); break; } } } void EditorSkeletalAnimationEditor::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { } void EditorSkeletalAnimationEditor::OnSwapChainWidgetGainedFocusEvent() { } <file_sep>/Engine/Source/Engine/ArcBallCamera.h #pragma once #include "Engine/Common.h" #include "Engine/Camera.h" class ArcBallCamera : public Camera { public: ArcBallCamera(); ~ArcBallCamera(); // Common properties const float3 &GetTarget() const { return m_target; } const float GetEyeDistance() const { return m_eyeDistance; } // Common properties void Reset(); void SetTarget(const float3 &t) { m_target = t; UpdateArcBallViewMatrix(); } void SetEyeDistance(float v) { m_eyeDistance = v; UpdateArcBallViewMatrix(); } // handle mouse/keyboard input events void RotateFromMouseMovement(int32 mouseDiffX, int32 mouseDiffY); // time update void Update(const float &dt); protected: void UpdateArcBallViewMatrix(); // common properties float3 m_target; float m_eyeDistance; }; <file_sep>/Engine/Source/Renderer/Shaders/DepthOnlyShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/DepthOnlyShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(DepthOnlyShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DepthOnlyShader) END_SHADER_COMPONENT_PARAMETERS() bool DepthOnlyShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL) return false; return true; } bool DepthOnlyShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DepthOnlyShader.hlsl", "VSMain"); if (!pParameters->MaterialShaderName.IsEmpty()) { pParameters->AddPreprocessorMacro(StaticString("WITH_MATERIAL"), StaticString("1")); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DepthOnlyShader.hlsl", "PSMain"); } return true; } <file_sep>/Engine/Source/Engine/TerrainRendererNull.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainRendererNull.h" #include "Engine/ResourceManager.h" #include "Engine/Camera.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderMap.h" #include "Renderer/RenderWorld.h" Log_SetChannel(TerrainRendererNull); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TerrainRendererNull ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TerrainRendererNull::TerrainRendererNull(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList) : TerrainRenderer(TERRAIN_RENDERER_TYPE_CDLOD, pParameters, pLayerList) { } TerrainRendererNull::~TerrainRendererNull() { TerrainRendererNull::ReleaseGPUResources(); } TerrainSectionRenderProxy *TerrainRendererNull::CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) { return new TerrainSectionRenderProxyNull(entityId, this, pSection); } bool TerrainRendererNull::CreateGPUResources() { return true; } void TerrainRendererNull::ReleaseGPUResources() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TerrainRenderProxyNull ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TerrainSectionRenderProxyNull::TerrainSectionRenderProxyNull(uint32 entityId, const TerrainRendererNull *pRenderer, const TerrainSection *pSection) : TerrainSectionRenderProxy(entityId, pSection), m_pRenderer(pRenderer) { } TerrainSectionRenderProxyNull::~TerrainSectionRenderProxyNull() { } void TerrainSectionRenderProxyNull::OnLayersModified() { } void TerrainSectionRenderProxyNull::OnPointHeightModified(uint32 x, uint32 y) { } void TerrainSectionRenderProxyNull::OnPointLayersModified(uint32 x, uint32 y) { } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUContext.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11Common.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUBuffer.h" #include "D3D11Renderer/D3D11GPUTexture.h" #include "D3D11Renderer/D3D11GPUShaderProgram.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(D3D11GPUContext); D3D11GPUContext::D3D11GPUContext(D3D11GPUDevice *pDevice, ID3D11Device *pD3DDevice, ID3D11Device1 *pD3DDevice1, ID3D11DeviceContext *pImmediateContext) : m_pDevice(pDevice) , m_pD3DDevice(pD3DDevice) , m_pD3DDevice1(pD3DDevice1) , m_pD3DContext(pImmediateContext) , m_pD3DContext1(nullptr) , m_pConstants(nullptr) { // add references m_pDevice->AddRef(); // null memory Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); m_currentTopology = DRAW_TOPOLOGY_UNDEFINED; // null current states Y_memzero(m_pCurrentVertexBuffers, sizeof(m_pCurrentVertexBuffers)); Y_memzero(m_currentVertexBufferOffsets, sizeof(m_currentVertexBufferOffsets)); Y_memzero(m_currentVertexBufferStrides, sizeof(m_currentVertexBufferStrides)); m_currentVertexBufferBindCount = 0; m_pCurrentIndexBuffer = NULL; m_currentIndexFormat = GPU_INDEX_FORMAT_COUNT; m_currentIndexBufferOffset = 0; m_pCurrentShaderProgram = NULL; Y_memzero(m_shaderStates, sizeof(m_shaderStates)); for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { ShaderStageState *state = &m_shaderStates[i]; state->ConstantBufferDirtyLowerBounds = state->ConstantBufferDirtyUpperBounds = -1; state->ResourceDirtyLowerBounds = state->ResourceDirtyUpperBounds = -1; state->SamplerDirtyLowerBounds = state->SamplerDirtyUpperBounds = -1; state->UAVDirtyLowerBounds = state->UAVDirtyUpperBounds = -1; } m_pCurrentRasterizerState = NULL; m_pCurrentDepthStencilState = NULL; m_currentDepthStencilRef = 0; m_pCurrentBlendState = NULL; m_currentBlendStateBlendFactors.SetZero(); m_pCurrentSwapChain = NULL; Y_memzero(m_pCurrentRenderTargetViews, sizeof(m_pCurrentRenderTargetViews)); m_pCurrentDepthBufferView = nullptr; m_nCurrentRenderTargets = 0; m_pCurrentPredicate = nullptr; m_pCurrentPredicateD3D = nullptr; m_predicateBypassCount = 0; m_pUserVertexBuffer = NULL; m_userVertexBufferSize = 16 * 1024 * 1024; // 16MB m_userVertexBufferPosition = 0; } D3D11GPUContext::~D3D11GPUContext() { // clear any state ClearState(true, true, false, true); m_pD3DContext->RSSetState(nullptr); m_pD3DContext->OMSetDepthStencilState(nullptr, 0); m_pD3DContext->OMSetBlendState(nullptr, nullptr, 0); m_pD3DContext->OMSetRenderTargets(0, nullptr, nullptr); m_pD3DContext->ClearState(); m_pD3DContext->Flush(); DebugAssert(m_predicateBypassCount == 0); if (m_pCurrentPredicateD3D != nullptr) { m_pD3DContext->SetPredication(nullptr, FALSE); m_pCurrentPredicateD3D = nullptr; } SAFE_RELEASE(m_pCurrentPredicate); // release our references to states and targets. d3d references will die when the device goes down. for (uint32 i = 0; i < countof(m_pCurrentVertexBuffers); i++) { SAFE_RELEASE(m_pCurrentVertexBuffers[i]); } SAFE_RELEASE(m_pCurrentIndexBuffer); SAFE_RELEASE(m_pCurrentShaderProgram); for (uint32 stage = 0; stage < SHADER_PROGRAM_STAGE_COUNT; stage++) { ShaderStageState &state = m_shaderStates[stage]; for (uint32 i = 0; i < state.ConstantBufferBindCount; i++) { SAFE_RELEASE(state.ConstantBuffers[i]); } for (uint32 i = 0; i < state.ResourceBindCount; i++) { SAFE_RELEASE(state.Resources[i]); } for (uint32 i = 0; i < state.SamplerBindCount; i++) { SAFE_RELEASE(state.Samplers[i]); } for (uint32 i = 0; i < state.UAVBindCount; i++) { SAFE_RELEASE(state.UAVs[i]); } } for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; if (constantBuffer->pGPUBuffer != nullptr) constantBuffer->pGPUBuffer->Release(); delete[] constantBuffer->pLocalMemory; } SAFE_RELEASE(m_pCurrentRasterizerState); SAFE_RELEASE(m_pCurrentDepthStencilState); SAFE_RELEASE(m_pCurrentBlendState); for (uint32 i = 0; i < countof(m_pCurrentRenderTargetViews); i++) { SAFE_RELEASE(m_pCurrentRenderTargetViews[i]); } SAFE_RELEASE(m_pCurrentDepthBufferView); SAFE_RELEASE(m_pUserVertexBuffer); delete m_pConstants; // clear swapchain last, like gl SAFE_RELEASE(m_pCurrentSwapChain); m_pDevice->Release(); } bool D3D11GPUContext::Create() { HRESULT hResult; // get the 11.1 context, if there was a 11.1 device successfully retrieved if (m_pD3DDevice1 != nullptr) { if (FAILED(hResult = m_pD3DContext->QueryInterface(__uuidof(ID3D11DeviceContext1), (void **)&m_pD3DContext1))) { Log_ErrorPrintf("D3D11GPUContext::Create: Failed to retrieve ID3D11DeviceContext1 interface with hResult %08X", hResult); return false; } } // allocate constants m_pConstants = new GPUContextConstants(m_pDevice, this); // create constant buffers if (!CreateConstantBuffers()) return false; // create user buffers { D3D11_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; bufferDesc.StructureByteStride = 0; // vertex buffer bufferDesc.ByteWidth = m_userVertexBufferSize; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; if (FAILED(hResult = m_pD3DDevice->CreateBuffer(&bufferDesc, NULL, &m_pUserVertexBuffer))) { Log_ErrorPrintf("Failed to create user vertex buffer %08X", hResult); return false; } } return true; } void D3D11GPUContext::ClearState(bool clearShaders /* = true */, bool clearBuffers /* = true */, bool clearStates /* = true */, bool clearRenderTargets /* = true */) { if (clearShaders) { SetShaderProgram(nullptr); for (uint32 stage = 0; stage < SHADER_PROGRAM_STAGE_COUNT; stage++) { ShaderStageState &state = m_shaderStates[stage]; if (state.ConstantBufferBindCount > 0) { for (uint32 i = 0; i < state.ConstantBufferBindCount; i++) { SAFE_RELEASE(state.ConstantBuffers[i]); } state.ConstantBufferDirtyLowerBounds = 0; state.ConstantBufferDirtyUpperBounds = state.ConstantBufferBindCount - 1; } if (state.ResourceBindCount > 0) { for (uint32 i = 0; i < state.ResourceBindCount; i++) { SAFE_RELEASE(state.Resources[i]); } state.ResourceDirtyLowerBounds = 0; state.ResourceDirtyUpperBounds = state.ResourceBindCount - 1; } if (state.SamplerBindCount > 0) { for (uint32 i = 0; i < state.SamplerBindCount; i++) { SAFE_RELEASE(state.Samplers[i]); } state.SamplerDirtyLowerBounds = 0; state.SamplerDirtyUpperBounds = state.SamplerBindCount - 1; } if (state.UAVBindCount > 0) { for (uint32 i = 0; i < state.UAVBindCount; i++) { SAFE_RELEASE(state.UAVs[i]); } state.UAVDirtyLowerBounds = 0; state.UAVDirtyUpperBounds = state.UAVBindCount - 1; } } SynchronizeShaderStates(); } if (clearBuffers) { if (m_currentVertexBufferBindCount > 0) { static GPUBuffer *nullVertexBuffers[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { nullptr }; static const uint32 nullSizeOrOffset[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { 0 }; SetVertexBuffers(0, m_currentVertexBufferBindCount, nullVertexBuffers, nullSizeOrOffset, nullSizeOrOffset); } if (m_pCurrentIndexBuffer != nullptr) SetIndexBuffer(nullptr, GPU_INDEX_FORMAT_UINT16, 0); } if (clearStates) { SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState()); SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(), 0); SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); SetDrawTopology(DRAW_TOPOLOGY_UNDEFINED); RENDERER_SCISSOR_RECT scissor(0, 0, 0, 0); SetFullViewport(nullptr); SetScissorRect(&scissor); } if (clearRenderTargets) { SetRenderTargets(0, nullptr, nullptr); } } GPURasterizerState *D3D11GPUContext::GetRasterizerState() { return m_pCurrentRasterizerState; } void D3D11GPUContext::SetRasterizerState(GPURasterizerState *pRasterizerState) { if (m_pCurrentRasterizerState != pRasterizerState) { if (m_pCurrentRasterizerState != NULL) m_pCurrentRasterizerState->Release(); if ((m_pCurrentRasterizerState = static_cast<D3D11RasterizerState *>(pRasterizerState)) != NULL) { m_pCurrentRasterizerState->AddRef(); m_pD3DContext->RSSetState(m_pCurrentRasterizerState->GetD3DRasterizerState()); } else { m_pD3DContext->RSSetState(NULL); } } } GPUDepthStencilState *D3D11GPUContext::GetDepthStencilState() { return m_pCurrentDepthStencilState; } uint8 D3D11GPUContext::GetDepthStencilStateStencilRef() { return m_currentDepthStencilRef; } void D3D11GPUContext::SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) { if (m_pCurrentDepthStencilState != pDepthStencilState || m_currentDepthStencilRef != stencilRef) { if (m_pCurrentDepthStencilState == pDepthStencilState) { // just changing ref value m_pD3DContext->OMSetDepthStencilState(m_pCurrentDepthStencilState->GetD3DDepthStencilState(), stencilRef); } else { if (m_pCurrentDepthStencilState != NULL) m_pCurrentDepthStencilState->Release(); if ((m_pCurrentDepthStencilState = static_cast<D3D11DepthStencilState *>(pDepthStencilState)) != NULL) { m_pCurrentDepthStencilState->AddRef(); m_pD3DContext->OMSetDepthStencilState(m_pCurrentDepthStencilState->GetD3DDepthStencilState(), stencilRef); } else { m_pD3DContext->OMSetDepthStencilState(NULL, stencilRef); } } m_currentDepthStencilRef = stencilRef; } } GPUBlendState *D3D11GPUContext::GetBlendState() { return m_pCurrentBlendState; } const float4 &D3D11GPUContext::GetBlendStateBlendFactor() { return m_currentBlendStateBlendFactors; }; void D3D11GPUContext::SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor /* = float4::One */) { if (m_pCurrentBlendState != pBlendState || blendFactor != m_currentBlendStateBlendFactors) { if (m_pCurrentBlendState != NULL) m_pCurrentBlendState->Release(); if ((m_pCurrentBlendState = static_cast<D3D11BlendState *>(pBlendState)) != NULL) { m_pCurrentBlendState->AddRef(); m_pD3DContext->OMSetBlendState(m_pCurrentBlendState->GetD3DBlendState(), blendFactor.ele, 0xFFFFFFFF); } else { m_pD3DContext->OMSetBlendState(NULL, blendFactor.ele, 0xFFFFFFFF); } m_currentBlendStateBlendFactors = blendFactor; } } const RENDERER_VIEWPORT *D3D11GPUContext::GetViewport() { return &m_currentViewport; } void D3D11GPUContext::SetViewport(const RENDERER_VIEWPORT *pNewViewport) { if (Y_memcmp(&m_currentViewport, pNewViewport, sizeof(RENDERER_VIEWPORT)) == 0) return; Y_memcpy(&m_currentViewport, pNewViewport, sizeof(m_currentViewport)); D3D11_VIEWPORT D3DViewport; D3DViewport.TopLeftX = (float)m_currentViewport.TopLeftX; D3DViewport.TopLeftY = (float)m_currentViewport.TopLeftY; D3DViewport.Width = (float)m_currentViewport.Width; D3DViewport.Height = (float)m_currentViewport.Height; D3DViewport.MinDepth = pNewViewport->MinDepth; D3DViewport.MaxDepth = pNewViewport->MaxDepth; m_pD3DContext->RSSetViewports(1, &D3DViewport); // update constants m_pConstants->SetViewportOffset((float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, false); m_pConstants->SetViewportSize((float)m_currentViewport.Width, (float)m_currentViewport.Height, false); m_pConstants->CommitChanges(); } void D3D11GPUContext::SetFullViewport(GPUTexture *pForRenderTarget /* = NULL */) { RENDERER_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; if (pForRenderTarget == nullptr && m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { if (m_pCurrentSwapChain != nullptr) { viewport.Width = m_pCurrentSwapChain->GetWidth(); viewport.Height = m_pCurrentSwapChain->GetHeight(); } else { viewport.Width = 1; viewport.Height = 1; } } else { DebugAssert(m_pCurrentRenderTargetViews[0] != nullptr || pForRenderTarget != nullptr); GPUTexture *pRT = pForRenderTarget; if (pRT != nullptr || m_nCurrentRenderTargets > 0) { uint3 renderTargetDimensions = Renderer::GetTextureDimensions((pRT != nullptr) ? pRT : m_pCurrentRenderTargetViews[0]->GetTargetTexture()); viewport.Width = renderTargetDimensions.x; viewport.Height = renderTargetDimensions.y; } else { viewport.Width = m_pCurrentSwapChain->GetWidth(); viewport.Height = m_pCurrentSwapChain->GetHeight(); } } viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; SetViewport(&viewport); } const RENDERER_SCISSOR_RECT *D3D11GPUContext::GetScissorRect() { return &m_scissorRect; } void D3D11GPUContext::SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) { if (Y_memcmp(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)) == 0) return; Y_memcpy(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)); D3D11_RECT D3DRect; D3DRect.left = pScissorRect->Left; D3DRect.top = pScissorRect->Top; D3DRect.right = pScissorRect->Right; D3DRect.bottom = pScissorRect->Bottom; m_pD3DContext->RSSetScissorRects(1, &D3DRect); } void D3D11GPUContext::ClearTargets(bool clearColor /* = true */, bool clearDepth /* = true */, bool clearStencil /* = true */, const float4 &clearColorValue /* = float4::Zero */, float clearDepthValue /* = 1.0f */, uint8 clearStencilValue /* = 0 */) { uint32 clearFlags = 0; if (clearDepth) clearFlags |= D3D11_CLEAR_DEPTH; if (clearStencil) clearFlags |= D3D11_CLEAR_STENCIL; if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { ID3D11RenderTargetView *pRTV = m_pCurrentSwapChain->GetRenderTargetView(); ID3D11DepthStencilView *pDSV = m_pCurrentSwapChain->GetDepthStencilView(); if (clearColor) m_pD3DContext->ClearRenderTargetView(pRTV, clearColorValue); if (clearFlags != 0 && pDSV != nullptr) m_pD3DContext->ClearDepthStencilView(pDSV, clearFlags, clearDepthValue, clearStencilValue); } } else { if (clearColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) m_pD3DContext->ClearRenderTargetView(m_pCurrentRenderTargetViews[i]->GetD3DRTV(), clearColorValue); } } if (clearFlags != 0 && m_pCurrentDepthBufferView != nullptr) m_pD3DContext->ClearDepthStencilView(m_pCurrentDepthBufferView->GetD3DDSV(), clearFlags, clearDepthValue, clearStencilValue); } } void D3D11GPUContext::DiscardTargets(bool discardColor /* = true */, bool discardDepth /* = true */, bool discardStencil /* = true */) { // only supported on 11.1+ if (m_pD3DContext1 == nullptr) return; if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { if (discardColor) m_pD3DContext1->DiscardView(m_pCurrentSwapChain->GetRenderTargetView()); if (discardDepth && discardStencil && m_pCurrentSwapChain->GetDepthStencilView() != nullptr) m_pD3DContext1->DiscardView(m_pCurrentSwapChain->GetDepthStencilView()); } } else { if (discardColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) m_pD3DContext1->DiscardView(m_pCurrentRenderTargetViews[i]->GetD3DRTV()); } } if (discardDepth && discardStencil && m_pCurrentDepthBufferView != nullptr) m_pD3DContext1->DiscardView(m_pCurrentDepthBufferView->GetD3DDSV()); } } GPUOutputBuffer *D3D11GPUContext::GetOutputBuffer() { return m_pCurrentSwapChain; } void D3D11GPUContext::SetOutputBuffer(GPUOutputBuffer *pSwapChain) { if (m_pCurrentSwapChain == pSwapChain) return; // copy out old swap chain D3D11GPUOutputBuffer *pOldSwapChain = m_pCurrentSwapChain; // copy in new swap chain if ((m_pCurrentSwapChain = static_cast<D3D11GPUOutputBuffer *>(pSwapChain)) != nullptr) { // DebugAssert(m_pCurrentSwapChain->GetOwnerContext() == nullptr); // if (m_pCurrentSwapChain->IsManaged()) // static_cast<D3D11RendererOutputWindow *>(m_pCurrentSwapChain)->SetOwnerContext(this); // else // static_cast<D3D11GPUOutputBuffer *>(m_pCurrentSwapChain)->SetOwnerContext(this); m_pCurrentSwapChain->AddRef(); } // Currently rendering to window? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) SynchronizeRenderTargetsAndUAVs(); // update references if (pOldSwapChain != NULL) { // DebugAssert(pOldSwapChain->GetOwnerContext() == this); // if (pOldSwapChain->IsManaged()) // static_cast<D3D11RendererOutputWindow *>(pOldSwapChain)->SetOwnerContext(nullptr); // else // static_cast<D3D11GPUOutputBuffer *>(pOldSwapChain)->SetOwnerContext(nullptr); pOldSwapChain->Release(); } } bool D3D11GPUContext::GetExclusiveFullScreen() { BOOL currentState; HRESULT hResult = m_pCurrentSwapChain->GetDXGISwapChain()->GetFullscreenState(&currentState, nullptr); if (FAILED(hResult)) return false; return (currentState == TRUE); } bool D3D11GPUContext::SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) { HRESULT hResult; // bound to pipeline? have to clear before switching modes if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) m_pD3DContext->OMSetRenderTargets(0, nullptr, nullptr); // switch successful? ie have to resize buffers bool switchResult = true; uint32 newWidth = width; uint32 newHeight = height; // get current fullscreen state BOOL currentFullScreenState; if (FAILED(m_pCurrentSwapChain->GetDXGISwapChain()->GetFullscreenState(&currentFullScreenState, nullptr))) currentFullScreenState = FALSE; // to fullscreen? if (enabled) { // get output IDXGIOutput *pOutput; hResult = m_pDevice->GetDXGIAdapter()->EnumOutputs(0, &pOutput); if (SUCCEEDED(hResult)) { // fill in mode details with requested width/height DXGI_MODE_DESC modeDesc; Y_memzero(&modeDesc, sizeof(modeDesc)); modeDesc.Width = width; modeDesc.Height = height; modeDesc.RefreshRate.Numerator = refreshRate; modeDesc.RefreshRate.Denominator = 1; modeDesc.Format = m_pDevice->GetSwapChainBackBufferFormat(); // find the best mode match DXGI_MODE_DESC closestMatch; hResult = pOutput->FindClosestMatchingMode(&modeDesc, &closestMatch, m_pD3DDevice); if (SUCCEEDED(hResult)) { // update dimensions with closest match Log_InfoPrintf("D3D11GPUContext::SetExclusiveFullScreen: Switching to closest mode match %ux%u RefreshRate %u/%u", closestMatch.Width, closestMatch.Height, closestMatch.RefreshRate.Numerator, closestMatch.RefreshRate.Denominator); newWidth = closestMatch.Width; newHeight = closestMatch.Height; // switch to fullscreen state if (!currentFullScreenState) { hResult = m_pCurrentSwapChain->GetDXGISwapChain()->SetFullscreenState(TRUE, pOutput); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::SetExclusiveFullScreen: IDXGISwapChain::SetFullscreenState failed with hResult %08X.", hResult); switchResult = false; } } // resize the target if (switchResult) { // call ResizeTarget to fix up the window size hResult = m_pCurrentSwapChain->GetDXGISwapChain()->ResizeTarget(&closestMatch); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::SetExclusiveFullScreen: IDXGISwapChain::ResizeTarget failed with hResult %08X.", hResult); switchResult = false; } } } else { Log_ErrorPrintf("D3D11GPUContext::SetExclusiveFullScreen: IDXGIOutput::FindClosestMatchingMode failed with hResult %08X.", hResult); switchResult = false; } pOutput->Release(); } else { Log_ErrorPrintf("D3D11GPUContext::SetExclusiveFullScreen: IDXGIAdapter::EnumOutputs failed with hResult %08X.", hResult); switchResult = false; } } else { // remove if currently set if (currentFullScreenState) { hResult = m_pCurrentSwapChain->GetDXGISwapChain()->SetFullscreenState(FALSE, nullptr); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::SetExclusiveFullScreen: IDXGISwapChain::SetFullscreenState failed with hResult %08X.", hResult); switchResult = false; } else { // update dimensions RECT clientRect; GetClientRect(m_pCurrentSwapChain->GetHWND(), &clientRect); newWidth = Max(clientRect.right - clientRect.left, (LONG)1); newHeight = Max(clientRect.bottom - clientRect.top, (LONG)1); } } } // switch successful? if (switchResult) { // resize buffers m_pCurrentSwapChain->InternalResizeBuffers(newWidth, newHeight, m_pCurrentSwapChain->GetVSyncType()); } // synchronize render targets if we were bound if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) SynchronizeRenderTargetsAndUAVs(); // done return true; } bool D3D11GPUContext::ResizeOutputBuffer(uint32 width /* = 0 */, uint32 height /* = 0 */) { if (width == 0 || height == 0) { // get the new size of the window RECT clientRect; GetClientRect(m_pCurrentSwapChain->GetHWND(), &clientRect); // changed? width = Max(clientRect.right - clientRect.left, (LONG)1); height = Max(clientRect.bottom - clientRect.top, (LONG)1); } // changed? if (m_pCurrentSwapChain->GetWidth() == width && m_pCurrentSwapChain->GetHeight() == height) return true; // unbind if we're currently bound to the pipeline if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) m_pD3DContext->OMSetRenderTargets(0, nullptr, nullptr); // invoke the resize m_pCurrentSwapChain->InternalResizeBuffers(width, height, m_pCurrentSwapChain->GetVSyncType()); // synchronize render targets if we were bound if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) SynchronizeRenderTargetsAndUAVs(); // done return true; } void D3D11GPUContext::PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) { m_pCurrentSwapChain->GetDXGISwapChain()->Present((presentBehaviour == GPU_PRESENT_BEHAVIOUR_WAIT_FOR_VBLANK) ? 1 : 0, 0); } void D3D11GPUContext::BeginFrame() { } void D3D11GPUContext::Flush() { m_pD3DContext->Flush(); } void D3D11GPUContext::Finish() { // Doesn't exist in D3D11? } uint32 D3D11GPUContext::GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) { uint32 i, j; for (i = 0; i < m_nCurrentRenderTargets && i < nRenderTargets; i++) ppRenderTargetViews[i] = m_pCurrentRenderTargetViews[i]; for (j = i; j < nRenderTargets; j++) ppRenderTargetViews[j] = nullptr; if (ppDepthBufferView != nullptr) *ppDepthBufferView = m_pCurrentDepthBufferView; return i; } void D3D11GPUContext::SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) { // to system framebuffer? if ((nRenderTargets == 0 || (nRenderTargets == 1 && ppRenderTargets[0] == nullptr)) && pDepthBufferView == nullptr) { // change? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) return; // kill current targets for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { m_pCurrentRenderTargetViews[i]->Release(); m_pCurrentRenderTargetViews[i] = nullptr; } if (m_pCurrentDepthBufferView != nullptr) { m_pCurrentDepthBufferView->Release(); m_pCurrentDepthBufferView = nullptr; } m_nCurrentRenderTargets = 0; SynchronizeShaderStates(); SynchronizeRenderTargetsAndUAVs(); } else { DebugAssert(nRenderTargets < countof(m_pCurrentRenderTargetViews)); uint32 slot; uint32 newRenderTargetCount = 0; bool doUpdate = false; // set inclusive slots for (slot = 0; slot < nRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != ppRenderTargets[slot]) { if (m_pCurrentRenderTargetViews[slot] != nullptr) m_pCurrentRenderTargetViews[slot]->Release(); if ((m_pCurrentRenderTargetViews[slot] = static_cast<D3D11GPURenderTargetView *>(ppRenderTargets[slot])) != nullptr) m_pCurrentRenderTargetViews[slot]->AddRef(); doUpdate = true; } if (m_pCurrentRenderTargetViews[slot] != nullptr) newRenderTargetCount = slot + 1; } // clear extra slots for (; slot < m_nCurrentRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != nullptr) { m_pCurrentRenderTargetViews[slot]->Release(); m_pCurrentRenderTargetViews[slot] = nullptr; doUpdate = true; } } // update counter if (newRenderTargetCount != m_nCurrentRenderTargets) doUpdate = true; m_nCurrentRenderTargets = newRenderTargetCount; if (m_pCurrentDepthBufferView != pDepthBufferView) { if (m_pCurrentDepthBufferView != nullptr) m_pCurrentDepthBufferView->Release(); if ((m_pCurrentDepthBufferView = static_cast<D3D11GPUDepthStencilBufferView *>(pDepthBufferView)) != nullptr) m_pCurrentDepthBufferView->AddRef(); doUpdate = true; } if (doUpdate) { SynchronizeShaderStates(); SynchronizeRenderTargetsAndUAVs(); } } } DRAW_TOPOLOGY D3D11GPUContext::GetDrawTopology() { return m_currentTopology; } void D3D11GPUContext::SetDrawTopology(DRAW_TOPOLOGY topology) { static const D3D11_PRIMITIVE_TOPOLOGY D3D11Topologies[DRAW_TOPOLOGY_COUNT] = { D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED, // DRAW_TOPOLOGY_UNDEFINED D3D11_PRIMITIVE_TOPOLOGY_POINTLIST, // DRAW_TOPOLOGY_POINTS D3D11_PRIMITIVE_TOPOLOGY_LINELIST, // DRAW_TOPOLOGY_LINE_LIST D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, // DRAW_TOPOLOGY_LINE_STRIP D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // DRAW_TOPOLOGY_TRIANGLE_LIST D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, // DRAW_TOPOLOGY_TRIANGLE_STRIP }; if (topology == m_currentTopology) return; DebugAssert(topology < DRAW_TOPOLOGY_COUNT); m_pD3DContext->IASetPrimitiveTopology(D3D11Topologies[topology]); m_currentTopology = topology; } uint32 D3D11GPUContext::GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < countof(m_pCurrentVertexBuffers)); uint32 saveCount; for (saveCount = 0; saveCount < nBuffers; saveCount++) { if ((firstBuffer + saveCount) > m_currentVertexBufferBindCount) break; ppVertexBuffers[saveCount] = m_pCurrentVertexBuffers[firstBuffer + saveCount]; pVertexBufferOffsets[saveCount] = m_currentVertexBufferOffsets[firstBuffer + saveCount]; pVertexBufferStrides[saveCount] = m_currentVertexBufferStrides[firstBuffer + saveCount]; } return saveCount; } void D3D11GPUContext::SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) { ID3D11Buffer *pD3DBuffers[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; UINT D3DBufferOffsets[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; UINT D3DBufferStrides[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; for (uint32 i = 0; i < nBuffers; i++) { D3D11GPUBuffer *pD3D11VertexBuffer = static_cast<D3D11GPUBuffer *>(ppVertexBuffers[i]); uint32 bufferIndex = firstBuffer + i; if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) { m_pCurrentVertexBuffers[bufferIndex]->Release(); m_pCurrentVertexBuffers[bufferIndex] = nullptr; } if ((m_pCurrentVertexBuffers[bufferIndex] = pD3D11VertexBuffer) != nullptr) { pD3D11VertexBuffer->AddRef(); m_currentVertexBufferOffsets[bufferIndex] = pVertexBufferOffsets[i]; m_currentVertexBufferStrides[bufferIndex] = pVertexBufferStrides[i]; pD3DBuffers[i] = pD3D11VertexBuffer->GetD3DBuffer(); D3DBufferOffsets[i] = pVertexBufferOffsets[i]; D3DBufferStrides[i] = pVertexBufferStrides[i]; } else { m_currentVertexBufferOffsets[bufferIndex] = 0; m_currentVertexBufferStrides[bufferIndex] = 0; pD3DBuffers[i] = nullptr; D3DBufferOffsets[i] = 0; D3DBufferStrides[i] = 0; } } // todo: pending set m_pD3DContext->IASetVertexBuffers(firstBuffer, nBuffers, pD3DBuffers, D3DBufferStrides, D3DBufferOffsets); // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((firstBuffer + nBuffers), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D11GPUContext::SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { if (m_pCurrentVertexBuffers[bufferIndex] == pVertexBuffer && m_currentVertexBufferOffsets[bufferIndex] == offset && m_currentVertexBufferStrides[bufferIndex] == stride) { return; } if (m_pCurrentVertexBuffers[bufferIndex] != pVertexBuffer) { if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) m_pCurrentVertexBuffers[bufferIndex]->Release(); if ((m_pCurrentVertexBuffers[bufferIndex] = static_cast<D3D11GPUBuffer *>(pVertexBuffer)) != nullptr) m_pCurrentVertexBuffers[bufferIndex]->AddRef(); } m_currentVertexBufferOffsets[bufferIndex] = offset; m_currentVertexBufferStrides[bufferIndex] = stride; // todo: pending set ID3D11Buffer *pD3DBuffer = (pVertexBuffer != nullptr) ? static_cast<D3D11GPUBuffer *>(pVertexBuffer)->GetD3DBuffer() : nullptr; UINT D3DOffset = (pVertexBuffer != nullptr) ? offset : 0; UINT D3DStride = (pVertexBuffer != nullptr) ? stride : 0; m_pD3DContext->IASetVertexBuffers(bufferIndex, 1, &pD3DBuffer, &D3DStride, &D3DOffset); // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((bufferIndex + 1), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D11GPUContext::GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) { *ppBuffer = m_pCurrentIndexBuffer; *pFormat = m_currentIndexFormat; *pOffset = m_currentIndexBufferOffset; } void D3D11GPUContext::SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) { if (m_pCurrentIndexBuffer == pBuffer && m_currentIndexFormat == format && m_currentIndexBufferOffset == offset) return; if (m_pCurrentIndexBuffer != pBuffer) { if (m_pCurrentIndexBuffer != NULL) m_pCurrentIndexBuffer->Release(); if ((m_pCurrentIndexBuffer = static_cast<D3D11GPUBuffer *>(pBuffer)) != NULL) m_pCurrentIndexBuffer->AddRef(); } m_currentIndexFormat = format; m_currentIndexBufferOffset = offset; if (m_pCurrentIndexBuffer != NULL) m_pD3DContext->IASetIndexBuffer(m_pCurrentIndexBuffer->GetD3DBuffer(), (format == GPU_INDEX_FORMAT_UINT16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, m_currentIndexBufferOffset); else m_pD3DContext->IASetIndexBuffer(NULL, DXGI_FORMAT_R16_UINT, 0); } void D3D11GPUContext::SetShaderProgram(GPUShaderProgram *pShaderProgram) { if (m_pCurrentShaderProgram == pShaderProgram) return; D3D11GPUShaderProgram *pNewShaderProgram = static_cast<D3D11GPUShaderProgram *>(pShaderProgram); if (m_pCurrentShaderProgram != nullptr && pNewShaderProgram != nullptr) { // have both so do fast switch pNewShaderProgram->Switch(this, m_pCurrentShaderProgram); m_pCurrentShaderProgram->Release(); m_pCurrentShaderProgram = pNewShaderProgram; m_pCurrentShaderProgram->AddRef(); } else { // one or the other isn't present, so take the slow path if (m_pCurrentShaderProgram != nullptr) { m_pCurrentShaderProgram->Unbind(this); m_pCurrentShaderProgram->Release(); } if ((m_pCurrentShaderProgram = pNewShaderProgram) != nullptr) { m_pCurrentShaderProgram->Bind(this); m_pCurrentShaderProgram->AddRef(); } } g_pRenderer->GetCounters()->IncrementShaderChangeCounter(); } void D3D11GPUContext::SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValue(this, index, valueType, pValue); } void D3D11GPUContext::SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValueArray(this, index, valueType, pValue, firstElement, numElements); } void D3D11GPUContext::SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStruct(this, index, pValue, valueSize); } void D3D11GPUContext::SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStructArray(this, index, pValue, valueSize, firstElement, numElements); } void D3D11GPUContext::SetShaderParameterResource(uint32 index, GPUResource *pResource) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pResource, nullptr); } void D3D11GPUContext::SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pTexture, pSamplerState); } bool D3D11GPUContext::CreateConstantBuffers() { uint32 memoryUsage = 0; uint32 activeCount = 0; // allocate constant buffer storage const ShaderConstantBuffer::RegistryType *registry = ShaderConstantBuffer::GetRegistry(); m_constantBuffers.Resize(registry->GetNumTypes()); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; constantBuffer->pGPUBuffer = nullptr; constantBuffer->Size = 0; constantBuffer->pLocalMemory = nullptr; constantBuffer->DirtyLowerBounds = constantBuffer->DirtyUpperBounds = -1; // applicable to us? const ShaderConstantBuffer *declaration = registry->GetTypeInfoByIndex(i); if (declaration == nullptr) continue; if (declaration->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && declaration->GetPlatformRequirement() != RENDERER_PLATFORM_D3D11) continue; if (declaration->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && declaration->GetMinimumFeatureLevel() > m_pDevice->GetFeatureLevel()) continue; // set size so we know to allocate it later or on demand constantBuffer->Size = declaration->GetBufferSize(); // stats memoryUsage += constantBuffer->Size; activeCount++; } // preallocate constant buffers, todo lazy allocation Log_DevPrintf("Preallocating %u constant buffers, total VRAM usage: %u bytes", activeCount, memoryUsage); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; if (constantBuffer->Size == 0) continue; // allocate local memory first (so we can use it as initialization data) constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; Y_memzero(constantBuffer->pLocalMemory, constantBuffer->Size); // create the gpu buffer GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER | GPU_BUFFER_FLAG_WRITABLE, constantBuffer->Size); constantBuffer->pGPUBuffer = static_cast<D3D11GPUBuffer *>(m_pDevice->CreateBuffer(&bufferDesc, constantBuffer->pLocalMemory)); if (constantBuffer->pGPUBuffer == nullptr) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(i); Log_ErrorPrintf("D3D11GPUContext::CreateResources: Failed to allocate constant buffer %u (%s)", i, declaration->GetBufferName()); return false; } } return true; } D3D11GPUBuffer *D3D11GPUContext::GetConstantBuffer(uint32 index) { ConstantBuffer *constantBuffer = &m_constantBuffers[index]; if (constantBuffer->Size == 0) return nullptr; if (constantBuffer->pGPUBuffer == nullptr) { // lazy create? if (constantBuffer->pLocalMemory == nullptr) constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; // create the gpu buffer GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER | GPU_BUFFER_FLAG_WRITABLE, constantBuffer->Size); constantBuffer->pGPUBuffer = static_cast<D3D11GPUBuffer *>(m_pDevice->CreateBuffer(&bufferDesc, constantBuffer->pLocalMemory)); if (constantBuffer->pGPUBuffer == nullptr) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(index); Log_ErrorPrintf("D3D11GPUContext::GetConstantBuffer: Failed to lazy-allocate constant buffer %u (%s)", index, declaration->GetBufferName()); return nullptr; } } return constantBuffer->pGPUBuffer; } void D3D11GPUContext::WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit /* = false */) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pGPUBuffer == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } DebugAssert(count > 0 && (offset + count) <= cbInfo->Size); if (Y_memcmp(cbInfo->pLocalMemory + offset, pData, count) != 0) { Y_memcpy(cbInfo->pLocalMemory + offset, pData, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + count; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + count - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D11GPUContext::WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit /*= false*/) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pGPUBuffer == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } uint32 writeSize = bufferStride * count; DebugAssert(writeSize > 0 && (offset + writeSize) <= cbInfo->Size); if (Y_memcmp_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count) != 0) { Y_memcpy_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + writeSize; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + writeSize - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D11GPUContext::CommitConstantBuffer(uint32 bufferIndex) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pGPUBuffer == nullptr || cbInfo->DirtyLowerBounds < 0) return; // block predicates BypassPredication(); // d3d11.0 does not support partial constant buffer updates // if (m_pD3DContext1 != nullptr) // { // // align the dirty bounds to 16 bytes // int32 alignedDirtyLowerBounds = cbInfo->DirtyLowerBounds & (~15); // int32 alignedDirtyUpperBounds = (cbInfo->DirtyUpperBounds + 15) & (~15); // D3D11_BOX destinationBox = { static_cast<UINT>(alignedDirtyLowerBounds), 0, 0, static_cast<UINT>(alignedDirtyUpperBounds - alignedDirtyLowerBounds), 1, 1 }; // m_pD3DContext1->UpdateSubresource1(cbInfo->pGPUBuffer->GetD3DBuffer(), 0, &destinationBox, cbInfo->pLocalMemory + alignedDirtyLowerBounds, 0, 0, D3D11_COPY_NO_OVERWRITE); // } // else { m_pD3DContext->UpdateSubresource(cbInfo->pGPUBuffer->GetD3DBuffer(), 0, nullptr, cbInfo->pLocalMemory, 0, 0); } // restore predicates RestorePredication(); // reset range cbInfo->DirtyLowerBounds = cbInfo->DirtyUpperBounds = -1; } void D3D11GPUContext::SetShaderConstantBuffers(SHADER_PROGRAM_STAGE stage, uint32 index, ID3D11Buffer *pBuffer) { ShaderStageState *state = &m_shaderStates[stage]; if (state->ConstantBuffers[index] == pBuffer) return; if (state->ConstantBuffers[index] != nullptr) state->ConstantBuffers[index]->Release(); if ((state->ConstantBuffers[index] = pBuffer) != nullptr) pBuffer->AddRef(); if (state->ConstantBufferDirtyLowerBounds < 0) { state->ConstantBufferDirtyLowerBounds = index; state->ConstantBufferDirtyUpperBounds = index; } else { state->ConstantBufferDirtyLowerBounds = Min(state->ConstantBufferDirtyLowerBounds, (int32)index); state->ConstantBufferDirtyUpperBounds = Max(state->ConstantBufferDirtyUpperBounds, (int32)index); } } void D3D11GPUContext::SetShaderResources(SHADER_PROGRAM_STAGE stage, uint32 index, ID3D11ShaderResourceView *pResource) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Resources[index] == pResource) return; if (state->Resources[index] != nullptr) state->Resources[index]->Release(); if ((state->Resources[index] = pResource) != nullptr) pResource->AddRef(); if (state->ResourceDirtyLowerBounds < 0) { state->ResourceDirtyLowerBounds = index; state->ResourceDirtyUpperBounds = index; } else { state->ResourceDirtyLowerBounds = Min(state->ResourceDirtyLowerBounds, (int32)index); state->ResourceDirtyUpperBounds = Max(state->ResourceDirtyUpperBounds, (int32)index); } } void D3D11GPUContext::SetShaderSamplers(SHADER_PROGRAM_STAGE stage, uint32 index, ID3D11SamplerState *pSampler) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Samplers[index] == pSampler) return; if (state->Samplers[index] != nullptr) state->Samplers[index]->Release(); if ((state->Samplers[index] = pSampler) != nullptr) pSampler->AddRef(); if (state->SamplerDirtyLowerBounds < 0) { state->SamplerDirtyLowerBounds = index; state->SamplerDirtyUpperBounds = index; } else { state->SamplerDirtyLowerBounds = Min(state->SamplerDirtyLowerBounds, (int32)index); state->SamplerDirtyUpperBounds = Max(state->SamplerDirtyUpperBounds, (int32)index); } } void D3D11GPUContext::SetShaderUAVs(SHADER_PROGRAM_STAGE stage, uint32 index, ID3D11UnorderedAccessView *pResource) { ShaderStageState *state = &m_shaderStates[stage]; if (state->UAVs[index] == pResource) return; if (state->UAVs[index] != nullptr) state->UAVs[index]->Release(); if ((state->UAVs[index] = pResource) != nullptr) pResource->AddRef(); if (state->UAVDirtyLowerBounds < 0) { state->UAVDirtyLowerBounds = index; state->UAVDirtyUpperBounds = index; } else { state->UAVDirtyLowerBounds = Min(state->UAVDirtyLowerBounds, (int32)index); state->UAVDirtyUpperBounds = Max(state->UAVDirtyUpperBounds, (int32)index); } } void D3D11GPUContext::SynchronizeRenderTargetsAndUAVs() { ID3D11RenderTargetView *renderTargetViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; ID3D11DepthStencilView *depthStencilView = nullptr; uint32 renderTargetCount = 0; // get render target views if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // using swap chain if (m_pCurrentSwapChain != nullptr) { renderTargetViews[0] = m_pCurrentSwapChain->GetRenderTargetView(); depthStencilView = m_pCurrentSwapChain->GetDepthStencilView(); renderTargetCount = 1; } } else { // get render target views for (uint32 renderTargetIndex = 0; renderTargetIndex < m_nCurrentRenderTargets; renderTargetIndex++) { if (m_pCurrentRenderTargetViews[renderTargetIndex] != nullptr) { if ((renderTargetViews[renderTargetIndex] = m_pCurrentRenderTargetViews[renderTargetIndex]->GetD3DRTV()) != nullptr) renderTargetCount = renderTargetIndex + 1; } } // get depth stencil view if (m_pCurrentDepthBufferView != nullptr) depthStencilView = m_pCurrentDepthBufferView->GetD3DDSV(); } // get unordered access views ID3D11UnorderedAccessView *unorderedAccessViews[D3D11_PS_CS_UAV_REGISTER_COUNT]; UINT unorderedAccessViewInitialCounts[D3D11_PS_CS_UAV_REGISTER_COUNT]; uint32 unorderedAccessCount = 0; if (m_shaderStates[SHADER_PROGRAM_STAGE_PIXEL_SHADER].UAVBindCount > 0) { const ShaderStageState *state = &m_shaderStates[SHADER_PROGRAM_STAGE_PIXEL_SHADER]; for (uint32 i = 0; i < state->UAVBindCount; i++) unorderedAccessViewInitialCounts[i] = 0; unorderedAccessCount = state->UAVBindCount; } // call through if (unorderedAccessCount > 0) m_pD3DContext->OMSetRenderTargetsAndUnorderedAccessViews(renderTargetCount, (renderTargetCount > 0) ? renderTargetViews : nullptr, depthStencilView, 0, unorderedAccessCount, unorderedAccessViews, unorderedAccessViewInitialCounts); else m_pD3DContext->OMSetRenderTargets(renderTargetCount, (renderTargetCount > 0) ? renderTargetViews : nullptr, depthStencilView); } void D3D11GPUContext::SynchronizeShaderStates() { // switch shader // update states for (uint32 stage = 0; stage < SHADER_PROGRAM_STAGE_COUNT; stage++) { ShaderStageState *state = &m_shaderStates[stage]; // Constant buffers if (state->ConstantBufferDirtyLowerBounds >= 0) { int32 firstConstantBuffer = state->ConstantBufferDirtyLowerBounds; int32 setCount = state->ConstantBufferDirtyUpperBounds - state->ConstantBufferDirtyLowerBounds + 1; // find the new bind count uint32 searchMax = Max((uint32)state->ConstantBufferDirtyUpperBounds + 1, state->ConstantBufferBindCount); uint32 bindCount = 0; for (uint32 i = 0; i < searchMax; i++) { if (state->ConstantBuffers[i] != nullptr) bindCount = i + 1; } state->ConstantBufferBindCount = bindCount; state->ConstantBufferDirtyLowerBounds = state->ConstantBufferDirtyUpperBounds = -1; // update d3d switch (stage) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: m_pD3DContext->VSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; case SHADER_PROGRAM_STAGE_HULL_SHADER: m_pD3DContext->HSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: m_pD3DContext->DSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: m_pD3DContext->GSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: m_pD3DContext->PSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: m_pD3DContext->CSSetConstantBuffers(firstConstantBuffer, setCount, state->ConstantBuffers + firstConstantBuffer); break; } } // Resources if (state->ResourceDirtyLowerBounds >= 0) { int32 firstResource = state->ResourceDirtyLowerBounds; int32 setCount = state->ResourceDirtyUpperBounds - state->ResourceDirtyLowerBounds + 1; // find the new bind count uint32 searchMax = Max((uint32)state->ResourceDirtyUpperBounds + 1, state->ResourceBindCount); uint32 bindCount = 0; for (uint32 i = 0; i < searchMax; i++) { if (state->Resources[i] != nullptr) bindCount = i + 1; } state->ResourceBindCount = bindCount; state->ResourceDirtyLowerBounds = state->ResourceDirtyUpperBounds = -1; // update d3d switch (stage) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: m_pD3DContext->VSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; case SHADER_PROGRAM_STAGE_HULL_SHADER: m_pD3DContext->HSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: m_pD3DContext->DSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: m_pD3DContext->GSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: m_pD3DContext->PSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: m_pD3DContext->CSSetShaderResources(firstResource, setCount, state->Resources + firstResource); break; } } // Samplers if (state->SamplerDirtyLowerBounds >= 0) { int32 firstSampler = state->SamplerDirtyLowerBounds; int32 setCount = state->SamplerDirtyUpperBounds - state->SamplerDirtyLowerBounds + 1; // find the new bind count uint32 searchMax = Max((uint32)state->SamplerDirtyUpperBounds + 1, state->SamplerBindCount); uint32 bindCount = 0; for (uint32 i = 0; i < searchMax; i++) { if (state->Samplers[i] != nullptr) bindCount = i + 1; } state->SamplerBindCount = bindCount; state->SamplerDirtyLowerBounds = state->SamplerDirtyUpperBounds = -1; // update d3d switch (stage) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: m_pD3DContext->VSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; case SHADER_PROGRAM_STAGE_HULL_SHADER: m_pD3DContext->HSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: m_pD3DContext->DSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: m_pD3DContext->GSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: m_pD3DContext->PSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: m_pD3DContext->CSSetSamplers(firstSampler, setCount, state->Samplers + firstSampler); break; } } // UAVs if (state->UAVDirtyLowerBounds >= 0) { int32 firstUAV = state->UAVDirtyLowerBounds; int32 setCount = state->UAVDirtyUpperBounds - state->UAVDirtyLowerBounds + 1; // find the new bind count uint32 searchMax = Max((uint32)state->UAVDirtyUpperBounds + 1, state->UAVBindCount); uint32 bindCount = 0; for (uint32 i = 0; i < searchMax; i++) { if (state->UAVs[i] != nullptr) bindCount = i + 1; } state->UAVBindCount = bindCount; state->UAVDirtyLowerBounds = state->UAVDirtyUpperBounds = -1; // update d3d switch (stage) { case SHADER_PROGRAM_STAGE_PIXEL_SHADER: SynchronizeRenderTargetsAndUAVs(); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: m_pD3DContext->CSSetUnorderedAccessViews(firstUAV, setCount, state->UAVs + firstUAV, nullptr); break; } } } // update the local constant buffer for the active program m_pConstants->CommitGlobalConstantBufferChanges(); } void D3D11GPUContext::Draw(uint32 firstVertex, uint32 nVertices) { if (nVertices == 0) return; DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); m_pD3DContext->Draw(nVertices, firstVertex); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D11GPUContext::DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) { if (nVertices == 0 || nInstances == 0) return; DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); m_pD3DContext->DrawInstanced(nVertices, nInstances, firstVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D11GPUContext::DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) { if (nIndices == 0) return; DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); m_pD3DContext->DrawIndexed(nIndices, startIndex, baseVertex); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D11GPUContext::DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) { if (nIndices == 0) return; DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); m_pD3DContext->DrawIndexedInstanced(nIndices, nInstances, startIndex, baseVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D11GPUContext::Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) { DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); m_pD3DContext->Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D11GPUContext::DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) { const byte *pVerticesPtr = reinterpret_cast<const byte *>(pVertices); uint32 remainingVertices = nVertices; // setup draw DebugAssert(m_pCurrentShaderProgram != nullptr); SynchronizeShaderStates(); // while we still have vertices left to draw... while (remainingVertices > 0) { uint32 maxVertices = Min(nVertices, (m_userVertexBufferSize / vertexSize)); uint32 requestedSpace = maxVertices * vertexSize; DebugAssert(maxVertices > 0); HRESULT hResult; D3D11_MAPPED_SUBRESOURCE mappedSubResource; if ((m_userVertexBufferPosition + requestedSpace) < m_userVertexBufferSize) { // fit into remaining space hResult = m_pD3DContext->Map(m_pUserVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedSubResource); } else { // discard all of the buffer m_userVertexBufferPosition = 0; hResult = m_pD3DContext->Map(m_pUserVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedSubResource); } // should be valid if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::DrawUserPointer: Map failed with hResult %08X", hResult); return; } // fill buffer Y_memcpy(reinterpret_cast<byte *>(mappedSubResource.pData) + m_userVertexBufferPosition, pVerticesPtr, vertexSize * maxVertices); // unmap buffer m_pD3DContext->Unmap(m_pUserVertexBuffer, 0); // update vb m_pD3DContext->IASetVertexBuffers(0, 1, &m_pUserVertexBuffer, &vertexSize, &m_userVertexBufferPosition); // draw it m_pD3DContext->Draw(maxVertices, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); // increment positions m_userVertexBufferPosition += requestedSpace; pVerticesPtr += maxVertices * vertexSize; remainingVertices -= maxVertices; } // restore state if (m_currentVertexBufferBindCount > 0) { ID3D11Buffer *pD3DBuffer = (m_pCurrentVertexBuffers[0] != nullptr) ? m_pCurrentVertexBuffers[0]->GetD3DBuffer() : nullptr; UINT D3DOffset = m_currentVertexBufferOffsets[0]; UINT D3DStride = m_currentVertexBufferStrides[0]; m_pD3DContext->IASetVertexBuffers(0, 1, &pD3DBuffer, &D3DStride, &D3DOffset); } else { // unbind the temp one ID3D11Buffer *pNullD3DBuffer = NULL; UINT nullD3DOffsetStride = 0; m_pD3DContext->IASetVertexBuffers(0, 1, &pNullD3DBuffer, &nullD3DOffsetStride, &nullD3DOffsetStride); } } bool D3D11GPUContext::CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) { // textures have to be compatible, for now this means same texture format D3D11GPUTexture2D *pD3D11SourceTexture = static_cast<D3D11GPUTexture2D *>(pSourceTexture); D3D11GPUTexture2D *pD3D11DestinationTexture = static_cast<D3D11GPUTexture2D *>(pDestinationTexture); if (pD3D11SourceTexture->GetDesc()->Width != pD3D11DestinationTexture->GetDesc()->Width || pD3D11SourceTexture->GetDesc()->Height != pD3D11DestinationTexture->GetDesc()->Height || pD3D11SourceTexture->GetDesc()->Format != pD3D11DestinationTexture->GetDesc()->Format || pD3D11SourceTexture->GetDesc()->MipLevels != pD3D11DestinationTexture->GetDesc()->MipLevels) { return false; } // copy it m_pD3DContext->CopyResource(pD3D11DestinationTexture->GetD3DTexture(), pD3D11SourceTexture->GetD3DTexture()); return true; } bool D3D11GPUContext::CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) { // textures have to be compatible, for now this means same texture format D3D11GPUTexture2D *pD3D11SourceTexture = static_cast<D3D11GPUTexture2D *>(pSourceTexture); D3D11GPUTexture2D *pD3D11DestinationTexture = static_cast<D3D11GPUTexture2D *>(pDestinationTexture); if (pD3D11SourceTexture->GetDesc()->Format != pD3D11DestinationTexture->GetDesc()->Format || pD3D11SourceTexture->GetDesc()->MipLevels != pD3D11DestinationTexture->GetDesc()->MipLevels) { return false; } // create source box, copy it D3D11_BOX sourceBox = { sourceX, sourceY, 0, sourceX + width, sourceY + height, 1 }; m_pD3DContext->CopySubresourceRegion(pD3D11DestinationTexture->GetD3DTexture(), D3D11CalcSubresource(destMipLevel, 0, pD3D11DestinationTexture->GetDesc()->MipLevels), destX, destY, 0, pD3D11SourceTexture->GetD3DTexture(), D3D11CalcSubresource(sourceMipLevel, 0, pD3D11SourceTexture->GetDesc()->MipLevels), &sourceBox); return true; } void D3D11GPUContext::BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /*= RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST*/) { DebugAssert(m_nCurrentRenderTargets <= 1); // read source formats DebugAssert(static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE); DXGI_FORMAT sourceTextureFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Format); ID3D11Resource *pSourceResource = static_cast<D3D11GPUTexture2D *>(pTexture)->GetD3DTexture(); uint32 sourceTextureWidth = static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Width; uint32 sourceTextureHeight = static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Height; // read destination format DXGI_FORMAT destinationTextureFormat = DXGI_FORMAT_UNKNOWN; ID3D11Resource *pDestinationResource = NULL; uint32 destinationTextureWidth = 0, destinationTextureHeight = 0; if (m_nCurrentRenderTargets == 0) { destinationTextureFormat = static_cast<D3D11GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferFormat(); pDestinationResource = static_cast<D3D11GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferTexture(); destinationTextureWidth = static_cast<D3D11GPUOutputBuffer *>(m_pCurrentSwapChain)->GetWidth(); destinationTextureHeight = static_cast<D3D11GPUOutputBuffer *>(m_pCurrentSwapChain)->GetHeight(); } else { switch (m_pCurrentRenderTargetViews[0]->GetTargetTexture()->GetTextureType()) { case TEXTURE_TYPE_2D: destinationTextureFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Format); pDestinationResource = static_cast<D3D11GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetD3DTexture(); destinationTextureWidth = static_cast<D3D11GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Width; destinationTextureHeight = static_cast<D3D11GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Height; break; default: Panic("D3D11GPUContext::BlitFrameBuffer: Destination is an unsupported texture type"); return; } } // d3d11 can do a direct copy between identical types if (sourceTextureFormat == destinationTextureFormat && sourceWidth == destWidth && sourceHeight == destHeight) { // whole texture? if (sourceX == 0 && sourceY == 0 && destX == 0 && destY == 0 && sourceWidth == sourceTextureWidth && sourceHeight == sourceTextureHeight) { // use CopyResource m_pD3DContext->CopyResource(pDestinationResource, pSourceResource); return; } else { // use CopySubResourceRegion D3D11_BOX sourceBox = { sourceX, sourceY, 0, sourceX + sourceWidth, sourceY + sourceHeight, 1 }; m_pD3DContext->CopySubresourceRegion(pDestinationResource, 0, destX, destY, 0, pSourceResource, 0, &sourceBox); return; } } // use shader g_pRenderer->BlitTextureUsingShader(this, pTexture, sourceX, sourceY, sourceWidth, sourceHeight, 0, destX, destY, destWidth, destHeight, resizeFilter, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE); } void D3D11GPUContext::GenerateMips(GPUTexture *pTexture) { ID3D11ShaderResourceView *pSRV = nullptr; uint32 flags = 0; switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_1D: pSRV = static_cast<D3D11GPUTexture1D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTexture1D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_1D_ARRAY: pSRV = static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_2D: pSRV = static_cast<D3D11GPUTexture2D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_2D_ARRAY: pSRV = static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_3D: pSRV = static_cast<D3D11GPUTexture3D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTexture3D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_CUBE: pSRV = static_cast<D3D11GPUTextureCube *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTextureCube *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_CUBE_ARRAY: pSRV = static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetDesc()->Flags; break; } if (pSRV == nullptr || !(flags & GPU_TEXTURE_FLAG_GENERATE_MIPS)) { Log_ErrorPrintf("D3D11GPUContext::GenerateMips: Texture not created with GPU_TEXTURE_FLAG_GENERATE_MIPS."); return; } m_pD3DContext->GenerateMips(pSRV); } GPUCommandList *D3D11GPUContext::CreateCommandList() { return nullptr; } bool D3D11GPUContext::OpenCommandList(GPUCommandList *pCommandList) { return false; } bool D3D11GPUContext::CloseCommandList(GPUCommandList *pCommandList) { return false; } void D3D11GPUContext::ExecuteCommandList(GPUCommandList *pCommandList) { Panic("Not available."); } <file_sep>/Engine/Source/D3D11Renderer/PrecompiledHeader.h #pragma once #include "D3D11Renderer/D3D11Common.h" <file_sep>/Engine/Source/Renderer/Shaders/DepthOnlyShader.h #pragma once #include "Renderer/ShaderComponent.h" class DepthOnlyShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DepthOnlyShader, ShaderComponent); public: DepthOnlyShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { }; static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Editor/Source/Editor/MapEditor/moc_EditorMapWindow.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorMapWindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorMapWindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorMapWindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorMapWindow_t { QByteArrayData data[43]; char stringdata[1216]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorMapWindow_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorMapWindow_t qt_meta_stringdata_EditorMapWindow = { { QT_MOC_LITERAL(0, 0, 15), // "EditorMapWindow" QT_MOC_LITERAL(1, 16, 27), // "OnActionFileNewMapTriggered" QT_MOC_LITERAL(2, 44, 0), // "" QT_MOC_LITERAL(3, 45, 28), // "OnActionFileOpenMapTriggered" QT_MOC_LITERAL(4, 74, 28), // "OnActionFileSaveMapTriggered" QT_MOC_LITERAL(5, 103, 30), // "OnActionFileSaveMapAsTriggered" QT_MOC_LITERAL(6, 134, 29), // "OnActionFileCloseMapTriggered" QT_MOC_LITERAL(7, 164, 25), // "OnActionFileExitTriggered" QT_MOC_LITERAL(8, 190, 51), // "OnActionEditReferenceCoordina..." QT_MOC_LITERAL(9, 242, 7), // "checked" QT_MOC_LITERAL(10, 250, 51), // "OnActionEditReferenceCoordina..." QT_MOC_LITERAL(11, 302, 34), // "OnActionViewWorldOutlinerTrig..." QT_MOC_LITERAL(12, 337, 36), // "OnActionViewResourceBrowserTr..." QT_MOC_LITERAL(13, 374, 28), // "OnActionViewToolboxTriggered" QT_MOC_LITERAL(14, 403, 35), // "OnActionViewPropertyEditorTri..." QT_MOC_LITERAL(15, 439, 21), // "OnActionViewThemeNone" QT_MOC_LITERAL(16, 461, 21), // "OnActionViewThemeDark" QT_MOC_LITERAL(17, 483, 26), // "OnActionViewThemeDarkOther" QT_MOC_LITERAL(18, 510, 33), // "OnActionToolsMapEditModeTrigg..." QT_MOC_LITERAL(19, 544, 36), // "OnActionToolsEntityEditModeTr..." QT_MOC_LITERAL(20, 581, 38), // "OnActionToolsGeometryEditMode..." QT_MOC_LITERAL(21, 620, 48), // "OnActionToolsHeightfieldTerra..." QT_MOC_LITERAL(22, 669, 35), // "OnActionToolsCreateTerrainTri..." QT_MOC_LITERAL(23, 705, 35), // "OnActionToolsDeleteTerrainTri..." QT_MOC_LITERAL(24, 741, 40), // "OnActionToolsCreateBlockTerra..." QT_MOC_LITERAL(25, 782, 40), // "OnActionToolsDeleteBlockTerra..." QT_MOC_LITERAL(26, 823, 33), // "OnStatusBarGridSnapEnabledTog..." QT_MOC_LITERAL(27, 857, 34), // "OnStatusBarGridSnapIntervalCh..." QT_MOC_LITERAL(28, 892, 5), // "value" QT_MOC_LITERAL(29, 898, 34), // "OnStatusBarGridLinesVisibleTo..." QT_MOC_LITERAL(30, 933, 35), // "OnStatusBarGridLinesIntervalC..." QT_MOC_LITERAL(31, 969, 29), // "OnWorldOutlinerEntitySelected" QT_MOC_LITERAL(32, 999, 22), // "const EditorMapEntity*" QT_MOC_LITERAL(33, 1022, 7), // "pEntity" QT_MOC_LITERAL(34, 1030, 30), // "OnWorldOutlinerEntityActivated" QT_MOC_LITERAL(35, 1061, 32), // "OnToolboxTabWidgetCurrentChanged" QT_MOC_LITERAL(36, 1094, 5), // "index" QT_MOC_LITERAL(37, 1100, 31), // "OnPropertyEditorPropertyChanged" QT_MOC_LITERAL(38, 1132, 11), // "const char*" QT_MOC_LITERAL(39, 1144, 12), // "propertyName" QT_MOC_LITERAL(40, 1157, 13), // "propertyValue" QT_MOC_LITERAL(41, 1171, 25), // "OnFrameExecutionTriggered" QT_MOC_LITERAL(42, 1197, 18) // "timeSinceLastFrame" }, "EditorMapWindow\0OnActionFileNewMapTriggered\0" "\0OnActionFileOpenMapTriggered\0" "OnActionFileSaveMapTriggered\0" "OnActionFileSaveMapAsTriggered\0" "OnActionFileCloseMapTriggered\0" "OnActionFileExitTriggered\0" "OnActionEditReferenceCoordinateSystemLocalTriggered\0" "checked\0OnActionEditReferenceCoordinateSystemWorldTriggered\0" "OnActionViewWorldOutlinerTriggered\0" "OnActionViewResourceBrowserTriggered\0" "OnActionViewToolboxTriggered\0" "OnActionViewPropertyEditorTriggered\0" "OnActionViewThemeNone\0OnActionViewThemeDark\0" "OnActionViewThemeDarkOther\0" "OnActionToolsMapEditModeTriggered\0" "OnActionToolsEntityEditModeTriggered\0" "OnActionToolsGeometryEditModeTriggered\0" "OnActionToolsHeightfieldTerrainEditModeTriggered\0" "OnActionToolsCreateTerrainTriggered\0" "OnActionToolsDeleteTerrainTriggered\0" "OnActionToolsCreateBlockTerrainTriggered\0" "OnActionToolsDeleteBlockTerrainTriggered\0" "OnStatusBarGridSnapEnabledToggled\0" "OnStatusBarGridSnapIntervalChanged\0" "value\0OnStatusBarGridLinesVisibleToggled\0" "OnStatusBarGridLinesIntervalChanged\0" "OnWorldOutlinerEntitySelected\0" "const EditorMapEntity*\0pEntity\0" "OnWorldOutlinerEntityActivated\0" "OnToolboxTabWidgetCurrentChanged\0index\0" "OnPropertyEditorPropertyChanged\0" "const char*\0propertyName\0propertyValue\0" "OnFrameExecutionTriggered\0timeSinceLastFrame" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorMapWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 32, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 174, 2, 0x08 /* Private */, 3, 0, 175, 2, 0x08 /* Private */, 4, 0, 176, 2, 0x08 /* Private */, 5, 0, 177, 2, 0x08 /* Private */, 6, 0, 178, 2, 0x08 /* Private */, 7, 0, 179, 2, 0x08 /* Private */, 8, 1, 180, 2, 0x08 /* Private */, 10, 1, 183, 2, 0x08 /* Private */, 11, 1, 186, 2, 0x08 /* Private */, 12, 1, 189, 2, 0x08 /* Private */, 13, 1, 192, 2, 0x08 /* Private */, 14, 1, 195, 2, 0x08 /* Private */, 15, 0, 198, 2, 0x08 /* Private */, 16, 0, 199, 2, 0x08 /* Private */, 17, 0, 200, 2, 0x08 /* Private */, 18, 1, 201, 2, 0x08 /* Private */, 19, 1, 204, 2, 0x08 /* Private */, 20, 1, 207, 2, 0x08 /* Private */, 21, 1, 210, 2, 0x08 /* Private */, 22, 0, 213, 2, 0x08 /* Private */, 23, 0, 214, 2, 0x08 /* Private */, 24, 0, 215, 2, 0x08 /* Private */, 25, 0, 216, 2, 0x08 /* Private */, 26, 1, 217, 2, 0x08 /* Private */, 27, 1, 220, 2, 0x08 /* Private */, 29, 1, 223, 2, 0x08 /* Private */, 30, 1, 226, 2, 0x08 /* Private */, 31, 1, 229, 2, 0x08 /* Private */, 34, 1, 232, 2, 0x08 /* Private */, 35, 1, 235, 2, 0x08 /* Private */, 37, 2, 238, 2, 0x08 /* Private */, 41, 1, 243, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Double, 28, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Double, 28, QMetaType::Void, 0x80000000 | 32, 33, QMetaType::Void, 0x80000000 | 32, 33, QMetaType::Void, QMetaType::Int, 36, QMetaType::Void, 0x80000000 | 38, 0x80000000 | 38, 39, 40, QMetaType::Void, QMetaType::Float, 42, 0 // eod }; void EditorMapWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorMapWindow *_t = static_cast<EditorMapWindow *>(_o); switch (_id) { case 0: _t->OnActionFileNewMapTriggered(); break; case 1: _t->OnActionFileOpenMapTriggered(); break; case 2: _t->OnActionFileSaveMapTriggered(); break; case 3: _t->OnActionFileSaveMapAsTriggered(); break; case 4: _t->OnActionFileCloseMapTriggered(); break; case 5: _t->OnActionFileExitTriggered(); break; case 6: _t->OnActionEditReferenceCoordinateSystemLocalTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnActionEditReferenceCoordinateSystemWorldTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnActionViewWorldOutlinerTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->OnActionViewResourceBrowserTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnActionViewToolboxTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 11: _t->OnActionViewPropertyEditorTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->OnActionViewThemeNone(); break; case 13: _t->OnActionViewThemeDark(); break; case 14: _t->OnActionViewThemeDarkOther(); break; case 15: _t->OnActionToolsMapEditModeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 16: _t->OnActionToolsEntityEditModeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 17: _t->OnActionToolsGeometryEditModeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 18: _t->OnActionToolsHeightfieldTerrainEditModeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 19: _t->OnActionToolsCreateTerrainTriggered(); break; case 20: _t->OnActionToolsDeleteTerrainTriggered(); break; case 21: _t->OnActionToolsCreateBlockTerrainTriggered(); break; case 22: _t->OnActionToolsDeleteBlockTerrainTriggered(); break; case 23: _t->OnStatusBarGridSnapEnabledToggled((*reinterpret_cast< bool(*)>(_a[1]))); break; case 24: _t->OnStatusBarGridSnapIntervalChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 25: _t->OnStatusBarGridLinesVisibleToggled((*reinterpret_cast< bool(*)>(_a[1]))); break; case 26: _t->OnStatusBarGridLinesIntervalChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 27: _t->OnWorldOutlinerEntitySelected((*reinterpret_cast< const EditorMapEntity*(*)>(_a[1]))); break; case 28: _t->OnWorldOutlinerEntityActivated((*reinterpret_cast< const EditorMapEntity*(*)>(_a[1]))); break; case 29: _t->OnToolboxTabWidgetCurrentChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 30: _t->OnPropertyEditorPropertyChanged((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< const char*(*)>(_a[2]))); break; case 31: _t->OnFrameExecutionTriggered((*reinterpret_cast< float(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorMapWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_EditorMapWindow.data, qt_meta_data_EditorMapWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorMapWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorMapWindow::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorMapWindow.stringdata)) return static_cast<void*>(const_cast< EditorMapWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int EditorMapWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 32) qt_static_metacall(this, _c, _id, _a); _id -= 32; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 32) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 32; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/GameFramework/SunLightEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/SunLightEntity.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Engine/World.h" DEFINE_ENTITY_TYPEINFO(SunLightEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(SunLightEntity); BEGIN_ENTITY_PROPERTIES(SunLightEntity) PROPERTY_TABLE_MEMBER_BOOL("Enabled", 0, offsetof(SunLightEntity, m_bEnabled), OnEnabledPropertyChange, NULL) PROPERTY_TABLE_MEMBER_UINT("LightShadowFlags", 0, offsetof(SunLightEntity, m_iLightShadowFlags), OnShadowPropertyChange, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(SunLightEntity) END_ENTITY_SCRIPT_FUNCTIONS() SunLightEntity::SunLightEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_bEnabled(true), m_iLightShadowFlags(LIGHT_SHADOW_FLAG_CAST_STATIC_SHADOWS | LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS), m_timeOfDay(0), m_timeScale(1.0f), m_pRenderProxy(nullptr) { // create the render proxies m_pRenderProxy = new DirectionalLightRenderProxy(GetEntityID(), m_bEnabled, float3::One, float3::Zero, m_iLightShadowFlags, float3::NegativeUnitZ); // setup the object bounds SetBounds(AABox::MaxSize, Sphere::MaxSize); } SunLightEntity::~SunLightEntity() { m_pRenderProxy->Release(); } void SunLightEntity::SetEnabled(bool enabled) { m_bEnabled = enabled; OnEnabledPropertyChange(this); } void SunLightEntity::SetLightShadowFlags(uint32 lightShadowFlags) { m_iLightShadowFlags = lightShadowFlags; OnShadowPropertyChange(this); } void SunLightEntity::Create(uint32 entityID, const bool enabled /* = true */, uint32 shadowFlags /* = LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS */) { m_mobility = ENTITY_MOBILITY_MOVABLE; m_bEnabled = enabled; m_iLightShadowFlags = shadowFlags; Initialize(entityID, EmptyString); UpdateLight(); } bool SunLightEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; UpdateLight(); return true; } void SunLightEntity::Update(float timeSinceLastUpdate) { BaseClass::Update(timeSinceLastUpdate); m_timeOfDay += timeSinceLastUpdate * m_timeScale; while (m_timeOfDay >= 86400.0f) m_timeOfDay -= 86400.0f; /*m_timeOfDaySeconds += timeSinceLastUpdate * m_timeScale; while (m_timeOfDaySeconds >= 60.0f) { m_timeOfDayMinutes += 1.0f; m_timeOfDaySeconds -= 60.0f; while (m_timeOfDayMinutes >= 60.0f) { m_timeOfDayHours += 1.0f; m_timeOfDayMinutes -= 60.0f; while (m_timeOfDayHours >= 24.0f) m_timeOfDayHours -= 24.0f; } }*/ UpdateLight(); } void SunLightEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); pWorld->RegisterEntityForUpdate(this, 0.0f); // add render proxy to world pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void SunLightEntity::OnRemoveFromWorld(World *pWorld) { // remove render proxy from world pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); m_pWorld->UnregisterEntityForUpdate(this); BaseClass::OnRemoveFromWorld(pWorld); } void SunLightEntity::OnTransformChange() { BaseClass::OnTransformChange(); } void SunLightEntity::OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetEnabled(pEntity->m_bEnabled); } void SunLightEntity::OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetShadowFlags(pEntity->m_iLightShadowFlags); } void SunLightEntity::AddStep(float hours, float minutes, const float3 &direction, uint32 color, float brightness, float ambientTerm) { Step step; step.Hours = hours; step.Minutes = minutes; step.Direction = direction; step.Color = color; step.Brightness = brightness; step.AmbientTerm = ambientTerm; step.StartTime = hours * 3600.0f + minutes * 60.0f; m_steps.Add(step); SortSteps(); } void SunLightEntity::SortSteps() { m_steps.SortCB([](const Step &left, const Step &right) { return (left.StartTime < right.StartTime) ? -1 : ((left.StartTime == right.StartTime) ? 0 : 1); }); } void SunLightEntity::UpdateLight() { if (m_steps.IsEmpty()) return; // find closest step uint32 foundStepIndex = 0; for (uint32 stepIndex = 0; stepIndex < m_steps.GetSize(); stepIndex++) { const Step &step = m_steps[stepIndex]; if (step.StartTime <= m_timeOfDay) foundStepIndex = stepIndex; else break; } // get this and next const Step &thisStep = m_steps[foundStepIndex]; const Step &nextStep = m_steps[(foundStepIndex + 1) % m_steps.GetSize()]; float range = (nextStep.StartTime > thisStep.StartTime) ? (nextStep.StartTime - thisStep.StartTime) : (86400.0f - thisStep.StartTime + nextStep.StartTime); float factor = (m_timeOfDay - thisStep.StartTime) / range; // lerp values float3 direction = thisStep.Direction.Lerp(nextStep.Direction, factor); float4 color = PixelFormatHelpers::ConvertRGBAToFloat4(thisStep.Color).Lerp(PixelFormatHelpers::ConvertRGBAToFloat4(nextStep.Color), factor); float brightness = Math::Lerp(thisStep.Brightness, nextStep.Brightness, factor); float ambient = Math::Lerp(thisStep.AmbientTerm, nextStep.AmbientTerm, factor); // update light m_pRenderProxy->SetDirection(direction); m_pRenderProxy->SetLightColor(color.xyz() * brightness); m_pRenderProxy->SetAmbientColor(color.xyz() * ambient); } void SunLightEntity::AddDefaultSteps() { AddStep(0.0f, 0.0f, float3(0.0f, 1.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.1f, 0.1f); AddStep(1.5f, 0.0f, float3(0.5f, 0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.1f, 0.1f); AddStep(3.0f, 0.0f, float3(1.0f, 0.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.1f, 0.1f); AddStep(4.5f, 0.0f, float3(0.5f, -0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.275f, 0.2f); AddStep(6.0f, 0.0f, float3(0.0f, -1.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.6f, 0.3f); AddStep(7.5f, 0.0f, float3(-0.5f, -0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.7f, 0.3f); AddStep(9.0f, 0.0f, float3(-1.0f, 0.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.8f, 0.3f); AddStep(10.5f, 0.0f, float3(-0.5f, 0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 1.0f, 0.4f); AddStep(12.0f, 0.0f, float3(0.0f, 1.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 1.2f, 0.5f); AddStep(13.5f, 0.0f, float3(0.5f, 0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 1.0f, 0.45f); AddStep(15.0f, 0.0f, float3(1.0f, 0.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.8f, 0.4f); AddStep(17.5f, 0.0f, float3(0.5f, -0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.7f, 0.35f); AddStep(18.0f, 0.0f, float3(0.0f, -1.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.3f, 0.3f); AddStep(19.5f, 0.0f, float3(-0.5f, -0.5f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.2f, 0.2f); AddStep(21.0f, 0.0f, float3(-1.0f, 0.0f, -0.7f).Normalize(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), 0.1f, 0.1f); } void SunLightEntity::SetTimeOfDay(float hours, float minutes, float seconds) { m_timeOfDay = Y_fmodf(hours, 60.0f) * 3600.0f + Y_fmodf(minutes, 60.0f) * 60.0f + seconds; } void SunLightEntity::SetTimeOfDay(float secondInDay) { m_timeOfDay = Y_fmodf(secondInDay, 86400.0f); } <file_sep>/Engine/Source/Engine/ParticleSystemRenderProxy.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemRenderProxy.h" #include "Engine/Engine.h" #include "Renderer/Renderer.h" ParticleSystemRenderProxy::ParticleSystemRenderProxy(const ParticleSystem *pParticleSystem, uint32 entityID) : RenderProxy(entityID), m_pParticleSystem(pParticleSystem), m_pEmitterInstanceData(nullptr), m_pEmitterInstanceRenderData(nullptr), m_emitterCount(0), m_timeSinceLastUpdate(0.0f) { m_pParticleSystem->AddRef(); // create instance data CreateInstanceData(); } ParticleSystemRenderProxy::~ParticleSystemRenderProxy() { // cleanup instance data DeleteInstanceData(); m_pParticleSystem->Release(); } void ParticleSystemRenderProxy::CreateInstanceData() { DebugAssert(m_pParticleSystem->GetEmitterCount() > 0); m_emitterCount = m_pParticleSystem->GetEmitterCount(); m_pEmitterInstanceData = new ParticleSystemEmitter::InstanceData[m_emitterCount]; m_pEmitterInstanceRenderData = new ParticleSystemEmitter::InstanceRenderData[m_emitterCount]; for (uint32 emitterIndex = 0; emitterIndex < m_emitterCount; emitterIndex++) { const ParticleSystemEmitter *pEmitter = m_pParticleSystem->GetEmitter(emitterIndex); pEmitter->InitializeInstance(&m_pEmitterInstanceData[emitterIndex]); pEmitter->InitializeRenderData(&m_pEmitterInstanceRenderData[emitterIndex]); } } void ParticleSystemRenderProxy::DeleteInstanceData() { for (uint32 emitterIndex = 0; emitterIndex < m_emitterCount; emitterIndex++) { const ParticleSystemEmitter *pEmitter = m_pParticleSystem->GetEmitter(emitterIndex); pEmitter->CleanupRenderData(&m_pEmitterInstanceRenderData[emitterIndex]); pEmitter->CleanupInstance(&m_pEmitterInstanceData[emitterIndex]); } delete[] m_pEmitterInstanceRenderData; m_pEmitterInstanceRenderData = nullptr; delete[] m_pEmitterInstanceData; m_pEmitterInstanceData = nullptr; m_emitterCount = 0; } void ParticleSystemRenderProxy::SetParticleSystem(const ParticleSystem *pParticleSystem) { DebugAssert(m_pParticleSystem != nullptr && pParticleSystem != nullptr); DeleteInstanceData(); if (m_pParticleSystem != pParticleSystem) { m_pParticleSystem->Release(); m_pParticleSystem = pParticleSystem; m_pParticleSystem->AddRef(); } CreateInstanceData(); } void ParticleSystemRenderProxy::Reset() { // fixme properly DeleteInstanceData(); CreateInstanceData(); } void ParticleSystemRenderProxy::Update(const Transform *pBaseTransform, float deltaTime) { m_timeSinceLastUpdate += deltaTime; if (m_timeSinceLastUpdate >= m_pParticleSystem->GetUpdateInterval()) { // simulate each emitter for (uint32 emitterIndex = 0; emitterIndex < m_emitterCount; emitterIndex++) m_pParticleSystem->GetEmitter(emitterIndex)->UpdateInstance(&m_pEmitterInstanceData[emitterIndex], pBaseTransform, g_pEngine->GetRandomNumberGenerator(), m_timeSinceLastUpdate); // queue update on render thread ReferenceCountedHolder<ParticleSystemRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis]() { // update render thread copy AABox systemBoundingBox; for (uint32 emitterIndex = 0; emitterIndex < pThis->m_emitterCount; emitterIndex++) { pThis->m_pParticleSystem->GetEmitter(emitterIndex)->UpdateRenderData(&pThis->m_pEmitterInstanceData[emitterIndex], &pThis->m_pEmitterInstanceRenderData[emitterIndex]); if (emitterIndex == 0) systemBoundingBox.SetBounds(pThis->m_pEmitterInstanceRenderData[emitterIndex].BoundingBox); else systemBoundingBox.Merge(pThis->m_pEmitterInstanceRenderData[emitterIndex].BoundingBox); } // update bounding box if (systemBoundingBox != pThis->GetBoundingBox()) pThis->SetBounds(systemBoundingBox, Sphere::FromAABox(systemBoundingBox)); }); // schedule next update m_timeSinceLastUpdate = 0.0f; } } void ParticleSystemRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // Use the emitter slot index as the user data for (uint32 emitterIndex = 0; emitterIndex < m_pParticleSystem->GetEmitterCount(); emitterIndex++) m_pParticleSystem->GetEmitter(emitterIndex)->QueueForRender(this, emitterIndex, &m_pEmitterInstanceRenderData[emitterIndex], pCamera, pRenderQueue); } void ParticleSystemRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { uint32 emitterIndex = pQueueEntry->UserData[0]; DebugAssert(emitterIndex < m_emitterCount); const ParticleSystemEmitter *pEmitter = m_pParticleSystem->GetEmitter(pQueueEntry->UserData[0]); pEmitter->SetupForDraw(&m_pEmitterInstanceRenderData[emitterIndex], pCamera, pQueueEntry, pCommandList, pShaderProgram); } void ParticleSystemRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { uint32 emitterIndex = pQueueEntry->UserData[0]; DebugAssert(emitterIndex < m_emitterCount); const ParticleSystemEmitter *pEmitter = m_pParticleSystem->GetEmitter(pQueueEntry->UserData[0]); pEmitter->DrawQueueEntry(&m_pEmitterInstanceRenderData[emitterIndex], pCamera, pQueueEntry, pCommandList); } <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUContext.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUCommandList.h" #include "D3D12Renderer/D3D12GPUBuffer.h" #include "D3D12Renderer/D3D12GPUTexture.h" #include "D3D12Renderer/D3D12GPUShaderProgram.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12Helpers.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(D3D12RenderBackend); D3D12GPUContext::D3D12GPUContext(D3D12GPUDevice *pDevice, ID3D12Device *pD3DDevice, D3D12CommandQueue *pGraphicsCommandQueue) : m_pDevice(pDevice) , m_pD3DDevice(pD3DDevice) , m_pGraphicsCommandQueue(pGraphicsCommandQueue) , m_pConstants(nullptr) , m_pCommandList(nullptr) , m_pCurrentScratchBuffer(nullptr) , m_pCurrentScratchViewHeap(nullptr) , m_pCurrentScratchSamplerHeap(nullptr) , m_commandCounter(0) { m_pDevice->AddRef(); m_pDevice->SetImmediateContext(this); // null memory Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); m_currentTopology = DRAW_TOPOLOGY_UNDEFINED; m_currentD3DTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; // null current states Y_memzero(m_pCurrentVertexBuffers, sizeof(m_pCurrentVertexBuffers)); Y_memzero(m_currentVertexBufferOffsets, sizeof(m_currentVertexBufferOffsets)); Y_memzero(m_currentVertexBufferStrides, sizeof(m_currentVertexBufferStrides)); m_currentVertexBufferBindCount = 0; m_pCurrentIndexBuffer = nullptr; m_currentIndexFormat = GPU_INDEX_FORMAT_COUNT; m_currentIndexBufferOffset = 0; m_pCurrentShaderProgram = nullptr; m_shaderStates.Resize(SHADER_PROGRAM_STAGE_COUNT); m_shaderStates.ZeroContents(); m_perDrawConstantBuffers.Resize(D3D12_LEGACY_GRAPHICS_ROOT_PER_DRAW_CONSTANT_BUFFER_SLOTS); m_perDrawConstantBufferCount = 0; m_perDrawConstantBuffersDirty = false; m_pCurrentRasterizerState = nullptr; m_pCurrentDepthStencilState = nullptr; m_currentDepthStencilRef = 0; m_pCurrentBlendState = nullptr; m_currentBlendStateBlendFactors.SetZero(); m_pipelineChanged = false; m_pCurrentSwapChain = nullptr; Y_memzero(m_pCurrentRenderTargetViews, sizeof(m_pCurrentRenderTargetViews)); m_pCurrentDepthBufferView = nullptr; m_nCurrentRenderTargets = 0; m_pCurrentPredicate = nullptr; //m_pCurrentPredicateD3D = nullptr; m_predicateBypassCount = 0; } D3D12GPUContext::~D3D12GPUContext() { // execute all pending commands and wait until they're completed if (m_pCommandList != nullptr) { CloseAndExecuteCommandList(false, false); m_pGraphicsCommandQueue->ReleaseCommandList(m_pCommandList); } // release everything back to the queue (not done above because we don't want another one after this) uint64 syncFence = m_pGraphicsCommandQueue->CreateSynchronizationPoint(); if (m_pCurrentCommandAllocator != nullptr) { m_pGraphicsCommandQueue->ReleaseCommandAllocator(m_pCurrentCommandAllocator, syncFence); m_pCurrentCommandAllocator = nullptr; } if (m_pCurrentScratchBuffer != nullptr) { m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer, syncFence); m_pCurrentScratchBuffer = nullptr; } if (m_pCurrentScratchViewHeap != nullptr) { m_pGraphicsCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap, syncFence); m_pCurrentScratchViewHeap = nullptr; } if (m_pCurrentScratchSamplerHeap != nullptr) { m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap, syncFence); m_pCurrentScratchSamplerHeap = nullptr; } // wait for the gpu to catch up m_pGraphicsCommandQueue->WaitForFence(syncFence); #if 0 // clear any state ClearState(true, true, true, true); m_pD3DContext->OMSetRenderTargets(0, nullptr, nullptr); m_pD3DContext->ClearState(); m_pD3DContext->Flush(); DebugAssert(m_predicateBypassCount == 0); if (m_pCurrentPredicateD3D != nullptr) { m_pD3DContext->SetPredication(nullptr, FALSE); m_pCurrentPredicateD3D = nullptr; } SAFE_RELEASE(m_pCurrentPredicate); #endif // release our references to states and targets. d3d references will die when the device goes down. for (uint32 i = 0; i < countof(m_pCurrentVertexBuffers); i++) { SAFE_RELEASE(m_pCurrentVertexBuffers[i]); } SAFE_RELEASE(m_pCurrentIndexBuffer); SAFE_RELEASE(m_pCurrentShaderProgram); m_shaderStates.Obliterate(); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; delete[] constantBuffer->pLocalMemory; } SAFE_RELEASE(m_pCurrentRasterizerState); SAFE_RELEASE(m_pCurrentDepthStencilState); SAFE_RELEASE(m_pCurrentBlendState); for (uint32 i = 0; i < countof(m_pCurrentRenderTargetViews); i++) { SAFE_RELEASE(m_pCurrentRenderTargetViews[i]); } SAFE_RELEASE(m_pCurrentDepthBufferView); delete m_pConstants; SAFE_RELEASE(m_pCurrentSwapChain); m_pDevice->SetThreadCopyCommandQueue(nullptr); m_pDevice->SetImmediateContext(nullptr); m_pDevice->Release(); } void D3D12GPUContext::ResourceBarrier(ID3D12Resource *pResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState) { D3D12_RESOURCE_BARRIER resourceBarrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { pResource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, beforeState, afterState } }; m_pCommandList->ResourceBarrier(1, &resourceBarrier); m_commandCounter++; } void D3D12GPUContext::ResourceBarrier(ID3D12Resource *pResource, uint32 subResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState) { D3D12_RESOURCE_BARRIER resourceBarrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { pResource, subResource, beforeState, afterState } }; m_pCommandList->ResourceBarrier(1, &resourceBarrier); m_commandCounter++; } bool D3D12GPUContext::Create() { // allocate constants m_pConstants = new GPUContextConstants(m_pDevice, this); CreateConstantBuffers(); // create command list if (!CreateInternalCommandList()) return false; // reset to known state ClearState(true, true, true, true); return true; } void D3D12GPUContext::CreateConstantBuffers() { // allocate constant buffer storage const ShaderConstantBuffer::RegistryType *registry = ShaderConstantBuffer::GetRegistry(); m_constantBuffers.Resize(registry->GetNumTypes()); m_constantBuffers.ZeroContents(); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; // applicable to us? const ShaderConstantBuffer *declaration = registry->GetTypeInfoByIndex(i); if (declaration == nullptr) continue; if (declaration->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && declaration->GetPlatformRequirement() != RENDERER_PLATFORM_D3D12) continue; if (declaration->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && declaration->GetMinimumFeatureLevel() > m_pDevice->GetFeatureLevel()) continue; // set size so we know to allocate it later or on demand constantBuffer->Size = declaration->GetBufferSize(); constantBuffer->DirtyLowerBounds = constantBuffer->DirtyUpperBounds = -1; constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; Y_memzero(constantBuffer->pLocalMemory, constantBuffer->Size); // create per-draw constant buffers constantBuffer->PerDraw = (declaration->GetUpdateFrequency() == SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_DRAW); } } bool D3D12GPUContext::CreateInternalCommandList() { // allocate everything m_pCurrentCommandAllocator = m_pGraphicsCommandQueue->RequestCommandAllocator(); m_pCurrentScratchBuffer = m_pGraphicsCommandQueue->RequestLinearBufferHeap(); m_pCurrentScratchViewHeap = m_pGraphicsCommandQueue->RequestLinearViewHeap(); m_pCurrentScratchSamplerHeap = m_pGraphicsCommandQueue->RequestLinearSamplerHeap(); m_pCommandList = m_pGraphicsCommandQueue->RequestAndOpenCommandList(m_pCurrentCommandAllocator); // issue copies on the graphics queue m_pDevice->SetThreadCopyCommandQueue(m_pCommandList); // set initial state ResetCommandList(false, false); return true; } void D3D12GPUContext::BeginFrame() { } void D3D12GPUContext::Flush() { CloseAndExecuteCommandList(false, false); ResetCommandList(true, false); } void D3D12GPUContext::Finish() { // allocator refresh not needed because of wait CloseAndExecuteCommandList(true, false); ResetCommandList(true, false); } void D3D12GPUContext::CloseAndExecuteCommandList(bool waitForCompletion, bool forceWithoutDrawCommands) { // transition pending resources before execution. m_pDevice->TransitionPendingResources(m_pGraphicsCommandQueue); // close the command list HRESULT hResult = m_pCommandList->Close(); if (SUCCEEDED(hResult)) { // execute it if (m_commandCounter > 0 || forceWithoutDrawCommands) m_pGraphicsCommandQueue->ExecuteCommandList(m_pCommandList); // wait for the gpu to catch up if (waitForCompletion) { // re-use the same allocators since the gpu has caught up uint64 fenceValue = m_pGraphicsCommandQueue->CreateSynchronizationPoint(); m_pGraphicsCommandQueue->WaitForFence(fenceValue); m_pGraphicsCommandQueue->ReleaseStaleResources(); m_pCurrentScratchBuffer->Reset(true); m_pCurrentScratchViewHeap->Reset(); m_pCurrentScratchSamplerHeap->Reset(); } } else { Log_ErrorPrintf("ID3D12CommandList::Close failed with hResult %08X, some commands may not be executed.", hResult); // mark command list as failed and get a new list m_pGraphicsCommandQueue->ReleaseFailedCommandList(m_pCommandList); m_pCommandList = m_pGraphicsCommandQueue->RequestCommandList(); // issue copies on the graphics queue m_pDevice->SetThreadCopyCommandQueue(m_pCommandList); // since the command list was not executed, allocators can be re-used m_pCurrentScratchBuffer->Reset(true); m_pCurrentScratchViewHeap->Reset(); m_pCurrentScratchSamplerHeap->Reset(); } // clear command counter m_commandCounter = 0; } void D3D12GPUContext::ResetCommandList(bool restoreState, bool refreshAllocators) { // allocator refresh needed? if (refreshAllocators) { // get new allocators GetNewAllocators(m_pGraphicsCommandQueue->GetNextFenceValue()); // take this opportunity to clean up stale resources (even if we're not waiting, it's a good place, since the gpu will be busy for a while) m_pGraphicsCommandQueue->ReleaseStaleResources(); } // re-open the command list HRESULT hResult = m_pCommandList->Reset(m_pCurrentCommandAllocator, nullptr); if (FAILED(hResult)) Log_WarningPrintf("ID3D12CommandList:Reset failed with hResult %08X", hResult); // restore state? if (restoreState) { // graphics root m_pCommandList->SetGraphicsRootSignature(m_pDevice->GetLegacyGraphicsRootSignature()); m_pCommandList->SetComputeRootSignature(m_pDevice->GetLegacyComputeRootSignature()); UpdateShaderDescriptorHeaps(); // pipeline state UpdatePipelineState(true); // render targets SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); // other stuff D3D12_VIEWPORT D3D12Viewport = { (float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, (float)m_currentViewport.Width, (float)m_currentViewport.Height, m_currentViewport.MinDepth, m_currentViewport.MaxDepth }; m_pCommandList->RSSetViewports(1, &D3D12Viewport); m_pCommandList->IASetPrimitiveTopology(D3D12Helpers::GetD3D12PrimitiveTopology(m_currentTopology)); m_pCommandList->OMSetBlendFactor(m_currentBlendStateBlendFactors); m_pCommandList->OMSetStencilRef(m_currentDepthStencilRef); // vertex buffers if (m_currentVertexBufferBindCount > 0) { D3D12_VERTEX_BUFFER_VIEW vertexBufferViews[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; for (uint32 i = 0; i < m_currentVertexBufferBindCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) { vertexBufferViews[i].BufferLocation = m_pCurrentVertexBuffers[i]->GetD3DResource()->GetGPUVirtualAddress() + m_currentVertexBufferOffsets[i]; vertexBufferViews[i].SizeInBytes = m_pCurrentVertexBuffers[i]->GetDesc()->Size - m_currentVertexBufferOffsets[i]; vertexBufferViews[i].StrideInBytes = m_currentVertexBufferStrides[i]; } else { Y_memzero(&vertexBufferViews[i], sizeof(D3D12_VERTEX_BUFFER_VIEW)); } } m_pCommandList->IASetVertexBuffers(0, m_currentVertexBufferBindCount, vertexBufferViews); } if (m_pCurrentIndexBuffer != nullptr) { D3D12_INDEX_BUFFER_VIEW bufferView; bufferView.BufferLocation = m_pCurrentIndexBuffer->GetD3DResource()->GetGPUVirtualAddress() + m_currentIndexBufferOffset; bufferView.SizeInBytes = m_pCurrentIndexBuffer->GetDesc()->Size - m_currentIndexBufferOffset; bufferView.Format = (m_currentIndexFormat == GPU_INDEX_FORMAT_UINT16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; m_pCommandList->IASetIndexBuffer(&bufferView); } } else { // graphics root m_pCommandList->SetGraphicsRootSignature(m_pDevice->GetLegacyGraphicsRootSignature()); m_pCommandList->SetComputeRootSignature(m_pDevice->GetLegacyComputeRootSignature()); UpdateShaderDescriptorHeaps(); // pipeline state m_shaderStates.ZeroContents(); SAFE_RELEASE(m_pCurrentShaderProgram); m_perDrawConstantBuffers.ZeroContents(); m_perDrawConstantBufferCount = 0; m_perDrawConstantBuffersDirty = false; m_pipelineChanged = false; UpdatePipelineState(true); // render targets -- still needs to be re-synced for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) SAFE_RELEASE(m_pCurrentRenderTargetViews[i]); SAFE_RELEASE(m_pCurrentDepthBufferView); m_nCurrentRenderTargets = 0; SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); // input assembler for (uint32 i = 0; i < m_currentVertexBufferBindCount; i++) { SAFE_RELEASE(m_pCurrentVertexBuffers[i]); m_currentVertexBufferStrides[i] = 0; m_currentVertexBufferOffsets[i] = 0; } m_currentVertexBufferBindCount = 0; SAFE_RELEASE(m_pCurrentIndexBuffer); // predicate //SAFE_RELEASE(m_pCurrentPredicate); // other stuff m_currentTopology = DRAW_TOPOLOGY_UNDEFINED; m_currentD3DTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; m_currentBlendStateBlendFactors.SetZero(); m_currentDepthStencilRef = 0; Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); } } void D3D12GPUContext::GetNewAllocators(uint64 fenceValue) { // get a new set of allocators. if anything fails, wait for the gpu, and re-use the current one. ID3D12CommandAllocator *pCommandAllocator = m_pGraphicsCommandQueue->RequestCommandAllocator(); if (pCommandAllocator == nullptr) { m_pGraphicsCommandQueue->WaitForFence(fenceValue); pCommandAllocator->Reset(); } else { m_pGraphicsCommandQueue->ReleaseCommandAllocator(m_pCurrentCommandAllocator, fenceValue); m_pCurrentCommandAllocator = pCommandAllocator; } D3D12LinearBufferHeap *pBufferHeap = m_pGraphicsCommandQueue->RequestLinearBufferHeap(); if (pBufferHeap == nullptr) { m_pGraphicsCommandQueue->WaitForFence(fenceValue); pBufferHeap->Reset(true); } else { m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer, fenceValue); m_pCurrentScratchBuffer = pBufferHeap; } D3D12LinearDescriptorHeap *pViewHeap = m_pGraphicsCommandQueue->RequestLinearViewHeap(); if (pViewHeap == nullptr) { m_pGraphicsCommandQueue->WaitForFence(fenceValue); pViewHeap->Reset(); } else { m_pGraphicsCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap, fenceValue); m_pCurrentScratchViewHeap = pViewHeap; } D3D12LinearDescriptorHeap *pSamplerHeap = m_pGraphicsCommandQueue->RequestLinearSamplerHeap(); if (pSamplerHeap == nullptr) { m_pGraphicsCommandQueue->WaitForFence(fenceValue); pSamplerHeap->Reset(); } else { m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap, fenceValue); m_pCurrentScratchSamplerHeap = pSamplerHeap; } // update per-draw constant buffers, they need new pointers. for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *pConstantBuffer = &m_constantBuffers[i]; if (pConstantBuffer->PerDraw) { void *pCPUPointer; D3D12_GPU_VIRTUAL_ADDRESS pGPUAddress; if (AllocateScratchBufferMemory(pConstantBuffer->Size, D3D12_CONSTANT_BUFFER_ALIGNMENT, nullptr, nullptr, &pCPUPointer, &pGPUAddress)) { Y_memcpy(pCPUPointer, pConstantBuffer->pLocalMemory, pConstantBuffer->Size); pConstantBuffer->LastAddress = pGPUAddress; } } } } void D3D12GPUContext::UpdateShaderDescriptorHeaps() { ID3D12DescriptorHeap *pDescriptorHeaps[] = { m_pCurrentScratchViewHeap->GetD3DHeap(), m_pCurrentScratchSamplerHeap->GetD3DHeap() }; m_pCommandList->SetDescriptorHeaps(countof(pDescriptorHeaps), pDescriptorHeaps); } bool D3D12GPUContext::GetPerDrawConstantBufferGPUAddress(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS *pAddress) { DebugAssert(index < m_constantBuffers.GetSize()); if (m_constantBuffers[index].PerDraw) { *pAddress = m_constantBuffers[index].LastAddress; return true; } return false; } bool D3D12GPUContext::AllocateScratchBufferMemory(uint32 size, uint32 alignment, ID3D12Resource **ppScratchBufferResource, uint32 *pScratchBufferOffset, void **ppCPUPointer, D3D12_GPU_VIRTUAL_ADDRESS *pGPUAddress) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (size > m_pGraphicsCommandQueue->GetLinearBufferHeapSize()) return false; uint32 offset; if (!m_pCurrentScratchBuffer->AllocateAligned(size, alignment, &offset)) { // get a new buffer. we can't release the buffer with a new fence, since the command line hasn't been executed yet. D3D12LinearBufferHeap *pNewBuffer = m_pGraphicsCommandQueue->RequestLinearBufferHeap(); DebugAssert(pNewBuffer != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer); m_pCurrentScratchBuffer = pNewBuffer; // retry allocation on new buffer if (!m_pCurrentScratchBuffer->AllocateAligned(size, alignment, &offset)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } if (ppScratchBufferResource != nullptr) *ppScratchBufferResource = m_pCurrentScratchBuffer->GetResource(); if (pScratchBufferOffset != nullptr) *pScratchBufferOffset = offset; if (ppCPUPointer != nullptr) *ppCPUPointer = m_pCurrentScratchBuffer->GetPointer(offset); if (pGPUAddress != nullptr) *pGPUAddress = m_pCurrentScratchBuffer->GetGPUAddress(offset); return true; } bool D3D12GPUContext::AllocateScratchView(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (count > m_pGraphicsCommandQueue->GetLinearViewHeapSize()) return false; if (!m_pCurrentScratchViewHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { // get a new buffer D3D12LinearDescriptorHeap *pNewHeap = m_pGraphicsCommandQueue->RequestLinearViewHeap(); DebugAssert(pNewHeap != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap); m_pCurrentScratchViewHeap = pNewHeap; UpdateShaderDescriptorHeaps(); // retry allocation on new buffer if (!m_pCurrentScratchViewHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } return true; } bool D3D12GPUContext::AllocateScratchSamplers(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (count > m_pGraphicsCommandQueue->GetLinearSamplerHeapSize()) return false; if (!m_pCurrentScratchSamplerHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { // get a new buffer D3D12LinearDescriptorHeap *pNewHeap = m_pGraphicsCommandQueue->RequestLinearSamplerHeap(); DebugAssert(pNewHeap != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap); m_pCurrentScratchSamplerHeap = pNewHeap; UpdateShaderDescriptorHeaps(); // retry allocation on new buffer if (!m_pCurrentScratchSamplerHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } return true; } void D3D12GPUContext::GetCurrentRenderTargetDimensions(uint32 *width, uint32 *height) { uint3 textureDimensions; if (m_pCurrentDepthBufferView != nullptr) textureDimensions = Renderer::GetTextureDimensions(m_pCurrentDepthBufferView->GetTargetTexture()); else if (m_nCurrentRenderTargets > 0) textureDimensions = Renderer::GetTextureDimensions(m_pCurrentRenderTargetViews[0]->GetTargetTexture()); else if (m_pCurrentSwapChain != nullptr) textureDimensions.Set(m_pCurrentSwapChain->GetWidth(), m_pCurrentSwapChain->GetHeight(), 1); else textureDimensions.Set(1, 1, 1); *width = textureDimensions.x; *height = textureDimensions.y; } D3D12_RESOURCE_STATES D3D12GPUContext::GetCurrentResourceState(GPUResource *pResource) { GPU_RESOURCE_TYPE resourceType = pResource->GetResourceType(); if (resourceType == GPU_RESOURCE_TYPE_BUFFER) { for (uint32 i = 0; i < m_currentVertexBufferBindCount; i++) { if (m_pCurrentVertexBuffers[i] == pResource) return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; } if (IsBoundAsUnorderedAccess(pResource)) return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; return static_cast<D3D12GPUBuffer *>(pResource)->GetDefaultResourceState(); } else { if (resourceType >= GPU_RESOURCE_TYPE_TEXTURE1D && resourceType <= GPU_RESOURCE_TYPE_DEPTH_TEXTURE) { if (IsBoundAsRenderTarget(static_cast<GPUTexture *>(pResource))) return D3D12_RESOURCE_STATE_RENDER_TARGET; if (IsBoundAsDepthBuffer(static_cast<GPUTexture *>(pResource))) return D3D12_RESOURCE_STATE_DEPTH_WRITE; switch (resourceType) { case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<D3D12GPUTexture2D *>(pResource)->GetDefaultResourceState(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<D3D12GPUTexture2DArray *>(pResource)->GetDefaultResourceState(); } } } return D3D12_RESOURCE_STATE_COMMON; } bool D3D12GPUContext::IsBoundAsRenderTarget(GPUTexture *pTexture) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr && m_pCurrentRenderTargetViews[i]->GetTargetTexture() == pTexture) return true; } return false; } bool D3D12GPUContext::IsBoundAsDepthBuffer(GPUTexture *pTexture) { return (m_pCurrentDepthBufferView != nullptr && m_pCurrentDepthBufferView->GetTargetTexture() == pTexture); } bool D3D12GPUContext::IsBoundAsUnorderedAccess(GPUResource *pResource) { // @TODO check UAVs return false; } void D3D12GPUContext::UpdateScissorRect() { if (m_pCurrentRasterizerState != nullptr && m_pCurrentRasterizerState->GetDesc()->ScissorEnable) { D3D12_RECT scissorRect = { (LONG)m_scissorRect.Left, (LONG)m_scissorRect.Top, (LONG)m_scissorRect.Right, (LONG)m_scissorRect.Bottom }; m_pCommandList->RSSetScissorRects(1, &scissorRect); } else { // get current render target dimensions uint32 width, height; GetCurrentRenderTargetDimensions(&width, &height); // set scissor D3D12_RECT scissorRect = { (LONG)0, (LONG)0, (LONG)width, (LONG)height }; m_pCommandList->RSSetScissorRects(1, &scissorRect); } } void D3D12GPUContext::ClearState(bool clearShaders /* = true */, bool clearBuffers /* = true */, bool clearStates /* = true */, bool clearRenderTargets /* = true */) { if (clearShaders) { SetShaderProgram(nullptr); m_shaderStates.ZeroContents(); } if (clearBuffers) { if (m_currentVertexBufferBindCount > 0) { static GPUBuffer *nullVertexBuffers[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { nullptr }; static const uint32 nullSizeOrOffset[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { 0 }; SetVertexBuffers(0, m_currentVertexBufferBindCount, nullVertexBuffers, nullSizeOrOffset, nullSizeOrOffset); } if (m_pCurrentIndexBuffer != nullptr) SetIndexBuffer(nullptr, GPU_INDEX_FORMAT_UINT16, 0); } if (clearStates) { SetRasterizerState(m_pDevice->GetDefaultRasterizerState()); SetDepthStencilState(m_pDevice->GetDefaultDepthStencilState(), 0); SetBlendState(m_pDevice->GetDefaultBlendState()); SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); RENDERER_SCISSOR_RECT scissor(0, 0, 0, 0); SetFullViewport(nullptr); SetScissorRect(&scissor); } if (clearRenderTargets) { SetRenderTargets(0, nullptr, nullptr); } } GPURasterizerState *D3D12GPUContext::GetRasterizerState() { return m_pCurrentRasterizerState; } void D3D12GPUContext::SetRasterizerState(GPURasterizerState *pRasterizerState) { if (m_pCurrentRasterizerState != pRasterizerState) { bool oldScissorState = (m_pCurrentRasterizerState != nullptr) ? m_pCurrentRasterizerState->GetDesc()->ScissorEnable : false; if (m_pCurrentRasterizerState != nullptr) m_pCurrentRasterizerState->Release(); bool newScissorState = (pRasterizerState != nullptr) ? pRasterizerState->GetDesc()->ScissorEnable : false; if ((m_pCurrentRasterizerState = static_cast<D3D12GPURasterizerState *>(pRasterizerState)) != nullptr) m_pCurrentRasterizerState->AddRef(); m_pipelineChanged = true; // set scissor rect if scissor is not enabled if (oldScissorState != newScissorState) UpdateScissorRect(); } } GPUDepthStencilState *D3D12GPUContext::GetDepthStencilState() { return m_pCurrentDepthStencilState; } uint8 D3D12GPUContext::GetDepthStencilStateStencilRef() { return m_currentDepthStencilRef; } void D3D12GPUContext::SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) { if (m_pCurrentDepthStencilState != pDepthStencilState) { if (m_pCurrentDepthStencilState != nullptr) m_pCurrentDepthStencilState->Release(); if ((m_pCurrentDepthStencilState = static_cast<D3D12GPUDepthStencilState *>(pDepthStencilState)) != nullptr) m_pCurrentDepthStencilState->AddRef(); m_pipelineChanged = true; } if (m_currentDepthStencilRef != stencilRef) { m_pCommandList->OMSetStencilRef(stencilRef); m_currentDepthStencilRef = stencilRef; } } GPUBlendState *D3D12GPUContext::GetBlendState() { return m_pCurrentBlendState; } const float4 &D3D12GPUContext::GetBlendStateBlendFactor() { return m_currentBlendStateBlendFactors; }; void D3D12GPUContext::SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor /* = float4::One */) { if (m_pCurrentBlendState != pBlendState) { if (m_pCurrentBlendState != nullptr) m_pCurrentBlendState->Release(); if ((m_pCurrentBlendState = static_cast<D3D12GPUBlendState *>(pBlendState)) != nullptr) m_pCurrentBlendState->AddRef(); m_pipelineChanged = true; } if (blendFactor != m_currentBlendStateBlendFactors) { m_pCommandList->OMSetBlendFactor(blendFactor.ele); m_currentBlendStateBlendFactors = blendFactor; } } const RENDERER_VIEWPORT *D3D12GPUContext::GetViewport() { return &m_currentViewport; } void D3D12GPUContext::SetViewport(const RENDERER_VIEWPORT *pNewViewport) { if (Y_memcmp(&m_currentViewport, pNewViewport, sizeof(RENDERER_VIEWPORT)) == 0) return; Y_memcpy(&m_currentViewport, pNewViewport, sizeof(m_currentViewport)); D3D12_VIEWPORT D3D12Viewport = { (float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, (float)m_currentViewport.Width, (float)m_currentViewport.Height, m_currentViewport.MinDepth, m_currentViewport.MaxDepth }; m_pCommandList->RSSetViewports(1, &D3D12Viewport); // update constants m_pConstants->SetViewportOffset((float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, false); m_pConstants->SetViewportSize((float)m_currentViewport.Width, (float)m_currentViewport.Height, false); m_pConstants->CommitChanges(); } void D3D12GPUContext::SetFullViewport(GPUTexture *pForRenderTarget /* = NULL */) { RENDERER_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; if (pForRenderTarget != nullptr) { uint3 textureDimensions = Renderer::GetTextureDimensions(pForRenderTarget); viewport.Width = textureDimensions.x; viewport.Height = textureDimensions.y; } else { GetCurrentRenderTargetDimensions(&viewport.Width, &viewport.Height); } SetViewport(&viewport); } const RENDERER_SCISSOR_RECT *D3D12GPUContext::GetScissorRect() { return &m_scissorRect; } void D3D12GPUContext::SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) { if (Y_memcmp(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)) == 0) return; Y_memcpy(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)); // only set if rasterizer state permits if (m_pCurrentRasterizerState != nullptr && m_pCurrentRasterizerState->GetDesc()->ScissorEnable) { D3D12_RECT D3D12ScissorRect = { (LONG)m_scissorRect.Left, (LONG)m_scissorRect.Top, (LONG)m_scissorRect.Right, (LONG)m_scissorRect.Bottom }; m_pCommandList->RSSetScissorRects(1, &D3D12ScissorRect); } } void D3D12GPUContext::ClearTargets(bool clearColor /* = true */, bool clearDepth /* = true */, bool clearStencil /* = true */, const float4 &clearColorValue /* = float4::Zero */, float clearDepthValue /* = 1.0f */, uint8 clearStencilValue /* = 0 */) { D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0; if (clearDepth) clearFlags |= D3D12_CLEAR_FLAG_DEPTH; if (clearStencil) clearFlags |= D3D12_CLEAR_FLAG_STENCIL; if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { if (clearColor) { m_pCommandList->ClearRenderTargetView(m_pCurrentSwapChain->GetCurrentBackBufferViewDescriptorCPUHandle(), clearColorValue, 0, nullptr); m_commandCounter++; } if (clearDepth && m_pCurrentSwapChain->GetDepthStencilBufferResource() != nullptr) { m_pCommandList->ClearDepthStencilView(m_pCurrentSwapChain->GetDepthStencilBufferViewDescriptorCPUHandle(), clearFlags, clearDepthValue, clearStencilValue, 0, nullptr); m_commandCounter++; } } } else { if (clearColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) { m_pCommandList->ClearRenderTargetView(m_pCurrentRenderTargetViews[i]->GetDescriptorHandle(), clearColorValue, 0, nullptr); m_commandCounter++; } } } if (clearFlags != 0 && m_pCurrentDepthBufferView != nullptr) { m_pCommandList->ClearDepthStencilView(m_pCurrentDepthBufferView->GetDescriptorHandle(), clearFlags, clearDepthValue, clearStencilValue, 0, nullptr); m_commandCounter++; } } } void D3D12GPUContext::DiscardTargets(bool discardColor /* = true */, bool discardDepth /* = true */, bool discardStencil /* = true */) { if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { if (discardColor) { m_pCommandList->DiscardResource(m_pCurrentSwapChain->GetCurrentBackBufferResource(), nullptr); m_commandCounter++; } if (discardDepth && discardStencil && m_pCurrentSwapChain->HasDepthStencilBuffer()) { m_pCommandList->DiscardResource(m_pCurrentSwapChain->GetDepthStencilBufferResource(), nullptr); m_commandCounter++; } } } else { if (discardColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) { m_pCommandList->DiscardResource(m_pCurrentRenderTargetViews[i]->GetD3DResource(), nullptr); m_commandCounter++; } } } if (discardDepth && discardStencil && m_pCurrentDepthBufferView != nullptr) { m_pCommandList->DiscardResource(m_pCurrentDepthBufferView->GetD3DResource(), nullptr); m_commandCounter++; } } } GPUOutputBuffer *D3D12GPUContext::GetOutputBuffer() { return m_pCurrentSwapChain; } void D3D12GPUContext::SetOutputBuffer(GPUOutputBuffer *pSwapChain) { DebugAssert(pSwapChain != nullptr); if (m_pCurrentSwapChain == pSwapChain) return; // copy out old swap chain D3D12GPUOutputBuffer *pOldSwapChain = m_pCurrentSwapChain; // copy in new swap chain if ((m_pCurrentSwapChain = static_cast<D3D12GPUOutputBuffer *>(pSwapChain)) != nullptr) m_pCurrentSwapChain->AddRef(); // Currently rendering to window? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); } // update references if (pOldSwapChain != nullptr) pOldSwapChain->Release(); } bool D3D12GPUContext::GetExclusiveFullScreen() { BOOL currentState; HRESULT hResult = m_pCurrentSwapChain->GetDXGISwapChain()->GetFullscreenState(&currentState, nullptr); if (FAILED(hResult)) return false; return (currentState == TRUE); } bool D3D12GPUContext::SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) { // @TODO return false; } bool D3D12GPUContext::ResizeOutputBuffer(uint32 width /* = 0 */, uint32 height /* = 0 */) { if (width == 0 || height == 0) { // get the new size of the window RECT clientRect; GetClientRect(m_pCurrentSwapChain->GetHWND(), &clientRect); // changed? width = Max(clientRect.right - clientRect.left, (LONG)1); height = Max(clientRect.bottom - clientRect.top, (LONG)1); } // changed? if (m_pCurrentSwapChain->GetWidth() == width && m_pCurrentSwapChain->GetHeight() == height) return true; // unbind if we're currently bound to the pipeline if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) m_pCommandList->OMSetRenderTargets(0, nullptr, FALSE, nullptr); // invoke the resize m_pCurrentSwapChain->InternalResizeBuffers(width, height, m_pCurrentSwapChain->GetVSyncType()); // synchronize render targets if we were bound if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); } // done return true; } void D3D12GPUContext::PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) { // the barrier *to* present state has to be queued ResourceBarrier(m_pCurrentSwapChain->GetCurrentBackBufferResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); // ensure all commands have been queued. don't refresh allocators yet, because otherwise we could block here when trying to get // the new allocators. Instead, push the delay to BeginFrame, which will have some time passed. //FlushCommandList(true, false, false); //FlushCommandList(true, false, true); CloseAndExecuteCommandList(false, false); #if 1 // vsync off? if (presentBehaviour == GPU_PRESENT_BEHAVIOUR_IMMEDIATE) { // test if we can present DWORD waitResult = WaitForSingleObject(m_pCurrentSwapChain->GetDXGISwapChain()->GetFrameLatencyWaitableObject(), 0); if (waitResult == WAIT_OBJECT_0) m_pCurrentSwapChain->GetDXGISwapChain()->Present(0, DXGI_PRESENT_RESTART); else g_pRenderer->GetCounters()->IncrementFramesDroppedCounter(); } else { // vsync on m_pCurrentSwapChain->GetDXGISwapChain()->Present(1, 0); } #else if (presentBehaviour == GPU_PRESENT_BEHAVIOUR_IMMEDIATE) m_pCurrentSwapChain->GetDXGISwapChain()->Present(0, DXGI_PRESENT_RESTART); else m_pCurrentSwapChain->GetDXGISwapChain()->Present(1, 0); #endif // restore state (since new command list) ResetCommandList(true, true); // create a new synchronization point for the next frame. m_pGraphicsCommandQueue->CreateSynchronizationPoint(); } uint32 D3D12GPUContext::GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) { uint32 i, j; for (i = 0; i < m_nCurrentRenderTargets && i < nRenderTargets; i++) ppRenderTargetViews[i] = m_pCurrentRenderTargetViews[i]; for (j = i; j < nRenderTargets; j++) ppRenderTargetViews[j] = nullptr; if (ppDepthBufferView != nullptr) *ppDepthBufferView = m_pCurrentDepthBufferView; return i; } void D3D12GPUContext::SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) { // @TODO only update pipeline on format change / # targets change // to system framebuffer? if ((nRenderTargets == 0 || (nRenderTargets == 1 && ppRenderTargets[0] == nullptr)) && pDepthBufferView == nullptr) { // change? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) return; // kill current targets for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[i]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[i]->GetD3DResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, defaultState); m_pCurrentRenderTargetViews[i]->Release(); m_pCurrentRenderTargetViews[i] = nullptr; } if (m_pCurrentDepthBufferView != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), D3D12_RESOURCE_STATE_DEPTH_WRITE, defaultState); m_pCurrentDepthBufferView->Release(); m_pCurrentDepthBufferView = nullptr; } m_nCurrentRenderTargets = 0; SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); m_pipelineChanged = true; } else { DebugAssert(nRenderTargets < countof(m_pCurrentRenderTargetViews)); uint32 slot; uint32 newRenderTargetCount = 0; bool doUpdate = false; // transition states - unbind old targets // this is needed because if a target changes index it'll transition incorrectly otherwise. for (slot = 0; slot < m_nCurrentRenderTargets; slot++) { DebugAssert(m_pCurrentRenderTargetViews[slot] != nullptr); if (slot >= nRenderTargets || m_pCurrentRenderTargetViews[slot] != ppRenderTargets[slot]) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[slot]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[slot]->GetD3DResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, defaultState); } } // set inclusive slots for (slot = 0; slot < nRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != ppRenderTargets[slot]) { if (m_pCurrentRenderTargetViews[slot] != nullptr) m_pCurrentRenderTargetViews[slot]->Release(); if ((m_pCurrentRenderTargetViews[slot] = static_cast<D3D12GPURenderTargetView *>(ppRenderTargets[slot])) != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[slot]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[slot]->GetD3DResource(), defaultState, D3D12_RESOURCE_STATE_RENDER_TARGET); m_pCurrentRenderTargetViews[slot]->AddRef(); } doUpdate = true; } if (m_pCurrentRenderTargetViews[slot] != nullptr) newRenderTargetCount = slot + 1; } // clear extra slots for (; slot < m_nCurrentRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != nullptr) { m_pCurrentRenderTargetViews[slot]->Release(); m_pCurrentRenderTargetViews[slot] = nullptr; doUpdate = true; } } // update counter if (newRenderTargetCount != m_nCurrentRenderTargets) doUpdate = true; m_nCurrentRenderTargets = newRenderTargetCount; if (m_pCurrentDepthBufferView != pDepthBufferView) { if (m_pCurrentDepthBufferView != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), D3D12_RESOURCE_STATE_DEPTH_WRITE, defaultState); m_pCurrentDepthBufferView->Release(); } if ((m_pCurrentDepthBufferView = static_cast<D3D12GPUDepthStencilBufferView *>(pDepthBufferView)) != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), defaultState, D3D12_RESOURCE_STATE_DEPTH_WRITE); m_pCurrentDepthBufferView->AddRef(); } doUpdate = true; } if (doUpdate) { SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); m_pipelineChanged = true; } } } DRAW_TOPOLOGY D3D12GPUContext::GetDrawTopology() { return m_currentTopology; } void D3D12GPUContext::SetDrawTopology(DRAW_TOPOLOGY topology) { if (topology == m_currentTopology) return; D3D12_PRIMITIVE_TOPOLOGY D3DPrimitiveTopology = D3D12Helpers::GetD3D12PrimitiveTopology(topology); D3D12_PRIMITIVE_TOPOLOGY_TYPE D3DPrimitiveTopologyType = D3D12Helpers::GetD3D12PrimitiveTopologyType(topology); m_pCommandList->IASetPrimitiveTopology(D3DPrimitiveTopology); m_currentTopology = topology; if (D3DPrimitiveTopologyType != m_currentD3DTopologyType) { m_currentD3DTopologyType = D3DPrimitiveTopologyType; m_pipelineChanged = true; } } uint32 D3D12GPUContext::GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < countof(m_pCurrentVertexBuffers)); uint32 saveCount; for (saveCount = 0; saveCount < nBuffers; saveCount++) { if ((firstBuffer + saveCount) > m_currentVertexBufferBindCount) break; ppVertexBuffers[saveCount] = m_pCurrentVertexBuffers[firstBuffer + saveCount]; pVertexBufferOffsets[saveCount] = m_currentVertexBufferOffsets[firstBuffer + saveCount]; pVertexBufferStrides[saveCount] = m_currentVertexBufferStrides[firstBuffer + saveCount]; } return saveCount; } void D3D12GPUContext::SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) { D3D12_VERTEX_BUFFER_VIEW vertexBufferViews[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; uint32 dirtyFirst = Y_UINT32_MAX; uint32 dirtyLast = 0; for (uint32 i = 0; i < nBuffers; i++) { D3D12GPUBuffer *pD3D12VertexBuffer = static_cast<D3D12GPUBuffer *>(ppVertexBuffers[i]); uint32 bufferIndex = firstBuffer + i; if (m_pCurrentVertexBuffers[bufferIndex] == ppVertexBuffers[i] && m_currentVertexBufferOffsets[bufferIndex] == pVertexBufferOffsets[i] && m_currentVertexBufferStrides[bufferIndex] == pVertexBufferStrides[i]) { continue; } if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) { m_pCurrentVertexBuffers[bufferIndex]->Release(); m_pCurrentVertexBuffers[bufferIndex] = nullptr; } if ((m_pCurrentVertexBuffers[bufferIndex] = pD3D12VertexBuffer) != nullptr) { pD3D12VertexBuffer->AddRef(); m_currentVertexBufferOffsets[bufferIndex] = pVertexBufferOffsets[i]; m_currentVertexBufferStrides[bufferIndex] = pVertexBufferStrides[i]; // @TODO cache this address, save virtual call? DebugAssert(pVertexBufferOffsets[i] < pD3D12VertexBuffer->GetDesc()->Size); vertexBufferViews[i].BufferLocation = pD3D12VertexBuffer->GetD3DResource()->GetGPUVirtualAddress() + pVertexBufferOffsets[i]; vertexBufferViews[i].SizeInBytes = pD3D12VertexBuffer->GetDesc()->Size - pVertexBufferOffsets[i]; vertexBufferViews[i].StrideInBytes = pVertexBufferStrides[i]; } else { m_currentVertexBufferOffsets[bufferIndex] = 0; m_currentVertexBufferStrides[bufferIndex] = 0; Y_memzero(&vertexBufferViews[i], sizeof(vertexBufferViews[0])); } dirtyFirst = Min(dirtyFirst, bufferIndex); dirtyLast = Max(dirtyLast, bufferIndex); } // changes? if (dirtyFirst == Y_UINT32_MAX) return; // pass to command list // @TODO may be worth batching this to a dirty range? m_pCommandList->IASetVertexBuffers(dirtyFirst, dirtyLast - dirtyFirst + 1, &vertexBufferViews[dirtyFirst - firstBuffer]); // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((firstBuffer + nBuffers), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D12GPUContext::SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { if (m_pCurrentVertexBuffers[bufferIndex] == pVertexBuffer && m_currentVertexBufferOffsets[bufferIndex] == offset && m_currentVertexBufferStrides[bufferIndex] == stride) { return; } if (m_pCurrentVertexBuffers[bufferIndex] != pVertexBuffer) { if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) m_pCurrentVertexBuffers[bufferIndex]->Release(); if ((m_pCurrentVertexBuffers[bufferIndex] = static_cast<D3D12GPUBuffer *>(pVertexBuffer)) != nullptr) m_pCurrentVertexBuffers[bufferIndex]->AddRef(); } m_currentVertexBufferOffsets[bufferIndex] = offset; m_currentVertexBufferStrides[bufferIndex] = stride; // set in command list if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) { D3D12_VERTEX_BUFFER_VIEW bufferView; DebugAssert(offset < m_pCurrentVertexBuffers[bufferIndex]->GetDesc()->Size); bufferView.BufferLocation = m_pCurrentVertexBuffers[bufferIndex]->GetD3DResource()->GetGPUVirtualAddress() + offset; bufferView.SizeInBytes = m_pCurrentVertexBuffers[bufferIndex]->GetDesc()->Size - offset; bufferView.StrideInBytes = stride; m_pCommandList->IASetVertexBuffers(bufferIndex, 1, &bufferView); } else { m_pCommandList->IASetVertexBuffers(bufferIndex, 1, nullptr); } // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((bufferIndex + 1), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D12GPUContext::GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) { *ppBuffer = m_pCurrentIndexBuffer; *pFormat = m_currentIndexFormat; *pOffset = m_currentIndexBufferOffset; } void D3D12GPUContext::SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) { if (m_pCurrentIndexBuffer == pBuffer && m_currentIndexFormat == format && m_currentIndexBufferOffset == offset) return; if (m_pCurrentIndexBuffer != pBuffer) { if (m_pCurrentIndexBuffer != nullptr) m_pCurrentIndexBuffer->Release(); if ((m_pCurrentIndexBuffer = static_cast<D3D12GPUBuffer *>(pBuffer)) != nullptr) m_pCurrentIndexBuffer->AddRef(); } m_currentIndexFormat = format; m_currentIndexBufferOffset = offset; if (m_pCurrentIndexBuffer != nullptr) { D3D12_INDEX_BUFFER_VIEW bufferView; DebugAssert(offset < m_pCurrentIndexBuffer->GetDesc()->Size); bufferView.BufferLocation = m_pCurrentIndexBuffer->GetD3DResource()->GetGPUVirtualAddress() + offset; bufferView.SizeInBytes = m_pCurrentIndexBuffer->GetDesc()->Size - offset; bufferView.Format = (format == GPU_INDEX_FORMAT_UINT16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; m_pCommandList->IASetIndexBuffer(&bufferView); } else { m_pCommandList->IASetIndexBuffer(nullptr); } } void D3D12GPUContext::SetShaderProgram(GPUShaderProgram *pShaderProgram) { if (m_pCurrentShaderProgram == pShaderProgram) return; if (m_pCurrentShaderProgram != nullptr) m_pCurrentShaderProgram->Release(); if ((m_pCurrentShaderProgram = static_cast<D3D12GPUShaderProgram *>(pShaderProgram)) != nullptr) m_pCurrentShaderProgram->AddRef(); g_pRenderer->GetCounters()->IncrementPipelineChangeCounter(); m_pipelineChanged = true; } void D3D12GPUContext::SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValue(this, index, valueType, pValue); } void D3D12GPUContext::SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValueArray(this, index, valueType, pValue, firstElement, numElements); } void D3D12GPUContext::SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStruct(this, index, pValue, valueSize); } void D3D12GPUContext::SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStructArray(this, index, pValue, valueSize, firstElement, numElements); } void D3D12GPUContext::SetShaderParameterResource(uint32 index, GPUResource *pResource) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pResource, nullptr); } void D3D12GPUContext::SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pTexture, pSamplerState); } void D3D12GPUContext::WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit /* = false */) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } DebugAssert(count > 0 && (offset + count) <= cbInfo->Size); if (Y_memcmp(cbInfo->pLocalMemory + offset, pData, count) != 0) { Y_memcpy(cbInfo->pLocalMemory + offset, pData, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + count; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + count - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D12GPUContext::WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit /*= false*/) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } uint32 writeSize = bufferStride * count; DebugAssert(writeSize > 0 && (offset + writeSize) <= cbInfo->Size); if (Y_memcmp_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count) != 0) { Y_memcpy_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + writeSize; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + writeSize - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D12GPUContext::CommitConstantBuffer(uint32 bufferIndex) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr || cbInfo->DirtyLowerBounds < 0) return; // work out count to modify uint32 modifySize = cbInfo->DirtyUpperBounds - cbInfo->DirtyLowerBounds + 1; // handle per-draw constant buffers if (!cbInfo->PerDraw) { // allocate scratch buffer memory ID3D12Resource *pScratchBufferResource; uint32 scratchBufferOffset; void *pCPUPointer; if (!AllocateScratchBufferMemory(modifySize, 0, &pScratchBufferResource, &scratchBufferOffset, &pCPUPointer, nullptr)) { Log_ErrorPrintf("D3D12GPUContext::CommitConstantBuffer: Failed to allocate scratch buffer memory."); return; } // copy from the constant memory store to the scratch buffer Y_memcpy(pCPUPointer, cbInfo->pLocalMemory + cbInfo->DirtyLowerBounds, modifySize); // get constant buffer pointer ID3D12Resource *pConstantBufferResource = m_pDevice->GetConstantBufferResource(bufferIndex); DebugAssert(pConstantBufferResource != nullptr); // block predicates BypassPredication(); // queue a copy to the actual buffer ResourceBarrier(pConstantBufferResource, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST); m_pCommandList->CopyBufferRegion(pConstantBufferResource, cbInfo->DirtyLowerBounds, pScratchBufferResource, scratchBufferOffset, modifySize); m_commandCounter++; ResourceBarrier(pConstantBufferResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // restore predicates RestorePredication(); } else { void *pCPUPointer; D3D12_GPU_VIRTUAL_ADDRESS pGPUPointer; if (!AllocateScratchBufferMemory(cbInfo->Size, D3D12_CONSTANT_BUFFER_ALIGNMENT, nullptr, nullptr, &pCPUPointer, &pGPUPointer)) { Log_ErrorPrintf("D3D12GPUContext::CommitConstantBuffer: Failed to allocate per-draw scratch buffer memory."); return; } // copy from the constant memory store to the scratch buffer Y_memcpy(pCPUPointer, cbInfo->pLocalMemory, cbInfo->Size); // per-draw cbInfo->LastAddress = pGPUPointer; if (m_pCurrentShaderProgram != nullptr && !m_pipelineChanged) m_pCurrentShaderProgram->RebindPerDrawConstantBuffer(this, bufferIndex, pGPUPointer); } // reset range cbInfo->DirtyLowerBounds = cbInfo->DirtyUpperBounds = -1; } void D3D12GPUContext::SetShaderConstantBuffers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->ConstantBuffers[index] == handle) return; state->ConstantBuffers[index] = handle; state->ConstantBufferBindCount = Max(state->ConstantBufferBindCount, index + 1); state->ConstantBuffersDirty = true; } void D3D12GPUContext::SetShaderResources(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Resources[index] == handle) return; state->Resources[index] = handle; if (!handle.IsNull()) { // update max count state->ResourceBindCount = Max(state->ResourceBindCount, index + 1); } else { state->ResourceBindCount = 0; for (uint32 i = 0; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; i++) { if (!state->Resources[i].IsNull()) state->ResourceBindCount = i + 1; } } state->ResourcesDirty = true; } void D3D12GPUContext::SetShaderSamplers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Samplers[index] == handle) return; state->Samplers[index] = handle; state->SamplerBindCount = Max(state->SamplerBindCount, index + 1); state->SamplersDirty = true; } void D3D12GPUContext::SetShaderUAVs(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->UAVs[index] == handle) return; state->UAVs[index] = handle; state->UAVBindCount = Max(state->UAVBindCount, index + 1); state->UAVsDirty = true; } void D3D12GPUContext::SetPerDrawConstantBuffer(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS address) { DebugAssert(index < m_perDrawConstantBuffers.GetSize()); if (m_perDrawConstantBuffers[index] == address) return; m_perDrawConstantBuffers[index] = address; m_perDrawConstantBufferCount = Max(m_perDrawConstantBufferCount, index + 1); m_perDrawConstantBuffersDirty = true; } void D3D12GPUContext::SynchronizeRenderTargetsAndUAVs() { D3D12_CPU_DESCRIPTOR_HANDLE renderTargetHandles[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; D3D12_CPU_DESCRIPTOR_HANDLE depthStencilHandle; uint32 renderTargetCount = 0; bool hasDepthStencil = false; // get render target views if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // using swap chain if (m_pCurrentSwapChain != nullptr) { // update the render target index if (m_pCurrentSwapChain->UpdateCurrentBackBuffer()) { // it's changed, so we need a resource barrier ResourceBarrier(m_pCurrentSwapChain->GetCurrentBackBufferResource(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); } renderTargetHandles[0] = m_pCurrentSwapChain->GetCurrentBackBufferViewDescriptorCPUHandle(); depthStencilHandle = m_pCurrentSwapChain->GetDepthStencilBufferViewDescriptorCPUHandle(); hasDepthStencil = m_pCurrentSwapChain->HasDepthStencilBuffer(); renderTargetCount = 1; } } else { // get render target views for (uint32 renderTargetIndex = 0; renderTargetIndex < m_nCurrentRenderTargets; renderTargetIndex++) { if (m_pCurrentRenderTargetViews[renderTargetIndex] != nullptr) { renderTargetHandles[renderTargetIndex] = m_pCurrentRenderTargetViews[renderTargetIndex]->GetDescriptorHandle(); renderTargetCount = renderTargetIndex + 1; } else { renderTargetHandles[renderTargetIndex].ptr = 0; } } // get depth stencil view if (m_pCurrentDepthBufferView != nullptr) { hasDepthStencil = true; depthStencilHandle = m_pCurrentDepthBufferView->GetDescriptorHandle(); } } m_pCommandList->OMSetRenderTargets(renderTargetCount, (renderTargetCount > 0) ? renderTargetHandles : nullptr, FALSE, (hasDepthStencil) ? &depthStencilHandle : nullptr); } bool D3D12GPUContext::UpdatePipelineState(bool force) { // new pipeline state required? force = force || m_pipelineChanged; if (m_pCurrentShaderProgram != nullptr) { if (m_pipelineChanged || force) { // fill pipeline state key D3D12GPUShaderProgram::PipelineStateKey key; Y_memzero(&key, sizeof(key)); // render targets if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { if (m_pCurrentSwapChain != nullptr) { key.RenderTargetCount = 1; key.RTVFormats[0] = m_pCurrentSwapChain->GetBackBufferFormat(); key.DSVFormat = m_pCurrentSwapChain->GetDepthStencilBufferFormat(); } } else { key.RenderTargetCount = m_nCurrentRenderTargets; for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) key.RTVFormats[i] = (m_pCurrentRenderTargetViews[i] != nullptr) ? m_pCurrentRenderTargetViews[i]->GetDesc()->Format : PIXEL_FORMAT_UNKNOWN; key.DSVFormat = (m_pCurrentDepthBufferView != nullptr) ? m_pCurrentDepthBufferView->GetDesc()->Format : PIXEL_FORMAT_UNKNOWN; } // rasterizer state if (m_pCurrentRasterizerState == nullptr) return false; Y_memcpy(&key.RasterizerState, m_pCurrentRasterizerState->GetD3DRasterizerStateDesc(), sizeof(key.RasterizerState)); // depthstencil state if (m_pCurrentDepthStencilState == nullptr) return false; Y_memcpy(&key.DepthStencilState, m_pCurrentDepthStencilState->GetD3DDepthStencilDesc(), sizeof(key.DepthStencilState)); // blend state if (m_pCurrentBlendState == nullptr) return false; Y_memcpy(&key.BlendState, m_pCurrentBlendState->GetD3DBlendDesc(), sizeof(key.BlendState)); // topology key.PrimitiveTopologyType = m_currentD3DTopologyType; if (!m_pCurrentShaderProgram->Switch(this, m_pCommandList, &key)) return false; // up-to-date g_pRenderer->GetCounters()->IncrementPipelineChangeCounter(); m_pipelineChanged = false; } } else if (!force) { // no shader bound and not restoring return false; } // allocate an array of cpu pointers, uses alloca so it's at the end of the stack D3D12_CPU_DESCRIPTOR_HANDLE *pCPUHandles = (D3D12_CPU_DESCRIPTOR_HANDLE *)alloca(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) * 32); uint32 *pCPUHandleCounts = (uint32 *)alloca(sizeof(uint32) * 32); for (uint32 i = 0; i < 32; i++) pCPUHandleCounts[i] = 1; // update states for (uint32 stage = 0; stage <= SHADER_PROGRAM_STAGE_PIXEL_SHADER; stage++) { ShaderStageState *state = &m_shaderStates[stage]; //uint32 base = (stage == SHADER_PROGRAM_STAGE_PIXEL_SHADER) ? 3 : 0; uint32 base = stage * 3; // Constant buffers if (state->ConstantBuffersDirty || force) { // find the new bind count for (uint32 i = 0; i < state->ConstantBufferBindCount; i++) { if (!state->ConstantBuffers[i].IsNull()) pCPUHandles[i] = state->ConstantBuffers[i]; else pCPUHandles[i] = m_pDevice->GetNullCBVDescriptorHandle(); } for (uint32 i = state->ConstantBufferBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullCBVDescriptorHandle(); // allocate scratch descriptors and copy if (AllocateScratchView(D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, &state->CBVTableCPUHandle, &state->CBVTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->CBVTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); m_pCommandList->SetGraphicsRootDescriptorTable(base + 0, state->CBVTableGPUHandle); } state->ConstantBuffersDirty = false; } // Resources if (state->ResourcesDirty || force) { // find the new bind count for (uint32 i = 0; i < state->ResourceBindCount; i++) { if (!state->Resources[i].IsNull()) pCPUHandles[i] = state->Resources[i]; else pCPUHandles[i] = m_pDevice->GetNullSRVDescriptorHandle(); } for (uint32 i = state->ResourceBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullSRVDescriptorHandle(); // allocate scratch descriptors and copy if (AllocateScratchView(D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS, &state->SRVTableCPUHandle, &state->SRVTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->SRVTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); m_pCommandList->SetGraphicsRootDescriptorTable(base + 1, state->SRVTableGPUHandle); } state->ResourcesDirty = false; } // Samplers if (state->SamplersDirty || force) { // find the new bind count for (uint32 i = 0; i < state->SamplerBindCount; i++) { if (!state->Samplers[i].IsNull()) pCPUHandles[i] = state->Samplers[i]; else pCPUHandles[i] = m_pDevice->GetNullSamplerHandle(); } for (uint32 i = state->SamplerBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullSamplerHandle(); // allocate scratch descriptors and copy if (AllocateScratchSamplers(D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS, &state->SamplerTableCPUHandle, &state->SamplerTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->SamplerTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); m_pCommandList->SetGraphicsRootDescriptorTable(base + 2, state->SamplerTableGPUHandle); } state->SamplersDirty = false; } // // UAVs // if (stage == SHADER_PROGRAM_STAGE_PIXEL_SHADER && (state->UAVsDirty || force)) // { // // find the new bind count // uint32 bindCount = 0; // for (uint32 i = 0; i < state->SamplerBindCount; i++) // { // if (!state->UAVs[i].IsNull()) // { // pCPUHandles[i] = state->UAVs[i]; // bindCount = i + 1; // } // else // { // pCPUHandles[i].ptr = 0; // } // } // state->UAVBindCount = bindCount; // state->UAVsDirty = false; // // // allocate scratch descriptors and copy // if (bindCount > 0 && AllocateScratchView(bindCount, &state->UAVTableCPUHandle, &state->UAVTableGPUHandle)) // { // m_pD3DDevice->CopyDescriptors(1, &state->UAVTableCPUHandle, &bindCount, bindCount, pCPUHandles, nullptr, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); // m_pCommandList->SetGraphicsRootDescriptorTable(15, state->UAVTableGPUHandle); // } // } } // Commit global constant buffer m_pConstants->CommitGlobalConstantBufferChanges(); // per-draw constants if (m_perDrawConstantBuffersDirty || force) { for (uint32 i = 0; i < m_perDrawConstantBufferCount; i++) m_pCommandList->SetGraphicsRootConstantBufferView(16 + i, m_perDrawConstantBuffers[i]); for (uint32 i = m_perDrawConstantBufferCount; i < D3D12_LEGACY_GRAPHICS_ROOT_PER_DRAW_CONSTANT_BUFFER_SLOTS; i++) m_pCommandList->SetGraphicsRootConstantBufferView(16 + i, m_pCurrentScratchBuffer->GetGPUAddress(0)); m_perDrawConstantBuffersDirty = false; } return true; } void D3D12GPUContext::Draw(uint32 firstVertex, uint32 nVertices) { if (nVertices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawInstanced(nVertices, 1, firstVertex, 0); m_commandCounter++; g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUContext::DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) { if (nVertices == 0 || nInstances == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawInstanced(nVertices, nInstances, firstVertex, 0); m_commandCounter++; g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUContext::DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) { if (nIndices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawIndexedInstanced(nIndices, 1, startIndex, baseVertex, 0); m_commandCounter++; g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUContext::DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) { if (nIndices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawIndexedInstanced(nIndices, nInstances, startIndex, baseVertex, 0); m_commandCounter++; g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUContext::Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) { if (!UpdatePipelineState(false)) return; m_pCommandList->Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); m_commandCounter++; g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUContext::DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) { if (!UpdatePipelineState(false)) return; #if 1 // can use scratch buffer directly. // this probably should use a threshold to go to an upload buffer.. uint32 bufferSpaceRequired = vertexSize * nVertices; ID3D12Resource *pScratchBufferResource; void *pScratchBufferCPUPointer; D3D12_GPU_VIRTUAL_ADDRESS scratchBufferGPUPointer; uint32 scratchBufferOffset; if (!AllocateScratchBufferMemory(bufferSpaceRequired, 0, &pScratchBufferResource, &scratchBufferOffset, &pScratchBufferCPUPointer, &scratchBufferGPUPointer)) return; // copy the contents in Y_memcpy(pScratchBufferCPUPointer, pVertices, bufferSpaceRequired); // set vertex buffer D3D12_VERTEX_BUFFER_VIEW vertexBufferView; vertexBufferView.BufferLocation = scratchBufferGPUPointer; vertexBufferView.SizeInBytes = bufferSpaceRequired; vertexBufferView.StrideInBytes = vertexSize; m_pCommandList->IASetVertexBuffers(0, 1, &vertexBufferView); // invoke draw m_pCommandList->DrawInstanced(nVertices, 1, 0, 0); m_commandCounter++; // restore vertex buffer if (m_pCurrentVertexBuffers[0] != nullptr) { vertexBufferView.BufferLocation = m_pCurrentVertexBuffers[0]->GetD3DResource()->GetGPUVirtualAddress() + m_currentVertexBufferOffsets[0]; vertexBufferView.SizeInBytes = m_pCurrentVertexBuffers[0]->GetDesc()->Size - m_currentVertexBufferOffsets[0]; vertexBufferView.StrideInBytes = m_currentVertexBufferStrides[0]; m_pCommandList->IASetVertexBuffers(0, 1, &vertexBufferView); } else { m_pCommandList->IASetVertexBuffers(0, 1, nullptr); } #else uint32 bufferSpaceRequired = vertexSize * nVertices; ID3D12Resource *pResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, bufferSpaceRequired + 1, 1, 1, 1, DXGI_FORMAT_UNKNOWN,{ 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE }; HRESULT hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&pResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommitedResource for upload resource failed with hResult %08X", hResult); return; } // map the upload buffer void *pMappedPointer; D3D12_RANGE readRange = { 0, 0 }; hResult = pResource->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), &pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to map upload buffer: %08X", hResult); pResource->Release(); return; } // copy the contents over, and unmap the buffer D3D12_RANGE writeRange = { 0, bufferSpaceRequired }; Y_memcpy(pMappedPointer, pVertices, bufferSpaceRequired); pResource->Unmap(0, D3D12_MAP_RANGE_PARAM(&writeRange)); ID3D12Resource *pResource2; heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pResource2)); m_pCommandList->CopyBufferRegion(pResource2, 0, pResource, 0, bufferSpaceRequired); ResourceBarrier(pResource2, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // set vertex buffer D3D12_VERTEX_BUFFER_VIEW vertexBufferView; vertexBufferView.BufferLocation = pResource2->GetGPUVirtualAddress(); vertexBufferView.SizeInBytes = bufferSpaceRequired; vertexBufferView.StrideInBytes = vertexSize; m_pCommandList->IASetVertexBuffers(0, 1, &vertexBufferView); m_pCommandList->DrawInstanced(nVertices, 1, 0, 0); D3D12RenderBackend::GetInstance()->GetGraphicsCommandQueue()->ScheduleResourceForDeletion(pResource); D3D12RenderBackend::GetInstance()->GetGraphicsCommandQueue()->ScheduleResourceForDeletion(pResource2); #endif g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } bool D3D12GPUContext::CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) { // textures have to be compatible, for now this means same texture format D3D12GPUTexture2D *pD3D12SourceTexture = static_cast<D3D12GPUTexture2D *>(pSourceTexture); D3D12GPUTexture2D *pD3D12DestinationTexture = static_cast<D3D12GPUTexture2D *>(pDestinationTexture); if (pD3D12SourceTexture->GetDesc()->Width != pD3D12DestinationTexture->GetDesc()->Width || pD3D12SourceTexture->GetDesc()->Height != pD3D12DestinationTexture->GetDesc()->Height || pD3D12SourceTexture->GetDesc()->Format != pD3D12DestinationTexture->GetDesc()->Format || pD3D12SourceTexture->GetDesc()->MipLevels != pD3D12DestinationTexture->GetDesc()->MipLevels) { return false; } // get old state for both D3D12_RESOURCE_STATES sourceResourceState = GetCurrentResourceState(pSourceTexture); D3D12_RESOURCE_STATES destinationResourceState = GetCurrentResourceState(pDestinationTexture); // switch to copy states ResourceBarrier(pD3D12SourceTexture->GetD3DResource(), sourceResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); ResourceBarrier(pD3D12DestinationTexture->GetD3DResource(), destinationResourceState, D3D12_RESOURCE_STATE_COPY_DEST); // copy each mip level for (uint32 i = 0; i < pD3D12SourceTexture->GetDesc()->MipLevels; i++) { D3D12_TEXTURE_COPY_LOCATION sourceLocation = { pD3D12SourceTexture->GetD3DResource(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, i }; D3D12_TEXTURE_COPY_LOCATION destinationLocation = { pD3D12DestinationTexture->GetD3DResource(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, i }; m_pCommandList->CopyTextureRegion(&destinationLocation, 0, 0, 0, &sourceLocation, nullptr); m_commandCounter++; } // switch back from copy states ResourceBarrier(pD3D12SourceTexture->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_SOURCE, sourceResourceState); ResourceBarrier(pD3D12DestinationTexture->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_DEST, destinationResourceState); return true; } bool D3D12GPUContext::CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) { #if 0 // textures have to be compatible, for now this means same texture format D3D12GPUTexture2D *pD3D12SourceTexture = static_cast<D3D12GPUTexture2D *>(pSourceTexture); D3D12GPUTexture2D *pD3D12DestinationTexture = static_cast<D3D12GPUTexture2D *>(pDestinationTexture); if (pD3D12SourceTexture->GetDesc()->Format != pD3D12DestinationTexture->GetDesc()->Format || pD3D12SourceTexture->GetDesc()->MipLevels != pD3D12DestinationTexture->GetDesc()->MipLevels) { return false; } // create source box, copy it D3D12_BOX sourceBox = { sourceX, sourceY, 0, sourceX + width, sourceY + height, 1 }; m_pD3DContext->CopySubresourceRegion(pD3D12DestinationTexture->GetD3DTexture(), D3D12CalcSubresource(destMipLevel, 0, pD3D12DestinationTexture->GetDesc()->MipLevels), destX, destY, 0, pD3D12SourceTexture->GetD3DTexture(), D3D12CalcSubresource(sourceMipLevel, 0, pD3D12SourceTexture->GetDesc()->MipLevels), &sourceBox); return true; #endif return false; } void D3D12GPUContext::BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /*= RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST*/) { #if 0 DebugAssert(m_nCurrentRenderTargets <= 1); // read source formats DebugAssert(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE); DXGI_FORMAT sourceTextureFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Format); ID3D12Resource *pSourceResource = static_cast<D3D12GPUTexture2D *>(pTexture)->GetD3DTexture(); uint32 sourceTextureWidth = static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Width; uint32 sourceTextureHeight = static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Height; // read destination format DXGI_FORMAT destinationTextureFormat = DXGI_FORMAT_UNKNOWN; ID3D12Resource *pDestinationResource = NULL; uint32 destinationTextureWidth = 0, destinationTextureHeight = 0; if (m_nCurrentRenderTargets == 0) { destinationTextureFormat = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferFormat(); pDestinationResource = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferTexture(); destinationTextureWidth = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetWidth(); destinationTextureHeight = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetHeight(); } else { switch (m_pCurrentRenderTargetViews[0]->GetTargetTexture()->GetTextureType()) { case TEXTURE_TYPE_2D: destinationTextureFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Format); pDestinationResource = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetD3DTexture(); destinationTextureWidth = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Width; destinationTextureHeight = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Height; break; default: Panic("D3D12GPUContext::BlitFrameBuffer: Destination is an unsupported texture type"); return; } } // D3D12 can do a direct copy between identical types if (sourceTextureFormat == destinationTextureFormat && sourceWidth == destWidth && sourceHeight == destHeight) { // whole texture? if (sourceX == 0 && sourceY == 0 && destX == 0 && destY == 0 && sourceWidth == sourceTextureWidth && sourceHeight == sourceTextureHeight) { // use CopyResource m_pD3DContext->CopyResource(pDestinationResource, pSourceResource); return; } else { // use CopySubResourceRegion D3D12_BOX sourceBox = { sourceX, sourceY, 0, sourceX + sourceWidth, sourceY + sourceHeight, 1 }; m_pD3DContext->CopySubresourceRegion(pDestinationResource, 0, destX, destY, 0, pSourceResource, 0, &sourceBox); return; } } // use shader g_pRenderer->BlitTextureUsingShader(this, pTexture, sourceX, sourceY, sourceWidth, sourceHeight, 0, destX, destY, destWidth, destHeight, resizeFilter, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE); #endif } void D3D12GPUContext::GenerateMips(GPUTexture *pTexture) { // @TODO has to be done using shaders :( #if 0 ID3D12ShaderResourceView *pSRV = nullptr; uint32 flags = 0; switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_1D: pSRV = static_cast<D3D12GPUTexture1D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTexture1D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_1D_ARRAY: pSRV = static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_2D: pSRV = static_cast<D3D12GPUTexture2D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_2D_ARRAY: pSRV = static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_3D: pSRV = static_cast<D3D12GPUTexture3D *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTexture3D *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_CUBE: pSRV = static_cast<D3D12GPUTextureCube *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTextureCube *>(pTexture)->GetDesc()->Flags; break; case TEXTURE_TYPE_CUBE_ARRAY: pSRV = static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetD3DSRV(); flags = static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetDesc()->Flags; break; } if (pSRV == nullptr || !(flags & GPU_TEXTURE_FLAG_GENERATE_MIPS)) { Log_ErrorPrintf("D3D12GPUContext::GenerateMips: Texture not created with GPU_TEXTURE_FLAG_GENERATE_MIPS."); return; } m_pD3DContext->GenerateMips(pSRV); #endif } GPUCommandList *D3D12GPUContext::CreateCommandList() { D3D12GPUCommandList *pCommandList = new D3D12GPUCommandList(m_pDevice, m_pD3DDevice); if (!pCommandList->Create(m_pGraphicsCommandQueue)) { pCommandList->Release(); return nullptr; } return pCommandList; } bool D3D12GPUContext::OpenCommandList(GPUCommandList *pCommandList) { D3D12GPUCommandList *pD3D12CommandList = reinterpret_cast<D3D12GPUCommandList *>(pCommandList); return pD3D12CommandList->Open(m_pGraphicsCommandQueue, m_pCurrentSwapChain); } bool D3D12GPUContext::CloseCommandList(GPUCommandList *pCommandList) { D3D12GPUCommandList *pD3D12CommandList = reinterpret_cast<D3D12GPUCommandList *>(pCommandList); // no errors? if (pD3D12CommandList->Close()) return true; // release everything it's used pD3D12CommandList->ReleaseAllocators(m_pGraphicsCommandQueue->GetNextFenceValue()); return false; } void D3D12GPUContext::ExecuteCommandList(GPUCommandList *pCommandList) { D3D12GPUCommandList *pD3D12CommandList = reinterpret_cast<D3D12GPUCommandList *>(pCommandList); // if there was no worthwhile (draw, copy) commands issued since the last flush, don't flush this list if (m_commandCounter == 0) { // but still transition pending resources m_pDevice->TransitionPendingResources(m_pGraphicsCommandQueue); } else { // current command list has to be executed before (this will also take care of any transitions) CloseAndExecuteCommandList(false, false); ResetCommandList(true, false); } // execute on our command queue m_pGraphicsCommandQueue->ExecuteCommandList(pD3D12CommandList->GetD3DCommandList()); // release everything the command list used pD3D12CommandList->ReleaseAllocators(m_pGraphicsCommandQueue->GetNextFenceValue()); // flag all constant buffers as dirty, as the command list may have modified them for (ConstantBuffer &constantBuffer : m_constantBuffers) { if (constantBuffer.pLocalMemory != nullptr) { constantBuffer.DirtyLowerBounds = 0; constantBuffer.DirtyUpperBounds = constantBuffer.Size - 1; } } } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2RenderBackend.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "OpenGLES2Renderer/OpenGLES2GPUBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUOutputBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" #include "Engine/EngineCVars.h" #include "Engine/SDLHeaders.h" Log_SetChannel(OpenGLES2RenderBackend); static bool SetSDLGLColorAttributes(PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilBufferFormat) { // set colour buffer attributes uint32 redBits = 0; uint32 greenBits = 0; uint32 blueBits = 0; uint32 alphaBits = 0; bool srgbEnabled = false; switch (backBufferFormat) { case PIXEL_FORMAT_R8G8B8A8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 8; srgbEnabled = false; break; case PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 8; srgbEnabled = true; break; case PIXEL_FORMAT_B8G8R8A8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 0; srgbEnabled = true; break; case PIXEL_FORMAT_B8G8R8X8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 0; srgbEnabled = false; break; default: Log_ErrorPrintf("SetSDLGLColorAttributes: Unhandled backbuffer format '%s'.", PixelFormat_GetPixelFormatInfo(backBufferFormat)->Name); return false; } // set depth buffer attributes uint32 depthBits = 0; uint32 stencilBits = 0; switch (depthStencilBufferFormat) { case PIXEL_FORMAT_D16_UNORM: depthBits = 16; stencilBits = 0; break; case PIXEL_FORMAT_D24_UNORM_S8_UINT: depthBits = 24; stencilBits = 8; break; case PIXEL_FORMAT_D32_FLOAT: depthBits = 32; stencilBits = 0; break; case PIXEL_FORMAT_D32_FLOAT_S8X24_UINT: depthBits = 32; stencilBits = 8; break; case PIXEL_FORMAT_UNKNOWN: depthBits = 0; stencilBits = 0; break; default: Log_ErrorPrintf("SetSDLGLColorAttributes: Unhandled depthstencil format '%s'.", PixelFormat_GetPixelFormatInfo(depthStencilBufferFormat)->Name); return false; } // pass them to sdl SDL_GL_SetAttribute(SDL_GL_RED_SIZE, redBits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, greenBits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, blueBits); // GLX doesn't seem to like the alpha bits... :S #if !Y_PLATFORM_LINUX SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, alphaBits); #endif SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilBits); //SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, (srgbEnabled) ? 1 : 0); // no MSAA for now SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); return true; } static bool SetSDLGLVersionAttributes() { // we always want h/w acceleration SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); //SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); return true; } static bool InitializeGLAD() { // use the sdl loader if (gladLoadGLES2Loader(SDL_GL_GetProcAddress) != GL_TRUE) { Log_ErrorPrint("OpenGLRenderer::Create: Failed to initialize GLAD"); return false; } return true; } bool OpenGLES2RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer) { // select formats PIXEL_FORMAT outputBackBufferFormat = pCreateParameters->BackBufferFormat; PIXEL_FORMAT outputDepthStencilFormat = pCreateParameters->DepthStencilBufferFormat; // if the backbuffer format is unspecified, use the best for the platform if (outputBackBufferFormat == PIXEL_FORMAT_UNKNOWN) { // by default this is rgba8 outputBackBufferFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; } // initialize colour attributes if (!SetSDLGLColorAttributes(outputBackBufferFormat, outputDepthStencilFormat)) { Log_ErrorPrintf("OpenGLES2RenderBackend::Create: Failed to set opengl window system parameters."); return false; } // no sharing possible as there is no current context SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0); // set the attributes SetSDLGLVersionAttributes(); // create context Log_DevPrintf("OpenGLES2RenderBackend::Create: Trying to create a GLES 2.0 context"); SDL_GLContext pSDLGLContext = SDL_GL_CreateContext(pSDLWindow); if (pSDLGLContext == nullptr) { Log_ErrorPrintf("OpenGLES2RenderBackend::Create: Failed to create an acceptable GL context"); return false; } // log+return Log_InfoPrintf("OpenGLES2RenderBackend::Create: Got a GLES 2.0 context."); // initialize glew if (!InitializeGLAD()) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Failed to initialize GLEW"); SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(pSDLGLContext); return false; } // set context settings RENDERER_FEATURE_LEVEL featureLevel = RENDERER_FEATURE_LEVEL_ES2; TEXTURE_PLATFORM texturePlatform = TEXTURE_PLATFORM_ES2_DXTC; // log some info { Log_InfoPrintf("OpenGL ES2 Renderer Feature Level: %s", NameTable_GetNameString(NameTables::RendererFeatureLevelFullName, featureLevel)); Log_InfoPrintf("Texture Platform: %s", NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); // log vendor info Log_InfoPrintf("GL_VENDOR: %s", (glGetString(GL_VENDOR) != NULL) ? glGetString(GL_VENDOR) : (const GLubyte *)"NULL"); Log_InfoPrintf("GL_RENDERER: %s", (glGetString(GL_RENDERER) != NULL) ? glGetString(GL_RENDERER) : (const GLubyte *)"NULL"); Log_InfoPrintf("GL_VERSION: %s", (glGetString(GL_VERSION) != NULL) ? glGetString(GL_VERSION) : (const GLubyte *)"NULL"); // log extensions //Log_InfoPrintf("GL_EXTENSIONS: %s", (glGetString(GL_EXTENSIONS) != NULL) ? glGetString(GL_EXTENSIONS) : (const GLubyte *)"NULL"); const char *extensionString = (const char *)glGetString(GL_EXTENSIONS); if (extensionString != nullptr) { Log_InfoPrint("GL_EXTENSIONS:"); Log_InfoPrint(extensionString); } } #ifdef GL_EXT_texture_filter_anisotropic // run glget calls uint32 maxTextureAnisotropy = 0; if (GLAD_GL_EXT_texture_filter_anisotropic) { glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, reinterpret_cast<GLint *>(&maxTextureAnisotropy)); Log_DevPrintf("glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT): %u", maxTextureAnisotropy); } #endif // query max attributes and max render targets uint32 maxVertexAttributes = 0; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); Log_DevPrintf("glGetIntegerv(GL_MAX_VERTEX_ATTRIBS): %u", maxVertexAttributes); // create output buffer OpenGLES2GPUOutputBuffer *pOutputBuffer = new OpenGLES2GPUOutputBuffer(pSDLWindow, outputBackBufferFormat, outputDepthStencilFormat, pCreateParameters->ImplicitSwapChainVSyncType, false); // create device and context OpenGLES2GPUDevice *pGPUDevice = new OpenGLES2GPUDevice(pSDLGLContext, featureLevel, texturePlatform, outputBackBufferFormat, outputDepthStencilFormat); OpenGLES2GPUContext *pGPUContext = new OpenGLES2GPUContext(pGPUDevice, pSDLGLContext, pOutputBuffer); if (!pGPUContext->Create()) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Could not create device context."); pGPUContext->Release(); pGPUDevice->Release(); return false; } // set pointers *ppDevice = pGPUDevice; *ppImmediateContext = pGPUContext; *ppOutputBuffer = pOutputBuffer; Log_InfoPrint("OpenGL ES 2.0 render backend creation successful."); return true; } <file_sep>/Engine/Source/Renderer/Shaders/ForwardShadingShaders.h #pragma once #include "Renderer/ShaderComponent.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" class BasePassShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(BasePassShader, ShaderComponent); public: enum FLAGS { WITH_EMISSIVE = (1 << 0), WITH_LIGHTMAP = (1 << 1), }; public: BasePassShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class DirectionalLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DirectionalLightShader, ShaderComponent); public: enum FLAGS { WITH_SHADOW_MAP = (1 << 0), SHOW_CASCADES = (1 << 1), USE_HARDWARE_PCF = (1 << 2), SHADOW_FILTER_1X1 = (1 << 3), SHADOW_FILTER_3X3 = (1 << 4), SHADOW_FILTER_5X5 = (1 << 5), SHADOW_BITS_MASK = WITH_SHADOW_MAP | SHOW_CASCADES | USE_HARDWARE_PCF | SHADOW_FILTER_1X1 | SHADOW_FILTER_3X3 | SHADOW_FILTER_5X5 }; public: DirectionalLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } // get flags based on cvar values static uint32 CalculateFlags(bool enableShadows, bool useHardwareShadowFiltering, RENDERER_SHADOW_FILTER shadowFilter, bool showCascades); // light params static void SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData); static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData); // common functions static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EmissiveShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(EmissiveShader, ShaderComponent); public: EmissiveShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PointLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(PointLightShader, ShaderComponent); public: enum FLAGS { WITH_SHADOW_MAP = (1 << 0), USE_HARDWARE_PCF = (1 << 1), SHADOW_BITS_MASK = WITH_SHADOW_MAP | USE_HARDWARE_PCF }; public: PointLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static uint32 CalculateFlags(bool enableShadows, bool useHardwareShadowFiltering); static void SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData); static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PointLightListShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(PointLightListShader, ShaderComponent); public: static const uint32 MAX_LIGHTS = 8; public: PointLightListShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetLightParameters(GPUCommandList *pCommandList, uint32 lightIndex, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); static void SetActiveLightCount(GPUCommandList *pCommandList, uint32 activeLightCount); static void CommitParameters(GPUCommandList *pCommandList); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class VolumetricLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(VolumetricLightShader, ShaderComponent); public: enum Flags { Flag_BoxPrimitive = (1 << 0), Flag_SpherePrimitive = (1 << 1), }; public: VolumetricLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static uint32 GetTypeFlagsForPrimitive(VOLUMETRIC_LIGHT_PRIMITIVE primitive); static void SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight); static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Editor/Source/Editor/EditorVisualComponent.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorVisualComponent.h" #include "MapCompiler/MapSource.h" #include "Engine/Entity.h" #include "Engine/ResourceManager.h" #include "Renderer/RenderProxies/SpriteRenderProxy.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Renderer/RenderProxies/PointLightRenderProxy.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "YBaseLib/XMLReader.h" static Quaternion ParseRotationValue(const char *rotationValue) { uint32 rvLen = Y_strlen(rotationValue); char *rvCopy = (char *)alloca(rvLen + 1); Y_memcpy(rvCopy, rotationValue, rvLen + 1); if (!Y_strnicmp(rvCopy, "euler(", 6)) { char *tokens[3]; if (Y_strsplit3(rvCopy, ',', tokens, countof(tokens)) == 3) { float pitch = StringConverter::StringToFloat(tokens[0]); float yaw = StringConverter::StringToFloat(tokens[1]); float roll = StringConverter::StringToFloat(tokens[2]); return Quaternion::FromEulerAngles(pitch, yaw, roll); } else { return Quaternion::Identity; } } return StringConverter::StringToQuaternion(rvCopy); } EditorVisualComponentDefinition::EditorVisualComponentDefinition() { } EditorVisualComponentDefinition::~EditorVisualComponentDefinition() { } EditorVisualComponentInstance::EditorVisualComponentInstance(uint32 pickingID) : m_pickingID(pickingID), m_visualBounds(AABox::Zero) { } EditorVisualComponentInstance::~EditorVisualComponentInstance() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorVisualComponentDefinition_DirectionalLight::EditorVisualComponentDefinition_DirectionalLight() { m_bEnabled = true; m_Rotation = Quaternion::Identity; m_RotationOffset = Quaternion::Identity; m_Color = float3::One; m_Brightness = 1.0f; m_iShadowFlags = 0; m_fAmbientFactor = 0.2f; m_bOnlyShowWhenSelected = false; } EditorVisualComponentDefinition_DirectionalLight::~EditorVisualComponentDefinition_DirectionalLight() { } EditorVisualComponentDefinition *EditorVisualComponentDefinition_DirectionalLight::Clone() const { EditorVisualComponentDefinition_DirectionalLight *pClone = new EditorVisualComponentDefinition_DirectionalLight(); pClone->m_bEnabled = m_bEnabled; pClone->m_strEnabledFromPropertyName = m_strEnabledFromPropertyName; pClone->m_Rotation = m_Rotation; pClone->m_strRotationFromPropertyName = m_strRotationFromPropertyName; pClone->m_RotationOffset = m_RotationOffset; pClone->m_Color = m_Color; pClone->m_strColorFromPropertyName = m_strColorFromPropertyName; pClone->m_Brightness = m_Brightness; pClone->m_strBrightnessFromPropertyName = m_strBrightnessFromPropertyName; pClone->m_iShadowFlags = m_iShadowFlags; pClone->m_strShadowFlagsFromPropertyName = m_strShadowFlagsFromPropertyName; pClone->m_fAmbientFactor = m_fAmbientFactor; pClone->m_strAmbientFactorFromPropertyName = m_strAmbientFactorFromPropertyName; pClone->m_bOnlyShowWhenSelected = m_bOnlyShowWhenSelected; return pClone; } bool EditorVisualComponentDefinition_DirectionalLight::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 visualSelection = xmlReader.Select("enabled|rotation|color|brightness|shadow-flags|ambient-factor|only-show-when-selected"); if (visualSelection < 0) return false; switch (visualSelection) { // enabled case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_bEnabled = StringConverter::StringToBool(valueStr); if (fromPropertyStr != NULL) m_strEnabledFromPropertyName = fromPropertyStr; } break; // rotation case 1: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Rotation = ParseRotationValue(valueStr); if (offsetStr != NULL) m_RotationOffset = ParseRotationValue(offsetStr); if (fromPropertyStr != NULL) m_strRotationFromPropertyName = fromPropertyStr; } break; // color case 2: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Color = StringConverter::StringToFloat3(valueStr); if (fromPropertyStr != NULL) m_strColorFromPropertyName = fromPropertyStr; } break; // brightness case 3: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Brightness = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strBrightnessFromPropertyName = fromPropertyStr; } break; // shadow-flags case 4: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_iShadowFlags = StringConverter::StringToUInt32(valueStr); if (fromPropertyStr != NULL) m_strShadowFlagsFromPropertyName = fromPropertyStr; } break; // ambient-factor case 5: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_fAmbientFactor = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strAmbientFactorFromPropertyName = fromPropertyStr; } break; // only-show-when-selected case 6: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_bOnlyShowWhenSelected = StringConverter::StringToBool(valueStr); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualComponentInstance *EditorVisualComponentDefinition_DirectionalLight::CreateVisual(uint32 pickingID) const { return new EditorVisualComponentInstance_DirectionalLight(pickingID, this); } EditorVisualComponentInstance_DirectionalLight::EditorVisualComponentInstance_DirectionalLight(uint32 pickingID, const EditorVisualComponentDefinition_DirectionalLight *pDefinition) : EditorVisualComponentInstance(pickingID), m_pDefinition(pDefinition) { // read other defaults from definition m_Enabled = m_pDefinition->GetEnabled(); m_Rotation = m_pDefinition->GetRotation(); m_Color = m_pDefinition->GetColor(); m_Brightness = m_pDefinition->GetBrightness(); m_ShadowFlags = m_pDefinition->GetShadowFlags(); m_AmbientFactor = m_pDefinition->GetAmbientFactor(); // create render proxy m_pDirectionalLightRenderProxy = new DirectionalLightRenderProxy(pickingID, m_Enabled, float3::One, float3::Zero, m_ShadowFlags, CalculateDirection()); UpdateLightColor(); // update bounds m_visualBounds = AABox::MaxSize; } EditorVisualComponentInstance_DirectionalLight::~EditorVisualComponentInstance_DirectionalLight() { m_pDirectionalLightRenderProxy->Release(); } float3 EditorVisualComponentInstance_DirectionalLight::CalculateDirection() { return (m_Rotation * m_pDefinition->GetRotationOffset()) * float3::NegativeUnitZ; } void EditorVisualComponentInstance_DirectionalLight::OnAddedToRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->AddRenderable(m_pDirectionalLightRenderProxy); } void EditorVisualComponentInstance_DirectionalLight::OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->RemoveRenderable(m_pDirectionalLightRenderProxy); } void EditorVisualComponentInstance_DirectionalLight::OnPropertyChange(const char *propertyName, const char *propertyValue) { // enabled if (m_pDefinition->GetEnabledFromPropertyName().CompareInsensitive(propertyName)) { m_Enabled = StringConverter::StringToBool(propertyValue); m_pDirectionalLightRenderProxy->SetEnabled(m_Enabled); } // rotation if (m_pDefinition->GetRotationFromPropertyName().CompareInsensitive(propertyName)) { m_Rotation = StringConverter::StringToQuaternion(propertyValue); m_pDirectionalLightRenderProxy->SetDirection(CalculateDirection()); } // color if (m_pDefinition->GetColorFromPropertyName().CompareInsensitive(propertyName)) { m_Color = StringConverter::StringToFloat3(propertyValue); UpdateLightColor(); } // brightness if (m_pDefinition->GetBrightnessFromPropertyName().CompareInsensitive(propertyName)) { m_Brightness = StringConverter::StringToFloat(propertyValue); UpdateLightColor(); } // dynamic shadows if (m_pDefinition->GetShadowFlagsFromPropertyName().CompareInsensitive(propertyName)) { m_ShadowFlags = StringConverter::StringToUInt32(propertyValue); m_pDirectionalLightRenderProxy->SetShadowFlags(m_ShadowFlags); } // ambient coefficient if (m_pDefinition->GetAmbientFactorFromPropertyName().CompareInsensitive(propertyName)) { m_AmbientFactor = StringConverter::StringToFloat(propertyValue); UpdateLightColor(); } } void EditorVisualComponentInstance_DirectionalLight::OnSelectionStateChange(bool selected) { if (m_pDefinition->GetOnlyShowWhenSelected()) { m_pDirectionalLightRenderProxy->SetEnabled(m_Enabled); m_pDirectionalLightRenderProxy->SetEnabled((m_AmbientFactor != 0.0f) ? m_Enabled : false); } } void EditorVisualComponentInstance_DirectionalLight::UpdateLightColor() { SIMDVector3f lightColor(m_Color); SIMDVector3f directionalLightColor(lightColor * (m_Brightness * (1.0f - m_AmbientFactor))); SIMDVector3f ambientLightColor(lightColor * (m_Brightness * m_AmbientFactor)); m_pDirectionalLightRenderProxy->SetLightColor(directionalLightColor); m_pDirectionalLightRenderProxy->SetAmbientColor(ambientLightColor); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorVisualComponentDefinition_PointLight::EditorVisualComponentDefinition_PointLight() { m_bEnabled = true; m_Position = float3::Zero; m_PositionOffset = float3::Zero; m_Range = 128.0f; m_Color = float3::One; m_Brightness = 1.0f; m_FalloffExponent = 2.0f; m_iShadowFlags = 0; m_bOnlyShowWhenSelected = false; } EditorVisualComponentDefinition_PointLight::~EditorVisualComponentDefinition_PointLight() { } EditorVisualComponentDefinition *EditorVisualComponentDefinition_PointLight::Clone() const { EditorVisualComponentDefinition_PointLight *pClone = new EditorVisualComponentDefinition_PointLight(); pClone->m_bEnabled = m_bEnabled; pClone->m_strEnabledFromPropertyName = m_strEnabledFromPropertyName; pClone->m_Position = m_Position; pClone->m_strPositionFromPropertyName = m_strPositionFromPropertyName; pClone->m_PositionOffset = m_PositionOffset; pClone->m_Range = m_Range; pClone->m_strRangeFromPropertyName = m_strRangeFromPropertyName; pClone->m_Color = m_Color; pClone->m_strColorFromPropertyName = m_strColorFromPropertyName; pClone->m_Brightness = m_Brightness; pClone->m_strBrightnessFromPropertyName = m_strBrightnessFromPropertyName; pClone->m_FalloffExponent = m_FalloffExponent; pClone->m_strFalloffExponentFromPropertyName = m_strFalloffExponentFromPropertyName; pClone->m_iShadowFlags = m_iShadowFlags; pClone->m_strShadowFlagsFromPropertyName = m_strShadowFlagsFromPropertyName; pClone->m_bOnlyShowWhenSelected = m_bOnlyShowWhenSelected; return pClone; } bool EditorVisualComponentDefinition_PointLight::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 visualSelection = xmlReader.Select("enabled|position|range|color|brightness|shadowflags|falloff-exponent|only-show-when-selected"); if (visualSelection < 0) return false; switch (visualSelection) { // enabled case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_bEnabled = StringConverter::StringToBool(valueStr); if (fromPropertyStr != NULL) m_strEnabledFromPropertyName = fromPropertyStr; } break; // position case 1: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Position = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_PositionOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strPositionFromPropertyName = fromPropertyStr; } break; // range case 2: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Range = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strRangeFromPropertyName = fromPropertyStr; } break; // color case 3: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Color = StringConverter::StringToFloat3(valueStr); if (fromPropertyStr != NULL) m_strColorFromPropertyName = fromPropertyStr; } break; // brightness case 4: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Brightness = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strBrightnessFromPropertyName = fromPropertyStr; } break; // shadowflags case 5: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_iShadowFlags = StringConverter::StringToUInt32(valueStr); if (fromPropertyStr != NULL) m_strShadowFlagsFromPropertyName = fromPropertyStr; } break; // falloff-exponent case 6: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_FalloffExponent = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strFalloffExponentFromPropertyName = fromPropertyStr; } break; // only-show-when-selected case 7: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_bOnlyShowWhenSelected = StringConverter::StringToBool(valueStr); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualComponentInstance *EditorVisualComponentDefinition_PointLight::CreateVisual(uint32 pickingID) const { return new EditorVisualComponentInstance_PointLight(pickingID, this); } EditorVisualComponentInstance_PointLight::EditorVisualComponentInstance_PointLight(uint32 pickingID, const EditorVisualComponentDefinition_PointLight *pDefinition) : EditorVisualComponentInstance(pickingID), m_pDefinition(pDefinition) { // read other defaults from definition m_Enabled = m_pDefinition->GetEnabled(); m_Position = m_pDefinition->GetPosition(); m_Range = m_pDefinition->GetRange(); m_Color = m_pDefinition->GetColor(); m_Brightness = m_pDefinition->GetBrightness(); m_ShadowFlags = m_pDefinition->GetShadowFlags(); m_FalloffExponent = m_pDefinition->GetFalloffExponent(); m_EntityPosition.SetZero(); // create render proxy m_pRenderProxy = new PointLightRenderProxy(pickingID, m_Position + m_pDefinition->GetPositionOffset(), m_Range, m_Color, 0, m_FalloffExponent); // update bounds UpdateBounds(); } EditorVisualComponentInstance_PointLight::~EditorVisualComponentInstance_PointLight() { m_pRenderProxy->Release(); } void EditorVisualComponentInstance_PointLight::OnAddedToRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->AddRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_PointLight::OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->RemoveRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_PointLight::OnPropertyChange(const char *propertyName, const char *propertyValue) { // enabled if (m_pDefinition->GetEnabledFromPropertyName().CompareInsensitive(propertyName)) { m_Enabled = StringConverter::StringToBool(propertyValue); m_pRenderProxy->SetEnabled(m_Enabled); } // position if (m_pDefinition->GetPositionFromPropertyName().CompareInsensitive(propertyName)) { m_Position = StringConverter::StringToFloat3(propertyValue); m_pRenderProxy->SetPosition(m_Position + m_pDefinition->GetPositionOffset()); UpdateBounds(); } // range if (m_pDefinition->GetRangeFromPropertyName().CompareInsensitive(propertyName)) { m_Range = StringConverter::StringToFloat(propertyValue); m_pRenderProxy->SetRange(m_Range); UpdateBounds(); } // color if (m_pDefinition->GetColorFromPropertyName().CompareInsensitive(propertyName)) { m_Color = StringConverter::StringToFloat3(propertyValue); m_pRenderProxy->SetColor(m_Color * m_Brightness); } // brightness if (m_pDefinition->GetBrightnessFromPropertyName().CompareInsensitive(propertyName)) { m_Brightness = StringConverter::StringToFloat(propertyValue); m_pRenderProxy->SetColor(m_Color * m_Brightness); } // dynamic shadows if (m_pDefinition->GetShadowFlagsFromPropertyName().CompareInsensitive(propertyName)) { m_ShadowFlags = StringConverter::StringToUInt32(propertyValue); m_pRenderProxy->SetShadowFlags(m_ShadowFlags); } // falloff exponent if (m_pDefinition->GetFalloffExponentFromPropertyName().CompareInsensitive(propertyName)) { m_FalloffExponent = StringConverter::StringToFloat(propertyValue); m_pRenderProxy->SetFalloffExponent(m_FalloffExponent); } } void EditorVisualComponentInstance_PointLight::OnSelectionStateChange(bool selected) { if (m_pDefinition->GetOnlyShowWhenSelected()) m_pRenderProxy->SetEnabled(selected ? m_Enabled : false); } void EditorVisualComponentInstance_PointLight::UpdateBounds() { SIMDVector3f actualPosition = m_Position + m_pDefinition->GetPositionOffset(); SIMDVector3f minBounds = actualPosition - m_Range; SIMDVector3f maxBounds = actualPosition + m_Range; m_visualBounds.SetBounds(minBounds, maxBounds); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorVisualComponentDefinition_Sprite::EditorVisualComponentDefinition_Sprite() { // set defaults m_Position = float3::Zero; m_PositionOffset = float3::Zero; m_Scale = float3::One; m_ScaleOffset = float3::One; m_bVisible = true; m_iShadowFlags = 0; m_strTextureName = g_pEngine->GetDefaultTexture2DName(); m_eBlendingMode = MATERIAL_BLENDING_MODE_STRAIGHT; m_fWidth = 128.0f; m_fHeight = 128.0f; m_TintColor = 0xFFFFFFFF; m_SelectedTintColor = 0xFFFFFFFF; m_bOnlyShowWhenSelected = false; } EditorVisualComponentDefinition_Sprite::~EditorVisualComponentDefinition_Sprite() { } EditorVisualComponentDefinition *EditorVisualComponentDefinition_Sprite::Clone() const { EditorVisualComponentDefinition_Sprite *pClone = new EditorVisualComponentDefinition_Sprite(); pClone->m_Position = m_Position; pClone->m_strPositionFromPropertyName = m_strPositionFromPropertyName; pClone->m_PositionOffset = m_PositionOffset; pClone->m_Scale = m_Scale; pClone->m_strScaleFromPropertyName = m_strScaleFromPropertyName; pClone->m_ScaleOffset = m_ScaleOffset; pClone->m_bVisible = m_bVisible; pClone->m_strVisibleFromPropertyName = m_strVisibleFromPropertyName; pClone->m_iShadowFlags = m_iShadowFlags; pClone->m_strShadowFlagsFromPropertyName = m_strShadowFlagsFromPropertyName; pClone->m_strTextureName = m_strTextureName; pClone->m_strTextureFromPropertyName = m_strTextureFromPropertyName; pClone->m_eBlendingMode = m_eBlendingMode; pClone->m_strBlendingModeFromPropertyName = m_strBlendingModeFromPropertyName; pClone->m_fWidth = m_fWidth; pClone->m_strWidthFromPropertyName = m_strWidthFromPropertyName; pClone->m_fHeight = m_fHeight; pClone->m_strHeightFromPropertyName = m_strHeightFromPropertyName; pClone->m_TintColor = m_TintColor; pClone->m_SelectedTintColor = m_SelectedTintColor; pClone->m_bOnlyShowWhenSelected = m_bOnlyShowWhenSelected; return pClone; } bool EditorVisualComponentDefinition_Sprite::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 visualSelection = xmlReader.Select("position|scale|visible|shadowflags|texture|blending|width|height|tint-color|selected-tint-color|only-show-when-selected"); if (visualSelection < 0) return false; switch (visualSelection) { // position case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Position = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_PositionOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strPositionFromPropertyName = fromPropertyStr; } break; // scale case 1: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Scale = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_ScaleOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strScaleFromPropertyName = fromPropertyStr; } break; // visible case 2: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_bVisible = StringConverter::StringToBool(valueStr); if (fromPropertyStr != NULL) m_strVisibleFromPropertyName = fromPropertyStr; } break; // shadowflags case 3: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_iShadowFlags = StringConverter::StringToUInt32(valueStr); if (fromPropertyStr != NULL) m_strShadowFlagsFromPropertyName = fromPropertyStr; } break; // texture case 4: { const char *nameStr = xmlReader.FetchAttribute("name"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (nameStr != NULL) m_strTextureName = nameStr; if (fromPropertyStr != NULL) m_strTextureFromPropertyName = fromPropertyStr; } break; // blending case 5: { const char *modeStr = xmlReader.FetchAttribute("mode"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (modeStr != NULL) { if (!NameTable_TranslateType(NameTables::MaterialBlendingMode, modeStr, &m_eBlendingMode, true)) { xmlReader.PrintError("invalid blending mode: '%s'", modeStr); return false; } } if (fromPropertyStr != NULL) m_strBlendingModeFromPropertyName = fromPropertyStr; } break; // width case 6: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_fWidth = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strTextureFromPropertyName = fromPropertyStr; } break; // height case 7: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_fHeight = StringConverter::StringToFloat(valueStr); if (fromPropertyStr != NULL) m_strTextureFromPropertyName = fromPropertyStr; } break; // tint-color case 8: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_TintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // selected-tint-color case 9: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_SelectedTintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // only-show-when-selected case 10: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_bOnlyShowWhenSelected = StringConverter::StringToBool(valueStr); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualComponentInstance *EditorVisualComponentDefinition_Sprite::CreateVisual(uint32 pickingID) const { return new EditorVisualComponentInstance_Sprite(pickingID, this); } EditorVisualComponentInstance_Sprite::EditorVisualComponentInstance_Sprite(uint32 pickingID, const EditorVisualComponentDefinition_Sprite *pDefinition) : EditorVisualComponentInstance(pickingID), m_pDefinition(pDefinition) { // set default texture if ((m_pTexture = g_pResourceManager->GetTexture2D(pDefinition->GetTextureName())) == NULL) m_pTexture = g_pResourceManager->GetDefaultTexture2D(); // read other defaults from definition m_eBlendingMode = pDefinition->GetBlendingMode(); m_Position = pDefinition->GetPosition(); m_Scale = pDefinition->GetScale(); m_Visible = pDefinition->GetVisible(); m_ShadowFlags = pDefinition->GetShadowFlags(); m_fWidth = pDefinition->GetWidth(); m_fHeight = pDefinition->GetHeight(); // create render proxy m_pRenderProxy = new SpriteRenderProxy(pickingID, m_pTexture, m_Position + pDefinition->GetPositionOffset()); m_pRenderProxy->SetSizeByDimensions(m_fWidth, m_fHeight); // update bounds UpdateBounds(); } EditorVisualComponentInstance_Sprite::~EditorVisualComponentInstance_Sprite() { m_pRenderProxy->Release(); m_pTexture->Release(); } void EditorVisualComponentInstance_Sprite::OnAddedToRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->AddRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_Sprite::OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->RemoveRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_Sprite::OnPropertyChange(const char *propertyName, const char *propertyValue) { // position if (m_pDefinition->GetPositionFromPropertyName().CompareInsensitive(propertyName)) { m_Position = StringConverter::StringToFloat3(propertyValue); m_pRenderProxy->SetPosition(m_Position + m_pDefinition->GetPositionOffset()); UpdateBounds(); } // scale if (m_pDefinition->GetScaleFromPropertyName().CompareInsensitive(propertyName)) { m_Scale = StringConverter::StringToFloat3(propertyValue); //UpdateTransform(); } // visible if (m_pDefinition->GetVisibleFromPropertyName().CompareInsensitive(propertyName)) { m_Visible = StringConverter::StringToBool(propertyValue); m_pRenderProxy->SetVisibility(m_Visible); } // shadowflags if (m_pDefinition->GetVisibleFromPropertyName().CompareInsensitive(propertyName)) { m_ShadowFlags = StringConverter::StringToUInt32(propertyValue); //m_pRenderProxy->SetShadowFlags(m_ShadowFlags); } // texture name if (m_pDefinition->GetTextureFromPropertyName().CompareInsensitive(propertyName)) { const Texture2D *pTexture; if ((pTexture = g_pResourceManager->GetTexture2D(propertyValue)) == NULL) { if ((pTexture = g_pResourceManager->GetTexture2D(m_pDefinition->GetTextureName())) == NULL) pTexture = g_pResourceManager->GetDefaultTexture2D(); } Swap(m_pTexture, pTexture); pTexture->Release(); } // blending mode if (m_pDefinition->GetBlendingModeFromPropertyName().CompareInsensitive(propertyValue)) { m_eBlendingMode = (MATERIAL_BLENDING_MODE)StringConverter::StringToUInt32(propertyValue); if (m_eBlendingMode >= MATERIAL_BLENDING_MODE_COUNT) m_eBlendingMode = m_pDefinition->GetBlendingMode(); } // width if (m_pDefinition->GetWidthFromPropertyName().CompareInsensitive(propertyValue)) { m_fWidth = StringConverter::StringToFloat(propertyValue); UpdateBounds(); } // height if (m_pDefinition->GetHeightFromPropertyName().CompareInsensitive(propertyValue)) { m_fHeight = StringConverter::StringToFloat(propertyValue); UpdateBounds(); } } void EditorVisualComponentInstance_Sprite::OnSelectionStateChange(bool selected) { uint32 tintColor = m_pDefinition->GetTintColor(); uint32 selectedTintColor = m_pDefinition->GetSelectedTintColor(); if (tintColor != selectedTintColor) { uint32 currentColor = selected ? selectedTintColor : tintColor; if (currentColor != 0xFFFFFFFF) m_pRenderProxy->SetTintColor(true, selectedTintColor); else m_pRenderProxy->SetTintColor(false); } if (m_pDefinition->GetOnlyShowWhenSelected()) m_pRenderProxy->SetVisibility(selected ? m_Visible : false); } void EditorVisualComponentInstance_Sprite::UpdateBounds() { float halfWidth = m_fWidth * 0.5f; float halfHeight = m_fHeight * 0.5f; float3 actualPosition = m_Position + m_pDefinition->GetPositionOffset(); float3 minBounds = float3(actualPosition.x - halfWidth, actualPosition.y - halfWidth, actualPosition.z - halfHeight); float3 maxBounds = float3(actualPosition.x + halfWidth, actualPosition.y + halfWidth, actualPosition.z + halfHeight); m_visualBounds.SetBounds(minBounds, maxBounds); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorVisualComponentDefinition_StaticMesh::EditorVisualComponentDefinition_StaticMesh() { m_Position = float3::Zero; m_PositionOffset = float3::Zero; m_Rotation = Quaternion::Identity; m_RotationOffset = Quaternion::Identity; m_Scale = float3::One; m_ScaleOffset = float3::One; m_bVisible = true; m_iShadowFlags = 0; m_strMeshName = g_pEngine->GetDefaultStaticMeshName(); m_TintColor = 0xFFFFFFFF; m_SelectedTintColor = 0xFFFFFFFF; m_bOnlyShowWhenSelected = false; } EditorVisualComponentDefinition_StaticMesh::~EditorVisualComponentDefinition_StaticMesh() { } EditorVisualComponentDefinition *EditorVisualComponentDefinition_StaticMesh::Clone() const { EditorVisualComponentDefinition_StaticMesh *pClone = new EditorVisualComponentDefinition_StaticMesh(); pClone->m_Position = m_Position; pClone->m_strPositionFromPropertyName = m_strPositionFromPropertyName; pClone->m_PositionOffset = m_PositionOffset; pClone->m_Rotation = m_Rotation; pClone->m_strRotationFromPropertyName = m_strRotationFromPropertyName; pClone->m_RotationOffset = m_RotationOffset; pClone->m_Scale = m_Scale; pClone->m_strScaleFromPropertyName = m_strScaleFromPropertyName; pClone->m_ScaleOffset = m_ScaleOffset; pClone->m_bVisible = m_bVisible; pClone->m_strVisibleFromPropertyName = m_strVisibleFromPropertyName; pClone->m_iShadowFlags = m_iShadowFlags; pClone->m_strShadowFlagsFromPropertyName = m_strShadowFlagsFromPropertyName; pClone->m_strMeshName = m_strMeshName; pClone->m_strMeshFromPropertyName = m_strMeshFromPropertyName; pClone->m_TintColor = m_TintColor; pClone->m_SelectedTintColor = m_SelectedTintColor; pClone->m_bOnlyShowWhenSelected = m_bOnlyShowWhenSelected; return pClone; } bool EditorVisualComponentDefinition_StaticMesh::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 visualSelection = xmlReader.Select("position|rotation|scale|visible|shadowflags|mesh|tint-color|selected-tint-color|only-show-when-selected"); if (visualSelection < 0) return false; switch (visualSelection) { // position case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Position = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_PositionOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strPositionFromPropertyName = fromPropertyStr; } break; // rotation case 1: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Rotation = ParseRotationValue(valueStr); if (offsetStr != NULL) m_RotationOffset = ParseRotationValue(offsetStr); if (fromPropertyStr != NULL) m_strRotationFromPropertyName = fromPropertyStr; } break; // scale case 2: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Scale = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_ScaleOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strScaleFromPropertyName = fromPropertyStr; } break; // visible case 3: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_bVisible = StringConverter::StringToBool(valueStr); if (fromPropertyStr != NULL) m_strVisibleFromPropertyName = fromPropertyStr; } break; // shadowflags case 4: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_iShadowFlags = StringConverter::StringToUInt32(valueStr); if (fromPropertyStr != NULL) m_strShadowFlagsFromPropertyName = fromPropertyStr; } break; // mesh case 5: { const char *nameStr = xmlReader.FetchAttribute("name"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (nameStr != NULL) m_strMeshName = nameStr; if (fromPropertyStr != NULL) m_strMeshFromPropertyName = fromPropertyStr; } break; // tint-color case 6: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_TintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // selected-tint-color case 7: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_SelectedTintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // only-show-when-selected case 8: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_bOnlyShowWhenSelected = StringConverter::StringToBool(valueStr); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualComponentInstance *EditorVisualComponentDefinition_StaticMesh::CreateVisual(uint32 pickingID) const { return new EditorVisualComponentInstance_StaticMesh(pickingID, this); } EditorVisualComponentInstance_StaticMesh::EditorVisualComponentInstance_StaticMesh(uint32 pickingID, const EditorVisualComponentDefinition_StaticMesh *pDefinition) : EditorVisualComponentInstance(pickingID), m_pDefinition(pDefinition) { // get mesh pointer if ((m_pStaticMesh = g_pResourceManager->GetStaticMesh(pDefinition->GetMeshName())) == NULL) m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); // read other defaults from definition m_Position = pDefinition->GetPosition(); m_Rotation = pDefinition->GetRotation(); m_Scale = pDefinition->GetScale(); m_Visible = pDefinition->GetVisible(); m_ShadowFlags = pDefinition->GetShadowFlags(); // create render proxy m_pRenderProxy = new StaticMeshRenderProxy(pickingID, m_pStaticMesh, Transform::Identity, m_ShadowFlags); // update bounds UpdateTransform(); } EditorVisualComponentInstance_StaticMesh::~EditorVisualComponentInstance_StaticMesh() { m_pRenderProxy->Release(); m_pStaticMesh->Release(); } void EditorVisualComponentInstance_StaticMesh::OnAddedToRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->AddRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_StaticMesh::OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->RemoveRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_StaticMesh::OnPropertyChange(const char *propertyName, const char *propertyValue) { // position if (m_pDefinition->GetPositionFromPropertyName().CompareInsensitive(propertyName)) { m_Position = StringConverter::StringToFloat3(propertyValue); UpdateTransform(); } // rotation if (m_pDefinition->GetRotationFromPropertyName().CompareInsensitive(propertyName)) { m_Rotation = StringConverter::StringToQuaternion(propertyValue); UpdateTransform(); } // scale if (m_pDefinition->GetScaleFromPropertyName().CompareInsensitive(propertyName)) { m_Scale = StringConverter::StringToFloat3(propertyValue); UpdateTransform(); } // visible if (m_pDefinition->GetVisibleFromPropertyName().CompareInsensitive(propertyName)) { m_Visible = StringConverter::StringToBool(propertyValue); m_pRenderProxy->SetVisibility(m_Visible); } // shadowflags if (m_pDefinition->GetShadowFlagsFromPropertyName().CompareInsensitive(propertyName)) { m_ShadowFlags = StringConverter::StringToUInt32(propertyValue); m_pRenderProxy->SetShadowFlags(m_ShadowFlags); } // mesh name if (m_pDefinition->GetMeshFromPropertyName().CompareInsensitive(propertyName)) { const StaticMesh *pStaticMesh; if ((pStaticMesh = g_pResourceManager->GetStaticMesh(propertyValue)) == NULL) { if ((pStaticMesh = g_pResourceManager->GetStaticMesh(m_pDefinition->GetMeshName())) == NULL) pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); } if (m_pStaticMesh != pStaticMesh) { // set mesh m_pStaticMesh->Release(); m_pStaticMesh = pStaticMesh; // update render proxy m_pRenderProxy->SetStaticMesh(pStaticMesh); // fix up bounds UpdateBounds(); } else { // no change needed pStaticMesh->Release(); } } } void EditorVisualComponentInstance_StaticMesh::OnSelectionStateChange(bool selected) { uint32 tintColor = m_pDefinition->GetTintColor(); uint32 selectedTintColor = m_pDefinition->GetSelectedTintColor(); if (tintColor != selectedTintColor) { uint32 currentColor = selected ? selectedTintColor : tintColor; if (currentColor != 0xFFFFFFFF) m_pRenderProxy->SetTintColor(true, selectedTintColor); else m_pRenderProxy->SetTintColor(false); } if (m_pDefinition->GetOnlyShowWhenSelected()) m_pRenderProxy->SetVisibility(selected ? m_Visible : false); } void EditorVisualComponentInstance_StaticMesh::UpdateTransform() { Transform offsetTransform(m_pDefinition->GetPositionOffset(), m_pDefinition->GetRotationOffset(), m_pDefinition->GetScaleOffset()); Transform localTransform(m_Position, m_Rotation, m_Scale); Transform fullTransform(Transform::ConcatenateTransforms(offsetTransform, localTransform)); // effective order: LS * LR * LT * ER * ET m_CachedTransform = fullTransform; m_pRenderProxy->SetTransform(m_CachedTransform); // fix up bounds too UpdateBounds(); } void EditorVisualComponentInstance_StaticMesh::UpdateBounds() { m_visualBounds = m_CachedTransform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorVisualComponentDefinition_BlockMesh::EditorVisualComponentDefinition_BlockMesh() { m_Position = float3::Zero; m_PositionOffset = float3::Zero; m_Rotation = Quaternion::Identity; m_RotationOffset = Quaternion::Identity; m_Scale = float3::One; m_ScaleOffset = float3::One; m_bVisible = true; m_iShadowFlags = 0; m_strMeshName = g_pEngine->GetDefaultBlockMeshName(); m_TintColor = 0xFFFFFFFF; m_SelectedTintColor = 0xFFFFFFFF; m_bOnlyShowWhenSelected = false; } EditorVisualComponentDefinition_BlockMesh::~EditorVisualComponentDefinition_BlockMesh() { } EditorVisualComponentDefinition *EditorVisualComponentDefinition_BlockMesh::Clone() const { EditorVisualComponentDefinition_BlockMesh *pClone = new EditorVisualComponentDefinition_BlockMesh(); pClone->m_Position = m_Position; pClone->m_strPositionFromPropertyName = m_strPositionFromPropertyName; pClone->m_PositionOffset = m_PositionOffset; pClone->m_Rotation = m_Rotation; pClone->m_strRotationFromPropertyName = m_strRotationFromPropertyName; pClone->m_RotationOffset = m_RotationOffset; pClone->m_Scale = m_Scale; pClone->m_strScaleFromPropertyName = m_strScaleFromPropertyName; pClone->m_ScaleOffset = m_ScaleOffset; pClone->m_bVisible = m_bVisible; pClone->m_strVisibleFromPropertyName = m_strVisibleFromPropertyName; pClone->m_iShadowFlags = m_iShadowFlags; pClone->m_strShadowFlagsFromPropertyName = m_strShadowFlagsFromPropertyName; pClone->m_strMeshName = m_strMeshName; pClone->m_strMeshFromPropertyName = m_strMeshFromPropertyName; pClone->m_TintColor = m_TintColor; pClone->m_SelectedTintColor = m_SelectedTintColor; pClone->m_bOnlyShowWhenSelected = m_bOnlyShowWhenSelected; return pClone; } bool EditorVisualComponentDefinition_BlockMesh::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 visualSelection = xmlReader.Select("position|rotation|scale|visible|shadowflags|mesh|tint-color|selected-tint-color|only-show-when-selected"); if (visualSelection < 0) return false; switch (visualSelection) { // position case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Position = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_PositionOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strPositionFromPropertyName = fromPropertyStr; } break; // rotation case 1: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Rotation = ParseRotationValue(valueStr); if (offsetStr != NULL) m_RotationOffset = ParseRotationValue(offsetStr); if (fromPropertyStr != NULL) m_strRotationFromPropertyName = fromPropertyStr; } break; // scale case 2: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_Scale = StringConverter::StringToFloat3(valueStr); if (offsetStr != NULL) m_ScaleOffset = StringConverter::StringToFloat3(offsetStr); if (fromPropertyStr != NULL) m_strScaleFromPropertyName = fromPropertyStr; } break; // visible case 3: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_bVisible = StringConverter::StringToBool(valueStr); if (fromPropertyStr != NULL) m_strVisibleFromPropertyName = fromPropertyStr; } break; // shadowflags case 4: { const char *valueStr = xmlReader.FetchAttribute("value"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (valueStr != NULL) m_iShadowFlags = StringConverter::StringToUInt32(valueStr); if (fromPropertyStr != NULL) m_strShadowFlagsFromPropertyName = fromPropertyStr; } break; // mesh case 5: { const char *nameStr = xmlReader.FetchAttribute("name"); const char *fromPropertyStr = xmlReader.FetchAttribute("from-property"); if (nameStr != NULL) m_strMeshName = nameStr; if (fromPropertyStr != NULL) m_strMeshFromPropertyName = fromPropertyStr; } break; // tint-color case 6: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_TintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // selected-tint-color case 7: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_SelectedTintColor = StringConverter::StringToColor(valueStr) | 0xff000000; } break; // only-show-when-selected case 8: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr != NULL) m_bOnlyShowWhenSelected = StringConverter::StringToBool(valueStr); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualComponentInstance *EditorVisualComponentDefinition_BlockMesh::CreateVisual(uint32 pickingID) const { return new EditorVisualComponentInstance_BlockMesh(pickingID, this); } EditorVisualComponentInstance_BlockMesh::EditorVisualComponentInstance_BlockMesh(uint32 pickingID, const EditorVisualComponentDefinition_BlockMesh *pDefinition) : EditorVisualComponentInstance(pickingID), m_pDefinition(pDefinition) { // get mesh pointer if ((m_pBlockMesh = g_pResourceManager->GetBlockMesh(pDefinition->GetMeshName())) == NULL) m_pBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); // read other defaults from definition m_Position = pDefinition->GetPosition(); m_Rotation = pDefinition->GetRotation(); m_Scale = pDefinition->GetScale(); m_Visible = pDefinition->GetVisible(); m_ShadowFlags = pDefinition->GetShadowFlags(); // create render proxy m_pRenderProxy = new BlockMeshRenderProxy(pickingID, m_pBlockMesh, Transform::Identity, m_ShadowFlags); // update bounds UpdateTransform(); } EditorVisualComponentInstance_BlockMesh::~EditorVisualComponentInstance_BlockMesh() { m_pRenderProxy->Release(); m_pBlockMesh->Release(); } void EditorVisualComponentInstance_BlockMesh::OnAddedToRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->AddRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_BlockMesh::OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) { pRenderWorld->RemoveRenderable(m_pRenderProxy); } void EditorVisualComponentInstance_BlockMesh::OnPropertyChange(const char *propertyName, const char *propertyValue) { // position if (m_pDefinition->GetPositionFromPropertyName().CompareInsensitive(propertyName)) { m_Position = StringConverter::StringToFloat3(propertyValue); UpdateTransform(); } // rotation if (m_pDefinition->GetRotationFromPropertyName().CompareInsensitive(propertyName)) { m_Rotation = StringConverter::StringToQuaternion(propertyValue); UpdateTransform(); } // scale if (m_pDefinition->GetScaleFromPropertyName().CompareInsensitive(propertyName)) { m_Scale = StringConverter::StringToFloat3(propertyValue); UpdateTransform(); } // visible if (m_pDefinition->GetVisibleFromPropertyName().CompareInsensitive(propertyName)) { m_Visible = StringConverter::StringToBool(propertyValue); m_pRenderProxy->SetVisibility(m_Visible); } // shadowflags if (m_pDefinition->GetShadowFlagsFromPropertyName().CompareInsensitive(propertyName)) { m_ShadowFlags = StringConverter::StringToUInt32(propertyValue); m_pRenderProxy->SetShadowFlags(m_ShadowFlags); } // mesh name if (m_pDefinition->GetMeshFromPropertyName().CompareInsensitive(propertyName)) { const BlockMesh *pStaticBlockMesh; if ((pStaticBlockMesh = g_pResourceManager->GetBlockMesh(propertyValue)) == NULL) { if ((pStaticBlockMesh = g_pResourceManager->GetBlockMesh(m_pDefinition->GetMeshName())) == NULL) pStaticBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); } if (m_pBlockMesh != pStaticBlockMesh) { // set mesh m_pBlockMesh->Release(); m_pBlockMesh = pStaticBlockMesh; // update render proxy m_pRenderProxy->SetBlockMesh(pStaticBlockMesh); // fix up bounds UpdateBounds(); } else { // no change needed pStaticBlockMesh->Release(); } } } void EditorVisualComponentInstance_BlockMesh::OnSelectionStateChange(bool selected) { uint32 tintColor = m_pDefinition->GetTintColor(); uint32 selectedTintColor = m_pDefinition->GetSelectedTintColor(); if (tintColor != selectedTintColor) { uint32 currentColor = selected ? selectedTintColor : tintColor; if (currentColor != 0xFFFFFFFF) m_pRenderProxy->SetTintColor(true, selectedTintColor); else m_pRenderProxy->SetTintColor(false); } if (m_pDefinition->GetOnlyShowWhenSelected()) m_pRenderProxy->SetVisibility(selected ? m_Visible : false); } void EditorVisualComponentInstance_BlockMesh::UpdateTransform() { Transform offsetTransform(m_pDefinition->GetPositionOffset(), m_pDefinition->GetRotationOffset(), m_pDefinition->GetScaleOffset()); Transform localTransform(m_Position, m_Rotation, m_Scale); Transform fullTransform(Transform::ConcatenateTransforms(offsetTransform, localTransform)); // effective order: LS * LR * LT * ER * ET m_CachedTransform = fullTransform; m_pRenderProxy->SetTransform(m_CachedTransform); // fix up bounds too UpdateBounds(); } void EditorVisualComponentInstance_BlockMesh::UpdateBounds() { m_visualBounds = m_CachedTransform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()); }<file_sep>/Engine/Source/MathLib/Frustum.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/Matrixf.h" #include "MathLib/Plane.h" #include "MathLib/AABox.h" #include "MathLib/Sphere.h" enum FRUSTUM_PLANE { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_COUNT, }; class Frustum { public: enum IntersectionType { INTERSECTION_TYPE_OUTSIDE, // completely outside the frustum INTERSECTION_TYPE_INTERSECTS, // one of the planes intersects with the object INTERSECTION_TYPE_INSIDE, // completely inside the frustum }; public: Frustum() {} Frustum(const Frustum &frCopy); // Builds a frustum from a concatenated view/projection matrix. void SetFromMatrix(const Matrix4x4f &matViewProj); // Builds a frustum from the specified AABox. void SetFromAABox(const AABox &aabBox); // Accesses the planes of the frustum. const Plane &GetPlane(FRUSTUM_PLANE PlaneIndex) const { return m_planes[PlaneIndex]; } // Tests if the object intersects the frustum, or is contained in the frustum. bool AABoxIntersection(const AABox &aabBounds) const; bool SphereIntersection(const Sphere &sphere) const; // Gets the intersection type for the object IntersectionType AABoxIntersectionType(const AABox &box) const; IntersectionType SphereIntersectionType(const Sphere &sphere) const; // Gets the corner vertices. void GetCornerVertices(Vector3f pVertices[8]) const; void GetCornerVertices(SIMDVector3f pVertices[8]) const; // Gets an AABox containing the frustum. AABox GetBoundingAABox() const; // Gets a sphere containing the frustum. Sphere GetBoundingSphere() const; // Operators bool operator==(const Frustum &Comp) const; bool operator!=(const Frustum &Comp) const; Frustum &operator=(const Frustum &Copy); private: // clipping planes Plane m_planes[FRUSTUM_PLANE_COUNT]; }; <file_sep>/Engine/Source/Engine/Physics/SphereCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" class btSphereShape; namespace Physics { class SphereCollisionShape : public CollisionShape { public: SphereCollisionShape(); SphereCollisionShape(const float3 &center, const float radius); ~SphereCollisionShape(); const float3 &GetCenter() const { return m_center; } const float GetRadius() const { return m_radius; } // Virtual methods virtual const COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: AABox m_bounds; float3 m_center; float m_radius; btSphereShape *m_pBulletShape; }; } // namespace Physics <file_sep>/Engine/Source/D3D12Renderer/D3D12CommandQueue.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12Helpers.h" #include "D3D12Renderer/D3D12CVars.h" #include "Engine/EngineCVars.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(D3D12GPUDevice); D3D12CommandQueue::D3D12CommandQueue(D3D12GPUDevice *pGPUDevice, ID3D12Device *pD3DDevice, D3D12_COMMAND_LIST_TYPE type, uint32 linearBufferHeapSize, uint32 linearViewHeapSize, uint32 linearSamplerHeapSize) : m_pGPUDevice(pGPUDevice) , m_pD3DDevice(pD3DDevice) , m_type(type) , m_linearBufferHeapSize(linearBufferHeapSize) , m_linearViewHeapSize(linearViewHeapSize) , m_linearSamplerHeapSize(linearSamplerHeapSize) , m_maxCommandAllocatorPoolSize(16) , m_maxLinearBufferHeapPoolSize(256) , m_maxLinearViewHeapPoolSize(1024) , m_maxLinearSamplerHeapPoolSize(1024) , m_pD3DFence(nullptr) , m_fenceEvent(NULL) , m_nextFenceValue(1) , m_lastCompletedFenceValue(0) , m_outstandingCommandAllocators(0) , m_outstandingLinearBufferHeaps(0) , m_outstandingLinearViewHeaps(0) , m_outstandingLinearSamplerHeaps(0) { } D3D12CommandQueue::~D3D12CommandQueue() { // sync, then destroy everything if (m_pD3DCommandQueue != nullptr) { uint64 fenceValue = CreateSynchronizationPoint(); WaitForFence(fenceValue); } // shouldn't have anything outstanding Assert(m_outstandingCommandLists == 0); Assert(m_outstandingCommandAllocators == 0); Assert(m_outstandingLinearBufferHeaps == 0); Assert(m_outstandingLinearViewHeaps == 0); Assert(m_outstandingLinearSamplerHeaps == 0); // nuke command lists while (!m_commandListPool.IsEmpty()) m_commandListPool.PopBack()->Release(); // nuke command allocators while (!m_commandAllocatorPool.IsEmpty()) { CommandAllocatorEntry entry; m_commandAllocatorPool.PopBack(&entry); entry.Key->Release(); } // nuke linear buffer heaps while (!m_linearBufferHeapPool.IsEmpty()) { LinearBufferHeapEntry entry; m_linearBufferHeapPool.PopBack(&entry); delete entry.Key; } // nuke linear view heaps while (!m_linearViewHeapPool.IsEmpty()) { LinearResourceDescriptorHeapEntry entry; m_linearViewHeapPool.PopBack(&entry); delete entry.Key; } // nuke linear view heaps while (!m_linearSamplerHeapPool.IsEmpty()) { LinearSamplerDescriptorHeapEntry entry; m_linearSamplerHeapPool.PopBack(&entry); delete entry.Key; } // nuke descriptors for (uint32 i = 0; i < m_pendingDeletionDescriptors.GetSize(); i++) m_pGPUDevice->GetCPUDescriptorHeap(m_pendingDeletionDescriptors[i].Handle.Type)->Free(m_pendingDeletionDescriptors[i].Handle); // nuke resources for (uint32 i = 0; i < m_pendingDeletionResources.GetSize(); i++) m_pendingDeletionResources[i].pResource->Release(); if (m_fenceEvent != NULL) CloseHandle(m_fenceEvent); SAFE_RELEASE(m_pD3DFence); SAFE_RELEASE(m_pD3DCommandQueue); } bool D3D12CommandQueue::Initialize() { HRESULT hResult; // allocate command queue D3D12_COMMAND_QUEUE_DESC queueDesc = { m_type, D3D12_COMMAND_QUEUE_PRIORITY_NORMAL, D3D12_COMMAND_QUEUE_FLAG_NONE, 1 }; hResult = m_pD3DDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_pD3DCommandQueue)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommandQueue failed with hResult %08X", hResult); return false; } // allocate fence hResult = m_pD3DDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_pD3DFence)); if (FAILED(hResult)) { Log_ErrorPrintf("ID3D12Device::CreateFence failed with hResult %08X", hResult); return false; } // allocate reached event m_fenceEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); if (m_fenceEvent == NULL) { Log_ErrorPrintf("CreateEvent failed (%u).", GetLastError()); return false; } return true; } uint64 D3D12CommandQueue::CreateSynchronizationPoint() { uint64 returnValue = m_nextFenceValue++; HRESULT hResult = m_pD3DCommandQueue->Signal(m_pD3DFence, returnValue); if (FAILED(hResult)) Log_WarningPrintf("ID3D12CommandQueue::Signal failed with hResult %08X", hResult); return returnValue; } void D3D12CommandQueue::ExecuteCommandList(ID3D12CommandList *pCommandList) { m_pD3DCommandQueue->ExecuteCommandLists(1, &pCommandList); } ID3D12GraphicsCommandList *D3D12CommandQueue::RequestCommandList() { RecursiveMutexLock lock(m_allocatorLock); // free one if (!m_commandListPool.IsEmpty()) { m_outstandingCommandLists++; return m_commandListPool.PopFront(); } // create one, we need a temporary allocator ID3D12CommandAllocator *pTemporaryAllocator = RequestCommandAllocator(); ID3D12GraphicsCommandList *pCommandList; HRESULT hResult = m_pD3DDevice->CreateCommandList(1, m_type, pTemporaryAllocator, nullptr, IID_PPV_ARGS(&pCommandList)); if (FAILED(hResult)) Panic("Failed to create command list."); // close the command list hResult = pCommandList->Close(); if (FAILED(hResult)) Log_WarningPrintf("Closing new command list failed with HRESULT %08X", hResult); // and release allocator back ReleaseCommandAllocator(pTemporaryAllocator, m_lastCompletedFenceValue); // return new list m_outstandingCommandLists++; return pCommandList; } ID3D12GraphicsCommandList *D3D12CommandQueue::RequestAndOpenCommandList(ID3D12CommandAllocator *pCommandAllocator) { RecursiveMutexLock lock(m_allocatorLock); // free one if (!m_commandListPool.IsEmpty()) { ID3D12GraphicsCommandList *pCommandList = m_commandListPool.PopFront(); HRESULT hResult = pCommandList->Reset(pCommandAllocator, nullptr); if (FAILED(hResult)) Panic("Failed to reset pooled command list."); m_outstandingCommandLists++; return pCommandList; } // create a new list on the specified allocator ID3D12GraphicsCommandList *pCommandList; HRESULT hResult = m_pD3DDevice->CreateCommandList(1, m_type, pCommandAllocator, nullptr, IID_PPV_ARGS(&pCommandList)); if (FAILED(hResult)) Panic("Failed to create command list."); // return new list m_outstandingCommandLists++; return pCommandList; } void D3D12CommandQueue::ReleaseCommandList(ID3D12GraphicsCommandList *pCommandList) { DebugAssert(m_outstandingCommandLists > 0); m_commandListPool.Add(pCommandList); m_outstandingCommandLists--; } void D3D12CommandQueue::ReleaseFailedCommandList(ID3D12GraphicsCommandList *pCommandList) { // don't put it back in the pool DebugAssert(m_outstandingCommandLists > 0); m_outstandingCommandLists--; pCommandList->Release(); } template<class T> T *D3D12CommandQueue::SearchPool(MemArray<KeyValuePair<T *, uint64>> &pool) { if (pool.IsEmpty()) return nullptr; if (m_lastCompletedFenceValue < pool[0].Value) UpdateLastCompletedFenceValue(); if (m_lastCompletedFenceValue < pool[0].Value) return nullptr; T *pReturn = pool[0].Key; pool.RemoveFront(); return pReturn; } template<class T> T *D3D12CommandQueue::SearchPoolAndWait(MemArray<KeyValuePair<T *, uint64>> &pool) { DebugAssert(!pool.IsEmpty()); WaitForFence(pool[0].Value); T *pReturn = pool[0].Key; pool.RemoveFront(); return pReturn; } template<class T> void D3D12CommandQueue::InsertIntoPool(MemArray<KeyValuePair<T *, uint64>> &pool, T *pItem, uint64 fenceValue) { uint32 pos = 0; for (; pos < pool.GetSize(); pos++) { if (pool[pos].Value > fenceValue) break; } pool.Insert(KeyValuePair<T *, uint64>(pItem, fenceValue), pos); } ID3D12CommandAllocator *D3D12CommandQueue::RequestCommandAllocator() { ID3D12CommandAllocator *pReturnAllocator; RecursiveMutexLock lock(m_allocatorLock); // search the pool first pReturnAllocator = SearchPool<ID3D12CommandAllocator>(m_commandAllocatorPool); if (pReturnAllocator != nullptr) { // reset the allocator, ready for use HRESULT hResult = pReturnAllocator->Reset(); if (FAILED(hResult)) Panic("ID3D12CommandAllocator::Reset failed."); // have one ready to go, so release it m_outstandingCommandAllocators++; return pReturnAllocator; } // can we allocate a new one? if ((m_outstandingCommandAllocators + m_commandAllocatorPool.GetSize()) < m_maxCommandAllocatorPoolSize) { Log_PerfPrintf("Allocating new command allocator."); // create allocator HRESULT hResult = m_pD3DDevice->CreateCommandAllocator(m_type, IID_PPV_ARGS(&pReturnAllocator)); if (SUCCEEDED(hResult)) { // return the new allocator m_outstandingCommandAllocators++; return pReturnAllocator; } else { Log_ErrorPrintf("ID3D12Device::CreateCommandAllocator failed with hResult %08X", hResult); return false; } } // wait for one to free up (assuming pool is in ascending order, which it should be) pReturnAllocator = SearchPoolAndWait<ID3D12CommandAllocator>(m_commandAllocatorPool); if (pReturnAllocator != nullptr) { // reset the allocator, ready for use HRESULT hResult = pReturnAllocator->Reset(); if (FAILED(hResult)) Panic("ID3D12CommandAllocator::Reset failed."); // have one ready to go, so release it m_outstandingCommandAllocators++; return pReturnAllocator; } // shouldn't hit here ever. [unless pool allocation failed and had never succeeded] UnreachableCode(); return nullptr; } void D3D12CommandQueue::ReleaseCommandAllocator(ID3D12CommandAllocator *pAllocator, uint64 availableFenceValue) { RecursiveMutexLock lock(m_allocatorLock); DebugAssert(m_outstandingCommandAllocators > 0); InsertIntoPool<ID3D12CommandAllocator>(m_commandAllocatorPool, pAllocator, availableFenceValue); m_outstandingCommandAllocators--; } D3D12LinearBufferHeap *D3D12CommandQueue::RequestLinearBufferHeap() { D3D12LinearBufferHeap *pReturnHeap; RecursiveMutexLock lock(m_allocatorLock); // search the pool first pReturnHeap = SearchPool<D3D12LinearBufferHeap>(m_linearBufferHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(true); m_outstandingLinearBufferHeaps++; return pReturnHeap; } // can we allocate a new one? if ((m_outstandingLinearBufferHeaps + m_linearBufferHeapPool.GetSize()) < m_maxLinearBufferHeapPoolSize) { Log_PerfPrintf("Allocating new linear buffer heap."); pReturnHeap = D3D12LinearBufferHeap::Create(m_pD3DDevice, m_linearBufferHeapSize); if (pReturnHeap != nullptr) { m_outstandingLinearBufferHeaps++; return pReturnHeap; } } // wait for one to free up (assuming pool is in ascending order, which it should be) pReturnHeap = SearchPoolAndWait<D3D12LinearBufferHeap>(m_linearBufferHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(true); m_outstandingLinearBufferHeaps++; return pReturnHeap; } // shouldn't hit here ever. [unless pool allocation failed and had never succeeded] UnreachableCode(); return nullptr; } void D3D12CommandQueue::ReleaseLinearBufferHeap(D3D12LinearBufferHeap *pHeap, uint64 availableFenceValue) { RecursiveMutexLock lock(m_allocatorLock); DebugAssert(m_outstandingLinearBufferHeaps > 0); InsertIntoPool<D3D12LinearBufferHeap>(m_linearBufferHeapPool, pHeap, availableFenceValue); m_outstandingLinearBufferHeaps--; } D3D12LinearDescriptorHeap *D3D12CommandQueue::RequestLinearViewHeap() { D3D12LinearDescriptorHeap *pReturnHeap; RecursiveMutexLock lock(m_allocatorLock); // search the pool first pReturnHeap = SearchPool<D3D12LinearDescriptorHeap>(m_linearViewHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(); m_outstandingLinearViewHeaps++; return pReturnHeap; } // can we allocate a new one? if ((m_outstandingLinearViewHeaps + m_linearViewHeapPool.GetSize()) < m_maxLinearViewHeapPoolSize) { Log_PerfPrintf("Allocating new linear view heap."); pReturnHeap = D3D12LinearDescriptorHeap::Create(m_pD3DDevice, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, m_linearViewHeapSize); if (pReturnHeap != nullptr) { m_outstandingLinearViewHeaps++; return pReturnHeap; } } // wait for one to free up (assuming pool is in ascending order, which it should be) pReturnHeap = SearchPoolAndWait<D3D12LinearDescriptorHeap>(m_linearViewHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(); m_outstandingLinearViewHeaps++; return pReturnHeap; } // shouldn't hit here ever. [unless pool allocation failed and had never succeeded] UnreachableCode(); return nullptr; } void D3D12CommandQueue::ReleaseLinearViewHeap(D3D12LinearDescriptorHeap *pHeap, uint64 availableFenceValue) { RecursiveMutexLock lock(m_allocatorLock); DebugAssert(m_outstandingLinearViewHeaps > 0); InsertIntoPool<D3D12LinearDescriptorHeap>(m_linearViewHeapPool, pHeap, availableFenceValue); m_outstandingLinearViewHeaps--; } D3D12LinearDescriptorHeap *D3D12CommandQueue::RequestLinearSamplerHeap() { D3D12LinearDescriptorHeap *pReturnHeap; RecursiveMutexLock lock(m_allocatorLock); // search the pool first pReturnHeap = SearchPool<D3D12LinearDescriptorHeap>(m_linearSamplerHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(); m_outstandingLinearSamplerHeaps++; return pReturnHeap; } // can we allocate a new one? if ((m_outstandingLinearSamplerHeaps + m_linearSamplerHeapPool.GetSize()) < m_maxLinearSamplerHeapPoolSize) { Log_PerfPrintf("Allocating new linear sampler heap."); pReturnHeap = D3D12LinearDescriptorHeap::Create(m_pD3DDevice, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, m_linearViewHeapSize); if (pReturnHeap != nullptr) { m_outstandingLinearSamplerHeaps++; return pReturnHeap; } } // wait for one to free up (assuming pool is in ascending order, which it should be) pReturnHeap = SearchPoolAndWait<D3D12LinearDescriptorHeap>(m_linearSamplerHeapPool); if (pReturnHeap != nullptr) { // have one ready to go, so release it pReturnHeap->Reset(); m_outstandingLinearSamplerHeaps++; return pReturnHeap; } // shouldn't hit here ever. [unless pool allocation failed and had never succeeded] UnreachableCode(); return nullptr; } void D3D12CommandQueue::ReleaseLinearSamplerHeap(D3D12LinearDescriptorHeap *pHeap, uint64 availableFenceValue) { RecursiveMutexLock lock(m_allocatorLock); DebugAssert(m_outstandingLinearSamplerHeaps > 0); InsertIntoPool<D3D12LinearDescriptorHeap>(m_linearSamplerHeapPool, pHeap, availableFenceValue); m_outstandingLinearSamplerHeaps--; } void D3D12CommandQueue::WaitForFence(uint64 fence) { UpdateLastCompletedFenceValue(); if (m_lastCompletedFenceValue < fence) { #if defined(Y_BUILD_CONFIG_DEBUG) && 0 Timer waitTimer; m_pD3DFence->SetEventOnCompletion(fence, m_fenceEvent); WaitForSingleObject(m_fenceEvent, INFINITE); Log_ProfilePrintf("GPU took %.4f ms to catch up to fence", waitTimer.GetTimeMilliseconds()); #else m_pD3DFence->SetEventOnCompletion(fence, m_fenceEvent); WaitForSingleObject(m_fenceEvent, INFINITE); #endif UpdateLastCompletedFenceValue(); } } void D3D12CommandQueue::UpdateLastCompletedFenceValue() { m_lastCompletedFenceValue = m_pD3DFence->GetCompletedValue(); } void D3D12CommandQueue::ReleaseStaleResources() { // clean up as much as we can UpdateLastCompletedFenceValue(); DeletePendingResources(m_lastCompletedFenceValue); } void D3D12CommandQueue::ScheduleResourceForDeletion(ID3D12Pageable *pResource) { ScheduleResourceForDeletion(pResource, m_nextFenceValue); } void D3D12CommandQueue::ScheduleResourceForDeletion(ID3D12Pageable *pResource, uint64 fenceValue /* = GetCurrentCleanupFenceValue() */) { PendingDeletionResource pdr; pdr.pResource = pResource; pdr.FenceValue = fenceValue; m_pendingResourceLock.Lock(); m_pendingDeletionResources.Add(pdr); m_pendingResourceLock.Unlock(); } void D3D12CommandQueue::ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle) { ScheduleDescriptorForDeletion(handle, m_nextFenceValue); } void D3D12CommandQueue::ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle, uint64 fenceValue /* = GetCurrentCleanupFenceValue() */) { PendingDeletionDescriptor pdr; pdr.Handle = handle; pdr.FenceValue = fenceValue; m_pendingResourceLock.Lock(); m_pendingDeletionDescriptors.Add(pdr); m_pendingResourceLock.Unlock(); } //thread_local D3D12_RESOURCE_DESC rsz; void D3D12CommandQueue::DeletePendingResources(uint64 fenceValue) { m_pendingResourceLock.Lock(); for (uint32 i = 0; i < m_pendingDeletionResources.GetSize(); ) { if (m_pendingDeletionResources[i].FenceValue > fenceValue) { i++; continue; } ID3D12Pageable *pResource = m_pendingDeletionResources[i].pResource; // ID3D12Resource *pr; // D3D12_RESOURCE_DESC desc; // if (pResource->QueryInterface(IID_PPV_ARGS(&pr)) == S_OK) // { // desc = pr->GetDesc(); // rsz = desc; // pr->Release(); // } SAFE_RELEASE_LAST(pResource); m_pendingDeletionResources.FastRemove(i); } for (uint32 i = 0; i < m_pendingDeletionDescriptors.GetSize(); ) { PendingDeletionDescriptor &desc = m_pendingDeletionDescriptors[i]; if (desc.FenceValue > fenceValue) { i++; continue; } DebugAssert(desc.Handle.Type < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES); m_pGPUDevice->GetCPUDescriptorHeap(desc.Handle.Type)->Free(desc.Handle); m_pendingDeletionDescriptors.FastRemove(i); } m_pendingResourceLock.Unlock(); } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUShaderProgram.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUShaderProgram.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" #include "OpenGLRenderer/OpenGLShaderCacheEntry.h" Log_SetChannel(OpenGLES2RenderBackend); OpenGLES2GPUShaderProgram::OpenGLES2GPUShaderProgram() : m_pBoundContext(nullptr) { Y_memzero(m_iGLShaderId, sizeof(m_iGLShaderId)); m_iGLProgramId = 0; } OpenGLES2GPUShaderProgram::~OpenGLES2GPUShaderProgram() { DebugAssert(m_pBoundContext == nullptr); if (m_iGLProgramId > 0) glDeleteProgram(m_iGLProgramId); for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] > 0) glDeleteShader(m_iGLShaderId[i]); } } void OpenGLES2GPUShaderProgram::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { // fixme if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void OpenGLES2GPUShaderProgram::SetDebugName(const char *name) { // set shaders for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] != 0) OpenGLES2Helpers::SetObjectDebugName(GL_SHADER, m_iGLShaderId[i], name); } // set program OpenGLES2Helpers::SetObjectDebugName(GL_PROGRAM, m_iGLProgramId, name); } bool OpenGLES2GPUShaderProgram::LoadProgram(OpenGLES2GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { // binary reader BinaryReader binaryReader(pByteCodeStream); // read/validate header OpenGLShaderCacheEntryHeader header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Signature != OPENGL_SHADER_CACHE_ENTRY_HEADER || header.Platform != RENDERER_PLATFORM_OPENGLES2 || header.UniformBlockCount > 0 || header.FragmentDataCount > 0 || header.StageSize[SHADER_PROGRAM_STAGE_HULL_SHADER] > 0 || header.StageSize[SHADER_PROGRAM_STAGE_DOMAIN_SHADER] > 0 || header.StageSize[SHADER_PROGRAM_STAGE_GEOMETRY_SHADER] > 0 || header.StageSize[SHADER_PROGRAM_STAGE_COMPUTE_SHADER] > 0) { Log_ErrorPrintf("OpenGLES2GPUShaderProgram::Create: Shader cache entry header corrupted."); return false; } // begin checked section GL_CHECKED_SECTION_BEGIN(); // time stuff Timer operationTimer; // generate shader ids for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if ((i != SHADER_PROGRAM_STAGE_VERTEX_SHADER && i != SHADER_PROGRAM_STAGE_PIXEL_SHADER) || header.StageSize[i] == 0) continue; // read into memory GLint stageSourceLength = (GLint)header.StageSize[i]; GLchar *pStageSource = new GLchar[stageSourceLength]; if (!binaryReader.SafeReadBytes(pStageSource, stageSourceLength)) { delete[] pStageSource; return false; } // lookup table of i -> GL shader stage static const GLenum shaderStageMapping[SHADER_PROGRAM_STAGE_COUNT] = { GL_VERTEX_SHADER, 0, 0, 0, GL_FRAGMENT_SHADER, 0 }; // create the shader object if ((m_iGLShaderId[i] = glCreateShader(shaderStageMapping[i])) == 0) { GL_PRINT_ERROR("OpenGLES2GPUShaderProgram::Create: glCreateShader failed: "); return false; } // pass it the shader source, and compile it glShaderSource(m_iGLShaderId[i], 1, (const GLchar **)&pStageSource, &stageSourceLength); glCompileShader(m_iGLShaderId[i]); delete[] pStageSource; GLint shaderStatus = GL_FALSE; GLint shaderInfoLogLength = 0; glGetShaderiv(m_iGLShaderId[i], GL_COMPILE_STATUS, &shaderStatus); glGetShaderiv(m_iGLShaderId[i], GL_INFO_LOG_LENGTH, &shaderInfoLogLength); if (shaderStatus == GL_FALSE) { Log_ErrorPrintf("OpenGLES2GPUShaderProgram::Create: %s failed compilation:\n", NameTable_GetNameString(NameTables::ShaderProgramStage, i)); if (shaderInfoLogLength > 1) { GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetShaderInfoLog(m_iGLShaderId[i], shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_ErrorPrint(shaderInfoLog); delete[] shaderInfoLog; } return false; } if (shaderInfoLogLength > 1) { Log_WarningPrintf("OpenGLES2GPUShaderProgram::Create: %s compiled, with warnings:\n", NameTable_GetNameString(NameTables::ShaderProgramStage, i)); GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetShaderInfoLog(m_iGLShaderId[i], shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_WarningPrint(shaderInfoLog); delete[] shaderInfoLog; } Log_PerfPrintf("OpenGLES2GPUShaderProgram::Create: %s took %.4f msec to compile.", NameTable_GetNameString(NameTables::ShaderProgramStage, i), operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); } // generate program id if ((m_iGLProgramId = glCreateProgram()) == 0) { GL_PRINT_ERROR("GLShaderProgram::Create: glCreateProgram failed: "); return false; } // attach shaders to program for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] != 0) glAttachShader(m_iGLProgramId, m_iGLShaderId[i]); } // check for any errors if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("GLShaderProgram::Create: One or more glAttachShader calls failed: "); return false; } // log Log_PerfPrintf("OpenGLES2GPUShaderProgram::Create: Took %.4f msec to attach.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); // bind attributes if (header.VertexAttributeCount > 0) { for (uint32 attributeIndex = 0; attributeIndex < header.VertexAttributeCount; attributeIndex++) { OpenGLShaderCacheEntryVertexAttribute attribute; SmallString attributeVariableName; if (!binaryReader.SafeReadBytes(&attribute, sizeof(attribute)) || !binaryReader.SafeReadFixedString(attribute.NameLength, &attributeVariableName)) return false; // find the corresponding vertex element in spec uint32 ilIndex; for (ilIndex = 0; ilIndex < nVertexElements; ilIndex++) { if (pVertexElements[ilIndex].Semantic == (GPU_VERTEX_ELEMENT_SEMANTIC)attribute.SemanticName && pVertexElements[ilIndex].SemanticIndex == attribute.SemanticIndex) { // bind to the corresponding attribute location glBindAttribLocation(m_iGLProgramId, ilIndex, attributeVariableName); break; } } // found? if (ilIndex == nVertexElements) { Log_ErrorPrintf("OpenGLES2GPUShaderProgram::Create: Failed to find binding for required shader input attribute '%s'", attributeVariableName.GetCharArray()); return false; } } // check for errors if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUShaderProgram::Create: One or more glBindAttribLocation calls failed: "); return false; } // to avoid bouncing around vertex formats too often we're going to just store the whole thing, this could be moved to a cache m_vertexAttributes.AddRange(pVertexElements, nVertexElements); } // pull in parameters if (header.ParameterCount > 0) { m_parameters.Resize(header.ParameterCount); for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { OpenGLShaderCacheEntryParameter inParameter; SmallString parameterName; if (!binaryReader.SafeReadBytes(&inParameter, sizeof(inParameter)) || !binaryReader.SafeReadFixedString(inParameter.NameLength, &parameterName)) return false; // create parameter information ShaderParameter *outParameter = &m_parameters[parameterIndex]; outParameter->Name = parameterName; outParameter->Type = (SHADER_PARAMETER_TYPE)inParameter.Type; outParameter->ArraySize = inParameter.ArraySize; outParameter->ArrayStride = inParameter.ArrayStride; outParameter->BindTarget = inParameter.BindTarget; outParameter->BindLocation = -1; outParameter->BindSlot = -1; outParameter->LibraryID = OpenGLES2ConstantLibrary::ConstantIndexInvalid; outParameter->LibraryValueChanged = false; } } // log Log_PerfPrintf("OpenGLES2GPUShaderProgram::Create: Took %.4f msec to bind.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); // link program { glLinkProgram(m_iGLProgramId); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUShaderProgram::Create: glLinkProgram failed: "); return false; } // check link status GLint shaderStatus = GL_FALSE; GLint shaderInfoLogLength = 0; glGetProgramiv(m_iGLProgramId, GL_LINK_STATUS, &shaderStatus); glGetProgramiv(m_iGLProgramId, GL_INFO_LOG_LENGTH, &shaderInfoLogLength); if (shaderStatus == GL_FALSE) { Log_ErrorPrintf("OpenGLES2GPUShaderProgram::Create: Program failed to link:\n"); if (shaderInfoLogLength > 1) { GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetProgramInfoLog(m_iGLProgramId, shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_ErrorPrint(shaderInfoLog); delete[] shaderInfoLog; } return false; } if (shaderInfoLogLength > 1) { Log_WarningPrintf("OpenGLES2GPUShaderProgram::Create: Program linked, with warnings:\n"); GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetProgramInfoLog(m_iGLProgramId, shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_WarningPrint(shaderInfoLog); delete[] shaderInfoLog; } // logging Log_PerfPrintf("OpenGLES2GPUShaderProgram::Create: Took %.4f msec to link.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); } #ifdef Y_BUILD_CONFIG_DEBUG if (header.DebugNameLength > 0) { SmallString debugName; if (binaryReader.SafeReadFixedString(header.DebugNameLength, &debugName)) SetDebugName(debugName); } #endif #if 1 // todo: lazy bind // store the current program for this thread's context GLint currentProgramId = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &currentProgramId); // bind this program glUseProgram(m_iGLProgramId); // slot allocators uint32 textureSlotAllocator = 0; // get parameter locations for (uint32 i = 0; i < m_parameters.GetSize(); i++) { ShaderParameter *parameter = &m_parameters[i]; switch (parameter->BindTarget) { case OPENGL_SHADER_BIND_TARGET_UNIFORM: { // Find the uniform location for this parameter GLint uniformLocation = glGetUniformLocation(m_iGLProgramId, parameter->Name); if (uniformLocation < 0) { // optimized out continue; } // Store the location parameter->BindLocation = uniformLocation; // we have to check the library for a mapping of a constant buffer entry to this parameter. parameter->LibraryID = pDevice->GetConstantLibrary()->LookupConstantID(parameter->Name); parameter->LibraryValueChanged = (parameter->LibraryID != OpenGLES2ConstantLibrary::ConstantIndexInvalid); } break; case OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT: { // Find the uniform location for this parameter GLint uniformLocation = glGetUniformLocation(m_iGLProgramId, parameter->Name); if (uniformLocation < 0) { // optimized out continue; } // Store the location, and allocate a slot parameter->BindLocation = uniformLocation; parameter->BindSlot = textureSlotAllocator++; // and pass this to the shader glUniform1i(parameter->BindLocation, parameter->BindSlot); } break; } } // rebind old program glUseProgram(currentProgramId); Log_PerfPrintf("OpenGLES2GPUShaderProgram::Create: Took %.4f msec to do parameter linking.", operationTimer.GetTimeMilliseconds()); #endif // all ok return true; } void OpenGLES2GPUShaderProgram::Bind(OpenGLES2GPUContext *pContext) { DebugAssert(m_pBoundContext == NULL); // bind program glUseProgram(m_iGLProgramId); m_pBoundContext = pContext; // bind attributes pContext->SetShaderVertexAttributes(m_vertexAttributes.GetBasePointer(), m_vertexAttributes.GetSize()); // bind params for (ShaderParameter &parameter : m_parameters) { // if from constant library, reprogram if (parameter.LibraryID != OpenGLES2ConstantLibrary::ConstantIndexInvalid) parameter.LibraryValueChanged = true; } } void OpenGLES2GPUShaderProgram::Switch(OpenGLES2GPUContext *pContext, OpenGLES2GPUShaderProgram *pCurrentProgram) { // bind program glUseProgram(m_iGLProgramId); // swap pointers pCurrentProgram->m_pBoundContext = nullptr; m_pBoundContext = pContext; // bind attributes pContext->SetShaderVertexAttributes(m_vertexAttributes.GetBasePointer(), m_vertexAttributes.GetSize()); // bind params for (ShaderParameter &parameter : m_parameters) { // if from constant library, reprogram if (parameter.LibraryID != OpenGLES2ConstantLibrary::ConstantIndexInvalid) parameter.LibraryValueChanged = true; } } void OpenGLES2GPUShaderProgram::OnLibraryConstantChanged(OpenGLES2ConstantLibrary::ConstantID constantID) { for (ShaderParameter &parameter : m_parameters) { if (parameter.LibraryID == constantID) { parameter.LibraryValueChanged = true; break; } } } void OpenGLES2GPUShaderProgram::CommitLibraryConstants(OpenGLES2GPUContext *pContext) { for (ShaderParameter &parameter : m_parameters) { if (parameter.LibraryValueChanged) { // pull from constant library pContext->GetConstantLibrary()->UpdateProgramConstant(pContext->GetConstantLibraryBuffer(), parameter.LibraryID, parameter.BindLocation); parameter.LibraryValueChanged = false; } } } void OpenGLES2GPUShaderProgram::Unbind(OpenGLES2GPUContext *pContext) { DebugAssert(m_pBoundContext == pContext); // unbind program glUseProgram(0); m_pBoundContext = nullptr; } void OpenGLES2GPUShaderProgram::InternalSetParameterValue(OpenGLES2GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == valueType); DebugAssert(parameterInfo->BindTarget == OPENGL_SHADER_BIND_TARGET_UNIFORM); DebugAssert(pContext == m_pBoundContext); // Library member? Shouldn't be set via this method, but just in case. DebugAssert(parameterInfo->LibraryID == OpenGLES2ConstantLibrary::ConstantIndexInvalid); // GL uniform if (parameterInfo->BindLocation >= 0) { // Send to GL OpenGLES2Helpers::GLUniformWrapper(parameterInfo->Type, parameterInfo->BindLocation, 1, pValue); } } void OpenGLES2GPUShaderProgram::InternalSetParameterValueArray(OpenGLES2GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == valueType); DebugAssert(parameterInfo->BindTarget == OPENGL_SHADER_BIND_TARGET_UNIFORM); DebugAssert(pContext == m_pBoundContext); // Library member? Shouldn't be set via this method, but just in case. DebugAssert(parameterInfo->LibraryID == OpenGLES2ConstantLibrary::ConstantIndexInvalid); // GL uniform? if (parameterInfo->BindLocation >= 0) { // Send to GL OpenGLES2Helpers::GLUniformWrapper(parameterInfo->Type, parameterInfo->BindLocation + firstElement, numElements, pValue); } } void OpenGLES2GPUShaderProgram::InternalSetParameterTexture(OpenGLES2GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource) { const ShaderParameter *parameter = &m_parameters[parameterIndex]; DebugAssert(parameter->BindTarget == OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT); if (parameter->BindSlot < 0) return; pContext->SetShaderTextureUnit(parameter->BindSlot, static_cast<GPUTexture *>(pResource)); } uint32 OpenGLES2GPUShaderProgram::GetParameterCount() const { return m_parameters.GetSize(); } void OpenGLES2GPUShaderProgram::GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) { const ShaderParameter *parameter = &m_parameters[index]; *name = parameter->Name; *type = parameter->Type; *arraySize = parameter->ArraySize; } GPUShaderProgram *OpenGLES2GPUDevice::CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { OpenGLES2GPUShaderProgram *pProgram = new OpenGLES2GPUShaderProgram(); if (!pProgram->LoadProgram(this, pVertexElements, nVertexElements, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } GPUShaderProgram *OpenGLES2GPUDevice::CreateComputeProgram(ByteStream *pByteCodeStream) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateComputeProgram: Unsupported on GLES 2.0"); return nullptr; } <file_sep>/Engine/Source/Engine/SkeletalAnimationPlayer.h #pragma once #include "Engine/Common.h" #include "Engine/Skeleton.h" #include "Engine/SkeletalMesh.h" #include "Engine/SkeletalAnimation.h" class SkeletalMeshRenderProxy; class SkeletalAnimationPlayer { public: enum WrapMode { WrapMode_None, // resets back to base frame at completion WrapMode_Once, // plays animation once, then resets back to first frame WrapMode_Hold, // plays animation once, and keeps state at last frame WrapMode_PingPong, // plays animation forward then backwards, one repeat is one forward or backwards cycle and hold there WrapMode_Count, }; class MeshState { public: MeshState(); MeshState(uint32 boneCount); void SetBoneCount(uint32 boneCount); const Transform &GetBoneTransform(uint32 boneIndex) const { return m_transforms[boneIndex]; } void SetBoneTransform(uint32 boneIndex, const Transform &transform) { m_transforms[boneIndex] = transform; } const Transform *GetBoneTransformArray() const { return m_transforms.GetBasePointer(); } const uint32 GetBoneTransformArraySize() const { return m_transforms.GetSize(); } MeshState *Copy() const; void CopyFrom(const MeshState *state); private: MemArray<Transform> m_transforms; }; class Channel { friend SkeletalAnimationPlayer; public: const uint32 GetIndex() const { return m_index; } const float GetWeight() const { return m_weight; } const WrapMode GetWrapMode() const { return m_wrapMode; } const float GetTime() const { return m_time; } const bool IsPlaying() const { return m_playing; } const SkeletalAnimation *GetAnimation() const { return m_pAnimation; } const float GetPlaybackSpeed() const { return Math::Abs(m_playbackSpeed); } const int32 GetLoopCount() const { return m_loopCount; } // change weight void SetWeight(float weight) { m_weight = weight; } // change repeat mode void SetWrapMode(WrapMode mode) { m_wrapMode = mode; } // change playback speed void SetPlaybackSpeed(float speed) { m_playbackSpeed = speed; } // change loop count void SetLoopCount(int32 loopCount) { m_loopCount = loopCount; } // clear any animation void Clear(); // stops the animation in its current state void Stop() { m_playing = false; } // restarts the animation from the last position void Play() { m_playing = true; } // full play invoke void PlayAnimation(const SkeletalAnimation *pAnimation, float playbackSpeed = 1.0f, int32 loopCount = 0, float transitionTime = 0.0f, bool resetTime = true); // update void Update(float deltaTime); private: // channel information SkeletalAnimationPlayer *m_pPlayer; uint32 m_index; float m_weight; WrapMode m_wrapMode; float m_time; bool m_playing; // transitions MeshState *m_pTransitionMeshState; float m_transitionTime; // current state const SkeletalAnimation *m_pAnimation; float m_playbackSpeed; int32 m_loopCount; // queued animation /*struct QueuedAnimation { const SkeletalAnimation *pAnimation; float PlaybackSpeed; float TransitionTime; int32 LoopCount; };*/ }; public: SkeletalAnimationPlayer(); SkeletalAnimationPlayer(const SkeletalMesh *pSkeletalMesh); ~SkeletalAnimationPlayer(); // reference skeleton const SkeletalMesh *GetSkeletalMesh() const { return m_pSkeletalMesh; } void SetSkeletalMesh(const SkeletalMesh *pSkeletalMesh); // channel allocation const Channel *GetChannel(uint32 channelIndex) const { return &m_channels[channelIndex]; } Channel *GetChannel(uint32 channelIndex) { return &m_channels[channelIndex]; } uint32 GetChannelCount() const { return m_channels.GetSize(); } void SetChannelCount(uint32 channelCount); // current state const SkeletalAnimation *GetChannelAnimation(uint32 channelIndex) const { return m_channels[channelIndex].GetAnimation(); } uint32 GetChannelLoopCount(uint32 channelIndex) const { return m_channels[channelIndex].GetLoopCount(); } float GetChannelPlaybackSpeed(uint32 channelIndex) const { return m_channels[channelIndex].GetPlaybackSpeed(); } float GetChannelElapsedTime(uint32 channelIndex) const { return m_channels[channelIndex].GetTime(); } bool GetChannelPlaying(uint32 channelIndex) const { return m_channels[channelIndex].IsPlaying(); } // playback control, negative playbackSpeed will play the animation in reverse, loopCount of -1 will loop infinitely, if hold is set, will remain in pose after completion void PlayAnimation(const SkeletalAnimation *pAnimation, float playbackSpeed = 1.0f, int32 loopCount = 1, bool hold = true, uint32 channelIndex = 0, float weight = 1.0f, float transitionTime = 0.3f); // temporarily pause playback, call ResumeAnimation to resume it void PauseAnimation(uint32 channelIndex = 0); // resume paused playback void ResumeAnimation(uint32 channelIndex = 0); // clear the current animation and reset to base frame void ClearAnimation(uint32 channelIndex = 0); // clear all channels animations void ClearAllAnimations(); // modify playback void SetPlaybackSpeed(float playbackSpeed, uint32 channelIndex = 0); void SetPlaybackLoopCount(int32 loopCount, uint32 channelIndex = 0); void SetPlaybackHold(bool hold, uint32 channelIndex = 0); // call every frame void Update(const float deltaTime); // call before passing to render proxy void UpdateMeshState(); // transform cache const MeshState *GetMeshState() const { return &m_meshState; } const Transform &GetBoneTransform(uint32 boneIndex) const { return m_meshState.GetBoneTransform(boneIndex); } // local space Transform GetFullBoneTransform(uint32 boneIndex) const; void UpdateSkeletalMeshRenderProxy(SkeletalMeshRenderProxy *pRenderProxy); private: // reset to base frame void ResetToBaseFrame(); // calculate the pose for a bone (assumes that the parent bone has been done) void UpdateBoneTransform(const Skeleton::Bone *pSkeletonBone, const Transform *parentBoneTransform); // vars const SkeletalMesh *m_pSkeletalMesh; // channel array MemArray<Channel> m_channels; // current mesh state in skeleton, not bone space MeshState m_meshState; }; <file_sep>/Engine/Source/Renderer/RenderProxies/PointLightRenderProxy.h #pragma once #include "Renderer/RenderProxy.h" class PointLightRenderProxy : public RenderProxy { public: PointLightRenderProxy(uint32 entityId, const float3 &position = float3::Zero, const float range = 64.0f, const float3 &color = float3::One, uint32 shadowFlags = 0, const float falloffExponent = 2.0f); ~PointLightRenderProxy(); // can be called at any time. void SetEnabled(bool newEnabled); void SetPosition(const float3 &newPosition); void SetRange(const float newRange); void SetShadowFlags(uint32 newShadowFlags); void SetColor(const float3 &newColor); void SetFalloffExponent(const float newFalloffExponent); // virtual methods virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; // helper functions to calculate bounding volumes static AABox CalculatePointLightBoundingBox(const float3 &position, float range); static Sphere CalculatePointLightBoundingSphere(const float3 &position, float range); protected: // update bounds void UpdateBounds(); // read and written from render thread, no game thread access bool m_enabled; float3 m_position; float m_range; float3 m_color; uint32 m_shadowFlags; float m_falloffExponent; }; <file_sep>/Engine/Source/MathLib/Sphere.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" class AABox; class Transform; struct Matrix3x3f; struct Matrix3x4f; struct Matrix4x4f; class Sphere { public: Sphere() {} Sphere(const Vector3f &centre, float radius); Sphere(const Sphere &copy); void SetCenter(const Vector3f &centre) { m_center = centre; } void SetRadius(float radius) { m_radius = radius; } void SetCenterAndRadius(const Vector3f &centre, float radius) { m_center = centre; m_radius = radius; } const Vector3f &GetCenter() const { return m_center; } float GetRadius() const { return m_radius; } void Merge(const Vector3f &point); void Merge(const Sphere &sphere); bool AABoxIntersection(const AABox &box) const; bool AABoxIntersection(const AABox &box, Vector3f &contactNormal, Vector3f &contactPoint) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const; bool SphereIntersection(const Sphere &sphere) const; bool SphereIntersection(const Sphere &sphere, Vector3f &contactNormal, Vector3f &contactPoint) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const; float TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const; // transform void ApplyTransform(const Transform &transform); void ApplyTransform(const Matrix3x3f &transform); void ApplyTransform(const Matrix3x4f &transform); void ApplyTransform(const Matrix4x4f &transform); // get transformed Sphere GetTransformed(const Transform &transform) const; Sphere GetTransformed(const Matrix3x3f &transform) const; Sphere GetTransformed(const Matrix3x4f &transform) const; Sphere GetTransformed(const Matrix4x4f &transform) const; bool operator==(const Sphere &comp) const; bool operator!=(const Sphere &comp) const; Sphere &operator=(const Sphere &copy); static Sphere FromAABox(const AABox &box); static Sphere FromPoints(const SIMDVector3f *pPoints, uint32 nPoints); static Sphere FromPoints(const Vector3f *pPoints, uint32 nPoints); static Sphere Merge(const Sphere &left, const Sphere &right); static const Sphere &Zero; static const Sphere &MaxSize; private: Vector3f m_center; float m_radius; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUQuery.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUQuery.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUCommandList.h" GPUQuery *D3D12GPUDevice::CreateQuery(GPU_QUERY_TYPE type) { return nullptr; } bool D3D12GPUContext::BeginQuery(GPUQuery *pQuery) { return false; } bool D3D12GPUContext::EndQuery(GPUQuery *pQuery) { return false; } GPU_QUERY_GETDATA_RESULT D3D12GPUContext::GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) { return GPU_QUERY_GETDATA_RESULT_ERROR; } void D3D12GPUContext::SetPredication(GPUQuery *pQuery) { } void D3D12GPUContext::BypassPredication() { } void D3D12GPUContext::RestorePredication() { } bool D3D12GPUCommandList::BeginQuery(GPUQuery *pQuery) { return false; } bool D3D12GPUCommandList::EndQuery(GPUQuery *pQuery) { return false; } void D3D12GPUCommandList::SetPredication(GPUQuery *pQuery) { } void D3D12GPUCommandList::BypassPredication() { } void D3D12GPUCommandList::RestorePredication() { } <file_sep>/Engine/Source/ResourceCompiler/TextureGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/TextureGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/DataFormats.h" #include "Core/ImageCodec.h" #include "Core/Image.h" #include "Core/DDSReader.h" #include "YBaseLib/ZipArchive.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(TextureGenerator); static const IMAGE_RESIZE_FILTER DEFAULT_MIPMAP_RESIZE_FILTER = IMAGE_RESIZE_FILTER_LANCZOS3; const char *TextureGenerator::Properties::Usage = "Usage"; const char *TextureGenerator::Properties::SourceSRGB = "SourceSRGB"; const char *TextureGenerator::Properties::SourcePremultipliedAlpha = "SourcePremultipliedAlpha"; const char *TextureGenerator::Properties::MaxFilter = "MaxFilter"; const char *TextureGenerator::Properties::AddressU = "AddressU"; const char *TextureGenerator::Properties::AddressV = "AddressV"; const char *TextureGenerator::Properties::AddressW = "AddressW"; const char *TextureGenerator::Properties::BorderColor = "BorderColor"; const char *TextureGenerator::Properties::GenerateMipmaps = "GenerateMipmaps"; const char *TextureGenerator::Properties::MipmapResizeFilter = "MipmapResizeFilter"; const char *TextureGenerator::Properties::NPOTMipmaps = "NPOTMipmaps"; const char *TextureGenerator::Properties::EnableSRGB = "EnableSRGB"; const char *TextureGenerator::Properties::EnablePremultipliedAlpha = "EnablePremultipliedAlpha"; const char *TextureGenerator::Properties::EnableTextureCompression = "EnableTextureCompression"; TextureGenerator::TextureGenerator() : m_eTextureType(TEXTURE_TYPE_COUNT), m_eTexturePlatform(TEXTURE_PLATFORM_DXTC), m_ePixelFormat(PIXEL_FORMAT_UNKNOWN), m_nMipLevels(0), m_nArraySize(0), m_analyzed(false), m_bHasAlpha(false), m_bHasAlphaLevels(false), m_iWidth(0), m_iHeight(0), m_iDepth(0), m_pImages(NULL), m_nImages(0) { } TextureGenerator::TextureGenerator(const TextureGenerator &copy) : m_eTextureType(copy.m_eTextureType), m_eTexturePlatform(copy.m_eTexturePlatform), m_propertyList(copy.m_propertyList), m_ePixelFormat(copy.m_ePixelFormat), m_nMipLevels(copy.m_nMipLevels), m_nArraySize(copy.m_nArraySize), m_analyzed(copy.m_analyzed), m_bHasAlpha(copy.m_bHasAlpha), m_bHasAlphaLevels(copy.m_bHasAlphaLevels), m_iWidth(copy.m_iWidth), m_iHeight(copy.m_iHeight), m_iDepth(copy.m_iDepth), m_nImages(copy.m_nImages) { DebugAssert(m_nImages > 0); m_pImages = new Image[m_nImages]; for (uint32 i = 0; i < m_nImages; i++) m_pImages[i].Copy(copy.m_pImages[i]); } TextureGenerator::~TextureGenerator() { if (m_pImages != NULL) delete[] m_pImages; } void TextureGenerator::SetTexturePlatform(TEXTURE_PLATFORM platform) { m_eTexturePlatform = platform; } void TextureGenerator::SetTextureUsage(TEXTURE_USAGE usage) { m_propertyList.SetPropertyValue(Properties::Usage, NameTable_GetNameString(NameTables::TextureUsage, usage)); } void TextureGenerator::SetTextureFilter(TEXTURE_FILTER filter) { m_propertyList.SetPropertyValue(Properties::MaxFilter, NameTable_GetNameString(NameTables::TextureFilter, filter)); } void TextureGenerator::SetTextureAddressModeU(TEXTURE_ADDRESS_MODE mode) { m_propertyList.SetPropertyValue(Properties::AddressU, NameTable_GetNameString(NameTables::TextureAddressMode, mode)); } void TextureGenerator::SetTextureAddressModeV(TEXTURE_ADDRESS_MODE mode) { m_propertyList.SetPropertyValue(Properties::AddressV, NameTable_GetNameString(NameTables::TextureAddressMode, mode)); } void TextureGenerator::SetTextureAddressModeW(TEXTURE_ADDRESS_MODE mode) { m_propertyList.SetPropertyValue(Properties::AddressW, NameTable_GetNameString(NameTables::TextureAddressMode, mode)); } void TextureGenerator::SetMipMapResizeFilter(IMAGE_RESIZE_FILTER filter) { m_propertyList.SetPropertyValue(Properties::MipmapResizeFilter, NameTable_GetNameString(NameTables::ImageResizeFilter, filter)); } void TextureGenerator::SetGenerateMipmaps(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::GenerateMipmaps, enabled); } void TextureGenerator::SetSourcePremultipliedAlpha(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::SourcePremultipliedAlpha, enabled); } void TextureGenerator::SetEnablePremultipliedAlpha(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::EnablePremultipliedAlpha, enabled); } void TextureGenerator::SetEnableTextureCompression(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::EnableTextureCompression, enabled); } void TextureGenerator::SetEnableSRGB(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::EnableSRGB, enabled); } void TextureGenerator::SetSourceSRGB(bool enabled) { m_propertyList.SetPropertyValueBool(Properties::SourceSRGB, enabled); } const Image *TextureGenerator::GetImage(uint32 arrayIndex, uint32 mipIndex) const { DebugAssert(arrayIndex < m_nArraySize && mipIndex < m_nMipLevels); return &m_pImages[arrayIndex * m_nMipLevels + mipIndex]; } void TextureGenerator::SetDefaultProperties(TEXTURE_USAGE usage) { bool useSRGB = (usage == TEXTURE_USAGE_COLOR_MAP); m_propertyList.SetPropertyValue(Properties::Usage, NameTable_GetNameString(NameTables::TextureUsage, usage)); m_propertyList.SetPropertyValueBool(Properties::SourceSRGB, useSRGB); m_propertyList.SetPropertyValueBool(Properties::SourcePremultipliedAlpha, false); m_propertyList.SetPropertyValue(Properties::MaxFilter, NameTable_GetNameString(NameTables::TextureFilter, TEXTURE_FILTER_ANISOTROPIC)); m_propertyList.SetPropertyValue(Properties::AddressU, NameTable_GetNameString(NameTables::TextureAddressMode, TEXTURE_ADDRESS_MODE_CLAMP)); m_propertyList.SetPropertyValue(Properties::AddressV, NameTable_GetNameString(NameTables::TextureAddressMode, TEXTURE_ADDRESS_MODE_CLAMP)); m_propertyList.SetPropertyValue(Properties::AddressW, NameTable_GetNameString(NameTables::TextureAddressMode, TEXTURE_ADDRESS_MODE_CLAMP)); m_propertyList.SetPropertyValueFloat4(Properties::BorderColor, float4::One); m_propertyList.SetPropertyValueBool(Properties::GenerateMipmaps, true); m_propertyList.SetPropertyValue(Properties::MipmapResizeFilter, NameTable_GetNameString(NameTables::ImageResizeFilter, DEFAULT_MIPMAP_RESIZE_FILTER)); m_propertyList.SetPropertyValueBool(Properties::NPOTMipmaps, false); m_propertyList.SetPropertyValueBool(Properties::EnableSRGB, useSRGB); m_propertyList.SetPropertyValueBool(Properties::EnablePremultipliedAlpha, true); m_propertyList.SetPropertyValueBool(Properties::EnableTextureCompression, true); } bool TextureGenerator::InternalCreate(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 mipLevels, uint32 arraySize) { DebugAssert(textureType < TEXTURE_TYPE_COUNT); DebugAssert(pixelFormat != PIXEL_FORMAT_UNKNOWN && pixelFormat < PIXEL_FORMAT_COUNT); if (arraySize == 0 || mipLevels == 0) return false; // check dimensions switch (textureType) { case TEXTURE_TYPE_1D: case TEXTURE_TYPE_1D_ARRAY: { if (width < 1 || height != 1 || depth != 1) return false; if ((textureType == TEXTURE_TYPE_1D && arraySize != 1) || (textureType == TEXTURE_TYPE_1D_ARRAY && arraySize == 0)) { return false; } } break; case TEXTURE_TYPE_2D: case TEXTURE_TYPE_2D_ARRAY: { if (width < 1 || height < 1 || depth != 1) return false; if ((textureType == TEXTURE_TYPE_2D && arraySize != 1) || (textureType == TEXTURE_TYPE_2D_ARRAY && arraySize == 0)) { return false; } } break; case TEXTURE_TYPE_3D: { if (width < 1 || height < 1 || depth < 1) return false; } break; case TEXTURE_TYPE_CUBE: case TEXTURE_TYPE_CUBE_ARRAY: { if (width < 1 || height < 1 || depth != 1) return false; if ((textureType == TEXTURE_TYPE_CUBE && arraySize != 6) || (textureType == TEXTURE_TYPE_CUBE_ARRAY && (arraySize < 6 || (arraySize % 6) != 0))) { return false; } } break; } // check mip count if (mipLevels == 0 || mipLevels > TEXTURE_MAX_MIPMAP_COUNT) return false; // setup everything m_eTextureType = textureType; m_ePixelFormat = pixelFormat; m_nMipLevels = mipLevels; m_nArraySize = arraySize; m_iWidth = width; m_iHeight = height; m_iDepth = depth; // set defaults here too, but they'll be replaced m_bHasAlpha = false; m_bHasAlphaLevels = false; // setup image array m_nImages = m_nMipLevels * m_nArraySize; m_pImages = new Image[m_nImages]; uint32 imageIndex = 0; for (uint32 i = 0; i < m_nArraySize; i++) { for (uint32 j = 0; j < m_nMipLevels; j++) { uint32 mipWidth = Max(width >> j, (uint32)1); uint32 mipHeight = Max(height >> j, (uint32)1); uint32 mipDepth = Max(depth >> j, (uint32)1); m_pImages[imageIndex].Create(m_ePixelFormat, mipWidth, mipHeight, mipDepth); Y_memzero(m_pImages[imageIndex].GetData(), m_pImages[imageIndex].GetDataSize()); imageIndex++; } } return true; } bool TextureGenerator::Create(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 arraySize, TEXTURE_USAGE usage /* = TEXTURE_USAGE_NONE */) { if (!InternalCreate(textureType, pixelFormat, width, height, depth, 1, arraySize)) return false; SetDefaultProperties(usage); return true; } bool TextureGenerator::Create(TEXTURE_TYPE textureType, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 depth, uint32 mipLevels, uint32 arraySize, TEXTURE_USAGE usage /* = TEXTURE_USAGE_NONE */) { if (!InternalCreate(textureType, pixelFormat, width, height, depth, mipLevels, arraySize)) return false; SetDefaultProperties(usage); return true; } bool TextureGenerator::Load(const char *fileName, ByteStream *pStream) { ZipArchive *pArchive = ZipArchive::OpenArchiveReadOnly(pStream); if (pArchive == NULL) { Log_ErrorPrintf("TextureGenerator::Load: Could not open '%s' as archive.", fileName); return false; } bool result = false; // load xml { AutoReleasePtr<ByteStream> pDescriptorStream = pArchive->OpenFile("texture.xml", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pDescriptorStream == NULL) { Log_ErrorPrintf("TextureGenerator::Load: Could not find 'texture.xml' in archive '%s'.", fileName); goto CLEANUP; } XMLReader xmlReader; if (!xmlReader.Create(pDescriptorStream, "texture.xml") || !xmlReader.SkipToElement("texture")) { Log_ErrorPrintf("TextureGenerator::Load: Could not parse 'texture.xml' in archive '%s'.", fileName); goto CLEANUP; } // read attributes const char *textureTypeStr = xmlReader.FetchAttribute("type"); const char *textureMipLevelsStr = xmlReader.FetchAttribute("miplevels"); const char *textureArraySizeStr = xmlReader.FetchAttribute("arraysize"); const char *texturePixelFormatStr = xmlReader.FetchAttribute("format"); const char *textureWidthStr = xmlReader.FetchAttribute("width"); const char *textureHeightStr = xmlReader.FetchAttribute("height"); const char *textureDepthStr = xmlReader.FetchAttribute("depth"); if (textureTypeStr == NULL || textureMipLevelsStr == NULL || textureArraySizeStr == NULL || texturePixelFormatStr == NULL || textureWidthStr == NULL || textureHeightStr == NULL || textureDepthStr == NULL) { xmlReader.PrintError("missing attributes"); goto CLEANUP; } TEXTURE_TYPE textureType; if (!NameTable_TranslateType(NameTables::TextureType, textureTypeStr, &textureType, true)) { xmlReader.PrintError("invalid texture type: %s", textureTypeStr); goto CLEANUP; } PIXEL_FORMAT pixelFormat; if (!NameTable_TranslateType(NameTables::PixelFormat, texturePixelFormatStr, &pixelFormat, true)) { xmlReader.PrintError("invalid pixel format: %s", texturePixelFormatStr); goto CLEANUP; } if (!InternalCreate(textureType, pixelFormat, StringConverter::StringToUInt32(textureWidthStr), StringConverter::StringToUInt32(textureHeightStr), StringConverter::StringToUInt32(textureDepthStr), StringConverter::StringToUInt32(textureMipLevelsStr), StringConverter::StringToUInt32(textureArraySizeStr))) { xmlReader.PrintError("could not create images"); goto CLEANUP; } if (!xmlReader.SkipToElement("properties")) { xmlReader.PrintError("could not skip to properties element"); goto CLEANUP; } if (!m_propertyList.LoadFromXML(xmlReader)) { xmlReader.PrintError("could not parse properties"); goto CLEANUP; } } // load images { PathString imageFileName; for (uint32 i = 0; i < m_nImages; i++) { imageFileName.Format("%u.png", i); AutoReleasePtr<ByteStream> pImageStream = pArchive->OpenFile(imageFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pImageStream == NULL) { Log_ErrorPrintf("TextureGenerator::Load: Could not find '%s' in archive '%s'.", imageFileName.GetCharArray(), fileName); goto CLEANUP; } Image decodedImage; ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(imageFileName, pImageStream); if (pCodec == NULL || !pCodec->DecodeImage(&decodedImage, imageFileName, pImageStream)) { Log_ErrorPrintf("TextureGenerator::Load: Could not decode image '%s' in archive '%s'.", imageFileName.GetCharArray(), fileName); goto CLEANUP; } Image &destinationImage = m_pImages[i]; if (decodedImage.GetPixelFormat() != destinationImage.GetPixelFormat()) { // freeimage likes to nuke the alpha channel on fully opaque images for us.. thanks for that.. so convert back to the original format if (!decodedImage.ConvertPixelFormat(m_ePixelFormat)) { Log_ErrorPrintf("TextureGenerator::Load: Image '%s' pixel format %s different to texture %s and conversion failed", imageFileName.GetCharArray(), NameTable_GetNameString(NameTables::PixelFormat, decodedImage.GetPixelFormat()), NameTable_GetNameString(NameTables::PixelFormat, destinationImage.GetPixelFormat())); goto CLEANUP; } } if (decodedImage.GetWidth() != destinationImage.GetWidth() || decodedImage.GetHeight() != destinationImage.GetHeight() || decodedImage.GetDepth() != destinationImage.GetDepth()) { Log_ErrorPrintf("TextureGenerator::Load: Image '%s' dimensions %ux%ux%u different to texture %ux%ux%u", imageFileName.GetCharArray(), decodedImage.GetWidth(), decodedImage.GetHeight(), decodedImage.GetDepth(), destinationImage.GetWidth(), destinationImage.GetHeight(), destinationImage.GetDepth()); goto CLEANUP; } destinationImage.Copy(decodedImage); } } result = true; CLEANUP: delete pArchive; return result; } bool TextureGenerator::Save(ByteStream *pOutputStream) const { ZipArchive *pArchive = ZipArchive::CreateArchive(pOutputStream); if (pArchive == NULL) { Log_ErrorPrintf("TextureGenerator::Save: Could not create archive."); return false; } bool result = false; // save xml { AutoReleasePtr<ByteStream> pTextureOutputSTream = pArchive->OpenFile("texture.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pTextureOutputSTream == NULL) { Log_ErrorPrintf("TextureGenerator::Save: Could not open texture.xml for writing"); goto CLEANUP; } XMLWriter xmlWriter; if (!xmlWriter.Create(pTextureOutputSTream)) { Log_ErrorPrintf("TextureGenerator::Save: Could not create texture.xml XMLWriter"); goto CLEANUP; } xmlWriter.StartElement("texture"); { xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::TextureType, m_eTextureType)); xmlWriter.WriteAttribute("miplevels", StringConverter::UInt32ToString(m_nMipLevels)); xmlWriter.WriteAttribute("arraysize", StringConverter::UInt32ToString(m_nArraySize)); xmlWriter.WriteAttribute("format", NameTable_GetNameString(NameTables::PixelFormat, m_ePixelFormat)); xmlWriter.WriteAttribute("width", StringConverter::UInt32ToString(m_iWidth)); xmlWriter.WriteAttribute("height", StringConverter::UInt32ToString(m_iHeight)); xmlWriter.WriteAttribute("depth", StringConverter::UInt32ToString(m_iDepth)); // write properties xmlWriter.StartElement("properties"); m_propertyList.SaveToXML(xmlWriter); xmlWriter.EndElement(); } xmlWriter.EndElement(); if (xmlWriter.InErrorState() || pTextureOutputSTream->InErrorState()) goto CLEANUP; xmlWriter.Close(); } // save images { PathString imageFileName; PropertyTable encoderOptions; encoderOptions.SetPropertyValueUInt32(ImageCodecEncoderOptions::PNG_COMPRESSION_LEVEL, 6); for (uint32 i = 0; i < m_nImages; i++) { imageFileName.Format("%u.png", i); ImageCodec *pCodec = ImageCodec::GetImageCodecForFileName(imageFileName); if (pCodec == NULL) { Log_ErrorPrintf("TextureGenerator::Save: Could not get image codec for '%s'", imageFileName.GetCharArray()); goto CLEANUP; } AutoReleasePtr<ByteStream> pImageStream = pArchive->OpenFile(imageFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pImageStream == NULL) { Log_ErrorPrintf("TextureGenerator::Save: Could not open '%s' for writing", imageFileName.GetCharArray()); goto CLEANUP; } if (!pCodec->EncodeImage(imageFileName, pImageStream, &m_pImages[i], encoderOptions)) { Log_ErrorPrintf("TextureGenerator::Save: Could not encode image '%s'", imageFileName.GetCharArray()); goto CLEANUP; } } } // ok result = true; CLEANUP: if (result) { pArchive->CommitChanges(); pOutputStream->Commit(); delete pArchive; } else { pArchive->DiscardChanges(); pOutputStream->Discard(); delete pArchive; } return result; } bool TextureGenerator::Resize(IMAGE_RESIZE_FILTER resizeFilter, uint32 width, uint32 height, uint32 depth) { // throw away mip chain Image *pNewImages = new Image[m_nArraySize]; for (uint32 i = 0; i < m_nImages; i++) { if (!pNewImages[i].CopyAndResize(m_pImages[i * m_nMipLevels], resizeFilter, width, height, depth)) { delete[] pNewImages; return false; } } delete[] m_pImages; m_nMipLevels = 1; m_pImages = pNewImages; m_nImages = m_nArraySize; return true; } bool TextureGenerator::AddMask(uint32 arrayIndex, const Image *pMaskImage) { DebugAssert(arrayIndex < m_nArraySize); if (m_ePixelFormat != PIXEL_FORMAT_R8G8B8A8_UNORM) { Log_ErrorPrintf("TextureGenerator::AddMask: Pixel format must be R8G8B8A8"); return false; } Image &destinationImage = m_pImages[arrayIndex * m_nMipLevels]; if (destinationImage.GetWidth() != pMaskImage->GetWidth() || destinationImage.GetHeight() != pMaskImage->GetHeight()) { Log_ErrorPrintf("TextureGenerator::AddMask: Image dimensions must match"); return false; } const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pMaskImage->GetPixelFormat()); bool useAlphaChannel = pPixelFormatInfo->HasAlpha; Image tempImage; if (useAlphaChannel) { if (!tempImage.CopyAndConvertPixelFormat(*pMaskImage, PIXEL_FORMAT_R8G8B8A8_UNORM)) return false; // take the alpha channel from each pixel of the mask and apply it to the source for (uint32 y = 0; y < destinationImage.GetHeight(); y++) { const byte *pMaskPixels = tempImage.GetData() + (y * tempImage.GetDataRowPitch()); byte *pPixels = destinationImage.GetData() + (y * destinationImage.GetDataRowPitch()); for (uint32 x = 0; x < destinationImage.GetWidth(); x++) { pPixels[3] = pMaskPixels[3]; pMaskPixels += 4; pPixels += 4; } } } else { if (!tempImage.CopyAndConvertPixelFormat(*pMaskImage, PIXEL_FORMAT_R8_UNORM)) return false; // take the alpha channel from each pixel of the mask and apply it to the source's alpha channel for (uint32 y = 0; y < destinationImage.GetHeight(); y++) { const byte *pMaskPixels = tempImage.GetData() + (y * tempImage.GetDataRowPitch()); byte *pPixels = destinationImage.GetData() + (y * destinationImage.GetDataRowPitch()); for (uint32 x = 0; x < destinationImage.GetWidth(); x++) { pPixels[3] = pMaskPixels[0]; pMaskPixels++; pPixels += 4; } } } // change analyzed flag m_analyzed = false; return true; } bool TextureGenerator::AddImage(const Image *pImage) { if (m_eTextureType != TEXTURE_TYPE_2D_ARRAY) return false; Image &referenceImage = m_pImages[0]; if (pImage->GetWidth() != referenceImage.GetWidth() || pImage->GetHeight() != referenceImage.GetHeight() || pImage->GetDepth() != referenceImage.GetDepth() || pImage->GetPixelFormat() != referenceImage.GetPixelFormat()) { Log_ErrorPrintf("TextureGenerator::AddImage: Incompatible image."); return false; } uint32 arrayIndex = m_nArraySize; SetArraySize(m_nArraySize + 1); if (!SetImage(arrayIndex, pImage)) { SetArraySize(arrayIndex); return false; } return true; } bool TextureGenerator::SetImage(uint32 arrayIndex, const Image *pImage) { if (arrayIndex >= m_nArraySize) { Log_ErrorPrintf("TextureGenerator::SetImage: Array index (%u) out of range (%u).", arrayIndex, m_nArraySize); return false; } Image &destinationImage = m_pImages[arrayIndex * m_nMipLevels + 0]; if (pImage->GetWidth() != destinationImage.GetWidth() || pImage->GetHeight() != destinationImage.GetHeight() || pImage->GetDepth() != destinationImage.GetDepth() || pImage->GetPixelFormat() != destinationImage.GetPixelFormat()) { Log_ErrorPrintf("TextureGenerator::SetImage: Incompatible image."); return false; } destinationImage.Copy(*pImage); return true; } bool TextureGenerator::SetImage(uint32 arrayIndex, uint32 mipIndex, const Image *pImage) { if (arrayIndex >= m_nArraySize) { Log_ErrorPrintf("TextureGenerator::SetImage: Array index (%u) out of range (%u).", arrayIndex, m_nArraySize); return false; } if (mipIndex >= m_nMipLevels) { Log_ErrorPrintf("TextureGenerator::SetImage: Mip index (%u) out of range (%u).", mipIndex, m_nMipLevels); return false; } Image &destinationImage = m_pImages[arrayIndex * m_nMipLevels + mipIndex]; if (pImage->GetWidth() != destinationImage.GetWidth() || pImage->GetHeight() != destinationImage.GetHeight() || pImage->GetDepth() != destinationImage.GetDepth() || pImage->GetPixelFormat() != destinationImage.GetPixelFormat()) { Log_ErrorPrintf("TextureGenerator::SetImage: Incompatible image."); return false; } destinationImage.Copy(*pImage); return true; } void TextureGenerator::SetArraySize(uint32 newArraySize) { DebugAssert(newArraySize > 0); DebugAssert(m_eTextureType == TEXTURE_TYPE_1D_ARRAY || m_eTextureType == TEXTURE_TYPE_2D_ARRAY || m_eTextureType == TEXTURE_TYPE_CUBE_ARRAY); if (newArraySize == m_nArraySize) return; Image *pNewImages = new Image[newArraySize]; uint32 i; for (i = 0; i < m_nArraySize && i < newArraySize; i++) { // copy existing image pNewImages[i].Copy(m_pImages[i * m_nMipLevels]); } for (; i < newArraySize; i++) { // empty new image pNewImages[i].Create(m_ePixelFormat, m_iWidth, m_iHeight, m_iDepth); Y_memzero(pNewImages[i].GetData(), pNewImages[i].GetDataSize()); } // update size delete[] m_pImages; m_pImages = pNewImages; m_nImages = newArraySize; m_nMipLevels = 1; m_nArraySize = newArraySize; } bool TextureGenerator::GenerateMipmaps() { DebugAssert(m_nImages > 0 && m_nArraySize > 0); // get uncompressed pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); DebugAssert(pPixelFormatInfo != NULL); if (m_ePixelFormat != pPixelFormatInfo->UncompressedFormat) { // cannot allocate mips while image is still compressed return false; } // npot mipmaps? uint32 baseWidth = m_iWidth; uint32 baseHeight = m_iHeight; uint32 baseDepth = m_iDepth; if (!m_propertyList.GetPropertyValueDefaultBool(Properties::NPOTMipmaps, false)) { if (baseWidth > 0 && !Y_ispow2(baseWidth)) baseWidth = Y_nextpow2(baseWidth); if (baseHeight > 0 && !Y_ispow2(baseHeight)) baseHeight = Y_nextpow2(baseHeight); if (baseDepth > 0 && !Y_ispow2(baseDepth)) baseDepth = Y_nextpow2(baseDepth); } // determine number of mipmaps uint32 currentWidth = baseWidth; uint32 currentHeight = baseHeight; uint32 currentDepth = baseDepth; uint32 nMips = 1; for (;;) { if ((currentWidth == 1 && currentHeight == 1 && currentDepth == 1) || nMips == TEXTURE_MAX_MIPMAP_COUNT) break; currentWidth = Max(currentWidth / 2, (uint32)1); currentHeight = Max(currentHeight / 2, (uint32)1); currentDepth = Max(currentDepth / 2, (uint32)1); nMips++; } // calculate new image count uint32 nNewImages = nMips * m_nArraySize; Image *pNewImageArray = new Image[nNewImages]; Log_InfoPrintf("TextureGenerator::GenerateMipmaps: Generating %u mipmaps per image...", nMips); // get mip resize filter IMAGE_RESIZE_FILTER resizeFilter; if (!NameTable_TranslateType(NameTables::ImageResizeFilter, m_propertyList.GetPropertyValueDefault(Properties::MipmapResizeFilter), &resizeFilter, true)) resizeFilter = DEFAULT_MIPMAP_RESIZE_FILTER; // for each array image uint32 i, j; for (i = 0; i < m_nArraySize; i++) { // convert to the uncompressed format Image baseImage; baseImage.Copy(m_pImages[i * m_nMipLevels]); // resize full scale image if necessary if (baseWidth != baseImage.GetWidth() || baseHeight != baseImage.GetHeight() || baseDepth != baseImage.GetDepth()) { if (!baseImage.Resize(resizeFilter, baseWidth, baseHeight, baseDepth)) { Log_ErrorPrintf("TextureGenerator::GenerateMipmaps: Could not resize base image."); delete[] pNewImageArray; return false; } } // store mip levels currentWidth = baseWidth; currentHeight = baseHeight; currentDepth = baseDepth; for (j = 0; j < nMips; j++) { Image &destImage = pNewImageArray[i * nMips + j]; if (j == 0) { // miplevel 0 can just be copied destImage.Copy(baseImage); } else { if (!destImage.CopyAndResize(baseImage, resizeFilter, currentWidth, currentHeight, currentDepth)) { Log_ErrorPrintf("TextureGenerator::GenerateMipmaps: Could not copy/resize miplevel %u of array index %u", j, i); delete[] pNewImageArray; return false; } } currentWidth = Max(currentWidth / 2, (uint32)1); currentHeight = Max(currentHeight / 2, (uint32)1); currentDepth = Max(currentDepth / 2, (uint32)1); } } // store everything m_iWidth = baseWidth; m_iHeight = baseHeight; m_iDepth = baseDepth; m_nMipLevels = nMips; m_nImages = nNewImages; // update images delete[] m_pImages; m_pImages = pNewImageArray; return true; } bool TextureGenerator::ConvertToPixelFormat(PIXEL_FORMAT newPixelFormat) { if (m_ePixelFormat == newPixelFormat) return true; uint32 i; Image *pNewImageArray = new Image[m_nImages]; for (i = 0; i < m_nImages; i++) { if (!pNewImageArray[i].CopyAndConvertPixelFormat(m_pImages[i], newPixelFormat)) { Log_ErrorPrintf("TextureGenerator::ConvertToPixelFormat: Failed to convert pixel format of image %u", i); delete[] pNewImageArray; return false; } } m_ePixelFormat = newPixelFormat; delete[] m_pImages; m_pImages = pNewImageArray; return true; } bool TextureGenerator::AnalyzeImage() { uint32 i; Image tempImage; m_bHasAlpha = false; m_bHasAlphaLevels = false; // if it doesn't have an alpha channel, skip it outright const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->HasAlpha) { // only look at miplevel 0 for (i = 0; i < m_nImages; i += m_nMipLevels) { // convert to r8g8b8a8 Image *pImageToAnalyse; if (m_pImages[i].GetPixelFormat() == PIXEL_FORMAT_R8G8B8A8_UNORM) { // use in place pImageToAnalyse = &m_pImages[i]; } else { if (!tempImage.CopyAndConvertPixelFormat(m_pImages[i], PIXEL_FORMAT_R8G8B8A8_UNORM)) { Log_ErrorPrintf("TextureGenerator::AnalyseImage: CopyAndConvertPixelFormat failed."); return false; } pImageToAnalyse = &tempImage; } const byte *pDataPtr = pImageToAnalyse->GetData(); for (uint32 j = 0; j < pImageToAnalyse->GetDepth(); j++) { const byte *pSlicePtr = pDataPtr; for (uint32 k = 0; k < pImageToAnalyse->GetHeight(); k++) { const uint32 *pRowPtr = reinterpret_cast<const uint32 *>(pSlicePtr); for (uint32 l = 0; l < pImageToAnalyse->GetWidth(); l++) { uint32 pixel = *(pRowPtr++); uint8 alpha = uint8(pixel >> 24); if (alpha != 0xFF) { m_bHasAlpha = true; if (alpha != 0x00) m_bHasAlphaLevels = true; } } pSlicePtr += pImageToAnalyse->GetDataRowPitch(); } pDataPtr += pImageToAnalyse->GetDataSlicePitch(); } } } m_analyzed = true; return true; } bool TextureGenerator::UncompressImage() { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); DebugAssert(pPixelFormatInfo != NULL); if (m_ePixelFormat == pPixelFormatInfo->UncompressedFormat) return true; return ConvertToPixelFormat(pPixelFormatInfo->UncompressedFormat); } bool TextureGenerator::RemoveAlphaChannel() { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); DebugAssert(pPixelFormatInfo != NULL); if (!pPixelFormatInfo->HasAlpha) return true; if (!ConvertToPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM)) return false; // update analysis m_bHasAlpha = false; m_bHasAlphaLevels = false; return true; } bool TextureGenerator::RemoveAlphaChannelIfOpaque() { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); DebugAssert(pPixelFormatInfo != NULL); if (!pPixelFormatInfo->HasAlpha) return true; if (!m_analyzed && !AnalyzeImage()) return false; if (m_bHasAlpha) return true; Log_InfoPrintf("TextureGenerator::RemoveAlphaChannelIfOpaque: Image is completely opaque, removing alpha channel (%s -> R8G8B8_UNORM)...", NameTable_GetNameString(NameTables::PixelFormat, m_ePixelFormat)); return ConvertToPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM); } bool TextureGenerator::ConvertBGRToRGB() { // convert BGR[A] formats to RGB[A]. this is what freeimage will read them back currently as. if (m_ePixelFormat == PIXEL_FORMAT_B8G8R8_UNORM || m_ePixelFormat == PIXEL_FORMAT_B8G8R8X8_UNORM) { if (!ConvertToPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM)) return false; } else if (m_ePixelFormat == PIXEL_FORMAT_B8G8R8A8_UNORM) { if (!ConvertToPixelFormat(PIXEL_FORMAT_R8G8B8A8_UNORM)) return false; } return true; } bool TextureGenerator::ConvertToTextureArray() { if (m_eTextureType != TEXTURE_TYPE_2D) return false; // this can just be switched, nothing else really has to change as it will only contain one image DebugAssert(m_nArraySize == 1); m_eTextureType = TEXTURE_TYPE_2D_ARRAY; return true; } bool TextureGenerator::ConvertToPremultipliedAlpha() { if (m_propertyList.GetPropertyValueDefaultBool(Properties::SourcePremultipliedAlpha, true)) return true; if (!ConvertToPixelFormat(PIXEL_FORMAT_R8G8B8A8_UNORM)) return false; Log_InfoPrintf("TextureGenerator::ConvertToPremultipliedAlpha: Converting to premultiplied alpha..."); uint32 i, j, k; for (i = 0; i < m_nImages; i++) { Image *pCurrentImage = &m_pImages[i]; byte *pRow = reinterpret_cast<byte *>(pCurrentImage->GetData()); for (j = 0; j < pCurrentImage->GetHeight(); j++) { byte *pPixels = pRow; for (k = 0; k < pCurrentImage->GetWidth(); k++) { float r = ((float)pPixels[0]) / 255.0f; float g = ((float)pPixels[1]) / 255.0f; float b = ((float)pPixels[2]) / 255.0f; float a = ((float)pPixels[3]) / 255.0f; pPixels[0] = (byte)Math::Clamp(((uint32)(r * a * 255.0f)), (uint32)0, (uint32)255); pPixels[1] = (byte)Math::Clamp(((uint32)(g * a * 255.0f)), (uint32)0, (uint32)255); pPixels[2] = (byte)Math::Clamp(((uint32)(b * a * 255.0f)), (uint32)0, (uint32)255); pPixels += 4; } pRow += pCurrentImage->GetDataRowPitch(); } } m_propertyList.SetPropertyValueBool(Properties::SourcePremultipliedAlpha, true); return true; } PIXEL_FORMAT TextureGenerator::GetBestPixelFormat(bool allowCompression) const { if (!m_analyzed && !const_cast<TextureGenerator *>(this)->AnalyzeImage()) return m_ePixelFormat; // disable compression on small images if (m_iWidth < 4 || m_iHeight < 4) allowCompression = false; // get usage TEXTURE_USAGE textureUsage; if (!NameTable_TranslateType(NameTables::TextureUsage, m_propertyList.GetPropertyValueDefault(Properties::Usage, ""), &textureUsage, true)) textureUsage = TEXTURE_USAGE_NONE; // automatically determine best output format switch (m_eTexturePlatform) { case TEXTURE_PLATFORM_DXTC: { switch (textureUsage) { case TEXTURE_USAGE_NONE: case TEXTURE_USAGE_COLOR_MAP: case TEXTURE_USAGE_UI_ASSET: { // TODO: Optional BC7 if (allowCompression) return (m_bHasAlpha && m_bHasAlphaLevels) ? PIXEL_FORMAT_BC3_UNORM : PIXEL_FORMAT_BC1_UNORM; else return PIXEL_FORMAT_R8G8B8A8_UNORM; } break; case TEXTURE_USAGE_GLOSS_MAP: case TEXTURE_USAGE_ALPHA_MAP: case TEXTURE_USAGE_UI_LUMINANCE_ASSET: case TEXTURE_USAGE_HEIGHT_MAP: { //if (allowCompression) //return PIXEL_FORMAT_BC4_UNORM; //else return PIXEL_FORMAT_R8_UNORM; } break; case TEXTURE_USAGE_NORMAL_MAP: { //if (allowCompression) //return PIXEL_FORMAT_BC5_UNORM; //else return PIXEL_FORMAT_R8G8B8A8_UNORM; } break; } return PIXEL_FORMAT_R8G8B8A8_UNORM; } break; case TEXTURE_PLATFORM_PVRTC: case TEXTURE_PLATFORM_ATC: case TEXTURE_PLATFORM_ETC: case TEXTURE_PLATFORM_ES2_NOTC: case TEXTURE_PLATFORM_ES2_DXTC: { // RGBA textures for everything return PIXEL_FORMAT_R8G8B8A8_UNORM; } break; } return m_ePixelFormat; } bool TextureGenerator::Optimize() { if (!UncompressImage()) return false; if (!ConvertBGRToRGB()) return false; if (!m_analyzed && !AnalyzeImage()) return false; if (!RemoveAlphaChannelIfOpaque()) return false; // convert to premultiplied alpha if (m_bHasAlphaLevels && !m_propertyList.GetPropertyValueDefaultBool(Properties::SourcePremultipliedAlpha, false)) { if (m_propertyList.GetPropertyValueDefaultBool(Properties::EnablePremultipliedAlpha, true)) { if (!ConvertToPremultipliedAlpha()) return false; m_propertyList.SetPropertyValueBool(Properties::SourcePremultipliedAlpha, true); } } // generate mipmaps if (m_nMipLevels == 1 && m_propertyList.GetPropertyValueDefaultBool(Properties::GenerateMipmaps, true) && !GenerateMipmaps()) return false; return true; } bool TextureGenerator::Compile(ByteStream *pOutputStream, TEXTURE_PLATFORM platform /* = NUM_TEXTURE_PLATFORMS */) const { TextureGenerator copy(*this); if (platform != NUM_TEXTURE_PLATFORMS) copy.SetTexturePlatform(platform); return copy.InternalCompile(pOutputStream); } bool TextureGenerator::InternalCompile(ByteStream *pOutputStream) { if (!m_analyzed && !AnalyzeImage()) return false; // convert to premultiplied alpha bool isPremultipliedAlpha = false; if (m_bHasAlpha || m_bHasAlphaLevels) { isPremultipliedAlpha = m_propertyList.GetPropertyValueDefaultBool(Properties::SourcePremultipliedAlpha, false); if (!isPremultipliedAlpha && m_propertyList.GetPropertyValueDefaultBool(Properties::EnablePremultipliedAlpha, true)) { if (!UncompressImage() || !ConvertToPremultipliedAlpha()) return false; isPremultipliedAlpha = true; } } // generate mipmaps if (m_nMipLevels == 1 && m_propertyList.GetPropertyValueDefaultBool(Properties::GenerateMipmaps, true) && !GenerateMipmaps()) return false; // todo: srgb conversion // get format PIXEL_FORMAT preferredPixelFormat = GetBestPixelFormat(m_propertyList.GetPropertyValueDefaultBool(Properties::EnableTextureCompression, true)); if (m_ePixelFormat != preferredPixelFormat) { Log_DevPrintf("TextureGenerator::InternalCompile: Converting from %s to optimal format %s", NameTable_GetNameString(NameTables::PixelFormat, m_ePixelFormat), NameTable_GetNameString(NameTables::PixelFormat, preferredPixelFormat)); if (!ConvertToPixelFormat(preferredPixelFormat)) return false; } // switch to srgb format bool platformSupportsSRGB = (m_eTexturePlatform < TEXTURE_PLATFORM_ES2_NOTC); if (m_propertyList.GetPropertyValueDefaultBool(Properties::SourceSRGB, false) && platformSupportsSRGB) { PIXEL_FORMAT srgbFormat = PixelFormatHelpers::GetSRGBFormat(m_ePixelFormat); if (srgbFormat == PIXEL_FORMAT_UNKNOWN) { Log_ErrorPrintf("TextureGenerator::InternalCompile: No matching SRGB format for %s", NameTable_GetNameString(NameTables::PixelFormat, m_ePixelFormat)); return false; } // just change the image formats for (uint32 i = 0; i < m_nImages; i++) { if (!m_pImages[i].SetPixelFormatWithoutConversion(srgbFormat)) { Log_ErrorPrintf("TextureGenerator::InternalCompile: Failed to change pixel format from %s to %s", NameTable_GetNameString(NameTables::PixelFormat, m_ePixelFormat), NameTable_GetNameString(NameTables::PixelFormat, srgbFormat)); return false; } } // and update the internal format m_ePixelFormat = srgbFormat; } // save to stream { uint32 currentOffset = 0; DF_TEXTURE_HEADER textureHeader; textureHeader.Magic = DF_TEXTURE_HEADER_MAGIC; textureHeader.HeaderSize = sizeof(textureHeader); textureHeader.TextureType = (uint32)m_eTextureType; textureHeader.TexturePlatform = (uint32)m_eTexturePlatform; // properties { const String *pPropertyValue; if ((pPropertyValue = m_propertyList.GetPropertyValuePointer(Properties::Usage)) == NULL || !NameTable_TranslateType(NameTables::TextureUsage, *pPropertyValue, &textureHeader.TextureUsage, true)) { Log_WarningPrintf("Texture Compiler Warning: Unknown value for %s (%s), using default.", Properties::Usage, (pPropertyValue != NULL) ? pPropertyValue->GetCharArray() : "null"); textureHeader.TextureUsage = TEXTURE_USAGE_NONE; } if ((pPropertyValue = m_propertyList.GetPropertyValuePointer(Properties::MaxFilter)) == NULL || !NameTable_TranslateType(NameTables::TextureFilter, *pPropertyValue, &textureHeader.TextureFilter, true)) { Log_WarningPrintf("Texture Compiler Warning: Unknown value for %s (%s), using default.", Properties::MaxFilter, (pPropertyValue != NULL) ? pPropertyValue->GetCharArray() : "null"); textureHeader.TextureFilter = TEXTURE_FILTER_ANISOTROPIC; } if ((pPropertyValue = m_propertyList.GetPropertyValuePointer(Properties::AddressU)) == NULL || !NameTable_TranslateType(NameTables::TextureAddressMode, *pPropertyValue, &textureHeader.AddressModeU, true)) { Log_WarningPrintf("Texture Compiler Warning: Unknown value for %s (%s), using default.", Properties::AddressU, (pPropertyValue != NULL) ? pPropertyValue->GetCharArray() : "null"); textureHeader.AddressModeU = TEXTURE_ADDRESS_MODE_CLAMP; } if ((pPropertyValue = m_propertyList.GetPropertyValuePointer(Properties::AddressV)) == NULL || !NameTable_TranslateType(NameTables::TextureAddressMode, *pPropertyValue, &textureHeader.AddressModeV, true)) { Log_WarningPrintf("Texture Compiler Warning: Unknown value for %s (%s), using default.", Properties::AddressV, (pPropertyValue != NULL) ? pPropertyValue->GetCharArray() : "null"); textureHeader.AddressModeV = TEXTURE_ADDRESS_MODE_CLAMP; } if ((pPropertyValue = m_propertyList.GetPropertyValuePointer(Properties::AddressW)) == NULL || !NameTable_TranslateType(NameTables::TextureAddressMode, *pPropertyValue, &textureHeader.AddressModeW, true)) { Log_WarningPrintf("Texture Compiler Warning: Unknown value for %s (%s), using default.", Properties::AddressW, (pPropertyValue != NULL) ? pPropertyValue->GetCharArray() : "null"); textureHeader.AddressModeW = TEXTURE_ADDRESS_MODE_CLAMP; } } if (m_bHasAlpha) textureHeader.BlendingMode = (isPremultipliedAlpha) ? MATERIAL_BLENDING_MODE_PREMULTIPLIED : MATERIAL_BLENDING_MODE_STRAIGHT; else textureHeader.BlendingMode = MATERIAL_BLENDING_MODE_NONE; textureHeader.MinLOD = 0; textureHeader.MaxLOD = (int32)m_nMipLevels; textureHeader.PixelFormat = (uint32)m_ePixelFormat; textureHeader.ArraySize = m_nArraySize; textureHeader.Width = m_iWidth; textureHeader.Height = m_iHeight; textureHeader.Depth = m_iDepth; textureHeader.MipLevels = m_nMipLevels; textureHeader.ImageCount = m_nImages; pOutputStream->Write2(&textureHeader, sizeof(textureHeader)); currentOffset += sizeof(textureHeader); currentOffset += sizeof(uint32) * m_nImages; // determine and write offsets for (uint32 i = 0; i < m_nImages; i++) { const Image &img = m_pImages[i]; pOutputStream->Write2(&currentOffset, sizeof(currentOffset)); currentOffset += sizeof(DF_TEXTURE_IMAGE_HEADER); currentOffset += img.GetDataSize(); } // write images for (uint32 i = 0; i < m_nImages; i++) { const Image &img = m_pImages[i]; DF_TEXTURE_IMAGE_HEADER imageHeader; imageHeader.Size = img.GetDataSize(); imageHeader.RowPitch = img.GetDataRowPitch(); imageHeader.SlicePitch = img.GetDataSlicePitch(); pOutputStream->Write2(&imageHeader, sizeof(imageHeader)); pOutputStream->Write2(img.GetData(), img.GetDataSize()); } } return !pOutputStream->InErrorState(); } bool TextureGenerator::ImportDDS(const char *fileName, ByteStream *pStream) { DDSReader ddsReader; if (!ddsReader.Open(fileName, pStream) || !ddsReader.LoadAllMipLevels()) { Log_ErrorPrintf("TextureGenerator::ImportDDS: Failed to load DDS file."); return false; } TEXTURE_TYPE textureType; switch (ddsReader.GetType()) { case DDS_TEXTURE_TYPE_1D: textureType = (ddsReader.GetArraySize() > 1) ? TEXTURE_TYPE_1D_ARRAY : TEXTURE_TYPE_1D; break; case DDS_TEXTURE_TYPE_2D: textureType = (ddsReader.GetArraySize() > 1) ? TEXTURE_TYPE_2D_ARRAY : TEXTURE_TYPE_2D; break; case DDS_TEXTURE_TYPE_3D: textureType = TEXTURE_TYPE_3D; break; case DDS_TEXTURE_TYPE_CUBE: textureType = (ddsReader.GetArraySize() > 6) ? TEXTURE_TYPE_CUBE_ARRAY : TEXTURE_TYPE_CUBE; break; default: Log_ErrorPrintf("TextureGenerator::ImportDDS: Invalid type."); return false; } DebugAssert(ddsReader.GetWidth() == 1 || Y_ispow2(ddsReader.GetWidth())); DebugAssert(ddsReader.GetHeight() == 1 || Y_ispow2(ddsReader.GetHeight())); DebugAssert(ddsReader.GetDepth() == 1 || Y_ispow2(ddsReader.GetDepth())); Log_InfoPrintf("TextureGenerator::LoadDDS: Source is a %u x %u x %u image with %u mip levels and %u array textures (%s)", ddsReader.GetWidth(), ddsReader.GetHeight(), ddsReader.GetDepth(), ddsReader.GetNumMipLevels(), ddsReader.GetArraySize(), NameTable_GetNameString(NameTables::PixelFormat, ddsReader.GetPixelFormat())); // create texture if (!Create(textureType, ddsReader.GetPixelFormat(), ddsReader.GetWidth(), ddsReader.GetHeight(), ddsReader.GetDepth(), ddsReader.GetNumMipLevels(), ddsReader.GetArraySize())) { Log_ErrorPrintf("TextureGenerator::ImportDDS: Could not create texture."); return false; } // get pfi const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); DebugAssert(pPixelFormatInfo != NULL); // add images for (uint32 i = 0; i < m_nArraySize; i++) { for (uint32 j = 0; j < m_nMipLevels; j++) { Image &destinationImage = m_pImages[i * m_nMipLevels + j]; const byte *pMipLevelData = ddsReader.GetMipLevelData(i, j); uint32 mipPitch = ddsReader.GetMipPitch(i, j); // get number of rows uint32 rows = destinationImage.GetHeight(); if (pPixelFormatInfo->IsBlockCompressed) rows = Max(rows / pPixelFormatInfo->BlockSize, (uint32)1); if (ddsReader.GetMipSize(i, j) < (mipPitch * rows)) { Log_ErrorPrintf("TextureGenerator::ImportDDS: Invalid mip data size (%u, %u).", i, j); return false; } Y_memcpy_stride(destinationImage.GetData(), destinationImage.GetDataRowPitch(), pMipLevelData, mipPitch, Min(mipPitch, destinationImage.GetDataRowPitch()), rows); } } if (!UncompressImage()) return false; if (!ConvertBGRToRGB()) return false; if (!RemoveAlphaChannelIfOpaque()) return false; return true; } bool TextureGenerator::ImportFromImage(const char *fileName, ByteStream *pStream) { // check for .dds const char *extension = Y_strrchr(fileName, '.'); if (extension != NULL && Y_stricmp(extension, ".dds") == 0) return ImportDDS(fileName, pStream); // find codec ImageCodec *pImageCodec = ImageCodec::GetImageCodecForStream(fileName, pStream); if (pImageCodec == NULL) { Log_ErrorPrintf("TextureGenerator::ImportFromImage: No image codec found."); return false; } Image decodedImage; if (!pImageCodec->DecodeImage(&decodedImage, fileName, pStream)) { Log_ErrorPrintf("TextureGenerator::ImportFromImage: Failed to decode image."); return false; } return ImportFromImage(decodedImage); } bool TextureGenerator::ImportFromImage(const Image &image) { if (!Create(TEXTURE_TYPE_2D, image.GetPixelFormat(), image.GetWidth(), image.GetHeight(), image.GetDepth(), 1)) { Log_ErrorPrintf("TextureGenerator::ImportFromImage: Failed to create texture."); return false; } DebugAssert(m_nImages == 1); m_pImages[0].Copy(image); if (!UncompressImage()) return false; if (!ConvertBGRToRGB()) return false; if (!RemoveAlphaChannelIfOpaque()) return false; return true; } /* bool TextureGenerator::Load2DImage(const char *FileName, ByteStream *pStream) { DebugAssert(m_pImages == NULL); // setup everything m_eTextureType = TEXTURE_TYPE_2D; m_eTextureUsage = TEXTURE_USAGE_NONE; m_eTextureFilter = TEXTURE_FILTER_COUNT; m_ePixelFormat = decodedImage.GetPixelFormat(); m_nMipLevels = 1; m_nArraySize = 1; m_iWidth = decodedImage.GetWidth(); m_iHeight = decodedImage.GetHeight(); m_iDepth = decodedImage.GetDepth(); // set defaults here too, but they'll be replaced m_bHasAlpha = false; m_bHasAlphaLevels = false; // setup image array m_nImages = 1; m_pImages = new Image[m_nImages]; m_pImages[0].Copy(decodedImage); if (!AnalyseImage()) { Log_WarningPrintf("TextureGenerator::Load: Failed to analyse image."); return false; } return true; } */ // Interface BinaryBlob *ResourceCompiler::CompileTexture(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name) { SmallString textureSourceFileName; textureSourceFileName.Format("%s.tex.zip", name); BinaryBlob *pTextureSource = pCallbacks->GetFileContents(textureSourceFileName); if (pTextureSource == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileTexture: Failed to read '%s'", textureSourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pTextureSource->GetDataPointer(), pTextureSource->GetDataSize()); TextureGenerator *pGenerator = new TextureGenerator(); if (!pGenerator->Load(textureSourceFileName, pStream)) { delete pGenerator; pStream->Release(); pTextureSource->Release(); return nullptr; } pStream->Release(); pTextureSource->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream, platform)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Editor/Source/Editor/moc_EditorVectorEditWidget.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorVectorEditWidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorVectorEditWidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorVectorEditWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorVectorEditWidget_t { QByteArrayData data[24]; char stringdata[317]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorVectorEditWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorVectorEditWidget_t qt_meta_stringdata_EditorVectorEditWidget = { { QT_MOC_LITERAL(0, 0, 22), // "EditorVectorEditWidget" QT_MOC_LITERAL(1, 23, 18), // "ValueChangedFloat2" QT_MOC_LITERAL(2, 42, 0), // "" QT_MOC_LITERAL(3, 43, 6), // "float2" QT_MOC_LITERAL(4, 50, 5), // "value" QT_MOC_LITERAL(5, 56, 18), // "ValueChangedFloat3" QT_MOC_LITERAL(6, 75, 6), // "float3" QT_MOC_LITERAL(7, 82, 18), // "ValueChangedFloat4" QT_MOC_LITERAL(8, 101, 6), // "float4" QT_MOC_LITERAL(9, 108, 18), // "ValueChangedString" QT_MOC_LITERAL(10, 127, 16), // "SetNumComponents" QT_MOC_LITERAL(11, 144, 6), // "uint32" QT_MOC_LITERAL(12, 151, 13), // "numComponents" QT_MOC_LITERAL(13, 165, 8), // "SetValue" QT_MOC_LITERAL(14, 174, 1), // "x" QT_MOC_LITERAL(15, 176, 1), // "y" QT_MOC_LITERAL(16, 178, 1), // "z" QT_MOC_LITERAL(17, 180, 1), // "w" QT_MOC_LITERAL(18, 182, 21), // "OnExpandButtonClicked" QT_MOC_LITERAL(19, 204, 20), // "OnPopupPanelXChanged" QT_MOC_LITERAL(20, 225, 20), // "OnPopupPanelYChanged" QT_MOC_LITERAL(21, 246, 20), // "OnPopupPanelZChanged" QT_MOC_LITERAL(22, 267, 20), // "OnPopupPanelWChanged" QT_MOC_LITERAL(23, 288, 28) // "OnPopupPanelNormalizeClicked" }, "EditorVectorEditWidget\0ValueChangedFloat2\0" "\0float2\0value\0ValueChangedFloat3\0" "float3\0ValueChangedFloat4\0float4\0" "ValueChangedString\0SetNumComponents\0" "uint32\0numComponents\0SetValue\0x\0y\0z\0" "w\0OnExpandButtonClicked\0OnPopupPanelXChanged\0" "OnPopupPanelYChanged\0OnPopupPanelZChanged\0" "OnPopupPanelWChanged\0OnPopupPanelNormalizeClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorVectorEditWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 16, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 4, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 94, 2, 0x06 /* Public */, 5, 1, 97, 2, 0x06 /* Public */, 7, 1, 100, 2, 0x06 /* Public */, 9, 1, 103, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 1, 106, 2, 0x0a /* Public */, 13, 4, 109, 2, 0x0a /* Public */, 13, 3, 118, 2, 0x2a /* Public | MethodCloned */, 13, 2, 125, 2, 0x2a /* Public | MethodCloned */, 13, 1, 130, 2, 0x2a /* Public | MethodCloned */, 13, 0, 133, 2, 0x2a /* Public | MethodCloned */, 18, 0, 134, 2, 0x08 /* Private */, 19, 1, 135, 2, 0x08 /* Private */, 20, 1, 138, 2, 0x08 /* Private */, 21, 1, 141, 2, 0x08 /* Private */, 22, 1, 144, 2, 0x08 /* Private */, 23, 0, 147, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, 0x80000000 | 6, 4, QMetaType::Void, 0x80000000 | 8, 4, QMetaType::Void, QMetaType::QString, 4, // slots: parameters QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, QMetaType::Float, QMetaType::Float, QMetaType::Float, QMetaType::Float, 14, 15, 16, 17, QMetaType::Void, QMetaType::Float, QMetaType::Float, QMetaType::Float, 14, 15, 16, QMetaType::Void, QMetaType::Float, QMetaType::Float, 14, 15, QMetaType::Void, QMetaType::Float, 14, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Double, 4, QMetaType::Void, QMetaType::Double, 4, QMetaType::Void, QMetaType::Double, 4, QMetaType::Void, QMetaType::Double, 4, QMetaType::Void, 0 // eod }; void EditorVectorEditWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorVectorEditWidget *_t = static_cast<EditorVectorEditWidget *>(_o); switch (_id) { case 0: _t->ValueChangedFloat2((*reinterpret_cast< const float2(*)>(_a[1]))); break; case 1: _t->ValueChangedFloat3((*reinterpret_cast< const float3(*)>(_a[1]))); break; case 2: _t->ValueChangedFloat4((*reinterpret_cast< const float4(*)>(_a[1]))); break; case 3: _t->ValueChangedString((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 4: _t->SetNumComponents((*reinterpret_cast< uint32(*)>(_a[1]))); break; case 5: _t->SetValue((*reinterpret_cast< float(*)>(_a[1])),(*reinterpret_cast< float(*)>(_a[2])),(*reinterpret_cast< float(*)>(_a[3])),(*reinterpret_cast< float(*)>(_a[4]))); break; case 6: _t->SetValue((*reinterpret_cast< float(*)>(_a[1])),(*reinterpret_cast< float(*)>(_a[2])),(*reinterpret_cast< float(*)>(_a[3]))); break; case 7: _t->SetValue((*reinterpret_cast< float(*)>(_a[1])),(*reinterpret_cast< float(*)>(_a[2]))); break; case 8: _t->SetValue((*reinterpret_cast< float(*)>(_a[1]))); break; case 9: _t->SetValue(); break; case 10: _t->OnExpandButtonClicked(); break; case 11: _t->OnPopupPanelXChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 12: _t->OnPopupPanelYChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 13: _t->OnPopupPanelZChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 14: _t->OnPopupPanelWChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 15: _t->OnPopupPanelNormalizeClicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (EditorVectorEditWidget::*_t)(const float2 & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorVectorEditWidget::ValueChangedFloat2)) { *result = 0; } } { typedef void (EditorVectorEditWidget::*_t)(const float3 & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorVectorEditWidget::ValueChangedFloat3)) { *result = 1; } } { typedef void (EditorVectorEditWidget::*_t)(const float4 & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorVectorEditWidget::ValueChangedFloat4)) { *result = 2; } } { typedef void (EditorVectorEditWidget::*_t)(const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorVectorEditWidget::ValueChangedString)) { *result = 3; } } } } const QMetaObject EditorVectorEditWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorVectorEditWidget.data, qt_meta_data_EditorVectorEditWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorVectorEditWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorVectorEditWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorVectorEditWidget.stringdata)) return static_cast<void*>(const_cast< EditorVectorEditWidget*>(this)); return QWidget::qt_metacast(_clname); } int EditorVectorEditWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 16) qt_static_metacall(this, _c, _id, _a); _id -= 16; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 16) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 16; } return _id; } // SIGNAL 0 void EditorVectorEditWidget::ValueChangedFloat2(const float2 & _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void EditorVectorEditWidget::ValueChangedFloat3(const float3 & _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void EditorVectorEditWidget::ValueChangedFloat4(const float4 & _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void EditorVectorEditWidget::ValueChangedString(const QString & _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ResourceCompiler/ObjectTemplateManager.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "ResourceCompiler/ResourceCompiler.h" #include "YBaseLib/XMLReader.h" Log_SetChannel(ObjectTemplate); static const char *OBJECT_TEMPLATE_BASE_PATH = "resources/engine/object_templates"; ObjectTemplateManager::ObjectTemplateManager() : m_allTemplatesLoaded(false) { } ObjectTemplateManager::~ObjectTemplateManager() { for (StorageMap::Iterator itr = m_templates.Begin(); !itr.AtEnd(); itr.Forward()) delete itr->Value; } const ObjectTemplate *ObjectTemplateManager::GetObjectTemplate(const char *typeName) { const StorageMap::Member *pMember = m_templates.Find(typeName); if (pMember != nullptr) return pMember->Value; // skip loading if everything is already loaded if (m_allTemplatesLoaded) return nullptr; // try a load first ObjectTemplate *pTemplate = LoadObjectTemplate(typeName); if (pTemplate == nullptr) { // load failed, insert a null reference Log_ErrorPrintf("ObjectTemplateManager::GetObjectTemplate: Failed to load template for type '%s'", typeName); m_templates.Insert(typeName, pTemplate); return nullptr; } // store it first // this assert is here in case the child class reloaded this class DebugAssert(m_templates.Find(pTemplate->GetTypeName()) == nullptr); m_templates.Insert(pTemplate->GetTypeName(), pTemplate); return pTemplate; } const ObjectTemplate *ObjectTemplateManager::GetObjectTemplate(ResourceCompilerCallbacks *pCallbacks, const char *typeName) { const StorageMap::Member *pMember = m_templates.Find(typeName); if (pMember != nullptr) return pMember->Value; // skip loading if everything is already loaded if (m_allTemplatesLoaded) return nullptr; // try a load first ObjectTemplate *pTemplate = LoadObjectTemplate(pCallbacks, typeName); if (pTemplate == nullptr) { // load failed, insert a null reference Log_ErrorPrintf("ObjectTemplateManager::GetObjectTemplate: Failed to load template for type '%s'", typeName); m_templates.Insert(typeName, pTemplate); return nullptr; } // store it first // this assert is here in case the child class reloaded this class DebugAssert(m_templates.Find(pTemplate->GetTypeName()) == nullptr); m_templates.Insert(pTemplate->GetTypeName(), pTemplate); return pTemplate; } ObjectTemplate *ObjectTemplateManager::LoadObjectTemplate(const char *typeName) { PathString fileName; fileName.Format("%s/%s.xml", OBJECT_TEMPLATE_BASE_PATH, typeName); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return nullptr; ObjectTemplate *pTemplate = new ObjectTemplate(); if (!pTemplate->LoadFromStream(fileName, pStream)) { delete pTemplate; pStream->Release(); return nullptr; } // this assert is here in case the child class reloaded this class pStream->Release(); return pTemplate; } ObjectTemplate *ObjectTemplateManager::LoadObjectTemplate(ResourceCompilerCallbacks *pCallbacks, const char *typeName) { PathString fileName; fileName.Format("%s/%s.xml", OBJECT_TEMPLATE_BASE_PATH, typeName); AutoReleasePtr<BinaryBlob> pBlob = pCallbacks->GetFileContents(fileName); if (pBlob == nullptr) return nullptr; AutoReleasePtr<ByteStream> pStream = pBlob->CreateReadOnlyStream(); ObjectTemplate *pTemplate = new ObjectTemplate(); if (!pTemplate->LoadFromStream(fileName, pStream)) { delete pTemplate; pStream->Release(); return nullptr; } // this assert is here in case the child class reloaded this class pStream->Release(); return pTemplate; } bool ObjectTemplateManager::LoadAllTemplates() { SmallString entityTypeName; // search for templates FileSystem::FindResultsArray findResults; g_pVirtualFileSystem->FindFiles(OBJECT_TEMPLATE_BASE_PATH, "*.xml", FILESYSTEM_FIND_FILES, &findResults); // no templates? if (findResults.GetSize() == 0) { Log_WarningPrintf("ObjectTemplate::LoadEntityTemplates: No templates found!"); return false; } // go through find results for (uint32 i = 0; i < findResults.GetSize(); i++) { FILESYSTEM_FIND_DATA &findData = findResults[i]; // derive the type name from the filename const char *posExtensionStart = Y_strrchr(findData.FileName, '.'); const char *posFileNameStart = Y_strrchr(findData.FileName, '/'); if (posExtensionStart == nullptr || posFileNameStart == nullptr || posExtensionStart <= posFileNameStart) { Log_ErrorPrintf("ObjectTemplate::LoadEntityTemplates: Could not open derive type name from file name '%s'", findData.FileName); return false; } // work out entity type name entityTypeName.Clear(); entityTypeName.AppendSubString(posFileNameStart + 1, 0, (int32)(posExtensionStart - posFileNameStart - 1)); // does it already exist? StorageMap::Member *pExistingMember = m_templates.Find(entityTypeName); if (pExistingMember != nullptr) { // if it was loaded as a base class, and failed, we should've bailed out at the below branch. DebugAssert(pExistingMember->Value != nullptr); continue; } // open stream ByteStream *pStream = g_pVirtualFileSystem->OpenFile(findData.FileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_WarningPrintf("ObjectTemplate::LoadEntityTemplates: Could not open template file '%s'", findData.FileName); continue; } ObjectTemplate *pTemplate = new ObjectTemplate(); if (!pTemplate->LoadFromStream(findData.FileName, pStream)) { Log_ErrorPrintf("ObjectTemplate::LoadEntityTemplates: Failed to load template '%s'", findData.FileName); delete pTemplate; pStream->Release(); return false; } // can lose the strema now pStream->Release(); // should match the filename DebugAssert(entityTypeName.CompareInsensitive(pTemplate->GetTypeName())); // insert into map m_templates.Insert(pTemplate->GetTypeName(), pTemplate); } Log_InfoPrintf("ObjectTemplateManager::LoadAllTemplates: Loaded %u templates.", m_templates.GetMemberCount()); m_allTemplatesLoaded = true; return true; } <file_sep>/Engine/Source/Renderer/VertexBufferBindingArray.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/Renderer.h" VertexBufferBindingArray::VertexBufferBindingArray() { Y_memzero(m_pVertexBuffers, sizeof(m_pVertexBuffers)); Y_memzero(m_iVertexBufferOffsets, sizeof(m_iVertexBufferOffsets)); Y_memzero(m_iVertexBufferStrides, sizeof(m_iVertexBufferStrides)); m_nActiveBuffers = 0; } VertexBufferBindingArray::VertexBufferBindingArray(const VertexBufferBindingArray &vbb) { Y_memzero(m_pVertexBuffers, sizeof(m_pVertexBuffers)); Y_memzero(m_iVertexBufferOffsets, sizeof(m_iVertexBufferOffsets)); Y_memzero(m_iVertexBufferStrides, sizeof(m_iVertexBufferStrides)); for (uint32 i = 0; i < vbb.m_nActiveBuffers; i++) { if ((m_pVertexBuffers[i] = vbb.m_pVertexBuffers[i]) != NULL) m_pVertexBuffers[i]->AddRef(); m_iVertexBufferOffsets[i] = vbb.m_iVertexBufferOffsets[i]; m_iVertexBufferStrides[i] = vbb.m_iVertexBufferStrides[i]; } m_nActiveBuffers = vbb.m_nActiveBuffers; } VertexBufferBindingArray::~VertexBufferBindingArray() { for (uint32 i = 0; i < m_nActiveBuffers; i++) { if (m_pVertexBuffers[i] != NULL) m_pVertexBuffers[i]->Release(); } } void VertexBufferBindingArray::SetBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { uint32 i; DebugAssert(bufferIndex < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS); if (m_pVertexBuffers[bufferIndex] != pVertexBuffer) { if (m_pVertexBuffers[bufferIndex] != NULL) m_pVertexBuffers[bufferIndex]->Release(); if ((m_pVertexBuffers[bufferIndex] = pVertexBuffer) != NULL) m_pVertexBuffers[bufferIndex]->AddRef(); } if (pVertexBuffer != NULL) { m_iVertexBufferOffsets[bufferIndex] = offset; m_iVertexBufferStrides[bufferIndex] = stride; } else { m_iVertexBufferOffsets[bufferIndex] = 0; m_iVertexBufferStrides[bufferIndex] = 0; } m_nActiveBuffers = 0; for (i = 0; i < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS; i++) { if (m_pVertexBuffers[i] != NULL) m_nActiveBuffers = i + 1; } } void VertexBufferBindingArray::SetDebugName(const char *debugName) { for (uint32 i = 0; i < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS; i++) { if (m_pVertexBuffers[i] != NULL) m_pVertexBuffers[i]->SetDebugName(debugName); } } VertexBufferBindingArray &VertexBufferBindingArray::operator=(const VertexBufferBindingArray &vbb) { for (uint32 i = 0; i < m_nActiveBuffers; i++) { if (m_pVertexBuffers[i] != NULL) m_pVertexBuffers[i]->Release(); } Y_memzero(m_pVertexBuffers, sizeof(m_pVertexBuffers)); Y_memzero(m_iVertexBufferOffsets, sizeof(m_iVertexBufferOffsets)); Y_memzero(m_iVertexBufferStrides, sizeof(m_iVertexBufferStrides)); for (uint32 i = 0; i < vbb.m_nActiveBuffers; i++) { if ((m_pVertexBuffers[i] = vbb.m_pVertexBuffers[i]) != NULL) m_pVertexBuffers[i]->AddRef(); m_iVertexBufferOffsets[i] = vbb.m_iVertexBufferOffsets[i]; m_iVertexBufferStrides[i] = vbb.m_iVertexBufferStrides[i]; } m_nActiveBuffers = vbb.m_nActiveBuffers; return *this; } void VertexBufferBindingArray::BindBuffers(GPUCommandList *pCommandList) const { pCommandList->SetVertexBuffers(0, m_nActiveBuffers, m_pVertexBuffers, m_iVertexBufferOffsets, m_iVertexBufferStrides); } void VertexBufferBindingArray::Clear() { for (uint32 i = 0; i < m_nActiveBuffers; i++) { if (m_pVertexBuffers[i] != NULL) m_pVertexBuffers[i]->Release(); } Y_memzero(m_pVertexBuffers, sizeof(m_pVertexBuffers)); Y_memzero(m_iVertexBufferOffsets, sizeof(m_iVertexBufferOffsets)); Y_memzero(m_iVertexBufferStrides, sizeof(m_iVertexBufferStrides)); m_nActiveBuffers = 0; } <file_sep>/Engine/Source/ResourceCompiler/ShaderGraph.h #pragma once #include "Engine/Common.h" #include "ResourceCompiler/ShaderGraphNode.h" #include "ResourceCompiler/ShaderGraphSchema.h" class XMLReader; class XMLWriter; class ShaderGraph { public: ShaderGraph(); ~ShaderGraph(); const ShaderGraphSchema *GetSchema() const { return m_pSchema; } const uint32 GetNextNodeId() const { return m_iNextNodeId; } const ShaderGraphNode *GetShaderInputsNode() const { return m_pShaderInputsNode; } const ShaderGraphNode *GetShaderOutputsNode() const { return m_pShaderOutputsNode; } const uint32 GetNodeCount() const { return m_Nodes.GetSize(); } const ShaderGraphNode *GetNodeByID(uint32 NodeID) const; const ShaderGraphNode *GetNodeByArrayIndex(uint32 ArrayIndex) const { DebugAssert(ArrayIndex < m_Nodes.GetSize()); return m_Nodes[ArrayIndex]; } const ShaderGraphNode *GetNodeByName(const char *Name) const; ShaderGraphNode *GetNodeByID(uint32 NodeID); ShaderGraphNode *GetNodeByArrayIndex(uint32 ArrayIndex) { DebugAssert(ArrayIndex < m_Nodes.GetSize()); return m_Nodes[ArrayIndex]; } ShaderGraphNode *GetNodeByName(const char *Name); bool AddNode(ShaderGraphNode *pNode); bool RemoveNode(ShaderGraphNode *pNode); bool AddLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle); bool RemoveLink(ShaderGraphNode *pTargetNode, uint32 InputIndex); bool RemoveLink(ShaderGraphNodeInput *pInput); bool Create(const ShaderGraphSchema *pSchema); bool LoadFromXML(const ShaderGraphSchema *pSchema, XMLReader &xmlReader); bool SaveToXML(XMLWriter &xmlWriter) const; // Type registration. static void RegisterBuiltinTypes(); // helper functions static bool GetValueSwizzleFromString(SHADER_GRAPH_VALUE_SWIZZLE *pSwizzle, const char *str); static bool GetStringForValueSwizzle(char outString[5], SHADER_GRAPH_VALUE_SWIZZLE swizzle); static uint32 GetValueSwizzleComponentCount(SHADER_GRAPH_VALUE_SWIZZLE swizzle); static uint32 GetValueSwizzleComponent(SHADER_GRAPH_VALUE_SWIZZLE swizzle, uint32 index) { return (swizzle >> ((3 - index) * 8)) & 0xFF; } protected: bool ParseXMLNodes(XMLReader &xmlReader); bool ParseXMLLinks(XMLReader &xmlReader); const ShaderGraphSchema *m_pSchema; typedef PODArray<ShaderGraphNode *> NodeArray; NodeArray m_Nodes; uint32 m_iNextNodeId; typedef PODArray<ShaderGraphNodeInput *> LinkArray; LinkArray m_Links; // schema nodes ShaderGraphNode *m_pShaderInputsNode; ShaderGraphNode *m_pShaderOutputsNode; private: ShaderGraph(const ShaderGraph &); ShaderGraph &operator=(const ShaderGraph &); }; <file_sep>/Editor/Source/Editor/MapEditor/EditorMapEntity.h #pragma once #include "Editor/Common.h" class RenderWorld; class MapSourceEntityData; class MapSourceEntityComponent; class ObjectTemplate; class EditorMap; class EditorVisualDefinition; class EditorVisualInstance; class EditorMapEntity { public: ~EditorMapEntity(); const uint32 GetArrayIndex() const { return m_arrayIndex; } const ObjectTemplate *GetTemplate() const { return m_pTemplate; } const EditorVisualDefinition *GetVisualDefinition() const { return m_pVisualDefinition; } const MapSourceEntityData *GetEntityData() const { return m_pEntityData; } const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } const float3 &GetPosition() const { return m_position; } const Quaternion &GetRotation() const { return m_rotation; } const float3 &GetScale() const { return m_scale; } const bool IsSelected() const { return m_selected; } // helpers const bool IsBrush() const; const bool IsEntity() const; // creation static EditorMapEntity *Create(EditorMap *pMap, uint32 arrayIndex, MapSourceEntityData *pEntityData); // visual creation/deletion const EditorVisualInstance *GetVisualInstance() const { return m_pVisualInstance; } EditorVisualInstance *GetVisualInstance() { return m_pVisualInstance; } const bool IsVisualCreated() const { return m_visualsCreated; } void CreateVisual(); void DeleteVisual(); // property access String GetEntityPropertyValue(const char *propertyName) const; bool SetEntityPropertyValue(const char *propertyName, const char *propertyValue); // transform access void SetPosition(const float3 &position); void SetRotation(const Quaternion &rotation); void SetScale(const float3 &scale); // events void OnPropertyModified(const char *propertyName, const char *propertyValue); void OnSelectedStateChanged(bool selected); void OnComponentSelectedStateChanged(uint32 index, bool selected); // components const ObjectTemplate *GetComponentTemplate(uint32 index) const; const MapSourceEntityComponent *GetComponentData(uint32 index) const; const uint32 GetComponentCount() const { return m_components.GetSize(); } String GetComponentPropertyValue(uint32 index, const char *propertyName) const; void SetComponentPropertyValue(uint32 index, const char *propertyName, const char *propertyValue); int32 CreateComponent(const char *componentTypeName, const char *componentName = nullptr); int32 CreateComponent(const ObjectTemplate *pTemplate, const char *componentName = nullptr); void RemoveComponent(uint32 index); protected: struct ComponentData { const ObjectTemplate *pTemplate; const EditorVisualDefinition *pVisualDefinition; MapSourceEntityComponent *pData; EditorVisualInstance *pVisual; }; EditorMapEntity(EditorMap *pMap, uint32 arrayIndex, const ObjectTemplate *pTemplate, const EditorVisualDefinition *pVisualDefinition, MapSourceEntityData *pEntityData); void InternalCreateComponentVisual(ComponentData *data); uint32 InternalCreateComponent(const ObjectTemplate *pTemplate, MapSourceEntityComponent *pComponentData); EditorMap *m_pMap; uint32 m_arrayIndex; const ObjectTemplate *m_pTemplate; const EditorVisualDefinition *m_pVisualDefinition; MapSourceEntityData *m_pEntityData; EditorVisualInstance *m_pVisualInstance; bool m_visualsCreated; // bounding box of all visuals AABox m_boundingBox; Sphere m_boundingSphere; // we track position, rotation, scale for the purpose of the widget float3 m_position; Quaternion m_rotation; float3 m_scale; bool m_selected; // component data MemArray<ComponentData> m_components; }; <file_sep>/Engine/Source/Engine/Camera.h #pragma once #include "Engine/Common.h" struct RENDERER_VIEWPORT; enum CAMERA_PROJECTION_TYPE { CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC, CAMERA_PROJECTION_TYPE_PERSPECTIVE, CAMERA_PROJECTION_TYPE_COUNT, }; class Camera { public: Camera(); Camera(const Camera &camera); Camera(const float4x4 &viewMatrix); // all types const float3 &GetPosition() const { return m_position; } const Quaternion &GetRotation() const { return m_rotation; } const CAMERA_PROJECTION_TYPE GetProjectionType() const { return m_projectionType; } const float GetNearPlaneDistance() const { return m_nearPlaneDistance; } const float GetFarPlaneDistance() const { return m_farPlaneDistance; } // object culling distance const float GetObjectCullDistance() const { return m_objectCullDistance; } void SetObjectCullDistance(float distance) { m_objectCullDistance = distance; } void SetObjectCullDistanceFromNearFar() { m_objectCullDistance = m_farPlaneDistance + m_nearPlaneDistance; } // ortho-specific const float GetOrthoWindowLeft() const { return m_orthoWindowLeft; } const float GetOrthoWindowRight() const { return m_orthoWindowRight; } const float GetOrthoWindowBottom() const { return m_orthoWindowBottom; } const float GetOrthoWindowTop() const { return m_orthoWindowTop; } // perspective-specific const float GetPerspectiveFieldOfView() const { return m_perspectiveFieldOfView; } const float GetPerspectiveAspect() const { return m_perspectiveAspect; } // cache -- replace with dirty flags at some point? const Frustum &GetFrustum() const { return m_frustum; } const float4x4 &GetViewMatrix() const { return m_viewMatrix; } const float4x4 &GetProjectionMatrix() const { return m_projectionMatrix; } const float4x4 &GetInverseViewMatrix() const { return m_inverseViewMatrix; } const float4x4 &GetInverseProjectionMatrix() const { return m_inverseProjectionMatrix; } const float4x4 &GetViewProjectionMatrix() const { return m_viewProjectionMatrix; } const float4x4 &GetInverseViewProjectionMatrix() const { return m_inverseViewProjectionMatrix; } // determined on-the-fly float3 CalculateViewDirection() const; float3 CalculateUpDirection() const; // calculate the depth or distance to a point in world space float CalculateDepthToPoint(const float3 &point) const; // calculate the depth to any of the planes in a box in world space float CalculateDepthToBox(const AABox &box) const; // setters void SetPosition(const float3 &position); void SetRotation(const Quaternion &rotation); // setting a view matrix assumes that the matrix coming in is still using a z-up convention void SetViewMatrix(const float4x4 &viewMatrix); // look at a specific point void LookAt(const float3 &eye, const float3 &target, const float3 &upVector); // look in a direction, keeping position intact void LookDirection(const float3 &direction, const float3 &upVector); // projection setup void SetProjectionType(CAMERA_PROJECTION_TYPE type); void SetNearFarPlaneDistances(float nearDistance, float farDistance); void SetNearPlaneDistance(float distance); void SetFarPlaneDistance(float distance); // set an override projection matrix void SetProjectionMatrix(const float4x4 &projectionMatrix); // get a biased projection matrix, *will* ignore any custom projection matrix set float4x4 GetBiasedProjectionMatrix(float amount) const; // perspective -- field of view is in degrees void SetPerspectiveFieldOfView(float fieldOfView); void SetPerspectiveAspect(float aspect); void SetPerspectiveAspect(float width, float height); // orthographic void SetOrthographicWindow(float left, float right, float bottom, float top); void SetOrthographicWindow(float width, float height); // get a picking ray Ray GetPickRay(float x, float y, const RENDERER_VIEWPORT *pViewport) const; // project a world coordinate to window coordinates float3 Project(const float3 &worldCoordindates, const RENDERER_VIEWPORT *pViewport) const; // unproject window coordinates to world coordinates float3 Unproject(const float3 &windowCoordinates, const RENDERER_VIEWPORT *pViewport) const; // operators Camera &operator=(const Camera &camera); protected: // update view matrix and associated variables void UpdateViewMatrix(); // update projection matrix and associated variables void UpdateProjectionMatrix(); // update anything affected by view or projection changes void UpdateFrustum(); // common to all float3 m_position; Quaternion m_rotation; // object maximum render distance float m_objectCullDistance; // projection CAMERA_PROJECTION_TYPE m_projectionType; float m_nearPlaneDistance; float m_farPlaneDistance; // orthographic float m_orthoWindowLeft; float m_orthoWindowRight; float m_orthoWindowTop; float m_orthoWindowBottom; // perspective float m_perspectiveFieldOfView; float m_perspectiveAspect; // cache Frustum m_frustum; float4x4 m_viewMatrix; float4x4 m_projectionMatrix; float4x4 m_inverseViewMatrix; float4x4 m_inverseProjectionMatrix; float4x4 m_viewProjectionMatrix; float4x4 m_inverseViewProjectionMatrix; public: // common stuff static const float4x4 &GetWorldToCameraCoordinateSystemTransform(); static const float4x4 &GetCameraToWorldCoordinateSystemTransform(); static float3 TransformFromWorldToCameraCoordinateSystem(const float3 &v); static float3 TransformFromCameraToWorldCoordinateSystem(const float3 &v); }; <file_sep>/Engine/Source/Engine/BlockPalette.h #pragma once #include "Engine/Common.h" #include "Engine/Material.h" #include "Engine/Texture.h" #include "Engine/StaticMesh.h" #define BLOCK_MESH_MAX_BLOCK_TYPES 0xFF enum BLOCK_MESH_BLOCK_TYPE_FLAG { BLOCK_MESH_BLOCK_TYPE_FLAG_SOLID = (1 << 0), BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS = (1 << 2), BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME = (1 << 3), BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_UNTILEABLE = (1 << 4), // autogenerated flags BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCK_LIGHT_EMITTER = (1 << 27), BLOCK_MESH_BLOCK_TYPE_FLAG_POINT_LIGHT_EMITTER = (1 << 28), BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE = (1 << 29), BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY = (1 << 30), BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE = (1 << 31), }; enum BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE { BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_COUNT, }; enum BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE { BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR, BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE, BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL, BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT, }; enum BLOCK_MESH_TEXTURE_BLENDING { BLOCK_MESH_TEXTURE_BLENDING_NONE, BLOCK_MESH_TEXTURE_BLENDING_MASKED, BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT, BLOCK_MESH_TEXTURE_BLENDING_COUNT, }; enum BLOCK_MESH_TEXTURE_EFFECT { BLOCK_MESH_TEXTURE_EFFECT_NONE, BLOCK_MESH_TEXTURE_EFFECT_SCROLL, BLOCK_MESH_TEXTURE_EFFECT_ANIMATION, BLOCK_MESH_TEXTURE_EFFECT_COUNT, }; class BlockPaletteGenerator; class BlockPalette : public Resource { public: struct BlockType { bool IsAllocated; uint32 BlockTypeIndex; String Name; uint32 Flags; BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE ShapeType; struct VisualParameters { BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE Type; uint32 MaterialIndex; uint32 Color; float3 MinUV; float3 MaxUV; float4 AtlasUVRange; }; struct CubeShapeFace { VisualParameters Visual; }; struct SlabShape { float Height; }; struct PlaneShape { VisualParameters Visual; // these are 0-1 factors float OffsetX; float OffsetY; float Width; float Height; // in degrees float BaseRotation; uint32 RepeatCount; float RepeatRotation; }; struct MeshShape { uint32 MeshIndex; float Scale; }; struct BlockLightEmitter { uint32 Radius; }; struct PointLightEmitter { float3 Offset; uint32 Color; float Brightness; float Range; float Falloff; }; CubeShapeFace CubeShapeFaces[CUBE_FACE_COUNT]; SlabShape SlabShapeSettings; PlaneShape PlaneShapeSettings; MeshShape MeshShapeSettings; BlockLightEmitter BlockLightEmitterSettings; PointLightEmitter PointLightEmitterSettings; }; public: BlockPalette(); ~BlockPalette(); // serialization bool Load(const char *FileName, ByteStream *pStream); // accessors const BlockPalette::BlockType *GetBlockType(uint32 i) const { DebugAssert(i < BLOCK_MESH_MAX_BLOCK_TYPES); return &m_BlockTypes[i]; } const Texture *GetTexture(uint32 i) const { DebugAssert(i < m_textures.GetSize()); return m_textures[i]; } const uint32 GetTextureCount() const { return m_textures.GetSize(); } const Material *GetMaterial(uint32 i) const { DebugAssert(i < m_materials.GetSize()); return m_materials[i]; } const uint32 GetMaterialCount() const { return m_materials.GetSize(); } const StaticMesh *GetMesh(uint32 i) const { DebugAssert(i < m_meshes.GetSize()); return m_meshes[i]; } const uint32 GetMeshCount() const { return m_meshes.GetSize(); } // find block type by name const BlockPalette::BlockType *GetBlockTypeByName(const char *name) const; // gpu resources bool CreateGPUResources() const; void ReleaseGPUResources() const; private: BlockPalette::BlockType m_BlockTypes[BLOCK_MESH_MAX_BLOCK_TYPES]; PODArray<const Texture *> m_textures; PODArray<const Material *> m_materials; PODArray<const StaticMesh *> m_meshes; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12LinearHeaps.h #pragma once #include "D3D12Renderer/D3D12Common.h" class D3D12LinearBufferHeap { // @TODO maybe use something like a circular buffer here? public: static D3D12LinearBufferHeap *Create(ID3D12Device *pDevice, uint32 size); ~D3D12LinearBufferHeap(); ID3D12Resource *GetResource() const { return m_pResource; } uint32 GetSize() const { return m_size; } void *GetPointer(uint32 offset) const; D3D12_GPU_VIRTUAL_ADDRESS GetGPUAddress(uint32 offset) const; bool Allocate(uint32 size, uint32 *pOutOffset); bool AllocateAligned(uint32 size, uint32 alignment, uint32 *pOutOffset); bool Reset(bool resetPosition); void Commit(); private: D3D12LinearBufferHeap(ID3D12Resource *pResource, byte *pMappedPointer, uint32 size); D3D12_GPU_VIRTUAL_ADDRESS m_gpuAddress; ID3D12Resource *m_pResource; byte *m_pMappedPointer; uint32 m_size; uint32 m_position; uint32 m_resetPosition; }; class D3D12LinearDescriptorHeap { public: static D3D12LinearDescriptorHeap *Create(ID3D12Device *pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 count); ~D3D12LinearDescriptorHeap(); ID3D12DescriptorHeap *GetD3DHeap() const { return m_pD3DHeap; } uint32 GetSize() const { return m_size; } bool Allocate(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle); void Reset(); private: D3D12LinearDescriptorHeap(ID3D12DescriptorHeap *pHeap, uint32 count, uint32 incrementSize); ID3D12DescriptorHeap *m_pD3DHeap; D3D12_CPU_DESCRIPTOR_HANDLE m_cpuHandleStart; D3D12_GPU_DESCRIPTOR_HANDLE m_gpuHandleStart; uint32 m_size; uint32 m_position; uint32 m_incrementSize; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUShaderProgram.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUShaderProgram.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUCommandList.h" #include "D3D12Renderer/D3D12Helpers.h" #include "D3D12Renderer/D3D12CVars.h" #include "Renderer/ShaderConstantBuffer.h" #include "Engine/EngineCVars.h" #include "Core/ThirdParty/MurmurHash3.h" Log_SetChannel(D3D12RenderBackend); // lookup table for types static const DXGI_FORMAT s_GPUVertexElementTypeToDXGIFormat[GPU_VERTEX_ELEMENT_TYPE_COUNT] = { DXGI_FORMAT_R8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE DXGI_FORMAT_R8G8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE2 DXGI_FORMAT_R8G8B8A8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE4 DXGI_FORMAT_R8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE DXGI_FORMAT_R8G8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE2 DXGI_FORMAT_R8G8B8A8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE4 DXGI_FORMAT_R16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF DXGI_FORMAT_R16G16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF2 DXGI_FORMAT_R16G16B16A16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF4 DXGI_FORMAT_R32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT DXGI_FORMAT_R32G32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT2 DXGI_FORMAT_R32G32B32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT3 DXGI_FORMAT_R32G32B32A32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT4 DXGI_FORMAT_R32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT DXGI_FORMAT_R32G32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT2 DXGI_FORMAT_R32G32B32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT3 DXGI_FORMAT_R32G32B32A32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT4 DXGI_FORMAT_R32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT DXGI_FORMAT_R32G32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT2 DXGI_FORMAT_R32G32B32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT3 DXGI_FORMAT_R32G32B32A32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT4 DXGI_FORMAT_R8G8B8A8_SNORM, // GPU_VERTEX_ELEMENT_TYPE_SNORM4 DXGI_FORMAT_R8G8B8A8_UNORM, // GPU_VERTEX_ELEMENT_TYPE_UNORM4 }; D3D12GPUShaderProgram::D3D12GPUShaderProgram(D3D12GPUDevice *pDevice) : m_pDevice(pDevice) { m_pDevice->AddRef(); Y_memzero(m_pStageByteCode, sizeof(m_pStageByteCode)); } D3D12GPUShaderProgram::~D3D12GPUShaderProgram() { for (uint32 i = 0; i < m_pipelineStates.GetSize(); i++) { if (m_pipelineStates[i].pPipelineState != nullptr) m_pDevice->ScheduleResourceForDeletion(m_pipelineStates[i].pPipelineState); } for (uint32 i = 0; i < countof(m_pStageByteCode); i++) { if (m_pStageByteCode[i] != nullptr) m_pStageByteCode[i]->Release(); } m_pDevice->Release(); } ID3D12PipelineState *D3D12GPUShaderProgram::GetPipelineState(const PipelineStateKey *pKey) { // get keys uint32 key1; uint32 key2[4]; MurmurHash3_x86_32(pKey, sizeof(*pKey), 0x3B9AC9FC, &key1); #ifdef Y_CPU_X86 MurmurHash3_x86_128(pKey, sizeof(*pKey), 0xFE54B014, key2); #else MurmurHash3_x64_128(pKey, sizeof(*pKey), 0<KEY>, key2); #endif // search the list m_pDevice->GetShaderPipelineStateLock()->LockShared(); for (uint32 i = 0; i < m_pipelineStates.GetSize(); i++) { const PipelineState *ps = &m_pipelineStates[i]; if (ps->Key1 > key1) break; else if (ps->Key1 < key1) continue; if (Y_memcmp(ps->Key2, key2, sizeof(key2)) == 0) { m_pDevice->GetShaderPipelineStateLock()->UnlockShared(); return ps->pPipelineState; } } // move to a write lock m_pDevice->GetShaderPipelineStateLock()->UpgradeSharedLockToExclusive(); // ensure another thread hasn't created the pipeline in the meantime for (uint32 i = 0; i < m_pipelineStates.GetSize(); i++) { const PipelineState *ps = &m_pipelineStates[i]; if (ps->Key1 > key1) break; else if (ps->Key1 < key1) continue; if (Y_memcmp(ps->Key2, key2, sizeof(key2)) == 0) { m_pDevice->GetShaderPipelineStateLock()->UnlockExclusive(); return ps->pPipelineState; } } // fill new details D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineDesc; Y_memzero(&pipelineDesc, sizeof(pipelineDesc)); pipelineDesc.pRootSignature = m_pDevice->GetLegacyGraphicsRootSignature(); // stage bytecode if (m_pStageByteCode[SHADER_PROGRAM_STAGE_VERTEX_SHADER] != nullptr) { pipelineDesc.VS.pShaderBytecode = m_pStageByteCode[SHADER_PROGRAM_STAGE_VERTEX_SHADER]->GetDataPointer(); pipelineDesc.VS.BytecodeLength = m_pStageByteCode[SHADER_PROGRAM_STAGE_VERTEX_SHADER]->GetDataSize(); } else { pipelineDesc.VS.pShaderBytecode = nullptr; pipelineDesc.VS.BytecodeLength = 0; } if (m_pStageByteCode[SHADER_PROGRAM_STAGE_HULL_SHADER] != nullptr) { pipelineDesc.HS.pShaderBytecode = m_pStageByteCode[SHADER_PROGRAM_STAGE_HULL_SHADER]->GetDataPointer(); pipelineDesc.HS.BytecodeLength = m_pStageByteCode[SHADER_PROGRAM_STAGE_HULL_SHADER]->GetDataSize(); } else { pipelineDesc.HS.pShaderBytecode = nullptr; pipelineDesc.HS.BytecodeLength = 0; } if (m_pStageByteCode[SHADER_PROGRAM_STAGE_DOMAIN_SHADER] != nullptr) { pipelineDesc.DS.pShaderBytecode = m_pStageByteCode[SHADER_PROGRAM_STAGE_DOMAIN_SHADER]->GetDataPointer(); pipelineDesc.DS.BytecodeLength = m_pStageByteCode[SHADER_PROGRAM_STAGE_DOMAIN_SHADER]->GetDataSize(); } else { pipelineDesc.DS.pShaderBytecode = nullptr; pipelineDesc.DS.BytecodeLength = 0; } if (m_pStageByteCode[SHADER_PROGRAM_STAGE_GEOMETRY_SHADER] != nullptr) { pipelineDesc.GS.pShaderBytecode = m_pStageByteCode[SHADER_PROGRAM_STAGE_GEOMETRY_SHADER]->GetDataPointer(); pipelineDesc.GS.BytecodeLength = m_pStageByteCode[SHADER_PROGRAM_STAGE_GEOMETRY_SHADER]->GetDataSize(); } else { pipelineDesc.GS.pShaderBytecode = nullptr; pipelineDesc.GS.BytecodeLength = 0; } if (m_pStageByteCode[SHADER_PROGRAM_STAGE_PIXEL_SHADER] != nullptr) { pipelineDesc.PS.pShaderBytecode = m_pStageByteCode[SHADER_PROGRAM_STAGE_PIXEL_SHADER]->GetDataPointer(); pipelineDesc.PS.BytecodeLength = m_pStageByteCode[SHADER_PROGRAM_STAGE_PIXEL_SHADER]->GetDataSize(); } else { pipelineDesc.PS.pShaderBytecode = nullptr; pipelineDesc.PS.BytecodeLength = 0; } // streamout Y_memzero(&pipelineDesc.StreamOutput, sizeof(pipelineDesc.StreamOutput)); // states Y_memcpy(&pipelineDesc.BlendState, &pKey->BlendState, sizeof(pipelineDesc.BlendState)); Y_memcpy(&pipelineDesc.RasterizerState, &pKey->RasterizerState, sizeof(pipelineDesc.RasterizerState)); Y_memcpy(&pipelineDesc.DepthStencilState, &pKey->DepthStencilState, sizeof(pipelineDesc.DepthStencilState)); pipelineDesc.InputLayout.NumElements = m_vertexAttributes.GetSize(); pipelineDesc.InputLayout.pInputElementDescs = m_vertexAttributes.GetBasePointer(); pipelineDesc.SampleMask = 0xFFFFFFFF; pipelineDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF; pipelineDesc.PrimitiveTopologyType = pKey->PrimitiveTopologyType; pipelineDesc.NumRenderTargets = pKey->RenderTargetCount; for (uint32 i = 0; i < pKey->RenderTargetCount; i++) pipelineDesc.RTVFormats[i] = D3D12Helpers::PixelFormatToDXGIFormat(pKey->RTVFormats[i]); for (uint32 i = pKey->RenderTargetCount; i < 8; i++) pipelineDesc.RTVFormats[i] = DXGI_FORMAT_UNKNOWN; pipelineDesc.DSVFormat = D3D12Helpers::PixelFormatToDXGIFormat(pKey->DSVFormat); pipelineDesc.SampleDesc.Count = 1; pipelineDesc.SampleDesc.Quality = 0; pipelineDesc.NodeMask = 0; pipelineDesc.CachedPSO.pCachedBlob = nullptr; pipelineDesc.CachedPSO.CachedBlobSizeInBytes = 0; pipelineDesc.Flags = (CVars::r_use_debug_shaders.GetBool() && CVars::r_d3d12_force_warp.GetBool()) ? D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG : D3D12_PIPELINE_STATE_FLAG_NONE; // create it ID3D12PipelineState *pPipelineState; HRESULT hResult = m_pDevice->GetD3DDevice()->CreateGraphicsPipelineState(&pipelineDesc, IID_PPV_ARGS(&pPipelineState)); if (SUCCEEDED(hResult)) { // set debug name if (!m_debugName.IsEmpty()) D3D12Helpers::SetD3D12ObjectName(pPipelineState, m_debugName); } else { Log_ErrorPrintf("CreateGraphicsPipelineState failed with hResult %08X", hResult); pPipelineState = nullptr; } // store it PipelineState ps; ps.pPipelineState = pPipelineState; ps.Key1 = key1; Y_memcpy(ps.Key2, key2, sizeof(ps.Key2)); // insert into appropriate place in list, saving sorting bool inserted = false; for (uint32 i = 0; i < m_pipelineStates.GetSize(); i++) { if (m_pipelineStates[i].Key1 > key1) { m_pipelineStates.Insert(ps, i); inserted = true; break; } } if (!inserted) m_pipelineStates.Add(ps); // done m_pDevice->GetShaderPipelineStateLock()->UnlockExclusive(); return ps.pPipelineState; } void D3D12GPUShaderProgram::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { // dummy values for now if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D12GPUShaderProgram::SetDebugName(const char *name) { m_debugName = name; } bool D3D12GPUShaderProgram::Create(D3D12GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, ByteStream *pByteCodeStream) { BinaryReader binaryReader(pByteCodeStream); // get the header of the shader cache entry D3DShaderCacheEntryHeader header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Signature != D3D_SHADER_CACHE_ENTRY_HEADER) { Log_ErrorPrintf("D3D12GPUShaderProgram::Create: Shader cache entry header corrupted."); return false; } // create d3d shader objects, and arrays for them for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (header.StageSize[stageIndex] == 0) continue; // create binary blob for bytecode m_pStageByteCode[stageIndex] = BinaryBlob::Allocate(header.StageSize[stageIndex]); if (!binaryReader.SafeReadBytes(m_pStageByteCode[stageIndex]->GetDataPointer(), header.StageSize[stageIndex])) return false; } // load up vertex attributes if (header.VertexAttributeCount > 0) { // create a filtered list of vertex attributes provided and those used by the shader m_vertexAttributes.Reserve(header.VertexAttributeCount); for (uint32 i = 0; i < header.VertexAttributeCount; i++) { D3DShaderCacheEntryVertexAttribute attribute; if (!binaryReader.SafeReadBytes(&attribute, sizeof(attribute))) return false; // search in the list provided uint32 listIndex; for (listIndex = 0; listIndex < nVertexAttributes; listIndex++) { if (pVertexAttributes[listIndex].Semantic == (GPU_VERTEX_ELEMENT_SEMANTIC)attribute.SemanticName && pVertexAttributes[listIndex].SemanticIndex == attribute.SemanticIndex) { break; } } // make sure it exists if (listIndex == nVertexAttributes) { Log_ErrorPrintf("D3D12ShaderProgram::Create: failed to match shader attribute with provided attributes"); return false; } // copy info in D3D12_INPUT_ELEMENT_DESC vertexAttribute; vertexAttribute.SemanticName = NameTable_GetNameString(NameTables::GPUVertexElementSemantic, pVertexAttributes[listIndex].Semantic); vertexAttribute.SemanticIndex = pVertexAttributes[listIndex].SemanticIndex; vertexAttribute.Format = s_GPUVertexElementTypeToDXGIFormat[pVertexAttributes[listIndex].Type]; vertexAttribute.InputSlot = pVertexAttributes[listIndex].StreamIndex; vertexAttribute.AlignedByteOffset = pVertexAttributes[listIndex].StreamOffset; vertexAttribute.InputSlotClass = (pVertexAttributes[listIndex].InstanceStepRate != 0) ? D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA : D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; vertexAttribute.InstanceDataStepRate = pVertexAttributes[listIndex].InstanceStepRate; m_vertexAttributes.Add(vertexAttribute); } } // load up constant buffers if (header.ConstantBufferCount > 0) { m_constantBuffers.Resize(header.ConstantBufferCount); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { D3DShaderCacheEntryConstantBuffer srcConstantBufferInfo; ConstantBuffer *pDstConstantBuffer = &m_constantBuffers[i]; if (!binaryReader.SafeReadBytes(&srcConstantBufferInfo, sizeof(srcConstantBufferInfo))) return false; // read name if (!binaryReader.SafeReadFixedString(srcConstantBufferInfo.NameLength, &pDstConstantBuffer->Name)) return false; // constant buffer struct pDstConstantBuffer->MinimumSize = srcConstantBufferInfo.MinimumSize; pDstConstantBuffer->ParameterIndex = srcConstantBufferInfo.ParameterIndex; pDstConstantBuffer->EngineConstantBufferIndex = 0; // lookup engine constant buffer const ShaderConstantBuffer *pEngineConstantBuffer = ShaderConstantBuffer::GetShaderConstantBufferByName(pDstConstantBuffer->Name, RENDERER_PLATFORM_D3D11, m_pDevice->GetFeatureLevel()); if (pEngineConstantBuffer == nullptr) { Log_ErrorPrintf("D3D12ShaderProgram::Create: Shader is requesting unknown constant buffer named '%s'.", pDstConstantBuffer->Name); return false; } // store index pDstConstantBuffer->EngineConstantBufferIndex = pEngineConstantBuffer->GetIndex(); } } // load parameters if (header.ParameterCount > 0) { m_parameters.Resize(header.ParameterCount); for (uint32 i = 0; i < m_parameters.GetSize(); i++) { D3DShaderCacheEntryParameter srcParameter; ShaderParameter *pDstParameterInfo = &m_parameters[i]; if (!binaryReader.SafeReadBytes(&srcParameter, sizeof(srcParameter))) return false; // read name if (!binaryReader.SafeReadFixedString(srcParameter.NameLength, &pDstParameterInfo->Name)) return false; pDstParameterInfo->Type = srcParameter.Type; pDstParameterInfo->ConstantBufferIndex = srcParameter.ConstantBufferIndex; pDstParameterInfo->ConstantBufferOffset = srcParameter.ConstantBufferOffset; pDstParameterInfo->ArraySize = srcParameter.ArraySize; pDstParameterInfo->ArrayStride = srcParameter.ArrayStride; pDstParameterInfo->BindTarget = (D3D_SHADER_BIND_TARGET)srcParameter.BindTarget; Y_memcpy(pDstParameterInfo->BindPoint, srcParameter.BindPoint, sizeof(pDstParameterInfo->BindPoint)); pDstParameterInfo->LinkedSamplerIndex = srcParameter.LinkedSamplerIndex; } } // all ok return true; } bool D3D12GPUShaderProgram::Switch(D3D12GPUContext *pContext, ID3D12GraphicsCommandList *pD3DCommandList, const PipelineStateKey *pKey) { // get pipeline state ID3D12PipelineState *pPipelineState = GetPipelineState(pKey); if (pPipelineState == nullptr) return false; pD3DCommandList->SetPipelineState(pPipelineState); // bind constant buffers for (const ConstantBuffer &constantBuffer : m_constantBuffers) { const ShaderParameter &parameter = m_parameters[constantBuffer.ParameterIndex]; DebugAssert(parameter.Type == SHADER_PARAMETER_TYPE_CONSTANT_BUFFER); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (parameter.BindPoint[stageIndex] < 0) continue; if (parameter.BindPoint[stageIndex] < D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS) { // bind to table const D3D12DescriptorHandle *pHandle = m_pDevice->GetConstantBufferDescriptor(constantBuffer.EngineConstantBufferIndex); if (pHandle != nullptr) pContext->SetShaderConstantBuffers((SHADER_PROGRAM_STAGE)stageIndex, parameter.BindPoint[stageIndex], *pHandle); } else { // bind to per-draw D3D12_GPU_VIRTUAL_ADDRESS virtualAddress; if (pContext->GetPerDrawConstantBufferGPUAddress(constantBuffer.EngineConstantBufferIndex, &virtualAddress)) pContext->SetPerDrawConstantBuffer(parameter.BindPoint[stageIndex] - D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, virtualAddress); } } } // done return true; } bool D3D12GPUShaderProgram::Switch(D3D12GPUCommandList *pCommandList, ID3D12GraphicsCommandList *pD3DCommandList, const PipelineStateKey *pKey) { // get pipeline state ID3D12PipelineState *pPipelineState = GetPipelineState(pKey); if (pPipelineState == nullptr) return false; pD3DCommandList->SetPipelineState(pPipelineState); // bind constant buffers for (const ConstantBuffer &constantBuffer : m_constantBuffers) { const ShaderParameter &parameter = m_parameters[constantBuffer.ParameterIndex]; DebugAssert(parameter.Type == SHADER_PARAMETER_TYPE_CONSTANT_BUFFER); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (parameter.BindPoint[stageIndex] < 0) continue; if (parameter.BindPoint[stageIndex] < D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS) { // bind to table const D3D12DescriptorHandle *pHandle = m_pDevice->GetConstantBufferDescriptor(constantBuffer.EngineConstantBufferIndex); if (pHandle != nullptr) pCommandList->SetShaderConstantBuffers((SHADER_PROGRAM_STAGE)stageIndex, parameter.BindPoint[stageIndex], *pHandle); } else { // bind to per-draw D3D12_GPU_VIRTUAL_ADDRESS virtualAddress; if (pCommandList->GetPerDrawConstantBufferGPUAddress(constantBuffer.EngineConstantBufferIndex, &virtualAddress)) pCommandList->SetPerDrawConstantBuffer(parameter.BindPoint[stageIndex] - D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, virtualAddress); } } } // done return true; } void D3D12GPUShaderProgram::RebindPerDrawConstantBuffer(D3D12GPUContext *pContext, uint32 constantBufferIndex, D3D12_GPU_VIRTUAL_ADDRESS address) { for (const ConstantBuffer &constantBuffer : m_constantBuffers) { if (constantBuffer.EngineConstantBufferIndex == constantBufferIndex) { const ShaderParameter &parameter = m_parameters[constantBuffer.ParameterIndex]; DebugAssert(parameter.Type == SHADER_PARAMETER_TYPE_CONSTANT_BUFFER); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (parameter.BindPoint[stageIndex] >= D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS) pContext->SetPerDrawConstantBuffer(parameter.BindPoint[stageIndex] - D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, address); } } } } void D3D12GPUShaderProgram::RebindPerDrawConstantBuffer(D3D12GPUCommandList *pCommandList, uint32 constantBufferIndex, D3D12_GPU_VIRTUAL_ADDRESS address) { for (const ConstantBuffer &constantBuffer : m_constantBuffers) { if (constantBuffer.EngineConstantBufferIndex == constantBufferIndex) { const ShaderParameter &parameter = m_parameters[constantBuffer.ParameterIndex]; DebugAssert(parameter.Type == SHADER_PARAMETER_TYPE_CONSTANT_BUFFER); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (parameter.BindPoint[stageIndex] >= D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS) pCommandList->SetPerDrawConstantBuffer(parameter.BindPoint[stageIndex] - D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, address); } } } } void D3D12GPUShaderProgram::InternalSetParameterValue(D3D12GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D12GPUShaderProgram::InternalSetParameterValue(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pCommandList->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D12GPUShaderProgram::InternalSetParameterValueArray(D3D12GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pContext->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D12GPUShaderProgram::InternalSetParameterValueArray(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pCommandList->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pCommandList->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D12GPUShaderProgram::InternalSetParameterStruct(D3D12GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D12GPUShaderProgram::InternalSetParameterStruct(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, const void *pValue, uint32 valueSize) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pCommandList->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D12GPUShaderProgram::InternalSetParameterStructArray(D3D12GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pContext->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D12GPUShaderProgram::InternalSetParameterStructArray(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // get constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); const ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pCommandList->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pCommandList->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D12GPUShaderProgram::InternalSetParameterResource(D3D12GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; // branch out according to target switch (parameterInfo->BindTarget) { case D3D_SHADER_BIND_TARGET_RESOURCE: { D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSRVHandle(pResource, &handle); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderResources((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } break; case D3D_SHADER_BIND_TARGET_SAMPLER: { D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSamplerHandle(pResource, &handle); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } break; case D3D_SHADER_BIND_TARGET_UNORDERED_ACCESS_VIEW: { // ID3D12UnorderedAccessView *pD3DUAV = (pResource != nullptr && pResource->GetResourceType() == GPU_RESOURCE_TYPE_COMPUTE_VIEW) ? static_cast<D3D12GPUComputeView *>(pResource)->GetD3DUAV() : nullptr; // for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) // { // int32 bindPoint = parameterInfo->BindPoint[stageIndex]; // if (bindPoint >= 0) // pContext->SetShaderUAVs((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DUAV); // } } break; } // for texture types with a linked sampler state, update it if (parameterInfo->LinkedSamplerIndex >= 0) { const ShaderParameter *samplerParameterInfo = &m_parameters[parameterInfo->LinkedSamplerIndex]; DebugAssert(samplerParameterInfo->Type == SHADER_PARAMETER_TYPE_SAMPLER_STATE && samplerParameterInfo->BindTarget == D3D_SHADER_BIND_TARGET_SAMPLER); // get handle - might look nasty, but handle is nulled in the constructor. D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSamplerHandle((pLinkedSamplerState != nullptr) ? static_cast<GPUResource *>(pLinkedSamplerState) : pResource, &handle); // write to stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = samplerParameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } } void D3D12GPUShaderProgram::InternalSetParameterResource(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; // branch out according to target switch (parameterInfo->BindTarget) { case D3D_SHADER_BIND_TARGET_RESOURCE: { D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSRVHandle(pResource, &handle); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pCommandList->SetShaderResources((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } break; case D3D_SHADER_BIND_TARGET_SAMPLER: { D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSamplerHandle(pResource, &handle); for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pCommandList->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } break; case D3D_SHADER_BIND_TARGET_UNORDERED_ACCESS_VIEW: { // ID3D12UnorderedAccessView *pD3DUAV = (pResource != nullptr && pResource->GetResourceType() == GPU_RESOURCE_TYPE_COMPUTE_VIEW) ? static_cast<D3D12GPUComputeView *>(pResource)->GetD3DUAV() : nullptr; // for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) // { // int32 bindPoint = parameterInfo->BindPoint[stageIndex]; // if (bindPoint >= 0) // pContext->SetShaderUAVs((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DUAV); // } } break; } // for texture types with a linked sampler state, update it if (parameterInfo->LinkedSamplerIndex >= 0) { const ShaderParameter *samplerParameterInfo = &m_parameters[parameterInfo->LinkedSamplerIndex]; DebugAssert(samplerParameterInfo->Type == SHADER_PARAMETER_TYPE_SAMPLER_STATE && samplerParameterInfo->BindTarget == D3D_SHADER_BIND_TARGET_SAMPLER); // get handle - might look nasty, but handle is nulled in the constructor. D3D12DescriptorHandle handle; D3D12Helpers::GetResourceSamplerHandle((pLinkedSamplerState != nullptr) ? static_cast<GPUResource *>(pLinkedSamplerState) : pResource, &handle); // write to stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = samplerParameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pCommandList->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, handle); } } } uint32 D3D12GPUShaderProgram::GetParameterCount() const { return m_parameters.GetSize(); } void D3D12GPUShaderProgram::GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) { const ShaderParameter *parameter = &m_parameters[index]; *name = parameter->Name; *type = parameter->Type; *arraySize = parameter->ArraySize; } GPUShaderProgram *D3D12GPUDevice::CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { D3D12GPUShaderProgram *pProgram = new D3D12GPUShaderProgram(this); if (!pProgram->Create(this, pVertexElements, nVertexElements, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } GPUShaderProgram *D3D12GPUDevice::CreateComputeProgram(ByteStream *pByteCodeStream) { D3D12GPUShaderProgram *pProgram = new D3D12GPUShaderProgram(this); if (!pProgram->Create(this, nullptr, 0, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } <file_sep>/Engine/Source/Core/PropertyTemplate.h #pragma once #include "Core/Common.h" #include "Core/Property.h" #include "YBaseLib/Pair.h" #include "YBaseLib/Array.h" #include "YBaseLib/PODArray.h" class ByteStream; class XMLReader; class PropertyTemplate; class PropertyTemplateProperty; class PropertyTemplateValueSelector; enum PROPERTY_TEMPLATE_PROPERTY_FLAGS { PROPERTY_TEMPLATE_PROPERTY_FLAG_HIDDEN = (1 << 0), PROPERTY_TEMPLATE_PROPERTY_FLAG_READONLY = (1 << 1), }; enum PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE { PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_RESOURCE, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_COLOR, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SLIDER, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SPINNER, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_CHOICE, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_EULER_ANGLES, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_FLAGS, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_COUNT, }; class PropertyTemplate { public: PropertyTemplate(); PropertyTemplate(const PropertyTemplate &from); ~PropertyTemplate(); void AddPropertyDefinition(PropertyTemplateProperty *pProperty); const PropertyTemplateProperty *GetPropertyDefinition(uint32 i) const { DebugAssert(i < m_propertyDefinitions.GetSize()); return m_propertyDefinitions[i]; } const PropertyTemplateProperty *GetPropertyDefinitionByName(const char *propertyName) const; const uint32 GetPropertyDefinitionCount() const { return m_propertyDefinitions.GetSize(); } template<class T> void EnumerateProperties(T callback) const { for (uint32 i = 0; i < m_propertyDefinitions.GetSize(); i++) callback(m_propertyDefinitions[i]); } #ifdef HAVE_LIBXML2 bool LoadFromStream(const char *FileName, ByteStream *pStream); bool LoadFromXML(XMLReader &xmlReader); #endif private: typedef PODArray<PropertyTemplateProperty *> PropertyDefinitionArray; PropertyDefinitionArray m_propertyDefinitions; }; class PropertyTemplateProperty { public: PropertyTemplateProperty(); ~PropertyTemplateProperty(); const PROPERTY_TYPE GetType() const { return m_eType; } const String &GetName() const { return m_strName; } const uint32 GetFlags() const { return m_flags; } const String &GetCategory() const { return m_strCategory; } const String &GetLabel() const { return m_strLabel; } const String &GetDescription() const { return m_strDescription; } const String &GetDefaultValue() const { return m_strDefaultValue; } const PropertyTemplateValueSelector *GetSelector() const { return m_pSelector; } PropertyTemplateProperty *Clone() const; #ifdef HAVE_LIBXML2 bool ParseXML(XMLReader &xmlReader); #endif private: PROPERTY_TYPE m_eType; String m_strName; uint32 m_flags; String m_strCategory; String m_strLabel; String m_strDescription; String m_strDefaultValue; PropertyTemplateValueSelector *m_pSelector; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector { public: PropertyTemplateValueSelector(const PropertyTemplateProperty *pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE type); virtual ~PropertyTemplateValueSelector(); const PropertyTemplateProperty *GetOwner() const { return m_pOwner; } const PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE GetType() const { return m_eType; } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) = 0; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) = 0; #endif private: const PropertyTemplateProperty *m_pOwner; PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE m_eType; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Resource : public PropertyTemplateValueSelector { public: PropertyTemplateValueSelector_Resource(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Resource(); const String &GetResourceTypeName() const { return m_strResourceTypeName; } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif private: String m_strResourceTypeName; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Color : public PropertyTemplateValueSelector { public: PropertyTemplateValueSelector_Color(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Color(); virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Slider : public PropertyTemplateValueSelector { public: PropertyTemplateValueSelector_Slider(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Slider(); const float GetMinValue() const { return m_fMinValue; } const float GetMaxValue() const { return m_fMaxValue; } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif private: float m_fMinValue; float m_fMaxValue; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Spinner : public PropertyTemplateValueSelector { public: PropertyTemplateValueSelector_Spinner(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Spinner(); const float GetMinValue() const { return m_fMinValue; } const float GetIncrement() const { return m_fIncrement; } const float GetMaxValue() const { return m_fMaxValue; } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif private: float m_fMinValue; float m_fIncrement; float m_fMaxValue; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Choice : public PropertyTemplateValueSelector { public: typedef Pair<String, String> Choice; public: PropertyTemplateValueSelector_Choice(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Choice(); const Choice &GetChoice(uint32 i) const { DebugAssert(i < m_Choices.GetSize()); return m_Choices[i]; } const uint32 GetChoiceCount() const { return m_Choices.GetSize(); } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif private: Array<Choice> m_Choices; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_EulerAngles : public PropertyTemplateValueSelector { public: PropertyTemplateValueSelector_EulerAngles(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_EulerAngles(); virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PropertyTemplateValueSelector_Flags : public PropertyTemplateValueSelector { public: struct Flag { uint32 Value; String Label; String Description; }; public: PropertyTemplateValueSelector_Flags(const PropertyTemplateProperty *pOwner); ~PropertyTemplateValueSelector_Flags(); const Flag &GetFlag(uint32 i) const { DebugAssert(i < m_Flags.GetSize()); return m_Flags[i]; } const uint32 GetFlagCount() const { return m_Flags.GetSize(); } virtual PropertyTemplateValueSelector *Clone(const PropertyTemplateProperty *pOwner) override final; #ifdef HAVE_LIBXML2 virtual bool ParseXML(XMLReader &xmlReader) override final; #endif private: Array<Flag> m_Flags; }; <file_sep>/Engine/Source/Engine/Physics/ScaledTriangleMeshCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/ScaledTriangleMeshCollisionShape.h" #include "Engine/Physics/BulletHeaders.h" Log_SetChannel(TriangleMeshCollisionShape); namespace Physics { ScaledTriangleMeshCollisionShape::ScaledTriangleMeshCollisionShape(const TriangleMeshCollisionShape *pParentShape, const float3 &scale) : CollisionShape(), m_Bounds(AABox::Zero), m_pParentShape(NULL), m_scale(scale), m_pTriangleMeshShape(NULL), m_pScaledTriangleMeshShape(NULL) { // set m_pParentShape = pParentShape; m_pParentShape->AddRef(); // create scaled shape m_pTriangleMeshShape = m_pParentShape->m_pTriangleMeshShape; m_pScaledTriangleMeshShape = new btScaledBvhTriangleMeshShape(m_pTriangleMeshShape, Float3ToBulletVector(scale)); // determine bounds btVector3 minBounds, maxBounds; m_pTriangleMeshShape->getAabb(btTransform::getIdentity(), minBounds, maxBounds); m_Bounds.SetBounds(BulletVector3ToFloat3(minBounds), BulletVector3ToFloat3(maxBounds)); } ScaledTriangleMeshCollisionShape::~ScaledTriangleMeshCollisionShape() { delete m_pScaledTriangleMeshShape; DebugAssert(m_pParentShape != NULL); m_pParentShape->Release(); } const COLLISION_SHAPE_TYPE ScaledTriangleMeshCollisionShape::GetType() const { return COLLISION_SHAPE_TYPE_SCALED_TRIANGLE_MESH; } const AABox &ScaledTriangleMeshCollisionShape::GetLocalBoundingBox() const { return m_Bounds; } bool ScaledTriangleMeshCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { return false; } bool ScaledTriangleMeshCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { return false; } CollisionShape *ScaledTriangleMeshCollisionShape::CreateScaledShape(const float3 &scale) const { return new ScaledTriangleMeshCollisionShape(m_pParentShape, scale); } void ScaledTriangleMeshCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { } void ScaledTriangleMeshCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { } btCollisionShape *ScaledTriangleMeshCollisionShape::GetBulletShape() const { return static_cast<btCollisionShape *>(m_pScaledTriangleMeshShape); } } // namespace Physics <file_sep>/Engine/Source/GameFramework/ParticleEmitterComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/ParticleEmitterComponent.h" #include "Engine/ParticleSystemRenderProxy.h" #include "Engine/Entity.h" #include "Engine/World.h" #include "Renderer/RenderWorld.h" DEFINE_COMPONENT_TYPEINFO(ParticleEmitterComponent); DEFINE_COMPONENT_GENERIC_FACTORY(ParticleEmitterComponent); BEGIN_COMPONENT_PROPERTIES(ParticleEmitterComponent) END_COMPONENT_PROPERTIES() ParticleEmitterComponent::ParticleEmitterComponent(const ComponentTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_pParticleSystem(nullptr), m_autoStart(true), m_pRenderProxy(nullptr), m_active(false) { } ParticleEmitterComponent::~ParticleEmitterComponent() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pParticleSystem != nullptr) m_pParticleSystem->Release(); } void ParticleEmitterComponent::SetParticleSystem(const ParticleSystem *pParticleSystem) { if (m_pParticleSystem != pParticleSystem) { m_pParticleSystem->Release(); m_pParticleSystem = pParticleSystem; m_pParticleSystem->AddRef(); m_pRenderProxy->SetParticleSystem(pParticleSystem); } else { m_pRenderProxy->Reset(); } } bool ParticleEmitterComponent::Create(const ParticleSystem *pParticleSystem, const float3 &offsetPosition /* = float3::Zero */, const Quaternion &offsetRotation /* = Quaternion::Identity */) { DebugAssert(m_pParticleSystem == nullptr && pParticleSystem != nullptr); m_pParticleSystem = pParticleSystem; m_pParticleSystem->AddRef(); m_localPosition = offsetPosition; m_localRotation = offsetRotation; m_localScale = float3::One; m_active = false; return Initialize(); } void ParticleEmitterComponent::Activate() { if (m_active) return; m_active = true; if (IsAttachedToEntity()) m_pEntity->RegisterForUpdates(0.0f); } void ParticleEmitterComponent::Deactivate() { m_active = false; } bool ParticleEmitterComponent::Initialize() { if (!BaseClass::Initialize()) return false; // create render proxy DebugAssert(m_pRenderProxy == nullptr); m_pRenderProxy = new ParticleSystemRenderProxy(m_pParticleSystem, 0); return true; } void ParticleEmitterComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // update cached transform m_cachedTransform = Transform::ConcatenateTransforms(Transform(m_localPosition, m_localRotation, m_localScale), pEntity->GetTransform()); // update render proxy's entity id m_pRenderProxy->SetEntityID(pEntity->GetEntityID()); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoStart && pEntity->IsInWorld()) { pEntity->RegisterForUpdates(0.0f); m_active = true; } } void ParticleEmitterComponent::OnRemoveFromEntity(Entity *pEntity) { BaseClass::OnRemoveFromEntity(pEntity); // ensure we're deactivated m_active = false; } void ParticleEmitterComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // add render proxy to world pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoStart) m_active = true; if (m_active) m_pEntity->RegisterForUpdates(0.0f); } void ParticleEmitterComponent::OnRemoveFromWorld(World *pWorld) { BaseClass::OnRemoveFromWorld(pWorld); // remove render proxy from world pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); } void ParticleEmitterComponent::OnLocalTransformChange() { // update cached transform, if attached to entity if (m_pEntity != nullptr) m_cachedTransform = Transform::ConcatenateTransforms(Transform(m_localPosition, m_localRotation, m_localScale), m_pEntity->GetTransform()); } void ParticleEmitterComponent::OnEntityTransformChange() { // update cached transform m_cachedTransform = Transform::ConcatenateTransforms(Transform(m_localPosition, m_localRotation, m_localScale), m_pEntity->GetTransform()); } void ParticleEmitterComponent::Update(float timeSinceLastUpdate) { if (m_active) { // update the particle system m_pRenderProxy->Update(&m_cachedTransform, timeSinceLastUpdate); // compare bounds AABox boundingBox(m_pRenderProxy->GetParticleSystemBoundingBox()); if (boundingBox != m_boundingBox) SetBounds(boundingBox, Sphere::FromAABox(boundingBox)); } } <file_sep>/Editor/Source/Editor/EditorProgressDialog.h #pragma once #include "Editor/Common.h" #include "Editor/EditorProgressCallbacks.h" #include "Editor/ui_EditorProgressDialog.h" class EditorProgressDialog : public QDialog, public EditorProgressCallbacks { Q_OBJECT public: EditorProgressDialog(QWidget *pParent, Qt::WindowFlags windowFlags = 0); ~EditorProgressDialog(); virtual void SetCancellable(bool cancellable); virtual void SetStatusText(const char *statusText); virtual void SetProgressRange(uint32 range); virtual void SetProgressValue(uint32 value); virtual void DisplayError(const char *message); virtual void DisplayWarning(const char *message); virtual void DisplayInformation(const char *message); virtual void DisplayDebugMessage(const char *message); private: Ui_EditorProgressDialog *m_ui; }; <file_sep>/Engine/Source/Engine/Physics/GhostObject.cpp #include "Engine/PrecompiledHeader.h" <file_sep>/Engine/Source/Core/ClassTable.cpp #include "Core/PrecompiledHeader.h" #include "Core/ClassTable.h" #include "Core/ClassTableDataFormat.h" #include "Core/ObjectTypeInfo.h" #include "Core/Object.h" #include "YBaseLib/Log.h" #include "YBaseLib/BinaryReader.h" #include "YBaseLib/BinaryWriter.h" Log_SetChannel(ClassTable); static const char *MISSING_PROPERTY_NAME_STRING = "___MISSING___"; ClassTable::ClassTable() : m_pTypeMappings(nullptr), m_typeCount(0) { } ClassTable::~ClassTable() { for (uint32 i = 0; i < m_typeCount; i++) delete[] m_pTypeMappings[i].m_ppPropertyMapping; delete[] m_pTypeMappings; } const int32 ClassTable::GetTypeMappingForType(const ObjectTypeInfo *pTypeInfo) const { for (uint32 typeIndex = 0; typeIndex < m_typeCount; typeIndex++) { if (m_pTypeMappings[typeIndex].m_pTypeInfo == pTypeInfo) return (int32)typeIndex; } return -1; } bool ClassTable::LoadFromStream(ByteStream *pStream, bool abortOnError /* = false */) { #if 0 uint32 bufferSize = (uint32)(pStream->GetSize() - pStream->GetPosition()); byte *tempBuffer = new byte[bufferSize]; if (!pStream->Read2(tempBuffer, bufferSize)) { delete[] tempBuffer; return false; } bool result = LoadFromBuffer(tempBuffer, bufferSize, abortOnError); delete[] tempBuffer; return result; #else BinaryReader binaryReader(pStream); SmallString extractedString; // read/validate header DF_CLASS_TABLE_HEADER header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Magic != DF_CLASS_TABLE_HEADER_MAGIC || header.HeaderSize != sizeof(DF_CLASS_TABLE_HEADER)) { return false; } // allocate types m_pTypeMappings = (TypeMapping *)Y_realloc(m_pTypeMappings, sizeof(TypeMapping) * header.TypeCount); Y_memzero(m_pTypeMappings, sizeof(TypeMapping) * header.TypeCount); m_typeCount = header.TypeCount; // read types for (uint32 typeIndex = 0; typeIndex < m_typeCount; typeIndex++) { // read header DF_CLASS_TABLE_TYPE typeHeader; if (!binaryReader.SafeReadBytes(&typeHeader, sizeof(typeHeader)) || typeHeader.TotalSize < (sizeof(DF_CLASS_TABLE_TYPE) + typeHeader.TypeNameLength)) return false; // work out offset to next type in case we have to skip it uint64 nextTypeOffset = binaryReader.GetStreamPosition() + (typeHeader.TotalSize - sizeof(DF_CLASS_TABLE_TYPE)); // read type name if (!binaryReader.SafeReadFixedString(typeHeader.TypeNameLength, &extractedString)) return false; // try to map this to a type we know const ObjectTypeInfo *pTypeInfo = ObjectTypeInfo::GetRegistry().GetTypeInfoByName(extractedString); if (pTypeInfo == nullptr) { Log_WarningPrintf("ClassTable::LoadFromStream: Table contains unknown type '%s'", extractedString.GetCharArray()); if (abortOnError) return false; // skip this type if (!binaryReader.SafeSeekAbsolute(nextTypeOffset)) return false; } // allocate properties TypeMapping *destMapping = &m_pTypeMappings[typeIndex]; destMapping->m_pTypeInfo = pTypeInfo; destMapping->m_ppPropertyMapping = new const PROPERTY_DECLARATION *[typeHeader.PropertyCount]; destMapping->m_propertyCount = typeHeader.PropertyCount; Y_memzero(destMapping->m_ppPropertyMapping, sizeof(const PROPERTY_DECLARATION *) * typeHeader.PropertyCount); // read properties for (uint32 propertyIndex = 0; propertyIndex < destMapping->m_propertyCount; propertyIndex++) { // extract and increment pointer DF_CLASS_TABLE_TYPE_PROPERTY propertyHeader; if (!binaryReader.SafeReadBytes(&propertyHeader, sizeof(propertyHeader))) return false; // read the property name if (!binaryReader.SafeReadFixedString(propertyHeader.PropertyNameLength, &extractedString)) return false; // find the mapping if ((destMapping->m_ppPropertyMapping[propertyIndex] = pTypeInfo->GetPropertyDeclarationByName(extractedString)) == nullptr) { Log_WarningPrintf("ClassTable::LoadFromStream: Table for type '%s' contains unknown property '%s'", pTypeInfo->GetTypeName(), extractedString.GetCharArray()); if (abortOnError) return false; } } // should be in the correct position if (pStream->GetPosition() != nextTypeOffset) return false; } return true; #endif } bool ClassTable::LoadFromBuffer(const void *pBuffer, uint32 bufferSize, bool abortOnError /* = false */) { const DF_CLASS_TABLE_HEADER *pHeader = reinterpret_cast<const DF_CLASS_TABLE_HEADER *>(pBuffer); if (pHeader->Magic != DF_CLASS_TABLE_HEADER_MAGIC || pHeader->HeaderSize != sizeof(DF_CLASS_TABLE_HEADER) || pHeader->TotalSize > bufferSize) { return false; } const byte *pDataPointer = reinterpret_cast<const byte *>(pHeader) + pHeader->HeaderSize; SmallString extractedString; // allocate types m_pTypeMappings = (TypeMapping *)Y_realloc(m_pTypeMappings, sizeof(TypeMapping) * pHeader->TypeCount); Y_memzero(m_pTypeMappings, sizeof(TypeMapping) * pHeader->TypeCount); m_typeCount = pHeader->TypeCount; // read types for (uint32 typeIndex = 0; typeIndex < m_typeCount; typeIndex++) { TypeMapping *destMapping = &m_pTypeMappings[typeIndex]; // get header const DF_CLASS_TABLE_TYPE *sourceType = reinterpret_cast<const DF_CLASS_TABLE_TYPE *>(pDataPointer); // extract name extractedString.Clear(); extractedString.AppendString(sourceType->TypeName, sourceType->TypeNameLength); // try to map this to a type we know const ObjectTypeInfo *pTypeInfo = ObjectTypeInfo::GetRegistry().GetTypeInfoByName(extractedString); if (pTypeInfo == nullptr) { Log_WarningPrintf("ClassTable::LoadFromBuffer: Table contains unknown type '%s'", extractedString.GetCharArray()); if (abortOnError) return false; // skip this type pDataPointer += sourceType->TotalSize; continue; } // allocate properties destMapping->m_pTypeInfo = pTypeInfo; destMapping->m_ppPropertyMapping = new const PROPERTY_DECLARATION *[sourceType->PropertyCount]; destMapping->m_propertyCount = sourceType->PropertyCount; Y_memzero(destMapping->m_ppPropertyMapping, sizeof(const PROPERTY_DECLARATION *) * sourceType->PropertyCount); // start on properties const byte *pPropertyPointer = pDataPointer + sizeof(DF_CLASS_TABLE_TYPE) + sourceType->TypeNameLength; for (uint32 propertyIndex = 0; propertyIndex < sourceType->PropertyCount; propertyIndex++) { // extract and increment pointer const DF_CLASS_TABLE_TYPE_PROPERTY *sourceProperty = reinterpret_cast<const DF_CLASS_TABLE_TYPE_PROPERTY *>(pPropertyPointer); pPropertyPointer += sizeof(DF_CLASS_TABLE_TYPE_PROPERTY) + sourceProperty->PropertyNameLength; // find the mapping extractedString.Clear(); extractedString.AppendString(sourceProperty->PropertyName, sourceProperty->PropertyNameLength); if ((destMapping->m_ppPropertyMapping[propertyIndex] = pTypeInfo->GetPropertyDeclarationByName(extractedString)) == nullptr) { Log_WarningPrintf("ClassTable::LoadFromBuffer: Table for type '%s' contains unknown property '%s'", pTypeInfo->GetTypeName(), extractedString.GetCharArray()); if (abortOnError) return false; } } // increment data pointer pDataPointer += sourceType->TotalSize; } // done return true; } bool ClassTable::SaveToStream(ByteStream *pStream) const { BinaryWriter binaryWriter(pStream); uint32 *pTypeSizes = (uint32 *)alloca(sizeof(uint32) * m_typeCount); // avoiding seeking so we can push this straight to the output stream, but we need to know the total size uint32 totalSize = sizeof(DF_CLASS_TABLE_HEADER); for (uint32 typeIndex = 0; typeIndex < m_typeCount; typeIndex++) { const TypeMapping *pTypeMapping = &m_pTypeMappings[typeIndex]; uint32 typeSize = sizeof(DF_CLASS_TABLE_TYPE); if (pTypeMapping->m_pTypeInfo == nullptr) typeSize += Y_strlen(MISSING_PROPERTY_NAME_STRING); else typeSize += Y_strlen(pTypeMapping->GetTypeInfo()->GetTypeName()); for (uint32 propertyIndex = 0; propertyIndex < pTypeMapping->GetPropertyCount(); propertyIndex++) { typeSize += sizeof(DF_CLASS_TABLE_TYPE_PROPERTY); if (pTypeMapping->m_ppPropertyMapping[propertyIndex] == nullptr) typeSize += Y_strlen(MISSING_PROPERTY_NAME_STRING); else typeSize += Y_strlen(pTypeMapping->m_ppPropertyMapping[propertyIndex]->Name); } pTypeSizes[typeIndex] = typeSize; totalSize += typeSize; } // write header DF_CLASS_TABLE_HEADER header; header.Magic = DF_CLASS_TABLE_HEADER_MAGIC; header.TotalSize = totalSize; header.HeaderSize = sizeof(header); header.TypeCount = m_typeCount; if (!binaryWriter.SafeWriteBytes(&header, sizeof(header))) return false; // write types for (uint32 typeIndex = 0; typeIndex < m_typeCount; typeIndex++) { const TypeMapping *pTypeMapping = &m_pTypeMappings[typeIndex]; DF_CLASS_TABLE_TYPE typeHeader; typeHeader.TotalSize = pTypeSizes[typeIndex]; typeHeader.PropertyCount = pTypeMapping->GetPropertyCount(); if (pTypeMapping->m_pTypeInfo != nullptr) { typeHeader.TypeNameLength = Y_strlen(pTypeMapping->m_pTypeInfo->GetTypeName()); if (!binaryWriter.SafeWriteBytes(&typeHeader, sizeof(typeHeader)) || !binaryWriter.SafeWriteBytes(pTypeMapping->m_pTypeInfo->GetTypeName(), typeHeader.TypeNameLength)) return false; } else { typeHeader.TypeNameLength = Y_strlen(MISSING_PROPERTY_NAME_STRING); if (!binaryWriter.SafeWriteBytes(&typeHeader, sizeof(typeHeader)) || !binaryWriter.SafeWriteBytes(MISSING_PROPERTY_NAME_STRING, typeHeader.TypeNameLength)) return false; } // write properties for (uint32 propertyIndex = 0; propertyIndex < pTypeMapping->GetPropertyCount(); propertyIndex++) { const PROPERTY_DECLARATION *pProperty = pTypeMapping->GetPropertyMapping(propertyIndex); DF_CLASS_TABLE_TYPE_PROPERTY propertyHeader; if (pProperty != nullptr) { propertyHeader.PropertyType = pProperty->Type; propertyHeader.PropertyNameLength = Y_strlen(pProperty->Name); if (!binaryWriter.SafeWriteBytes(&propertyHeader, sizeof(propertyHeader)) || !binaryWriter.SafeWriteBytes(pProperty->Name, propertyHeader.PropertyNameLength)) return false; } else { propertyHeader.PropertyType = PROPERTY_TYPE_STRING; propertyHeader.PropertyNameLength = Y_strlen(MISSING_PROPERTY_NAME_STRING); if (!binaryWriter.SafeWriteBytes(&propertyHeader, sizeof(propertyHeader)) || !binaryWriter.SafeWriteBytes(MISSING_PROPERTY_NAME_STRING, propertyHeader.PropertyNameLength)) return false; } } } return true; } uint32 ClassTable::AddType(const ObjectTypeInfo *pTypeInfo) { DebugAssert(GetTypeMappingForType(pTypeInfo) < 0); // reallocate for space uint32 typeIndex = m_typeCount; m_pTypeMappings = (TypeMapping *)Y_realloc(m_pTypeMappings, sizeof(TypeMapping) * (m_typeCount + 1)); DebugAssert(m_pTypeMappings != nullptr); m_typeCount++; // add it TypeMapping *pTypeMapping = &m_pTypeMappings[typeIndex]; pTypeMapping->m_pTypeInfo = pTypeInfo; pTypeMapping->m_ppPropertyMapping = new const PROPERTY_DECLARATION *[pTypeInfo->GetPropertyCount()]; pTypeMapping->m_propertyCount = pTypeInfo->GetPropertyCount(); for (uint32 i = 0; i < pTypeMapping->m_propertyCount; i++) pTypeMapping->m_ppPropertyMapping[i] = pTypeInfo->GetPropertyDeclarationByIndex(i); // return index return typeIndex; } bool ClassTable::SerializeObject(const Object *pObject, ByteStream *pStream) { BinaryWriter binaryWriter(pStream); // in list? int32 typeIndex = GetTypeMappingForType(pObject->GetObjectTypeInfo()); if (typeIndex < 0) { // add it typeIndex = (int32)AddType(pObject->GetObjectTypeInfo()); } // serialize the object's properties const TypeMapping *pTypeMapping = &m_pTypeMappings[typeIndex]; for (uint32 propertyIndex = 0; propertyIndex < pTypeMapping->GetPropertyCount(); propertyIndex++) { // write the property value to the buffer if (!WritePropertyValueToBuffer(pObject, pTypeMapping->GetPropertyMapping(propertyIndex), binaryWriter)) return false; } return true; } Object *ClassTable::UnserializeObject(ByteStream *pStream, uint32 typeIndex) { // should be a valid type index const TypeMapping *pTypeMapping = &m_pTypeMappings[typeIndex]; DebugAssert(typeIndex < m_typeCount); // is it mapped const ObjectTypeInfo *pTypeInfo = pTypeMapping->GetTypeInfo(); if (pTypeInfo == nullptr) { Log_ErrorPrintf("ClassTable::UnserializeObject: Missing mapping for type %u", typeIndex); return nullptr; } // create the object ObjectFactory *pFactory = pTypeInfo->GetFactory(); Object *pObject = (pFactory != nullptr) ? pFactory->CreateObject() : nullptr; if (pObject == nullptr) { Log_ErrorPrintf("ClassTable::UnserializeObject: Failed to create instance of type '%s'", pTypeMapping->GetTypeInfo()->GetTypeName()); return nullptr; } // import properties for (uint32 propertyIndex = 0; propertyIndex < pTypeMapping->GetPropertyCount(); propertyIndex++) { // // read property info // uint32 propertySize; // if (!pStream->Read2(&propertySize, sizeof(propertySize))) // return nullptr; // mapped? const PROPERTY_DECLARATION *pMappedProperty = pTypeMapping->GetPropertyMapping(propertyIndex); if (pMappedProperty == nullptr) { // skip the property uint32 propertySize; if (!pStream->Read2(&propertySize, sizeof(propertySize)) || !pStream->SeekRelative((int64)propertySize)) { pFactory->DeleteObject(pObject); return nullptr; } continue; } // FIXME BinaryReader binaryReader(pStream); if (!ReadPropertyValueFromBuffer(pObject, pMappedProperty, binaryReader)) { pFactory->DeleteObject(pObject); return nullptr; } } // all done return pObject; } <file_sep>/Engine/Source/Engine/BulletDebugDraw.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BulletDebugDraw.h" Log_SetChannel(BulletDebugDraw); using namespace Physics; BulletDebugDraw::BulletDebugDraw() : m_debugMode(0) { } BulletDebugDraw::~BulletDebugDraw() { } void BulletDebugDraw::SetViewportDimensions(const uint32 width, const uint32 height) { m_guiContext.SetViewportDimensions(width, height); } void BulletDebugDraw::BeginDraw() { m_guiContext.PushManualFlush(); m_guiContext.SetDepthTestingEnabled(true); m_guiContext.SetAlphaBlendingEnabled(false); } void BulletDebugDraw::EndDraw() { m_guiContext.Flush(); m_guiContext.PopManualFlush(); } void BulletDebugDraw::drawLine(const btVector3& from,const btVector3& to,const btVector3& color) { float3 fromVec(BulletVector3ToFloat3(from)); float3 toVec(BulletVector3ToFloat3(to)); float3 colorVec(BulletVector3ToFloat3(color)); uint8 r = (uint8)Math::Clamp(colorVec.r * 255.0f, 0.0f, 255.0f); uint8 g = (uint8)Math::Clamp(colorVec.g * 255.0f, 0.0f, 255.0f); uint8 b = (uint8)Math::Clamp(colorVec.b * 255.0f, 0.0f, 255.0f); m_guiContext.Draw3DLine(fromVec, toVec, MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, 255)); } void BulletDebugDraw::drawLine(const btVector3& from,const btVector3& to, const btVector3& fromColor, const btVector3& toColor) { float3 fromVec(BulletVector3ToFloat3(from)); float3 fromColorVec(BulletVector3ToFloat3(fromColor)); float3 toVec(BulletVector3ToFloat3(to)); float3 toColorVec(BulletVector3ToFloat3(toColor)); uint8 fromR = (uint8)Math::Clamp(fromColorVec.r * 255.0f, 0.0f, 255.0f); uint8 fromG = (uint8)Math::Clamp(fromColorVec.g * 255.0f, 0.0f, 255.0f); uint8 fromB = (uint8)Math::Clamp(fromColorVec.b * 255.0f, 0.0f, 255.0f); uint8 toR = (uint8)Math::Clamp(toColorVec.r * 255.0f, 0.0f, 255.0f); uint8 toG = (uint8)Math::Clamp(toColorVec.g * 255.0f, 0.0f, 255.0f); uint8 toB = (uint8)Math::Clamp(toColorVec.b * 255.0f, 0.0f, 255.0f); m_guiContext.Draw3DLine(fromVec, MAKE_COLOR_R8G8B8A8_UNORM(fromR, fromG, fromB, 255), toVec, MAKE_COLOR_R8G8B8A8_UNORM(toR, toG, toB, 255)); } void BulletDebugDraw::drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color) { //Log_DevPrintf("BulletDebugDraw::drawContactPoint: %f %f %f", PointOnB.x(), PointOnB.y(), PointOnB.z()); btVector3 to= PointOnB+normalOnB*1;//distance; const btVector3&from = PointOnB; drawLine(from, to, color); } void BulletDebugDraw::reportErrorWarning(const char* warningString) { Log_WarningPrintf("BulletDebugDraw::reportErrorWarning: '%s'", warningString); } void BulletDebugDraw::draw3dText(const btVector3& location,const char* textString) { Log_DevPrintf("BulletDebugDraw::draw3dText: '%s' @ %f %f %f", textString, location.x(), location.y(), location.z()); } void BulletDebugDraw::setDebugMode(int debugMode) { m_debugMode = debugMode; } int BulletDebugDraw::getDebugMode() const { return m_debugMode; } <file_sep>/Engine/Source/BlockEngine/CMakeLists.txt set(HEADER_FILES BlockAnimation.h BlockDrawTemplate.h BlockEngineCVars.h BlockWorldChunkCollisionShape.h BlockWorldChunk.h BlockWorldChunkRenderProxy.h BlockWorldGenerator.h BlockWorld.h BlockWorldMesher.h BlockWorldSection.h BlockWorldTypes.h BlockWorldVertexFactory.h ) set(SOURCE_FILES BlockAnimation.cpp BlockDrawTemplate.cpp BlockEngineCVars.cpp BlockWorldChunkCollisionShape.cpp BlockWorldChunk.cpp BlockWorldChunkRenderProxy.cpp BlockWorld.cpp BlockWorldGenerator.cpp BlockWorldMesher.cpp BlockWorldSection.cpp BlockWorldVertexFactory.cpp ) include_directories(${ENGINE_BASE_DIRECTORY}) add_library(EngineBlockEngine STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineBlockEngine EngineMain EngineCore) <file_sep>/Engine/Source/Renderer/WorldRenderers/DebugNormalsWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/DebugNormalsWorldRenderer.h" #include "Renderer/RenderQueue.h" #include "Renderer/RenderProxy.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderComponent.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/Material.h" class DebugNormalsShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DebugNormalsShader, ShaderComponent); public: DebugNormalsShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == nullptr || pMaterialShader == nullptr) return false; return true; } static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DebugNormalsShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DebugNormalsShader.hlsl", "PSMain"); return true; } }; DEFINE_SHADER_COMPONENT_INFO(DebugNormalsShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DebugNormalsShader) END_SHADER_COMPONENT_PARAMETERS() DebugNormalsWorldRenderer::DebugNormalsWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : SingleShaderWorldRenderer(pGPUContext, pOptions) { } DebugNormalsWorldRenderer::~DebugNormalsWorldRenderer() { } void DebugNormalsWorldRenderer::DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { ShaderProgram *pShaderProgram; if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(DebugNormalsShader), 0, pQueueEntry)) == NULL) return; m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); m_pGPUContext->SetRasterizerState(pQueueEntry->pMaterial->GetShader()->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pQueueEntry->pMaterial->GetShader()->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } <file_sep>/Engine/Source/D3D11Renderer/D3DShaderCacheEntry.h #pragma once enum D3D_SHADER_BIND_TARGET { D3D_SHADER_BIND_TARGET_CONSTANT_BUFFER, D3D_SHADER_BIND_TARGET_RESOURCE, D3D_SHADER_BIND_TARGET_SAMPLER, D3D_SHADER_BIND_TARGET_UNORDERED_ACCESS_VIEW, D3D_SHADER_BIND_TARGET_COUNT, }; #pragma pack(push, 1) #define D3D_SHADER_CACHE_ENTRY_HEADER ((uint32)'D3DS') #define D3D_SHADER_CACHE_ENTRY_MAX_NAME_LENGTH 256 #define D3D_GLOBAL_CONSTANT_BUFFER_SIZE (65536) // 64KiB struct D3DShaderCacheEntryHeader { uint32 Signature; uint32 FeatureLevel; uint32 StageSize[SHADER_PROGRAM_STAGE_COUNT]; uint32 VertexAttributeCount; uint32 ConstantBufferCount; uint32 ParameterCount; }; struct D3DShaderCacheEntryVertexAttribute { uint32 SemanticName; uint32 SemanticIndex; }; struct D3DShaderCacheEntryConstantBuffer { uint32 NameLength; uint32 MinimumSize; uint32 ParameterIndex; // <char> * NameLength follows }; struct D3DShaderCacheEntryParameter { uint32 NameLength; SHADER_PARAMETER_TYPE Type; int32 ConstantBufferIndex; uint32 ConstantBufferOffset; uint32 ArraySize; uint32 ArrayStride; uint32 BindTarget; int32 BindPoint[SHADER_PROGRAM_STAGE_COUNT]; int32 LinkedSamplerIndex; // <char> * NameLength follows }; #pragma pack(pop) <file_sep>/Engine/Source/ContentConverterStandalone/ContentConverter.h #include "ContentConverter/Common.h" #include "ContentConverter/OBJImporter.h" #include "ContentConverter/TextureImporter.h" #include "ContentConverter/FontImporter.h" #include "ContentConverter/AssimpSkeletonImporter.h" #include "ContentConverter/AssimpSkeletalMeshImporter.h" #include "ContentConverter/AssimpSkeletalAnimationImporter.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "ContentConverter/AssimpSceneImporter.h" int RunOBJImporter(int argc, char *argv[]); bool ParseOBJConverterOption(OBJImporterOptions &Options, int &i, int argc, char *argv[]); int RunTextureImporter(int argc, char *argv[]); bool ParseTextureImporterOption(TextureImporterOptions &Options, int &i, int argc, char *argv[]); int RunFontImporter(int argc, char *argv[]); bool ParseFontImporterOption(FontImporterOptions &Options, int &i, int argc, char *argv[]); int RunAssimpSkeletonImporter(int argc, char *argv[]); bool ParseAssimpSkeletonImporterOption(AssimpSkeletonImporter::Options &Options, int &i, int argc, char *argv[]); int RunAssimpSkeletalMeshImporter(int argc, char *argv[]); bool ParseAssimpSkeletalMeshImporterOption(AssimpSkeletalMeshImporter::Options &Options, int &i, int argc, char *argv[]); int RunAssimpSkeletalAnimationImporter(int argc, char *argv[]); bool ParseAssimpSkeletalAnimationImporterOption(AssimpSkeletalAnimationImporter::Options &Options, int &i, int argc, char *argv[]); int RunAssimpStaticMeshImporter(int argc, char *argv[]); bool ParseAssimpStaticMeshImporterOption(AssimpStaticMeshImporter::Options &Options, int &i, int argc, char *argv[]); int RunAssimpSceneImporter(int argc, char *argv[]); bool ParseAssimpSceneImporterOption(AssimpStaticMeshImporter::Options &Options, int &i, int argc, char *argv[]); <file_sep>/Engine/Source/ContentConverter/AssimpSceneImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpCommon.h" #include "ContentConverter/AssimpSceneImporter.h" #include "ContentConverter/AssimpMaterialImporter.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "MapCompiler/MapSource.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" using AssimpHelpers::AssimpVector3ToFloat3; using AssimpHelpers::AssimpQuaternionToQuaternion; using AssimpHelpers::Float4x4ToAssimpMatrix4x4; AssimpSceneImporter::AssimpSceneImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(nullptr), m_pLogStream(nullptr), m_pScene(nullptr) { } AssimpSceneImporter::~AssimpSceneImporter() { delete m_pLogStream; delete m_pImporter; for (uint32 i = 0; i < m_meshes.GetSize(); i++) delete m_meshes[i].pGenerator; } void AssimpSceneImporter::SetDefaultOptions(Options *pOptions) { pOptions->ImportMaterials = false; pOptions->DefaultMaterialName = "materials/engine/default"; pOptions->BuildCollisionShapeType = StaticMeshGenerator::CollisionShapeType_TriangleMesh; pOptions->TransformMatrix.SetIdentity(); pOptions->CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; pOptions->CenterMeshes = StaticMeshGenerator::CenterOrigin_Count; } bool AssimpSceneImporter::Execute() { Timer timer; if (m_pOptions->SourcePath.IsEmpty() || m_pOptions->DefaultMaterialName.IsEmpty() || (m_pOptions->ImportMaterials && m_pOptions->MaterialDirectory.IsEmpty())) { m_pProgressCallbacks->ModalError("Missing parameters"); return false; } // ensure assimp is initialized if (!AssimpHelpers::InitializeAssimp()) { m_pProgressCallbacks->ModalError("assimp initialization failed"); return false; } timer.Reset(); if (!LoadScene()) { m_pProgressCallbacks->ModalError("LoadScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("LoadScene(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateMaterials()) { m_pProgressCallbacks->ModalError("CreateMaterials() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateMaterials(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!ParseScene()) { m_pProgressCallbacks->ModalError("ParseScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("ParseScene(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!WriteMeshes()) { m_pProgressCallbacks->ModalError("WriteMeshes() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("WriteMeshes(): %.4f ms", timer.GetTimeMilliseconds()); if (m_pOptions->OutputMapName.GetLength() > 0) { timer.Reset(); if (!WriteMap()) { m_pProgressCallbacks->ModalError("WriteMap() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("WriteMap(): %.4f ms", timer.GetTimeMilliseconds()); } return true; } bool AssimpSceneImporter::LoadScene() { // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // get postprocessing flags int postProcessFlags = AssimpHelpers::GetAssimpStaticMeshImportPostProcessingFlags(); // remove crap postProcessFlags &= ~(aiProcess_OptimizeMeshes); postProcessFlags &= ~(aiProcess_OptimizeGraph); //postProcessFlags &= ~(aiProcess_FlipUVs); postProcessFlags |= aiProcess_FindInstances; // get coordinate system transform bool reverseWinding; float4x4 coordinateSystemTransform(float4x4::MakeCoordinateSystemConversionMatrix(m_pOptions->CoordinateSystem, COORDINATE_SYSTEM_Z_UP_RH, &reverseWinding)); if (reverseWinding) postProcessFlags |= aiProcess_FlipWindingOrder; // create global transform m_globalTransform = m_pOptions->TransformMatrix * coordinateSystemTransform; // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(postProcessFlags); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } bool AssimpSceneImporter::CreateMaterials() { if (!m_pOptions->ImportMaterials) { for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { m_materialMapping.Add(m_pOptions->DefaultMaterialName); } return true; } for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { const aiMaterial *pAIMaterial = m_pScene->mMaterials[i]; aiString aiMaterialName; if (aiGetMaterialString(pAIMaterial, AI_MATKEY_NAME, &aiMaterialName) != aiReturn_SUCCESS || aiMaterialName.length == 0) aiMaterialName.Set(String::FromFormat("material%u", i)); SmallString sanitizedMaterialName = aiMaterialName.C_Str(); Resource::SanitizeResourceName(sanitizedMaterialName); PathString materialResourceName; PathString fileName; materialResourceName.Format("%s/%s%s", m_pOptions->MaterialDirectory.GetCharArray(), m_pOptions->MaterialPrefix.GetCharArray(), sanitizedMaterialName.GetCharArray()); m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' -> '%s'", aiMaterialName.C_Str(), materialResourceName.GetCharArray()); // does this material exist? fileName.Format("%s.mtl.xml", materialResourceName.GetCharArray()); if (g_pVirtualFileSystem->FileExists(fileName)) { m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' already exists, skipping import...", materialResourceName.GetCharArray()); m_materialMapping.Add(materialResourceName); continue; } // import the material if (!AssimpMaterialImporter::ImportMaterial(pAIMaterial, m_pOptions->SourcePath, m_pOptions->MaterialDirectory, m_pOptions->MaterialPrefix, materialResourceName, m_pProgressCallbacks)) { m_pProgressCallbacks->DisplayFormattedWarning("Material '%s' failed import, using default material.", materialResourceName.GetCharArray()); m_materialMapping.Add(m_pOptions->DefaultMaterialName); continue; } // add it m_materialMapping.Add(materialResourceName); } return true; } bool AssimpSceneImporter::ParseScene() { const aiNode *pRootNode = m_pScene->mRootNode; // parse the root node aiMatrix4x4 rootTransform(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); return ParseNode(pRootNode, &rootTransform); } bool AssimpSceneImporter::ParseNode(const aiNode *pNode, const void *parentTransform) { // create transform for this node aiMatrix4x4 nodeTransform(*reinterpret_cast<const aiMatrix4x4 *>(parentTransform) * pNode->mTransformation); // parse all meshes in this node if (pNode->mNumMeshes > 0) { // is this mesh already done? uint32 meshIndex; for (meshIndex = 0; meshIndex < m_meshes.GetSize(); meshIndex++) { if (m_meshes[meshIndex].nSourceMeshes == pNode->mNumMeshes && Y_memcmp(m_meshes[meshIndex].pSourceMeshes, pNode->mMeshes, sizeof(unsigned int) * pNode->mNumMeshes) == 0) { // mesh set matches break; } } // mesh in list? if (meshIndex == m_meshes.GetSize()) { uint32 meshAddSuffix = 0; String meshName; for (;;) { // create mesh name if (pNode->mName.length != 0) meshName.AppendString(pNode->mName.C_Str()); else if (m_pScene->mMeshes[pNode->mMeshes[0]]->mName.length != 0) meshName.AppendString(m_pScene->mMeshes[pNode->mMeshes[0]]->mName.C_Str()); else meshName.AppendString("node"); // append suffix if (meshAddSuffix != 0) meshName.AppendFormattedString("_%u", meshAddSuffix); // sanitize it Resource::SanitizeResourceName(meshName); // add mesh prefix meshName.PrependFormattedString("%s/%s", m_pOptions->MeshDirectory.GetCharArray(), m_pOptions->MeshPrefix.GetCharArray()); // do we have anything with this name alreadY? for (meshIndex = 0; meshIndex < m_meshes.GetSize(); meshIndex++) { if (m_meshes[meshIndex].MeshName.CompareInsensitive(meshName)) break; } if (meshIndex != m_meshes.GetSize()) { // name already in use meshAddSuffix++; meshName.Clear(); continue; } // use this name break; } // have to generate it StaticMeshGenerator *pGenerator = new StaticMeshGenerator(); uint32 lodIndex = pGenerator->AddLOD(); // parse each mesh for (uint32 subMeshIndex = 0; subMeshIndex < pNode->mNumMeshes; subMeshIndex++) { const aiMesh *pMesh = m_pScene->mMeshes[pNode->mMeshes[subMeshIndex]]; if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) { m_pProgressCallbacks->DisplayFormattedWarning("Skipping non-triangle mesh %u", subMeshIndex); continue; } if (pMesh->mNumVertices == 0 || pMesh->mNumFaces == 0) { m_pProgressCallbacks->DisplayFormattedWarning("Skipping empty mesh %u", subMeshIndex); continue; } if (!ParseMesh(pMesh, pGenerator, lodIndex, meshName)) { delete pGenerator; return false; } } // store it OutputMesh mesh; mesh.pSourceMeshes = pNode->mMeshes; mesh.nSourceMeshes = pNode->mNumMeshes; mesh.MeshName = meshName; mesh.pGenerator = pGenerator; mesh.Offset.SetZero(); // center mesh if (m_pOptions->CenterMeshes != StaticMeshGenerator::CenterOrigin_Count) pGenerator->CenterMesh((StaticMeshGenerator::CenterOrigin)m_pOptions->CenterMeshes, &mesh.Offset); // finalize mesh if (!FinalizeMesh(pGenerator, meshName)) { delete pGenerator; return false; } // add to list m_meshes.Add(mesh); } const OutputMesh &outputMesh = m_meshes[meshIndex]; // get mesh translation matrix aiMatrix4x4 meshTranslation; aiMatrix4x4::Translation(aiVector3D(outputMesh.Offset.x, outputMesh.Offset.y, outputMesh.Offset.z), meshTranslation); // work out transform - remove the global transform first, remove the mesh offset, move it into place, and reapply global transform aiMatrix4x4 newNodeTransform = meshTranslation.Inverse() * Float4x4ToAssimpMatrix4x4(m_globalTransform) * nodeTransform * //meshTranslation * Float4x4ToAssimpMatrix4x4(m_globalTransform.Inverse()) * meshTranslation; // decompose transform aiVector3D dcPosition; aiQuaternion dcRotation; aiVector3D dcScale; newNodeTransform.Decompose(dcScale, dcRotation, dcPosition); // create the instance OutputMeshInstance meshInstance; meshInstance.MeshIndex = meshIndex; meshInstance.Position = AssimpVector3ToFloat3(dcPosition);// -outputMesh.Offset; meshInstance.Rotation = AssimpQuaternionToQuaternion(dcRotation); meshInstance.Scale = AssimpVector3ToFloat3(dcScale); m_meshInstances.Add(meshInstance); m_pProgressCallbacks->DisplayFormattedInformation("NNR: %f %f %f %f", dcRotation.x, dcRotation.y, dcRotation.z, dcRotation.w); } // parse node children for (uint32 i = 0; i < pNode->mNumChildren; i++) { if (!ParseNode(pNode->mChildren[i], &nodeTransform)) return false; } // ok return true; } bool AssimpSceneImporter::ParseMesh(const aiMesh *pMesh, StaticMeshGenerator *pOutputGenerator, uint32 lodIndex, const char *meshName) { // CS transform //const aiMatrix4x4 CSTransformMatrix(AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4()); // for each mesh... //uint64 smoothingGroupMask = (1 << 0); // create output mesh, using max nweights for now //m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] using material %s", meshName, m_pOutputGenerator->GetMaterialNameByIndex(m_materialMapping[pMesh->mMaterialIndex]).GetCharArray()); // set mesh flags if (pMesh->GetNumUVChannels() > 0) pOutputGenerator->SetVertexTextureCoordinatesEnabled(true); if (pMesh->GetNumColorChannels() > 0) pOutputGenerator->SetVertexColorsEnabled(true); // for this mesh PODArray<uint32> meshVertexIndices; // create the batch DebugAssert(pMesh->mMaterialIndex < m_materialMapping.GetSize()); uint32 batchIndex = pOutputGenerator->AddBatch(lodIndex, m_materialMapping[pMesh->mMaterialIndex]); // create vertices without any weights in them for (uint32 vertexIndex = 0; vertexIndex < pMesh->mNumVertices; vertexIndex++) { float3 vertexPosition = m_globalTransform.TransformPoint(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mVertices[vertexIndex])); //float3 vertexPosition = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mVertices[vertexIndex])); float2 vertexTextureCoordinates = ((pMesh->GetNumUVChannels() > 0) ? AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTextureCoords[0][vertexIndex]).xy() : float2::Zero); uint32 vertexColor = ((pMesh->GetNumColorChannels() > 0) ? AssimpHelpers::AssimpColor4ToColor(pMesh->mColors[0][vertexIndex]) : MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); float3 vertexTangent; float3 vertexBinormal; float3 vertexNormal; if (pMesh->HasTangentsAndBitangents()) { vertexTangent = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTangents[vertexIndex])); vertexBinormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mBitangents[vertexIndex])); vertexNormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else if (pMesh->HasNormals()) { vertexTangent = float3::UnitX; vertexBinormal = float3::UnitY; vertexNormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else { vertexTangent = float3::UnitX; vertexBinormal = float3::UnitY; vertexNormal = float3::UnitZ; } // add to list uint32 outVertexIndex = pOutputGenerator->AddVertex(lodIndex, vertexPosition, vertexTangent, vertexBinormal, vertexNormal, vertexTextureCoordinates, vertexColor); meshVertexIndices.Add(outVertexIndex); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u vertices", meshName, pMesh->mNumVertices); // read triangles for (uint32 faceIndex = 0; faceIndex < pMesh->mNumFaces; faceIndex++) { const aiFace *pFace = &pMesh->mFaces[faceIndex]; if (pFace->mNumIndices != 3) { m_pProgressCallbacks->DisplayFormattedError("in mesh %s: face %u does not have 3 indices", meshName, faceIndex); return false; } DebugAssert(pFace->mIndices[0] < meshVertexIndices.GetSize() && pFace->mIndices[1] < meshVertexIndices.GetSize() && pFace->mIndices[2] < meshVertexIndices.GetSize()); pOutputGenerator->AddTriangle(lodIndex, batchIndex, meshVertexIndices[pFace->mIndices[0]], meshVertexIndices[pFace->mIndices[1]], meshVertexIndices[pFace->mIndices[2]]); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u faces/triangles", meshName, pMesh->mNumFaces); return true; } bool AssimpSceneImporter::FinalizeMesh(StaticMeshGenerator *pOutputGenerator, const char *meshName) { if (!pOutputGenerator->IsCompleteMesh()) return false; pOutputGenerator->GenerateTangents(0); pOutputGenerator->CalculateBounds(); // build collision shape if (m_pOptions->BuildCollisionShapeType != StaticMeshGenerator::CollisionShapeType_Count) { // build box m_pProgressCallbacks->DisplayFormattedInformation("Generating collision shape..."); if (!pOutputGenerator->BuildCollisionShape((StaticMeshGenerator::CollisionShapeType)m_pOptions->BuildCollisionShapeType)) { m_pProgressCallbacks->DisplayError("Failed to generate collision shape."); return false; } } return true; } bool AssimpSceneImporter::WriteMeshes() { PathString outputResourceFileName; // write meshes for (uint32 meshIndex = 0; meshIndex < m_meshes.GetSize(); meshIndex++) { outputResourceFileName.Format("%s.staticmesh.xml", m_meshes[meshIndex].MeshName.GetCharArray()); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputResourceFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not open file '%s'", outputResourceFileName.GetCharArray()); return false; } if (!m_meshes[meshIndex].pGenerator->SaveToXML(pStream)) { m_pProgressCallbacks->DisplayError("failed to save xml file"); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); } return true; } bool AssimpSceneImporter::WriteMap() { // get template for StaticMeshBrush const ObjectTemplate *pStaticMeshTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("StaticMeshBrush"); if (pStaticMeshTemplate == nullptr) { m_pProgressCallbacks->DisplayError("Failed to get StaticMeshBrush template."); return false; } // create map MapSource *pMapSource = new MapSource(); pMapSource->Create(); // create entities for (uint32 i = 0; i < m_meshInstances.GetSize(); i++) { // get mesh const OutputMeshInstance &meshInstance = m_meshInstances[i]; const OutputMesh &mesh = m_meshes[meshInstance.MeshIndex]; // create entity MapSourceEntityData *pEntityData = pMapSource->CreateEntityFromTemplate(pStaticMeshTemplate); DebugAssert(pEntityData != nullptr); // set mesh name property pEntityData->SetPropertyValue("StaticMeshName", mesh.MeshName); // work out the transform float3 offsetPosition(meshInstance.Position + mesh.Offset); pEntityData->SetPropertyValueFloat3("Position", offsetPosition); pEntityData->SetPropertyValueQuaternion("Rotation", meshInstance.Rotation); pEntityData->SetPropertyValueFloat3("Scale", meshInstance.Scale); } // write out the map bool result = pMapSource->SaveAs(m_pOptions->OutputMapName, m_pProgressCallbacks); delete pMapSource; return result; } <file_sep>/Editor/Source/Editor/moc_EditorResourcePreviewWidget.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorResourcePreviewWidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorResourcePreviewWidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorResourcePreviewWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorResourcePreviewWidget_t { QByteArrayData data[24]; char stringdata[515]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorResourcePreviewWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorResourcePreviewWidget_t qt_meta_stringdata_EditorResourcePreviewWidget = { { QT_MOC_LITERAL(0, 0, 27), // "EditorResourcePreviewWidget" QT_MOC_LITERAL(1, 28, 13), // "OnFocusGained" QT_MOC_LITERAL(2, 42, 0), // "" QT_MOC_LITERAL(3, 43, 11), // "OnFocusLost" QT_MOC_LITERAL(4, 55, 29), // "OnToolbarViewWireframeClicked" QT_MOC_LITERAL(5, 85, 7), // "checked" QT_MOC_LITERAL(6, 93, 25), // "OnToolbarViewUnlitClicked" QT_MOC_LITERAL(7, 119, 23), // "OnToolbarViewLitClicked" QT_MOC_LITERAL(8, 143, 32), // "OnToolbarViewLightingOnlyClicked" QT_MOC_LITERAL(9, 176, 27), // "OnToolbarFlagShadowsClicked" QT_MOC_LITERAL(10, 204, 36), // "OnToolbarFlagWireframeOverlay..." QT_MOC_LITERAL(11, 241, 24), // "OnSwapChainWidgetResized" QT_MOC_LITERAL(12, 266, 22), // "OnSwapChainWidgetPaint" QT_MOC_LITERAL(13, 289, 30), // "OnSwapChainWidgetKeyboardEvent" QT_MOC_LITERAL(14, 320, 16), // "const QKeyEvent*" QT_MOC_LITERAL(15, 337, 14), // "pKeyboardEvent" QT_MOC_LITERAL(16, 352, 27), // "OnSwapChainWidgetMouseEvent" QT_MOC_LITERAL(17, 380, 18), // "const QMouseEvent*" QT_MOC_LITERAL(18, 399, 11), // "pMouseEvent" QT_MOC_LITERAL(19, 411, 27), // "OnSwapChainWidgetWheelEvent" QT_MOC_LITERAL(20, 439, 18), // "const QWheelEvent*" QT_MOC_LITERAL(21, 458, 11), // "pWheelEvent" QT_MOC_LITERAL(22, 470, 25), // "OnFrameExecutionTriggered" QT_MOC_LITERAL(23, 496, 18) // "timeSinceLastFrame" }, "EditorResourcePreviewWidget\0OnFocusGained\0" "\0OnFocusLost\0OnToolbarViewWireframeClicked\0" "checked\0OnToolbarViewUnlitClicked\0" "OnToolbarViewLitClicked\0" "OnToolbarViewLightingOnlyClicked\0" "OnToolbarFlagShadowsClicked\0" "OnToolbarFlagWireframeOverlayClicked\0" "OnSwapChainWidgetResized\0" "OnSwapChainWidgetPaint\0" "OnSwapChainWidgetKeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "OnSwapChainWidgetMouseEvent\0" "const QMouseEvent*\0pMouseEvent\0" "OnSwapChainWidgetWheelEvent\0" "const QWheelEvent*\0pWheelEvent\0" "OnFrameExecutionTriggered\0timeSinceLastFrame" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorResourcePreviewWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 14, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 84, 2, 0x08 /* Private */, 3, 0, 85, 2, 0x08 /* Private */, 4, 1, 86, 2, 0x08 /* Private */, 6, 1, 89, 2, 0x08 /* Private */, 7, 1, 92, 2, 0x08 /* Private */, 8, 1, 95, 2, 0x08 /* Private */, 9, 1, 98, 2, 0x08 /* Private */, 10, 1, 101, 2, 0x08 /* Private */, 11, 0, 104, 2, 0x08 /* Private */, 12, 0, 105, 2, 0x08 /* Private */, 13, 1, 106, 2, 0x08 /* Private */, 16, 1, 109, 2, 0x08 /* Private */, 19, 1, 112, 2, 0x08 /* Private */, 22, 1, 115, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Bool, 5, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 14, 15, QMetaType::Void, 0x80000000 | 17, 18, QMetaType::Void, 0x80000000 | 20, 21, QMetaType::Void, QMetaType::Float, 23, 0 // eod }; void EditorResourcePreviewWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorResourcePreviewWidget *_t = static_cast<EditorResourcePreviewWidget *>(_o); switch (_id) { case 0: _t->OnFocusGained(); break; case 1: _t->OnFocusLost(); break; case 2: _t->OnToolbarViewWireframeClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 3: _t->OnToolbarViewUnlitClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 4: _t->OnToolbarViewLitClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnToolbarViewLightingOnlyClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnToolbarFlagShadowsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnToolbarFlagWireframeOverlayClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnSwapChainWidgetResized(); break; case 9: _t->OnSwapChainWidgetPaint(); break; case 10: _t->OnSwapChainWidgetKeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 11: _t->OnSwapChainWidgetMouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 12: _t->OnSwapChainWidgetWheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 13: _t->OnFrameExecutionTriggered((*reinterpret_cast< float(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorResourcePreviewWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorResourcePreviewWidget.data, qt_meta_data_EditorResourcePreviewWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorResourcePreviewWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorResourcePreviewWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorResourcePreviewWidget.stringdata)) return static_cast<void*>(const_cast< EditorResourcePreviewWidget*>(this)); return QWidget::qt_metacast(_clname); } int EditorResourcePreviewWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 14) qt_static_metacall(this, _c, _id, _a); _id -= 14; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 14) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 14; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ResourceCompiler/ResourceCompilerInterfaceRemoteServer.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompilerInterface/ResourceCompilerInterfaceRemote.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/MaterialShader.h" #include "Engine/MaterialShader.h" #include "Engine/Skeleton.h" #include "Renderer/ShaderComponentTypeInfo.h" #include "Renderer/VertexFactoryTypeInfo.h" #include "Renderer/ShaderCompilerFrontend.h" #include "YBaseLib/BinaryWriteBuffer.h" #include "YBaseLib/BinaryReadBuffer.h" Log_SetChannel(ResourceCompilerInterfaceRemote); static bool SendCommandAndPayload(Subprocess::Connection *pConnection, REMOTE_COMMAND command, const void *payload, uint32 payloadSize) { REMOTE_COMMAND_HEADER hdr; hdr.Command = command; hdr.PayloadSize = payloadSize; if (pConnection->WriteData(&hdr, sizeof(hdr)) != sizeof(hdr)) return false; if (payloadSize > 0 && pConnection->WriteData(payload, payloadSize) != payloadSize) return false; return true; } static bool WaitForCommandResult(Subprocess::Connection *pConnection, BinaryBlob **ppResultsBlob) { for (;;) { REMOTE_COMMAND_HEADER hdr; if (pConnection->ReadDataBlocking(&hdr, sizeof(hdr)) != sizeof(hdr)) { *ppResultsBlob = nullptr; return false; } switch (hdr.Command) { case REMOTE_COMMAND_SUCCESS: case REMOTE_COMMAND_FAILURE: { if (hdr.PayloadSize == 0) { *ppResultsBlob = nullptr; } else { BinaryBlob *pBlob = BinaryBlob::Allocate(hdr.PayloadSize); if (pConnection->ReadDataBlocking(pBlob->GetDataPointer(), hdr.PayloadSize) != hdr.PayloadSize) { pBlob->Release(); *ppResultsBlob = nullptr; return false; } *ppResultsBlob = pBlob; } return (hdr.Command == REMOTE_COMMAND_SUCCESS); } break; } } } struct RemoteProcessCallbacks : public ResourceCompilerCallbacks { RemoteProcessCallbacks(Subprocess::Connection *pConnection) : m_pConnection(pConnection) {} virtual BinaryBlob *GetFileContents(const char *name) override { if (!SendCommandAndPayload(m_pConnection, REMOTE_COMMAND_GET_FILE_CONTENTS, name, Y_strlen(name))) return nullptr; BinaryBlob *pBlob; if (!WaitForCommandResult(m_pConnection, &pBlob) && pBlob != nullptr) { pBlob->Release(); pBlob = nullptr; } return pBlob; } virtual const MaterialShader *GetCompiledMaterialShader(const char *name) override { if (!SendCommandAndPayload(m_pConnection, REMOTE_COMMAND_GET_COMPILED_MATERIAL_SHADER, name, Y_strlen(name))) return nullptr; BinaryBlob *pBlob; if (!WaitForCommandResult(m_pConnection, &pBlob)) { if (pBlob != nullptr) pBlob->Release(); return nullptr; } MaterialShader *pMaterialShader = new MaterialShader(); ByteStream *pStream = pBlob->CreateReadOnlyStream(); if (!pMaterialShader->Load(name, pStream)) { Log_ErrorPrintf("RemoteProcessCallbacks::GetCompiledMaterialShader: Failed to load MaterialShader data provided by client (name: %s)", name); pStream->Release(); pMaterialShader->Release(); return nullptr; } pStream->Release(); pBlob->Release(); return pMaterialShader; } virtual const Skeleton *GetCompiledSkeleton(const char *name) override { if (!SendCommandAndPayload(m_pConnection, REMOTE_COMMAND_GET_COMPILED_SKELETON, name, Y_strlen(name))) return nullptr; BinaryBlob *pBlob; if (!WaitForCommandResult(m_pConnection, &pBlob)) { if (pBlob != nullptr) pBlob->Release(); return nullptr; } Skeleton *pSkeleton = new Skeleton(); ByteStream *pStream = pBlob->CreateReadOnlyStream(); if (!pSkeleton->LoadFromStream(name, pStream)) { Log_ErrorPrintf("RemoteProcessCallbacks::GetCompiledSkeleton: Failed to load skeleton data provided by client (name: %s)", name); pStream->Release(); pSkeleton->Release(); return nullptr; } pStream->Release(); pBlob->Release(); return pSkeleton; } private: Subprocess::Connection *m_pConnection; }; static BinaryBlob *ProcessCompileFontCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; uint32 texturePlatform; if (!buffer.SafeReadUInt32(&texturePlatform) || !buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile texture command"); return nullptr; } Log_InfoPrintf("Compiling font '%s' for platform '%s'", resourceName.GetCharArray(), NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); return ResourceCompiler::CompileFont(pCallbacks, (TEXTURE_PLATFORM)texturePlatform, resourceName); } static BinaryBlob *ProcessCompileTextureCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; uint32 texturePlatform; if (!buffer.SafeReadUInt32(&texturePlatform) || !buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile texture command"); return nullptr; } Log_InfoPrintf("Compiling texture '%s' for platform '%s'", resourceName.GetCharArray(), NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); return ResourceCompiler::CompileTexture(pCallbacks, (TEXTURE_PLATFORM)texturePlatform, resourceName); } static BinaryBlob *ProcessCompileMaterialCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile material command"); return nullptr; } Log_InfoPrintf("Compiling material '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileMaterial(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileMaterialShaderCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile material shader command"); return nullptr; } Log_InfoPrintf("Compiling material shader '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileMaterialShader(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileStaticMeshCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile static mesh command"); return nullptr; } Log_InfoPrintf("Compiling static mesh '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileStaticMesh(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileSkeletonCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile skeleton command"); return nullptr; } Log_InfoPrintf("Compiling skeleton '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileSkeleton(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileSkeletalMeshCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile skeletal mesh command"); return nullptr; } Log_InfoPrintf("Compiling skeletal mesh '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileSkeletalMesh(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileSkeletalAnimationCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile skeletal animation command"); return nullptr; } Log_InfoPrintf("Compiling skeletal animation '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileSkeletalAnimation(pCallbacks, resourceName); } static BinaryBlob *ProcessCompileBlockPaletteCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; uint32 texturePlatform; if (!buffer.SafeReadUInt32(&texturePlatform) || !buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile block palette command"); return nullptr; } Log_InfoPrintf("Compiling block palette '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileBlockPalette(pCallbacks, (TEXTURE_PLATFORM)texturePlatform, resourceName); } static BinaryBlob *ProcessCompileBlockMeshCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { String resourceName; if (!buffer.SafeReadSizePrefixedString(&resourceName)) { Log_ErrorPrintf("Failed to parse compile block mesh command"); return nullptr; } Log_InfoPrintf("Compiling block mesh '%s'", resourceName.GetCharArray()); return ResourceCompiler::CompileBlockMesh(pCallbacks, resourceName); } static bool ProcessCompileShaderCommand(Subprocess::Connection *pConnection, RemoteProcessCallbacks *pCallbacks, BinaryReadBuffer &buffer) { uint32 rendererPlatform; uint32 rendererFeatureLevel; uint32 compilerFlags; if (!buffer.SafeReadUInt32(&rendererPlatform) || !buffer.SafeReadUInt32(&rendererFeatureLevel) || !buffer.SafeReadUInt32(&compilerFlags)) { Log_ErrorPrintf("Failed to parse compile shader command"); return false; } ShaderCompilerParameters compilerParameters; compilerParameters.Platform = (RENDERER_PLATFORM)rendererPlatform; compilerParameters.FeatureLevel = (RENDERER_FEATURE_LEVEL)rendererFeatureLevel; compilerParameters.CompilerFlags = compilerFlags; // read stage info for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (!buffer.SafeReadSizePrefixedString(&compilerParameters.StageFileNames[i]) || !buffer.SafeReadSizePrefixedString(&compilerParameters.StageEntryPoints[i])) { Log_ErrorPrintf("Failed to parse compile shader command"); return false; } } uint32 macroCount; if (!buffer.SafeReadSizePrefixedString(&compilerParameters.VertexFactoryFileName) || !buffer.SafeReadSizePrefixedString(&compilerParameters.MaterialShaderName) || !buffer.SafeReadUInt32(&compilerParameters.MaterialShaderFlags) || !buffer.SafeReadBool(&compilerParameters.EnableVerboseInfoLog) || !buffer.SafeReadUInt32(&macroCount)) { Log_ErrorPrintf("Failed to parse compile shader command"); return false; } // read macros for (uint32 i = 0; i < macroCount; i++) { ShaderCompilerParameters::PreprocessorMacro macro; if (!buffer.SafeReadSizePrefixedString(&macro.Key) || !buffer.SafeReadSizePrefixedString(&macro.Value)) { Log_ErrorPrintf("Failed to parse compile shader command"); return false; } Log_DevPrintf(" Preprocessor macro: %s %s", macro.Key.GetCharArray(), macro.Value.GetCharArray()); compilerParameters.PreprocessorMacros.Add(macro); } // pass through to shader compiler GrowableMemoryByteStream *pCodeStream = ByteStream_CreateGrowableMemoryStream(); GrowableMemoryByteStream *pInfoLogStream = (compilerParameters.EnableVerboseInfoLog) ? ByteStream_CreateGrowableMemoryStream() : nullptr; bool result = ResourceCompiler::CompileShader(pCallbacks, &compilerParameters, pCodeStream, pInfoLogStream); // still append the streams BinaryWriteBuffer outBuffer; outBuffer.WriteUInt32((uint32)pCodeStream->GetSize()); outBuffer.WriteUInt32((pInfoLogStream != nullptr) ? (uint32)pInfoLogStream->GetSize() : 0); pCodeStream->SeekAbsolute(0); ByteStream_AppendStream(pCodeStream, outBuffer.GetStream()); if (pInfoLogStream != nullptr) { pInfoLogStream->SeekAbsolute(0); ByteStream_AppendStream(pInfoLogStream, outBuffer.GetStream()); } if (pInfoLogStream != nullptr) pInfoLogStream->Release(); pCodeStream->Release(); // write output return SendCommandAndPayload(pConnection, (result) ? REMOTE_COMMAND_SUCCESS : REMOTE_COMMAND_FAILURE, outBuffer.GetBufferPointer(), outBuffer.GetBufferSize()); } void ResourceCompilerInterfaceRemote::RemoteProcessLoop() { Log_DevPrintf("ResourceCompilerInterfaceRemote::RemoteProcessLoop: Connecting to parent..."); Subprocess::Connection *pConnection = Subprocess::ConnectToParent(); if (pConnection == nullptr) { Log_ErrorPrint("ResourceCompilerInterfaceRemote::RemoteProcessLoop: Failed to connect to parent."); return; } // Create callback interface RemoteProcessCallbacks callbacks(pConnection); bool exitingWithError = false; // Main loop while (!pConnection->IsExitRequested() && pConnection->IsOtherSideAlive()) { REMOTE_COMMAND_HEADER hdr; if (pConnection->ReadDataBlocking(&hdr, sizeof(hdr)) != sizeof(hdr)) { Log_ErrorPrintf("Failed to read command id"); exitingWithError = true; break; } // Handle exit command Log_DevPrintf("Recv command %u size %u", hdr.Command, hdr.PayloadSize); if (hdr.Command == REMOTE_COMMAND_EXIT) break; // Create a buffer of the received payload BinaryReadBuffer buffer(hdr.PayloadSize); Log_DevPrintf("buf sz = %u, ptr = %p", buffer.GetBufferSize(), buffer.GetBufferPointer()); if (pConnection->ReadDataBlocking(buffer.GetBufferPointer(), hdr.PayloadSize) != hdr.PayloadSize) { Log_ErrorPrintf("Failed to read remaining payload bytes"); exitingWithError = true; break; } // Invoke correct method based on type. BinaryBlob *pReturnBlob = nullptr; switch (hdr.Command) { case REMOTE_COMMAND_COMPILE_FONT: pReturnBlob = ProcessCompileFontCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_TEXTURE: pReturnBlob = ProcessCompileTextureCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_MATERIAL_SHADER: pReturnBlob = ProcessCompileMaterialShaderCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_MATERIAL: pReturnBlob = ProcessCompileMaterialCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_STATIC_MESH: pReturnBlob = ProcessCompileStaticMeshCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_SKELETON: pReturnBlob = ProcessCompileSkeletonCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_SKELETAL_MESH: pReturnBlob = ProcessCompileSkeletalMeshCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_SKELETAL_ANIMATION: pReturnBlob = ProcessCompileSkeletalAnimationCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_BLOCK_PALETTE: pReturnBlob = ProcessCompileBlockPaletteCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_BLOCK_MESH: pReturnBlob = ProcessCompileBlockMeshCommand(pConnection, &callbacks, buffer); break; case REMOTE_COMMAND_COMPILE_SHADER: { if (!ProcessCompileShaderCommand(pConnection, &callbacks, buffer)) { Log_ErrorPrintf("Failed to process compile shader command"); exitingWithError = true; break; } } continue; } // Send resource back if (pReturnBlob != nullptr) { if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_SUCCESS, pReturnBlob->GetDataPointer(), pReturnBlob->GetDataSize())) { Log_ErrorPrintf("Failed to send success and data"); pReturnBlob->Release(); exitingWithError = true; break; } pReturnBlob->Release(); } else { if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_FAILURE, nullptr, 0)) { Log_ErrorPrintf("Failed to send failure code"); exitingWithError = true; break; } } } if (exitingWithError) Thread::Sleep(2500); } <file_sep>/Engine/Source/Renderer/VertexBufferBindingArray.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" class VertexBufferBindingArray { public: VertexBufferBindingArray(); VertexBufferBindingArray(const VertexBufferBindingArray &vbb); ~VertexBufferBindingArray(); GPUBuffer *GetBuffer(uint32 bufferIndex) const { DebugAssert(bufferIndex < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS); return m_pVertexBuffers[bufferIndex]; } uint32 GetBufferOffset(uint32 bufferIndex) const { DebugAssert(bufferIndex < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS); return m_iVertexBufferOffsets[bufferIndex]; } uint32 GetBufferStride(uint32 bufferIndex) const { DebugAssert(bufferIndex < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS); return m_iVertexBufferStrides[bufferIndex]; } GPUBuffer *const *GetBuffers() const { return m_pVertexBuffers; } const uint32 *GetBufferOffsets() const { return m_iVertexBufferOffsets; } const uint32 *GetBufferStrides() const { return m_iVertexBufferStrides; } const uint32 GetActiveBufferCount() const { return m_nActiveBuffers; } void SetBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride); void BindBuffers(GPUCommandList *pCommandList) const; void Clear(); // sets debug name on all bound buffers void SetDebugName(const char *debugName); VertexBufferBindingArray &operator=(const VertexBufferBindingArray &vbb); private: GPUBuffer *m_pVertexBuffers[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_iVertexBufferOffsets[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_iVertexBufferStrides[GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS]; uint32 m_nActiveBuffers; };<file_sep>/Editor/Source/Editor/MapEditor/EditorMapEntity.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "Editor/EditorVisual.h" #include "Editor/EditorVisualComponent.h" #include "Editor/Editor.h" #include "MapCompiler/MapSource.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "Engine/Entity.h" #include "Renderer/RenderProxy.h" #include "Renderer/RenderWorld.h" Log_SetChannel(EditorMapEntity); EditorMapEntity::EditorMapEntity(EditorMap *pMap, uint32 arrayIndex, const ObjectTemplate *pTemplate, const EditorVisualDefinition *pVisualDefinition, MapSourceEntityData *pEntityData) : m_pMap(pMap), m_arrayIndex(arrayIndex), m_pTemplate(pTemplate), m_pVisualDefinition(pVisualDefinition), m_pEntityData(pEntityData), m_pVisualInstance(nullptr), m_visualsCreated(false), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_position(float3::Zero), m_rotation(Quaternion::Identity), m_scale(float3::One), m_selected(false) { } EditorMapEntity::~EditorMapEntity() { for (uint32 i = 0; i < m_components.GetSize(); i++) delete m_components[i].pVisual; delete m_pVisualInstance; } const bool EditorMapEntity::IsBrush() const { const ObjectTemplate *pBaseTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("StaticObject"); DebugAssert(pBaseTemplate != nullptr); return m_pTemplate->IsDerivedFrom(pBaseTemplate); } const bool EditorMapEntity::IsEntity() const { const ObjectTemplate *pBaseTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("Entity"); DebugAssert(pBaseTemplate != nullptr); return m_pTemplate->IsDerivedFrom(pBaseTemplate); } void EditorMapEntity::CreateVisual() { if (m_visualsCreated) return; m_pVisualInstance = EditorVisualInstance::Create(m_arrayIndex + 1, m_pVisualDefinition, m_pEntityData->GetPropertyTable()); if (m_pVisualInstance != nullptr) { m_pVisualInstance->AddToRenderWorld(m_pMap->GetRenderWorld()); // fix up selected state m_pVisualInstance->OnSelectedStateChanged(m_selected); // fix up bounding box if (m_boundingBox != m_pVisualInstance->GetBoundingBox()) { m_boundingBox = m_pVisualInstance->GetBoundingBox(); m_pMap->OnEntityBoundsChanged(this); } m_boundingSphere = m_pVisualInstance->GetBoundingSphere(); } for (uint32 i = 0; i < m_components.GetSize(); i++) { ComponentData *data = &m_components[i]; DebugAssert(data->pVisual == nullptr); InternalCreateComponentVisual(data); } m_visualsCreated = true; } void EditorMapEntity::DeleteVisual() { for (uint32 i = 0; i < m_components.GetSize(); i++) delete m_components[i].pVisual; delete m_pVisualInstance; m_pVisualInstance = nullptr; m_visualsCreated = false; } EditorMapEntity *EditorMapEntity::Create(EditorMap *pMap, uint32 arrayIndex, MapSourceEntityData *pEntityData) { // find object template const ObjectTemplate *pTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pEntityData->GetTypeName()); if (pTemplate == nullptr) { Log_WarningPrintf("No object template found for type '%s' referenced by entity '%s'. No visual will be shown, and the entity will not be editable.", pEntityData->GetTypeName().GetCharArray(), pEntityData->GetEntityName().GetCharArray()); return nullptr; } // find definition for this entity type const EditorVisualDefinition *pVisualDefinition = g_pEditor->GetVisualDefinitionForObjectTemplate(pTemplate); if (pVisualDefinition == nullptr) { Log_WarningPrintf("No visual definition found for type '%s' referenced by entity '%s'. No visual will be shown.", pEntityData->GetTypeName().GetCharArray(), pEntityData->GetEntityName().GetCharArray()); return nullptr; } // create object EditorMapEntity *pMapEntity = new EditorMapEntity(pMap, arrayIndex, pTemplate, pVisualDefinition, pEntityData); // import transform { const String *propertyValue; // position propertyValue = pEntityData->GetPropertyValuePointer("Position"); if (propertyValue != nullptr) pMapEntity->m_position = StringConverter::StringToFloat3(*propertyValue); // rotation propertyValue = pEntityData->GetPropertyValuePointer("Rotation"); if (propertyValue != nullptr) pMapEntity->m_rotation = StringConverter::StringToQuaternion(*propertyValue); // scale propertyValue = pEntityData->GetPropertyValuePointer("Scale"); if (propertyValue != nullptr) pMapEntity->m_scale = StringConverter::StringToFloat3(*propertyValue); } // set inital bounding box pMapEntity->m_boundingBox.SetBounds(pMapEntity->m_position, pMapEntity->m_position); pMapEntity->m_boundingSphere.SetCenter(pMapEntity->m_position); // create components for (uint32 componentIndex = 0; componentIndex < pEntityData->GetComponentCount(); componentIndex++) { MapSourceEntityComponent *pComponentData = pEntityData->GetComponentByIndex(componentIndex); // get template const ObjectTemplate *pComponentTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pComponentData->GetTypeName()); if (pComponentTemplate == nullptr) { Log_WarningPrintf("No object template found for component type '%s' referenced by entity '%s'. No visual will be shown, and the component will not be editable.", pComponentData->GetTypeName().GetCharArray(), pEntityData->GetEntityName().GetCharArray()); continue; } // create internal copy pMapEntity->InternalCreateComponent(pComponentTemplate, pComponentData); } // all done return pMapEntity; } void EditorMapEntity::OnPropertyModified(const char *propertyName, const char *propertyValue) { // pass to visual if (m_pVisualInstance != nullptr) { m_pVisualInstance->OnPropertyModified(propertyName, propertyValue); if (m_boundingBox != m_pVisualInstance->GetBoundingBox()) { m_boundingBox = m_pVisualInstance->GetBoundingBox(); m_pMap->OnEntityBoundsChanged(this); } m_boundingSphere = m_pVisualInstance->GetBoundingSphere(); } // handle base position + rotation if (Y_stricmp(propertyName, "Position") == 0) { m_position = StringConverter::StringToFloat3(propertyValue); // handle psuedo-properties for components for (uint32 i = 0; i < m_components.GetSize(); i++) { ComponentData *data = &m_components[i]; if (data->pVisual != nullptr) data->pVisual->OnPropertyModified("Position", StringConverter::Float3ToString(m_position + data->pData->GetPropertyTable()->GetPropertyValueDefaultFloat3("LocalPosition", float3::Zero))); } } else if (Y_stricmp(propertyName, "Rotation") == 0) { m_rotation = StringConverter::StringToQuaternion(propertyValue); // handle psuedo-properties for components for (uint32 i = 0; i < m_components.GetSize(); i++) { ComponentData *data = &m_components[i]; if (data->pVisual != nullptr) data->pVisual->OnPropertyModified("Rotation", StringConverter::QuaternionToString((m_rotation * data->pData->GetPropertyTable()->GetPropertyValueDefaultQuaternion("LocalRotation", Quaternion::Identity)).Normalize())); } } else if (Y_stricmp(propertyName, "Scale") == 0) { m_scale = StringConverter::StringToFloat3(propertyValue); // handle psuedo-properties for components for (uint32 i = 0; i < m_components.GetSize(); i++) { ComponentData *data = &m_components[i]; if (data->pVisual != nullptr) data->pVisual->OnPropertyModified("Scale", StringConverter::Float3ToString(m_scale * data->pData->GetPropertyTable()->GetPropertyValueDefaultFloat3("LocalScale", float3::One))); } } // notify map m_pMap->OnEntityPropertyChanged(this, propertyName, propertyValue); } void EditorMapEntity::SetPosition(const float3 &position) { SetEntityPropertyValue("Position", StringConverter::Float3ToString(position)); } void EditorMapEntity::SetRotation(const Quaternion &rotation) { SetEntityPropertyValue("Rotation", StringConverter::QuaternionToString(rotation)); } void EditorMapEntity::SetScale(const float3 &scale) { SetEntityPropertyValue("Scale", StringConverter::Float3ToString(scale)); } void EditorMapEntity::OnSelectedStateChanged(bool selected) { if (m_visualsCreated) { if (m_pVisualInstance != nullptr) m_pVisualInstance->OnSelectedStateChanged(selected); for (uint32 i = 0; i < m_components.GetSize(); i++) { ComponentData *data = &m_components[i]; if (data->pVisual != nullptr) data->pVisual->OnSelectedStateChanged(selected); } } m_selected = selected; } void EditorMapEntity::OnComponentSelectedStateChanged(uint32 index, bool selected) { DebugAssert(index < m_components.GetSize()); ComponentData *data = &m_components[index]; if (data->pVisual != nullptr) data->pVisual->OnSelectedStateChanged(selected); } String EditorMapEntity::GetEntityPropertyValue(const char *propertyName) const { return m_pEntityData->GetPropertyValueString(propertyName); } bool EditorMapEntity::SetEntityPropertyValue(const char *propertyName, const char *propertyValue) { if (m_pTemplate->GetPropertyDefinitionByName(propertyName) == nullptr) { Log_WarningPrintf("Attempting to set non-existant property '%s' on entity '%s' to '%s'.", propertyName, m_pEntityData->GetEntityName().GetCharArray(), propertyValue); return false; } String oldValue = m_pEntityData->GetPropertyValueString(propertyName); if (oldValue == propertyValue) return true; m_pEntityData->SetPropertyValue(propertyName, propertyValue); // notify the visuals OnPropertyModified(propertyName, propertyValue); return true; } const ObjectTemplate *EditorMapEntity::GetComponentTemplate(uint32 index) const { return m_components[index].pTemplate; } const MapSourceEntityComponent *EditorMapEntity::GetComponentData(uint32 index) const { return m_components[index].pData; } String EditorMapEntity::GetComponentPropertyValue(uint32 index, const char *propertyName) const { return m_components[index].pData->GetPropertyValueString(propertyName); } void EditorMapEntity::SetComponentPropertyValue(uint32 index, const char *propertyName, const char *propertyValue) { ComponentData *data = &m_components[index]; data->pData->SetPropertyValue(propertyName, propertyValue); // handle positional if (data->pVisual != nullptr) { data->pVisual->OnPropertyModified(propertyName, propertyValue); // handle psuedo-properties if (Y_stricmp(propertyName, "LocalPosition") == 0) data->pVisual->OnPropertyModified("Position", StringConverter::Float3ToString(m_position + StringConverter::StringToFloat3(propertyValue))); else if (Y_stricmp(propertyName, "LocalRotation") == 0) data->pVisual->OnPropertyModified("Rotation", StringConverter::QuaternionToString((m_rotation * StringConverter::StringToQuaternion(propertyValue)).Normalize())); else if (Y_stricmp(propertyName, "LocalScale") == 0) data->pVisual->OnPropertyModified("Scale", StringConverter::Float3ToString(m_scale * StringConverter::StringToFloat3(propertyValue))); } } int32 EditorMapEntity::CreateComponent(const char *componentTypeName, const char *componentName /*= nullptr*/) { const ObjectTemplate *pTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(componentTypeName); if (pTemplate == nullptr) return -1; return CreateComponent(pTemplate, componentName); } int32 EditorMapEntity::CreateComponent(const ObjectTemplate *pTemplate, const char *componentName /*= nullptr*/) { // forward through MapSourceEntityComponent *pComponentData = m_pEntityData->CreateComponent(pTemplate, componentName); if (pComponentData == nullptr) return -1; return (int32)InternalCreateComponent(pTemplate, pComponentData); } uint32 EditorMapEntity::InternalCreateComponent(const ObjectTemplate *pTemplate, MapSourceEntityComponent *pComponentData) { // find definition for this entity type const EditorVisualDefinition *pVisualDefinition = g_pEditor->GetVisualDefinitionForObjectTemplate(pTemplate); if (pVisualDefinition == nullptr) Log_WarningPrintf("No visual definition found for component type '%s' referenced by entity '%s'. No visual will be shown.", pComponentData->GetTypeName().GetCharArray(), m_pEntityData->GetEntityName().GetCharArray()); // create our structure ComponentData entry; entry.pTemplate = pTemplate; entry.pVisualDefinition = pVisualDefinition; entry.pData = pComponentData; entry.pVisual = nullptr; // create visual if the entity's visuals are created if (m_visualsCreated) InternalCreateComponentVisual(&entry); // add to list uint32 returnValue = m_components.GetSize(); m_components.Add(entry); return returnValue; } void EditorMapEntity::InternalCreateComponentVisual(ComponentData *data) { if (data->pVisualDefinition == nullptr) return; data->pVisual = EditorVisualInstance::Create(m_arrayIndex + 1, data->pVisualDefinition, data->pData->GetPropertyTable()); if (data->pVisual != nullptr) { // create psuedo-properties data->pVisual->OnPropertyModified("Position", StringConverter::Float3ToString(m_position + data->pData->GetPropertyTable()->GetPropertyValueDefaultFloat3("LocalPosition", float3::Zero))); data->pVisual->OnPropertyModified("Rotation", StringConverter::QuaternionToString((m_rotation * data->pData->GetPropertyTable()->GetPropertyValueDefaultQuaternion("LocalRotation", Quaternion::Identity)).Normalize())); data->pVisual->OnPropertyModified("Scale", StringConverter::Float3ToString(m_scale * data->pData->GetPropertyTable()->GetPropertyValueDefaultFloat3("LocalScale", float3::One))); // add to world data->pVisual->AddToRenderWorld(m_pMap->GetRenderWorld()); // fix up selected state data->pVisual->OnSelectedStateChanged(m_selected); // fix up bounding box AABox newBoundingBox(AABox::Merge(m_boundingBox, data->pVisual->GetBoundingBox())); if (newBoundingBox != m_boundingBox) { m_boundingBox = newBoundingBox; m_pMap->OnEntityBoundsChanged(this); } // update bounding sphere m_boundingSphere = Sphere::Merge(m_boundingSphere, data->pVisual->GetBoundingSphere()); } } void EditorMapEntity::RemoveComponent(uint32 index) { DebugAssert(index < m_components.GetSize()); ComponentData *data = &m_components[index]; m_pEntityData->RemoveComponent(data->pData); delete data->pVisual; m_components.OrderedRemove(index); } <file_sep>/Editor/Source/Editor/EditorVisual.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorVisual.h" #include "Editor/EditorVisualComponent.h" #include "Editor/Editor.h" #include "ResourceCompiler/ObjectTemplate.h" #include "YBaseLib/XMLReader.h" Log_SetChannel(EditorVisualDefinition); static const char *MISSING_VISUAL_TYPE_NAME = "__missing__"; static const char *VISUAL_BASE_PATH = "resources/engine/editor_visuals"; EditorVisualDefinition::EditorVisualDefinition() { } EditorVisualDefinition::~EditorVisualDefinition() { for (uint32 i = 0; i < m_visualComponentDefinitions.GetSize(); i++) delete m_visualComponentDefinitions[i]; } bool EditorVisualDefinition::CreateFromName(const char *name) { bool loadMissing = false; PathString fileName; // init name m_strName = name; // load this name { // format filename fileName.Format("%s/%s.xml", VISUAL_BASE_PATH, name); // try opening it AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // try loading from stream if (!LoadComponentsFromStream(fileName, pStream)) loadMissing = true; } else { Log_WarningPrintf("EditorVisualDefinition::CreateFromName: No visual template found for '%s'.", name); loadMissing = true; } } // have to load the missing type? if (loadMissing || m_visualComponentDefinitions.GetSize() == 0) { fileName.Format("%s/%s.xml", VISUAL_BASE_PATH, MISSING_VISUAL_TYPE_NAME); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr || !LoadComponentsFromStream(fileName, pStream)) { Log_ErrorPrintf("EditorVisualDefinition::CreateFromTemplate: Failed to load missing visual."); return false; } } Log_DevPrintf("Editor visual definition loaded: '%s' (%u visual elements)", m_strName.GetCharArray(), m_visualComponentDefinitions.GetSize()); return true; } bool EditorVisualDefinition::CreateFromTemplate(const ObjectTemplate *pTemplate) { bool loadMissing = false; PathString fileName; // init name m_strName = pTemplate->GetTypeName(); // load each type in the inheritance chain { const ObjectTemplate *pCurrentType = pTemplate; while (pCurrentType != nullptr) { // format filename fileName.Format("%s/%s.xml", VISUAL_BASE_PATH, pCurrentType->GetTypeName().GetCharArray()); // try opening it AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // try loading from stream if (!LoadComponentsFromStream(fileName, pStream)) loadMissing = true; } else { Log_WarningPrintf("EditorVisualDefinition::CreateFromTemplate: No visual template found for '%s'.", pCurrentType->GetTypeName().GetCharArray()); loadMissing = true; } // go to next class in inheritance chain pCurrentType = pCurrentType->GetBaseClassTemplate(); } } // have to load the missing type? if (loadMissing || m_visualComponentDefinitions.GetSize() == 0) { fileName.Format("%s/%s.xml", VISUAL_BASE_PATH, MISSING_VISUAL_TYPE_NAME); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr || !LoadComponentsFromStream(fileName, pStream)) { Log_ErrorPrintf("EditorVisualDefinition::CreateFromTemplate: Failed to load missing visual."); return false; } } Log_DevPrintf("Editor visual definition loaded: '%s' (%u visual elements)", m_strName.GetCharArray(), m_visualComponentDefinitions.GetSize()); return true; } bool EditorVisualDefinition::LoadComponentsFromStream(const char *FileName, ByteStream *pStream) { // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { xmlReader.PrintError("could not create xml reader"); return false; } // skip to entity-definition element if (!xmlReader.SkipToElement("editor-visual")) { xmlReader.PrintError("could not skip to editor-visual element"); return false; } // // read attributes // const char *nameStr = xmlReader.FetchAttribute("name"); // const char *baseStr = xmlReader.FetchAttribute("base"); // const char *canCreateStr = xmlReader.FetchAttribute("can-create"); // if (nameStr == NULL || canCreateStr == NULL) // { // xmlReader.PrintError("incomplete entity definition"); // return false; // } // read elements if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 editorVisualSelection = xmlReader.Select("visual"); if (editorVisualSelection < 0) return false; switch (editorVisualSelection) { // visual case 0: { int32 typeSelection = xmlReader.SelectAttribute("type", "Sprite|StaticMesh|BlockMesh|PointLight|DirectionalLight"); if (typeSelection < 0) return false; EditorVisualComponentDefinition *pVisualDefinition = NULL; switch (typeSelection) { // Sprite case 0: pVisualDefinition = new EditorVisualComponentDefinition_Sprite(); break; // StaticMesh case 1: pVisualDefinition = new EditorVisualComponentDefinition_StaticMesh(); break; // StaticBlockMesh case 2: pVisualDefinition = new EditorVisualComponentDefinition_BlockMesh(); break; // PointLight case 3: pVisualDefinition = new EditorVisualComponentDefinition_PointLight(); break; // DirectionalLight case 4: pVisualDefinition = new EditorVisualComponentDefinition_DirectionalLight(); break; default: UnreachableCode(); break; } DebugAssert(pVisualDefinition != NULL); if (!pVisualDefinition->ParseXML(xmlReader)) { delete pVisualDefinition; return false; } m_visualComponentDefinitions.Add(pVisualDefinition); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "editor-visual") == 0); break; } else { UnreachableCode(); break; } } } return true; } EditorVisualInstance::EditorVisualInstance(const EditorVisualDefinition *pDefinition) : m_pDefinition(pDefinition), m_pRenderWorld(nullptr), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero) { } EditorVisualInstance::~EditorVisualInstance() { for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) { if (m_pRenderWorld != nullptr) m_visualInstances[i]->OnRemovedFromRenderWorld(m_pRenderWorld); delete m_visualInstances[i]; } } EditorVisualInstance *EditorVisualInstance::Create(uint32 pickingID, const EditorVisualDefinition *pDefinition, const PropertyTable *pInitialProperties /* = &PropertyTable::EmptyPropertyList */) { EditorVisualInstance *pInstance = new EditorVisualInstance(pDefinition); // create visual components for (uint32 i = 0; i < pDefinition->GetVisualDefinitionCount(); i++) { const EditorVisualComponentDefinition *pVisualDefinition = pDefinition->GetVisualDefinition(i); EditorVisualComponentInstance *pVisualInstance = pVisualDefinition->CreateVisual(pickingID); if (pVisualInstance == nullptr) continue; // notify of all property values pInitialProperties->EnumerateProperties([pVisualInstance](const char *propertyName, const char *propertyValue) { pVisualInstance->OnPropertyChange(propertyName, propertyValue); }); // add to list pInstance->m_visualInstances.Add(pVisualInstance); } // if no visuals were created, bail out if (pInstance->m_visualInstances.GetSize() == 0) { delete pInstance; return nullptr; } // update bounds, and done pInstance->UpdateBounds(); return pInstance; } void EditorVisualInstance::AddToRenderWorld(RenderWorld *pWorld) { DebugAssert(m_pRenderWorld == nullptr); m_pRenderWorld = pWorld; for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) m_visualInstances[i]->OnAddedToRenderWorld(pWorld); } void EditorVisualInstance::RemoveFromRenderWorld(RenderWorld *pWorld) { DebugAssert(m_pRenderWorld == pWorld); for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) m_visualInstances[i]->OnRemovedFromRenderWorld(pWorld); m_pRenderWorld = nullptr; } void EditorVisualInstance::OnPropertyModified(const char *propertyName, const char *propertyValue) { // pass message to render proxies for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) { // notify visual m_visualInstances[i]->OnPropertyChange(propertyName, propertyValue); } // update bounds UpdateBounds(); } void EditorVisualInstance::OnSelectedStateChanged(bool selected) { // pass message to render proxies for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) { // notify visual m_visualInstances[i]->OnSelectionStateChange(selected); } } void EditorVisualInstance::UpdateBounds() { bool boundsSet = false; m_boundingBox = AABox::Zero; for (uint32 i = 0; i < m_visualInstances.GetSize(); i++) { const AABox &visualBounds = m_visualInstances[i]->GetVisualBounds(); // skip bounds that are max size, it throws everything off if (visualBounds != AABox::MaxSize || visualBounds.GetMinBounds() == float3::NegativeInfinite || visualBounds.GetMaxBounds() == float3::Infinite) { if (boundsSet) { m_boundingBox.Merge(visualBounds); } else { boundsSet = true; m_boundingBox = visualBounds; } } } m_boundingSphere = Sphere::FromAABox(m_boundingBox); } <file_sep>/Engine/Source/ResourceCompiler/StaticMeshGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "Engine/DataFormats.h" #include "Core/ChunkFileReader.h" #include "Core/ChunkFileWriter.h" #include "Core/MeshUtilties.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(StaticMeshGenerator); StaticMeshGenerator::StaticMeshGenerator() : m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_pCollisionShapeGenerator(nullptr) { } StaticMeshGenerator::~StaticMeshGenerator() { delete m_pCollisionShapeGenerator; for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { LOD *lod = m_lods[lodIndex]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) delete lod->Batches[batchIndex]; delete lod; } } bool StaticMeshGenerator::GetVertexTextureCoordinatesEnabled() const { return m_properties.GetPropertyValueDefaultBool("EnableVertexTextureCoordinates", false); } void StaticMeshGenerator::SetVertexTextureCoordinatesEnabled(bool enabled) { m_properties.SetPropertyValueBool("EnableVertexTextureCoordinates", enabled); } bool StaticMeshGenerator::GetVertexColorsEnabled() const { return m_properties.GetPropertyValueDefaultBool("EnableVertexColors", false); } void StaticMeshGenerator::SetVertexColorsEnabled(bool enabled) { m_properties.SetPropertyValueBool("EnableVertexColors", enabled); } uint32 StaticMeshGenerator::GetVertexTextureCoordinateComponentCount() const { return m_properties.GetPropertyValueDefaultUInt32("VertexTextureCoordinateComponents", 2); } void StaticMeshGenerator::SetVertexTextureCoordinateComponentCount(uint32 components) { m_properties.SetPropertyValueUInt32("VertexTextureCoordinateComponents", components); } bool StaticMeshGenerator::Create(bool enableVertexTextureCoordinates /* = true */, bool enableVertexColors /* = false */, uint32 textureCoordinateComponents /* = 2 */) { DebugAssert(m_pCollisionShapeGenerator == nullptr); DebugAssert(m_lods.GetSize() == 0); // set initial properties SetVertexTextureCoordinatesEnabled(enableVertexTextureCoordinates); SetVertexColorsEnabled(enableVertexColors); SetVertexTextureCoordinateComponentCount(textureCoordinateComponents); // set bounds to zero m_boundingBox = AABox::Zero; m_boundingSphere = Sphere::Zero; return true; } bool StaticMeshGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) return false; if (!xmlReader.SkipToElement("static-mesh")) { xmlReader.PrintError("could not skip to static-mesh element."); return false; } // process xml nodes for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 staticMeshSelection = xmlReader.Select("properties|bounds|collision-shape|lods"); if (staticMeshSelection < 0) return false; switch (staticMeshSelection) { // properties case 0: { if (!xmlReader.IsEmptyElement() && !m_properties.LoadFromXML(xmlReader)) return false; } break; // bounds case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 boundsSelection = xmlReader.Select("bounding-box|bounding-sphere"); if (boundsSelection < 0) return false; switch (boundsSelection) { // bounding-box case 0: { float3 minBounds = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("min-bounds", "0 0 0")); float3 maxBounds = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("max-bounds", "0 0 0")); m_boundingBox.SetBounds(minBounds, maxBounds); if (!xmlReader.SkipCurrentElement()) return false; } break; // bounding-sphere case 1: { float3 sphereCenter = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("center", "0 0 0")); float sphereRadius = StringConverter::StringToFloat(xmlReader.FetchAttributeDefault("radius", "0")); m_boundingSphere.SetCenter(sphereCenter); m_boundingSphere.SetRadius(sphereRadius); if (!xmlReader.SkipCurrentElement()) return false; } break; } } else { if (!xmlReader.ExpectEndOfElementName("bounds")) return false; break; } } } } break; // collision-shape case 2: { if (m_pCollisionShapeGenerator != nullptr) { xmlReader.PrintError("collision shape already defined"); return false; } m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(); if (!m_pCollisionShapeGenerator->LoadFromXML(xmlReader)) return false; } break; // lods case 3: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 lodsSelection = xmlReader.Select("lod"); if (lodsSelection < 0) return false; switch (lodsSelection) { // lod case 0: { LOD *lod = new LOD(); m_lods.Add(lod); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 lodSelection = xmlReader.Select("vertices|batches"); if (lodSelection < 0) return false; switch (lodSelection) { // vertices case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 verticesSelection = xmlReader.Select("vertex"); if (verticesSelection < 0) return false; // init vertex Vertex vertex; vertex.Position = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("position", "0 0 0")); vertex.TexCoord = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("texcoord", "0 0 0")); vertex.Tangent = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("tangent", "1 0 0")); vertex.Binormal = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("binormal", "0 1 0")); vertex.Normal = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("normal", "0 0 1")); vertex.Color = StringConverter::StringToColor(xmlReader.FetchAttributeDefault("color", "#00000000")); if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; // store it lod->Vertices.Add(vertex); } else { if (!xmlReader.ExpectEndOfElementName("vertices")) return false; break; } } } } break; // batches case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 batchesSelection = xmlReader.Select("batch"); if (batchesSelection < 0) return false; switch (batchesSelection) { // batch case 0: { const char *materialNameStr = xmlReader.FetchAttribute("material"); if (materialNameStr == nullptr) { xmlReader.PrintError("missing material name for batch"); return false; } Batch *batch = new Batch(); batch->MaterialName = materialNameStr; lod->Batches.Add(batch); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 batchSelection = xmlReader.Select("triangles"); if (batchSelection < 0) return false; switch (batchSelection) { // triangles case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 trianglesSelection = xmlReader.Select("triangle"); if (trianglesSelection < 0) return false; Triangle triangle; triangle.Indices[0] = StringConverter::StringToUInt32(xmlReader.FetchAttributeDefault("vertex1", "0")); triangle.Indices[1] = StringConverter::StringToUInt32(xmlReader.FetchAttributeDefault("vertex2", "0")); triangle.Indices[2] = StringConverter::StringToUInt32(xmlReader.FetchAttributeDefault("vertex3", "0")); // validate indices if (triangle.Indices[0] >= lod->Vertices.GetSize() || triangle.Indices[1] >= lod->Vertices.GetSize() || triangle.Indices[2] >= lod->Vertices.GetSize()) { xmlReader.PrintError("triangle contains out of range vertex indices"); return false; } if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; // store it batch->Triangles.Add(triangle); } else { if (!xmlReader.ExpectEndOfElementName("triangles")) return false; break; } } } } break; } } else { if (!xmlReader.ExpectEndOfElementName("batch")) return false; break; } } } } break; } } else { if (!xmlReader.ExpectEndOfElementName("batches")) return false; break; } } } } break; } } else { if (!xmlReader.ExpectEndOfElementName("lod")) return false; break; } } } } break; } } else { if (!xmlReader.ExpectEndOfElementName("lods")) return false; break; } } } } break; } } else { if (!xmlReader.ExpectEndOfElementName("static-mesh")) return false; break; } } return true; } bool StaticMeshGenerator::IsCompleteMesh() const { if (m_lods.GetSize() == 0) return false; for (uint32 i = 0; i < m_lods.GetSize(); i++) { if (m_lods[i]->Batches.GetSize() == 0) return false; for (uint32 j = 0; j < m_lods[i]->Batches.GetSize(); j++) { if (m_lods[i]->Batches[j]->Triangles.GetSize() == 0) return false; } } return true; } bool StaticMeshGenerator::SaveToXML(ByteStream *pStream) const { XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; SmallString tempString; xmlWriter.StartElement("static-mesh"); xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); // </properties> // write bounds xmlWriter.StartElement("bounds"); { // bounding box xmlWriter.StartElement("bounding-box"); { StringConverter::Float3ToString(tempString, m_boundingBox.GetMinBounds()); xmlWriter.WriteAttribute("min-bounds", tempString); StringConverter::Float3ToString(tempString, m_boundingBox.GetMaxBounds()); xmlWriter.WriteAttribute("max-bounds", tempString); } xmlWriter.EndElement(); // bounding sphere xmlWriter.StartElement("bounding-sphere"); { StringConverter::Float3ToString(tempString, m_boundingSphere.GetCenter()); xmlWriter.WriteAttribute("center", tempString); StringConverter::FloatToString(tempString, m_boundingSphere.GetRadius()); xmlWriter.WriteAttribute("radius", tempString); } xmlWriter.EndElement(); } xmlWriter.EndElement(); // write collision shape if (m_pCollisionShapeGenerator != NULL) { xmlWriter.StartElement("collision-shape"); if (!m_pCollisionShapeGenerator->SaveToXML(xmlWriter)) return false; xmlWriter.EndElement(); } // write lods xmlWriter.StartElement("lods"); { for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { const LOD *lod = m_lods[lodIndex]; xmlWriter.StartElement("lod"); { xmlWriter.StartElement("vertices"); { for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) { const Vertex &vertex = lod->Vertices[vertexIndex]; xmlWriter.StartElement("vertex"); { StringConverter::Float3ToString(tempString, vertex.Position); xmlWriter.WriteAttribute("position", tempString); StringConverter::Float3ToString(tempString, vertex.TexCoord); xmlWriter.WriteAttribute("texcoord", tempString); StringConverter::Float3ToString(tempString, vertex.Tangent); xmlWriter.WriteAttribute("tangent", tempString); StringConverter::Float3ToString(tempString, vertex.Binormal); xmlWriter.WriteAttribute("binormal", tempString); StringConverter::Float3ToString(tempString, vertex.Normal); xmlWriter.WriteAttribute("normal", tempString); StringConverter::ColorToString(tempString, vertex.Color); xmlWriter.WriteAttribute("color", tempString); } xmlWriter.EndElement(); // </vertex> } } xmlWriter.EndElement(); // </vertices> xmlWriter.StartElement("batches"); { for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; xmlWriter.StartElement("batch"); { xmlWriter.WriteAttribute("material", batch->MaterialName); xmlWriter.StartElement("triangles"); { for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle &triangle = batch->Triangles[triangleIndex]; xmlWriter.StartElement("triangle"); { StringConverter::UInt32ToString(tempString, triangle.Indices[0]); xmlWriter.WriteAttribute("vertex1", tempString); StringConverter::UInt32ToString(tempString, triangle.Indices[1]); xmlWriter.WriteAttribute("vertex2", tempString); StringConverter::UInt32ToString(tempString, triangle.Indices[2]); xmlWriter.WriteAttribute("vertex3", tempString); } xmlWriter.EndElement(); // </triangle> } } xmlWriter.EndElement(); // </triangles> } xmlWriter.EndElement(); // </batch> } } xmlWriter.EndElement(); // </batches> } xmlWriter.EndElement(); // </lod> } } xmlWriter.EndElement(); // </lods> // end static mesh xmlWriter.EndElement(); // test state bool result = (!xmlWriter.InErrorState()); xmlWriter.Close(); return result; } bool StaticMeshGenerator::Compile(ByteStream *pStream) const { // valid mesh? if (!IsCompleteMesh()) return false; // calculate size of a vertex uint32 vertexFlags = 0; if (GetVertexTextureCoordinatesEnabled()) { if (GetVertexTextureCoordinateComponentCount() == 3) vertexFlags |= DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT3; else vertexFlags |= DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT2; } if (GetVertexColorsEnabled()) vertexFlags |= DF_STATICMESH_VERTEX_FLAG_COLOR; // compile a list of materials PODArray<const String *> uniqueMaterials; for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { const LOD *lod = m_lods[lodIndex]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const String &material = lod->Batches[batchIndex]->MaterialName; uint32 materialIndex; for (materialIndex = 0; materialIndex < uniqueMaterials.GetSize(); materialIndex++) { if (uniqueMaterials[materialIndex]->CompareInsensitive(material)) break; } if (materialIndex == uniqueMaterials.GetSize()) uniqueMaterials.Add(&material); } } if (uniqueMaterials.GetSize() == 0) return false; // create writer BinaryWriter binaryWriter(pStream); // fill header DF_STATICMESH_HEADER meshHeader; meshHeader.Magic = DF_STATICMESH_HEADER_MAGIC; meshHeader.Size = sizeof(DF_STATICMESH_HEADER); meshHeader.CreationTime = static_cast<uint64>(Timestamp::Now().AsUnixTimestamp()); meshHeader.BoundingBoxMin = m_boundingBox.GetMinBounds(); meshHeader.BoundingBoxMax = m_boundingBox.GetMaxBounds(); meshHeader.BoundingSphereCenter = m_boundingSphere.GetCenter(); meshHeader.BoundingSphereRadius = m_boundingSphere.GetRadius(); meshHeader.CollisionShapeType = (m_pCollisionShapeGenerator != NULL) ? (uint32)m_pCollisionShapeGenerator->GetType() : (uint32)Physics::COLLISION_SHAPE_TYPE_NONE; meshHeader.CollisionShapeSize = 0; meshHeader.CollisionShapeOffset = 0; meshHeader.VertexFlags = vertexFlags; meshHeader.MaterialCount = 0; meshHeader.MaterialNamesOffset = 0; meshHeader.LODCount = 0; meshHeader.LODOffsetsOffset = 0; // write header uint64 headerOffset = pStream->GetPosition(); if (!pStream->Write2(&meshHeader, sizeof(meshHeader))) return false; // write collision shape if (m_pCollisionShapeGenerator != nullptr) { BinaryBlob *pCollisionDataBlob; if (!m_pCollisionShapeGenerator->Compile(&pCollisionDataBlob)) return false; meshHeader.CollisionShapeOffset = (uint32)(pStream->GetPosition() - headerOffset); meshHeader.CollisionShapeSize = pCollisionDataBlob->GetDataSize(); if (!pStream->Write2(pCollisionDataBlob->GetDataPointer(), meshHeader.CollisionShapeSize)) { pCollisionDataBlob->Release(); return false; } pCollisionDataBlob->Release(); } // write materials { meshHeader.MaterialCount = uniqueMaterials.GetSize(); meshHeader.MaterialNamesOffset = (uint32)(pStream->GetPosition() - headerOffset); for (uint32 materialIndex = 0; materialIndex < uniqueMaterials.GetSize(); materialIndex++) { //if (!binaryWriter.WriteCString(*uniqueMaterials[materialIndex])) //return false; binaryWriter.WriteCString(*uniqueMaterials[materialIndex]); } } // write lods { meshHeader.LODCount = m_lods.GetSize(); meshHeader.LODOffsetsOffset = (uint32)(pStream->GetPosition() - headerOffset); // write an empty offset for each lod, which gets filled in later uint64 lodOffsetsOffset = pStream->GetPosition(); uint32 *lodOffsets = (uint32 *)alloca(sizeof(uint32) * m_lods.GetSize()); Y_memzero(lodOffsets, sizeof(uint32) * m_lods.GetSize()); if (!pStream->Write2(lodOffsets, sizeof(uint32) * m_lods.GetSize())) return false; // write each lod for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { const LOD *lod = m_lods[lodIndex]; // calculate offset to lod uint64 lodHeaderOffset = pStream->GetPosition(); lodOffsets[lodIndex] = (uint32)(lodHeaderOffset - headerOffset); // write lod header DF_STATICMESH_LOD_HEADER lodHeader; lodHeader.VertexCount = 0; lodHeader.VerticesOffset = 0; lodHeader.IndexCount = 0; lodHeader.IndexFormat = 0; lodHeader.IndicesOffset = 0; lodHeader.BatchCount = 0; lodHeader.BatchesOffset = 0; if (!pStream->Write2(&lodHeader, sizeof(lodHeader))) return false; // write vertices { lodHeader.VertexCount = lod->Vertices.GetSize(); lodHeader.VerticesOffset = (uint32)(pStream->GetPosition() - headerOffset); for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) { const Vertex &sourceVertex = lod->Vertices[vertexIndex]; DF_STATICMESH_VERTEX fileVertex; sourceVertex.Position.Store(fileVertex.Position); sourceVertex.Tangent.Store(fileVertex.Tangent); sourceVertex.Binormal.Store(fileVertex.Binormal); sourceVertex.Normal.Store(fileVertex.Normal); sourceVertex.TexCoord.Store(fileVertex.TexCoord); fileVertex.Color = sourceVertex.Color; if (!pStream->Write2(&fileVertex, sizeof(fileVertex))) return false; } } // write indices // assume that batches are stored sequentially after one another { // find total number of indices uint32 totalIndices = 0; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) totalIndices += lod->Batches[batchIndex]->Triangles.GetSize() * 3; // should have indices... DebugAssert(totalIndices > 0); // can use 16-bit indices? if (lod->Vertices.GetSize() <= 0xFFFF) { uint16 *pOutIndices = new uint16[totalIndices]; uint16 *pOutIndexPointer = pOutIndices; // add indices for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle *pTriangle = &batch->Triangles[triangleIndex]; *(pOutIndexPointer++) = (uint16)pTriangle->Indices[0]; *(pOutIndexPointer++) = (uint16)pTriangle->Indices[1]; *(pOutIndexPointer++) = (uint16)pTriangle->Indices[2]; } } // write indices lodHeader.IndexCount = totalIndices; lodHeader.IndexFormat = GPU_INDEX_FORMAT_UINT16; lodHeader.IndicesOffset = (uint32)(pStream->GetPosition() - headerOffset); if (!pStream->Write2(pOutIndices, sizeof(uint16) * totalIndices)) { delete[] pOutIndices; return false; } delete[] pOutIndices; } else { uint32 *pOutIndices = new uint32[totalIndices]; uint32 *pOutIndexPointer = pOutIndices; // add indices for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle *pTriangle = &batch->Triangles[triangleIndex]; *(pOutIndexPointer++) = pTriangle->Indices[0]; *(pOutIndexPointer++) = pTriangle->Indices[1]; *(pOutIndexPointer++) = pTriangle->Indices[2]; } } // write indices lodHeader.IndexCount = totalIndices; lodHeader.IndexFormat = GPU_INDEX_FORMAT_UINT32; lodHeader.IndicesOffset = (uint32)(pStream->GetPosition() - headerOffset); if (!pStream->Write2(pOutIndices, sizeof(uint32) * totalIndices)) { delete[] pOutIndices; return false; } delete[] pOutIndices; } } // write batches // the triangle starting index is easy to calculate now { uint32 startingIndex = 0; lodHeader.BatchCount = lod->Batches.GetSize(); lodHeader.BatchesOffset = (uint32)(pStream->GetPosition() - headerOffset); for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; uint32 batchIndices = batch->Triangles.GetSize() * 3; // find the material index uint32 batchMaterial = 0; for (uint32 materialIndex = 0; materialIndex < uniqueMaterials.GetSize(); materialIndex++) { if (uniqueMaterials[materialIndex]->Compare(batch->MaterialName)) { batchMaterial = materialIndex; break; } } // write data DF_STATICMESH_BATCH fileBatch; fileBatch.MaterialIndex = batchMaterial; fileBatch.StartIndex = startingIndex; fileBatch.NumIndices = batchIndices; if (!pStream->Write2(&fileBatch, sizeof(fileBatch))) return false; // increment starting triangle startingIndex += fileBatch.NumIndices; } } // rewrite the lod header uint64 seekOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(lodHeaderOffset) || !pStream->Write2(&lodHeader, sizeof(lodHeader)) || !pStream->SeekAbsolute(seekOffset)) return false; } // rewrite lod offset table uint64 seekOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(lodOffsetsOffset) || !pStream->Write2(lodOffsets, sizeof(uint32) * m_lods.GetSize()) || !pStream->SeekAbsolute(seekOffset)) return false; } // rewrite header uint64 seekOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(headerOffset) || !pStream->Write2(&meshHeader, sizeof(meshHeader)) || !pStream->SeekAbsolute(seekOffset)) return false; // done return (!pStream->InErrorState()); } void StaticMeshGenerator::Copy(const StaticMeshGenerator *pGenerator) { // trash everything first delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = nullptr; for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { LOD *lod = m_lods[lodIndex]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) delete lod->Batches[batchIndex]; delete lod; } m_lods.Obliterate(); m_properties.Clear(); // copy everything in m_boundingBox = pGenerator->m_boundingBox; m_boundingSphere = pGenerator->m_boundingSphere; m_properties.CopyProperties(&pGenerator->m_properties); // copy the collision shape if (pGenerator->m_pCollisionShapeGenerator != nullptr) { m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(); m_pCollisionShapeGenerator->Copy(pGenerator->m_pCollisionShapeGenerator); } // copy lods for (uint32 lodIndex = 0; lodIndex < pGenerator->m_lods.GetSize(); lodIndex++) { const LOD *srcLOD = pGenerator->m_lods[lodIndex]; LOD *destLOD = new LOD; destLOD->Vertices.Assign(srcLOD->Vertices); for (uint32 batchIndex = 0; batchIndex < srcLOD->Batches.GetSize(); batchIndex++) { const Batch *srcBatch = srcLOD->Batches[batchIndex]; Batch *destBatch = new Batch; destBatch->MaterialName = srcBatch->MaterialName; destBatch->Triangles.Assign(srcBatch->Triangles); destLOD->Batches.Add(destBatch); } m_lods.Add(destLOD); } } uint32 StaticMeshGenerator::AddLOD() { LOD *lod = new LOD; m_lods.Add(lod); return m_lods.GetSize() - 1; } uint32 StaticMeshGenerator::AddVertex(uint32 lod, const float3 &position, const float3 &tangent /* = float3::UnitX */, const float3 &binormal /* = float3::UnitY */, const float3 &normal /* = float3::UnitZ */, const float3 &texCoord /* = float3::Zero */, const uint32 color /* = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)*/) { Vertex v; v.Position = position; v.Tangent = tangent; v.Binormal = binormal; v.Normal = normal; v.TexCoord = texCoord; v.Color = color; DebugAssert(lod < m_lods.GetSize()); m_lods[lod]->Vertices.Add(v); return m_lods[lod]->Vertices.GetSize() - 1; } uint32 StaticMeshGenerator::AddBatch(uint32 lod, const char *materialName) { Batch *batch = new Batch; batch->MaterialName = materialName; DebugAssert(lod < m_lods.GetSize()); m_lods[lod]->Batches.Add(batch); return m_lods[lod]->Batches.GetSize() - 1; } uint32 StaticMeshGenerator::AddTriangle(uint32 lod, uint32 batchIndex, const uint32 i0, const uint32 i1, const uint32 i2) { Triangle t; t.Indices[0] = i0; t.Indices[1] = i1; t.Indices[2] = i2; DebugAssert(lod < m_lods.GetSize() && batchIndex < m_lods[lod]->Batches.GetSize()); m_lods[lod]->Batches[batchIndex]->Triangles.Add(t); return m_lods[lod]->Batches[batchIndex]->Triangles.GetSize() - 1; } void StaticMeshGenerator::CalculateBounds() { // get bounding box { bool first = true; AABox boundingBox(AABox::Zero); for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { const LOD *lod = m_lods[lodIndex]; for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) { if (first) { boundingBox.SetBounds(lod->Vertices[vertexIndex].Position); first = false; } else { boundingBox.Merge(lod->Vertices[vertexIndex].Position); } } } m_boundingBox = boundingBox; } // get bounding sphere { // set the sphere center to the box center m_boundingSphere.SetCenter(m_boundingBox.GetCenter()); m_boundingSphere.SetRadius(0.0f); // insert points for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { const LOD *lod = m_lods[lodIndex]; for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) m_boundingSphere.Merge(lod->Vertices[vertexIndex].Position); } } } void StaticMeshGenerator::GenerateTangents(uint32 LODIndex) { DebugAssert(LODIndex < m_lods.GetSize()); LOD *lod = m_lods[LODIndex]; // zero all tangents for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) { Vertex *vertex = &lod->Vertices[vertexIndex]; vertex->Tangent.SetZero(); vertex->Binormal.SetZero(); vertex->Normal.SetZero(); } // calculate tangents for each vertex for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle *triangle = &batch->Triangles[triangleIndex]; Vertex *v0 = &lod->Vertices[triangle->Indices[0]]; Vertex *v1 = &lod->Vertices[triangle->Indices[1]]; Vertex *v2 = &lod->Vertices[triangle->Indices[2]]; // use texcoords to generate tangent vectors float3 tx, ty, tz; MeshUtilites::CalculateTangentSpaceVectors(v0->Position, v1->Position, v2->Position, v0->TexCoord.xy(), v1->TexCoord.xy(), v2->TexCoord.xy(), tx, ty, tz); // add to vertices v0->Tangent += tx; v0->Binormal += ty; v0->Normal += tz; v1->Tangent += tx; v1->Binormal += ty; v1->Normal += tz; v2->Tangent += tx; v2->Binormal += ty; v2->Normal += tz; } } // normalize each tangent for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) { Vertex *vertex = &lod->Vertices[vertexIndex]; if (vertex->Tangent.SquaredLength() > 0.0f) vertex->Tangent.NormalizeInPlace(); if (vertex->Binormal.SquaredLength() > 0.0f) vertex->Binormal.NormalizeInPlace(); if (vertex->Normal.SquaredLength() > 0.0f) vertex->Normal.NormalizeInPlace(); } } void StaticMeshGenerator::JoinBatches() { for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { LOD *lod = m_lods[lodIndex]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); ) { Batch *batch = lod->Batches[batchIndex]; bool wasMerged = false; for (uint32 mergeBatchIndex = batchIndex + 1; mergeBatchIndex < lod->Batches.GetSize(); mergeBatchIndex++) { Batch *mergeBatch = lod->Batches[mergeBatchIndex]; if (mergeBatch->MaterialName == batch->MaterialName) { DebugAssert(mergeBatch != batch); Log_DevPrintf("StaticMeshGenerator::CollapseBatches: Merge LOD %u batch %u -> %u", lodIndex, mergeBatchIndex, batchIndex); wasMerged = true; batch->Triangles.AddArray(mergeBatch->Triangles); lod->Batches.OrderedRemove(mergeBatchIndex); delete mergeBatch; break; } } if (!wasMerged) batchIndex++; } } } void StaticMeshGenerator::CenterMesh(CenterOrigin origin /* = CenterOrigin_Center */, float3 *pOffset /* = nullptr */) { // ensure bounding box is up to date CalculateBounds(); // some useful vars for the next part float3 boundingBoxMin(m_boundingBox.GetMinBounds()); float3 boundingBoxCenter(m_boundingBox.GetCenter()); float3 boundingBoxHalfExtents(m_boundingBox.GetExtents() * 0.5f); // work out the offset float3 moveOffset(float3::Zero); switch (origin) { case CenterOrigin_Center: moveOffset = -boundingBoxCenter; break; case CenterOrigin_CenterBottom: moveOffset = float3(-boundingBoxCenter.x, -boundingBoxCenter.y, -boundingBoxMin.z); break; } // apply the offset for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { LOD *lod = m_lods[lodIndex]; for (uint32 vertexIndex = 0; vertexIndex < lod->Vertices.GetSize(); vertexIndex++) lod->Vertices[vertexIndex].Position += moveOffset; } // recalculate bounds CalculateBounds(); // update offset if (pOffset != nullptr) *pOffset = moveOffset; } bool StaticMeshGenerator::BuildCollisionShape(CollisionShapeType type) { switch (type) { case CollisionShapeType_None: RemoveCollisionShape(); return true; case CollisionShapeType_Box: return BuildBoxCollisionShape(); case CollisionShapeType_Sphere: return BuildSphereCollisionShape(); case CollisionShapeType_TriangleMesh: return BuildTriangleMeshCollisionShape(0); case CollisionShapeType_ConvexHull: return BuildConvexHullCollisionShape(0); } return false; } void StaticMeshGenerator::InternalBuildTriangleMeshCollisionShape(uint32 buildFromLOD) { DebugAssert(buildFromLOD < m_lods.GetSize()); // nuke the old one delete m_pCollisionShapeGenerator; // build new m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH); // use lod const LOD *lod = m_lods[buildFromLOD]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { const Triangle *triangle = &batch->Triangles[triangleIndex]; m_pCollisionShapeGenerator->AddTriangle(lod->Vertices[triangle->Indices[0]].Position, lod->Vertices[triangle->Indices[1]].Position, lod->Vertices[triangle->Indices[2]].Position); } } } bool StaticMeshGenerator::BuildBoxCollisionShape() { delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_BOX); m_pCollisionShapeGenerator->SetBoxCenter(m_boundingBox.GetCenter()); m_pCollisionShapeGenerator->SetBoxHalfExtents(m_boundingBox.GetExtents() / 2.0f); return true; } bool StaticMeshGenerator::BuildSphereCollisionShape() { delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = new Physics::CollisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_SPHERE); m_pCollisionShapeGenerator->SetSphereCenter(m_boundingSphere.GetCenter()); m_pCollisionShapeGenerator->SetSphereRadius(m_boundingSphere.GetRadius()); return true; } bool StaticMeshGenerator::BuildTriangleMeshCollisionShape(uint32 buildFromLOD /* = 0 */) { InternalBuildTriangleMeshCollisionShape(buildFromLOD); return true; } bool StaticMeshGenerator::BuildConvexHullCollisionShape(uint32 buildFromLOD /* = 0 */) { //InternalBuildTriangleMeshCollisionShape(buildFromLOD); //m_pCollisionShapeGenerator->ConvertToConvexHull(); return false; } void StaticMeshGenerator::SetCollisionShape(Physics::CollisionShapeGenerator *pGenerator) { delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = pGenerator; } void StaticMeshGenerator::RemoveCollisionShape() { delete m_pCollisionShapeGenerator; m_pCollisionShapeGenerator = NULL; } void StaticMeshGenerator::FlipTriangleWinding() { for (uint32 lodIndex = 0; lodIndex < m_lods.GetSize(); lodIndex++) { LOD *lod = m_lods[lodIndex]; for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { Batch *batch = lod->Batches[batchIndex]; for (uint32 triangleIndex = 0; triangleIndex < batch->Triangles.GetSize(); triangleIndex++) { Triangle *triangle = &batch->Triangles[triangleIndex]; Swap(triangle->Indices[1], triangle->Indices[2]); } } } } // StaticMeshGenerator &StaticMeshGenerator::operator=(const StaticMeshGenerator &copyFrom) // { // m_boundingBox = copyFrom.m_boundingBox; // m_bVerticesHaveColors = copyFrom.m_bVerticesHaveColors; // m_bVerticesHaveTexCoords = copyFrom.m_bVerticesHaveTexCoords; // // m_Materials = copyFrom.m_Materials; // m_Vertices = copyFrom.m_Vertices; // m_Triangles = copyFrom.m_Triangles; // m_Batches = copyFrom.m_Batches; // m_LODs = copyFrom.m_LODs; // // return *this; // } // Interface BinaryBlob *ResourceCompiler::CompileStaticMesh(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.staticmesh.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileStaticMesh: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); StaticMeshGenerator *pGenerator = new StaticMeshGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Editor/Source/Editor/MapEditor/EditorEntityIdWorldRenderer.h #pragma once #include "Editor/Common.h" #include "Renderer/WorldRenderers/SingleShaderWorldRenderer.h" #include "Renderer/RenderQueue.h" class EditorEntityIdWorldRenderer : public SingleShaderWorldRenderer { public: EditorEntityIdWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~EditorEntityIdWorldRenderer(); private: virtual void DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); }; <file_sep>/Editor/Source/Editor/MapEditor/EditorEditMode.h #pragma once #include "Editor/Common.h" class ResourceTypeInfo; class EditorMapWindow; class EditorMap; class EditorMapViewport; class MiniGUIContext; class EditorEditMode : public QObject { Q_OBJECT public: EditorEditMode(EditorMap *pMap); virtual ~EditorEditMode(); const EditorMap *GetEditorMap() const { return m_pMap; } EditorMap *GetEditorMap() { return m_pMap; } virtual bool Initialize(ProgressCallbacks *pProgressCallbacks); virtual QWidget *CreateUI(QWidget *parentWidget); virtual void Activate(); virtual void Deactivate(); virtual void Update(const float timeSinceLastUpdate); virtual void OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue); virtual void OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport); virtual void OnViewportDrawBeforeWorld(EditorMapViewport *pViewport); virtual void OnViewportDrawAfterWorld(EditorMapViewport *pViewport); virtual void OnViewportDrawAfterPost(EditorMapViewport *pViewport); virtual void OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport); virtual void OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport); virtual bool HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent); virtual bool HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent); virtual bool HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent); virtual bool HandleResourceViewResourceActivatedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName); virtual bool HandleResourceViewResourceDroppedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName, const EditorMapViewport *pViewport, int32 x, int32 y); protected: EditorMap *m_pMap; bool m_bActive; private: // left/mouse button states bool m_cameraLeftMouseButtonDown; bool m_cameraRightMouseButtonDown; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUQuery.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" class OpenGLGPUQuery : public GPUQuery { public: OpenGLGPUQuery(GPU_QUERY_TYPE type, GLuint id); ~OpenGLGPUQuery(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override final; virtual void SetDebugName(const char *name) override final; virtual GPU_QUERY_TYPE GetQueryType() const override final { return m_eType; } GLuint GetGLQueryID() const { return m_iGLQueryId; } OpenGLGPUContext *GetOwningContext() const { return m_pOwningContext; } void SetOwningContext(OpenGLGPUContext *pContext) { m_pOwningContext = pContext; } protected: GPU_QUERY_TYPE m_eType; GLuint m_iGLQueryId; OpenGLGPUContext *m_pOwningContext; }; <file_sep>/Engine/Source/Core/MeshUtilties.cpp #include "Core/PrecompiledHeader.h" #include "Core/MeshUtilties.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Assert.h" #include "MathLib/SIMDVectorf.h" namespace MeshUtilites { void CalculateNormals(const void *pInVertices, uint32 uVertexStride, uint32 nVertices, const void *pInTriangles, uint32 uTriangleStride, uint32 nTriangles, void *pOutNormals, uint32 uNormalStride) { uint32 i, j; const byte *pInVerticesBytePtr = (const byte *)pInVertices; const byte *pInTrianglesBytePtr = (const byte *)pInTriangles; byte *pOutNormalsBytePtr = (byte *)pOutNormals; // initialize all normals to zero for (i = 0; i < nVertices; i++) reinterpret_cast<Vector3f *>(pOutNormalsBytePtr + i * uNormalStride)->SetZero(); // get number of triangles uint32 nActualTriangles = (pInTriangles != NULL) ? nTriangles : (nVertices / 3); // calculate face normals and add them to the vertex normals for (i = 0; i < nActualTriangles; i++) { Vector3f faceVertices[3]; Vector3f *pFaceNormals[3]; if (pInTriangles != NULL) { // using indices for (j = 0; j < 3; j++) { uint32 VertexIndex = *(uint32 *)(pInTrianglesBytePtr + i * uTriangleStride + j * sizeof(uint32)); faceVertices[j] = *reinterpret_cast<const Vector3f *>(pInVerticesBytePtr + VertexIndex * uVertexStride); pFaceNormals[j] = reinterpret_cast<Vector3f *>(pOutNormalsBytePtr + VertexIndex * uNormalStride); } } else { // using vertices for (j = 0; j < 3; j++) { faceVertices[j] = *reinterpret_cast<const Vector3f *>(pInVerticesBytePtr + (i * 3 + j) * uTriangleStride); pFaceNormals[j] = reinterpret_cast<Vector3f *>(pOutNormalsBytePtr + (i * 3 + j) * uNormalStride); } } // // calc face normal // MLVECTOR3 V2MinusV1; // MLVECTOR3 V3MinusV1; // mlVector3Subtract(&V2MinusV1, pFaceVertices[1], pFaceVertices[0]); // mlVector3Subtract(&V3MinusV1, pFaceVertices[2], pFaceVertices[0]); // // MLVECTOR3 FaceNormal; // mlVector3Cross(&FaceNormal, &V2MinusV1, &V3MinusV1); // // // add it to the vertex normals // for (j = 0; j < 3; j++) // mlVector3Add(pFaceNormals[j], pFaceNormals[j], &FaceNormal); Vector3f dv0 = faceVertices[1] - faceVertices[0]; Vector3f dv1 = faceVertices[2] - faceVertices[0]; Vector3f normal = dv0.Cross(dv1); for (j = 0; j < 3; j++) *pFaceNormals[j] = normal; } // normalize all the vertex normals // for (i = 0; i < nVertices; i++) // { // MLVECTOR3 *pNormal = (MLVECTOR3 *)(pOutNormalsBytePtr + i * uNormalStride); // if (mlVector3LengthSq(pNormal) < Y_FLT_EPSILON) // continue; // // mlVector3Normalize(pNormal, pNormal); // } } Vector3f CalculateFaceNormal(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) { Vector3f temp = (v1 - v0).Cross(v2 - v0); return temp.Normalize(); } Plane CalculateTrianglePlane(const Vector3f &TriangleNormal, const Vector3f &FirstVertex) { Plane p; p.a = TriangleNormal.x; p.b = TriangleNormal.y; p.c = TriangleNormal.z; p.d = -(TriangleNormal.Dot(FirstVertex)); p.Normalize(); return p; } void CalculateTangentSpaceVectors(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector2f &uv0, const Vector2f &uv1, const Vector2f &uv2, Vector3f &OutTangent, Vector3f &OutBinormal, Vector3f &OutNormal) { SIMDVector3f V0(v0); SIMDVector3f dv0 = SIMDVector3f(v1) - V0; SIMDVector3f dv1 = SIMDVector3f(v2) - V0; SIMDVector2f UV0(uv0); SIMDVector2f dt0 = SIMDVector2f(uv1) - uv0; SIMDVector2f dt1 = SIMDVector2f(uv2) - uv0; float tmp = (dt0.x * dt1.y - dt1.x * dt0.y); float r = (tmp == 0.0f) ? 0.0f : 1.0f / tmp; SIMDVector3f tangent(SIMDVector3f(dt1.y * dv0.x - dt0.y * dv1.x, dt1.y * dv0.y - dt0.y * dv1.y, dt1.y * dv0.z - dt0.y * dv1.z) * r); SIMDVector3f binormal(SIMDVector3f(dt0.x * dv1.x - dt1.x * dv0.x, dt0.x * dv1.y - dt1.x * dv0.y, dt0.x * dv1.z - dt1.x * dv0.z) * r); SIMDVector3f normal(dv0.Cross(dv1)); OutTangent = (tangent.SquaredLength() > 0.0f) ? tangent.Normalize() : tangent; OutBinormal = (binormal.SquaredLength() > 0.0f) ? binormal.Normalize() : binormal; OutNormal = (normal.SquaredLength() > 0.0f) ? normal.Normalize() : normal; } uint32 GenerateTriangleStripIndices(const void *pInVertices, uint32 uVertexStride, uint32 nVertices, void *pOutTriangles, uint32 uTriangleStride) { uint32 i, n; //const byte *pInVerticesBytePtr = (const byte *)pInVertices; const byte *pOutTrianglesBytePtr = (const byte *)pOutTriangles; // generate the actual indices DebugAssert(nVertices > 2); uint32 nTriangles = (nVertices - 2); bool Flip = true; uint32 *pTriIndices = (uint32 *)(pOutTrianglesBytePtr); // first triangle is generated outside the loop pTriIndices[0] = 0; pTriIndices[1] = 1; pTriIndices[2] = 2; n = 1; // generate the rest of the triangles for (i = 3; i < nVertices; i++) { pTriIndices = (uint32 *)(pOutTrianglesBytePtr + (uVertexStride * n)); n++; // http://en.wikipedia.org/wiki/File:Triangle_Strip_In_OpenGL.gif if (Flip) { pTriIndices[0] = i - 1; pTriIndices[1] = i - 2; Flip = false; } else { pTriIndices[0] = i - 2; pTriIndices[1] = i - 1; Flip = true; } // and the last vertex pTriIndices[2] = i; } DebugAssert(n == nTriangles); return nTriangles; } void ReverseTriangleWinding(void *pInOutTriangles, uint32 uTriangleStride, uint32 nTriangles) { uint32 i; const byte *pInOutTrianglesBytePtr = (const byte *)pInOutTriangles; for (i = 0; i < nTriangles; i++) { uint32 *pTriIndices = (uint32 *)(pInOutTrianglesBytePtr + (i * uTriangleStride)); uint32 tmp = pTriIndices[0]; pTriIndices[0] = pTriIndices[2]; pTriIndices[2] = tmp; } } void OptimizeIndicesForBatching(void *pInIndices, uint32 IndexStride, const void *pInMaterialIndices, uint32 MaterialIndexStride, uint32 nIndices) { uint32 i; int32 j; byte *pOutPtrIndices; byte *pOutPtrMaterials; int32 MinMaterialId; int32 MaxMaterialId; uint32 nTriangles = nIndices / 3; DebugAssert((nIndices % 3) == 0); uint32 *pSrcIndices = Y_mallocT<uint32>(nIndices); int32 *pSrcMaterials = Y_mallocT<int32>(nTriangles); Y_memcpy_stride(pSrcIndices, sizeof(uint32) * 3, pInIndices, IndexStride, sizeof(uint32) * 3, nTriangles); // initial pass to grab the maxes pOutPtrMaterials = (byte *)pInMaterialIndices; MinMaterialId = MaxMaterialId = pSrcMaterials[0] = *(uint32 *)pOutPtrMaterials; pOutPtrMaterials += MaterialIndexStride; for (i = 1; i < nTriangles; i++) { pSrcMaterials[i] = *(uint32 *)pOutPtrMaterials; pOutPtrMaterials += MaterialIndexStride; MinMaterialId = Min(MinMaterialId, pSrcMaterials[i]); MaxMaterialId = Max(MaxMaterialId, pSrcMaterials[i]); } // now loop through the material ids and add the indices uint32 NumOutputTriangles = 0; pOutPtrIndices = (byte *)pInIndices; pOutPtrMaterials = (byte *)pInMaterialIndices; for (j = MinMaterialId; j <= MaxMaterialId; j++) { for (i = 0; i < nTriangles; i++) { if (pSrcMaterials[i] == j) { // this one goes in ((uint32 *)pOutPtrIndices)[0] = pSrcIndices[i * 3 + 0]; ((uint32 *)pOutPtrIndices)[1] = pSrcIndices[i * 3 + 1]; ((uint32 *)pOutPtrIndices)[2] = pSrcIndices[i * 3 + 2]; *(uint32 *)pOutPtrMaterials = j; pOutPtrIndices += IndexStride; pOutPtrMaterials += MaterialIndexStride; NumOutputTriangles++; } } } // should be equal DebugAssert(NumOutputTriangles == nTriangles); // free temp memory Y_free(pSrcMaterials); Y_free(pSrcIndices); } static void CreateSphereSubDivide(Vector3f *&pCurrentVertex, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, uint32 Level, const float &Scale) { if (Level > 0) { Level--; Vector3f v3 = (v0 + v1).Normalize(); Vector3f v4 = (v1 + v2).Normalize(); Vector3f v5 = (v2 + v0).Normalize(); CreateSphereSubDivide(pCurrentVertex, v0, v3, v5, Level, Scale); CreateSphereSubDivide(pCurrentVertex, v3, v4, v5, Level, Scale); CreateSphereSubDivide(pCurrentVertex, v3, v1, v4, Level, Scale); CreateSphereSubDivide(pCurrentVertex, v5, v4, v2, Level, Scale); } else { *pCurrentVertex++ = v0 * Scale; *pCurrentVertex++ = v1 * Scale; *pCurrentVertex++ = v2 * Scale; } } void CreateSphere(Vector3f **ppVertices, uint32 *pNumVertices, uint32 SubDivLevel /* = 3 */, float Scale /* = 1.0f */) { uint32 nVertices = 8 * 3 * (1 << (2 * SubDivLevel)); Vector3f *pVertices = new Vector3f[nVertices]; // Tessellate a octahedron Vector3f px0(-1, 0, 0); Vector3f px1(1, 0, 0); Vector3f py0(0, -1, 0); Vector3f py1(0, 1, 0); Vector3f pz0(0, 0, -1); Vector3f pz1(0, 0, 1); Vector3f *pCurrentVertex = pVertices; CreateSphereSubDivide(pCurrentVertex, py0, px0, pz0, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py0, pz0, px1, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py0, px1, pz1, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py0, pz1, px0, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py1, pz0, px0, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py1, px0, pz1, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py1, pz1, px1, SubDivLevel, Scale); CreateSphereSubDivide(pCurrentVertex, py1, px1, pz0, SubDivLevel, Scale); DebugAssert((pCurrentVertex - pVertices) == (int32)nVertices); *ppVertices = pVertices; *pNumVertices = nVertices; } float InterpolateVector(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const float &c0, const float &c1, const float &c2, const Vector3f &p) { // determine barycentric coordinates of p float f01 = (v1.x - v0.x) * (p.y - v0.y) - (p.x - v0.x) * (v1.y - v0.y); float f12 = (v2.x - v1.x) * (p.y - v1.y) - (p.x - v1.x) * (v2.y - v1.y); float f20 = (v0.x - v2.x) * (p.y - v2.y) - (p.x - v2.x) * (v0.y - v2.y); float S = f01 + f12 + f20; float bca = f12 / S; float bcb = f20 / S; float bcy = f01 / S; return bca * c0 + bcb * c1 + bcy * c2; } bool PointInTriangle(const Vector3f &p, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &normal) { #if 0 float3 edge0(v1 - v0); float3 edge1(v2 - v0); float3 edge2(v0 - v2); float3 v0_to_p(p - v0); float3 v1_to_p(p - v1); float3 v2_to_p(p - v2); float3 edge0_normal(edge0.Cross(normal)); float3 edge1_normal(edge1.Cross(normal)); float3 edge2_normal(edge2.Cross(normal)); float r0 = edge0_normal.Dot(v0_to_p); float r1 = edge1_normal.Dot(v1_to_p); float r2 = edge2_normal.Dot(v2_to_p); return (r0 > 0.0f && r1 > 0.0f && r2 > 0.0f) || (r0 <= 0.0f && r1 <= 0.0f && r2 <= 0.0f); #else Vector3f u = v1 - v0; Vector3f v = v2 - v0; Vector3f w = p - v0; Vector3f vCrossW = v.Cross(w); Vector3f vCrossU = v.Cross(u); if (vCrossW.Dot(vCrossU) < 0.0f) return false; Vector3f uCrossW = u.Cross(w); Vector3f uCrossV = u.Cross(v); if (uCrossW.Dot(uCrossV) < 0.0f) return false; float denon = uCrossV.Length(); float invDenom = 1.0f / denon; float r = vCrossW.Length() * invDenom; float t = uCrossW.Length() * invDenom; return (r <= 1.0f && t <= 1.0f && (r + t) <= 1.0f); #endif } void OrthogonalizeTangent(const Vector3f &inTangent, const Vector3f &inBinormal, const Vector3f &inNormal, Vector3f &outTangent, float &outBinormalSign) { Vector3f tangent(inTangent); Vector3f binormal(inBinormal); Vector3f normal(inNormal); float NdotT = normal.Dot(tangent); Vector3f newTangent(tangent.x - NdotT * normal.x, tangent.y - NdotT * normal.y, tangent.z - NdotT * normal.z); float magT = newTangent.Length(); newTangent.NormalizeInPlace(); float NdotB = normal.Dot(binormal); float TdotB = newTangent.Dot(normal) * magT; Vector3f newBinormal(binormal.x - NdotB * normal.x - TdotB * newTangent.x, binormal.y - NdotB * normal.y - TdotB * newTangent.y, binormal.z - NdotB * normal.z - TdotB * newTangent.z); float magB = newBinormal.Length(); newBinormal.NormalizeInPlace(); if (magT <= 1e-6f || magB <= 1e-6f) { Vector3f axis1; Vector3f axis2; float dpXN = Math::Abs(Vector3f::UnitX.Dot(normal)); float dpYN = Math::Abs(Vector3f::UnitY.Dot(normal)); float dpZN = Math::Abs(Vector3f::UnitZ.Dot(normal)); if (dpXN <= dpYN && dpXN <= dpZN) { axis1 = Vector3f::UnitX; axis2 = (dpYN <= dpZN) ? Vector3f::UnitY : Vector3f::UnitZ; } else if (dpYN <= dpXN && dpYN <= dpZN) { axis1 = Vector3f::UnitY; axis2 = (dpYN <= dpZN) ? Vector3f::UnitX : Vector3f::UnitZ; } else { axis1 = Vector3f::UnitZ; axis2 = (dpYN <= dpZN) ? Vector3f::UnitX : Vector3f::UnitY; } newTangent = axis1 - (normal * normal.Dot(axis1)); newBinormal = axis2 - (normal * normal.Dot(axis2)) - (newTangent.SafeNormalize() * newTangent.Dot(axis2)); newTangent.SafeNormalizeInPlace(); newBinormal.SafeNormalizeInPlace(); } float dp = normal.Cross(newTangent).Dot(newBinormal); outTangent = newTangent; outBinormalSign = (dp < 0.0f) ? -1.0f : 1.0f; } } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUBuffer.h #pragma once #include "OpenGLES2Renderer/OpenGLES2Common.h" class OpenGLES2GPUBuffer : public GPUBuffer { public: OpenGLES2GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, GLuint glBufferId, GLenum glBufferTarget, GLenum glBufferUsage); virtual ~OpenGLES2GPUBuffer(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *debugName) override; const GLuint GetGLBufferId() const { return m_glBufferId; } const GLenum GetGLBufferTarget() const { return m_glBufferTarget; } const GLenum GetGLBufferUsage() const { return m_glBufferUsage; } private: GLuint m_glBufferId; GLenum m_glBufferTarget; GLenum m_glBufferUsage; }; <file_sep>/Engine/Source/ResourceCompiler/ShaderCompilerD3D.h #pragma once #include "ResourceCompiler/ShaderCompiler.h" #ifdef Y_PLATFORM_WINDOWS #include "D3D11Renderer/D3DShaderCacheEntry.h" #include <d3dcompiler.h> class ShaderCompilerD3D : public ShaderCompiler { public: ShaderCompilerD3D(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters); virtual ~ShaderCompilerD3D(); protected: // compile virtual bool InternalCompile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) override; // helper functions void BuildD3DDefineList(SHADER_PROGRAM_STAGE stage, MemArray<D3D_SHADER_MACRO> &D3DMacroArray); bool CompileShaderStage(SHADER_PROGRAM_STAGE stage); bool ReflectShader(SHADER_PROGRAM_STAGE stage); bool LinkResourceSamplerParameters(); bool LinkLocalConstantBuffersToParameters(); private: ID3DBlob *m_pStageByteCode[SHADER_PROGRAM_STAGE_COUNT]; MemArray<D3DShaderCacheEntryVertexAttribute> m_outVertexAttributes; MemArray<D3DShaderCacheEntryConstantBuffer> m_outConstantBuffers; MemArray<D3DShaderCacheEntryParameter> m_outParameters; Array<String> m_outConstantBufferNames; Array<String> m_outParameterNames; }; #endif // Y_PLATFORM_WINDOWS <file_sep>/Engine/Source/ResourceCompiler/ShaderCompiler.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderCompiler.h" #include "ResourceCompiler/ShaderGraphCompiler.h" #include "ResourceCompiler/ShaderGraphCompilerHLSL.h" #include "ResourceCompiler/MaterialShaderGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/MaterialShader.h" #include "Renderer/ShaderComponentTypeInfo.h" #include "Renderer/VertexFactoryTypeInfo.h" Log_SetChannel(ShaderCompiler); static const char SHADER_SOURCE_BASE_DIRECTORY[] = "shaders/base"; static const char MATERIAL_SHADER_TEMPLATE_HEADER_FILE[] = "shaders/base/MaterialTemplateHeader.hlsl"; static const char MATERIAL_SHADER_TEMPLATE_FOOTER_FILE[] = "shaders/base/MaterialTemplateFooter.hlsl"; ShaderCompiler::ShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters) : m_pResourceCompilerCallbacks(pCallbacks), m_pMaterialShaderCode(nullptr), m_eRendererPlatform(pParameters->Platform), m_eRendererFeatureLevel(pParameters->FeatureLevel), m_iShaderCompilerFlags(pParameters->CompilerFlags), m_iMaterialShaderFlags(pParameters->MaterialShaderFlags), m_pDumpWriter(NULL) { for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { m_StageFileNames[i] = pParameters->StageFileNames[i]; m_StageEntryPoints[i] = pParameters->StageEntryPoints[i]; } m_VertexFactoryFileName = pParameters->VertexFactoryFileName; m_MaterialShaderName = pParameters->MaterialShaderName; m_CompileMacros.Reserve(pParameters->PreprocessorMacros.GetSize()); for (uint32 i = 0; i < pParameters->PreprocessorMacros.GetSize(); i++) m_CompileMacros.Add(pParameters->PreprocessorMacros[i]); } ShaderCompiler::~ShaderCompiler() { if (m_pMaterialShaderCode != nullptr) m_pMaterialShaderCode->Release(); } void ShaderCompiler::AddCompileMacro(const char *macroName, const char *macroValue) { m_CompileMacros.Add(ShaderCompilerParameters::PreprocessorMacro(macroName, macroValue)); } void ShaderCompiler::SetupShaderGraphCompiler(MaterialShaderGenerator *pMaterialShaderSource, ShaderGraphCompiler *pCompiler) const { uint32 i; SmallString bindingName; DebugAssert(pMaterialShaderSource != NULL); // uniforms for (i = 0; i < pMaterialShaderSource->GetUniformParameterCount(); i++) { const MaterialShaderGenerator::UniformParameter *pUniformParameter = pMaterialShaderSource->GetUniformParameter(i); bindingName.Format("MTLUniformParameter_%s", pUniformParameter->Name.GetCharArray()); pCompiler->AddExternalUniformParameter(pUniformParameter->Name, pUniformParameter->Type, bindingName); } // textures for (i = 0; i < pMaterialShaderSource->GetTextureParameterCount(); i++) { const MaterialShaderGenerator::TextureParameter *pTextureParameter = pMaterialShaderSource->GetTextureParameter(i); bindingName.Format("MTLTextureParameter_%s", pTextureParameter->Name.GetCharArray()); pCompiler->AddExternalTextureParameter(pTextureParameter->Name, pTextureParameter->Type, bindingName); } // static switches -- since these are string allocated, they have to be pushed on the compiler parameters for (i = 0; i < pMaterialShaderSource->GetStaticSwitchParameterCount(); i++) { const MaterialShaderGenerator::StaticSwitchParameter *pStaticSwitchParameter = pMaterialShaderSource->GetStaticSwitchParameter(i); pCompiler->AddExternalStaticSwitchParameter(pStaticSwitchParameter->Name, (m_iMaterialShaderFlags & (1 << i)) != 0); } } bool ShaderCompiler::ReadIncludeFile(bool systemInclude, const char *filename, void **ppOutFileContents, uint32 *pOutFileLength) { AutoReleasePtr<GrowableMemoryByteStream> pOutStream = ByteStream_CreateGrowableMemoryStream(); BinaryBlob *pCodeBlob = nullptr; // Generated filenames if (Y_stricmp(filename, "VertexFactory.hlsl") == 0) pCodeBlob = (!m_VertexFactoryFileName.IsEmpty()) ? m_pResourceCompilerCallbacks->GetFileContents(m_VertexFactoryFileName) : nullptr; else if (Y_stricmp(filename, "Material.hlsl") == 0) pCodeBlob = (m_pMaterialShaderCode != nullptr) ? BinaryBlob::CreateFromPointer(m_pMaterialShaderCode->GetDataPointer(), m_pMaterialShaderCode->GetDataSize()) : nullptr; else { SmallString diskFilename; diskFilename.Format("%s/%s", SHADER_SOURCE_BASE_DIRECTORY, filename); pCodeBlob = m_pResourceCompilerCallbacks->GetFileContents(diskFilename); } if (pCodeBlob == nullptr) { Log_WarningPrintf("ShaderCompiler::ReadIncludeFile: Failed to include file '%s'", filename); return false; } pCodeBlob->DetachMemory(ppOutFileContents, pOutFileLength); pCodeBlob->Release(); return true; } void ShaderCompiler::FreeIncludeFile(void *pFileContents) { Y_free(pFileContents); } bool ShaderCompiler::Compile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) { SmallString fileName; // if a material shader was specified, load it's source, and compile the shader graph (if there is one) if (!m_MaterialShaderName.IsEmpty()) { // load source fileName.Format("%s.msh.xml", m_MaterialShaderName.GetCharArray()); BinaryBlob *pBlob = m_pResourceCompilerCallbacks->GetFileContents(fileName); if (pBlob == nullptr) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to find material shader source. (%s)", fileName.GetCharArray()); return false; } // create generator ByteStream *pMaterialSourceStream = pBlob->CreateReadOnlyStream(); MaterialShaderGenerator *pMaterialSource = new MaterialShaderGenerator(); if (!pMaterialSource->LoadFromXML(m_pResourceCompilerCallbacks, fileName, pMaterialSourceStream)) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to load material shader source. (%s)", fileName.GetCharArray()); return false; } // release source now pMaterialSourceStream->Release(); pBlob->Release(); // create the temporary output stream ByteStream *pCodeStream = ByteStream_CreateGrowableMemoryStream(); // append the material shader header pBlob = m_pResourceCompilerCallbacks->GetFileContents(MATERIAL_SHADER_TEMPLATE_HEADER_FILE); if (pBlob == nullptr || !pCodeStream->Write2(pBlob->GetDataPointer(), pBlob->GetDataSize())) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to read material shader common header."); if (pBlob != nullptr) pBlob->Release(); pCodeStream->Release(); delete pMaterialSource; return false; } // prefer code over graphs int32 currentFeatureLevel = (int32)m_eRendererFeatureLevel; for (; currentFeatureLevel >= 0; currentFeatureLevel--) { if (pMaterialSource->GetShaderCodeAvailability((RENDERER_FEATURE_LEVEL)currentFeatureLevel)) { const String *pCode = pMaterialSource->GetShaderCode((RENDERER_FEATURE_LEVEL)currentFeatureLevel); pCodeStream->Write2(pCode->GetCharArray(), pCode->GetLength()); break; } else if (pMaterialSource->GetShaderGraphAvailability((RENDERER_FEATURE_LEVEL)currentFeatureLevel)) { const ShaderGraph *pGraph = pMaterialSource->GetShaderGraph((RENDERER_FEATURE_LEVEL)currentFeatureLevel); ShaderGraphCompilerHLSL *pGraphCompiler = new ShaderGraphCompilerHLSL(pGraph); SetupShaderGraphCompiler(pMaterialSource, pGraphCompiler); if (!pGraphCompiler->Compile(pCodeStream)) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to compile shader graph at feature level %s for material shader %s.", NameTable_GetNameString(NameTables::RendererFeatureLevel, currentFeatureLevel), m_MaterialShaderName.GetCharArray()); delete pGraphCompiler; pCodeStream->Release(); delete pMaterialSource; return false; } delete pGraphCompiler; break; } } // material can be unloaded now delete pMaterialSource; // if we didn't get any code, that is fatal if (currentFeatureLevel < 0) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to get shader code for material shader %s.", m_MaterialShaderName.GetCharArray()); pCodeStream->Release(); return false; } // set material feature level switch (currentFeatureLevel) { case RENDERER_FEATURE_LEVEL_ES2: m_CompileMacros.Add(ShaderCompilerParameters::PreprocessorMacro(StaticString("MATERIAL_FEATURE_LEVEL"), StaticString("0"))); break; case RENDERER_FEATURE_LEVEL_ES3: m_CompileMacros.Add(ShaderCompilerParameters::PreprocessorMacro(StaticString("MATERIAL_FEATURE_LEVEL"), StaticString("1"))); break; case RENDERER_FEATURE_LEVEL_SM4: m_CompileMacros.Add(ShaderCompilerParameters::PreprocessorMacro(StaticString("MATERIAL_FEATURE_LEVEL"), StaticString("2"))); break; case RENDERER_FEATURE_LEVEL_SM5: m_CompileMacros.Add(ShaderCompilerParameters::PreprocessorMacro(StaticString("MATERIAL_FEATURE_LEVEL"), StaticString("3"))); break; } // append the material shader footer pBlob = m_pResourceCompilerCallbacks->GetFileContents(MATERIAL_SHADER_TEMPLATE_FOOTER_FILE); if (pBlob == nullptr || !pCodeStream->Write2(pBlob->GetDataPointer(), pBlob->GetDataSize())) { Log_ErrorPrintf("ShaderCompiler::Compile: Failed to read material shader common footer."); if (pBlob != nullptr) pBlob->Release(); pCodeStream->Release(); return false; } // turn the stream into a blob m_pMaterialShaderCode = BinaryBlob::CreateFromStream(pCodeStream); pCodeStream->Release(); } // add writer if (pInfoLogStream != NULL) m_pDumpWriter = new TextWriter(pInfoLogStream); // invoke compile bool returnValue = InternalCompile(pByteCodeStream, pInfoLogStream); // close writer delete m_pDumpWriter; m_pDumpWriter = NULL; // clean up return returnValue; } bool ResourceCompiler::CompileShader(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters, ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) { ShaderCompiler *pShaderCompiler; switch (pParameters->Platform) { #ifdef Y_PLATFORM_WINDOWS case RENDERER_PLATFORM_D3D11: case RENDERER_PLATFORM_D3D12: pShaderCompiler = ShaderCompiler::CreateD3D11ShaderCompiler(pCallbacks, pParameters); break; #endif case RENDERER_PLATFORM_OPENGL: case RENDERER_PLATFORM_OPENGLES2: pShaderCompiler = ShaderCompiler::CreateOpenGLShaderCompiler(pCallbacks, pParameters); break; default: Log_ErrorPrintf("ResourceCompiler::CompileShader: Unknown shader platform: %s", NameTable_GetNameString(NameTables::RendererPlatform, pParameters->Platform)); return false; } if (!pShaderCompiler->Compile(pByteCodeStream, pInfoLogStream)) { delete pShaderCompiler; return false; } delete pShaderCompiler; return true; } <file_sep>/Engine/Source/Renderer/ShaderMap.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderMap.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Engine/MaterialShader.h" #include "Engine/EngineCVars.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" Log_SetChannel(ShaderMap); int32 ShaderMap::Key::Compare(const Key *a, const Key *b) { return Y_memcmp(a, b, sizeof(Key)); } ShaderMap::ShaderMap() { } ShaderMap::~ShaderMap() { ReleaseGPUResources(); } ShaderProgram *ShaderMap::GetShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const { // binary search the list Key key(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, nullptr, 0, pMaterialShader, materialShaderFlags); const ProgramEntry *pProgramEntry = m_arrLoadedShaders.BinarySearchKey<Key>(key, [](const Key *key, const ProgramEntry *pe) { return Key::Compare(key, &pe->Key); }); if (pProgramEntry != nullptr) return pProgramEntry->Value; // load it return LoadShaderPermutation(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, nullptr, 0, pMaterialShader, materialShaderFlags, pVertexAttributes, nVertexAttributes); } ShaderProgram *ShaderMap::GetShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const { // binary search the list Key key(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags); const ProgramEntry *pProgramEntry = m_arrLoadedShaders.BinarySearchKey<Key>(key, [](const Key *key, const ProgramEntry *pe) { return Key::Compare(key, &pe->Key); }); if (pProgramEntry != nullptr) return pProgramEntry->Value; // load it GPU_VERTEX_ELEMENT_DESC vertexAttributes[GPU_INPUT_LAYOUT_MAX_ELEMENTS]; uint32 nVertexAttributes = (pVertexFactoryTypeInfo != nullptr) ? pVertexFactoryTypeInfo->GetVertexElementsDesc(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), vertexFactoryFlags, vertexAttributes) : 0; return LoadShaderPermutation(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags, vertexAttributes, nVertexAttributes); } void ShaderMap::ReleaseGPUResources() { for (uint32 i = 0; i < m_arrLoadedShaders.GetSize(); i++) delete m_arrLoadedShaders[i].Value; m_arrLoadedShaders.Obliterate(); } ShaderProgram *ShaderMap::LoadShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes) const { // stuff to load RENDERER_PLATFORM rendererPlatform = g_pRenderer->GetPlatform(); RENDERER_FEATURE_LEVEL rendererFeatureLevel = g_pRenderer->GetFeatureLevel(); // resultant gpu program GPUShaderProgram *pGPUProgram = nullptr; // get hash code for shader uint8 shaderHashCode[16]; SmallString hashCodeStr; PathString diskCacheFileName; ShaderCompilerFrontend::GenerateShaderHashCode(shaderHashCode, globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags); StringConverter::BytesToHexString(hashCodeStr, shaderHashCode, sizeof(shaderHashCode)); // can we use the disk cache? if (CVars::r_use_shader_cache.GetBool()) { // construct filename diskCacheFileName.Format("shadercache/%s_%s_%s/%s.bin", NameTable_GetNameString(NameTables::RendererPlatform, rendererPlatform), NameTable_GetNameString(NameTables::RendererFeatureLevel, rendererFeatureLevel), (CVars::r_use_debug_shaders.GetBool()) ? "DEBUG" : "RELEASE", hashCodeStr.GetCharArray()); // try opening it ByteStream *pStream = g_pVirtualFileSystem->OpenFile(diskCacheFileName, BYTESTREAM_OPEN_READ); if (pStream != nullptr) { Log_DevPrintf("ShaderMap::LoadShaderPermutation: Shader program '%s' found in cache, attempting to use it.", hashCodeStr.GetCharArray()); // read common header DF_SHADER_PROGRAM_COMMON_HEADER commonHeader; if (!pStream->Read2(&commonHeader, sizeof(commonHeader)) || commonHeader.Magic != DF_SHADER_PROGRAM_COMMON_HEADER_MAGIC) { Log_WarningPrintf("ShaderMap::LoadShaderPermutation: Bad common magic for shader program '%s'", hashCodeStr.GetCharArray()); pStream->Release(); } else { #if defined(WITH_RESOURCECOMPILER_EMBEDDED) || defined(WITH_RESOURCECOMPILER_SUBPROCESS) // check code changes, only if resourcecompiler is present uint32 baseShaderParameterCRC = (pBaseShaderTypeInfo != nullptr) ? pBaseShaderTypeInfo->GetParameterCRC() : 0; uint32 vertexFactoryParameterCRC = (pVertexFactoryTypeInfo != nullptr) ? pVertexFactoryTypeInfo->GetParameterCRC() : 0; uint32 materialShaderCRC = (pMaterialShader != nullptr) ? pMaterialShader->GetSourceCRC() : 0; if (commonHeader.ShaderStoreCRC != ShaderCompilerFrontend::GetShaderStoreHash() || commonHeader.BaseShaderParameterCRC != baseShaderParameterCRC || commonHeader.VertexFactoryParameterCRC != vertexFactoryParameterCRC || commonHeader.MaterialShaderCRC != materialShaderCRC) { Log_WarningPrintf("ShaderMap::LoadShaderPermutation: Shader program '%s' is out of date. Disregarding cache version.", hashCodeStr.GetCharArray()); pStream->Release(); } else { // create shader pGPUProgram = g_pRenderer->CreateGraphicsProgram(pVertexAttributes, nVertexAttributes, pStream); pStream->Release(); } #else // create shader, since we have no compiler support pGPUProgram = g_pRenderer->CreateGraphicsProgram(pVertexAttributes, nVertexAttributes, pStream); pStream->Release(); #endif } } else { // log a warning Log_WarningPrintf("ShaderMap::LoadShaderPermutation: Shader program '%s' not found in cache, attempting compilation.", hashCodeStr.GetCharArray()); } } #if defined(WITH_CONTENTCONVERTER_EMBEDDED) || defined(WITH_RESOURCECOMPILER_SUBPROCESS) // is a compile necessary? if (pGPUProgram == nullptr) { Log_InfoPrintf("ShaderMap::LoadShaderPermutation: Compiling program (%s, %s, %s, %X, %s, %X, %s, %X) -> %s...", NameTable_GetNameString(NameTables::RendererPlatform, rendererPlatform), NameTable_GetNameString(NameTables::RendererFeatureLevel, rendererFeatureLevel), (pBaseShaderTypeInfo != nullptr) ? pBaseShaderTypeInfo->GetTypeName() : "NULL", baseShaderFlags, (pVertexFactoryTypeInfo != nullptr) ? pVertexFactoryTypeInfo->GetTypeName() : "NULL", vertexFactoryFlags, (pMaterialShader != nullptr) ? pMaterialShader->GetName().GetCharArray() : "NULL", materialShaderFlags, hashCodeStr.GetCharArray()); // create streams AutoReleasePtr<GrowableMemoryByteStream> pByteCodeStream = ByteStream_CreateGrowableMemoryStream(); AutoReleasePtr<ByteStream> pInfoLogStream = nullptr; // setup dump stream if (CVars::r_dump_shaders.GetBool()) { PathString dumpFileName; StringConverter::BytesToHexString(hashCodeStr, shaderHashCode, sizeof(shaderHashCode)); dumpFileName.Format("shaderdump/%s_%s_%s/%s.txt", NameTable_GetNameString(NameTables::RendererPlatform, g_pRenderer->GetPlatform()), NameTable_GetNameString(NameTables::RendererFeatureLevel, g_pRenderer->GetFeatureLevel()), (CVars::r_use_debug_shaders.GetBool()) ? "DEBUG" : "RELEASE", hashCodeStr.GetCharArray()); pInfoLogStream = g_pVirtualFileSystem->OpenFile(dumpFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE); } // get resource compiler interface ResourceCompilerInterface *pCompilerInterface = g_pResourceManager->GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // forward through to compiler if (ShaderCompilerFrontend::CompileShader(pCompilerInterface, globalShaderFlags, g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags, CVars::r_use_debug_shaders.GetBool(), pByteCodeStream, pInfoLogStream)) { // write to disk cache if (CVars::r_use_shader_cache.GetBool() && CVars::r_allow_shader_cache_writes.GetBool()) { ByteStream *pStream = g_pVirtualFileSystem->OpenFile(diskCacheFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream != nullptr) { // generate the common header DF_SHADER_PROGRAM_COMMON_HEADER commonHeader; commonHeader.Magic = DF_SHADER_PROGRAM_COMMON_HEADER_MAGIC; commonHeader.ShaderStoreCRC = ShaderCompilerFrontend::GetShaderStoreHash(); commonHeader.BaseShaderParameterCRC = (pBaseShaderTypeInfo != nullptr) ? pBaseShaderTypeInfo->GetParameterCRC() : 0; commonHeader.VertexFactoryParameterCRC = (pVertexFactoryTypeInfo != nullptr) ? pVertexFactoryTypeInfo->GetParameterCRC() : 0; commonHeader.MaterialShaderCRC = (pMaterialShader != nullptr) ? pMaterialShader->GetSourceCRC() : 0; // write common header and bytecode pByteCodeStream->SeekAbsolute(0); if (pStream->Write2(&commonHeader, sizeof(commonHeader)) && ByteStream_AppendStream(pByteCodeStream, pStream)) pStream->Commit(); else pStream->Discard(); pStream->Release(); } } // create gpu object pByteCodeStream->SeekAbsolute(0); pGPUProgram = g_pRenderer->CreateGraphicsProgram(pVertexAttributes, nVertexAttributes, pByteCodeStream); } else { Log_ErrorPrintf("ShaderMap::LoadShaderPermutation: Compiling program %s failed.", hashCodeStr.GetCharArray()); } // release compiler interface g_pResourceManager->ReleaseResourceCompilerInterface(pCompilerInterface); } } #endif // set debug name #ifdef Y_BUILD_CONFIG_DEBUG if (pGPUProgram != nullptr) { pGPUProgram->SetDebugName(SmallString::FromFormat("%s<0x%x>:%s<0x%x>:%s<0x%x>", (pBaseShaderTypeInfo != nullptr) ? pBaseShaderTypeInfo->GetTypeName() : "null", baseShaderFlags, (pVertexFactoryTypeInfo != nullptr) ? pVertexFactoryTypeInfo->GetTypeName() : "null", vertexFactoryFlags, (pMaterialShader != nullptr) ? pMaterialShader->GetName().GetCharArray() : "null", materialShaderFlags)); } #endif // got a gpu program? ShaderProgram *pProgram = (pGPUProgram != nullptr) ? new ShaderProgram(pGPUProgram, globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags) : nullptr; // add to list, and re-sort it m_arrLoadedShaders.Add(ProgramEntry(Key(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags), pProgram)); m_arrLoadedShaders.SortCB([](const ProgramEntry &a, const ProgramEntry &b) { return Key::Compare(&a.Key, &b.Key); }); return pProgram; } <file_sep>/Engine/Source/Engine/Engine.h #pragma once #include "Engine/Common.h" #include "Engine/CommandQueue.h" #include "Core/RandomNumberGenerator.h" #include "YBaseLib/TaskQueue.h" class Font; class Engine { public: Engine(); ~Engine(); // default name accessors const String &GetDefaultTextureName(TEXTURE_TYPE TextureType) const; const String &GetDefaultTexture2DName() const { return m_strDefaultTexture2DName; } const String &GetDefaultTexture2DArrayName() const { return m_strDefaultTexture2DArrayName; } const String &GetDefaultTextureCubeName() const { return m_strDefaultTextureCubeName; } const String &GetDefaultMaterialShaderName() const { return m_strDefaultMaterialShaderName; } const String &GetDefaultMaterialName() const { return m_strDefaultMaterialName; } const String &GetDefaultFontName() const { return m_strDefaultFontName; } const String &GetDefaultStaticMeshName() const { return m_strDefaultStaticMeshName; } const String &GetDefaultBlockMeshName() const { return m_strDefaultBlockMeshName; } const String &GetDefaultSkeletalMeshName() const { return m_strDefaultSkeletalMeshName; } // fixed name accessors const String &GetSpriteMaterialShaderName() const { return m_strSpriteMaterialShaderName; } const String &GetRendererDebugFontName() const { return m_strRendererDebugFontName; } // default resource accessors. these DO increment the reference count upon retrieval. const Font *GetDefaultFont() const; // fixed resource accessors. these DO NOT increment the reference count upon retrieval, as they are assumed to be persistent. // Registers classes associated with the engine library virtual void RegisterEngineTypes(); // Unregister all classes. virtual void UnregisterTypes(); // initializes the remaining layers and calls application initialization. virtual bool Startup(); // shuts down all systems virtual void Shutdown(); // command queue access TaskQueue *GetMainThreadCommandQueue() { return &m_mainThreadCommandQueue; } TaskQueue *GetAsyncCommandQueue() { return &m_asyncCommandQueue; } TaskQueue *GetBackgroundCommandQueue() { return &m_backgroundCommandQueue; } // game thread random number generator // can only be accessed from game thread! RandomNumberGenerator *GetRandomNumberGenerator() { return &m_randomNumberGenerator; } private: // registers internal types void RegisterEngineResourceTypes(); void RegisterEngineComponentTypes(); void RegisterEngineEntityTypes(); void RegisterExternalTypes(); // default resource names String m_strDefaultTexture2DName; String m_strDefaultTexture2DArrayName; String m_strDefaultTextureCubeName; String m_strDefaultMaterialShaderName; String m_strDefaultMaterialName; String m_strDefaultFontName; String m_strDefaultStaticMeshName; String m_strDefaultBlockMeshName; String m_strDefaultSkeletalMeshName; // fixed resource names String m_strSpriteMaterialShaderName; String m_strRendererDebugFontName; // default resources mutable const Font *m_pDefaultFont; // fixed resources // worker thread pool ThreadPool *m_pWorkerThreadPool; // main thread command queue TaskQueue m_mainThreadCommandQueue; // async command queue TaskQueue m_asyncCommandQueue; // background command queue TaskQueue m_backgroundCommandQueue; // random number generator RandomNumberGenerator m_randomNumberGenerator; }; extern Engine *g_pEngine; // command queue helper macros #define QUEUE_MAIN_THREAD_COMMAND(obj) g_pEngine->GetMainThreadCommandQueue()->QueueTask(&obj, sizeof(obj)) #define QUEUE_MAIN_THREAD_LAMBDA_COMMAND g_pEngine->GetMainThreadCommandQueue()->QueueLambdaTask #define QUEUE_ASYNC_COMMAND(obj) g_pEngine->GetAsyncCommandQueue()->QueueTask(&obj, sizeof(obj)) #define QUEUE_ASYNC_LAMBDA_COMMAND g_pEngine->GetAsyncCommandQueue()->QueueLambdaTask #define QUEUE_BACKGROUND_COMMAND(obj) g_pEngine->GetBackgroundCommandQueue()->QueueTask(&obj, sizeof(obj)) #define QUEUE_BACKGROUND_LAMBDA_COMMAND g_pEngine->GetBackgroundCommandQueue()->QueueLambdaTask <file_sep>/Engine/Source/Engine/World.h #pragma once #include "Engine/Common.h" namespace Physics { class PhysicsWorld; } class RenderWorld; class Brush; class Entity; class ParticleSystem; class ParticleSystemRenderProxy; // Base world class doesn't implement entity storage class World { public: World(); virtual ~World(); // Bounds const AABox &GetWorldBoundingBox() const { return m_worldBoundingBox; } const Sphere &GetWorldBoundingSphere() const { return m_worldBoundingSphere; } // Game time const float GetGameTime() const { return m_gameTime; } // Physics World const Physics::PhysicsWorld *GetPhysicsWorld() const { return m_pPhysicsWorld; } Physics::PhysicsWorld *GetPhysicsWorld() { return m_pPhysicsWorld; } // Render World const RenderWorld *GetRenderWorld() const { return m_pRenderWorld; } RenderWorld *GetRenderWorld() { return m_pRenderWorld; } // Entity ID allocation uint32 GetNextEntityID() const { return m_nextEntityID; } uint32 AllocateEntityID() { return m_nextEntityID++; } void SetNextEntityID(uint32 NewNextEntityId) { DebugAssert(NewNextEntityId >= m_nextEntityID); m_nextEntityID = NewNextEntityId; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Implementation-specific methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // immediately adds an object to world virtual void AddBrush(Brush *pObject) = 0; // immediately removes an object from world, use with care virtual void RemoveBrush(Brush *pObject) = 0; // Searches for an entity by id. // Pointers returned by this method are guaranteed for the lifetime of the current frame. virtual const Entity *GetEntityByID(uint32 EntityId) const = 0; virtual Entity *GetEntityByID(uint32 EntityId) = 0; // immediately adds the entity to world virtual void AddEntity(Entity *pEntity) = 0; // updates spatial structure for new entity bounds virtual void MoveEntity(Entity *pEntity) = 0; // updates any needed internal information when an entity property is modified virtual void UpdateEntity(Entity *pEntity) = 0; // immediately removes the entity from world virtual void RemoveEntity(Entity *pEntity) = 0; // removes the entity from the world at the end of the frame, safer for game use void QueueRemoveEntity(Entity *pEntity); // observers uint32 GetObserverCount() const { return m_observers.GetSize(); } const float3 &GetObserverLocation(uint32 observerIndex) const { return m_observers[observerIndex].Value; } void AddObserver(const void *identifier, const float3 &location = float3::Zero); void UpdateObserver(const void *identifier, const float3 &location); void RemoveObserver(const void *identifier); // cast a ray into the world, returning the entity it hit (if any) bool RayCast(const Ray &ray, Entity **ppHitEntity, float3 *pContactNormal, float3 *pContactPoint); bool RayCast(const float3 &origin, const float3 &direction, float maxDistance, Entity **ppHitEntity, float3 *pContactNormal, float3 *pContactPoint) { return RayCast(Ray(origin, direction, maxDistance), ppHitEntity, pContactNormal, pContactPoint); } // temporary particle effects, these are allocated and managed by the world, // and automatically destroyed at the end of their lifetime. todo move to own class? void SpawnParticleEmitter(const ParticleSystem *pParticleSystem, float lifeSpan, const float3 &location, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const float3 &initialVelocity = float3::Zero, float mass = 0.0f); // active entities void RegisterEntityForUpdate(Entity *pEntity, float interval); void RegisterEntityForAsyncUpdate(Entity *pEntity, float interval); void UnregisterEntityForUpdate(Entity *pEntity); void UnregisterEntityForAsyncUpdate(Entity *pEntity); // Executed on the start of the frame virtual void BeginFrame(float deltaTime); // Update entities, async part virtual void UpdateAsync(float deltaTime); // Update entities virtual void Update(float deltaTime); // Execute on the end of the frame virtual void EndFrame(); protected: AABox m_worldBoundingBox; Sphere m_worldBoundingSphere; uint32 m_nextEntityID; float m_gameTime; // Bullet world Physics::PhysicsWorld *m_pPhysicsWorld; // Render world RenderWorld *m_pRenderWorld; // entity updates struct EntityUpdateData { Entity *pEntity; float UpdateInterval; float TimeSinceLastUpdate; }; typedef MemArray<EntityUpdateData> EntityUpdateDataArray; EntityUpdateDataArray m_activeEntities; EntityUpdateDataArray m_activeAsyncEntities; // sort the active entity list, entities with more frequent updates come first void SortActiveEntities(); void SortActiveAsyncEntities(); // observers typedef KeyValuePair<const void *, float3> ObserverEntry; typedef MemArray<ObserverEntry> ObserverArray; ObserverArray m_observers; // removal queue for end of frame PODArray<Entity *> m_removeQueue; // temporary particle effects void UpdateTemporaryParticleEffects(float deltaTime); struct TemporaryParticleEffect { ParticleSystemRenderProxy *pRenderProxy; Transform BaseTransform; float TimeRemaining; bool HasVelocity; float3 Velocity; float Mass; }; MemArray<TemporaryParticleEffect> m_temporaryParticleEffects; }; <file_sep>/DemoGame/CMakeLists.txt set(HEADER_FILES Source/DemoGame/BaseDemoGameState.h Source/DemoGame/BaseDemoWorldGameState.h Source/DemoGame/DemoCamera.h Source/DemoGame/DemoGame.h Source/DemoGame/DemoUtilities.h Source/DemoGame/DrawCallStressDemo.h Source/DemoGame/ImGuiDemo.h Source/DemoGame/LaunchpadGameState.h Source/DemoGame/PrecompiledHeader.h Source/DemoGame/SkeletalAnimationDemo.h ) set(SOURCE_FILES Source/DemoGame/BaseDemoGameState.cpp Source/DemoGame/BaseDemoWorldGameState.cpp Source/DemoGame/DemoCamera.cpp Source/DemoGame/DemoGame.cpp Source/DemoGame/DemoUtilities.cpp Source/DemoGame/DrawCallStressDemo.cpp Source/DemoGame/ImGuiDemo.cpp Source/DemoGame/LaunchpadGameState.cpp Source/DemoGame/Main.cpp Source/DemoGame/PrecompiledHeader.cpp Source/DemoGame/SkeletalAnimationDemo.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${GameEngineDev_SOURCE_DIR}/DemoGame/Source ${SDL2_INCLUDE_DIR}) if(ANDROID) add_library(DemoGameBin STATIC ${HEADER_FILES} ${SOURCE_FILES}) else() add_executable(DemoGameBin ${HEADER_FILES} ${SOURCE_FILES}) #if(APPLE) #set_target_properties(DemoGameBin PROPERTIES MACOSX_BUNDLE TRUE) #endif() install(TARGETS DemoGameBin DESTINATION ${INSTALL_BINARIES_DIRECTORY}) endif() target_link_libraries(DemoGameBin EngineBaseGame EngineMain EngineCore bullet) <file_sep>/Editor/Source/Editor/EditorLightSimulatorControlWidget.cpp #include "Editor/PrecompiledHeader.h" <file_sep>/Engine/Source/D3D12Renderer/D3D12DescriptorHeap.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" Log_SetChannel(D3D12RenderBackend); D3D12DescriptorHeap::D3D12DescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 descriptorCount, ID3D12DescriptorHeap *pD3DDescriptorHeap, uint32 incrementSize) : m_type(type) , m_descriptorCount(descriptorCount) , m_pD3DDescriptorHeap(pD3DDescriptorHeap) , m_CPUHandleStart(pD3DDescriptorHeap->GetCPUDescriptorHandleForHeapStart()) , m_GPUHandleStart(pD3DDescriptorHeap->GetGPUDescriptorHandleForHeapStart()) , m_allocationMap(descriptorCount) , m_incrementSize(incrementSize) { m_allocationMap.Clear(); } D3D12DescriptorHeap::~D3D12DescriptorHeap() { // shouldn't have any allocations size_t foundIndex; Assert(!m_allocationMap.FindFirstSetBit(&foundIndex)); m_pD3DDescriptorHeap->Release(); } D3D12DescriptorHeap *D3D12DescriptorHeap::Create(ID3D12Device *pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 descriptorCount, bool cpuOnly) { D3D12_DESCRIPTOR_HEAP_DESC desc; desc.Type = type; desc.NumDescriptors = descriptorCount; desc.Flags = (cpuOnly) ? D3D12_DESCRIPTOR_HEAP_FLAG_NONE : D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; desc.NodeMask = 0; ID3D12DescriptorHeap *pD3DDescriptorHeap; HRESULT hResult = pDevice->CreateDescriptorHeap(&desc, __uuidof(pD3DDescriptorHeap), (void **)&pD3DDescriptorHeap); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12DescriptorHeap::Create: CreateDescriptorHeap failed with hResult %08X", hResult); return nullptr; } uint32 incrementSize = pDevice->GetDescriptorHandleIncrementSize(type); return new D3D12DescriptorHeap(type, descriptorCount, pD3DDescriptorHeap, incrementSize); } bool D3D12DescriptorHeap::Allocate(D3D12DescriptorHandle *handle) { m_mutex.Lock(); // find a free index size_t index; if (!m_allocationMap.FindFirstClearBit(&index)) { m_mutex.Unlock(); return false; } // flag as allocated DebugAssert(!m_allocationMap.TestBit(index)); m_allocationMap.SetBit(index); m_mutex.Unlock(); // create handle handle->CPUHandle.ptr = m_CPUHandleStart.ptr + index * m_incrementSize; handle->GPUHandle.ptr = m_GPUHandleStart.ptr + index * m_incrementSize; handle->Type = m_type; handle->StartIndex = (uint32)index; handle->DescriptorCount = 1; handle->IncrementSize = m_incrementSize; return true; } bool D3D12DescriptorHeap::AllocateRange(uint32 count, D3D12DescriptorHandle *handle) { m_mutex.Lock(); // find a free index size_t startIndex; if (!m_allocationMap.FindContiguousClearBits(count, &startIndex)) { m_mutex.Unlock(); return false; } // flag as allocated for (uint32 i = 0; i < count; i++) { DebugAssert(!m_allocationMap.TestBit(startIndex + i)); m_allocationMap.SetBit(startIndex + i); } m_mutex.Unlock(); // create handle handle->CPUHandle.ptr = m_CPUHandleStart.ptr + startIndex * m_incrementSize; handle->GPUHandle.ptr = m_GPUHandleStart.ptr + startIndex * m_incrementSize; handle->Type = m_type; handle->StartIndex = (uint32)startIndex; handle->DescriptorCount = count; handle->IncrementSize = m_incrementSize; return true; } void D3D12DescriptorHeap::Free(D3D12DescriptorHandle &handle) { // free empty handle? if (handle.DescriptorCount == 0) return; // sanity check handle is correct offset and hasn't been corrupted uint32 startIndex = handle.StartIndex; DebugAssert(handle.Type == m_type); DebugAssert(startIndex < m_descriptorCount); DebugAssert((m_CPUHandleStart.ptr + startIndex * m_incrementSize) == handle.CPUHandle.ptr); DebugAssert((m_GPUHandleStart.ptr + startIndex * m_incrementSize) == handle.GPUHandle.ptr); m_mutex.Lock(); for (uint32 i = 0; i < handle.DescriptorCount; i++) { DebugAssert(m_allocationMap.TestBit(handle.StartIndex + i)); m_allocationMap.UnsetBit(handle.StartIndex + i); } m_mutex.Unlock(); // wipe handle handle.Clear(); } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DescriptorHandle::GetOffsetCPUHandle(uint32 index) const { D3D12_CPU_DESCRIPTOR_HANDLE handle = CPUHandle; handle.ptr += IncrementSize * index; return handle; } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DescriptorHandle::GetOffsetGPUHandle(uint32 index) const { D3D12_GPU_DESCRIPTOR_HANDLE handle = GPUHandle; handle.ptr += IncrementSize * index; return handle; } <file_sep>/Editor/Source/Editor/BlockMeshEditor/moc_EditorBlockMeshEditor.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorBlockMeshEditor.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorBlockMeshEditor.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorBlockMeshEditor.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorBlockMeshEditor_t { QByteArrayData data[40]; char stringdata[1025]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorBlockMeshEditor_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorBlockMeshEditor_t qt_meta_stringdata_EditorBlockMeshEditor = { { QT_MOC_LITERAL(0, 0, 21), // "EditorBlockMeshEditor" QT_MOC_LITERAL(1, 22, 23), // "OnActionSaveMeshClicked" QT_MOC_LITERAL(2, 46, 0), // "" QT_MOC_LITERAL(3, 47, 25), // "OnActionSaveMeshAsClicked" QT_MOC_LITERAL(4, 73, 20), // "OnActionCloseClicked" QT_MOC_LITERAL(5, 94, 23), // "OnActionEditUndoClicked" QT_MOC_LITERAL(6, 118, 23), // "OnActionEditRedoClicked" QT_MOC_LITERAL(7, 142, 34), // "OnActionCameraPerspectiveTrig..." QT_MOC_LITERAL(8, 177, 7), // "checked" QT_MOC_LITERAL(9, 185, 30), // "OnActionCameraArcballTriggered" QT_MOC_LITERAL(10, 216, 32), // "OnActionCameraIsometricTriggered" QT_MOC_LITERAL(11, 249, 30), // "OnActionViewWireframeTriggered" QT_MOC_LITERAL(12, 280, 26), // "OnActionViewUnlitTriggered" QT_MOC_LITERAL(13, 307, 24), // "OnActionViewLitTriggered" QT_MOC_LITERAL(14, 332, 32), // "OnActionViewFlagShadowsTriggered" QT_MOC_LITERAL(15, 365, 41), // "OnActionViewFlagWireframeOver..." QT_MOC_LITERAL(16, 407, 29), // "OnActionWidgetCameraTriggered" QT_MOC_LITERAL(17, 437, 35), // "OnActionWidgetSelectBlocksTri..." QT_MOC_LITERAL(18, 473, 33), // "OnActionWidgetSelectAreaTrigg..." QT_MOC_LITERAL(19, 507, 34), // "OnActionWidgetPlaceBlocksTrig..." QT_MOC_LITERAL(20, 542, 35), // "OnActionWidgetDeleteBlocksTri..." QT_MOC_LITERAL(21, 578, 39), // "OnActionWidgetLightManipulato..." QT_MOC_LITERAL(22, 618, 35), // "OnPlaceBlockWidgetToolButtonC..." QT_MOC_LITERAL(23, 654, 39), // "OnPlaceBlockWidgetListWidgetI..." QT_MOC_LITERAL(24, 694, 16), // "QListWidgetItem*" QT_MOC_LITERAL(25, 711, 5), // "pItem" QT_MOC_LITERAL(26, 717, 24), // "OnSwapChainWidgetResized" QT_MOC_LITERAL(27, 742, 22), // "OnSwapChainWidgetPaint" QT_MOC_LITERAL(28, 765, 30), // "OnSwapChainWidgetKeyboardEvent" QT_MOC_LITERAL(29, 796, 16), // "const QKeyEvent*" QT_MOC_LITERAL(30, 813, 14), // "pKeyboardEvent" QT_MOC_LITERAL(31, 828, 27), // "OnSwapChainWidgetMouseEvent" QT_MOC_LITERAL(32, 856, 18), // "const QMouseEvent*" QT_MOC_LITERAL(33, 875, 11), // "pMouseEvent" QT_MOC_LITERAL(34, 887, 27), // "OnSwapChainWidgetWheelEvent" QT_MOC_LITERAL(35, 915, 18), // "const QWheelEvent*" QT_MOC_LITERAL(36, 934, 11), // "pWheelEvent" QT_MOC_LITERAL(37, 946, 33), // "OnSwapChainWidgetGainedFocusE..." QT_MOC_LITERAL(38, 980, 25), // "OnFrameExecutionTriggered" QT_MOC_LITERAL(39, 1006, 18) // "timeSinceLastFrame" }, "EditorBlockMeshEditor\0OnActionSaveMeshClicked\0" "\0OnActionSaveMeshAsClicked\0" "OnActionCloseClicked\0OnActionEditUndoClicked\0" "OnActionEditRedoClicked\0" "OnActionCameraPerspectiveTriggered\0" "checked\0OnActionCameraArcballTriggered\0" "OnActionCameraIsometricTriggered\0" "OnActionViewWireframeTriggered\0" "OnActionViewUnlitTriggered\0" "OnActionViewLitTriggered\0" "OnActionViewFlagShadowsTriggered\0" "OnActionViewFlagWireframeOverlayTriggered\0" "OnActionWidgetCameraTriggered\0" "OnActionWidgetSelectBlocksTriggered\0" "OnActionWidgetSelectAreaTriggered\0" "OnActionWidgetPlaceBlocksTriggered\0" "OnActionWidgetDeleteBlocksTriggered\0" "OnActionWidgetLightManipulatorTriggered\0" "OnPlaceBlockWidgetToolButtonClicked\0" "OnPlaceBlockWidgetListWidgetItemClicked\0" "QListWidgetItem*\0pItem\0OnSwapChainWidgetResized\0" "OnSwapChainWidgetPaint\0" "OnSwapChainWidgetKeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "OnSwapChainWidgetMouseEvent\0" "const QMouseEvent*\0pMouseEvent\0" "OnSwapChainWidgetWheelEvent\0" "const QWheelEvent*\0pWheelEvent\0" "OnSwapChainWidgetGainedFocusEvent\0" "OnFrameExecutionTriggered\0timeSinceLastFrame" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorBlockMeshEditor[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 28, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 154, 2, 0x08 /* Private */, 3, 0, 155, 2, 0x08 /* Private */, 4, 0, 156, 2, 0x08 /* Private */, 5, 0, 157, 2, 0x08 /* Private */, 6, 0, 158, 2, 0x08 /* Private */, 7, 1, 159, 2, 0x08 /* Private */, 9, 1, 162, 2, 0x08 /* Private */, 10, 1, 165, 2, 0x08 /* Private */, 11, 1, 168, 2, 0x08 /* Private */, 12, 1, 171, 2, 0x08 /* Private */, 13, 1, 174, 2, 0x08 /* Private */, 14, 1, 177, 2, 0x08 /* Private */, 15, 1, 180, 2, 0x08 /* Private */, 16, 1, 183, 2, 0x08 /* Private */, 17, 1, 186, 2, 0x08 /* Private */, 18, 1, 189, 2, 0x08 /* Private */, 19, 1, 192, 2, 0x08 /* Private */, 20, 1, 195, 2, 0x08 /* Private */, 21, 1, 198, 2, 0x08 /* Private */, 22, 1, 201, 2, 0x08 /* Private */, 23, 1, 204, 2, 0x08 /* Private */, 26, 0, 207, 2, 0x08 /* Private */, 27, 0, 208, 2, 0x08 /* Private */, 28, 1, 209, 2, 0x08 /* Private */, 31, 1, 212, 2, 0x08 /* Private */, 34, 1, 215, 2, 0x08 /* Private */, 37, 0, 218, 2, 0x08 /* Private */, 38, 1, 219, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, QMetaType::Bool, 8, QMetaType::Void, 0x80000000 | 24, 25, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 29, 30, QMetaType::Void, 0x80000000 | 32, 33, QMetaType::Void, 0x80000000 | 35, 36, QMetaType::Void, QMetaType::Void, QMetaType::Float, 39, 0 // eod }; void EditorBlockMeshEditor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorBlockMeshEditor *_t = static_cast<EditorBlockMeshEditor *>(_o); switch (_id) { case 0: _t->OnActionSaveMeshClicked(); break; case 1: _t->OnActionSaveMeshAsClicked(); break; case 2: _t->OnActionCloseClicked(); break; case 3: _t->OnActionEditUndoClicked(); break; case 4: _t->OnActionEditRedoClicked(); break; case 5: _t->OnActionCameraPerspectiveTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnActionCameraArcballTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnActionCameraIsometricTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnActionViewWireframeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->OnActionViewUnlitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnActionViewLitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 11: _t->OnActionViewFlagShadowsTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->OnActionViewFlagWireframeOverlayTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 13: _t->OnActionWidgetCameraTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 14: _t->OnActionWidgetSelectBlocksTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 15: _t->OnActionWidgetSelectAreaTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 16: _t->OnActionWidgetPlaceBlocksTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 17: _t->OnActionWidgetDeleteBlocksTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 18: _t->OnActionWidgetLightManipulatorTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 19: _t->OnPlaceBlockWidgetToolButtonClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 20: _t->OnPlaceBlockWidgetListWidgetItemClicked((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break; case 21: _t->OnSwapChainWidgetResized(); break; case 22: _t->OnSwapChainWidgetPaint(); break; case 23: _t->OnSwapChainWidgetKeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 24: _t->OnSwapChainWidgetMouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 25: _t->OnSwapChainWidgetWheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 26: _t->OnSwapChainWidgetGainedFocusEvent(); break; case 27: _t->OnFrameExecutionTriggered((*reinterpret_cast< float(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorBlockMeshEditor::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_EditorBlockMeshEditor.data, qt_meta_data_EditorBlockMeshEditor, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorBlockMeshEditor::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorBlockMeshEditor::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorBlockMeshEditor.stringdata)) return static_cast<void*>(const_cast< EditorBlockMeshEditor*>(this)); return QMainWindow::qt_metacast(_clname); } int EditorBlockMeshEditor::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 28) qt_static_metacall(this, _c, _id, _a); _id -= 28; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 28) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 28; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUTexture.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUTexture.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12Helpers.h" Log_SetChannel(D3D12RenderBackend); static void MapTextureFormatToViewFormat(DXGI_FORMAT *pCreationFormat, DXGI_FORMAT *pSRVFormat, DXGI_FORMAT *pRTVFormat, DXGI_FORMAT *pDSVFormat) { DXGI_FORMAT creationFormat = *pCreationFormat; // handle depth type mapping switch (creationFormat) { case DXGI_FORMAT_D16_UNORM: *pCreationFormat = DXGI_FORMAT_R16_TYPELESS; *pSRVFormat = DXGI_FORMAT_R16_UNORM; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D16_UNORM; break; case DXGI_FORMAT_D24_UNORM_S8_UINT: *pCreationFormat = DXGI_FORMAT_R24G8_TYPELESS; *pSRVFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; break; case DXGI_FORMAT_D32_FLOAT: *pCreationFormat = DXGI_FORMAT_R32_TYPELESS; *pSRVFormat = DXGI_FORMAT_R32_FLOAT; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D32_FLOAT; break; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: *pCreationFormat = DXGI_FORMAT_R32G8X24_TYPELESS; *pSRVFormat = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; break; default: *pCreationFormat = creationFormat; *pSRVFormat = creationFormat; *pRTVFormat = creationFormat; *pDSVFormat = DXGI_FORMAT_UNKNOWN; break; } } static D3D12_RESOURCE_FLAGS GetD3DResourceFlagsFromTextureFlags(uint32 textureFlags) { // get d3d resource flags D3D12_RESOURCE_FLAGS resourceFlags = D3D12_RESOURCE_FLAG_NONE; if (!(textureFlags & GPU_TEXTURE_FLAG_SHADER_BINDABLE)) resourceFlags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; if (textureFlags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; if (textureFlags & GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; if (textureFlags & GPU_TEXTURE_FLAG_BIND_COMPUTE_WRITABLE) resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; return resourceFlags; } static D3D12_RESOURCE_STATES GetD3DResourceStates(uint32 textureFlags) { // find generic state -- default to RTV/DSV only if not SRV D3D12_RESOURCE_STATES defaultResourceState = D3D12_RESOURCE_STATE_COMMON; if (textureFlags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) defaultResourceState |= D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; else if (textureFlags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) defaultResourceState |= D3D12_RESOURCE_STATE_RENDER_TARGET; else if (textureFlags & GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) defaultResourceState |= D3D12_RESOURCE_STATE_DEPTH_WRITE; return defaultResourceState; } ID3D12Resource *UploadTextureData(ID3D12Device *pD3DDevice, ID3D12GraphicsCommandList *pCommandList, ID3D12Resource *pD3DResource, const D3D12_RESOURCE_DESC *pResourceDesc, const void **ppInitialData, const uint32 *pInitialDataPitch, const uint32 *pInitialDataSlicePitch) { HRESULT hResult; DebugAssert(pResourceDesc->MipLevels > 0); // get the total number of subresource to upload uint32 subResourceCount = (pResourceDesc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) ? pResourceDesc->MipLevels : (pResourceDesc->MipLevels * pResourceDesc->DepthOrArraySize); DebugAssert(subResourceCount > 0); // get the footprints of each subresource D3D12_PLACED_SUBRESOURCE_FOOTPRINT *pSubResourceFootprints = new D3D12_PLACED_SUBRESOURCE_FOOTPRINT[subResourceCount]; UINT *pRowCounts = new UINT[subResourceCount]; UINT64 *pRowSizes = new UINT64[subResourceCount]; UINT64 intermediateSize; pD3DDevice->GetCopyableFootprints(pResourceDesc, 0, subResourceCount, 0, pSubResourceFootprints, pRowCounts, pRowSizes, &intermediateSize); // create upload buffer ID3D12Resource *pUploadResource; D3D12_HEAP_PROPERTIES uploadHeapProperties = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC uploadResourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, intermediateSize, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; hResult = pD3DDevice->CreateCommittedResource(&uploadHeapProperties, D3D12_HEAP_FLAG_NONE, &uploadResourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&pUploadResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommittedResource for upload resource failed with hResult %08X", hResult); return nullptr; } // map the upload resource byte *pMappedPointer; D3D12_RANGE readRange = { 0, 0 }; hResult = pUploadResource->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), (void **)&pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Map upload subresource for upload resource failed with hResult %08X", hResult); pUploadResource->Release(); return nullptr; } // uploading a non-3D texture? if (pResourceDesc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) { // loop through subresources for (uint32 subResourceIndex = 0; subResourceIndex < subResourceCount; subResourceIndex++) { // map this subresource uint32 rowPitch = pSubResourceFootprints[subResourceIndex].Footprint.RowPitch; DebugAssert(pRowSizes[subResourceIndex] <= rowPitch && pRowSizes[subResourceIndex] <= pInitialDataPitch[subResourceIndex]); // copy in data. this could result in a buffer overflow, except for the fact that we're only copying as much data as we can, // so if the gpu is aligning each row, we won't copy past the actual data if (rowPitch == pInitialDataPitch[subResourceIndex]) Y_memcpy(pMappedPointer + (size_t)pSubResourceFootprints[subResourceIndex].Offset, ppInitialData[subResourceIndex], rowPitch * pRowCounts[subResourceIndex]); else Y_memcpy_stride(pMappedPointer + (size_t)pSubResourceFootprints[subResourceIndex].Offset, rowPitch, ppInitialData[subResourceIndex], pInitialDataPitch[subResourceIndex], (size_t)pRowSizes[subResourceIndex], pRowCounts[subResourceIndex]); // invoke a copy of this subresource D3D12_TEXTURE_COPY_LOCATION sourceCopyLocation = { pUploadResource, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, pSubResourceFootprints[subResourceIndex] }; D3D12_TEXTURE_COPY_LOCATION destCopyLocation = { pD3DResource, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, subResourceIndex }; pCommandList->CopyTextureRegion(&destCopyLocation, 0, 0, 0, &sourceCopyLocation, nullptr); } } else { // upload process for 3D Texture is different. for (uint32 mipLevel = 0; mipLevel < subResourceCount; mipLevel++) { // map this subresource uint32 inRowPitch = pInitialDataPitch[mipLevel]; uint32 outRowPitch = pSubResourceFootprints[mipLevel].Footprint.RowPitch; uint32 rowSize = Min(pInitialDataPitch[mipLevel], (uint32)pRowSizes[mipLevel]); DebugAssert(pRowSizes[mipLevel] <= outRowPitch && pRowSizes[mipLevel] <= pInitialDataPitch[mipLevel]); DebugAssert(pInitialDataSlicePitch[mipLevel] <= pSubResourceFootprints[mipLevel].Footprint.RowPitch * pRowCounts[mipLevel]); // copy each slice individually const byte *pInPointer = (const byte *)ppInitialData[mipLevel]; byte *pOutPointer = pMappedPointer + (size_t)pSubResourceFootprints[mipLevel].Offset; for (uint32 z = 0; z < pResourceDesc->DepthOrArraySize; z++) { if (inRowPitch == outRowPitch) Y_memcpy(pOutPointer, pInPointer, inRowPitch * pRowCounts[mipLevel]); else Y_memcpy_stride(pOutPointer, outRowPitch, pInPointer, inRowPitch, rowSize, pRowCounts[mipLevel]); pInPointer += inRowPitch; pOutPointer += outRowPitch; } // copy the subresource D3D12_TEXTURE_COPY_LOCATION sourceCopyLocation = { pUploadResource, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, pSubResourceFootprints[mipLevel] }; D3D12_TEXTURE_COPY_LOCATION destCopyLocation = { pD3DResource, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, mipLevel }; pCommandList->CopyTextureRegion(&destCopyLocation, 0, 0, 0, &sourceCopyLocation, nullptr); } } // release the mapping - wrote the whole range D3D12_RANGE writeRange = { 0, (size_t)intermediateSize }; pUploadResource->Unmap(0, D3D12_MAP_RANGE_PARAM(&writeRange)); // free memory delete[] pRowSizes; delete[] pRowCounts; delete[] pSubResourceFootprints; return pUploadResource; } GPUTexture1D *D3D12GPUDevice::CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) { return false; } bool D3D12GPUContext::WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) { return false; } GPUTexture1DArray *D3D12GPUDevice::CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { return false; } bool D3D12GPUContext::WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { return false; } D3D12GPUTexture2D::D3D12GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, const D3D12DescriptorHandle &srvHandle, const D3D12DescriptorHandle &samplerHandle, D3D12_RESOURCE_STATES defaultResourceState) : GPUTexture2D(pDesc) , m_pDevice(pDevice) , m_pD3DResource(pD3DResource) , m_srvHandle(srvHandle) , m_samplerHandle(samplerHandle) , m_defaultResourceState(defaultResourceState) { m_pDevice->AddRef(); } D3D12GPUTexture2D::~D3D12GPUTexture2D() { if (!m_samplerHandle.IsNull()) m_pDevice->ScheduleDescriptorForDeletion(m_samplerHandle); if (!m_srvHandle.IsNull()) m_pDevice->ScheduleDescriptorForDeletion(m_srvHandle); m_pDevice->ScheduleResourceForDeletion(m_pD3DResource); m_pDevice->Release(); } void D3D12GPUTexture2D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage; } } void D3D12GPUTexture2D::SetDebugName(const char *name) { D3D12Helpers::SetD3D12ObjectName(m_pD3DResource, name); } GPUTexture2D *D3D12GPUDevice::CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // get d3d resource flags D3D12_RESOURCE_FLAGS resourceFlags = GetD3DResourceFlagsFromTextureFlags(pTextureDesc->Flags); D3D12_RESOURCE_STATES defaultResourceState = GetD3DResourceStates(pTextureDesc->Flags); // find the initial state D3D12_RESOURCE_STATES initialResourceState = (ppInitialData != nullptr) ? D3D12_RESOURCE_STATE_COPY_DEST : defaultResourceState; // clear value D3D12_CLEAR_VALUE optimizedClearValue; D3D12_CLEAR_VALUE *pOptimizedClearValue; if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) && D3D12Helpers::GetOptimizedClearValue(pTextureDesc->Format, &optimizedClearValue)) pOptimizedClearValue = &optimizedClearValue; else pOptimizedClearValue = nullptr; // create the texture resource ID3D12Resource *pD3DResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, pTextureDesc->Width, pTextureDesc->Height, 1, (UINT16)pTextureDesc->MipLevels, creationFormat, { 1, 0 }, D3D12_TEXTURE_LAYOUT_UNKNOWN, resourceFlags }; hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, initialResourceState, pOptimizedClearValue, IID_PPV_ARGS(&pD3DResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommittedResource failed with hResult %08X", hResult); return false; } // create SRV D3D12DescriptorHandle srvHandle; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { // allocate a descriptor if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Allocate(&srvHandle)) { pD3DResource->Release(); return false; } // fill the descriptor D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = pTextureDesc->MipLevels; srvDesc.Texture2D.PlaneSlice = 0; srvDesc.Texture2D.ResourceMinLODClamp = 0; m_pD3DDevice->CreateShaderResourceView(pD3DResource, &srvDesc, srvHandle); } // create sampler state D3D12DescriptorHandle samplerHandle; if (pSamplerStateDesc != nullptr) { // fill the descriptor D3D12_SAMPLER_DESC samplerDesc; if (!D3D12Helpers::FillD3D12SamplerStateDesc(pSamplerStateDesc, &samplerDesc)) { Log_ErrorPrintf("Failed to convert sampler state description."); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); pD3DResource->Release(); return false; } // allocate a descriptor if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)->Allocate(&samplerHandle)) { Log_ErrorPrintf("Failed to allocator sampler descriptor."); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); pD3DResource->Release(); return false; } // fill the descriptor @TODO use a pool here, since we'll have duplicates for sure.. also 2048 sampler per heap limit.. m_pD3DDevice->CreateSampler(&samplerDesc, samplerHandle); } // create the upload resource, and do the upload if (ppInitialData != nullptr) { // we need to batch the uploads, even on the render thread BeginResourceBatchUpload(); // upload the texture ID3D12Resource *pUploadResource = UploadTextureData(m_pD3DDevice, GetCurrentCopyCommandList(), pD3DResource, &resourceDesc, ppInitialData, pInitialDataPitch, nullptr); if (pUploadResource == nullptr) { Log_ErrorPrintf("Failed to upload texture data", hResult); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)->Free(samplerHandle); pD3DResource->Release(); return false; } // transition to its real resource state ResourceBarrier(pD3DResource, D3D12_RESOURCE_STATE_COPY_DEST, defaultResourceState); // done with the upload, and free the buffer ScheduleCopyResourceForDeletion(pUploadResource); EndResourceBatchUpload(); } // create class return new D3D12GPUTexture2D(pTextureDesc, this, pD3DResource, srvHandle, samplerHandle, defaultResourceState); } bool D3D12GPUContext::ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { // don't support block compression reads atm D3D12GPUTexture2D *pWrappedTexture = static_cast<D3D12GPUTexture2D *>(pTexture); DXGI_FORMAT textureDXGIFormat = D3D12Helpers::PixelFormatToDXGIFormat(pWrappedTexture->GetDesc()->Format); if (!PixelFormat_GetPixelFormatInfo(pTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get the state we need to restore to D3D12_RESOURCE_STATES returnResourceState = GetCurrentResourceState(pTexture); // fill descriptor information with the size we want to capture D3D12_RESOURCE_DESC regionDesc = { D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, countX, countY, 1, 1, textureDXGIFormat, { 1, 0 }, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE }; D3D12_PLACED_SUBRESOURCE_FOOTPRINT regionTextureFootprint; uint64 regionTextureRowSize; uint32 regionTextureRowCount; uint64 regionTextureSize; m_pD3DDevice->GetCopyableFootprints(&regionDesc, 0, 1, 0, &regionTextureFootprint, &regionTextureRowCount, &regionTextureRowSize, &regionTextureSize); // allocate a readback texture, with a descriptor matching the texture we're reading from D3D12_HEAP_PROPERTIES readbackHeapProperties = { D3D12_HEAP_TYPE_READBACK, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 1, 1 }; D3D12_RESOURCE_DESC readbackTextureDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, regionTextureSize, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; ID3D12Resource *pReadbackResource; HRESULT hResult = m_pD3DDevice->CreateCommittedResource(&readbackHeapProperties, D3D12_HEAP_FLAG_NONE, &readbackTextureDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pReadbackResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommittedResource failed with HRESULT %08X", hResult); return false; } // have to have a barrier here ResourceBarrier(pWrappedTexture->GetD3DResource(), returnResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); // issue the copy to our readback resource D3D12_TEXTURE_COPY_LOCATION copySource = { pWrappedTexture->GetD3DResource(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, mipIndex }; D3D12_TEXTURE_COPY_LOCATION copyDestination = { pReadbackResource, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, regionTextureFootprint }; D3D12_BOX copySourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pCommandList->CopyTextureRegion(&copyDestination, 0, 0, 0, &copySource, &copySourceBox); m_commandCounter++; // have to have a barrier here ResourceBarrier(pWrappedTexture->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_SOURCE, returnResourceState); // flush the queue, and wait for all operations to finish CloseAndExecuteCommandList(true, false); ResetCommandList(true, false); // map the readback texture void *pMappedPointer; hResult = pReadbackResource->Map(0, nullptr, &pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Map failed with HRESULT %08X", hResult); return false; } // copy from readback resource to the user-provided buffer DebugAssert(cbDestination >= destinationRowPitch * regionTextureRowCount); if (destinationRowPitch == regionTextureFootprint.Footprint.RowPitch) Y_memcpy(pDestination, pMappedPointer, (size_t)regionTextureRowSize * regionTextureRowCount); else Y_memcpy_stride(pDestination, destinationRowPitch, pMappedPointer, regionTextureFootprint.Footprint.RowPitch, Min((uint32)regionTextureRowSize, destinationRowPitch), regionTextureRowCount); // release readback resource pReadbackResource->Unmap(0, nullptr); pReadbackResource->Release(); return true; } bool D3D12GPUContext::WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } D3D12GPUTexture2DArray::D3D12GPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, const D3D12DescriptorHandle &srvHandle, const D3D12DescriptorHandle &samplerHandle, D3D12_RESOURCE_STATES defaultResourceState) : GPUTexture2DArray(pDesc) , m_pDevice(pDevice) , m_pD3DResource(pD3DResource) , m_srvHandle(srvHandle) , m_samplerHandle(samplerHandle) , m_defaultResourceState(defaultResourceState) { pDevice->AddRef(); } D3D12GPUTexture2DArray::~D3D12GPUTexture2DArray() { if (!m_samplerHandle.IsNull()) m_pDevice->ScheduleDescriptorForDeletion(m_samplerHandle); if (!m_srvHandle.IsNull()) m_pDevice->ScheduleDescriptorForDeletion(m_srvHandle); m_pDevice->ScheduleResourceForDeletion(m_pD3DResource); m_pDevice->Release(); } void D3D12GPUTexture2DArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage; } } void D3D12GPUTexture2DArray::SetDebugName(const char *name) { D3D12Helpers::SetD3D12ObjectName(m_pD3DResource, name); } GPUTexture2DArray *D3D12GPUDevice::CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->ArraySize > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // get d3d resource flags D3D12_RESOURCE_FLAGS resourceFlags = GetD3DResourceFlagsFromTextureFlags(pTextureDesc->Flags); D3D12_RESOURCE_STATES defaultResourceState = GetD3DResourceStates(pTextureDesc->Flags); // find the initial state D3D12_RESOURCE_STATES initialResourceState = (ppInitialData != nullptr) ? D3D12_RESOURCE_STATE_COPY_DEST : defaultResourceState; // clear value D3D12_CLEAR_VALUE optimizedClearValue; D3D12_CLEAR_VALUE *pOptimizedClearValue; if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) && D3D12Helpers::GetOptimizedClearValue(pTextureDesc->Format, &optimizedClearValue)) pOptimizedClearValue = &optimizedClearValue; else pOptimizedClearValue = nullptr; // create the texture resource ID3D12Resource *pD3DResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, pTextureDesc->Width, pTextureDesc->Height, (UINT16)pTextureDesc->ArraySize, (UINT16)pTextureDesc->MipLevels, creationFormat, { 1, 0 }, D3D12_TEXTURE_LAYOUT_UNKNOWN, resourceFlags }; hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, initialResourceState, pOptimizedClearValue, IID_PPV_ARGS(&pD3DResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommittedResource failed with hResult %08X", hResult); return false; } // create SRV D3D12DescriptorHandle srvHandle; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { // allocate a descriptor if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Allocate(&srvHandle)) { pD3DResource->Release(); return false; } // fill the descriptor D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Texture2DArray.MostDetailedMip = 0; srvDesc.Texture2DArray.MipLevels = pTextureDesc->MipLevels; srvDesc.Texture2DArray.FirstArraySlice = 0; srvDesc.Texture2DArray.ArraySize = pTextureDesc->ArraySize; srvDesc.Texture2DArray.PlaneSlice = 0; srvDesc.Texture2DArray.ResourceMinLODClamp = 0; m_pD3DDevice->CreateShaderResourceView(pD3DResource, &srvDesc, srvHandle); } // create sampler state D3D12DescriptorHandle samplerHandle; if (pSamplerStateDesc != nullptr) { // fill the descriptor D3D12_SAMPLER_DESC samplerDesc; if (!D3D12Helpers::FillD3D12SamplerStateDesc(pSamplerStateDesc, &samplerDesc)) { Log_ErrorPrintf("Failed to convert sampler state description."); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); pD3DResource->Release(); return false; } // allocate a descriptor if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)->Allocate(&samplerHandle)) { Log_ErrorPrintf("Failed to allocator sampler descriptor."); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); pD3DResource->Release(); return false; } // fill the descriptor @TODO use a pool here, since we'll have duplicates for sure.. also 2048 sampler per heap limit.. m_pD3DDevice->CreateSampler(&samplerDesc, samplerHandle); } // create the upload resource, and do the upload if (ppInitialData != nullptr) { // we need to batch the uploads, even on the render thread BeginResourceBatchUpload(); // upload the texture ID3D12Resource *pUploadResource = UploadTextureData(m_pD3DDevice, GetCurrentCopyCommandList(), pD3DResource, &resourceDesc, ppInitialData, pInitialDataPitch, nullptr); if (pUploadResource == nullptr) { Log_ErrorPrintf("Failed to upload texture data", hResult); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(srvHandle); GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)->Free(samplerHandle); pD3DResource->Release(); return false; } // transition to its real resource state ResourceBarrier(pD3DResource, D3D12_RESOURCE_STATE_COPY_DEST, defaultResourceState); // done with the upload, and free the buffer ScheduleCopyResourceForDeletion(pUploadResource); EndResourceBatchUpload(); } // create class return new D3D12GPUTexture2DArray(pTextureDesc, this, pD3DResource, srvHandle, samplerHandle, defaultResourceState); } bool D3D12GPUContext::ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } bool D3D12GPUContext::WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } GPUTexture3D *D3D12GPUDevice::CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/, const uint32 *pInitialDataSlicePitch /*= nullptr*/) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { return false; } bool D3D12GPUContext::WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { return false; } GPUTextureCube *D3D12GPUDevice::CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } bool D3D12GPUContext::WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } GPUTextureCubeArray *D3D12GPUDevice::CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= nullptr*/, const uint32 *pInitialDataPitch /*= nullptr*/) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } bool D3D12GPUContext::WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } GPUDepthTexture *D3D12GPUDevice::CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) { return nullptr; } bool D3D12GPUContext::ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } bool D3D12GPUContext::WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { return false; } D3D12GPURenderTargetView::D3D12GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource) : GPURenderTargetView(pTexture, pDesc) , m_pDevice(pDevice) , m_descriptorHandle(descriptorHandle) , m_pD3DResource(pD3DResource) { m_pDevice->AddRef(); } D3D12GPURenderTargetView::~D3D12GPURenderTargetView() { m_pDevice->ScheduleDescriptorForDeletion(m_descriptorHandle); m_pDevice->Release(); } void D3D12GPURenderTargetView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D12GPURenderTargetView::SetDebugName(const char *name) { //D3D12Helpers::SetD3D12DeviceChildDebugName(m_pD3DRTV, name); } GPURenderTargetView *D3D12GPUDevice::CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // we need to convert to d3d formats ID3D12Resource *pD3DResource; DXGI_FORMAT creationFormat, srvFormat, rtvFormat, dsvFormat; // fill in DSV structure D3D12_RENDER_TARGET_VIEW_DESC rtvDesc; switch (pTexture->GetResourceType()) { #if 0 case GPU_RESOURCE_TYPE_TEXTURE1D: pD3DResource = static_cast<D3D12GPUTexture1D *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture1D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; rtvDesc.Texture1D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: pD3DResource = static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; rtvDesc.Texture1DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture1DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture1DArray.ArraySize = pDesc->NumLayers; break; #endif case GPU_RESOURCE_TYPE_TEXTURE2D: pD3DResource = static_cast<D3D12GPUTexture2D *>(pTexture)->GetD3DResource(); creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = pDesc->MipLevel; rtvDesc.Texture2D.PlaneSlice = 0; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: pD3DResource = static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetD3DResource(); creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; rtvDesc.Texture2DArray.PlaneSlice = 0; break; #if 0 case GPU_RESOURCE_TYPE_TEXTURECUBE: pD3DResource = static_cast<D3D12GPUTextureCube *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTextureCube *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; rtvDesc.Texture2DArray.PlaneSlice = 0; break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: pD3DResource = static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; rtvDesc.Texture2DArray.PlaneSlice = 0; break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: //pD3DResource = static_cast<D3D12GPUDepthTexture *>(pTexture)->GetD3DTexture(); //creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUDepthTexture *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; rtvDesc.Texture2D.PlaneSlice = 0; break; #endif default: Log_ErrorPrintf("D3D12GPUDevice::CreateRenderTargetView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } // allocate handle D3D12DescriptorHandle handle; if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->Allocate(&handle)) { Log_ErrorPrintf("D3D12GPUDevice::CreateRenderTargetView: Failed to allocate descriptor."); return nullptr; } // create RTV m_pD3DDevice->CreateRenderTargetView(pD3DResource, &rtvDesc, handle); return new D3D12GPURenderTargetView(pTexture, pDesc, this, handle, pD3DResource); } D3D12GPUDepthStencilBufferView::D3D12GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource) : GPUDepthStencilBufferView(pTexture, pDesc) , m_pDevice(pDevice) , m_descriptorHandle(descriptorHandle) , m_pD3DResource(pD3DResource) { m_pDevice->AddRef(); } D3D12GPUDepthStencilBufferView::~D3D12GPUDepthStencilBufferView() { m_pDevice->ScheduleDescriptorForDeletion(m_descriptorHandle); m_pDevice->Release(); } void D3D12GPUDepthStencilBufferView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D12GPUDepthStencilBufferView::SetDebugName(const char *name) { //D3D12Helpers::SetD3D12DeviceChildDebugName(m_pD3DDSV, name); } GPUDepthStencilBufferView *D3D12GPUDevice::CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // we need to convert to d3d formats ID3D12Resource *pD3DResource; DXGI_FORMAT creationFormat, srvFormat, rtvFormat, dsvFormat; // fill in DSV structure D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc; switch (pTexture->GetResourceType()) { #if 0 case GPU_RESOURCE_TYPE_TEXTURE1D: pD3DResource = static_cast<D3D12GPUTexture1D *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture1D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D; dsvDesc.Flags = 0; dsvDesc.Texture1D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: pD3DResource = static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture1DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture1DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture1DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture1DArray.ArraySize = pDesc->NumLayers; break; #endif case GPU_RESOURCE_TYPE_TEXTURE2D: pD3DResource = static_cast<D3D12GPUTexture2D *>(pTexture)->GetD3DResource(); creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.Texture2D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: pD3DResource = static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetD3DResource(); creationFormat = D3D12Helpers::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; #if 0 case GPU_RESOURCE_TYPE_TEXTURECUBE: pD3DResource = static_cast<D3D12GPUTextureCube *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTextureCube *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: pD3DResource = static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTextureCubeArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: pD3DResource = static_cast<D3D12GPUDepthTexture *>(pTexture)->GetD3DTexture(); creationFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUDepthTexture *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = 0; dsvDesc.Texture2D.MipSlice = 0; break; #endif default: Log_ErrorPrintf("D3D12GPUDevice::CreateDepthBufferView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } // allocate handle D3D12DescriptorHandle handle; if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)->Allocate(&handle)) { Log_ErrorPrintf("D3D12GPUDevice::CreateRenderTargetView: Failed to allocate descriptor."); return nullptr; } // create RTV m_pD3DDevice->CreateDepthStencilView(pD3DResource, &dsvDesc, handle); return new D3D12GPUDepthStencilBufferView(pTexture, pDesc, this, handle, pD3DResource); } D3D12GPUComputeView::D3D12GPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource) : GPUComputeView(pResource, pDesc) , m_pDevice(pDevice) , m_descriptorHandle(descriptorHandle) , m_pD3DResource(pD3DResource) { m_pDevice->AddRef(); } D3D12GPUComputeView::~D3D12GPUComputeView() { m_pDevice->ScheduleDescriptorForDeletion(m_descriptorHandle); m_pDevice->Release(); } void D3D12GPUComputeView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D12GPUComputeView::SetDebugName(const char *name) { //D3D12Helpers::SetD3D12DeviceChildDebugName(m_pD3DUAV, name); } GPUComputeView *D3D12GPUDevice::CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { Panic("Unimplemented"); return nullptr; } <file_sep>/Engine/Source/Renderer/MiniGUIContext.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/MiniGUIContext.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Engine/Camera.h" #include "Engine/Font.h" #include "Engine/Texture.h" Log_SetChannel(MiniGUIContext); const MINIGUI_UV_RECT MINIGUI_UV_RECT::FULL_RECT = { 0.0f, 1.0f, 0.0f, 1.0f }; // todo: investigate using strips instead and degenerates inbetween //#define MINIGUI_TRACING 1 #ifdef MINIGUI_TRACING #define MiniGUIContext_Log_TracePrint(x) Log_TracePrint(x) #define MiniGUIContext_Log_TracePrintf(x, ...) Log_TracePrintf(x, __VA_ARGS__) #else #define MiniGUIContext_Log_TracePrint(x) #define MiniGUIContext_Log_TracePrintf(x, ...) #endif MiniGUIContext::MiniGUIContext(GPUContext *pGPUContext /* = nullptr */, uint32 viewportWidth /* = 1 */, uint32 viewportHeight /* = 1 */) : m_pGPUContext(pGPUContext), m_viewportWidth(viewportWidth), m_viewportHeight(viewportHeight), m_depthTestingEnabled(false), m_alphaBlendingMode(ALPHABLENDING_MODE_NONE), m_manualFlushCount(0), m_immediatePrimitive(IMMEDIATE_PRIMITIVE_COUNT), m_immediateStartVertex(0), m_textCaretPositionX(0), m_textCaretPositionY(0), m_textHorizontalAlign(MINIGUI_HORIZONTAL_ALIGNMENT_LEFT), m_textVerticalAlign(MINIGUI_VERTICAL_ALIGNMENT_TOP), m_textWordWrap(false), m_batchType(BATCH_TYPE_NONE), m_pBatchTexture(nullptr) { SET_MINIGUI_RECT(&m_topRect, 0, viewportWidth, 0, viewportHeight); } MiniGUIContext::~MiniGUIContext() { ClearState(); DebugAssert(m_rectStack.GetSize() == 0); DebugAssert(m_pBatchTexture == nullptr); } void MiniGUIContext::SetViewportDimensions(uint32 width, uint32 height) { // rect stack should be empty before changing RT DebugAssert(m_rectStack.GetSize() == 0); // clear quuee if (m_batchType != BATCH_TYPE_NONE) Flush(); if (m_viewportWidth != width || m_viewportHeight != height) { // update vars m_viewportWidth = width; m_viewportHeight = height; } // fix rects SET_MINIGUI_RECT(&m_topRect, 0, width, 0, height); } void MiniGUIContext::SetViewportDimensions(const RENDERER_VIEWPORT *pViewport) { SetViewportDimensions(pViewport->Width, pViewport->Height); } void MiniGUIContext::SetDepthTestingEnabled(bool enabled) { if (enabled == m_depthTestingEnabled) return; Flush(); m_depthTestingEnabled = enabled; } void MiniGUIContext::SetAlphaBlendingEnabled(bool enabled) { SetAlphaBlendingMode((enabled) ? ALPHABLENDING_MODE_STRAIGHT : ALPHABLENDING_MODE_NONE); } void MiniGUIContext::SetAlphaBlendingMode(ALPHABLENDING_MODE mode) { DebugAssert(mode < ALPHABLENDING_MODE_COUNT); if (m_alphaBlendingMode == mode) return; Flush(); m_alphaBlendingMode = mode; } void MiniGUIContext::PushManualFlush() { m_manualFlushCount++; } void MiniGUIContext::PopManualFlush() { DebugAssert(m_manualFlushCount > 0); m_manualFlushCount--; if (m_manualFlushCount == 0) Flush(); } void MiniGUIContext::ClearState() { DebugAssert(m_manualFlushCount == 0); m_depthTestingEnabled = false; m_alphaBlendingMode = ALPHABLENDING_MODE_NONE; SET_MINIGUI_RECT(&m_topRect, 0, m_viewportWidth, 0, m_viewportHeight); m_batchType = BATCH_TYPE_NONE; SAFE_RELEASE(m_pBatchTexture); m_batchVertices2D.Clear(); m_batchVertices3D.Clear(); } void MiniGUIContext::PushRect(const MINIGUI_RECT *pRect) { MINIGUI_RECT translatedRect; TranslateRect(&translatedRect, pRect); m_rectStack.Add(translatedRect); Y_memcpy(&m_topRect, &translatedRect, sizeof(m_topRect)); MiniGUIContext_Log_TracePrintf("MiniGUIContext::PushRect(%i, %i, %i, %i)", pRect->left, pRect->right, pRect->top, pRect->bottom); } void MiniGUIContext::PopRect() { DebugAssert(m_rectStack.GetSize() > 0); m_rectStack.RemoveBack(); if (m_rectStack.GetSize() > 0) Y_memcpy(&m_topRect, &m_rectStack[m_rectStack.GetSize() - 1], sizeof(m_topRect)); else SET_MINIGUI_RECT(&m_topRect, 0, m_viewportWidth, 0, m_viewportHeight); MiniGUIContext_Log_TracePrint("MiniGUIContext::PopRect()"); } bool MiniGUIContext::ValidateRect(const MINIGUI_RECT *pRect) { if (pRect->left > pRect->right || pRect->top > pRect->bottom) { //Log_WarningPrintf("MiniGUIContext: RECT FAILED VALIDATION: left=%i right=%i top=%i bottom=%i", pRect->left, pRect->right, pRect->top, pRect->bottom); MiniGUIContext_Log_TracePrintf("MiniGUIContext: RECT FAILED VALIDATION: left=%i right=%i top=%i bottom=%i", pRect->left, pRect->right, pRect->top, pRect->bottom); return false; } return true; } void MiniGUIContext::TranslateRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect) { if (m_rectStack.GetSize() > 0) { pDestinationRect->left = pSourceRect->left + m_topRect.left; pDestinationRect->right = pSourceRect->right + m_topRect.left; pDestinationRect->top = pSourceRect->top + m_topRect.top; pDestinationRect->bottom = pSourceRect->bottom + m_topRect.top; } else if (pSourceRect != pDestinationRect) { pDestinationRect->left = pSourceRect->left; pDestinationRect->right = pSourceRect->right; pDestinationRect->top = pSourceRect->top; pDestinationRect->bottom = pSourceRect->bottom; } } void MiniGUIContext::UntranslateRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect) { if (m_rectStack.GetSize() > 0) { pDestinationRect->left = pSourceRect->left - m_topRect.left; pDestinationRect->right = pSourceRect->right - m_topRect.left; pDestinationRect->top = pSourceRect->top - m_topRect.top; pDestinationRect->bottom = pSourceRect->bottom - m_topRect.top; } else if (pSourceRect != pDestinationRect) { pDestinationRect->left = pSourceRect->left; pDestinationRect->right = pSourceRect->right; pDestinationRect->top = pSourceRect->top; pDestinationRect->bottom = pSourceRect->bottom; } } void MiniGUIContext::ClipRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect) { if (m_rectStack.GetSize() > 0) { pDestinationRect->left = Max(pSourceRect->left, m_topRect.left); pDestinationRect->right = Min(pSourceRect->right, m_topRect.right); pDestinationRect->top = Max(pSourceRect->top, m_topRect.top); pDestinationRect->bottom = Min(pSourceRect->bottom, m_topRect.bottom); } else if (pDestinationRect != pSourceRect) { pDestinationRect->left = pSourceRect->left; pDestinationRect->right = pSourceRect->right; pDestinationRect->top = pSourceRect->top; pDestinationRect->bottom = pSourceRect->bottom; } } void MiniGUIContext::TranslateAndClipRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect) { MINIGUI_RECT tempRect; TranslateRect(&tempRect, pSourceRect); ClipRect(pDestinationRect, &tempRect); } void MiniGUIContext::ClipUVRect(MINIGUI_UV_RECT *pDestinationUVRect, const MINIGUI_UV_RECT *pSourceUVRect, const MINIGUI_RECT *pClippedRect, const MINIGUI_RECT *pOriginalRect) { int32 totalWidth = pOriginalRect->right - pOriginalRect->left; int32 totalHeight = pOriginalRect->bottom - pOriginalRect->top; float fTotalWidth = (float)totalWidth; float fTotalHeight = (float)totalHeight; float fUVWidth = pSourceUVRect->right - pSourceUVRect->left; float fUVHeight = pSourceUVRect->bottom - pSourceUVRect->top; float f; // left clipped? if (pClippedRect->left > pOriginalRect->left) { f = (float)(pClippedRect->left - pOriginalRect->left) / fTotalWidth; pDestinationUVRect->left = pSourceUVRect->left + fUVWidth * f; } else { pDestinationUVRect->left = pSourceUVRect->left; } // top clipped? if (pClippedRect->top > pOriginalRect->top) { f = (float)(pClippedRect->top - pOriginalRect->top) / fTotalHeight; pDestinationUVRect->top = pSourceUVRect->top + fUVHeight * f; } else { pDestinationUVRect->top = pSourceUVRect->top; } // right clipped? if (pClippedRect->right > pOriginalRect->right) { f = (float)(pClippedRect->right - pOriginalRect->right) / fTotalWidth; pDestinationUVRect->right = pSourceUVRect->right + fUVWidth * f; } else { pDestinationUVRect->right = pSourceUVRect->right; } // bottom clipped? if (pClippedRect->bottom > pOriginalRect->bottom) { f = (float)(pClippedRect->bottom - pOriginalRect->bottom) / fTotalHeight; pDestinationUVRect->bottom = pSourceUVRect->bottom + fUVHeight * f; } else { pDestinationUVRect->bottom = pSourceUVRect->bottom; } } int2 MiniGUIContext::TranslateAndClipPoint(const int2 &Point) { int2 ret = Point; // if (m_rectStack.GetSize() > 0) // { // ret.x += m_topRect.left; // ret.y += m_topRect.top; // } if (m_rectStack.GetSize() > 0) { ret.x = Max(Min(m_topRect.left + Point.x, m_topRect.right), m_topRect.left); ret.y = Max(Min(m_topRect.top + Point.y, m_topRect.bottom), m_topRect.top); } return ret; } void MiniGUIContext::InternalDrawText(const Font *pFontData, float scale, uint32 color, const MINIGUI_RECT *pRect, const char *text, uint32 nCharacters, bool skipFlushCheck) { if (!ValidateRect(pRect)) return; // last bound texture int32 lastTextureIndex = -1; // is it one of ours? if (m_batchType == BATCH_TYPE_2D_TEXT) { for (uint32 i = 0; i < pFontData->GetTextureCount(); i++) { if (pFontData->GetTexture(i)->GetGPUTexture() == m_pBatchTexture) { lastTextureIndex = (uint32)i; break; } } } // current pos int32 curX = pRect->left; int32 curY = pRect->top; // premultiply the alpha in color if ((color >> 24) != 0xFF) { float fraction = static_cast<float>(color >> 24) / 255.0f; color = (color & 0xFF000000) | static_cast<uint32>(static_cast<float>(color & 0xFF) / 255.0f * fraction * 255.0f) | static_cast<uint32>(static_cast<float>((color >> 8) & 0xFF) / 255.0f * fraction * 255.0f) << 8 | static_cast<uint32>(static_cast<float>((color >> 16) & 0xFF) / 255.0f * fraction * 255.0f) << 16; } // prep vertex fields that the font function doesn't fill in OverlayShader::Vertex2D Vertices[6]; for (uint32 i = 0; i < countof(Vertices); i++) Vertices[i].Set(float2::Zero, float2::Zero, color); // generate vertices for (uint32 i = 0; i < nCharacters; i++) { char ch = text[i]; // some that we skip if (ch == '\r' || ch == '\n' || ch == '\t') continue; // get char info const Font::CharacterData *pCharacterData = pFontData->GetCharacterDataForCodePoint(ch); if (pCharacterData == NULL) continue; // generate vertex for it if (pFontData->GetVertex<OverlayShader::Vertex2D>(pCharacterData, curX, curY, scale, pRect->right, pRect->bottom, Vertices)) { if ((int32)pCharacterData->TextureIndex != lastTextureIndex) { Flush(); // get texture ptr GPUTexture2D *pGPUTexture = static_cast<GPUTexture2D *>(pFontData->GetTexture(pCharacterData->TextureIndex)->GetGPUTexture()); if (pGPUTexture != NULL) { // setup batch m_batchType = BATCH_TYPE_2D_TEXT; m_pBatchTexture = pGPUTexture; m_pBatchTexture->AddRef(); // set last texture lastTextureIndex = pCharacterData->TextureIndex; // add vertices AddVertices(Vertices, countof(Vertices)); } } else { // add vertices AddVertices(Vertices, countof(Vertices)); } } } if (!m_manualFlushCount && !skipFlushCheck) Flush(); } void MiniGUIContext::SetBatchType(BATCH_TYPE type) { if (m_batchType != type && m_batchType != BATCH_TYPE_NONE) Flush(); m_batchType = type; } void MiniGUIContext::Flush() { Renderer::FixedResources *pStateManager = g_pRenderer->GetFixedResources(); if (m_batchType == BATCH_TYPE_NONE) return; // rasterizer state m_pGPUContext->SetRasterizerState(pStateManager->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE)); // depth state -- we never test depth for 2d drawing if (m_batchType >= BATCH_TYPE_3D_COLORED_LINES) m_pGPUContext->SetDepthStencilState(pStateManager->GetDepthStencilState(m_depthTestingEnabled, false, GPU_COMPARISON_FUNC_LESS_EQUAL), 0); else m_pGPUContext->SetDepthStencilState(pStateManager->GetDepthStencilState(false, false, GPU_COMPARISON_FUNC_LESS_EQUAL), 0); // alphablending state if (m_batchType == BATCH_TYPE_2D_TEXT || m_batchType == BATCH_TYPE_3D_TEXT) { // force premultipled alpha for text m_pGPUContext->SetBlendState(pStateManager->GetBlendStatePremultipliedAlpha()); } else { // use saved mode switch (m_alphaBlendingMode) { case ALPHABLENDING_MODE_NONE: m_pGPUContext->SetBlendState(pStateManager->GetBlendStateNoBlending()); break; case ALPHABLENDING_MODE_STRAIGHT: m_pGPUContext->SetBlendState(pStateManager->GetBlendStateAlphaBlending()); break; case ALPHABLENDING_MODE_PREMULTIPLIED: m_pGPUContext->SetBlendState(pStateManager->GetBlendStatePremultipliedAlpha()); break; default: UnreachableCode(); break; } } // select shader switch (m_batchType) { case BATCH_TYPE_2D_COLORED_LINES: case BATCH_TYPE_2D_COLORED_TRIANGLES: m_pGPUContext->SetShaderProgram(pStateManager->GetOverlayShaderColoredScreen()->GetGPUProgram()); break; case BATCH_TYPE_2D_TEXTURED_TRIANGLES: case BATCH_TYPE_2D_TEXT: m_pGPUContext->SetShaderProgram(pStateManager->GetOverlayShaderTexturedScreen()->GetGPUProgram()); OverlayShader::SetTexture(m_pGPUContext, pStateManager->GetOverlayShaderTexturedScreen(), m_pBatchTexture); break; case BATCH_TYPE_3D_COLORED_LINES: case BATCH_TYPE_3D_COLORED_TRIANGLES: m_pGPUContext->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); m_pGPUContext->SetShaderProgram(pStateManager->GetOverlayShaderColoredWorld()->GetGPUProgram()); break; case BATCH_TYPE_3D_TEXTURED_TRIANGLES: case BATCH_TYPE_3D_TEXT: m_pGPUContext->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); m_pGPUContext->SetShaderProgram(pStateManager->GetOverlayShaderTexturedWorld()->GetGPUProgram()); OverlayShader::SetTexture(m_pGPUContext, pStateManager->GetOverlayShaderTexturedWorld(), m_pBatchTexture); break; default: UnreachableCode(); break; } // set topology switch (m_batchType) { case BATCH_TYPE_2D_COLORED_LINES: case BATCH_TYPE_3D_COLORED_LINES: m_pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_LINE_LIST); break; case BATCH_TYPE_2D_COLORED_TRIANGLES: case BATCH_TYPE_2D_TEXTURED_TRIANGLES: case BATCH_TYPE_2D_TEXT: case BATCH_TYPE_3D_COLORED_TRIANGLES: case BATCH_TYPE_3D_TEXTURED_TRIANGLES: case BATCH_TYPE_3D_TEXT: m_pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); break; default: UnreachableCode(); break; } // invoke correct draw switch (m_batchType) { case BATCH_TYPE_2D_COLORED_LINES: case BATCH_TYPE_2D_COLORED_TRIANGLES: case BATCH_TYPE_2D_TEXTURED_TRIANGLES: case BATCH_TYPE_2D_TEXT: m_pGPUContext->DrawUserPointer(m_batchVertices2D.GetBasePointer(), sizeof(OverlayShader::Vertex2D), m_batchVertices2D.GetSize()); break; case BATCH_TYPE_3D_COLORED_LINES: case BATCH_TYPE_3D_COLORED_TRIANGLES: case BATCH_TYPE_3D_TEXTURED_TRIANGLES: case BATCH_TYPE_3D_TEXT: m_pGPUContext->DrawUserPointer(m_batchVertices3D.GetBasePointer(), sizeof(OverlayShader::Vertex3D), m_batchVertices3D.GetSize()); break; default: UnreachableCode(); break; } // restore state m_batchType = BATCH_TYPE_NONE; SAFE_RELEASE(m_pBatchTexture); m_batchVertices2D.Clear(); m_batchVertices3D.Clear(); } void MiniGUIContext::BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive) { DebugAssertMsg(m_immediatePrimitive == IMMEDIATE_PRIMITIVE_COUNT, "Immediate draw not begun"); switch (primitive) { case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: SetBatchType(BATCH_TYPE_2D_COLORED_LINES); break; case IMMEDIATE_PRIMITIVE_TRIANGLES: case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: case IMMEDIATE_PRIMITIVE_QUADS: case IMMEDIATE_PRIMITIVE_QUAD_STRIP: SetBatchType(BATCH_TYPE_2D_COLORED_TRIANGLES); break; } m_immediatePrimitive = primitive; m_immediateStartVertex = m_batchVertices2D.GetSize(); } void MiniGUIContext::BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive, const Texture2D *pTexture) { GPUTexture *pGPUTexture = pTexture->GetGPUTexture(); if (pGPUTexture != nullptr) BeginImmediate2D(primitive, pGPUTexture); else BeginImmediate2D(primitive); } void MiniGUIContext::BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive, GPUTexture *pGPUTexture) { DebugAssertMsg(m_immediatePrimitive == IMMEDIATE_PRIMITIVE_COUNT, "Immediate draw not begun"); if (m_pBatchTexture != pGPUTexture) Flush(); switch (primitive) { case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: SetBatchType(BATCH_TYPE_2D_COLORED_LINES); break; case IMMEDIATE_PRIMITIVE_TRIANGLES: case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: case IMMEDIATE_PRIMITIVE_QUADS: case IMMEDIATE_PRIMITIVE_QUAD_STRIP: SetBatchType(BATCH_TYPE_2D_TEXTURED_TRIANGLES); break; } DebugAssert(m_pBatchTexture == nullptr); m_pBatchTexture = pGPUTexture; m_pBatchTexture->AddRef(); m_immediatePrimitive = primitive; m_immediateStartVertex = m_batchVertices2D.GetSize(); } void MiniGUIContext::BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive) { DebugAssertMsg(m_immediatePrimitive == IMMEDIATE_PRIMITIVE_COUNT, "Immediate draw not begun"); switch (primitive) { case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: SetBatchType(BATCH_TYPE_3D_COLORED_LINES); break; case IMMEDIATE_PRIMITIVE_TRIANGLES: case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: case IMMEDIATE_PRIMITIVE_QUADS: case IMMEDIATE_PRIMITIVE_QUAD_STRIP: SetBatchType(BATCH_TYPE_3D_COLORED_TRIANGLES); break; } m_immediatePrimitive = primitive; m_immediateStartVertex = m_batchVertices3D.GetSize(); } void MiniGUIContext::BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive, const Texture2D *pTexture) { GPUTexture *pGPUTexture = pTexture->GetGPUTexture(); if (pGPUTexture != nullptr) BeginImmediate3D(primitive, pGPUTexture); else BeginImmediate3D(primitive); } void MiniGUIContext::BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive, GPUTexture *pGPUTexture) { DebugAssertMsg(m_immediatePrimitive == IMMEDIATE_PRIMITIVE_COUNT, "Immediate draw not begun"); if (m_pBatchTexture != pGPUTexture) Flush(); switch (primitive) { case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: SetBatchType(BATCH_TYPE_3D_COLORED_LINES); break; case IMMEDIATE_PRIMITIVE_TRIANGLES: case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: case IMMEDIATE_PRIMITIVE_QUADS: case IMMEDIATE_PRIMITIVE_QUAD_STRIP: SetBatchType(BATCH_TYPE_3D_TEXTURED_TRIANGLES); break; } DebugAssert(m_pBatchTexture == nullptr); m_pBatchTexture = pGPUTexture; m_pBatchTexture->AddRef(); m_immediatePrimitive = primitive; m_immediateStartVertex = m_batchVertices3D.GetSize(); } void MiniGUIContext::AddVertices(const OverlayShader::Vertex2D *pVertices, uint32 nVertices) { DebugAssert(m_batchType < BATCH_TYPE_3D_COLORED_LINES); m_batchVertices2D.AddRange(pVertices, nVertices); } void MiniGUIContext::AddVertices(const OverlayShader::Vertex3D *pVertices, uint32 nVertices) { DebugAssert(m_batchType >= BATCH_TYPE_3D_COLORED_LINES); m_batchVertices3D.AddRange(pVertices, nVertices); } void MiniGUIContext::ImmediateVertex(const OverlayShader::Vertex2D &vertex) { DebugAssert(m_batchType < BATCH_TYPE_3D_COLORED_LINES); // number of immediate vertices uint32 vertexCount = m_batchVertices2D.GetSize(); uint32 immVertexPos = vertexCount - m_immediateStartVertex; uint32 immVertexCount = immVertexPos + 1; // insert extra vertices where necessary switch (m_immediatePrimitive) { //case IMMEDIATE_PRIMITIVE_POINTS: case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_TRIANGLES: { // add vertex as normal m_batchVertices2D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: { // add last vertex if not the first m_batchVertices2D.EnsureReserve(2); if (immVertexPos > 0) m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 1]); // add vertex m_batchVertices2D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: { // add the last two vertices, flipping the winding on even vertices if (immVertexCount >= 3) { m_batchVertices2D.EnsureReserve(3); if ((immVertexCount % 2) == 0) { m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 2]); m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 1]); } else { m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 1]); m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 2]); } } // add vertex m_batchVertices2D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: { // create triangle fan m_batchVertices2D.EnsureReserve(3); m_batchVertices2D.Add(vertex); m_batchVertices2D.Add(m_batchVertices2D[vertexCount - 1]); m_batchVertices2D.Add(m_batchVertices2D[m_immediateStartVertex]); } break; case IMMEDIATE_PRIMITIVE_QUADS: { // we have to add the last 2 vertices in reverse order uint32 currentIndex = immVertexPos % 6; if (currentIndex == 3) { // ensure it is large enough so the array doesn't get moved in memory m_batchVertices2D.EnsureReserve(3); // copy in case array gets resized and pointers invalidated uint32 baseIndex = vertexCount - 3; OverlayShader::Vertex2D topLeftVertex(m_batchVertices2D[baseIndex + 0]); OverlayShader::Vertex2D bottomLeftVertex(m_batchVertices2D[baseIndex + 1]); OverlayShader::Vertex2D bottomRightVertex(m_batchVertices2D[baseIndex + 2]); OverlayShader::Vertex2D topRightVertex(vertex); // reorder first triangle m_batchVertices2D[baseIndex + 0] = bottomLeftVertex; m_batchVertices2D[baseIndex + 1] = topLeftVertex; m_batchVertices2D[baseIndex + 2] = bottomRightVertex; // create second triangle m_batchVertices2D.Add(bottomRightVertex); m_batchVertices2D.Add(topLeftVertex); m_batchVertices2D.Add(topRightVertex); } else { // add vertex as-is m_batchVertices2D.Add(vertex); } } break; } } void MiniGUIContext::ImmediateVertex(const OverlayShader::Vertex3D &vertex) { DebugAssert(m_batchType >= BATCH_TYPE_3D_COLORED_LINES); // number of immediate vertices uint32 vertexCount = m_batchVertices3D.GetSize(); uint32 immVertexPos = vertexCount - m_immediateStartVertex; uint32 immVertexCount = immVertexPos + 1; // insert extra vertices where necessary switch (m_immediatePrimitive) { //case IMMEDIATE_PRIMITIVE_POINTS: case IMMEDIATE_PRIMITIVE_LINES: case IMMEDIATE_PRIMITIVE_TRIANGLES: { // add vertex as normal m_batchVertices3D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_LINE_STRIP: case IMMEDIATE_PRIMITIVE_LINE_LOOP: { // add last vertex if not the first m_batchVertices3D.EnsureReserve(2); if (immVertexPos > 0) m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 1]); // add vertex m_batchVertices3D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP: { // add the last two vertices, flipping the winding on even vertices if (immVertexCount >= 3) { m_batchVertices3D.EnsureReserve(3); if ((immVertexCount % 2) == 0) { m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 2]); m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 1]); } else { m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 1]); m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 2]); } } // add vertex m_batchVertices3D.Add(vertex); } break; case IMMEDIATE_PRIMITIVE_TRIANGLE_FAN: { // create triangle fan m_batchVertices3D.EnsureReserve(3); m_batchVertices3D.Add(vertex); m_batchVertices3D.Add(m_batchVertices3D[vertexCount - 1]); m_batchVertices3D.Add(m_batchVertices3D[m_immediateStartVertex]); } break; case IMMEDIATE_PRIMITIVE_QUADS: { // we have to add the last 2 vertices in reverse order uint32 currentIndex = immVertexPos % 6; if (currentIndex == 3) { // ensure it is large enough so the array doesn't get moved in memory m_batchVertices3D.EnsureReserve(3); // copy in case array gets resized and pointers invalidated uint32 baseIndex = vertexCount - 3; OverlayShader::Vertex3D topLeftVertex(m_batchVertices3D[baseIndex + 0]); OverlayShader::Vertex3D bottomLeftVertex(m_batchVertices3D[baseIndex + 1]); OverlayShader::Vertex3D bottomRightVertex(m_batchVertices3D[baseIndex + 2]); OverlayShader::Vertex3D topRightVertex(vertex); // reorder first triangle m_batchVertices3D[baseIndex + 0] = bottomLeftVertex; m_batchVertices3D[baseIndex + 1] = topLeftVertex; m_batchVertices3D[baseIndex + 2] = bottomRightVertex; // create second triangle m_batchVertices3D.Add(bottomRightVertex); m_batchVertices3D.Add(topLeftVertex); m_batchVertices3D.Add(topRightVertex); } else { // add vertex as-is m_batchVertices3D.Add(vertex); } } break; } } void MiniGUIContext::EndImmediate() { bool is3D = (m_batchType >= BATCH_TYPE_3D_COLORED_LINES); uint32 immVertexCount = (is3D ? m_batchVertices3D.GetSize() : m_batchVertices2D.GetSize()) - m_immediateStartVertex; if (immVertexCount > 0) { // handle primitive-specific stuff switch (m_immediatePrimitive) { case IMMEDIATE_PRIMITIVE_LINE_LOOP: { // line loops have to be closed DebugAssert(immVertexCount > 2); if (is3D) { m_batchVertices2D.EnsureReserve(2); m_batchVertices2D.Add(m_batchVertices2D[m_batchVertices2D.GetSize() - 1]); m_batchVertices2D.Add(m_batchVertices2D[m_immediateStartVertex]); } else { m_batchVertices3D.EnsureReserve(2); m_batchVertices3D.Add(m_batchVertices3D[m_batchVertices3D.GetSize() - 1]); m_batchVertices3D.Add(m_batchVertices3D[m_immediateStartVertex]); } } break; } // clear immediate state m_immediatePrimitive = IMMEDIATE_PRIMITIVE_COUNT; m_immediateStartVertex = 0; // invoke draw if not manually flushing if (!m_manualFlushCount) Flush(); } else { // clear immediate state m_immediatePrimitive = IMMEDIATE_PRIMITIVE_COUNT; m_immediateStartVertex = 0; } } void MiniGUIContext::ImmediateVertex(const float2 &position) { OverlayShader::Vertex2D vertex; vertex.Set(position, float2::Zero, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(const float2 &position, const float2 &texCoord) { OverlayShader::Vertex2D vertex; vertex.Set(position, texCoord, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(const float2 &position, const uint32 color) { OverlayShader::Vertex2D vertex; vertex.Set(position, float2::Zero, color); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(const float3 &position) { OverlayShader::Vertex3D vertex; vertex.Set(position, float2::Zero, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(const float3 &position, const float2 &texCoord) { OverlayShader::Vertex3D vertex; vertex.Set(position, texCoord, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(const float3 &position, const uint32 color) { OverlayShader::Vertex3D vertex; vertex.Set(position, float2::Zero, color); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y) { OverlayShader::Vertex2D vertex; vertex.Set(x, y, 0.0f, 0.0f, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y, float u, float v) { OverlayShader::Vertex2D vertex; vertex.Set(x, y, u, v, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y, uint32 color) { OverlayShader::Vertex2D vertex; vertex.Set(x, y, 0.0f, 0.0f, color); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y, float z) { OverlayShader::Vertex3D vertex; vertex.Set(x, y, z, 0.0f, 0.0f, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y, float z, float u, float v) { OverlayShader::Vertex3D vertex; vertex.Set(x, y, z, u, v, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); ImmediateVertex(vertex); } void MiniGUIContext::ImmediateVertex(float x, float y, float z, uint32 color) { OverlayShader::Vertex3D vertex; vertex.Set(x, y, z, 0.0f, 0.0f, color); ImmediateVertex(vertex); } void MiniGUIContext::DrawLine(const int2 &LineVertex1, const int2 &LineVertex2, const uint32 Color) { int2 clippedVertex1 = TranslateAndClipPoint(LineVertex1); int2 clippedVertex2 = TranslateAndClipPoint(LineVertex2); if (m_batchType != BATCH_TYPE_2D_COLORED_LINES) { Flush(); m_batchType = BATCH_TYPE_2D_COLORED_LINES; } OverlayShader::Vertex2D Vertices[2]; Vertices[0].SetColor((float)clippedVertex1.x, (float)clippedVertex1.y, Color); Vertices[1].SetColor((float)clippedVertex2.x, (float)clippedVertex2.y, Color); AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::DrawLine(const int2 &LineVertex1, const uint32 Color1, const int2 &LineVertex2, const uint32 Color2) { int2 clippedVertex1 = TranslateAndClipPoint(LineVertex1); int2 clippedVertex2 = TranslateAndClipPoint(LineVertex2); if (m_batchType != BATCH_TYPE_2D_COLORED_LINES) { Flush(); m_batchType = BATCH_TYPE_2D_COLORED_LINES; } OverlayShader::Vertex2D Vertices[2]; Vertices[0].SetColor((float)clippedVertex1.x, (float)clippedVertex1.y, Color1); Vertices[1].SetColor((float)clippedVertex2.x, (float)clippedVertex2.y, Color2); AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::DrawRect(const MINIGUI_RECT *pRect, const uint32 Color) { MINIGUI_RECT realRect; TranslateAndClipRect(&realRect, pRect); if (!ValidateRect(&realRect)) return; SetBatchType(BATCH_TYPE_2D_COLORED_LINES); OverlayShader::Vertex2D Vertices[8]; Vertices[0].SetColor((float)realRect.left, (float)realRect.top, Color); // top Vertices[1].SetColor((float)realRect.right, (float)realRect.top, Color); // top Vertices[2].SetColor((float)realRect.right, (float)realRect.top, Color); // right Vertices[3].SetColor((float)realRect.right, (float)realRect.bottom, Color); // right Vertices[4].SetColor((float)realRect.right, (float)realRect.bottom, Color); // bottom Vertices[5].SetColor((float)realRect.left, (float)realRect.bottom, Color); // bottom Vertices[6].SetColor((float)realRect.left, (float)realRect.bottom, Color); // left Vertices[7].SetColor((float)realRect.left, (float)realRect.top, Color); // left AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); MiniGUIContext_Log_TracePrintf("MiniGUIContext::DrawRect(%i, %i, %i, %i)", pRect->left, pRect->right, pRect->top, pRect->bottom); } void MiniGUIContext::DrawFilledRect(const MINIGUI_RECT *pRect, const uint32 Color) { DrawFilledRect(pRect, Color, Color, Color, Color); } void MiniGUIContext::DrawFilledRect(const MINIGUI_RECT *pRect, const uint32 Color1, const uint32 Color2, const uint32 Color3, const uint32 Color4) { // check state SetBatchType(BATCH_TYPE_2D_COLORED_TRIANGLES); // clip rect MINIGUI_RECT clippedRect; TranslateAndClipRect(&clippedRect, pRect); if (!ValidateRect(&clippedRect)) return; // find points float2 p1, p2, p3, p4; p1.Set((float)clippedRect.left, (float)clippedRect.top); p2.Set((float)clippedRect.right, (float)clippedRect.top); p3.Set((float)clippedRect.right, (float)clippedRect.bottom); p4.Set((float)clippedRect.left, (float)clippedRect.bottom); // generate vertices OverlayShader::Vertex2D Vertices[6]; Vertices[0].SetColor(p1, Color1); Vertices[1].SetColor(p4, Color4); Vertices[2].SetColor(p2, Color2); Vertices[3].SetColor(p2, Color2); Vertices[4].SetColor(p4, Color4); Vertices[5].SetColor(p3, Color3); AddVertices(Vertices, countof(Vertices)); // flush if (!m_manualFlushCount) Flush(); MiniGUIContext_Log_TracePrintf("MiniGUIContext::DrawFilledRect(%i, %i, %i, %i)", pRect->left, pRect->right, pRect->top, pRect->bottom); } void MiniGUIContext::DrawGradientRect(const MINIGUI_RECT *pRect, const uint32 Color1, const uint32 Color2, bool Horizontal /*= false*/) { if (Horizontal) DrawFilledRect(pRect, Color1, Color2, Color2, Color1); else DrawFilledRect(pRect, Color1, Color1, Color2, Color2); } void MiniGUIContext::DrawTexturedRect(const MINIGUI_RECT *pRect, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture) { GPUTexture2D *pGPUTexture = static_cast<GPUTexture2D *>(pTexture->GetGPUTexture()); if (pGPUTexture != NULL) DrawTexturedRect(pRect, pUVRect, pGPUTexture); } void MiniGUIContext::DrawTexturedRect(const MINIGUI_RECT *pRect, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture) { // check state if (m_batchType != BATCH_TYPE_2D_TEXTURED_TRIANGLES || m_pBatchTexture != pDeviceTexture) { Flush(); m_batchType = BATCH_TYPE_2D_TEXTURED_TRIANGLES; m_pBatchTexture = pDeviceTexture; m_pBatchTexture->AddRef(); } // clip rect MINIGUI_RECT realRect; MINIGUI_RECT translatedRect; MINIGUI_UV_RECT clippedUVRect; TranslateRect(&translatedRect, pRect); TranslateAndClipRect(&realRect, pRect); ClipUVRect(&clippedUVRect, pUVRect, &realRect, &translatedRect); if (!ValidateRect(&realRect)) return; // due to batching, we have to use triangle lists. OverlayShader::Vertex2D Vertices[6]; Vertices[0].SetUV((float)realRect.left, (float)realRect.top, clippedUVRect.left, clippedUVRect.top); // topleft Vertices[1].SetUV((float)realRect.left, (float)realRect.bottom, clippedUVRect.left, clippedUVRect.bottom); // bottomleft Vertices[2].SetUV((float)realRect.right, (float)realRect.top, clippedUVRect.right, clippedUVRect.top); // topright Vertices[3].SetUV((float)realRect.right, (float)realRect.top, clippedUVRect.right, clippedUVRect.top); // topright Vertices[4].SetUV((float)realRect.left, (float)realRect.bottom, clippedUVRect.left, clippedUVRect.bottom); // bottomleft Vertices[5].SetUV((float)realRect.right, (float)realRect.bottom, clippedUVRect.right, clippedUVRect.bottom); // bottomright AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); MiniGUIContext_Log_TracePrintf("MiniGUIContext::DrawTexturedRect(%i, %i, %i, %i)", pRect->left, pRect->right, pRect->top, pRect->bottom); } void MiniGUIContext::DrawEmissiveRect(const MINIGUI_RECT *pRect, const Material *pMaterial) { MiniGUIContext_Log_TracePrintf("MiniGUIContext::DrawEmissiveRect(%i, %i, %i, %i, %s)", pRect->left, pRect->right, pRect->top, pRect->bottom, pMaterial->GetName().GetCharArray()); } void MiniGUIContext::DrawText(const Font *pFontData, int32 Size, const MINIGUI_RECT *pRect, const char *Text, const uint32 Color /* = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255) */, bool AllowFormatting /* = false */, MINIGUI_HORIZONTAL_ALIGNMENT hAlign /* = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT */, MINIGUI_VERTICAL_ALIGNMENT vAlign /* = MINIGUI_VERTICAL_ALIGNMENT_TOP */) { if (pFontData == NULL || !ValidateRect(pRect)) return; // determine the number of lines of text, and the maximum number of characters in a line const char *pLineStart = Text; const char *pTextPointer = Text; uint32 maxCharactersPerLine = 0; uint32 nCharacters = 0; uint32 nLines = 1; for (; *pTextPointer != '\0'; pTextPointer++) { char ch = *pTextPointer; if (ch == '\n') { maxCharactersPerLine = Max(maxCharactersPerLine, nCharacters); nCharacters = 0; nLines++; } else { nCharacters++; } } // calc scale float Scale = (float)Size / (float)pFontData->GetHeight(); // calculate y start position int32 curY; if (vAlign == MINIGUI_VERTICAL_ALIGNMENT_TOP) curY = pRect->top; else if (vAlign == MINIGUI_VERTICAL_ALIGNMENT_CENTER) curY = (int32)((float)(pRect->bottom - pRect->top) * 0.5f) - (int32)((float)Size * 0.5f) - ((nLines - 1) * Size); else curY = pRect->bottom - (nLines * Size); // draw each line of the text // everything will get batched together, hopefully :) pLineStart = Text; pTextPointer = pLineStart; for (; *pTextPointer != '\0'; ) { nCharacters = 0; pLineStart = pTextPointer; while (*pTextPointer != '\n' && *pTextPointer != '\0') { nCharacters++; pTextPointer++; } // increment the text pointer for the next line if (*pTextPointer != '\0') pTextPointer++; // special case: no characters and newline, just increment the y position if (nCharacters == 0 && *pLineStart == '\n') { curY += Size; continue; } // calculate the width of the text int32 lineWidth = (int32)pFontData->GetTextWidth(pLineStart, nCharacters, Scale); if (lineWidth == 0) { curY += Size; continue; } // calculate line rect MINIGUI_RECT lineRect; lineRect.top = curY; lineRect.bottom = curY + (Size * 2); // horizontal alignment if (hAlign == MINIGUI_HORIZONTAL_ALIGNMENT_LEFT) { lineRect.left = pRect->left; lineRect.right = lineRect.left + lineWidth; } else if (hAlign == MINIGUI_HORIZONTAL_ALIGNMENT_CENTER) { float halfWidth = (float)(pRect->right - pRect->left) * 0.5f; float halfTextWidth = (float)(lineWidth) * 0.5f; lineRect.left = pRect->left + (int32)Y_floorf(halfWidth - halfTextWidth); lineRect.right = pRect->left + (int32)Y_ceilf(halfWidth + halfTextWidth); } else // MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT { lineRect.left = pRect->right - lineWidth; lineRect.right = lineRect.left + lineWidth; } // clip to provided bounds lineRect.left = Max(lineRect.left, pRect->left); lineRect.right = Min(lineRect.right, pRect->right); lineRect.top = Max(lineRect.top, pRect->top); lineRect.bottom = Min(lineRect.bottom, pRect->bottom); // translate and clip to stack rect MINIGUI_RECT realRect; TranslateAndClipRect(&realRect, &lineRect); // draw text InternalDrawText(pFontData, Scale, Color, &realRect, pLineStart, nCharacters, true); // increment y position curY += Size; } if (!m_manualFlushCount) Flush(); MiniGUIContext_Log_TracePrintf("MiniGUIContext::DrawText(%i, %i, %i, %i, %s)", pRect->left, pRect->right, pRect->top, pRect->bottom, Text); } void MiniGUIContext::DrawText(const Font *pFontData, int32 Size, const int2 &Position, const char *Text, const uint32 Color /* = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255) */, bool AllowFormatting /* = false */, MINIGUI_HORIZONTAL_ALIGNMENT hAlign /* = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT */, MINIGUI_VERTICAL_ALIGNMENT vAlign /* = MINIGUI_VERTICAL_ALIGNMENT_TOP */) { MINIGUI_RECT drawRect; if (Position.x < 0) { drawRect.left = m_topRect.right + Position.x; drawRect.right = m_topRect.right; } else { drawRect.left = m_topRect.left + Position.x; drawRect.right = m_topRect.right; } if (Position.y < 0) { drawRect.top = m_topRect.bottom + Position.y; drawRect.bottom = m_topRect.bottom; } else { drawRect.top = m_topRect.top + Position.y; drawRect.bottom = m_topRect.bottom; } UntranslateRect(&drawRect, &drawRect); DrawText(pFontData, Size, &drawRect, Text, Color, AllowFormatting, hAlign, vAlign); } void MiniGUIContext::DrawText(const Font *pFontData, int32 Size, int32 x, int32 y, const char *Text, const uint32 Color /* = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255) */, bool AllowFormatting /* = false */, MINIGUI_HORIZONTAL_ALIGNMENT hAlign /* = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT */, MINIGUI_VERTICAL_ALIGNMENT vAlign /* = MINIGUI_VERTICAL_ALIGNMENT_TOP */) { DrawText(pFontData, Size, int2(x, y), Text, Color, AllowFormatting, hAlign, vAlign); } void MiniGUIContext::Draw3DLine(const float3 &p0, const float3 &p1, const uint32 color) { Draw3DLine(p0, color, p1, color); } void MiniGUIContext::Draw3DLine(const float3 &p0, const uint32 color1, const float3 &p1, const uint32 color2) { SetBatchType(BATCH_TYPE_3D_COLORED_LINES); OverlayShader::Vertex3D vertices[2]; vertices[0].SetColor(p0.x, p0.y, p0.z, color1); vertices[1].SetColor(p1.x, p1.y, p1.z, color2); AddVertices(vertices, countof(vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DLineWidth(const float3 &p0, const float3 &p1, const uint32 color, float lineWidth, bool widthScale /* = true */) { Draw3DLineWidth(p0, color, p1, color, lineWidth, widthScale); } static float ComputeConstantScale(const float3 &pos, const float4x4 &viewMatrix, const float4x4 &projectionMatrix, uint32 vpwidth) { float3 ppcam0(viewMatrix.TransformPoint(pos)); float3 ppcam1(ppcam0); ppcam1.x += 1.0f; float l1 = 1.0f/(ppcam0.x*projectionMatrix[3][0] + ppcam0.y*projectionMatrix[3][1] + ppcam0.z*projectionMatrix[3][2] + projectionMatrix[3][3]); float c1 = (ppcam0.x*projectionMatrix[0][0] + ppcam0.y*projectionMatrix[0][1] + ppcam0.z*projectionMatrix[0][2] + projectionMatrix[0][3])*l1; float l2 = 1.0f/(ppcam1.x*projectionMatrix[3][0] + ppcam1.y*projectionMatrix[3][1] + ppcam1.z*projectionMatrix[3][2] + projectionMatrix[3][3]); float c2 = (ppcam1.x*projectionMatrix[0][0] + ppcam1.y*projectionMatrix[0][1] + ppcam1.z*projectionMatrix[0][2] + projectionMatrix[0][3])*l2; float CorrectScale = 1.0f/(c2 - c1); return CorrectScale / float(vpwidth); } static float3 ComputePoint(float x, float y, const float4x4 &inverseView, const float3 &trans) { return float3(trans.x + x * inverseView[0][0] + y * inverseView[0][1], trans.y + x * inverseView[1][0] + y * inverseView[1][1], trans.z + x * inverseView[2][0] + y * inverseView[2][1]); } void MiniGUIContext::Draw3DLineWidth(const float3 &p0, const uint32 color1, const float3 &p1, const uint32 color2, float lineWidth, bool widthScale /* = true */) { // OPTIMIZE ME! // http://www.flipcode.com/archives/Textured_Lines_In_D3D.shtml const float4x4 &viewMatrix = g_pRenderer->GetGPUContext()->GetConstants()->GetCameraViewMatrix(); const float4x4 &projectionMatrix = g_pRenderer->GetGPUContext()->GetConstants()->GetCameraProjectionMatrix(); float4x4 inverseViewMatrix(viewMatrix.Transpose()); // transform the delta by the view matrix rotation component float3 deltaDiff(p1 - p0); float3 delta(deltaDiff.Dot(viewMatrix.GetRow(0).xyz()), deltaDiff.Dot(viewMatrix.GetRow(1).xyz()), deltaDiff.Dot(viewMatrix.GetRow(2).xyz())); // calculate the sizes at each end of the line float sizep0 = lineWidth; float sizep1 = lineWidth; if (widthScale) { sizep0 *= ComputeConstantScale(p0, viewMatrix, projectionMatrix, m_viewportWidth); sizep1 *= ComputeConstantScale(p1, viewMatrix, projectionMatrix, m_viewportWidth); } // compute quad vertices float theta0 = Math::ArcTan(-delta.x, -delta.y); float c0 = sizep0 * Math::Cos(theta0); float s0 = sizep0 * Math::Sin(theta0); float3 q_v0(ComputePoint(c0, -s0, inverseViewMatrix, p0)); float3 q_v1(ComputePoint(-c0, s0, inverseViewMatrix, p0)); float theta1 = Math::ArcTan(delta.x, delta.y); float c1 = sizep1 * Math::Cos(theta1); float s1 = sizep1 * Math::Sin(theta1); float3 q_v2(ComputePoint(-c1, s1, inverseViewMatrix, p1)); float3 q_v3(ComputePoint(c1, -s1, inverseViewMatrix, p1)); SetBatchType(BATCH_TYPE_3D_COLORED_TRIANGLES); OverlayShader::Vertex3D vertices[6]; vertices[0].SetColor(q_v0.x, q_v0.y, q_v0.z, color1); vertices[1].SetColor(q_v1.x, q_v1.y, q_v1.z, color1); vertices[2].SetColor(q_v2.x, q_v2.y, q_v2.z, color2); vertices[3].SetColor(q_v2.x, q_v2.y, q_v2.z, color2); vertices[4].SetColor(q_v1.x, q_v1.y, q_v1.z, color1); vertices[5].SetColor(q_v3.x, q_v3.y, q_v3.z, color2); AddVertices(vertices, countof(vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DRect(const float3 &p0, const float3 &p1, const uint32 color) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DRect(float3(pmin.x, pmax.y, pmin.z), float3(pmin.x, pmin.y, pmax.z), float3(pmax.x, pmin.y, pmax.z), float3(pmax.x, pmax.y, pmin.z), color); } void MiniGUIContext::Draw3DRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color) { SetBatchType(BATCH_TYPE_3D_COLORED_LINES); OverlayShader::Vertex3D Vertices[8]; Vertices[0].Set(p0, float2::Zero, color); Vertices[1].Set(p1, float2::Zero, color); Vertices[2].Set(p1, float2::Zero, color); Vertices[3].Set(p2, float2::Zero, color); Vertices[4].Set(p2, float2::Zero, color); Vertices[5].Set(p3, float2::Zero, color); Vertices[6].Set(p3, float2::Zero, color); Vertices[7].Set(p0, float2::Zero, color); AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DRectWidth(const float3 &p0, const float3 &p1, const uint32 color, float lineWidth, bool widthScale /*= true*/) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DRectWidth(float3(pmin.x, pmax.y, pmin.z), float3(pmin.x, pmin.y, pmax.z), float3(pmax.x, pmin.y, pmax.z), float3(pmax.x, pmax.y, pmin.z), color, lineWidth, widthScale); } void MiniGUIContext::Draw3DRectWidth(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color, float lineWidth, bool widthScale /*= true*/) { // force auto flush since we're going to call the same routine a bunch of times PushManualFlush(); // invoke the line draws Draw3DLineWidth(p0, color, p1, color, lineWidth, widthScale); Draw3DLineWidth(p1, color, p2, color, lineWidth, widthScale); Draw3DLineWidth(p2, color, p3, color, lineWidth, widthScale); Draw3DLineWidth(p3, color, p0, color, lineWidth, widthScale); // restore flush state PopManualFlush(); } void MiniGUIContext::Draw3DFilledRect(const float3 &p0, const float3 &p1, const uint32 color) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DFilledRect(float3(pmin.x, pmax.y, pmin.z), float3(pmin.x, pmin.y, pmax.z), float3(pmax.x, pmin.y, pmax.z), float3(pmax.x, pmax.y, pmin.z), color); } void MiniGUIContext::Draw3DFilledRect(const float3 &p0, const uint32 color0, const float3 &p1, const uint32 color1) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DFilledRect(float3(pmin.x, pmax.y, pmin.z), color1, float3(pmin.x, pmin.y, pmax.z), color0, float3(pmax.x, pmin.y, pmax.z), color0, float3(pmax.x, pmax.y, pmin.z), color1); } void MiniGUIContext::Draw3DFilledRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color) { Draw3DFilledRect(p0, color, p1, color, p2, color, p3, color); } void MiniGUIContext::Draw3DFilledRect(const float3 &p0, const uint32 color0, const float3 &p1, const uint32 color1, const float3 &p2, const uint32 color2, const float3 &p3, const uint32 color3) { // check state SetBatchType(BATCH_TYPE_3D_COLORED_TRIANGLES); // generate vertices OverlayShader::Vertex3D Vertices[6]; Vertices[0].Set(p0, float2::Zero, color0); Vertices[1].Set(p1, float2::Zero, color1); Vertices[2].Set(p3, float2::Zero, color2); Vertices[3].Set(p3, float2::Zero, color2); Vertices[4].Set(p1, float2::Zero, color1); Vertices[5].Set(p2, float2::Zero, color3); AddVertices(Vertices, countof(Vertices)); // flush if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DGradientRect(const float3 &p0, const float3 &p1, const uint32 fromColor, const uint32 toColor, bool horizontal /* = false */) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DFilledRect(float3(pmin.x, pmax.y, pmin.z), horizontal ? fromColor : toColor, float3(pmin.x, pmin.y, pmax.z), horizontal ? fromColor : fromColor, float3(pmax.x, pmin.y, pmax.z), horizontal ? toColor : fromColor, float3(pmax.x, pmax.y, pmin.z), horizontal ? toColor : toColor); } void MiniGUIContext::Draw3DTexturedRect(const float3 &p0, const float3 &p1, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DTexturedRect(float3(pmin.x, pmax.y, pmin.z), float3(pmin.x, pmin.y, pmax.z), float3(pmax.x, pmin.y, pmax.z), float3(pmax.x, pmax.y, pmin.z), pUVRect, pTexture); } void MiniGUIContext::Draw3DTexturedRect(const float3 &p0, const float3 &p1, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture) { float3 pmin(p0.Min(p1)); float3 pmax(p0.Max(p1)); // go ccw Draw3DTexturedRect(float3(pmin.x, pmax.y, pmin.z), float3(pmin.x, pmin.y, pmax.z), float3(pmax.x, pmin.y, pmax.z), float3(pmax.x, pmax.y, pmin.z), pUVRect, pDeviceTexture); } void MiniGUIContext::Draw3DTexturedRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture) { GPUTexture2D *pGPUTexture = static_cast<GPUTexture2D *>(pTexture->GetGPUTexture()); if (pGPUTexture != NULL) Draw3DTexturedRect(p0, p1, p2, p3, pUVRect, pGPUTexture); } void MiniGUIContext::Draw3DTexturedRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture) { if (m_batchType != BATCH_TYPE_3D_TEXTURED_TRIANGLES || m_pBatchTexture != pDeviceTexture) { Flush(); m_batchType = BATCH_TYPE_3D_TEXTURED_TRIANGLES; m_pBatchTexture = pDeviceTexture; m_pBatchTexture->AddRef(); } OverlayShader::Vertex3D vertices[6]; vertices[0].SetUV(p0.x, p0.y, p0.z, pUVRect->left, pUVRect->top); // topleft vertices[1].SetUV(p1.x, p1.y, p1.z, pUVRect->left, pUVRect->bottom); // bottomleft vertices[2].SetUV(p3.x, p3.y, p3.z, pUVRect->right, pUVRect->top); // topright vertices[3].SetUV(p3.x, p3.y, p3.z, pUVRect->right, pUVRect->top); // topright vertices[4].SetUV(p1.x, p1.y, p1.z, pUVRect->left, pUVRect->bottom); // bottomleft vertices[5].SetUV(p2.x, p2.y, p2.z, pUVRect->right, pUVRect->bottom); // bottomright AddVertices(vertices, countof(vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DEmissiveRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const Material *pMaterial) { } void MiniGUIContext::Draw3DGrid(const Plane &groundPlane, const float3 &origin, const float gridWidth, const float gridHeight, const float lineStep /* = 0.0f */, const uint32 lineColor /* = 0 */) { SetBatchType(BATCH_TYPE_3D_COLORED_LINES); const float gridRangeX = gridWidth * 0.5f; const float gridRangeY = gridHeight * 0.5f; float3 vOrigin(origin); OverlayShader::Vertex3D vertices[2]; uint32 drawRows; uint32 drawColumns; float x, y; uint32 i; if (lineStep > 0.0f) { drawRows = (uint32)Y_ceilf(gridRangeX * 2.0f / lineStep); drawColumns = (uint32)Y_ceilf(gridRangeY * 2.0f / lineStep); // draw columns for (i = 0, x = 0.0f; i <= drawColumns; i++, x += lineStep) { vertices[0].Set(vOrigin + float3(-gridRangeX + x, gridRangeY, 0.0f), float2::Zero, lineColor); vertices[1].Set(vOrigin + float3(-gridRangeX + x, -gridRangeY, 0.0f), float2::Zero, lineColor); AddVertices(vertices, countof(vertices)); } // draw rows for (i = 0, y = 0.0f; i <= drawRows; i++, y += lineStep) { vertices[0].Set(vOrigin + float3(-gridRangeX, -gridRangeY + y, 0.0f), float2::Zero, lineColor); vertices[1].Set(vOrigin + float3(gridRangeX, -gridRangeY + y, 0.0f), float2::Zero, lineColor); AddVertices(vertices, countof(vertices)); } } if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DGrid(const float3 &minCoordinates, const float3 &maxCoordinates, const float3 &gridStep, const uint32 lineColor) { SetBatchType(BATCH_TYPE_3D_COLORED_LINES); OverlayShader::Vertex3D vertices[2]; float x, y, z; uint32 i; float3 gridRange = float3(maxCoordinates) - float3(minCoordinates); uint32 drawLinesX = (gridStep.x > 0.0f) ? (uint32)Y_ceilf(gridRange.x / gridStep.x) : 0; uint32 drawLinesY = (gridStep.y > 0.0f) ? (uint32)Y_ceilf(gridRange.y / gridStep.y) : 0; uint32 drawLinesZ = (gridStep.z > 0.0f) ? (uint32)Y_ceilf(gridRange.z / gridStep.z) : 0; if (drawLinesX > 0) { for (i = 0, x = 0.0f; i <= drawLinesX; i++, x += gridStep.x) { vertices[0].Set(float3(minCoordinates.x + x, minCoordinates.y, minCoordinates.z), float2::Zero, lineColor); vertices[1].Set(float3(minCoordinates.x + x, maxCoordinates.y, maxCoordinates.z), float2::Zero, lineColor); AddVertices(vertices, countof(vertices)); } } if (drawLinesY > 0) { for (i = 0, y = 0.0f; i <= drawLinesY; i++, y += gridStep.y) { vertices[0].Set(float3(minCoordinates.x, minCoordinates.y + y, minCoordinates.z), float2::Zero, lineColor); vertices[1].Set(float3(maxCoordinates.x, minCoordinates.y + y, maxCoordinates.z), float2::Zero, lineColor); AddVertices(vertices, countof(vertices)); } } if (drawLinesZ > 0) { for (i = 0, z = 0.0f; i <= drawLinesZ; i++, z += gridStep.z) { vertices[0].Set(float3(minCoordinates.x, minCoordinates.y, minCoordinates.z + z), float2::Zero, lineColor); vertices[1].Set(float3(maxCoordinates.x, maxCoordinates.y, minCoordinates.z + z), float2::Zero, lineColor); AddVertices(vertices, countof(vertices)); } } if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DWireBox(const float3 &minBounds, const float3 &maxBounds, const uint32 color) { SetBatchType(BATCH_TYPE_3D_COLORED_LINES); OverlayShader::Vertex3D Vertices[24]; OverlayShader::Vertex3D *pVertex = Vertices; (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); } static void MakeSinCosTable(float *sinTable, float *cosTable, uint32 n, int32 a) { DebugAssert(n > 0); float angle = 2.0f * Y_PI / (float)a; // first sinTable[0] = 0.0f; cosTable[0] = 1.0f; // entries for (uint32 i = 1; i < n; i++) Math::SinCos(angle * (float)i, &sinTable[i], &cosTable[i]); // last sinTable[n] = 0.0f; cosTable[n] = 1.0f; } void MiniGUIContext::Draw3DWireSphere(const float3 &sphereCenter, float radius, uint32 color, uint32 slices /* = 16 */, uint32 stacks /* = 16 */) { // based on freeglut code DebugAssert(slices > 0 && stacks > 0); SetBatchType(BATCH_TYPE_3D_COLORED_LINES); // allocate storage for sin/cos table uint32 table1Size = slices + 1; uint32 table2Size = stacks * 2 + 1; float *sinTable1 = (float *)alloca(sizeof(float) * table1Size); float *cosTable1 = (float *)alloca(sizeof(float) * table1Size); float *sinTable2 = (float *)alloca(sizeof(float) * table2Size); float *cosTable2 = (float *)alloca(sizeof(float) * table2Size); // initialize sin/cos table for stacks MakeSinCosTable(sinTable1, cosTable1, stacks, -(int32)slices); MakeSinCosTable(sinTable2, cosTable2, stacks * 2, stacks * 2); // draw slices lines for each stack for (uint32 i = 1; i < stacks; i++) { float z = cosTable2[i] * radius; float r = sinTable2[i]; // create first vertex OverlayShader::Vertex3D firstVertex; OverlayShader::Vertex3D lastVertex; firstVertex.Set(float3(r * radius, 0.0f, z) + sphereCenter, float2::Zero, color); Y_memcpy(&lastVertex, &firstVertex, sizeof(lastVertex)); for (uint32 j = 1; j <= slices; j++) { float x = cosTable1[j]; float y = sinTable1[j]; // create vertex OverlayShader::Vertex3D vertex; vertex.Set(float3(x * r * radius, y * r * radius, z) + sphereCenter, float2::Zero, color); // create line m_batchVertices3D.Add(lastVertex); m_batchVertices3D.Add(vertex); // store as last Y_memcpy(&lastVertex, &vertex, sizeof(lastVertex)); } // and from last to first m_batchVertices3D.Add(lastVertex); m_batchVertices3D.Add(firstVertex); } // draw stacks lines for each slice for (uint32 i = 0; i < slices; i++) { // create first vertex OverlayShader::Vertex3D lastVertex; lastVertex.Set(float3(0.0f, 0.0f, radius) + sphereCenter, float2::Zero, color); // for each stack for (uint32 j = 1; j <= stacks; j++) { float x = cosTable1[i] * sinTable2[j]; float y = sinTable1[i] * sinTable2[j]; float z = cosTable2[j]; // create vertex OverlayShader::Vertex3D vertex; vertex.Set(float3(x, y, z) * radius + sphereCenter, float2::Zero, color); // create line m_batchVertices3D.Add(lastVertex); m_batchVertices3D.Add(vertex); // store as last Y_memcpy(&lastVertex, &vertex, sizeof(lastVertex)); } } if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DBox(const float3 &minBounds, const float3 &maxBounds, const uint32 color) { SetBatchType(BATCH_TYPE_3D_COLORED_TRIANGLES); OverlayShader::Vertex3D Vertices[36]; OverlayShader::Vertex3D *pVertex = Vertices; // front face (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); // bottom-front-left (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); // top-front-left (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); // top-front-left (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); // top-front-right // back face (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-right (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-right (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); // top-back-right // left face (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); // bottom-back-left (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); // bottom-front-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); // bottom-front-left (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); // top-front-left // right face (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); // bottom-back-right (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); // top-back-right (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); // top-back-right (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); // top-front-right // top face (pVertex++)->SetColor(minBounds.x, minBounds.y, maxBounds.z, color); // top-front-left (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); // top-front-right (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, maxBounds.z, color); // top-back-left (pVertex++)->SetColor(maxBounds.x, minBounds.y, maxBounds.z, color); // top-front-right (pVertex++)->SetColor(maxBounds.x, maxBounds.y, maxBounds.z, color); // top-back-right // bottom face (pVertex++)->SetColor(minBounds.x, minBounds.y, minBounds.z, color); // bottom-front-left (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-left (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(maxBounds.x, minBounds.y, minBounds.z, color); // bottom-front-right (pVertex++)->SetColor(minBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-left (pVertex++)->SetColor(maxBounds.x, maxBounds.y, minBounds.z, color); // bottom-back-right AddVertices(Vertices, countof(Vertices)); if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DSphere(const float3 &sphereCenter, float radius, uint32 color, uint32 slices /* = 16 */, uint32 stacks /* = 16 */) { if (m_batchType != BATCH_TYPE_3D_COLORED_TRIANGLES) { Flush(); m_batchType = BATCH_TYPE_3D_COLORED_TRIANGLES; } if (!m_manualFlushCount) Flush(); } void MiniGUIContext::Draw3DArrow(const float3 &arrowStart, const float3 &arrowDirection, float lineLength, float lineThickness, float tipLength, float tipRadius, uint32 color, uint32 tipVertexCount /* = 24 */) { // multiple draw calls, so save flush state and force manual flush PushManualFlush(); // http://www.freemancw.com/2012/06/opengl-cone-function/#code // Draw line if (lineLength > 0.0f && lineThickness > 0.0f) Draw3DLineWidth(arrowStart, arrowStart + arrowDirection * lineLength, color, lineThickness); // Draw tip if (tipLength > 0.0f && tipRadius > 0.0f) { // ensure we're drawing triangles SetBatchType(BATCH_TYPE_3D_COLORED_TRIANGLES); // get axis float3 absDirection(arrowDirection.Abs()); float3 e0; if (absDirection.x <= absDirection.y && absDirection.x <= absDirection.z) e0 = arrowDirection.Cross(float3::UnitX); else if (absDirection.y <= absDirection.x && absDirection.y <= absDirection.z) e0 = arrowDirection.Cross(float3::UnitY); else e0 = arrowDirection.Cross(float3::UnitZ); float3 e1(e0.Cross(arrowDirection)); // determine vars uint32 arrowVertexStep = 360 / tipVertexCount; float3 tipStart(arrowStart + arrowDirection * lineLength); float3 tipEnd(tipStart + arrowDirection * tipLength); // determine vertices for (uint32 i = 0; i < tipVertexCount; i++) { float sinAngle, cosAngle; float sinNextAngle, cosNextAngle; Math::SinCos(Math::DegreesToRadians((float)(arrowVertexStep * i)), &sinAngle, &cosAngle); Math::SinCos(Math::DegreesToRadians((float)(arrowVertexStep * (i + 1))), &sinNextAngle, &cosNextAngle); // vertex float3 p0(tipStart + (((e0 * cosAngle) + (e1 * sinAngle)) * tipRadius)); float3 p1(tipStart + (((e0 * cosNextAngle) + (e1 * sinNextAngle)) * tipRadius)); // build vertices OverlayShader::Vertex3D vertices[6]; // bottom part vertices[0].SetColor(tipStart.x, tipStart.y, tipStart.z, color); vertices[1].SetColor(p0.x, p0.y, p0.z, color); vertices[2].SetColor(p1.x, p1.y, p1.z, color); // top part vertices[3].SetColor(p0.x, p0.y, p0.z, color); vertices[4].SetColor(tipEnd.x, tipEnd.y, tipEnd.z, color); vertices[5].SetColor(p1.x, p1.y, p1.z, color); // add vertices AddVertices(vertices, countof(vertices)); } } PopManualFlush(); } void MiniGUIContext::DrawText(const Font *pFont, int32 size, uint32 color, const char *text) { // work out font scale float textScale = (float)size / (float)pFont->GetHeight(); // work out how many pixels we have to work with int32 widthAvailable = m_topRect.right - m_topRect.left - m_textCaretPositionX; int32 heightAvailable = m_topRect.bottom - m_topRect.top - m_textCaretPositionY; if (widthAvailable <= 0 || heightAvailable <= 0) return; // keep adding characters until we either hit the end of the line (word wrap), or finish the string int32 lineStart = 0; int32 lineLength = 0; int32 lineWidth = 0; int32 textLength = (int32)Y_strlen(text); for (int32 i = 0; i < textLength; i++) { int32 characterWidth = (int32)pFont->GetTextWidth(&text[i], 1, textScale); if ((lineWidth + characterWidth) > widthAvailable) { // draw this line if (lineLength > 0) { MINIGUI_RECT drawRect(m_topRect.left + m_textCaretPositionX, m_topRect.right, m_topRect.top + m_textCaretPositionY, m_topRect.bottom); InternalDrawText(pFont, textScale, color, &drawRect, text + lineStart, lineLength, false); lineStart += lineLength; lineLength = 0; lineWidth = 0; } // move to next line? if (m_textWordWrap) { m_textCaretPositionX = 0; m_textCaretPositionY += size; widthAvailable = m_topRect.right - m_topRect.left - m_textCaretPositionX; heightAvailable = m_topRect.bottom - m_topRect.top - m_textCaretPositionY; if (widthAvailable <= 0 || heightAvailable <= 0) return; } else { // don't draw any more return; } } // add this character lineLength++; lineWidth += characterWidth; } // anything left-over? if (lineLength > 0) { MINIGUI_RECT drawRect(m_topRect.left + m_textCaretPositionX, m_topRect.right, m_topRect.top + m_textCaretPositionY, m_topRect.bottom); InternalDrawText(pFont, textScale, color, &drawRect, text + lineStart, lineLength, false); } } void MiniGUIContext::DrawFormattedText(const Font *pFont, int32 size, uint32 color, const char *format, ...) { SmallString str; va_list ap; va_start(ap, format); str.FormatVA(format, ap); DrawText(pFont, size, color, str); va_end(ap); } void MiniGUIContext::DrawTextAt(int32 x, int32 y, const Font *pFont, int32 size, uint32 color, const char *text) { // backup the old caret position int32 oldCaretPositionX = m_textCaretPositionX; int32 oldCaretPositionY = m_textCaretPositionY; // set new caret position to x/y m_textCaretPositionX = x; m_textCaretPositionY = y; // draw the text DrawText(pFont, size, color, text); // restore caret positio m_textCaretPositionX = oldCaretPositionX; m_textCaretPositionY = oldCaretPositionY; } void MiniGUIContext::DrawFormattedTextAt(int32 x, int32 y, const Font *pFont, int32 size, uint32 color, const char *format, ...) { SmallString str; va_list ap; va_start(ap, format); str.FormatVA(format, ap); DrawTextAt(x, y, pFont, size, color, str); va_end(ap); } <file_sep>/Engine/Source/Engine/BlockPalette.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockPalette.h" #include "Engine/StaticMesh.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" #include "Renderer/Renderer.h" #include "Core/ChunkFileReader.h" Log_SetChannel(BlockPalette); BlockPalette::BlockPalette() { uint32 i; BlockPalette::BlockType *pBlockType; for (i = 0; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { pBlockType = &m_BlockTypes[i]; pBlockType->IsAllocated = false; pBlockType->BlockTypeIndex = i; pBlockType->Flags = 0; pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE; Y_memzero(pBlockType->CubeShapeFaces, sizeof(pBlockType->CubeShapeFaces)); Y_memzero(&pBlockType->SlabShapeSettings, sizeof(pBlockType->SlabShapeSettings)); Y_memzero(&pBlockType->PlaneShapeSettings, sizeof(pBlockType->PlaneShapeSettings)); Y_memzero(&pBlockType->MeshShapeSettings, sizeof(pBlockType->MeshShapeSettings)); Y_memzero(&pBlockType->BlockLightEmitterSettings, sizeof(pBlockType->BlockLightEmitterSettings)); Y_memzero(&pBlockType->PointLightEmitterSettings, sizeof(pBlockType->PointLightEmitterSettings)); } // setup blocktype 0 pBlockType = &m_BlockTypes[0]; pBlockType->Name = "___NONE___"; pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE; } BlockPalette::~BlockPalette() { uint32 i; for (i = 0; i < m_materials.GetSize(); i++) { const Material *pMaterial = m_materials[i]; if (pMaterial != NULL) pMaterial->Release(); } for (i = 0; i < m_textures.GetSize(); i++) { const Texture *pTexture = m_textures[i]; if (pTexture != NULL) pTexture->Release(); } for (i = 0; i < m_meshes.GetSize(); i++) { const StaticMesh *pStaticMesh = m_meshes[i]; if (pStaticMesh != NULL) pStaticMesh->Release(); } } bool BlockPalette::Load(const char *FileName, ByteStream *pStream) { PathString tempString; #define ABORTREASON(Reason) Log_ErrorPrintf("Could not load BlockPalette '%s': %s", FileName, Reason) // set name m_strName = FileName; // read header DF_BLOCK_PALETTE_LIST_HEADER blockListHeader; if (!pStream->Read2(&blockListHeader, sizeof(blockListHeader))) return false; // validate header if (blockListHeader.Magic != DF_BLOCK_PALETTE_HEADER_MAGIC || blockListHeader.HeaderSize != sizeof(blockListHeader)) { return false; } // init chunkloader ChunkFileReader chunkReader; if (!chunkReader.Initialize(pStream)) return false; // load block types uint32 nBlockTypes = blockListHeader.BlockTypeCount; if (nBlockTypes > 0 && chunkReader.LoadChunk(DF_BLOCK_PALETTE_CHUNK_BLOCK_TYPES) && chunkReader.GetCurrentChunkTypeCount<DF_BLOCK_PALETTE_BLOCK_TYPE>() == nBlockTypes) { const DF_BLOCK_PALETTE_BLOCK_TYPE *pSourceBlockType = chunkReader.GetCurrentChunkTypePointer<DF_BLOCK_PALETTE_BLOCK_TYPE>(); for (uint32 i = 0; i < nBlockTypes; i++, pSourceBlockType++) { if (pSourceBlockType->BlockTypeIndex == 0 || pSourceBlockType->BlockTypeIndex >= BLOCK_MESH_MAX_BLOCK_TYPES || m_BlockTypes[pSourceBlockType->BlockTypeIndex].IsAllocated) { ABORTREASON("invalid block type index"); return false; } BlockPalette::BlockType *pDestinationBlockType = &m_BlockTypes[pSourceBlockType->BlockTypeIndex]; pDestinationBlockType->IsAllocated = true; pDestinationBlockType->Name = chunkReader.GetStringByIndex(pSourceBlockType->NameStringIndex); pDestinationBlockType->Flags = pSourceBlockType->Flags; pDestinationBlockType->ShapeType = (BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE)pSourceBlockType->ShapeType; if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB || pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) pDestinationBlockType->SlabShapeSettings.Height = pSourceBlockType->SlabSettings.Height; for (uint32 j = 0; j < CUBE_FACE_COUNT; j++) { const DF_BLOCK_PALETTE_BLOCK_TYPE::CubeShapeFace *inCubeFaceDef = &pSourceBlockType->CubeShapeFaces[j]; BlockPalette::BlockType::CubeShapeFace *outCubeFaceDef = &pDestinationBlockType->CubeShapeFaces[j]; outCubeFaceDef->Visual.Type = (BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE)inCubeFaceDef->Visual.Type; outCubeFaceDef->Visual.MaterialIndex = inCubeFaceDef->Visual.MaterialIndex; outCubeFaceDef->Visual.Color = inCubeFaceDef->Visual.Color; outCubeFaceDef->Visual.MinUV.Load(inCubeFaceDef->Visual.MinUV); outCubeFaceDef->Visual.MaxUV.Load(inCubeFaceDef->Visual.MaxUV); outCubeFaceDef->Visual.AtlasUVRange.Load(inCubeFaceDef->Visual.AtlasUVRange); } } else if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { const DF_BLOCK_PALETTE_BLOCK_TYPE::PlaneShape &inPlaneSettings = pSourceBlockType->PlaneSettings; BlockPalette::BlockType::PlaneShape &outPlaneSettings = pDestinationBlockType->PlaneShapeSettings; outPlaneSettings.Visual.Type = (BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE)inPlaneSettings.Visual.Type; outPlaneSettings.Visual.MaterialIndex = inPlaneSettings.Visual.MaterialIndex; outPlaneSettings.Visual.Color = inPlaneSettings.Visual.Color; outPlaneSettings.Visual.MinUV.Load(inPlaneSettings.Visual.MinUV); outPlaneSettings.Visual.MaxUV.Load(inPlaneSettings.Visual.MaxUV); outPlaneSettings.Visual.AtlasUVRange.Load(inPlaneSettings.Visual.AtlasUVRange); outPlaneSettings.OffsetX = inPlaneSettings.OffsetX; outPlaneSettings.OffsetY = inPlaneSettings.OffsetY; outPlaneSettings.Width = inPlaneSettings.Width; outPlaneSettings.Height = inPlaneSettings.Height; outPlaneSettings.BaseRotation = inPlaneSettings.BaseRotation; outPlaneSettings.RepeatCount = inPlaneSettings.RepeatCount; outPlaneSettings.RepeatRotation = inPlaneSettings.RepeatRotation; } else if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { const DF_BLOCK_PALETTE_BLOCK_TYPE::MeshShape &inMeshSettings = pSourceBlockType->MeshSettings; BlockPalette::BlockType::MeshShape &outMeshSettings = pDestinationBlockType->MeshShapeSettings; outMeshSettings.MeshIndex = inMeshSettings.MeshIndex; outMeshSettings.Scale = inMeshSettings.Scale; } // block light emitter pDestinationBlockType->BlockLightEmitterSettings.Radius = pSourceBlockType->BlockLightEmitterSettings.Radius; // point light emitter pDestinationBlockType->PointLightEmitterSettings.Offset.Load(pSourceBlockType->PointLightEmitterSettings.Offset); pDestinationBlockType->PointLightEmitterSettings.Color = pSourceBlockType->PointLightEmitterSettings.Color; pDestinationBlockType->PointLightEmitterSettings.Brightness = pSourceBlockType->PointLightEmitterSettings.Brightness; pDestinationBlockType->PointLightEmitterSettings.Range = pSourceBlockType->PointLightEmitterSettings.Range; pDestinationBlockType->PointLightEmitterSettings.Falloff = pSourceBlockType->PointLightEmitterSettings.Falloff; } } else { ABORTREASON("invalid block list"); return false; } // load textures uint32 nTextures = blockListHeader.TextureCount; if (nTextures > 0) { if (chunkReader.LoadChunk(DF_BLOCK_PALETTE_CHUNK_TEXTURES) && chunkReader.GetCurrentChunkSize() >= (sizeof(DF_BLOCK_PALETTE_TEXTURE) * nTextures)) { m_textures.Resize(nTextures); Y_memzero(m_textures.GetBasePointer(), sizeof(const Texture *) * nTextures); const byte *pChunkBasePointer = (const byte *)chunkReader.GetCurrentChunkPointer(); uint32 chunkSize = chunkReader.GetCurrentChunkSize(); const DF_BLOCK_PALETTE_TEXTURE *pTextureHeader = (const DF_BLOCK_PALETTE_TEXTURE *)pChunkBasePointer; for (uint32 i = 0; i < nTextures; i++, pTextureHeader++) { // validate range if ((pTextureHeader->TextureOffset + pTextureHeader->TextureSize) > chunkSize || pTextureHeader->TextureSize == 0) { ABORTREASON("corrupted texture chunk"); return false; } // create stream AutoReleasePtr<ByteStream> pTextureStream = ByteStream_CreateReadOnlyMemoryStream(pChunkBasePointer + pTextureHeader->TextureOffset, pTextureHeader->TextureSize); DebugAssert(pTextureStream != NULL); // work out texture type TEXTURE_TYPE textureType = Texture::GetTextureTypeForStream("BLOCKLIST_INTERNAL_TEXTURE", pTextureStream); if (textureType == TEXTURE_TYPE_COUNT) { ABORTREASON("corrupted internal texture"); return false; } // create an internal texture Texture *pInternalTexture = Texture::CreateTextureObjectForType(textureType); DebugAssert(pInternalTexture != NULL); // gen texture name tempString.Format("%s:InternalTexture%u", m_strName.GetCharArray(), i); // load it if (!pInternalTexture->Load(tempString, pTextureStream)) { ABORTREASON("corrupted internal texture"); pInternalTexture->Release(); return false; } // store it m_textures[i] = pInternalTexture; } } else { ABORTREASON("invalid texture chunk"); return false; } } // load materials uint32 nMaterials = blockListHeader.MaterialCount; if (nMaterials > 0) { if (chunkReader.LoadChunk(DF_BLOCK_PALETTE_CHUNK_MATERIALS) && chunkReader.GetCurrentChunkTypeCount<DF_BLOCK_PALETTE_MATERIAL>() == nMaterials) { m_materials.Resize(nMaterials); Y_memzero(m_materials.GetBasePointer(), sizeof(const Material *) * nMaterials); const DF_BLOCK_PALETTE_MATERIAL *pSourceMaterial = chunkReader.GetCurrentChunkTypePointer<DF_BLOCK_PALETTE_MATERIAL>(); for (uint32 i = 0; i < nMaterials; i++, pSourceMaterial++) { DebugAssert(pSourceMaterial->MaterialType < DF_BLOCK_PALETTE_MATERIAL_TYPE_COUNT); // validate everything is in range if ((pSourceMaterial->DiffuseMapTextureIndex != 0xFFFFFFFF && pSourceMaterial->DiffuseMapTextureIndex >= m_textures.GetSize()) || (pSourceMaterial->SpecularMapTextureIndex != 0xFFFFFFFF && pSourceMaterial->SpecularMapTextureIndex >= m_textures.GetSize()) || (pSourceMaterial->NormalMapTextureIndex != 0xFFFFFFFF && pSourceMaterial->NormalMapTextureIndex >= m_textures.GetSize())) { ABORTREASON("internal material has out-of-range texture indices"); return false; } // lookup supershader if (pSourceMaterial->MaterialType == DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL) { // external material if ((m_materials[i] = g_pResourceManager->GetMaterial(chunkReader.GetStringByIndex(pSourceMaterial->MaterialNameStringIndex))) == NULL) m_materials[i] = g_pResourceManager->GetDefaultMaterial(); } else { // autogen materials // material name array const char *materialNames[DF_BLOCK_PALETTE_MATERIAL_TYPE_COUNT] = { NULL, // DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL "shaders/engine/block_mesh/color", // DF_BLOCK_PALETTE_MATERIAL_TYPE_COLOR "shaders/engine/block_mesh/translucent_color", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_COLOR "shaders/engine/block_mesh/texture", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE "shaders/engine/block_mesh/texture_array", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY "shaders/engine/block_mesh/texture_atlas", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS "shaders/engine/block_mesh/masked_texture", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE "shaders/engine/block_mesh/masked_texture_array", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY "shaders/engine/block_mesh/masked_texture_atlas", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS "shaders/engine/block_mesh/translucent_texture", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE "shaders/engine/block_mesh/translucent_texture_array", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY "shaders/engine/block_mesh/translucent_texture_atlas", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS "shaders/engine/block_mesh/texture_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_WITH_NORMAL_MAP "shaders/engine/block_mesh/texture_array_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY_WITH_NORMAL_MAP "shaders/engine/block_mesh/texture_atlas_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS_WITH_NORMAL_MAP "shaders/engine/block_mesh/masked_texture_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_WITH_NORMAL_MAP "shaders/engine/block_mesh/masked_texture_array_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY_WITH_NORMAL_MAP "shaders/engine/block_mesh/masked_texture_atlas_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS_WITH_NORMAL_MAP "shaders/engine/block_mesh/translucent_texture_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_WITH_NORMAL_MAP "shaders/engine/block_mesh/translucent_texture_array_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY_WITH_NORMAL_MAP "shaders/engine/block_mesh/translucent_texture_atlas_with_normal_map", // DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS_WITH_NORMAL_MAP }; // get shader AutoReleasePtr<const MaterialShader> pMaterialShader = g_pResourceManager->GetMaterialShader(materialNames[pSourceMaterial->MaterialType]); // found? if (pMaterialShader == NULL) { // use default material as a fallback Log_WarningPrintf("Unable to load blockmesh material shader %s, using default", materialNames[pSourceMaterial->MaterialType]); m_materials[i] = g_pResourceManager->GetDefaultMaterial(); } else { // autogen material Material *pInternalMaterial = new Material(); pInternalMaterial->Create(chunkReader.GetStringByIndex(pSourceMaterial->MaterialNameStringIndex), pMaterialShader); // static switches if (pSourceMaterial->MaterialFlags & DF_BLOCK_PALETTE_MATERIAL_FLAG_SCROLLED_TEXTURE) pInternalMaterial->SetShaderStaticSwitchParameterByName("EnableTextureScrolling", true); else if (pSourceMaterial->MaterialFlags & DF_BLOCK_PALETTE_MATERIAL_FLAG_ANIMATED_TEXTURE) pInternalMaterial->SetShaderStaticSwitchParameterByName("EnableTextureAnimation", true); // blend vertex colours on everything for now pInternalMaterial->SetShaderStaticSwitchParameterByName("BlendVertexColors", true); // bind textures // diffuse if (pSourceMaterial->DiffuseMapTextureIndex != 0xFFFFFFFF) { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseDiffuseMap", true); pInternalMaterial->SetShaderTextureParameterByName("DiffuseMap", m_textures[pSourceMaterial->DiffuseMapTextureIndex]); } else { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseDiffuseMap", false); } // specular if (pSourceMaterial->SpecularMapTextureIndex != 0xFFFFFFFF) { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseSpecularMap", true); pInternalMaterial->SetShaderTextureParameterByName("SpecularMap", m_textures[pSourceMaterial->SpecularMapTextureIndex]); } else { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseSpecularMap", false); } // normal if (pSourceMaterial->NormalMapTextureIndex != 0xFFFFFFFF) { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseNormalMap", true); pInternalMaterial->SetShaderTextureParameterByName("NormalMap", m_textures[pSourceMaterial->NormalMapTextureIndex]); } else { pInternalMaterial->SetShaderStaticSwitchParameterByName("UseNormalMap", false); } // scroll vector pInternalMaterial->SetShaderUniformParameterByName("ScrollVector", SHADER_PARAMETER_TYPE_FLOAT2, float2(pSourceMaterial->TextureScrollVector)); // store internal material m_materials[i] = pInternalMaterial; } } } } else { ABORTREASON("invalid material chunk"); return false; } } // load meshes uint32 nMeshes = blockListHeader.MeshCount; if (nMeshes > 0) { if (chunkReader.LoadChunk(DF_BLOCK_PALETTE_CHUNK_MESHES) && chunkReader.GetCurrentChunkTypeCount<DF_BLOCK_PALETTE_MESH>() == nMeshes) { m_meshes.Resize(nMeshes); m_meshes.ZeroContents(); const DF_BLOCK_PALETTE_MESH *pSourceMesh = chunkReader.GetCurrentChunkTypePointer<DF_BLOCK_PALETTE_MESH>(); for (uint32 i = 0; i < nMeshes; i++, pSourceMesh++) { if ((m_meshes[i] = g_pResourceManager->GetStaticMesh(chunkReader.GetStringByIndex(pSourceMesh->MeshNameStringIndex))) == NULL) m_meshes[i] = g_pResourceManager->GetDefaultStaticMesh(); } } else { ABORTREASON("invalid mesh chunk"); return false; } } // validate that everything points to valid ranges @todo move this to the compiler for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { const BlockPalette::BlockType *pBlockType = &m_BlockTypes[i]; if (!pBlockType->IsAllocated) continue; switch (pBlockType->ShapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE: break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB: { if (pBlockType->SlabShapeSettings.Height <= 0.0f || pBlockType->SlabShapeSettings.Height > 1.0f) { ABORTREASON("invalid slab height"); return false; } } // break deliberately ommitted to fall through //break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE: case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS: { for (uint32 j = 0; j < CUBE_FACE_COUNT; j++) { if (pBlockType->CubeShapeFaces[j].Visual.MaterialIndex >= m_materials.GetSize()) { ABORTREASON("block type has out-of-range material"); return false; } } } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE: { if (pBlockType->PlaneShapeSettings.Visual.MaterialIndex >= m_materials.GetSize()) { ABORTREASON("block type has out-of-range material"); return false; } } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH: { if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH && pBlockType->MeshShapeSettings.MeshIndex >= m_meshes.GetSize()) { ABORTREASON("block type has out-of-range mesh"); return false; } } break; default: { ABORTREASON("unhandled block visual type"); return false; } break; } } #undef ABORTREASON // create on gpu if (g_pRenderer != nullptr && !CreateGPUResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } const BlockPalette::BlockType *BlockPalette::GetBlockTypeByName(const char *name) const { for (uint32 i = 0; i < countof(m_BlockTypes); i++) { if (m_BlockTypes[i].Name.Compare(name)) return &m_BlockTypes[i]; } return nullptr; } bool BlockPalette::CreateGPUResources() const { for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (!m_textures[i]->CreateDeviceResources()) return false; } for (uint32 i = 0; i < m_materials.GetSize(); i++) { if (!m_materials[i]->CreateDeviceResources()) return false; } for (uint32 i = 0; i < m_meshes.GetSize(); i++) { if (!m_meshes[i]->CreateGPUResources()) return false; } return true; } void BlockPalette::ReleaseGPUResources() const { for (uint32 i = 0; i < m_materials.GetSize(); i++) m_materials[i]->ReleaseDeviceResources(); for (uint32 i = 0; i < m_textures.GetSize(); i++) m_textures[i]->ReleaseDeviceResources(); } <file_sep>/Engine/Source/Renderer/Renderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Renderer.h" #include "Engine/ResourceManager.h" #include "Engine/Font.h" #include "Engine/Material.h" #include "Engine/MaterialShader.h" #include "Engine/Camera.h" #include "Engine/World.h" #include "Engine/Texture.h" #include "Engine/EngineCVars.h" #include "Engine/Engine.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderConstantBuffer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/Shaders/OverlayShader.h" #include "Renderer/Shaders/TextureBlitShader.h" #include "Renderer/Shaders/DownsampleShader.h" #include "Engine/SDLHeaders.h" Log_SetChannel(Renderer); // fix up a warning #ifdef SDL_VIDEO_DRIVER_WINDOWS #undef WIN32_LEAN_AND_MEAN #endif #include <SDL/SDL_syswm.h> // Calculates the scissor rectangle for a given point light. // If this returns false, it means the light is not present on the screen at all. // bool CalculatePointLightScissor(const Vector3 &LightPosition, float LightRadius, const Matrix4 &ViewMatrix, const Matrix4 &ProjectionMatrix, float NearDistance, RENDERER_SCISSOR_RECT *pScissorRect); // bool CalculateAABoxScissor(const AABox &aabBounds, const Matrix4 &ViewMatrix, const Matrix4 &ProjectionMatrix, RENDERER_SCISSOR_RECT *pScissorRect); //----------------------------------------------------- RenderSystem Creation Functions ----------------------------------------------------------------------------------------------- // renderer creation functions typedef bool(*RendererFactoryFunction)(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer); #if defined(WITH_RENDERER_D3D11) extern bool D3D11RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer); #endif #if defined(WITH_RENDERER_D3D12) extern bool D3D12RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer); #endif #if defined(WITH_RENDERER_OPENGL) extern bool OpenGLRenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer); #endif #if defined(WITH_RENDERER_OPENGLES2) extern bool OpenGLES2RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer); #endif struct RENDERER_PLATFORM_FACTORY_FUNCTION { RENDERER_PLATFORM Platform; RendererFactoryFunction Function; bool RequiresImplicitSwapChain; }; static const RENDERER_PLATFORM_FACTORY_FUNCTION s_renderSystemDeclarations[] = { #if defined(WITH_RENDERER_D3D11) { RENDERER_PLATFORM_D3D11, D3D11RenderBackend_Create, false }, #endif #if defined(WITH_RENDERER_D3D12) { RENDERER_PLATFORM_D3D12, D3D12RenderBackend_Create, false }, #endif #if defined(WITH_RENDERER_OPENGL) { RENDERER_PLATFORM_OPENGL, OpenGLRenderBackend_Create, true }, #endif #if defined(WITH_RENDERER_OPENGLES2) { RENDERER_PLATFORM_OPENGLES2, OpenGLES2RenderBackend_Create, true }, #endif }; //----------------------------------------------------- Global Variables ---------------------------------------------------------------------------------------------------------- // active renderer pointer Renderer *g_pRenderer = NULL; Thread::ThreadIdType Renderer::s_renderThreadId = static_cast<Thread::ThreadIdType>(0); TaskQueue Renderer::s_renderCommandQueue; TaskQueue Renderer::s_renderWorkerCommandQueue; //----------------------------------------------------- Output Window Class ---------------------------------------------------------------------------------------------------------- RendererOutputWindow::RendererOutputWindow(SDL_Window *pSDLWindow, GPUOutputBuffer *pBuffer, RENDERER_FULLSCREEN_STATE fullscreenState) : m_pSDLWindow(pSDLWindow), m_pOutputBuffer(pBuffer), m_fullscreenState(fullscreenState), m_hasFocus(true), m_visible(true), m_title(SDL_GetWindowTitle(pSDLWindow)), m_mouseGrabbed(false), m_mouseRelativeMovement(false) { SDL_GetWindowPosition(m_pSDLWindow, &m_positionX, &m_positionY); SDL_GetWindowSize(m_pSDLWindow, reinterpret_cast<int *>(&m_width), reinterpret_cast<int *>(&m_height)); } RendererOutputWindow::~RendererOutputWindow() { // Buffer should no longer be used if (m_pOutputBuffer != nullptr) { uint32 bufferReferenceCount = m_pOutputBuffer->Release(); Assert(bufferReferenceCount == 0); } // Destroy window itself SDL_DestroyWindow(m_pSDLWindow); } void RendererOutputWindow::SetWindowTitle(const char *title) { DebugAssert(Renderer::IsOnRenderThread()); m_title = title; SDL_SetWindowTitle(m_pSDLWindow, title); } void RendererOutputWindow::SetWindowVisibility(bool visible) { DebugAssert(Renderer::IsOnRenderThread()); m_visible = visible; if (visible) SDL_ShowWindow(m_pSDLWindow); else SDL_HideWindow(m_pSDLWindow); } void RendererOutputWindow::SetWindowPosition(int32 x, int32 y) { DebugAssert(Renderer::IsOnRenderThread()); SDL_SetWindowPosition(m_pSDLWindow, x, y); SDL_GetWindowPosition(m_pSDLWindow, &m_positionX, &m_positionY); } void RendererOutputWindow::SetWindowSize(uint32 width, uint32 height) { DebugAssert(Renderer::IsOnRenderThread()); SDL_SetWindowSize(m_pSDLWindow, width, height); SDL_GetWindowSize(m_pSDLWindow, reinterpret_cast<int *>(&m_width), reinterpret_cast<int *>(&m_height)); } void RendererOutputWindow::SetMouseGrab(bool enabled) { DebugAssert(Renderer::IsOnRenderThread()); SDL_SetWindowGrab(m_pSDLWindow, (enabled) ? SDL_TRUE : SDL_FALSE); } void RendererOutputWindow::SetMouseRelativeMovement(bool enabled) { DebugAssert(Renderer::IsOnRenderThread()); if (enabled) { SDL_RaiseWindow(m_pSDLWindow); SDL_SetRelativeMouseMode(SDL_TRUE); } else { SDL_SetRelativeMouseMode(SDL_FALSE); } } //----------------------------------------------------- Init/Startup/Shutdown ----------------------------------------------------------------------------------------------------- RENDERER_PLATFORM Renderer::GetDefaultPlatform() { #if defined(Y_PLATFORM_WINDOWS) return RENDERER_PLATFORM_D3D11; #elif defined(Y_PLATFORM_LINUX) || defined(Y_PLATFORM_OSX) return RENDERER_PLATFORM_OPENGL; #elif defined(Y_PLATFORM_ANDROID) || defined(Y_PLATFORM_IOS) || defined(Y_PLATFORM_HTML5) return RENDERER_PLATFORM_OPENGLES2; #else return RENDERER_PLATFORM_OPENGL; #endif } bool Renderer::StartRenderThread(bool createWorkerThread) { // TODO: Make use of command buffer optional //uint32 commandBufferSize = CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE * 4; uint32 commandBufferSize = (createWorkerThread) ? CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE * 4 : 0; uint32 workerThreadCount = (createWorkerThread) ? 1 : 0; if (createWorkerThread) Log_InfoPrintf(" Creating render thread with a command buffer of %u bytes", commandBufferSize); else //Log_PerfPrintf(" Not using threaded rendering. Creating a command buffer of %u bytes.", commandBufferSize); Log_PerfPrintf(" Not using threaded rendering.", commandBufferSize); if (!s_renderCommandQueue.Initialize(commandBufferSize, workerThreadCount)) { Log_ErrorPrintf(" Failed to create renderer worker thread."); return false; } s_renderThreadId = (createWorkerThread) ? s_renderCommandQueue.GetWorkerThreadID(0) : Thread::GetCurrentThreadId(); Log_DevPrintf(" Renderer is owned by thread ID %u", (uint32)s_renderThreadId); return true; } void Renderer::StopRenderThread() { Log_InfoPrintf("Shutting down render thread..."); s_renderCommandQueue.ExitWorkers(); } bool Renderer::Create(const RendererInitializationParameters *pCreateParameters) { Assert(g_pRenderer == nullptr); Assert(pCreateParameters != nullptr); // apply cvar changes Log_DevPrintf("Applying pending renderer cvar changes..."); g_pConsole->ApplyPendingRenderCVars(); // if we were compiled with resource compiler, ensure the shader compiler is ready-to-go #if defined(WITH_RESOURCECOMPILER_EMBEDDED) || defined(WITH_RESOURCECOMPILER_SUBPROCESS) ShaderCompilerFrontend::InitializeShaderCompilerSupport(); #endif // create start Log_InfoPrint("------- Renderer::Create() -------"); Log_DevPrintf("Platform: %s", NameTable_GetNameString(NameTables::RendererPlatformFullName, pCreateParameters->Platform)); Log_DevPrintf("Render thread is %s", pCreateParameters->EnableThreadedRendering ? "enabled" : "disabled"); Log_DevPrintf("Backbuffer format: %s", PixelFormat_GetPixelFormatName(pCreateParameters->BackBufferFormat)); Log_DevPrintf("Depth-stencil format: %s", PixelFormat_GetPixelFormatName(pCreateParameters->DepthStencilBufferFormat)); Log_DevPrintf("Implicit window is %s", pCreateParameters->HideImplicitSwapChain ? "hidden" : ((pCreateParameters->ImplicitSwapChainFullScreen == RENDERER_FULLSCREEN_STATE_FULLSCREEN) ? "fullscreen" : "windowed")); Log_DevPrintf("Implicit window dimensions: %ux%u", pCreateParameters->ImplicitSwapChainWidth, pCreateParameters->ImplicitSwapChainHeight); // create render thread StartRenderThread(pCreateParameters->EnableThreadedRendering); // event that gets triggered once the renderer is created, or creation fails QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([pCreateParameters]() { // initialize video subsystem static bool sdlVideoSubSystemInitialized = false; if (!sdlVideoSubSystemInitialized) { Log_DevPrintf(" Calling SDL_Init(SDL_INIT_VIDEO)..."); if (SDL_Init(SDL_INIT_VIDEO) < 0) { Log_ErrorPrintf(" Failed to initialize SDL video subsystem: %s", SDL_GetError()); return; } sdlVideoSubSystemInitialized = true; } // output window flags uint32 windowFlags = SDL_WINDOW_RESIZABLE; if (pCreateParameters->HideImplicitSwapChain) windowFlags |= SDL_WINDOW_HIDDEN; else windowFlags |= SDL_WINDOW_SHOWN; if (pCreateParameters->ImplicitSwapChainFullScreen == RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN) windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; // Try the preferred renderer first bool backendInitialized = false; SDL_Window *pSDLWindow = nullptr; GPUDevice *pDevice = nullptr; GPUContext *pImmediateContext = nullptr; GPUOutputBuffer *pOutputBuffer = nullptr; Log_InfoPrintf(" Requested renderer: %s", NameTable_GetNameString(NameTables::RendererPlatform, pCreateParameters->Platform)); for (uint32 i = 0; i < countof(s_renderSystemDeclarations); i++) { if (s_renderSystemDeclarations[i].Platform == pCreateParameters->Platform) { // create output window if (!pCreateParameters->HideImplicitSwapChain || s_renderSystemDeclarations[i].RequiresImplicitSwapChain) { // fix flags for opengl if (s_renderSystemDeclarations[i].RequiresImplicitSwapChain) windowFlags |= SDL_WINDOW_OPENGL; else windowFlags &= ~SDL_WINDOW_OPENGL; Log_DevPrintf(" Creating implicit output window..."); pSDLWindow = SDL_CreateWindow(pCreateParameters->ImplicitSwapChainCaption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pCreateParameters->ImplicitSwapChainWidth, pCreateParameters->ImplicitSwapChainHeight, windowFlags); if (pSDLWindow == nullptr) { Log_ErrorPrintf(" Failed to create implicit output window."); return; } } Log_InfoPrintf(" Creating \"%s\" render backend...", NameTable_GetNameString(NameTables::RendererPlatform, s_renderSystemDeclarations[i].Platform)); backendInitialized = s_renderSystemDeclarations[i].Function(pCreateParameters, pSDLWindow, &pDevice, &pImmediateContext, &pOutputBuffer); if (!backendInitialized && pSDLWindow != nullptr) { SDL_DestroyWindow(pSDLWindow); pSDLWindow = nullptr; } break; } } if (!backendInitialized) { Log_ErrorPrintf(" Unknown render backend or failed to create: %s", NameTable_GetNameString(NameTables::RendererPlatform, pCreateParameters->Platform)); for (uint32 i = 0; i < countof(s_renderSystemDeclarations); i++) { // no point creating the same thing again if (s_renderSystemDeclarations[i].Platform != pCreateParameters->Platform) { // create output window if (!pCreateParameters->HideImplicitSwapChain || s_renderSystemDeclarations[i].RequiresImplicitSwapChain) { // fix flags for opengl if (s_renderSystemDeclarations[i].RequiresImplicitSwapChain) windowFlags |= SDL_WINDOW_OPENGL; else windowFlags &= ~SDL_WINDOW_OPENGL; Log_DevPrintf(" Creating implicit output window..."); pSDLWindow = SDL_CreateWindow(pCreateParameters->ImplicitSwapChainCaption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pCreateParameters->ImplicitSwapChainWidth, pCreateParameters->ImplicitSwapChainHeight, windowFlags); if (pSDLWindow == nullptr) { Log_ErrorPrintf(" Failed to create implicit output window."); return; } } Log_InfoPrintf(" Creating \"%s\" render backend...", NameTable_GetNameString(NameTables::RendererPlatform, s_renderSystemDeclarations[i].Platform)); backendInitialized = s_renderSystemDeclarations[i].Function(pCreateParameters, pSDLWindow, &pDevice, &pImmediateContext, &pOutputBuffer); if (backendInitialized) break; if (pSDLWindow != nullptr) { SDL_DestroyWindow(pSDLWindow); pSDLWindow = nullptr; } } } } if (!backendInitialized) { Log_ErrorPrintf(" No renderer backend was created."); SDL_DestroyWindow(pSDLWindow); return; } // create window wrapper class RendererOutputWindow *pOutputWindow = nullptr; if (pOutputBuffer != nullptr) pOutputWindow = new RendererOutputWindow(pSDLWindow, pOutputBuffer, RENDERER_FULLSCREEN_STATE_WINDOWED); // create renderer object g_pRenderer = new Renderer(pDevice, pImmediateContext, pOutputWindow); // do base startup if (!g_pRenderer->BaseOnStart()) { // cleanup renderer Log_ErrorPrintf(" Renderer backend creation succeeded, but renderer startup failed."); g_pRenderer->BaseOnShutdown(); delete g_pRenderer; g_pRenderer = nullptr; // cleanup backend pImmediateContext->Release(); pDevice->Release(); if (pOutputBuffer != nullptr) { pOutputWindow->SetOutputBuffer(nullptr); pOutputBuffer->Release(); } if (pOutputWindow != nullptr) pOutputWindow->Release(); return; } // attempt to switch to exclusive fullscreen if possible if (pCreateParameters->ImplicitSwapChainFullScreen != RENDERER_FULLSCREEN_STATE_WINDOWED) { Log_DevPrintf(" Attempting to switch to fullscreen..."); g_pRenderer->ChangeResolution(RENDERER_FULLSCREEN_STATE_FULLSCREEN, pCreateParameters->ImplicitSwapChainWidth, pCreateParameters->ImplicitSwapChainHeight, 60); } // clear state ready for rendering pImmediateContext->ClearState(true, true, true, true); }); // fail? if (g_pRenderer == nullptr) { Log_ErrorPrintf(" No renderer could be created."); StopRenderThread(); return false; } // create render workers if (!s_renderWorkerCommandQueue.Initialize(TaskQueue::DefaultQueueSize, 4)) { Log_ErrorPrintf(" Can't create render worker threads."); g_pRenderer->Shutdown(); return false; } Log_InfoPrint("-----------------------------------"); return true; } void Renderer::Shutdown() { DebugAssert(g_pRenderer != nullptr); Log_InfoPrint("------ Renderer::Shutdown() -------"); // has to be executed on the render thread QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([]() { // save backend interface pointer RendererOutputWindow *pOutputWindow = g_pRenderer->m_pImplicitOutputWindow; GPUOutputBuffer *pOutputBuffer = pOutputWindow->GetOutputBuffer(); GPUDevice *pDevice = g_pRenderer->m_pDevice; GPUContext *pImmediateContext = g_pRenderer->m_pImmediateContext; // window has to be swapped out to release later if (pOutputWindow != nullptr) pOutputWindow->SetOutputBuffer(nullptr); // shutdown renderer part (it doesn't release the context/device pointers) g_pRenderer->BaseOnShutdown(); delete g_pRenderer; g_pRenderer = nullptr; // release output buffer if (pOutputBuffer != nullptr) pOutputBuffer->Release(); // release context pImmediateContext->Release(); // releasing the device should remove the last reference. uint32 refCount = pDevice->Release(); if (refCount != 0) Log_ErrorPrintf("GPU resource leak detected: device still has references after shutdown."); // now the window can be freed if (pOutputWindow != nullptr) pOutputWindow->Release(); }); Log_InfoPrint("-----------------------------------"); } Renderer::Renderer(GPUDevice *pDevice, GPUContext *pImmediateContext, RendererOutputWindow *pOutputWindow) : m_fixedResources(this) , m_pDevice(pDevice) , m_pImmediateContext(pImmediateContext) , m_pImplicitOutputWindow(pOutputWindow) , m_outstandingCommandListCount(0) { m_eRendererPlatform = pDevice->GetPlatform(); m_eRendererFeatureLevel = pDevice->GetFeatureLevel(); m_eTexturePlatform = pDevice->GetTexturePlatform(); // default caps, supports nothing Y_memzero(&m_capabilities, sizeof(m_capabilities)); pDevice->GetCapabilities(&m_capabilities); } Renderer::~Renderer() { } bool Renderer::BaseOnStart() { // set render thread id s_renderThreadId = Thread::GetCurrentThreadId(); // states if (!m_fixedResources.CreateResources()) { m_fixedResources.ReleaseResources(); return false; } // resource manager g_pResourceManager->CreateDeviceResources(); // init gui context m_guiContext.SetGPUContext(GetGPUContext()); m_guiContext.SetViewportDimensions(GetGPUContext()->GetViewport()); // ok return true; } void Renderer::BaseOnShutdown() { // clear all state GetGPUContext()->ClearState(true, true, true, true); // release resources m_fixedResources.ReleaseResources(); // release gpu resources on all managed resources g_pResourceManager->ReleaseDeviceResources(); // release all non-material shaders m_nullMaterialShaderMap.ReleaseGPUResources(); // free command list pool Assert(m_outstandingCommandListCount == 0); while (m_freeCommandListPool.GetSize() > 0) { GPUCommandList *pCommandList = m_freeCommandListPool.PopFront(); pCommandList->Release(); } } GPUContext *Renderer::GetGPUContext() const { DebugAssert(IsOnRenderThread()); return m_pImmediateContext; } RendererCounters::RendererCounters() : m_frameNumber(0) , m_drawCallCounter(0) , m_shaderChangeCounter(0) , m_pipelineChangeCounter(0) , m_framesDroppedCounter(0) { Y_memzero((void *)m_resourceCPUMemoryUsage, sizeof(m_resourceCPUMemoryUsage)); Y_memzero((void *)m_resourceGPUMemoryUsage, sizeof(m_resourceGPUMemoryUsage)); } RendererCounters::~RendererCounters() { } void RendererCounters::ResetPerFrameCounters() { m_frameNumber++; m_drawCallCounter = 0; m_shaderChangeCounter = 0; } void RendererCounters::OnResourceCreated(const GPUResource *pResource) { GPU_RESOURCE_TYPE type = pResource->GetResourceType(); uint32 cpuMemoryUsage, gpuMemoryUsage; pResource->GetMemoryUsage(&cpuMemoryUsage, &gpuMemoryUsage); Y_AtomicAdd(m_resourceCPUMemoryUsage[type], (ptrdiff_t)cpuMemoryUsage); Y_AtomicAdd(m_resourceGPUMemoryUsage[type], (ptrdiff_t)gpuMemoryUsage); } void RendererCounters::OnResourceDeleted(const GPUResource *pResource) { GPU_RESOURCE_TYPE type = pResource->GetResourceType(); uint32 cpuMemoryUsage, gpuMemoryUsage; pResource->GetMemoryUsage(&cpuMemoryUsage, &gpuMemoryUsage); Y_AtomicAdd(m_resourceCPUMemoryUsage[type], -(ptrdiff_t)cpuMemoryUsage); Y_AtomicAdd(m_resourceGPUMemoryUsage[type], -(ptrdiff_t)gpuMemoryUsage); } bool Renderer::CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat /*= NULL*/) const { return m_pDevice->CheckTexturePixelFormatCompatibility(PixelFormat, CompatibleFormat); } RendererOutputWindow *Renderer::CreateOutputWindow(const char *windowTitle, uint32 windowWidth, uint32 windowHeight, RENDERER_VSYNC_TYPE vsyncType) { // Determine SDL window flags uint32 sdlWindowFlags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN; // Create the SDL window SDL_Window *pSDLWindow = SDL_CreateWindow(windowTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, sdlWindowFlags); // Created? if (pSDLWindow == nullptr) { Log_ErrorPrintf("Renderer::CreateOutputWindow: SDL_CreateWindow failed: %s", SDL_GetError()); return nullptr; } // create output buffer GPUOutputBuffer *pOutputBuffer; if (m_capabilities.SupportsMultithreadedResourceCreation) { // forward straight through pOutputBuffer = m_pDevice->CreateOutputBuffer(pSDLWindow, vsyncType); } else { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pSDLWindow, vsyncType, &pOutputBuffer]() { pOutputBuffer = m_pDevice->CreateOutputBuffer(pSDLWindow, vsyncType); }); } return new RendererOutputWindow(pSDLWindow, pOutputBuffer, RENDERER_FULLSCREEN_STATE_WINDOWED); } GPUOutputBuffer *Renderer::CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateOutputBuffer(hWnd, vsyncType); GPUOutputBuffer *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, hWnd, vsyncType, &pReturnValue]() { pReturnValue = m_pDevice->CreateOutputBuffer(hWnd, vsyncType); }); return pReturnValue; } GPUOutputBuffer *Renderer::CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateOutputBuffer(pSDLWindow, vsyncType); GPUOutputBuffer *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pSDLWindow, vsyncType, &pReturnValue]() { pReturnValue = m_pDevice->CreateOutputBuffer(pSDLWindow, vsyncType); }); return pReturnValue; } GPUDepthStencilState *Renderer::CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateDepthStencilState(pDepthStencilStateDesc); GPUDepthStencilState *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pDepthStencilStateDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateDepthStencilState(pDepthStencilStateDesc); }); return pReturnValue; } GPURasterizerState *Renderer::CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateRasterizerState(pRasterizerStateDesc); GPURasterizerState *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pRasterizerStateDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateRasterizerState(pRasterizerStateDesc); }); return pReturnValue; } GPUBlendState *Renderer::CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateBlendState(pBlendStateDesc); GPUBlendState *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pBlendStateDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateBlendState(pBlendStateDesc); }); return pReturnValue; } GPUQuery *Renderer::CreateQuery(GPU_QUERY_TYPE type) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateQuery(type); GPUQuery *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, type, &pReturnValue]() { pReturnValue = m_pDevice->CreateQuery(type); }); return pReturnValue; } GPUBuffer *Renderer::CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateBuffer(pDesc, pInitialData); GPUBuffer *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pDesc, pInitialData, &pReturnValue]() { pReturnValue = m_pDevice->CreateBuffer(pDesc, pInitialData); }); return pReturnValue; } GPUTexture1D *Renderer::CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTexture1D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTexture1D *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTexture1D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTexture1DArray *Renderer::CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTexture1DArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTexture1DArray *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTexture1DArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTexture2D *Renderer::CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTexture2D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTexture2D *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTexture2D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTexture2DArray *Renderer::CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTexture2DArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTexture2DArray *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTexture2DArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTexture3D *Renderer::CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/, const uint32 *pInitialDataSlicePitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTexture3D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTexture3D *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTexture3D(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTextureCube *Renderer::CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTextureCube(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTextureCube *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTextureCube(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUTextureCubeArray *Renderer::CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /*= NULL*/, const uint32 *pInitialDataPitch /*= NULL*/) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateTextureCubeArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); GPUTextureCubeArray *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch, &pReturnValue]() { pReturnValue = m_pDevice->CreateTextureCubeArray(pTextureDesc, pSamplerStateDesc, ppInitialData, pInitialDataPitch); }); return pReturnValue; } GPUDepthTexture *Renderer::CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateDepthTexture(pTextureDesc); GPUDepthTexture *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTextureDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateDepthTexture(pTextureDesc); }); return pReturnValue; } GPUSamplerState *Renderer::CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateSamplerState(pSamplerStateDesc); GPUSamplerState *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pSamplerStateDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateSamplerState(pSamplerStateDesc); }); return pReturnValue; } GPURenderTargetView *Renderer::CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateRenderTargetView(pTexture, pDesc); GPURenderTargetView *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTexture, pDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateRenderTargetView(pTexture, pDesc); }); return pReturnValue; } GPUDepthStencilBufferView *Renderer::CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateDepthStencilBufferView(pTexture, pDesc); GPUDepthStencilBufferView *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pTexture, pDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateDepthStencilBufferView(pTexture, pDesc); }); return pReturnValue; } GPUComputeView *Renderer::CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateComputeView(pResource, pDesc); GPUComputeView *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pResource, pDesc, &pReturnValue]() { pReturnValue = m_pDevice->CreateComputeView(pResource, pDesc); }); return pReturnValue; } GPUShaderProgram *Renderer::CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateGraphicsProgram(pVertexElements, nVertexElements, pByteCodeStream); GPUShaderProgram *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pVertexElements, nVertexElements, pByteCodeStream, &pReturnValue]() { pReturnValue = m_pDevice->CreateGraphicsProgram(pVertexElements, nVertexElements, pByteCodeStream); }); return pReturnValue; } GPUShaderProgram *Renderer::CreateComputeProgram(ByteStream *pByteCodeStream) { if (m_capabilities.SupportsMultithreadedResourceCreation) return m_pDevice->CreateComputeProgram(pByteCodeStream); GPUShaderProgram *pReturnValue; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, pByteCodeStream, &pReturnValue]() { pReturnValue = m_pDevice->CreateComputeProgram(pByteCodeStream); }); return pReturnValue; } GPUCommandList *Renderer::AllocateCommandList() { DebugAssert(Renderer::IsOnRenderThread()); m_outstandingCommandListCount++; // free one in pool? if (m_freeCommandListPool.GetSize() > 0) return m_freeCommandListPool.PopFront(); // alloc new GPUCommandList *pCommandList = GetGPUContext()->CreateCommandList(); if (pCommandList == nullptr) Log_ErrorPrintf("Command list allocation failed."); return pCommandList; } void Renderer::ReleaseCommandList(GPUCommandList *pCommandList) { DebugAssert(m_outstandingCommandListCount > 0); m_freeCommandListPool.Add(pCommandList); m_outstandingCommandListCount--; } bool Renderer::ChangeResolution(RENDERER_FULLSCREEN_STATE state, uint32 width /*= 0*/, uint32 height /*= 0*/, uint32 refreshRate /*= 0*/) { // no change if (state == m_pImplicitOutputWindow->GetFullscreenState() && width == m_pImplicitOutputWindow->GetWidth() && height == m_pImplicitOutputWindow->GetHeight()) return true; // get context GPUContext *pGPUContext = GetGPUContext(); DebugAssert(pGPUContext != nullptr && pGPUContext->GetOutputBuffer() == m_pImplicitOutputWindow->GetOutputBuffer()); // fullscreen mode change? if (state == RENDERER_FULLSCREEN_STATE_FULLSCREEN) { // lose windowed fullscreen bool wasWindowedFullscreen = (m_pImplicitOutputWindow->GetFullscreenState() == RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN); if (wasWindowedFullscreen) SDL_SetWindowFullscreen(m_pImplicitOutputWindow->GetSDLWindow(), 0); // switch modes if (!pGPUContext->SetExclusiveFullScreen(true, width, height, refreshRate)) { // switch failed Log_WarningPrintf("Failed to switch fullscreen resolution %ux%u@%uhz", width, height, refreshRate); // restore windowed fullscreen if (wasWindowedFullscreen) SDL_SetWindowFullscreen(m_pImplicitOutputWindow->GetSDLWindow(), SDL_WINDOW_FULLSCREEN_DESKTOP); // can't do much else return false; } // alter window dimensions width = m_pImplicitOutputWindow->GetOutputBuffer()->GetWidth(); height = m_pImplicitOutputWindow->GetOutputBuffer()->GetHeight(); m_pImplicitOutputWindow->SetDimensions(width, height); } else { if (m_pImplicitOutputWindow->GetFullscreenState() == RENDERER_FULLSCREEN_STATE_FULLSCREEN) { // leaving fullscreen pGPUContext->SetExclusiveFullScreen(false, 0, 0, 0); } // windows fullscreen if (state == RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN) { if (m_pImplicitOutputWindow->GetFullscreenState() != RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN) SDL_SetWindowFullscreen(m_pImplicitOutputWindow->GetSDLWindow(), SDL_WINDOW_FULLSCREEN_DESKTOP); } else { // remove windowed fullscreen flag if (m_pImplicitOutputWindow->GetFullscreenState() == RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN) SDL_SetWindowFullscreen(m_pImplicitOutputWindow->GetSDLWindow(), 0); // resize the window SDL_SetWindowSize(m_pImplicitOutputWindow->GetSDLWindow(), width, height); } // fix up the window dimensions int windowWidth, windowHeight; SDL_GetWindowSize(m_pImplicitOutputWindow->GetSDLWindow(), &windowWidth, &windowHeight); m_pImplicitOutputWindow->SetDimensions(width, height); } // alter state m_pImplicitOutputWindow->SetFullscreenState(state); // adjust the buffers if (!pGPUContext->ResizeOutputBuffer()) { Log_WarningPrintf("Failed to resize output buffer."); return false; } // done static const char *stateStrings[RENDERER_FULLSCREEN_STATE_COUNT] = { "Windowed", "Windowed Fullscreen", "Exclusive Fullscreen" }; Log_InfoPrintf("Renderer::ChangeResolution: Switched to %s @ %ux%u@%uhz", stateStrings[state], width, height, refreshRate); return true; } bool Renderer::InternalDrawPlain(GPUContext *pGPUDevice, const PlainVertexFactory::Vertex *pVertices, uint32 nVertices, uint32 flags) { const uint32 vertexSize = PlainVertexFactory::GetVertexSize(m_eRendererPlatform, m_eRendererFeatureLevel, flags); const uint32 bufferSize = vertexSize * nVertices; // allocate buffer byte buffer[4096]; byte *pHeapBuffer = NULL; byte *pBuffer = buffer; if (bufferSize > countof(buffer)) { // use heap buffer pHeapBuffer = new byte[bufferSize]; pBuffer = pHeapBuffer; } // fill buffer if (!PlainVertexFactory::FillBuffer(m_eRendererPlatform, m_eRendererFeatureLevel, flags, pVertices, nVertices, pBuffer, bufferSize)) { delete[] pHeapBuffer; return false; } // invoke draw pGPUDevice->DrawUserPointer(pBuffer, vertexSize, nVertices); // free any memory delete[] pHeapBuffer; return true; } void Renderer::DrawFullScreenQuad(GPUCommandList *pCommandList) { pCommandList->SetVertexBuffer(0, m_fixedResources.GetFullScreenQuadVertexBuffer(), 0, sizeof(FixedResources::ScreenQuadVertex)); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_STRIP); pCommandList->Draw(0, 4); } void Renderer::BlitTextureUsingShader(GPUCommandList *pCommandList, GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, int32 sourceLevel, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /* = RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST */, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE blendMode /* = RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE */) { // calculate source size and offset in texels uint32 sourceTextureWidth = pSourceTexture->GetDesc()->Width; uint32 sourceTextureHeight = pSourceTexture->GetDesc()->Height; float2 sourceOffset((float)sourceX / (float)sourceTextureWidth, (float)sourceY / (float)sourceTextureHeight); float2 sourceSize((float)sourceWidth / (float)sourceTextureWidth, (float)sourceHeight / (float)sourceTextureHeight); // select sampler state GPUSamplerState *pSamplerState; if (resizeFilter == RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST) pSamplerState = m_fixedResources.GetPointSamplerState(); else // if (resizeFilter == RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_LINEAR) pSamplerState = m_fixedResources.GetLinearSamplerState(); // select blend state GPUBlendState *pBlendState; if (blendMode == RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_ADDITIVE) pBlendState = m_fixedResources.GetBlendStateAdditive(); else if (blendMode == RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_ALPHA_BLENDING) pBlendState = m_fixedResources.GetBlendStateAlphaBlending(); else pBlendState = m_fixedResources.GetBlendStateNoBlending(); // get program ShaderProgram *pShaderProgram = (sourceLevel < 0) ? m_fixedResources.GetTextureBlitShader() : m_fixedResources.GetTextureBlitLODShader(); DebugAssert(pShaderProgram != nullptr); // set state pCommandList->SetRasterizerState(m_fixedResources.GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); pCommandList->SetDepthStencilState(m_fixedResources.GetDepthStencilState(false, false), 0); pCommandList->SetBlendState(pBlendState); pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); TextureBlitShader::SetProgramParameters(pCommandList, pShaderProgram, pSourceTexture, pSamplerState, sourceLevel); // create vertices FixedResources::ScreenQuadVertex vertices[4]; vertices[0].Set((float)destX, (float)destY, sourceOffset.x, sourceOffset.y); vertices[1].Set((float)destX, (float)(destY + destHeight), sourceOffset.x, sourceOffset.y + sourceSize.y); vertices[2].Set((float)(destX + destWidth), (float)destY, sourceOffset.x + sourceSize.x, sourceOffset.y); vertices[3].Set((float)(destX + destWidth), (float)(destY + destHeight), sourceOffset.x + sourceSize.x, sourceOffset.y + sourceSize.y); // draw the quad pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_STRIP); pCommandList->DrawUserPointer(vertices, sizeof(vertices[0]), countof(vertices)); } // void Renderer::DrawTextureMips(GPUContext *pContext, GPUTexture2D *pTexture, int32 maxLevel /* = -1 */) // { // const GPU_TEXTURE2D_DESC *pDesc = pTexture->GetDesc(); // // // set common state // ShaderProgram *pDownsampleShader = m_fixedResources.GetDownsampleShader(); // pContext->SetRasterizerState(m_fixedResources.GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); // pContext->SetDepthStencilState(m_fixedResources.GetDepthStencilState(false, false), 0); // pContext->SetBlendState(m_fixedResources.GetBlendStateNoBlending()); // pContext->SetShaderProgram(pDownsampleShader->GetGPUProgram()); // // // draw each mip level apart from the top // uint32 maxMipLevel = (maxLevel > 0) ? (uint32)maxLevel : pDesc->MipLevels; // for (uint32 mipLevel = 1; mipLevel < maxMipLevel; mipLevel++) // { // uint32 mipWidth = Max((uint32)1, (pDesc->Width >> mipLevel)); // uint32 mipHeight = Max((uint32)1, (pDesc->Height >> mipLevel)); // RENDERER_VIEWPORT mipViewport(0, 0, mipWidth, mipHeight, 0.0f, 1.0f); // int32 layer = -1; // // // set source/destination texture // pContext->SetRenderTargetLayers(1, reinterpret_cast<GPUTexture **>(pTexture), &mipLevel, &layer, nullptr, 0, -1); // DownsampleShader::SetProgramParameters(pContext, pDownsampleShader, pTexture, mipLevel - 1); // pContext->SetViewport(&mipViewport); // // // draw away // DrawFullScreenQuad(pContext); // } // // // clear out the targets in case they are used immediately afterwards before being unbound // pContext->ClearState(true, false, false, true); // } // // void Renderer::DrawDebugText(int32 x, int32 y, int32 Height, const char *Text, MINIGUI_HORIZONTAL_ALIGNMENT hAlign /* = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT */, MINIGUI_VERTICAL_ALIGNMENT vAlign /* = MINIGUI_VERTICAL_ALIGNMENT_TOP */) // { // m_GUIContext.DrawText(m_pDebugTextFont, Height, x, y, Text, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), false, hAlign, vAlign); // } ShaderProgram *Renderer::GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { MutexLock lock(m_shaderLock); // select shader map to use ShaderMap &shaderMap = (pMaterialShader != NULL) ? pMaterialShader->GetShaderMap() : m_nullMaterialShaderMap; // look up shader return shaderMap.GetShaderPermutation(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexAttributes, nVertexAttributes, pMaterialShader, materialShaderFlags); } ShaderProgram *Renderer::GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { MutexLock lock(m_shaderLock); // select shader map to use ShaderMap &shaderMap = (pMaterialShader != NULL) ? pMaterialShader->GetShaderMap() : m_nullMaterialShaderMap; // look up shader return shaderMap.GetShaderPermutation(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags); } uint3 Renderer::GetTextureDimensions(const GPUTexture *pTexture) { switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_1D: { const GPU_TEXTURE1D_DESC *pDesc = static_cast<const GPUTexture1D *>(pTexture)->GetDesc(); return uint3(pDesc->Width, 1, 1); } case TEXTURE_TYPE_1D_ARRAY: { const GPU_TEXTURE1DARRAY_DESC *pDesc = static_cast<const GPUTexture1DArray *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->ArraySize, 1); } case TEXTURE_TYPE_2D: { const GPU_TEXTURE2D_DESC *pDesc = static_cast<const GPUTexture2D *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, 1); } case TEXTURE_TYPE_2D_ARRAY: { const GPU_TEXTURE2DARRAY_DESC *pDesc = static_cast<const GPUTexture2DArray *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, pDesc->ArraySize); } case TEXTURE_TYPE_3D: { const GPU_TEXTURE3D_DESC *pDesc = static_cast<const GPUTexture3D *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, pDesc->Depth); } case TEXTURE_TYPE_CUBE: { const GPU_TEXTURECUBE_DESC *pDesc = static_cast<const GPUTextureCube *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, 1); } case TEXTURE_TYPE_CUBE_ARRAY: { const GPU_TEXTURECUBEARRAY_DESC *pDesc = static_cast<const GPUTextureCubeArray *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, pDesc->ArraySize); } case TEXTURE_TYPE_DEPTH: { const GPU_DEPTH_TEXTURE_DESC *pDesc = static_cast<const GPUDepthTexture *>(pTexture)->GetDesc(); return uint3(pDesc->Width, pDesc->Height, 1); } default: UnreachableCode(); } return uint3::Zero; } void Renderer::FillDefaultRasterizerState(RENDERER_RASTERIZER_STATE_DESC *pRasterizerState) { pRasterizerState->FillMode = RENDERER_FILL_SOLID; //pRasterizerState->CullMode = RENDERER_CULL_NONE; pRasterizerState->CullMode = RENDERER_CULL_BACK; //pRasterizerState->FrontCounterClockwise = false; pRasterizerState->FrontCounterClockwise = true; pRasterizerState->ScissorEnable = false; pRasterizerState->DepthBias = 0; pRasterizerState->SlopeScaledDepthBias = 0.0f; pRasterizerState->DepthClipEnable = true; } void Renderer::FillDefaultDepthStencilState(RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState) { pDepthStencilState->DepthTestEnable = true; pDepthStencilState->DepthWriteEnable = true; pDepthStencilState->DepthFunc = GPU_COMPARISON_FUNC_LESS; pDepthStencilState->StencilTestEnable = false; pDepthStencilState->StencilReadMask = 0xFF; pDepthStencilState->StencilWriteMask = 0xFF; pDepthStencilState->StencilFrontFace.FailOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilFrontFace.DepthFailOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilFrontFace.PassOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilFrontFace.CompareFunc = GPU_COMPARISON_FUNC_ALWAYS; pDepthStencilState->StencilBackFace.FailOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilBackFace.DepthFailOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilBackFace.PassOp = RENDERER_STENCIL_OP_KEEP; pDepthStencilState->StencilBackFace.CompareFunc = GPU_COMPARISON_FUNC_ALWAYS; } void Renderer::FillDefaultBlendState(RENDERER_BLEND_STATE_DESC *pBlendState) { pBlendState->BlendEnable = false; pBlendState->SrcBlend = RENDERER_BLEND_ONE; pBlendState->DestBlend = RENDERER_BLEND_ZERO; pBlendState->BlendOp = RENDERER_BLEND_OP_ADD; pBlendState->SrcBlendAlpha = RENDERER_BLEND_ONE; pBlendState->DestBlendAlpha = RENDERER_BLEND_ZERO; pBlendState->BlendOpAlpha = RENDERER_BLEND_OP_ADD; pBlendState->ColorWriteEnable = true; } void Renderer::FillDefaultSamplerState(GPU_SAMPLER_STATE_DESC *pSamplerState) { pSamplerState->Filter = TEXTURE_FILTER_ANISOTROPIC; pSamplerState->MaxAnisotropy = 16; pSamplerState->AddressU = TEXTURE_ADDRESS_MODE_WRAP; pSamplerState->AddressV = TEXTURE_ADDRESS_MODE_WRAP; pSamplerState->AddressW = TEXTURE_ADDRESS_MODE_WRAP; pSamplerState->BorderColor.SetZero(); pSamplerState->LODBias = 0.0f; pSamplerState->MinLOD = Y_INT32_MIN; pSamplerState->MaxLOD = Y_INT32_MAX; pSamplerState->ComparisonFunc = GPU_COMPARISON_FUNC_NEVER; } void Renderer::CorrectTextureFilter(GPU_SAMPLER_STATE_DESC *pSamplerState) { const RendererCapabilities &capabilities = g_pRenderer->GetCapabilities(); bool isComparisonFilter = (pSamplerState->Filter < TEXTURE_FILTER_COUNT && pSamplerState->Filter >= TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT); switch (CVars::r_texture_filtering.GetInt()) { // bilinear case 1: { if (isComparisonFilter) { if (pSamplerState->Filter > TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT) pSamplerState->Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; } else { if (pSamplerState->Filter > TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT) pSamplerState->Filter = TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT; } pSamplerState->MaxAnisotropy = 1; } break; // trilinear case 2: { if (isComparisonFilter) { if (pSamplerState->Filter > TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR) pSamplerState->Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; } else { if (pSamplerState->Filter > TEXTURE_FILTER_MIN_MAG_MIP_LINEAR) pSamplerState->Filter = TEXTURE_FILTER_MIN_MAG_MIP_LINEAR; } pSamplerState->MaxAnisotropy = 1; } break; // anisotropic case 3: { if (capabilities.MaxTextureAnisotropy > 0) { // HACKFIX! FIXME! if (pSamplerState->Filter == TEXTURE_FILTER_COUNT) pSamplerState->Filter = TEXTURE_FILTER_ANISOTROPIC; if (pSamplerState->Filter == TEXTURE_FILTER_ANISOTROPIC || pSamplerState->Filter == TEXTURE_FILTER_COMPARISON_ANISOTROPIC) pSamplerState->MaxAnisotropy = Min((uint32)CVars::r_max_anisotropy.GetInt(), capabilities.MaxTextureAnisotropy); else pSamplerState->MaxAnisotropy = 1; } else { // fallback to trilinear if (isComparisonFilter) { if (pSamplerState->Filter > TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR) pSamplerState->Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; } else { if (pSamplerState->Filter > TEXTURE_FILTER_MIN_MAG_MIP_LINEAR) pSamplerState->Filter = TEXTURE_FILTER_MIN_MAG_MIP_LINEAR; } pSamplerState->MaxAnisotropy = 1; } } break; // point default: { if (isComparisonFilter) { if (pSamplerState->Filter > TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT) pSamplerState->Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT; } else { if (pSamplerState->Filter > TEXTURE_FILTER_MIN_MAG_MIP_POINT) pSamplerState->Filter = TEXTURE_FILTER_MIN_MAG_MIP_POINT; } pSamplerState->MaxAnisotropy = 1; } break; } } bool Renderer::TextureFilterRequiresMips(TEXTURE_FILTER filter) { switch (filter) { case TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR: case TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR: case TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR: case TEXTURE_FILTER_MIN_MAG_MIP_LINEAR: case TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR: case TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR: case TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR: case TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR: return true; default: return false; } } uint32 Renderer::CalculateMipCount(uint32 width, uint32 height /* = 1 */, uint32 depth /* = 1 */) { uint32 currentWidth = width; uint32 currentHeight = height; uint32 currentDepth = depth; uint32 mipCount = 1; while (currentWidth > 1 || currentHeight > 1 || currentDepth > 1) { if (currentWidth > 1) currentWidth /= 2; if (currentHeight > 1) currentHeight /= 2; if (currentDepth > 1) currentDepth /= 2; mipCount++; } return mipCount; } bool Renderer::CalculateAABoxScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const AABox &Bounds, const float4x4 &ViewMatrix, int32 RTWidth, int32 RTHeight) { return false; } bool Renderer::CalculatePointLightScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const float3 &LightPosition, const float &LightRange, const float4x4 &ViewMatrix, int32 RTWidth, int32 RTHeight) { // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=173666&page=2 float aspect = (float)RTWidth / (float)RTHeight; const int32 &sx = RTWidth; const int32 &sy = RTHeight; int32 outRect[4] = { 0, 0, RTWidth, RTHeight }; const float &r = LightRange; float r2 = r * r; SIMDVector3f l = (ViewMatrix * SIMDVector4f(LightPosition, 1.0f)).xyz(); SIMDVector3f l2 = l * l; float e1 = 1.2f; float e2 = 1.2f * aspect; float d = r2 * l2.x - (l2.x + l2.z) * (r2 - l2.z); if (d>=0) { d = Y_sqrtf(d); float nx1 = (r*l.x + d) / (l2.x + l2.z); float nx2 = (r*l.x - d) / (l2.x + l2.z); float nz1 = (r - nx1*l.x) / l.z; float nz2 = (r - nx2*l.x) / l.z; //float e = 1.25f; //float a = aspect; float pz1 = (l2.x + l2.z-r2) / (l.z - (nz1 / nx1) * l.x); float pz2 = (l2.x + l2.z-r2) / (l.z - (nz2 / nx2) * l.x); if (pz1 >= 0.0f && pz2 >= 0.0f) return false; if (pz1 < 0) { float fx=nz1*e1/nx1; int ix=(int)((fx+1.0f)*sx*0.5f); float px=-pz1*nz1/nx1; if (px<l.x) outRect[0] = Max(outRect[0],ix); else outRect[2] = Min(outRect[2],ix); } if (pz2<0) { float fx=nz2*e1/nx2; int ix=(int)((fx+1.0f)*sx*0.5f); float px=-pz2*nz2/nx2; if (px<l.x) outRect[0] = Max(outRect[0],ix); else outRect[2] = Min(outRect[2],ix); } if (outRect[2] <= outRect[0]) return false; } d=r2*l2.y - (l2.y+l2.z)*(r2-l2.z); if (d >= 0.0f) { d = Y_sqrtf(d); float ny1=(r*l.y + d)/(l2.y + l2.z); float ny2=(r*l.y - d)/(l2.y + l2.z); float nz1=(r - ny1*l.y)/l.z; float nz2=(r - ny2*l.y)/l.z; float pz1=(l2.y + l2.z-r2)/(l.z - (nz1/ny1)*l.y); float pz2=(l2.y + l2.z-r2)/(l.z - (nz2/ny2)*l.y); if (pz1>=0 && pz2>=0) return false; if (pz1<0) { float fy=nz1*e2/ny1; int iy=(int)((fy+1.0f)*sy*0.5f); float py=-pz1*nz1/ny1; if (py<l.y) outRect[1]=Max(outRect[1],iy); else outRect[3]=Min(outRect[3],iy); } if (pz2<0) { float fy=nz2*e2/ny2; int iy=(int)((fy+1.0f)*sy*0.5f); float py=-pz2*nz2/ny2; if (py<l.y) outRect[1]=Max(outRect[1],iy); else outRect[3]=Min(outRect[3],iy); } if (outRect[3]<=outRect[1]) return false; } // gen scissor rect pScissorRect->Left = outRect[0]; pScissorRect->Top = outRect[1]; pScissorRect->Right = outRect[2]; pScissorRect->Bottom = outRect[3]; return true; } bool Renderer::CalculateAABoxScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const AABox &Bounds) { GPURenderTargetView *pRenderTargetView; g_pRenderer->GetGPUContext()->GetRenderTargets(1, &pRenderTargetView, nullptr); const float4x4 &viewMatrix = g_pRenderer->GetGPUContext()->GetConstants()->GetCameraViewMatrix(); uint3 renderTargetDimensions = (pRenderTargetView != NULL) ? GetTextureDimensions(pRenderTargetView->GetTargetTexture()) : uint3::One; return CalculateAABoxScissorRect(pScissorRect, Bounds, viewMatrix, renderTargetDimensions.x, renderTargetDimensions.y); } bool Renderer::CalculatePointLightScissorRect(RENDERER_SCISSOR_RECT *pScissorRect, const float3 &LightPosition, const float &LightRange) { GPURenderTargetView *pRenderTargetView; g_pRenderer->GetGPUContext()->GetRenderTargets(1, &pRenderTargetView, nullptr); const float4x4 &viewMatrix = g_pRenderer->GetGPUContext()->GetConstants()->GetCameraViewMatrix(); uint3 renderTargetDimensions = (pRenderTargetView != NULL) ? GetTextureDimensions(pRenderTargetView->GetTargetTexture()) : uint3::One; return CalculatePointLightScissorRect(pScissorRect, LightPosition, LightRange, viewMatrix, renderTargetDimensions.x, renderTargetDimensions.y); } void Renderer::BuildIndexBufferContents(uint32 sourceVertexCount, const uint32 *pSourceIndices, uint32 nIndicesPerPrimitive, uint32 nPrimitives, uint32 sourceIndicesStride, void **ppOutBuffer, GPU_INDEX_FORMAT *pOutIndexFormat, uint32 *pOutIndexCount) { uint32 nIndices = nIndicesPerPrimitive * nPrimitives; GPU_INDEX_FORMAT indexFormat; void *pOutIndices; uint32 cbOutIndices; if (sourceVertexCount <= Y_UINT16_MAX) { indexFormat = GPU_INDEX_FORMAT_UINT16; pOutIndices = Y_mallocT<uint16>(nIndices); cbOutIndices = sizeof(uint16) * nIndices; } else { indexFormat = GPU_INDEX_FORMAT_UINT32; pOutIndices = Y_mallocT<uint32>(nIndices); cbOutIndices = sizeof(uint32) * nIndices; } FillIndexBufferContents(pSourceIndices, nIndicesPerPrimitive, nPrimitives, sourceIndicesStride, indexFormat, pOutIndices, cbOutIndices); *ppOutBuffer = pOutIndices; *pOutIndexFormat = indexFormat; *pOutIndexCount = nIndices; } void Renderer::FillIndexBufferContents(const uint32 *pSourceIndices, uint32 nIndicesPerPrimitive, uint32 nPrimitives, uint32 sourceIndicesStride, GPU_INDEX_FORMAT indexFormat, void *pDestinationIndices, uint32 cbDestinationIndices) { const byte *pSourcePtr = reinterpret_cast<const byte *>(pSourceIndices); if (indexFormat == GPU_INDEX_FORMAT_UINT16) { uint16 *pOutPtr = reinterpret_cast<uint16 *>(pDestinationIndices); Assert(cbDestinationIndices >= (sizeof(uint16) * nIndicesPerPrimitive * nPrimitives)); for (uint32 i = 0; i < nPrimitives; i++) { const uint32 *pCurrentPrimitive = reinterpret_cast<const uint32 *>(pSourcePtr); for (uint32 j = 0; j < nIndicesPerPrimitive; j++) *(pOutPtr++) = static_cast<uint16>(*(pCurrentPrimitive++)); pSourcePtr += sourceIndicesStride; } } else { uint32 *pOutPtr = reinterpret_cast<uint32 *>(pDestinationIndices); Assert(cbDestinationIndices >= (sizeof(uint32) * nIndicesPerPrimitive * nPrimitives)); for (uint32 i = 0; i < nPrimitives; i++) { const uint32 *pCurrentPrimitive = reinterpret_cast<const uint32 *>(pSourcePtr); for (uint32 j = 0; j < nIndicesPerPrimitive; j++) *(pOutPtr++) = *(pCurrentPrimitive++); pSourcePtr += sourceIndicesStride; } } } float2 Renderer::GetClipSpaceCoordinatesForPixelCoordinates(int32 x, int32 y, uint32 windowWidth, uint32 windowHeight) { DebugAssert(windowWidth > 1 && windowHeight > 1); float outX = (float)x / (float)(windowWidth - 1); float outY = (float)y / (float)(windowHeight - 1); outX *= 2.0f; outY *= 2.0f; outX -= 1.0f; outY = 1.0f - outY; return float2(outX, outY); } float2 Renderer::GetTextureSpaceCoordinatesForPixelCoordinates(int32 x, int32 y, uint32 textureWidth, uint32 textureHeight) { DebugAssert(textureWidth > 1 && textureHeight > 1); float outX = (float)x / (float)(textureWidth - 1); float outY = (float)y / (float)(textureHeight - 1); return float2(outX, outY); } Renderer::FixedResources::FixedResources(Renderer *pRenderer) : m_pRenderer(pRenderer), m_pBlendStateNoBlending(nullptr), m_pBlendStateNoColorWrites(nullptr), m_pBlendStateAdditive(nullptr), m_pBlendStateAlphaBlending(nullptr), m_pBlendStateAlphaBlendingAdditive(nullptr), m_pBlendStatePremultipliedAlpha(nullptr), m_pBlendStatePremultipliedAlphaAdditive(nullptr), m_pBlendStateBlendFactor(nullptr), m_pBlendStateBlendFactorAdditive(nullptr), m_pBlendStateBlendFactorPremultipliedAlpha(nullptr), m_pBlendStateApplyBlendFactorAlpha(nullptr), m_pPointSamplerState(nullptr), m_pLinearSamplerState(nullptr), m_pLinearMipSamplerState(nullptr), m_pDebugFont(nullptr), m_pNoiseTexture(nullptr), m_pRandomTexture(nullptr), m_pTextureBlitShader(nullptr), m_pTextureBlitLODShader(nullptr), m_pDownsampleShader(nullptr), m_pFullScreenQuadVertexBuffer(nullptr), m_pOverlayShaderColoredScreen(nullptr), m_pOverlayShaderColoredWorld(nullptr), m_pOverlayShaderTexturedScreen(nullptr), m_pOverlayShaderTexturedWorld(nullptr) { Y_memzero(m_pRasterizerStates, sizeof(m_pRasterizerStates)); Y_memzero(m_pDepthStencilStates, sizeof(m_pDepthStencilStates)); } Renderer::FixedResources::~FixedResources() { for (uint32 fillMode = 0; fillMode < RENDERER_FILL_MODE_COUNT; fillMode++) { for (uint32 cullMode = 0; cullMode < RENDERER_CULL_MODE_COUNT; cullMode++) { for (uint32 depthBiasFlag = 0; depthBiasFlag < 2; depthBiasFlag++) { for (uint32 depthClampFlag = 0; depthClampFlag < 2; depthClampFlag++) { for (uint32 scissorFlag = 0; scissorFlag < 2; scissorFlag++) { DebugAssert(m_pRasterizerStates[fillMode][cullMode][depthBiasFlag][depthClampFlag][scissorFlag] == nullptr); } } } } } for (uint32 depthTestFlag = 0; depthTestFlag < 2; depthTestFlag++) { for (uint32 depthWriteFlag = 0; depthWriteFlag < 2; depthWriteFlag++) { for (uint32 comparisonFunc = 0; comparisonFunc < GPU_COMPARISON_FUNC_COUNT; comparisonFunc++) { DebugAssert(m_pDepthStencilStates[depthTestFlag][depthWriteFlag][comparisonFunc] == nullptr); } } } DebugAssert(m_pBlendStateNoBlending == nullptr); DebugAssert(m_pBlendStateNoColorWrites == nullptr); DebugAssert(m_pBlendStateAdditive == nullptr); DebugAssert(m_pBlendStateAlphaBlending == nullptr); DebugAssert(m_pBlendStateAlphaBlendingAdditive == nullptr); DebugAssert(m_pBlendStatePremultipliedAlpha == nullptr); DebugAssert(m_pBlendStatePremultipliedAlphaAdditive == nullptr); DebugAssert(m_pBlendStateBlendFactor == nullptr); DebugAssert(m_pBlendStateBlendFactorAdditive == nullptr); DebugAssert(m_pBlendStateBlendFactorPremultipliedAlpha == nullptr); DebugAssert(m_pBlendStateApplyBlendFactorAlpha == nullptr); DebugAssert(m_pPointSamplerState == nullptr); DebugAssert(m_pLinearSamplerState == nullptr); DebugAssert(m_pLinearMipSamplerState == nullptr); DebugAssert(m_pDebugFont == nullptr); DebugAssert(m_pNoiseTexture == nullptr); DebugAssert(m_pRandomTexture == nullptr); DebugAssert(m_pTextureBlitShader == nullptr); DebugAssert(m_pTextureBlitLODShader == nullptr); DebugAssert(m_pDownsampleShader == nullptr); DebugAssert(m_pFullScreenQuadVertexBuffer == nullptr); } GPURasterizerState *Renderer::FixedResources::GetRasterizerState(RENDERER_FILL_MODE fillMode /*= RENDERER_FILL_SOLID*/, RENDERER_CULL_MODE cullMode /*= RENDERER_CULL_BACK*/, bool depthBias /*= false*/, bool depthClamping /*= false*/, bool scissorTest /*= false*/) { GPURasterizerState *pRasterizerState = m_pRasterizerStates[fillMode][cullMode][depthBias][depthClamping][scissorTest].Load(); if (pRasterizerState == nullptr) { RENDERER_RASTERIZER_STATE_DESC rasterizerStateDesc; Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.FillMode = (RENDERER_FILL_MODE)fillMode; rasterizerStateDesc.CullMode = (RENDERER_CULL_MODE)cullMode; rasterizerStateDesc.DepthBias = (depthBias) ? -1000 : 0; rasterizerStateDesc.DepthClipEnable = (depthClamping) ? false : true; rasterizerStateDesc.ScissorEnable = (scissorTest) ? true : false; if ((pRasterizerState = m_pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == nullptr) { Log_ErrorPrintf("Renderer::FixedResources::GetRasterizerState: Rasterizer state failed creation"); return nullptr; } if (!m_pRasterizerStates[fillMode][cullMode][depthBias][depthClamping][scissorTest].Set(pRasterizerState)) { pRasterizerState->Release(); pRasterizerState = m_pRasterizerStates[fillMode][cullMode][depthBias][depthClamping][scissorTest].Load(); } } return pRasterizerState; } GPUDepthStencilState *Renderer::FixedResources::GetDepthStencilState(bool depthTestEnabled /*= true*/, bool depthWriteEnabled /*= true*/, GPU_COMPARISON_FUNC comparisonFunc /*= GPU_COMPARISON_FUNC_LESS*/) { GPUDepthStencilState *pDepthStencilState = m_pDepthStencilStates[depthTestEnabled][depthWriteEnabled][comparisonFunc].Load(); if (pDepthStencilState == nullptr) { RENDERER_DEPTHSTENCIL_STATE_DESC depthStencilStateDesc; Renderer::FillDefaultDepthStencilState(&depthStencilStateDesc); depthStencilStateDesc.DepthTestEnable = depthTestEnabled; depthStencilStateDesc.DepthWriteEnable = depthWriteEnabled; depthStencilStateDesc.DepthFunc = comparisonFunc; if ((pDepthStencilState = m_pRenderer->CreateDepthStencilState(&depthStencilStateDesc)) == nullptr) { Log_ErrorPrintf("Renderer::FixedResources::GetDepthStencilState: DepthStencil state failed creation"); return nullptr; } if (!m_pDepthStencilStates[depthTestEnabled][depthWriteEnabled][comparisonFunc].Set(pDepthStencilState)) { pDepthStencilState->Release(); pDepthStencilState = m_pDepthStencilStates[depthTestEnabled][depthWriteEnabled][comparisonFunc].Load(); } } return pDepthStencilState; } const GPU_VERTEX_ELEMENT_DESC *Renderer::FixedResources::GetPositionOnlyVertexAttributes() { static const GPU_VERTEX_ELEMENT_DESC attributes[] = { { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT3, 0, 0, 0 }, }; return attributes; } const uint32 Renderer::FixedResources::GetPositionOnlyVertexAttributeCount() { // has to match above! return 1; } const GPU_VERTEX_ELEMENT_DESC *Renderer::FixedResources::GetFullScreenQuadVertexAttributes() { static const GPU_VERTEX_ELEMENT_DESC fullscreenQuadAttributes[] = { { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT4, 0, offsetof(ScreenQuadVertex, Position), 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, 0, offsetof(ScreenQuadVertex, TexCoord), 0 } }; return fullscreenQuadAttributes; } const uint32 Renderer::FixedResources::GetFullScreenQuadVertexAttributeCount() { // has to match above! return 2; } bool Renderer::FixedResources::CreateResources() { #if 0 // rasterizer { // rs[wireframe][culling][depthbias][depthclip][scissor] RENDERER_RASTERIZER_STATE_DESC rasterizerStateDesc; Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); // wireframe for (uint32 fillMode = 0; fillMode < RENDERER_FILL_MODE_COUNT; fillMode++) { rasterizerStateDesc.FillMode = (RENDERER_FILL_MODE)fillMode; // culling for (uint32 cullMode = 0; cullMode < RENDERER_CULL_MODE_COUNT; cullMode++) { rasterizerStateDesc.CullMode = (RENDERER_CULL_MODE)cullMode; // depthbias for (uint32 depthBiasFlag = 0; depthBiasFlag < 2; depthBiasFlag++) { rasterizerStateDesc.DepthBias = (depthBiasFlag == 0) ? 0 : 1; // depthclip for (uint32 depthClampFlag = 0; depthClampFlag < 2; depthClampFlag++) { rasterizerStateDesc.DepthClipEnable = (depthClampFlag == 0) ? TRUE : FALSE; // scissor for (uint32 scissorFlag = 0; scissorFlag < 2; scissorFlag++) { rasterizerStateDesc.ScissorEnable = (scissorFlag == 0) ? FALSE : TRUE; if ((m_pRasterizerStates[fillMode][cullMode][depthBiasFlag][depthClampFlag][scissorFlag] = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == nullptr) return false; } } } } } // normal if ((m_pRasterizerStateNormal = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // nocull Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.FillMode = RENDERER_FILL_SOLID; rasterizerStateDesc.CullMode = RENDERER_CULL_NONE; if ((m_pRasterizerStateNoCull = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // 1 depthbias, normal Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.DepthBias = 16; rasterizerStateDesc.SlopeScaledDepthBias = 16.0f; if ((m_pRasterizerStateOneDepthBias = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // wireframe Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.FillMode = RENDERER_FILL_WIREFRAME; if ((m_pRasterizerStateWireframe = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // wireframe, depth bias Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.FillMode = RENDERER_FILL_WIREFRAME; rasterizerStateDesc.DepthBias = 1; if ((m_pRasterizerStateWireframeOneDepthBias = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // wireframe no cull Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.FillMode = RENDERER_FILL_WIREFRAME; rasterizerStateDesc.CullMode = RENDERER_CULL_NONE; if ((m_pRasterizerStateWireframeNoCull = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; // scissor Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); rasterizerStateDesc.ScissorEnable = true; if ((m_pRasterizerStateScissor = pRenderer->CreateRasterizerState(&rasterizerStateDesc)) == NULL) return false; } // depthstencil { RENDERER_DEPTHSTENCIL_STATE_DESC DepthStencilStateDesc; // less Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); if ((m_pDepthStencilStateLess = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; // less + no writes Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); DepthStencilStateDesc.DepthWriteEnable = false; if ((m_pDepthStencilStateLessNoWrite = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; // lessequal Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); DepthStencilStateDesc.DepthFunc = GPU_COMPARISON_FUNC_LESS_EQUAL; if ((m_pDepthStencilStateLessEqual = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; // lessequal + no writes Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); DepthStencilStateDesc.DepthFunc = GPU_COMPARISON_FUNC_LESS_EQUAL; DepthStencilStateDesc.DepthWriteEnable = false; if ((m_pDepthStencilStateLessEqualNoWrite = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; // equal Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); DepthStencilStateDesc.DepthFunc = GPU_COMPARISON_FUNC_EQUAL; DepthStencilStateDesc.DepthWriteEnable = false; if ((m_pDepthStencilStateEqual = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; // notests Renderer::FillDefaultDepthStencilState(&DepthStencilStateDesc); DepthStencilStateDesc.DepthTestEnable = false; DepthStencilStateDesc.DepthWriteEnable = false; if ((m_pDepthStencilStateNoTest = pRenderer->CreateDepthStencilState(&DepthStencilStateDesc)) == NULL) return false; } #endif // get some more common states GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false); GetDepthStencilState(false, false); GetDepthStencilState(true, true); // blend { RENDERER_BLEND_STATE_DESC blendStateDesc; // noblending Renderer::FillDefaultBlendState(&blendStateDesc); if ((m_pBlendStateNoBlending = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // nocolorwrites Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.ColorWriteEnable = false; if ((m_pBlendStateNoColorWrites = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // additive Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_ONE; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_ONE; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_ONE; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_ONE; if ((m_pBlendStateAdditive = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // srcalpha + invsrcalpha Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_SRC_ALPHA; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_ONE; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_INV_SRC_ALPHA; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_INV_SRC_ALPHA; if ((m_pBlendStateAlphaBlending = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // srcalpha + dstcolor Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_SRC_ALPHA; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_ZERO; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_ONE; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_ONE; if ((m_pBlendStateAlphaBlendingAdditive = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // premultiplied alpha Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_ONE; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_ONE; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_INV_SRC_ALPHA; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_INV_SRC_ALPHA; if ((m_pBlendStatePremultipliedAlpha = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // premultiplied alpha additive Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_ONE; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_ONE; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_ONE; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_ONE; if ((m_pBlendStatePremultipliedAlphaAdditive = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // blend factor Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_ZERO; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOpAlpha = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_ZERO; if ((m_pBlendStateBlendFactor = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // blend factor additive Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_ONE; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOpAlpha = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_ONE; if ((m_pBlendStateBlendFactorAdditive = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // blend factor premultiplied alpha Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_INV_SRC_ALPHA; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOpAlpha = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_INV_SRC_ALPHA; if ((m_pBlendStateBlendFactorPremultipliedAlpha = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; // blend factor apply blend factor alpha Renderer::FillDefaultBlendState(&blendStateDesc); blendStateDesc.BlendEnable = true; blendStateDesc.SrcBlend = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOp = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlend = RENDERER_BLEND_INV_BLEND_FACTOR; blendStateDesc.SrcBlendAlpha = RENDERER_BLEND_BLEND_FACTOR; blendStateDesc.BlendOpAlpha = RENDERER_BLEND_OP_ADD; blendStateDesc.DestBlendAlpha = RENDERER_BLEND_INV_BLEND_FACTOR; if ((m_pBlendStateApplyBlendFactorAlpha = m_pRenderer->CreateBlendState(&blendStateDesc)) == nullptr) return false; } // sampler, only generate on SM4+ if (m_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_SM4) { GPU_SAMPLER_STATE_DESC samplerStateDesc; // point samplerStateDesc.Set(TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_ALWAYS); if ((m_pPointSamplerState = m_pRenderer->CreateSamplerState(&samplerStateDesc)) == nullptr) return false; // linear samplerStateDesc.Set(TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_ALWAYS); if ((m_pLinearSamplerState = m_pRenderer->CreateSamplerState(&samplerStateDesc)) == nullptr) return false; // linear/mips samplerStateDesc.Set(TEXTURE_FILTER_MIN_MAG_MIP_LINEAR, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_ALWAYS); if ((m_pLinearMipSamplerState = m_pRenderer->CreateSamplerState(&samplerStateDesc)) == nullptr) return false; } // resources { // debug font if ((m_pDebugFont = g_pResourceManager->GetFont(g_pEngine->GetRendererDebugFontName())) == nullptr) { Log_WarningPrintf("RendererFixedResources::CreateResources: Failed to load renderer debug font (%s), using default font.", g_pEngine->GetRendererDebugFontName().GetCharArray()); m_pDebugFont = g_pEngine->GetDefaultFont(); } // noise texture if ((m_pNoiseTexture = g_pResourceManager->GetTexture2D("textures/engine/noise")) == nullptr) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to load noise texture"); return false; } // random texture if ((m_pRandomTexture = g_pResourceManager->GetTexture2D("textures/engine/random")) == nullptr) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to load random texture"); return false; } // fullscreen quad buffer { static const ScreenQuadVertex vertices[4] = { { { -1.0f, 1.0f }, { 0.0f, 0.0f } }, { { -1.0f, -1.0f }, { 0.0f, 1.0f } }, { { 1.0f, 1.0f }, { 1.0f, 0.0f } }, // CCW, move up one for CW { { 1.0f, -1.0f }, { 1.0f, 1.0f } } }; GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, sizeof(vertices)); if ((m_pFullScreenQuadVertexBuffer = m_pRenderer->CreateBuffer(&bufferDesc, vertices)) == nullptr) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to create fullscreen quad vertex buffer."); return false; } #ifdef Y_BUILD_CONFIG_DEBUG m_pFullScreenQuadVertexBuffer->SetDebugName("Static FullScreen Quad"); #endif } // texture blit shader if ((m_pTextureBlitShader = m_pRenderer->GetShaderProgram(0, SHADER_COMPONENT_INFO(TextureBlitShader), 0, GetFullScreenQuadVertexAttributes(), GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr || (m_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_ES3 && (m_pTextureBlitLODShader = m_pRenderer->GetShaderProgram(0, SHADER_COMPONENT_INFO(TextureBlitShader), TextureBlitShader::USE_TEXTURE_LOD, GetFullScreenQuadVertexAttributes(), GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr)) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to create texture blit shader."); return false; } // overlay shaders { static const GPU_VERTEX_ELEMENT_DESC attributes2D[] = { { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, 0, offsetof(OverlayShader::Vertex2D, Position), 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, 0, offsetof(OverlayShader::Vertex2D, TexCoord), 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_COLOR, 0, GPU_VERTEX_ELEMENT_TYPE_UNORM4, 0, offsetof(OverlayShader::Vertex2D, Color), 0 } }; static const GPU_VERTEX_ELEMENT_DESC attributes3D[] = { { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT3, 0, offsetof(OverlayShader::Vertex3D, Position), 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, 0, offsetof(OverlayShader::Vertex3D, TexCoord), 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_COLOR, 0, GPU_VERTEX_ELEMENT_TYPE_UNORM4, 0, offsetof(OverlayShader::Vertex3D, Color), 0 } }; if ((m_pOverlayShaderColoredScreen = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(OverlayShader), 0, attributes2D, countof(attributes2D), nullptr, 0)) == nullptr || (m_pOverlayShaderColoredWorld = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(OverlayShader), OverlayShader::WITH_3D_VERTEX, attributes3D, countof(attributes3D), nullptr, 0)) == nullptr || (m_pOverlayShaderTexturedScreen = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(OverlayShader), OverlayShader::WITH_TEXTURE, attributes2D, countof(attributes2D), nullptr, 0)) == nullptr || (m_pOverlayShaderTexturedWorld = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(OverlayShader), OverlayShader::WITH_TEXTURE | OverlayShader::WITH_3D_VERTEX, attributes3D, countof(attributes3D), nullptr, 0)) == nullptr) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to create overlay shaders."); return false; } } // only on SM4+ if (m_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_SM4) { // downsample shader if ((m_pDownsampleShader = m_pRenderer->GetShaderProgram(0, SHADER_COMPONENT_INFO(DownsampleShader), 0, GetFullScreenQuadVertexAttributes(), GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr) { Log_ErrorPrintf("RendererFixedResources::CreateResources: Failed to create DownsampleShader."); return false; } } } return true; } void Renderer::FixedResources::ReleaseResources() { for (uint32 fillMode = 0; fillMode < RENDERER_FILL_MODE_COUNT; fillMode++) { for (uint32 cullMode = 0; cullMode < RENDERER_CULL_MODE_COUNT; cullMode++) { for (uint32 depthBiasFlag = 0; depthBiasFlag < 2; depthBiasFlag++) { for (uint32 depthClampFlag = 0; depthClampFlag < 2; depthClampFlag++) { for (uint32 scissorFlag = 0; scissorFlag < 2; scissorFlag++) { GPURasterizerState *pState = m_pRasterizerStates[fillMode][cullMode][depthBiasFlag][depthClampFlag][scissorFlag].Load(); if (pState != nullptr) { m_pRasterizerStates[fillMode][cullMode][depthBiasFlag][depthClampFlag][scissorFlag].Clear(pState); pState->Release(); } } } } } } for (uint32 depthTestFlag = 0; depthTestFlag < 2; depthTestFlag++) { for (uint32 depthWriteFlag = 0; depthWriteFlag < 2; depthWriteFlag++) { for (uint32 comparisonFunc = 0; comparisonFunc < GPU_COMPARISON_FUNC_COUNT; comparisonFunc++) { GPUDepthStencilState *pState = m_pDepthStencilStates[depthTestFlag][depthWriteFlag][comparisonFunc]; if (pState != nullptr) { m_pDepthStencilStates[depthTestFlag][depthWriteFlag][comparisonFunc].Clear(pState); pState->Release(); } } } } // Owned by ShaderMap hence null not release m_pOverlayShaderColoredScreen = nullptr; m_pOverlayShaderColoredWorld = nullptr; m_pOverlayShaderTexturedScreen = nullptr; m_pOverlayShaderTexturedWorld = nullptr; SAFE_RELEASE(m_pFullScreenQuadVertexBuffer); SAFE_RELEASE(m_pRandomTexture); SAFE_RELEASE(m_pNoiseTexture); SAFE_RELEASE(m_pDebugFont); SAFE_RELEASE(m_pLinearMipSamplerState); SAFE_RELEASE(m_pLinearSamplerState); SAFE_RELEASE(m_pPointSamplerState); SAFE_RELEASE(m_pBlendStateNoBlending); SAFE_RELEASE(m_pBlendStateNoColorWrites); SAFE_RELEASE(m_pBlendStateAdditive); SAFE_RELEASE(m_pBlendStateAlphaBlending); SAFE_RELEASE(m_pBlendStateAlphaBlendingAdditive); SAFE_RELEASE(m_pBlendStatePremultipliedAlpha); SAFE_RELEASE(m_pBlendStatePremultipliedAlphaAdditive); SAFE_RELEASE(m_pBlendStateBlendFactor); SAFE_RELEASE(m_pBlendStateBlendFactorAdditive); SAFE_RELEASE(m_pBlendStateBlendFactorPremultipliedAlpha); SAFE_RELEASE(m_pBlendStateApplyBlendFactorAlpha); // unset input layouts/shaders, these will be cleaned up by the cache list m_pTextureBlitShader = nullptr; m_pTextureBlitLODShader = nullptr; m_pDownsampleShader = nullptr; } // constant buffer declarations DECLARE_SHADER_CONSTANT_BUFFER(cbObjectConstants); DECLARE_SHADER_CONSTANT_BUFFER(cbViewConstants); // constant buffer definitions BEGIN_SHADER_CONSTANT_BUFFER(cbObjectConstants, "ObjectConstantsBuffer", "ObjectConstants", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_DRAW) SHADER_CONSTANT_BUFFER_FIELD("WorldMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("InverseWorldMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("MaterialTintColor", SHADER_PARAMETER_TYPE_FLOAT4, 1) END_SHADER_CONSTANT_BUFFER(cbObjectConstants) BEGIN_SHADER_CONSTANT_BUFFER(cbViewConstants, "ViewConstantsBuffer", "ViewConstants", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_VIEW) SHADER_CONSTANT_BUFFER_FIELD("ViewMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("InverseViewMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("ProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("InverseProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("ViewProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("InverseViewProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("ScreenProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) SHADER_CONSTANT_BUFFER_FIELD("EyePosition", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("WorldTime", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LogrithmicToLinearZDenominator", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LogrithmicToLinearZNumerator", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("ZNear", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("ZFar", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("PerspectiveAspectRatio", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("PerspectiveFOV", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("ViewportOffset", SHADER_PARAMETER_TYPE_FLOAT2, 1) SHADER_CONSTANT_BUFFER_FIELD("ViewportSize", SHADER_PARAMETER_TYPE_FLOAT2, 1) SHADER_CONSTANT_BUFFER_FIELD("ViewportOffsetFraction", SHADER_PARAMETER_TYPE_FLOAT2, 1) SHADER_CONSTANT_BUFFER_FIELD("InverseViewportSize", SHADER_PARAMETER_TYPE_FLOAT2, 1) END_SHADER_CONSTANT_BUFFER(cbViewConstants) DECLARE_RAW_SHADER_CONSTANT_BUFFER(cbGlobalConstants); DEFINE_RAW_SHADER_CONSTANT_BUFFER(cbGlobalConstants, "$Globals", "", 65536, RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_SM4, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM); GPUContextConstants::GPUContextConstants(GPUDevice *pDevice, GPUCommandList *pCommandList) : m_pDevice(pDevice) , m_pCommandList(pCommandList) , m_recalculateCombinedMatrices(false) , m_recalculateViewportFractions(false) { m_localToWorldMatrix.SetZero(); m_materialTintColor.SetZero(); m_cameraViewMatrix.SetZero(); m_cameraProjectionMatrix.SetZero(); m_cameraEyePosition.SetZero(); m_viewportOffset.SetZero(); m_viewportSize.SetZero(); m_worldTime = 0.0f; } GPUContextConstants::~GPUContextConstants() { } void GPUContextConstants::SetLocalToWorldMatrix(const float4x4 &rMatrix, bool Commit /*= true*/) { if (Y_memcmp(&rMatrix, &m_localToWorldMatrix, sizeof(m_localToWorldMatrix)) == 0) return; // set m_localToWorldMatrix = rMatrix; // calculate the inverse (transpose will do) float4x4 worldToLocalMatrix(m_localToWorldMatrix.Inverse()); // write constant buffers cbObjectConstants.SetFieldFloat4x4(m_pCommandList, 0, m_localToWorldMatrix, false); cbObjectConstants.SetFieldFloat4x4(m_pCommandList, 1, worldToLocalMatrix, false); // commit away if (Commit) CommitChanges(); } void GPUContextConstants::SetMaterialTintColor(const float4 &tintColor, bool Commit /*= true*/) { if (Y_memcmp(&tintColor, &m_materialTintColor, sizeof(m_localToWorldMatrix)) == 0) return; m_materialTintColor = tintColor; // write constant buffers cbObjectConstants.SetFieldFloat4(m_pCommandList, 2, m_materialTintColor, false); // commit away if (Commit) CommitChanges(); } void GPUContextConstants::SetCameraViewMatrix(const float4x4 &rMatrix, bool Commit /*= true*/) { if (Y_memcmp(&rMatrix, &m_cameraViewMatrix, sizeof(m_cameraViewMatrix)) == 0) return; m_cameraViewMatrix = rMatrix; m_recalculateCombinedMatrices = true; if (Commit) CommitChanges(); } void GPUContextConstants::SetCameraProjectionMatrix(const float4x4 &rMatrix, bool Commit /*= true*/) { if (Y_memcmp(&rMatrix, &m_cameraProjectionMatrix, sizeof(m_cameraProjectionMatrix)) == 0) return; m_cameraProjectionMatrix = rMatrix; m_recalculateCombinedMatrices = true; if (Commit) CommitChanges(); } void GPUContextConstants::SetCameraEyePosition(const float3 &Position, bool Commit /*= true*/) { if (Y_memcmp(&Position, &m_cameraEyePosition, sizeof(m_cameraEyePosition)) == 0) return; m_cameraEyePosition = Position; cbViewConstants.SetFieldFloat3(m_pCommandList, 7, Position, false); if (Commit) CommitChanges(); } void GPUContextConstants::SetFromCamera(const Camera &camera, bool commit /*= true*/) { // push view/projection matrices through, let the inverses be deferred for all we care SetCameraViewMatrix(camera.GetViewMatrix(), false); SetCameraProjectionMatrix(camera.GetProjectionMatrix(), false); SetCameraEyePosition(camera.GetPosition(), false); // calc z ratio uniform // https://mynameismjp.wordpress.com/2010/09/05/position-from-depth-3/ with negated far plane distance float logrithmicToLinearZDenominator = camera.GetFarPlaneDistance() / (camera.GetFarPlaneDistance() - camera.GetNearPlaneDistance()); float logrithmicToLinearZNumerator = (camera.GetFarPlaneDistance() * camera.GetNearPlaneDistance()) / (camera.GetFarPlaneDistance() - camera.GetNearPlaneDistance()); cbViewConstants.SetFieldFloat(m_pCommandList, 9, logrithmicToLinearZDenominator, false); cbViewConstants.SetFieldFloat(m_pCommandList, 10, logrithmicToLinearZNumerator, false); // set the remaining fields directly to the constant buffer cbViewConstants.SetFieldFloat(m_pCommandList, 11, camera.GetNearPlaneDistance(), false); cbViewConstants.SetFieldFloat(m_pCommandList, 12, camera.GetFarPlaneDistance(), false); cbViewConstants.SetFieldFloat(m_pCommandList, 13, camera.GetPerspectiveAspect(), false); cbViewConstants.SetFieldFloat(m_pCommandList, 14, Math::DegreesToRadians(camera.GetPerspectiveFieldOfView()), false); // commit if (commit) CommitChanges(); } void GPUContextConstants::SetViewportOffset(float offsetX, float offsetY, bool commit /*= true*/) { float2 viewportOffset(offsetX, offsetY); if (Y_memcmp(&viewportOffset, &m_viewportOffset, sizeof(m_viewportOffset)) == 0) return; m_viewportOffset = viewportOffset; cbViewConstants.SetFieldFloat2(m_pCommandList, 15, viewportOffset, false); m_recalculateViewportFractions = true; if (commit) CommitChanges(); } void GPUContextConstants::SetViewportSize(float width, float height, bool commit /*= true*/) { float2 viewportSize(width, height); if (Y_memcmp(&viewportSize, &m_viewportSize, sizeof(m_viewportSize)) == 0) return; m_viewportSize = viewportSize; cbViewConstants.SetFieldFloat2(m_pCommandList, 16, viewportSize, false); m_recalculateViewportFractions = true; if (commit) CommitChanges(); } void GPUContextConstants::SetWorldTime(float worldTime, bool commit /*= true*/) { if (m_worldTime == worldTime) return; m_worldTime = worldTime; cbViewConstants.SetFieldFloat(m_pCommandList, 8, worldTime, false); if (commit) CommitChanges(); } void GPUContextConstants::Reset() { m_localToWorldMatrix.SetZero(); m_materialTintColor.SetZero(); m_cameraViewMatrix.SetZero(); m_cameraProjectionMatrix.SetZero(); m_cameraEyePosition.SetZero(); m_viewportOffset.SetZero(); m_viewportSize.SetZero(); m_worldTime = 0.0f; } void GPUContextConstants::CommitChanges() { // commit object buffer cbObjectConstants.CommitChanges(m_pCommandList); // rebuild view constants if (m_recalculateCombinedMatrices) { // adjust projection matrix to renderer-specific attributes float4x4 adjustedProjectionMatrix(m_cameraProjectionMatrix); g_pRenderer->GetGPUDevice()->CorrectProjectionMatrix(adjustedProjectionMatrix); // calculate inverse matrices float4x4 inverseViewMatrix(m_cameraViewMatrix.Inverse()); float4x4 inverseProjectionMatrix(adjustedProjectionMatrix.Inverse()); // calculate view/projection matrix and inverses float4x4 viewProjectionMatrix(adjustedProjectionMatrix * m_cameraViewMatrix); float4x4 inverseViewProjectionMatrix(viewProjectionMatrix.Inverse());// replace with view * proj? // set in constant buffers cbViewConstants.SetFieldFloat4x4(m_pCommandList, 0, m_cameraViewMatrix, false); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 1, inverseViewMatrix, false); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 2, adjustedProjectionMatrix, false); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 3, inverseProjectionMatrix, false); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 4, viewProjectionMatrix, false); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 5, inverseViewProjectionMatrix, false); m_recalculateCombinedMatrices = false; } // rebuild viewport constants if (m_recalculateViewportFractions) { float2 vpSizeF((float)m_viewportSize.x, (float)m_viewportSize.y); float2 invVPSizeF(vpSizeF.Reciprocal()); float2 offsetFraction(float2((float)m_viewportOffset.x, (float)m_viewportOffset.y) * invVPSizeF); cbViewConstants.SetFieldFloat2(m_pCommandList, 17, offsetFraction, false); cbViewConstants.SetFieldFloat2(m_pCommandList, 18, invVPSizeF, false); // create ortho projection matrix float texelOffset = m_pDevice->GetTexelOffset(); float4x4 screenProjectionMatrix(float4x4::MakeOrthographicOffCenterProjectionMatrix((float)0.0f, (float)m_viewportSize.x, (float)m_viewportSize.y, 0.0f, 0.0f, 1.0f) * float4x4::MakeTranslationMatrix(texelOffset, texelOffset, 0.0f)); m_pDevice->CorrectProjectionMatrix(screenProjectionMatrix); cbViewConstants.SetFieldFloat4x4(m_pCommandList, 6, screenProjectionMatrix, false); m_recalculateViewportFractions = false; } // commit view buffer cbViewConstants.CommitChanges(m_pCommandList); } void GPUContextConstants::CommitGlobalConstantBufferChanges() { cbGlobalConstants.CommitChanges(m_pCommandList); } <file_sep>/Engine/Source/Engine/ParticleSystemRenderProxy.h #pragma once #include "Engine/ParticleSystem.h" #include "Renderer/RenderProxy.h" // ParticleSystemRenderProxy does not hold a reference on the instance data, it is assumed the // holding class will maintain this reference, and keep a copy of the associated data. class ParticleSystemRenderProxy : public RenderProxy { public: ParticleSystemRenderProxy(const ParticleSystem *pParticleSystem, uint32 entityID); virtual ~ParticleSystemRenderProxy(); // get the current bounding box of the particle system (game thread) const AABox &GetParticleSystemBoundingBox() const { return m_pEmitterInstanceData->BoundingBox; } // particle system const ParticleSystem *GetParticleSystem() const { return m_pParticleSystem; } void SetParticleSystem(const ParticleSystem *pParticleSystem); // reset the particle system back to initial state void Reset(); // update the particle system. call from the game thread. void Update(const Transform *pBaseTransform, float deltaTime); // Draw methods virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override final; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override final; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override final; private: // Create instance data void CreateInstanceData(); // Cleanup instance data void DeleteInstanceData(); const ParticleSystem *m_pParticleSystem; ParticleSystemEmitter::InstanceData *m_pEmitterInstanceData; ParticleSystemEmitter::InstanceRenderData *m_pEmitterInstanceRenderData; uint32 m_emitterCount; float m_timeSinceLastUpdate; }; <file_sep>/Engine/Source/ContentConverterStandalone/CMakeLists.txt set(HEADER_FILES ContentConverter.h ) set(SOURCE_FILES AssimpSceneImporter.cpp AssimpSkeletalAnimationImporter.cpp AssimpSkeletalMeshImporter.cpp AssimpSkeletonImporter.cpp AssimpStaticMeshImporter.cpp FontImporter.cpp Main.cpp OBJImporter.cpp TextureImporter.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${TOOLS_BASE_DIRECTORY}/ContentConverter) add_executable(ContentConverter ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(ContentConverter EngineContentConverter EngineMain EngineCore) <file_sep>/Engine/Source/Engine/SkeletalAnimation.h #pragma once #include "Engine/Common.h" #include "Engine/Skeleton.h" class SkeletalAnimation : public Resource { DECLARE_RESOURCE_TYPE_INFO(SkeletalAnimation, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(SkeletalAnimation); public: class TransformTrack { public: typedef KeyValuePair<float, Transform> KeyFrame; public: const float GetDuration() const { return m_duration; } // look up the keyframes for a specified time void GetKeyFrames(float time, const KeyFrame **ppStartKeyFrame, const KeyFrame **ppEndKeyFrame, float *pFactor) const; // look up the transform for a specified time void GetBoneTransform(float time, Transform *pTransform, bool interpolate = true) const; protected: // load keyframes from stream bool LoadKeyFramesFromStream(ByteStream *pStream, float duration, uint32 keyFrameCount); // keyframe data float m_duration; MemArray<KeyFrame> m_keyFrames; }; class BoneTrack : public TransformTrack { public: // look up bone index const uint32 GetBoneIndex() const { return m_boneIndex; } // read from a stream bool LoadFromStream(ByteStream *pStream, const Skeleton *pSkeleton); protected: uint32 m_boneIndex; }; class RootMotionTrack : public TransformTrack { public: // read from a stream bool LoadFromStream(ByteStream *pStream, const Skeleton *pSkeleton); }; public: SkeletalAnimation(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); virtual ~SkeletalAnimation(); // skeleton const Skeleton *GetSkeleton() const { return m_pSkeleton; } // parameters float GetDuration() const { return m_duration; } // bone tracks const TransformTrack *GetBoneTrack(uint32 trackIndex) { DebugAssert(trackIndex < m_boneTrackCount); return &m_pBoneTracks[trackIndex]; } const TransformTrack *GetBoneTrackForBone(uint32 boneIndex) { DebugAssert(boneIndex < m_pSkeleton->GetBoneCount()); return m_ppBoneIndexToBoneTrack[boneIndex]; } const uint32 GetBoneTrackCount() const { return m_boneTrackCount; } // root motion track const RootMotionTrack *GetRootMotionTrack() const { return m_pRootMotionTrack; } bool HasRootMotionTrack() const { return (m_pRootMotionTrack != nullptr); } // initialization bool LoadFromStream(const char *name, ByteStream *pStream); // fast path to find the relative transform for a bone bool CalculateRelativeBoneTransform(uint32 boneIndex, float time, Transform *pTransform, bool interpolate = true) const; // slow path to find the absolute transform for a bone void CalculateAbsoluteBoneTransform(uint32 boneIndex, float time, Transform *pTransform, bool interpolate = true) const; private: const Skeleton *m_pSkeleton; float m_duration; BoneTrack *m_pBoneTracks; const BoneTrack **m_ppBoneIndexToBoneTrack; uint32 m_boneTrackCount; RootMotionTrack *m_pRootMotionTrack; }; <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUContext.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" #include "OpenGLES2Renderer/OpenGLES2GPUOutputBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUTexture.h" #include "OpenGLES2Renderer/OpenGLES2GPUBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUShaderProgram.h" #include "OpenGLES2Renderer/OpenGLES2ConstantLibrary.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(OpenGLES2RenderBackend); #define DEFER_SHADER_STATE_CHANGES 1 OpenGLES2GPUContext::OpenGLES2GPUContext(OpenGLES2GPUDevice *pDevice, SDL_GLContext pSDLGLContext, OpenGLES2GPUOutputBuffer *pOutputBuffer) { m_pDevice = pDevice; m_pDevice->SetImmediateContext(this); m_pDevice->AddRef(); m_pSDLGLContext = pSDLGLContext; m_pCurrentOutputBuffer = pOutputBuffer; m_pCurrentOutputBuffer->AddRef(); m_pConstants = nullptr; m_pConstantLibrary = nullptr; m_pConstantLibraryBuffer = nullptr; Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); m_drawTopology = DRAW_TOPOLOGY_TRIANGLE_LIST; m_glDrawTopology = GL_TRIANGLES; m_activeVertexBuffers = 0; m_dirtyVertexBuffers = false; m_activeVertexAttributes = 0; m_dirtyVertexAttributes = false; m_pCurrentIndexBuffer = nullptr; m_currentIndexFormat = GPU_INDEX_FORMAT_UINT16; m_currentIndexBufferOffset = 0; m_pCurrentShaderProgram = nullptr; m_activeTextureUnitBindings = 0; m_dirtyTextureUnitsLowerBounds = -1; m_dirtyTextureUnitsUpperBounds = -1; m_pCurrentRasterizerState = nullptr; m_pCurrentDepthStencilState = nullptr; m_currentDepthStencilStateStencilRef = 0; m_pCurrentBlendState = nullptr; m_currentBlendStateBlendFactors.SetZero(); m_drawFrameBufferObjectId = 0; m_readFrameBufferObjectId = 0; m_usingFrameBufferObject = false; m_pCurrentRenderTarget = nullptr; m_pCurrentDepthStencilBuffer = nullptr; m_pUserVertexBuffer = nullptr; m_userVertexBufferSize = 1024 * 1024; m_userVertexBufferPosition = 0; } OpenGLES2GPUContext::~OpenGLES2GPUContext() { // unbind shader stuff SetShaderVertexAttributes(nullptr, 0); CommitVertexAttributes(); for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i] != nullptr) SetShaderTextureUnit(i, nullptr); } if (m_pCurrentShaderProgram != nullptr) SetShaderProgram(nullptr); CommitShaderResources(); if (m_drawFrameBufferObjectId > 0) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &m_drawFrameBufferObjectId); } if (m_readFrameBufferObjectId > 0) glDeleteFramebuffers(1, &m_readFrameBufferObjectId); for (uint32 i = 0; i < m_activeVertexBuffers; i++) SAFE_RELEASE(m_currentVertexBuffers[i].pVertexBuffer); SAFE_RELEASE(m_pCurrentIndexBuffer); SAFE_RELEASE(m_pCurrentRasterizerState); SAFE_RELEASE(m_pCurrentDepthStencilState); SAFE_RELEASE(m_pCurrentBlendState); SAFE_RELEASE(m_pCurrentRenderTarget); SAFE_RELEASE(m_pCurrentDepthStencilBuffer); //SAFE_RELEASE(m_pUserIndexBuffer); SAFE_RELEASE(m_pUserVertexBuffer); Y_free(m_pConstantLibraryBuffer); delete m_pConstants; // unbind the context, and delete it. no more gl calls are allowed after this! DebugAssert(SDL_GL_GetCurrentContext() == m_pSDLGLContext); SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(m_pSDLGLContext); // last thing to release is the output window, this is safe because it won't make any gl calls SAFE_RELEASE(m_pCurrentOutputBuffer); // no longer the context m_pDevice->SetImmediateContext(nullptr); m_pDevice->Release(); } void OpenGLES2GPUContext::UpdateVSyncState(RENDERER_VSYNC_TYPE vsyncType) { int swapInterval = 0; switch (vsyncType) { case RENDERER_VSYNC_TYPE_NONE: swapInterval = 0; break; case RENDERER_VSYNC_TYPE_VSYNC: swapInterval = 1; break; case RENDERER_VSYNC_TYPE_ADAPTIVE_VSYNC: swapInterval = -1; break; case RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING: swapInterval = 1; break; } SDL_GL_SetSwapInterval(swapInterval); } bool OpenGLES2GPUContext::Create() { glGenFramebuffers(1, &m_drawFrameBufferObjectId); glGenFramebuffers(1, &m_readFrameBufferObjectId); if (m_drawFrameBufferObjectId == 0 || m_readFrameBufferObjectId == 0) { GL_PRINT_ERROR("OpenGLES2GPUContext::Create: glGenFrameBuffers failed: "); return false; } // allocate shader state arrays uint32 maxCombinedTextureImageUnits = 0; uint32 maxVertexAttributes = 0; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, reinterpret_cast<GLint *>(&maxCombinedTextureImageUnits)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); // these should be >0 if (maxCombinedTextureImageUnits == 0 || maxVertexAttributes == 0) { Log_ErrorPrintf("OpenGLES2GPUContext::Create: GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%u) or GL_MAX_VERTEX_ATTRIBS (%u) is below required amounts.", maxCombinedTextureImageUnits, maxVertexAttributes); return false; } // allocate storage m_currentTextureUnitBindings.Resize(maxCombinedTextureImageUnits); m_currentTextureUnitBindings.ZeroContents(); m_currentVertexAttributes.Resize(maxVertexAttributes); m_currentVertexAttributes.ZeroContents(); m_currentVertexBuffers.Resize(maxVertexAttributes); m_currentVertexBuffers.ZeroContents(); // set deps m_mutatorTextureUnit = m_currentTextureUnitBindings.GetSize() - 1; // create plain vertex buffer { GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_MAPPABLE | GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, m_userVertexBufferSize); if ((m_pUserVertexBuffer = static_cast<OpenGLES2GPUBuffer *>(m_pDevice->CreateBuffer(&vertexBufferDesc, NULL))) == NULL) { Log_ErrorPrintf("OpenGLES2GPUContext::Create: Failed to create plain dynamic vertex buffer."); return false; } } // create constants m_pConstants = new GPUContextConstants(m_pDevice, this); // allocate constant library buffer m_pConstantLibrary = m_pDevice->GetConstantLibrary(); m_pConstantLibraryBuffer = (byte *)Y_malloc(m_pConstantLibrary->GetConstantStorageBufferSize()); // update swap interval UpdateVSyncState(m_pCurrentOutputBuffer->GetVSyncType()); Log_InfoPrint("OpenGLES2GPUContext::Create: Context creation complete."); return true; } void OpenGLES2GPUContext::ClearState(bool clearShaders /* = true */, bool clearBuffers /* = true */, bool clearStates /* = true */, bool clearRenderTargets /* = true */) { if (clearShaders) { SetShaderProgram(nullptr); // unbind shader stuff SetShaderVertexAttributes(nullptr, 0); CommitVertexAttributes(); for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i] != nullptr) SetShaderTextureUnit(i, nullptr); } CommitShaderResources(); } if (clearBuffers) { for (uint32 i = 0; i < m_activeVertexBuffers; i++) SetVertexBuffer(i, nullptr, 0, 0); SetIndexBuffer(nullptr, GPU_INDEX_FORMAT_UINT16, 0); CommitVertexAttributes(); } if (clearStates) { SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState()); SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(), 0); SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); SetDrawTopology(DRAW_TOPOLOGY_UNDEFINED); RENDERER_SCISSOR_RECT scissor(0, 0, 0, 0); SetFullViewport(nullptr); SetScissorRect(&scissor); } if (clearRenderTargets) SetRenderTargets(0, nullptr, nullptr); } GPURasterizerState *OpenGLES2GPUContext::GetRasterizerState() { return m_pCurrentRasterizerState; } void OpenGLES2GPUContext::SetRasterizerState(GPURasterizerState *pRasterizerState) { if (m_pCurrentRasterizerState == pRasterizerState) return; // if new buffer is null, unbind old if (m_pCurrentRasterizerState != nullptr) { if (pRasterizerState == nullptr) m_pCurrentRasterizerState->Unapply(); m_pCurrentRasterizerState->Release(); } if ((m_pCurrentRasterizerState = static_cast<OpenGLES2GPURasterizerState *>(pRasterizerState)) != NULL) { m_pCurrentRasterizerState->AddRef(); m_pCurrentRasterizerState->Apply(); } } GPUDepthStencilState *OpenGLES2GPUContext::GetDepthStencilState() { return m_pCurrentDepthStencilState; } uint8 OpenGLES2GPUContext::GetDepthStencilStateStencilRef() { return m_currentDepthStencilStateStencilRef; } void OpenGLES2GPUContext::SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 StencilRef) { if (m_pCurrentDepthStencilState == pDepthStencilState && m_currentDepthStencilStateStencilRef == StencilRef) return; m_currentDepthStencilStateStencilRef = StencilRef; // if new buffer is null, unbind old if (m_pCurrentDepthStencilState != nullptr) { if (pDepthStencilState == nullptr) m_pCurrentDepthStencilState->Unapply(); m_pCurrentDepthStencilState->Release(); } if ((m_pCurrentDepthStencilState = static_cast<OpenGLES2GPUDepthStencilState *>(pDepthStencilState)) != NULL) { m_pCurrentDepthStencilState->AddRef(); m_pCurrentDepthStencilState->Apply(StencilRef); } } GPUBlendState *OpenGLES2GPUContext::GetBlendState() { return m_pCurrentBlendState; } const float4 &OpenGLES2GPUContext::GetBlendStateBlendFactor() { return m_currentBlendStateBlendFactors; } void OpenGLES2GPUContext::SetBlendState(GPUBlendState *pBlendState, const float4 &BlendFactor /* = float4::One */) { if (m_pCurrentBlendState != pBlendState) { // if new buffer is null, unbind old if (m_pCurrentBlendState != nullptr) { if (pBlendState == nullptr) m_pCurrentBlendState->Unapply(); m_pCurrentBlendState->Release(); } if ((m_pCurrentBlendState = static_cast<OpenGLES2GPUBlendState *>(pBlendState)) != NULL) { m_pCurrentBlendState->AddRef(); m_pCurrentBlendState->Apply(); } } if (BlendFactor != m_currentBlendStateBlendFactors) { m_currentBlendStateBlendFactors = BlendFactor; glBlendColor(BlendFactor.r, BlendFactor.g, BlendFactor.b, BlendFactor.a); } } const RENDERER_VIEWPORT *OpenGLES2GPUContext::GetViewport() { return &m_currentViewport; } void OpenGLES2GPUContext::SetViewport(const RENDERER_VIEWPORT *pNewViewport) { if (Y_memcmp(&m_currentViewport, pNewViewport, sizeof(RENDERER_VIEWPORT)) == 0) return; Y_memcpy(&m_currentViewport, pNewViewport, sizeof(m_currentViewport)); glViewport(m_currentViewport.TopLeftX, m_currentViewport.TopLeftY, m_currentViewport.Width, m_currentViewport.Height); glDepthRangef(m_currentViewport.MinDepth, m_currentViewport.MaxDepth); // update constants m_pConstants->SetViewportOffset((float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, false); m_pConstants->SetViewportSize((float)m_currentViewport.Width, (float)m_currentViewport.Height, false); m_pConstants->CommitChanges(); } void OpenGLES2GPUContext::SetFullViewport(GPUTexture *pForRenderTarget /*= NULL*/) { RENDERER_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; if (pForRenderTarget == nullptr && m_pCurrentRenderTarget == nullptr && m_pCurrentDepthStencilBuffer == nullptr) { viewport.Width = m_pCurrentOutputBuffer->GetWidth(); viewport.Height = m_pCurrentOutputBuffer->GetHeight(); } else { DebugAssert(m_pCurrentRenderTarget != nullptr || m_pCurrentDepthStencilBuffer != nullptr || pForRenderTarget != nullptr); GPUTexture *pRT = pForRenderTarget; if (pRT == nullptr) pRT = (m_pCurrentRenderTarget != nullptr) ? m_pCurrentDepthStencilBuffer->GetTargetTexture() : m_pCurrentRenderTarget->GetTargetTexture(); DebugAssert(pRT != nullptr); uint3 renderTargetDimensions = Renderer::GetTextureDimensions(pRT); viewport.Width = renderTargetDimensions.x; viewport.Height = renderTargetDimensions.y; } viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; SetViewport(&viewport); // fix scissor rect if (m_scissorRect.Top != m_scissorRect.Bottom) glScissor(m_scissorRect.Left, m_currentViewport.Height - m_scissorRect.Bottom, m_scissorRect.Right - m_scissorRect.Left, m_scissorRect.Bottom - m_scissorRect.Top); } const RENDERER_SCISSOR_RECT *OpenGLES2GPUContext::GetScissorRect() { return &m_scissorRect; } void OpenGLES2GPUContext::SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) { if (Y_memcmp(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)) == 0) return; Y_memcpy(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)); glScissor(m_scissorRect.Left, m_currentViewport.Height - m_scissorRect.Bottom, m_scissorRect.Right - m_scissorRect.Left, m_scissorRect.Bottom - m_scissorRect.Top); } void OpenGLES2GPUContext::ClearTargets(bool clearColor /* = true */, bool clearDepth /* = true */, bool clearStencil /* = true */, const float4 &clearColorValue /* = float4::Zero */, float clearDepthValue /* = 1.0f */, uint8 clearStencilValue /* = 0 */) { bool oldColorWritesEnabled = (m_pCurrentBlendState == nullptr) ? true : m_pCurrentBlendState->GetGLColorWritesEnabled(); GLboolean oldDepthMask = (m_pCurrentDepthStencilState == nullptr) ? GL_TRUE : m_pCurrentDepthStencilState->GetGLDepthMask(); GLuint oldStencilMask = (m_pCurrentDepthStencilState == nullptr) ? 0xFF : m_pCurrentDepthStencilState->GetGLStencilWriteMask(); bool oldScissorTest = (m_pCurrentRasterizerState == nullptr) ? false : m_pCurrentRasterizerState->GetGLScissorTestEnable(); // change settings so the whole RT gets cleared if (!oldColorWritesEnabled) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if (oldDepthMask == GL_FALSE) glDepthMask(GL_TRUE); if (oldStencilMask != 0xFF) glStencilMask(0xFF); if (oldScissorTest) glDisable(GL_SCISSOR_TEST); // new functions aren't available on GLES GLbitfield clearMask = 0; if (clearColor) { glClearColor(clearColorValue.r, clearColorValue.g, clearColorValue.b, clearColorValue.a); clearMask |= GL_COLOR_BUFFER_BIT; } if (clearDepth) { glDepthMask(GL_TRUE); glClearDepthf(clearDepthValue); clearMask |= GL_DEPTH_BUFFER_BIT; } if (clearStencil) { glClearStencil(clearStencilValue); clearMask |= GL_STENCIL_BUFFER_BIT; } // invoke if (clearMask != 0) glClear(clearMask); // restore settings if (oldScissorTest) glEnable(GL_SCISSOR_TEST); if (oldStencilMask != 0xFF) glStencilMask(0xFF); if (oldDepthMask == GL_FALSE) glDepthMask(GL_FALSE); if (!oldColorWritesEnabled) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } void OpenGLES2GPUContext::DiscardTargets(bool discardColor /* = true */, bool discardDepth /* = true */, bool discardStencil /* = true */) { #ifdef GL_EXT_discard_framebuffer if (GLAD_GL_EXT_discard_framebuffer) { GLenum attachments[3]; uint32 nAttachments = 0; // ugh, multiple paths again??! if (m_pCurrentRenderTarget != nullptr || m_pCurrentDepthStencilBuffer != nullptr) { if (discardColor) attachments[nAttachments++] = GL_COLOR_ATTACHMENT0; if (discardDepth) attachments[nAttachments++] = GL_DEPTH_ATTACHMENT; if (discardStencil) attachments[nAttachments++] = GL_STENCIL_ATTACHMENT; } else { if (discardColor) attachments[nAttachments++] = GL_COLOR_EXT; if (discardDepth) attachments[nAttachments++] = GL_DEPTH_EXT; if (discardStencil) attachments[nAttachments++] = GL_STENCIL_EXT; } glDiscardFramebufferEXT(GL_FRAMEBUFFER, nAttachments, attachments); } #endif } GPUOutputBuffer *OpenGLES2GPUContext::GetOutputBuffer() { return m_pCurrentOutputBuffer; } void OpenGLES2GPUContext::SetOutputBuffer(GPUOutputBuffer *pSwapChain) { OpenGLES2GPUOutputBuffer *pOpenGLOutputBuffer = static_cast<OpenGLES2GPUOutputBuffer *>(pSwapChain); DebugAssert(pOpenGLOutputBuffer != nullptr); // same? if (m_pCurrentOutputBuffer == pOpenGLOutputBuffer) return; // make this the new current context if (SDL_GL_MakeCurrent(pOpenGLOutputBuffer->GetSDLWindow(), m_pSDLGLContext) != 0) { Log_ErrorPrintf("OpenGLES2GPUContext::SetOutputBuffer: SDL_GL_MakeCurrent failed: %s", SDL_GetError()); Panic("SDL_GL_MakeCurrent failed"); } // update swap interval if (pOpenGLOutputBuffer->GetVSyncType() != m_pCurrentOutputBuffer->GetVSyncType()) UpdateVSyncState(pOpenGLOutputBuffer->GetVSyncType()); // update pointers m_pCurrentOutputBuffer->Release(); m_pCurrentOutputBuffer = pOpenGLOutputBuffer; m_pCurrentOutputBuffer->AddRef(); } bool OpenGLES2GPUContext::GetExclusiveFullScreen() { if (SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN) return true; else return false; } bool OpenGLES2GPUContext::SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) { if (enabled) { // find the matching sdl pixel format SDL_DisplayMode preferredDisplayMode; preferredDisplayMode.w = (width == 0) ? m_pCurrentOutputBuffer->GetWidth() : width; preferredDisplayMode.h = (height == 0) ? m_pCurrentOutputBuffer->GetHeight() : height; preferredDisplayMode.refresh_rate = refreshRate; preferredDisplayMode.driverdata = nullptr; // we only have a limited number of backbuffer format possibilities switch (m_pCurrentOutputBuffer->GetBackBufferFormat()) { case PIXEL_FORMAT_R8G8B8A8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_RGBA8888; break; case PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_RGBA8888; break; case PIXEL_FORMAT_B8G8R8A8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRA8888; break; case PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRA8888; break; case PIXEL_FORMAT_B8G8R8X8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRX8888; break; case PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRX8888; break; default: Log_ErrorPrintf("OpenGLES2GPUContext::SetExclusiveFullScreen: Unable to find SDL pixel format for %s", PixelFormat_GetPixelFormatInfo(m_pCurrentOutputBuffer->GetBackBufferFormat())->Name); return false; } // find the closest match SDL_DisplayMode foundDisplayMode; if (SDL_GetClosestDisplayMode(0, &preferredDisplayMode, &foundDisplayMode) == nullptr) { Log_ErrorPrintf("OpenGLES2GPUContext::SetExclusiveFullScreen: Unable to find matching video mode for: %i x %i (%s)", preferredDisplayMode.w, preferredDisplayMode.h, PixelFormat_GetPixelFormatInfo(m_pCurrentOutputBuffer->GetBackBufferFormat())->Name); return false; } // change to this mode if (SDL_SetWindowDisplayMode(m_pCurrentOutputBuffer->GetSDLWindow(), &foundDisplayMode) != 0) { Log_ErrorPrintf("OpenGLES2GPUContext::SetExclusiveFullScreen: SDL_SetWindowDisplayMode failed: %s", SDL_GetError()); return false; } // and switch to fullscreen if not already there if (!(SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN)) { if (SDL_SetWindowFullscreen(m_pCurrentOutputBuffer->GetSDLWindow(), SDL_WINDOW_FULLSCREEN) != 0) { Log_ErrorPrintf("OpenGLES2GPUContext::SetExclusiveFullScreen: SDL_SetWindowFullscreen failed: %s", SDL_GetError()); return false; } } // update the window size m_pCurrentOutputBuffer->Resize(foundDisplayMode.w, foundDisplayMode.h); return true; } else { // leaving fullscreen if (SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN) { if (SDL_SetWindowFullscreen(m_pCurrentOutputBuffer->GetSDLWindow(), 0) != 0) { Log_ErrorPrintf("OpenGLES2GPUContext::SetExclusiveFullScreen: SDL_SetWindowFullscreen failed: %s", SDL_GetError()); return false; } } // get window size int windowWidth, windowHeight; SDL_GetWindowSize(m_pCurrentOutputBuffer->GetSDLWindow(), &windowWidth, &windowHeight); m_pCurrentOutputBuffer->Resize(windowWidth, windowHeight); return true; } } bool OpenGLES2GPUContext::ResizeOutputBuffer(uint32 width /* = 0 */, uint32 height /* = 0 */) { // GL buffers are automatically resized m_pCurrentOutputBuffer->Resize(width, height); return true; } void OpenGLES2GPUContext::PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) { // @TODO: Present Behaviour SDL_GL_SwapWindow(m_pCurrentOutputBuffer->GetSDLWindow()); } void OpenGLES2GPUContext::BeginFrame() { } void OpenGLES2GPUContext::Flush() { glFlush(); } void OpenGLES2GPUContext::Finish() { glFinish(); } uint32 OpenGLES2GPUContext::GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) { if (nRenderTargets >= 1) ppRenderTargetViews[0] = m_pCurrentRenderTarget; if (ppDepthBufferView != nullptr) *ppDepthBufferView = m_pCurrentDepthStencilBuffer; return (m_pCurrentRenderTarget != nullptr) ? Min(nRenderTargets, (uint32)1) : 0; } void OpenGLES2GPUContext::SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) { // GLES only does 1 render target DebugAssert(nRenderTargets <= 1); // switch to swap chain? if ((nRenderTargets == 0 || ppRenderTargets[0] == nullptr) && pDepthBufferView == nullptr) { // currently using FBO? if (m_usingFrameBufferObject) { if (m_pCurrentRenderTarget != nullptr) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); m_pCurrentRenderTarget->Release(); m_pCurrentRenderTarget = nullptr; } if (m_pCurrentDepthStencilBuffer != nullptr) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, m_pCurrentDepthStencilBuffer->GetAttachmentPoint(), GL_RENDERBUFFER, 0); m_pCurrentDepthStencilBuffer->Release(); m_pCurrentDepthStencilBuffer = nullptr; } glBindFramebuffer(GL_FRAMEBUFFER, 0); m_usingFrameBufferObject = false; } // done return; } // not currently using fbo? if (!m_usingFrameBufferObject) { // bind fbo glBindFramebuffer(GL_FRAMEBUFFER, m_drawFrameBufferObjectId); m_usingFrameBufferObject = true; } // rtv changed? if ((nRenderTargets == 0 && m_pCurrentRenderTarget != nullptr) || (nRenderTargets > 0 && m_pCurrentRenderTarget != ppRenderTargets[0])) { OpenGLES2GPURenderTargetView *pOldRTV = m_pCurrentRenderTarget; if (nRenderTargets > 0 && ppRenderTargets[0] != nullptr) { m_pCurrentRenderTarget = static_cast<OpenGLES2GPURenderTargetView *>(ppRenderTargets[0]); m_pCurrentRenderTarget->AddRef(); switch (m_pCurrentRenderTarget->GetTextureType()) { case TEXTURE_TYPE_2D: glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pCurrentRenderTarget->GetTextureName(), m_pCurrentRenderTarget->GetDesc()->MipLevel); break; default: glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); break; } if (pOldRTV != nullptr) pOldRTV->Release(); } else if (pOldRTV != nullptr) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); pOldRTV->Release(); } } // dsv changed? if (m_pCurrentDepthStencilBuffer != pDepthBufferView) { OpenGLES2GPUDepthStencilBufferView *pOldDSV = m_pCurrentDepthStencilBuffer; if (pDepthBufferView != nullptr) { m_pCurrentDepthStencilBuffer = static_cast<OpenGLES2GPUDepthStencilBufferView *>(pDepthBufferView); m_pCurrentDepthStencilBuffer->AddRef(); switch (m_pCurrentDepthStencilBuffer->GetTextureType()) { case TEXTURE_TYPE_2D: glFramebufferTexture2D(GL_FRAMEBUFFER, m_pCurrentDepthStencilBuffer->GetAttachmentPoint(), GL_TEXTURE_2D, m_pCurrentDepthStencilBuffer->GetTextureName(), m_pCurrentDepthStencilBuffer->GetDesc()->MipLevel); break; case TEXTURE_TYPE_DEPTH: glFramebufferRenderbuffer(GL_FRAMEBUFFER, m_pCurrentDepthStencilBuffer->GetAttachmentPoint(), GL_RENDERBUFFER, m_pCurrentDepthStencilBuffer->GetTextureName()); break; default: glFramebufferRenderbuffer(GL_FRAMEBUFFER, m_pCurrentDepthStencilBuffer->GetAttachmentPoint(), GL_RENDERBUFFER, 0); break; } if (pOldDSV != nullptr) pOldDSV->Release(); } else if (pOldDSV != nullptr) { glFramebufferTexture2D(GL_FRAMEBUFFER, pOldDSV->GetAttachmentPoint(), 0, 0, 0); pOldDSV->Release(); } } #ifdef Y_BUILD_CONFIG_DEBUG // check fbo completeness GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); DebugAssert(status == GL_FRAMEBUFFER_COMPLETE); #endif } DRAW_TOPOLOGY OpenGLES2GPUContext::GetDrawTopology() { return m_drawTopology; } void OpenGLES2GPUContext::SetDrawTopology(DRAW_TOPOLOGY topology) { DebugAssert(topology < DRAW_TOPOLOGY_COUNT); if (topology == m_drawTopology) return; m_drawTopology = topology; switch (topology) { case DRAW_TOPOLOGY_POINTS: m_glDrawTopology = GL_POINTS; break; case DRAW_TOPOLOGY_LINE_LIST: m_glDrawTopology = GL_LINES; break; case DRAW_TOPOLOGY_LINE_STRIP: m_glDrawTopology = GL_LINE_STRIP; break; case DRAW_TOPOLOGY_TRIANGLE_LIST: m_glDrawTopology = GL_TRIANGLES; break; case DRAW_TOPOLOGY_TRIANGLE_STRIP: m_glDrawTopology = GL_TRIANGLE_STRIP; break; } } uint32 OpenGLES2GPUContext::GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < m_currentVertexBuffers.GetSize()); uint32 count; for (count = 0; count < nBuffers; count++) { uint32 idx = firstBuffer + count; if (idx >= m_activeVertexBuffers) break; VertexBufferBinding *vb = &m_currentVertexBuffers[idx]; ppVertexBuffers[count] = vb->pVertexBuffer; pVertexBufferOffsets[count] = vb->Offset; pVertexBufferStrides[count] = vb->Stride; } return count; } void OpenGLES2GPUContext::SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < m_currentVertexBuffers.GetSize()); // update each buffer bool updateDirtyFlag = false; for (uint32 i = 0; i < nBuffers; i++) { uint32 bufferIndex = firstBuffer + i; VertexBufferBinding *vbBinding = &m_currentVertexBuffers[bufferIndex]; OpenGLES2GPUBuffer *pBuffer = static_cast<OpenGLES2GPUBuffer *>(ppVertexBuffers[i]); uint32 bufferOffset = pVertexBufferOffsets[i]; uint32 bufferStride = pVertexBufferStrides[i]; // any changes? if (vbBinding->pVertexBuffer != pBuffer || vbBinding->Offset != bufferOffset || vbBinding->Stride != bufferStride) { // buffer change? if (vbBinding->pVertexBuffer != pBuffer) { if (vbBinding->pVertexBuffer != nullptr) vbBinding->pVertexBuffer->Release(); if ((vbBinding->pVertexBuffer = pBuffer) != nullptr) { vbBinding->pVertexBuffer->AddRef(); vbBinding->Offset = pVertexBufferOffsets[i]; vbBinding->Stride = pVertexBufferStrides[i]; } else { vbBinding->Offset = 0; vbBinding->Stride = 0; } } // dirty flag vbBinding->Dirty = true; updateDirtyFlag = true; } } // update active range uint32 searchCount = Max(m_activeVertexBuffers, firstBuffer + nBuffers); uint32 activeCount = 0; for (uint32 i = 0; i < searchCount; i++) { const VertexBufferBinding *binding = &m_currentVertexBuffers[i]; if (binding->pVertexBuffer != nullptr || binding->Dirty) activeCount = i + 1; } m_activeVertexBuffers = activeCount; // dirty flag m_dirtyVertexBuffers |= updateDirtyFlag; } void OpenGLES2GPUContext::SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { DebugAssert(bufferIndex < m_currentVertexBuffers.GetSize()); VertexBufferBinding *vbBinding = &m_currentVertexBuffers[bufferIndex]; OpenGLES2GPUBuffer *pBuffer = static_cast<OpenGLES2GPUBuffer *>(pVertexBuffer); // any changes? if (vbBinding->pVertexBuffer != pBuffer || vbBinding->Offset != offset || vbBinding->Stride != stride) { // buffer change? if (vbBinding->pVertexBuffer != pBuffer) { if (vbBinding->pVertexBuffer != nullptr) vbBinding->pVertexBuffer->Release(); if ((vbBinding->pVertexBuffer = pBuffer) != nullptr) { vbBinding->pVertexBuffer->AddRef(); vbBinding->Offset = offset; vbBinding->Stride = stride; } else { vbBinding->Offset = 0; vbBinding->Stride = 0; } } // dirty flag vbBinding->Dirty = true; } else { // no changes return; } // update active range if (bufferIndex >= m_activeVertexBuffers) { m_activeVertexBuffers = bufferIndex + 1; } else if ((bufferIndex + 1) == m_activeVertexBuffers) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeVertexBuffers; i++) { const VertexBufferBinding *binding = &m_currentVertexBuffers[i]; if (binding->pVertexBuffer != nullptr || binding->Dirty) lastPos = i + 1; } m_activeVertexBuffers = lastPos; } // dirty flag m_dirtyVertexBuffers = true; } void OpenGLES2GPUContext::SetShaderVertexAttributes(const GPU_VERTEX_ELEMENT_DESC *pAttributeDescriptors, uint32 nAttributes) { uint32 attributeIndex; for (attributeIndex = 0; attributeIndex < nAttributes; attributeIndex++) { const GPU_VERTEX_ELEMENT_DESC *pAttributeDesc = &pAttributeDescriptors[attributeIndex]; VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; // convert to gl bool integerType; GLenum glType; GLint glSize; GLboolean glNormalized; OpenGLES2TypeConversion::GetOpenGLVAOTypeAndSizeForVertexElementType(pAttributeDesc->Type, &integerType, &glType, &glSize, &glNormalized); // handle format changes if (!pAttributeBinding->Initialized || pAttributeBinding->VertexBufferIndex != pAttributeDesc->StreamIndex || pAttributeBinding->Offset != pAttributeDesc->StreamOffset || pAttributeBinding->IntegerFormat != integerType || pAttributeBinding->Type != glType || pAttributeBinding->Size != glSize || pAttributeBinding->Normalized != glNormalized) { // initialize struct // todo: different dirty flags for each field (main, dividor, etc), worth it? pAttributeBinding->Initialized = true; pAttributeBinding->VertexBufferIndex = pAttributeDesc->StreamIndex; pAttributeBinding->Offset = pAttributeDesc->StreamOffset; pAttributeBinding->IntegerFormat = integerType; pAttributeBinding->Type = glType; pAttributeBinding->Size = glSize; pAttributeBinding->Normalized = glNormalized; pAttributeBinding->Dirty = true; m_dirtyVertexAttributes = true; } } // disable remaining attributes for (; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (pAttributeBinding->Initialized) { pAttributeBinding->VertexBufferIndex = 0; pAttributeBinding->Offset = 0; pAttributeBinding->Type = 0; pAttributeBinding->Size = 0; pAttributeBinding->Normalized = GL_FALSE; pAttributeBinding->Divisor = 0; pAttributeBinding->IntegerFormat = false; pAttributeBinding->Initialized = false; pAttributeBinding->Dirty = true; m_dirtyVertexAttributes = true; } } // update active count, keep it as low as possible m_activeVertexAttributes = Max(m_activeVertexAttributes, nAttributes); } void OpenGLES2GPUContext::CommitVertexAttributes() { if (!(m_dirtyVertexAttributes | m_dirtyVertexBuffers)) return; uint32 lastBufferIndex = 0xFFFFFFFF; uint32 nActiveAttributes = 0; for (uint32 attributeIndex = 0; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (!pAttributeBinding->Initialized) { // non-initialized attributes, should be disabled, could also check dirty flag here too if (pAttributeBinding->Enabled) { glDisableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = false; pAttributeBinding->Dirty = false; } // skip continue; } // skip non-dirty attributes+buffers const VertexBufferBinding *pVertexBufferBinding = &m_currentVertexBuffers[pAttributeBinding->VertexBufferIndex]; if (!(pAttributeBinding->Dirty | pVertexBufferBinding->Dirty)) { nActiveAttributes = attributeIndex + 1; continue; } // determine whether it should be enabled if (pVertexBufferBinding->pVertexBuffer != nullptr) { // should it be enabled? if (lastBufferIndex != pAttributeBinding->VertexBufferIndex) { glBindBuffer(GL_ARRAY_BUFFER, pVertexBufferBinding->pVertexBuffer->GetGLBufferId()); lastBufferIndex = pAttributeBinding->VertexBufferIndex; } // set the pointer if (pAttributeBinding->IntegerFormat) glVertexAttribIPointer(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pVertexBufferBinding->Stride, reinterpret_cast<const void *>(pVertexBufferBinding->Offset + pAttributeBinding->Offset)); else glVertexAttribPointer(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pAttributeBinding->Normalized, pVertexBufferBinding->Stride, reinterpret_cast<const void *>(pVertexBufferBinding->Offset + pAttributeBinding->Offset)); // and divisor glVertexAttribDivisor(attributeIndex, pAttributeBinding->Divisor); // enable attribute if (!pAttributeBinding->Enabled) { glEnableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = true; } // update max index nActiveAttributes = attributeIndex + 1; } else { // disable attribute if enabled if (pAttributeBinding->Enabled) { glDisableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = false; } } // clear dirty flag on attribute pAttributeBinding->Dirty = false; } // clear buffer binding if (lastBufferIndex != 0xFFFFFFFF) glBindBuffer(GL_ARRAY_BUFFER, 0); // flag all vertex buffers as clean for (uint32 vertexBufferIndex = 0; vertexBufferIndex < m_activeVertexBuffers; vertexBufferIndex++) m_currentVertexBuffers[vertexBufferIndex].Dirty = false; // and the global flags m_dirtyVertexAttributes = false; m_dirtyVertexBuffers = false; } void OpenGLES2GPUContext::GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) { *ppBuffer = m_pCurrentIndexBuffer; *pFormat = m_currentIndexFormat; *pOffset = m_currentIndexBufferOffset; } void OpenGLES2GPUContext::SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) { if (m_pCurrentIndexBuffer == pBuffer && m_currentIndexFormat == format && m_currentIndexBufferOffset == offset) return; GPUBuffer *pOldIndexBuffer = m_pCurrentIndexBuffer; if ((m_pCurrentIndexBuffer = static_cast<OpenGLES2GPUBuffer *>(pBuffer)) != NULL) { m_pCurrentIndexBuffer->AddRef(); m_currentIndexFormat = format; DebugAssert(m_pCurrentIndexBuffer->GetGLBufferTarget() == GL_ELEMENT_ARRAY_BUFFER); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pCurrentIndexBuffer->GetGLBufferId()); } else { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_currentIndexFormat = GPU_INDEX_FORMAT_UINT16; } if (pOldIndexBuffer != NULL) pOldIndexBuffer->Release(); } void OpenGLES2GPUContext::SetShaderProgram(GPUShaderProgram *pShaderProgram) { if (m_pCurrentShaderProgram == pShaderProgram) return; OpenGLES2GPUShaderProgram *pGLShaderProgram = static_cast<OpenGLES2GPUShaderProgram *>(pShaderProgram); if (m_pCurrentShaderProgram != nullptr && pGLShaderProgram != nullptr) { pGLShaderProgram->Switch(this, m_pCurrentShaderProgram); m_pCurrentShaderProgram->Release(); m_pCurrentShaderProgram = pGLShaderProgram; m_pCurrentShaderProgram->AddRef(); } else { if (m_pCurrentShaderProgram != nullptr) { m_pCurrentShaderProgram->Unbind(this); m_pCurrentShaderProgram->Release(); } if ((m_pCurrentShaderProgram = pGLShaderProgram) != nullptr) { m_pCurrentShaderProgram->Bind(this); m_pCurrentShaderProgram->AddRef(); } } } void OpenGLES2GPUContext::SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValue(this, index, valueType, pValue); } void OpenGLES2GPUContext::SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValueArray(this, index, valueType, pValue, firstElement, numElements); } void OpenGLES2GPUContext::SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) { Log_ErrorPrintf("Unsupported in GLES 2.0"); return; } void OpenGLES2GPUContext::SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { Log_ErrorPrintf("Unsupported in GLES 2.0"); return; } void OpenGLES2GPUContext::SetShaderParameterResource(uint32 index, GPUResource *pResource) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterTexture(this, index, pResource); } void OpenGLES2GPUContext::SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (pSamplerState != nullptr) Log_WarningPrintf("Sampler state will be ignored for GLES 2.0"); m_pCurrentShaderProgram->InternalSetParameterTexture(this, index, pTexture); } void OpenGLES2GPUContext::WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit /* = false */) { // Get the starting offset uint32 globalBufferOffset = m_pConstantLibrary->GetBufferStartOffset(bufferIndex); if (globalBufferOffset == OpenGLES2ConstantLibrary::BufferOffsetInvalid) return; // Check buffer bounds globalBufferOffset += offset; DebugAssert((globalBufferOffset + count) <= m_pConstantLibrary->GetConstantStorageBufferSize()); // No changes, bail out if (Y_memcmp(pData, m_pConstantLibraryBuffer + globalBufferOffset, count) == 0) return; // Move data in Y_memcpy(m_pConstantLibraryBuffer + globalBufferOffset, pData, count); // Update shader if (m_pCurrentShaderProgram != nullptr) { // got a field index? if (fieldIndex != 0xFFFFFFFF) { // Lookup this constant in the library OpenGLES2ConstantLibrary::ConstantID constantID = m_pConstantLibrary->LookupConstantID(bufferIndex, fieldIndex); if (constantID != OpenGLES2ConstantLibrary::ConstantIndexInvalid) m_pCurrentShaderProgram->OnLibraryConstantChanged(constantID); } else { // if field offset isn't specified, we have to find what intersects OpenGLES2ConstantLibrary::ConstantID firstConstantID, lastConstantID; if (!m_pConstantLibrary->FindConstantsAtOffset(bufferIndex, offset, offset + count - 1, &firstConstantID, &lastConstantID)) return; // Notify shader if (m_pCurrentShaderProgram != nullptr) { for (OpenGLES2ConstantLibrary::ConstantID constantID = firstConstantID; constantID <= lastConstantID; constantID++) m_pCurrentShaderProgram->OnLibraryConstantChanged(constantID); } } } } void OpenGLES2GPUContext::WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit) { // Get the starting offset uint32 globalBufferOffset = m_pConstantLibrary->GetBufferStartOffset(bufferIndex); if (globalBufferOffset == OpenGLES2ConstantLibrary::BufferOffsetInvalid) return; // Check buffer bounds globalBufferOffset += offset; DebugAssert((globalBufferOffset + count * bufferStride) <= m_pConstantLibrary->GetConstantStorageBufferSize()); // Anything changed? if (Y_memcmp_stride(pData, copySize, m_pConstantLibraryBuffer + globalBufferOffset, bufferStride, copySize, count) == 0) return; // Move data in Y_memcpy_stride(m_pConstantLibraryBuffer + globalBufferOffset, bufferStride, pData, copySize, copySize, count); // Update shader if (m_pCurrentShaderProgram != nullptr) { // got a field index? if (fieldIndex != 0xFFFFFFFF) { // Lookup this constant in the library OpenGLES2ConstantLibrary::ConstantID constantID = m_pConstantLibrary->LookupConstantID(bufferIndex, fieldIndex); if (constantID != OpenGLES2ConstantLibrary::ConstantIndexInvalid) m_pCurrentShaderProgram->OnLibraryConstantChanged(constantID); } else { // if field offset isn't specified, we have to find what intersects OpenGLES2ConstantLibrary::ConstantID firstConstantID, lastConstantID; if (!m_pConstantLibrary->FindConstantsAtOffset(bufferIndex, offset, offset + count - 1, &firstConstantID, &lastConstantID)) return; // Notify shader if (m_pCurrentShaderProgram != nullptr) { for (OpenGLES2ConstantLibrary::ConstantID constantID = firstConstantID; constantID <= lastConstantID; constantID++) m_pCurrentShaderProgram->OnLibraryConstantChanged(constantID); } } } } void OpenGLES2GPUContext::CommitConstantBuffer(uint32 bufferIndex) { // Update the current program's view of the constants in this buffer (just do all buffers, ehh.) // TODO: Apply range only #if !DEFER_SHADER_STATE_CHANGES if (m_pCurrentShaderProgram != nullptr) m_pCurrentShaderProgram->CommitLibraryConstants(this); #endif } void OpenGLES2GPUContext::SetShaderTextureUnit(uint32 index, GPUTexture *pTexture) { GPUTexture *pOldTexture = m_currentTextureUnitBindings[index]; #if DEFER_SHADER_STATE_CHANGES if (pOldTexture == pTexture) return; if (pOldTexture != pTexture) { // release the old (if any) texture reference if (pOldTexture != nullptr) pOldTexture->Release(); if ((m_currentTextureUnitBindings[index] = pTexture) != nullptr) pTexture->AddRef(); } // update dirty range if (m_dirtyTextureUnitsLowerBounds < 0) { m_dirtyTextureUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = (int32)index; } else { m_dirtyTextureUnitsLowerBounds = Min(m_dirtyTextureUnitsLowerBounds, (int32)index); m_dirtyTextureUnitsUpperBounds = Max(m_dirtyTextureUnitsUpperBounds, (int32)index); } #else // texture changed? if (pOldTexture != pTexture) { // alter the binding glActiveTexture(GL_TEXTURE0 + index); OpenGLES2Helpers::BindOpenGLTexture(pTexture); glActiveTexture(GL_TEXTURE0); if (pOldTexture != nullptr) pOldTexture->Release(); if ((m_currentTextureUnitBindings[index] = pTexture) != nullptr) pTexture->AddRef(); } #endif // update counters if (pTexture != nullptr) { if (index >= m_activeTextureUnitBindings) m_activeTextureUnitBindings = index + 1; } else { if ((index + 1) == m_activeTextureUnitBindings) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i] != nullptr) lastPos = i + 1; } m_activeTextureUnitBindings = lastPos; } } } void OpenGLES2GPUContext::CommitShaderResources() { #if DEFER_SHADER_STATE_CHANGES // texture units if (m_dirtyTextureUnitsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyTextureUnitsUpperBounds - m_dirtyTextureUnitsLowerBounds + 1); for (uint32 i = 0; i < countToBind; i++) { GPUTexture *pTexture = m_currentTextureUnitBindings[m_dirtyTextureUnitsLowerBounds + i]; glActiveTexture(GL_TEXTURE0 + m_dirtyTextureUnitsLowerBounds + i); OpenGLES2Helpers::BindOpenGLTexture(pTexture); } glActiveTexture(GL_TEXTURE0); // reset dirty range m_dirtyTextureUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = -1; } if (m_pCurrentShaderProgram != nullptr) m_pCurrentShaderProgram->CommitLibraryConstants(this); #endif } void OpenGLES2GPUContext::BindMutatorTextureUnit() { glActiveTexture(GL_TEXTURE0 + m_mutatorTextureUnit); } void OpenGLES2GPUContext::RestoreMutatorTextureUnit() { OpenGLES2Helpers::BindOpenGLTexture(m_currentTextureUnitBindings[m_mutatorTextureUnit]); glActiveTexture(GL_TEXTURE0); } void OpenGLES2GPUContext::Draw(uint32 firstVertex, uint32 nVertices) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nVertices == 0) return; CommitVertexAttributes(); CommitShaderResources(); glDrawArrays(m_glDrawTopology, firstVertex, nVertices); //m_drawCallCounter++; } void OpenGLES2GPUContext::DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) { Log_ErrorPrintf("OpenGLES2GPUContext::DrawInstanced: Unsupported on GLES 2.0"); } void OpenGLES2GPUContext::DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nIndices == 0) return; DebugAssert(m_pCurrentIndexBuffer != nullptr); CommitVertexAttributes(); CommitShaderResources(); GLenum arrayType; uint32 indexBufferOffset = m_currentIndexBufferOffset; if (m_currentIndexFormat == GPU_INDEX_FORMAT_UINT32) { indexBufferOffset += startIndex * sizeof(uint32); arrayType = GL_UNSIGNED_INT; } else { indexBufferOffset += startIndex * sizeof(uint16); arrayType = GL_UNSIGNED_SHORT; } // TODO handle baseVertex > 0 by shuffling around the vertex pointers.. ugh. DebugAssert(baseVertex == 0); glDrawElements(m_glDrawTopology, nIndices, arrayType, reinterpret_cast<GLvoid *>(indexBufferOffset)); //m_drawCallCounter++; } void OpenGLES2GPUContext::DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) { Log_ErrorPrintf("OpenGLES2GPUContext::DrawIndexedInstanced: Unsupported on GLES 2.0"); } void OpenGLES2GPUContext::Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) { Log_ErrorPrintf("OpenGLES2GPUContext::Dispatch: Unsupported on GLES 2.0"); } void OpenGLES2GPUContext::DrawUserPointer(const void *pVertices, uint32 VertexSize, uint32 nVertices) { uint32 maxVerticesPerPass = m_userVertexBufferSize / VertexSize; DebugAssert(m_pCurrentShaderProgram != nullptr); // obtain the current vertex buffer in slot zero, since we need to overwrite this OpenGLES2GPUBuffer *pRestoreVertexBuffer = m_currentVertexBuffers[0].pVertexBuffer; uint32 restoreVertexBufferOffset = m_currentVertexBuffers[0].Offset; uint32 restoreVertexBufferStride = m_currentVertexBuffers[0].Stride; if (pRestoreVertexBuffer != nullptr) pRestoreVertexBuffer->AddRef(); // update uniforms CommitShaderResources(); // draw vertices loop const byte *pCurrentVertexPointer = reinterpret_cast<const byte *>(pVertices); uint32 nRemainingVertices = nVertices; while (nRemainingVertices > 0) { uint32 nVerticesThisPass = Min(nRemainingVertices, maxVerticesPerPass); uint32 spaceRequired = VertexSize * nVerticesThisPass; // use buffer sub data for ES2. discard buffer if it'll overflow. if ((m_userVertexBufferPosition + spaceRequired) >= m_userVertexBufferSize) m_userVertexBufferPosition = 0; // write to end of buffer WriteBuffer(m_pUserVertexBuffer, pCurrentVertexPointer, m_userVertexBufferPosition, spaceRequired); // bind the vertex buffer OpenGLES2GPUContext::SetVertexBuffer(0, m_pUserVertexBuffer, m_userVertexBufferPosition, VertexSize); CommitVertexAttributes(); // invoke draw glDrawArrays(m_glDrawTopology, 0, nVerticesThisPass); //m_drawCallCounter++; // increment pointers m_userVertexBufferPosition += spaceRequired; pCurrentVertexPointer += VertexSize * nVerticesThisPass; nRemainingVertices -= nVerticesThisPass; } // re-bind saved vertex buffer OpenGLES2GPUContext::SetVertexBuffer(0, pRestoreVertexBuffer, restoreVertexBufferOffset, restoreVertexBufferStride); if (pRestoreVertexBuffer != nullptr) pRestoreVertexBuffer->Release(); // leave the commit out here, next draw will fix it up anyway //CommitVertexAttributes(); } bool OpenGLES2GPUContext::CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) { // textures have to be compatible, for now this means same texture format OpenGLES2GPUTexture2D *pOpenGLSourceTexture = static_cast<OpenGLES2GPUTexture2D *>(pSourceTexture); OpenGLES2GPUTexture2D *pOpenGLDestinationTexture = static_cast<OpenGLES2GPUTexture2D *>(pDestinationTexture); if (pOpenGLSourceTexture->GetDesc()->Width != pOpenGLDestinationTexture->GetDesc()->Width || pOpenGLSourceTexture->GetDesc()->Height != pOpenGLDestinationTexture->GetDesc()->Height || pOpenGLSourceTexture->GetDesc()->Format != pOpenGLDestinationTexture->GetDesc()->Format || pOpenGLSourceTexture->GetDesc()->MipLevels != pOpenGLDestinationTexture->GetDesc()->MipLevels) { return false; } Panic(""); return true; } bool OpenGLES2GPUContext::CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) { // textures have to be compatible, for now this means same texture format OpenGLES2GPUTexture2D *pOpenGLSourceTexture = static_cast<OpenGLES2GPUTexture2D *>(pSourceTexture); OpenGLES2GPUTexture2D *pOpenGLDestinationTexture = static_cast<OpenGLES2GPUTexture2D *>(pDestinationTexture); if (pOpenGLSourceTexture->GetDesc()->Format != pOpenGLDestinationTexture->GetDesc()->Format || pOpenGLSourceTexture->GetDesc()->MipLevels != pOpenGLDestinationTexture->GetDesc()->MipLevels) { return false; } Panic(""); return true; } void OpenGLES2GPUContext::GenerateMips(GPUTexture *pTexture) { BindMutatorTextureUnit(); switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_2D: glBindTexture(GL_TEXTURE_2D, static_cast<OpenGLES2GPUTexture2D *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_2D); break; case TEXTURE_TYPE_CUBE: glBindTexture(GL_TEXTURE_CUBE_MAP, static_cast<OpenGLES2GPUTextureCube *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); break; } RestoreMutatorTextureUnit(); } // stubs bool OpenGLES2GPUContext::BeginQuery(GPUQuery *pQuery) { Log_ErrorPrint("OpenGLES2GPUContext::BeginQuery: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::EndQuery(GPUQuery *pQuery) { Log_ErrorPrint("OpenGLES2GPUContext::EndQuery: Unsupported on GLES2"); return false; } GPU_QUERY_GETDATA_RESULT OpenGLES2GPUContext::GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) { Log_ErrorPrint("OpenGLES2GPUContext::GetQueryData: Unsupported on GLES2"); return GPU_QUERY_GETDATA_RESULT_ERROR; } bool OpenGLES2GPUContext::ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) { Log_ErrorPrint("OpenGLES2GPUContext::ReadTexture<Texture1D>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) { Log_ErrorPrint("OpenGLES2GPUContext::WriteTexture<Texture1D>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { Log_ErrorPrint("OpenGLES2GPUContext::ReadTexture<Texture1DArray>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { Log_ErrorPrint("OpenGLES2GPUContext::WriteTexture<Texture1DArray>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { Log_ErrorPrint("OpenGLES2GPUContext::ReadTexture<Texture2DArray>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { Log_ErrorPrint("OpenGLES2GPUContext::WriteTexture<Texture2DArray>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { Log_ErrorPrint("OpenGLES2GPUContext::ReadTexture<Texture3D>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { Log_ErrorPrint("OpenGLES2GPUContext::WriteTexture<Texture3D>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { Log_ErrorPrint("OpenGLES2GPUContext::ReadTexture<GPUTextureCubeArray>: Unsupported on GLES2"); return false; } bool OpenGLES2GPUContext::WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { Log_ErrorPrint("OpenGLES2GPUContext::WriteTexture<TextureCubeArray>: Unsupported on GLES2"); return false; } void OpenGLES2GPUContext::SetPredication(GPUQuery *pQuery) { Log_ErrorPrint("OpenGLES2GPUContext::SetPredication: Unsupported on GLES2"); } void OpenGLES2GPUContext::BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /*= RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST*/) { Log_ErrorPrint("OpenGLES2GPUContext::BlitFrameBuffer: Unsupported on GLES2"); } GPUCommandList *OpenGLES2GPUContext::CreateCommandList() { return nullptr; } bool OpenGLES2GPUContext::OpenCommandList(GPUCommandList *pCommandList) { return false; } bool OpenGLES2GPUContext::CloseCommandList(GPUCommandList *pCommandList) { return false; } void OpenGLES2GPUContext::ExecuteCommandList(GPUCommandList *pCommandList) { Panic("Not available."); } <file_sep>/Engine/Source/Renderer/ShaderConstantBuffer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderConstantBuffer.h" #include "Renderer/Renderer.h" Log_SetChannel(ShaderConstantBuffer); ShaderConstantBuffer::RegistryType *ShaderConstantBuffer::GetRegistry() { static RegistryType registry; return &registry; } ShaderConstantBuffer::ShaderConstantBuffer(const char *bufferName, const char *instanceName, SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *pFieldDeclarations, RENDERER_PLATFORM platformRequirement, RENDERER_FEATURE_LEVEL minimumFeatureLevel, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY updateFrequency) : m_index(0xFFFFFFFF), m_bufferName(bufferName), m_instanceName(instanceName), m_platformRequirement(platformRequirement), m_updateFrequency(updateFrequency), m_pFields(pFieldDeclarations), m_nFields(0) { // count fields for (; m_pFields[m_nFields].FieldName != nullptr; m_nFields++); CalculateBufferSize(); // add to registry m_index = GetRegistry()->RegisterTypeInfo(this, m_bufferName, 0); } ShaderConstantBuffer::ShaderConstantBuffer(const char *bufferName, const char *instanceName, uint32 structSize, RENDERER_PLATFORM platformRequirement, RENDERER_FEATURE_LEVEL minimumFeatureLevel, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY updateFrequency) : m_index(0xFFFFFFFF), m_bufferName(bufferName), m_instanceName(instanceName), m_platformRequirement(platformRequirement), m_updateFrequency(updateFrequency), m_pFields(nullptr), m_nFields(0), m_bufferSize(structSize) { // add to registry m_index = GetRegistry()->RegisterTypeInfo(this, m_bufferName, 0); } ShaderConstantBuffer::~ShaderConstantBuffer() { // remove from registry GetRegistry()->UnregisterTypeInfo(this); } void ShaderConstantBuffer::CalculateBufferSize() { // packing rules for both d3d constant buffers and opengl uniform buffers: // if each field fits into the remainder of a vec4, store it there // otherwise, overflow into the next vec4. array elements are each // stored in their own vec4. static const uint32 REGISTER_SIZE_BYTES = 16; uint32 currentRegisterIndex = 0; uint32 currentRegisterOffset = 0; for (uint32 fieldIndex = 0; fieldIndex < m_nFields; fieldIndex++) { SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *field = &m_pFields[fieldIndex]; uint32 valueSize = (field->FieldType == SHADER_PARAMETER_TYPE_STRUCT) ? field->BufferArrayStride : ShaderParameterValueTypeSize(field->FieldType); uint32 registersRequired = valueSize / REGISTER_SIZE_BYTES; // if there is an array if (field->ArraySize > 1) { // start a new vec4 if (currentRegisterOffset != 0) { currentRegisterIndex++; currentRegisterOffset = 0; } // store starting offset field->BufferOffset = currentRegisterIndex * REGISTER_SIZE_BYTES; // update the alignment of each array element field->BufferArrayStride = valueSize; uint32 valueStrideRem = field->BufferArrayStride % REGISTER_SIZE_BYTES; if (valueStrideRem != 0) field->BufferArrayStride += (REGISTER_SIZE_BYTES - valueStrideRem); // align each array element to a register if (registersRequired == 0) currentRegisterIndex += field->ArraySize; else currentRegisterIndex += registersRequired * field->ArraySize; // if there are leftover bytes in the last register, save it currentRegisterOffset = valueStrideRem; } else { // can it fit in the current register? if (currentRegisterOffset != 0 && (valueSize + currentRegisterOffset) <= REGISTER_SIZE_BYTES) { // store it field->BufferOffset = currentRegisterIndex * REGISTER_SIZE_BYTES + currentRegisterOffset; field->BufferArrayStride = valueSize; // increment offset in current register currentRegisterOffset += valueSize; } else { // spill into next register if (currentRegisterOffset != 0) { currentRegisterIndex++; currentRegisterOffset = 0; } // store it field->BufferOffset = currentRegisterIndex * REGISTER_SIZE_BYTES; field->BufferArrayStride = valueSize; // leave space after the field in case another can be packed into this register currentRegisterIndex += registersRequired; currentRegisterOffset = valueSize % REGISTER_SIZE_BYTES; } } //Log_DevPrintf("constant buffer '%s' field %u (%s) offset %u stride %u", m_name, fieldIndex, field->FieldName, field->BufferOffset, field->BufferArrayStride); } // align up to the next register, opengl seems to behave this way, d3d doesn't if (currentRegisterOffset != 0) { currentRegisterIndex++; currentRegisterOffset = 0; } // calculate the overall size of the buffer m_bufferSize = currentRegisterIndex * REGISTER_SIZE_BYTES + currentRegisterOffset; //Log_DevPrintf("constant buffer '%s' buffer size %u", m_name, m_bufferSize); } // void ShaderConstantBuffer::SetContantLibraryIndex(uint32 index) // { // DebugAssert((m_index == 0xFFFFFFFF && index != 0xFFFFFFFF) || (m_index != 0xFFFFFFFF && index == 0xFFFFFFFF)); // m_index = index; // } void ShaderConstantBuffer::SetField(GPUCommandList *pCommandList, uint32 field, SHADER_PARAMETER_TYPE type, const void *pValue, bool commitChanges /* = false */) const { DebugAssert(field < m_nFields); const SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *fieldDeclaration = &m_pFields[field]; DebugAssert(fieldDeclaration->FieldType == type); uint32 valueSize = ShaderParameterValueTypeSize(fieldDeclaration->FieldType); pCommandList->WriteConstantBuffer(m_index, field, fieldDeclaration->BufferOffset, valueSize, pValue, commitChanges); } void ShaderConstantBuffer::SetFieldArray(GPUCommandList *pCommandList, uint32 field, SHADER_PARAMETER_TYPE type, uint32 firstElement, uint32 numElements, const void *pValues, bool commitChanges /* = false */) const { DebugAssert(field < m_nFields); const SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *fieldDeclaration = &m_pFields[field]; DebugAssert(fieldDeclaration->FieldType == type); DebugAssert((firstElement + numElements) <= fieldDeclaration->ArraySize); uint32 valueSize = ShaderParameterValueTypeSize(fieldDeclaration->FieldType); // do strided write? if (valueSize != fieldDeclaration->BufferArrayStride) pCommandList->WriteConstantBufferStrided(m_index, field, fieldDeclaration->BufferOffset + (firstElement * fieldDeclaration->BufferArrayStride), fieldDeclaration->BufferArrayStride, valueSize, numElements, pValues, commitChanges); else pCommandList->WriteConstantBuffer(m_index, field, fieldDeclaration->BufferOffset + (firstElement * valueSize), valueSize * numElements, pValues, commitChanges); } void ShaderConstantBuffer::SetFieldStruct(GPUCommandList *pCommandList, uint32 field, const void *pValue, uint32 valueSize, bool commitChanges) const { DebugAssert(field < m_nFields); const SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *fieldDeclaration = &m_pFields[field]; DebugAssert(fieldDeclaration->FieldType == SHADER_PARAMETER_TYPE_STRUCT); DebugAssert(valueSize <= fieldDeclaration->BufferArrayStride); pCommandList->WriteConstantBuffer(m_index, 0xFFFFFFFF, fieldDeclaration->BufferOffset, valueSize, pValue, commitChanges); } void ShaderConstantBuffer::SetFieldStructArray(GPUCommandList *pCommandList, uint32 field, const void *pValues, uint32 valueSize, uint32 firstElement, uint32 numElements, bool commitChanges) const { DebugAssert(field < m_nFields); const SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *fieldDeclaration = &m_pFields[field]; DebugAssert(fieldDeclaration->FieldType == SHADER_PARAMETER_TYPE_STRUCT); DebugAssert((firstElement + numElements) <= fieldDeclaration->ArraySize); // do strided write? if (valueSize != fieldDeclaration->BufferArrayStride) pCommandList->WriteConstantBufferStrided(m_index, 0xFFFFFFFF, fieldDeclaration->BufferOffset + (firstElement * fieldDeclaration->BufferArrayStride), fieldDeclaration->BufferArrayStride, valueSize, numElements, pValues, commitChanges); else pCommandList->WriteConstantBuffer(m_index, 0xFFFFFFFF, fieldDeclaration->BufferOffset + (firstElement * valueSize), valueSize * numElements, pValues, commitChanges); } void ShaderConstantBuffer::SetRawData(GPUCommandList *pCommandList, uint32 offset, uint32 size, const void *data, bool commitChanges /* = false */) { DebugAssert((offset + size) <= m_bufferSize); pCommandList->WriteConstantBuffer(m_index, 0xFFFFFFFF, offset, size, data, commitChanges); } void ShaderConstantBuffer::CommitChanges(GPUCommandList *pCommandList) { // just forward through pCommandList->CommitConstantBuffer(m_index); } const ShaderConstantBuffer *ShaderConstantBuffer::GetShaderConstantBufferByName(const char *name, RENDERER_PLATFORM platform /*= RENDERER_PLATFORM_COUNT*/, RENDERER_FEATURE_LEVEL featureLevel /*= RENDERER_FEATURE_LEVEL_COUNT*/) { const ShaderConstantBuffer::RegistryType *registry = GetRegistry(); for (uint32 index = 0; index < registry->GetNumTypes(); index++) { const ShaderConstantBuffer *pBuffer = registry->GetTypeInfoByIndex(index); if (pBuffer == nullptr) continue; // check platform requirement if (platform != RENDERER_PLATFORM_COUNT && pBuffer->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && pBuffer->GetPlatformRequirement() != platform) continue; // check feature level requirement if (featureLevel != RENDERER_FEATURE_LEVEL_COUNT && pBuffer->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && pBuffer->GetMinimumFeatureLevel() > featureLevel) continue; // check name if (Y_strcmp(pBuffer->GetBufferName(), name) == 0) return pBuffer; } return nullptr; } <file_sep>/Engine/Source/Renderer/RenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxy.h" #include "Renderer/RenderWorld.h" RenderProxy::RenderProxy(uint32 entityId) : m_iEntityId(entityId), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_pRenderWorld(NULL) { } RenderProxy::~RenderProxy() { DebugAssert(m_pRenderWorld == NULL); } void RenderProxy::SetBounds(const AABox &boundingBox, const Sphere &boundingSphere) { if (m_boundingBox != boundingBox || m_boundingSphere != boundingSphere) { m_boundingBox = boundingBox; m_boundingSphere = boundingSphere; if (m_pRenderWorld != NULL) m_pRenderWorld->MoveRenderable(this); } } <file_sep>/Engine/Source/D3D11Renderer/CMakeLists.txt set(HEADER_FILES ) set(SOURCE_FILES ) #include_directories(${ENGINE_BASE_DIRECTORY}) #add_library(EngineMain STATIC ${HEADER_FILES} ${SOURCE_FILES}) #target_link_libraries(EngineMain EngineCore bullet) <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUShaderProgram.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D11Renderer/D3DShaderCacheEntry.h" class ShaderConstantBuffer; class D3D12GPUShaderProgram : public GPUShaderProgram { public: struct ConstantBuffer { // @TODO this class could potentially be removed to save a level of indirection String Name; uint32 ParameterIndex; uint32 MinimumSize; uint32 EngineConstantBufferIndex; const ShaderConstantBuffer *pEngineConstantBuffer; }; struct ShaderParameter { String Name; SHADER_PARAMETER_TYPE Type; uint32 ConstantBufferIndex; uint32 ConstantBufferOffset; uint32 ArraySize; uint32 ArrayStride; D3D_SHADER_BIND_TARGET BindTarget; int32 BindPoint[SHADER_PROGRAM_STAGE_COUNT]; int32 LinkedSamplerIndex; }; // pipeline object key struct PipelineStateKey { D3D12_RASTERIZER_DESC RasterizerState; D3D12_DEPTH_STENCIL_DESC DepthStencilState; D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType; D3D12_BLEND_DESC BlendState; uint32 RenderTargetCount; PIXEL_FORMAT RTVFormats[8]; PIXEL_FORMAT DSVFormat; }; public: D3D12GPUShaderProgram(D3D12GPUDevice *pDevice); virtual ~D3D12GPUShaderProgram(); // resource virtuals virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; // create bool Create(D3D12GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, ByteStream *pByteCodeStream); // switch context to a new shader bool Switch(D3D12GPUContext *pContext, ID3D12GraphicsCommandList *pD3DCommandList, const PipelineStateKey *pKey); bool Switch(D3D12GPUCommandList *pCommandList, ID3D12GraphicsCommandList *pD3DCommandList, const PipelineStateKey *pKey); void RebindPerDrawConstantBuffer(D3D12GPUContext *pContext, uint32 constantBufferIndex, D3D12_GPU_VIRTUAL_ADDRESS address); void RebindPerDrawConstantBuffer(D3D12GPUCommandList *pCommandList, uint32 constantBufferIndex, D3D12_GPU_VIRTUAL_ADDRESS address); // --- internal query api --- uint32 InternalGetParameterCount() const { return m_parameters.GetSize(); } const ShaderParameter *GetParameter(uint32 Index) const { DebugAssert(Index < m_parameters.GetSize()); return &m_parameters[Index]; } // --- internal parameter api --- void InternalSetParameterValue(D3D12GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue); void InternalSetParameterValue(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue); void InternalSetParameterValueArray(D3D12GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements); void InternalSetParameterValueArray(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements); void InternalSetParameterStruct(D3D12GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize); void InternalSetParameterStruct(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, const void *pValue, uint32 valueSize); void InternalSetParameterStructArray(D3D12GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements); void InternalSetParameterStructArray(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements); void InternalSetParameterResource(D3D12GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState); void InternalSetParameterResource(D3D12GPUCommandList *pCommandList, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState); // --- pipeline state accessor --- ID3D12PipelineState *GetPipelineState(const PipelineStateKey *pKey); // --- public parameter api --- virtual uint32 GetParameterCount() const override; virtual void GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) override; protected: // arrays typedef Array<ConstantBuffer> ConstantBufferArray; typedef Array<ShaderParameter> ParameterArray; // device pointer D3D12GPUDevice *m_pDevice; // compiled pipeline object struct PipelineState { ID3D12PipelineState *pPipelineState; uint32 Key1; uint32 Key2[4]; }; MemArray<PipelineState> m_pipelineStates; ReadWriteLock m_pipelineStateLock; // vertex attributes MemArray<D3D12_INPUT_ELEMENT_DESC> m_vertexAttributes; // arrays of above ConstantBufferArray m_constantBuffers; ParameterArray m_parameters; // copies of bytecode for all shader stages BinaryBlob *m_pStageByteCode[SHADER_PROGRAM_STAGE_COUNT]; // debug name String m_debugName; }; <file_sep>/Engine/Source/MathLib/StringConverters.cpp #include "MathLib/StringConverters.h" #include "YBaseLib/StringConverter.h" Vector2f StringConverter::StringToVector2f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector2f res(Vector2f::Zero); for (; strCur < strEnd && c < 2; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector3f StringConverter::StringToVector3f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector3f res(Vector3f::Zero); for (; strCur < strEnd && c < 3; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector4f StringConverter::StringToVector4f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector4f res(Vector4f::Zero); for (; strCur < strEnd && c < 4; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } void StringConverter::Vector2fToString(String &Destination, const Vector2f &Source) { Destination.Format("%f %f", Source.x, Source.y); } void StringConverter::Vector3fToString(String &Destination, const Vector3f &Source) { Destination.Format("%f %f %f", Source.x, Source.y, Source.z); } void StringConverter::Vector4fToString(String &Destination, const Vector4f &Source) { Destination.Format("%f %f %f %f", Source.x, Source.y, Source.z, Source.w); } Vector2i StringConverter::StringToVector2i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector2i res(Vector2i::Zero); for (; strCur < strEnd && c < 2; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector3i StringConverter::StringToVector3i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector3i res(Vector3i::Zero); for (; strCur < strEnd && c < 3; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector4i StringConverter::StringToVector4i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector4i res(Vector4i::Zero); for (; strCur < strEnd && c < 4; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector2u StringConverter::StringToVector2u(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector2u res(Vector2u::Zero); for (; strCur < strEnd && c < 2; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtouint32(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector3u StringConverter::StringToVector3u(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector3u res(Vector3u::Zero); for (; strCur < strEnd && c < 3; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtouint32(strCur, &EndPtr); strCur = EndPtr; } return res; } Vector4u StringConverter::StringToVector4u(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector4u res(Vector4u::Zero); for (; strCur < strEnd && c < 4; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtouint32(strCur, &EndPtr); strCur = EndPtr; } return res; } void StringConverter::Vector2iToString(String &Destination, const Vector2i &Source) { Destination.Format("%i %i", Source.x, Source.y); } void StringConverter::Vector3iToString(String &Destination, const Vector3i &Source) { Destination.Format("%i %i %i", Source.x, Source.y, Source.z); } void StringConverter::Vector4iToString(String &Destination, const Vector4i &Source) { Destination.Format("%i %i %i %i", Source.x, Source.y, Source.z, Source.w); } void StringConverter::Vector2uToString(String &Destination, const Vector2u &Source) { Destination.Format("%u %u", Source.x, Source.y); } void StringConverter::Vector3uToString(String &Destination, const Vector3u &Source) { Destination.Format("%u %u %u", Source.x, Source.y, Source.z); } void StringConverter::Vector4uToString(String &Destination, const Vector4u &Source) { Destination.Format("%u %u %u %u", Source.x, Source.y, Source.z, Source.w); } SIMDVector2f StringConverter::StringToSIMDVector2f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector2f res(SIMDVector2f::Zero); for (; strCur < strEnd && c < 2; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } SIMDVector3f StringConverter::StringToSIMDVector3f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector3f res(SIMDVector3f::Zero); for (; strCur < strEnd && c < 3; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } SIMDVector4f StringConverter::StringToSIMDVector4f(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector4f res(SIMDVector4f::Zero); for (; strCur < strEnd && c < 4; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return res; } void StringConverter::SIMDVector2fToString(String &Destination, const SIMDVector2f &Source) { Destination.Format("%f %f", Source.x, Source.y); } void StringConverter::SIMDVector3fToString(String &Destination, const SIMDVector3f &Source) { Destination.Format("%f %f %f", Source.x, Source.y, Source.z); } void StringConverter::SIMDVector4fToString(String &Destination, const SIMDVector4f &Source) { Destination.Format("%f %f %f %f", Source.x, Source.y, Source.z, Source.w); } SIMDVector2i StringConverter::StringToSIMDVector2i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector2i res(SIMDVector2i::Zero); for (; strCur < strEnd && c < 2; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } SIMDVector3i StringConverter::StringToSIMDVector3i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector3i res(SIMDVector3i::Zero); for (; strCur < strEnd && c < 3; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } SIMDVector4i StringConverter::StringToSIMDVector4i(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; SIMDVector4i res(SIMDVector4i::Zero); for (; strCur < strEnd && c < 4; ) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtoint32(strCur, &EndPtr); strCur = EndPtr; } return res; } void StringConverter::SIMDVector2iToString(String &Destination, const SIMDVector2i &Source) { Destination.Format("%i %i", Source.x, Source.y); } void StringConverter::SIMDVector3iToString(String &Destination, const SIMDVector3i &Source) { Destination.Format("%i %i %i", Source.x, Source.y, Source.z); } void StringConverter::SIMDVector4iToString(String &Destination, const SIMDVector4i &Source) { Destination.Format("%i %i %i %i", Source.x, Source.y, Source.z, Source.w); } Quaternion StringConverter::StringToQuaternion(const char *Source) { uint32 strLength = Y_strlen(Source); const char *strCur = Source; const char *strEnd = Source + strLength; uint32 c = 0; Vector4f res(0.0f, 0.0f, 0.0f, 1.0f); for (; strCur < strEnd && c < 4;) { if (*strCur == '(' || *strCur == ')' || *strCur == ',' || *strCur == ' ') { strCur++; continue; } char *EndPtr; res[c++] = Y_strtofloat(strCur, &EndPtr); strCur = EndPtr; } return Quaternion(res.x, res.y, res.z, res.w); } void StringConverter::QuaternionToString(String &Destination, const Quaternion &Source) { Destination.Format("%f %f %f %f", Source.x, Source.y, Source.z, Source.w); } void StringConverter::TransformToString(String &dest, const Transform &transform) { const Vector3f &translation = transform.GetPosition(); const Vector4f rotation = transform.GetRotation().GetVectorRepresentation(); const Vector3f &scale = transform.GetScale(); dest.Format("(%f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f)", translation.x, translation.y, translation.z, rotation.x, rotation.y, rotation.z, rotation.w, scale.x, scale.y, scale.z); } Transform StringConverter::StringToTranform(const String &str) { if (str.GetLength() < 2) return Transform::Identity; uint32 i = 0; SmallString tempString; Transform outTransform; outTransform.SetIdentity(); while (i < str.GetLength() && str[i++] != '('); if (i < str.GetLength()) { while (i < str.GetLength() && str[i] != ')') tempString.AppendCharacter(str[i++]); outTransform.SetPosition(StringConverter::StringToVector3f(tempString)); tempString.Clear(); while (i < str.GetLength() && str[i++] != ','); while (i < str.GetLength() && str[i++] != '('); if (i < str.GetLength()) { while (i < str.GetLength() && str[i] != ')') tempString.AppendCharacter(str[i++]); outTransform.SetRotation(Quaternion(StringConverter::StringToVector4f(tempString))); tempString.Clear(); while (i < str.GetLength() && str[i++] != ','); while (i < str.GetLength() && str[i++] != '('); if (i < str.GetLength()) { while (i < str.GetLength() && str[i] != ')') tempString.AppendCharacter(str[i++]); outTransform.SetScale(StringConverter::StringToVector3f(tempString)); tempString.Clear(); } } } return outTransform; } TinyString StringConverter::Vector2fToString(const Vector2f &Source) { TinyString ret; Vector2fToString(ret, Source); return ret; } TinyString StringConverter::Vector3fToString(const Vector3f &Source) { TinyString ret; Vector3fToString(ret, Source); return ret; } TinyString StringConverter::Vector4fToString(const Vector4f &Source) { TinyString ret; Vector4fToString(ret, Source); return ret; } TinyString StringConverter::Vector2iToString(const Vector2i &Source) { TinyString ret; SIMDVector2iToString(ret, Source); return ret; } TinyString StringConverter::Vector3iToString(const Vector3i &Source) { TinyString ret; SIMDVector3iToString(ret, Source); return ret; } TinyString StringConverter::Vector4iToString(const Vector4i &Source) { TinyString ret; SIMDVector4iToString(ret, Source); return ret; } TinyString StringConverter::Vector2uToString(const Vector2u &Source) { TinyString ret; Vector2uToString(ret, Source); return ret; } TinyString StringConverter::Vector3uToString(const Vector3u &Source) { TinyString ret; Vector3uToString(ret, Source); return ret; } TinyString StringConverter::Vector4uToString(const Vector4u &Source) { TinyString ret; Vector4uToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector2fToString(const SIMDVector2f &Source) { TinyString ret; SIMDVector2fToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector3fToString(const SIMDVector3f &Source) { TinyString ret; SIMDVector3fToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector4fToString(const SIMDVector4f &Source) { TinyString ret; SIMDVector4fToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector2iToString(const SIMDVector2i &Source) { TinyString ret; SIMDVector2iToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector3iToString(const SIMDVector3i &Source) { TinyString ret; SIMDVector3iToString(ret, Source); return ret; } TinyString StringConverter::SIMDVector4iToString(const SIMDVector4i &Source) { TinyString ret; SIMDVector4iToString(ret, Source); return ret; } TinyString StringConverter::QuaternionToString(const Quaternion &Source) { TinyString ret; QuaternionToString(ret, Source); return ret; } SmallString StringConverter::TransformToString(const Transform &Source) { SmallString ret; TransformToString(ret, Source); return ret; } <file_sep>/Editor/Source/Editor/MapEditor/ui_EditorMapWindow.h #pragma once #include "Editor/EditorPropertyEditorWidget.h" #include "Editor/MapEditor/EditorWorldOutlinerWidget.h" #include "Editor/ResourceBrowser/EditorResourceBrowserWidget.h" struct Ui_EditorMapWindow { QMainWindow *mainWindow; // actions QAction *actionFileNewMap; QAction *actionFileOpenMap; QAction *actionFileSaveMap; QAction *actionFileSaveMapAs; QAction *actionFileCloseMap; QAction *actionFileExit; QAction *actionEditUndo; QAction *actionEditRedo; QAction *actionEditReferenceCoordinateSystemLocal; QAction *actionEditReferenceCoordinateSystemWorld; QAction *actionViewWorldOutliner; QAction *actionViewResourceBrowser; QAction *actionViewToolbox; QAction *actionViewPropertyEditor; QAction *actionViewViewportLayout1x1; QAction *actionViewViewportLayout2x2; QAction *actionViewThemeNone; QAction *actionViewThemeDark; QAction *actionViewThemeDarkOther; QAction *actionViewVisibleLayers; QAction *actionToolsMapEditor; QAction *actionToolsEntityEditor; QAction *actionToolsGeometryEditor; QAction *actionToolsTerrainEditor; QAction *actionToolsCreateTerrain; QAction *actionToolsDeleteTerrain; // menus QMenu *menuFile; QMenu *menuEdit; QMenu *menuEditReferenceCoordinateSystem; QMenu *menuView; QMenu *menuViewViewportLayout; QMenu *menuViewTheme; QMenu *menuInsert; QMenu *menuInsertEntity; QMenu *menuTools; QMenu *menuHelp; // left pane QWidget *closedMapBlankPanel; // world browser edit dock QDockWidget *worldOutlinerDock; EditorWorldOutlinerWidget *worldOutliner; // resource browser edit dock QDockWidget *resourceBrowserDock; EditorResourceBrowserWidget *resourceBrowser; // tool dock QDockWidget *toolboxDockWidget; QTabWidget *toolboxTabWidget; // properties dock QDockWidget *propertyEditorDockWidget; EditorPropertyEditorWidget *propertyEditor; // widgets QMenuBar *menubar; QToolBar *toolbar; QStatusBar *statusBar; QLabel *statusBarMainText; QCheckBox *statusBarGridSnapEnabled; QDoubleSpinBox *statusBarGridSnapInterval; QCheckBox *statusBarGridLinesVisible; QDoubleSpinBox *statusBarGridLinesInterval; QLabel *statusBarCameraPosition; QLabel *statusBarCameraDirection; QLabel *statusBarFPS; void CreateUI(EditorMapWindow *pMainWindow) { // resize window mainWindow = pMainWindow; //mainWindow->resize(1280, 720); mainWindow->resize(1366, 768); actionFileNewMap = new QAction(pMainWindow); actionFileNewMap->setIcon(QIcon(QStringLiteral(":/editor/icons/NewDocumentHS.png"))); actionFileNewMap->setText(pMainWindow->tr("&New Map")); actionFileOpenMap = new QAction(pMainWindow); actionFileOpenMap->setIcon(QIcon(QStringLiteral(":/editor/icons/openHS.png"))); actionFileOpenMap->setText(pMainWindow->tr("&Open Map")); actionFileSaveMap = new QAction(pMainWindow); actionFileSaveMap->setIcon(QIcon(QStringLiteral(":/editor/icons/saveHS.png"))); actionFileSaveMap->setText(pMainWindow->tr("&Save Map")); actionFileSaveMapAs = new QAction(pMainWindow); actionFileSaveMapAs->setText(pMainWindow->tr("Save Map &As...")); actionFileCloseMap = new QAction(pMainWindow); actionFileCloseMap->setText(pMainWindow->tr("&Close Map")); actionFileExit = new QAction(pMainWindow); actionFileExit->setText(pMainWindow->tr("E&xit")); actionEditUndo = new QAction(pMainWindow); actionEditUndo->setIcon(QIcon(QStringLiteral(":/editor/icons/Edit_UndoHS.png"))); actionEditUndo->setText(pMainWindow->tr("&Undo")); actionEditRedo = new QAction(pMainWindow); actionEditRedo->setIcon(QIcon(QStringLiteral(":/editor/icons/Edit_RedoHS.png"))); actionEditRedo->setText(pMainWindow->tr("&Undo")); actionEditReferenceCoordinateSystemLocal = new QAction(pMainWindow); actionEditReferenceCoordinateSystemLocal->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_LocalCoordSystem.png"))); actionEditReferenceCoordinateSystemLocal->setText(pMainWindow->tr("&Local")); actionEditReferenceCoordinateSystemLocal->setCheckable(true); actionEditReferenceCoordinateSystemWorld = new QAction(pMainWindow); actionEditReferenceCoordinateSystemWorld->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_WorldCoordSystem.png"))); actionEditReferenceCoordinateSystemWorld->setText(pMainWindow->tr("&World")); actionEditReferenceCoordinateSystemWorld->setCheckable(true); actionViewWorldOutliner = new QAction(pMainWindow); actionViewWorldOutliner->setText(pMainWindow->tr("&World Outliner")); actionViewWorldOutliner->setIcon(QIcon(QStringLiteral(":/editor/icons/camera.png"))); actionViewWorldOutliner->setCheckable(true); actionViewResourceBrowser = new QAction(pMainWindow); actionViewResourceBrowser->setText(pMainWindow->tr("&Resource Browser")); actionViewResourceBrowser->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); actionViewResourceBrowser->setCheckable(true); actionViewToolbox = new QAction(pMainWindow); actionViewToolbox->setText(pMainWindow->tr("&Toolbox")); actionViewToolbox->setIcon(QIcon(QStringLiteral(":/editor/icons/HighlightHH.png"))); actionViewToolbox->setCheckable(true); actionViewPropertyEditor = new QAction(pMainWindow); actionViewPropertyEditor->setText(pMainWindow->tr("&Property Editor")); actionViewPropertyEditor->setIcon(QIcon(QStringLiteral(":/editor/icons/HighlightHH.png"))); actionViewPropertyEditor->setCheckable(true); actionViewViewportLayout1x1 = new QAction(pMainWindow); actionViewViewportLayout1x1->setText(pMainWindow->tr("1x1")); actionViewViewportLayout1x1->setCheckable(true); actionViewViewportLayout2x2 = new QAction(pMainWindow); actionViewViewportLayout2x2->setText(pMainWindow->tr("2x2")); actionViewViewportLayout2x2->setCheckable(true); actionViewThemeNone = new QAction(pMainWindow); actionViewThemeNone->setText(pMainWindow->tr("&None")); actionViewThemeDark = new QAction(pMainWindow); actionViewThemeDark->setText(pMainWindow->tr("&Dark")); actionViewThemeDarkOther = new QAction(pMainWindow); actionViewThemeDarkOther->setText(pMainWindow->tr("Dark &Other")); actionViewVisibleLayers = new QAction(pMainWindow->tr("Visible &Layers"), pMainWindow); actionViewVisibleLayers->setIcon(QIcon(QStringLiteral(":/editor/icons/Directory_16x16.png"))); actionToolsMapEditor = new QAction(pMainWindow); actionToolsMapEditor->setText(pMainWindow->tr("&Map Editor")); actionToolsMapEditor->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolsMapEditor->setCheckable(true); actionToolsEntityEditor = new QAction(pMainWindow); actionToolsEntityEditor->setText(pMainWindow->tr("&Entity Editor")); actionToolsEntityEditor->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); actionToolsEntityEditor->setCheckable(true); actionToolsGeometryEditor = new QAction(pMainWindow); actionToolsGeometryEditor->setText(pMainWindow->tr("&Geometry Editor")); actionToolsGeometryEditor->setIcon(QIcon(QStringLiteral(":/editor/icons/HighlightHH.png"))); actionToolsGeometryEditor->setCheckable(true); actionToolsTerrainEditor = new QAction(pMainWindow); actionToolsTerrainEditor->setText(pMainWindow->tr("&Terrain Editor")); actionToolsTerrainEditor->setIcon(QIcon(QStringLiteral(":/editor/icons/BreakpointHS.png"))); actionToolsTerrainEditor->setCheckable(true); actionToolsCreateTerrain = new QAction(pMainWindow); actionToolsCreateTerrain->setText(pMainWindow->tr("Create Terrain")); actionToolsDeleteTerrain = new QAction(pMainWindow); actionToolsDeleteTerrain->setText(pMainWindow->tr("Delete Terrain")); menuFile = new QMenu(pMainWindow); menuFile->setTitle(pMainWindow->tr("&File")); menuFile->addAction(actionFileNewMap); menuFile->addAction(actionFileOpenMap); menuFile->addAction(actionFileSaveMap); menuFile->addAction(actionFileSaveMapAs); menuFile->addAction(actionFileCloseMap); menuFile->addSeparator(); menuFile->addAction(actionFileExit); menuEdit = new QMenu(pMainWindow); menuEdit->setTitle(pMainWindow->tr("&Edit")); menuEdit->addAction(actionEditUndo); menuEdit->addAction(actionEditRedo); menuEdit->addSeparator(); menuEditReferenceCoordinateSystem = new QMenu(pMainWindow); menuEditReferenceCoordinateSystem->setTitle(pMainWindow->tr("&Reference Coordinate System")); menuEditReferenceCoordinateSystem->addAction(actionEditReferenceCoordinateSystemLocal); menuEditReferenceCoordinateSystem->addAction(actionEditReferenceCoordinateSystemWorld); menuEdit->addMenu(menuEditReferenceCoordinateSystem); menuView = new QMenu(pMainWindow); menuView->setTitle(pMainWindow->tr("&View")); menuView->addAction(actionViewWorldOutliner); menuView->addAction(actionViewResourceBrowser); menuView->addAction(actionViewToolbox); menuView->addAction(actionViewPropertyEditor); menuView->addSeparator(); menuView->addAction(actionViewVisibleLayers); menuView->addSeparator(); menuViewViewportLayout = new QMenu(menuView); menuViewViewportLayout->setTitle(pMainWindow->tr("&Viewport Layout")); menuViewViewportLayout->addAction(actionViewViewportLayout1x1); menuViewViewportLayout->addAction(actionViewViewportLayout2x2); menuView->addMenu(menuViewViewportLayout); menuView->addSeparator(); menuViewTheme = new QMenu(menuView); menuViewTheme->setTitle(pMainWindow->tr("&Theme")); menuViewTheme->addAction(actionViewThemeNone); menuViewTheme->addAction(actionViewThemeDark); menuViewTheme->addAction(actionViewThemeDarkOther); menuView->addMenu(menuViewTheme); menuInsertEntity = new QMenu(pMainWindow); menuInsertEntity->setTitle(pMainWindow->tr("&Entity")); menuInsert = new QMenu(pMainWindow); menuInsert->setTitle(pMainWindow->tr("&Insert")); menuInsert->addMenu(menuInsertEntity); menuInsert->addSeparator(); menuTools = new QMenu(pMainWindow); menuTools->setTitle(pMainWindow->tr("&Tools")); menuTools->addAction(actionToolsMapEditor); menuTools->addAction(actionToolsEntityEditor); menuTools->addAction(actionToolsGeometryEditor); menuTools->addAction(actionToolsTerrainEditor); menuTools->addSeparator(); menuTools->addAction(actionToolsCreateTerrain); menuTools->addAction(actionToolsDeleteTerrain); menuHelp = new QMenu(pMainWindow); menuHelp->setTitle(pMainWindow->tr("&Help")); menubar = new QMenuBar(pMainWindow); { menubar->addMenu(menuFile); menubar->addMenu(menuEdit); menubar->addMenu(menuView); menubar->addMenu(menuInsert); menubar->addMenu(menuTools); menubar->addMenu(menuHelp); } pMainWindow->setMenuBar(menubar); toolbar = new QToolBar(pMainWindow); { toolbar->setIconSize(QSize(16, 16)); toolbar->addAction(actionFileNewMap); toolbar->addAction(actionFileOpenMap); toolbar->addAction(actionFileSaveMap); toolbar->addSeparator(); toolbar->addAction(actionEditUndo); toolbar->addAction(actionEditRedo); toolbar->addSeparator(); toolbar->addAction(actionEditReferenceCoordinateSystemLocal); toolbar->addAction(actionEditReferenceCoordinateSystemWorld); toolbar->addSeparator(); toolbar->addAction(actionViewVisibleLayers); toolbar->addSeparator(); toolbar->addAction(actionViewWorldOutliner); toolbar->addAction(actionViewResourceBrowser); toolbar->addAction(actionViewToolbox); toolbar->addAction(actionViewPropertyEditor); toolbar->addSeparator(); toolbar->addAction(actionToolsMapEditor); toolbar->addAction(actionToolsEntityEditor); toolbar->addAction(actionToolsGeometryEditor); toolbar->addAction(actionToolsTerrainEditor); } pMainWindow->addToolBar(toolbar); statusBar = new QStatusBar(pMainWindow); { statusBarMainText = new QLabel(statusBar); statusBar->addWidget(statusBarMainText, 1); // grid snap { QWidget *gridSnapContainer = new QWidget(statusBar); QHBoxLayout *horizontalLayout = new QHBoxLayout(gridSnapContainer); horizontalLayout->setMargin(0); horizontalLayout->setSpacing(0); horizontalLayout->setContentsMargins(0, 0, 0, 0); statusBarGridSnapEnabled = new QCheckBox(gridSnapContainer); horizontalLayout->addWidget(statusBarGridSnapEnabled); statusBarGridSnapInterval = new QDoubleSpinBox(gridSnapContainer); statusBarGridSnapInterval->setMinimum(0.1); statusBarGridSnapInterval->setMaximum(100.0); statusBarGridSnapInterval->setSingleStep(0.1); horizontalLayout->addWidget(statusBarGridSnapInterval); gridSnapContainer->setLayout(horizontalLayout); statusBar->addWidget(gridSnapContainer); } // grid lines { QWidget *gridLinesContainer = new QWidget(statusBar); QHBoxLayout *horizontalLayout = new QHBoxLayout(gridLinesContainer); horizontalLayout->setMargin(0); horizontalLayout->setSpacing(0); horizontalLayout->setContentsMargins(0, 0, 0, 0); statusBarGridLinesVisible = new QCheckBox(gridLinesContainer); horizontalLayout->addWidget(statusBarGridLinesVisible); statusBarGridLinesInterval = new QDoubleSpinBox(gridLinesContainer); statusBarGridLinesInterval->setMinimum(0.1); statusBarGridLinesInterval->setMaximum(100.0); statusBarGridLinesInterval->setSingleStep(0.1); horizontalLayout->addWidget(statusBarGridLinesInterval); gridLinesContainer->setLayout(horizontalLayout); statusBar->addWidget(gridLinesContainer); } statusBarCameraPosition = new QLabel(statusBar); statusBar->addWidget(statusBarCameraPosition); statusBarCameraDirection = new QLabel(statusBar); statusBar->addWidget(statusBarCameraDirection); statusBarFPS = new QLabel(statusBar); statusBar->addWidget(statusBarFPS); } pMainWindow->setStatusBar(statusBar); closedMapBlankPanel = new QWidget(pMainWindow); pMainWindow->setCentralWidget(closedMapBlankPanel); worldOutlinerDock = new QDockWidget(pMainWindow); worldOutlinerDock->setWindowTitle(pMainWindow->tr("World Outliner")); worldOutlinerDock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); worldOutliner = new EditorWorldOutlinerWidget(worldOutlinerDock); worldOutlinerDock->setWidget(worldOutliner); pMainWindow->addDockWidget(Qt::LeftDockWidgetArea, worldOutlinerDock); resourceBrowserDock = new QDockWidget(pMainWindow); resourceBrowserDock->setWindowTitle(pMainWindow->tr("Resource Browser")); resourceBrowserDock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); resourceBrowser = new EditorResourceBrowserWidget(pMainWindow, resourceBrowserDock); resourceBrowserDock->setWidget(resourceBrowser); pMainWindow->addDockWidget(Qt::LeftDockWidgetArea, resourceBrowserDock); toolboxDockWidget = new QDockWidget(pMainWindow); toolboxDockWidget->setWindowTitle(pMainWindow->tr("Tool")); toolboxDockWidget->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); toolboxTabWidget = new QTabWidget(toolboxDockWidget); toolboxTabWidget->setTabPosition(QTabWidget::East); toolboxDockWidget->setWidget(toolboxTabWidget); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, toolboxDockWidget); propertyEditorDockWidget = new QDockWidget(pMainWindow); propertyEditorDockWidget->setWindowTitle(pMainWindow->tr("Property Editor")); propertyEditorDockWidget->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); propertyEditor = new EditorPropertyEditorWidget(propertyEditorDockWidget); propertyEditorDockWidget->setWidget(propertyEditor); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, propertyEditorDockWidget); // set the initial state of everything actionFileSaveMap->setEnabled(false); actionFileSaveMapAs->setEnabled(false); actionFileCloseMap->setEnabled(false); actionEditUndo->setEnabled(false); actionEditRedo->setEnabled(false); actionEditReferenceCoordinateSystemLocal->setEnabled(false); actionEditReferenceCoordinateSystemWorld->setEnabled(false); actionEditReferenceCoordinateSystemWorld->setCheckable(true); actionToolsMapEditor->setEnabled(false); actionToolsEntityEditor->setEnabled(false); actionToolsGeometryEditor->setEnabled(false); actionToolsTerrainEditor->setEnabled(false); actionToolsCreateTerrain->setEnabled(false); actionToolsDeleteTerrain->setEnabled(false); actionViewWorldOutliner->setEnabled(false); actionViewResourceBrowser->setEnabled(true); actionViewResourceBrowser->setChecked(true); actionViewToolbox->setEnabled(false); actionViewPropertyEditor->setEnabled(false); menuViewViewportLayout->setEnabled(false); menuInsert->setEnabled(false); menuInsertEntity->setEnabled(false); menuViewViewportLayout->setEnabled(false); // and hide the windows ToggleWorldOutliner(false); ToggleResourceBrowser(true); ToggleToolbox(false); TogglePropertyEditor(false); } void ToggleWorldOutliner(bool visible) { (visible) ? worldOutlinerDock->show() : worldOutlinerDock->hide(); actionViewWorldOutliner->setChecked(visible); } void ToggleResourceBrowser(bool visible) { (visible) ? resourceBrowserDock->show() : resourceBrowserDock->hide(); actionViewResourceBrowser->setChecked(visible); } void ToggleToolbox(bool visible) { (visible) ? toolboxDockWidget->show() : toolboxDockWidget->hide(); actionViewToolbox->setChecked(visible); } void TogglePropertyEditor(bool visible) { (visible) ? propertyEditorDockWidget->show() : propertyEditorDockWidget->hide(); actionViewPropertyEditor->setChecked(visible); } void OnReferenceCoordinateSystemChanged(EDITOR_REFERENCE_COORDINATE_SYSTEM coordinateSystem) { actionEditReferenceCoordinateSystemLocal->setChecked((coordinateSystem == EDITOR_REFERENCE_COORDINATE_SYSTEM_LOCAL)); actionEditReferenceCoordinateSystemWorld->setChecked((coordinateSystem == EDITOR_REFERENCE_COORDINATE_SYSTEM_WORLD)); } void OnMapFileNameChanged(EditorMap *pEditorMap) { QString windowTitle = mainWindow->tr("Map Editor"); if (pEditorMap != NULL) { windowTitle.append(" - "); if (pEditorMap->GetMapFileName().GetLength() == 0) windowTitle.append("<unsaved map>"); else windowTitle.append(pEditorMap->GetMapFileName().GetCharArray()); } mainWindow->setWindowTitle(windowTitle); } void UpdateUIForEditMode(EDITOR_EDIT_MODE editMode) { DebugAssert(editMode < EDITOR_EDIT_MODE_COUNT); if (editMode != EDITOR_EDIT_MODE_NONE) toolboxTabWidget->setCurrentIndex((int)editMode - 1); actionToolsMapEditor->setChecked((editMode == EDITOR_EDIT_MODE_MAP)); actionToolsEntityEditor->setChecked((editMode == EDITOR_EDIT_MODE_ENTITY)); actionToolsGeometryEditor->setChecked((editMode == EDITOR_EDIT_MODE_GEOMETRY)); actionToolsTerrainEditor->setChecked((editMode == EDITOR_EDIT_MODE_TERRAIN)); ToggleToolbox(true); } }; <file_sep>/Engine/Source/Core/FIFVolume.h #pragma once #include "Core/Common.h" #include "YBaseLib/String.h" #include "YBaseLib/Timestamp.h" #include "YBaseLib/FileSystem.h" typedef struct fif_mount_s *fif_mount_handle; class FIFVolume { public: ~FIFVolume(); // archive operations bool StatFile(const char *filename, FILESYSTEM_STAT_DATA *pStatData) const; bool FindFiles(const char *path, const char *pattern, uint32 flags, FileSystem::FindResultsArray *pResults) const; ByteStream *OpenFile(const char *filename, uint32 openMode, uint32 compressionLevel = 6); bool DeleteFile(const char *filename); // open a new volume static FIFVolume *CreateVolume(ByteStream *pStream, ByteStream *pTraceStream = nullptr); // open an existing volume. static FIFVolume *OpenVolume(ByteStream *pStream, ByteStream *pTraceStream = nullptr); private: FIFVolume(ByteStream *pStream, ByteStream *pTraceStream, fif_mount_handle mountHandle); bool ParseZip(); ByteStream *m_pStream; ByteStream *m_pTraceStream; fif_mount_handle m_mountHandle; }; <file_sep>/Engine/Source/Renderer/Shaders/MobileShaders.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/MobileShaders.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderConstantBuffer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(MobileBasePassShader); BEGIN_SHADER_COMPONENT_PARAMETERS(MobileBasePassShader) END_SHADER_COMPONENT_PARAMETERS() bool MobileBasePassShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (baseShaderFlags & WITH_EMISSIVE && pMaterialShader->GetLightingType() != MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool MobileBasePassShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/MobileBasePassShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/MobileBasePassShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_EMISSIVE) pParameters->AddPreprocessorMacro("WITH_EMISSIVE", "1"); if (baseShaderFlags & WITH_LIGHTMAP) pParameters->AddPreprocessorMacro("WITH_LIGHTMAP", "1"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(MobileDirectionalLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(MobileDirectionalLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("ShadowMapTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbMobileDirectionalLightParameters, "MobileDirectionalLightParametersBuffer", "MobileDirectionalLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightVector", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("AmbientColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("ShadowMapSize", SHADER_PARAMETER_TYPE_FLOAT4, 1) SHADER_CONSTANT_BUFFER_FIELD("ShadowMapViewProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, 1) END_SHADER_CONSTANT_BUFFER(cbMobileDirectionalLightParameters) uint32 MobileDirectionalLightShader::CalculateFlags(bool enableShadows, RENDERER_SHADOW_FILTER shadowFilter) { uint32 flags = 0; if (enableShadows) { flags |= WITH_SHADOW_MAP; switch (shadowFilter) { case RENDERER_SHADOW_FILTER_3X3: flags |= SHADOW_FILTER_3X3; break; case RENDERER_SHADOW_FILTER_5X5: flags |= SHADOW_FILTER_5X5; break; //case RENDERER_SHADOW_FILTER_1X1: default: flags |= SHADOW_FILTER_1X1; break; } } return flags; } void MobileDirectionalLightShader::SetLightParameters(GPUContext *pContext, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const SSMShadowMapRenderer::ShadowMapData *pShadowMapData) { cbMobileDirectionalLightParameters.SetFieldFloat3(pContext, 0, pLight->Direction, false); cbMobileDirectionalLightParameters.SetFieldFloat3(pContext, 1, pLight->LightColor, false); cbMobileDirectionalLightParameters.SetFieldFloat3(pContext, 2, pLight->AmbientColor, false); if (pShadowMapData != nullptr) { uint32 shadowMapWidth = pShadowMapData->pShadowMapTexture->GetDesc()->Width; uint32 shadowMapHeight = pShadowMapData->pShadowMapTexture->GetDesc()->Height; float4 shadowMapSize((float)shadowMapWidth, (float)shadowMapHeight, 1.0f / (float)shadowMapWidth, 1.0f / (float)shadowMapHeight); cbMobileDirectionalLightParameters.SetFieldFloat4(pContext, 3, shadowMapSize, false); cbMobileDirectionalLightParameters.SetFieldFloat4x4(pContext, 4, pShadowMapData->ViewProjectionMatrix, false); } cbMobileDirectionalLightParameters.CommitChanges(pContext); } void MobileDirectionalLightShader::SetProgramParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const SSMShadowMapRenderer::ShadowMapData *pShadowMapData) { if (pShadowMapData != nullptr) pShaderProgram->SetBaseShaderParameterTexture(pContext, 0, pShadowMapData->pShadowMapTexture, nullptr); } bool MobileDirectionalLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool MobileDirectionalLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/MobileDirectionalLightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/MobileDirectionalLightShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_SHADOW_MAP) { pParameters->AddPreprocessorMacro("WITH_SHADOW_MAP", "1"); // filter if (baseShaderFlags & SHADOW_FILTER_3X3) pParameters->AddPreprocessorMacro("SHADOW_FILTER_3X3", "1"); else if (baseShaderFlags & SHADOW_FILTER_5X5) pParameters->AddPreprocessorMacro("SHADOW_FILTER_5X5", "1"); else //if (baseShaderFlags & SHADOW_FILTER_1X1) pParameters->AddPreprocessorMacro("SHADOW_FILTER_1X1", "1"); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(MobileFinalCompositeShader); BEGIN_SHADER_COMPONENT_PARAMETERS(MobileFinalCompositeShader) DEFINE_SHADER_COMPONENT_PARAMETER("SceneTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void MobileFinalCompositeShader::SetInputParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pHDRTexture) { pShaderProgram->SetBaseShaderParameterTexture(pContext, 0, pHDRTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); } bool MobileFinalCompositeShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool MobileFinalCompositeShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/MobileFinalCompositeShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Engine/Source/Engine/TerrainSection.h #pragma once #include "Engine/Common.h" #include "Engine/TerrainTypes.h" #include "Engine/TerrainQuadTree.h" class GPUTexture2D; class TerrainLayerList; class TerrainManager; class StaticMesh; class TerrainSection : public ReferenceCounted { friend class TerrainManager; public: struct DetailMesh { uint32 MeshIndex; const StaticMesh *pStaticMesh; float DrawDistance; }; struct DetailMeshInstance { // stored uint32 MeshIndex; float NormalizedX; float NormalizedY; float Scale; float RotationZ; // calculated float3 Position; float3x4 TransformMatrix; }; public: TerrainSection(const TerrainParameters *pParameters, int32 sectionX, int32 sectionY, uint32 LODLevel); ~TerrainSection(); const TERRAIN_HEIGHT_STORAGE_FORMAT GetHeightStorageFormat() const { return m_parameters.HeightStorageFormat; } const int32 GetSectionX() const { return m_sectionX; } const int32 GetSectionY() const { return m_sectionY; } const uint32 GetStorageLODLevel() const { return m_LODLevel; } const uint32 GetPointCount() const { return m_pointCount; } const AABox &GetBoundingBox() const { return m_bounds; } const bool IsChanged() const { return m_changed; } void SetChanged() { m_changed = true; } void ClearChangedFlag() { m_changed = false; } void Create(float createHeight, uint8 createLayer); bool LoadFromStream(ByteStream *pStream); bool SaveToStream(ByteStream *pStream) const; // raw data for deploying straight to texture void GetRawHeightMapData(const void **pDataPointer, uint32 *pValueSize, uint32 *pRowPitch) const; void GetRawSplatMapData(uint32 mapIndex, const void **pDataPointer, uint32 *pValueSize, uint32 *pRowPitch) const; // quadtree const TerrainSectionQuadTree *GetQuadTree() const { return m_pQuadTree; } TerrainSectionQuadTree *GetQuadTree() { return m_pQuadTree; } // raycast into the section bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection = false) const; // callback is in format of callback(const float3 vertices[4]) template<typename CALLBACK_TYPE> void EnumerateQuadsIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const; // callback is in format of callback(const float3 vertices[3]) template<typename CALLBACK_TYPE> void EnumerateTrianglesIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const; // heightmap access const float GetHeightMapValue(uint32 offsetX, uint32 offsetY) const; void SetHeightMapValue(uint32 offsetX, uint32 offsetY, float height); void SetAllHeightMapValues(float height); // normal calculation float3 CalculateNormalAtPoint(uint32 x, uint32 y) const; // sample heightmap float SampleHeightMap(float normalizedX, float normalizedY) const; float3 SampleNormal(float normalizedX, float normalizedY) const; // splatmap channel information access const uint32 GetSplatMapCount() const { return m_nSplatMaps; } const uint32 GetSplatMapChannelCount(uint32 mapIndex) const { DebugAssert(mapIndex < m_nSplatMaps); return m_pSplatMaps[mapIndex].LayerCount; } const uint8 GetSplatMapChannel(uint32 mapIndex, uint32 channelIndex) const { DebugAssert(mapIndex < m_nSplatMaps && channelIndex < m_pSplatMaps[mapIndex].LayerCount); return m_pSplatMaps[mapIndex].Layers[channelIndex]; } const bool HasSplatMapForLayer(uint8 layerIndex) const; const uint8 GetSplatMapDominantLayer(uint32 offsetX, uint32 offsetY) const; const uint32 GetSplatMapValues(uint32 offsetX, uint32 offsetY, uint8 *outLayers, float *outLayerWeights, uint32 maxLayers) const; // splatmap data access, setting a value will automatically re-weight/normalize the weights const float GetSplatMapValue(uint32 offsetX, uint32 offsetY, uint8 layer) const; void SetSplatMapValue(uint32 offsetX, uint32 offsetY, uint8 layer, float value, bool renormalize = true); void ClearSplatMapValues(uint32 offsetX, uint32 offsetY); void SetAllSplatMapValues(uint8 layer, float value = 1.0f); // copy weights from one section's point to another void CopySplatMapValue(const TerrainSection *pSourceSection, uint32 sourceOffsetX, uint32 sourceOffsetY, uint32 destinationOffsetX, uint32 destinationOffsetY); // normalize a single point's weights void NormalizeSplatMapValue(uint32 offsetX, uint32 offsetY); // remove low weighted points from a single point void FilterSplatMapValues(uint32 offsetX, uint32 offsetY, float threshold = 0.1f, bool normalizeAfterRemove = true); // detail mesh manipulation int32 GetDetailMeshIndex(const StaticMesh *pStaticMesh) const; int32 AddDetailMesh(const StaticMesh *pStaticMesh, float drawDistance); void SetDetailMeshDrawDistance(const StaticMesh *pStaticMesh, float drawDistance); // detail mesh accessors const DetailMesh *GetDetailMesh(uint32 index) const { return &m_detailMeshes[index]; } const uint32 GetDetailMeshCount() const { return m_detailMeshes.GetSize(); } const DetailMeshInstance *GetDetailMeshInstance(uint32 index) const { return &m_detailMeshInstances[index]; } const uint32 GetDetailMeshInstanceCount() const { return m_detailMeshInstances.GetSize(); } // detail mesh instance manipulation void AddDetailMeshInstance(uint32 meshIndex, float normalizedX, float normalizedY, float scale, float rotationZ); void RemoveDetailMeshInstancesBox(float normalizedXStart, float normalizedXEnd, float normalizedYStart, float normalizedYEnd); void RemoveDetailMeshInstancesCircle(float normalizedX, float normalizedY, float radius); // rebuilding bool RebuildQuadTree(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void RebuildSplatMaps(bool filterValues = true, float filterThreshold = 0.1f); private: // splatmap manipulators void AllocateLayerInSplatMap(uint8 layerIndex, uint32 *pMapIndex, uint32 *pChannelIndex); bool GetSplatMapLocation(uint8 layerIndex, uint32 *pMapIndex, uint32 *pChannelIndex) const; uint8 GetSplatMapValue(uint32 mapIndex, uint32 channelIndex, uint32 offsetX, uint32 offsetY) const; void SetSplatMapValue(uint32 mapIndex, uint32 channelIndex, uint32 offsetX, uint32 offsetY, uint8 value); // detail mesh helpers void UpdateDetailMeshLocations(uint32 offsetX, uint32 offsetY); void GetDetailMeshLocation(float normalizedX, float normalizedY, float rotationZ, float3 *pOutPosition, Quaternion *pOutRotation); // vars TerrainParameters m_parameters; int32 m_sectionX; int32 m_sectionY; uint32 m_LODLevel; // includes the neighbouring row/column uint32 m_pointCount; AABox m_bounds; bool m_changed; // height map byte *m_pHeightValues; uint32 m_heightValueSize; uint32 m_heightMapRowPitch; // splat map struct SplatMap { uint8 Layers[4]; uint32 LayerCount; uint32 ChannelCount; uint32 RowPitch; uint8 *pData; }; SplatMap *m_pSplatMaps; uint32 m_nSplatMaps; // details MemArray<DetailMesh> m_detailMeshes; MemArray<DetailMeshInstance> m_detailMeshInstances; // quadtree TerrainSectionQuadTree *m_pQuadTree; }; template<typename CALLBACK_TYPE> void TerrainSection::EnumerateQuadsIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const { int32 unitsPerPoint = (int32)m_parameters.Scale; float fUnitsPerPoint = (float)m_parameters.Scale; int32 sectionSizeMinusOne = (int32)m_parameters.SectionSize - 1; // find the overlapping points float3 sectionMinBounds(m_bounds.GetMinBounds()); float3 sectionMaxBounds(m_bounds.GetMaxBounds()); float3 sectionMinPoints((box.GetMinBounds() - sectionMinBounds) / fUnitsPerPoint); float3 sectionMaxPoints((box.GetMaxBounds() - sectionMinBounds) / fUnitsPerPoint); // quantize them int32 startXi = Math::Truncate(Math::Floor(sectionMinPoints.x)); int32 startYi = Math::Truncate(Math::Floor(sectionMinPoints.y)); int32 endXi = Math::Truncate(Math::Ceil(sectionMaxPoints.x)); int32 endYi = Math::Truncate(Math::Ceil(sectionMaxPoints.y)); // fix up range uint32 startX = (uint32)Min(Max(startXi, (int32)0), sectionSizeMinusOne); uint32 startY = (uint32)Min(Max(startYi, (int32)0), sectionSizeMinusOne); uint32 endX = (uint32)Min(Max(endXi, (int32)0), sectionSizeMinusOne); uint32 endY = (uint32)Min(Max(endYi, (int32)0), sectionSizeMinusOne); // iterate over points float3 triangleVertices[4]; for (uint32 ly = startY; ly <= endY; ly++) { for (uint32 lx = startX; lx <= endX; lx++) { triangleVertices[0].Set(sectionMinBounds.x + (float)((lx)* unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), GetHeightMapValue(lx, ly + 1)); triangleVertices[1].Set(sectionMinBounds.x + (float)((lx) * unitsPerPoint), sectionMinBounds.y + (float)((ly) * unitsPerPoint), GetHeightMapValue(lx, ly)); triangleVertices[2].Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), GetHeightMapValue(lx + 1, ly + 1)); triangleVertices[3].Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly) * unitsPerPoint), GetHeightMapValue(lx + 1, ly)); // run callback callback(triangleVertices); } } } template<typename CALLBACK_TYPE> void TerrainSection::EnumerateTrianglesIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const { EnumerateQuadsIntersectingBox(box, [box, &callback](const float3 quadVertices[4]) { // recreate the array with a triangle float3 triangleVertices[3]; triangleVertices[0] = quadVertices[0]; triangleVertices[1] = quadVertices[1]; triangleVertices[2] = quadVertices[2]; callback(triangleVertices); // and the second triangle with flipped first two vertices triangleVertices[0] = quadVertices[2]; triangleVertices[1] = quadVertices[1]; triangleVertices[2] = quadVertices[3]; callback(triangleVertices); }); } <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUCommandList.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUCommandList.h" #include "D3D12Renderer/D3D12GPUBuffer.h" #include "D3D12Renderer/D3D12GPUTexture.h" #include "D3D12Renderer/D3D12GPUShaderProgram.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12Helpers.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(D3D12RenderBackend); D3D12GPUCommandList::D3D12GPUCommandList(D3D12GPUDevice *pDevice, ID3D12Device *pD3DDevice) : m_pDevice(pDevice) , m_pD3DDevice(pD3DDevice) , m_pGraphicsCommandQueue(nullptr) , m_pConstants(nullptr) , m_pCommandList(nullptr) , m_pCurrentCommandAllocator(nullptr) , m_pCurrentScratchBuffer(nullptr) , m_pCurrentScratchViewHeap(nullptr) , m_pCurrentScratchSamplerHeap(nullptr) { m_open = false; m_pDevice->AddRef(); // null memory Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); m_currentTopology = DRAW_TOPOLOGY_UNDEFINED; m_currentD3DTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; // null current states Y_memzero(m_pCurrentVertexBuffers, sizeof(m_pCurrentVertexBuffers)); Y_memzero(m_currentVertexBufferOffsets, sizeof(m_currentVertexBufferOffsets)); Y_memzero(m_currentVertexBufferStrides, sizeof(m_currentVertexBufferStrides)); m_currentVertexBufferBindCount = 0; m_pCurrentIndexBuffer = nullptr; m_currentIndexFormat = GPU_INDEX_FORMAT_COUNT; m_currentIndexBufferOffset = 0; m_pCurrentShaderProgram = nullptr; m_shaderStates.Resize(SHADER_PROGRAM_STAGE_COUNT); m_shaderStates.ZeroContents(); m_perDrawConstantBuffers.Resize(D3D12_LEGACY_GRAPHICS_ROOT_PER_DRAW_CONSTANT_BUFFER_SLOTS); m_perDrawConstantBufferCount = 0; m_perDrawConstantBuffersDirty = false; m_pCurrentRasterizerState = nullptr; m_pCurrentDepthStencilState = nullptr; m_currentDepthStencilRef = 0; m_pCurrentBlendState = nullptr; m_currentBlendStateBlendFactors.SetZero(); m_pipelineChanged = false; m_pCurrentSwapChain = nullptr; Y_memzero(m_pCurrentRenderTargetViews, sizeof(m_pCurrentRenderTargetViews)); m_pCurrentDepthBufferView = nullptr; m_nCurrentRenderTargets = 0; m_pCurrentPredicate = nullptr; //m_pCurrentPredicateD3D = nullptr; m_predicateBypassCount = 0; } D3D12GPUCommandList::~D3D12GPUCommandList() { // command list should *never* be destructed while open. Assert(!m_open); // still have resources open? release them if (m_pGraphicsCommandQueue != nullptr) ReleaseAllocators(m_pGraphicsCommandQueue->GetNextFenceValue()); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; delete[] constantBuffer->pLocalMemory; } delete m_pConstants; m_pDevice->Release(); } void D3D12GPUCommandList::ResourceBarrier(ID3D12Resource *pResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState) { D3D12_RESOURCE_BARRIER resourceBarrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { pResource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, beforeState, afterState } }; m_pCommandList->ResourceBarrier(1, &resourceBarrier); } void D3D12GPUCommandList::ResourceBarrier(ID3D12Resource *pResource, uint32 subResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState) { D3D12_RESOURCE_BARRIER resourceBarrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { pResource, subResource, beforeState, afterState } }; m_pCommandList->ResourceBarrier(1, &resourceBarrier); } bool D3D12GPUCommandList::Create(D3D12CommandQueue *pCommandQueue) { // allocate constants m_pConstants = new GPUContextConstants(m_pDevice, this); CreateConstantBuffers(); return true; } void D3D12GPUCommandList::CreateConstantBuffers() { // allocate constant buffer storage const ShaderConstantBuffer::RegistryType *registry = ShaderConstantBuffer::GetRegistry(); m_constantBuffers.Resize(registry->GetNumTypes()); m_constantBuffers.ZeroContents(); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; // applicable to us? const ShaderConstantBuffer *declaration = registry->GetTypeInfoByIndex(i); if (declaration == nullptr) continue; if (declaration->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && declaration->GetPlatformRequirement() != RENDERER_PLATFORM_D3D12) continue; if (declaration->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && declaration->GetMinimumFeatureLevel() > m_pDevice->GetFeatureLevel()) continue; // set size so we know to allocate it later or on demand constantBuffer->Size = declaration->GetBufferSize(); constantBuffer->DirtyLowerBounds = constantBuffer->DirtyUpperBounds = -1; constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; Y_memzero(constantBuffer->pLocalMemory, constantBuffer->Size); // create per-draw constant buffers constantBuffer->PerDraw = (declaration->GetUpdateFrequency() == SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_DRAW); } } bool D3D12GPUCommandList::Open(D3D12CommandQueue *pCommandQueue, D3D12GPUOutputBuffer *pOutputBuffer) { // should not be open Assert(!m_open); // release anything if we didn't execute if (m_pGraphicsCommandQueue != nullptr) ReleaseAllocators(m_pGraphicsCommandQueue->GetLastCompletedFenceValue()); // set command queue m_pGraphicsCommandQueue = pCommandQueue; // allocate everything m_pCurrentCommandAllocator = m_pGraphicsCommandQueue->RequestCommandAllocator(); m_pCurrentScratchBuffer = m_pGraphicsCommandQueue->RequestLinearBufferHeap(); m_pCurrentScratchViewHeap = m_pGraphicsCommandQueue->RequestLinearViewHeap(); m_pCurrentScratchSamplerHeap = m_pGraphicsCommandQueue->RequestLinearSamplerHeap(); if (m_pCurrentCommandAllocator == nullptr || m_pCurrentScratchBuffer == nullptr || m_pCurrentScratchViewHeap == nullptr || m_pCurrentScratchSamplerHeap == nullptr) { if (m_pCurrentCommandAllocator != nullptr) { pCommandQueue->ReleaseCommandAllocator(m_pCurrentCommandAllocator); m_pCurrentCommandAllocator = nullptr; } if (m_pCurrentScratchBuffer != nullptr) { pCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer); m_pCurrentScratchBuffer = nullptr; } if (m_pCurrentScratchViewHeap != nullptr) { pCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap); m_pCurrentScratchViewHeap = nullptr; } if (m_pCurrentScratchSamplerHeap != nullptr) { pCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap); m_pCurrentScratchSamplerHeap = nullptr; } m_pGraphicsCommandQueue = nullptr; return false; } // reset the command list m_pCommandList = m_pGraphicsCommandQueue->RequestAndOpenCommandList(m_pCurrentCommandAllocator); DebugAssert(m_pCommandList != nullptr); // set output buffer DebugAssert(m_pCurrentSwapChain == nullptr); if ((m_pCurrentSwapChain = pOutputBuffer) != nullptr) m_pCurrentSwapChain->AddRef(); // set default state DebugAssert(m_pCurrentRasterizerState == nullptr && m_pCurrentDepthStencilState == nullptr && m_pCurrentBlendState == nullptr); m_pCurrentRasterizerState = m_pDevice->GetDefaultRasterizerState(); m_pCurrentRasterizerState->AddRef(); m_pCurrentDepthStencilState = m_pDevice->GetDefaultDepthStencilState(); m_pCurrentDepthStencilState->AddRef(); m_pCurrentBlendState = m_pDevice->GetDefaultBlendState(); m_pCurrentBlendState->AddRef(); m_currentDepthStencilRef = 0; m_currentBlendStateBlendFactors.SetZero(); m_currentTopology = DRAW_TOPOLOGY_TRIANGLE_LIST; m_currentD3DTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; for (ShaderStageState &stageState : m_shaderStates) { stageState.ConstantBuffersDirty = true; stageState.ResourcesDirty = true; stageState.SamplersDirty = true; stageState.UAVsDirty = true; } // flag all constant buffers as dirty, since their state is unknown at execution time. m_pConstants->Reset(); for (ConstantBuffer &constantBuffer : m_constantBuffers) { constantBuffer.DirtyLowerBounds = 0; constantBuffer.DirtyUpperBounds = constantBuffer.Size - 1; if (constantBuffer.pLocalMemory != nullptr) Y_memzero(constantBuffer.pLocalMemory, constantBuffer.Size); } // restore state SetFullViewport(); RestoreCommandListDependantState(); // flag as open m_open = true; return true; } bool D3D12GPUCommandList::Close() { HRESULT hResult; // should be open Assert(m_open); // transition any render targets back for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[i]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[i]->GetD3DResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, defaultState); m_pCurrentRenderTargetViews[i]->Release(); m_pCurrentRenderTargetViews[i] = nullptr; } if (m_pCurrentDepthBufferView != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), D3D12_RESOURCE_STATE_DEPTH_WRITE, defaultState); m_pCurrentDepthBufferView->Release(); m_pCurrentDepthBufferView = nullptr; } m_nCurrentRenderTargets = 0; // release everything we own m_shaderStates.ZeroContents(); SAFE_RELEASE(m_pCurrentShaderProgram); m_perDrawConstantBuffers.ZeroContents(); m_perDrawConstantBufferCount = 0; m_perDrawConstantBuffersDirty = false; m_pipelineChanged = false; // vertex buffers for (uint32 i = 0; i < m_currentVertexBufferBindCount; i++) { SAFE_RELEASE(m_pCurrentVertexBuffers[i]); m_currentVertexBufferOffsets[i] = 0; m_currentVertexBufferStrides[i] = 0; } m_currentVertexBufferBindCount = 0; SAFE_RELEASE(m_pCurrentIndexBuffer); // render targets -- still needs to be re-synced for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) SAFE_RELEASE(m_pCurrentRenderTargetViews[i]); SAFE_RELEASE(m_pCurrentDepthBufferView); // predicate //SAFE_RELEASE(m_pCurrentPredicate); // other stuff m_currentTopology = DRAW_TOPOLOGY_UNDEFINED; m_currentD3DTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; m_currentBlendStateBlendFactors.SetZero(); m_currentDepthStencilRef = 0; Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); SAFE_RELEASE(m_pCurrentRasterizerState); SAFE_RELEASE(m_pCurrentDepthStencilState); SAFE_RELEASE(m_pCurrentBlendState); // output buffer SAFE_RELEASE(m_pCurrentSwapChain); // close d3d command list hResult = m_pCommandList->Close(); if (FAILED(hResult)) { Log_ErrorPrintf("ID3D12CommandList::Close failed with hResult %08X. This command list will not be executed.", hResult); return false; } // okay m_open = false; return true; } void D3D12GPUCommandList::ReleaseAllocators(uint64 fenceValue) { DebugAssert(m_pGraphicsCommandQueue != nullptr); // release everything back to the queue m_pGraphicsCommandQueue->ReleaseCommandAllocator(m_pCurrentCommandAllocator); m_pGraphicsCommandQueue->ReleaseCommandList(m_pCommandList); for (D3D12LinearBufferHeap *pBuffer : m_scratchBufferReleaseList) m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(pBuffer, fenceValue); m_scratchBufferReleaseList.Clear(); m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer, fenceValue); m_pCurrentScratchBuffer = nullptr; for (D3D12LinearDescriptorHeap *pHeap : m_scratchViewHeapReleaseList) m_pGraphicsCommandQueue->ReleaseLinearViewHeap(pHeap, fenceValue); m_scratchViewHeapReleaseList.Clear(); m_pGraphicsCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap, fenceValue); m_pCurrentScratchViewHeap = nullptr; for (D3D12LinearDescriptorHeap *pHeap : m_scratchSamplerReleaseList) m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(pHeap, fenceValue); m_scratchSamplerReleaseList.Clear(); m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap, fenceValue); m_pCurrentScratchSamplerHeap = nullptr; // null out command queue m_pGraphicsCommandQueue = nullptr; } void D3D12GPUCommandList::UpdateShaderDescriptorHeaps() { ID3D12DescriptorHeap *pDescriptorHeaps[] = { m_pCurrentScratchViewHeap->GetD3DHeap(), m_pCurrentScratchSamplerHeap->GetD3DHeap() }; m_pCommandList->SetDescriptorHeaps(countof(pDescriptorHeaps), pDescriptorHeaps); } void D3D12GPUCommandList::RestoreCommandListDependantState() { // graphics root m_pCommandList->SetGraphicsRootSignature(m_pDevice->GetLegacyGraphicsRootSignature()); m_pCommandList->SetComputeRootSignature(m_pDevice->GetLegacyComputeRootSignature()); UpdateShaderDescriptorHeaps(); // pipeline state UpdatePipelineState(true); // render targets SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); // other stuff D3D12_VIEWPORT D3D12Viewport = { (float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, (float)m_currentViewport.Width, (float)m_currentViewport.Height, m_currentViewport.MinDepth, m_currentViewport.MaxDepth }; m_pCommandList->RSSetViewports(1, &D3D12Viewport); m_pCommandList->IASetPrimitiveTopology(D3D12Helpers::GetD3D12PrimitiveTopology(m_currentTopology)); m_pCommandList->OMSetBlendFactor(m_currentBlendStateBlendFactors); m_pCommandList->OMSetStencilRef(m_currentDepthStencilRef); } bool D3D12GPUCommandList::GetPerDrawConstantBufferGPUAddress(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS *pAddress) { DebugAssert(index < m_constantBuffers.GetSize()); if (m_constantBuffers[index].PerDraw) { *pAddress = m_constantBuffers[index].LastAddress; return true; } return false; } bool D3D12GPUCommandList::AllocateScratchBufferMemory(uint32 size, uint32 alignment, ID3D12Resource **ppScratchBufferResource, uint32 *pScratchBufferOffset, void **ppCPUPointer, D3D12_GPU_VIRTUAL_ADDRESS *pGPUAddress) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (size > m_pGraphicsCommandQueue->GetLinearBufferHeapSize()) return false; uint32 offset; if (!m_pCurrentScratchBuffer->AllocateAligned(size, alignment, &offset)) { // get a new buffer. we can't release the buffer with a new fence, since the command line hasn't been executed yet. D3D12LinearBufferHeap *pNewBuffer = m_pGraphicsCommandQueue->RequestLinearBufferHeap(); DebugAssert(pNewBuffer != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearBufferHeap(m_pCurrentScratchBuffer); m_pCurrentScratchBuffer = pNewBuffer; // retry allocation on new buffer if (!m_pCurrentScratchBuffer->AllocateAligned(size, alignment, &offset)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } if (ppScratchBufferResource != nullptr) *ppScratchBufferResource = m_pCurrentScratchBuffer->GetResource(); if (pScratchBufferOffset != nullptr) *pScratchBufferOffset = offset; if (ppCPUPointer != nullptr) *ppCPUPointer = m_pCurrentScratchBuffer->GetPointer(offset); if (pGPUAddress != nullptr) *pGPUAddress = m_pCurrentScratchBuffer->GetGPUAddress(offset); return true; } bool D3D12GPUCommandList::AllocateScratchView(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (count > m_pGraphicsCommandQueue->GetLinearViewHeapSize()) return false; if (!m_pCurrentScratchViewHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { // get a new buffer D3D12LinearDescriptorHeap *pNewHeap = m_pGraphicsCommandQueue->RequestLinearViewHeap(); DebugAssert(pNewHeap != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearViewHeap(m_pCurrentScratchViewHeap); m_pCurrentScratchViewHeap = pNewHeap; UpdateShaderDescriptorHeaps(); // retry allocation on new buffer if (!m_pCurrentScratchViewHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } return true; } bool D3D12GPUCommandList::AllocateScratchSamplers(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle) { // outright refuse if it's larger than the buffer size (since the alloc will always fail) if (count > m_pGraphicsCommandQueue->GetLinearSamplerHeapSize()) return false; if (!m_pCurrentScratchSamplerHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { // get a new buffer D3D12LinearDescriptorHeap *pNewHeap = m_pGraphicsCommandQueue->RequestLinearSamplerHeap(); DebugAssert(pNewHeap != nullptr); // release the old buffer m_pGraphicsCommandQueue->ReleaseLinearSamplerHeap(m_pCurrentScratchSamplerHeap); m_pCurrentScratchSamplerHeap = pNewHeap; UpdateShaderDescriptorHeaps(); // retry allocation on new buffer if (!m_pCurrentScratchSamplerHeap->Allocate(count, pOutCPUHandle, pOutGPUHandle)) { Log_ErrorPrintf("Failed to allocate on new scratch buffer (this shouldn't happen)"); return false; } } return true; } void D3D12GPUCommandList::GetCurrentRenderTargetDimensions(uint32 *width, uint32 *height) { uint3 textureDimensions; if (m_pCurrentDepthBufferView != nullptr) textureDimensions = Renderer::GetTextureDimensions(m_pCurrentDepthBufferView->GetTargetTexture()); else if (m_nCurrentRenderTargets > 0) textureDimensions = Renderer::GetTextureDimensions(m_pCurrentRenderTargetViews[0]->GetTargetTexture()); else if (m_pCurrentSwapChain != nullptr) textureDimensions.Set(m_pCurrentSwapChain->GetWidth(), m_pCurrentSwapChain->GetHeight(), 1); else textureDimensions.Set(1, 1, 1); *width = textureDimensions.x; *height = textureDimensions.y; } D3D12_RESOURCE_STATES D3D12GPUCommandList::GetCurrentResourceState(GPUResource *pResource) { GPU_RESOURCE_TYPE resourceType = pResource->GetResourceType(); if (resourceType == GPU_RESOURCE_TYPE_BUFFER) { for (uint32 i = 0; i < m_currentVertexBufferBindCount; i++) { if (m_pCurrentVertexBuffers[i] == pResource) return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; } if (IsBoundAsUnorderedAccess(pResource)) return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; return static_cast<D3D12GPUBuffer *>(pResource)->GetDefaultResourceState(); } else { if (resourceType >= GPU_RESOURCE_TYPE_TEXTURE1D && resourceType <= GPU_RESOURCE_TYPE_DEPTH_TEXTURE) { if (IsBoundAsRenderTarget(static_cast<GPUTexture *>(pResource))) return D3D12_RESOURCE_STATE_RENDER_TARGET; if (IsBoundAsDepthBuffer(static_cast<GPUTexture *>(pResource))) return D3D12_RESOURCE_STATE_DEPTH_WRITE; switch (resourceType) { case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<D3D12GPUTexture2D *>(pResource)->GetDefaultResourceState(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<D3D12GPUTexture2DArray *>(pResource)->GetDefaultResourceState(); } } } return D3D12_RESOURCE_STATE_COMMON; } bool D3D12GPUCommandList::IsBoundAsRenderTarget(GPUTexture *pTexture) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr && m_pCurrentRenderTargetViews[i]->GetTargetTexture() == pTexture) return true; } return false; } bool D3D12GPUCommandList::IsBoundAsDepthBuffer(GPUTexture *pTexture) { return (m_pCurrentDepthBufferView != nullptr && m_pCurrentDepthBufferView->GetTargetTexture() == pTexture); } bool D3D12GPUCommandList::IsBoundAsUnorderedAccess(GPUResource *pResource) { // @TODO check UAVs return false; } void D3D12GPUCommandList::UpdateScissorRect() { if (m_pCurrentRasterizerState != nullptr && m_pCurrentRasterizerState->GetDesc()->ScissorEnable) { D3D12_RECT scissorRect = { (LONG)m_scissorRect.Left, (LONG)m_scissorRect.Top, (LONG)m_scissorRect.Right, (LONG)m_scissorRect.Bottom }; m_pCommandList->RSSetScissorRects(1, &scissorRect); } else { // get current render target dimensions uint32 width, height; GetCurrentRenderTargetDimensions(&width, &height); // set scissor D3D12_RECT scissorRect = { (LONG)0, (LONG)0, (LONG)width, (LONG)height }; m_pCommandList->RSSetScissorRects(1, &scissorRect); } } void D3D12GPUCommandList::ClearState(bool clearShaders /* = true */, bool clearBuffers /* = true */, bool clearStates /* = true */, bool clearRenderTargets /* = true */) { if (clearShaders) { SetShaderProgram(nullptr); m_shaderStates.ZeroContents(); } if (clearBuffers) { if (m_currentVertexBufferBindCount > 0) { static GPUBuffer *nullVertexBuffers[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { nullptr }; static const uint32 nullSizeOrOffset[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = { 0 }; SetVertexBuffers(0, m_currentVertexBufferBindCount, nullVertexBuffers, nullSizeOrOffset, nullSizeOrOffset); } if (m_pCurrentIndexBuffer != nullptr) SetIndexBuffer(nullptr, GPU_INDEX_FORMAT_UINT16, 0); } if (clearStates) { SetRasterizerState(m_pDevice->GetDefaultRasterizerState()); SetDepthStencilState(m_pDevice->GetDefaultDepthStencilState(), 0); SetBlendState(m_pDevice->GetDefaultBlendState()); SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); RENDERER_SCISSOR_RECT scissor(0, 0, 0, 0); SetFullViewport(nullptr); SetScissorRect(&scissor); } if (clearRenderTargets) { SetRenderTargets(0, nullptr, nullptr); } } GPURasterizerState *D3D12GPUCommandList::GetRasterizerState() { return m_pCurrentRasterizerState; } void D3D12GPUCommandList::SetRasterizerState(GPURasterizerState *pRasterizerState) { if (m_pCurrentRasterizerState != pRasterizerState) { bool oldScissorState = (m_pCurrentRasterizerState != nullptr) ? m_pCurrentRasterizerState->GetDesc()->ScissorEnable : false; if (m_pCurrentRasterizerState != nullptr) m_pCurrentRasterizerState->Release(); bool newScissorState = (pRasterizerState != nullptr) ? pRasterizerState->GetDesc()->ScissorEnable : false; if ((m_pCurrentRasterizerState = static_cast<D3D12GPURasterizerState *>(pRasterizerState)) != nullptr) m_pCurrentRasterizerState->AddRef(); m_pipelineChanged = true; // set scissor rect if scissor is not enabled if (oldScissorState != newScissorState) UpdateScissorRect(); } } GPUDepthStencilState *D3D12GPUCommandList::GetDepthStencilState() { return m_pCurrentDepthStencilState; } uint8 D3D12GPUCommandList::GetDepthStencilStateStencilRef() { return m_currentDepthStencilRef; } void D3D12GPUCommandList::SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) { if (m_pCurrentDepthStencilState != pDepthStencilState) { if (m_pCurrentDepthStencilState != nullptr) m_pCurrentDepthStencilState->Release(); if ((m_pCurrentDepthStencilState = static_cast<D3D12GPUDepthStencilState *>(pDepthStencilState)) != nullptr) m_pCurrentDepthStencilState->AddRef(); m_pipelineChanged = true; } if (m_currentDepthStencilRef != stencilRef) { m_pCommandList->OMSetStencilRef(stencilRef); m_currentDepthStencilRef = stencilRef; } } GPUBlendState *D3D12GPUCommandList::GetBlendState() { return m_pCurrentBlendState; } const float4 &D3D12GPUCommandList::GetBlendStateBlendFactor() { return m_currentBlendStateBlendFactors; }; void D3D12GPUCommandList::SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor /* = float4::One */) { if (m_pCurrentBlendState != pBlendState) { if (m_pCurrentBlendState != nullptr) m_pCurrentBlendState->Release(); if ((m_pCurrentBlendState = static_cast<D3D12GPUBlendState *>(pBlendState)) != nullptr) m_pCurrentBlendState->AddRef(); m_pipelineChanged = true; } if (blendFactor != m_currentBlendStateBlendFactors) { m_pCommandList->OMSetBlendFactor(blendFactor.ele); m_currentBlendStateBlendFactors = blendFactor; } } const RENDERER_VIEWPORT *D3D12GPUCommandList::GetViewport() { return &m_currentViewport; } void D3D12GPUCommandList::SetViewport(const RENDERER_VIEWPORT *pNewViewport) { if (Y_memcmp(&m_currentViewport, pNewViewport, sizeof(RENDERER_VIEWPORT)) == 0) return; Y_memcpy(&m_currentViewport, pNewViewport, sizeof(m_currentViewport)); D3D12_VIEWPORT D3D12Viewport = { (float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, (float)m_currentViewport.Width, (float)m_currentViewport.Height, m_currentViewport.MinDepth, m_currentViewport.MaxDepth }; m_pCommandList->RSSetViewports(1, &D3D12Viewport); // update constants m_pConstants->SetViewportOffset((float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, false); m_pConstants->SetViewportSize((float)m_currentViewport.Width, (float)m_currentViewport.Height, false); m_pConstants->CommitChanges(); } void D3D12GPUCommandList::SetFullViewport(GPUTexture *pForRenderTarget /* = NULL */) { RENDERER_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; if (pForRenderTarget != nullptr) { uint3 textureDimensions = Renderer::GetTextureDimensions(pForRenderTarget); viewport.Width = textureDimensions.x; viewport.Height = textureDimensions.y; } else { GetCurrentRenderTargetDimensions(&viewport.Width, &viewport.Height); } SetViewport(&viewport); } const RENDERER_SCISSOR_RECT *D3D12GPUCommandList::GetScissorRect() { return &m_scissorRect; } void D3D12GPUCommandList::SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) { if (Y_memcmp(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)) == 0) return; Y_memcpy(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)); // only set if rasterizer state permits if (m_pCurrentRasterizerState != nullptr && m_pCurrentRasterizerState->GetDesc()->ScissorEnable) { D3D12_RECT D3D12ScissorRect = { (LONG)m_scissorRect.Left, (LONG)m_scissorRect.Top, (LONG)m_scissorRect.Right, (LONG)m_scissorRect.Bottom }; m_pCommandList->RSSetScissorRects(1, &D3D12ScissorRect); } } void D3D12GPUCommandList::ClearTargets(bool clearColor /* = true */, bool clearDepth /* = true */, bool clearStencil /* = true */, const float4 &clearColorValue /* = float4::Zero */, float clearDepthValue /* = 1.0f */, uint8 clearStencilValue /* = 0 */) { D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0; if (clearDepth) clearFlags |= D3D12_CLEAR_FLAG_DEPTH; if (clearStencil) clearFlags |= D3D12_CLEAR_FLAG_STENCIL; if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { if (clearColor) m_pCommandList->ClearRenderTargetView(m_pCurrentSwapChain->GetCurrentBackBufferViewDescriptorCPUHandle(), clearColorValue, 0, nullptr); if (clearDepth && m_pCurrentSwapChain->GetDepthStencilBufferResource() != nullptr) m_pCommandList->ClearDepthStencilView(m_pCurrentSwapChain->GetDepthStencilBufferViewDescriptorCPUHandle(), clearFlags, clearDepthValue, clearStencilValue, 0, nullptr); } } else { if (clearColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) m_pCommandList->ClearRenderTargetView(m_pCurrentRenderTargetViews[i]->GetDescriptorHandle(), clearColorValue, 0, nullptr); } } if (clearFlags != 0 && m_pCurrentDepthBufferView != nullptr) m_pCommandList->ClearDepthStencilView(m_pCurrentDepthBufferView->GetDescriptorHandle(), clearFlags, clearDepthValue, clearStencilValue, 0, nullptr); } } void D3D12GPUCommandList::DiscardTargets(bool discardColor /* = true */, bool discardDepth /* = true */, bool discardStencil /* = true */) { if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // on swapchain if (m_pCurrentSwapChain != nullptr) { if (discardColor) m_pCommandList->DiscardResource(m_pCurrentSwapChain->GetCurrentBackBufferResource(), nullptr); if (discardDepth && discardStencil && m_pCurrentSwapChain->HasDepthStencilBuffer()) m_pCommandList->DiscardResource(m_pCurrentSwapChain->GetDepthStencilBufferResource(), nullptr); } } else { if (discardColor) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargetViews[i] != nullptr) m_pCommandList->DiscardResource(m_pCurrentRenderTargetViews[i]->GetD3DResource(), nullptr); } } if (discardDepth && discardStencil && m_pCurrentDepthBufferView != nullptr) m_pCommandList->DiscardResource(m_pCurrentDepthBufferView->GetD3DResource(), nullptr); } } GPUOutputBuffer *D3D12GPUCommandList::GetOutputBuffer() { return m_pCurrentSwapChain; } void D3D12GPUCommandList::SetOutputBuffer(GPUOutputBuffer *pSwapChain) { DebugAssert(pSwapChain != nullptr); if (m_pCurrentSwapChain == pSwapChain) return; // copy out old swap chain D3D12GPUOutputBuffer *pOldSwapChain = m_pCurrentSwapChain; // copy in new swap chain if ((m_pCurrentSwapChain = static_cast<D3D12GPUOutputBuffer *>(pSwapChain)) != nullptr) m_pCurrentSwapChain->AddRef(); // Currently rendering to window? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); } // update references if (pOldSwapChain != nullptr) pOldSwapChain->Release(); } uint32 D3D12GPUCommandList::GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) { uint32 i, j; for (i = 0; i < m_nCurrentRenderTargets && i < nRenderTargets; i++) ppRenderTargetViews[i] = m_pCurrentRenderTargetViews[i]; for (j = i; j < nRenderTargets; j++) ppRenderTargetViews[j] = nullptr; if (ppDepthBufferView != nullptr) *ppDepthBufferView = m_pCurrentDepthBufferView; return i; } void D3D12GPUCommandList::SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) { // @TODO only update pipeline on format change / # targets change // to system framebuffer? if ((nRenderTargets == 0 || (nRenderTargets == 1 && ppRenderTargets[0] == nullptr)) && pDepthBufferView == nullptr) { // change? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) return; // kill current targets for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[i]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[i]->GetD3DResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, defaultState); m_pCurrentRenderTargetViews[i]->Release(); m_pCurrentRenderTargetViews[i] = nullptr; } if (m_pCurrentDepthBufferView != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), D3D12_RESOURCE_STATE_DEPTH_WRITE, defaultState); m_pCurrentDepthBufferView->Release(); m_pCurrentDepthBufferView = nullptr; } m_nCurrentRenderTargets = 0; SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); m_pipelineChanged = true; } else { DebugAssert(nRenderTargets < countof(m_pCurrentRenderTargetViews)); uint32 slot; uint32 newRenderTargetCount = 0; bool doUpdate = false; // transition states - unbind old targets // this is needed because if a target changes index it'll transition incorrectly otherwise. for (slot = 0; slot < m_nCurrentRenderTargets; slot++) { DebugAssert(m_pCurrentRenderTargetViews[slot] != nullptr); if (slot >= nRenderTargets || m_pCurrentRenderTargetViews[slot] != ppRenderTargets[slot]) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[slot]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[slot]->GetD3DResource(), D3D12_RESOURCE_STATE_RENDER_TARGET, defaultState); } } // set inclusive slots for (slot = 0; slot < nRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != ppRenderTargets[slot]) { if (m_pCurrentRenderTargetViews[slot] != nullptr) m_pCurrentRenderTargetViews[slot]->Release(); if ((m_pCurrentRenderTargetViews[slot] = static_cast<D3D12GPURenderTargetView *>(ppRenderTargets[slot])) != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentRenderTargetViews[slot]->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_RENDER_TARGET) ResourceBarrier(m_pCurrentRenderTargetViews[slot]->GetD3DResource(), defaultState, D3D12_RESOURCE_STATE_RENDER_TARGET); m_pCurrentRenderTargetViews[slot]->AddRef(); } doUpdate = true; } if (m_pCurrentRenderTargetViews[slot] != nullptr) newRenderTargetCount = slot + 1; } // clear extra slots for (; slot < m_nCurrentRenderTargets; slot++) { if (m_pCurrentRenderTargetViews[slot] != nullptr) { m_pCurrentRenderTargetViews[slot]->Release(); m_pCurrentRenderTargetViews[slot] = nullptr; doUpdate = true; } } // update counter if (newRenderTargetCount != m_nCurrentRenderTargets) doUpdate = true; m_nCurrentRenderTargets = newRenderTargetCount; if (m_pCurrentDepthBufferView != pDepthBufferView) { if (m_pCurrentDepthBufferView != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), D3D12_RESOURCE_STATE_DEPTH_WRITE, defaultState); m_pCurrentDepthBufferView->Release(); } if ((m_pCurrentDepthBufferView = static_cast<D3D12GPUDepthStencilBufferView *>(pDepthBufferView)) != nullptr) { D3D12_RESOURCE_STATES defaultState = D3D12Helpers::GetResourceDefaultState(m_pCurrentDepthBufferView->GetTargetTexture()); if (defaultState != D3D12_RESOURCE_STATE_DEPTH_WRITE) ResourceBarrier(m_pCurrentDepthBufferView->GetD3DResource(), defaultState, D3D12_RESOURCE_STATE_DEPTH_WRITE); m_pCurrentDepthBufferView->AddRef(); } doUpdate = true; } if (doUpdate) { SynchronizeRenderTargetsAndUAVs(); UpdateScissorRect(); m_pipelineChanged = true; } } } DRAW_TOPOLOGY D3D12GPUCommandList::GetDrawTopology() { return m_currentTopology; } void D3D12GPUCommandList::SetDrawTopology(DRAW_TOPOLOGY topology) { if (topology == m_currentTopology) return; D3D12_PRIMITIVE_TOPOLOGY D3DPrimitiveTopology = D3D12Helpers::GetD3D12PrimitiveTopology(topology); D3D12_PRIMITIVE_TOPOLOGY_TYPE D3DPrimitiveTopologyType = D3D12Helpers::GetD3D12PrimitiveTopologyType(topology); m_pCommandList->IASetPrimitiveTopology(D3DPrimitiveTopology); m_currentTopology = topology; if (D3DPrimitiveTopologyType != m_currentD3DTopologyType) { m_currentD3DTopologyType = D3DPrimitiveTopologyType; m_pipelineChanged = true; } } uint32 D3D12GPUCommandList::GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < countof(m_pCurrentVertexBuffers)); uint32 saveCount; for (saveCount = 0; saveCount < nBuffers; saveCount++) { if ((firstBuffer + saveCount) > m_currentVertexBufferBindCount) break; ppVertexBuffers[saveCount] = m_pCurrentVertexBuffers[firstBuffer + saveCount]; pVertexBufferOffsets[saveCount] = m_currentVertexBufferOffsets[firstBuffer + saveCount]; pVertexBufferStrides[saveCount] = m_currentVertexBufferStrides[firstBuffer + saveCount]; } return saveCount; } void D3D12GPUCommandList::SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) { D3D12_VERTEX_BUFFER_VIEW vertexBufferViews[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; uint32 dirtyFirst = Y_UINT32_MAX; uint32 dirtyLast = 0; for (uint32 i = 0; i < nBuffers; i++) { D3D12GPUBuffer *pD3D12VertexBuffer = static_cast<D3D12GPUBuffer *>(ppVertexBuffers[i]); uint32 bufferIndex = firstBuffer + i; if (m_pCurrentVertexBuffers[bufferIndex] == ppVertexBuffers[i] && m_currentVertexBufferOffsets[bufferIndex] == pVertexBufferOffsets[i] && m_currentVertexBufferStrides[bufferIndex] == pVertexBufferStrides[i]) { continue; } if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) { m_pCurrentVertexBuffers[bufferIndex]->Release(); m_pCurrentVertexBuffers[bufferIndex] = nullptr; } if ((m_pCurrentVertexBuffers[bufferIndex] = pD3D12VertexBuffer) != nullptr) { pD3D12VertexBuffer->AddRef(); m_currentVertexBufferOffsets[bufferIndex] = pVertexBufferOffsets[i]; m_currentVertexBufferStrides[bufferIndex] = pVertexBufferStrides[i]; // @TODO cache this address, save virtual call? DebugAssert(pVertexBufferOffsets[i] < pD3D12VertexBuffer->GetDesc()->Size); vertexBufferViews[i].BufferLocation = pD3D12VertexBuffer->GetD3DResource()->GetGPUVirtualAddress() + pVertexBufferOffsets[i]; vertexBufferViews[i].SizeInBytes = pD3D12VertexBuffer->GetDesc()->Size - pVertexBufferOffsets[i]; vertexBufferViews[i].StrideInBytes = pVertexBufferStrides[i]; } else { m_currentVertexBufferOffsets[bufferIndex] = 0; m_currentVertexBufferStrides[bufferIndex] = 0; Y_memzero(&vertexBufferViews[i], sizeof(vertexBufferViews[0])); } dirtyFirst = Min(dirtyFirst, bufferIndex); dirtyLast = Max(dirtyLast, bufferIndex); } // changes? if (dirtyFirst == Y_UINT32_MAX) return; // pass to command list // @TODO may be worth batching this to a dirty range? m_pCommandList->IASetVertexBuffers(dirtyFirst, dirtyLast - dirtyFirst + 1, &vertexBufferViews[dirtyFirst - firstBuffer]); // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((firstBuffer + nBuffers), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D12GPUCommandList::SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { if (m_pCurrentVertexBuffers[bufferIndex] == pVertexBuffer && m_currentVertexBufferOffsets[bufferIndex] == offset && m_currentVertexBufferStrides[bufferIndex] == stride) { return; } if (m_pCurrentVertexBuffers[bufferIndex] != pVertexBuffer) { if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) m_pCurrentVertexBuffers[bufferIndex]->Release(); if ((m_pCurrentVertexBuffers[bufferIndex] = static_cast<D3D12GPUBuffer *>(pVertexBuffer)) != nullptr) m_pCurrentVertexBuffers[bufferIndex]->AddRef(); } m_currentVertexBufferOffsets[bufferIndex] = offset; m_currentVertexBufferStrides[bufferIndex] = stride; // set in command list if (m_pCurrentVertexBuffers[bufferIndex] != nullptr) { D3D12_VERTEX_BUFFER_VIEW bufferView; DebugAssert(offset < m_pCurrentVertexBuffers[bufferIndex]->GetDesc()->Size); bufferView.BufferLocation = m_pCurrentVertexBuffers[bufferIndex]->GetD3DResource()->GetGPUVirtualAddress() + offset; bufferView.SizeInBytes = m_pCurrentVertexBuffers[bufferIndex]->GetDesc()->Size - offset; bufferView.StrideInBytes = stride; m_pCommandList->IASetVertexBuffers(bufferIndex, 1, &bufferView); } else { m_pCommandList->IASetVertexBuffers(bufferIndex, 1, nullptr); } // update new bind count uint32 bindCount = 0; uint32 searchCount = Max((bufferIndex + 1), m_currentVertexBufferBindCount); for (uint32 i = 0; i < searchCount; i++) { if (m_pCurrentVertexBuffers[i] != nullptr) bindCount = i + 1; } m_currentVertexBufferBindCount = bindCount; } void D3D12GPUCommandList::GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) { *ppBuffer = m_pCurrentIndexBuffer; *pFormat = m_currentIndexFormat; *pOffset = m_currentIndexBufferOffset; } void D3D12GPUCommandList::SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) { if (m_pCurrentIndexBuffer == pBuffer && m_currentIndexFormat == format && m_currentIndexBufferOffset == offset) return; if (m_pCurrentIndexBuffer != pBuffer) { if (m_pCurrentIndexBuffer != nullptr) m_pCurrentIndexBuffer->Release(); if ((m_pCurrentIndexBuffer = static_cast<D3D12GPUBuffer *>(pBuffer)) != nullptr) m_pCurrentIndexBuffer->AddRef(); } m_currentIndexFormat = format; m_currentIndexBufferOffset = offset; if (m_pCurrentIndexBuffer != nullptr) { D3D12_INDEX_BUFFER_VIEW bufferView; DebugAssert(offset < m_pCurrentIndexBuffer->GetDesc()->Size); bufferView.BufferLocation = m_pCurrentIndexBuffer->GetD3DResource()->GetGPUVirtualAddress() + offset; bufferView.SizeInBytes = m_pCurrentIndexBuffer->GetDesc()->Size - offset; bufferView.Format = (format == GPU_INDEX_FORMAT_UINT16) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; m_pCommandList->IASetIndexBuffer(&bufferView); } else { m_pCommandList->IASetIndexBuffer(nullptr); } } void D3D12GPUCommandList::SetShaderProgram(GPUShaderProgram *pShaderProgram) { if (m_pCurrentShaderProgram == pShaderProgram) return; if (m_pCurrentShaderProgram != nullptr) m_pCurrentShaderProgram->Release(); if ((m_pCurrentShaderProgram = static_cast<D3D12GPUShaderProgram *>(pShaderProgram)) != nullptr) m_pCurrentShaderProgram->AddRef(); g_pRenderer->GetCounters()->IncrementPipelineChangeCounter(); m_pipelineChanged = true; } void D3D12GPUCommandList::SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValue(this, index, valueType, pValue); } void D3D12GPUCommandList::SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValueArray(this, index, valueType, pValue, firstElement, numElements); } void D3D12GPUCommandList::SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStruct(this, index, pValue, valueSize); } void D3D12GPUCommandList::SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStructArray(this, index, pValue, valueSize, firstElement, numElements); } void D3D12GPUCommandList::SetShaderParameterResource(uint32 index, GPUResource *pResource) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pResource, nullptr); } void D3D12GPUCommandList::SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pTexture, pSamplerState); } void D3D12GPUCommandList::WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit /* = false */) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } DebugAssert(count > 0 && (offset + count) <= cbInfo->Size); if (Y_memcmp(cbInfo->pLocalMemory + offset, pData, count) != 0) { Y_memcpy(cbInfo->pLocalMemory + offset, pData, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + count; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + count - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D12GPUCommandList::WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit /*= false*/) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr) { Log_WarningPrintf("Skipping write of %u bytes to non-existant constant buffer %u", count, bufferIndex); return; } uint32 writeSize = bufferStride * count; DebugAssert(writeSize > 0 && (offset + writeSize) <= cbInfo->Size); if (Y_memcmp_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count) != 0) { Y_memcpy_stride(cbInfo->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count); if (cbInfo->DirtyUpperBounds < 0) { cbInfo->DirtyLowerBounds = offset; cbInfo->DirtyUpperBounds = offset + writeSize; } else { cbInfo->DirtyLowerBounds = Min(cbInfo->DirtyLowerBounds, (int32)offset); cbInfo->DirtyUpperBounds = Max(cbInfo->DirtyUpperBounds, (int32)(offset + writeSize - 1)); } if (commit) CommitConstantBuffer(bufferIndex); } } void D3D12GPUCommandList::CommitConstantBuffer(uint32 bufferIndex) { ConstantBuffer *cbInfo = &m_constantBuffers[bufferIndex]; if (cbInfo->pLocalMemory == nullptr || cbInfo->DirtyLowerBounds < 0) return; // work out count to modify uint32 modifySize = cbInfo->DirtyUpperBounds - cbInfo->DirtyLowerBounds + 1; // handle per-draw constant buffers if (!cbInfo->PerDraw) { // allocate scratch buffer memory ID3D12Resource *pScratchBufferResource; uint32 scratchBufferOffset; void *pCPUPointer; if (!AllocateScratchBufferMemory(modifySize, 0, &pScratchBufferResource, &scratchBufferOffset, &pCPUPointer, nullptr)) { Log_ErrorPrintf("D3D12GPUCommandList::CommitConstantBuffer: Failed to allocate scratch buffer memory."); return; } // copy from the constant memory store to the scratch buffer Y_memcpy(pCPUPointer, cbInfo->pLocalMemory + cbInfo->DirtyLowerBounds, modifySize); // get constant buffer pointer ID3D12Resource *pConstantBufferResource = m_pDevice->GetConstantBufferResource(bufferIndex); DebugAssert(pConstantBufferResource != nullptr); // block predicates BypassPredication(); // queue a copy to the actual buffer ResourceBarrier(pConstantBufferResource, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST); m_pCommandList->CopyBufferRegion(pConstantBufferResource, cbInfo->DirtyLowerBounds, pScratchBufferResource, scratchBufferOffset, modifySize); ResourceBarrier(pConstantBufferResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // restore predicates RestorePredication(); } else { void *pCPUPointer; D3D12_GPU_VIRTUAL_ADDRESS pGPUPointer; if (!AllocateScratchBufferMemory(cbInfo->Size, D3D12_CONSTANT_BUFFER_ALIGNMENT, nullptr, nullptr, &pCPUPointer, &pGPUPointer)) { Log_ErrorPrintf("D3D12GPUCommandList::CommitConstantBuffer: Failed to allocate per-draw scratch buffer memory."); return; } // copy from the constant memory store to the scratch buffer Y_memcpy(pCPUPointer, cbInfo->pLocalMemory, cbInfo->Size); // per-draw cbInfo->LastAddress = pGPUPointer; if (m_pCurrentShaderProgram != nullptr && !m_pipelineChanged) m_pCurrentShaderProgram->RebindPerDrawConstantBuffer(this, bufferIndex, pGPUPointer); } // reset range cbInfo->DirtyLowerBounds = cbInfo->DirtyUpperBounds = -1; } void D3D12GPUCommandList::SetShaderConstantBuffers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->ConstantBuffers[index] == handle) return; state->ConstantBuffers[index] = handle; state->ConstantBufferBindCount = Max(state->ConstantBufferBindCount, index + 1); state->ConstantBuffersDirty = true; } void D3D12GPUCommandList::SetShaderResources(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Resources[index] == handle) return; state->Resources[index] = handle; if (!handle.IsNull()) { // update max count state->ResourceBindCount = Max(state->ResourceBindCount, index + 1); } else { state->ResourceBindCount = 0; for (uint32 i = 0; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; i++) { if (!state->Resources[i].IsNull()) state->ResourceBindCount = i + 1; } } state->ResourcesDirty = true; } void D3D12GPUCommandList::SetShaderSamplers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->Samplers[index] == handle) return; state->Samplers[index] = handle; state->SamplerBindCount = Max(state->SamplerBindCount, index + 1); state->SamplersDirty = true; } void D3D12GPUCommandList::SetShaderUAVs(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle) { ShaderStageState *state = &m_shaderStates[stage]; if (state->UAVs[index] == handle) return; state->UAVs[index] = handle; state->UAVBindCount = Max(state->UAVBindCount, index + 1); state->UAVsDirty = true; } void D3D12GPUCommandList::SetPerDrawConstantBuffer(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS address) { DebugAssert(index < m_perDrawConstantBuffers.GetSize()); if (m_perDrawConstantBuffers[index] == address) return; m_perDrawConstantBuffers[index] = address; m_perDrawConstantBufferCount = Max(m_perDrawConstantBufferCount, index + 1); m_perDrawConstantBuffersDirty = true; } void D3D12GPUCommandList::SynchronizeRenderTargetsAndUAVs() { D3D12_CPU_DESCRIPTOR_HANDLE renderTargetHandles[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; D3D12_CPU_DESCRIPTOR_HANDLE depthStencilHandle; uint32 renderTargetCount = 0; bool hasDepthStencil = false; // get render target views if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { // using swap chain if (m_pCurrentSwapChain != nullptr) { // update the render target index if (m_pCurrentSwapChain->UpdateCurrentBackBuffer()) { // it's changed, so we need a resource barrier ResourceBarrier(m_pCurrentSwapChain->GetCurrentBackBufferResource(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); } renderTargetHandles[0] = m_pCurrentSwapChain->GetCurrentBackBufferViewDescriptorCPUHandle(); depthStencilHandle = m_pCurrentSwapChain->GetDepthStencilBufferViewDescriptorCPUHandle(); hasDepthStencil = m_pCurrentSwapChain->HasDepthStencilBuffer(); renderTargetCount = 1; } } else { // get render target views for (uint32 renderTargetIndex = 0; renderTargetIndex < m_nCurrentRenderTargets; renderTargetIndex++) { if (m_pCurrentRenderTargetViews[renderTargetIndex] != nullptr) { renderTargetHandles[renderTargetIndex] = m_pCurrentRenderTargetViews[renderTargetIndex]->GetDescriptorHandle(); renderTargetCount = renderTargetIndex + 1; } else { renderTargetHandles[renderTargetIndex].ptr = 0; } } // get depth stencil view if (m_pCurrentDepthBufferView != nullptr) { hasDepthStencil = true; depthStencilHandle = m_pCurrentDepthBufferView->GetDescriptorHandle(); } } m_pCommandList->OMSetRenderTargets(renderTargetCount, (renderTargetCount > 0) ? renderTargetHandles : nullptr, FALSE, (hasDepthStencil) ? &depthStencilHandle : nullptr); } bool D3D12GPUCommandList::UpdatePipelineState(bool force) { // new pipeline state required? force = force || m_pipelineChanged; if (m_pCurrentShaderProgram != nullptr) { if (m_pipelineChanged || force) { // fill pipeline state key D3D12GPUShaderProgram::PipelineStateKey key; Y_memzero(&key, sizeof(key)); // render targets if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthBufferView == nullptr) { if (m_pCurrentSwapChain != nullptr) { key.RenderTargetCount = 1; key.RTVFormats[0] = m_pCurrentSwapChain->GetBackBufferFormat(); key.DSVFormat = m_pCurrentSwapChain->GetDepthStencilBufferFormat(); } } else { key.RenderTargetCount = m_nCurrentRenderTargets; for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) key.RTVFormats[i] = (m_pCurrentRenderTargetViews[i] != nullptr) ? m_pCurrentRenderTargetViews[i]->GetDesc()->Format : PIXEL_FORMAT_UNKNOWN; key.DSVFormat = (m_pCurrentDepthBufferView != nullptr) ? m_pCurrentDepthBufferView->GetDesc()->Format : PIXEL_FORMAT_UNKNOWN; } // rasterizer state if (m_pCurrentRasterizerState == nullptr) return false; Y_memcpy(&key.RasterizerState, m_pCurrentRasterizerState->GetD3DRasterizerStateDesc(), sizeof(key.RasterizerState)); // depthstencil state if (m_pCurrentDepthStencilState == nullptr) return false; Y_memcpy(&key.DepthStencilState, m_pCurrentDepthStencilState->GetD3DDepthStencilDesc(), sizeof(key.DepthStencilState)); // blend state if (m_pCurrentBlendState == nullptr) return false; Y_memcpy(&key.BlendState, m_pCurrentBlendState->GetD3DBlendDesc(), sizeof(key.BlendState)); // topology key.PrimitiveTopologyType = m_currentD3DTopologyType; if (!m_pCurrentShaderProgram->Switch(this, m_pCommandList, &key)) return false; // up-to-date g_pRenderer->GetCounters()->IncrementPipelineChangeCounter(); m_pipelineChanged = false; } } else if (!force) { // no shader bound and not restoring return false; } // allocate an array of cpu pointers, uses alloca so it's at the end of the stack D3D12_CPU_DESCRIPTOR_HANDLE *pCPUHandles = (D3D12_CPU_DESCRIPTOR_HANDLE *)alloca(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) * 32); uint32 *pCPUHandleCounts = (uint32 *)alloca(sizeof(uint32) * 32); for (uint32 i = 0; i < 32; i++) pCPUHandleCounts[i] = 1; // update states for (uint32 stage = 0; stage <= SHADER_PROGRAM_STAGE_PIXEL_SHADER; stage++) { ShaderStageState *state = &m_shaderStates[stage]; //uint32 base = (stage == SHADER_PROGRAM_STAGE_PIXEL_SHADER) ? 3 : 0; uint32 base = stage * 3; // Constant buffers if (state->ConstantBuffersDirty || force) { // find the new bind count for (uint32 i = 0; i < state->ConstantBufferBindCount; i++) { if (!state->ConstantBuffers[i].IsNull()) pCPUHandles[i] = state->ConstantBuffers[i]; else pCPUHandles[i] = m_pDevice->GetNullCBVDescriptorHandle(); } for (uint32 i = state->ConstantBufferBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullCBVDescriptorHandle(); // allocate scratch descriptors and copy if (AllocateScratchView(D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, &state->CBVTableCPUHandle, &state->CBVTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->CBVTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); m_pCommandList->SetGraphicsRootDescriptorTable(base + 0, state->CBVTableGPUHandle); } state->ConstantBuffersDirty = false; } // Resources if (state->ResourcesDirty || force) { // find the new bind count for (uint32 i = 0; i < state->ResourceBindCount; i++) { if (!state->Resources[i].IsNull()) pCPUHandles[i] = state->Resources[i]; else pCPUHandles[i] = m_pDevice->GetNullSRVDescriptorHandle(); } for (uint32 i = state->ResourceBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullSRVDescriptorHandle(); // allocate scratch descriptors and copy if (AllocateScratchView(D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS, &state->SRVTableCPUHandle, &state->SRVTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->SRVTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); m_pCommandList->SetGraphicsRootDescriptorTable(base + 1, state->SRVTableGPUHandle); } state->ResourcesDirty = false; } // Samplers if (state->SamplersDirty || force) { // find the new bind count for (uint32 i = 0; i < state->SamplerBindCount; i++) { if (!state->Samplers[i].IsNull()) pCPUHandles[i] = state->Samplers[i]; else pCPUHandles[i] = m_pDevice->GetNullSamplerHandle(); } for (uint32 i = state->SamplerBindCount; i < D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS; i++) pCPUHandles[i] = m_pDevice->GetNullSamplerHandle(); // allocate scratch descriptors and copy if (AllocateScratchSamplers(D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS, &state->SamplerTableCPUHandle, &state->SamplerTableGPUHandle)) { uint32 count = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS; m_pD3DDevice->CopyDescriptors(1, &state->SamplerTableCPUHandle, &count, count, pCPUHandles, pCPUHandleCounts, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); m_pCommandList->SetGraphicsRootDescriptorTable(base + 2, state->SamplerTableGPUHandle); } state->SamplersDirty = false; } // // UAVs // if (stage == SHADER_PROGRAM_STAGE_PIXEL_SHADER && (state->UAVsDirty || force)) // { // // find the new bind count // uint32 bindCount = 0; // for (uint32 i = 0; i < state->SamplerBindCount; i++) // { // if (!state->UAVs[i].IsNull()) // { // pCPUHandles[i] = state->UAVs[i]; // bindCount = i + 1; // } // else // { // pCPUHandles[i].ptr = 0; // } // } // state->UAVBindCount = bindCount; // state->UAVsDirty = false; // // // allocate scratch descriptors and copy // if (bindCount > 0 && AllocateScratchView(bindCount, &state->UAVTableCPUHandle, &state->UAVTableGPUHandle)) // { // m_pD3DDevice->CopyDescriptors(1, &state->UAVTableCPUHandle, &bindCount, bindCount, pCPUHandles, nullptr, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); // m_pCommandList->SetGraphicsRootDescriptorTable(15, state->UAVTableGPUHandle); // } // } } // Commit global constant buffer m_pConstants->CommitGlobalConstantBufferChanges(); // per-draw constants if (m_perDrawConstantBuffersDirty || force) { for (uint32 i = 0; i < m_perDrawConstantBufferCount; i++) m_pCommandList->SetGraphicsRootConstantBufferView(16 + i, m_perDrawConstantBuffers[i]); for (uint32 i = m_perDrawConstantBufferCount; i < D3D12_LEGACY_GRAPHICS_ROOT_PER_DRAW_CONSTANT_BUFFER_SLOTS; i++) m_pCommandList->SetGraphicsRootConstantBufferView(16 + i, m_pCurrentScratchBuffer->GetGPUAddress(0)); m_perDrawConstantBuffersDirty = false; } return true; } void D3D12GPUCommandList::Draw(uint32 firstVertex, uint32 nVertices) { if (nVertices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawInstanced(nVertices, 1, firstVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUCommandList::DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) { if (nVertices == 0 || nInstances == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawInstanced(nVertices, nInstances, firstVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUCommandList::DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) { if (nIndices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawIndexedInstanced(nIndices, 1, startIndex, baseVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUCommandList::DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) { if (nIndices == 0 || !UpdatePipelineState(false)) return; m_pCommandList->DrawIndexedInstanced(nIndices, nInstances, startIndex, baseVertex, 0); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUCommandList::Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) { if (!UpdatePipelineState(false)) return; m_pCommandList->Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ); g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } void D3D12GPUCommandList::DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) { if (!UpdatePipelineState(false)) return; // can use scratch buffer directly. // this probably should use a threshold to go to an upload buffer.. uint32 bufferSpaceRequired = vertexSize * nVertices; ID3D12Resource *pScratchBufferResource; void *pScratchBufferCPUPointer; D3D12_GPU_VIRTUAL_ADDRESS scratchBufferGPUPointer; uint32 scratchBufferOffset; if (!AllocateScratchBufferMemory(bufferSpaceRequired, 0, &pScratchBufferResource, &scratchBufferOffset, &pScratchBufferCPUPointer, &scratchBufferGPUPointer)) return; // copy the contents in Y_memcpy(pScratchBufferCPUPointer, pVertices, bufferSpaceRequired); // set vertex buffer D3D12_VERTEX_BUFFER_VIEW vertexBufferView; vertexBufferView.BufferLocation = scratchBufferGPUPointer; vertexBufferView.SizeInBytes = bufferSpaceRequired; vertexBufferView.StrideInBytes = vertexSize; m_pCommandList->IASetVertexBuffers(0, 1, &vertexBufferView); // invoke draw m_pCommandList->DrawInstanced(nVertices, 1, 0, 0); // restore vertex buffer if (m_pCurrentVertexBuffers[0] != nullptr) { vertexBufferView.BufferLocation = m_pCurrentVertexBuffers[0]->GetD3DResource()->GetGPUVirtualAddress() + m_currentVertexBufferOffsets[0]; vertexBufferView.SizeInBytes = m_pCurrentVertexBuffers[0]->GetDesc()->Size - m_currentVertexBufferOffsets[0]; vertexBufferView.StrideInBytes = m_currentVertexBufferStrides[0]; m_pCommandList->IASetVertexBuffers(0, 1, &vertexBufferView); } else { m_pCommandList->IASetVertexBuffers(0, 1, nullptr); } g_pRenderer->GetCounters()->IncrementDrawCallCounter(); } bool D3D12GPUCommandList::CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) { // textures have to be compatible, for now this means same texture format D3D12GPUTexture2D *pD3D12SourceTexture = static_cast<D3D12GPUTexture2D *>(pSourceTexture); D3D12GPUTexture2D *pD3D12DestinationTexture = static_cast<D3D12GPUTexture2D *>(pDestinationTexture); if (pD3D12SourceTexture->GetDesc()->Width != pD3D12DestinationTexture->GetDesc()->Width || pD3D12SourceTexture->GetDesc()->Height != pD3D12DestinationTexture->GetDesc()->Height || pD3D12SourceTexture->GetDesc()->Format != pD3D12DestinationTexture->GetDesc()->Format || pD3D12SourceTexture->GetDesc()->MipLevels != pD3D12DestinationTexture->GetDesc()->MipLevels) { return false; } // get old state for both D3D12_RESOURCE_STATES sourceResourceState = GetCurrentResourceState(pSourceTexture); D3D12_RESOURCE_STATES destinationResourceState = GetCurrentResourceState(pDestinationTexture); // switch to copy states ResourceBarrier(pD3D12SourceTexture->GetD3DResource(), sourceResourceState, D3D12_RESOURCE_STATE_COPY_SOURCE); ResourceBarrier(pD3D12DestinationTexture->GetD3DResource(), destinationResourceState, D3D12_RESOURCE_STATE_COPY_DEST); // copy each mip level for (uint32 i = 0; i < pD3D12SourceTexture->GetDesc()->MipLevels; i++) { D3D12_TEXTURE_COPY_LOCATION sourceLocation = { pD3D12SourceTexture->GetD3DResource(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, i }; D3D12_TEXTURE_COPY_LOCATION destinationLocation = { pD3D12DestinationTexture->GetD3DResource(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, i }; m_pCommandList->CopyTextureRegion(&destinationLocation, 0, 0, 0, &sourceLocation, nullptr); } // switch back from copy states ResourceBarrier(pD3D12SourceTexture->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_SOURCE, sourceResourceState); ResourceBarrier(pD3D12DestinationTexture->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_DEST, destinationResourceState); return true; } bool D3D12GPUCommandList::CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) { #if 0 // textures have to be compatible, for now this means same texture format D3D12GPUTexture2D *pD3D12SourceTexture = static_cast<D3D12GPUTexture2D *>(pSourceTexture); D3D12GPUTexture2D *pD3D12DestinationTexture = static_cast<D3D12GPUTexture2D *>(pDestinationTexture); if (pD3D12SourceTexture->GetDesc()->Format != pD3D12DestinationTexture->GetDesc()->Format || pD3D12SourceTexture->GetDesc()->MipLevels != pD3D12DestinationTexture->GetDesc()->MipLevels) { return false; } // create source box, copy it D3D12_BOX sourceBox = { sourceX, sourceY, 0, sourceX + width, sourceY + height, 1 }; m_pD3DContext->CopySubresourceRegion(pD3D12DestinationTexture->GetD3DTexture(), D3D12CalcSubresource(destMipLevel, 0, pD3D12DestinationTexture->GetDesc()->MipLevels), destX, destY, 0, pD3D12SourceTexture->GetD3DTexture(), D3D12CalcSubresource(sourceMipLevel, 0, pD3D12SourceTexture->GetDesc()->MipLevels), &sourceBox); return true; #endif return false; } void D3D12GPUCommandList::BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /*= RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST*/) { Panic("Not implemented"); #if 0 DebugAssert(m_nCurrentRenderTargets <= 1); // read source formats DebugAssert(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE); DXGI_FORMAT sourceTextureFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Format); ID3D12Resource *pSourceResource = static_cast<D3D12GPUTexture2D *>(pTexture)->GetD3DTexture(); uint32 sourceTextureWidth = static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Width; uint32 sourceTextureHeight = static_cast<D3D12GPUTexture2D *>(pTexture)->GetDesc()->Height; // read destination format DXGI_FORMAT destinationTextureFormat = DXGI_FORMAT_UNKNOWN; ID3D12Resource *pDestinationResource = NULL; uint32 destinationTextureWidth = 0, destinationTextureHeight = 0; if (m_nCurrentRenderTargets == 0) { destinationTextureFormat = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferFormat(); pDestinationResource = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetBackBufferTexture(); destinationTextureWidth = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetWidth(); destinationTextureHeight = static_cast<D3D12GPUOutputBuffer *>(m_pCurrentSwapChain)->GetHeight(); } else { switch (m_pCurrentRenderTargetViews[0]->GetTargetTexture()->GetTextureType()) { case TEXTURE_TYPE_2D: destinationTextureFormat = D3D12TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Format); pDestinationResource = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetD3DTexture(); destinationTextureWidth = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Width; destinationTextureHeight = static_cast<D3D12GPUTexture2D *>(m_pCurrentRenderTargetViews[0]->GetTargetTexture())->GetDesc()->Height; break; default: Panic("D3D12GPUCommandList::BlitFrameBuffer: Destination is an unsupported texture type"); return; } } // D3D12 can do a direct copy between identical types if (sourceTextureFormat == destinationTextureFormat && sourceWidth == destWidth && sourceHeight == destHeight) { // whole texture? if (sourceX == 0 && sourceY == 0 && destX == 0 && destY == 0 && sourceWidth == sourceTextureWidth && sourceHeight == sourceTextureHeight) { // use CopyResource m_pD3DContext->CopyResource(pDestinationResource, pSourceResource); return; } else { // use CopySubResourceRegion D3D12_BOX sourceBox = { sourceX, sourceY, 0, sourceX + sourceWidth, sourceY + sourceHeight, 1 }; m_pD3DContext->CopySubresourceRegion(pDestinationResource, 0, destX, destY, 0, pSourceResource, 0, &sourceBox); return; } } // use shader g_pRenderer->BlitTextureUsingShader(this, pTexture, sourceX, sourceY, sourceWidth, sourceHeight, 0, destX, destY, destWidth, destHeight, resizeFilter, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE); #endif } void D3D12GPUCommandList::GenerateMips(GPUTexture *pTexture) { // @TODO has to be done using shaders :( } <file_sep>/Engine/Source/Engine/ResourceManager.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ResourceManager.h" #include "Engine/Engine.h" #include "Engine/Texture.h" #include "Engine/MaterialShader.h" #include "Engine/Material.h" #include "Engine/StaticMesh.h" #include "Engine/Font.h" #include "Engine/BlockPalette.h" #include "Engine/TerrainLayerList.h" #include "Engine/BlockMesh.h" #include "Engine/Skeleton.h" #include "Engine/SkeletalMesh.h" #include "Engine/SkeletalAnimation.h" #include "Engine/ParticleSystem.h" #include "Engine/EngineCVars.h" #include "Renderer/Renderer.h" #include "ResourceCompilerInterface/ResourceCompilerInterface.h" #include "Core/DefinitionFile.h" Log_SetChannel(Renderer); static ResourceManager s_ResourceManager; ResourceManager *g_pResourceManager = &s_ResourceManager; ResourceManager::ResourceManager() { m_pDefaultTexture2D = NULL; m_pDefaultTextureCube = NULL; m_pDefaultMaterial = NULL; m_pDefaultStaticMesh = NULL; m_pDefaultBlockMesh = NULL; m_pDefaultSkeletalMesh = NULL; m_pResourceModificationChangeNotifier = nullptr; m_pResourceCompilerInterface = nullptr; m_resourceCompilerInUse = false; } ResourceManager::~ResourceManager() { DebugAssert(m_pDefaultTexture2D == NULL); DebugAssert(m_pDefaultTextureCube == NULL); DebugAssert(m_pDefaultMaterial == NULL); DebugAssert(m_pDefaultStaticMesh == NULL); DebugAssert(m_pDefaultBlockMesh == NULL); DebugAssert(m_pDefaultSkeletalMesh == NULL); DebugAssert(m_htMaterials.GetMemberCount() == 0); DebugAssert(m_htTextures.GetMemberCount() == 0); DebugAssert(m_htStaticMeshes.GetMemberCount() == 0); DebugAssert(m_htFonts.GetMemberCount() == 0); DebugAssert(m_htBlockPalette.GetMemberCount() == 0); DebugAssert(m_htTerrainLayerList.GetMemberCount() == 0); DebugAssert(m_htBlockMesh.GetMemberCount() == 0); DebugAssert(m_htSkeleton.GetMemberCount() == 0); DebugAssert(m_htSkeletalMesh.GetMemberCount() == 0); DebugAssert(m_htSkeletalAnimation.GetMemberCount() == 0); DebugAssert(m_htParticleSystem.GetMemberCount() == 0); delete m_pResourceModificationChangeNotifier; DebugAssert(m_pResourceCompilerInterface == nullptr); } const ResourceTypeInfo *ResourceManager::GetResourceTypeForFile(const char *FileName) { PathString temp; return GetResourceTypeForStream(FileName, NULL, temp); } const ResourceTypeInfo *ResourceManager::GetResourceTypeForFile(const char *FileName, String &resourceName) { return GetResourceTypeForStream(FileName, NULL, resourceName); } const ResourceTypeInfo *ResourceManager::GetResourceTypeForStream(const char *FileName, ByteStream *pStream) { PathString temp; return GetResourceTypeForStream(FileName, pStream, temp); } const ResourceTypeInfo *ResourceManager::GetResourceTypeForStream(const char *FileName, ByteStream *pStream, String &resourceName) { resourceName = FileName; // Material if (resourceName.EndsWith(".mtl", false)) { resourceName.Erase(-4); return Material::StaticTypeInfo(); } else if (resourceName.EndsWith(".mtl.xml", false)) { resourceName.Erase(-8); return Material::StaticTypeInfo(); } // MaterialShader if (resourceName.EndsWith(".msh", false)) { resourceName.Erase(-4); return MaterialShader::StaticTypeInfo(); } else if (resourceName.EndsWith(".msh.xml", false)) { resourceName.Erase(-8); return MaterialShader::StaticTypeInfo(); } // Textures if (resourceName.EndsWith(".tex", false)) { resourceName.Erase(-4); TEXTURE_TYPE textureType; if (pStream == NULL) { pStream = g_pVirtualFileSystem->OpenFile(FileName, BYTESTREAM_OPEN_READ); if (pStream == NULL) return NULL; textureType = Texture::GetTextureTypeForStream(FileName, pStream); SAFE_RELEASE(pStream); } else { textureType = Texture::GetTextureTypeForStream(FileName, pStream); } return (textureType != TEXTURE_TYPE_COUNT) ? Texture2D::GetResourceTypeInfoForTextureType(textureType) : NULL; } else if (resourceName.EndsWith(".tex.dds", false)) { resourceName.Erase(-8); return Texture::StaticTypeInfo(); } // StaticMesh if (resourceName.EndsWith(".staticmesh", false)) { resourceName.Erase(-11); return StaticMesh::StaticTypeInfo(); } else if (resourceName.EndsWith(".staticmesh.xml", false)) { resourceName.Erase(-15); return StaticMesh::StaticTypeInfo(); } // Font if (resourceName.EndsWith(".font", false)) { resourceName.Erase(-5); return Font::StaticTypeInfo(); } else if (resourceName.EndsWith(".font.zip", false)) { resourceName.Erase(-9); return Font::StaticTypeInfo(); } // BlockMeshBlockList if (resourceName.EndsWith(".blp", false)) { resourceName.Erase(-4); return BlockPalette::StaticTypeInfo(); } else if (resourceName.EndsWith(".blp.xml", false)) { resourceName.Erase(-8); return BlockPalette::StaticTypeInfo(); } // BlockMeshBlockList if (resourceName.EndsWith(".layerlist", false)) { resourceName.Erase(-10); return TerrainLayerList::StaticTypeInfo(); } else if (resourceName.EndsWith(".layerlist.xml", false)) { resourceName.Erase(-14); return TerrainLayerList::StaticTypeInfo(); } // StaticBlockMesh if (resourceName.EndsWith(".blm", false)) { resourceName.Erase(-4); return BlockMesh::StaticTypeInfo(); } else if (resourceName.EndsWith(".blm.xml", false)) { resourceName.Erase(-8); return BlockMesh::StaticTypeInfo(); } // Skeleton if (resourceName.EndsWith(".skl", false)) { resourceName.Erase(-4); return Skeleton::StaticTypeInfo(); } else if (resourceName.EndsWith(".skl.xml", false)) { resourceName.Erase(-8); return Skeleton::StaticTypeInfo(); } // SkeletalMesh if (resourceName.EndsWith(".skm", false)) { resourceName.Erase(-4); return SkeletalMesh::StaticTypeInfo(); } else if (resourceName.EndsWith(".skm.xml", false)) { resourceName.Erase(-8); return SkeletalMesh::StaticTypeInfo(); } // SkeletalAnimation if (resourceName.EndsWith(".ska", false)) { resourceName.Erase(-4); return SkeletalAnimation::StaticTypeInfo(); } else if (resourceName.EndsWith(".ska.xml", false)) { resourceName.Erase(-8); return SkeletalAnimation::StaticTypeInfo(); } // ParticleSystem if (resourceName.EndsWith(".ParticleSystem", false)) { resourceName.Erase(-15); return ParticleSystem::StaticTypeInfo(); } else if (resourceName.EndsWith(".ParticleSystem.xml", false)) { resourceName.Erase(-19); return ParticleSystem::StaticTypeInfo(); } return nullptr; } void ResourceManager::ReleaseResources() { Log_DevPrint("ResourceManager is releasing all managed resources..."); // delete particle systems for (ParticleSystemTable::Iterator itr = m_htParticleSystem.Begin(); !itr.AtEnd();) { ParticleSystemTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htParticleSystem.Remove(pMember); } // delete skeletal animation sets for (SkeletalAnimationTable::Iterator itr = m_htSkeletalAnimation.Begin(); !itr.AtEnd(); ) { SkeletalAnimationTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htSkeletalAnimation.Remove(pMember); } // delete skeletal meshes for (SkeletalMeshTable::Iterator itr = m_htSkeletalMesh.Begin(); !itr.AtEnd();) { SkeletalMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htSkeletalMesh.Remove(pMember); } SAFE_RELEASE(m_pDefaultSkeletalMesh); // delete skeletons for (SkeletonTable::Iterator itr = m_htSkeleton.Begin(); !itr.AtEnd();) { SkeletonTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htSkeleton.Remove(pMember); } // delete static block meshes for (BlockMeshTable::Iterator itr = m_htBlockMesh.Begin(); !itr.AtEnd(); ) { BlockMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htBlockMesh.Remove(pMember); } SAFE_RELEASE(m_pDefaultBlockMesh); // delete terrain layer lists for (TerrainLayerListTable::Iterator itr = m_htTerrainLayerList.Begin(); !itr.AtEnd(); ) { TerrainLayerListTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htTerrainLayerList.Remove(pMember); } // delete block mesh block lists for (BlockPaletteTable::Iterator itr = m_htBlockPalette.Begin(); !itr.AtEnd(); ) { BlockPaletteTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htBlockPalette.Remove(pMember); } // delete font data for (FontTable::Iterator itr = m_htFonts.Begin(); !itr.AtEnd(); ) { FontTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htFonts.Remove(pMember); } // delete staticmesh for (StaticMeshTable::Iterator itr = m_htStaticMeshes.Begin(); !itr.AtEnd(); ) { StaticMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htStaticMeshes.Remove(pMember); } SAFE_RELEASE(m_pDefaultStaticMesh); // delete materials for (MaterialTable::Iterator itr = m_htMaterials.Begin(); !itr.AtEnd(); ) { MaterialTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htMaterials.Remove(pMember); } SAFE_RELEASE(m_pDefaultMaterial); // delete textures for (TextureTable::Iterator itr = m_htTextures.Begin(); !itr.AtEnd(); ) { TextureTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htTextures.Remove(pMember); } SAFE_RELEASE(m_pDefaultTexture2D); SAFE_RELEASE(m_pDefaultTexture2DArray); SAFE_RELEASE(m_pDefaultTextureCube); // delete material shaders for (MaterialShaderTable::Iterator itr = m_htMaterialShaders.Begin(); !itr.AtEnd(); ) { MaterialShaderTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) pMember->Value->Release(); m_htMaterialShaders.Remove(pMember); } SAFE_RELEASE(m_pDefaultMaterialShader); } static bool GetResourceStatus(String &resourceName, const char *compiledExtension, const char *sourceExtension, bool &compileResource, bool &hasSourceVersion, bool &hasCompiledVersion) { FILESYSTEM_STAT_DATA uncompiledStatData, compiledStatData; PathString currentFileName; // firstly check for the compiled version currentFileName.Format("%s%s", resourceName.GetCharArray(), compiledExtension); hasCompiledVersion = g_pVirtualFileSystem->StatFile(currentFileName, &compiledStatData); if (hasCompiledVersion) { // extract the resource name from it if (g_pVirtualFileSystem->GetFileName(currentFileName)) { resourceName.Clear(); resourceName.AppendSubString(currentFileName, 0, -(int32)Y_strlen(compiledExtension)); } } #if defined(WITH_RESOURCECOMPILER_EMBEDDED) || defined(WITH_RESOURCECOMPILER_SUBPROCESS) // now check for the uncompiled version if (CVars::rm_enable_resource_compilation.GetBool()) { currentFileName.Format("%s%s", resourceName.GetCharArray(), sourceExtension); hasSourceVersion = g_pVirtualFileSystem->StatFile(currentFileName, &uncompiledStatData); if (hasSourceVersion) { // we only use the uncompiled version if it's modification time is greater if (hasCompiledVersion && uncompiledStatData.ModificationTime <= compiledStatData.ModificationTime) { // don't use the source version compileResource = false; } else { // extract the resource name from it if (g_pVirtualFileSystem->GetFileName(currentFileName)) { resourceName.Clear(); resourceName.AppendSubString(currentFileName, 0, -(int32)Y_strlen(sourceExtension)); } // make the resource compile compileResource = true; } } else { // no source version, so can't compile, duh compileResource = false; } } else #endif { // resource compilation not enabled hasSourceVersion = false; compileResource = false; } // if we have neither, return false return (hasCompiledVersion | hasSourceVersion); } Material *ResourceManager::LoadMaterial(const char *Name) { PathString fileName; Material *pMaterial = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".mtl", ".mtl.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.mtl", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pMaterial = new Material(); if (!pMaterial->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadMaterial: Failed to load Material '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pMaterial->Release(); pMaterial = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadMaterial: Failed to load Material '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile material AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileMaterial(resourceName); if (pCompiledBlob != nullptr) { // release compiler here since we're no longer using it and something else could trigger compiling ReleaseResourceCompilerInterface(pCompilerInterface); // write it to disk fileName.Format("%s.mtl", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadMaterial: Failed to write Material '%s' to disk.", resourceName.GetCharArray()); // load the material from memory (saves a round-trip to the disk) pMaterial = new Material(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pMaterial->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadMaterial: Failed to load just-compiled Material '%s'.", resourceName.GetCharArray()); pMaterial->Release(); pMaterial = nullptr; } } else { // compile material failed Log_ErrorPrintf("ResourceManager::LoadMaterial: Failed to compile Material '%s'.", resourceName.GetCharArray()); ReleaseResourceCompilerInterface(pCompilerInterface); } } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadMaterial: Could not compile Material '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadMaterial: Material '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pMaterial != nullptr) Log_ProfilePrintf("PROFILE: Material load of '%s' took %.3f msec", pMaterial->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pMaterial; } const Material *ResourceManager::UncachedGetMaterial(const char *Name) { MaterialTable::Member *pMember = m_htMaterials.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadMaterial(Name); } const Material *ResourceManager::GetMaterial(const char *Name) { m_resourceLock.LockShared(); MaterialTable::Member *pMember = m_htMaterials.Find(Name); if (pMember == nullptr) { m_resourceLock.UnlockShared(); Material *pMaterial = LoadMaterial(Name); m_resourceLock.LockExclusive(); pMember = m_htMaterials.Find(Name); if (pMember == nullptr) pMember = m_htMaterials.Insert((pMaterial != nullptr) ? pMaterial->GetName().GetCharArray() : Name, pMaterial); else if (pMaterial != nullptr) pMaterial->Release(); m_resourceLock.UnlockExclusive(); } else { m_resourceLock.UnlockShared(); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const Material *ResourceManager::GetDefaultMaterial() { if (m_pDefaultMaterial == nullptr && (m_pDefaultMaterial = GetMaterial(g_pEngine->GetDefaultMaterialName())) == nullptr) Panic("GetDefaultMaterial() called, and the default material failed to load."); m_pDefaultMaterial->AddRef(); return m_pDefaultMaterial; } const Material *ResourceManager::SafeGetMaterial(const char *Name) { if (Name != nullptr) { const Material *pMaterial = GetMaterial(Name); if (pMaterial != nullptr) return pMaterial; } return GetDefaultMaterial(); } MaterialShader *ResourceManager::LoadMaterialShader(const char *Name) { PathString fileName; MaterialShader *pMaterialShader = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".msh", ".msh.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.msh", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pMaterialShader = new MaterialShader(); if (!pMaterialShader->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadMaterialShader: Failed to load MaterialShader '%s', read failed.", resourceName.GetCharArray()); pMaterialShader->Release(); pMaterialShader = nullptr; compileResource = hasSourceVersion; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadMaterialShader: Failed to load MaterialShader '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile material AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileMaterialShader(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.msh", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadMaterialShader: Failed to write MaterialShader '%s' to disk.", resourceName.GetCharArray()); // load the material from memory (saves a round-trip to the disk) pMaterialShader = new MaterialShader(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pMaterialShader->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadMaterialShader: Failed to load just-compiled MaterialShader '%s'.", resourceName.GetCharArray()); pMaterialShader->Release(); pMaterialShader = nullptr; } } else { // compile material failed Log_ErrorPrintf("ResourceManager::LoadMaterialShader: Failed to compile MaterialShader '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadMaterialShader: Could not compile MaterialShader '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadMaterialShader: MaterialShader '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pMaterialShader != nullptr) Log_ProfilePrintf("PROFILE: Material shader load of '%s' took %.3f msec", pMaterialShader->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pMaterialShader; } const MaterialShader *ResourceManager::GetMaterialShader(const char *Name) { m_resourceLock.LockShared(); MaterialShaderTable::Member *pMember = m_htMaterialShaders.Find(Name); if (pMember == nullptr) { m_resourceLock.UnlockShared(); MaterialShader *pMaterialShader = LoadMaterialShader(Name); m_resourceLock.LockExclusive(); pMember = m_htMaterialShaders.Find(Name); if (pMember == nullptr) pMember = m_htMaterialShaders.Insert((pMaterialShader != nullptr) ? pMaterialShader->GetName().GetCharArray() : Name, pMaterialShader); else if (pMaterialShader != nullptr) pMaterialShader->Release(); m_resourceLock.UnlockExclusive(); } else { m_resourceLock.UnlockShared(); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const MaterialShader *ResourceManager::UncachedGetMaterialShader(const char *Name) { MaterialShaderTable::Member *pMember = m_htMaterialShaders.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadMaterialShader(Name); } const MaterialShader *ResourceManager::GetDefaultMaterialShader() { if (m_pDefaultMaterialShader == nullptr && (m_pDefaultMaterialShader = GetMaterialShader(g_pEngine->GetDefaultMaterialShaderName())) == nullptr) Panic("GetDefaultShader() called, and the default material shader failed to load."); m_pDefaultMaterialShader->AddRef(); return m_pDefaultMaterialShader; } const MaterialShader *ResourceManager::SafeGetMaterialShader(const char *Name) { if (Name != nullptr) { const MaterialShader *pMaterialShader = GetMaterialShader(Name); if (pMaterialShader != nullptr) return pMaterialShader; } return GetDefaultMaterialShader(); } Texture *ResourceManager::LoadTexture(const char *Name) { PathString fileName; Texture *pTexture = nullptr; // get extension for current texture platform TEXTURE_PLATFORM texturePlatform = (g_pRenderer != nullptr) ? g_pRenderer->GetTexturePlatform() : TEXTURE_PLATFORM_DXTC; TinyString texturePlatformExtension; texturePlatformExtension.Format(".tex_%s", NameTable_GetNameString(NameTables::TexturePlatformFileExtension, texturePlatform)); #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, texturePlatformExtension, ".tex.zip", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it TEXTURE_TYPE textureType = Texture::GetTextureTypeForStream(fileName, pStream); pTexture = Texture::CreateTextureObjectForType(textureType); if (pTexture == nullptr || !pTexture->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadTexture: Failed to load Texture '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; SAFE_RELEASE(pTexture); } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadTexture: Failed to load Texture '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile Texture AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileTexture(texturePlatform, resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::GetTexture: Failed to write Texture '%s' to disk.", resourceName.GetCharArray()); // load the Texture from memory (saves a round-trip to the disk) AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); TEXTURE_TYPE textureType = Texture::GetTextureTypeForStream(fileName, pStream); pTexture = Texture::CreateTextureObjectForType(textureType); if (pTexture == nullptr || !pTexture->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadTexture: Failed to load just-compiled Texture '%s'.", resourceName.GetCharArray()); SAFE_RELEASE(pTexture); } } else { // compile Texture failed Log_ErrorPrintf("ResourceManager::LoadTexture: Failed to compile Texture '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadTexture: Could not compile Texture '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadTexture: Texture '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pTexture != nullptr) { Log_ProfilePrintf("PROFILE: Texture load of \"%s\" (%s, %s) took %.3f msec", pTexture->GetName().GetCharArray(), pTexture->GetResourceTypeInfo()->GetTypeName(), PixelFormat_GetPixelFormatInfo(pTexture->GetPixelFormat())->Name, loadTimer.GetTimeMilliseconds()); } #endif return pTexture; } const Texture *ResourceManager::GetTexture(const char *Name) { m_resourceLock.LockShared(); TextureTable::Member *pMember = m_htTextures.Find(Name); if (pMember == nullptr) { m_resourceLock.UnlockShared(); Texture *pTexture = LoadTexture(Name); m_resourceLock.LockExclusive(); pMember = m_htTextures.Find(Name); if (pMember == nullptr) pMember = m_htTextures.Insert((pTexture != nullptr) ? pTexture->GetName().GetCharArray() : Name, pTexture); else if (pTexture != nullptr) pTexture->Release(); m_resourceLock.UnlockExclusive(); } else { m_resourceLock.UnlockShared(); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const Texture2D *ResourceManager::GetTexture2D(const char *Name) { const Texture *pTexture = GetTexture(Name); if (pTexture == nullptr) return nullptr; const Texture2D *pTexture2D = pTexture->SafeCast<Texture2D>(); if (pTexture2D == NULL) { Log_ErrorPrintf("RESOURCE TYPE MISMATCH: Attempting to access resource '%s' as a Texture2D, when it is a %s", pTexture->GetName().GetCharArray(), pTexture->GetResourceTypeInfo()->GetTypeName()); pTexture->Release(); return nullptr; } return pTexture2D; } const Texture2DArray *ResourceManager::GetTexture2DArray(const char *Name) { const Texture *pTexture = GetTexture(Name); if (pTexture == nullptr) return nullptr; const Texture2DArray *pTexture2DArray = pTexture->SafeCast<Texture2DArray>(); if (pTexture2DArray == nullptr) { Log_ErrorPrintf("RESOURCE TYPE MISMATCH: Attempting to access resource '%s' as a Texture2DArray, when it is a %s", pTexture->GetName().GetCharArray(), pTexture->GetResourceTypeInfo()->GetTypeName()); pTexture->Release(); return NULL; } return pTexture2DArray; } const TextureCube *ResourceManager::GetTextureCube(const char *Name) { const Texture *pTexture = GetTexture(Name); if (pTexture == nullptr) return nullptr; const TextureCube *pTextureCube = pTexture->SafeCast<TextureCube>(); if (pTextureCube == nullptr) { Log_ErrorPrintf("RESOURCE TYPE MISMATCH: Attempting to access resource '%s' as a TextureCube, when it is a %s", pTexture->GetName().GetCharArray(), pTexture->GetResourceTypeInfo()->GetTypeName()); pTexture->Release(); return NULL; } return pTextureCube; } const Texture *ResourceManager::UncachedGetTexture(const char *Name) { TextureTable::Member *pMember = m_htTextures.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadTexture(Name); } const Texture *ResourceManager::GetDefaultTexture(TEXTURE_TYPE TextureType) { switch (TextureType) { case TEXTURE_TYPE_2D: return GetDefaultTexture2D(); case TEXTURE_TYPE_2D_ARRAY: return GetDefaultTexture2DArray(); case TEXTURE_TYPE_CUBE: return GetDefaultTextureCube(); } UnreachableCode(); return nullptr; } const Texture2D *ResourceManager::GetDefaultTexture2D() { if (m_pDefaultTexture2D == nullptr && (m_pDefaultTexture2D = GetTexture2D(g_pEngine->GetDefaultTexture2DName())) == nullptr) Panic("GetDefaultTexture2D() called, and the default texture failed to load."); m_pDefaultTexture2D->AddRef(); return m_pDefaultTexture2D; } const Texture2DArray *ResourceManager::GetDefaultTexture2DArray() { if (m_pDefaultTexture2DArray == nullptr && (m_pDefaultTexture2DArray = GetTexture2DArray(g_pEngine->GetDefaultTexture2DArrayName())) == nullptr) Panic("GetDefaultTexture2DArray() called, and the default texture failed to load."); m_pDefaultTexture2DArray->AddRef(); return m_pDefaultTexture2DArray; } const TextureCube *ResourceManager::GetDefaultTextureCube() { if (m_pDefaultTextureCube == nullptr && (m_pDefaultTextureCube = GetTextureCube(g_pEngine->GetDefaultTextureCubeName())) == nullptr) Panic("GetDefaultTextureCube() called, and the default texture failed to load."); m_pDefaultTextureCube->AddRef(); return m_pDefaultTextureCube; } const Texture2D *ResourceManager::SafeGetTexture2D(const char *Name) { if (Name != nullptr) { const Texture2D *pTexture2D = GetTexture2D(Name); if (pTexture2D != nullptr) return pTexture2D; } return GetDefaultTexture2D(); } const Texture2DArray *ResourceManager::SafeGetTexture2DArray(const char *Name) { if (Name != nullptr) { const Texture2DArray *pTexture2DArray = GetTexture2DArray(Name); if (pTexture2DArray != nullptr) return pTexture2DArray; } return GetDefaultTexture2DArray(); } const TextureCube *ResourceManager::SafeGetTextureCube(const char *Name) { if (Name != nullptr) { const TextureCube *pTextureCube = GetTextureCube(Name); if (pTextureCube != nullptr) return pTextureCube; } return GetDefaultTextureCube(); } StaticMesh *ResourceManager::LoadStaticMesh(const char *Name) { PathString fileName; StaticMesh *pStaticMesh = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".staticmesh", ".staticmesh.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.staticmesh", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pStaticMesh = new StaticMesh(); if (!pStaticMesh->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadStaticMesh: Failed to load StaticMesh '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pStaticMesh->Release(); pStaticMesh = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadStaticMesh: Failed to load StaticMesh '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile StaticMesh AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileStaticMesh(resourceName); if (pCompiledBlob != nullptr) { // release compiler here since we're no longer using it and something else could trigger compiling ReleaseResourceCompilerInterface(pCompilerInterface); // write it to disk fileName.Format("%s.staticmesh", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadStaticMesh: Failed to write StaticMesh '%s' to disk.", resourceName.GetCharArray()); // load the StaticMesh from memory (saves a round-trip to the disk) pStaticMesh = new StaticMesh(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pStaticMesh->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadStaticMesh: Failed to load just-compiled StaticMesh '%s'.", resourceName.GetCharArray()); pStaticMesh->Release(); pStaticMesh = nullptr; } } else { // compile StaticMesh failed Log_ErrorPrintf("ResourceManager::LoadStaticMesh: Failed to compile StaticMesh '%s'.", resourceName.GetCharArray()); ReleaseResourceCompilerInterface(pCompilerInterface); } } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadStaticMesh: Could not compile StaticMesh '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadStaticMesh: StaticMesh '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pStaticMesh != nullptr) Log_ProfilePrintf("PROFILE: StaticMesh load of '%s' took %.3f msec", pStaticMesh->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pStaticMesh; } const StaticMesh *ResourceManager::GetStaticMesh(const char *Name) { StaticMeshTable::Member *pMember = m_htStaticMeshes.Find(Name); if (pMember == nullptr) { StaticMesh *pStaticMesh = LoadStaticMesh(Name); pMember = m_htStaticMeshes.Insert((pStaticMesh != nullptr) ? pStaticMesh->GetName().GetCharArray() : Name, pStaticMesh); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const StaticMesh *ResourceManager::UncachedGetStaticMesh(const char *Name) { StaticMeshTable::Member *pMember = m_htStaticMeshes.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadStaticMesh(Name); } const StaticMesh *ResourceManager::GetDefaultStaticMesh() { if (m_pDefaultStaticMesh == nullptr && (m_pDefaultStaticMesh = GetStaticMesh(g_pEngine->GetDefaultStaticMeshName())) == nullptr) Panic("GetDefaultStaticMesh() called, and the default texture failed to load."); m_pDefaultStaticMesh->AddRef(); return m_pDefaultStaticMesh; } const StaticMesh *ResourceManager::SafeGetStaticMesh(const char *Name) { if (Name != nullptr) { const StaticMesh *pStaticMesh = GetStaticMesh(Name); if (pStaticMesh != nullptr) return pStaticMesh; } return GetDefaultStaticMesh(); } Font *ResourceManager::LoadFont(const char *Name) { PathString fileName; Font *pFont = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // get extension for current texture platform TEXTURE_PLATFORM texturePlatform = (g_pRenderer != nullptr) ? g_pRenderer->GetTexturePlatform() : TEXTURE_PLATFORM_DXTC; TinyString texturePlatformExtension; texturePlatformExtension.Format(".tex_%s", NameTable_GetNameString(NameTables::TexturePlatformFileExtension, texturePlatform)); // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, texturePlatformExtension, ".font.zip", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pFont = new Font(); if (!pFont->LoadFromStream(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadFont: Failed to load Font '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pFont->Release(); pFont = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadFont: Failed to load Font '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile Font AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileFont(texturePlatform, resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadFont: Failed to write Font '%s' to disk.", resourceName.GetCharArray()); // load the Font from memory (saves a round-trip to the disk) pFont = new Font(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pFont->LoadFromStream(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadFont: Failed to load just-compiled Font '%s'.", resourceName.GetCharArray()); pFont->Release(); pFont = nullptr; } } else { // compile Font failed Log_ErrorPrintf("ResourceManager::LoadFont: Failed to compile Font '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadFont: Could not compile Font '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadFont: Font '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pFont != nullptr) Log_ProfilePrintf("PROFILE: Font load of '%s' took %.3f msec", pFont->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pFont; } const Font *ResourceManager::GetFont(const char *name) { FontTable::Member *pMember = m_htFonts.Find(name); if (pMember == nullptr) { Font *pFont = LoadFont(name); pMember = m_htFonts.Insert((pFont != nullptr) ? pFont->GetName().GetCharArray() : name, pFont); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const Font *ResourceManager::UncachedGetFont(const char *Name) { FontTable::Member *pMember = m_htFonts.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadFont(Name); } BlockPalette *ResourceManager::LoadBlockPalette(const char *Name) { PathString fileName; BlockPalette *pBlockPalette = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // get extension for current texture platform TEXTURE_PLATFORM texturePlatform = (g_pRenderer != nullptr) ? g_pRenderer->GetTexturePlatform() : TEXTURE_PLATFORM_DXTC; TinyString texturePlatformExtension; texturePlatformExtension.Format(".blp_%s", NameTable_GetNameString(NameTables::TexturePlatformFileExtension, texturePlatform)); // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, texturePlatformExtension, ".blp.zip", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pBlockPalette = new BlockPalette(); if (!pBlockPalette->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadBlockPalette: Failed to load BlockPalette '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pBlockPalette->Release(); pBlockPalette = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadBlockPalette: Failed to load BlockPalette '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile BlockPalette AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileBlockPalette(texturePlatform, resourceName); if (pCompiledBlob != nullptr) { // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); // write it to disk fileName.Format("%s%s", resourceName.GetCharArray(), texturePlatformExtension.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadBlockPalette: Failed to write BlockPalette '%s' to disk.", resourceName.GetCharArray()); // load the BlockPalette from memory (saves a round-trip to the disk) pBlockPalette = new BlockPalette(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pBlockPalette->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadBlockPalette: Failed to load just-compiled BlockPalette '%s'.", resourceName.GetCharArray()); pBlockPalette->Release(); pBlockPalette = nullptr; } } else { // compile BlockPalette failed Log_ErrorPrintf("ResourceManager::LoadBlockPalette: Failed to compile BlockPalette '%s'.", resourceName.GetCharArray()); ReleaseResourceCompilerInterface(pCompilerInterface); } } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadBlockPalette: Could not compile BlockPalette '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadBlockPalette: BlockPalette '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pBlockPalette != nullptr) Log_ProfilePrintf("PROFILE: BlockPalette load of '%s' took %.3f msec", pBlockPalette->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pBlockPalette; } const BlockPalette *ResourceManager::GetBlockPalette(const char *Name) { BlockPaletteTable::Member *pMember = m_htBlockPalette.Find(Name); if (pMember == nullptr) { BlockPalette *pPalette = LoadBlockPalette(Name); pMember = m_htBlockPalette.Insert((pPalette != nullptr) ? pPalette->GetName().GetCharArray() : Name, pPalette); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const BlockPalette *ResourceManager::UncachedGetBlockPalette(const char *Name) { BlockPaletteTable::Member *pMember = m_htBlockPalette.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadBlockPalette(Name); } TerrainLayerList *ResourceManager::LoadTerrainLayerList(const char *Name) { PathString fileName; TerrainLayerList *pTerrainLayerList = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".layerlist", ".layerlist.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.layerlist", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pTerrainLayerList = new TerrainLayerList(); if (!pTerrainLayerList->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadTerrainLayerList: Failed to load TerrainLayerList '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pTerrainLayerList->Release(); pTerrainLayerList = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadTerrainLayerList: Failed to load TerrainLayerList '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile TerrainLayerList AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileTerrainLayerList(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.layerlist", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadTerrainLayerList: Failed to write TerrainLayerList '%s' to disk.", resourceName.GetCharArray()); // load the TerrainLayerList from memory (saves a round-trip to the disk) pTerrainLayerList = new TerrainLayerList(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pTerrainLayerList->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadTerrainLayerList: Failed to load just-compiled TerrainLayerList '%s'.", resourceName.GetCharArray()); pTerrainLayerList->Release(); pTerrainLayerList = nullptr; } } else { // compile TerrainLayerList failed Log_ErrorPrintf("ResourceManager::LoadTerrainLayerList: Failed to compile TerrainLayerList '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadTerrainLayerList: Could not compile TerrainLayerList '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadTerrainLayerList: TerrainLayerList '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pTerrainLayerList != nullptr) Log_ProfilePrintf("PROFILE: TerrainLayerList load of '%s' took %.3f msec", pTerrainLayerList->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pTerrainLayerList; } const TerrainLayerList *ResourceManager::GetTerrainLayerList(const char *Name) { TerrainLayerListTable::Member *pMember = m_htTerrainLayerList.Find(Name); if (pMember == nullptr) { TerrainLayerList *pLayerList = LoadTerrainLayerList(Name); pMember = m_htTerrainLayerList.Insert((pLayerList != nullptr) ? pLayerList->GetName().GetCharArray() : Name, pLayerList); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const TerrainLayerList *ResourceManager::UncachedGetTerrainLayerList(const char *Name) { TerrainLayerListTable::Member *pMember = m_htTerrainLayerList.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadTerrainLayerList(Name); } BlockMesh *ResourceManager::LoadBlockMesh(const char *Name) { PathString fileName; BlockMesh *pBlockMesh = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".blm", ".blm.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.blm", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pBlockMesh = new BlockMesh(); if (!pBlockMesh->Load(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadBlockMesh: Failed to load BlockMesh '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pBlockMesh->Release(); pBlockMesh = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadBlockMesh: Failed to load BlockMesh '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile BlockMesh AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileBlockMesh(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.mtl", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadBlockMesh: Failed to write BlockMesh '%s' to disk.", resourceName.GetCharArray()); // load the BlockMesh from memory (saves a round-trip to the disk) pBlockMesh = new BlockMesh(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pBlockMesh->Load(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadBlockMesh: Failed to load just-compiled BlockMesh '%s'.", resourceName.GetCharArray()); pBlockMesh->Release(); pBlockMesh = nullptr; } } else { // compile BlockMesh failed Log_ErrorPrintf("ResourceManager::LoadBlockMesh: Failed to compile BlockMesh '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadBlockMesh: Could not compile BlockMesh '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadBlockMesh: BlockMesh '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pBlockMesh != nullptr) Log_ProfilePrintf("PROFILE: BlockMesh load of '%s' took %.3f msec", pBlockMesh->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pBlockMesh; } const BlockMesh *ResourceManager::GetBlockMesh(const char *Name) { BlockMeshTable::Member *pMember = m_htBlockMesh.Find(Name); if (pMember == nullptr) { BlockMesh *pBlockMesh = LoadBlockMesh(Name); pMember = m_htBlockMesh.Insert((pBlockMesh != nullptr) ? pBlockMesh->GetName().GetCharArray() : Name, pBlockMesh); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const BlockMesh *ResourceManager::UncachedGetBlockMesh(const char *Name) { BlockMeshTable::Member *pMember = m_htBlockMesh.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadBlockMesh(Name); } const BlockMesh *ResourceManager::GetDefaultBlockMesh() { if (m_pDefaultBlockMesh == nullptr && (m_pDefaultBlockMesh = GetBlockMesh(g_pEngine->GetDefaultBlockMeshName())) == nullptr) Panic("GetDefaultBlockMesh() called, and the default mesh failed to load."); m_pDefaultBlockMesh->AddRef(); return m_pDefaultBlockMesh; } const BlockMesh *ResourceManager::SafeGetBlockMesh(const char *Name) { if (Name != nullptr) { const BlockMesh *pStaticBlockMesh = GetBlockMesh(Name); if (pStaticBlockMesh != nullptr) return pStaticBlockMesh; } return GetDefaultBlockMesh(); } Skeleton *ResourceManager::LoadSkeleton(const char *Name) { PathString fileName; Skeleton *pSkeleton = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".skl", ".skl.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.skl", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pSkeleton = new Skeleton(); if (!pSkeleton->LoadFromStream(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadSkeleton: Failed to load Skeleton '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pSkeleton->Release(); pSkeleton = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadSkeleton: Failed to load Skeleton '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile Skeleton AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileSkeleton(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.skl", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadSkeleton: Failed to write Skeleton '%s' to disk.", resourceName.GetCharArray()); // load the Skeleton from memory (saves a round-trip to the disk) pSkeleton = new Skeleton(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pSkeleton->LoadFromStream(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadSkeleton: Failed to load just-compiled Skeleton '%s'.", resourceName.GetCharArray()); pSkeleton->Release(); pSkeleton = nullptr; } } else { // compile Skeleton failed Log_ErrorPrintf("ResourceManager::LoadSkeleton: Failed to compile Skeleton '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadSkeleton: Could not compile Skeleton '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadSkeleton: Skeleton '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pSkeleton != nullptr) Log_ProfilePrintf("PROFILE: Skeleton load of '%s' took %.3f msec", pSkeleton->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pSkeleton; } const Skeleton *ResourceManager::GetSkeleton(const char *name) { SkeletonTable::Member *pMember = m_htSkeleton.Find(name); if (pMember == nullptr) { Skeleton *pSkeleton = LoadSkeleton(name); pMember = m_htSkeleton.Insert((pSkeleton != nullptr) ? pSkeleton->GetName().GetCharArray() : name, pSkeleton); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const Skeleton *ResourceManager::UncachedGetSkeleton(const char *Name) { SkeletonTable::Member *pMember = m_htSkeleton.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadSkeleton(Name); } SkeletalMesh *ResourceManager::LoadSkeletalMesh(const char *Name) { PathString fileName; SkeletalMesh *pSkeletalMesh = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".skm", ".skm.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.skm", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pSkeletalMesh = new SkeletalMesh(); if (!pSkeletalMesh->LoadFromStream(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadSkeletalMesh: Failed to load SkeletalMesh '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pSkeletalMesh->Release(); pSkeletalMesh = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadSkeletalMesh: Failed to load SkeletalMesh '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile SkeletalMesh AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileSkeletalMesh(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.skm", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadSkeletalMesh: Failed to write SkeletalMesh '%s' to disk.", resourceName.GetCharArray()); // load the SkeletalMesh from memory (saves a round-trip to the disk) pSkeletalMesh = new SkeletalMesh(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pSkeletalMesh->LoadFromStream(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadSkeletalMesh: Failed to load just-compiled SkeletalMesh '%s'.", resourceName.GetCharArray()); pSkeletalMesh->Release(); pSkeletalMesh = nullptr; } } else { // compile SkeletalMesh failed Log_ErrorPrintf("ResourceManager::LoadSkeletalMesh: Failed to compile SkeletalMesh '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadSkeletalMesh: Could not compile SkeletalMesh '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadSkeletalMesh: SkeletalMesh '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pSkeletalMesh != nullptr) Log_ProfilePrintf("PROFILE: SkeletalMesh load of '%s' took %.3f msec", pSkeletalMesh->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pSkeletalMesh; } const SkeletalMesh *ResourceManager::GetSkeletalMesh(const char *name) { SkeletalMeshTable::Member *pMember = m_htSkeletalMesh.Find(name); if (pMember == nullptr) { SkeletalMesh *pSkeletalMesh = LoadSkeletalMesh(name); pMember = m_htSkeletalMesh.Insert((pSkeletalMesh != nullptr) ? pSkeletalMesh->GetName().GetCharArray() : name, pSkeletalMesh); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const SkeletalMesh *ResourceManager::UncachedGetSkeletalMesh(const char *Name) { SkeletalMeshTable::Member *pMember = m_htSkeletalMesh.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadSkeletalMesh(Name); } const SkeletalMesh *ResourceManager::GetDefaultSkeletalMesh() { if (m_pDefaultSkeletalMesh == nullptr && (m_pDefaultSkeletalMesh = GetSkeletalMesh(g_pEngine->GetDefaultBlockMeshName())) == nullptr) Panic("GetDefaultSkeletalMesh() called, and the default mesh failed to load."); m_pDefaultSkeletalMesh->AddRef(); return m_pDefaultSkeletalMesh; } const SkeletalMesh *ResourceManager::SafeGetSkeletalMesh(const char *Name) { if (Name != nullptr) { const SkeletalMesh *pSkeletalMesh = GetSkeletalMesh(Name); if (pSkeletalMesh != nullptr) return pSkeletalMesh; } return GetDefaultSkeletalMesh(); } SkeletalAnimation *ResourceManager::LoadSkeletalAnimation(const char *Name) { PathString fileName; SkeletalAnimation *pSkeletalAnimation = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".ska", ".ska.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.ska", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pSkeletalAnimation = new SkeletalAnimation(); if (!pSkeletalAnimation->LoadFromStream(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadSkeletalAnimation: Failed to load SkeletalAnimation '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pSkeletalAnimation->Release(); pSkeletalAnimation = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadSkeletalAnimation: Failed to load SkeletalAnimation '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile SkeletalAnimation AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileSkeletalAnimation(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.ska", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadSkeletalAnimation: Failed to write SkeletalAnimation '%s' to disk.", resourceName.GetCharArray()); // load the SkeletalAnimation from memory (saves a round-trip to the disk) pSkeletalAnimation = new SkeletalAnimation(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pSkeletalAnimation->LoadFromStream(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadSkeletalAnimation: Failed to load just-compiled SkeletalAnimation '%s'.", resourceName.GetCharArray()); pSkeletalAnimation->Release(); pSkeletalAnimation = nullptr; } } else { // compile SkeletalAnimation failed Log_ErrorPrintf("ResourceManager::LoadSkeletalAnimation: Failed to compile SkeletalAnimation '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadSkeletalAnimation: Could not compile SkeletalAnimation '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadSkeletalAnimation: SkeletalAnimation '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pSkeletalAnimation != nullptr) Log_ProfilePrintf("PROFILE: SkeletalAnimation load of '%s' took %.3f msec", pSkeletalAnimation->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pSkeletalAnimation; } const SkeletalAnimation *ResourceManager::GetSkeletalAnimation(const char *name) { SkeletalAnimationTable::Member *pMember = m_htSkeletalAnimation.Find(name); if (pMember == nullptr) { SkeletalAnimation *pSkeletalAnimation = LoadSkeletalAnimation(name); pMember = m_htSkeletalAnimation.Insert((pSkeletalAnimation != nullptr) ? pSkeletalAnimation->GetName().GetCharArray() : name, pSkeletalAnimation); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const SkeletalAnimation *ResourceManager::UncachedGetSkeletalAnimation(const char *Name) { SkeletalAnimationTable::Member *pMember = m_htSkeletalAnimation.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadSkeletalAnimation(Name); } ParticleSystem *ResourceManager::LoadParticleSystem(const char *Name) { PathString fileName; ParticleSystem *pParticleSystem = nullptr; #if PROFILE_RESOURCEMANAGER_LOAD_TIMES Timer loadTimer; #endif // build name (for now) PathString resourceName; resourceName.AppendString(Name); // see what we have bool compileResource, hasSourceVersion, hasCompiledVersion; if (GetResourceStatus(resourceName, ".ParticleSystem", ".ParticleSystem.xml", compileResource, hasSourceVersion, hasCompiledVersion)) { // loading the compiled version? if (hasCompiledVersion) { AutoReleasePtr<ByteStream> pStream; fileName.Format("%s.ParticleSystem", resourceName.GetCharArray()); pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream != nullptr) { // load it pParticleSystem = new ParticleSystem(); if (!pParticleSystem->LoadFromStream(resourceName, pStream)) { // log the error, then try to recompile it Log_ErrorPrintf("ResourceManager::LoadParticleSystem: Failed to load ParticleSystem '%s', read failed.", resourceName.GetCharArray()); compileResource = hasSourceVersion; pParticleSystem->Release(); pParticleSystem = nullptr; } } else { // open failed Log_ErrorPrintf("ResourceManager::LoadParticleSystem: Failed to load ParticleSystem '%s', open failed.", resourceName.GetCharArray()); } } // loading the uncompiled version? if (compileResource) { // open resource compiler ResourceCompilerInterface *pCompilerInterface = GetResourceCompilerInterface(); if (pCompilerInterface != nullptr) { // compile ParticleSystem AutoReleasePtr<BinaryBlob> pCompiledBlob = pCompilerInterface->CompileParticleSystem(resourceName); if (pCompiledBlob != nullptr) { // write it to disk fileName.Format("%s.ParticleSystem", resourceName.GetCharArray()); if (!g_pVirtualFileSystem->PutFileContents(fileName, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize(), true, true)) Log_WarningPrintf("ResourceManager::LoadParticleSystem: Failed to write ParticleSystem '%s' to disk.", resourceName.GetCharArray()); // load the ParticleSystem from memory (saves a round-trip to the disk) pParticleSystem = new ParticleSystem(); AutoReleasePtr<ByteStream> pStream = pCompiledBlob->CreateReadOnlyStream(); if (!pParticleSystem->LoadFromStream(resourceName, pStream)) { Log_ErrorPrintf("ResourceManager::LoadParticleSystem: Failed to load just-compiled ParticleSystem '%s'.", resourceName.GetCharArray()); pParticleSystem->Release(); pParticleSystem = nullptr; } } else { // compile ParticleSystem failed Log_ErrorPrintf("ResourceManager::LoadParticleSystem: Failed to compile ParticleSystem '%s'.", resourceName.GetCharArray()); } // release compiler ReleaseResourceCompilerInterface(pCompilerInterface); } else { // open resource compiler failed Log_ErrorPrintf("ResourceManager::LoadParticleSystem: Could not compile ParticleSystem '%s', no compiler available.", resourceName.GetCharArray()); } } } else { Log_WarningPrintf("ResourceManager::LoadParticleSystem: ParticleSystem '%s' is unavailable or does not exit.", resourceName.GetCharArray()); } #if PROFILE_RESOURCEMANAGER_LOAD_TIMES if (pParticleSystem != nullptr) Log_ProfilePrintf("PROFILE: ParticleSystem load of '%s' took %.3f msec", pParticleSystem->GetName().GetCharArray(), loadTimer.GetTimeMilliseconds()); #endif return pParticleSystem; } const ParticleSystem *ResourceManager::GetParticleSystem(const char *name) { m_resourceLock.LockShared(); ParticleSystemTable::Member *pMember = m_htParticleSystem.Find(name); if (pMember == nullptr) { m_resourceLock.UnlockShared(); ParticleSystem *pParticleSystem = LoadParticleSystem(name); m_resourceLock.LockExclusive(); pMember = m_htParticleSystem.Find(name); if (pMember == nullptr) pMember = m_htParticleSystem.Insert((pParticleSystem != nullptr) ? pParticleSystem->GetName().GetCharArray() : name, pParticleSystem); else if (pParticleSystem != nullptr) pParticleSystem->Release(); m_resourceLock.UnlockExclusive(); } else { m_resourceLock.UnlockShared(); } if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } const ParticleSystem *ResourceManager::UncachedGetParticleSystem(const char *Name) { ParticleSystemTable::Member *pMember = m_htParticleSystem.Find(Name); if (pMember != nullptr) { if (pMember->Value != nullptr) pMember->Value->AddRef(); return pMember->Value; } return LoadParticleSystem(Name); } void ResourceManager::CreateDeviceResources() { // recreate lost resources Log_InfoPrint("ResourceManager::CreateDeviceResources() Recreating lost resources..."); // textures for (TextureTable::Iterator itr = m_htTextures.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateDeviceResources(); } // shader for (MaterialShaderTable::Iterator itr = m_htMaterialShaders.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateDeviceResources(); } // material for (MaterialTable::Iterator itr = m_htMaterials.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateDeviceResources(); } // staticmesh for (StaticMeshTable::Iterator itr = m_htStaticMeshes.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateGPUResources(); } // blocklists for (BlockPaletteTable::Iterator itr = m_htBlockPalette.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateGPUResources(); } // static block meshes for (BlockMeshTable::Iterator itr = m_htBlockMesh.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateGPUResources(); } // skeletal meshes for (SkeletalMeshTable::Iterator itr = m_htSkeletalMesh.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->CreateGPUResources(); } } void ResourceManager::ReleaseDeviceResources() { Log_InfoPrint("ResourceManager::ReleaseDeviceResources()"); // skeletal meshes for (SkeletalMeshTable::Iterator itr = m_htSkeletalMesh.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseGPUResources(); } // static block meshes for (BlockMeshTable::Iterator itr = m_htBlockMesh.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseGPUResources(); } // terrain layer lists for (TerrainLayerListTable::Iterator itr = m_htTerrainLayerList.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseGPUResources(); } // blocklists for (BlockPaletteTable::Iterator itr = m_htBlockPalette.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseGPUResources(); } // staticmesh for (StaticMeshTable::Iterator itr = m_htStaticMeshes.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseGPUResources(); } // material for (MaterialTable::Iterator itr = m_htMaterials.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseDeviceResources(); } // shader for (MaterialShaderTable::Iterator itr = m_htMaterialShaders.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseDeviceResources(); } // textures for (TextureTable::Iterator itr = m_htTextures.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value != NULL) itr->Value->ReleaseDeviceResources(); } } // the way this is currently done is a bit of a hack, basically we add a reference, then release it immediately, // giving the current reference count on return, if this is one, the only copy left is inside the resource manager, // so we drop it. if the pointer is null, we just remove it anyway. void ResourceManager::CompactResources() { uint32 nRefCount; Log_DevPrint("ResourceManager is compacting managed resources..."); // delete skeletal animation sets for (ParticleSystemTable::Iterator itr = m_htParticleSystem.Begin(); !itr.AtEnd();) { ParticleSystemTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping ParticleSystem '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htParticleSystem.Remove(pMember); } // delete skeletal animation sets for (SkeletalAnimationTable::Iterator itr = m_htSkeletalAnimation.Begin(); !itr.AtEnd();) { SkeletalAnimationTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping SkeletalAnimationSet '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htSkeletalAnimation.Remove(pMember); } // delete skeletal meshes for (SkeletalMeshTable::Iterator itr = m_htSkeletalMesh.Begin(); !itr.AtEnd();) { SkeletalMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping SkeletalMesh '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htSkeletalMesh.Remove(pMember); } // delete skeletons for (SkeletonTable::Iterator itr = m_htSkeleton.Begin(); !itr.AtEnd();) { SkeletonTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping Skeleton '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htSkeleton.Remove(pMember); } // delete block meshes for (BlockMeshTable::Iterator itr = m_htBlockMesh.Begin(); !itr.AtEnd(); ) { BlockMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping BlockMesh '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htBlockMesh.Remove(pMember); } // delete terrain layer lists for (TerrainLayerListTable::Iterator itr = m_htTerrainLayerList.Begin(); !itr.AtEnd();) { TerrainLayerListTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping TerrainLayerList '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htTerrainLayerList.Remove(pMember); } // delete block mesh block lists for (BlockPaletteTable::Iterator itr = m_htBlockPalette.Begin(); !itr.AtEnd(); ) { BlockPaletteTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping BlockMeshBlockList '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htBlockPalette.Remove(pMember); } // delete font data for (FontTable::Iterator itr = m_htFonts.Begin(); !itr.AtEnd(); ) { FontTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping FontData '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htFonts.Remove(pMember); } // delete staticmesh for (StaticMeshTable::Iterator itr = m_htStaticMeshes.Begin(); !itr.AtEnd(); ) { StaticMeshTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping StaticMesh '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htStaticMeshes.Remove(pMember); } // delete materials for (MaterialTable::Iterator itr = m_htMaterials.Begin(); !itr.AtEnd(); ) { MaterialTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping Material '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htMaterials.Remove(pMember); } // delete material shaders for (MaterialShaderTable::Iterator itr = m_htMaterialShaders.Begin(); !itr.AtEnd(); ) { MaterialShaderTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping MaterialShader '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htMaterialShaders.Remove(pMember); } // delete textures for (TextureTable::Iterator itr = m_htTextures.Begin(); !itr.AtEnd(); ) { TextureTable::Member *pMember = &(*itr++); if (pMember->Value != NULL) { pMember->Value->AddRef(); if (pMember->Value->Release() > 1) continue; // drop last reference Log_DevPrintf(" dropping Texture '%s'...", pMember->Value->GetName().GetCharArray()); nRefCount = pMember->Value->Release(); DebugAssert(nRefCount == 0); } m_htTextures.Remove(pMember); } } const Resource *ResourceManager::GetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *Name) { if (pResourceTypeInfo->IsDerived(Texture::StaticTypeInfo())) return GetTexture(Name); else if (pResourceTypeInfo == Material::StaticTypeInfo()) return GetMaterial(Name); else if (pResourceTypeInfo == MaterialShader::StaticTypeInfo()) return GetMaterialShader(Name); else if (pResourceTypeInfo == StaticMesh::StaticTypeInfo()) return GetStaticMesh(Name); else if (pResourceTypeInfo == BlockMesh::StaticTypeInfo()) return GetBlockMesh(Name); else if (pResourceTypeInfo == Skeleton::StaticTypeInfo()) return GetSkeleton(Name); else if (pResourceTypeInfo == SkeletalMesh::StaticTypeInfo()) return GetSkeletalMesh(Name); else if (pResourceTypeInfo == SkeletalAnimation::StaticTypeInfo()) return GetSkeletalAnimation(Name); return NULL; } const Resource *ResourceManager::SafeGetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *Name) { if (pResourceTypeInfo->IsDerived(Texture::StaticTypeInfo())) { if (pResourceTypeInfo == Texture2D::StaticTypeInfo()) return SafeGetTexture2D(Name); else if (pResourceTypeInfo == TextureCube::StaticTypeInfo()) return SafeGetTextureCube(Name); } else if (pResourceTypeInfo == Material::StaticTypeInfo()) return SafeGetMaterial(Name); else if (pResourceTypeInfo == MaterialShader::StaticTypeInfo()) return SafeGetMaterialShader(Name); else if (pResourceTypeInfo == StaticMesh::StaticTypeInfo()) return SafeGetStaticMesh(Name); else if (pResourceTypeInfo == BlockMesh::StaticTypeInfo()) return SafeGetBlockMesh(Name); else if (pResourceTypeInfo == SkeletalMesh::StaticTypeInfo()) return SafeGetSkeletalMesh(Name); return NULL; } const Resource *ResourceManager::UncachedGetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *Name) { if (pResourceTypeInfo->IsDerived(Texture::StaticTypeInfo())) return UncachedGetTexture(Name); else if (pResourceTypeInfo == Material::StaticTypeInfo()) return UncachedGetMaterial(Name); else if (pResourceTypeInfo == MaterialShader::StaticTypeInfo()) return UncachedGetMaterialShader(Name); else if (pResourceTypeInfo == StaticMesh::StaticTypeInfo()) return UncachedGetStaticMesh(Name); else if (pResourceTypeInfo == BlockMesh::StaticTypeInfo()) return UncachedGetBlockMesh(Name); else if (pResourceTypeInfo == Skeleton::StaticTypeInfo()) return UncachedGetSkeleton(Name); else if (pResourceTypeInfo == SkeletalMesh::StaticTypeInfo()) return UncachedGetSkeletalMesh(Name); else if (pResourceTypeInfo == SkeletalAnimation::StaticTypeInfo()) return UncachedGetSkeletalAnimation(Name); return NULL; } void ResourceManager::SetResourceModificationDetectionEnabled(bool enabled) { if (!enabled) { if (m_pResourceModificationChangeNotifier != nullptr) { delete m_pResourceModificationChangeNotifier; m_pResourceModificationChangeNotifier = nullptr; Log_InfoPrint("ResourceManager: Resource modification detection disabled."); } } else { m_pResourceModificationChangeNotifier = g_pVirtualFileSystem->CreateChangeNotifier(); if (m_pResourceModificationChangeNotifier != nullptr) Log_InfoPrint("ResourceManager: Resource modification detection enabled successfully."); else Log_WarningPrint("ResourceManager: Failed to enable resource modification detection."); } } void ResourceManager::CheckForModifiedResources() { if (m_pResourceModificationChangeNotifier == nullptr) return; m_pResourceModificationChangeNotifier->EnumerateChanges([](const FileSystem::ChangeNotifier::ChangeInfo *pChangeInfo) { const char *changeTypeStr = "unknown"; if (pChangeInfo->Event == FileSystem::ChangeNotifier::ChangeEvent_FileAdded) changeTypeStr = "ChangeEvent_FileAdded"; else if (pChangeInfo->Event == FileSystem::ChangeNotifier::ChangeEvent_FileRemoved) changeTypeStr = "ChangeEvent_FileRemoved"; else if (pChangeInfo->Event == FileSystem::ChangeNotifier::ChangeEvent_FileModified) changeTypeStr = "ChangeEvent_FileModified"; else if (pChangeInfo->Event == FileSystem::ChangeNotifier::ChangeEvent_RenamedOldName) changeTypeStr = "ChangeEvent_RenamedOldName"; else if (pChangeInfo->Event == FileSystem::ChangeNotifier::ChangeEvent_RenamedNewName) changeTypeStr = "ChangeEvent_RenamedNewName"; Log_DevPrintf("ResourceManager::CheckForModifiedResources: Change %s on file '%s'", changeTypeStr, pChangeInfo->Path); }); } ResourceCompilerInterface *ResourceManager::GetResourceCompilerInterface() { #if defined(WITH_RESOURCECOMPILER_SUBPROCESS) // hold the lock m_resourceCompilerLock.Lock(); // primary in use? if (m_resourceCompilerInUse) { // resource compiler is in use, so spawn another one return ResourceCompilerInterface::CreateRemoteInterface(); } // if there's an existing interface, use it if (m_pResourceCompilerInterface != nullptr) { m_resourceCompilerInUse = true; return m_pResourceCompilerInterface; } // spawn nw m_pResourceCompilerInterface = ResourceCompilerInterface::CreateRemoteInterface(); if (m_pResourceCompilerInterface == nullptr) { Log_ErrorPrintf("ResourceManager::GetResourceCompilerInterface: Failed to create interface."); m_resourceCompilerLock.Unlock(); return nullptr; } m_resourceCompilerInUse = true; m_resourceCompilerSpawnTime.Reset(); return m_pResourceCompilerInterface; #else Log_ErrorPrintf("ResourceManager::GetResourceCompilerInterface: This engine was not built with ResourceCompiler support."); return nullptr; #endif // WITH_RESOURCECOMPILER_SUBPROCESS } void ResourceManager::ReleaseResourceCompilerInterface(ResourceCompilerInterface *pInterface) { #if defined(WITH_RESOURCECOMPILER_SUBPROCESS) if (pInterface == m_pResourceCompilerInterface) { DebugAssert(m_resourceCompilerInUse); m_resourceCompilerInUse = false; // if there is a zero delay, just close it immediately if (CVars::rm_remote_resource_compiler_close_delay.GetUInt() == 0) { m_pResourceCompilerInterface->Release(); m_pResourceCompilerInterface = nullptr; } } else { // was one of the extra spawned ones, so just despawn it pInterface->Release(); } // release lock m_resourceCompilerLock.Unlock(); #endif // WITH_RESOURCECOMPILER_SUBPROCESS } void ResourceManager::Update() { // perform maintenance uint32 timeDiff = (uint32)Math::Truncate((float)m_lastMaintenanceTime.GetTimeSeconds()); if (timeDiff >= CVars::rm_maintenance_interval.GetUInt()) { // update changed resources CheckForModifiedResources(); #if defined(WITH_RESOURCECOMPILER_SUBPROCESS) // release resource compiler if it hasn't been used in x time // potential race here, it just means we'll miss cleaning it up for a loop, which // is unlikely to have the time elapsed anyway, and it saves locking every frame if (m_pResourceCompilerInterface != nullptr && m_resourceCompilerLock.TryLock()) { uint32 timeElapsed = (uint32)Math::Truncate((float)m_resourceCompilerSpawnTime.GetTimeSeconds()); if (!m_resourceCompilerInUse && timeElapsed >= CVars::rm_remote_resource_compiler_close_delay.GetUInt()) { // release him m_pResourceCompilerInterface->Release(); m_pResourceCompilerInterface = nullptr; } m_resourceCompilerLock.Unlock(); } #endif // WITH_RESOURCECOMPILER_SUBPROCESS } } <file_sep>/Engine/Source/Engine/TerrainLayerList.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainLayerList.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" #include "Renderer/Renderer.h" #include "Core/ChunkFileReader.h" Log_SetChannel(TerrainLayerList); DEFINE_RESOURCE_TYPE_INFO(TerrainLayerList); DEFINE_RESOURCE_GENERIC_FACTORY(TerrainLayerList); TerrainLayerList::TerrainLayerList(const ResourceTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pBaseLayers(NULL), m_baseLayerArraySize(0), m_ppTextures(NULL), m_textureCount(0), m_combinedBaseLayerBaseTextureIndex(-1), m_combinedBaseLayerNormalTextureIndex(-1) { } TerrainLayerList::~TerrainLayerList() { delete[] m_pBaseLayers; for (uint32 i = 0; i < m_textureCount; i++) { if (m_ppTextures[i] != NULL) m_ppTextures[i]->Release(); } delete[] m_ppTextures; } const TerrainLayerListBaseLayer *TerrainLayerList::GetBaseLayerByName(const char *name) const { for (uint32 i = 0; i < m_baseLayerArraySize; i++) { if (m_pBaseLayers[i].Allocated && m_pBaseLayers[i].Name.Compare(name)) return &m_pBaseLayers[i]; } return NULL; } bool TerrainLayerList::Load(const char *FileName, ByteStream *pStream) { PathString tempString; #define ABORTREASON(Reason) Log_ErrorPrintf("Could not load TerrainLayerList '%s': %s", FileName, Reason) // set name m_strName = FileName; // read header DF_TERRAIN_LAYER_LIST_HEADER header; if (!pStream->Read2(&header, sizeof(header))) return false; // validate header if (header.Magic != DF_TERRAIN_LAYER_LIST_HEADER_MAGIC || header.HeaderSize != sizeof(header)) { return false; } // init chunkloader ChunkFileReader chunkReader; if (!chunkReader.Initialize(pStream)) return false; // load textures uint32 nTextures = header.TextureCount; if (nTextures > 0) { if (chunkReader.LoadChunk(DF_TERRAIN_LAYER_LIST_CHUNK_TEXTURES) && chunkReader.GetCurrentChunkSize() >= (sizeof(DF_TERRAIN_LAYER_LIST_TEXTURE) * nTextures)) { m_ppTextures = new const Texture *[nTextures]; m_textureCount = nTextures; Y_memzero(m_ppTextures, sizeof(const Texture *) * nTextures); const byte *pChunkBasePointer = (const byte *)chunkReader.GetCurrentChunkPointer(); uint32 chunkSize = chunkReader.GetCurrentChunkSize(); const DF_TERRAIN_LAYER_LIST_TEXTURE *pTextureHeader = (const DF_TERRAIN_LAYER_LIST_TEXTURE *)pChunkBasePointer; for (uint32 i = 0; i < nTextures; i++, pTextureHeader++) { // generate name tempString.Format("%s:%u", m_strName.GetCharArray(), i); // validate range if ((pTextureHeader->TextureOffset + pTextureHeader->TextureSize) > chunkSize || pTextureHeader->TextureSize == 0) { ABORTREASON("corrupted texture chunk"); return false; } // create stream AutoReleasePtr<ByteStream> pTextureStream = ByteStream_CreateReadOnlyMemoryStream(pChunkBasePointer + pTextureHeader->TextureOffset, pTextureHeader->TextureSize); DebugAssert(pTextureStream != NULL); // work out texture type TEXTURE_TYPE textureType = Texture::GetTextureTypeForStream(tempString, pTextureStream); if (textureType == TEXTURE_TYPE_COUNT) { ABORTREASON("corrupted internal texture"); return false; } // create an internal texture Texture *pInternalTexture = Texture::CreateTextureObjectForType(textureType); DebugAssert(pInternalTexture != NULL); // load it if (!pInternalTexture->Load(tempString, pTextureStream)) { ABORTREASON("corrupted internal texture"); pInternalTexture->Release(); return false; } // store it m_ppTextures[i] = pInternalTexture; } } else { ABORTREASON("invalid texture chunk"); return false; } } // load base layers uint32 baseLayerCount = header.BaseLayerCount; uint32 baseLayerArraySize = header.BaseLayerArraySize; if (baseLayerCount > 0 && chunkReader.LoadChunk(DF_TERRAIN_LAYER_LIST_CHUNK_BASE_LAYERS) && chunkReader.GetCurrentChunkTypeCount<DF_TERRAIN_LAYER_LIST_BASE_LAYER>() == baseLayerCount) { DebugAssert(baseLayerArraySize < TERRAIN_MAX_LAYERS); m_pBaseLayers = new TerrainLayerListBaseLayer[baseLayerArraySize]; m_baseLayerArraySize = baseLayerArraySize; // init layers as blank for (uint32 i = 0; i < baseLayerArraySize; i++) { m_pBaseLayers[i].Index = i; m_pBaseLayers[i].Allocated = false; m_pBaseLayers[i].TextureRepeatInterval = 0; m_pBaseLayers[i].BaseTextureIndex = -1; m_pBaseLayers[i].BaseTextureArrayIndex = -1; m_pBaseLayers[i].NormalTextureIndex = -1; m_pBaseLayers[i].NormalTextureArrayIndex = -1; } // read them in const DF_TERRAIN_LAYER_LIST_BASE_LAYER *pSourceBaseLayer = chunkReader.GetCurrentChunkTypePointer<DF_TERRAIN_LAYER_LIST_BASE_LAYER>(); for (uint32 i = 0; i < baseLayerCount; i++, pSourceBaseLayer++) { if (pSourceBaseLayer->LayerIndex >= baseLayerArraySize || m_pBaseLayers[pSourceBaseLayer->LayerIndex].Allocated) { ABORTREASON("invalid base layer index"); return false; } // store fields TerrainLayerListBaseLayer *pDestinationBaseLayer = &m_pBaseLayers[pSourceBaseLayer->LayerIndex]; pDestinationBaseLayer->Allocated = true; pDestinationBaseLayer->Name = chunkReader.GetStringByIndex(pSourceBaseLayer->NameStringIndex); pDestinationBaseLayer->TextureRepeatInterval = pSourceBaseLayer->TextureRepeatInterval; pDestinationBaseLayer->BaseTextureIndex = pSourceBaseLayer->BaseTextureIndex; pDestinationBaseLayer->BaseTextureArrayIndex = pSourceBaseLayer->BaseTextureArrayIndex; pDestinationBaseLayer->NormalTextureIndex = pSourceBaseLayer->NormalTextureIndex; pDestinationBaseLayer->NormalTextureArrayIndex = pSourceBaseLayer->NormalTextureArrayIndex; // validate data if ((pDestinationBaseLayer->BaseTextureIndex >= 0 && (uint32)pDestinationBaseLayer->BaseTextureIndex >= m_textureCount) || (pDestinationBaseLayer->NormalTextureIndex >= 0 && (uint32)pDestinationBaseLayer->NormalTextureIndex >= m_textureCount)) { ABORTREASON("invalid base layer texture index"); return false; } } } else { ABORTREASON("invalid base layers chunk"); return false; } // store fields m_combinedBaseLayerBaseTextureIndex = header.CombinedBaseLayerBaseTextureIndex; m_combinedBaseLayerNormalTextureIndex = header.CombinedBaseLayerNormalTextureIndex; // validate fields if ((m_combinedBaseLayerBaseTextureIndex >= 0 && (uint32)m_combinedBaseLayerBaseTextureIndex >= m_textureCount) || (m_combinedBaseLayerNormalTextureIndex >= 0 && (uint32)m_combinedBaseLayerNormalTextureIndex >= m_textureCount)) { ABORTREASON("invalid combined texture indices"); return false; } #undef ABORTREASON // create on gpu if (!CreateGPUResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool TerrainLayerList::CreateGPUResources() { uint32 i; for (i = 0; i < m_textureCount; i++) { if (!m_ppTextures[i]->CreateDeviceResources()) return false; } return true; } void TerrainLayerList::ReleaseGPUResources() { } uint32 TerrainLayerList::GetFirstLayerIndex() const { for (uint32 i = 0; i < m_baseLayerArraySize; i++) { if (m_pBaseLayers[i].Allocated) return i; } Panic("No base layers"); return 0; } const Material *TerrainLayerList::CreateBaseLayerRenderMaterial(const int32 *pLayerIndices, uint32 nLayerIndices, GPUTexture2D *pNormalMapTexture, GPUTexture **pWeightTextures, uint32 nWeightTextures) const { DebugAssert(nLayerIndices > 0 && nWeightTextures > 0); // expect a 2d texture and <= 4 weights if (nWeightTextures == 1 && pWeightTextures[0]->GetTextureType() == TEXTURE_TYPE_2D) { // get textures const Texture *pBaseTexture = (m_combinedBaseLayerBaseTextureIndex >= 0) ? m_ppTextures[m_combinedBaseLayerBaseTextureIndex] : nullptr; //const Texture *pNormalTexture = (m_combinedBaseLayerNormalTextureIndex >= 0) ? m_ppTextures[m_combinedBaseLayerNormalTextureIndex] : nullptr; // todo: handle normal maps AutoReleasePtr<const MaterialShader> pShader = g_pResourceManager->GetMaterialShader("shaders/engine/terrain/section_texture_array"); if (pShader == nullptr) return nullptr; // create an instance of it Material *pMaterial = new Material(); pMaterial->Create("<terrain section render material>", pShader); float4 uniformTerrainTextureArrayIndices; float4 uniformTerrainTextureArrayRepeatIntervals; for (uint32 j = 0; j < 4; j++) { if (j < nLayerIndices && pLayerIndices[j] >= 0 && (uint32)pLayerIndices[j] < m_baseLayerArraySize && m_pBaseLayers[pLayerIndices[j]].Allocated) { uniformTerrainTextureArrayIndices[j] = (float)pLayerIndices[j]; uniformTerrainTextureArrayRepeatIntervals[j] = 1.0f / (float)m_pBaseLayers[pLayerIndices[j]].TextureRepeatInterval; } else { uniformTerrainTextureArrayIndices[j] = 0.0f; uniformTerrainTextureArrayRepeatIntervals[j] = 0.0f; } } pMaterial->SetShaderUniformParameterByName("TerrainTextureArrayIndices", SHADER_PARAMETER_TYPE_FLOAT4, &uniformTerrainTextureArrayIndices); pMaterial->SetShaderUniformParameterByName("TerrainTextureArrayRepeatIntervals", SHADER_PARAMETER_TYPE_FLOAT4, &uniformTerrainTextureArrayRepeatIntervals); pMaterial->SetShaderTextureParameterByName("NormalMap", pNormalMapTexture); pMaterial->SetShaderTextureParameterByName("BaseLayerAlphaMap", pWeightTextures[0]); pMaterial->SetShaderTextureParameterByName("BaseLayerDiffuseMap", pBaseTexture); // done return pMaterial; } // nothing created return nullptr; } <file_sep>/Engine/Source/BlockEngine/BlockWorldSection.h #pragma once #include "BlockEngine/BlockWorldTypes.h" #include "BlockEngine/BlockWorldChunk.h" class BlockWorldSection : public ReferenceCounted { public: enum LoadState { LoadState_Loaded, LoadState_Changed, LoadState_Generating, LoadState_Count, }; public: BlockWorldSection(BlockWorld *pWorld, int32 sectionX, int32 sectionY); ~BlockWorldSection(); // accessors const BlockWorld *GetWorld() const { return m_pWorld; } const int32 GetSectionSize() const { return m_sectionSize; } const int32 GetChunkSize() const { return m_chunkSize; } const int32 GetSectionX() const { return m_sectionX; } const int32 GetSectionY() const { return m_sectionY; } const int32 GetLODLevels() const { return m_lodLevels; } const int32 GetBaseChunkX() const { return m_baseChunkX; } const int32 GetBaseChunkY() const { return m_baseChunkY; } const AABox &GetBoundingBox() const { return m_boundingBox; } const int32 GetLoadedLODLevel() const { return m_loadedLODLevel; } // changed state const bool IsChanged() const { return (m_loadState != LoadState_Loaded); } const LoadState GetLoadState() const { return m_loadState; } void SetLoadState(LoadState loadState) { m_loadState = loadState; } // initialization void Create(int32 minChunkZ = 0, int32 maxChunkZ = 0); bool LoadFromStream(ByteStream *pStream, int32 maxLODLevel); bool SaveToStream(ByteStream *pStream) const; // load any lods to the specified level bool LoadLODs(ByteStream *pStream, int32 maxLODLevel); // unload any lods below the specified lod void UnloadLODs(int32 lodLevel); // chunks - everything here uses relative coordinates const int32 GetChunkCountZ() const { return m_chunkCountZ; } const int32 GetChunkCount() const { return m_chunkCount; } const int32 GetMinChunkZ() const { return m_minChunkZ; } const int32 GetMaxChunkZ() const { return m_maxChunkZ; } // chunks bool GetChunkAvailability(int32 chunkX, int32 chunkY, int32 chunkZ) const; const BlockWorldChunk *GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const; BlockWorldChunk *GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ); const BlockWorldChunk *SafeGetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const; BlockWorldChunk *SafeGetChunk(int32 chunkX, int32 chunkY, int32 chunkZ); BlockWorldChunk *CreateChunk(int32 chunkX, int32 chunkY, int32 chunkZ); void DeleteChunk(int32 chunkX, int32 chunkY, int32 chunkZ); // render groups pending meshing const int32 GetChunksPendingMeshing() const { return m_chunksPendingMeshing; } void AddChunkPendingMeshing() { m_chunksPendingMeshing++; } void RemoveChunkPendingMeshing() { m_chunksPendingMeshing--; } // update all lods that depend on a block void UpdateChunkLODLevels(BlockWorldChunk *pChunk, int32 lodLevel, int32 blockX, int32 blockY, int32 blockZ); // rebuild lods for a chunk void RebuildLODsForChunk(int32 chunkX, int32 chunkY, int32 chunkZ); // rebuild all lods for this section void RebuildLODs(int32 lodCount); // enumerate chunks template<typename CALLBACK_TYPE> void EnumerateChunks(CALLBACK_TYPE callback) const { for (int32 i = 0; i < m_chunkCount; i++) { if (m_ppChunks[i] != nullptr) callback(m_ppChunks[i]); } } template<typename CALLBACK_TYPE> void EnumerateChunks(CALLBACK_TYPE callback) { for (int32 i = 0; i < m_chunkCount; i++) { if (m_ppChunks[i] != nullptr) callback(m_ppChunks[i]); } } // remove empty chunks void RemoveEmptyChunks(); // add/remove entities, does not clean them up afterwards void AddEntity(Entity *pEntity); void MoveEntity(Entity *pEntity); void RemoveEntity(Entity *pEntity); private: // chunk availability void SetChunkAvailability(int32 chunkX, int32 chunkY, int32 chunkZ, bool availability); // chunk array initializers int32 GetChunkArrayIndex(int32 chunkX, int32 chunkY, int32 chunkZ) const; void InitializeChunkArray(int32 minChunkZ, int32 maxChunkZ); void ResizeChunkArray(int32 minChunkZ, int32 maxChunkZ); // internal load procedure bool InternalLoadLODs(ByteStream *pStream, int32 maxLODLevel); // info BlockWorld *m_pWorld; int32 m_sectionSize; int32 m_chunkSize; int32 m_sectionX; int32 m_sectionY; int32 m_lodLevels; int32 m_baseChunkX; int32 m_baseChunkY; // state AABox m_boundingBox; int32 m_loadedLODLevel; int32 m_chunksPendingMeshing; // chunk storage int32 m_minChunkZ; int32 m_maxChunkZ; int32 m_chunkCountZ; int32 m_chunkCount; BitSet32 m_chunkAvailability; BlockWorldChunk **m_ppChunks; // entities in section, only for lod0 MemArray<BlockWorldEntityReference> m_entities; // changed state LoadState m_loadState; }; <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUTexture.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUTexture.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUDevice.h" Log_SetChannel(D3D11GPUContext); static DWORD MapTextureFlagsToD3DBindFlags(uint32 textureFlags) { uint32 bindFlags = 0; if (textureFlags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) bindFlags |= D3D11_BIND_SHADER_RESOURCE; if (textureFlags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) bindFlags |= D3D11_BIND_RENDER_TARGET; if (textureFlags & GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) bindFlags |= D3D11_BIND_DEPTH_STENCIL; if (textureFlags & GPU_TEXTURE_FLAG_BIND_COMPUTE_WRITABLE) bindFlags |= D3D11_BIND_UNORDERED_ACCESS; return bindFlags; } static DWORD MapTextureFlagsToD3DMiscFlags(uint32 textureFlags) { uint32 miscFlags = 0; if (textureFlags & GPU_TEXTURE_FLAG_GENERATE_MIPS) miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; return miscFlags; } static void MapTextureFormatToViewFormat(DXGI_FORMAT *pCreationFormat, DXGI_FORMAT *pSRVFormat, DXGI_FORMAT *pRTVFormat, DXGI_FORMAT *pDSVFormat) { DXGI_FORMAT creationFormat = *pCreationFormat; // handle depth type mapping switch (creationFormat) { case DXGI_FORMAT_D16_UNORM: *pCreationFormat = DXGI_FORMAT_R16_TYPELESS; *pSRVFormat = DXGI_FORMAT_R16_UNORM; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D16_UNORM; break; case DXGI_FORMAT_D24_UNORM_S8_UINT: *pCreationFormat = DXGI_FORMAT_R24G8_TYPELESS; *pSRVFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; break; case DXGI_FORMAT_D32_FLOAT: *pCreationFormat = DXGI_FORMAT_R32_TYPELESS; *pSRVFormat = DXGI_FORMAT_R32_FLOAT; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D32_FLOAT; break; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: *pCreationFormat = DXGI_FORMAT_R32G8X24_TYPELESS; *pSRVFormat = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; *pRTVFormat = DXGI_FORMAT_UNKNOWN; *pDSVFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; break; default: *pCreationFormat = creationFormat; *pSRVFormat = creationFormat; *pRTVFormat = creationFormat; *pDSVFormat = DXGI_FORMAT_UNKNOWN; break; } } D3D11GPUTexture1D::D3D11GPUTexture1D(const GPU_TEXTURE1D_DESC *pDesc, ID3D11Texture1D *pD3DTexture, ID3D11Texture1D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTexture1D(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTexture1D::~D3D11GPUTexture1D() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTexture1D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage; } } void D3D11GPUTexture1D::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTexture1D *D3D11GPUDevice::CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE1D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = 1; D3DTextureDesc.Format = creationFormat; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags); // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture1D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture1D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1D: CreateTexture1D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture1D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE1D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture1D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1D: CreateTexture1D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = pTextureDesc->MipLevels; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1D: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1D: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTexture1D(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) { HRESULT hResult; D3D11GPUTexture1D *pD3DTexture = static_cast<D3D11GPUTexture1D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(count > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[Texture1D]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy(pDestination, reinterpret_cast<const byte *>(mappedSubResource.pData), Min(cbDestination, (uint32)mappedSubResource.RowPitch)); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) { D3D11GPUTexture1D *pD3DTexture = static_cast<D3D11GPUTexture1D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(count > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, cbSource, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTexture1DArray::D3D11GPUTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pDesc, ID3D11Texture1D *pD3DTexture, ID3D11Texture1D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTexture1DArray(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTexture1DArray::~D3D11GPUTexture1DArray() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTexture1DArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage * m_desc.ArraySize; } } void D3D11GPUTexture1DArray::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTexture1DArray *D3D11GPUDevice::CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE1D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = pTextureDesc->ArraySize; D3DTextureDesc.Format = creationFormat; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags); // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels * pTextureDesc->ArraySize; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture1D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture1D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1DArray: CreateTexture1D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture1D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE1D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture1D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1DArray: CreateTexture1D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; srvDesc.Texture1DArray.MostDetailedMip = 0; srvDesc.Texture1DArray.MipLevels = pTextureDesc->MipLevels; srvDesc.Texture1DArray.FirstArraySlice = 0; srvDesc.Texture1DArray.ArraySize = pTextureDesc->ArraySize; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1DArray: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture1DArray: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTexture1DArray(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { HRESULT hResult; D3D11GPUTexture1DArray *pD3DTexture = static_cast<D3D11GPUTexture1DArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(count > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth || arrayIndex >= pTexture->GetDesc()->ArraySize) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, arrayIndex, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[Texture1DArray]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy(pDestination, reinterpret_cast<const byte *>(mappedSubResource.pData), Min(cbDestination, (uint32)mappedSubResource.RowPitch)); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { D3D11GPUTexture1DArray *pD3DTexture = static_cast<D3D11GPUTexture1DArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(count > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth || arrayIndex >= pD3DTexture->GetDesc()->ArraySize) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, arrayIndex, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, cbSource, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTexture2D::D3D11GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTexture2D(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTexture2D::~D3D11GPUTexture2D() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTexture2D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage; } } void D3D11GPUTexture2D::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTexture2D *D3D11GPUDevice::CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE2D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = 1; D3DTextureDesc.Format = creationFormat; D3DTextureDesc.SampleDesc.Count = 1; D3DTextureDesc.SampleDesc.Quality = 0; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags); // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture2D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture2D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2D: CreateTexture2D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture2D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE2D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.SampleDesc.Count = D3DTextureDesc.SampleDesc.Count; D3DStagingTextureDesc.SampleDesc.Quality = D3DTextureDesc.SampleDesc.Quality; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2D: CreateTexture2D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = pTextureDesc->MipLevels; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2D: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2D: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTexture2D(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { HRESULT hResult; D3D11GPUTexture2D *pD3DTexture = static_cast<D3D11GPUTexture2D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[Texture2D]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy_stride(pDestination, destinationRowPitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.RowPitch, Min(mappedSubResource.RowPitch, destinationRowPitch), countY); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { D3D11GPUTexture2D *pD3DTexture = static_cast<D3D11GPUTexture2D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, sourceRowPitch, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTexture2DArray::D3D11GPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTexture2DArray(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTexture2DArray::~D3D11GPUTexture2DArray() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTexture2DArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage * m_desc.ArraySize; } } void D3D11GPUTexture2DArray::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTexture2DArray *D3D11GPUDevice::CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE2D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = pTextureDesc->ArraySize; D3DTextureDesc.Format = creationFormat; D3DTextureDesc.SampleDesc.Count = 1; D3DTextureDesc.SampleDesc.Quality = 0; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags); // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels * pTextureDesc->ArraySize; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture2D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture2D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2DArray: CreateTexture2D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture2D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE2D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.SampleDesc.Count = D3DTextureDesc.SampleDesc.Count; D3DStagingTextureDesc.SampleDesc.Quality = D3DTextureDesc.SampleDesc.Quality; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2DArray: CreateTexture2D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; srvDesc.Texture2DArray.MostDetailedMip = 0; srvDesc.Texture2DArray.MipLevels = pTextureDesc->MipLevels; srvDesc.Texture2DArray.FirstArraySlice = 0; srvDesc.Texture2DArray.ArraySize = pTextureDesc->ArraySize; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2DArray: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture2DArray: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTexture2DArray(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { HRESULT hResult; D3D11GPUTexture2DArray *pD3DTexture = static_cast<D3D11GPUTexture2DArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pTexture->GetDesc()->ArraySize) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, arrayIndex, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[Texture2DArray]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy_stride(pDestination, destinationRowPitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.RowPitch, Min(mappedSubResource.RowPitch, destinationRowPitch), countY); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { D3D11GPUTexture2DArray *pD3DTexture = static_cast<D3D11GPUTexture2DArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pD3DTexture->GetDesc()->ArraySize) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, arrayIndex, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, sourceRowPitch, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTexture3D::D3D11GPUTexture3D(const GPU_TEXTURE3D_DESC *pDesc, ID3D11Texture3D *pD3DTexture, ID3D11Texture3D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTexture3D(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTexture3D::~D3D11GPUTexture3D() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTexture3D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), Max(m_desc.Depth >> j, (uint32)1)); *gpuMemoryUsage = memoryUsage; } } void D3D11GPUTexture3D::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTexture3D *D3D11GPUDevice::CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */, const uint32 *pInitialDataSlicePitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE3D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.Depth = pTextureDesc->Depth; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.Format = creationFormat; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags); // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = pInitialDataSlicePitch[i]; } } // create texture ID3D11Texture3D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture3D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture3D: CreateTexture3D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture3D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE3D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.Depth = D3DTextureDesc.Depth; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture3D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture3D: CreateTexture3D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; srvDesc.Texture3D.MostDetailedMip = 0; srvDesc.Texture3D.MipLevels = pTextureDesc->MipLevels; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture3D: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTexture3D: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTexture3D(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { HRESULT hResult; D3D11GPUTexture3D *pD3DTexture = static_cast<D3D11GPUTexture3D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); uint32 mipDepth = Max(pD3DTexture->GetDesc()->Depth >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || (startZ + countZ) > mipDepth) return false; // check destination size if ((countZ * destinationSlicePitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, startZ, startX + countX, startY + countY, startZ + countZ }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[Texture3D]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line if (destinationRowPitch != mappedSubResource.RowPitch) { const byte *pSourcePointer = reinterpret_cast<const byte *>(mappedSubResource.pData); byte *pDestinationPointer = reinterpret_cast<byte *>(pDestination); for (uint32 i = 0; i < countZ; i++) { Y_memcpy_stride(pDestinationPointer, destinationRowPitch, pSourcePointer, mappedSubResource.RowPitch, Min(destinationRowPitch, mappedSubResource.RowPitch), countY); pSourcePointer += mappedSubResource.DepthPitch; pDestinationPointer += destinationSlicePitch; } } else { Y_memcpy_stride(pDestination, destinationSlicePitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.DepthPitch, Min(mappedSubResource.DepthPitch, destinationSlicePitch), countZ); } // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { D3D11GPUTexture3D *pD3DTexture = static_cast<D3D11GPUTexture3D *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); uint32 mipDepth = Max(pD3DTexture->GetDesc()->Depth >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || (startZ + countZ) > mipDepth) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, 0, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { startX, startY, startZ, startX + countX, startY + countY, startZ + countZ }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, sourceRowPitch, sourceSlicePitch); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTextureCube::D3D11GPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTextureCube(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTextureCube::~D3D11GPUTextureCube() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTextureCube::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage * CUBEMAP_FACE_COUNT; } } void D3D11GPUTextureCube::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTextureCube *D3D11GPUDevice::CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE2D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = CUBEMAP_FACE_COUNT; D3DTextureDesc.Format = creationFormat; D3DTextureDesc.SampleDesc.Count = 1; D3DTextureDesc.SampleDesc.Quality = 0; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags) | D3D11_RESOURCE_MISC_TEXTURECUBE; // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels * CUBEMAP_FACE_COUNT; pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture2D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture2D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCube: CreateTexture2D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture2D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE2D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.SampleDesc.Count = D3DTextureDesc.SampleDesc.Count; D3DStagingTextureDesc.SampleDesc.Quality = D3DTextureDesc.SampleDesc.Quality; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCube: CreateTexture2D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; srvDesc.TextureCube.MostDetailedMip = 0; srvDesc.TextureCube.MipLevels = pTextureDesc->MipLevels; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCube: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCube: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTextureCube(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { HRESULT hResult; D3D11GPUTextureCube *pD3DTexture = static_cast<D3D11GPUTextureCube *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || face >= CUBEMAP_FACE_COUNT) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, (uint32)face, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[TextureCube]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy_stride(pDestination, destinationRowPitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.RowPitch, Min(mappedSubResource.RowPitch, destinationRowPitch), countY); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { D3D11GPUTextureCube *pD3DTexture = static_cast<D3D11GPUTextureCube *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || face >= CUBE_FACE_COUNT) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, (uint32)face, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, sourceRowPitch, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUTextureCubeArray::D3D11GPUTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState) : GPUTextureCubeArray(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture), m_pD3DSRV(pD3DSRV), m_pD3DSamplerState(pD3DSamplerState) { } D3D11GPUTextureCubeArray::~D3D11GPUTextureCubeArray() { if (m_pD3DSamplerState != nullptr) m_pD3DSamplerState->Release(); if (m_pD3DSRV != nullptr) m_pD3DSRV->Release(); if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUTextureCubeArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage * (m_desc.ArraySize * CUBEMAP_FACE_COUNT); } } void D3D11GPUTextureCubeArray::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUTextureCubeArray *D3D11GPUDevice::CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && creationFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0 && (pTextureDesc->ArraySize % CUBEMAP_FACE_COUNT) == 0); // determine view formats DXGI_FORMAT srvFormat, rtvFormat, dsvFormat; MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); // fill in known fields D3D11_TEXTURE2D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.MipLevels = pTextureDesc->MipLevels; D3DTextureDesc.ArraySize = pTextureDesc->ArraySize; D3DTextureDesc.Format = creationFormat; D3DTextureDesc.SampleDesc.Count = 1; D3DTextureDesc.SampleDesc.Quality = 0; // determine usage if (pTextureDesc->Flags & (GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // set to default usage D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; } else if (pTextureDesc->Flags) { // otherwise immutable, ensure we have data DebugAssert(ppInitialData != nullptr); D3DTextureDesc.Usage = D3D11_USAGE_IMMUTABLE; } // bindflags D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.BindFlags = MapTextureFlagsToD3DBindFlags(pTextureDesc->Flags); D3DTextureDesc.MiscFlags = MapTextureFlagsToD3DMiscFlags(pTextureDesc->Flags) | D3D11_RESOURCE_MISC_TEXTURECUBE; // initial data D3D11_SUBRESOURCE_DATA *pD3DInitialData = nullptr; if (ppInitialData != nullptr) { uint32 nInitializers = pTextureDesc->MipLevels * (pTextureDesc->ArraySize * CUBEMAP_FACE_COUNT); pD3DInitialData = (D3D11_SUBRESOURCE_DATA *)alloca(sizeof(D3D11_SUBRESOURCE_DATA)* nInitializers); for (uint32 i = 0; i < nInitializers; i++) { pD3DInitialData[i].pSysMem = ppInitialData[i]; pD3DInitialData[i].SysMemPitch = pInitialDataPitch[i]; pD3DInitialData[i].SysMemSlicePitch = 0; } } // create texture ID3D11Texture2D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture2D(&D3DTextureDesc, pD3DInitialData, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCubeArray: CreateTexture2D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture2D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE2D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.SampleDesc.Count = D3DTextureDesc.SampleDesc.Count; D3DStagingTextureDesc.SampleDesc.Quality = D3DTextureDesc.SampleDesc.Quality; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCubeArray: CreateTexture2D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create shader resource view ID3D11ShaderResourceView *pD3DSRV = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(srvFormat != DXGI_FORMAT_UNKNOWN); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; srvDesc.TextureCubeArray.MostDetailedMip = 0; srvDesc.TextureCubeArray.MipLevels = pTextureDesc->MipLevels; srvDesc.TextureCubeArray.First2DArrayFace = 0; srvDesc.TextureCubeArray.NumCubes = pTextureDesc->ArraySize / CUBEMAP_FACE_COUNT; hResult = m_pD3DDevice->CreateShaderResourceView(pD3DTexture, &srvDesc, &pD3DSRV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCubeArray: CreateShaderResourceView failed with hResult %08X", hResult); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create sampler state ID3D11SamplerState *pD3DSamplerState = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { DebugAssert(pSamplerStateDesc != nullptr); if ((pD3DSamplerState = D3D11Helpers::CreateD3D11SamplerState(m_pD3DDevice, pSamplerStateDesc)) == nullptr) { Log_ErrorPrintf("D3D11GPUDevice::CreateTextureCubeArray: Failed to create sampler state for texture."); SAFE_RELEASE(pD3DSRV); SAFE_RELEASE(pD3DStagingTexture); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUTextureCubeArray(pTextureDesc, pD3DTexture, pD3DStagingTexture, pD3DSRV, pD3DSamplerState); } bool D3D11GPUContext::ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { HRESULT hResult; D3D11GPUTextureCubeArray *pD3DTexture = static_cast<D3D11GPUTextureCubeArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pTexture->GetDesc()->ArraySize || face >= CUBEMAP_FACE_COUNT) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), D3D11CalcSubresource(mipIndex, (arrayIndex * CUBEMAP_FACE_COUNT) + (uint32)face, pD3DTexture->GetDesc()->MipLevels), &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[TextureCubeArray]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy_stride(pDestination, destinationRowPitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.RowPitch, Min(mappedSubResource.RowPitch, destinationRowPitch), countY); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { D3D11GPUTextureCubeArray *pD3DTexture = static_cast<D3D11GPUTextureCubeArray *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pD3DTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pD3DTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pD3DTexture->GetDesc()->ArraySize || face >= CUBEMAP_FACE_COUNT) return false; // find subresource uint32 subResourceToUpdate = D3D11CalcSubresource(mipIndex, (arrayIndex * CUBEMAP_FACE_COUNT) + (uint32)face, pD3DTexture->GetDesc()->MipLevels); // invoke update D3D11_BOX destinationBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), subResourceToUpdate, &destinationBox, pSource, sourceRowPitch, 0); return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D11GPUDepthTexture::D3D11GPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture) : GPUDepthTexture(pDesc), m_pD3DTexture(pD3DTexture), m_pD3DStagingTexture(pD3DStagingTexture) { } D3D11GPUDepthTexture::~D3D11GPUDepthTexture() { if (m_pD3DStagingTexture != nullptr) m_pD3DStagingTexture->Release(); if (m_pD3DTexture != nullptr) m_pD3DTexture->Release(); } void D3D11GPUDepthTexture::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = PixelFormat_CalculateImageSize(m_desc.Format, m_desc.Width, m_desc.Height, 1); } void D3D11GPUDepthTexture::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DTexture, name); } GPUDepthTexture *D3D11GPUDevice::CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) { HRESULT hResult; // validate pixel formats. const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DXGI_FORMAT textureFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && textureFormat != DXGI_FORMAT_UNKNOWN); UNREFERENCED_PARAMETER(pPixelFormatInfo); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->Flags & GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER); // fill in known fields D3D11_TEXTURE2D_DESC D3DTextureDesc; D3DTextureDesc.Width = pTextureDesc->Width; D3DTextureDesc.Height = pTextureDesc->Height; D3DTextureDesc.MipLevels = 1; D3DTextureDesc.ArraySize = 1; D3DTextureDesc.Format = textureFormat; D3DTextureDesc.SampleDesc.Count = 1; D3DTextureDesc.SampleDesc.Quality = 0; D3DTextureDesc.Usage = D3D11_USAGE_DEFAULT; D3DTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; D3DTextureDesc.CPUAccessFlags = 0; D3DTextureDesc.MiscFlags = 0; // create texture ID3D11Texture2D *pD3DTexture; hResult = m_pD3DDevice->CreateTexture2D(&D3DTextureDesc, nullptr, &pD3DTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateDepthTexture: CreateTexture2D failed with hResult %08X", hResult); return false; } // create staging texture if readable texture requested ID3D11Texture2D *pD3DStagingTexture = nullptr; if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_READABLE) { D3D11_TEXTURE2D_DESC D3DStagingTextureDesc; D3DStagingTextureDesc.Width = D3DTextureDesc.Width; D3DStagingTextureDesc.Height = D3DTextureDesc.Height; D3DStagingTextureDesc.MipLevels = 1; D3DStagingTextureDesc.ArraySize = 1; D3DStagingTextureDesc.Format = D3DTextureDesc.Format; D3DStagingTextureDesc.SampleDesc.Count = D3DTextureDesc.SampleDesc.Count; D3DStagingTextureDesc.SampleDesc.Quality = D3DTextureDesc.SampleDesc.Quality; D3DStagingTextureDesc.Usage = D3D11_USAGE_STAGING; D3DStagingTextureDesc.BindFlags = 0; D3DStagingTextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; D3DStagingTextureDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&D3DStagingTextureDesc, nullptr, &pD3DStagingTexture); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateDepthTexture: CreateTexture2D failed for staging texture with hResult %08X", hResult); pD3DTexture->Release(); return false; } } // create class return new D3D11GPUDepthTexture(pTextureDesc, pD3DTexture, pD3DStagingTexture); } bool D3D11GPUContext::ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { HRESULT hResult; D3D11GPUDepthTexture *pD3DTexture = static_cast<D3D11GPUDepthTexture *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level if ((startX + countX) > pD3DTexture->GetDesc()->Width || (startY + countY) > pD3DTexture->GetDesc()->Height) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // copy the texture to the staging texture // if this is a higher mip level, or a non-full-copy, it'll only partially fill the staging texture, this is okay. D3D11_BOX sourceBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->CopySubresourceRegion(pD3DTexture->GetD3DStagingTexture(), 0, 0, 0, 0, pD3DTexture->GetD3DTexture(), 0, &sourceBox); // map the staging texture D3D11_MAPPED_SUBRESOURCE mappedSubResource; hResult = m_pD3DContext->Map(pD3DTexture->GetD3DStagingTexture(), 0, D3D11_MAP_READ, 0, &mappedSubResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadTexture[DepthTexture]: Mapping staging texture failed with hResult %08X", hResult); return false; } // copy line by line Y_memcpy_stride(pDestination, destinationRowPitch, reinterpret_cast<const byte *>(mappedSubResource.pData), mappedSubResource.RowPitch, Min(mappedSubResource.RowPitch, destinationRowPitch), countY); // unmap resource again m_pD3DContext->Unmap(pD3DTexture->GetD3DStagingTexture(), 0); return true; } bool D3D11GPUContext::WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { D3D11GPUDepthTexture *pD3DTexture = static_cast<D3D11GPUDepthTexture *>(pTexture); DebugAssert(pD3DTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pD3DTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level if ((startX + countX) > pD3DTexture->GetDesc()->Width || (startY + countY) > pD3DTexture->GetDesc()->Height) return false; // invoke update D3D11_BOX destinationBox = { startX, startY, 0, startX + countX, startY + countY, 1 }; m_pD3DContext->UpdateSubresource(pD3DTexture->GetD3DTexture(), 0, &destinationBox, pSource, sourceRowPitch, 0); return true; } D3D11GPURenderTargetView::D3D11GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, ID3D11RenderTargetView *pD3DRTV, ID3D11Resource *pD3DResource) : GPURenderTargetView(pTexture, pDesc), m_pD3DRTV(pD3DRTV), m_pD3DResource(pD3DResource) { } D3D11GPURenderTargetView::~D3D11GPURenderTargetView() { m_pD3DRTV->Release(); } void D3D11GPURenderTargetView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D11GPURenderTargetView::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DRTV, name); } GPURenderTargetView *D3D11GPUDevice::CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // we need to convert to d3d formats ID3D11Resource *pD3DResource; DXGI_FORMAT creationFormat, srvFormat, rtvFormat, dsvFormat; // fill in DSV structure D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: pD3DResource = static_cast<D3D11GPUTexture1D *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture1D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D; rtvDesc.Texture1D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: pD3DResource = static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY; rtvDesc.Texture1DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture1DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture1DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURE2D: pD3DResource = static_cast<D3D11GPUTexture2D *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: pD3DResource = static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURECUBE: pD3DResource = static_cast<D3D11GPUTextureCube *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTextureCube *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: pD3DResource = static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; rtvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; rtvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; rtvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: pD3DResource = static_cast<D3D11GPUDepthTexture *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUDepthTexture *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; break; default: Log_ErrorPrintf("D3D11GPUDevice::CreateRenderTargetView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } ID3D11RenderTargetView *pD3DRTV; HRESULT hResult = m_pD3DDevice->CreateRenderTargetView(pD3DResource, &rtvDesc, &pD3DRTV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateRenderTargetView: CreateRenderTargetView failed with hResult %08X", hResult); return nullptr; } return new D3D11GPURenderTargetView(pTexture, pDesc, pD3DRTV, pD3DResource); } D3D11GPUDepthStencilBufferView::D3D11GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, ID3D11DepthStencilView *pD3DDSV, ID3D11Resource *pD3DResource) : GPUDepthStencilBufferView(pTexture, pDesc), m_pD3DDSV(pD3DDSV), m_pD3DResource(pD3DResource) { } D3D11GPUDepthStencilBufferView::~D3D11GPUDepthStencilBufferView() { m_pD3DDSV->Release(); } void D3D11GPUDepthStencilBufferView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D11GPUDepthStencilBufferView::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DDSV, name); } GPUDepthStencilBufferView *D3D11GPUDevice::CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // we need to convert to d3d formats ID3D11Resource *pD3DResource; DXGI_FORMAT creationFormat, srvFormat, rtvFormat, dsvFormat; // fill in DSV structure D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: pD3DResource = static_cast<D3D11GPUTexture1D *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture1D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1D; dsvDesc.Flags = 0; dsvDesc.Texture1D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: pD3DResource = static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture1DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture1DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture1DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture1DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURE2D: pD3DResource = static_cast<D3D11GPUTexture2D *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2D *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = 0; dsvDesc.Texture2D.MipSlice = pDesc->MipLevel; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: pD3DResource = static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTexture2DArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURECUBE: pD3DResource = static_cast<D3D11GPUTextureCube *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTextureCube *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: pD3DResource = static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUTextureCubeArray *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Flags = 0; dsvDesc.Texture2DArray.MipSlice = pDesc->MipLevel; dsvDesc.Texture2DArray.FirstArraySlice = pDesc->FirstLayerIndex; dsvDesc.Texture2DArray.ArraySize = pDesc->NumLayers; break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: pD3DResource = static_cast<D3D11GPUDepthTexture *>(pTexture)->GetD3DTexture(); creationFormat = D3D11TypeConversion::PixelFormatToDXGIFormat(static_cast<D3D11GPUDepthTexture *>(pTexture)->GetDesc()->Format); MapTextureFormatToViewFormat(&creationFormat, &srvFormat, &rtvFormat, &dsvFormat); dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = 0; dsvDesc.Texture2D.MipSlice = 0; break; default: Log_ErrorPrintf("D3D11GPUDevice::CreateDepthBufferView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } ID3D11DepthStencilView *pD3DDSV; HRESULT hResult = m_pD3DDevice->CreateDepthStencilView(pD3DResource, &dsvDesc, &pD3DDSV); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateDepthBufferView: CreateDepthStencilView failed with hResult %08X", hResult); return nullptr; } return new D3D11GPUDepthStencilBufferView(pTexture, pDesc, pD3DDSV, pD3DResource); } D3D11GPUComputeView::D3D11GPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc, ID3D11UnorderedAccessView *pD3DUAV, ID3D11Resource *pD3DResource) : GPUComputeView(pResource, pDesc), m_pD3DUAV(pD3DUAV), m_pD3DResource(pD3DResource) { } D3D11GPUComputeView::~D3D11GPUComputeView() { m_pD3DUAV->Release(); } void D3D11GPUComputeView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void D3D11GPUComputeView::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DUAV, name); } GPUComputeView *D3D11GPUDevice::CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { Panic("Unimplemented"); return nullptr; } <file_sep>/Editor/Source/Editor/EditorBlockVolumeRenderProxy.h #pragma once #include "Editor/Common.h" #include "Engine/BlockMeshVolume.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/RendererTypes.h" class BlockPalette; class BlockMeshVertexFactory; class EditorTemporaryBlockMeshEntity; class EditorBlockVolumeRenderProxy : public RenderProxy { public: EditorBlockVolumeRenderProxy(uint32 entityId); ~EditorBlockVolumeRenderProxy(); void BuildMesh(const BlockMeshVolume *pVolume, bool useAmbientOcclusion); void ClearMesh(); void SetTransform(const float4x4 &newLocalToWorldMatrix); void SetShadowFlags(uint32 shadowFlags); void SetTintColor(bool enabled, uint32 color = 0); void SetVisibility(bool visible); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual bool CreateDeviceResources() const override; protected: // batch info struct RenderBatch { uint32 MaterialIndex; uint32 StartIndex; uint32 IndexCount; bool DrawShadows; RenderBatch(uint32 materialIndex, uint32 startIndex, uint32 indexCount, bool drawShadows) : MaterialIndex(materialIndex), StartIndex(startIndex), IndexCount(indexCount), DrawShadows(drawShadows) {} }; // maintain a reference to the block list mutable const BlockPalette *m_pPalette; bool m_visibility; float4x4 m_localToWorldMatrix; uint32 m_shadowFlags; bool m_tintEnabled; uint32 m_tintColor; // bounding box in local space AABox m_localBoundingBox; Sphere m_localBoundingSphere; // we don't keep a copy of the triangles in memory, we store them only on the gpu VertexBufferBindingArray m_vertexBuffers; uint32 m_vertexFactoryFlags; GPUBuffer *m_pIndexBuffer; GPU_INDEX_FORMAT m_indexFormat; MemArray<RenderBatch> m_batches; }; <file_sep>/Engine/Source/Renderer/Shaders/FullBrightShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/FullBrightShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(FullBrightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(FullBrightShader) END_SHADER_COMPONENT_PARAMETERS() bool FullBrightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; return true; } bool FullBrightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/FullBrightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/FullBrightShader.hlsl", "PSMain"); return true; } <file_sep>/Engine/Source/GameFramework/SpriteEntity.h #include "Engine/Entity.h" class SpriteEntity : public Entity { DECLARE_ENTITY_TYPEINFO(SpriteEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(SpriteEntity); public: SpriteEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~SpriteEntity(); }; <file_sep>/Engine/Source/GameFramework/PrecompiledHeader.h #pragma once #include "GameFramework/Common.h" <file_sep>/Engine/Source/Engine/CommandQueue.h #pragma once #include "Engine/Common.h" class CommandQueue { public: // 1MiB default queue size static const uint32 DEFAULT_COMMAND_QUEUE_SIZE = 1048576; private: struct CommandBase { virtual ~CommandBase() {} virtual void Execute() = 0; }; template<class T> struct CommandLambdaTrampoline { T m_callback; CommandLambdaTrampoline(const T &callback) : m_callback(callback) {} CommandLambdaTrampoline(T &&callback) : m_callback(std::move(callback)) {} virtual ~CommandLambdaTrampoline() {} virtual void Execute() { m_callback(); } }; public: CommandQueue(); ~CommandQueue(); // Initialize the command queue bool Initialize(uint32 commandQueueSize = DEFAULT_COMMAND_QUEUE_SIZE, uint32 workerThreadCount = 1); // Initialize the command queue using a shared thread pool bool Initialize(ThreadPool *pThreadPool, uint32 commandQueueSize = DEFAULT_COMMAND_QUEUE_SIZE, bool yieldToOtherJobs = false); // Wait until all workers are finished, and then end the threads. void ExitWorkers(); // Worker thread info const Thread *GetWorkerThread(uint32 idx) const { return m_workerThreads[idx]; } Thread::ThreadIdType GetWorkerThreadID(uint32 idx) const { return m_workerThreads[idx]->GetThreadId(); } uint32 GetWorkerThreadCount() const { return m_workerThreads.GetSize(); } // Pausing/resuming of thread void PauseWorkers(); void ResumeWorkers(); // Queuing of commands void QueueCommand(CommandBase *pCommand, uint32 commandSize); // Wrapper to assist with queueing lambda callbacks template<class T> void QueueLambdaCommand(const T &lambda) { if (m_commandQueueSize == 0) { lambda(); return; } LockQueueForNewCommand(); CommandLambdaTrampoline<T> *trampoline = (CommandLambdaTrampoline<T> *)FifoAllocateCommand(sizeof(CommandLambdaTrampoline<T>), false); new (trampoline)CommandLambdaTrampoline<T>(lambda); UnlockQueueForNewCommand(); } // Queue lambda command using move semantics template<class T> void QueueLambdaCommand(T &&lambda) { if (m_commandQueueSize == 0) { lambda(); return; } LockQueueForNewCommand(); CommandLambdaTrampoline<T> *trampoline = (CommandLambdaTrampoline<T> *)FifoAllocateCommand(sizeof(CommandLambdaTrampoline<T>), false); new (trampoline) CommandLambdaTrampoline<T>(std::move(lambda)); UnlockQueueForNewCommand(); } // blocking variants void QueueBlockingCommand(CommandBase *pCommand, uint32 commandSize); template<class T> void QueueBlockingLambdaCommand(const T &lambda) { if (m_commandQueueSize == 0 || m_workerThreads.IsEmpty()) { lambda(); return; } // currently blocking events are only supported coming from the main thread DebugAssert(Thread::GetCurrentThreadId() == m_creatorThreadID); LockQueueForNewCommand(); CommandLambdaTrampoline<T> *trampoline = (CommandLambdaTrampoline<T> *)FifoAllocateCommand(sizeof(CommandLambdaTrampoline<T>), true); new (trampoline)CommandLambdaTrampoline<T>(lambda); UnlockQueueForNewCommand(); // block m_barrier.Wait(); } // when not using a render thread, executes any pending commands, and blocks until the queue is empty // returns true if a command was executed, false if the queue was empty bool ExecuteQueuedCommands(); private: // worker thread class class WorkerThread : public Thread { public: WorkerThread(CommandQueue *pParent); protected: virtual int ThreadEntryPoint() override; CommandQueue *m_this; }; // thread pool task class class ThreadPoolTask : public ThreadPoolWorkItem { public: ThreadPoolTask(CommandQueue *pParent); bool IsActive() const { return m_active; } void SetActive() { m_active = true; } protected: virtual int32 ProcessWork() override; CommandQueue *m_this; bool m_active; }; // so the tasks can call our internal methods friend WorkerThread; friend ThreadPoolTask; // fifo queue entry struct FifoQueueEntryHeader { CommandBase *pCommand; uint32 Size; bool BlockingEvent; }; // allocate the queue void AllocateQueue(uint32 size); // lock the queue void LockQueueForNewCommand(); // unlock the queue, call this variant if no additional commands were added void UnlockQueueForNewCommand(); // allocate bytes in the queue, assumes that the queue lock is held void *FifoAllocateCommand(uint32 size, bool blockingEvent); // fifo is empty? bool FifoIsEmpty() const; // retreives the first command off the fifo, but does not destroy it yet FifoQueueEntryHeader *FifoGetNextCommand(); // release a fifo command void FifoReleaseCommand(FifoQueueEntryHeader *commandHdr); // creator thread Thread::ThreadIdType m_creatorThreadID; // worker thread PODArray<WorkerThread *> m_workerThreads; bool m_workerThreadExitFlag; // thread pool PODArray<ThreadPoolTask *> m_threadPoolTasks; ThreadPool *m_pThreadPool; volatile uint32 m_activeThreadPoolTasks; bool m_threadPoolYieldToOtherJobs; // fifo members PODArray<FifoQueueEntryHeader *> m_commandQueue; RecursiveMutex m_queueLock; volatile uint32 m_activeWorkerThreads; uint32 m_commandQueueSize; // events ConditionVariable m_conditionVariable; Barrier m_barrier; }; <file_sep>/DemoGame/Source/DemoGame/DemoCamera.h #pragma once #include "Engine/Camera.h" class World; class DemoCamera : public Camera { public: DemoCamera(); ~DemoCamera(); // Moved flag const bool IsMoved() const { return m_moved; } // Move the camera in the specified direction. void Move(const float3 &direction, float distance); // Pitch/yaw/roll the camera. void ModPitch(float Amount); void ModYaw(float Amount); void ModRoll(float Amount); // Rotate the camera around a specified axis and angle. void Rotate(const float3 &axis, float angle); // Rotate using the specified quaternion. void Rotate(const Quaternion &rotation); // time update void Update(const float &dt); // clip mode const World *GetWorld() const { return m_pWorld; } void SetWorld(const World *pWorld) { m_pWorld = pWorld; } float GetCameraSpeed() const { return m_fCameraSpeed; } void SetCameraSpeed(float speed) { m_fCameraSpeed = speed; } bool GetClippingEnabled() const { return m_clippingEnabled; } void SetClippingEnabled(bool enabled) { m_clippingEnabled = enabled; } // event handler bool HandleSDLEvent(const union SDL_Event *pEvent); protected: bool m_moved; bool m_clippingEnabled; float m_fCameraSpeed; const World *m_pWorld; // key states float3 m_moveDirection; bool m_turbo; }; <file_sep>/Editor/Source/Editor/EditorLightSimulator.h #pragma once #include "Editor/Common.h" class RenderWorld; class SpriteRenderProxy; class DirectionalLightRenderProxy; class PointLightRenderProxy; class EditorLightSimulator { enum LightType { LightType_Directional, LightType_Point, LightType_Spot, LightType_Count, }; public: EditorLightSimulator(uint32 entityID, RenderWorld *pRenderWorld); ~EditorLightSimulator(); // light type LightType GetLightType() const { return m_lightType; } void SetLightType(LightType type) { m_lightType = type; UpdateProxies(); UpdateIndicator(); } // indicator options const bool GetShowIndicator() const { return m_showIndicator; } void SetShowIndicator(bool enabled) { m_showIndicator = enabled; UpdateIndicator(); } // all light parameters const float3 &GetLightColor() const { return m_color; } const float GetLightBrightness() const { return m_brightness; } const bool GetCastShadows() const { return m_castShadows; } void SetLightColor(const float3 &color) { m_color = color; UpdateProxies(); } void SetLightBrightness(float brightness) { m_brightness = brightness; UpdateProxies(); } void SetCastShadows(bool castShadows) { m_castShadows = castShadows; UpdateProxies(); } // directional light parameters const float3 &GetDirectionalLightDirection() const { return m_directionalLightDirection; } const Quaternion &GetDirectionalLightRotation() const { return m_directionalLightRotation; } void SetDirectionalLightDirection(const float3 &direction) { m_directionalLightDirection = direction; m_directionalLightRotation = Quaternion::FromTwoVectors(float3::NegativeUnitZ, direction); UpdateProxies(); UpdateIndicator(); } void SetDirectionalLightRotation(const Quaternion &rotation) { m_directionalLightRotation = rotation; m_directionalLightDirection = rotation * float3::NegativeUnitZ; UpdateProxies(); UpdateIndicator(); } // point light parameters const float3 &GetPointLightLocation() const { return m_pointLightLocation; } const float GetPointLightRange() const { return m_pointLightRange; } const float GetPointLightFalloff() const { return m_pointLightFalloff; } void SetPointLightLocation(const float3 &location) { m_pointLightLocation = location; UpdateProxies(); UpdateIndicator(); } void SetPointLightRange(float range) { m_pointLightRange = range; UpdateProxies(); UpdateIndicator(); } void SetPointLightFalloff(float falloff) { m_pointLightFalloff = falloff; UpdateProxies(); } // manipulate from mouse movement void ManipulateFromMouseMovement(const int2 &mousePositionDelta); private: // rebuild the indicator parameters void UpdateIndicator(); // rebuild the light parameters void UpdateProxies(); // current type LightType m_lightType; // world we're attached to RenderWorld *m_pRenderWorld; // sprite for rendering indicator bool m_showIndicator; SpriteRenderProxy *m_pIndicatorRenderProxy; // for all float3 m_color; float m_brightness; bool m_castShadows; // for directional + sun float3 m_directionalLightDirection; Quaternion m_directionalLightRotation; float m_directionalLightAmbientFactor; DirectionalLightRenderProxy *m_pDirectionalLightRenderProxy; // for point float3 m_pointLightLocation; float m_pointLightRange; float m_pointLightFalloff; PointLightRenderProxy *m_pPointLightRenderProxy; }; <file_sep>/Engine/Source/Renderer/ImGuiBridge.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ImGuiBridge.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Shaders/OverlayShader.h" #include "Engine/SDLHeaders.h" Log_SetChannel(ImGuiBridge); static GPUBuffer *s_pVertexBuffer = nullptr; static GPUBuffer *s_pIndexBuffer = nullptr; static uint32 s_vertexBufferSize = 0; static uint32 s_indexBufferSize = 0; static void RenderDrawListsCallback(ImDrawData *pDrawData) { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); #if 1 // check buffer size if ((uint32)pDrawData->TotalVtxCount > s_vertexBufferSize) { uint32 newVertexCount = Max((s_vertexBufferSize != 0) ? (s_vertexBufferSize * 2) : 1024, (uint32)pDrawData->TotalVtxCount); Log_PerfPrintf("Reallocating ImGui vertex buffer, new count = %u (%s)", newVertexCount, StringConverter::SizeToHumanReadableString(newVertexCount * sizeof(ImDrawVert)).GetCharArray()); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, newVertexCount * sizeof(ImDrawVert)); if (g_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_ES3) bufferDesc.Flags |= GPU_BUFFER_FLAG_MAPPABLE; else bufferDesc.Flags |= GPU_BUFFER_FLAG_WRITABLE; GPUBuffer *pNewVertexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, nullptr); if (pNewVertexBuffer == nullptr) { Log_ErrorPrint("Failed to allocate ImGui vertex buffer."); return; } if (s_pVertexBuffer != nullptr) s_pVertexBuffer->Release(); s_pVertexBuffer = pNewVertexBuffer; s_vertexBufferSize = newVertexCount; } if ((uint32)pDrawData->TotalIdxCount > s_indexBufferSize) { uint32 newIndexCount = Max((s_indexBufferSize != 0) ? (s_indexBufferSize * 2) : 1024, (uint32)pDrawData->TotalIdxCount); Log_PerfPrintf("Reallocating ImGui index buffer, new count = %u (%s)", newIndexCount, StringConverter::SizeToHumanReadableString(newIndexCount * sizeof(ImDrawIdx)).GetCharArray()); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, newIndexCount * sizeof(ImDrawIdx)); if (g_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_ES3) bufferDesc.Flags |= GPU_BUFFER_FLAG_MAPPABLE; else bufferDesc.Flags |= GPU_BUFFER_FLAG_WRITABLE; GPUBuffer *pNewIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, nullptr); if (pNewIndexBuffer == nullptr) { Log_ErrorPrint("Failed to allocate ImGui index buffer."); return; } if (s_pIndexBuffer != nullptr) s_pIndexBuffer->Release(); s_pIndexBuffer = pNewIndexBuffer; s_indexBufferSize = newIndexCount; } // write to buffers if (g_pRenderer->GetFeatureLevel() >= RENDERER_FEATURE_LEVEL_ES3) { ImDrawVert *pMappedVertexBuffer; if (!pGPUContext->MapBuffer(s_pVertexBuffer, GPU_MAP_TYPE_WRITE_DISCARD, reinterpret_cast<void **>(&pMappedVertexBuffer))) { Log_ErrorPrint("Failed to map ImGui vertex buffer"); return; } ImDrawIdx *pMappedIndexBuffer; if (!pGPUContext->MapBuffer(s_pIndexBuffer, GPU_MAP_TYPE_WRITE_DISCARD, reinterpret_cast<void **>(&pMappedIndexBuffer))) { pGPUContext->Unmapbuffer(s_pVertexBuffer, pMappedVertexBuffer); Log_ErrorPrint("Failed to map ImGui index buffer"); return; } // copy vertices in ImDrawVert *pCurrentVertex = pMappedVertexBuffer; ImDrawIdx *pCurrentIndex = pMappedIndexBuffer; for (int i = 0; i < pDrawData->CmdListsCount; i++) { Y_memcpy(pCurrentVertex, pDrawData->CmdLists[i]->VtxBuffer.Data, pDrawData->CmdLists[i]->VtxBuffer.size() * sizeof(ImDrawVert)); Y_memcpy(pCurrentIndex, pDrawData->CmdLists[i]->IdxBuffer.Data, pDrawData->CmdLists[i]->IdxBuffer.size() * sizeof(ImDrawIdx)); pCurrentVertex += pDrawData->CmdLists[i]->VtxBuffer.size(); pCurrentIndex += pDrawData->CmdLists[i]->IdxBuffer.size(); } // unmap again pGPUContext->Unmapbuffer(s_pIndexBuffer, pMappedIndexBuffer); pGPUContext->Unmapbuffer(s_pVertexBuffer, pMappedVertexBuffer); } else { // annoyingly, ES2 doesn't have the ability to map buffers uint32 vertexBufferOffset = 0; uint32 indexBufferOffset = 0; for (int i = 0; i < pDrawData->CmdListsCount; i++) { pGPUContext->WriteBuffer(s_pVertexBuffer, pDrawData->CmdLists[i]->VtxBuffer.Data, vertexBufferOffset, pDrawData->CmdLists[i]->VtxBuffer.size() * sizeof(ImDrawVert)); pGPUContext->WriteBuffer(s_pIndexBuffer, pDrawData->CmdLists[i]->IdxBuffer.Data, indexBufferOffset, pDrawData->CmdLists[i]->IdxBuffer.size() * sizeof(ImDrawIdx)); vertexBufferOffset += pDrawData->CmdLists[i]->VtxBuffer.size() * sizeof(ImDrawVert); indexBufferOffset += pDrawData->CmdLists[i]->IdxBuffer.size() * sizeof(ImDrawIdx); } } // set up device pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE, false, false, true)); pGPUContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending()); // load shader ShaderProgram *pShaderProgram = g_pRenderer->GetFixedResources()->GetOverlayShaderTexturedScreen(); pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // set buffers pGPUContext->SetVertexBuffer(0, s_pVertexBuffer, 0, sizeof(ImDrawVert)); pGPUContext->SetIndexBuffer(s_pIndexBuffer, GPU_INDEX_FORMAT_UINT16, 0); // draw commands unsigned int baseVertex = 0; unsigned int baseIndex = 0; bool adjustBufferPointers = !(g_pRenderer->GetCapabilities().SupportsDrawBaseVertex); for (int i = 0; i < pDrawData->CmdListsCount; i++) { ImDrawList *pCmdList = pDrawData->CmdLists[i]; unsigned int firstIndex = 0; for (int j = 0; j < pCmdList->CmdBuffer.size(); j++) { const ImDrawCmd *pCmd = &pCmdList->CmdBuffer[j]; if (pCmd->UserCallback != nullptr) { pCmd->UserCallback(pCmdList, pCmd); continue; } // set up clip rect RENDERER_SCISSOR_RECT scissorRect((uint32)pCmd->ClipRect.x, (uint32)pCmd->ClipRect.y, (uint32)pCmd->ClipRect.z, (uint32)pCmd->ClipRect.w); pGPUContext->SetScissorRect(&scissorRect); // bind texture OverlayShader::SetTexture(pGPUContext, pShaderProgram, reinterpret_cast<GPUTexture2D *>(pCmd->TextureId)); // adjust buffer pointer if (adjustBufferPointers && baseVertex > 0) { pGPUContext->SetVertexBuffer(0, s_pVertexBuffer, sizeof(ImDrawVert) * baseVertex, sizeof(ImDrawVert)); pGPUContext->SetIndexBuffer(s_pIndexBuffer, GPU_INDEX_FORMAT_UINT16, sizeof(ImDrawIdx) * baseIndex); pGPUContext->DrawIndexed(firstIndex, pCmd->ElemCount, 0); } else { pGPUContext->DrawIndexed(baseIndex + firstIndex, pCmd->ElemCount, baseVertex); } // update pointers baseIndex += pCmd->ElemCount; } baseVertex += pCmdList->VtxBuffer.size(); } // clear bindings pGPUContext->ClearState(false, true, false, false); #else // set up device pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE, false, false, true)); pGPUContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending()); // load shader ShaderProgram *pShaderProgram = g_pRenderer->GetFixedResources()->GetOverlayShaderTexturedScreen(); pGPUContext->SetInputLayout(g_pRenderer->GetFixedResources()->GetOverlayInputLayoutScreen()); pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pDrawData->DeIndexAllBuffers(); // draw commands for (int i = 0; i < pDrawData->CmdListsCount; i++) { ImDrawList *pCmdList = pDrawData->CmdLists[i]; unsigned int startVertex = 0; for (int j = 0; j < pCmdList->CmdBuffer.size(); j++) { const ImDrawCmd *pCmd = &pCmdList->CmdBuffer[j]; if (pCmd->UserCallback != nullptr) { pCmd->UserCallback(pCmdList, pCmd); continue; } // set up clip rect RENDERER_SCISSOR_RECT scissorRect((uint32)pCmd->ClipRect.x, (uint32)pCmd->ClipRect.y, (uint32)pCmd->ClipRect.z, (uint32)pCmd->ClipRect.w); pGPUContext->SetScissorRect(&scissorRect); // bind texture OverlayShader::SetTexture(pGPUContext, pShaderProgram, reinterpret_cast<GPUTexture2D *>(pCmd->TextureId)); // this matches our overlay vertex format so we can just chuck it straight through.. actually would be an optimization to avoid it though pGPUContext->DrawUserPointer(&pCmdList->VtxBuffer[startVertex], sizeof(ImDrawVert), pCmd->ElemCount); startVertex += pCmd->ElemCount; } } #endif } bool ImGui::InitializeBridge() { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); GPUOutputBuffer *pOutputBuffer = pGPUContext->GetOutputBuffer(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = (float)pOutputBuffer->GetWidth(); io.DisplaySize.y = (float)pOutputBuffer->GetHeight(); io.DeltaTime = 0.0f; io.RenderDrawListsFn = RenderDrawListsCallback; io.IniFilename = nullptr; io.LogFilename = nullptr; // initialize rendering font { // get font pixels const void *pFontPixels; int fontWidth, fontHeight; uint32 pitch; io.Fonts->GetTexDataAsRGBA32((unsigned char **)&pFontPixels, &fontWidth, &fontHeight); pitch = PixelFormat_CalculateRowPitch(PIXEL_FORMAT_R8G8B8A8_UNORM, fontWidth); // Create the font as a GPU texture GPU_TEXTURE2D_DESC textureDesc(fontWidth, fontHeight, PIXEL_FORMAT_R8G8B8A8_UNORM, GPU_TEXTURE_FLAG_SHADER_BINDABLE, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_NEVER); GPUTexture2D *pFontTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, &pFontPixels, &pitch); if (pFontTexture == nullptr) { Log_ErrorPrintf("ImGui::InitializeBridge: Failed to create font texture."); return false; } io.Fonts->TexID = pFontTexture; } // initialize keyboard map { io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X; io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y; io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z; } // done return true; } void ImGui::SetViewportDimensions(uint32 width, uint32 height) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = (float)width; io.DisplaySize.y = (float)height; } void ImGui::NewFrame(float deltaTime) { ImGuiIO& io = ImGui::GetIO(); // update delta time io.DeltaTime = deltaTime; // update keyboard modifiers SDL_Keymod currentModifiers = SDL_GetModState(); io.KeyAlt = (currentModifiers & (KMOD_LALT | KMOD_RALT)) != 0; io.KeyCtrl = (currentModifiers & (KMOD_LCTRL | KMOD_RCTRL)) != 0; io.KeyShift = (currentModifiers & (KMOD_LSHIFT | KMOD_RSHIFT)) != 0; // fall through ImGui::NewFrame(); } bool ImGui::HandleSDLEvent(const SDL_Event *pEvent, bool forceCapture /* = false */) { ImGuiIO& io = ImGui::GetIO(); // keyboard events if (io.WantCaptureKeyboard || forceCapture) { switch (pEvent->type) { case SDL_KEYDOWN: case SDL_KEYUP: { if (pEvent->key.keysym.scancode < countof(io.KeysDown)) io.KeysDown[pEvent->key.keysym.scancode] = (pEvent->type == SDL_KEYDOWN); return true; } case SDL_TEXTINPUT: { // todo: utf-8 to utf-16 size_t length = Y_strlen(pEvent->text.text); for (uint32 i = 0; i < length; i++) io.AddInputCharacter((ImWchar)pEvent->text.text[i]); return true; } } } // mouse events if (io.WantCaptureMouse || forceCapture) { switch (pEvent->type) { case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { static const uint32 buttonMapping[5] = { 0, 0, 2, 1, 3 }; if (pEvent->button.button < countof(buttonMapping)) io.MouseDown[buttonMapping[pEvent->button.button]] = (pEvent->type == SDL_MOUSEBUTTONDOWN); return true; } case SDL_MOUSEMOTION: io.MousePos.x = (float)pEvent->motion.x; io.MousePos.y = (float)pEvent->motion.y; return true; case SDL_MOUSEWHEEL: io.MouseWheel = (float)pEvent->wheel.y; return true; } } return false; } void ImGui::FreeResources() { // release font ImGuiIO& io = ImGui::GetIO(); if (io.Fonts->TexID != nullptr) { GPUTexture2D *pTexture = reinterpret_cast<GPUTexture2D *>(io.Fonts->TexID); pTexture->Release(); io.Fonts->TexID = nullptr; } } <file_sep>/Engine/Source/Renderer/Shaders/TextureBlitShader.h #pragma once #include "Renderer/ShaderComponent.h" class GPUResource; class ShaderProgram; class TextureBlitShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(TextureBlitShader, ShaderComponent); public: enum FLAGS { USE_TEXTURE_LOD = (1 << 0), }; public: TextureBlitShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture *pSourceTexture, GPUSamplerState *pSamplerState, uint32 sourceLevel); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/Renderer/VertexFactoryTypeInfo.h #pragma once #include "Renderer/ShaderComponentTypeInfo.h" #include "Renderer/RendererTypes.h" class VertexFactory; class VertexFactoryTypeInfo : public ShaderComponentTypeInfo { public: typedef uint32(*GetVertexElementsDescFunction)(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); public: VertexFactoryTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, IsValidPermutationFunction fpIsValidPermutation, FillShaderCompilerParametersFunction fpFillShaderCompilerParameters, const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBindings, GetVertexElementsDescFunction fpGetVertexElementsDesc); ~VertexFactoryTypeInfo(); uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) const { return m_fpGetVertexElementsDesc(platform, featureLevel, flags, pElementsDesc); } protected: GetVertexElementsDescFunction m_fpGetVertexElementsDesc; }; #define DECLARE_VERTEX_FACTORY_TYPE_INFO(Type, ParentType) \ private: \ static VertexFactoryTypeInfo s_TypeInfo; \ static const SHADER_COMPONENT_PARAMETER_BINDING s_parameterBindings[]; \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const VertexFactoryTypeInfo *StaticTypeInfo() { return &s_TypeInfo; } \ static VertexFactoryTypeInfo *StaticMutableTypeInfo() { return &s_TypeInfo; } #define DECLARE_VERTEX_FACTORY_FACTORY(Type) \ public: \ static VertexFactory *CreateInstance(uint32 Flags, GPUVertexArray *pVertexArray) { return new Type(Flags, pVertexArray); } #define DEFINE_VERTEX_FACTORY_TYPE_INFO(Type) \ VertexFactoryTypeInfo Type::s_TypeInfo = VertexFactoryTypeInfo( #Type , OBJECT_TYPEINFO(BaseClass), \ &Type::IsValidPermutation, &Type::FillShaderCompilerParameters, \ Type::s_parameterBindings, \ &Type::GetVertexElementsDesc); #define VERTEX_FACTORY_TYPE_INFO(Type) Type::StaticTypeInfo() #define VERTEX_FACTORY_TYPE_INFO_PTR(Ptr) Ptr->StaticTypeInfo() #define VERTEX_FACTORY_MUTABLE_TYPE_INFO(Type) Type::StaticMutableTypeInfo() #define VERTEX_FACTORY_MUTABLE_TYPE_INFO_PTR(Type) Type->StaticMutableTypeInfo() <file_sep>/Engine/Source/Engine/Engine.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" #include "Engine/Font.h" #include "Engine/EngineCVars.h" #include "Renderer/Renderer.h" #include "YBaseLib/CPUID.h" Log_SetChannel(Engine); // instance of engine is created in file static Engine s_Engine; Engine *g_pEngine = &s_Engine; Engine::Engine() { // set to defaults, replace with config at some point m_strDefaultTexture2DName = "textures/engine/default"; m_strDefaultTexture2DArrayName = "textures/engine/default_array"; m_strDefaultTextureCubeName = "textures/engine/default_cube"; m_strDefaultMaterialShaderName = "materials/engine/default"; m_strDefaultMaterialName = "materials/engine/default"; m_strDefaultFontName = "resources/engine/fonts/small_font"; m_strDefaultStaticMeshName = "models/engine/unit_cube"; m_strDefaultBlockMeshName = "models/engine/single_block"; m_strDefaultSkeletalMeshName = "models/engine/default_skeletal_mesh"; m_strSpriteMaterialShaderName = "shaders/engine/simple_sprite"; m_strRendererDebugFontName = "resources/engine/fonts/fixedsyse_16"; // default resources m_pDefaultFont = nullptr; // fixed resources m_pWorkerThreadPool = nullptr; } Engine::~Engine() { DebugAssert(m_pWorkerThreadPool == nullptr); } const String &Engine::GetDefaultTextureName(TEXTURE_TYPE TextureType) const { switch (TextureType) { case TEXTURE_TYPE_2D: return GetDefaultTexture2DName(); case TEXTURE_TYPE_CUBE: return GetDefaultTextureCubeName(); } UnreachableCode(); return EmptyString; } bool Engine::Startup() { // create threadpool int32 workerThreadCount = CVars::e_worker_threads.GetInt(); if (workerThreadCount < 0) { // create NTHREADS - 2 (main thread, render thread) Y_CPUID_RESULT cpuidResult; Y_ReadCPUID(&cpuidResult); workerThreadCount = (cpuidResult.ThreadCount < 3) ? 1 : (int32)cpuidResult.ThreadCount - 2; } // HTML5 has no threads. #ifdef Y_PLATFORM_HTML5 workerThreadCount = 0; #endif if (workerThreadCount > 0) { Log_InfoPrintf("Creating %u worker threads...", workerThreadCount); // create threadpool m_pWorkerThreadPool = new ThreadPool(workerThreadCount); // create async command queue if (!m_asyncCommandQueue.Initialize(m_pWorkerThreadPool, CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE)) { Log_ErrorPrintf("Engine::Startup: Failed to initialize async command queue."); return false; } // create background command queue if (!m_backgroundCommandQueue.Initialize(m_pWorkerThreadPool, CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE, true)) { Log_ErrorPrintf("Engine::Startup: Failed to initialize background command queue."); return false; } // create main thread command queue if (!m_mainThreadCommandQueue.Initialize(CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE, 0)) { Log_ErrorPrintf("Engine::Startup: Failed to initialize main thread command queue."); return false; } } else { Log_InfoPrintf("Engine::Startup: Not using worker threads."); // create async command queue if (!m_asyncCommandQueue.Initialize(CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE, 0)) { Log_ErrorPrintf("Engine::Startup: Failed to initialize async command queue."); return false; } // create background command queue if (!m_backgroundCommandQueue.Initialize((uint32)0, 0)) // not using queue since it's not called back -- fix this { Log_ErrorPrintf("Engine::Startup: Failed to initialize background command queue."); return false; } // create main thread command queue if (!m_mainThreadCommandQueue.Initialize(CommandQueue::DEFAULT_COMMAND_QUEUE_SIZE, 0)) { Log_ErrorPrintf("Engine::Startup: Failed to initialize main thread command queue."); return false; } } // done return true; } void Engine::Shutdown() { // Shutdown async workers, run any remaining callbacks for (;;) { bool result; result = m_asyncCommandQueue.ExecuteQueuedTasks(); result |= m_backgroundCommandQueue.ExecuteQueuedTasks(); result |= m_mainThreadCommandQueue.ExecuteQueuedTasks(); if (result) continue; else break; } // Exit worker threads delete m_pWorkerThreadPool; m_pWorkerThreadPool = nullptr; // Release fixed resources // Release default resources SAFE_RELEASE(m_pDefaultFont); // Tell resource manager to resource all managed resources. g_pResourceManager->ReleaseResources(); } const Font *Engine::GetDefaultFont() const { if (m_pDefaultFont == NULL && (m_pDefaultFont = g_pResourceManager->GetFont(m_strDefaultFontName)) == NULL) Panic("GetDefaultFont() called, and the default font failed to load."); m_pDefaultFont->AddRef(); return m_pDefaultFont; } <file_sep>/Engine/Source/Engine/Physics/BulletHeaders.h #pragma once #include "Engine/Common.h" #ifdef Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable: 4127) // warning C4127: conditional expression is constant #pragma warning(disable: 4706) // warning C4706: assignment within conditional expression #endif #include "btBulletCollisionCommon.h" #include "btBulletDynamicsCommon.h" #include "BulletCollision/CollisionDispatch/btGhostObject.h" namespace Physics { inline btVector3 Float3ToBulletVector(const float3 &v) { return btVector3(v.x, v.y, v.z); } inline float3 BulletVector3ToFloat3(const btVector3 &v) { return float3(v.x(), v.y(), v.z()); } inline btVector3 SIMDVector3fToBulletVector(const SIMDVector3f &v) { return btVector3(v.x, v.y, v.z); } inline float3 BulletVector3ToSIMDVector3f(const btVector3 &v) { return SIMDVector3f(v.x(), v.y(), v.z()); } inline btQuaternion QuaternionToBulletQuaternion(const Quaternion &v) { return btQuaternion(v.x, v.y, v.z, v.w); } inline Quaternion BulletQuaternionToQuaternion(const btQuaternion &v) { return Quaternion(v.x(), v.y(), v.z(), v.w()); } // drops any scale component of the transform inline btTransform TransformToBulletTransform(const Transform &transform) { btTransform res; res.setRotation(QuaternionToBulletQuaternion(transform.GetRotation())); res.setOrigin(Float3ToBulletVector(transform.GetPosition())); return res; } inline Transform BulletTransformToTransform(const btTransform &bulletTransform, const float3 &scale) { Transform res; res.SetRotation(BulletQuaternionToQuaternion(bulletTransform.getRotation())); res.SetPosition(BulletVector3ToFloat3(bulletTransform.getOrigin())); res.SetScale(scale); return res; } } #ifdef Y_COMPILER_MSVC #pragma warning(pop) #endif <file_sep>/Engine/Source/OpenGLES2Renderer/PrecompiledHeader.h #pragma once #include "OpenGLES2Renderer/OpenGLES2Common.h" <file_sep>/Engine/Source/BaseGame/InteractiveEntity.cpp #include "BaseGame/PrecompiledHeader.h" #include "BaseGame/InteractiveEntity.h" DEFINE_ENTITY_TYPEINFO(InteractiveEntity, 0); BEGIN_ENTITY_PROPERTIES(InteractiveEntity) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(InteractiveEntity) END_ENTITY_SCRIPT_FUNCTIONS() InteractiveEntity::InteractiveEntity(const EntityTypeInfo *pTypeInfo /* = &s_typeInfo */) : GameEntity(pTypeInfo) { } InteractiveEntity::~InteractiveEntity() { } <file_sep>/Editor/Source/Editor/Editor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/EditorCVars.h" #include "Editor/EditorVisual.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Engine/ResourceManager.h" #include "Engine/Font.h" #include "Engine/Entity.h" #include "Engine/EntityTypeInfo.h" #include "Engine/SDLHeaders.h" #include "Renderer/Renderer.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "YBaseLib/CPUID.h" Log_SetChannel(Editor); Editor *g_pEditor = NULL; extern void RunEditorTestBedsPreStartup(); extern void RunEditorTestBeds(); static uint32 CalculateFrameTimerInterval() { float maxFps = CVars::e_max_fps.GetFloat(); int32 timerKickInterval = Math::Truncate(Math::Floor(1000.0f / maxFps)); return (uint32)timerKickInterval; } Editor::Editor(int &argc, char **argv) : QApplication(argc, argv), m_running(true), m_pFrameExecuteTimer(NULL), m_blockFrameExecution(0), m_frameExecutionQueued(false), m_editorFPSAccumulator(0), m_editorFPSTimeAccumulator(0.0f), m_editorFPS(0.0f), m_editorTheme(EDITOR_THEME_NONE), m_pViewportOverlayFont(NULL) { m_pCommandLineArguments = (const char **)argv; m_nCommandLineArguments = argc; m_pFrameExecuteTimer = new QTimer(this); g_pEditor = this; } Editor::~Editor() { DebugAssert(m_blockFrameExecution == 0); DebugAssert(m_mapWindows.GetSize() == 0); g_pEditor = NULL; } static void SetCVars() { // set vars //g_pConsole->SetCVarByName("e_threadpool_worker_count", "1"); g_pConsole->SetCVarByName("e_camera_max_speed", "6"); g_pConsole->SetCVarByName("e_camera_acceleration", "12"); //g_pConsole->SetCVarByName("r_use_shader_caching", "1"); g_pConsole->SetCVarByName("r_use_shader_caching", "0"); g_pConsole->SetCVarByName("r_allow_shader_cache_writes", "1"); #if Y_BUILD_CONFIG_DEBUG g_pConsole->SetCVarByName("r_use_debug_shaders", "1"); #endif } int Editor::Execute() { // sanity recursion check static bool executed = false; Assert(!executed); executed = true; // initialize sdl1 Log_InfoPrint("Initializing SDL..."); SDL_SetMainReady(); if (SDL_Init(0) != 0) { Log_ErrorPrintf("Editor::Execute: SDL_Init failed: %s", SDL_GetError()); return -1; } // clean up SDL last atexit(SDL_Quit); // startup { Timer startupTimer; // <<<testbeds>>> RunEditorTestBedsPreStartup(); // initialize if (!Initialize()) return -2; // startup if (!Startup()) return -3; // <<<testbeds>>> RunEditorTestBeds(); // log startup time Log_DevPrintf("<<<Editor started in %.4f msec>>>", startupTimer.GetTimeMilliseconds()); } // pass control over to qt int qtReturnCode = QApplication::exec(); // execute shutdown routines Shutdown(); // return code return qtReturnCode; } void Editor::Exit() { static bool exited = false; if (exited) return; exited = true; // invoke this method next event loop //QMetaObject::invokeMethod(this, SLOT(quit()), Qt::QueuedConnection); quit(); } bool Editor::Initialize() { // set cvars SetCVars(); // pass command line to console g_pConsole->ParseCommandLine(m_nCommandLineArguments, m_pCommandLineArguments); // print version info { Y_CPUID_RESULT CPUIDResult; Y_ReadCPUID(&CPUIDResult); Log_InfoPrint("=========== Editor Version 1.0 Initializing ==========="); Log_DevPrint("Build Configuration: " Y_BUILD_CONFIG_STR); Log_DevPrint("Host Platform: " Y_PLATFORM_STR); Log_DevPrint("Host Architecture: " Y_CPU_STR Y_CPU_FEATURES_STR); Log_DevPrintf("Host CPU: %s", CPUIDResult.SummaryString); } Log_InfoPrint("Initializing virtual file system..."); if (!g_pVirtualFileSystem->Initialize()) { Log_InfoPrint("Virtual file system initialization failed. Cannot continue."); return false; } // add types g_pEngine->RegisterEngineTypes(); RegisterEditorTypes(); // load property templates Log_InfoPrint("Loading object templates..."); if (!LoadObjectTemplates()) return false; // load entity definitions Log_InfoPrint("Loading visual definitions..."); if (!LoadVisualDefinitions()) return false; // done return true; } bool Editor::Startup() { // begin startup Log_InfoPrint("[Editor] Starting up..."); // startup engine if (!g_pEngine->Startup()) return false; // load icons if (!m_iconLibrary.PreloadIcons()) return false; // get viewport overlay font m_pViewportOverlayFont = g_pResourceManager->GetFont(g_pEngine->GetRendererDebugFontName()); if (m_pViewportOverlayFont == NULL) { Log_ErrorPrintf("Could not load viewport overlay font."); return false; } // create renderer RendererInitializationParameters createParameters; createParameters.EnableThreadedRendering = false; createParameters.HideImplicitSwapChain = true; if (!Renderer::Create(&createParameters)) return false; // create the initial map window Log_InfoPrint("[Editor] Creating initial map window..."); EditorMapWindow *pMapWindow = new EditorMapWindow(); pMapWindow->NewMap(); pMapWindow->show(); // start the frame timer connect(m_pFrameExecuteTimer, SIGNAL(timeout()), this, SLOT(OnFrameExecuteTimerTriggered())); m_pFrameExecuteTimer->start(CalculateFrameTimerInterval()); // connect the 'last window closed' event to the quit slot connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit())); // done return true; } void Editor::Shutdown() { // block frame execution BlockFrameExecution(); // stop frame execution timer m_pFrameExecuteTimer->stop(); // close all map windows CloseAllMapWindows(); // kill remaining main windows while (m_mainWindows.GetSize() > 0) { m_mainWindows[0]->close(); delete m_mainWindows[0]; } // kill resources m_pViewportOverlayFont->Release(); // kill definitions for (VisualDefinitionHashTable::Iterator itr = m_visualDefinitions.Begin(); !itr.AtEnd(); itr.Forward()) delete itr->Value; m_visualDefinitions.Clear(); // shutdown subsystems g_pRenderer->Shutdown(); g_pEngine->Shutdown(); // shutdown VFS layer g_pVirtualFileSystem->Shutdown(); // unregister types g_pEngine->UnregisterTypes(); // unblock again UnblockFrameExecution(); } void Editor::SetEditorTheme(EDITOR_THEME theme) { if (theme == m_editorTheme) return; m_editorTheme = theme; if (theme == EDITOR_THEME_NONE) { setStyleSheet(QStringLiteral("")); } else if (theme == EDITOR_THEME_DARK) { QFile file(":qdarkstyle/qdarkstylesheet.qss"); if (file.open(QFile::ReadOnly)) setStyleSheet(QLatin1String(file.readAll())); } else if (theme == EDITOR_THEME_DARK_OTHER) { QFile file(":/editor/style_dark/style.css"); if (file.open(QFile::ReadOnly)) setStyleSheet(QLatin1String(file.readAll())); } } EditorMapWindow *Editor::CreateMap() { BlockFrameExecution(); EditorMapWindow *pMapWindow = new EditorMapWindow(); pMapWindow->show(); UnblockFrameExecution(); return pMapWindow; } EditorMapWindow *Editor::OpenMap(const char *mapFileName) { BlockFrameExecution(); EditorMapWindow *pMapWindow = new EditorMapWindow(); if (!pMapWindow->OpenMap(mapFileName)) { UnblockFrameExecution(); delete pMapWindow; return NULL; } pMapWindow->show(); UnblockFrameExecution(); return pMapWindow; } void Editor::AddMapWindow(EditorMapWindow *pMapWindow) { m_mapWindows.Add(pMapWindow); } void Editor::RemoveMapWindow(EditorMapWindow *pMapWindow) { for (uint32 i = 0; i < m_mapWindows.GetSize(); i++) { if (m_mapWindows[i] == pMapWindow) { m_mapWindows.OrderedRemove(i); return; } } Panic("Attempting to remove untracked map window"); } void Editor::CloseAllMapWindows() { // block frame execution BlockFrameExecution(); // close map windows, may trigger a modal dialog box while (m_mapWindows.GetSize() > 0) { m_mapWindows[0]->close(); delete m_mapWindows[0]; } // unblock frame execution UnblockFrameExecution(); } void Editor::AddMainWindow(QMainWindow *pMainWindow) { m_mainWindows.Add(pMainWindow); } void Editor::RemoveMainWindow(QMainWindow *pMainWindow) { for (uint32 i = 0; i < m_mainWindows.GetSize(); i++) { if (m_mainWindows[i] == pMainWindow) { m_mainWindows.OrderedRemove(i); return; } } Panic("Attempting to remove untracked main window"); } const EditorVisualDefinition *Editor::GetVisualDefinitionByName(const char *typeName) const { const VisualDefinitionHashTable::Member *pMember = m_visualDefinitions.Find(typeName); return (pMember != nullptr) ? pMember->Value : nullptr; } const EditorVisualDefinition *Editor::GetVisualDefinitionForObjectTemplate(const ObjectTemplate *pTemplate) const { const VisualDefinitionHashTable::Member *pMember = m_visualDefinitions.Find(pTemplate->GetTypeName()); return (pMember != nullptr) ? pMember->Value : nullptr; } bool Editor::LoadObjectTemplates() { if (!ObjectTemplateManager::GetInstance().LoadAllTemplates()) { Log_ErrorPrintf("Editor::LoadObjectTemplates: ObjectTemplateManager::LoadAllTemplates failed."); return false; } // search for some common templates that should always be present #define CHECK_OBJECT_TEMPLATE(name) MULTI_STATEMENT_MACRO_BEGIN \ if (ObjectTemplateManager::GetInstance().GetObjectTemplate(name) == nullptr) { \ Log_ErrorPrintf("Editor::LoadObjectTemplates: Missing template for required type '%s'", name); \ return false; \ } \ MULTI_STATEMENT_MACRO_END CHECK_OBJECT_TEMPLATE("Brush"); CHECK_OBJECT_TEMPLATE("Entity"); CHECK_OBJECT_TEMPLATE("Map"); #undef CHECK_OBJECT_TEMPLATE return true; } bool Editor::LoadVisualDefinitions() { static const char *VISUAL_BASE_PATH = "resources/engine/editor_visuals"; // load definitions for all known object templates first ObjectTemplateManager::GetInstance().EnumerateObjectTemplates([this](const ObjectTemplate *pTemplate) { PathString fileName; fileName.Format("%s/%s.xml", VISUAL_BASE_PATH, pTemplate->GetTypeName().GetCharArray()); // skip nonexistant visuals if (!g_pVirtualFileSystem->FileExists(fileName)) return; // create it EditorVisualDefinition *pDefinition = new EditorVisualDefinition(); if (!pDefinition->CreateFromTemplate(pTemplate)) { Log_WarningPrintf("Editor::LoadVisualDefinitions: Failed to load visual definition for object type '%s'", pTemplate->GetTypeName().GetCharArray()); delete pDefinition; return; } // add to hash map DebugAssert(m_visualDefinitions.Find(pDefinition->GetName()) == nullptr); m_visualDefinitions.Insert(pDefinition->GetName(), pDefinition); }); // search for remaining templates FileSystem::FindResultsArray findResults; g_pVirtualFileSystem->FindFiles("resources/engine/editor_visuals", "*.xml", FILESYSTEM_FIND_FILES | FILESYSTEM_FIND_RELATIVE_PATHS, &findResults); // go through find results for (uint32 i = 0; i < findResults.GetSize(); i++) { FILESYSTEM_FIND_DATA &findData = findResults[i]; // strip the xml extension SmallString typeName; typeName.AppendString(findData.FileName); if (!typeName.EndsWith(".xml", false)) continue; typeName.Erase(-4); // already exists? and skip anything that's an object if (m_visualDefinitions.Find(typeName) != nullptr || ObjectTemplateManager::GetInstance().GetObjectTemplate(typeName) != nullptr) continue; // create it EditorVisualDefinition *pDefinition = new EditorVisualDefinition(); if (!pDefinition->CreateFromName(typeName)) { Log_WarningPrintf("Editor::LoadVisualDefinitions: Failed to load visual definition for object name '%s'", typeName.GetCharArray()); delete pDefinition; continue; } // add to hash map DebugAssert(m_visualDefinitions.Find(pDefinition->GetName()) == nullptr); m_visualDefinitions.Insert(pDefinition->GetName(), pDefinition); } Log_InfoPrintf("Editor::LoadVisualDefinitions: Loaded %u visuals.", m_visualDefinitions.GetMemberCount()); return true; } void Editor::QueueFrameExecution() { if (!m_frameExecutionQueued) { //QTimer::singleShot(0, g_pEditor, &Editor::OnFrameExecuteTimerTriggered); m_frameExecutionQueued = true; } } void Editor::OnFrameExecuteTimerTriggered() { if (m_blockFrameExecution > 0) return; // prevent any recursive calls (i.e. modal dialogs) m_blockFrameExecution++; // allow another frame to be immediately queued m_frameExecutionQueued = false; // reset the frame timer float timeSinceLastFrame = (float)m_lastFrameTime.GetTimeSeconds(); m_lastFrameTime.Reset(); // run any window's frame stuff OnFrameExecution(timeSinceLastFrame); // run any render commands queued from other threads g_pRenderer->GetCommandQueue()->ExecuteQueuedTasks(); // estimate the current fps //m_editorFPS = (float)(1000.0 / m_lastFrameTime.GetTimeMilliseconds()); m_editorFPSTimeAccumulator += (float)timeSinceLastFrame; m_editorFPSAccumulator++; if (m_editorFPSTimeAccumulator > 0.1f) { m_editorFPS = (float)m_editorFPSAccumulator / m_editorFPSTimeAccumulator; m_editorFPSTimeAccumulator = 0.0f; m_editorFPSAccumulator = 0; } // other end of recursive call block m_blockFrameExecution--; } void Editor::OnPendingCloseTriggered() { } void Editor::ProcessBackgroundEvents() { BlockFrameExecution(); QGuiApplication::processEvents(QEventLoop::ExcludeUserInputEvents); UnblockFrameExecution(); } <file_sep>/Engine/Source/ContentConverter/FontImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/FontImporter.h" #include "ResourceCompiler/FontGenerator.h" #if USE_FREETYPE2 #include "freetype2/ft2build.h" #include FT_FREETYPE_H #include FT_GLYPH_H #ifdef Y_COMPILER_MSVC #ifdef Y_BUILD_CONFIG_DEBUG #pragma comment(lib, "freetype26d") #else #pragma comment(lib, "freetype26") #endif #endif #else #define STBTT_malloc(x,u) malloc(x) #define STBTT_free(x,u) free(x) #define STB_TRUETYPE_IMPLEMENTATION 1 #include "ContentConverter/stb_truetype.h" #endif FontImporter::FontImporter(ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pGenerator(nullptr), m_renderWidth(0), m_renderHeight(0) #ifdef USE_FREETYPE2 , m_pFreeTypeLibrary(nullptr), m_pFreeTypeFace(nullptr), m_fontIsBitmap(false) #else , m_pInputFile(nullptr) #endif { } FontImporter::~FontImporter() { delete m_pGenerator; #ifdef USE_FREETYPE2 if (m_pFreeTypeFace != nullptr) FT_Done_Face(reinterpret_cast<FT_Face>(m_pFreeTypeFace)); if (m_pFreeTypeLibrary != nullptr) FT_Done_FreeType(reinterpret_cast<FT_Library>(m_pFreeTypeLibrary)); #else if (m_pInputFile != nullptr) m_pInputFile->Release(); #endif } uint32 FontImporter::ConvertPointsToPixels(float pointSize) { const float POINTS_PER_INCH = 72; const float DOTS_PER_INCH = 96; return (uint32)Math::Truncate(Math::Round(pointSize * (DOTS_PER_INCH / POINTS_PER_INCH))); } bool FontImporter::ParseFontSizeString(uint32 *pOutPixels, const char *value) { uint32 valueLen = Y_strlen(value); if (valueLen == 0) return false; char *temp = (char *)alloca(valueLen + 1); uint32 nDigits = 0; for (uint32 i = 0; i < valueLen; i++) { if (value[i] >= '0' && value[i] <= '9') temp[nDigits++] = value[i]; } if (nDigits == 0) return false; temp[nDigits] = 0; float valueFloat = StringConverter::StringToFloat(temp); const char *suffix = value + nDigits; if (Y_stricmp(suffix, "pt") == 0) { *pOutPixels = ConvertPointsToPixels(valueFloat); return true; } else if (Y_stricmp(suffix, "px") == 0) { *pOutPixels = (uint32)Math::Truncate(Math::Round(valueFloat)); return true; } else { return false; } } void FontImporter::ListSubFonts(const char *fileName, ProgressCallbacks *pProgressCallbacks) { FT_Library ftLibrary; FT_Error ftError = FT_Init_FreeType(&ftLibrary); if (ftError != 0) { pProgressCallbacks->DisplayFormattedError("Failed to initialize FreeType: %d", ftError); return; } // load the font FT_Face ftFace; ftError = FT_New_Face(ftLibrary, fileName, 0, &ftFace); if (ftError != 0) { pProgressCallbacks->DisplayFormattedError("FT_New_Face failed: %d", ftError); FT_Done_FreeType(ftLibrary); return; } pProgressCallbacks->DisplayFormattedInformation("Font '%s' has %u sub fonts:", fileName, (uint32)ftFace->num_faces); // iterate through font faces for (FT_Long subFontIndex = 0; subFontIndex < ftFace->num_faces; subFontIndex++) { FT_Face subFace; ftError = FT_New_Face(ftLibrary, fileName, subFontIndex, &subFace); if (ftError != 0) { pProgressCallbacks->DisplayFormattedError("FT_New_Face for subfont %u failed: %d", (uint32)subFontIndex, ftError); break; } SmallString summaryString; uint32 summaryStringCount = 0; if (subFace->family_name != nullptr) summaryString.AppendFormattedString("%sfamily: %s", ((summaryStringCount++) > 0) ? ", " : "", subFace->family_name); if (subFace->style_name != nullptr) summaryString.AppendFormattedString("%sstyle: %s", ((summaryStringCount++) > 0) ? ", " : "", subFace->style_name); if (subFace->style_flags & FT_STYLE_FLAG_BOLD) summaryString.AppendFormattedString("%sbold", ((summaryStringCount++) > 0) ? ", " : ""); if (subFace->style_flags & FT_STYLE_FLAG_ITALIC) summaryString.AppendFormattedString("%sitalic", ((summaryStringCount++) > 0) ? ", " : ""); if (!(ftFace->face_flags & FT_FACE_FLAG_SCALABLE) && (ftFace->available_sizes > 0)) { pProgressCallbacks->DisplayFormattedInformation(" Sub font %u (%s) is a bitmap font with %u sizes:", (uint32)subFontIndex, summaryString.GetCharArray(), (uint32)subFace->num_fixed_sizes); for (int i = 0; i < subFace->num_fixed_sizes; i++) pProgressCallbacks->DisplayFormattedInformation(" %u x %u pixels", (uint32)subFace->available_sizes[i].width, (uint32)subFace->available_sizes[i].height); } else { pProgressCallbacks->DisplayFormattedInformation(" Sub font %u (%s) is a outline font.", (uint32)subFontIndex, summaryString.GetCharArray(), (uint32)subFace->num_fixed_sizes); } FT_Done_Face(subFace); } FT_Done_Face(ftFace); FT_Done_FreeType(ftLibrary); } void FontImporter::ListFontSizes(const char *fileName, uint32 subFontIndex, ProgressCallbacks *pProgressCallbacks) { FT_Library ftLibrary; FT_Error ftError = FT_Init_FreeType(&ftLibrary); if (ftError != 0) { pProgressCallbacks->DisplayFormattedError("Failed to initialize FreeType: %d", ftError); return; } // load the font FT_Face ftFace; ftError = FT_New_Face(ftLibrary, fileName, subFontIndex, &ftFace); if (ftError != 0) { pProgressCallbacks->DisplayFormattedError("FT_New_Face failed: %d", ftError); FT_Done_FreeType(ftLibrary); return; } if (ftFace->num_fixed_sizes == 0) { pProgressCallbacks->DisplayFormattedError("Font '%s' is not a bitmap font.", fileName); FT_Done_Face(ftFace); FT_Done_FreeType(ftLibrary); return; } pProgressCallbacks->DisplayFormattedInformation("Bitmap font with %d sizes detected.", ftFace->num_fixed_sizes); for (int i = 0; i < ftFace->num_fixed_sizes; i++) pProgressCallbacks->DisplayFormattedInformation(" Bitmap size: %u x %u pixels", (uint32)ftFace->available_sizes[i].width, (uint32)ftFace->available_sizes[i].height); FT_Done_Face(ftFace); FT_Done_FreeType(ftLibrary); } void FontImporter::SetDefaultOptions(FontImporterOptions *pOptions) { pOptions->SubFontIndex = 0; pOptions->Type = FONT_TYPE_BITMAP; pOptions->AppendToFile = false; pOptions->RenderWidth = 0; pOptions->RenderHeight = 0; } bool FontImporter::AddCharacterSet(FontImporterOptions *pOptions, const char *blockName) { // latin1 - 32->126, 160->255 for (uint32 i = 32; i <= 126; i++) pOptions->UnicodeCodePointSet.Add(i); for (uint32 i = 160; i <= 255; i++) pOptions->UnicodeCodePointSet.Add(i); return true; } bool FontImporter::IsWhitespace(uint32 codePoint) { return (codePoint == '\r' || codePoint == '\n' || codePoint == '\t' || codePoint == ' '); } bool FontImporter::Execute(const FontImporterOptions *pOptions) { m_pProgressCallbacks->DisplayFormattedInformation("Requested render width: %u", pOptions->RenderWidth); m_pProgressCallbacks->DisplayFormattedInformation("Requested render height: %u", pOptions->RenderHeight); // open input file if (!ReadInputFile(pOptions->InputFileName, pOptions->SubFontIndex, pOptions->RenderWidth, pOptions->RenderHeight)) { m_pProgressCallbacks->DisplayFormattedModalError("ReadInputFile() failed, the log may contain more information."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("Actual render width: %u", m_renderWidth); m_pProgressCallbacks->DisplayFormattedInformation("Actual render height: %u", m_renderHeight); // load/open if (pOptions->AppendToFile) { if (!OpenExistingGenerator(pOptions->OutputName)) { m_pProgressCallbacks->DisplayFormattedModalError("OpenExistingGenerator() failed, the log may contain more information."); return false; } } else { if (!CreateNewGenerator(pOptions->Type)) { m_pProgressCallbacks->DisplayFormattedModalError("CreateNewGenerator() failed, the log may contain more information."); return false; } } // bake if (!AddCharacters(pOptions->UnicodeCodePointSet.GetBasePointer(), pOptions->UnicodeCodePointSet.GetSize())) { m_pProgressCallbacks->DisplayFormattedModalError("AddCharacters() failed, the log may contain more information."); return false; } // save if (!SaveGenerator(pOptions->OutputName)) { m_pProgressCallbacks->DisplayFormattedModalError("SaveGenerator() failed, the log may contain more information."); return false; } return true; } bool FontImporter::ReadInputFile(const char *fileName, uint32 subFontIndex, uint32 characterWidth, uint32 characterHeight) { #ifdef USE_FREETYPE2 FT_Library ftLibrary; FT_Error ftError = FT_Init_FreeType(&ftLibrary); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedError("Failed to initialize FreeType: %d", ftError); return false; } m_pFreeTypeLibrary = reinterpret_cast<void *>(ftLibrary); // load the font FT_Face ftFace; ftError = FT_New_Face(ftLibrary, fileName, subFontIndex, &ftFace); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedError("Failed to initialize face: %d", ftError); return false; } m_pFreeTypeFace = reinterpret_cast<void *>(ftFace); // for unspecified widths, set to the height if (characterHeight == 0) characterHeight = 16; if (characterWidth == 0) characterWidth = characterHeight; // is it a bitmap font? m_fontIsBitmap = !(ftFace->face_flags & FT_FACE_FLAG_SCALABLE) && (ftFace->available_sizes > 0); if (m_fontIsBitmap) { m_pProgressCallbacks->DisplayFormattedInformation("Bitmap font with %d sizes detected.", ftFace->num_fixed_sizes); uint32 closestDiff = (uint32)Math::Abs(ftFace->available_sizes[0].width - (int)characterWidth) + (uint32)Math::Abs(ftFace->available_sizes[0].height - (int)characterHeight); m_renderWidth = ftFace->available_sizes[0].width; m_renderHeight = ftFace->available_sizes[0].height; for (int i = 1; i < ftFace->num_fixed_sizes; i++) { uint32 thisDiff = (uint32)Math::Abs(ftFace->available_sizes[i].width - (int)characterWidth) + (uint32)Math::Abs(ftFace->available_sizes[i].height - (int)characterHeight); if (thisDiff < closestDiff) { m_renderWidth = ftFace->available_sizes[1].width; m_renderHeight = ftFace->available_sizes[1].height; closestDiff = thisDiff; } } } else { // use the specified size m_renderWidth = characterWidth; m_renderHeight = characterHeight; } // freetype mesures font size in 1/64th of pixels, or 26.6 fixed point //ftError = FT_Set_Char_Size(reinterpret_cast<FT_Face>(m_pFreeTypeFace), m_renderWidth * 64, m_renderHeight * 64, 96, 96); ftError = FT_Set_Pixel_Sizes(reinterpret_cast<FT_Face>(m_pFreeTypeFace), m_renderWidth, m_renderHeight); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedError("FT_Set_Pixel_Sizes failed: %d", ftError); return false; } return true; #else AutoReleasePtr<ByteStream> pStream = FileSystem::OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { m_pProgressCallbacks->DisplayFormattedError("Unable to open file '%s'", fileName); return false; } if ((m_pInputFile = BinaryBlob::CreateFromStream(pStream)) == nullptr) { m_pProgressCallbacks->DisplayFormattedError("Failed to read file '%s'", fileName); return false; } return true; #endif } bool FontImporter::CreateNewGenerator(FONT_TYPE type) { m_pGenerator = new FontGenerator(); m_pGenerator->Create(type, m_renderHeight); // mipmaps are off by default, texture filtering for non-bitmap sources only m_pGenerator->SetUseTextureFiltering(!m_fontIsBitmap); m_pGenerator->SetGenerateMipmaps(false); return true; } bool FontImporter::OpenExistingGenerator(const char *fontName) { PathString fileName; fileName.Format("%s.font.zip", fontName); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) { m_pProgressCallbacks->DisplayFormattedError("Failed to open existing font '%s'", fileName.GetCharArray()); return false; } m_pGenerator = new FontGenerator(); if (!m_pGenerator->Load(fileName, pStream)) { m_pProgressCallbacks->DisplayFormattedError("Failed to load existing font '%s'", fileName.GetCharArray()); return false; } // check the height if (m_pGenerator->GetCharacterHeight() != m_renderHeight) { m_pProgressCallbacks->DisplayFormattedError("Loaded font has a different height: %u vs %u", m_pGenerator->GetCharacterHeight(), m_renderHeight); return false; } return true; } bool FontImporter::SaveGenerator(const char *fontName) { PathString fileName; fileName.Format("%s.font.zip", fontName); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == nullptr) return false; if (!m_pGenerator->Save(pStream)) { pStream->Discard(); return false; } return pStream->Commit(); } bool FontImporter::AddCharacters(const uint32 *pCharacters, uint32 nCharacters) { m_pProgressCallbacks->DisplayFormattedInformation("Rendering %u characters...", nCharacters); for (uint32 characterIndex = 0; characterIndex < nCharacters; characterIndex++) { uint32 codePoint = pCharacters[characterIndex]; if (m_pGenerator->GetCharacterByCodePoint(codePoint) != nullptr) { m_pProgressCallbacks->DisplayFormattedWarning("Code point %u already exists, skipping.", codePoint); continue; } if (m_pGenerator->GetType() == FONT_TYPE_BITMAP) { if (!AddBitmapCharacter(codePoint)) { m_pProgressCallbacks->DisplayFormattedWarning("Failed to render code point %u.", codePoint); continue; } } else if (m_pGenerator->GetType() == FONT_TYPE_SIGNED_DISTANCE_FIELD) { if (!AddSignedDistanceFieldCharacter(codePoint)) { m_pProgressCallbacks->DisplayFormattedWarning("Failed to render code point %u.", codePoint); continue; } } } if (m_pGenerator->GetCharacterCount() == 0) { m_pProgressCallbacks->DisplayError("No characters were rendered."); return false; } return true; } bool FontImporter::AddBitmapCharacter(uint32 codePoint) { #if USE_FREETYPE2 FT_Error ftError; FT_Face ftFace = reinterpret_cast<FT_Face>(m_pFreeTypeFace); FT_UInt ftCharIndex = FT_Get_Char_Index(ftFace, codePoint); if (ftCharIndex == 0) { m_pProgressCallbacks->DisplayFormattedInformation("Code point %u does not exist in font", codePoint); return false; } // use mono? bool useMonoRenderMode = m_fontIsBitmap; // load glyph uint32 loadFlags = FT_LOAD_DEFAULT; if (useMonoRenderMode) loadFlags |= FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT; // load glyph ftError = FT_Load_Glyph(ftFace, ftCharIndex, loadFlags); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedInformation("Failed to load glyph: %d", ftError); return false; } // create glyph object FT_Glyph ftGlyph; ftError = FT_Get_Glyph(ftFace->glyph, &ftGlyph); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedError("Failed to load get glyph: %d", ftError); return false; } // convert to bitmap FT_BitmapGlyph ftBitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(ftGlyph); ftError = FT_Glyph_To_Bitmap(reinterpret_cast<FT_Glyph *>(&ftBitmapGlyph), (useMonoRenderMode) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL, nullptr, 0); if (ftError != 0) { m_pProgressCallbacks->DisplayFormattedError("Failed to convert glyph to bitmap: %d", ftError); FT_Done_Glyph(ftGlyph); return false; } // determine image dimensions uint32 imageWidth = ftBitmapGlyph->bitmap.width; uint32 imageHeight = ftBitmapGlyph->bitmap.rows; int32 baseLine = ftFace->size->metrics.height / 64; int32 lsBearing = ftFace->glyph->metrics.horiBearingX / 64; int32 tsBearing = ftFace->glyph->metrics.horiBearingY / 64; float advance = (float)ftFace->glyph->metrics.horiAdvance / 64.0f; // calculate draw offsets int32 drawOffsetX = lsBearing; int32 drawOffsetY = baseLine - tsBearing; m_pProgressCallbacks->DisplayFormattedDebugMessage("cp %u: %ux%u bitmap, bl %d, lsb %d, tsb %d, advance %.4f, ox %d, oy %d", codePoint, imageWidth, imageHeight, baseLine, lsBearing, tsBearing, advance, drawOffsetX, drawOffsetY); // check for whitespace if (IsWhitespace(codePoint) || imageWidth == 0 || imageHeight == 0) { // create a whitespace character return m_pGenerator->AddWhitespaceCharacter(codePoint, advance); } // create the image Image glyphBitmapImage; glyphBitmapImage.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, imageWidth, imageHeight, 1); Y_memzero(glyphBitmapImage.GetData(), glyphBitmapImage.GetDataSize()); // set pixels for (uint32 imageY = 0; imageY < imageHeight; imageY++) { uint32 *pRow = reinterpret_cast<uint32 *>(glyphBitmapImage.GetData() + (imageY * glyphBitmapImage.GetDataRowPitch())); for (uint32 imageX = 0; imageX < imageWidth; imageX++) { // don't premultiply the colour, the texture generation later on will take care of that byte alpha; if (useMonoRenderMode) { // find the texel byte texel = ftBitmapGlyph->bitmap.buffer[imageY * ftBitmapGlyph->bitmap.pitch + (imageX / 8)]; // find the bit uint32 bit = imageX % 8; alpha = (((texel >> (7 - bit)) & 0x1) != 0) ? 255 : 0; } else { // access 8-bit value directly alpha = ftBitmapGlyph->bitmap.buffer[imageY * ftBitmapGlyph->bitmap.pitch + imageX]; } pRow[imageX] = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, alpha); } } // cleanup freetype stuff FT_Done_Glyph(reinterpret_cast<FT_Glyph>(ftBitmapGlyph)); if (reinterpret_cast<FT_Glyph>(ftBitmapGlyph) != ftGlyph) FT_Done_Glyph(ftGlyph); // create character return m_pGenerator->AddCharacter(codePoint, 0, 0, drawOffsetX, drawOffsetY, advance, &glyphBitmapImage); #else stbtt_fontinfo fontInfo; if (!stbtt_InitFont(&fontInfo, m_pInputFile->GetDataPointer(), 0)) { m_pProgressCallbacks->DisplayFormattedDebugMessage("Font initialization failed"); return false; } float scale = stbtt_ScaleForPixelHeight(&fontInfo, (float)m_pGenerator->GetCharacterHeight()); int glyphIndex = stbtt_FindGlyphIndex(&fontInfo, codePoint); if (glyphIndex == 0) { m_pProgressCallbacks->DisplayFormattedDebugMessage("Glyph not found for code point %u", codePoint); return false; } int advance; int lsb; int x0, y0; int x1, y1; stbtt_GetGlyphHMetrics(&fontInfo, glyphIndex, &advance, &lsb); stbtt_GetGlyphBitmapBox(&fontInfo, glyphIndex, scale, scale, &x0, &y0, &x1, &y1); // check for whitespace if (IsWhitespace(codePoint) || x0 == x1 || y0 == y1) { // create a whitespace character return m_pGenerator->AddWhitespaceCharacter(codePoint, (float)advance * scale); } // allocate pixel buffer since this only writes alpha uint32 imageWidth = Math::Abs(x1 - x0) + 1; uint32 imageHeight = Math::Abs(y1 - y0) + 1; byte *pAlphaPixels = new byte[imageWidth * imageHeight]; Y_memzero(pAlphaPixels, imageWidth * imageHeight); stbtt_MakeGlyphBitmap(&fontInfo, pAlphaPixels, imageWidth, imageHeight, imageWidth, scale, scale, glyphIndex); // allocate the real image Image image; image.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, imageWidth, imageHeight, 1); Y_memzero(image.GetData(), image.GetDataSize()); // set pixels for (uint32 imageY = 0; imageY < imageHeight; imageY++) { uint32 *pRow = reinterpret_cast<uint32 *>(image.GetData() + (imageY * image.GetDataRowPitch())); for (uint32 imageX = 0; imageX < imageWidth; imageX++) { // don't premultiply the colour, the texture generation later on will take care of that byte alpha = pAlphaPixels[imageY * imageWidth + imageX]; pRow[imageX] = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, alpha); } } // this buffer can go now delete[] pAlphaPixels; // create character return m_pGenerator->AddCharacter(codePoint, 0, 0, (uint32)x0, (uint32)y0, (float)advance * scale, &image); #endif } bool FontImporter::AddSignedDistanceFieldCharacter(uint32 codePoint) { return false; } #if 0 bool FontImporter::Execute(const FontImporterOptions *pOptions) { uint32 i; uint32 x, y; String fileName; DDSWriter ddsWriter; if (pOptions->InputFileName.IsEmpty() || pOptions->OutputName.IsEmpty() || pOptions->UnicodeCodePointSet.GetSize() == 0) { m_pProgressCallbacks->ModalError("One or more required parameters not set."); return false; } ByteStream *pStream; if ((pStream = FileSystem::OpenFile(pOptions->InputFileName, BYTESTREAM_OPEN_READ)) == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open input file '%s'.", pOptions->InputFileName.GetCharArray()); return false; } uint32 cbFontData = (uint32)pStream->GetSize(); byte *pFontBytes = new byte[cbFontData]; if (!pStream->Read2(pFontBytes, cbFontData)) { m_pProgressCallbacks->DisplayFormattedError("Could not read font data."); delete[] pFontBytes; pStream->Release(); return false; } // close stream pStream->Release(); uint32 CurTextureSize = 128; uint32 FirstCharacter = 0; uint32 LastCharacter = 255; uint32 CurrentCharacter = FirstCharacter; uint32 CurrentTextureIndex = 0; m_arrCharacters.Resize(LastCharacter - CurrentCharacter + 1); Y_memzero(m_arrCharacters.GetBasePointer(), sizeof(DF_FONT_CHARACTER) * m_arrCharacters.GetSize()); for (i = 0; i < m_arrCharacters.GetSize(); i++) { DF_FONT_CHARACTER *pch = &m_arrCharacters[i]; pch->x0 = pch->x1 = 0; pch->y0 = pch->y1 = 0; pch->xOffset = pch->yOffset = pch->xAdvance = 0.0f; pch->TextureIndex = -1; pch->IsWhiteSpace = false; } while (CurrentCharacter <= LastCharacter) { byte *pPixels = new byte[CurTextureSize * CurTextureSize]; uint32 nCharacters = LastCharacter - CurrentCharacter + 1; stbtt_bakedchar *pBakedChars = new stbtt_bakedchar[nCharacters]; m_pProgressCallbacks->DisplayFormattedInformation("Baking %u characters to %u * %u texture", nCharacters, CurTextureSize, CurTextureSize); int r = stbtt_BakeFontBitmap(pFontBytes, 0, (float)pOptions->Height, pPixels, CurTextureSize, CurTextureSize, CurrentCharacter, nCharacters, pBakedChars); if (r < 0) { if ((CurTextureSize * 2) > pOptions->MaxTextureSize) { m_pProgressCallbacks->DisplayFormattedInformation("Only wrote %d characters, moving to new texture", -r); CurTextureSize = pOptions->MaxTextureSize; nCharacters = (uint32)(-r); CurrentTextureIndex++; } else { m_pProgressCallbacks->DisplayFormattedInformation("Only wrote %d characters, expanding texture", -r); CurTextureSize *= 2; delete[] pBakedChars; delete[] pPixels; continue; } } // allocate rgba pixels and convert them FontTexture t; t.pPixels = new byte[CurTextureSize * CurTextureSize * 4]; t.cbPixels = CurTextureSize * CurTextureSize * 4; t.pf = PIXEL_FORMAT_R8G8B8A8_UNORM; // apply alpha value, and premultiply the rgb values byte *pAPixel = pPixels; byte *pRGBAPixel = t.pPixels; for (y = 0; y < CurTextureSize; y++) { for (x = 0; x < CurTextureSize; x++) { *(pRGBAPixel++) = *(pAPixel); *(pRGBAPixel++) = *(pAPixel); *(pRGBAPixel++) = *(pAPixel); *(pRGBAPixel++) = *(pAPixel); pAPixel++; } } // compress textures? if (pOptions->CompressTextures) { static const PIXEL_FORMAT compressedPixelFormat = PIXEL_FORMAT_BC3_UNORM; uint32 cbCompressedPixels = PixelFormat_CalculateImageSize(compressedPixelFormat, CurTextureSize, CurTextureSize, 1); byte *pCompressedPixels = new byte[cbCompressedPixels]; if (PixelFormat_ConvertPixels(CurTextureSize, CurTextureSize, t.pPixels, PixelFormat_CalculateRowPitch(t.pf, CurTextureSize), t.pf, pCompressedPixels, PixelFormat_CalculateRowPitch(compressedPixelFormat, CurTextureSize), compressedPixelFormat, &cbCompressedPixels)) { m_pProgressCallbacks->DisplayFormattedInformation("Compressed font texture from %u bytes to %u bytes.", t.cbPixels, cbCompressedPixels); delete[] t.pPixels; t.pPixels = pCompressedPixels; t.cbPixels = cbCompressedPixels; t.pf = compressedPixelFormat; } else { m_pProgressCallbacks->DisplayFormattedError("Texture compression failed."); delete[] pCompressedPixels; } } m_arrTextures.Add(t); #if 0 FontTexture t; t.pPixels = pPixels; t.cbPixels = sizeof(byte) * CurTextureSize * CurTextureSize; t.pf = PIXEL_FORMAT_A8_UNORM; m_arrTextures.Add(t); #endif for (i = 0; i < nCharacters; i++) { uint32 realCh = CurrentCharacter + i; DebugAssert(realCh < m_arrCharacters.GetSize()); DF_FONT_CHARACTER *pch = &m_arrCharacters[realCh]; const stbtt_bakedchar *pbch = &pBakedChars[i]; pch->x0 = pbch->x0; pch->x1 = pbch->x1; pch->y0 = pbch->y0; pch->y1 = pbch->y1; pch->xOffset = pbch->xoff; pch->yOffset = pbch->yoff; pch->xAdvance = pbch->xadvance; pch->TextureIndex = CurrentTextureIndex; pch->IsWhiteSpace = ( realCh == '\r' || realCh == '\n' || realCh == '\t' || realCh == ' ' ); } CurrentCharacter += nCharacters; delete[] pBakedChars; } delete[] pFontBytes; // write output textures for (i = 0; i < m_arrTextures.GetSize(); i++) { fileName.Format("%s_%u.dds", pOptions->OutputName.GetCharArray(), i); FileSystem::BuildOSPath(fileName); if ((pStream = FileSystem::OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE)) == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open output file '%s'", fileName.GetCharArray()); return false; } ddsWriter.Initialize(pStream); if (!ddsWriter.WriteHeader(DDS_TEXTURE_TYPE_2D, m_arrTextures[i].pf, CurTextureSize, CurTextureSize, 1, 1) || !ddsWriter.WriteMipLevel(0, m_arrTextures[i].pPixels, m_arrTextures[i].cbPixels) || !ddsWriter.Finalize()) { m_pProgressCallbacks->DisplayFormattedError("Failed to write DDS stream to '%s'", fileName.GetCharArray()); return false; } pStream->Release(); } // write output font file fileName.Format("%s.font", pOptions->OutputName.GetCharArray()); FileSystem::BuildOSPath(fileName); if ((pStream = FileSystem::OpenFile(fileName.GetCharArray(), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE)) == NULL) { m_pProgressCallbacks->DisplayFormattedModalError("Could not open output file '%s'", fileName.GetCharArray()); return false; } DF_FONT_HEADER outHeader; outHeader.Magic = DF_FONT_HEADER_MAGIC; outHeader.Size = sizeof(DF_FONT_HEADER); outHeader.FontHeight = pOptions->Height; outHeader.TextureCount = m_arrTextures.GetSize(); outHeader.FirstCharacter = FirstCharacter; outHeader.LastCharacter = LastCharacter; if (!pStream->Write2(&outHeader, sizeof(outHeader)) || !pStream->Write2(m_arrCharacters.GetBasePointer(), sizeof(DF_FONT_CHARACTER) * m_arrCharacters.GetSize())) { m_pProgressCallbacks->DisplayFormattedError("Could not write output file '%s'", fileName.GetCharArray()); pStream->Release(); return false; } pStream->Release(); return true; } #endif <file_sep>/Engine/Source/MathLib/Common.h #pragma once // Import YStdLib, possibly move SSE stuff to here? #include "YBaseLib/Common.h" #include "YBaseLib/Math.h" // Global stuff, this really should be moved elsewhere though... // this is intentionally the same as the cubemap order enum CUBE_FACE { CUBE_FACE_RIGHT, // 0: positive-x CUBE_FACE_LEFT, // 1: negative-x CUBE_FACE_BACK, // 2: positive-y CUBE_FACE_FRONT, // 3: negative-y CUBE_FACE_TOP, // 4: positive-z CUBE_FACE_BOTTOM, // 5: negative-z CUBE_FACE_COUNT, }; enum COORDINATE_SYSTEM { COORDINATE_SYSTEM_Y_UP_LH, COORDINATE_SYSTEM_Y_UP_RH, COORDINATE_SYSTEM_Z_UP_LH, COORDINATE_SYSTEM_Z_UP_RH, COORDINATE_SYSTEM_COUNT, }; <file_sep>/Engine/Source/Renderer/WorldRenderers/CubeMapShadowMapRenderer.h #pragma once #include "Renderer/Renderer.h" #include "Renderer/RenderQueue.h" class Camera; class RenderWorld; class CubeMapShadowMapRenderer { public: // shadow map data structure struct ShadowMapData { bool IsActive; GPUTextureCube *pShadowMapTexture; GPUDepthStencilBufferView *pShadowMapDSV[CUBE_FACE_COUNT]; }; public: CubeMapShadowMapRenderer(uint32 shadowMapResolution = 256, PIXEL_FORMAT shadowMapFormat = PIXEL_FORMAT_D16_UNORM); virtual ~CubeMapShadowMapRenderer(); const uint32 GetShadowMapResolution() const { return m_shadowMapResolution; } const PIXEL_FORMAT GetShadowMapFormat() const { return m_shadowMapFormat; } bool AllocateShadowMap(ShadowMapData *pShadowMapData); void FreeShadowMap(ShadowMapData *pShadowMapData); void DrawShadowMap(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); private: static void BuildCubeMapCamera(Camera *pCamera, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, CUBE_FACE face); uint32 m_shadowMapResolution; PIXEL_FORMAT m_shadowMapFormat; RenderQueue m_renderQueue; }; <file_sep>/Engine/Source/Renderer/WorldRenderers/SingleShaderWorldRenderer.h #pragma once #include "Renderer/WorldRenderer.h" class SingleShaderWorldRenderer : public WorldRenderer { public: SingleShaderWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~SingleShaderWorldRenderer(); virtual void DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) override; protected: // Set by derived classes. virtual void PreDraw(const ViewParameters *pViewParameters); virtual void DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); virtual void PostDraw(const ViewParameters *pViewParameters); // common params void SetCommonShaderProgramParameters(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram); private: void DrawOpqaueObjects(const ViewParameters *pViewParameters); void DrawPostProcessObjects(const ViewParameters *pViewParameters); void DrawTranslucentObjects(const ViewParameters *pViewParameters); }; <file_sep>/Engine/Source/Engine/InputManager.h #pragma once #include "Engine/Common.h" // #include "Engine/InputTypes.h" #include <SDL_keyboard.h> #include <SDL_mouse.h> #include <SDL_joystick.h> #include <SDL_gamecontroller.h> #include <SDL_events.h> class InputManager { public: enum EventType { EventType_Action, EventType_BinaryState, EventType_AxisState, EventType_NormalizedAxisState, EventType_Count, }; // these map to the 360 controller, with a few extras enum ControllerAxis { ControllerAxis_LeftStickX, ControllerAxis_LeftStickY, ControllerAxis_RightStickX, ControllerAxis_RightStickY, ControllerAxis_LeftTrigger, ControllerAxis_RightTrigger, ControllerAxis_Extra1, ControllerAxis_Extra2, ControllerAxis_Count, }; // same for buttons enum ControllerButton { ControllerButton_A, ControllerButton_B, ControllerButton_X, ControllerButton_Y, ControllerButton_LeftBumper, ControllerButton_RightBumper, ControllerButton_LeftStick, ControllerButton_RightStick, ControllerButton_DPadLeft, ControllerButton_DPadRight, ControllerButton_DPadUp, ControllerButton_DPadDown, ControllerButton_Back, ControllerButton_Start, ControllerButton_Guide, ControllerButton_Extra1, ControllerButton_Extra2, ControllerButton_Extra3, ControllerButton_Extra4, ControllerButton_Extra5, ControllerButton_Count, }; struct BaseEvent { BaseEvent(EventType type, const void *pOwner, const char *name, const char *description) : Type(type), pOwnerPointer(pOwner), Name(name), Description(description) {} virtual ~BaseEvent() {} EventType Type; const void *pOwnerPointer; String Name; String Description; }; struct ActionEvent : public BaseEvent { typedef Functor CallbackType; ActionEvent(const void *pOwner, const char *name, const char *description, CallbackType *callback) : BaseEvent(EventType_Action, pOwner, name, description), pCallback(callback) {} virtual ~ActionEvent() { delete pCallback; } CallbackType *pCallback; }; struct BinaryStateEvent : public BaseEvent { typedef FunctorA1<bool> CallbackType; BinaryStateEvent(const void *pOwner, const char *name, const char *description, CallbackType *callback) : BaseEvent(EventType_BinaryState, pOwner, name, description), pCallback(callback) {} virtual ~BinaryStateEvent() { delete pCallback; } CallbackType *pCallback; }; struct AxisStateEvent : public BaseEvent { typedef FunctorA1<int32> CallbackType; AxisStateEvent(const void *pOwner, const char *name, const char *description, CallbackType *callback) : BaseEvent(EventType_AxisState, pOwner, name, description), pCallback(callback) {} virtual ~AxisStateEvent() { delete pCallback; } CallbackType *pCallback; }; struct NormalizedAxisStateEvent : public BaseEvent { typedef FunctorA1<float> CallbackType; NormalizedAxisStateEvent(const void *pOwner, const char *name, const char *description, CallbackType *callback) : BaseEvent(EventType_NormalizedAxisState, pOwner, name, description), pCallback(callback) {} virtual ~NormalizedAxisStateEvent() { delete pCallback; } CallbackType *pCallback; }; // // for binds // enum MouseAxis // { // MouseAxis_X, // MouseAxis_Y, // MouseAxis_Count, // }; // enum MouseButton // { // MouseButton_Left, // MouseButton_Right, // MouseButton_Middle, // MouseButton_Aux1, // MouseButton_Aux2, // MouseButton_Aux3, // MouseButton_Aux4, // MouseButton_Aux5, // MouseButton_Aux6, // MouseButton_Aux7, // MouseButton_Aux8, // MouseButton_Aux9, // MouseButton_Count, // }; public: InputManager(); ~InputManager(); bool Startup(); void Shutdown(); // --- register events. pointer ownership is transferred to input manager. --- // Action event, executed once when button is pressed const ActionEvent *RegisterActionEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, ActionEvent::CallbackType *pCallback); // Binary state event, executed whenever the state changes const BinaryStateEvent *RegisterBinaryStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, BinaryStateEvent::CallbackType *pCallback); // Axis state, executed whenever the state changes const AxisStateEvent *RegisterAxisStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, AxisStateEvent::CallbackType *pCallback); // Normalized state, executed whenever the state changes const NormalizedAxisStateEvent *RegisterNormalizedAxisStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, NormalizedAxisStateEvent::CallbackType *pCallback); // Event lookup const BaseEvent *LookupEventByName(const char *eventName); // Deregister an event void UnregisterEvent(const BaseEvent *pEvent); bool UnregisterEvent(const char *eventName); // Deregister all events matching an owner void UnregisterEventsWithOwner(const void *pOwnerPointer); // Bind something to events, set eventName to null to unbind bool BindKeyboardKey(const char *bindSetName, const char *keyName, const char *eventName, int32 activateDirection = 0); bool BindMouseAxis(const char *bindSetName, uint32 axisIndex, const char *eventName, int32 bindDirection = 0); bool BindMouseButton(const char *bindSetName, uint32 buttonIndex, const char *eventName, int32 activateDirection = 0); bool BindControllerAxis(const char *bindSetName, uint32 controllerIndex, ControllerAxis axis, const char *eventName); bool BindControllerButton(const char *bindSetName, uint32 controllerIndex, ControllerButton button, const char *eventName, int32 activateDirection = 0); // Bind something to events, set eventName to null to unbind (operates on global bind set) bool BindKeyboardKey(const char *keyName, const char *eventName, int32 activateDirection = 0) { return BindKeyboardKey(nullptr, keyName, eventName, activateDirection); } bool BindMouseAxis(uint32 axisIndex, const char *eventName, int32 bindDirection = 0) { return BindMouseAxis(nullptr, axisIndex, eventName, bindDirection); } bool BindMouseButton(uint32 buttonIndex, const char *eventName, int32 activateDirection = 0) { return BindMouseButton(nullptr, buttonIndex, eventName, activateDirection); } bool BindControllerAxis(uint32 controllerIndex, ControllerAxis axis, const char *eventName) { return BindControllerAxis(nullptr, controllerIndex, axis, eventName); } bool BindControllerButton(uint32 controllerIndex, ControllerButton button, const char *eventName, int32 activateDirection = 0) { return BindControllerButton(nullptr, controllerIndex, button, eventName, activateDirection); } // Bind set switcher bool SwitchBindSet(const char *bindSetName); // SDL event handlers bool HandleSDLEvent(const void *pEvent); // Event blocker, prevents input manager from handling events temporarily void PushEventBlocker() { m_eventBlockerCount++; } void PopEventBlocker() { DebugAssert(m_eventBlockerCount > 0); m_eventBlockerCount--; } private: //bool OpenJoysticks(); void CloseJoysticks(); // event handlers bool HandleKeyboardEvent(const SDL_Event *pEvent); bool HandleMouseEvent(const SDL_Event *pEvent); bool HandleJoystickEvent(const SDL_Event *pEvent); bool HandleControllerEvent(const SDL_Event *pEvent); struct OpenJoystick { uint32 Index; int32 SDLJoystickIndex; SDL_Joystick *pSDLJoystick; }; struct OpenController { uint32 Index; int32 SDLJoystickIndex; SDL_GameController *pSDLGameController; // we track the last axis value, that way we can pass a relative value int16 LastAxisPositions[ControllerAxis_Count]; }; MemArray<OpenJoystick> m_joysticks; MemArray<OpenController> m_controllers; OpenJoystick *GetJoystickBySDLIndex(int32 index); OpenController *GetControllerBySDLIndex(int32 index); typedef CIStringHashTable<BaseEvent *> EventHashTable; EventHashTable m_events; struct KeyboardBind { uint32 SDLScanCode; String EventName; int32 ActivateDirection; String CommandString; }; struct MouseAxisBind { uint32 AxisIndex; int32 BindDirection; String EventName; }; struct MouseButtonBind { uint32 ButtonIndex; String EventName; int32 ActivateDirection; }; struct ControllerAxisBind { uint32 ControllerIndex; ControllerAxis Axis; String EventName; }; struct ControllerButtonBind { uint32 ControllerIndex; ControllerButton Button; String EventName; int32 ActivateDirection; }; struct BindSet { String Name; Array<KeyboardBind> KeyboardBinds; Array<MouseAxisBind> MouseAxisBinds; Array<MouseButtonBind> MouseButtonBinds; Array<ControllerAxisBind> ControllerAxisBinds; Array<ControllerButtonBind> ControllerButtonBinds; }; // global bind set BindSet m_globalBindSet; // bind set table BindSet *GetOrCreateBindSetByName(const char *bindSetName); typedef CIStringHashTable <BindSet *> BindSetTable; BindSetTable m_bindSets; // currently active bind set BindSet *m_pActiveBindSet; // blocker uint32 m_eventBlockerCount; }; extern InputManager *g_pInputManager; <file_sep>/Engine/Source/Core/BSPTree.h #ifndef __Y_YMAIN_BSPTREE_H #define __Y_YMAIN_BSPTREE_H #include "ymain/Common.h" // till custom classes are added #include <list> Y_NAMESPACE_BEGIN template<class T> struct BSPTreeBoundsTrait { inline static void GetBounds(const T &); } template<class T, class BOUNDSCLASS> class BSPTree { public: BSPTree() { m_root = NULL; } ~BSPTree() { } // remove all members from bsp tree void Clear() { if (m_root != NULL) { _Clear(m_root); m_root = NULL; } m_members.clear(); } private: // recursive clear void _Clear(Node *node) { // clear children if (node->child[0] != NULL) _Clear(node->child[0]); if (node->child[1] != NULL) _Clear(node->child[1]); // clear this ndoe delete node; } // forward declare internal types class Node; class Member; typedef std::list<Member *> MemberPtrList; typedef std::list<Member> MemberList; // member type struct Member { Node *node; T value; }; // node type class Node { uint8 splitAxis; float splitDistance; Node *child[2]; MemberPtrList members; }; // root node pointer Node *m_root; // all members MemberList m_members; };<file_sep>/Engine/Source/ResourceCompiler/CollisionShapeGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/Physics/CollisionShape.h" class XMLReader; class XMLWriter; class BinaryBlob; namespace Physics { class CollisionShapeGenerator { public: CollisionShapeGenerator(COLLISION_SHAPE_TYPE type = COLLISION_SHAPE_TYPE_TRIANGLE_MESH); ~CollisionShapeGenerator(); // Accessors const COLLISION_SHAPE_TYPE GetType() const { return m_type; } void SetType(COLLISION_SHAPE_TYPE type); // Box functions const float3 &GetBoxCenter() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_BOX); return m_boxCenter; } const float3 &GetBoxExtents() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_BOX); return m_boxHalfExtents; } void SetBoxCenter(const float3 &center) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_BOX); m_boxCenter = center; } void SetBoxHalfExtents(const float3 &halfExtents) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_BOX); m_boxHalfExtents = halfExtents; } // Sphere functions const float3 &GetSphereCenter() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_SPHERE); return m_sphereCenter; } const float GetSphereRadius() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_SPHERE); return m_sphereRadius; } void SetSphereCenter(const float3 &center) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_SPHERE); m_sphereCenter = center; } void SetSphereRadius(const float radius) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_SPHERE); m_sphereRadius = radius; } // Triangle mesh building functions const uint32 GetTriangleCount() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_TRIANGLE_MESH); return m_triangleMeshTriangles.GetSize(); } void AddTriangle(const float3 &v0, const float3 &v1, const float3 &v2); // Convex hull building functions const uint32 GetConvexHullVertexCount() const { DebugAssert(m_type == COLLISION_SHAPE_TYPE_CONVEX_HULL); return m_convexHullVertices.GetSize(); } void AddConvexHullVertex(const float3 &v); // Conversion functions // These functions all operate on a mesh that is currently a triangle mesh. void ConvertToBox(); void ConvertToSphere(); void ConvertToConvexHull(); // Loading/saving to XML bool LoadFromXML(XMLReader &xmlReader); bool SaveToXML(XMLWriter &xmlWriter) const; // Compiling bool Compile(BinaryBlob **ppOutputBlob) const; // copying void Copy(const CollisionShapeGenerator *pGenerator); // applying a transform bool ApplyTransform(const Transform &transform); bool ApplyTransform(const float4x4 &transformMatrix); private: struct TriangleMeshTriangle { float3 VertexPositions[3]; }; typedef MemArray<TriangleMeshTriangle> TriangleMeshTriangleArray; typedef MemArray<float3> ConvexHullVertexArray; COLLISION_SHAPE_TYPE m_type; // BOX float3 m_boxCenter; float3 m_boxHalfExtents; // SPHERE float3 m_sphereCenter; float m_sphereRadius; // TRIANGLE MESH TriangleMeshTriangleArray m_triangleMeshTriangles; // CONVEX HULL ConvexHullVertexArray m_convexHullVertices; DeclareNonCopyable(CollisionShapeGenerator); }; }; <file_sep>/Engine/Source/Renderer/WorldRenderers/FullBrightWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/FullBrightWorldRenderer.h" #include "Renderer/RenderQueue.h" #include "Renderer/RenderProxy.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Shaders/FullBrightShader.h" #include "Engine/Material.h" FullBrightWorldRenderer::FullBrightWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : SingleShaderWorldRenderer(pGPUContext, pOptions) { } FullBrightWorldRenderer::~FullBrightWorldRenderer() { } void FullBrightWorldRenderer::DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { ShaderProgram *pShaderProgram; if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(FullBrightShader), 0, pQueueEntry)) == NULL) return; m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); m_pGPUContext->SetRasterizerState(pQueueEntry->pMaterial->GetShader()->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pQueueEntry->pMaterial->GetShader()->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } <file_sep>/Editor/Source/Editor/ResourceBrowser/moc_EditorResourceBrowserWidget.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorResourceBrowserWidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorResourceBrowserWidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorResourceBrowserWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorResourceBrowserWidget_t { QByteArrayData data[16]; char stringdata[451]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorResourceBrowserWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorResourceBrowserWidget_t qt_meta_stringdata_EditorResourceBrowserWidget = { { QT_MOC_LITERAL(0, 0, 27), // "EditorResourceBrowserWidget" QT_MOC_LITERAL(1, 28, 30), // "OnActionDirectoryBackTriggered" QT_MOC_LITERAL(2, 59, 0), // "" QT_MOC_LITERAL(3, 60, 28), // "OnActionDirectoryUpTriggered" QT_MOC_LITERAL(4, 89, 29), // "OnActionNewDirectoryTriggered" QT_MOC_LITERAL(5, 119, 31), // "OnActionDeleteResourceTriggered" QT_MOC_LITERAL(6, 151, 33), // "OnActionImportStaticMeshTrigg..." QT_MOC_LITERAL(7, 185, 31), // "OnActionInsertResourceTriggered" QT_MOC_LITERAL(8, 217, 30), // "OnActionEditBlockMeshTriggered" QT_MOC_LITERAL(9, 248, 33), // "OnActionEditSkeletalMeshTrigg..." QT_MOC_LITERAL(10, 282, 38), // "OnActionEditSkeletalAnimation..." QT_MOC_LITERAL(11, 321, 31), // "OnActionEditStaticMeshTriggered" QT_MOC_LITERAL(12, 353, 37), // "OnDirectoryTreeItemClickedOrA..." QT_MOC_LITERAL(13, 391, 5), // "index" QT_MOC_LITERAL(14, 397, 25), // "OnResourceListItemClicked" QT_MOC_LITERAL(15, 423, 27) // "OnResourceListItemActivated" }, "EditorResourceBrowserWidget\0" "OnActionDirectoryBackTriggered\0\0" "OnActionDirectoryUpTriggered\0" "OnActionNewDirectoryTriggered\0" "OnActionDeleteResourceTriggered\0" "OnActionImportStaticMeshTriggered\0" "OnActionInsertResourceTriggered\0" "OnActionEditBlockMeshTriggered\0" "OnActionEditSkeletalMeshTriggered\0" "OnActionEditSkeletalAnimationTriggered\0" "OnActionEditStaticMeshTriggered\0" "OnDirectoryTreeItemClickedOrActivated\0" "index\0OnResourceListItemClicked\0" "OnResourceListItemActivated" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorResourceBrowserWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 13, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 79, 2, 0x08 /* Private */, 3, 0, 80, 2, 0x08 /* Private */, 4, 0, 81, 2, 0x08 /* Private */, 5, 0, 82, 2, 0x08 /* Private */, 6, 0, 83, 2, 0x08 /* Private */, 7, 0, 84, 2, 0x08 /* Private */, 8, 0, 85, 2, 0x08 /* Private */, 9, 0, 86, 2, 0x08 /* Private */, 10, 0, 87, 2, 0x08 /* Private */, 11, 0, 88, 2, 0x08 /* Private */, 12, 1, 89, 2, 0x08 /* Private */, 14, 1, 92, 2, 0x08 /* Private */, 15, 1, 95, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QModelIndex, 13, QMetaType::Void, QMetaType::QModelIndex, 13, QMetaType::Void, QMetaType::QModelIndex, 13, 0 // eod }; void EditorResourceBrowserWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorResourceBrowserWidget *_t = static_cast<EditorResourceBrowserWidget *>(_o); switch (_id) { case 0: _t->OnActionDirectoryBackTriggered(); break; case 1: _t->OnActionDirectoryUpTriggered(); break; case 2: _t->OnActionNewDirectoryTriggered(); break; case 3: _t->OnActionDeleteResourceTriggered(); break; case 4: _t->OnActionImportStaticMeshTriggered(); break; case 5: _t->OnActionInsertResourceTriggered(); break; case 6: _t->OnActionEditBlockMeshTriggered(); break; case 7: _t->OnActionEditSkeletalMeshTriggered(); break; case 8: _t->OnActionEditSkeletalAnimationTriggered(); break; case 9: _t->OnActionEditStaticMeshTriggered(); break; case 10: _t->OnDirectoryTreeItemClickedOrActivated((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 11: _t->OnResourceListItemClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 12: _t->OnResourceListItemActivated((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorResourceBrowserWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorResourceBrowserWidget.data, qt_meta_data_EditorResourceBrowserWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorResourceBrowserWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorResourceBrowserWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorResourceBrowserWidget.stringdata)) return static_cast<void*>(const_cast< EditorResourceBrowserWidget*>(this)); return QWidget::qt_metacast(_clname); } int EditorResourceBrowserWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 13) qt_static_metacall(this, _c, _id, _a); _id -= 13; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 13) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 13; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Editor/Source/Editor/EditorResourceSelectionDialogModel.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourceSelectionDialogModel.h" #include "Editor/EditorResourcePreviewGenerator.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Engine/ResourceManager.h" #include "Core/Image.h" Log_SetChannel(EditorResourceSelectionDialog); EditorResourceSelectionDialogModel::DirectoryNode::DirectoryNode(EditorResourceSelectionDialogModel *pModel, const String &rootPath) : m_pModel(pModel), m_pParent(NULL), m_fullName(rootPath), m_pResourceType(NULL), m_populated(false) { } EditorResourceSelectionDialogModel::DirectoryNode::DirectoryNode(EditorResourceSelectionDialogModel *pModel, DirectoryNode *pParent) : m_pModel(pModel), m_pParent(pParent), m_pResourceType(NULL), m_populated(false) { } EditorResourceSelectionDialogModel::DirectoryNode::~DirectoryNode() { for (uint32 i = 0; i < m_children.GetSize(); i++) delete m_children[i]; } void EditorResourceSelectionDialogModel::DirectoryNode::Populate() { DebugAssert(!m_populated); DebugAssert(m_pResourceType == NULL); PathString filename; PathString resourceName; FileSystem::FindResultsArray findResults; if (g_pVirtualFileSystem->FindFiles(m_fullName, "*", FILESYSTEM_FIND_FOLDERS | FILESYSTEM_FIND_FILES | FILESYSTEM_FIND_RELATIVE_PATHS | FILESYSTEM_FIND_HIDDEN_FILES, &findResults)) { uint32 i; for (i = 0; i < findResults.GetSize(); i++) { const FILESYSTEM_FIND_DATA *pFindData = &findResults[i]; if (m_fullName.GetLength() == 0) filename = pFindData->FileName; else filename.Format("%s/%s", m_fullName.GetCharArray(), pFindData->FileName); if (pFindData->Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY) { // skip over directories? if (!m_pModel->GetIncludeDirectories()) continue; DirectoryNode *pNode = new DirectoryNode(m_pModel, this); pNode->m_displayName = pFindData->FileName; pNode->m_fullName = filename; pNode->m_modifiedTime = pFindData->ModificationTime; m_children.Add(pNode); } else { // skip over anything that could be a resource if requested if (!m_pModel->GetIncludeResources()) continue; // determine the type of resource ByteStream *pStream = g_pVirtualFileSystem->OpenFile(filename, BYTESTREAM_OPEN_READ); if (pStream == NULL) continue; const ResourceTypeInfo *pResourceTypeInfo = g_pResourceManager->GetResourceTypeForStream(filename, pStream, resourceName); pStream->Release(); // got resource type? if (pResourceTypeInfo == NULL || !m_pModel->ShouldIncludeResourceType(pResourceTypeInfo)) continue; // ensure it doesn't already exist uint32 j; for (j = 0; j < m_children.GetSize(); j++) { if (m_children[j]->m_fullName.CompareInsensitive(resourceName) && m_children[j]->m_pResourceType == pResourceTypeInfo) break; } DirectoryNode *pNode; if (j != m_children.GetSize()) { if (m_children[j]->m_modifiedTime >= pFindData->ModificationTime) continue; pNode = m_children[j]; } else { pNode = new DirectoryNode(m_pModel, this); m_children.Add(pNode); } // create node pNode->m_displayName = resourceName.SubString(resourceName.RFind('/') + 1); pNode->m_fullName = resourceName; pNode->m_pResourceType = pResourceTypeInfo; pNode->m_modifiedTime = pFindData->ModificationTime; } } } m_populated = true; } EditorResourceSelectionDialogModel::EditorResourceSelectionDialogModel(const String &rootPath, bool includeDirectories /* = true */, bool includeResources /* = true */, uint32 previewIconSize /* = 0 */, QWidget *pParent /* = NULL */) : QAbstractItemModel(pParent), m_rootPath(rootPath), m_includeDirectories(includeDirectories), m_includeResources(includeResources), m_previewIconSize(previewIconSize), m_ppResourceTypeInfoFilter(NULL), m_nResourceTypeInfoFilters(0) { m_pRootNode = new DirectoryNode(this, rootPath); } EditorResourceSelectionDialogModel::~EditorResourceSelectionDialogModel() { delete m_pRootNode; } EditorResourceSelectionDialogModel::DirectoryNode *EditorResourceSelectionDialogModel::InternalGetDirectoryNode(const QModelIndex &index) const { DirectoryNode *pDirectoryNode = reinterpret_cast<DirectoryNode *>(index.internalPointer()); DebugAssert(pDirectoryNode != NULL); return pDirectoryNode; } void EditorResourceSelectionDialogModel::SetResourceFilter(const ResourceTypeInfo **pResourceTypeInfo, uint32 nResourceTypeInfos) { m_ppResourceTypeInfoFilter = pResourceTypeInfo; m_nResourceTypeInfoFilters = nResourceTypeInfos; } bool EditorResourceSelectionDialogModel::ShouldIncludeResourceType(const ResourceTypeInfo *pResourceTypeInfo) { if (m_nResourceTypeInfoFilters == 0) return true; for (uint32 i = 0; i < m_nResourceTypeInfoFilters; i++) { if (m_ppResourceTypeInfoFilter[i] == pResourceTypeInfo) return true; } return false; } const EditorResourceSelectionDialogModel::DirectoryNode *EditorResourceSelectionDialogModel::GetDirectoryNodeForIndex(const QModelIndex &index) const { if (!index.isValid()) return NULL; return InternalGetDirectoryNode(index); } QModelIndex EditorResourceSelectionDialogModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex()*/) const { if (!hasIndex(row, column, parent)) return QModelIndex(); DirectoryNode *pParentItem; if (!parent.isValid()) pParentItem = m_pRootNode; else pParentItem = InternalGetDirectoryNode(parent); if ((uint32)row >= pParentItem->GetChildren().GetSize()) return QModelIndex(); else return createIndex(row, column, reinterpret_cast<void *>(pParentItem->GetChildren()[row])); } QModelIndex EditorResourceSelectionDialogModel::parent(const QModelIndex &child) const { if (!child.isValid()) return QModelIndex(); DirectoryNode *pDirectoryNode = InternalGetDirectoryNode(child); DirectoryNode *pParentNode = pDirectoryNode->GetParent(); if (pParentNode == m_pRootNode) return QModelIndex(); uint32 row; const PODArray<DirectoryNode *> &childrenArray = pParentNode->GetChildren(); for (row = 0; row < childrenArray.GetSize(); row++) { if (childrenArray[row] == pDirectoryNode) break; } return createIndex(row, 0, reinterpret_cast<void *>(pParentNode)); } int EditorResourceSelectionDialogModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return 0; if (!parent.isValid()) { if (!m_pRootNode->IsPopulated()) m_pRootNode->Populate(); return m_pRootNode->GetChildren().GetSize(); } DirectoryNode *pDirectoryNode = InternalGetDirectoryNode(parent); if (pDirectoryNode->IsDirectory() && !pDirectoryNode->IsPopulated()) pDirectoryNode->Populate(); return pDirectoryNode->GetChildren().GetSize(); } int EditorResourceSelectionDialogModel::columnCount(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return 0; return 3; } QVariant EditorResourceSelectionDialogModel::headerData(int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/) const { if (orientation == Qt::Horizontal) { if (role != Qt::DisplayRole) return QVariant(); switch (section) { case 0: return tr("Name"); case 1: return tr("Type"); case 2: return tr("Date Modified"); default: return QVariant(); } } return QAbstractItemModel::headerData(section, orientation, role); } bool EditorResourceSelectionDialogModel::hasChildren(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return false; if (!parent.isValid()) return true; DirectoryNode *pDirectoryNode = InternalGetDirectoryNode(parent); return pDirectoryNode->IsDirectory(); } QVariant EditorResourceSelectionDialogModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole*/) const { if (!index.isValid()) return QVariant(); DirectoryNode *pDirectoryNode = InternalGetDirectoryNode(index); if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return QVariant(pDirectoryNode->GetDisplayName()); case 1: return QVariant((pDirectoryNode->GetResourceTypeInfo() != NULL) ? pDirectoryNode->GetResourceTypeInfo()->GetTypeName() : "Directory"); case 2: return QVariant(pDirectoryNode->GetModifiedTime().ToString("%Y-%m-%d %H:%M:%S")); default: return QVariant(); } } else if (role == Qt::DecorationRole) { switch (index.column()) { case 0: { if (pDirectoryNode->GetResourceTypeInfo() != NULL) { if (m_previewIconSize > 0) { // generate a preview icon Image previewImage; previewImage.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, m_previewIconSize, m_previewIconSize, 1); // actually generate it EditorResourcePreviewGenerator generator; generator.SetGPUContext(g_pRenderer->GetGPUContext()); if (generator.GenerateResourcePreview(&previewImage, pDirectoryNode->GetResourceTypeInfo(), pDirectoryNode->GetFullName())) { // return an icon from this QPixmap pixmap; if (EditorHelpers::ConvertImageToQPixmap(previewImage, &pixmap)) return pixmap; else return QVariant(); } else { // error... //Y_memzero(previewImage.GetData(), previewImage.GetDataSize()); return QVariant(); } } else { // use resource icon return g_pEditor->GetIconLibrary()->GetIconForResourceType(pDirectoryNode->GetResourceTypeInfo()); } } else { // folders can't have any preview generated... return g_pEditor->GetIconLibrary()->GetListViewDirectoryIcon(); } } break; } } return QVariant(); } <file_sep>/Engine/Source/Engine/Physics/BoxCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/BoxCollisionShape.h" #include "Engine/Physics/BulletHeaders.h" Log_SetChannel(BoxCollisionShape); namespace Physics { BoxCollisionShape::BoxCollisionShape() : m_bounds(AABox::Zero), m_center(float3::Zero), m_halfExtents(float3::Zero), m_pBulletShape(nullptr) { } BoxCollisionShape::BoxCollisionShape(const float3 &boxCenter, const float3 &halfExtents) { m_bounds.SetBounds(boxCenter - halfExtents, boxCenter + halfExtents); m_center = boxCenter; m_halfExtents = halfExtents; m_pBulletShape = new btBoxShape(Float3ToBulletVector(halfExtents)); } BoxCollisionShape::~BoxCollisionShape() { delete m_pBulletShape; } const COLLISION_SHAPE_TYPE BoxCollisionShape::GetType() const { return COLLISION_SHAPE_TYPE_BOX; } const AABox & BoxCollisionShape::GetLocalBoundingBox() const { return m_bounds; } bool BoxCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { AutoReleasePtr<ByteStream> pStream = ByteStream_CreateReadOnlyMemoryStream(pData, dataSize); return LoadFromStream(pStream, dataSize); } bool BoxCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { // check size if (dataSize != (sizeof(float3) + sizeof(float3))) return false; BinaryReader binaryReader(pStream); binaryReader >> m_center >> m_halfExtents; if (binaryReader.GetErrorState()) return false; m_bounds.SetBounds(m_center - m_halfExtents, m_center + m_halfExtents); delete m_pBulletShape; m_pBulletShape = new btBoxShape(SIMDVector3fToBulletVector(m_halfExtents)); return true; } CollisionShape *BoxCollisionShape::CreateScaledShape(const float3 &scale) const { // straight up create a new shape, memory's gonna be the same anyway return new BoxCollisionShape(m_center, SIMDVector3f(m_halfExtents) * SIMDVector3f(scale)); } void BoxCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { // if we have a nonzero center, this has to be transformed prior to the world transform if (m_center.SquaredLength() > 0.0f) //worldTransform = worldTransform * btTransform(btMatrix3x3::getIdentity(), Float3ToBulletVector(m_center)); worldTransform.setOrigin(worldTransform.getOrigin() + Float3ToBulletVector(m_center)); } void BoxCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { // if we have a nonzero center, this has to be transformed prior to the world transform if (m_center.SquaredLength() > 0.0f) //worldTransform = worldTransform * btTransform(btMatrix3x3::getIdentity(), Float3ToBulletVector(m_center)); worldTransform.setOrigin(worldTransform.getOrigin() - Float3ToBulletVector(m_center)); } btCollisionShape *BoxCollisionShape::GetBulletShape() const { DebugAssert(m_pBulletShape != nullptr); return m_pBulletShape; } } // namespace Physics <file_sep>/Engine/Source/Engine/BlockMeshBuilder.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/BlockMeshVolume.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" //Log_SetChannel(BlockMeshBuilder); enum BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT { // For lighting BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_LEFT = (1 << 6), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE = (1 << 7), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_RIGHT = (1 << 8), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT = (1 << 9), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT = (1 << 10), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_LEFT = (1 << 11), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE = (1 << 12), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_RIGHT = (1 << 13), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_LEFT = (1 << 14), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE = (1 << 15), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_RIGHT = (1 << 16), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT = (1 << 17), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT = (1 << 18), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_LEFT = (1 << 19), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE = (1 << 20), BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_RIGHT = (1 << 21), }; const uint32 MATERIAL_INDEX_SHADOW_BIT_MASK = ((uint32)1 << 31); const uint32 MATERIAL_INDEX_SHADOW_BIT_SET = ((uint32)1 << 31); const uint32 MATERIAL_INDEX_MASK = ~((uint32)1 << 31); BlockMeshBuilder::BlockMeshBuilder() : m_pPalette(NULL), m_width(0), m_length(0), m_height(0), m_pBlockData(NULL), m_translation(float3::Zero), m_scale(1.0f), m_ambientOcclusion(false), m_outputVertexFactoryFlags(0), m_outputBoundingBox(AABox::Zero), m_outputBoundingSphere(Sphere::Zero) { Y_memzero(m_pNeighbourBlockData, sizeof(m_pNeighbourBlockData)); } BlockMeshBuilder::~BlockMeshBuilder() { } void BlockMeshBuilder::SetFromVolume(const BlockMeshVolume *pVolume) { m_width = pVolume->GetWidth(); m_length = pVolume->GetLength(); m_height = pVolume->GetHeight(); m_pBlockData = pVolume->GetData(); m_translation = float3((float)pVolume->GetMinCoordinates().x, (float)pVolume->GetMinCoordinates().y, (float)pVolume->GetMinCoordinates().z) * pVolume->GetScale(); m_scale = pVolume->GetScale(); if (pVolume->GetPalette() != NULL) m_pPalette = pVolume->GetPalette(); } const BlockVolumeBlockType BlockMeshBuilder::GetBlockValueAt(uint32 x, uint32 y, uint32 z) const { DebugAssert(x < m_width && y < m_length && z < m_height); return m_pBlockData[(z * m_width * m_length) + (y * m_width) + x]; } const BlockVolumeBlockType BlockMeshBuilder::GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME neighbour, uint32 x, uint32 y, uint32 z) const { DebugAssert(neighbour < NEIGHBOUR_VOLUME_COUNT); if (m_pNeighbourBlockData[neighbour] == nullptr) return 0; DebugAssert(x < m_width && y < m_length && z < m_height); return m_pNeighbourBlockData[neighbour][(z * m_width * m_length) + (y * m_width) + x]; } const bool BlockMeshBuilder::IsVisibleBlockAt(uint32 x, uint32 y, uint32 z) const { BlockVolumeBlockType blockTypeId = GetBlockValueAt(x, y, z); const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockTypeId); return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) != 0; } const bool BlockMeshBuilder::IsVisibleNonTransparentBlockAt(uint32 x, uint32 y, uint32 z) const { BlockVolumeBlockType blockTypeId = GetBlockValueAt(x, y, z); const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockTypeId); return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE && !(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE)); } const bool BlockMeshBuilder::HasCubeLightBlockingBlockAt(uint32 x, uint32 y, uint32 z) const { BlockVolumeBlockType blockValue = GetBlockValueAt(x, y, z); if (blockValue == 0) return false; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) != 0; } const bool BlockMeshBuilder::HasCubeVisibilityBlockingBlockAt(const BlockPalette::BlockType *pVolumeBlockType, int32 x, int32 y, int32 z) const { BlockVolumeBlockType blockValue = 0; int32 width = (int32)m_width; int32 length = (int32)m_length; int32 height = (int32)m_height; // can handle one direction of negativeness if (x < 0) blockValue = (y >= 0 && z >= 0 && y < length && z < height) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_LEFT, m_width - 1, y, z) : 0; else if (x == width) blockValue = (y >= 0 && z >= 0 && y < length && z < height) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_RIGHT, 0, y, z) : 0; else if (y < 0) blockValue = (x >= 0 && z >= 0 && x < width && z < height) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_BACK, x, m_length - 1, z) : 0; else if (y == length) blockValue = (x >= 0 && z >= 0 && x < width && z < height) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_FRONT, x, 0, z) : 0; else if (z < 0) blockValue = (x >= 0 && y >= 0 && x < width && y < length) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_BOTTOM, x, y, m_height - 1) : 0; else if (z == height) blockValue = (x >= 0 && y >= 0 && x < width && y < length) ? GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_TOP, x, y, 0) : 0; else blockValue = GetBlockValueAt((uint32)x, (uint32)y, (uint32)z); if (blockValue == 0) return false; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); // is volume and next to each other if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME && blockValue == pVolumeBlockType->BlockTypeIndex) return true; // is not cube if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; // or visibility-blocking/solid if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) return true; return false; } const uint32 BlockMeshBuilder::CalculateCubeVertexColor(const BlockPalette::BlockType *pBlockType, const uint32 vertexIndex, const uint32 blockData, uint32 faceColor) { float4 outVertexColor; // start by taking the face colour outVertexColor = float4(float(faceColor & 0xFF), float((faceColor >> 8) & 0xFF), float((faceColor >> 16) & 0xFF), float((faceColor >> 24) & 0xFF)) / 255.0f; // calculate the vertex AO if (!(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME)) { uint32 lightLevel = 4; switch (vertexIndex) { case 0: // top back left lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE) != 0) ? 1 : 0; break; case 1: // top back right lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE) != 0) ? 1 : 0; break; case 2: // top front left lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE) != 0) ? 1 : 0; break; case 3: // top front right lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE) != 0) ? 1 : 0; break; case 4: // bottom back left lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE) != 0) ? 1 : 0; break; case 5: // bottom back right lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE) != 0) ? 1 : 0; break; case 6: // bottom front left lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_LEFT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE) != 0) ? 1 : 0; break; case 7: // bottom front right lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_RIGHT) != 0) ? 1 : 0; lightLevel -= ((blockData & BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE) != 0) ? 1 : 0; break; } // multiply that static const float lightLevels[5] = { 0.0f, 0.4f, 0.6f, 0.8f, 1.0f }; outVertexColor *= float4(lightLevels[lightLevel], lightLevels[lightLevel], lightLevels[lightLevel], 1.0f); } // return vertex colour { uint8 r, g, b, a; r = (uint8)Math::Clamp(outVertexColor.r * 255.0f, 0.0f, 255.0f); g = (uint8)Math::Clamp(outVertexColor.g * 255.0f, 0.0f, 255.0f); b = (uint8)Math::Clamp(outVertexColor.b * 255.0f, 0.0f, 255.0f); a = (uint8)Math::Clamp(outVertexColor.a * 255.0f, 0.0f, 255.0f); return MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a); } } #define BLOCK_VALUE_ARRAY_ACCESS(x, y, z) m_pBlockData[(z) * zStride + (y) * yStride + (x)] #define BLOCK_DATA_ARRAY_ACCESS(x, y, z) pBlockDataArray[(z) * zStride + (y) * yStride + (x)] #define BLOCK_WORLD_COORDINATES(x, y, z) (SIMDVector3f((float)x, (float)y, (float)z) * blockScale + basePosition) void BlockMeshBuilder::GenerateBlocks(float3 &outMinBounds, float3 &outMaxBounds) { static const uint32 ALL_FACES_ALLOCATED_MASK = 0x3F; const float blockScale = m_scale; const uint32 yStride = m_width; const uint32 zStride = yStride * m_length; const BlockPalette::BlockType *pBlockType; BlockVolumeBlockType blockValue, searchBlockValue; uint32 blockData, searchBlockData; bool tileMismatchedData; uint32 x, y, z; SIMDVector3f basePosition(m_translation); uint32 *pBlockDataArray = new uint32[m_width * m_length * m_height]; uint32 meshSizes[3] = { m_width, m_length, m_height }; bool isEdgeZBlockPos, isEdgeZBlockNeg; bool isEdgeYBlockPos, isEdgeYBlockNeg; bool isEdgeXBlockPos, isEdgeXBlockNeg; // strip out faces that have blocks adjacent to them. for (z = 0; z < m_height; z++) { isEdgeZBlockNeg = (z == 0); isEdgeZBlockPos = (z == (m_height - 1)); for (y = 0; y < m_length; y++) { isEdgeYBlockNeg = (y == 0); isEdgeYBlockPos = (y == (m_length - 1)); for (x = 0; x < m_width; x++) { isEdgeXBlockNeg = (x == 0); isEdgeXBlockPos = (x == (m_width - 1)); // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0) { BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; continue; } pBlockType = m_pPalette->GetBlockType(blockValue); if (!(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE)) { BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; continue; } if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // get block data blockData = ALL_FACES_ALLOCATED_MASK; // Culling values if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x + 1, (int32)y + 0, (int32)z + 0)) { blockData &= ~(1 << CUBE_FACE_RIGHT); } if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x - 1, (int32)y + 0, (int32)z + 0)) { blockData &= ~(1 << CUBE_FACE_LEFT); } if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x + 0, (int32)y + 1, (int32)z + 0)) { blockData &= ~(1 << CUBE_FACE_BACK); } if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x + 0, (int32)y - 1, (int32)z + 0)) { blockData &= ~(1 << CUBE_FACE_FRONT); } if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x + 0, (int32)y + 0, (int32)z + 1)) { blockData &= ~(1 << CUBE_FACE_TOP); } if (HasCubeVisibilityBlockingBlockAt(pBlockType, (int32)x + 0, (int32)y + 0, (int32)z - 1)) { blockData &= ~(1 << CUBE_FACE_BOTTOM); } // work out the block data if (m_ambientOcclusion) { if (!isEdgeZBlockNeg) { if (!isEdgeYBlockNeg) { blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 0, y - 1, z - 1) << 20; // bottom-front-middle if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y - 1, z - 1) << 19; // bottom-front-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y - 1, z - 1) << 21; // bottom-front-right } if (!isEdgeYBlockPos) { blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 0, y + 1, z - 1) << 15; // bottom-back-middle if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y + 1, z - 1) << 14; // bottom-back-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y + 1, z - 1) << 16; // bottom-back-right } if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y + 0, z - 1) << 17; // bottom-middle-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y + 0, z - 1) << 18; // bottom-middle-right } if (!isEdgeZBlockPos) { if (!isEdgeYBlockNeg) { blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 0, y - 1, z + 1) << 12; // top-front-middle if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y - 1, z + 1) << 11; // top-front-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y - 1, z + 1) << 13; // top-front-right } if (!isEdgeYBlockPos) { blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 0, y + 1, z + 1) << 7; // top-back-middle if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y + 1, z + 1) << 6; // top-back-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y + 1, z + 1) << 8; // top-back-right } if (!isEdgeXBlockNeg) blockData |= (uint32)HasCubeLightBlockingBlockAt(x - 1, y + 0, z + 1) << 9; // top-middle-left if (!isEdgeXBlockPos) blockData |= (uint32)HasCubeLightBlockingBlockAt(x + 1, y + 0, z + 1) << 10; // top-middle-right } } // store face mask BLOCK_DATA_ARRAY_ACCESS(x, y, z) = blockData; } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { // planes get set to 0 when generated BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 1; } else { // mark all faces as generated, so we don't come back to them BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; } } } } for (z = 0; z < m_height; z++) { for (y = 0; y < m_length; y++) { for (x = 0; x < m_width; x++) { // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0 || (pBlockType = m_pPalette->GetBlockType(blockValue))->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE) continue; // get block data blockData = BLOCK_DATA_ARRAY_ACCESS(x, y, z); // switch shape type if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { tileMismatchedData = (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) != 0; //tileMismatchedData = true; //tileMismatchedData = false; // generate each face for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { uint32 currentFaceMask = (1 << faceIndex); if ((blockData & currentFaceMask) == 0) continue; // determine which axis to sweep uint32 sliceAxis = 0, sweepAxis0 = 0, sweepAxis1 = 0; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: sliceAxis = 0; sweepAxis0 = 1; sweepAxis1 = 2; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: sliceAxis = 1; sweepAxis0 = 0; sweepAxis1 = 2; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: sliceAxis = 2; sweepAxis0 = 1; sweepAxis1 = 0; break; } // mask of lighting bits that we care about for this face static const uint32 faceLightingMatchMasks[CUBE_FACE_COUNT] = { // CUBE_FACE_RIGHT BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE, // CUBE_FACE_LEFT BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE, // CUBE_FACE_BACK BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_RIGHT, // CUBE_FACE_FRONT BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_RIGHT, // CUBE_FACE_TOP BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_BACK_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_TOP_FRONT_RIGHT, // CUBE_FACE_BOTTOM BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_BACK_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_LEFT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_MIDDLE | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_MIDDLE_RIGHT | BLOCK_MESH_BLOCK_DATA_NEIGHBOUR_PRESENT_BOTTOM_FRONT_RIGHT, }; // get the lighting bit mask uint32 faceLightingMatchMask = faceLightingMatchMasks[faceIndex]; uint32 faceLightingMask = blockData & faceLightingMatchMask; // determine the quad boundaries by sweeping each axis, then in reverse uint32 baseCoordinates[3]; uint32 blockCoordinates[3]; uint32 quadBoundaries[2][3]; uint32 i, j, k; #if 1 // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundaries[0], baseCoordinates, sizeof(quadBoundaries[0])); Y_memcpy(&quadBoundaries[1], baseCoordinates, sizeof(quadBoundaries[1])); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... { // axis 0 for (i = quadBoundaries[0][sweepAxis0] + 1; i < meshSizes[sweepAxis0]; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { quadBoundaries[1][sweepAxis0]++; continue; } else { break; } } // axis 1 for (i = quadBoundaries[0][sweepAxis1] + 1; i < meshSizes[sweepAxis1]; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundaries[0][sweepAxis0]; j <= quadBoundaries[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundaries[1][sweepAxis1]++; else break; } } #elif 0 int32 quadBoundariesForward[2][3]; int32 quadBoundariesReverse[2][3]; // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundariesForward[0], baseCoordinates, sizeof(quadBoundariesForward[0])); Y_memcpy(&quadBoundariesForward[1], baseCoordinates, sizeof(quadBoundariesForward[1])); Y_memcpy(quadBoundariesReverse, quadBoundariesForward, sizeof(quadBoundariesReverse)); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... { // axis 0 for (i = quadBoundariesForward[0][sweepAxis0] + 1; i < meshSizes[sweepAxis0]; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { quadBoundariesForward[1][sweepAxis0]++; continue; } else { break; } } // axis 1 for (i = quadBoundariesForward[0][sweepAxis1] + 1; i < meshSizes[sweepAxis1]; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundariesForward[0][sweepAxis0]; j <= quadBoundariesForward[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundariesForward[1][sweepAxis1]++; else break; } } // reverse { // axis 0 for (i = quadBoundariesReverse[0][sweepAxis1] + 1; i < meshSizes[sweepAxis0]; i++) { blockCoordinates[sweepAxis0] = baseCoordinates[sweepAxis0]; blockCoordinates[sweepAxis1] = i; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { quadBoundariesReverse[1][sweepAxis1]++; continue; } else { break; } } // axis 1 for (i = quadBoundariesReverse[0][sweepAxis0] + 1; i < meshSizes[sweepAxis1]; i++) { blockCoordinates[sweepAxis0] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundariesReverse[0][sweepAxis1]; j <= quadBoundariesReverse[1][sweepAxis1]; j++) { blockCoordinates[sweepAxis1] = j; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask) && (tileMismatchedData || (searchBlockData & faceLightingMatchMask) == faceLightingMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundariesReverse[1][sweepAxis0]++; else break; } } // take the best one int32 areaForward = ((quadBoundariesForward[1][sweepAxis0] - quadBoundariesForward[0][sweepAxis0] + 1) * (quadBoundariesForward[1][sweepAxis1] - quadBoundariesForward[1][sweepAxis1] + 1)); int32 areaReverse = ((quadBoundariesForward[1][sweepAxis0] - quadBoundariesForward[0][sweepAxis0] + 1) * (quadBoundariesForward[1][sweepAxis1] - quadBoundariesForward[1][sweepAxis1] + 1)); if (areaReverse > areaForward) Y_memcpy(quadBoundaries, quadBoundariesReverse, sizeof(quadBoundaries)); else Y_memcpy(quadBoundaries, quadBoundariesReverse, sizeof(quadBoundaries)); #endif // mark all the faces as generated for (i = quadBoundaries[0][2]; i <= quadBoundaries[1][2]; i++) { for (j = quadBoundaries[0][1]; j <= quadBoundaries[1][1]; j++) { for (k = quadBoundaries[0][0]; k <= quadBoundaries[1][0]; k++) { // mark as allocated BLOCK_DATA_ARRAY_ACCESS(k, j, i) &= ~currentFaceMask; } } } // update the cached data too blockData &= ~currentFaceMask; // get uvs and color const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[faceIndex]; uint32 faceMaterialIndex = pFaceDef->Visual.MaterialIndex; uint32 faceColor = pFaceDef->Visual.Color; float3 faceMinUV = pFaceDef->Visual.MinUV; float3 faceMaxUV = pFaceDef->Visual.MaxUV; const float4 &faceAtlasUVRange = pFaceDef->Visual.AtlasUVRange; // set msb in material index if the block type does not allow shadows if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS) faceMaterialIndex |= MATERIAL_INDEX_SHADOW_BIT_SET; // repeat the texture uint32 blockCountX = (quadBoundaries[1][0] - quadBoundaries[0][0]) + 1; uint32 blockCountY = (quadBoundaries[1][1] - quadBoundaries[0][1]) + 1; uint32 blockCountZ = (quadBoundaries[1][2] - quadBoundaries[0][2]) + 1; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: faceMaxUV.x *= (float)blockCountY; faceMaxUV.y *= (float)blockCountZ; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: faceMaxUV.x *= (float)blockCountX; faceMaxUV.y *= (float)blockCountZ; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: faceMaxUV.x *= (float)blockCountX; faceMaxUV.y *= (float)blockCountY; break; } /* 0 top back left 1 top back right 2 top front left 3 top front right 4 bottom back left 5 bottom back right 6 bottom front left 7 bottom front right x, y, z = 6 sx, y, z = 7 sx, sy, z = 5 sx, sy, sz = 1 x, sy, z = 4 x, sy, sz = 0 x, y, sz = 2 sx, y, sz = 3 */ // generate vertices uint32 baseVertex = m_outputVertices.GetSize(); // generate quads switch (faceIndex) { case CUBE_FACE_RIGHT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_RIGHT));// top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_RIGHT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_RIGHT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_RIGHT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_LEFT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_LEFT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_LEFT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_LEFT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_LEFT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BACK: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_BACK)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_BACK)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_BACK)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_BACK)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_FRONT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_FRONT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_FRONT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_FRONT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_FRONT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_TOP: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_TOP)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_TOP)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_TOP)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_TOP)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BOTTOM: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_BOTTOM)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_BOTTOM)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_BOTTOM)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_BOTTOM)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; } // update bounds outMinBounds = outMinBounds.Min(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2])); outMaxBounds = outMaxBounds.Max(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1)); } } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // slabs have two behaviours, depending on if volume bit is set // if volume bit is set, they are generated like cubes, except the very top block // otherwise, they are generated independantly bool isVolumeBlock = (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) != 0; // generate each face for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { uint32 currentFaceMask = (1 << faceIndex); if ((blockData & currentFaceMask) == 0) continue; // determine which axis to sweep int32 sliceAxis = 0, sweepAxis0 = 0, sweepAxis1 = 0; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: sliceAxis = 0; sweepAxis0 = 1; sweepAxis1 = (isVolumeBlock) ? 2 : -1; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: sliceAxis = 1; sweepAxis0 = 0; sweepAxis1 = (isVolumeBlock) ? 2 : -1; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: sliceAxis = 2; sweepAxis0 = 1; sweepAxis1 = 0; break; } // determine the quad boundaries by sweeping each axis, then in reverse uint32 baseCoordinates[3]; uint32 blockCoordinates[3]; uint32 quadBoundaries[2][3]; uint32 i, j, k; // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundaries[0], baseCoordinates, sizeof(quadBoundaries[0])); Y_memcpy(&quadBoundaries[1], baseCoordinates, sizeof(quadBoundaries[1])); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... { // axis 0 for (i = quadBoundaries[0][sweepAxis0] + 1; i < meshSizes[sweepAxis0]; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask)) { quadBoundaries[1][sweepAxis0]++; continue; } else { break; } } // axis 1 if (sweepAxis1 >= 0) { for (i = quadBoundaries[0][sweepAxis1] + 1; i < meshSizes[sweepAxis1]; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundaries[0][sweepAxis0]; j <= quadBoundaries[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundaries[1][sweepAxis1]++; else break; } } } // mark all the faces as generated for (i = quadBoundaries[0][2]; i <= quadBoundaries[1][2]; i++) { for (j = quadBoundaries[0][1]; j <= quadBoundaries[1][1]; j++) { for (k = quadBoundaries[0][0]; k <= quadBoundaries[1][0]; k++) { // mark as allocated BLOCK_DATA_ARRAY_ACCESS(k, j, i) &= ~currentFaceMask; } } } // update the cached data too blockData &= ~currentFaceMask; // get uvs and color const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[faceIndex]; uint32 faceMaterialIndex = pFaceDef->Visual.MaterialIndex; uint32 faceColor = pFaceDef->Visual.Color; float3 faceMinUV = pFaceDef->Visual.MinUV; float3 faceMaxUV = pFaceDef->Visual.MaxUV; const float4 &faceAtlasUVRange = pFaceDef->Visual.AtlasUVRange; // set msb in material index if the block type does not allow shadows if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS) faceMaterialIndex |= MATERIAL_INDEX_SHADOW_BIT_SET; // repeat the texture uint32 blockCountX = (quadBoundaries[1][0] - quadBoundaries[0][0]) + 1; uint32 blockCountY = (quadBoundaries[1][1] - quadBoundaries[0][1]) + 1; uint32 blockCountZ = (quadBoundaries[1][2] - quadBoundaries[0][2]) + 1; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: faceMaxUV.x *= (float)blockCountY; faceMaxUV.y *= (float)blockCountZ; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: faceMaxUV.x *= (float)blockCountX; faceMaxUV.y *= (float)blockCountZ; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: faceMaxUV.x *= (float)blockCountX; faceMaxUV.y *= (float)blockCountY; break; } /* 0 top back left 1 top back right 2 top front left 3 top front right 4 bottom back left 5 bottom back right 6 bottom front left 7 bottom front right x, y, z = 6 sx, y, z = 7 sx, sy, z = 5 sx, sy, sz = 1 x, sy, z = 4 x, sy, sz = 0 x, y, sz = 2 sx, y, sz = 3 */ // generate vertices uint32 baseVertex = m_outputVertices.GetSize(); // subtract amount bool isTopSlab = true; if (isVolumeBlock) { // is the block above this the same type? if (z == (m_height - 1)) isTopSlab = (GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME_TOP, x, y, 0) != blockValue); else isTopSlab = (GetBlockValueAt(x, y, z + 1) != blockValue); } // calculate top slab subtract amount float3 topBlockSubtractAmount((isTopSlab) ? float3(0.0f, 0.0f, blockScale * (1.0f - pBlockType->SlabShapeSettings.Height)) : float3::Zero); // generate quads switch (faceIndex) { case CUBE_FACE_RIGHT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_RIGHT));// top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_RIGHT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_RIGHT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_RIGHT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_LEFT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_LEFT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_LEFT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_LEFT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_LEFT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BACK: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_BACK)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_BACK)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_BACK)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_BACK)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_FRONT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_FRONT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_FRONT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_FRONT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_FRONT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_TOP: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 0, blockData, faceColor), CUBE_FACE_TOP)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 1, blockData, faceColor), CUBE_FACE_TOP)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 2, blockData, faceColor), CUBE_FACE_TOP)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1) - topBlockSubtractAmount, float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 3, blockData, faceColor), CUBE_FACE_TOP)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BOTTOM: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 4, blockData, faceColor), CUBE_FACE_BOTTOM)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 5, blockData, faceColor), CUBE_FACE_BOTTOM)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 6, blockData, faceColor), CUBE_FACE_BOTTOM)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), faceAtlasUVRange, CalculateCubeVertexColor(pBlockType, 7, blockData, faceColor), CUBE_FACE_BOTTOM)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; } // update bounds outMinBounds = outMinBounds.Min(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2])); outMaxBounds = outMaxBounds.Max(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1) - topBlockSubtractAmount); } } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { const BlockPalette::BlockType::PlaneShape &planeSettings = pBlockType->PlaneShapeSettings; const BlockPalette::BlockType::VisualParameters &visualSettings = pBlockType->PlaneShapeSettings.Visual; float3 faceMinUV = visualSettings.MinUV; float3 faceMaxUV = visualSettings.MaxUV; uint32 faceMaterialIndex = visualSettings.MaterialIndex; // set msb in material index if the block type does not allow shadows if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS) faceMaterialIndex |= MATERIAL_INDEX_SHADOW_BIT_SET; // generate base vertices Vertex baseVertices[8]; baseVertices[0].Set(float3(-0.5f, 0.0f, 1.0f), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_FRONT); // top-left baseVertices[1].Set(float3(0.5f, 0.0f, 1.0f), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_FRONT); // top-right baseVertices[2].Set(float3(-0.5f, 0.0f, 0.0f), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_FRONT); // bottom-left baseVertices[3].Set(float3(0.5f, 0.0f, 0.0f), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_FRONT); // bottom-right baseVertices[4].Set(float3(-0.5f, 0.0f, 1.0f), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_BACK); // top-left baseVertices[5].Set(float3(0.5f, 0.0f, 1.0f), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_BACK); // top-right baseVertices[6].Set(float3(-0.5f, 0.0f, 0.0f), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_BACK); // bottom-left baseVertices[7].Set(float3(0.5f, 0.0f, 0.0f), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), visualSettings.AtlasUVRange, visualSettings.Color, CUBE_FACE_BACK); // bottom-right // do plane float currentRotation = pBlockType->PlaneShapeSettings.BaseRotation; for (uint32 i = 0; i < pBlockType->PlaneShapeSettings.RepeatCount; i++, currentRotation += pBlockType->PlaneShapeSettings.RepeatRotation) { // copy base Vertex planeVertices[8]; Y_memcpy(planeVertices, baseVertices, sizeof(planeVertices)); // create quat for rotation Quaternion planeRotation(Quaternion::FromEulerAngles(0.0f, 0.0f, currentRotation)); // rotate the vertices, and add the offsets for (uint32 j = 0; j < countof(planeVertices); j++) { planeVertices[j].Position = planeRotation * planeVertices[j].Position; planeVertices[j].Position.x *= planeSettings.Width; planeVertices[j].Position.z *= planeSettings.Height; planeVertices[j].Position.x += planeSettings.OffsetX; planeVertices[j].Position.y += planeSettings.OffsetY; // move so that the origin is the middle of the block (translation happens after rotation) planeVertices[j].Position.x += 0.5f; planeVertices[j].Position.y += 0.5f; } // move into world space for (uint32 j = 0; j < countof(planeVertices); j++) planeVertices[j].Position = (planeVertices[j].Position * m_scale) + BLOCK_WORLD_COORDINATES(x, y, z); // add to list uint32 baseVertex = m_outputVertices.GetSize(); for (uint32 j = 0; j < countof(planeVertices); j++) m_outputVertices.Add(planeVertices[j]); // generate 4 triangles, one for each quad m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 2, baseVertex + 3, baseVertex + 0)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 0, baseVertex + 3, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 6, baseVertex + 4, baseVertex + 7)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 7, baseVertex + 4, baseVertex + 5)); } } } } } /*for (uint32 i = 0; i < m_outputTriangles.GetSize(); i++) { const Triangle &t = m_outputTriangles[i]; float3 ot, ob, on; MeshUtilites::CalculateTangentSpaceVectors(m_outputVertices[t.Indices[0]].Position, m_outputVertices[t.Indices[1]].Position, m_outputVertices[t.Indices[2]].Position, m_outputVertices[t.Indices[0]].TexCoord.xy(), m_outputVertices[t.Indices[1]].TexCoord.xy(), m_outputVertices[t.Indices[2]].TexCoord.xy(), ot, ob, on); __asm int 3; }*/ delete[] pBlockDataArray; m_outputVertexFactoryFlags = BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD | BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS | BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX; } void BlockMeshBuilder::GenerateCollisionBlocks(float3 &outMinBounds, float3 &outMaxBounds) { static const uint32 ALL_FACES_ALLOCATED_MASK = 0x3F; const float blockScale = m_scale; const uint32 yStride = m_width; const uint32 zStride = yStride * m_length; const BlockPalette::BlockType *pBlockType; BlockVolumeBlockType blockValue, searchBlockValue; uint32 blockData, searchBlockData; uint32 x, y, z; SIMDVector3f basePosition(m_translation); uint32 *pBlockDataArray = new uint32[m_width * m_length * m_height]; uint32 meshSizes[3] = { m_width, m_length, m_height }; bool isEdgeZBlockPos, isEdgeZBlockNeg; bool isEdgeYBlockPos, isEdgeYBlockNeg; bool isEdgeXBlockPos, isEdgeXBlockNeg; // strip out faces that have blocks adjacent to them. for (z = 0; z < m_height; z++) { isEdgeZBlockNeg = (z == 0); isEdgeZBlockPos = (z == (m_height - 1)); for (y = 0; y < m_length; y++) { isEdgeYBlockNeg = (y == 0); isEdgeYBlockPos = (y == (m_length - 1)); for (x = 0; x < m_width; x++) { isEdgeXBlockNeg = (x == 0); isEdgeXBlockPos = (x == (m_width - 1)); // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0) { BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; continue; } pBlockType = m_pPalette->GetBlockType(blockValue); if (!(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE)) { BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; continue; } if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // get block data blockData = ALL_FACES_ALLOCATED_MASK; // Culling values if (!isEdgeXBlockPos && HasCubeVisibilityBlockingBlockAt(pBlockType, x + 1, y + 0, z + 0)) { blockData &= ~(1 << CUBE_FACE_RIGHT); } if (!isEdgeXBlockNeg && HasCubeVisibilityBlockingBlockAt(pBlockType, x - 1, y + 0, z + 0)) { blockData &= ~(1 << CUBE_FACE_LEFT); } if (!isEdgeYBlockPos && HasCubeVisibilityBlockingBlockAt(pBlockType, x + 0, y + 1, z + 0)) { blockData &= ~(1 << CUBE_FACE_BACK); } if (!isEdgeYBlockNeg && HasCubeVisibilityBlockingBlockAt(pBlockType, x + 0, y - 1, z + 0)) { blockData &= ~(1 << CUBE_FACE_FRONT); } if (!isEdgeZBlockPos && HasCubeVisibilityBlockingBlockAt(pBlockType, x + 0, y + 0, z + 1)) { blockData &= ~(1 << CUBE_FACE_TOP); } if (!isEdgeZBlockNeg && HasCubeVisibilityBlockingBlockAt(pBlockType, x + 0, y + 0, z - 1)) { blockData &= ~(1 << CUBE_FACE_BOTTOM); } // store face mask BLOCK_DATA_ARRAY_ACCESS(x, y, z) = blockData; } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { // planes get set to 0 when generated BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 1; } else { // mark all faces as generated, so we don't come back to them BLOCK_DATA_ARRAY_ACCESS(x, y, z) = 0; } } } } for (z = 0; z < m_height; z++) { for (y = 0; y < m_length; y++) { for (x = 0; x < m_width; x++) { // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0 || (pBlockType = m_pPalette->GetBlockType(blockValue))->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE) continue; // get block data blockData = BLOCK_DATA_ARRAY_ACCESS(x, y, z); // switch shape type if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // generate each face for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { uint32 currentFaceMask = (1 << faceIndex); if ((blockData & currentFaceMask) == 0) continue; // determine which axis to sweep uint32 sliceAxis = 0, sweepAxis0 = 0, sweepAxis1 = 0; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: sliceAxis = 0; sweepAxis0 = 1; sweepAxis1 = 2; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: sliceAxis = 1; sweepAxis0 = 0; sweepAxis1 = 2; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: sliceAxis = 2; sweepAxis0 = 1; sweepAxis1 = 0; break; } // determine the quad boundaries by sweeping each axis, then in reverse uint32 baseCoordinates[3]; uint32 blockCoordinates[3]; uint32 quadBoundaries[2][3]; uint32 i, j, k; // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundaries[0], baseCoordinates, sizeof(quadBoundaries[0])); Y_memcpy(&quadBoundaries[1], baseCoordinates, sizeof(quadBoundaries[1])); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... { // axis 0 for (i = quadBoundaries[0][sweepAxis0] + 1; i < meshSizes[sweepAxis0]; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask)) { quadBoundaries[1][sweepAxis0]++; continue; } else { break; } } // axis 1 for (i = quadBoundaries[0][sweepAxis1] + 1; i < meshSizes[sweepAxis1]; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundaries[0][sweepAxis0]; j <= quadBoundaries[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); searchBlockData = BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if ((searchBlockValue == blockValue) && (searchBlockData & currentFaceMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundaries[1][sweepAxis1]++; else break; } } // mark all the faces as generated for (i = quadBoundaries[0][2]; i <= quadBoundaries[1][2]; i++) { for (j = quadBoundaries[0][1]; j <= quadBoundaries[1][1]; j++) { for (k = quadBoundaries[0][0]; k <= quadBoundaries[1][0]; k++) { // mark as allocated BLOCK_DATA_ARRAY_ACCESS(k, j, i) &= ~currentFaceMask; } } } // update the cached data too blockData &= ~currentFaceMask; /* 0 top back left 1 top back right 2 top front left 3 top front right 4 bottom back left 5 bottom back right 6 bottom front left 7 bottom front right x, y, z = 6 sx, y, z = 7 sx, sy, z = 5 sx, sy, sz = 1 x, sy, z = 4 x, sy, sz = 0 x, y, sz = 2 sx, y, sz = 3 */ // generate vertices uint32 baseVertex = m_outputVertices.GetSize(); // generate quads switch (faceIndex) { case CUBE_FACE_RIGHT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT));// top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_RIGHT, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_RIGHT, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_LEFT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_LEFT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_LEFT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BACK: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_BACK, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_BACK, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_FRONT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_FRONT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_FRONT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_TOP: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_TOP, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_TOP, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BOTTOM: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // bottom-right m_outputTriangles.Add(Triangle(0, CUBE_FACE_BOTTOM, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(0, CUBE_FACE_BOTTOM, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; } // update bounds outMinBounds = outMinBounds.Min(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2])); outMaxBounds = outMaxBounds.Max(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1)); } } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { // do plane } } } } delete[] pBlockDataArray; } #undef BLOCK_WORLD_COORDINATES #undef BLOCK_DATA_ARRAY_ACCESS #undef BLOCK_VALUE_ARRAY_ACCESS #define BLOCK_VALUE_ARRAY_ACCESS(x, y, z) m_pBlockData[(z) * zStride + (y) * yStride + (x)] #define PENDING_FACES_ARRAY_ACCESS(x, y, z) pPendingFacesArray[(z) * zStride + (y) * yStride + (x)] #define BLOCK_WORLD_COORDINATES(x, y, z) (Vector3((float)x, (float)y, (float)z) * blockScale + basePosition) void BlockMeshBuilder::GenerateSilhouetteBlocks(float3 &outMinBounds, float3 &outMaxBounds) { /* static const byte ALL_FACES_ALLOCATED_MASK = 0x3F; const uint32 chunkSize = m_chunkSize; const float blockScale = m_blockScale; const uint32 yStride = chunkSize; const uint32 zStride = yStride * chunkSize; const BlockMeshBlockValue *pChunkBlockValues = m_pChunk->GetBlockValues(); const BlockPalette::BlockType *pBlockType; const BlockPalette::BlockType *pSearchBlockType; BlockMeshBlockValue blockValue; BlockMeshBlockValue searchBlockValue; byte blockFaceMask; byte currentFaceMask; uint32 x, y, z; uint32 sx, sy, sz; Vector3 basePosition(Vector3((float)m_chunkX, (float)m_chunkY, (float)m_chunkZ) * m_blockScale * (float)m_chunkSize); byte *pPendingFacesArray = new byte[chunkSize * chunkSize * chunkSize]; byte pendingFaceMask; // strip out faces that have blocks adjacent to them. for (z = 0; z < chunkSize; z++) { for (y = 0; y < chunkSize; y++) { for (x = 0; x < chunkSize; x++) { // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // get block data pendingFaceMask = ALL_FACES_ALLOCATED_MASK; // Culling values if (HasVisibilityBlockingBlockAt(pBlockType, x + 0, y + 0, z + 1)) { pendingFaceMask &= ~(1 << CUBE_FACE_TOP); } if (HasVisibilityBlockingBlockAt(pBlockType, x + 0, y + 1, z + 0)) { pendingFaceMask &= ~(1 << CUBE_FACE_BACK); } if (HasVisibilityBlockingBlockAt(pBlockType, x - 1, y + 0, z + 0)) { pendingFaceMask &= ~(1 << CUBE_FACE_LEFT); } if (HasVisibilityBlockingBlockAt(pBlockType, x + 1, y + 0, z + 0)) { pendingFaceMask &= ~(1 << CUBE_FACE_RIGHT); } if (HasVisibilityBlockingBlockAt(pBlockType, x + 0, y - 1, z + 0)) { pendingFaceMask &= ~(1 << CUBE_FACE_FRONT); } if (HasVisibilityBlockingBlockAt(pBlockType, x + 0, y + 0, z - 1)) { pendingFaceMask &= ~(1 << CUBE_FACE_BOTTOM); } // mask out each direcion if (pendingFaceMask & (1 << CUBE_FACE_RIGHT) && x != (chunkSize - 1)) { // look for any other blocks in this direction sx = x + 1; for (;;) { if (sx == chunkSize) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(sx, y, z); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sx++; } // found any? if (sx != chunkSize) pendingFaceMask &= ~(1 << CUBE_FACE_RIGHT); } if (pendingFaceMask & (1 << CUBE_FACE_LEFT) && x != 0) { // look for any other blocks in this direction sx = x - 1; for (;;) { if (sx == 0) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(sx, y, z); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sx--; } // found any? if (sx != 0) pendingFaceMask &= ~(1 << CUBE_FACE_LEFT); } if (pendingFaceMask & (1 << CUBE_FACE_BACK) && y != (chunkSize - 1)) { // look for any other blocks in this direction sy = y + 1; for (;;) { if (sy == chunkSize) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(x, sy, z); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sy++; } // found any? if (sy != chunkSize) pendingFaceMask &= ~(1 << CUBE_FACE_BACK); } if (pendingFaceMask & (1 << CUBE_FACE_FRONT) && y != 0) { // look for any other blocks in this direction sy = y - 1; for (;;) { if (sy == 0) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(x, sy, z); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sy--; } // found any? if (sy != 0) pendingFaceMask &= ~(1 << CUBE_FACE_FRONT); } if (pendingFaceMask & (1 << CUBE_FACE_TOP) && z != (chunkSize - 1)) { // look for any other blocks in this direction sz = z + 1; for (;;) { if (sz == chunkSize) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, sz); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sz++; } // found any? if (sz != chunkSize) pendingFaceMask &= ~(1 << CUBE_FACE_TOP); } if (pendingFaceMask & (1 << CUBE_FACE_BOTTOM) && z != 0) { // look for any other blocks in this direction sz = z - 1; for (;;) { if (sz == 0) break; searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, sz); if (searchBlockValue == 0 || !((pSearchBlockType = m_pPalette->GetBlockType(searchBlockValue))->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) || (pSearchBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT)) { break; } sz--; } // found any? if (sz != 0) pendingFaceMask &= ~(1 << CUBE_FACE_BOTTOM); } if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_TRANSPARENT) pendingFaceMask = 0; // store face mask PENDING_FACES_ARRAY_ACCESS(x, y, z) = pendingFaceMask; } else { // mark all faces as generated, so we don't come back to them PENDING_FACES_ARRAY_ACCESS(x, y, z) = 0; } } } } for (z = 0; z < chunkSize; z++) { for (y = 0; y < chunkSize; y++) { for (x = 0; x < chunkSize; x++) { // get block type blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0 || (pBlockType = m_pPalette->GetBlockType(blockValue))->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) continue; // get block data blockFaceMask = PENDING_FACES_ARRAY_ACCESS(x, y, z); // generate each face for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { currentFaceMask = (1 << faceIndex); if ((blockFaceMask & currentFaceMask) == 0) continue; // determine which axis to sweep uint32 sliceAxis = 0, sweepAxis0 = 0, sweepAxis1 = 0; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: sliceAxis = 0; sweepAxis0 = 1; sweepAxis1 = 2; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: sliceAxis = 1; sweepAxis0 = 0; sweepAxis1 = 2; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: sliceAxis = 2; sweepAxis0 = 1; sweepAxis1 = 0; break; } // determine the quad boundaries by sweeping each axis, then in reverse uint32 baseCoordinates[3]; uint32 blockCoordinates[3]; uint32 quadBoundaries[2][3]; uint32 i, j, k; // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundaries[0], baseCoordinates, sizeof(quadBoundaries[0])); Y_memcpy(&quadBoundaries[1], baseCoordinates, sizeof(quadBoundaries[1])); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... { // axis 0 for (i = quadBoundaries[0][sweepAxis0] + 1; i < chunkSize; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; if ((BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]) == blockValue) && (PENDING_FACES_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]) & blockFaceMask)) { quadBoundaries[1][sweepAxis0]++; continue; } else { break; } } // axis 1 for (i = quadBoundaries[0][sweepAxis1] + 1; i < chunkSize; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundaries[0][sweepAxis0]; j <= quadBoundaries[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; if ((BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]) == blockValue) && (PENDING_FACES_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]) & blockFaceMask)) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundaries[1][sweepAxis1]++; else break; } } // mark all the faces as generated for (i = quadBoundaries[0][2]; i <= quadBoundaries[1][2]; i++) { for (j = quadBoundaries[0][1]; j <= quadBoundaries[1][1]; j++) { for (k = quadBoundaries[0][0]; k <= quadBoundaries[1][0]; k++) { // mark as allocated PENDING_FACES_ARRAY_ACCESS(k, j, i) &= ~currentFaceMask; } } } // generate vertices const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[faceIndex]; const uint32 faceMaterialIndex = pFaceDef->SilhouetteMaterialIndex; uint32 baseVertex = m_outputVertices.GetSize(); // generate quads Vertex vertices[4]; Triangle triangles[2]; switch (faceIndex) { case CUBE_FACE_RIGHT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT));// top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_RIGHT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_RIGHT, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_LEFT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_LEFT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_LEFT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BACK: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BACK)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BACK, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; case CUBE_FACE_FRONT: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_FRONT)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_FRONT, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_TOP: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[1][2] + 1), float3::Zero, float4::Zero, 0, CUBE_FACE_TOP)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 0, baseVertex + 2, baseVertex + 1)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_TOP, baseVertex + 1, baseVertex + 2, baseVertex + 3)); } break; case CUBE_FACE_BOTTOM: { m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // top-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // top-right m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // bottom-left m_outputVertices.Add(Vertex(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[0][1], quadBoundaries[0][2]), float3::Zero, float4::Zero, 0, CUBE_FACE_BOTTOM)); // bottom-right m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 0, baseVertex + 1, baseVertex + 2)); m_outputTriangles.Add(Triangle(faceMaterialIndex, CUBE_FACE_BOTTOM, baseVertex + 1, baseVertex + 3, baseVertex + 2)); } break; } // update bounds outMinBounds = outMinBounds.Min(BLOCK_WORLD_COORDINATES(quadBoundaries[0][0], quadBoundaries[0][1], quadBoundaries[0][2])); outMaxBounds = outMaxBounds.Max(BLOCK_WORLD_COORDINATES(quadBoundaries[1][0] + 1, quadBoundaries[1][1] + 1, quadBoundaries[1][2] + 1)); } } } } delete[] pPendingFacesArray; */ } #undef BLOCK_WORLD_COORDINATES #undef PENDING_FACES_ARRAY_ACCESS #undef BLOCK_DATA_ARRAY_ACCESS void BlockMeshBuilder::GenerateMesh() { // min/max bounds float3 minBounds(float3::Infinite); float3 maxBounds(float3::NegativeInfinite); // generate cube faces GenerateBlocks(minBounds, maxBounds); // fill bounds if (minBounds <= maxBounds) { m_outputBoundingBox.SetBounds(minBounds, maxBounds); m_outputBoundingSphere = Sphere::FromAABox(m_outputBoundingBox); } // re-order triangles OptimizeTriangleOrder(); // generate batches GenerateBatches(); } void BlockMeshBuilder::GenerateCollisionMesh() { // min/max bounds float3 minBounds(float3::Infinite); float3 maxBounds(float3::NegativeInfinite); // generate cube faces GenerateCollisionBlocks(minBounds, maxBounds); // fill bounds if (minBounds <= maxBounds) { m_outputBoundingBox.SetBounds(minBounds, maxBounds); m_outputBoundingSphere = Sphere::FromAABox(m_outputBoundingBox); } } void BlockMeshBuilder::GenerateSilhouetteMesh() { // min/max bounds float3 minBounds(float3::Infinite); float3 maxBounds(float3::NegativeInfinite); // generate cube faces GenerateSilhouetteBlocks(minBounds, maxBounds); // fill bounds if (minBounds <= maxBounds) { m_outputBoundingBox.SetBounds(minBounds, maxBounds); m_outputBoundingSphere = Sphere::FromAABox(m_outputBoundingBox); } // re-order triangles OptimizeTriangleOrder(); // generate batches GenerateBatches(); } static int TriangleOrderSortFunction(const BlockMeshBuilder::Triangle *pLeft, const BlockMeshBuilder::Triangle *pRight) { // sort by material index first if (pLeft->MaterialIndex > pRight->MaterialIndex) return 1; else if (pLeft->MaterialIndex < pRight->MaterialIndex) return -1; // then by triangle indices for better use of the cache if (pLeft->Indices[0] > pRight->Indices[0]) return 1; else if (pLeft->Indices[0] < pRight->Indices[0]) return -1; if (pLeft->Indices[1] > pRight->Indices[1]) return 1; else if (pLeft->Indices[1] < pRight->Indices[1]) return -1; if (pLeft->Indices[2] > pRight->Indices[2]) return 1; else if (pLeft->Indices[2] < pRight->Indices[2]) return -1; return 0; } void BlockMeshBuilder::OptimizeTriangleOrder() { if (m_outputTriangles.GetSize() > 0) { /* MeshUtilites::OptimizeIndicesForBatching(reinterpret_cast<byte *>(m_outputTriangles.GetBasePointer()) + offsetof(Triangle, Indices[0]), sizeof(Triangle), reinterpret_cast<byte *>(m_outputTriangles.GetBasePointer()) + offsetof(Triangle, MaterialIndex), sizeof(Triangle), m_outputTriangles.GetSize() * 3); */ // use sort method instead m_outputTriangles.Sort(TriangleOrderSortFunction); } } void BlockMeshBuilder::GenerateBatches() { uint32 i; DebugAssert(m_outputBatches.GetSize() == 0); if (m_outputTriangles.GetSize() == 0) return; const Triangle *pTriangle = m_outputTriangles.GetBasePointer(); Batch batch; batch.StartIndex = 0; batch.NumIndices = 0; batch.MaterialIndex = pTriangle->MaterialIndex; for (i = 0; i < m_outputTriangles.GetSize(); i++, pTriangle++) { if (pTriangle->MaterialIndex == batch.MaterialIndex) { batch.NumIndices += 3; } else { DebugAssert(batch.NumIndices > 0); batch.DrawShadows = (batch.MaterialIndex & MATERIAL_INDEX_SHADOW_BIT_MASK) != 0; batch.MaterialIndex &= MATERIAL_INDEX_MASK; m_outputBatches.Add(batch); batch.StartIndex = i * 3; batch.NumIndices = 3; batch.MaterialIndex = pTriangle->MaterialIndex; } } if (batch.NumIndices > 0) { batch.DrawShadows = (batch.MaterialIndex & MATERIAL_INDEX_SHADOW_BIT_MASK) != 0; batch.MaterialIndex &= MATERIAL_INDEX_MASK; m_outputBatches.Add(batch); } } bool BlockMeshBuilder::CreateGPUBuffers(VertexBufferBindingArray *pVertexBuffers, uint32 *pVertexFactoryFlags, GPUBuffer **ppIndexBuffer, GPU_INDEX_FORMAT *pIndexFormat, uint32 inVertexFactoryFlags) { // determine vertex factory flags uint32 vertexFactoryFlags = m_outputVertexFactoryFlags | inVertexFactoryFlags; const RendererCapabilities &rendererCapabilities = g_pRenderer->GetCapabilities(); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD) { if (rendererCapabilities.SupportsTextureArrays) vertexFactoryFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY; else vertexFactoryFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS; } VertexBufferBindingArray vertexBuffers; if (!BlockMeshVertexFactory::CreateVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), vertexFactoryFlags, m_outputVertices.GetBasePointer(), m_outputVertices.GetSize(), &vertexBuffers)) return false; // generate indices uint32 i, n; GPUBuffer *pIndexBuffer; GPU_INDEX_FORMAT indexFormat; if (m_outputVertices.GetSize() <= 0xFFFF) { uint16 *pIndices = new uint16[m_outputVertices.GetSize() * 3]; for (i = 0, n = 0; i < m_outputTriangles.GetSize(); i++) { const Triangle &t = m_outputTriangles[i]; pIndices[n++] = (uint16)t.Indices[0]; pIndices[n++] = (uint16)t.Indices[1]; pIndices[n++] = (uint16)t.Indices[2]; } GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, sizeof(uint16)* m_outputTriangles.GetSize() * 3); pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pIndices); indexFormat = GPU_INDEX_FORMAT_UINT16; delete[] pIndices; } else { uint32 *pIndices = new uint32[m_outputTriangles.GetSize() * 3]; for (i = 0, n = 0; i < m_outputTriangles.GetSize(); i++) { const Triangle &t = m_outputTriangles[i]; pIndices[n++] = t.Indices[0]; pIndices[n++] = t.Indices[1]; pIndices[n++] = t.Indices[2]; } GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, sizeof(uint32)* m_outputTriangles.GetSize() * 3); pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pIndices); indexFormat = GPU_INDEX_FORMAT_UINT32; delete[] pIndices; } if (pIndexBuffer == NULL) return false; BlockMeshVertexFactory::ShareVerticesBuffer(pVertexBuffers, &vertexBuffers); *ppIndexBuffer = pIndexBuffer; *pIndexFormat = indexFormat; *pVertexFactoryFlags = vertexFactoryFlags; return true; } <file_sep>/Engine/Source/ContentConverter/PrecompiledHeader.h #pragma once #include "ContentConverter/Common.h" <file_sep>/Engine/Source/Engine/Component.h #pragma once #include "Engine/Common.h" #include "Engine/ComponentTypeInfo.h" class PropertyTable; class Entity; class World; class Component : public Object { DECLARE_COMPONENT_TYPEINFO(Component, Object); DECLARE_COMPONENT_NO_FACTORY(Component); public: Component(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~Component(); // Retrieves the type information for this object. const ComponentTypeInfo *GetComponentTypeInfo() const { return static_cast<const ComponentTypeInfo *>(m_pObjectTypeInfo); } // entity that we are attached to const Entity *GetEntity() const { return m_pEntity; } Entity *GetEntity() { return m_pEntity; } bool IsAttachedToEntity() const { return (m_pEntity != nullptr); } // local position/offset const float3 &GetLocalPosition() const { return m_localPosition; } const Quaternion &GetLocalRotation() const { return m_localRotation; } const float3 &GetLocalScale() const { return m_localScale; } // bounding volumes const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } // events virtual bool Initialize(); virtual void OnAddToEntity(Entity *pEntity); virtual void OnRemoveFromEntity(Entity *pEntity); virtual void OnAddToWorld(World *pWorld); virtual void OnRemoveFromWorld(World *pWorld); virtual void OnLocalTransformChange(); virtual void OnEntityTransformChange(); // Invoked events virtual void Update(float timeSinceLastUpdate); virtual void UpdateAsync(float timeSinceLastUpdate); // local position modifiers void SetLocalPosition(const float3 &localPosition); void SetLocalRotation(const Quaternion &localRotation); void SetLocalScale(const float3 &localScale); protected: // calculates the transform for the component after transforming into local space Transform CalculateWorldTransform() const; // change the bounds of the component. will notify the entity if changed. void SetBounds(const AABox &boundingBox, const Sphere &boundingSphere, bool notifyEntity = true); // helper for initializing properties of an entity based on its type information static bool InitializePropertiesFromTable(Component *pComponent, const PropertyTable *pPropertyTable); protected: // entity we are attached to Entity *m_pEntity; // local offset float3 m_localPosition; Quaternion m_localRotation; float3 m_localScale; // these bounds are in world-space AABox m_boundingBox; Sphere m_boundingSphere; private: // local transform change callback static void ProperyCallbackOnLocalTransformChange(Component *pComponent, void *pUserData = nullptr); }; <file_sep>/CMakeModules/FindPCRE.cmake # <NAME> <<EMAIL>> # License: GPLv2/v3 # # Try to find libpcre (Perl Compatible Regular Expressions) # # Once done this will define # # PCRE_FOUND - system has libpcre # PCRE_INCLUDE_DIR - the libpcre include directory # PCRE_LIBRARY - where to find libpcre # PCRE_LIBRARIES - Link these to use libpcre if(PCRE_INCLUDE_DIR AND PCRE_LIBRARIES) # in cache already set(LIBUSB_FOUND TRUE) else(PCRE_INCLUDE_DIR AND PCRE_LIBRARIES) if(NOT WIN32) # use pkg-config to get the directories and then use these values # in the FIND_PATH() and FIND_LIBRARY() calls find_package(PkgConfig) pkg_check_modules(PC_PCRE libpcre) endif(NOT WIN32) find_path(PCRE_INCLUDE_DIR NAMES pcre.h HINTS ${PCRE_PKG_INCLUDE_DIRS} PATHS /usr/include /usr/local/include ) find_library(PCRE_LIBRARY NAMES pcre HINTS ${PCRE_PKG_LIBRARY_DIRS} PATHS /usr/lib /usr/local/lib ) set(PCRE_LIBRARIES ${PCRE_LIBRARY}) # handle the QUIETLY AND REQUIRED arguments AND set PCRE_FOUND to TRUE if # all listed variables are TRUE # include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(PCRE DEFAULT_MSG PCRE_LIBRARY PCRE_INCLUDE_DIR) mark_as_advanced(PCRE_INCLUDE_DIR PCRE_LIBRARY) endif(PCRE_INCLUDE_DIR AND PCRE_LIBRARIES) <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUTexture.h #pragma once #include "D3D11Renderer/D3D11Common.h" class D3D11GPUTexture1D : public GPUTexture1D { public: D3D11GPUTexture1D(const GPU_TEXTURE1D_DESC *pDesc, ID3D11Texture1D *pD3DTexture, ID3D11Texture1D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTexture1D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture1D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture1D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture1D *m_pD3DTexture; ID3D11Texture1D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTexture1DArray : public GPUTexture1DArray { public: D3D11GPUTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pDesc, ID3D11Texture1D *pD3DTexture, ID3D11Texture1D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTexture1DArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture1D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture1D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture1D *m_pD3DTexture; ID3D11Texture1D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTexture2D : public GPUTexture2D { public: D3D11GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTexture2D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture2D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture2D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture2D *m_pD3DTexture; ID3D11Texture2D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTexture2DArray : public GPUTexture2DArray { public: D3D11GPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTexture2DArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture2D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture2D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture2D *m_pD3DTexture; ID3D11Texture2D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTexture3D : public GPUTexture3D { public: D3D11GPUTexture3D(const GPU_TEXTURE3D_DESC *pDesc, ID3D11Texture3D *pD3DTexture, ID3D11Texture3D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTexture3D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture3D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture3D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture3D *m_pD3DTexture; ID3D11Texture3D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTextureCube : public GPUTextureCube { public: D3D11GPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTextureCube(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture2D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture2D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture2D *m_pD3DTexture; ID3D11Texture2D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUTextureCubeArray : public GPUTextureCubeArray { public: D3D11GPUTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture, ID3D11ShaderResourceView *pD3DSRV, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11GPUTextureCubeArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture2D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture2D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } ID3D11ShaderResourceView *GetD3DSRV() const { return m_pD3DSRV; } ID3D11SamplerState *GetD3DSamplerState() const { return m_pD3DSamplerState; } protected: ID3D11Texture2D *m_pD3DTexture; ID3D11Texture2D *m_pD3DStagingTexture; ID3D11ShaderResourceView *m_pD3DSRV; ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11GPUDepthTexture : public GPUDepthTexture { public: D3D11GPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, ID3D11Texture2D *pD3DTexture, ID3D11Texture2D *pD3DStagingTexture); virtual ~D3D11GPUDepthTexture(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Texture2D *GetD3DTexture() const { return m_pD3DTexture; } ID3D11Texture2D *GetD3DStagingTexture() const { return m_pD3DStagingTexture; } protected: ID3D11Texture2D *m_pD3DTexture; ID3D11Texture2D *m_pD3DStagingTexture; }; class D3D11GPURenderTargetView : public GPURenderTargetView { public: D3D11GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, ID3D11RenderTargetView *pD3DRTV, ID3D11Resource *pD3DResource); virtual ~D3D11GPURenderTargetView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11RenderTargetView *GetD3DRTV() const { return m_pD3DRTV; } ID3D11Resource *GetD3DResource() const { return m_pD3DResource; } protected: ID3D11RenderTargetView *m_pD3DRTV; ID3D11Resource *m_pD3DResource; }; class D3D11GPUDepthStencilBufferView : public GPUDepthStencilBufferView { public: D3D11GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, ID3D11DepthStencilView *pD3DDSV, ID3D11Resource *pD3DResource); virtual ~D3D11GPUDepthStencilBufferView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11DepthStencilView *GetD3DDSV() const { return m_pD3DDSV; } ID3D11Resource *GetD3DResource() const { return m_pD3DResource; } protected: ID3D11DepthStencilView *m_pD3DDSV; ID3D11Resource *m_pD3DResource; }; class D3D11GPUComputeView : public GPUComputeView { public: D3D11GPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc, ID3D11UnorderedAccessView *pD3DUAV, ID3D11Resource *pD3DResource); virtual ~D3D11GPUComputeView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11UnorderedAccessView *GetD3DUAV() const { return m_pD3DUAV; } ID3D11Resource *GetD3DResource() const { return m_pD3DResource; } protected: ID3D11UnorderedAccessView *m_pD3DUAV; ID3D11Resource *m_pD3DResource; }; <file_sep>/Engine/Source/Core/Object.h #pragma once #include "Core/ObjectTypeInfo.h" // // Object // Object class does its own reference counting and lifetime management, as the factories can do pooling. // class Object { // OBJECT TYPE STUFF private: static ObjectTypeInfo s_typeInfo; public: typedef Object ThisClass; static const ObjectTypeInfo *StaticTypeInfo() { return &s_typeInfo; } static ObjectTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } static const PROPERTY_DECLARATION *StaticPropertyMap() { return nullptr; } static ObjectFactory *StaticFactory() { return nullptr; } // END OBJECT TYPE STUFF public: Object(const ObjectTypeInfo *pObjectTypeInfo = &s_typeInfo); virtual ~Object(); // Retrieves the type information for this object. const ObjectTypeInfo *GetObjectTypeInfo() const { return m_pObjectTypeInfo; } // Cast from one object type to another, unchecked. template<class T> const T *Cast() const { DebugAssert(m_pObjectTypeInfo->IsDerived(T::StaticTypeInfo())); return static_cast<const T *>(this); } template<class T> T *Cast() { DebugAssert(m_pObjectTypeInfo->IsDerived(T::StaticTypeInfo())); return static_cast<T *>(this); } // Cast from one object type to another, checked. template<class T> const T *SafeCast() const { return (m_pObjectTypeInfo->IsDerived(T::StaticTypeInfo())) ? static_cast<const T *>(this) : NULL; } template<class T> T *SafeCast() { return (m_pObjectTypeInfo->IsDerived(T::StaticTypeInfo())) ? static_cast<T *>(this) : NULL; } // Test if one object type is derived from another. template<class T> bool IsDerived() const { return (m_pObjectTypeInfo->IsDerived(T::StaticTypeInfo())); } bool IsDerived(const ObjectTypeInfo *pTypeInfo) const { return (m_pObjectTypeInfo->IsDerived(pTypeInfo)); } // Life management. void AddRef() const; uint32 Release() const; protected: // Type info pointer. Set by subclasses. const ObjectTypeInfo *m_pObjectTypeInfo; // Life management. The user *must* use the AddRef/Release methods to modify these, // hence why they are private. mutable Y_ATOMIC_DECL uint32 m_iReferenceCount; mutable uint32 m_iReferenceCountValid; // Disable copy constructor and assignment operators, since that will copy the reference count value. DeclareNonCopyable(Object); }; // // GenericObjectFactory<T> // template<class T> struct GenericObjectFactory : public ObjectFactory { Object *CreateObject() { return new T(); } void DeleteObject(Object *pObject) { delete pObject; } }; #define DECLARE_OBJECT_GENERIC_FACTORY(Type) \ private: \ static GenericObjectFactory<Type> s_GenericFactory; \ public: \ static ObjectFactory *StaticFactory() { return &s_GenericFactory; } #define DEFINE_OBJECT_GENERIC_FACTORY(Type) \ GenericObjectFactory<Type> Type::s_GenericFactory = GenericObjectFactory<Type>(); <file_sep>/Engine/Source/Engine/Entity.h #pragma once #include "Engine/EntityTypeInfo.h" #include "Engine/ScriptObject.h" class Component; class World; enum ENTITY_MOBILITY { ENTITY_MOBILITY_STATIC, // Entity is static, cannot move, and is allocated and removed with the sector. ENTITY_MOBILITY_MOVABLE, // Entity is movable, and allocated/removed with the sector. ENTITY_MOBILITY_DEFERRED, // Entity is movable, allocated with the sector, but not removed if/when the sector is unloaded. ENTITY_MOBILITY_GLOBAL, // Entity is global, allocated on map load, and never removed. ENTITY_MOBILITY_COUNT, }; enum ENTITY_ACTION { ENTITY_ACTION_FIRST_USER = 100, }; class Entity : public ScriptObject { DECLARE_ENTITY_TYPEINFO(Entity, ScriptObject); DECLARE_ENTITY_NO_FACTORY(Entity); public: Entity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~Entity(); // Retrieves the type information for this object. const uint32 GetEntityID() const { return m_entityID; } const String &GetEntityName() const { return m_entityName; } const EntityTypeInfo *GetEntityTypeInfo() const { return static_cast<const EntityTypeInfo *>(m_pObjectTypeInfo); } // Transform accessors. const ENTITY_MOBILITY GetMobility() const { return static_cast<ENTITY_MOBILITY>(m_mobility); } const Transform &GetTransform() const { return m_transform; } const float3 &GetPosition() const { return m_transform.GetPosition(); } const Quaternion &GetRotation() const { return m_transform.GetRotation(); } const float3 &GetScale() const { return m_transform.GetScale(); } // Bounding volumes. const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } // World. World *GetWorld() const { return m_pWorld; } bool IsInWorld() const { return (m_pWorld != nullptr); } // World data, do not modify from anywhere except world class. void *GetWorldData() const { return m_pWorldData; } void SetWorldData(void *pWorldData) { m_pWorldData = pWorldData; } // Events -- todo look at making these protected instead? // Called when the entity is finishing creation, after all properties have been set. virtual bool Initialize(uint32 entityID, const String &entityName); // Called when the entity is added to the world. virtual void OnAddToWorld(World *pWorld); // Called prior to the entity being removed from the world. virtual void OnRemoveFromWorld(World *pWorld); // Called when the transform changes. virtual void OnTransformChange(); // Can be called by components when their bounds changes. virtual void OnComponentBoundsChange(); // Called when an action is performed by another entity. virtual void OnAction(Entity *pInitiator, uint32 action); // To prevent a transform change from occurring, override this and return false. virtual bool SetTransform(const Transform &transform); // Invoked events virtual void Update(float timeSinceLastUpdate); virtual void UpdateAsync(float timeSinceLastUpdate); // register/unregister for updates void RegisterForUpdates(float interval = 0.0f); void RegisterForAsyncUpdates(float interval = 0.0f); void UnregisterForUpdates(); void UnregisterForAsyncUpdates(); // Position setters. bool SetPosition(const float3 &position); bool SetRotation(const Quaternion &rotation); bool SetScale(const float3 &scale); // Component accessors. uint32 GetComponentCount() const { return m_components.GetSize(); } const Component *GetComponent(uint32 i) const { return m_components[i]; } Component *GetComponent(uint32 i) { return m_components[i]; } // Component add/remove. void AddComponent(Component *pComponent); void RemoveComponent(Component *pComponent); protected: // gets the bounds of all components bool GetComponentBounds(AABox &boundingBox, Sphere &boundingSphere); // update the bounding box of the entity, optionally taking into account components void SetBounds(const AABox &boundingBox, const Sphere &boundingSphere, bool mergeWithComponents = true); // callbacks for property system static bool PropertyCallbackGetPosition(Entity *pObjectPtr, const void *pUserData, float3 *pValuePtr); static bool PropertyCallbackSetPosition(Entity *pObjectPtr, const void *pUserData, const float3 *pValuePtr); static bool PropertyCallbackGetRotation(Entity *pObjectPtr, const void *pUserData, Quaternion *pValuePtr); static bool PropertyCallbackSetRotation(Entity *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr); static bool PropertyCallbackGetScale(Entity *pObjectPtr, const void *pUserData, float3 *pValuePtr); static bool PropertyCallbackSetScale(Entity *pObjectPtr, const void *pUserData, const float3 *pValuePtr); protected: // ID of entity. Unique to world it lives inside. uint32 m_entityID; String m_entityName; // Base object transform. uint32 m_mobility; Transform m_transform; // World-space bounds of the object. AABox m_boundingBox; Sphere m_boundingSphere; // World this object is located inside. World *m_pWorld; void *m_pWorldData; // Component array. typedef PODArray<Component *> ComponentArray; ComponentArray m_components; private: // Properties/update state uint32 m_registeredUpdateCount; float m_registeredUpdateInterval; uint32 m_registeredAsyncUpdateCount; float m_registeredAsyncUpdateInterval; }; // helper functions SIMDVector4f EncodeUInt32ToColor(uint32 EntityId); uint32 DecodeUInt32FromColorR8G8B8A8(const void *pValue); uint32 DecodeUInt32IdFromColor(const float4 &EncodedColor); <file_sep>/Engine/Source/MathLib/Quaternion.cpp #include "MathLib/Quaternion.h" // constants static const float __QuaternionIdentity[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; const Quaternion &Quaternion::Identity = reinterpret_cast<const Quaternion &>(__QuaternionIdentity); Quaternion Quaternion::Normalize() const { Quaternion ret; float Length = Y_sqrtf(x * x + y * y + z * z + w * w); ret.x = x / Length; ret.y = y / Length; ret.z = z / Length; ret.w = w / Length; return ret; } Quaternion Quaternion::NormalizeEst() const { Quaternion ret; float invLength = Y_rsqrtf(x * x + y * y + z * z + w * w); ret.x = x * invLength; ret.y = y * invLength; ret.z = z * invLength; ret.w = w * invLength; return ret; } void Quaternion::NormalizeInPlace() { float Length = Y_sqrtf(x * x + y * y + z * z + w * w); x /= Length; y /= Length; z /= Length; w /= Length; } void Quaternion::NormalizeEstInPlace() { float invLength = Y_rsqrtf(x * x + y * y + z * z + w * w); x *= invLength; y *= invLength; z *= invLength; w *= invLength; } void Quaternion::ConjugateInPlace() { x = -x; y = -y; z = -z; } void Quaternion::InvertInPlace() { NormalizeInPlace(); ConjugateInPlace(); } Quaternion Quaternion::operator*(const Quaternion &q) const { Quaternion res; res.x = w * q.x + x * q.w + y * q.z - z * q.y; res.y = w * q.y + y * q.w + z * q.x - x * q.z; res.z = w * q.z + z * q.w + x * q.y - y * q.x; res.w = w * q.w - x * q.x - y * q.y - z * q.z; return res; } Quaternion &Quaternion::operator*=(const Quaternion &q) { Quaternion temp(*this); *this = temp * q; return *this; } bool Quaternion::operator==(const Quaternion &q) const { return (x == q.x && y == q.y && z == q.z && w == q.w); } bool Quaternion::operator!=(const Quaternion &q) const { return (x != q.x || y != q.y || z != q.z || w != q.w); } SIMDVector3f Quaternion::operator*(const SIMDVector3f &v) const { // v' = q * v * v^(-1) // Quaternion vRotated(*this * Quaternion(v.x, v.y, v.z, 0.0f)); // vRotated *= Inverse(); // return Vector3(vRotated.x, vRotated.y, vRotated.z); // // http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ // Vector3 qAsVec(x, y, z); // Vector3 t(qAsVec.Cross(v) * 2.0f); // return v + (t * w) + qAsVec.Cross(t); SIMDVector3f qAsVec(x, y, z); SIMDVector3f uv(qAsVec.Cross(v)); SIMDVector3f uuv(qAsVec.Cross(uv)); return v + (uv * (2.0f * w)) + (uuv * 2.0f); } Vector3f Quaternion::operator*(const Vector3f &v) const { // v' = q * v * v^(-1) // Quaternion vRotated(*this * Quaternion(v.x, v.y, v.z, 0.0f)); // vRotated *= Inverse(); // return float3(vRotated.x, vRotated.y, vRotated.z); // // http://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ // Vector3 vAsVec(v); // Vector3 qAsVec(x, y, z); // Vector3 t(qAsVec.Cross(v) * 2.0f); // return vAsVec + (t * w) + qAsVec.Cross(t); SIMDVector3f vAsVec(v); SIMDVector3f qAsVec(x, y, z); SIMDVector3f uv(qAsVec.Cross(vAsVec)); SIMDVector3f uuv(qAsVec.Cross(uv)); return vAsVec + (uv * (2.0f * w)) + (uuv * 2.0f); } void Quaternion::GetAxisAngle(Vector3f &axis, Angle &angle) const { // assume unnormalized input Quaternion qNormalized = Normalize(); float cosA = qNormalized.w; float sinA = Y_sqrtf(1.0f - cosA * cosA); if (Y_fabs(sinA) < 0.0005f) sinA = 1.0f; angle.SetRadians(Y_acosf(cosA) * 2.0f); axis.Set(qNormalized.x, qNormalized.y, qNormalized.z); axis /= sinA; } void Quaternion::GetAxes(Vector3f &xAxis, Vector3f &yAxis, Vector3f &zAxis) const { Matrix4x4f Temp = GetMatrix4x4(); xAxis = Temp.GetColumn(0).xyz(); yAxis = Temp.GetColumn(1).xyz(); zAxis = Temp.GetColumn(2).xyz(); } Vector3f Quaternion::GetEulerAngles() const { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm /* float sqx = Math::Square(x); float sqy = Math::Square(y); float sqz = Math::Square(z); float sqw = Math::Square(w); float unit = sqx + sqy + sqz + sqw; float test = x * y + z * w; // singularity at north pole if (test > 0.499f * unit) return float3(Y_HALF_PI, 2.0f * Y_atan2f(x, w), 0.0f); // singularity at south pole if (test < -0.499f * unit) return float3(-Y_HALF_PI, -2.0f * Y_atan2f(x, w), 0.0f); return float3(Y_asinf(2.0f * test / unit), Y_atan2f(2.0f * y * w - 2.0f * x * z, sqx - sqy - sqz + sqw), Y_atan2f(2.0f * x * w - 2.0f * y * z, -sqx + sqy - sqz + sqw));*/ Quaternion n(Normalize()); float test = n.x * n.y + n.z * n.w; if (test > 0.499f) return Vector3f(90.0f, 360.0f / Y_PI * Y_atan2f(n.x, n.w), 0.0f); if (test < -0.499f) return Vector3f(-90.0f, 360.0f / Y_PI * Y_atan2f(n.x, n.w), 0.0f); float sqx = Math::Square(n.x); float sqy = Math::Square(n.y); float sqz = Math::Square(n.z); return Vector3f(Math::RadiansToDegrees(2.0f * test), Math::RadiansToDegrees(Y_atan2f(2.0f * n.y * n.w - 2.0f * n.x * n.z, 1.0f - 2.0f * sqy - 2.0f * sqz)), Math::RadiansToDegrees(Y_atan2f(2.0f * n.x * n.w - 2.0f * n.y * n.z, 1.0f - 2.0f * sqx - 2.0f * sqz))); } Quaternion Quaternion::FromEulerAngles(const Vector3f &v) { return FromEulerAngles(v.x, v.y, v.z); } Quaternion Quaternion::FromEulerAngles(const Angle x, const Angle y, const Angle z) { return (Quaternion::FromNormalizedAxisAngle(Vector3f::UnitZ, z) * Quaternion::FromNormalizedAxisAngle(Vector3f::UnitY, y) * Quaternion::FromNormalizedAxisAngle(Vector3f::UnitX, x)); } Quaternion Quaternion::FromNormalizedAxisAngle(const Vector3f &axis, Angle angle) { float SinAngle, CosAngle; Y_sincosf(angle.Radians() / 2.0f, &SinAngle, &CosAngle); SIMDVector3f axisMulSin = axis * SinAngle; return Quaternion(axisMulSin.x, axisMulSin.y, axisMulSin.z, CosAngle); } Quaternion Quaternion::FromAxisAngle(const Vector3f &axis, Angle angle) { return FromNormalizedAxisAngle(axis.Normalize(), angle); } Quaternion Quaternion::FromAxes(const Vector3f &xAxis, const Vector3f &yAxis, const Vector3f &zAxis) { Matrix4x4f Temp; Temp.SetColumn(0, Vector4f(xAxis, 0.0f)); Temp.SetColumn(1, Vector4f(yAxis, 0.0f)); Temp.SetColumn(2, Vector4f(zAxis, 1.0f)); return FromFloat4x4(Temp); } // assumes matrix class has an operator() template<typename T> Quaternion QuaternionFromMatrixHelper(const T &mat) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm float trace = mat(0, 0) + mat(1, 1) + mat(2, 2); if (trace > 0.0f) { float S = 0.5f / Math::Sqrt(trace + 1.0f); float W = 0.25f / S; float X = (mat(2, 1) - mat(1, 2)) * S; float Y = (mat(0, 2) - mat(2, 0)) * S; float Z = (mat(1, 0) - mat(0, 1)) * S; return Quaternion(X, Y, Z, W); } else { if (mat(0, 0) > mat(1, 1) && mat(0, 0) > mat(2, 2)) { float S = Math::Sqrt(1.0f + mat(0, 0) - mat(1, 1) - mat(2, 2)) * 2.0f; float Qw = (mat(2, 1) - mat(1, 2)) / S; float Qx = 0.25f * S; float Qy = (mat(0, 1) + mat(1, 0)) / S; float Qz = (mat(0, 2) + mat(2, 0)) / S; return Quaternion(Qx, Qy, Qz, Qw); } else if (mat(1, 1) > mat(0, 0) && mat(1, 1) > mat(2, 2)) { float S = Math::Sqrt(1.0f + mat(1, 1) - mat(0, 0) - mat(2, 2)) * 2.0f; float Qw = (mat(0, 2) - mat(2, 0)) / S; float Qx = (mat(0, 1) + mat(1, 0)) / S; float Qy = 0.25f * S; float Qz = (mat(1, 2) + mat(2, 1)) / S; return Quaternion(Qx, Qy, Qz, Qw); } else// if (RotationMatrix(2, 2) > RotationMatrix(0, 0) && RotationMatrix(2, 2) > RotationMatrix(1, 1)) { float S = Math::Sqrt(1.0f + mat(2, 2) - mat(0, 0) - mat(1, 1)) * 2.0f; float Qw = (mat(1, 0) - mat(0, 1)) / S; float Qx = (mat(0, 2) + mat(2, 0)) / S; float Qy = (mat(1, 2) + mat(2, 1)) / S; float Qz = 0.25f * S; return Quaternion(Qx, Qy, Qz, Qw); } } } Vector4f Quaternion::GetVectorRepresentation() const { return Vector4f(x, y, z, w); } template<typename T> T QuaternionToMatrixHelper(const Quaternion &q) { // http://www.flipcode.com/documents/matrfaq.html#Q54 T res; float xx = q.x * q.x; float xy = q.x * q.y; float xz = q.x * q.z; float xw = q.x * q.w; float yy = q.y * q.y; float yz = q.y * q.z; float yw = q.y * q.w; float zz = q.z * q.z; float zw = q.z * q.w; res(0, 0) = 1 - 2 * (yy + zz); res(0, 1) = 2 * (xy - zw); res(0, 2) = 2 * (xz + yw); res(1, 0) = 2 * (xy + zw); res(1, 1) = 1 - 2 * (xx + zz); res(1, 2) = 2 * (yz - xw); res(2, 0) = 2 * (xz - yw); res(2, 1) = 2 * (yz + xw); res(2, 2) = 1 - 2 * (xx + yy); return res; } Quaternion Quaternion::FromFloat3x3(const Matrix3x3f &rotationMatrix) { return QuaternionFromMatrixHelper<Matrix3x3f>(rotationMatrix).Normalize(); } Quaternion Quaternion::FromFloat3x4(const Matrix3x4f &rotationMatrix) { return QuaternionFromMatrixHelper<Matrix3x4f>(rotationMatrix).Normalize(); } Quaternion Quaternion::FromFloat4x4(const Matrix4x4f &rotationMatrix) { return QuaternionFromMatrixHelper<Matrix4x4f>(rotationMatrix).Normalize(); } Matrix3x3f Quaternion::GetMatrix3x3() const { Matrix3x3f res = QuaternionToMatrixHelper<Matrix3x3f>(*this); return res; } SIMDMatrix3x3f Quaternion::GetSIMDMatrix3() const { SIMDMatrix3x3f res = QuaternionToMatrixHelper<SIMDMatrix3x3f>(*this); return res; } Matrix3x4f Quaternion::GetMatrix3x4() const { Matrix3x4f res = QuaternionToMatrixHelper<Matrix3x4f>(*this); // fill in remaining fields res[0][3] = res[1][3] = res[2][3] = res[0][3] = 0.0f; return res; } Matrix4x4f Quaternion::GetMatrix4x4() const { Matrix4x4f res = QuaternionToMatrixHelper<Matrix4x4f>(*this); // fill in remaining fields res[0][3] = res[1][3] = res[2][3] = res[0][3] = res[3][0] = res[3][1] = res[3][2] = 0.0f; res[3][3] = 1.0f; return res; } SIMDMatrix4x4f Quaternion::GetSIMDMatrix4() const { SIMDMatrix4x4f res = QuaternionToMatrixHelper<SIMDMatrix4x4f>(*this); // fill in remaining fields res[0][3] = res[1][3] = res[2][3] = res[0][3] = res[3][0] = res[3][1] = res[3][2] = 0.0f; res[3][3] = 1.0f; return res; } Quaternion Quaternion::FromTwoVectors(const Vector3f &u, const Vector3f &v) { //float cos_theta = u.Normalize().Dot(v.Normalize()); //float angle = Y_acosf(cos_theta); //float3 w(u.Cross(v).Normalize()); //return Quaternion::FromAxisAngle(w, angle); float kCosTheta = u.Dot(v); float k = Math::Sqrt(u.SquaredLength() * v.SquaredLength()); if (Math::NearEqual(kCosTheta / k, -1.0f, Y_FLT_EPSILON)) { Vector3f other((Math::Abs(u.Dot(Vector3f::UnitX)) < 1.0f) ? Vector3f::UnitX : Vector3f::UnitY); return Quaternion::FromNormalizedAxisAngle(u.Cross(other).Normalize(), 180.0f); } return Quaternion(Vector4f(u.Cross(v), kCosTheta + k)).Normalize(); } Quaternion Quaternion::FromTwoUnitVectors(const Vector3f &u, const Vector3f &v) { Vector3f w(u.Cross(v)); return Quaternion(w.x, w.y, w.z, 1.0f + u.Dot(v)); } Quaternion Quaternion::LinearInterpolate(const Quaternion &start, const Quaternion &end, float factor) { // from assimp float cosineTheta = start.x * end.x + start.y * end.y + start.z * end.z + start.w * end.w; // fix signs Quaternion newEnd; if (cosineTheta < 0.0f) { cosineTheta = -cosineTheta; newEnd.Set(-end.x, -end.y, -end.z, -end.w); } else { newEnd = end; } // calculate coefficients float sclp, sclq; if ((1.0f - cosineTheta) > Y_FLT_EPSILON) { float omega = Y_acosf(cosineTheta); float sinTheta = Math::Sin(omega); sclp = Math::Sin((1.0f - factor) * omega) / sinTheta; sclq = Math::Sin(factor * omega) / sinTheta; } else { // do lerp approximation sclp = 1.0f - factor; sclq = factor; } Quaternion returnValue; returnValue.x = sclp * start.x + sclq * newEnd.x; returnValue.y = sclp * start.y + sclq * newEnd.y; returnValue.z = sclp * start.z + sclq * newEnd.z; returnValue.w = sclp * start.w + sclq * newEnd.w; return returnValue; } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunkRenderProxy.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldChunkRenderProxy.h" #include "BlockEngine/BlockWorldChunk.h" #include "BlockEngine/BlockWorldSection.h" #include "BlockEngine/BlockWorldMesher.h" #include "BlockEngine/BlockWorld.h" #include "BlockEngine/BlockEngineCVars.h" #include "BlockEngine/BlockWorldVertexFactory.h" #include "Engine/Camera.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" #include "Renderer/Renderer.h" //#define USE_LOCAL_TO_WORLD_TRANSFORM BlockWorldChunkRenderProxy::BlockWorldChunkRenderProxy(uint32 entityID, const BlockPalette *pPalette, const float4x4 &transformMatrix, int32 lodLevel, BlockWorldMesher *pBuilder) : RenderProxy(entityID), m_pPalette(pPalette), m_transformMatrix(transformMatrix), m_lodLevel(lodLevel), m_renderResourcesCreated(false), m_pIndexBuffer(nullptr), m_indexFormat(GPU_INDEX_FORMAT_COUNT), m_pMeshInstanceBuffer(nullptr) { // we maintain a reference to the section and palette because they may be deleted before it is // removed from world if the render thread is behind m_pPalette->AddRef(); } BlockWorldChunkRenderProxy::~BlockWorldChunkRenderProxy() { if (m_pMeshInstanceBuffer != nullptr) m_pMeshInstanceBuffer->Release(); m_vertexBuffers.Clear(); if (m_pIndexBuffer != nullptr) m_pIndexBuffer->Release(); m_pPalette->Release(); } BlockWorldMesher *BlockWorldChunkRenderProxy::CreateMesher(const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel) { // find the neighbouring chunks const BlockWorldChunk *pNeighbourChunks[CUBE_FACE_COUNT]; { int32 sectionSize = pWorld->GetSectionSize(); int32 sectionSizeMinusOne = sectionSize - 1; int32 relativeX = pChunk->GetRelativeChunkX(); int32 relativeY = pChunk->GetRelativeChunkY(); int32 relativeZ = pChunk->GetRelativeChunkZ(); int32 globalX = pChunk->GetGlobalChunkX(); int32 globalY = pChunk->GetGlobalChunkY(); int32 globalZ = pChunk->GetGlobalChunkZ(); pNeighbourChunks[CUBE_FACE_LEFT] = (relativeX == 0) ? pWorld->GetChunk(globalX - 1, globalY, globalZ) : pSection->GetChunk(relativeX - 1, relativeY, relativeZ); pNeighbourChunks[CUBE_FACE_RIGHT] = (relativeX == sectionSizeMinusOne) ? pWorld->GetChunk(globalX + 1, globalY, globalZ) : pSection->GetChunk(relativeX + 1, relativeY, relativeZ); pNeighbourChunks[CUBE_FACE_BACK] = (relativeY == 0) ? pWorld->GetChunk(globalX, globalY - 1, globalZ) : pSection->GetChunk(relativeX, relativeY - 1, relativeZ); pNeighbourChunks[CUBE_FACE_FRONT] = (relativeY == sectionSizeMinusOne) ? pWorld->GetChunk(globalX, globalY + 1, globalZ) : pSection->GetChunk(relativeX, relativeY + 1, relativeZ); pNeighbourChunks[CUBE_FACE_BOTTOM] = pSection->SafeGetChunk(relativeX, relativeY, relativeZ - 1); pNeighbourChunks[CUBE_FACE_TOP] = pSection->SafeGetChunk(relativeX, relativeY, relativeZ + 1); // if anything doesn't have the lod level required, skip it for (uint32 i = 0; i < countof(pNeighbourChunks); i++) { if (pNeighbourChunks[i] != nullptr && pNeighbourChunks[i]->GetLoadedLODLevel() > lodLevel) pNeighbourChunks[i] = nullptr; } } // allocate the volume int32 chunkSize = (pChunk->GetChunkSize() >> lodLevel); int32 chunkSizeMinusOne = chunkSize - 1; int32 volumeSize = chunkSize + 2; int32 volumeSizeMinusOne = volumeSize - 1; #ifdef USE_LOCAL_TO_WORLD_TRANSFORM BlockWorldMesher *pBuilder = new BlockWorldMesher(pWorld->GetPalette(), volumeSize, lodLevel, float3::Zero, CVars::r_block_world_use_lightmaps.GetBool()); #else BlockWorldMesher *pBuilder = new BlockWorldMesher(pWorld->GetPalette(), volumeSize, lodLevel, pChunk->GetBasePosition(), CVars::r_block_world_use_lightmaps.GetBool()); #endif BlockWorldBlockType *pBlockValues = pBuilder->GetBlockValues(); BlockWorldBlockDataType *pBlockData = pBuilder->GetBlockData(); int32 srcZStride = (chunkSize * chunkSize); int32 srcYStride = (chunkSize); int32 zStride = (volumeSize * volumeSize); int32 yStride = (volumeSize); // initialize the volume to zero Y_memzero(pBuilder->GetBlockValues(), sizeof(BlockWorldBlockType) * volumeSize * volumeSize * volumeSize); Y_memzero(pBuilder->GetBlockData(), sizeof(BlockWorldBlockDataType) * volumeSize * volumeSize * volumeSize); // extract the volume information. start at the bottom, and work up in height for (int32 z = 0; z < volumeSize; z++) { BlockWorldBlockType *pLayerStart = pBlockValues + (zStride * z); BlockWorldBlockDataType *pLayerDataStart = pBlockData + (zStride * z); #define BLOCK(x_, y_) pLayerStart[(y_) * yStride + (x_)] #define BLOCKDATA(x_, y_) pLayerDataStart[(y_) * yStride + (x_)] // the corners should always be zero //BLOCK(0, 0) = 0; //BLOCK(0, volumeSizeMinusOne) = 0; //BLOCK(volumeSizeMinusOne, 0) = 0; //BLOCK(volumeSizeMinusOne, volumeSizeMinusOne) = 0; // bottom slab? if (z == 0) { // copy the bottom slab's top layer to our bottom slab if (pNeighbourChunks[CUBE_FACE_BOTTOM] != nullptr) { Y_memcpy_stride(&BLOCK(1, 1), sizeof(BlockWorldBlockType) * yStride, pNeighbourChunks[CUBE_FACE_BOTTOM]->GetBlockValues(lodLevel) + (srcZStride * chunkSizeMinusOne), sizeof(BlockWorldBlockType) * srcYStride, sizeof(BlockWorldBlockType) * chunkSize, chunkSize); Y_memcpy_stride(&BLOCKDATA(1, 1), sizeof(BlockWorldBlockDataType) * yStride, pNeighbourChunks[CUBE_FACE_BOTTOM]->GetBlockData(lodLevel) + (srcZStride * chunkSizeMinusOne), sizeof(BlockWorldBlockDataType) * srcYStride, sizeof(BlockWorldBlockDataType) * chunkSize, chunkSize); } } // top slab? else if (z == volumeSizeMinusOne) { // copy the bottom slab's bottom layer to our top slab if (pNeighbourChunks[CUBE_FACE_TOP] != nullptr) { Y_memcpy_stride(&BLOCK(1, 1), sizeof(BlockWorldBlockType) * yStride, pNeighbourChunks[CUBE_FACE_TOP]->GetBlockValues(lodLevel), sizeof(BlockWorldBlockType) * srcYStride, sizeof(BlockWorldBlockType) * chunkSize, chunkSize); Y_memcpy_stride(&BLOCKDATA(1, 1), sizeof(BlockWorldBlockDataType) * yStride, pNeighbourChunks[CUBE_FACE_TOP]->GetBlockData(lodLevel), sizeof(BlockWorldBlockDataType) * srcYStride, sizeof(BlockWorldBlockDataType) * chunkSize, chunkSize); } } // normal slabs else { // set the left-most column to what's on the left chunk if (pNeighbourChunks[CUBE_FACE_LEFT] != nullptr) { for (int32 y = 0; y < chunkSize; y++) { BLOCK(0, y + 1) = pNeighbourChunks[CUBE_FACE_LEFT]->GetBlock(lodLevel, chunkSizeMinusOne, y, z - 1); BLOCKDATA(0, y + 1) = pNeighbourChunks[CUBE_FACE_LEFT]->GetBlockData(lodLevel, chunkSizeMinusOne, y, z - 1); } } // set the right-most column to what's on the right chunk if (pNeighbourChunks[CUBE_FACE_RIGHT] != nullptr) { for (int32 y = 0; y < chunkSize; y++) { BLOCK(volumeSizeMinusOne, y + 1) = pNeighbourChunks[CUBE_FACE_RIGHT]->GetBlock(lodLevel, 0, y, z - 1); BLOCKDATA(volumeSizeMinusOne, y + 1) = pNeighbourChunks[CUBE_FACE_RIGHT]->GetBlockData(lodLevel, 0, y, z - 1); } } // set the first row to what's on the back chunk if (pNeighbourChunks[CUBE_FACE_BACK] != nullptr) { for (int32 x = 0; x < chunkSize; x++) { BLOCK(x + 1, 0) = pNeighbourChunks[CUBE_FACE_BACK]->GetBlock(lodLevel, x, chunkSizeMinusOne, z - 1); BLOCKDATA(x + 1, 0) = pNeighbourChunks[CUBE_FACE_BACK]->GetBlockData(lodLevel, x, chunkSizeMinusOne, z - 1); } } // set the last row to what's on the front chunk if (pNeighbourChunks[CUBE_FACE_FRONT] != nullptr) { for (int32 x = 0; x < chunkSize; x++) { BLOCK(x + 1, volumeSizeMinusOne) = pNeighbourChunks[CUBE_FACE_FRONT]->GetBlock(lodLevel, x, 0, z - 1); BLOCKDATA(x + 1, volumeSizeMinusOne) = pNeighbourChunks[CUBE_FACE_FRONT]->GetBlockData(lodLevel, x, 0, z - 1); } } // set everything else to the actual chunk data //Y_memcpy_stride(&BLOCK(1, 1), yStride, pChunk->GetBlockValues(lodLevel) + (srcZStride * (z - 1)), sizeof(BlockWorldBlockType) * srcYStride, sizeof(BlockWorldBlockType) * chunkSize, chunkSize); for (int32 y = 0; y < chunkSize; y++) { for (int32 x = 0; x < chunkSize; x++) { BLOCK(x + 1, y + 1) = pChunk->GetBlock(lodLevel, x, y, z - 1); BLOCKDATA(x + 1, y + 1) = pChunk->GetBlockData(lodLevel, x, y, z - 1); } } } #undef BLOCKDATA #undef BLOCK } // // invoke builder // pBuilder->GenerateMesh(); // // // if nothing was output, bail out // if (pBuilder->GetOutputBatchCount() == 0 && pBuilder->GetOutputLightCount() == 0 && pBuilder->GetOutputMeshInstancesCount() == 0) // { // delete pBuilder; // return nullptr; // } return pBuilder; } BlockWorldChunkRenderProxy *BlockWorldChunkRenderProxy::CreateForChunk(uint32 entityID, const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel, BlockWorldMesher *pBuilder) { // create transform matrix float3 basePosition(pChunk->GetBasePosition()); #ifdef USE_LOCAL_TO_WORLD_TRANSFORM float4x4 transformMatrix(float4x4::MakeTranslationMatrix(pChunk->GetBasePosition())); #else float4x4 transformMatrix(float4x4::Identity); #endif // create chunk BlockWorldChunkRenderProxy *pRenderProxy = new BlockWorldChunkRenderProxy(entityID, pWorld->GetPalette(), transformMatrix, lodLevel, pBuilder); // set initial bounds #ifdef USE_LOCAL_TO_WORLD_TRANSFORM pRenderProxy->SetBounds(AABox(pBuilder->GetOutputBoundingBox().GetMinBounds() + basePosition, pBuilder->GetOutputBoundingBox().GetMaxBounds() + basePosition), Sphere(pBuilder->GetOutputBoundingSphere().GetCenter() + basePosition, pBuilder->GetOutputBoundingSphere().GetRadius())); #else pRenderProxy->SetBounds(pBuilder->GetOutputBoundingBox(), pBuilder->GetOutputBoundingSphere()); #endif // upload to gpu, either deferred or immediate if (g_pRenderer->GetCapabilities().SupportsMultithreadedResourceCreation) { // if deferred upload fails, queue it for next frame if (!pRenderProxy->UploadMeshToGPU(pBuilder)) pRenderProxy->QueueMeshUpload(pBuilder); } else { pRenderProxy->QueueMeshUpload(pBuilder); } // done return pRenderProxy; } bool BlockWorldChunkRenderProxy::RebuildForChunk(const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel, BlockWorldMesher *pBuilder) { // queue upload always QueueMeshUpload(pBuilder); return true; } void BlockWorldChunkRenderProxy::QueueMeshUpload(BlockWorldMesher *pBuilder) { DebugAssert(pBuilder != nullptr); // upload from render thread ReferenceCountedHolder<BlockWorldChunkRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, pBuilder]() { pThis->ReleaseDeviceResources(); if (!pThis->UploadMeshToGPU(pBuilder)) { // upload failed :/ try again next frame.. // this is basically a hack due to if we're not using threaded rendering, // the command will execute immediately, if it fails, again, causing a // stack overflow, so we ping-pong it back to the main thread QUEUE_MAIN_THREAD_LAMBDA_COMMAND([pThis, pBuilder]() { pThis->QueueMeshUpload(pBuilder); }); } }); } bool BlockWorldChunkRenderProxy::UploadMeshToGPU(BlockWorldMesher *pBuilder) { // create the gpu buffers if (!pBuilder->CreateGPUBuffers(&m_vertexBuffers, &m_pIndexBuffer, &m_indexFormat, &m_pMeshInstanceBuffer)) return false; // copy batches for (uint32 i = 0; i < pBuilder->GetOutputBatchCount(); i++) { const BlockWorldMesher::Batch &inBatch = pBuilder->GetOutputBatches().GetElement(i); m_renderBatches.Emplace(inBatch.MaterialIndex, inBatch.StartIndex, inBatch.NumIndices); } // copy mesh instances for (uint32 i = 0; i < pBuilder->GetOutputMeshInstancesCount(); i++) { const BlockWorldMesher::MeshInstances *inInstances = pBuilder->GetOutputMeshInstances().GetElement(i); m_renderMeshInstances.Emplace(inInstances->MeshIndex, inInstances->BufferOffset, inInstances->Transforms.GetSize()); } // fixup bounds #ifdef USE_LOCAL_TO_WORLD_TRANSFORM float3 basePosition(m_transformMatrix.GetColumn(3).xyz()); // hackity hack SetBounds(AABox(pBuilder->GetOutputBoundingBox().GetMinBounds() + basePosition, pBuilder->GetOutputBoundingBox().GetMaxBounds() + basePosition), Sphere(pBuilder->GetOutputBoundingSphere().GetCenter() + basePosition, pBuilder->GetOutputBoundingSphere().GetRadius())); #else SetBounds(pBuilder->GetOutputBoundingBox(), pBuilder->GetOutputBoundingSphere()); #endif // copy lights m_lights.Clear(); m_lights.AddArray(pBuilder->GetOutputLights()); // update lod level m_lodLevel = pBuilder->GetLODLevel(); // clean up delete pBuilder; m_renderResourcesCreated = true; return true; } bool BlockWorldChunkRenderProxy::CreateDeviceResources() const { if (m_renderResourcesCreated) return true; // can't create from this method return false; } void BlockWorldChunkRenderProxy::ReleaseDeviceResources() const { m_renderResourcesCreated = false; SAFE_RELEASE(m_pMeshInstanceBuffer); SAFE_RELEASE(m_pIndexBuffer); m_vertexBuffers.Clear(); m_indexFormat = GPU_INDEX_FORMAT_COUNT; m_renderMeshInstances.Clear(); m_renderBatches.Clear(); m_lights.Clear(); } void BlockWorldChunkRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // ensure upload has been done if (!m_renderResourcesCreated && !CreateDeviceResources()) return; // add lights if (pRenderQueue->IsAcceptingLights()) { for (const RENDER_QUEUE_POINT_LIGHT_ENTRY &light : m_lights) { if (pCamera->GetFrustum().SphereIntersection(Sphere(light.Position, light.Range))) pRenderQueue->AddLight(&light); } } // Store the requested render passes. uint32 wantedRenderPasses; if (CVars::r_block_world_use_lightmaps.GetBool()) wantedRenderPasses = RENDER_PASSES_DEFAULT | RENDER_PASS_LIGHTMAP; else wantedRenderPasses = RENDER_PASSES_DEFAULT; // cvar r_block_terrain_shadows ? //if (m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) wantedRenderPasses |= RENDER_PASS_SHADOW_MAP; //if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) //wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; // early exit? wantedRenderPasses &= pRenderQueue->GetAcceptingRenderPassMask(); if (wantedRenderPasses == 0) return; // get view distance float3 boundingBoxCenter(GetBoundingBox().GetCenter()); float viewDistance = pCamera->CalculateDepthToPoint(boundingBoxCenter); // cull based on xy distance if (viewDistance > pCamera->GetObjectCullDistance()) return; // get batches for (uint32 batchIndex = 0; batchIndex < m_renderBatches.GetSize(); batchIndex++) { const RenderBatch &renderBatch = m_renderBatches[batchIndex]; const Material *pMaterial = m_pPalette->GetMaterial(renderBatch.MaterialIndex); //if (renderBatch.MaterialIndex > 2) //pMaterial = g_pResourceManager->GetDefaultMaterial(); // get pass mask uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { // create queue entry for base layer RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory); queueEntry.pMaterial = pMaterial; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.RenderPassMask = renderPassMask; queueEntry.VertexFactoryFlags = 0; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); queueEntry.UserData[0] = 0; queueEntry.UserData[1] = batchIndex; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); // create occluder if enabled //if (pRenderQueue->IsAcceptingOccluders() && CVars::r_block_world_occlusion.GetBool()) //pRenderQueue->AddOccluder(this, queueEntry.BoundingBox, queueEntry.UserData, queueEntry.UserDataPointer); } } // occluder if (pRenderQueue->IsAcceptingOccluders() && CVars::r_block_world_occlusion.GetBool() && m_lodLevel == 0) pRenderQueue->AddOccluder(this, GetBoundingBox()); // add instances for (uint32 meshIndex = 0; meshIndex < m_renderMeshInstances.GetSize(); meshIndex++) { const RenderMeshInstance &renderMeshInstance = m_renderMeshInstances[meshIndex]; const StaticMesh *pMesh = m_pPalette->GetMesh(renderMeshInstance.MeshIndex); uint32 meshLODLevel = 0; for (uint32 meshBatchIndex = 0; meshBatchIndex < pMesh->GetLOD(meshLODLevel)->GetBatchCount(); meshBatchIndex++) { const StaticMesh::Batch *pBatch = pMesh->GetLOD(meshLODLevel)->GetBatch(meshBatchIndex); const Material *pMaterial = pMesh->GetMaterial(pBatch->MaterialIndex); uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(RENDER_PASSES_DEFAULT & pRenderQueue->GetAcceptingRenderPassMask()); if (renderPassMask != 0) { RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); queueEntry.pMaterial = pMaterial; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.RenderPassMask = renderPassMask; queueEntry.VertexFactoryFlags = pMesh->GetVertexFactoryFlags() | LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); queueEntry.UserData[0] = meshIndex + 1; queueEntry.UserData[1] = meshLODLevel; queueEntry.UserData[2] = meshBatchIndex; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } // debug stuff if (pRenderQueue->IsAcceptingDebugObjects() && CVars::r_block_world_show_lods.GetBool()) { pRenderQueue->AddDebugInfoObject(this); } } void BlockWorldChunkRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { if (pQueueEntry->UserData[0] == 0) { pCommandList->GetConstants()->SetLocalToWorldMatrix(m_transformMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); m_vertexBuffers.BindBuffers(pCommandList); pCommandList->SetIndexBuffer(m_pIndexBuffer, m_indexFormat, 0); } else { const RenderMeshInstance &renderMeshInstance = m_renderMeshInstances[pQueueEntry->UserData[0] - 1]; const StaticMesh *pMesh = m_pPalette->GetMesh(renderMeshInstance.MeshIndex); const StaticMesh::LOD *pLOD = pMesh->GetLOD(pQueueEntry->UserData[1]); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_transformMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pCommandList->SetVertexBuffer(0, pLOD->GetVertexBuffers()->GetBuffer(0), pLOD->GetVertexBuffers()->GetBufferOffset(0), pLOD->GetVertexBuffers()->GetBufferStride(0)); pCommandList->SetVertexBuffer(1, m_pMeshInstanceBuffer, renderMeshInstance.InstanceBufferOffset, sizeof(float3x4)); pCommandList->SetIndexBuffer(pLOD->GetIndexBuffer(), pLOD->GetIndexFormat(), 0); } } void BlockWorldChunkRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { if (pQueueEntry->UserData[0] == 0) { uint32 batchIndex = pQueueEntry->UserData[1]; DebugAssert(batchIndex < m_renderBatches.GetSize()); const RenderBatch &renderBatch = m_renderBatches[batchIndex]; pCommandList->DrawIndexed(renderBatch.StartIndex, renderBatch.IndexCount, 0); } else { const RenderMeshInstance &renderMeshInstance = m_renderMeshInstances[pQueueEntry->UserData[0] - 1]; const StaticMesh *pMesh = m_pPalette->GetMesh(renderMeshInstance.MeshIndex); const StaticMesh::LOD *pLOD = pMesh->GetLOD(pQueueEntry->UserData[1]); const StaticMesh::Batch *pBatch = pLOD->GetBatch(pQueueEntry->UserData[2]); pCommandList->DrawIndexedInstanced(pBatch->StartIndex, pBatch->NumIndices, 0, renderMeshInstance.InstanceCount); } } void BlockWorldChunkRenderProxy::DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const { if (CVars::r_block_world_show_lods.GetBool()) { static const uint32 lodColors[] = { MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255), MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 255, 255), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255), MAKE_COLOR_R8G8B8A8_UNORM(128, 255, 128, 255) }; uint32 color = (m_lodLevel >= countof(lodColors)) ? lodColors[countof(lodColors) - 1] : lodColors[m_lodLevel]; pGUIContext->SetDepthTestingEnabled(false); pGUIContext->SetAlphaBlendingEnabled(false); pGUIContext->Draw3DWireBox(GetBoundingBox(), color); } } <file_sep>/Engine/Source/Renderer/Shaders/OneColorShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/OneColorShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(OneColorShader); BEGIN_SHADER_COMPONENT_PARAMETERS(OneColorShader) DEFINE_SHADER_COMPONENT_PARAMETER("DrawColor", SHADER_PARAMETER_TYPE_FLOAT4) END_SHADER_COMPONENT_PARAMETERS() void OneColorShader::SetColor(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const float4 &col) { pShaderProgram->SetBaseShaderParameterValue(pCommandList, 0, SHADER_PARAMETER_TYPE_FLOAT4, &col); } bool OneColorShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL) return false; return true; } bool OneColorShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/OneColorShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/OneColorShader.hlsl", "PSMain"); return true; } <file_sep>/Engine/Source/GameFramework/StaticMeshEntity.h #pragma once #include "Engine/Entity.h" class StaticMesh; namespace Physics { class CollisionObject; } class StaticMeshRenderProxy; class StaticMeshEntity : public Entity { DECLARE_ENTITY_TYPEINFO(StaticMeshEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(StaticMeshEntity); public: StaticMeshEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~StaticMeshEntity(); // property accessors const StaticMesh *GetStaticMesh() const { return m_pStaticMesh; } const bool IsVisible() const { return m_visible; } const uint32 GetShadowFlags() const { return m_shadowFlags; } const bool IsCollidable() const { return m_collidable; } // property setters void SetStaticMesh(const StaticMesh *pStaticMesh); void SetVisible(bool visible); void SetCollidable(bool collidable); void SetShadowFlags(uint32 shadowFlags); // External creation method void Create(uint32 entityID, ENTITY_MOBILITY mobility = ENTITY_MOBILITY_MOVABLE, const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const StaticMesh *pStaticMesh = nullptr, bool visible = true, bool collidable = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // implemented methods virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; virtual void OnComponentBoundsChange() override; private: // property callbacks static bool PropertyCallbackGetStaticMeshName(ThisClass *pEntity, const void *pUserData, String *pValue); static bool PropertyCallbackSetStaticMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue); static void PropertyCallbackStaticMeshChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackVisibleChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackCollidableChanged(ThisClass *pEntity, const void *pUserData = nullptr); // update methods void UpdateRenderProxy(); void UpdateCollisionObject(); void UpdateBounds(); // vars const StaticMesh *m_pStaticMesh; bool m_visible; bool m_collidable; uint32 m_shadowFlags; // render proxy StaticMeshRenderProxy *m_pRenderProxy; // physics proxy Physics::CollisionObject *m_pCollisionObject; }; <file_sep>/Engine/Source/Renderer/DecalManager.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/DecalManager.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/Camera.h" #include "Engine/Material.h" Log_SetChannel(DecalManager); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// StaticDecal::StaticDecal(const AABox &boundingBox, const Sphere &boundingSphere, const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance, float lifetime, uint32 entityID) : RenderProxy(entityID), m_position(position), m_normal(normal), m_size(size), m_pMaterial(pMaterial), m_drawDistance(drawDistance), m_lifeRemaining(lifetime), m_pVertexBuffer(NULL) { SetBounds(boundingBox, boundingSphere); m_pMaterial->AddRef(); } StaticDecal::StaticDecal(const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance, float lifetime, uint32 entityID) : RenderProxy(entityID), m_position(position), m_normal(normal), m_size(size), m_pMaterial(pMaterial), m_drawDistance(drawDistance), m_lifeRemaining(lifetime), m_pVertexBuffer(NULL) { m_pMaterial->AddRef(); } StaticDecal::~StaticDecal() { m_pMaterial->Release(); if (m_pVertexBuffer != NULL) m_pVertexBuffer->Release(); } void StaticDecal::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // available mask for decals //const uint32 availableRenderPasses = RENDER_PASSES_DEFAULT; // get distance float distance = pCamera->CalculateDepthToPoint(m_position); // out of range? if (distance > m_drawDistance) return; // queue it //RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; //queueEntry.BoundingBox = } void StaticDecal::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { } void StaticDecal::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { } void StaticDecal::Rebuild(const float3 &position, const float3 &normal, const float2 &size) { // generate decal mesh DecalMeshGenerator decalMeshGenerator(position, normal, size.x, size.y); // collect vertices from objects RenderProxy::IntersectingTriangleArray intersectingTriangles; GetRenderWorld()->EnumerateRenderablesInAABox(decalMeshGenerator.GetDecalBox(), [&decalMeshGenerator, &intersectingTriangles](const RenderProxy *pRenderProxy) { pRenderProxy->GetIntersectingTriangles(decalMeshGenerator.GetDecalBox(), intersectingTriangles); }); // convert format Log_DevPrintf("%u intersecting triangles", intersectingTriangles.GetSize()); // generate triangles //uint32 nTriangles = decalMeshGenerator.GenerateDecalTriangles(intersectingTriangles); // calculate bounding box from vertices AABox boundingBox(decalMeshGenerator.GetBoundingBox()); Sphere boundingSphere(Sphere::FromAABox(boundingBox)); // update bounding box/sphere SetBounds(boundingBox, boundingSphere); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DecalManager::DecalManager(RenderWorld *pRenderWorld) : m_pRenderWorld(pRenderWorld) { } DecalManager::~DecalManager() { for (uint32 i = 0; i < m_staticDecals.GetSize(); i++) { m_pRenderWorld->RemoveRenderable(m_staticDecals[i]); m_staticDecals[i]->Release(); } } StaticDecal *DecalManager::CreateStaticDecal(const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance /*= Y_FLT_MAX*/, float lifetime /*= Y_FLT_INFINITE*/) { return NULL; } void DecalManager::MoveStaticDecal(StaticDecal *pDecal, const float3 &position, const float3 &normal) { } void DecalManager::ResizeStaticDecal(StaticDecal *pDecal, const float3 &size) { } void DecalManager::RemoveStaticDecal(StaticDecal *pDecal) { } StaticDecal *DecalManager::ProjectStaticDecal(const Ray &ray, const float2 &size, const Material *pMaterial, float drawDistance /*= Y_FLT_MAX*/, float lifetime /*= Y_FLT_INFINITE*/) { return nullptr; } void DecalManager::Tick(const float timeDifference) { } DecalMeshGenerator::DecalMeshGenerator(const float3 &position, const float3 &normal, const float width, const float height) : m_position(position), m_normal(normal), m_width(width), m_height(height), m_depth(Max(width, height)), m_rightVector(float3::UnitX), m_upVector(float3::UnitZ), m_decalBox(AABox::Zero), m_boundingBox(AABox::Zero) { CalculateDecalFrame(); CalculateDecalBox(); } DecalMeshGenerator::~DecalMeshGenerator() { } uint32 DecalMeshGenerator::GenerateDecalTriangles(const RenderProxy::IntersectingTriangleArray &inputTriangles) { return 0; } void DecalMeshGenerator::CalculateDecalFrame() { if (m_normal == float3::UnitZ) m_rightVector = float3::UnitX; else if (m_normal == float3::NegativeUnitZ) m_rightVector = float3::NegativeUnitX; else m_rightVector = (-m_normal).Cross(float3::UnitZ).Normalize(); m_upVector = m_rightVector.Cross(-m_normal).Normalize(); } void DecalMeshGenerator::CalculateDecalBox() { // get the maximum dimension float halfDepth = m_depth * 0.5f; float halfWidth = m_width * 0.5f; float halfHeight = m_height * 0.5f; // width float3 leftSide(m_position + (-m_rightVector) * halfWidth); float3 rightSide(m_position + (m_rightVector)* halfWidth); float3 topSide(m_position + (m_upVector)* halfHeight); float3 bottomSide(m_position + (-m_upVector) * halfHeight); float3 frontSide(m_position + (m_normal)* halfDepth); float3 backSide(m_position + (-m_normal) * halfDepth); AABox decalBox(m_position, m_position); decalBox.Merge(leftSide); decalBox.Merge(rightSide); decalBox.Merge(topSide); decalBox.Merge(bottomSide); decalBox.Merge(frontSide); decalBox.Merge(backSide); m_decalBox = decalBox; } void DecalMeshGenerator::CalculateBoundingBox() { } void DecalMeshGenerator::CalculateClippingPlanes() { float3 planeNormal; float3 planeRefPoint; planeNormal = m_normal; planeRefPoint = m_position + (planeNormal * m_depth); m_clippingPlanes[0] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); planeNormal = -m_normal; planeRefPoint = m_position + (planeNormal * m_depth); m_clippingPlanes[1] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); planeNormal = m_rightVector; planeRefPoint = m_position + (planeNormal * m_width); m_clippingPlanes[2] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); planeNormal = -m_rightVector; planeRefPoint = m_position + (planeNormal * m_width); m_clippingPlanes[3] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); planeNormal = m_upVector; planeRefPoint = m_position + (planeNormal * m_height); m_clippingPlanes[4] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); planeNormal = -m_upVector; planeRefPoint = m_position + (planeNormal * m_height); m_clippingPlanes[5] = Plane(planeNormal, planeRefPoint.Dot(planeNormal)); } void DecalMeshGenerator::GenerateClippedTriangles(const RenderProxy::IntersectingTriangleArray &inputTriangles) { } <file_sep>/Engine/Source/Renderer/RenderProxy.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderQueue.h" class Camera; class RenderWorld; class GPUCommandList; class MiniGUIContext; class ShaderProgram; class RenderProxy : public ReferenceCounted { friend class RenderWorld; public: RenderProxy(uint32 entityId); virtual ~RenderProxy(); uint32 GetEntityId() const { return m_iEntityId; } bool IsInWorld() const { return (m_pRenderWorld != nullptr); } const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } RenderWorld *GetRenderWorld() const { return m_pRenderWorld; } void SetEntityID(uint32 entityId) { m_iEntityId = entityId; } void SetBounds(const AABox &boundingBox, const Sphere &boundingSphere); virtual void OnAddToRenderWorld(RenderWorld *pRenderWorld) { } virtual void OnRemoveFromRenderWorld(RenderWorld *pRenderWorld) { } virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { } virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { } virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { } virtual void DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const { } virtual bool CreateDeviceResources() const { return true; } virtual void ReleaseDeviceResources() const { } // todo: (for decals) // RayCast // GetIntersectingTriangles virtual bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const { return false; } struct IntersectingTriangle { float3 Vertices[3]; float3 Normal; IntersectingTriangle() {} IntersectingTriangle(const float3 &v0, const float3 &v1, const float3 &v2, const float3 &normal) { Vertices[0] = v0; Vertices[1] = v1; Vertices[2] = v2; Normal = normal; } }; typedef MemArray<IntersectingTriangle> IntersectingTriangleArray; virtual uint32 GetIntersectingTriangles(const AABox &searchBox, IntersectingTriangleArray &intersectingTriangles) const { return 0; } private: uint32 m_iEntityId; AABox m_boundingBox; Sphere m_boundingSphere; RenderWorld *m_pRenderWorld; }; <file_sep>/Engine/Source/MathLib/Angle.cpp #include "MathLib/Angle.h" Angle::Angle(float degrees) : m_radians(Math::DegreesToRadians(degrees)) { } Angle::Angle(const Angle &angle) : m_radians(angle.m_radians) { } float Angle::Degrees() const { return Math::RadiansToDegrees(m_radians); } float Angle::Radians() const { return m_radians; } Angle Angle::Degrees(float degrees) { Angle ret; ret.m_radians = Math::DegreesToRadians(degrees); return ret; } Angle Angle::Radians(float radians) { Angle ret; ret.m_radians = radians; return ret; } void Angle::SetDegrees(float degrees) { m_radians = Math::DegreesToRadians(degrees); } void Angle::SetRadians(float radians) { m_radians = radians; } void Angle::Normalize() { m_radians = Math::NormalizeAngle(m_radians); } Angle Angle::Normalized() const { Angle ret; ret.m_radians = Math::NormalizeAngle(m_radians); return ret; } bool Angle::operator==(const Angle &other) const { return Math::NearEqual(m_radians, other.m_radians, Y_FLT_EPSILON); } bool Angle::operator!=(const Angle &other) const { return !Math::NearEqual(m_radians, other.m_radians, Y_FLT_EPSILON); } bool Angle::operator>=(const Angle &other) const { return m_radians >= other.m_radians; } bool Angle::operator<=(const Angle &other) const { return m_radians <= other.m_radians; } bool Angle::operator<(const Angle &other) const { return m_radians < other.m_radians; } bool Angle::operator>(const Angle &other) const { return m_radians > other.m_radians; } Angle &Angle::operator=(const Angle &other) { m_radians = other.m_radians; return *this; } Angle &Angle::operator+=(const Angle &other) { m_radians += other.m_radians; return *this; } Angle &Angle::operator-=(const Angle &other) { m_radians -= other.m_radians; return *this; } Angle Angle::operator+(const Angle &other) const { Angle ret; ret.m_radians = m_radians + other.m_radians; return ret; } Angle Angle::operator-(const Angle &other) const { Angle ret; ret.m_radians = m_radians - other.m_radians; return ret; } <file_sep>/Engine/Source/Engine/ParticleSystem.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystem.h" #include "Engine/DataFormats.h" #include "ResourceCompiler/ParticleSystemGenerator.h" #include "Core/ClassTable.h" DEFINE_RESOURCE_TYPE_INFO(ParticleSystem); DEFINE_RESOURCE_GENERIC_FACTORY(ParticleSystem); ParticleSystem::ParticleSystem(const ResourceTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : m_updateInterval(1.0f) { } ParticleSystem::~ParticleSystem() { for (uint32 i = 0; i < m_emitters.GetSize(); i++) delete m_emitters[i]; } void ParticleSystem::AddEmitter(const ParticleSystemEmitter *pEmitter) { m_emitters.Add(pEmitter); m_updateInterval = Min(m_updateInterval, pEmitter->GetUpdateInterval()); } void ParticleSystem::RemoveEmitter(const ParticleSystemEmitter *pEmitter) { int32 index = m_emitters.IndexOf(pEmitter); DebugAssert((uint32)index < m_emitters.GetSize()); m_emitters.OrderedRemove(index); } // bool ParticleSystem::InitializeInstance(InstanceData *pInstanceData) const // { // // } // // void ParticleSystem::CleanupInstance(InstanceData *pInstanceData) const // { // // } // // void ParticleSystem::UpdateInstance(InstanceData *pInstanceData, float deltaTime) const // { // // } bool ParticleSystem::LoadFromStream(const char *name, ByteStream *pStream) { BinaryReader binaryReader(pStream); uint64 headerOffset = binaryReader.GetStreamPosition(); // read header DF_PARTICLE_SYSTEM_HEADER particleSystemHeader; if (!binaryReader.SafeReadBytes(&particleSystemHeader, sizeof(particleSystemHeader))) return false; // check header if (particleSystemHeader.HeaderSize < sizeof(DF_PARTICLE_SYSTEM_HEADER) || particleSystemHeader.Magic != DF_PARTICLE_SYSTEM_HEADER_MAGIC || particleSystemHeader.EmitterCount == 0) { return false; } // load class table ClassTable classTable; if (!binaryReader.SafeSeekAbsolute(headerOffset + particleSystemHeader.ClassTableOffset) || !classTable.LoadFromStream(pStream, true)) return false; // allocate emitters m_emitters.Reserve(particleSystemHeader.EmitterCount); if (!binaryReader.SafeSeekAbsolute(headerOffset + particleSystemHeader.EmitterOffset)) return false; // load emitters for (uint32 emitterIndex = 0; emitterIndex < particleSystemHeader.EmitterCount; emitterIndex++) { DF_PARTICLE_SYSTEM_EMITTER_HEADER emitterHeader; uint64 emitterStartOffset = binaryReader.GetStreamPosition(); if (!binaryReader.SafeReadBytes(&emitterHeader, sizeof(emitterHeader))) return false; // seek to emitter properties if (!binaryReader.SafeSeekAbsolute(emitterHeader.PropertiesOffset)) return false; // create emitter object Object *pEmitterObject = classTable.UnserializeObject(pStream, emitterHeader.TypeIndex); ParticleSystemEmitter *pEmitter = (pEmitterObject != nullptr) ? pEmitterObject->SafeCast<ParticleSystemEmitter>() : nullptr; if (pEmitter == nullptr) { delete pEmitterObject; return false; } // reserve modules pEmitter->m_modules.Reserve(emitterHeader.ModuleCount); m_emitters.Add(pEmitter); // move to start of modules if (!binaryReader.SafeSeekAbsolute(emitterHeader.ModuleOffset)) return false; // load modules for (uint32 moduleIndex = 0; moduleIndex < emitterHeader.ModuleCount; moduleIndex++) { DF_PARTICLE_SYSTEM_MODULE_HEADER moduleHeader; uint64 moduleStartOffset = binaryReader.GetStreamPosition(); if (!binaryReader.SafeReadBytes(&moduleHeader, sizeof(moduleHeader))) return false; Object *pModuleObject = classTable.UnserializeObject(pStream, moduleHeader.TypeIndex); ParticleSystemModule *pModule = (pModuleObject != nullptr) ? pModuleObject->SafeCast<ParticleSystemModule>() : nullptr; if (pModuleObject == nullptr) { delete pModuleObject; return false; } pEmitter->m_modules.Add(pModule); // seek to next module if (!binaryReader.SafeSeekAbsolute(moduleStartOffset + moduleHeader.TotalSize)) return false; } // update interval fixup m_updateInterval = (emitterIndex == 0) ? pEmitter->GetUpdateInterval() : Min(m_updateInterval, pEmitter->GetUpdateInterval()); // seek to next emitter offset if (!binaryReader.SafeSeekAbsolute(emitterStartOffset + emitterHeader.TotalSize)) return false; } // done m_strName = name; return true; } <file_sep>/Engine/Source/OpenGLRenderer/CMakeLists.txt set(HEADER_FILES OpenGLCommon.h OpenGLCVars.h OpenGLDefines.h OpenGLGPUBuffer.h OpenGLGPUContext.h OpenGLGPUQuery.h OpenGLGPUShaderProgram.h OpenGLGPUTexture.h OpenGLRenderer.h OpenGLRendererOutputBuffer.h OpenGLShaderCacheEntry.h ) set(SOURCE_FILES OpenGLCVars.cpp OpenGLDefines.cpp OpenGLGPUBuffer.cpp OpenGLGPUContext.cpp OpenGLGPUQuery.cpp OpenGLGPUShaderProgram.cpp OpenGLGPUTexture.cpp OpenGLRenderer.cpp OpenGLRendererOutputBuffer.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${OPENGL_INCLUDE_DIR} ${SDL2_INCLUDE_DIR}) add_library(EngineOpenGLRenderer STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineOpenGLRenderer EngineMain EngineCore glad ${OPENGL_LIBRARIES} ${EXTRA_LIBRARIES}) <file_sep>/Editor/Source/Editor/moc_EditorRendererSwapChainWidget.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorRendererSwapChainWidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorRendererSwapChainWidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorRendererSwapChainWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorRendererSwapChainWidget_t { QByteArrayData data[18]; char stringdata[250]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorRendererSwapChainWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorRendererSwapChainWidget_t qt_meta_stringdata_EditorRendererSwapChainWidget = { { QT_MOC_LITERAL(0, 0, 29), // "EditorRendererSwapChainWidget" QT_MOC_LITERAL(1, 30, 12), // "ResizedEvent" QT_MOC_LITERAL(2, 43, 0), // "" QT_MOC_LITERAL(3, 44, 10), // "PaintEvent" QT_MOC_LITERAL(4, 55, 16), // "GainedFocusEvent" QT_MOC_LITERAL(5, 72, 14), // "LostFocusEvent" QT_MOC_LITERAL(6, 87, 13), // "KeyboardEvent" QT_MOC_LITERAL(7, 101, 16), // "const QKeyEvent*" QT_MOC_LITERAL(8, 118, 14), // "pKeyboardEvent" QT_MOC_LITERAL(9, 133, 10), // "MouseEvent" QT_MOC_LITERAL(10, 144, 18), // "const QMouseEvent*" QT_MOC_LITERAL(11, 163, 11), // "pMouseEvent" QT_MOC_LITERAL(12, 175, 10), // "WheelEvent" QT_MOC_LITERAL(13, 186, 18), // "const QWheelEvent*" QT_MOC_LITERAL(14, 205, 11), // "pWheelEvent" QT_MOC_LITERAL(15, 217, 9), // "DropEvent" QT_MOC_LITERAL(16, 227, 11), // "QDropEvent*" QT_MOC_LITERAL(17, 239, 10) // "pDropEvent" }, "EditorRendererSwapChainWidget\0" "ResizedEvent\0\0PaintEvent\0GainedFocusEvent\0" "LostFocusEvent\0KeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "MouseEvent\0const QMouseEvent*\0pMouseEvent\0" "WheelEvent\0const QWheelEvent*\0pWheelEvent\0" "DropEvent\0QDropEvent*\0pDropEvent" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorRendererSwapChainWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 8, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 8, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 54, 2, 0x06 /* Public */, 3, 0, 55, 2, 0x06 /* Public */, 4, 0, 56, 2, 0x06 /* Public */, 5, 0, 57, 2, 0x06 /* Public */, 6, 1, 58, 2, 0x06 /* Public */, 9, 1, 61, 2, 0x06 /* Public */, 12, 1, 64, 2, 0x06 /* Public */, 15, 1, 67, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 7, 8, QMetaType::Void, 0x80000000 | 10, 11, QMetaType::Void, 0x80000000 | 13, 14, QMetaType::Void, 0x80000000 | 16, 17, 0 // eod }; void EditorRendererSwapChainWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorRendererSwapChainWidget *_t = static_cast<EditorRendererSwapChainWidget *>(_o); switch (_id) { case 0: _t->ResizedEvent(); break; case 1: _t->PaintEvent(); break; case 2: _t->GainedFocusEvent(); break; case 3: _t->LostFocusEvent(); break; case 4: _t->KeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 5: _t->MouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 6: _t->WheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 7: _t->DropEvent((*reinterpret_cast< QDropEvent*(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (EditorRendererSwapChainWidget::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::ResizedEvent)) { *result = 0; } } { typedef void (EditorRendererSwapChainWidget::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::PaintEvent)) { *result = 1; } } { typedef void (EditorRendererSwapChainWidget::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::GainedFocusEvent)) { *result = 2; } } { typedef void (EditorRendererSwapChainWidget::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::LostFocusEvent)) { *result = 3; } } { typedef void (EditorRendererSwapChainWidget::*_t)(const QKeyEvent * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::KeyboardEvent)) { *result = 4; } } { typedef void (EditorRendererSwapChainWidget::*_t)(const QMouseEvent * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::MouseEvent)) { *result = 5; } } { typedef void (EditorRendererSwapChainWidget::*_t)(const QWheelEvent * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::WheelEvent)) { *result = 6; } } { typedef void (EditorRendererSwapChainWidget::*_t)(QDropEvent * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorRendererSwapChainWidget::DropEvent)) { *result = 7; } } } } const QMetaObject EditorRendererSwapChainWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorRendererSwapChainWidget.data, qt_meta_data_EditorRendererSwapChainWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorRendererSwapChainWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorRendererSwapChainWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorRendererSwapChainWidget.stringdata)) return static_cast<void*>(const_cast< EditorRendererSwapChainWidget*>(this)); return QWidget::qt_metacast(_clname); } int EditorRendererSwapChainWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 8) qt_static_metacall(this, _c, _id, _a); _id -= 8; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 8) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 8; } return _id; } // SIGNAL 0 void EditorRendererSwapChainWidget::ResizedEvent() { QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); } // SIGNAL 1 void EditorRendererSwapChainWidget::PaintEvent() { QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR); } // SIGNAL 2 void EditorRendererSwapChainWidget::GainedFocusEvent() { QMetaObject::activate(this, &staticMetaObject, 2, Q_NULLPTR); } // SIGNAL 3 void EditorRendererSwapChainWidget::LostFocusEvent() { QMetaObject::activate(this, &staticMetaObject, 3, Q_NULLPTR); } // SIGNAL 4 void EditorRendererSwapChainWidget::KeyboardEvent(const QKeyEvent * _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 4, _a); } // SIGNAL 5 void EditorRendererSwapChainWidget::MouseEvent(const QMouseEvent * _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 5, _a); } // SIGNAL 6 void EditorRendererSwapChainWidget::WheelEvent(const QWheelEvent * _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 6, _a); } // SIGNAL 7 void EditorRendererSwapChainWidget::DropEvent(QDropEvent * _t1) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 7, _a); } QT_END_MOC_NAMESPACE <file_sep>/Editor/CMakeLists.txt set(HEADER_FILES Source/Editor/BlockMeshEditor/EditorBlockMeshEditor.h Source/Editor/BlockMeshEditor/ui_EditorBlockMeshEditor.h Source/Editor/Common.h Source/Editor/Defines.h Source/Editor/EditorBlockVolumeRenderProxy.h Source/Editor/EditorCVars.h Source/Editor/Editor.h Source/Editor/EditorHelpers.h Source/Editor/EditorIconLibrary.h Source/Editor/EditorLightSimulatorControlWidget.h Source/Editor/EditorLightSimulator.h Source/Editor/EditorProgressCallbacks.h Source/Editor/EditorProgressDialog.h Source/Editor/EditorPropertyEditorDialog.h Source/Editor/EditorPropertyEditorWidget.h Source/Editor/EditorRendererSwapChainWidget.h Source/Editor/EditorResourcePreviewGenerator.h Source/Editor/EditorResourcePreviewWidget.h Source/Editor/EditorResourceSaveDialog.h Source/Editor/EditorResourceSelectionDialog.h Source/Editor/EditorResourceSelectionDialogModel.h Source/Editor/EditorResourceSelectionWidget.h Source/Editor/EditorScriptEditor.h Source/Editor/EditorSettings.h Source/Editor/EditorShaderGraphEditor.h Source/Editor/EditorVectorEditWidget.h Source/Editor/EditorViewController.h Source/Editor/EditorVirtualFileSystemModel.h Source/Editor/EditorVisualComponent.h Source/Editor/EditorVisual.h Source/Editor/FlowLayout.h Source/Editor/MapEditor/EditorCreateTerrainDialog.h Source/Editor/MapEditor/EditorEditMode.h Source/Editor/MapEditor/EditorEntityEditMode.h Source/Editor/MapEditor/EditorEntityIdWorldRenderer.h Source/Editor/MapEditor/EditorGeometryEditMode.h Source/Editor/MapEditor/EditorMapEditMode.h Source/Editor/MapEditor/EditorMapEntity.h Source/Editor/MapEditor/EditorMap.h Source/Editor/MapEditor/EditorMapViewport.h Source/Editor/MapEditor/EditorMapWindow.h Source/Editor/MapEditor/EditorTerrainEditMode.h Source/Editor/MapEditor/EditorWorldOutlinerWidget.h Source/Editor/MapEditor/ui_EditorCreateTerrainDialog.h Source/Editor/MapEditor/ui_EditorMapViewport.h Source/Editor/MapEditor/ui_EditorMapWindow.h Source/Editor/MaterialEditor/EditorMaterialEditor.h Source/Editor/MaterialShaderEditor/EditorMaterialShaderEditor.h Source/Editor/PrecompiledHeader.h Source/Editor/ResourceBrowser/EditorResourceBrowserWidget.h Source/Editor/ResourceBrowser/EditorStaticMeshImportDialog.h Source/Editor/ResourceBrowser/ui_EditorStaticMeshImportDialog.h Source/Editor/SignalBlocker.h Source/Editor/SimpleTreeModel.h Source/Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.h Source/Editor/SkeletalAnimationEditor/ui_EditorSkeletalAnimationEditor.h Source/Editor/SkeletalMeshEditor/EditorSkeletalMeshEditor.h Source/Editor/SkeletalMeshEditor/ui_EditorSkeletalMeshEditor.h Source/Editor/StaticMeshEditor/EditorStaticMeshEditor.h Source/Editor/StaticMeshEditor/ui_EditorStaticMeshEditor.h Source/Editor/ToolMenuWidget.h Source/Editor/ui_EditorProgressDialog.h Source/Editor/ui_EditorResourcePreviewWidget.h ) set(SOURCE_FILES Source/Editor/BlockMeshEditor/EditorBlockMeshEditor.cpp Source/Editor/BlockMeshEditor/moc_EditorBlockMeshEditor.cpp Source/Editor/Defines.cpp Source/Editor/EditorBlockVolumeRenderProxy.cpp Source/Editor/Editor.cpp Source/Editor/EditorCVars.cpp Source/Editor/EditorHelpers.cpp Source/Editor/EditorIconLibrary.cpp Source/Editor/EditorLightSimulatorControlWidget.cpp Source/Editor/EditorLightSimulator.cpp Source/Editor/EditorProgressCallbacks.cpp Source/Editor/EditorProgressDialog.cpp Source/Editor/EditorPropertyEditorDialog.cpp Source/Editor/EditorPropertyEditorWidget.cpp Source/Editor/EditorRendererSwapChainWidget.cpp Source/Editor/EditorResourcePreviewGenerator.cpp Source/Editor/EditorResourcePreviewWidget.cpp Source/Editor/EditorResourceSaveDialog.cpp Source/Editor/EditorResourceSelectionDialog.cpp Source/Editor/EditorResourceSelectionDialogModel.cpp Source/Editor/EditorResourceSelectionWidget.cpp Source/Editor/EditorScriptEditor.cpp Source/Editor/EditorSettings.cpp Source/Editor/EditorShaderGraphEditor.cpp Source/Editor/EditorTest.cpp Source/Editor/EditorTypes.cpp Source/Editor/EditorVectorEditWidget.cpp Source/Editor/EditorViewController.cpp Source/Editor/EditorVirtualFileSystemModel.cpp Source/Editor/EditorVisualComponent.cpp Source/Editor/EditorVisual.cpp Source/Editor/FlowLayout.cpp Source/Editor/Main.cpp Source/Editor/MapEditor/EditorCreateTerrainDialog.cpp Source/Editor/MapEditor/EditorEditMode.cpp Source/Editor/MapEditor/EditorEntityEditMode.cpp Source/Editor/MapEditor/EditorEntityIdWorldRenderer.cpp Source/Editor/MapEditor/EditorGeometryEditMode.cpp Source/Editor/MapEditor/EditorMap.cpp Source/Editor/MapEditor/EditorMapEditMode.cpp Source/Editor/MapEditor/EditorMapEntity.cpp Source/Editor/MapEditor/EditorMapViewport.cpp Source/Editor/MapEditor/EditorMapWindow.cpp Source/Editor/MapEditor/EditorTerrainEditMode.cpp Source/Editor/MapEditor/EditorWorldOutlinerWidget.cpp Source/Editor/MapEditor/moc_EditorCreateTerrainDialog.cpp Source/Editor/MapEditor/moc_EditorEditMode.cpp Source/Editor/MapEditor/moc_EditorEntityEditMode.cpp Source/Editor/MapEditor/moc_EditorGeometryEditMode.cpp Source/Editor/MapEditor/moc_EditorMapEditMode.cpp Source/Editor/MapEditor/moc_EditorMapViewport.cpp Source/Editor/MapEditor/moc_EditorMapWindow.cpp Source/Editor/MapEditor/moc_EditorTerrainEditMode.cpp Source/Editor/MapEditor/moc_EditorWorldOutlinerWidget.cpp Source/Editor/MaterialEditor/EditorMaterialEditor.cpp Source/Editor/MaterialShaderEditor/EditorMaterialShaderEditor.cpp Source/Editor/moc_Editor.cpp Source/Editor/moc_EditorProgressDialog.cpp Source/Editor/moc_EditorPropertyEditorDialog.cpp Source/Editor/moc_EditorPropertyEditorWidget.cpp Source/Editor/moc_EditorRendererSwapChainWidget.cpp Source/Editor/moc_EditorResourcePreviewWidget.cpp Source/Editor/moc_EditorResourceSaveDialog.cpp Source/Editor/moc_EditorResourceSelectionDialog.cpp Source/Editor/moc_EditorResourceSelectionDialogModel.cpp Source/Editor/moc_EditorResourceSelectionWidget.cpp Source/Editor/moc_EditorScriptEditor.cpp Source/Editor/moc_EditorVectorEditWidget.cpp Source/Editor/moc_EditorVirtualFileSystemModel.cpp Source/Editor/moc_SimpleTreeModel.cpp Source/Editor/moc_ToolMenuWidget.cpp Source/Editor/PrecompiledHeader.cpp Source/Editor/rcc_Editor.cpp Source/Editor/ResourceBrowser/EditorResourceBrowserWidget.cpp Source/Editor/ResourceBrowser/EditorStaticMeshImportDialog.cpp Source/Editor/ResourceBrowser/moc_EditorResourceBrowserWidget.cpp Source/Editor/ResourceBrowser/moc_EditorStaticMeshImportDialog.cpp Source/Editor/SimpleTreeModel.cpp Source/Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.cpp Source/Editor/SkeletalAnimationEditor/moc_EditorSkeletalAnimationEditor.cpp Source/Editor/SkeletalMeshEditor/EditorSkeletalMeshEditor.cpp Source/Editor/SkeletalMeshEditor/moc_EditorSkeletalMeshEditor.cpp Source/Editor/StaticMeshEditor/EditorStaticMeshEditor.cpp Source/Editor/StaticMeshEditor/moc_EditorStaticMeshEditor.cpp Source/Editor/ToolMenuWidget.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${Qt5Gui_PRIVATE_INCLUDE_DIRS} ${SDL2_INCLUDE_DIR} Source) # hackfix for icu issue on linux if(UNIX AND (NOT APPLE)) #set(EXTRA_LIBRARIES ":libicudata.so.52") set(EXTRA_LIBRARIES "") else() set(EXTRA_LIBRARIES "") endif() add_executable(Editor ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(Editor QtPropertyBrowser EngineContentConverter EngineMapCompiler EngineResourceCompiler EngineMain EngineCore ${EXTRA_LIBRARIES}) qt5_use_modules(Editor Core Gui Widgets) #if(APPLE) #include(DeployQt5) #set_target_properties(Editor PROPERTIES MACOSX_BUNDLE TRUE) #install_qt5_executable("Source/Editor/Tools/Editor/Editor.app") #endif() install(TARGETS Editor DESTINATION ${INSTALL_BINARIES_DIRECTORY}) <file_sep>/Engine/Source/BlockEngine/BlockWorldGenerator.h #pragma once #include "BlockEngine/BlockWorld.h" class BlockWorldGenerator { public: BlockWorldGenerator(BlockWorld *pBlockWorld); virtual ~BlockWorldGenerator(); const BlockWorld *GetBlockWorld() const { return m_pBlockWorld; } BlockWorld *GetBlockWorld() { return m_pBlockWorld; } BlockWorldBlockType LookupBlockTypeByName(const char *name); virtual bool CanGenerateSection(int32 sectionX, int32 sectionY) const; virtual bool GetZRange(int32 startX, int32 startY, int32 endX, int32 endY, int32 *minBlockZ, int32 *maxBlockZ) const; virtual bool GenerateBlocks(int32 startX, int32 startY, int32 endX, int32 endY) const; protected: // enumerate chunk coordinates for a specified section, returns global chunk coordinates template<typename T> void EnumerateChunksInSection(int32 sectionX, int32 sectionY, T callback) const { int32 baseChunkX = sectionX * m_pBlockWorld->GetSectionSize(); int32 baseChunkY = sectionY * m_pBlockWorld->GetSectionSize(); for (int32 chunkX = 0; chunkX < m_pBlockWorld->GetSectionSize(); chunkX++) { for (int32 chunkY = 0; chunkY < m_pBlockWorld->GetSectionSize(); chunkY++) { callback(baseChunkX + chunkX, baseChunkY + chunkY); } } } protected: BlockWorld *m_pBlockWorld; }; <file_sep>/Engine/Source/Renderer/WorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/OneColorShader.h" #include "Renderer/WorldRenderers/ForwardShadingWorldRenderer.h" #include "Renderer/WorldRenderers/DeferredShadingWorldRenderer.h" #include "Renderer/WorldRenderers/DebugNormalsWorldRenderer.h" #include "Renderer/WorldRenderers/FullBrightWorldRenderer.h" #include "Renderer/WorldRenderers/MobileWorldRenderer.h" #include "Renderer/Renderer.h" #include "Renderer/RenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderProgramSelector.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/WorldRenderer.h" #include "Engine/Camera.h" #include "Engine/EngineCVars.h" #include "Engine/Material.h" #include "Engine/Profiling.h" Log_SetChannel(WorldRenderer); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class OcclusionCullingShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(OcclusionCullingShader, ShaderComponent); public: OcclusionCullingShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { }; static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; DEFINE_SHADER_COMPONENT_INFO(OcclusionCullingShader); BEGIN_SHADER_COMPONENT_PARAMETERS(OcclusionCullingShader) END_SHADER_COMPONENT_PARAMETERS() bool OcclusionCullingShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool OcclusionCullingShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/OcclusionCullingShader.hlsl", "VSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// WorldRenderer::Options::Options() : EnableDepthPrepass(false) , EnableShadows(false) , EnablePointLightShadows(false) , EnableHardwareShadowFiltering(false) , EnableOcclusionCulling(false) , EnableOcclusionPredication(false) , WaitForOcclusionResults(false) , EnablePostProcessing(false) , EnableSSAO(false) , EnableBloom(false) , ShowDebugInfo(false) , ShowShadowMapCascades(false) , ShowIntermediateBuffers(false) , ShowWireframeOverlay(false) , RenderModeFullbright(false) , RenderModeNormals(false) , RenderModeLightingOnly(false) , EmulateMobile(false) , EnableMultithreadedRendering(false) , RenderWidth(640) , RenderHeight(480) , OcclusionCullingObjectsPerBatch(1) , ShadowMapPixelFormat(PIXEL_FORMAT_D16_UNORM) , DirectionalShadowMapResolution(1) , PointShadowMapResolution(1) , SpotShadowMapResolution(1) , ShadowMapFiltering(RENDERER_SHADOW_FILTER_1X1) , ShadowMapCascadeCount(1) { } WorldRenderer::Options::Options(const Options &options) { Y_memcpy(this, &options, sizeof(*this)); } void WorldRenderer::Options::InitFromCVars() { // depth prepass EnableDepthPrepass = CVars::r_depth_prepass.GetBool(); // occlusion culling EnableOcclusionCulling = CVars::r_occlusion_culling.GetBool(); EnableOcclusionPredication = CVars::r_occlusion_prediction.GetBool(); WaitForOcclusionResults = CVars::r_occlusion_culling_wait_for_results.GetBool(); OcclusionCullingObjectsPerBatch = CVars::r_occlusion_culling_objects_per_buffer.GetUInt(); // shadows enabled EnableShadows = (CVars::r_shadows.GetUInt() > 0); EnablePointLightShadows = EnableShadows && (CVars::r_shadows.GetUInt() != 2); EnableHardwareShadowFiltering = CVars::r_shadow_use_hardware_pcf.GetBool(); // shadow map resolutions DirectionalShadowMapResolution = CVars::r_directional_shadow_map_resolution.GetUInt(); PointShadowMapResolution = CVars::r_point_shadow_map_resolution.GetUInt(); SpotShadowMapResolution = CVars::r_spot_shadow_map_resolution.GetUInt(); // shadow map bits uint32 shadowMapBits = CVars::r_shadow_map_bits.GetUInt(); ShadowMapPixelFormat = PIXEL_FORMAT_D16_UNORM; if (shadowMapBits == 24) ShadowMapPixelFormat = PIXEL_FORMAT_D24_UNORM_S8_UINT; else if (shadowMapBits == 32) ShadowMapPixelFormat = PIXEL_FORMAT_D32_FLOAT; else if (shadowMapBits != 16) Log_WarningPrintf("WorldRenderer::Options::InitFromCVars: Invalid shadow map bits: %u (must be 16, 24, 32)", shadowMapBits); // shadow map filtering uint32 shadowMapFiltering = CVars::r_shadow_filtering.GetUInt(); ShadowMapFiltering = RENDERER_SHADOW_FILTER_1X1; if (shadowMapFiltering == 1) ShadowMapFiltering = RENDERER_SHADOW_FILTER_3X3; else if (shadowMapFiltering == 2) ShadowMapFiltering = RENDERER_SHADOW_FILTER_5X5; else if (shadowMapFiltering != 0) Log_WarningPrintf("WorldRenderer::Options::InitFromCVars: Invalid shadow map filtering value: %u (must be 0-2)", shadowMapFiltering); // shadow map cascade count for CSM ShadowMapCascadeCount = 3; // post processing EnablePostProcessing = CVars::r_post_processing.GetBool(); EnableSSAO = CVars::r_ssao.GetBool(); EnableBloom = true; // debug options ShowDebugInfo = CVars::r_show_debug_info.GetBool(); ShowShadowMapCascades = CVars::r_show_cascades.GetBool(); ShowIntermediateBuffers = CVars::r_show_buffers.GetBool(); ShowWireframeOverlay = CVars::r_wireframe.GetBool(); RenderModeFullbright = CVars::r_fullbright.GetBool(); RenderModeNormals = CVars::r_debug_normals.GetBool(); EmulateMobile = CVars::r_emulate_mobile.GetBool(); EnableMultithreadedRendering = CVars::r_multithreaded_rendering.GetBool(); } void WorldRenderer::Options::SetRenderResolution(uint32 width, uint32 height) { DebugAssert(width > 0 && height > 0); RenderWidth = width; RenderHeight = height; } void WorldRenderer::Options::DisableUnsupportedFeatures() { if (g_pRenderer->GetFeatureLevel() < RENDERER_FEATURE_LEVEL_ES3) { if (EnableOcclusionCulling || EnableOcclusionPredication) { Log_WarningPrintf("WorldRenderer::Options::DisableUnsupportedFeatures: Disabling occlusion culling."); EnableOcclusionCulling = false; EnableOcclusionPredication = false; } } EnableMultithreadedRendering &= g_pRenderer->GetCapabilities().SupportsCommandLists; } WorldRenderer::ViewParameters::ViewParameters() : ViewCamera() , MaximumShadowViewDistance(500.0f) , Viewport(0, 0, 1, 1, 0.0f, 1.0f) , WorldTime(0.0f) , FogMode(RENDERER_FOG_MODE_NONE) , FogStartDistance(10.0f) , FogEndDistance(20.0f) , FogDensity(1.0f) , FogColor(float3::Zero) , EnableManualExposure(true) , ManualExposure(1.0f) , MaximumExposure(4.0f) , EnableBloom(true) , BloomThreshold(0.3f) , BloomMagnitude(1.0f) { } WorldRenderer::ViewParameters::ViewParameters(const ViewParameters &parameters) : ViewCamera(parameters.ViewCamera) , MaximumShadowViewDistance(500.0f) , Viewport(parameters.Viewport) , WorldTime(parameters.WorldTime) , FogMode(parameters.FogMode) , FogStartDistance(parameters.FogStartDistance) , FogEndDistance(parameters.FogEndDistance) , FogDensity(parameters.FogDensity) , FogColor(parameters.FogColor) , EnableManualExposure(parameters.EnableManualExposure) , ManualExposure(parameters.ManualExposure) , MaximumExposure(parameters.MaximumExposure) , EnableBloom(parameters.EnableBloom) , BloomThreshold(parameters.BloomThreshold) , BloomMagnitude(parameters.BloomMagnitude) { } void WorldRenderer::ViewParameters::SetCamera(const Camera *pCamera) { ViewCamera = *pCamera; } WorldRenderer::WorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : m_pGPUContext(pGPUContext) , m_pGUIContext(nullptr) , m_options(*pOptions) , m_globalShaderFlags(0) , m_pOcclusionCullingCubeVertexBuffer(nullptr) , m_pOcclusionCullingCubeIndexBuffer(nullptr) , m_pOcclusionCullingProgram(nullptr) , m_hQueueingCommandsSemaphore(CreateSemaphore(nullptr, 0, Y_INT32_MAX, nullptr)) , m_commandListsPending(0) { // disable unusable features m_options.DisableUnsupportedFeatures(); // work out global shader flags m_globalShaderFlags = SHADER_GLOBAL_FLAG_SHADER_QUALITY_HIGH; } WorldRenderer::~WorldRenderer() { // free intermedidate buffers, assert that everything has been released DebugAssert(m_allIntermediateBuffers.GetSize() == m_freeIntermediateBuffers.GetSize()); for (IntermediateBuffer *buffer : m_allIntermediateBuffers) { if (buffer->pDSV != nullptr) buffer->pDSV->Release(); if (buffer->pRTV != nullptr) buffer->pRTV->Release(); buffer->pTexture->Release(); delete buffer; } m_freeIntermediateBuffers.Obliterate(); m_allIntermediateBuffers.Obliterate(); // free buffers SAFE_RELEASE(m_pOcclusionCullingCubeIndexBuffer); SAFE_RELEASE(m_pOcclusionCullingCubeVertexBuffer); for (uint32 i = 0; i < m_occlusionCullingQueryCacheArray.GetSize(); i++) m_occlusionCullingQueryCacheArray[i]->Release(); m_occlusionCullingQueryCacheArray.Obliterate(); m_occlusionCullingPendingQueries.Obliterate(); } bool WorldRenderer::Initialize() { // occlusion culling if ((m_options.EnableOcclusionCulling | m_options.EnableOcclusionPredication)) { // render program m_pOcclusionCullingProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(OcclusionCullingShader), 0, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (m_pOcclusionCullingProgram == nullptr) return false; // vertex buffer DebugAssert(m_options.OcclusionCullingObjectsPerBatch > 0); GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER | GPU_BUFFER_FLAG_MAPPABLE, sizeof(float3) * 8 * m_options.OcclusionCullingObjectsPerBatch); if ((m_pOcclusionCullingCubeVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc)) == NULL) return false; // Indices for drawing a cube using AABox corner points. static const uint16 cubeIndices[36] = { 0, 1, 2, 2, 1, 3, // left 4, 6, 5, 5, 6, 7, // right 0, 1, 5, 5, 0, 4, // front 3, 7, 2, 2, 7, 6, // back 1, 5, 3, 3, 5, 7, // top 0, 2, 4, 4, 2, 6 // bottom }; // index buffer GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, sizeof(cubeIndices)); if ((m_pOcclusionCullingCubeIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, cubeIndices)) == NULL) return false; } return true; } void WorldRenderer::DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) { } void WorldRenderer::GetRenderStats(RenderStats *pRenderStats) const { pRenderStats->ObjectCount = m_renderQueue.GetOpaqueRenderableCount() + m_renderQueue.GetTranslucentRenderableCount() + m_renderQueue.GetPostProcessRenderableCount(); pRenderStats->LightCount = m_renderQueue.GetDirectionalLightCount() + m_renderQueue.GetPointLightCount() + m_renderQueue.GetSpotLightCount() + m_renderQueue.GetVolumetricLightCount(); pRenderStats->ShadowMapCount = 0; pRenderStats->ObjectsCulledByOcclusion = m_renderQueue.GetNumObjectsInvalidatedByOcclusion(); pRenderStats->IntermediateBufferCount = m_allIntermediateBuffers.GetSize(); pRenderStats->IntermediateBufferMemoryUsage = 0; for (const IntermediateBuffer *buffer : m_allIntermediateBuffers) { uint32 cpuMemoryUsage, gpuMemoryUsage; buffer->pTexture->GetMemoryUsage(&cpuMemoryUsage, &gpuMemoryUsage); pRenderStats->IntermediateBufferMemoryUsage += gpuMemoryUsage; } } void WorldRenderer::OnFrameComplete() { // release autorelease buffers for (const DebugBufferView &dbv : m_debugBufferViews) { if (dbv.pBuffer != nullptr) ReleaseIntermediateBuffer(dbv.pBuffer); } m_debugBufferViews.Clear(); } WorldRenderer *WorldRenderer::Create(GPUContext *pGPUContext, const Options *pCreationParameters) { WorldRenderer *pWorldRenderer; if (pCreationParameters->RenderModeNormals) { // create normal renderer pWorldRenderer = new DebugNormalsWorldRenderer(pGPUContext, pCreationParameters); } else if (pCreationParameters->RenderModeFullbright) { // create fullbright renderer pWorldRenderer = new FullBrightWorldRenderer(pGPUContext, pCreationParameters); } else if (pCreationParameters->EmulateMobile || g_pRenderer->GetFeatureLevel() < RENDERER_FEATURE_LEVEL_SM4) { // use mobile renderer pWorldRenderer = new MobileWorldRenderer(pGPUContext, pCreationParameters); } else { // create standard forward shading renderer if (CVars::r_deferred_shading.GetBool()) pWorldRenderer = new DeferredShadingWorldRenderer(pGPUContext, pCreationParameters); else pWorldRenderer = new ForwardShadingWorldRenderer(pGPUContext, pCreationParameters); } // create resources if (!pWorldRenderer->Initialize()) { Log_ErrorPrint("WorldRenderer::CreateForCurrentRenderer: Initialize() failed"); delete pWorldRenderer; return nullptr; } // return it return pWorldRenderer; } ShaderProgram *WorldRenderer::GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialStaticSwitchMask) { // set shader quality globalShaderFlags |= SHADER_GLOBAL_FLAG_SHADER_QUALITY_HIGH; // pass through return g_pRenderer->GetShaderProgram(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialStaticSwitchMask); } ShaderProgram *WorldRenderer::GetShaderProgram(const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { const Material *pMaterial = pQueueEntry->pMaterial; // add in global tint uint32 globalShaderFlags = 0; if (pQueueEntry->RenderPassMask & RENDER_PASS_TINT) globalShaderFlags |= SHADER_GLOBAL_FLAG_MATERIAL_TINT; return GetShaderProgram(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags, pMaterial->GetShader(), pMaterial->GetShaderStaticSwitchMask()); } ShaderProgram *WorldRenderer::GetShaderProgram(const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags) { // set shader quality uint32 globalShaderFlags = SHADER_GLOBAL_FLAG_SHADER_QUALITY_HIGH; // pass through return g_pRenderer->GetShaderProgram(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0); } void WorldRenderer::SetBlendingModeForMaterial(GPUCommandList *pCommandList, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { switch (pQueueEntry->pMaterial->GetShader()->GetBlendMode()) { case MATERIAL_BLENDING_MODE_ADDITIVE: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive(), float4::One); break; case MATERIAL_BLENDING_MODE_STRAIGHT: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending(), float4::One); break; case MATERIAL_BLENDING_MODE_PREMULTIPLIED: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStatePremultipliedAlpha(), float4::One); break; case MATERIAL_BLENDING_MODE_SOFTMASKED: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending(), float4::One); break; default: { if ((pQueueEntry->RenderPassMask & RENDER_PASS_TINT) && (pQueueEntry->TintColor >> 24) != 0xFF) pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending(), float4::One); else pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending(), float4::One); } break; } // set blending colour if (pQueueEntry->RenderPassMask & RENDER_PASS_TINT) pCommandList->GetConstants()->SetMaterialTintColor(PixelFormatHelpers::ConvertRGBAToFloat4(pQueueEntry->TintColor), true); } void WorldRenderer::SetAdditiveBlendingModeForMaterial(GPUCommandList *pCommandList, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { switch (pQueueEntry->pMaterial->GetShader()->GetBlendMode()) { case MATERIAL_BLENDING_MODE_ADDITIVE: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive(), float4::One); break; case MATERIAL_BLENDING_MODE_STRAIGHT: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlendingAdditive(), float4::One); break; case MATERIAL_BLENDING_MODE_PREMULTIPLIED: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStatePremultipliedAlphaAdditive(), float4::One); break; case MATERIAL_BLENDING_MODE_SOFTMASKED: pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlendingAdditive(), float4::One); break; default: { if ((pQueueEntry->RenderPassMask & RENDER_PASS_TINT) && (pQueueEntry->TintColor >> 24) != 0xFF) pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlendingAdditive(), float4::One); else pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive(), float4::One); } break; } // set blending colour if (pQueueEntry->RenderPassMask & RENDER_PASS_TINT) pCommandList->GetConstants()->SetMaterialTintColor(PixelFormatHelpers::ConvertRGBAToFloat4(pQueueEntry->TintColor), true); } void WorldRenderer::FillRenderQueue(const Camera *pCamera, const RenderWorld *pRenderWorld) { MICROPROFILE_SCOPEI("WorldRenderer", "FillRenderQueue", MICROPROFILE_COLOR(0, 255, 255)); // clear render queue m_renderQueue.Clear(); // find renderables pRenderWorld->EnumerateRenderablesInFrustum(pCamera->GetFrustum(), [this, pCamera](const RenderProxy *pRenderProxy) { // add to render queue pRenderProxy->QueueForRender(pCamera, &m_renderQueue); }); // sort render queue m_renderQueue.Sort(); } void WorldRenderer::DrawDebugInfo(const Camera *pCamera) { MICROPROFILE_SCOPEI("WorldRenderer", "DrawDebugInfo", MICROPROFILE_COLOR(185, 20, 185)); // batch batch batch! SmallString tempString; m_pGUIContext->PushManualFlush(); // draw infos const RenderQueue::DebugDrawRenderableArray &debugInfoObjects = m_renderQueue.GetDebugObjects(); for (uint32 i = 0; i < debugInfoObjects.GetSize(); i++) debugInfoObjects[i]->DrawDebugInfo(pCamera, m_pGPUContext, m_pGUIContext); // // override cameras // if (pRenderProfiler != nullptr && pRenderProfiler->GetCameraCount() > 0) // { // tempString.Format("Total camera count: %u, camera override: %i", pRenderProfiler->GetCameraCount(), pRenderProfiler->GetCameraOverrideIndex()); // m_pGUIContext->DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), 16, 16, 4, tempString, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255)); // // for (uint32 i = 0; i < pRenderProfiler->GetCameraCount(); i++) // { // tempString.Format("Camera %u: '%s' at (%s)", i, pRenderProfiler->GetCameraName(i).GetCharArray(), StringConverter::Vector3fToString(pRenderProfiler->GetCamera(i)->GetPosition()).GetCharArray()); // m_pGUIContext->DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), 16, 20, i * 16 + 20, tempString, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255)); // } // } m_pGUIContext->PopManualFlush(); } void WorldRenderer::DrawWireframeOverlay(GPUCommandList *pCommandList, const Camera *pCamera, const RenderQueue::RenderableArray *pRenderables) { MICROPROFILE_SCOPEI("WorldRenderer", "DrawWireframeOverlay", MICROPROFILE_COLOR(20, 185, 185)); // set common state pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_WIREFRAME, RENDERER_CULL_BACK, true, false, false)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, false, GPU_COMPARISON_FUNC_LESS_EQUAL), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); // init shader selector, we want one color shader ShaderProgramSelector shaderSelector(m_globalShaderFlags); shaderSelector.SetBaseShader(OBJECT_TYPEINFO(OneColorShader), 0); // draw away const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = pRenderables->GetBasePointer(); const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = pQueueEntry + pRenderables->GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { float4 drawColor(float4::Zero); if (pQueueEntry->RenderPassMask & RENDER_PASS_EMISSIVE) drawColor.r += 0.5f; if (pQueueEntry->RenderPassMask & RENDER_PASS_LIGHTMAP) drawColor.g += 0.5f; if (pQueueEntry->RenderPassMask & RENDER_PASS_STATIC_LIGHTING) drawColor.r += 0.5f; if (pQueueEntry->RenderPassMask & RENDER_PASS_DYNAMIC_LIGHTING) drawColor.b += 0.5f; if (pQueueEntry->RenderPassMask & RENDER_PASS_SHADOWED_LIGHTING) drawColor.b += 0.5f; if (pQueueEntry->RenderPassMask & RENDER_PASS_OCCLUSION_CULLING_PROXY) drawColor.g += 0.5f; // skip anything that wouldn't get a colour if (drawColor == float4::Zero) continue; // mark translucent materials if (pQueueEntry->pMaterial->GetShader()->GetBlendMode() != MATERIAL_BLENDING_MODE_NONE) drawColor.r += 0.5f; // update selector, we set this manually so that tinting is not applied shaderSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); shaderSelector.SetMaterial(pQueueEntry->pMaterial); // draw it ShaderProgram *pShaderProgram = shaderSelector.MakeActive(pCommandList); if (pShaderProgram == nullptr) continue; OneColorShader::SetColor(pCommandList, pShaderProgram, drawColor); pQueueEntry->pRenderProxy->SetupForDraw(pCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(pCamera, pQueueEntry, pCommandList); } } void WorldRenderer::DrawOcclusionCullingProxies(GPUCommandList *pCommandList, const Camera *pCamera) { MICROPROFILE_SCOPEI("WorldRenderer", "DrawOcclusionCullingProxies", MICROPROFILE_COLOR(20, 20, 185)); Panic("Fixme for map!"); // Everything here uses the normal rasterizer state, so set that up here. pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, false, GPU_COMPARISON_FUNC_LESS_EQUAL), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoColorWrites()); // Set identity world matrix. pCommandList->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); // bind stuff pCommandList->SetShaderProgram(m_pOcclusionCullingProgram->GetGPUProgram()); // Bind buffers uint32 bufferOffset = 0; uint32 bufferStride = sizeof(float3); pCommandList->SetVertexBuffers(0, 1, &m_pOcclusionCullingCubeVertexBuffer, &bufferOffset, &bufferStride); pCommandList->SetIndexBuffer(m_pOcclusionCullingCubeIndexBuffer, GPU_INDEX_FORMAT_UINT16, 0); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // Get camera eye position. void *pBufferMappedPointer = nullptr; float3 *pBufferCurrentPointer = nullptr; uint32 nOccludersInBuffer = 0; // Get pointers. // We don't cull translucent materials. RENDER_QUEUE_OCCLUDER_ENTRY *pQueueEntry = m_renderQueue.GetOccluders().GetBasePointer(); RENDER_QUEUE_OCCLUDER_ENTRY *pQueueEntryEnd = m_renderQueue.GetOccluders().GetBasePointer() + m_renderQueue.GetOccluders().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { // get aabox. if we are located inside the frustum, skip culling process. if (pQueueEntry->BoundingBox.ContainsPoint(pCamera->GetPosition())) continue; // use cached query? GPUQuery *pOcclusionQuery; if (m_occlusionCullingPendingQueries.GetSize() < m_occlusionCullingQueryCacheArray.GetSize()) { // use the last cached one pOcclusionQuery = m_occlusionCullingQueryCacheArray[m_occlusionCullingPendingQueries.GetSize()]; } else { // create a new one pOcclusionQuery = g_pRenderer->CreateQuery(GPU_QUERY_TYPE_OCCLUSION); if (pOcclusionQuery == NULL) { // chances are it'll fail to create others too, so bail out now Log_WarningPrint("WorldRenderer::DrawOcclusionCullingProxies: Could not allocate query object"); break; } // store it for tracking and later use m_occlusionCullingQueryCacheArray.Add(pOcclusionQuery); } // map buffer if not mapped if (pBufferCurrentPointer == NULL) { if (!m_pGPUContext->MapBuffer(m_pOcclusionCullingCubeVertexBuffer, GPU_MAP_TYPE_WRITE_DISCARD, &pBufferMappedPointer)) return; pBufferCurrentPointer = reinterpret_cast<float3 *>(pBufferMappedPointer); } // get vertices, and write them to the vb float3 cubeVertices[8]; pQueueEntry->BoundingBox.GetCornerPoints(cubeVertices); Y_memcpy(pBufferCurrentPointer, cubeVertices, sizeof(float3) * 8); pBufferCurrentPointer += 8; nOccludersInBuffer++; // add to the array PendingOcclusionCullingQuery pendingQuery; pendingQuery.pRenderProxy = pQueueEntry->pRenderProxy; pendingQuery.MatchUserData = pQueueEntry->MatchUserData; if (pQueueEntry->MatchUserData) { Y_memcpy(pendingQuery.UserData, pQueueEntry->UserData, sizeof(pendingQuery.UserData)); Y_memcpy(pendingQuery.UserDataPointer, pQueueEntry->UserDataPointer, sizeof(pendingQuery.UserDataPointer)); } pendingQuery.pQuery = pOcclusionQuery; pendingQuery.Visible = true; m_occlusionCullingPendingQueries.Add(pendingQuery); // requires a flush? if (nOccludersInBuffer == m_options.OcclusionCullingObjectsPerBatch) { // flush buffer m_pGPUContext->Unmapbuffer(m_pOcclusionCullingCubeVertexBuffer, pBufferMappedPointer); pBufferMappedPointer = nullptr; pBufferCurrentPointer = nullptr; // issue the queries, and draw the occluders uint32 baseIndex = m_occlusionCullingPendingQueries.GetSize() - nOccludersInBuffer; for (uint32 i = 0; i < nOccludersInBuffer; i++) { GPUQuery *pCurrentQuery = m_occlusionCullingPendingQueries[baseIndex + i].pQuery; // draw it pCommandList->BeginQuery(pCurrentQuery); pCommandList->DrawIndexed(0, 36, i * 8); pCommandList->EndQuery(pCurrentQuery); } // reset count nOccludersInBuffer = 0; } } // remaining occluders? if (nOccludersInBuffer > 0) { // flush buffer m_pGPUContext->Unmapbuffer(m_pOcclusionCullingCubeVertexBuffer, pBufferMappedPointer); pBufferMappedPointer = nullptr; pBufferCurrentPointer = nullptr; // issue the queries, and draw the occluders uint32 baseIndex = m_occlusionCullingPendingQueries.GetSize() - nOccludersInBuffer; for (uint32 i = 0; i < nOccludersInBuffer; i++) { GPUQuery *pCurrentQuery = m_occlusionCullingPendingQueries[baseIndex + i].pQuery; // draw it pCommandList->BeginQuery(pCurrentQuery); pCommandList->DrawIndexed(0, 36, i * 8); pCommandList->EndQuery(pCurrentQuery); } } } void WorldRenderer::CollectOcclusionCullingResults() { static const uint32 keepRenderPasses = RENDER_PASS_OCCLUSION_CULLING_PROXY; MICROPROFILE_SCOPEI("WorldRenderer", "CollectOcclusionCullingResults", MICROPROFILE_COLOR(20, 50, 120)); uint32 queryFlags = 0; bool waitForResults = CVars::r_occlusion_culling_wait_for_results.GetBool(); if (!waitForResults) queryFlags |= GPU_QUERY_GETDATA_FLAG_NOFLUSH; // get data results for (uint32 i = 0; i < m_occlusionCullingPendingQueries.GetSize(); i++) { PendingOcclusionCullingQuery *pPendingQuery = &m_occlusionCullingPendingQueries[i]; // get result for (;;) { bool isVisible; GPU_QUERY_GETDATA_RESULT result = m_pGPUContext->GetQueryData(pPendingQuery->pQuery, &isVisible, sizeof(isVisible), queryFlags); if (result == GPU_QUERY_GETDATA_RESULT_NOT_READY && waitForResults) continue; if (result == GPU_QUERY_GETDATA_RESULT_OK) pPendingQuery->Visible = isVisible; else pPendingQuery->Visible = true; break; } } // kill the render passes of any OPAQUE objects that's occluding for (uint32 i = 0; i < m_occlusionCullingPendingQueries.GetSize(); i++) { const PendingOcclusionCullingQuery *pPendingQuery = &m_occlusionCullingPendingQueries[i]; if (!pPendingQuery->Visible) { if (!pPendingQuery->MatchUserData) m_renderQueue.InvalidateOpaqueRenderProxy(pPendingQuery->pRenderProxy); else m_renderQueue.InvalidateOpaqueRenderProxy(pPendingQuery->pRenderProxy, pPendingQuery->UserData, pPendingQuery->UserDataPointer); } } // clear the culled list m_occlusionCullingPendingQueries.Clear(); } void WorldRenderer::BindOcclusionQueriesToQueueEntries() { MICROPROFILE_SCOPEI("WorldRenderer", "BindOcclusionQueriesToQueueEntries", MICROPROFILE_COLOR(120, 50, 120)); // kill the render passes of any OPAQUE objects that's occluding for (uint32 i = 0; i < m_occlusionCullingPendingQueries.GetSize(); i++) { const PendingOcclusionCullingQuery *pPendingQuery = &m_occlusionCullingPendingQueries[i]; if (!pPendingQuery->MatchUserData) m_renderQueue.MarkRenderProxyWithPredicate(pPendingQuery->pRenderProxy, pPendingQuery->pQuery); else m_renderQueue.MarkRenderProxyWithPredicate(pPendingQuery->pRenderProxy, pPendingQuery->UserData, pPendingQuery->UserDataPointer, pPendingQuery->pQuery); } // clear the culled list m_occlusionCullingPendingQueries.Clear(); } void WorldRenderer::ScaleTexture(GPUCommandList *pCommandList, GPUTexture2D *pSourceTexture, GPURenderTargetView *pDestinationRTV, bool restoreViewport /* = true */, bool restoreTargets /* = true */) { DebugAssert(pDestinationRTV->GetTargetTexture()->GetResourceType() == GPU_RESOURCE_TYPE_TEXTURE2D); // old viewport RENDERER_VIEWPORT oldViewport; if (restoreViewport) Y_memcpy(&oldViewport, pCommandList->GetViewport(), sizeof(oldViewport)); // old render targets GPURenderTargetView *pOldRTVs[8]; GPUDepthStencilBufferView *pOldDSV; uint32 nOldRTVs; if (restoreTargets) { // read from context nOldRTVs = pCommandList->GetRenderTargets(countof(pOldRTVs), pOldRTVs, &pOldDSV); } else { // not strictly necessary, but spews warnings if not present nOldRTVs = 0; pOldDSV = nullptr; } // get source texture info uint32 sourceTextureWidth = pSourceTexture->GetDesc()->Width; uint32 sourceTextureHeight = pSourceTexture->GetDesc()->Height; // get destination texture GPUTexture2D *pDestinationTexture = static_cast<GPUTexture2D *>(pDestinationRTV->GetTargetTexture()); uint32 destTextureWidth = pDestinationTexture->GetDesc()->Width; uint32 destTextureHeight = pDestinationTexture->GetDesc()->Height; // save the old viewport, and set a new viewport covering the destination texture RENDERER_VIEWPORT downsampleViewport(0, 0, destTextureWidth, destTextureHeight, 0.0f, 1.0f); pCommandList->SetViewport(&downsampleViewport); // use texture blit shader pCommandList->SetRenderTargets(1, &pDestinationRTV, nullptr); pCommandList->DiscardTargets(true, false, false); g_pRenderer->BlitTextureUsingShader(pCommandList, pSourceTexture, 0, 0, sourceTextureWidth, sourceTextureHeight, 0, 0, 0, destTextureWidth, destTextureHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_LINEAR, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE); // restore old targets if (restoreTargets) pCommandList->SetRenderTargets(nOldRTVs, pOldRTVs, pOldDSV); // restore old viewport if (restoreViewport) pCommandList->SetViewport(&oldViewport); } WorldRenderer::IntermediateBuffer *WorldRenderer::RequestIntermediateBuffer(uint32 width, uint32 height, PIXEL_FORMAT pixelFormat, uint32 mipLevels) { // todo: binary sort the list for (uint32 i = 0; i < m_freeIntermediateBuffers.GetSize(); i++) { IntermediateBuffer *buffer = m_freeIntermediateBuffers[i]; if (buffer->Width == width && buffer->Height == height && buffer->PixelFormat == pixelFormat && buffer->MipLevels == mipLevels) { m_freeIntermediateBuffers.FastRemove(i); return buffer; } } // create new buffer IntermediateBuffer *buffer = new IntermediateBuffer(); buffer->Width = width; buffer->Height = height; buffer->PixelFormat = pixelFormat; buffer->MipLevels = mipLevels; // figure out texture flags uint32 flags = GPU_TEXTURE_FLAG_SHADER_BINDABLE; if (PixelFormatHelpers::IsDepthFormat(pixelFormat)) flags |= GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER; else flags |= GPU_TEXTURE_FLAG_BIND_RENDER_TARGET; if (mipLevels > 1) flags |= GPU_TEXTURE_FLAG_GENERATE_MIPS; // create texture descriptor GPU_TEXTURE2D_DESC textureDesc(width, height, pixelFormat, flags, mipLevels); GPU_SAMPLER_STATE_DESC pointSamplerDesc(TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_NEVER); if ((buffer->pTexture = g_pRenderer->CreateTexture2D(&textureDesc, &pointSamplerDesc)) == nullptr) { // todo log delete buffer; return nullptr; } // create rtv if (flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { GPU_RENDER_TARGET_VIEW_DESC rtvDesc((uint32)0, 0, 1, pixelFormat); if ((buffer->pRTV = g_pRenderer->CreateRenderTargetView(buffer->pTexture, &rtvDesc)) == nullptr) { buffer->pTexture->Release(); delete buffer; return nullptr; } buffer->pDSV = nullptr; } else if (flags & GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER) { // create dsv GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC dsvDesc((uint32)0, 0, 1, pixelFormat); if ((buffer->pDSV = g_pRenderer->CreateDepthStencilBufferView(buffer->pTexture, &dsvDesc)) == nullptr) { buffer->pTexture->Release(); delete buffer; return nullptr; } buffer->pRTV = nullptr; } else { buffer->pRTV = nullptr; buffer->pDSV = nullptr; } // done m_allIntermediateBuffers.Add(buffer); return buffer; } WorldRenderer::IntermediateBuffer *WorldRenderer::RequestIntermediateBufferMatching(const IntermediateBuffer *pIntermediateBuffer) { // forward to main method return RequestIntermediateBuffer(pIntermediateBuffer->Width, pIntermediateBuffer->Height, pIntermediateBuffer->PixelFormat, pIntermediateBuffer->MipLevels); } void WorldRenderer::ReleaseIntermediateBuffer(IntermediateBuffer *pIntermediateBuffer) { if (pIntermediateBuffer == nullptr) return; // append to free list DebugAssert(m_allIntermediateBuffers.Contains(pIntermediateBuffer)); DebugAssert(!m_freeIntermediateBuffers.Contains(pIntermediateBuffer)); m_freeIntermediateBuffers.Add(pIntermediateBuffer); } void WorldRenderer::AddDebugBufferView(GPUTexture *pTexture, const char *name) { DebugAssert(pTexture->GetResourceType() == GPU_RESOURCE_TYPE_TEXTURE2D || pTexture->GetResourceType() == GPU_RESOURCE_TYPE_TEXTURE2DARRAY); if (!m_options.ShowIntermediateBuffers) return; DebugBufferView dbv; dbv.pTexture = pTexture; dbv.pBuffer = nullptr; dbv.Name = name; m_debugBufferViews.Add(dbv); } void WorldRenderer::AddDebugBufferView(IntermediateBuffer *pBuffer, const char *name, bool autoRelease) { if (!m_options.ShowIntermediateBuffers) { if (autoRelease) ReleaseIntermediateBuffer(pBuffer); return; } DebugBufferView dbv; dbv.pTexture = pBuffer->pTexture; dbv.pBuffer = (autoRelease) ? pBuffer : nullptr; dbv.Name = name; m_debugBufferViews.Add(dbv); } void WorldRenderer::DrawIntermediateBuffers() { const uint32 LEFT_MARGIN = 32; const uint32 RIGHT_MARGIN = 32; const uint32 TOP_MARGIN = 32; const uint32 BOTTOM_MARGIN = 32; uint32 PREVIEW_TEXTURE_WIDTH = 128; uint32 PREVIEW_TEXTURE_HEIGHT = 128; uint32 PREVIEW_TEXTURE_MARGIN = 8; MICROPROFILE_SCOPEI("WorldRenderer", "DrawIntermediateBuffers", MICROPROFILE_COLOR(120, 120, 45)); // can't do much without gui context if (m_pGUIContext != nullptr) { // align to aspect ratio float aspect = (float)m_options.RenderWidth / (float)m_options.RenderHeight; PREVIEW_TEXTURE_HEIGHT = 128; PREVIEW_TEXTURE_WIDTH = Math::Truncate((float)PREVIEW_TEXTURE_WIDTH * aspect); // enable batching m_pGUIContext->PushManualFlush(); // find the size of the grid we're going to need to draw uint32 freeSpaceX = m_options.RenderWidth - LEFT_MARGIN - RIGHT_MARGIN; uint32 freeSpaceY = m_options.RenderHeight - TOP_MARGIN - BOTTOM_MARGIN; uint32 gridColumns = freeSpaceX / (PREVIEW_TEXTURE_WIDTH + PREVIEW_TEXTURE_MARGIN); uint32 gridRows = freeSpaceY / (PREVIEW_TEXTURE_HEIGHT + PREVIEW_TEXTURE_MARGIN); if (gridColumns > 0 && gridRows > 0) { // allocate used grid items bool *usedGridItems = (bool *)alloca(sizeof(bool) * gridColumns * gridRows); Y_memzero(usedGridItems, sizeof(bool) * gridColumns * gridRows); // for each texture for (const DebugBufferView &dbv : m_debugBufferViews) { uint32 neededColumns = 1; if (dbv.pTexture->GetResourceType() == GPU_RESOURCE_TYPE_TEXTURE2DARRAY) //neededColumns = static_cast<GPUTexture2DArray *>(dbv.pTexture)->GetDesc()->ArraySize; continue; // find a free spot uint32 row = 0; uint32 column = 0; for (; row < gridRows; row++) { for (column = 0; column < gridColumns; column++) { if ((column + neededColumns) > gridColumns) { column = gridColumns; break; } uint32 idx = row * gridColumns + column; if (usedGridItems[idx]) continue; for (uint32 i = 0; i < neededColumns; i++) usedGridItems[idx + i] = true; break; } if (column != gridColumns) break; } // found one? if (row != gridRows) { uint32 startX = LEFT_MARGIN + (column * (PREVIEW_TEXTURE_WIDTH + PREVIEW_TEXTURE_MARGIN) + PREVIEW_TEXTURE_MARGIN); uint32 endX = startX + ((PREVIEW_TEXTURE_WIDTH * neededColumns) - 1); uint32 endY = m_options.RenderHeight - (row * (PREVIEW_TEXTURE_HEIGHT + PREVIEW_TEXTURE_MARGIN) + PREVIEW_TEXTURE_MARGIN); uint32 startY = endY - (PREVIEW_TEXTURE_HEIGHT - 1); MINIGUI_RECT rect(startX, endX, startY, endY); MINIGUI_UV_RECT uvRect(0.0f, 1.0f, 0.0f, 1.0f); m_pGUIContext->DrawTexturedRect(&rect, &uvRect, dbv.pTexture); m_pGUIContext->DrawTextAt(startX + 4, startY + 4, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MICROPROFILE_COLOR(255, 255, 255), dbv.Name); } } } // end batching m_pGUIContext->PopManualFlush(); } } void WorldRenderer::ExecuteRenderPasses() { MICROPROFILE_SCOPEI("WorldRenderer", "ExecuteRenderPasses", MICROPROFILE_COLOR(50, 50, 200)); if (!m_options.EnableMultithreadedRendering) return; m_commandListLock.Lock(); for (;;) { if (m_commandListsPending == 0) break; m_commandListLock.Unlock(); WaitForSingleObject(m_hQueueingCommandsSemaphore, INFINITE); m_commandListLock.Lock(); // could be primary or secondary that woke us, so just execute as many secondaries as possible while (!m_readySecondaryCommandLists.IsEmpty()) { GPUCommandList *pCommandList = m_readySecondaryCommandLists.PopFront(); m_pGPUContext->ExecuteCommandList(pCommandList); g_pRenderer->ReleaseCommandList(pCommandList); } } // ensure the semaphore is zero while (WaitForSingleObject(m_hQueueingCommandsSemaphore, 0) == WAIT_OBJECT_0); // execute primary command lists while (!m_readyPrimaryCommandLists.IsEmpty()) { GPUCommandList *pCommandList = m_readyPrimaryCommandLists.PopFront(); m_pGPUContext->ExecuteCommandList(pCommandList); g_pRenderer->ReleaseCommandList(pCommandList); } m_commandListLock.Unlock(); } <file_sep>/Engine/Source/Core/DDSWriter.h #pragma once #include "Core/Common.h" #include "Core/PixelFormat.h" #include "Core/DDSReader.h" #include "YBaseLib/ByteStream.h" class DDSWriter { public: DDSWriter(); ~DDSWriter(); void Initialize(ByteStream *pOutputStream); bool WriteHeader(DDS_TEXTURE_TYPE Type, PIXEL_FORMAT Format, uint32 Width, uint32 Height, uint32 DepthOrArraySize, uint32 MipCount); bool WriteMipLevel(uint32 MipLevel, const void *pData, uint32 cbData); bool Finalize(); private: ByteStream *m_pOutputStream; DDS_TEXTURE_TYPE m_eType; PIXEL_FORMAT m_pfFormat; uint32 m_uWidth, m_uHeight, m_uDepth; uint32 m_uArraySize, m_uMipCount; uint32 m_uCurrentMipLevel; uint32 m_uCurrentWidth, m_uCurrentHeight, m_uCurrentDepth; }; <file_sep>/Editor/Source/Editor/BlockMeshEditor/EditorBlockMeshEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/BlockMeshEditor/EditorBlockMeshEditor.h" #include "Editor/EditorRendererSwapChainWidget.h" #include "Editor/EditorResourcePreviewGenerator.h" #include "Editor/EditorProgressDialog.h" #include "Editor/EditorResourceSaveDialog.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorBlockVolumeRenderProxy.h" #include "Editor/EditorLightSimulator.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/BlockMeshUtilities.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" #include "Renderer/RenderWorld.h" Log_SetChannel(EditorBlockMeshEditor); // ui - must come last #include "Editor/BlockMeshEditor/ui_EditorBlockMeshEditor.h" static const uint32 BLOCK_TYPE_ICON_SIZE = 32; static const uint32 SELECTED_BLOCKS_TINT_COLOR = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 100, 100); static const uint32 PREVIEW_BLOCK_TINT_COLOR = MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 200); EditorBlockMeshEditor::EditorBlockMeshEditor() : QMainWindow(nullptr, 0), m_ui(new Ui_EditorBlockMeshEditor()), m_pBlockList(nullptr), m_pGenerator(nullptr), m_pAvailableBlockTypes(nullptr), m_nAvailableBlockTypes(0), m_renderMode(EDITOR_RENDER_MODE_FULLBRIGHT), m_viewportFlags(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS), m_pSwapChain(nullptr), m_pWorldRenderer(nullptr), m_bHardwareResourcesCreated(false), m_bRedrawPending(false), m_pRenderWorld(nullptr), m_pLightSimulator(nullptr), m_pMeshRenderProxy(nullptr), m_pSelectedRenderProxy(nullptr), m_pPreviewRenderProxy(nullptr), m_currentLOD(Y_UINT32_MAX), m_eCurrentWidget(WIDGET_COUNT), m_MouseOverBlock(int3::Zero), m_bMouseOverBlockSet(false), m_iMouseOverBlockFaceIndex(CUBE_FACE_COUNT), m_bMouseOverPlaceBlockSet(false), m_MouseOverPlaceBlock(int3::Zero), m_iPlaceBlockToolBlockType(0), m_iSelectedAreaCount(0), m_eCurrentState(STATE_NONE), m_iStateData(0), m_lastMousePosition(int2::Zero) { // init view controller m_viewController.SetCameraMode(EDITOR_CAMERA_MODE_PERSPECTIVE); // create ui m_ui->CreateUI(this); m_ui->UpdateUIForCameraMode(m_viewController.GetCameraMode()); m_ui->UpdateUIForRenderMode(m_renderMode); m_ui->UpdateUIForViewportFlags(m_viewportFlags); // add this as a tracked main window g_pEditor->AddMainWindow(this); } EditorBlockMeshEditor::~EditorBlockMeshEditor() { // force close can bypass this if (m_pGenerator != NULL) Deinitialize(); // remove tracked main window g_pEditor->RemoveMainWindow(this); // delete ui delete m_ui; } void EditorBlockMeshEditor::SetCameraMode(EDITOR_CAMERA_MODE cameraMode) { DebugAssert(cameraMode < EDITOR_CAMERA_MODE_COUNT); m_viewController.SetCameraMode(cameraMode); m_ui->UpdateUIForCameraMode(cameraMode); } void EditorBlockMeshEditor::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } // update state m_renderMode = renderMode; m_ui->UpdateUIForRenderMode(renderMode); delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); FlagForRedraw(); // update ui } void EditorBlockMeshEditor::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorBlockMeshEditor::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } bool EditorBlockMeshEditor::Create(const char *meshName, const BlockPalette *pBlockList, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pGenerator == NULL); m_meshName = meshName; m_meshFileName.Format("%s.blm.xml", meshName); // create the generator m_pGenerator = new BlockMeshGenerator(); if (!m_pGenerator->Create(pBlockList)) return false; m_pBlockList = pBlockList; m_pBlockList->AddRef(); return Initialize(pProgressCallbacks); } bool EditorBlockMeshEditor::Load(const char *meshName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pGenerator == NULL); m_meshFileName.Format("%s.blm.xml", meshName); if (!g_pVirtualFileSystem->GetFileName(m_meshFileName)) return false; AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(m_meshFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == NULL) return false; // update mesh name m_meshName = m_meshFileName.SubString(0, -8); // create the generator m_pGenerator = new BlockMeshGenerator(); if (!m_pGenerator->LoadFromXML(m_meshFileName, pStream)) return false; // init blocklist m_pBlockList = m_pGenerator->GetBlockList(); m_pBlockList->AddRef(); // init everything else return Initialize(pProgressCallbacks); } bool EditorBlockMeshEditor::Save(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pGenerator != NULL); // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(m_meshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } return true; } bool EditorBlockMeshEditor::SaveAs(const char *meshName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pGenerator != NULL); PathString newMeshFileName; newMeshFileName.Format("%s.blm.xml", meshName); // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(newMeshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } // update names m_meshName = meshName; m_meshFileName = newMeshFileName; // update ui m_ui->UpdateUIForOpenMesh(m_meshName); return true; } bool EditorBlockMeshEditor::IsBlockSelected(const int3 &coords) { uint32 i; for (i = 0; i < m_SelectedBlocks.GetSize(); i++) { if (m_SelectedBlocks[i] == coords) return true; } return false; } void EditorBlockMeshEditor::SelectBlock(const int3 &coords) { // has to be in range if (coords.AnyLess(m_pGenerator->GetMeshMinCoordinates(m_currentLOD)) || coords.AnyGreater(m_pGenerator->GetMeshMaxCoordinates(m_currentLOD))) return; // does it actually exist? BlockVolumeBlockType blockType = m_pGenerator->GetBlock(m_currentLOD, coords); if (blockType == 0) return; // already selected? uint32 i; for (i = 0; i < m_SelectedBlocks.GetSize(); i++) { if (m_SelectedBlocks[i] == coords) return; } // add to list m_SelectedBlocks.Add(coords); // remove blocks from the volume mesh // add blocks to the selected mesh m_meshVolume.SetBlock(coords, 0); m_selectedVolume.SetBlock(coords, blockType); UpdateMeshView(); UpdateSelectedBlocksView(); } void EditorBlockMeshEditor::DeselectBlock(const int3 &coords) { uint32 i; for (i = 0; i < m_SelectedBlocks.GetSize(); i++) { if (m_SelectedBlocks[i] == coords) break; } if (i == m_SelectedBlocks.GetSize()) return; m_SelectedBlocks.OrderedRemove(i); // get value BlockVolumeBlockType blockType = m_pGenerator->GetBlock(m_currentLOD, coords); // update meshes m_meshVolume.SetBlock(coords, blockType); m_selectedVolume.SetBlock(coords, 0); UpdateMeshView(); UpdateSelectedBlocksView(); } void EditorBlockMeshEditor::DeselectAllBlocks() { m_SelectedBlocks.Clear(); // fast path for this, just reset the view mesh m_meshVolume = m_pGenerator->GetMeshVolume(m_currentLOD); // clear the selection mesh m_selectedVolume.Clear(); // update views UpdateMeshView(); UpdateSelectedBlocksView(); } void EditorBlockMeshEditor::ExpandSelectionToHeight() { /* if (m_iSelectedAreaCount == 2) { m_SelectedArea[0].z = m_pGenerator->GetMinCoordinates().z; m_SelectedArea[1].z = m_pGenerator->GetMaxCoordinates().z; FlagForRedraw(); } */ } void EditorBlockMeshEditor::ExpandSelection(const int3 &direction) { /* if (m_iSelectedAreaCount == 2) { if (direction.x < 0) m_SelectedArea[0].x += direction.x; else if (direction.x > 0) m_SelectedArea[1].x += direction.x; if (direction.y < 0) m_SelectedArea[0].y += direction.y; else if (direction.y > 0) m_SelectedArea[1].y += direction.y; if (direction.z < 0) m_SelectedArea[0].z += direction.z; else if (direction.z > 0) m_SelectedArea[1].z += direction.z; m_SelectedArea[0] = m_SelectedArea[0].Max(m_pGenerator->GetMinCoordinates()); m_SelectedArea[1] = m_SelectedArea[1].Min(m_pGenerator->GetMaxCoordinates()); FlagForRedraw(); }*/ } void EditorBlockMeshEditor::ClearSelectedArea() { m_SelectedArea[0].SetZero(); m_SelectedArea[1].SetZero(); m_iSelectedAreaCount = 0; FlagForRedraw(); } void EditorBlockMeshEditor::MoveSelectedBlocks(const int3 &direction) { /* int3 oldMinCoordinates = m_pGenerator->GetMinCoordinates(); int3 oldMaxCoordinates = m_pGenerator->GetMaxCoordinates(); if (m_eCurrentWidget == WIDGET_SELECT_BLOCKS) { uint32 i; for (i = 0; i < m_SelectedBlocks.GetSize(); i++) m_pGenerator->MoveBlock(m_SelectedBlocks[i], direction); } else if (m_eCurrentWidget == WIDGET_SELECT_AREA && m_iSelectedAreaCount == 2) { m_pGenerator->MoveBlocks(m_SelectedArea[0], m_SelectedArea[1], direction); } int3 newMinCoordinates = m_pGenerator->GetMinCoordinates(); int3 newMaxCoordinates = m_pGenerator->GetMaxCoordinates(); if (newMinCoordinates != oldMinCoordinates || newMaxCoordinates != oldMaxCoordinates) { m_pMeshPreviewEntity->Resize(m_pGenerator->GetMinCoordinates(), m_pGenerator->GetMaxCoordinates()); m_pCallbacks->OnMeshResized(newMinCoordinates, newMaxCoordinates); } m_pMeshPreviewEntity->CopyBlockData(m_pGenerator->GetBlockData()); FlagForRedraw();*/ } void EditorBlockMeshEditor::SetCurrentLOD(uint32 LOD) { if (m_currentLOD == LOD) return; if (m_SelectedBlocks.GetSize() > 0) DeselectAllBlocks(); DebugAssert(LOD < m_pGenerator->GetLODCount()); m_currentLOD = LOD; m_ui->UpdateUIForCurrentLOD(LOD); // copy lod to current mesh m_meshVolume = m_pGenerator->GetMeshVolume(LOD); m_selectedVolume.Resize(m_meshVolume.GetMinCoordinates(), m_meshVolume.GetMaxCoordinates()); m_selectedVolume.Clear(); m_ui->UpdateUIForMeshSize(m_meshVolume.GetWidth(), m_meshVolume.GetLength(), m_meshVolume.GetHeight()); // update views UpdateMeshView(); } void EditorBlockMeshEditor::SetWidget(WIDGET t) { if (m_eCurrentWidget == t) return; // remove anything from current switch (m_eCurrentWidget) { case WIDGET_PLACE_BLOCKS: m_pPreviewRenderProxy->ClearMesh(); break; } // set new m_eCurrentWidget = t; m_ui->UpdateUIForWidget(t); // update new switch (m_eCurrentWidget) { case WIDGET_SELECT_BLOCKS: UpdateMouseBlockCoordinates(); break; case WIDGET_PLACE_BLOCKS: { UpdateMouseBlockCoordinates(); // refresh all the ui junk BlockVolumeBlockType oldPlaceValue = m_iPlaceBlockToolBlockType; m_iPlaceBlockToolBlockType = BLOCK_MESH_MAX_BLOCK_TYPES; SetPlaceBlockWidgetBlockType(oldPlaceValue); } break; case WIDGET_DELETE_BLOCKS: UpdateMouseBlockCoordinates(); break; } FlagForRedraw(); } void EditorBlockMeshEditor::SetPlaceBlockWidgetBlockType(BlockVolumeBlockType t) { if (m_iPlaceBlockToolBlockType == t) return; m_iPlaceBlockToolBlockType = t; UpdatePreviewMesh(t); for (uint32 i = 0; i < m_nAvailableBlockTypes; i++) { if (m_pAvailableBlockTypes[i].pBlockType->BlockTypeIndex == (uint32)t) { m_ui->UpdateUISelectedPlaceBlockType(m_pAvailableBlockTypes, m_nAvailableBlockTypes, i, m_eCurrentWidget); break; } } } void EditorBlockMeshEditor::SetNextPlaceBlockWidgetBlockType() { uint32 currentIndex; for (currentIndex = 0; currentIndex < m_nAvailableBlockTypes; currentIndex++) { if (m_pAvailableBlockTypes[currentIndex].pBlockType->BlockTypeIndex == (uint32)m_iPlaceBlockToolBlockType) break; } if (currentIndex == m_nAvailableBlockTypes) return; currentIndex++; currentIndex %= m_nAvailableBlockTypes; SetPlaceBlockWidgetBlockType((BlockVolumeBlockType)m_pAvailableBlockTypes[currentIndex].pBlockType->BlockTypeIndex); } void EditorBlockMeshEditor::SetPreviousPlaceBlockWidgetBlockType() { uint32 currentIndex; for (currentIndex = 0; currentIndex < m_nAvailableBlockTypes; currentIndex++) { if (m_pAvailableBlockTypes[currentIndex].pBlockType->BlockTypeIndex == (uint32)m_iPlaceBlockToolBlockType) break; } if (currentIndex == m_nAvailableBlockTypes) return; if (currentIndex == 0) currentIndex = m_nAvailableBlockTypes - 1; else currentIndex--; SetPlaceBlockWidgetBlockType((BlockVolumeBlockType)m_pAvailableBlockTypes[currentIndex].pBlockType->BlockTypeIndex); } bool EditorBlockMeshEditor::CreateHardwareResources() { Log_DevPrintf("Creating hardware resources for EditorStaticBlockMeshEditor (%u x %u)", (uint32)m_ui->swapChainWidget->size().width(), (uint32)m_ui->swapChainWidget->size().height()); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == NULL) return false; m_pSwapChain->AddRef(); } // get dimensions uint32 swapChainWidth = m_pSwapChain->GetWidth(); uint32 swapChainHeight = m_pSwapChain->GetHeight(); // update gui context, camera m_viewController.SetViewportDimensions(swapChainWidth, swapChainHeight); m_guiContext.SetViewportDimensions(swapChainWidth, swapChainHeight); // create render context if (m_pWorldRenderer == NULL) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); // cancel any pending draws until the windows are arranged and a paint is requested. m_bHardwareResourcesCreated = true; return true; } void EditorBlockMeshEditor::ReleaseHardwareResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; m_pWorldRenderer = NULL; SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_bHardwareResourcesCreated = false; } void EditorBlockMeshEditor::OnFrameExecutionTriggered(float timeSinceLastFrame) { // update camera m_viewController.Update(timeSinceLastFrame); // force draw if requested by camera if (m_viewController.IsChanged()) FlagForRedraw(); // redraw if required if (m_bRedrawPending) Draw(); } void EditorBlockMeshEditor::Draw() { // create hardware resources if (!m_bHardwareResourcesCreated && !CreateHardwareResources()) return; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // clear it pGPUContext->SetOutputBuffer(m_pSwapChain); pGPUContext->SetRenderTargets(0, NULL, NULL); pGPUContext->SetViewport(m_viewController.GetViewport()); pGPUContext->ClearTargets(true, true, true); // setup 3d state pGPUContext->GetConstants()->SetFromCamera(m_viewController.GetCamera(), true); // invoke draws DrawGrid(); DrawView(); // bias the projection matrix slightly FIXME //pGPUConstants->SetCameraProjectionMatrix(m_viewController.GetBiasedProjectionMatrix(0.01f), true); Draw3DOverlays(); // clear state pGPUContext->ClearState(true, true, true, true); // present pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // clear pending flag m_bRedrawPending = false; } void EditorBlockMeshEditor::DrawGrid() { const int3 &minCoordinates = m_pGenerator->GetMeshMinCoordinates(m_currentLOD); const int3 &maxCoordinates = m_pGenerator->GetMeshMaxCoordinates(m_currentLOD); float scale = m_pGenerator->GetMeshVolume(m_currentLOD).GetScale(); float3 minWorldCoordinates = float3(float(minCoordinates.x - 1), float(minCoordinates.y - 1), 0.0f) * scale; float3 maxWorldCoordinates = float3(float(maxCoordinates.x + 2), float(maxCoordinates.y + 2), 0.0f) * scale; m_guiContext.Draw3DGrid(minWorldCoordinates, maxWorldCoordinates, float3(scale, scale, scale), MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255)); } void EditorBlockMeshEditor::DrawView() { m_pWorldRenderer->DrawWorld(m_pRenderWorld, m_viewController.GetViewParameters(), NULL, NULL); } void EditorBlockMeshEditor::Draw3DOverlays() { // begin batching m_guiContext.SetDepthTestingEnabled(false); m_guiContext.SetAlphaBlendingEnabled(false); m_guiContext.PushManualFlush(); switch (m_eCurrentWidget) { case WIDGET_SELECT_BLOCKS: { // draw box around the currently highlighted block if (m_bMouseOverBlockSet) { float3 minCoordinates(float3((float)m_MouseOverBlock.x, (float)m_MouseOverBlock.y, (float)m_MouseOverBlock.z) * m_meshVolume.GetScale()); float3 maxCoordinates(minCoordinates + m_meshVolume.GetScale()); m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255)); } // draw boxes around each selected block for (uint32 i = 0; i < m_SelectedBlocks.GetSize(); i++) { const int3 &blockCoordinates = m_SelectedBlocks[i]; float3 minCoordinates(float3((float)blockCoordinates.x, (float)blockCoordinates.y, (float)blockCoordinates.z) * m_meshVolume.GetScale()); float3 maxCoordinates(minCoordinates + m_meshVolume.GetScale()); m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255)); } } break; /* case WIDGET_SELECT_AREA: { // do we have an area yet? if (m_iSelectedAreaCount == 2) { // yup, so draw a box around the whole area minCoordinates = Vector3(Vector3i(m_SelectedArea[0])) * blockSize; maxCoordinates = Vector3(Vector3i(m_SelectedArea[1])) * blockSize + blockSize; m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 150, 255)); } else { // do we have anything? if (m_iSelectedAreaCount == 1) { // draw a green box on the starting position minCoordinates = Vector3(Vector3i(m_SelectedArea[0])) * blockSize; maxCoordinates = minCoordinates + blockSize; m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255)); } // draw boxes around the spot where the block will be placed if (m_bMouseOverBlockSet || m_bMouseOverPlaceBlockSet) { minCoordinates = Vector3(Vector3i((m_bMouseOverBlockSet) ? m_MouseOverBlock : m_MouseOverPlaceBlock)) * blockSize; maxCoordinates = minCoordinates + blockSize; m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255)); } } } break;*/ case WIDGET_PLACE_BLOCKS: { // draw boxes around the spot where the block will be placed if (m_bMouseOverPlaceBlockSet) { float3 minCoordinates(float3((float)m_MouseOverPlaceBlock.x, (float)m_MouseOverPlaceBlock.y, (float)m_MouseOverPlaceBlock.z) * m_meshVolume.GetScale()); float3 maxCoordinates(minCoordinates + m_meshVolume.GetScale()); m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255)); } } break; case WIDGET_DELETE_BLOCKS: { // draw boxes around the block which will be deleted if (m_bMouseOverBlockSet) { float3 minCoordinates(float3((float)m_MouseOverBlock.x, (float)m_MouseOverBlock.y, (float)m_MouseOverBlock.z) * m_meshVolume.GetScale()); float3 maxCoordinates(minCoordinates + m_meshVolume.GetScale()); m_guiContext.Draw3DWireBox(minCoordinates, maxCoordinates, MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255)); } } break; } m_guiContext.Flush(); m_guiContext.PopManualFlush(); } bool EditorBlockMeshEditor::Initialize(ProgressCallbacks *pProgressCallbacks) { // generate block types { Timer generationTimer; pProgressCallbacks->SetStatusText("Building available block types..."); if (!GenerateAvailableBlockTypes(pProgressCallbacks)) return false; Log_PerfPrintf("EditorStaticBlockMeshEditor::Initialize: Available block type generation took %.4f msec", generationTimer.GetTimeMilliseconds()); } // create preview volume m_meshVolume.SetPalette(m_pBlockList); m_selectedVolume.SetPalette(m_pBlockList); m_previewVolume.SetPalette(m_pBlockList); m_previewVolume.Resize(int3::Zero, int3::Zero); // create world m_pRenderWorld = new RenderWorld(); // create light m_pLightSimulator = new EditorLightSimulator(0, m_pRenderWorld); // create composite render proxy m_pMeshRenderProxy = new EditorBlockVolumeRenderProxy(0); m_pRenderWorld->AddRenderable(m_pMeshRenderProxy); // creat selected render proxy m_pSelectedRenderProxy = new EditorBlockVolumeRenderProxy(0); m_pRenderWorld->AddRenderable(m_pSelectedRenderProxy); // create preview composite render proxy m_pPreviewRenderProxy = new EditorBlockVolumeRenderProxy(0); m_pRenderWorld->AddRenderable(m_pPreviewRenderProxy); // update ui for mesh m_ui->UpdateUIForOpenMesh(m_meshName); m_ui->UpdateUIForLODCount(m_pGenerator->GetLODCount(), false); // update camera m_viewController.SetCameraMode(EDITOR_CAMERA_MODE_PERSPECTIVE); m_viewController.SetPerspectiveAcceleration(10.0f * m_pGenerator->GetScale()); m_viewController.SetPerspectiveMaxSpeed(2.0f * m_pGenerator->GetScale()); m_viewController.Reset(); // set modes SetWidget(WIDGET_CAMERA); SetCurrentLOD(0); // connect ui events ConnectUIEvents(); // ok return true; } void EditorBlockMeshEditor::Deinitialize() { // kill gpu resources ReleaseHardwareResources(); // kill world and entities SAFE_RELEASE(m_pMeshRenderProxy); SAFE_RELEASE(m_pPreviewRenderProxy); delete m_pLightSimulator; delete m_pRenderWorld; m_pRenderWorld = nullptr; delete m_pGenerator; m_pGenerator = nullptr; SAFE_RELEASE(m_pBlockList); // ensure the frame event dies disconnect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); } bool EditorBlockMeshEditor::GenerateAvailableBlockTypes(ProgressCallbacks *pProgressCallbacks) { uint32 nAvailableBlocks = 0; for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { if (m_pBlockList->GetBlockType(i)->IsAllocated) nAvailableBlocks++; } m_pAvailableBlockTypes = new AvailableBlockType[nAvailableBlocks + 1]; m_nAvailableBlockTypes = nAvailableBlocks; nAvailableBlocks = 0; // add air m_pAvailableBlockTypes[nAvailableBlocks].pBlockType = m_pBlockList->GetBlockType(0); m_pAvailableBlockTypes[nAvailableBlocks].BlockName = "None"; nAvailableBlocks++; // prepare the icon Image renderedBlockTypeIcon; renderedBlockTypeIcon.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, BLOCK_TYPE_ICON_SIZE, BLOCK_TYPE_ICON_SIZE, 1); // init preview generator EditorResourcePreviewGenerator previewGenerator; previewGenerator.SetGPUContext(g_pRenderer->GetGPUContext()); // setup progress pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetProgressRange(m_nAvailableBlockTypes); pProgressCallbacks->SetProgressValue(0); // generate icons for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { const BlockPalette::BlockType *pBlockType = m_pBlockList->GetBlockType(i); if (!pBlockType->IsAllocated) continue; m_pAvailableBlockTypes[nAvailableBlocks].pBlockType = pBlockType; m_pAvailableBlockTypes[nAvailableBlocks].BlockName = pBlockType->Name; if (!previewGenerator.GenerateBlockMeshBlockListBlockPreview(&renderedBlockTypeIcon, m_pBlockList, (BlockVolumeBlockType)pBlockType->BlockTypeIndex)) { Log_WarningPrintf("EditorStaticBlockMeshEditor::GenerateAvailableBlockTypes: Generate icon for %u (%s) failed.", i, pBlockType->Name.GetCharArray()); Y_memset(renderedBlockTypeIcon.GetData(), 0xFF, renderedBlockTypeIcon.GetDataSize()); } QPixmap qPixmap; if (!EditorHelpers::ConvertImageToQPixmap(renderedBlockTypeIcon, &qPixmap)) Log_WarningPrintf("EditorStaticBlockMeshEditor::GenerateAvailableBlockTypes: Conversion to image for %u (%s) failed.", i, pBlockType->Name.GetCharArray()); else m_pAvailableBlockTypes[nAvailableBlocks].BlockTypeIcon.addPixmap(qPixmap); pProgressCallbacks->SetProgressValue(nAvailableBlocks); nAvailableBlocks++; } // set the various combo boxes up m_ui->UpdateUIAvailableBlockTypes(BLOCK_TYPE_ICON_SIZE, m_pAvailableBlockTypes, m_nAvailableBlockTypes); pProgressCallbacks->SetProgressValue(m_nAvailableBlockTypes); return true; } bool EditorBlockMeshEditor::OnCloseAttempt() { if (m_pGenerator != NULL && m_pGenerator->IsChanged()) { int result = QMessageBox::question(this, tr("Save open mesh?"), tr("The current open mesh is changed, do you wish to save the changes made to it?"), (QMessageBox::StandardButtons)(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel), QMessageBox::Yes); if (result == QMessageBox::Yes) OnActionSaveMeshClicked(); else if (result == QMessageBox::Cancel) return false; } return true; } bool EditorBlockMeshEditor::GetBlockCoordinatesForMousePosition(int3 *pBlockCoordinates, CUBE_FACE *pFaceIndex, const int2 &mousePosition) const { Ray hitRay = m_viewController.GetPickRay(mousePosition.x, mousePosition.y); //Log_DevPrintf("[%i, %i] -> %s --- %s (%s) (%f)", mousePosition.x, mousePosition.y, StringConverter::Float3ToString(hitRay.GetOrigin()).GetCharArray(), StringConverter::Float3ToString(hitRay.GetEnd()).GetCharArray(), StringConverter::Float3ToString(hitRay.GetDirection()).GetCharArray(), hitRay.GetDistance()); float intersectionTime; return m_pGenerator->GetMeshVolume(m_currentLOD).RayCastTimeFace(hitRay, pBlockCoordinates, &intersectionTime, pFaceIndex, false); } bool EditorBlockMeshEditor::GetPlaceBlockCoordinatesForMousePosition(int3 *pBlockCoordinates, const int2 &mousePosition) const { Ray hitRay = m_viewController.GetPickRay(mousePosition.x, mousePosition.y); int3 meshHitBlock; float meshHitDistance; CUBE_FACE meshHitFace; // hit against the mesh if (!m_pGenerator->GetMeshVolume(m_currentLOD).RayCastTimeFace(hitRay, &meshHitBlock, &meshHitDistance, &meshHitFace, false)) meshHitDistance = Y_FLT_INFINITE; // hit against the plane Plane groundPlane(float3::UnitZ, 0.0f); float3 planeHitLocation; float3 planeHitNormal; float planeHitDistance; if (hitRay.PlaneIntersection(groundPlane, planeHitNormal, planeHitLocation)) planeHitDistance = (planeHitLocation - hitRay.GetOrigin()).Length(); else planeHitDistance = Y_FLT_INFINITE; // perfer mesh over plane if (meshHitDistance <= planeHitDistance) { // cater for both == inf case if (meshHitDistance == Y_FLT_INFINITE) return false; // we need to offset the block, depending on which face was hit switch (meshHitFace) { case CUBE_FACE_RIGHT: meshHitBlock.x++; break; case CUBE_FACE_LEFT: meshHitBlock.x--; break; case CUBE_FACE_BACK: meshHitBlock.y++; break; case CUBE_FACE_FRONT: meshHitBlock.y--; break; case CUBE_FACE_TOP: meshHitBlock.z++; break; case CUBE_FACE_BOTTOM: meshHitBlock.z--; break; } *pBlockCoordinates = meshHitBlock; return true; } // work out which block on the plane the ray is colliding with float3 hitBlockCoordsF = planeHitLocation / (float)m_meshVolume.GetScale(); int3 hitBlockCoords(Math::Truncate(Math::Floor(hitBlockCoordsF.x)), Math::Truncate(Math::Floor(hitBlockCoordsF.y)), 0); //Log_DevPrintf("hitloc: %f %f %f, block: %i %i %i", planeHitLocation.x, planeHitLocation.y, planeHitLocation.z, hitBlockCoords.x, hitBlockCoords.y, hitBlockCoords.z); // make sure that block isn't occupied by anything currently. additionally, if it's +/- 1 // from the mesh boundaries, we'll allow it, otherwise ignore it (out of range) if (((hitBlockCoords >= m_pGenerator->GetMeshMinCoordinates(m_currentLOD) && hitBlockCoords <= m_pGenerator->GetMeshMaxCoordinates(m_currentLOD)) && m_pGenerator->GetBlock(m_currentLOD, hitBlockCoords) != 0) || ((hitBlockCoords + int3::One) >= m_pGenerator->GetMeshMinCoordinates(m_currentLOD) && (hitBlockCoords - int3::One) <= m_pGenerator->GetMeshMaxCoordinates(m_currentLOD))) { *pBlockCoordinates = hitBlockCoords; return true; } // nothing return false; } void EditorBlockMeshEditor::SetBlock(const int3 &blockPosition, BlockVolumeBlockType value) { Log_DevPrintf("EditorStaticBlockMeshEditor::SetBlock(%i, %i, %i, %u)", blockPosition.x, blockPosition.y, blockPosition.z, (uint32)value); m_pGenerator->SetBlock(m_currentLOD, blockPosition, value); CheckForMeshSizeChanges(); m_meshVolume.SetBlock(blockPosition, value); UpdateMeshView(); } void EditorBlockMeshEditor::CheckForMeshSizeChanges() { const BlockMeshVolume &realVolume = m_pGenerator->GetMeshVolume(m_currentLOD); if (m_meshVolume.GetMinCoordinates() != realVolume.GetMinCoordinates() || m_meshVolume.GetMaxCoordinates() != realVolume.GetMaxCoordinates()) { m_meshVolume.Resize(realVolume.GetMinCoordinates(), realVolume.GetMaxCoordinates()); m_selectedVolume.Resize(realVolume.GetMinCoordinates(), realVolume.GetMaxCoordinates()); m_ui->UpdateUIForMeshSize(realVolume.GetWidth(), realVolume.GetLength(), realVolume.GetHeight()); } } void EditorBlockMeshEditor::UpdateMouseBlockCoordinates() { int3 mouseOverBlock; CUBE_FACE mouseOverBlockFaceIndex; bool validMouseOverBlock = GetBlockCoordinatesForMousePosition(&mouseOverBlock, &mouseOverBlockFaceIndex, m_lastMousePosition); if (validMouseOverBlock) { if (!m_bMouseOverBlockSet || (m_MouseOverBlock != mouseOverBlock)) { Log_DevPrintf("block under mouse set: %i,%i,%i", m_MouseOverBlock.x, m_MouseOverBlock.y, m_MouseOverBlock.z); m_MouseOverBlock = mouseOverBlock; m_iMouseOverBlockFaceIndex = mouseOverBlockFaceIndex; m_bMouseOverBlockSet = true; if (m_eCurrentWidget == WIDGET_SELECT_BLOCKS || m_eCurrentWidget == WIDGET_SELECT_AREA || m_eCurrentWidget == WIDGET_DELETE_BLOCKS) FlagForRedraw(); } } else if (m_bMouseOverBlockSet) { Log_DevPrintf("block under mouse set: NONE"); m_bMouseOverBlockSet = false; m_MouseOverBlock.SetZero(); if (m_eCurrentWidget == WIDGET_SELECT_BLOCKS || m_eCurrentWidget == WIDGET_SELECT_AREA || m_eCurrentWidget == WIDGET_DELETE_BLOCKS) FlagForRedraw(); } // are we in a placeable block position? int3 mouseOverPlaceBlock; bool validMouseOverPlaceBlock = GetPlaceBlockCoordinatesForMousePosition(&mouseOverPlaceBlock, m_lastMousePosition); if (validMouseOverPlaceBlock) { if (!m_bMouseOverPlaceBlockSet || (mouseOverPlaceBlock != m_MouseOverPlaceBlock)) { Log_DevPrintf("place block position set: %i,%i,%i", mouseOverPlaceBlock.x, mouseOverPlaceBlock.y, mouseOverPlaceBlock.z); m_MouseOverPlaceBlock = mouseOverPlaceBlock; m_bMouseOverPlaceBlockSet = true; if (m_eCurrentWidget == WIDGET_PLACE_BLOCKS) { // work out new base offset of the place block mesh float3 placeMeshOffset(float3((float)mouseOverPlaceBlock.x, (float)mouseOverPlaceBlock.y, (float)mouseOverPlaceBlock.z) * m_meshVolume.GetScale()); m_pPreviewRenderProxy->SetTransform(Transform(placeMeshOffset, Quaternion::Identity, float3::One).GetTransformMatrix4x4()); m_pPreviewRenderProxy->SetVisibility(true); FlagForRedraw(); } } } else if (m_bMouseOverPlaceBlockSet) { Log_DevPrintf("place block position set: NONE"); m_bMouseOverPlaceBlockSet = false; m_MouseOverPlaceBlock.SetZero(); if (m_eCurrentWidget == WIDGET_PLACE_BLOCKS) { // clear the preview mesh m_pPreviewRenderProxy->SetVisibility(false); FlagForRedraw(); } } } void EditorBlockMeshEditor::UpdateMeshView() { m_pMeshRenderProxy->BuildMesh(&m_meshVolume, m_pGenerator->GetUseAmbientOcclusion()); FlagForRedraw(); } void EditorBlockMeshEditor::UpdateSelectedBlocksView() { m_pSelectedRenderProxy->BuildMesh(&m_selectedVolume, m_pGenerator->GetUseAmbientOcclusion()); FlagForRedraw(); } void EditorBlockMeshEditor::UpdatePreviewMesh(BlockVolumeBlockType blockType) { m_previewVolume.SetBlock(0, 0, 0, blockType); if (blockType != 0) m_pPreviewRenderProxy->BuildMesh(&m_previewVolume, m_pGenerator->GetUseAmbientOcclusion()); else m_pPreviewRenderProxy->ClearMesh(); if (m_eCurrentWidget == WIDGET_PLACE_BLOCKS) FlagForRedraw(); } void EditorBlockMeshEditor::ConnectUIEvents() { // actions connect(m_ui->actionSaveMesh, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshClicked())); connect(m_ui->actionSaveMeshAs, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshAsClicked())); connect(m_ui->actionClose, SIGNAL(triggered()), this, SLOT(OnActionCloseClicked())); connect(m_ui->actionEditUndo, SIGNAL(triggered()), this, SLOT(OnActionEditUndoClicked())); connect(m_ui->actionEditRedo, SIGNAL(triggered()), this, SLOT(OnActionEditRedoClicked())); connect(m_ui->actionCameraPerspective, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraPerspectiveTriggered(bool))); connect(m_ui->actionCameraArcball, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraArcballTriggered(bool))); connect(m_ui->actionCameraIsometric, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraIsometricTriggered(bool))); connect(m_ui->actionViewWireframe, SIGNAL(triggered(bool)), this, SLOT(OnActionViewWireframeTriggered(bool))); connect(m_ui->actionViewUnlit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewUnlitTriggered(bool))); connect(m_ui->actionViewLit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewLitTriggered(bool))); connect(m_ui->actionViewFlagShadows, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagShadowsTriggered(bool))); connect(m_ui->actionViewFlagWireframeOverlay, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagWireframeOverlayTriggered(bool))); connect(m_ui->actionWidgetCamera, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetCameraTriggered(bool))); connect(m_ui->actionWidgetSelectBlocks, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetSelectBlocksTriggered(bool))); connect(m_ui->actionWidgetSelectArea, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetSelectAreaTriggered(bool))); connect(m_ui->actionWidgetPlaceBlocks, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetPlaceBlocksTriggered(bool))); connect(m_ui->actionWidgetDeleteBlocks, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetDeleteBlocksTriggered(bool))); connect(m_ui->actionWidgetLightManipulator, SIGNAL(triggered(bool)), this, SLOT(OnActionWidgetLightManipulatorTriggered(bool))); // place widget connect(m_ui->placeBlocksWidgetPaletteList, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(OnPlaceBlockWidgetListWidgetItemClicked(QListWidgetItem *))); // swapchain connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); connect(m_ui->swapChainWidget, SIGNAL(DropEvent(QDropEvent *)), this, SLOT(OnSwapChainWidgetDropEvent(QDropEvent *))); // frame event connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); } void EditorBlockMeshEditor::closeEvent(QCloseEvent *pCloseEvent) { if (!OnCloseAttempt()) { pCloseEvent->ignore(); return; } QMainWindow::closeEvent(pCloseEvent); Deinitialize(); deleteLater(); } void EditorBlockMeshEditor::OnActionSaveMeshClicked() { EditorProgressDialog progressDialog(this); progressDialog.show(); if (!Save(&progressDialog)) QMessageBox::critical(this, tr("Save mesh operation failed"), tr("Save mesh operation failed. Any changes on-disk have been reverted."), QMessageBox::Ok); } void EditorBlockMeshEditor::OnActionSaveMeshAsClicked() { PathString tempPath; for (;;) { EditorResourceSaveDialog saveDialog(this, OBJECT_TYPEINFO(BlockMesh)); int res = saveDialog.exec(); if (res == 0) return; // construct temporary path tempPath.Format("%s.staticblockmesh.xml", saveDialog.GetReturnValueResourceName().GetCharArray()); if (g_pVirtualFileSystem->FileExists(tempPath)) { res = QMessageBox::question(this, tr("Question"), tr("The specified file already exists. Do you wish to overwrite it?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (res == QMessageBox::Cancel) return; if (res == QMessageBox::No) continue; } tempPath.Clear(); tempPath.AppendString(saveDialog.GetReturnValueResourceName()); break; } EditorProgressDialog progressDialog(this); progressDialog.show(); if (!SaveAs(tempPath, &progressDialog)) QMessageBox::critical(this, tr("Save mesh operation failed"), tr("Save mesh operation failed. Any changes on-disk have been reverted."), QMessageBox::Ok); } void EditorBlockMeshEditor::OnActionCloseClicked() { close(); } void EditorBlockMeshEditor::OnActionEditUndoClicked() { } void EditorBlockMeshEditor::OnActionEditRedoClicked() { } void EditorBlockMeshEditor::OnSwapChainWidgetResized() { uint32 newWidth = (uint32)m_ui->swapChainWidget->size().width(); uint32 newHeight = (uint32)m_ui->swapChainWidget->size().height(); // kill old swapchain refs if (m_pSwapChain != NULL) { m_pSwapChain->Release(); m_pSwapChain = NULL; } // skip full recreation if we can just do the resize if (m_bHardwareResourcesCreated && (m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) != NULL) m_pSwapChain->AddRef(); else m_bHardwareResourcesCreated = false; m_viewController.SetViewportDimensions(newWidth, newHeight); m_guiContext.SetViewportDimensions(newWidth, newHeight); // flag for redraw FlagForRedraw(); } void EditorBlockMeshEditor::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorBlockMeshEditor::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // // we handle camera movement via the keyboard. // bool isKeyDownEvent = (pKeyboardEvent->Event == INPUT_EVENT_TYPE_KEYBOARD_KEY_DOWN); // bool isKeyUpEvent = (pKeyboardEvent->Event == INPUT_EVENT_TYPE_KEYBOARD_KEY_UP); // if ((isKeyDownEvent | isKeyUpEvent)) // { // // } // pass to camera m_viewController.HandleKeyboardEvent(pKeyboardEvent); } void EditorBlockMeshEditor::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { // if not currently in any state, determine which state to transition to if (m_eCurrentState == STATE_NONE) { switch (m_eCurrentWidget) { case WIDGET_CAMERA: m_eCurrentState = STATE_MOVE_CAMERA; return; case WIDGET_SELECT_BLOCKS: { if (m_bMouseOverBlockSet) { if (!IsBlockSelected(m_MouseOverBlock)) SelectBlock(m_MouseOverBlock); else DeselectBlock(m_MouseOverBlock); FlagForRedraw(); return; } } break; case WIDGET_PLACE_BLOCKS: { // set the block if (m_bMouseOverPlaceBlockSet) { SetBlock(m_MouseOverPlaceBlock, m_iPlaceBlockToolBlockType); UpdateMouseBlockCoordinates(); FlagForRedraw(); } } break; case WIDGET_SELECT_AREA: { // have a selection? if (m_iSelectedAreaCount < 2 && (m_bMouseOverBlockSet || m_bMouseOverPlaceBlockSet)) { m_SelectedArea[m_iSelectedAreaCount++] = (m_bMouseOverBlockSet) ? m_MouseOverBlock : m_MouseOverPlaceBlock; if (m_iSelectedAreaCount == 2) { int3 fixedMinCoords = m_SelectedArea[0].Min(m_SelectedArea[1]); int3 fixedMaxCoords = m_SelectedArea[0].Max(m_SelectedArea[1]); m_SelectedArea[0] = fixedMinCoords; m_SelectedArea[1] = fixedMaxCoords; } FlagForRedraw(); } } break; case WIDGET_DELETE_BLOCKS: { // delete the block the mouse is over if (m_bMouseOverBlockSet) { SetBlock(m_MouseOverBlock, 0); UpdateMouseBlockCoordinates(); FlagForRedraw(); } } break; case WIDGET_LIGHT_MANIPULATOR: { m_eCurrentState = STATE_MANIPULATE_LIGHT; } break; } } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { switch (m_eCurrentState) { case STATE_MOVE_CAMERA: case STATE_ROTATE_CAMERA: case STATE_MANIPULATE_LIGHT: { m_eCurrentState = STATE_NONE; return; } break; } } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_eCurrentState == STATE_NONE) { // right mouse button enters camera rotation state m_eCurrentState = STATE_ROTATE_CAMERA; return; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_eCurrentState == STATE_ROTATE_CAMERA) { m_eCurrentState = STATE_NONE; return; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pMouseEvent->x(), pMouseEvent->y()); int2 lastMousePosition(m_lastMousePosition); int2 mousePositionDiff(currentMousePosition - lastMousePosition); m_lastMousePosition = currentMousePosition; // update the block position that we are under UpdateMouseBlockCoordinates(); // handle mouse movement based on state switch (m_eCurrentState) { case STATE_NONE: { } break; case STATE_MOVE_CAMERA: { m_viewController.MoveFromMousePosition(mousePositionDiff); FlagForRedraw(); } break; case STATE_ROTATE_CAMERA: { m_viewController.RotateFromMousePosition(mousePositionDiff); FlagForRedraw(); } break; case STATE_MANIPULATE_LIGHT: { m_pLightSimulator->ManipulateFromMouseMovement(mousePositionDiff); FlagForRedraw(); } break; } } } void EditorBlockMeshEditor::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { if (m_eCurrentWidget == WIDGET_PLACE_BLOCKS && pWheelEvent->orientation() == Qt::Vertical) (pWheelEvent->delta() > 0) ? SetPreviousPlaceBlockWidgetBlockType() : SetNextPlaceBlockWidgetBlockType(); } void EditorBlockMeshEditor::OnSwapChainWidgetGainedFocusEvent() { } void EditorBlockMeshEditor::OnPlaceBlockWidgetToolButtonClicked(bool checked) { // find the index of the sender QObject *pSender = sender(); uint32 index; for (index = 0; index < m_nAvailableBlockTypes; index++) { if (m_ui->placeBlocksWidgetPaletteIcons[index] == pSender) break; } if (index == m_nAvailableBlockTypes) return; SetPlaceBlockWidgetBlockType((BlockVolumeBlockType)m_pAvailableBlockTypes[index].pBlockType->BlockTypeIndex); } void EditorBlockMeshEditor::OnPlaceBlockWidgetListWidgetItemClicked(QListWidgetItem *pItem) { int row = m_ui->placeBlocksWidgetPaletteList->currentRow(); if ((uint32)row < m_nAvailableBlockTypes) SetPlaceBlockWidgetBlockType((BlockVolumeBlockType)m_pAvailableBlockTypes[row].pBlockType->BlockTypeIndex); } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUQuery.h #pragma once #include "D3D11Renderer/D3D11Common.h" class D3D11GPUQuery : public GPUQuery { public: D3D11GPUQuery(GPU_QUERY_TYPE type, ID3D11Query *pQuery, ID3D11Predicate *pPredicate); ~D3D11GPUQuery(); virtual GPU_QUERY_TYPE GetQueryType() const override { return m_eType; } virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11Query *GetD3DQuery() const { return m_pD3DQuery; } ID3D11Predicate *GetD3DPredicate() const { return m_pD3DPredicate; } D3D11GPUContext *GetOwningContext() const { return m_pOwningContext; } void SetOwningContext(D3D11GPUContext *pContext) { m_pOwningContext = pContext; } protected: GPU_QUERY_TYPE m_eType; ID3D11Query *m_pD3DQuery; ID3D11Predicate *m_pD3DPredicate; D3D11GPUContext *m_pOwningContext; }; <file_sep>/Engine/Source/GameFramework/ParticleEmitterEntity.h #pragma once #include "Engine/Entity.h" #include "Engine/ParticleSystem.h" class ParticleSystemRenderProxy; class ParticleEmitterEntity : public Entity { DECLARE_ENTITY_TYPEINFO(ParticleEmitterEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(ParticleEmitterEntity); public: ParticleEmitterEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ParticleEmitterEntity(); // accessors bool IsActive() const { return m_active; } // particle system const ParticleSystem *GetParticleSystem() const { return m_pParticleSystem; } void SetParticleSystem(const ParticleSystem *pParticleSystem); // create new instance void Create(uint32 entityID, const ParticleSystem *pParticleSystem, const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One); // reset to initial state void Reset(); // activate/deactivate void Activate(); void Deactivate(); // Events virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; virtual void OnComponentBoundsChange() override; virtual void Update(float timeSinceLastUpdate) override; private: const ParticleSystem *m_pParticleSystem; bool m_autoStart; ParticleSystemRenderProxy *m_pRenderProxy; bool m_active; }; <file_sep>/Engine/Source/Engine/Map.h #pragma once #include "Engine/Common.h" #include "Engine/DynamicWorld.h" #include "Engine/TerrainTypes.h" class Camera; class MapRegion; class ZipArchive; class ClassTable; namespace Physics { class StaticObject; } class TerrainLayerList; class TerrainSection; class TerrainSectionCollisionShape; class TerrainSectionRenderProxy; class TerrainRenderer; class Map { friend class MapRegion; public: Map(); virtual ~Map(); // accessors const String &GetMapName() const { return m_mapName; } const AABox &GetMapBounds() const { return m_mapBounds; } const uint32 GetRegionSize() const { return m_regionSize; } const uint32 GetLoadRadius() const { return m_regionLoadRadius; } const uint32 GetActivationRadius() const { return m_regionActivationRadius; } const World *GetWorld() const { return m_pWorld; } // terrain const TerrainParameters *GetTerrainParameters() const { return &m_terrainParameters; } const TerrainLayerList *GetTerrainManager() const { return m_pTerrainLayerList; } const TerrainRenderer *GetTerrainRenderer() const { return m_pTerrainRenderer; } TerrainRenderer *GetTerrainRenderer() { return m_pTerrainRenderer; } // non-const accessors DynamicWorld *GetWorld() { return m_pWorld; } // helper methods const int2 GetRegionForPosition(const float3 &position) const; // World entity id tracking const uint32 GetWorldEntityIdForMapEntityName(const char *mapEntityName); // Loading of map directory bool LoadMap(const char *mapName, const float3 *pInitialPositionOverride = nullptr, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // Region management bool LoadRegion(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool ChangeRegionLOD(int32 regionX, int32 regionY, int32 newLOD, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void UnloadRegion(int32 regionX, int32 regionY); void LoadAllRegions(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void UnloadAllRegions(); // Streaming void HandleStreaming(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); private: bool LoadRegionsHeader(ProgressCallbacks *pProgressCallbacks); bool LoadTerrainHeader(ProgressCallbacks *pProgressCallbacks); bool LoadGlobalEntities(ProgressCallbacks *pProgressCallbacks); uint32 CreateEntitiesFromStream(ByteStream *pStream, uint32 entityCount, uint32 entityDataSize, PODArray<uint32> *pOutDynamicEntityIDArray, PODArray<Brush *> *pOutStaticObjectsArray, ProgressCallbacks *pProgressCallbacks); String m_mapName; ZipArchive *m_pMapArchive; ClassTable *m_pClassTable; AABox m_mapBounds; uint32 m_regionSize; uint32 m_regionLODLevels; uint32 m_regionLoadRadius; uint32 m_regionActivationRadius; typedef HashTable<int2, MapRegion *> MapRegionTable; MapRegionTable m_regions; DynamicWorld *m_pWorld; CIStringHashTable<uint32> m_mapEntityNameMapping; // TODO: Global static entities, load on camera distance < threshold // terrain TerrainParameters m_terrainParameters; const TerrainLayerList *m_pTerrainLayerList; TerrainRenderer *m_pTerrainRenderer; }; class MapRegion { public: MapRegion(Map *pMap, int32 regionX, int32 regionY); ~MapRegion(); const int32 GetRegionX() const { return m_regionX; } const int32 GetRegionY() const { return m_regionY; } const int32 GetLoadedLODLevel() const { return m_loadedLODLevel; } const bool IsLoaded() const { return (m_loadedLODLevel >= 0); } bool LoadRegion(ByteStream *pStream, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks); void UnloadRegion(); private: Map *m_pMap; int32 m_regionX, m_regionY; int32 m_loadedLODLevel; PODArray<uint32> m_loadedEntityIDs; PODArray<Brush *> m_loadedStaticObjects; struct RegionTerrainSection { TerrainSection *pData; TerrainSectionCollisionShape *pCollisionShape; Physics::StaticObject *pCollisionObject; TerrainSectionRenderProxy *pRenderProxy; }; MemArray<RegionTerrainSection> m_terrainSections; }; <file_sep>/Editor/Source/Editor/EditorRendererSwapChainWidget.h #pragma once #include "Editor/Common.h" class EditorRendererSwapChainWidget : public QWidget { Q_OBJECT public: EditorRendererSwapChainWidget(QWidget *pParent, Qt::WindowFlags flags = 0); ~EditorRendererSwapChainWidget(); GPUOutputBuffer *GetSwapChain() const; void DestroySwapChain(); protected: virtual QPaintEngine *paintEngine() const; virtual void resizeEvent(QResizeEvent *pEvent); virtual void paintEvent(QPaintEvent *pEvent); virtual void focusInEvent(QFocusEvent *pEvent); virtual void focusOutEvent(QFocusEvent *pEvent); virtual void keyPressEvent(QKeyEvent *pKeyEvent); virtual void keyReleaseEvent(QKeyEvent *pKeyEvent); virtual void mouseMoveEvent(QMouseEvent *pMouseEvent); virtual void mousePressEvent(QMouseEvent *pMouseEvent); virtual void mouseReleaseEvent(QMouseEvent *pMouseEvent); virtual void wheelEvent(QWheelEvent *pWheelEvent); virtual void dropEvent(QDropEvent *pDropEvent); Q_SIGNALS: void ResizedEvent(); void PaintEvent(); void GainedFocusEvent(); void LostFocusEvent(); void KeyboardEvent(const QKeyEvent *pKeyboardEvent); void MouseEvent(const QMouseEvent *pMouseEvent); void WheelEvent(const QWheelEvent *pWheelEvent); void DropEvent(QDropEvent *pDropEvent); private: void RecreateSwapChain(); GPUOutputBuffer *m_pSwapChain; }; <file_sep>/Engine/Source/GameFramework/PointLightComponent.h #include "Engine/Component.h" class PointLightRenderProxy; class PointLightComponent : public Component { DECLARE_COMPONENT_TYPEINFO(PointLightComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(PointLightComponent); public: PointLightComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~PointLightComponent(); // property accessors const bool GetEnabled() const { return m_enabled; } const float GetRange() const { return m_range; } const float3 &GetColor() const { return m_color; } const float GetBrightness() const { return m_brightness; } const uint32 GetShadowFlags() const { return m_shadowFlags; } const float GetFalloffExponent() const { return m_falloffExponent; } // property setters void SetEnabled(bool enabled); void SetRange(float range); void SetColor(const float3 &color); void SetBrightness(float brightness); void SetShadowFlags(uint32 lightShadowFlags); void SetFalloffExponent(float falloffExponent); // External creation method void Create(const float3 &localPosition = float3::Zero, bool enabled = true, float range = 8.0f, const float3 &color = float3::One, float brightness = 1.0f, uint32 shadowFlags = 0, float falloffExponent = 1.0f); // inherited methods virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; private: // helper functions float3 CalculateLightPosition() const; float3 CalculateLightColor() const; // property callbacks static void OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData = nullptr); static void OnRangePropertyChange(ThisClass *pEntity, const void *pUserData = nullptr); static void OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData = nullptr); static void OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData = nullptr); static void OnFalloffExponentChange(ThisClass *pEntity, const void *pUserData = nullptr); // local copy of properties bool m_enabled; float m_range; float3 m_color; float m_brightness; uint32 m_shadowFlags; float m_falloffExponent; // instance of render proxy PointLightRenderProxy *m_pRenderProxy; }; <file_sep>/Engine/Source/Engine/BlockMesh.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockMesh.h" #include "Engine/DataFormats.h" #include "Engine/ResourceManager.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/Physics/CollisionShape.h" #include "Engine/BlockMeshCollisionShape.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" #include "Core/ChunkFileReader.h" Log_SetChannel(BlockMesh); DEFINE_RESOURCE_TYPE_INFO(BlockMesh); DEFINE_RESOURCE_GENERIC_FACTORY(BlockMesh); BlockMesh::BlockMesh(const ResourceTypeInfo *pResourceTypeInfo /*= &s_TypeInfo*/) : Resource(pResourceTypeInfo), m_pPalette(NULL), m_scale(0.0f), m_useAmbientOcclusion(false), m_nLODLevels(0), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_pLODLevels(NULL), m_pCollisionShape(NULL), m_pRenderData(NULL), m_vertexFactoryFlags(0), m_bGPUResourcesCreated(false) { } BlockMesh::~BlockMesh() { ReleaseGPUResources(); if (m_pPalette != NULL) m_pPalette->Release(); if (m_pCollisionShape != NULL) m_pCollisionShape->Release(); if (m_pRenderData != NULL) { for (uint32 i = 0; i < m_nLODLevels; i++) { delete[] m_pRenderData[i].pVertices; Y_free((void *)m_pRenderData[i].pIndices); delete[] m_pRenderData[i].pBatches; } delete[] m_pRenderData; } delete[] m_pLODLevels; } bool BlockMesh::Load(const char *resourceName, ByteStream *pStream) { // set name m_strName = resourceName; BinaryReader binaryReader(pStream); if (binaryReader.ReadUInt32() != DF_BLOCK_MESH_HEADER_MAGIC) { Log_ErrorPrintf("BlockMesh::Load: '%s': Invalid file magic", resourceName); return false; } PathString paletteName; binaryReader.ReadSizePrefixedString(paletteName); if ((m_pPalette = g_pResourceManager->GetBlockPalette(paletteName)) == NULL) { Log_ErrorPrintf("BlockMesh::Load: '%s': Could not load palette '%s'", resourceName, paletteName.GetCharArray()); return false; } m_scale = binaryReader.ReadFloat(); m_useAmbientOcclusion = binaryReader.ReadBool(); m_nLODLevels = binaryReader.ReadUInt32(); if (m_nLODLevels > MAX_LOD_LEVELS) { Log_ErrorPrintf("BlockMesh::Load: '%s': Invalid LOD level count", resourceName); return false; } // bounds binaryReader >> m_boundingBox; binaryReader >> m_boundingSphere; // lod levels m_pLODLevels = new LODLevel[m_nLODLevels]; for (uint32 i = 0; i < m_nLODLevels; i++) { float levelScale; float3 levelBoundingBoxMinBounds; float3 levelBoundingBoxMaxBounds; float3 levelBoundingSphereCenter; float levelBoundingSphereRadius; binaryReader >> levelScale; binaryReader >> levelBoundingBoxMinBounds; binaryReader >> levelBoundingBoxMaxBounds; binaryReader >> levelBoundingSphereCenter; binaryReader >> levelBoundingSphereRadius; int3 levelMinCoordinates; int3 levelMaxCoordinates; uint32 levelWidth; uint32 levelLength; uint32 levelHeight; binaryReader >> levelMinCoordinates; binaryReader >> levelMaxCoordinates; binaryReader >> levelWidth; binaryReader >> levelLength; binaryReader >> levelHeight; // some sanity checks if (levelMinCoordinates.AnyGreater(levelMaxCoordinates) || levelMaxCoordinates.AnyLess(levelMinCoordinates)) { Log_ErrorPrintf("BlockMesh::Load: '%s': Corrupted data", resourceName); return false; } // init the volume LODLevel &lodLevel = m_pLODLevels[i]; lodLevel.Volume.SetPalette(m_pPalette); lodLevel.Volume.SetScale(levelScale); lodLevel.Volume.Resize(levelMinCoordinates, levelMaxCoordinates); if (lodLevel.Volume.GetWidth() != levelWidth || lodLevel.Volume.GetLength() != levelLength || lodLevel.Volume.GetHeight() != levelHeight) { Log_ErrorPrintf("BlockMesh::Load: '%s': Corrupted data", resourceName); return false; } // set other parameters to level lodLevel.BoundingBox.SetBounds(levelBoundingBoxMinBounds, levelBoundingBoxMaxBounds); lodLevel.BoundingSphere.SetCenterAndRadius(levelBoundingSphereCenter, levelBoundingSphereRadius); // fill the volume uint32 nBlocks = levelWidth * levelLength * levelHeight; binaryReader.ReadBytes(lodLevel.Volume.GetData(), sizeof(BlockVolumeBlockType) * nBlocks); } // collision shape uint32 collisionShapeType = binaryReader.ReadUInt32(); if (collisionShapeType != Physics::COLLISION_SHAPE_TYPE_NONE) { if (collisionShapeType == Physics::COLLISION_SHAPE_TYPE_BLOCK_MESH) { // create block collision shape m_pCollisionShape = new BlockMeshCollisionShape(this); } else { // load the collision shape uint32 collisionShapeDataSize = binaryReader.ReadUInt32(); DebugAssert(collisionShapeDataSize > 0); // create collision shape data if ((m_pCollisionShape = Physics::CollisionShape::CreateFromStream(pStream, collisionShapeDataSize)) == nullptr) { Log_ErrorPrintf("BlockMesh::Load: '%s': Could not create collision shape", resourceName); return false; } } } if (g_pRenderer != NULL && !CreateRenderData()) { Log_ErrorPrintf("BlockMesh::Load: '%s': Could not create render data", resourceName); return false; } if (pStream->InErrorState()) { Log_DevPrintf("Stream in error state."); return false; } // create on gpu if (!CreateGPUResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool BlockMesh::CreateRenderData() { DebugAssert(m_pRenderData == NULL); m_pRenderData = new RenderData[m_nLODLevels]; // keep pointers to null for (uint32 i = 0; i < m_nLODLevels; i++) { RenderData &renderData = m_pRenderData[i]; renderData.pVertices = NULL; renderData.pIndices = NULL; renderData.pBatches = NULL; renderData.pIndexBuffer = NULL; } // build data for (uint32 i = 0; i < m_nLODLevels; i++) { const LODLevel &lodLevel = m_pLODLevels[i]; RenderData &renderData = m_pRenderData[i]; // setup builder BlockMeshBuilder builder; builder.SetPalette(m_pPalette); builder.SetFromVolume(&lodLevel.Volume); // build it builder.GenerateMesh(); // copy results out to render data renderData.VertexCount = builder.GetOutputVertexCount(); renderData.IndexCount = builder.GetOutputTriangleCount() * 3; renderData.IndexFormat = (renderData.VertexCount <= 0xFFFF) ? GPU_INDEX_FORMAT_UINT16 : GPU_INDEX_FORMAT_UINT32; renderData.BatchCount = builder.GetOutputBatchCount(); // skip if no tris if (renderData.BatchCount > 0) { // verts BlockMeshBuilder::Vertex *pVertices = new BlockMeshBuilder::Vertex[renderData.VertexCount]; Y_memcpy(pVertices, builder.GetOutputVertices().GetBasePointer(), sizeof(BlockMeshBuilder::Vertex) * renderData.VertexCount); renderData.pVertices = pVertices; // tris if (renderData.IndexFormat == GPU_INDEX_FORMAT_UINT16) { uint16 *pIndices = Y_mallocT<uint16>(renderData.IndexCount); for (uint32 j = 0, o = 0; j < builder.GetOutputTriangleCount(); j++) { const BlockMeshBuilder::Triangle &tri = builder.GetOutputTriangles()[j]; pIndices[o++] = (uint16)tri.Indices[0]; pIndices[o++] = (uint16)tri.Indices[1]; pIndices[o++] = (uint16)tri.Indices[2]; } renderData.pIndices = pIndices; } else { uint32 *pIndices = Y_mallocT<uint32>(renderData.IndexCount); for (uint32 j = 0, o = 0; j < renderData.IndexCount; j++) { const BlockMeshBuilder::Triangle &tri = builder.GetOutputTriangles()[j]; pIndices[o++] = tri.Indices[0]; pIndices[o++] = tri.Indices[1]; pIndices[o++] = tri.Indices[2]; } renderData.pIndices = pIndices; } // batches Batch *pBatches = new Batch[renderData.BatchCount]; for (uint32 j = 0; j < renderData.BatchCount; j++) { const BlockMeshBuilder::Batch &sourceBatch = builder.GetOutputBatches()[j]; Batch &destBatch = pBatches[j]; destBatch.MaterialIndex = sourceBatch.MaterialIndex; destBatch.StartIndex = sourceBatch.StartIndex; destBatch.IndexCount = sourceBatch.NumIndices; } renderData.pBatches = pBatches; } } // figure out flags m_vertexFactoryFlags = BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD | BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS | BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX; if (g_pRenderer->GetCapabilities().SupportsTextureArrays) m_vertexFactoryFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY; else m_vertexFactoryFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS; return true; } bool BlockMesh::CreateGPUResources() const { if (m_bGPUResourcesCreated) return true; DebugAssert(m_pRenderData != NULL); for (uint32 i = 0; i < m_nLODLevels; i++) { RenderData &renderData = m_pRenderData[i]; if (renderData.VertexBuffers.GetBuffer(0) == NULL) { if (!BlockMeshVertexFactory::CreateVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_vertexFactoryFlags, renderData.pVertices, renderData.VertexCount, &renderData.VertexBuffers)) return false; } if (renderData.pIndexBuffer == NULL) { GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, renderData.IndexCount * ((renderData.IndexFormat == GPU_INDEX_FORMAT_UINT16) ? sizeof(uint16) : sizeof(uint32))); if ((renderData.pIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, renderData.pIndices)) == NULL) return false; } } m_bGPUResourcesCreated = true; return true; } void BlockMesh::ReleaseGPUResources() const { if (m_pRenderData != NULL) { for (uint32 i = 0; i < m_nLODLevels; i++) { RenderData &renderData = m_pRenderData[i]; renderData.VertexBuffers.Clear(); SAFE_RELEASE(renderData.pIndexBuffer); } } m_bGPUResourcesCreated = false; } bool BlockMesh::CheckGPUResources() const { if (!m_bGPUResourcesCreated && !CreateGPUResources()) return false; return true; } <file_sep>/Engine/Source/D3D12Renderer/D3D12LinearHeaps.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12LinearHeaps.h" #include "D3D12Renderer/D3D12Helpers.h" Log_SetChannel(D3D12RenderBackend); D3D12LinearBufferHeap::D3D12LinearBufferHeap(ID3D12Resource *pResource, byte *pMappedPointer, uint32 size) : m_gpuAddress(pResource->GetGPUVirtualAddress()) , m_pResource(pResource) , m_pMappedPointer(pMappedPointer) , m_size(size) , m_position(0) , m_resetPosition(0) { } D3D12LinearBufferHeap *D3D12LinearBufferHeap::Create(ID3D12Device *pDevice, uint32 size) { HRESULT hResult; ID3D12Resource *pResource; // create resource D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; hResult = pDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, __uuidof(ID3D12Resource), (void **)&pResource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12ScratchBuffer::Create: CreateCommittedResource failed with hResult %08X", hResult); return nullptr; } byte *pMappedPointer = nullptr; D3D12_RANGE readRange = { 0, 0 }; hResult = pResource->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), (void **)&pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Map failed with hResult %08X", hResult); return false; } return new D3D12LinearBufferHeap(pResource, pMappedPointer, size); } D3D12LinearBufferHeap::~D3D12LinearBufferHeap() { DebugAssert(m_pMappedPointer == nullptr); m_pResource->Release(); } void *D3D12LinearBufferHeap::GetPointer(uint32 offset) const { DebugAssert(offset < m_size); return m_pMappedPointer + offset; } D3D12_GPU_VIRTUAL_ADDRESS D3D12LinearBufferHeap::GetGPUAddress(uint32 offset) const { DebugAssert(offset < m_size); return m_gpuAddress + offset; } bool D3D12LinearBufferHeap::Allocate(uint32 size, uint32 *pOutOffset) { DebugAssert(m_pMappedPointer != nullptr); if ((m_position + size) > m_size) return false; *pOutOffset = m_position; m_position += size; return true; } bool D3D12LinearBufferHeap::AllocateAligned(uint32 size, uint32 alignment, uint32 *pOutOffset) { if (alignment == 0) return Allocate(size, pOutOffset); uint32 alignedStart = (m_position > 0) ? ALIGNED_SIZE(m_position, alignment) : 0; if ((alignedStart + size) > m_size) return false; *pOutOffset = alignedStart; m_position = alignedStart + size; return true; } bool D3D12LinearBufferHeap::Reset(bool resetPosition) { // DebugAssert(m_pMappedPointer == nullptr); if (resetPosition) m_position = 0; m_resetPosition = m_position; // D3D12_RANGE readRange = { 0, 0 }; // HRESULT hResult = m_pResource->Map(0, nullptr/*&readRange*/, (void **)&m_pMappedPointer); // if (FAILED(hResult)) // { // Log_ErrorPrintf("Map failed with hResult %08X", hResult); // return false; // } return true; } void D3D12LinearBufferHeap::Commit() { // DebugAssert(m_pMappedPointer != nullptr); // // D3D12_RANGE writtenRange = { m_resetPosition, m_position }; // m_pResource->Unmap(0, nullptr/*&writtenRange*/); // m_pMappedPointer = nullptr; } D3D12LinearDescriptorHeap::D3D12LinearDescriptorHeap(ID3D12DescriptorHeap *pHeap, uint32 count, uint32 incrementSize) : m_pD3DHeap(pHeap) , m_cpuHandleStart(pHeap->GetCPUDescriptorHandleForHeapStart()) , m_gpuHandleStart(pHeap->GetGPUDescriptorHandleForHeapStart()) , m_size(count) , m_position(0) , m_incrementSize(incrementSize) { } D3D12LinearDescriptorHeap *D3D12LinearDescriptorHeap::Create(ID3D12Device *pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 count) { ID3D12DescriptorHeap *pDescriptorHeap; D3D12_DESCRIPTOR_HEAP_DESC descriptorHeapDesc = { type, count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0 }; HRESULT hResult = pDevice->CreateDescriptorHeap(&descriptorHeapDesc, IID_PPV_ARGS(&pDescriptorHeap)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12ScratchDescriptorHeap::Create: CreateDescriptorHeap failed with hResult %08X", hResult); return nullptr; } D3D12Helpers::SetD3D12ObjectName(pDescriptorHeap, "scratch descriptor heap"); return new D3D12LinearDescriptorHeap(pDescriptorHeap, count, pDevice->GetDescriptorHandleIncrementSize(type)); } D3D12LinearDescriptorHeap::~D3D12LinearDescriptorHeap() { m_pD3DHeap->Release(); } bool D3D12LinearDescriptorHeap::Allocate(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle) { DebugAssert(count > 0); if ((m_position + count) > m_size) return false; pOutCPUHandle->ptr = m_cpuHandleStart.ptr + m_incrementSize * m_position; pOutGPUHandle->ptr = m_gpuHandleStart.ptr + m_incrementSize * m_position; m_position += count; return true; } void D3D12LinearDescriptorHeap::Reset() { m_position = 0; } <file_sep>/Engine/Source/Engine/Physics/CollisionObject.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/CollisionObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/BulletHeaders.h" //Log_SetChannel(CollisionObject); namespace Physics { CollisionObject::CollisionObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform) : PhysicsProxy(entityID), m_pCollisionShape(nullptr), m_pOriginalCollisionShape(nullptr), m_transform(transform) { m_pOriginalCollisionShape = pCollisionShape; m_pOriginalCollisionShape->AddRef(); if (m_transform.GetScale() != float3::One) { m_pCollisionShape = m_pOriginalCollisionShape->CreateScaledShape(m_transform.GetScale()); } else { m_pCollisionShape = m_pOriginalCollisionShape; m_pCollisionShape->AddRef(); } } CollisionObject::~CollisionObject() { m_pCollisionShape->Release(); m_pOriginalCollisionShape->Release(); } void CollisionObject::SetCollisionShape(const CollisionShape *pCollisionShape) { if (pCollisionShape == m_pOriginalCollisionShape) return; // this has to be kept in order to maintain references for bullet const CollisionShape *pOldOriginalCollisionShape = m_pOriginalCollisionShape; const CollisionShape *pOldCollisionShape = m_pCollisionShape; m_pOriginalCollisionShape = pCollisionShape; m_pOriginalCollisionShape->AddRef(); if (m_transform.GetScale() != float3::One) { m_pCollisionShape = pCollisionShape->CreateScaledShape(m_transform.GetScale()); } else { m_pCollisionShape = pCollisionShape; m_pCollisionShape->AddRef(); } OnCollisionShapeChanged(); // cleanup references pOldCollisionShape->Release(); pOldOriginalCollisionShape->Release(); } void CollisionObject::SetTransform(const Transform &transform) { if (transform == m_transform) return; if (transform.GetScale() != m_transform.GetScale()) { // scaling from != 1.0 to 1.0 if (transform.GetScale() == float3::One) { if (m_transform.GetScale() != float3::One) { DebugAssert(m_pCollisionShape != m_pOriginalCollisionShape); // save current shape const CollisionShape *pDeleteCollisionShape = m_pCollisionShape; // set original shape m_pCollisionShape = m_pOriginalCollisionShape; m_pCollisionShape->AddRef(); OnCollisionShapeChanged(); // delete old shape pDeleteCollisionShape->Release(); } } else { // create new scaled collision shape CollisionShape *pNewScaledShape = m_pOriginalCollisionShape->CreateScaledShape(transform.GetScale()); const CollisionShape *pDeleteCollisionShape = m_pCollisionShape; // set new shape m_pCollisionShape = pNewScaledShape; OnCollisionShapeChanged(); // delete old shape pDeleteCollisionShape->Release(); } } m_transform = transform; OnTransformChanged(); } void CollisionObject::UpdateBoundingBox() { btCollisionObject *bulletCollisionObject = GetBulletCollisionObject(); // if in world, trigger an aabb update for this object if (m_pPhysicsWorld != nullptr) m_pPhysicsWorld->GetBulletWorld()->updateSingleAabb(bulletCollisionObject); // fix up our copy of the aabb btVector3 aabbMin, aabbMax; m_pCollisionShape->GetBulletShape()->getAabb(bulletCollisionObject->getWorldTransform(), aabbMin, aabbMax); m_boundingBox.SetBounds(BulletVector3ToFloat3(aabbMin), BulletVector3ToFloat3(aabbMax)); } const float CollisionObject::GetFriction() const { return GetBulletCollisionObject()->getFriction(); } const float CollisionObject::GetRollingFriction() const { return GetBulletCollisionObject()->getRollingFriction(); } const float3 CollisionObject::GetAnisotropicFriction() const { return BulletVector3ToFloat3(GetBulletCollisionObject()->getAnisotropicFriction()); } const float CollisionObject::GetRestitution() const { return GetBulletCollisionObject()->getRestitution(); } void CollisionObject::SetFriction(float friction) { GetBulletCollisionObject()->setFriction(friction); } void CollisionObject::SetRollingFriction(float rollingFriction) { GetBulletCollisionObject()->setRollingFriction(rollingFriction); } void CollisionObject::SetAnisotropicFriction(const float3 &anisotropicFriction) { GetBulletCollisionObject()->setAnisotropicFriction(Float3ToBulletVector(anisotropicFriction)); } void CollisionObject::SetRestitution(float restitution) { GetBulletCollisionObject()->setRestitution(restitution); } void CollisionObject::ConvertWorldTransformToBulletTransform(const Transform &worldTransform, btTransform *pBulletTransform) { // add shape transform pBulletTransform->setOrigin(Float3ToBulletVector(worldTransform.GetPosition())); pBulletTransform->setRotation(QuaternionToBulletQuaternion(worldTransform.GetRotation())); m_pCollisionShape->ApplyShapeTransform(*pBulletTransform); } void CollisionObject::ConvertBulletTransformToWorldTransform(const btTransform &bulletTransform, Transform *pWorldTransform) { // remove shape transform btTransform worldTransform(bulletTransform); m_pCollisionShape->ApplyInverseShapeTransform(worldTransform); // convert back pWorldTransform->SetPosition(BulletVector3ToFloat3(worldTransform.getOrigin())); pWorldTransform->SetRotation(BulletQuaternionToQuaternion(worldTransform.getRotation())); } } // namespace Physics <file_sep>/Engine/Source/Engine/BlockMeshVolume.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockMeshVolume.h" BlockMeshVolume::BlockMeshVolume() : m_pPalette(NULL), m_scale(1.0f), m_minCoordinates(int3::Zero), m_maxCoordinates(int3::Zero), m_width(0), m_length(0), m_height(0), m_pData(NULL) { } BlockMeshVolume::BlockMeshVolume(const BlockPalette *pPalette, float scale, const int3 &minCoordinates, const int3 &maxCoordinates) { DebugAssert(scale > 0.0f); DebugAssert(!minCoordinates.AnyGreater(maxCoordinates)); int3 range(maxCoordinates - minCoordinates); DebugAssert(!range.AnyLess(int3::Zero)); if ((m_pPalette = pPalette) != NULL) m_pPalette->AddRef(); m_scale = scale; m_minCoordinates = minCoordinates; m_maxCoordinates = maxCoordinates; m_width = (uint32)range.x + 1; m_length = (uint32)range.y + 1; m_height = (uint32)range.z + 1; uint32 nBlocks = m_width * m_length * m_height; m_pData = new BlockVolumeBlockType[nBlocks]; Y_memzero(m_pData, sizeof(BlockVolumeBlockType) * nBlocks); } BlockMeshVolume::BlockMeshVolume(const BlockMeshVolume &copy) : m_scale(copy.m_scale), m_minCoordinates(copy.m_minCoordinates), m_maxCoordinates(copy.m_maxCoordinates), m_width(copy.m_width), m_length(copy.m_length), m_height(copy.m_height) { uint32 nBlocks = m_width * m_length * m_height; m_pData = new BlockVolumeBlockType[nBlocks]; Y_memcpy(m_pData, copy.m_pData, sizeof(BlockVolumeBlockType) * nBlocks); } BlockMeshVolume::~BlockMeshVolume() { delete[] m_pData; } AABox BlockMeshVolume::CalculateBoundingBox() const { float3 minBounds(float3((float)m_minCoordinates.x, (float)m_minCoordinates.y, (float)m_minCoordinates.z) * m_scale); float3 maxBounds((float3((float)m_maxCoordinates.x, (float)m_maxCoordinates.y, (float)m_maxCoordinates.z) + 1.0f) * m_scale); return AABox(minBounds, maxBounds); } AABox BlockMeshVolume::CalculateActiveBoundingBox() const { int3 minActiveCoordinates; int3 maxActiveCoordinates; float3 minBounds(float3::Zero); float3 maxBounds(float3::Zero); if (GetActiveCoordinatesRange(&minActiveCoordinates, &maxActiveCoordinates)) { minBounds.x = (float)minActiveCoordinates.x * m_scale; minBounds.y = (float)minActiveCoordinates.y * m_scale; minBounds.z = (float)minActiveCoordinates.z * m_scale; maxBounds.x = (float)(maxActiveCoordinates.x + 1) * m_scale; maxBounds.y = (float)(maxActiveCoordinates.y + 1) * m_scale; maxBounds.z = (float)(maxActiveCoordinates.z + 1) * m_scale; } return AABox(minBounds, maxBounds); } void BlockMeshVolume::SetPalette(const BlockPalette *pPalette) { if (m_pPalette == pPalette) return; if (m_pPalette != NULL) m_pPalette->Release(); if ((m_pPalette = pPalette) != NULL) m_pPalette->AddRef(); } BlockVolumeBlockType BlockMeshVolume::GetBlock(int32 x, int32 y, int32 z) const { DebugAssert(x >= m_minCoordinates.x && y >= m_minCoordinates.y && z >= m_minCoordinates.z); DebugAssert(x <= m_maxCoordinates.x && y <= m_maxCoordinates.y && z <= m_maxCoordinates.z); uint32 offsetX = (uint32)(x - m_minCoordinates.x); uint32 offsetY = (uint32)(y - m_minCoordinates.y); uint32 offsetZ = (uint32)(z - m_minCoordinates.z); DebugAssert(offsetX < m_width && offsetY < m_length && offsetZ < m_height); return m_pData[offsetZ * (m_width * m_length) + offsetY * m_width + offsetX]; } void BlockMeshVolume::SetBlock(int32 x, int32 y, int32 z, BlockVolumeBlockType value) { DebugAssert(x >= m_minCoordinates.x && y >= m_minCoordinates.y && z >= m_minCoordinates.z); DebugAssert(x <= m_maxCoordinates.x && y <= m_maxCoordinates.y && z <= m_maxCoordinates.z); uint32 offsetX = (uint32)(x - m_minCoordinates.x); uint32 offsetY = (uint32)(y - m_minCoordinates.y); uint32 offsetZ = (uint32)(z - m_minCoordinates.z); DebugAssert(offsetX < m_width && offsetY < m_length && offsetZ < m_height); m_pData[offsetZ * (m_width * m_length) + offsetY * m_width + offsetX] = value; } bool BlockMeshVolume::GetActiveCoordinatesRange(int3 *pMinActiveCoordinates, int3 *pMaxActiveCoordinates) const { Vector3i minActiveBlockPosition; Vector3i maxActiveBlockPosition; const BlockVolumeBlockType *pCurrentBlock = m_pData; bool first = true; for (uint32 z = 0; z < m_height; z++) { for (uint32 y = 0; y < m_length; y++) { for (uint32 x = 0; x < m_width; x++) { if (*(pCurrentBlock++) != 0) { int32 realX = (int32)x + m_minCoordinates.x; int32 realY = (int32)y + m_minCoordinates.y; int32 realZ = (int32)z + m_minCoordinates.z; Vector3i blockPos(realX, realY, realZ); if (first) { minActiveBlockPosition = blockPos; maxActiveBlockPosition = blockPos; first = false; } else { minActiveBlockPosition = minActiveBlockPosition.Min(blockPos); maxActiveBlockPosition = maxActiveBlockPosition.Max(blockPos); } } } } } if (first) return false; *pMinActiveCoordinates = minActiveBlockPosition; *pMaxActiveCoordinates = maxActiveBlockPosition; return true; /* bool hasBlocks = false; int3 minActiveCoordinates, maxActiveCoordinates; uint32 nBlocks = m_width * m_length * m_height; uint32 zStride = m_length * m_width; uint32 yStride = m_width; for (uint32 i = 0; i < nBlocks; i++) { if (m_pData[i] != 0) { // reverse the index to coordinates uint32 temp = i; uint32 lz = temp / zStride; temp %= zStride; uint32 ly = temp / yStride; temp %= yStride; uint32 lx = temp; int3 coords(int3((int32)lx, (int32)ly, (int32)lz) + m_minCoordinates); if (hasBlocks) { minActiveCoordinates = minActiveCoordinates.Min(coords); maxActiveCoordinates = maxActiveCoordinates.Max(coords); } else { minActiveCoordinates = coords; maxActiveCoordinates = coords; hasBlocks = true; } } } if (!hasBlocks) return false; *pMinActiveCoordinates = minActiveCoordinates; *pMaxActiveCoordinates = maxActiveCoordinates; return true;*/ } void BlockMeshVolume::Clear() { uint32 nBlocks = m_width * m_length * m_height; Y_memzero(m_pData, sizeof(BlockVolumeBlockType) * nBlocks); } void BlockMeshVolume::Resize(const int3 &newMinCoordinates, const int3 &newMaxCoordinates) { DebugAssert(!newMinCoordinates.AnyGreater(newMaxCoordinates)); int3 newCoordinateRange(newMaxCoordinates - newMinCoordinates); uint32 newWidth = (uint32)newCoordinateRange.x + 1; uint32 newLength = (uint32)newCoordinateRange.y + 1; uint32 newHeight = (uint32)newCoordinateRange.z + 1; uint32 nNewBlocks = newWidth * newLength * newHeight; uint8 *pNewData = new uint8[nNewBlocks]; Y_memzero(pNewData, sizeof(uint8) * nNewBlocks); if (m_pData != NULL) { // load old data int32 oldMinX = m_minCoordinates.x; int32 oldMinY = m_minCoordinates.y; int32 oldMinZ = m_minCoordinates.z; int32 oldMaxX = m_maxCoordinates.x; int32 oldMaxY = m_maxCoordinates.y; int32 oldMaxZ = m_maxCoordinates.z; const uint8 *pOldDataPtr = m_pData; // map the old block data across int32 x, y, z; for (z = oldMinZ; z <= oldMaxZ; z++) { for (y = oldMinY; y <= oldMaxY; y++) { for (x = oldMinX; x <= oldMaxX; x++) { uint8 blockValue = *(pOldDataPtr++); if (blockValue != 0) { int3 blockPosition(x, y, z); if (blockPosition.AnyLess(newMinCoordinates) || blockPosition.AnyGreater(newMaxCoordinates)) continue; Vector3i blockArrayIndices = blockPosition - newMinCoordinates; uint32 newArrayIndex = (uint32)blockArrayIndices.z * (newWidth * newLength) + (uint32)blockArrayIndices.y * (newWidth) + (uint32)blockArrayIndices.x; DebugAssert(newArrayIndex < nNewBlocks); pNewData[newArrayIndex] = blockValue; } } } } delete[] m_pData; } // store new values m_minCoordinates = newMinCoordinates; m_maxCoordinates = newMaxCoordinates; m_width = newWidth; m_length = newLength; m_height = newHeight; m_pData = pNewData; } void BlockMeshVolume::Center() { int3 activeCoordinateMin, activeCoordinateMax; if (!GetActiveCoordinatesRange(&activeCoordinateMin, &activeCoordinateMax)) return; // get the current 'mid point' int3 currentMidPoint = activeCoordinateMin + ((activeCoordinateMax - activeCoordinateMin + int3::One) / 2); // work out the difference we have to move them int3 moveDelta = int3::Zero - currentMidPoint; if (moveDelta != int3::Zero) { // use copies here, since the dimensions will be resized MoveBlocks(int3(m_minCoordinates), int3(m_maxCoordinates), moveDelta); } } void BlockMeshVolume::Shrink() { // simply resize to the min/max range int3 newMinCoordinates, newMaxCoordinates; if (GetActiveCoordinatesRange(&newMinCoordinates, &newMaxCoordinates)) Resize(newMinCoordinates, newMaxCoordinates); else Resize(int3::Zero, int3::Zero); } void BlockMeshVolume::MoveBlock(const int3 &blockCoordinates, const int3 &moveDelta) { BlockVolumeBlockType oldValue = GetBlock(blockCoordinates); SetBlock(blockCoordinates + moveDelta, oldValue); SetBlock(blockCoordinates, 0); } void BlockMeshVolume::MoveBlocks(const int3 &selectionMin, const int3 &selectionMax, const int3 &moveDelta) { int3 moveSelectionMin = m_minCoordinates.Max(selectionMin); int3 moveSelectionMax = m_maxCoordinates.Min(selectionMax); int32 x, y, z; // take a copy of the mesh int3 oldMinCoordinates = m_minCoordinates; int3 oldMaxCoordinates = m_maxCoordinates; uint32 oldZStride = m_length * m_width; uint32 oldYStride = m_width; uint32 nBlocks = m_width * m_length * m_height; BlockVolumeBlockType *pMeshCopy = new BlockVolumeBlockType[nBlocks]; Y_memcpy(pMeshCopy, m_pData, sizeof(uint8) * nBlocks); // make sure we can fit int3 newMinCoordinates = oldMinCoordinates; int3 newMaxCoordinates = oldMaxCoordinates; (moveDelta.x < 0) ? newMinCoordinates.x += moveDelta.x : newMaxCoordinates.x += moveDelta.x; (moveDelta.y < 0) ? newMinCoordinates.y += moveDelta.y : newMaxCoordinates.y += moveDelta.y; (moveDelta.z < 0) ? newMinCoordinates.z += moveDelta.z : newMaxCoordinates.z += moveDelta.z; //Resize(newMinCoordinates, newMaxCoordinates); // pass 1: nuke the source blocks for (z = moveSelectionMin.z; z <= moveSelectionMax.z; z++) { for (y = moveSelectionMin.y; y <= moveSelectionMax.y; y++) { for (x = moveSelectionMin.x; x <= moveSelectionMax.x; x++) { SetBlock(x, y, z, 0); } } } // pass 2: set the blocks from the copy for (z = moveSelectionMin.z; z <= moveSelectionMax.z; z++) { for (y = moveSelectionMin.y; y <= moveSelectionMax.y; y++) { for (x = moveSelectionMin.x; x <= moveSelectionMax.x; x++) { int3 coords(x, y, z); int3 arrayIndices = coords - oldMinCoordinates; DebugAssert(!arrayIndices.AnyLess(Vector3i::Zero)); uint32 arrayIndex = (uint32)arrayIndices.z * oldZStride + (uint32)arrayIndices.y * oldYStride + (uint32)arrayIndices.x; DebugAssert(arrayIndex < nBlocks); BlockVolumeBlockType value = pMeshCopy[arrayIndex]; SetBlock(coords + moveDelta, value); } } } delete[] pMeshCopy; } bool BlockMeshVolume::RayCastTime(const Ray &ray, int3 *pIntersectingBlock, float *pIntersectionTime, bool exitAtFirstIntersection /* = false */) const { //Vector3 rayStartPosition = ray.sp / scale - mincoords; int32 minCoordsX = m_minCoordinates.x; int32 minCoordsY = m_minCoordinates.y; int32 minCoordsZ = m_minCoordinates.z; SIMDVector3f vec_scale(m_scale, m_scale, m_scale); SIMDVector3f vec_one_mul_scale(vec_scale); int3 bestBlock; float bestTime = Y_FLT_INFINITE; const BlockVolumeBlockType *pCurrentBlock = m_pData; for (uint32 z = 0; z < m_height; z++) { for (uint32 y = 0; y < m_length; y++) { for (uint32 x = 0; x < m_width; x++) { BlockVolumeBlockType blockType = *(pCurrentBlock++); if (blockType != 0) { int32 realX = (int32)x + minCoordsX; int32 realY = (int32)y + minCoordsY; int32 realZ = (int32)z + minCoordsZ; SIMDVector3f minBlockBounds(SIMDVector3f((float)realX, (float)realY, (float)realZ) * vec_scale); SIMDVector3f maxBlockBounds(minBlockBounds + vec_one_mul_scale); float time = ray.AABoxIntersectionTime(minBlockBounds, maxBlockBounds); if (time < bestTime) { bestBlock.Set(realX, realY, realZ); bestTime = time; if (exitAtFirstIntersection) { *pIntersectingBlock = bestBlock; *pIntersectionTime = time; return true; } } } } } } if (bestTime != Y_FLT_INFINITE) { *pIntersectingBlock = bestBlock; *pIntersectionTime = bestTime; return true; } return false; } bool BlockMeshVolume::RayCastTimeFace(const Ray &ray, int3 *pIntersectingBlock, float *pIntersectionTime, CUBE_FACE *pIntersectingFace, bool exitAtFirstIntersection /*= false*/) const { int32 minCoordsX = m_minCoordinates.x; int32 minCoordsY = m_minCoordinates.y; int32 minCoordsZ = m_minCoordinates.z; SIMDVector3f vec_scale(m_scale, m_scale, m_scale); int3 bestBlock(int3::Zero); float bestTime = Y_FLT_INFINITE; CUBE_FACE bestFace = CUBE_FACE_COUNT; const BlockVolumeBlockType *pCurrentBlock = m_pData; for (uint32 z = 0; z < m_height; z++) { for (uint32 y = 0; y < m_length; y++) { for (uint32 x = 0; x < m_width; x++) { BlockVolumeBlockType blockType = *(pCurrentBlock++); if (blockType != 0) { int32 realX = (int32)x + minCoordsX; int32 realY = (int32)y + minCoordsY; int32 realZ = (int32)z + minCoordsZ; SIMDVector3f minBlockBounds(SIMDVector3f((float)realX, (float)realY, (float)realZ) * vec_scale); SIMDVector3f maxBlockBounds(minBlockBounds + vec_scale); float time; CUBE_FACE face; if (ray.AABoxIntersectionTimeFace(minBlockBounds, maxBlockBounds, &time, &face) && time < bestTime) { bestBlock.Set(realX, realY, realZ); bestTime = time; bestFace = face; if (exitAtFirstIntersection) { *pIntersectingBlock = bestBlock; *pIntersectionTime = time; *pIntersectingFace = face; return true; } } } } } } if (bestTime != Y_FLT_INFINITE) { *pIntersectingBlock = bestBlock; *pIntersectionTime = bestTime; *pIntersectingFace = bestFace; return true; } return false; } BlockMeshVolume & BlockMeshVolume::operator=(const BlockMeshVolume &copy) { uint32 nBlocks = copy.m_width * copy.m_length * copy.m_height; if (m_width != copy.m_width || m_length != copy.m_length || m_height != copy.m_height) { m_width = copy.m_width; m_length = copy.m_length; m_height = copy.m_height; delete[] m_pData; m_pData = new BlockVolumeBlockType[nBlocks]; } m_scale = copy.m_scale; m_minCoordinates = copy.m_minCoordinates; m_maxCoordinates = copy.m_maxCoordinates; Y_memcpy(m_pData, copy.m_pData, sizeof(BlockVolumeBlockType) * nBlocks); return *this; } <file_sep>/Engine/Source/Engine/InputManager.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/InputManager.h" #include "Engine/SDLHeaders.h" Log_SetChannel(Input); static InputManager s_inputManager; InputManager *g_pInputManager = &s_inputManager; InputManager::InputManager() { m_eventBlockerCount = 0; } InputManager::~InputManager() { } bool InputManager::Startup() { Log_InfoPrint("InputManager::Startup"); Log_DevPrintf("SDL_InitSubSystem(SDL_INIT_JOYSTICK)..."); if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) Log_ErrorPrintf("SDL_InitSubSystem(SDL_INIT_JOYSTICK) failed: %s, joysticks will not be available.", SDL_GetError()); else Log_DevPrintf(" SDL_NumJoysticks() = %i", SDL_NumJoysticks()); Log_DevPrintf("SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)..."); if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0) Log_ErrorPrintf("SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) failed: %s, game controllers will not be available.", SDL_GetError()); Log_DevPrintf("SDL_InitSubSystem(SDL_INIT_HAPTIC)..."); if (SDL_InitSubSystem(SDL_INIT_HAPTIC) < 0) Log_ErrorPrintf("SDL_InitSubSystem(SDL_INIT_HAPTIC) failed: %s, force feedback will not be available.", SDL_GetError()); return true; } void InputManager::Shutdown() { Log_InfoPrint("InputManager::Shutdown"); for (BindSetTable::Iterator itr = m_bindSets.Begin(); !itr.AtEnd(); itr.Forward()) delete itr->Value; m_pActiveBindSet = nullptr; for (EventHashTable::Iterator itr = m_events.Begin(); !itr.AtEnd(); itr.Forward()) delete itr->Value; m_events.Clear(); } // bool InputManager::OpenJoysticks() // { // int nJoysticks = SDL_NumJoysticks(); // Log_DevPrintf("SDL_NumJoysticks() = %i", nJoysticks); // for (int i = 0; i < nJoysticks; i++) // { // if (SDL_IsGameController(i)) // { // const char *gameControllerName = SDL_GameControllerNameForIndex(i); // Log_DevPrintf(" Opening SDL game controller %i (%s)...", i, gameControllerName); // // SDL_GameController *pGameController = SDL_GameControllerOpen(i); // if (pGameController == nullptr) // { // Log_ErrorPrintf(" SDL_GameControllerOpen failed: %s", SDL_GetError()); // CloseJoysticks(); // return false; // } // // SDL_bool controllerAttached = SDL_GameControllerGetAttached(pGameController); // if (!controllerAttached) // Log_WarningPrintf(" Game controller %i is not attached.", i); // // m_gameControllers.Add(pGameController); // } // else // { // const char *joystickName = SDL_JoystickNameForIndex(i); // Log_DevPrintf(" Opening SDL joystick %i (%s)...", i, joystickName); // // SDL_Joystick *pJoystick = SDL_JoystickOpen(i); // if (pJoystick == nullptr) // { // Log_ErrorPrintf(" SDL_JoystickOpen failed: %s", SDL_GetError()); // CloseJoysticks(); // return false; // } // // m_joysticks.Add(pJoystick); // } // } // // return true; // } void InputManager::CloseJoysticks() { for (uint32 i = 0; i < m_controllers.GetSize(); i++) SDL_GameControllerClose(m_controllers[i].pSDLGameController); m_controllers.Clear(); for (uint32 i = 0; i < m_joysticks.GetSize(); i++) SDL_JoystickClose(m_joysticks[i].pSDLJoystick); m_joysticks.Clear(); } const InputManager::ActionEvent *InputManager::RegisterActionEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, ActionEvent::CallbackType *pCallback) { if (m_events.Find(eventName) != nullptr) { Log_ErrorPrintf("InputManager::RegisterActionEvent: Event '%s' already exists.", eventName); delete pCallback; return nullptr; } ActionEvent *pEvent = new ActionEvent(pOwnerPointer, eventName, displayName, pCallback); m_events.Insert(eventName, static_cast<BaseEvent *>(pEvent)); return pEvent; } const InputManager::BinaryStateEvent *InputManager::RegisterBinaryStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, BinaryStateEvent::CallbackType *pCallback) { if (m_events.Find(eventName) != nullptr) { Log_ErrorPrintf("InputManager::RegisterBinaryStateEvent: Event '%s' already exists.", eventName); delete pCallback; return nullptr; } BinaryStateEvent *pEvent = new BinaryStateEvent(pOwnerPointer, eventName, displayName, pCallback); m_events.Insert(eventName, static_cast<BaseEvent *>(pEvent)); return pEvent; } const InputManager::AxisStateEvent *InputManager::RegisterAxisStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, AxisStateEvent::CallbackType *pCallback) { if (m_events.Find(eventName) != nullptr) { Log_ErrorPrintf("InputManager::RegisterAxisStateEvent: Event '%s' already exists.", eventName); delete pCallback; return nullptr; } AxisStateEvent *pEvent = new AxisStateEvent(pOwnerPointer, eventName, displayName, pCallback); m_events.Insert(eventName, static_cast<BaseEvent *>(pEvent)); return pEvent; } const InputManager::NormalizedAxisStateEvent *InputManager::RegisterNormalizedAxisStateEvent(const void *pOwnerPointer, const char *eventName, const char *displayName, NormalizedAxisStateEvent::CallbackType *pCallback) { if (m_events.Find(eventName) != nullptr) { Log_ErrorPrintf("InputManager::RegisterNormalizedAxisStateEvent: Event '%s' already exists.", eventName); delete pCallback; return nullptr; } NormalizedAxisStateEvent *pEvent = new NormalizedAxisStateEvent(pOwnerPointer, eventName, displayName, pCallback); m_events.Insert(eventName, static_cast<BaseEvent *>(pEvent)); return pEvent; } const InputManager::BaseEvent *InputManager::LookupEventByName(const char *eventName) { EventHashTable::Member *pMember = m_events.Find(eventName); return (pMember != nullptr) ? pMember->Value : nullptr; } void InputManager::UnregisterEvent(const BaseEvent *pEvent) { EventHashTable::Member *pMember = m_events.Find(pEvent->Name); if (pMember != nullptr && pMember->Value == pEvent) { delete pMember->Value; m_events.Remove(pMember); } } bool InputManager::UnregisterEvent(const char *eventName) { EventHashTable::Member *pMember = m_events.Find(eventName); if (pMember != nullptr) { delete pMember->Value; m_events.Remove(pMember); return true; } return false; } void InputManager::UnregisterEventsWithOwner(const void *pOwnerPointer) { for (EventHashTable::Iterator itr = m_events.Begin(); !itr.AtEnd(); ) { EventHashTable::Member *pMember = &(*itr); itr.Forward(); if (pMember->Value->pOwnerPointer == pOwnerPointer) m_events.Remove(pMember); } } bool InputManager::BindKeyboardKey(const char *bindSetName, const char *keyName, const char *eventName, int32 activateDirection /* = 0 */) { BindSet *pBindSet = (bindSetName != nullptr) ? GetOrCreateBindSetByName(bindSetName) : &m_globalBindSet; DebugAssert(pBindSet != nullptr); // get sdl scancode SDL_Scancode scanCode = SDL_GetScancodeFromName(keyName); if (scanCode == SDL_SCANCODE_UNKNOWN) return false; // search for a bind that already exists for (uint32 i = 0; i < pBindSet->KeyboardBinds.GetSize(); i++) { // overwrite existing bind if ((SDL_Scancode)pBindSet->KeyboardBinds[i].SDLScanCode == scanCode) { // check for command executes if (Y_strnicmp(eventName, "exec ", 5) == 0) { // clip the exec part pBindSet->KeyboardBinds[i].CommandString = eventName + 5; } else { // write event name pBindSet->KeyboardBinds[i].ActivateDirection = activateDirection; pBindSet->KeyboardBinds[i].EventName = eventName; } return true; } } // create new bind KeyboardBind bind; bind.SDLScanCode = scanCode; // check for command executes if (Y_strnicmp(eventName, "exec ", 5) == 0) { // clip the exec part bind.CommandString = eventName + 5; } else { // write event name bind.EventName = eventName; bind.ActivateDirection = activateDirection; } // add to list pBindSet->KeyboardBinds.Add(bind); return true; } bool InputManager::BindMouseAxis(const char *bindSetName, uint32 axisIndex, const char *eventName, int32 bindDirection /* = 0 */) { BindSet *pBindSet = (bindSetName != nullptr) ? GetOrCreateBindSetByName(bindSetName) : &m_globalBindSet; DebugAssert(pBindSet != nullptr); // search for a bind that already exists for (uint32 i = 0; i < pBindSet->MouseAxisBinds.GetSize(); i++) { if (pBindSet->MouseAxisBinds[i].AxisIndex == axisIndex && pBindSet->MouseAxisBinds[i].BindDirection == bindDirection) { pBindSet->MouseAxisBinds[i].EventName = eventName; return true; } } // create new bind MouseAxisBind bind; bind.AxisIndex = axisIndex; bind.BindDirection = bindDirection; bind.EventName = eventName; pBindSet->MouseAxisBinds.Add(bind); return true; } bool InputManager::BindMouseButton(const char *bindSetName, uint32 buttonIndex, const char *eventName, int32 activateDirection /* = 0 */) { BindSet *pBindSet = (bindSetName != nullptr) ? GetOrCreateBindSetByName(bindSetName) : &m_globalBindSet; DebugAssert(pBindSet != nullptr); // search for a bind that already exists for (uint32 i = 0; i < pBindSet->MouseButtonBinds.GetSize(); i++) { if (pBindSet->MouseButtonBinds[i].ButtonIndex == buttonIndex) { pBindSet->MouseButtonBinds[i].EventName = eventName; pBindSet->MouseButtonBinds[i].ActivateDirection = activateDirection; return true; } } // create new bind MouseButtonBind bind; bind.ButtonIndex = buttonIndex; bind.EventName = eventName; bind.ActivateDirection = activateDirection; pBindSet->MouseButtonBinds.Add(bind); return true; } bool InputManager::BindControllerAxis(const char *bindSetName, uint32 controllerIndex, ControllerAxis axis, const char *eventName) { BindSet *pBindSet = (bindSetName != nullptr) ? GetOrCreateBindSetByName(bindSetName) : &m_globalBindSet; DebugAssert(pBindSet != nullptr); // search for a bind that already exists for (uint32 i = 0; i < pBindSet->ControllerAxisBinds.GetSize(); i++) { if (pBindSet->ControllerAxisBinds[i].ControllerIndex == controllerIndex && pBindSet->ControllerAxisBinds[i].Axis == axis) { pBindSet->ControllerAxisBinds[i].EventName = eventName; return true; } } // create new bind ControllerAxisBind bind; bind.ControllerIndex = controllerIndex; bind.Axis = axis; bind.EventName = eventName; pBindSet->ControllerAxisBinds.Add(bind); return true; } bool InputManager::BindControllerButton(const char *bindSetName, uint32 controllerIndex, ControllerButton button, const char *eventName, int32 activateDirection /* = 0 */) { BindSet *pBindSet = (bindSetName != nullptr) ? GetOrCreateBindSetByName(bindSetName) : &m_globalBindSet; DebugAssert(pBindSet != nullptr); // search for a bind that already exists for (uint32 i = 0; i < pBindSet->ControllerButtonBinds.GetSize(); i++) { if (pBindSet->ControllerButtonBinds[i].ControllerIndex == controllerIndex && pBindSet->ControllerButtonBinds[i].Button == button) { pBindSet->ControllerButtonBinds[i].EventName = eventName; pBindSet->ControllerButtonBinds[i].ActivateDirection = activateDirection; return true; } } // create new bind ControllerButtonBind bind; bind.ControllerIndex = controllerIndex; bind.Button = button; bind.EventName = eventName; bind.ActivateDirection = activateDirection; pBindSet->ControllerButtonBinds.Add(bind); return true; } InputManager::BindSet *InputManager::GetOrCreateBindSetByName(const char *bindSetName) { BindSetTable::Member *pMember = m_bindSets.Find(bindSetName); if (pMember != nullptr) return pMember->Value; // allocate new BindSet *pBindSet = new BindSet(); pBindSet->Name = bindSetName; m_bindSets.Insert(bindSetName, pBindSet); return pBindSet; } bool InputManager::SwitchBindSet(const char *bindSetName) { BindSetTable::Member *pMember = m_bindSets.Find(bindSetName); if (pMember != nullptr) { Log_DevPrintf("InputManager::SwitchBindSet(%s) success", pMember->Value->Name.GetCharArray()); m_pActiveBindSet = pMember->Value; return true; } Log_WarningPrintf("InputManager::SwitchBindSet(%s): no bind set with this name", bindSetName); m_pActiveBindSet = nullptr; return false; } bool InputManager::HandleSDLEvent(const void *pEvent) { if (m_eventBlockerCount > 0) return false; const SDL_Event *pRealEvent = reinterpret_cast<const SDL_Event *>(pEvent); switch (pRealEvent->type) { case SDL_KEYDOWN: case SDL_KEYUP: return HandleKeyboardEvent(pRealEvent); case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: return HandleMouseEvent(pRealEvent); case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYHATMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: return HandleJoystickEvent(pRealEvent); case SDL_CONTROLLERAXISMOTION: case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEREMOVED: case SDL_CONTROLLERDEVICEREMAPPED: return HandleControllerEvent(pRealEvent); } return false; } bool InputManager::HandleKeyboardEvent(const SDL_Event *pEvent) { // if the key repeat count is >0, skip it if (pEvent->key.repeat) return false; // find the binding const KeyboardBind *pKeyboardBind = nullptr; // search bind set (if active) if (m_pActiveBindSet != nullptr) { for (const KeyboardBind &keyboardBind : m_pActiveBindSet->KeyboardBinds) { if ((SDL_Keycode)keyboardBind.SDLScanCode == pEvent->key.keysym.scancode) { pKeyboardBind = &keyboardBind; break; } } } // search global bind set if we still didn't find anything if (pKeyboardBind == nullptr) { for (const KeyboardBind &keyboardBind : m_globalBindSet.KeyboardBinds) { if ((SDL_Keycode)keyboardBind.SDLScanCode == pEvent->key.keysym.scancode) { pKeyboardBind = &keyboardBind; break; } } } // if we didn't find anything, it's unhandled if (pKeyboardBind == nullptr) return false; // look up the event if (!pKeyboardBind->EventName.IsEmpty()) { const BaseEvent *pBoundEvent = LookupEventByName(pKeyboardBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // invoke action events on key down only if (pEvent->type == SDL_KEYDOWN) static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); } break; case EventType_BinaryState: { // binary state is 1 for down, or 0 for up static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke((pEvent->type == SDL_KEYDOWN)); } break; case EventType_AxisState: { // axis state is dependant on the bind direction, if it is set if (pKeyboardBind->ActivateDirection != 0) static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(pKeyboardBind->ActivateDirection * ((pEvent->type == SDL_KEYDOWN) ? 1 : 0)); else static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(((pEvent->type == SDL_KEYDOWN) ? 1 : 0)); } break; case EventType_NormalizedAxisState: { // axis state is dependant on the bind direction, if it is set if (pKeyboardBind->ActivateDirection != 0) static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(pKeyboardBind->ActivateDirection * ((pEvent->type == SDL_KEYDOWN) ? 1 : 0))); else static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(((pEvent->type == SDL_KEYDOWN) ? 1 : 0))); } break; } } } else if (!pKeyboardBind->CommandString.IsEmpty()) { // invoke command on key down if (pEvent->type == SDL_KEYDOWN) g_pConsole->ExecuteText(pKeyboardBind->CommandString); } // handled return true; } bool InputManager::HandleMouseEvent(const SDL_Event *pEvent) { switch (pEvent->type) { case SDL_MOUSEMOTION: { // bool wasHandled = false; int32 relativeAmounts[2] = { pEvent->motion.xrel, pEvent->motion.yrel }; for (uint32 axisIndex = 0; axisIndex < 2; axisIndex++) { if (relativeAmounts[axisIndex] == 0) continue; // get direction int32 direction = Math::Sign(relativeAmounts[axisIndex]); // search bind set (if active) const MouseAxisBind *pAxisBind = nullptr; if (m_pActiveBindSet != nullptr) { for (const MouseAxisBind &axisBind : m_pActiveBindSet->MouseAxisBinds) { if (axisBind.AxisIndex == axisIndex && (axisBind.BindDirection == 0 || axisBind.BindDirection == direction)) { pAxisBind = &axisBind; break; } } } // search global bindset if (pAxisBind == nullptr) { for (const MouseAxisBind &axisBind : m_globalBindSet.MouseAxisBinds) { if (axisBind.AxisIndex == axisIndex && (axisBind.BindDirection == 0 || axisBind.BindDirection == direction)) { pAxisBind = &axisBind; break; } } } // skip if nothing was found if (pAxisBind == nullptr) continue; // look up the event const BaseEvent *pBoundEvent = LookupEventByName(pAxisBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // trip event static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); wasHandled = true; } break; case EventType_AxisState: { // calculate relative amount static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(relativeAmounts[axisIndex]); wasHandled = true; } break; case EventType_NormalizedAxisState: { // look up the window size, and calculate the normalized value based on that SDL_Window *pSDLWindow = SDL_GetWindowFromID(pEvent->motion.windowID); if (pSDLWindow != nullptr) { // get window dimensions int32 winWidth, winHeight; SDL_GetWindowSize(pSDLWindow, &winWidth, &winHeight); // calculate normalized value int32 currentPosition = (axisIndex == 0) ? pEvent->motion.x : pEvent->motion.y; int32 axisSize = (axisIndex == 0) ? winWidth : winHeight; float normalizedValue = Math::Clamp((float)currentPosition / (float)axisSize, 0.0f, 1.0f); // pass through static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(normalizedValue); wasHandled = true; } } break; } } } // return if a handler was invoked return wasHandled; } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { // find the binding const MouseButtonBind *pButtonBind = nullptr; // search bind set (if active) if (m_pActiveBindSet != nullptr) { for (const MouseButtonBind &buttonBind : m_pActiveBindSet->MouseButtonBinds) { if (buttonBind.ButtonIndex == pEvent->button.button) { pButtonBind = &buttonBind; break; } } } // search global bind set if we still didn't find anything if (pButtonBind == nullptr) { for (const MouseButtonBind &buttonBind : m_globalBindSet.MouseButtonBinds) { if (buttonBind.ButtonIndex == pEvent->button.button) { pButtonBind = &buttonBind; break; } } } // if we didn't find anything, it's unhandled if (pButtonBind == nullptr) return false; // look up the event const BaseEvent *pBoundEvent = LookupEventByName(pButtonBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // invoke action events on key down only if (pEvent->type == SDL_MOUSEBUTTONDOWN) static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); } break; case EventType_BinaryState: { // binary state is 1 for down, or 0 for up static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke((pEvent->type == SDL_MOUSEBUTTONDOWN)); } break; case EventType_AxisState: { // axis state is dependant on the bind direction, if it is set if (pButtonBind->ActivateDirection != 0) static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(pButtonBind->ActivateDirection * ((pEvent->type == SDL_MOUSEBUTTONDOWN) ? 1 : 0)); else static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(((pEvent->type == SDL_MOUSEBUTTONDOWN) ? 1 : 0)); } break; case EventType_NormalizedAxisState: { // axis state is dependant on the bind direction, if it is set if (pButtonBind->ActivateDirection != 0) static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(pButtonBind->ActivateDirection * ((pEvent->type == SDL_MOUSEBUTTONDOWN) ? 1 : 0))); else static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(((pEvent->type == SDL_MOUSEBUTTONDOWN) ? 1 : 0))); } break; } } // handled return true; } break; case SDL_MOUSEWHEEL: { // find the binding const MouseAxisBind *pAxisBind = nullptr; // get x/y directions int32 xDirection = Math::Sign(pEvent->wheel.x); int32 yDirection = Math::Sign(pEvent->wheel.x); // search bind set (if active) if (m_pActiveBindSet != nullptr) { for (const MouseAxisBind &axisBind : m_pActiveBindSet->MouseAxisBinds) { if ((axisBind.AxisIndex == 3 && pEvent->wheel.x != 0 && (axisBind.BindDirection == 0 || axisBind.BindDirection == xDirection)) || (axisBind.AxisIndex == 2 && pEvent->wheel.y != 0 && (axisBind.BindDirection == 0 || axisBind.BindDirection == yDirection))) { pAxisBind = &axisBind; break; } } } // search global bind set if we still didn't find anything if (pAxisBind == nullptr) { for (const MouseAxisBind &axisBind : m_globalBindSet.MouseAxisBinds) { if ((axisBind.AxisIndex == 3 && pEvent->wheel.x != 0 && (axisBind.BindDirection == 0 || axisBind.BindDirection == xDirection)) || (axisBind.AxisIndex == 2 && pEvent->wheel.y != 0 && (axisBind.BindDirection == 0 || axisBind.BindDirection == yDirection))) { pAxisBind = &axisBind; break; } } } // if we didn't find anything, it's unhandled if (pAxisBind == nullptr) return false; // look up the event const BaseEvent *pBoundEvent = LookupEventByName(pAxisBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // invoke on any wheel action static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); } break; case EventType_BinaryState: { // binary state is 1 for up, or 0 for down if (pAxisBind->AxisIndex == 2) static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke((pEvent->wheel.y <= 0) ? 1 : 0); else static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke((pEvent->wheel.x <= 0) ? 0 : 1); } break; case EventType_AxisState: { if (pAxisBind->AxisIndex == 2) static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(pEvent->wheel.y); else static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(pEvent->wheel.x); } break; } } // handled return true; } break; } return false; } InputManager::OpenJoystick *InputManager::GetJoystickBySDLIndex(int32 index) { for (uint32 i = 0; i < m_joysticks.GetSize(); i++) { if (m_joysticks[i].SDLJoystickIndex == index) return &m_joysticks[i]; } return nullptr; } bool InputManager::HandleJoystickEvent(const SDL_Event *pEvent) { // skip anything for game controllers -- can't call this for removed event //if (SDL_IsGameController(pEvent->jdevice.which)) //return false; return false; } InputManager::OpenController *InputManager::GetControllerBySDLIndex(int32 index) { for (uint32 i = 0; i < m_controllers.GetSize(); i++) { if (m_controllers[i].SDLJoystickIndex == index) return &m_controllers[i]; } return nullptr; } bool InputManager::HandleControllerEvent(const SDL_Event *pEvent) { // mapping of sdl controller axis to our axis, buttons to our buttons static const ControllerAxis sdlControllerAxisMapping[SDL_CONTROLLER_AXIS_MAX] = { ControllerAxis_LeftStickX, // SDL_CONTROLLER_AXIS_LEFTX ControllerAxis_LeftStickY, // SDL_CONTROLLER_AXIS_LEFTY ControllerAxis_RightStickX, // SDL_CONTROLLER_AXIS_RIGHTX ControllerAxis_RightStickY, // SDL_CONTROLLER_AXIS_RIGHTY ControllerAxis_LeftTrigger, // SDL_CONTROLLER_AXIS_TRIGGERLEFT ControllerAxis_RightTrigger, // SDL_CONTROLLER_AXIS_TRIGGERRIGHT }; static const ControllerButton sdlControllerButtonMapping[SDL_CONTROLLER_BUTTON_MAX] = { ControllerButton_A, // SDL_CONTROLLER_BUTTON_A ControllerButton_B, // SDL_CONTROLLER_BUTTON_B ControllerButton_X, // SDL_CONTROLLER_BUTTON_X ControllerButton_Y, // SDL_CONTROLLER_BUTTON_Y ControllerButton_Back, // SDL_CONTROLLER_BUTTON_BACK ControllerButton_Guide, // SDL_CONTROLLER_BUTTON_GUIDE ControllerButton_Start, // SDL_CONTROLLER_BUTTON_START ControllerButton_LeftStick, // SDL_CONTROLLER_BUTTON_LEFTSTICK ControllerButton_RightStick, // SDL_CONTROLLER_BUTTON_RIGHTSTICK ControllerButton_LeftBumper, // SDL_CONTROLLER_BUTTON_LEFTSHOULER, ControllerButton_RightBumper, // SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ControllerButton_DPadUp, // SDL_CONTROLLER_BUTTON_DPAD_UP ControllerButton_DPadDown, // SDL_CONTROLLER_BUTTON_DPAD_DOWN ControllerButton_DPadLeft, // SDL_CONTROLLER_BUTTON_DPAD_LEFT ControllerButton_DPadRight, // SDL_CONTROLLER_BUTTON_DPAD_RIGHT }; switch (pEvent->type) { case SDL_CONTROLLERDEVICEADDED: { Log_InfoPrintf("InputManager::HandleGameControllerEvent: Controller %i (%s) connected. Opening...", pEvent->cdevice.which, SDL_GameControllerNameForIndex(pEvent->cdevice.which)); DebugAssert(GetControllerBySDLIndex(pEvent->cdevice.which) == nullptr); SDL_GameController *pGameController = SDL_GameControllerOpen(pEvent->cdevice.which); if (pGameController == nullptr) { Log_ErrorPrintf("InputManager::HandleGameControllerEvent: Failed to open controller %i: %s", pEvent->cdevice.which, SDL_GetError()); return true; } OpenController gameController; gameController.Index = m_controllers.GetSize(); gameController.SDLJoystickIndex = pEvent->cdevice.which; gameController.pSDLGameController = pGameController; // read the axis positions for relative movement Y_memzero(gameController.LastAxisPositions, sizeof(gameController.LastAxisPositions)); for (uint32 sdlAxisIndex = 0; sdlAxisIndex < SDL_CONTROLLER_AXIS_MAX; sdlAxisIndex++) gameController.LastAxisPositions[sdlControllerAxisMapping[sdlAxisIndex]] = SDL_GameControllerGetAxis(pGameController, (SDL_GameControllerAxis)sdlAxisIndex); // add it m_controllers.Add(gameController); return true; } break; case SDL_CONTROLLERDEVICEREMOVED: { OpenController *pGameController = GetControllerBySDLIndex(pEvent->cdevice.which); DebugAssert(pGameController != nullptr); Log_InfoPrintf("InputManager::HandleGameControllerEvent: Controller %i (%s) disconnected.", pEvent->cdevice.which, SDL_GameControllerName(pGameController->pSDLGameController)); SDL_GameControllerClose(pGameController->pSDLGameController); m_controllers.OrderedRemove(pGameController->Index); return true; } break; case SDL_CONTROLLERAXISMOTION: { OpenController *pGameController = GetControllerBySDLIndex(pEvent->caxis.which); if (pGameController == nullptr) return false; DebugAssert(pEvent->caxis.axis < SDL_CONTROLLER_AXIS_MAX); uint32 controllerIndex = pGameController->Index; ControllerAxis axis = sdlControllerAxisMapping[pEvent->caxis.axis]; // negate stick axises, so that up is positive int32 axisValue = (int32)pEvent->caxis.value; if (axis == ControllerAxis_LeftStickY || axis == ControllerAxis_RightStickY) axisValue = -axisValue; // calculate relative value int32 relativeValue = axisValue - (int32)pGameController->LastAxisPositions[axis]; pGameController->LastAxisPositions[axis] = (int16)axisValue; // find the binding const ControllerAxisBind *pAxisBind = nullptr; // search bind set (if active) if (m_pActiveBindSet != nullptr) { for (const ControllerAxisBind &axisBind : m_pActiveBindSet->ControllerAxisBinds) { if (axisBind.ControllerIndex == controllerIndex && axisBind.Axis == axis) { pAxisBind = &axisBind; break; } } } // search global bind set if we still didn't find anything if (pAxisBind == nullptr) { for (const ControllerAxisBind &axisBind : m_globalBindSet.ControllerAxisBinds) { if (axisBind.ControllerIndex == controllerIndex && axisBind.Axis == axis) { pAxisBind = &axisBind; break; } } } // if we didn't find anything, it's unhandled if (pAxisBind == nullptr) return false; // look up the event const BaseEvent *pBoundEvent = LookupEventByName(pAxisBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // invoke action events whenever the axis position changes static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); } break; case EventType_BinaryState: { // binary state is off for <= 0, on for >= 0.. use 1/10th deadzone static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke((axisValue >= 3276)); } break; case EventType_AxisState: { // pass through relative value static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(relativeValue); } break; case EventType_NormalizedAxisState: { // normalize it to -1..1 float normalizedValue = Math::Clamp((float)axisValue / 32767.0f, -1.0f, 1.0f); // invoke event static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(normalizedValue); } break; } } // handled return true; } break; case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: { OpenController *pGameController = GetControllerBySDLIndex(pEvent->cbutton.which); if (pGameController == nullptr) return false; DebugAssert(pEvent->cbutton.button < SDL_CONTROLLER_BUTTON_MAX); uint32 controllerIndex = pGameController->Index; ControllerButton button = sdlControllerButtonMapping[pEvent->cbutton.button]; bool buttonPressed = (pEvent->cbutton.state == SDL_PRESSED); // find the binding const ControllerButtonBind *pButtonBind = nullptr; // search bind set (if active) if (m_pActiveBindSet != nullptr) { for (const ControllerButtonBind &buttonBind : m_pActiveBindSet->ControllerButtonBinds) { if (buttonBind.ControllerIndex == controllerIndex && buttonBind.Button == button) { pButtonBind = &buttonBind; break; } } } // search global bind set if we still didn't find anything if (pButtonBind == nullptr) { for (const ControllerButtonBind &buttonBind : m_globalBindSet.ControllerButtonBinds) { if (buttonBind.ControllerIndex == controllerIndex && buttonBind.Button == button) { pButtonBind = &buttonBind; break; } } } // if we didn't find anything, it's unhandled if (pButtonBind == nullptr) return false; // look up the event const BaseEvent *pBoundEvent = LookupEventByName(pButtonBind->EventName); if (pBoundEvent != nullptr) { // handle it switch (pBoundEvent->Type) { case EventType_Action: { // invoke action events whenever the button is pushed down if (buttonPressed) static_cast<const ActionEvent *>(pBoundEvent)->pCallback->Invoke(); } break; case EventType_BinaryState: { // binary state is off for <= 0, on for >= 0 static_cast<const BinaryStateEvent *>(pBoundEvent)->pCallback->Invoke(buttonPressed); } break; case EventType_AxisState: { // axis state is dependant on the bind direction, if it is set if (pButtonBind->ActivateDirection != 0) static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(pButtonBind->ActivateDirection * ((buttonPressed) ? 1 : 0)); else static_cast<const AxisStateEvent *>(pBoundEvent)->pCallback->Invoke(((buttonPressed) ? 1 : 0)); } break; case EventType_NormalizedAxisState: { // axis state is dependant on the bind direction, if it is set if (pButtonBind->ActivateDirection != 0) static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(pButtonBind->ActivateDirection * ((buttonPressed) ? 1 : 0))); else static_cast<const NormalizedAxisStateEvent *>(pBoundEvent)->pCallback->Invoke(static_cast<float>(((buttonPressed) ? 1 : 0))); } break; } } // handled return true; } break; } return false; } <file_sep>/Engine/Source/Engine/BulletDebugDraw.h #pragma once #include "Engine/Common.h" #include "Renderer/MiniGUIContext.h" #include "Engine/Physics/BulletHeaders.h" class BulletDebugDraw : public btIDebugDraw { public: BulletDebugDraw(); ~BulletDebugDraw(); const MiniGUIContext &GetGUIContext() const { return m_guiContext; } void SetViewportDimensions(const uint32 width, const uint32 height); void BeginDraw(); void EndDraw(); virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color); virtual void drawLine(const btVector3& from,const btVector3& to, const btVector3& fromColor, const btVector3& toColor); virtual void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color); virtual void reportErrorWarning(const char* warningString); virtual void draw3dText(const btVector3& location,const char* textString); virtual void setDebugMode(int debugMode); virtual int getDebugMode() const; private: MiniGUIContext m_guiContext; int m_debugMode; }; <file_sep>/Engine/Source/MathLib/Transform.cpp #include "MathLib/Transform.h" Transform::Transform(const Transform &transform) : m_position(transform.m_position), m_rotation(transform.m_rotation), m_scale(transform.m_scale) { } Transform::Transform(const Vector3f &translation, const Quaternion &rotation, const Vector3f &scale) : m_position(translation), m_rotation(rotation), m_scale(scale) { } Transform::Transform(const Matrix4x4f &transformMatrix) { transformMatrix.Decompose(m_position, m_rotation, m_scale); } void Transform::SetIdentity() { m_position.SetZero(); m_rotation.SetIdentity(); m_scale = Vector3f::One; } Vector3f Transform::TransformPoint(const Vector3f &v) const { Vector3f ret; ret = v * m_scale; ret = m_rotation * ret; ret += m_position; return ret; } SIMDVector3f Transform::TransformPoint(const SIMDVector3f &v) const { SIMDVector3f ret; ret = v * m_scale; ret = m_rotation * ret; ret += SIMDVector3f(m_position); return ret; } Vector3f Transform::TransformNormal(const Vector3f &v) const { return (m_rotation * v).Normalize(); } SIMDVector3f Transform::TransformNormal(const SIMDVector3f &v) const { return (m_rotation * v).Normalize(); } Ray Transform::TransformRay(const Ray &v) const { Vector3f newOrigin(TransformPoint(v.GetOrigin())); Vector3f newEnd(TransformPoint(v.GetEnd())); return Ray(newOrigin, newEnd); } Vector3f Transform::UntransformPoint(const Vector3f &v) const { Vector3f ret; ret = v - m_position; ret = m_rotation.Inverse() * ret; ret /= m_scale; return ret; } SIMDVector3f Transform::UntransformPoint(const SIMDVector3f &v) const { SIMDVector3f ret; ret = v - SIMDVector3f(m_position); ret = m_rotation.Inverse() * ret; ret /= m_scale; return ret; } Vector3f Transform::UntransformNormal(const Vector3f &v) const { return (m_rotation.Inverse() * v).Normalize(); } SIMDVector3f Transform::UntransformNormal(const SIMDVector3f &v) const { return (m_rotation.Inverse() * v).Normalize(); } Ray Transform::UntransformRay(const Ray &v) const { Vector3f newOrigin(UntransformPoint(v.GetOrigin())); Vector3f newEnd(UntransformPoint(v.GetEnd())); return Ray(newOrigin, newEnd); } Transform Transform::Inverse() const { return Transform(-m_position, m_rotation.Inverse(), Vector3f::One / m_scale); } void Transform::InvertInPlace() { m_position = -m_position; m_rotation.InvertInPlace(); m_scale = Vector3f::One / m_scale; } Matrix3x4f Transform::GetTransformMatrix3x4() const { return Matrix3x4f(GetTransformMatrix4x4()); } Matrix4x4f Transform::GetTransformMatrix4x4() const { return Matrix4x4f::MakeTranslationMatrix(m_position) * m_rotation.GetMatrix4x4() * Matrix4x4f::MakeScaleMatrix(m_scale); } Matrix3x4f Transform::GetInverseTransformMatrix3x4() const { return Matrix3x4f(GetInverseTransformMatrix4x4()); } Matrix4x4f Transform::GetInverseTransformMatrix4x4() const { return Matrix4x4f::MakeScaleMatrix(Vector3f::One / m_scale) * m_rotation.Inverse().GetMatrix4x4() * Matrix4x4f::MakeTranslationMatrix(-m_position); } bool Transform::operator==(const Transform &transform) const { return (m_position == transform.m_position && m_rotation == transform.m_rotation && m_scale == transform.m_scale); } bool Transform::operator!=(const Transform &transform) const { return (m_position != transform.m_position || m_rotation != transform.m_rotation || m_scale != transform.m_scale); } Transform &Transform::operator=(const Transform &transform) { m_position = transform.m_position; m_rotation = transform.m_rotation; m_scale = transform.m_scale; return *this; } Transform Transform::operator*(const Transform &rightSide) const { return ConcatenateTransforms(*this, rightSide); } Vector3f Transform::operator*(const Vector3f &rhs) const { return TransformPoint(rhs); } SIMDVector3f Transform::operator*(const SIMDVector3f &rhs) const { return TransformPoint(rhs); } Transform &Transform::operator*=(const Transform &rightSide) { Transform temp(*this); *this = ConcatenateTransforms(temp, rightSide); return *this; } AABox Transform::TransformBoundingBox(const AABox &boundingBox) const { SIMDVector3f cornerPoints[8]; boundingBox.GetCornerPoints(cornerPoints); AABox newBoundingBox(TransformPoint(cornerPoints[0])); for (uint32 i = 1; i < 8; i++) newBoundingBox.Merge(TransformPoint(cornerPoints[i])); return newBoundingBox; } Sphere Transform::TransformBoundingSphere(const Sphere &boundingSphere) const { Sphere newBoundingSphere; newBoundingSphere.SetCenter(TransformPoint(boundingSphere.GetCenter())); newBoundingSphere.SetRadius(boundingSphere.GetRadius() * Max(m_scale.x, Max(m_scale.y, m_scale.z))); return newBoundingSphere; } Transform Transform::LinearInterpolate(const Transform &end, const float factor) { return Transform::LinearInterpolate(*this, end, factor); } Transform Transform::LinearInterpolate(const Transform &start, const Transform &end, const float factor) { Transform returnValue; returnValue.m_position = SIMDVector3f(start.m_position).Lerp(SIMDVector3f(end.m_position), factor); returnValue.m_rotation = Quaternion::LinearInterpolate(start.m_rotation, end.m_rotation, factor); returnValue.m_scale = SIMDVector3f(start.m_scale).Lerp(SIMDVector3f(end.m_scale), factor); return returnValue; } Transform Transform::ConcatenateTransforms(const Transform &leftSide, const Transform &rightSide) { #if 1 // left then right //float3 newTranslation(rightSide.TransformPoint(leftSide.GetPosition())); Vector3f newTranslation(rightSide.m_rotation * (leftSide.m_position * rightSide.m_scale) + rightSide.GetPosition()); Quaternion newRotation((rightSide.m_rotation * leftSide.m_rotation).Normalize()); Vector3f newScale(rightSide.m_scale * leftSide.m_scale); return Transform(newTranslation, newRotation, newScale); #else return Transform(rightSide.GetTransformMatrix3x4() * leftSide.GetTransformMatrix3x4()); #endif } static const float IdentityTransform[10] = { 0.0f, 0.0f, 0.0f, // translation 0.0f, 0.0f, 0.0f, 1.0f, // rotation 1.0f, 1.0f, 1.0f }; // scale const Transform& Transform::Identity = reinterpret_cast<const Transform &>(IdentityTransform); <file_sep>/Engine/Source/GameFramework/BlockMeshBrush.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/BlockMeshBrush.h" #include "Engine/BlockMesh.h" #include "Engine/Engine.h" #include "Engine/World.h" #include "Engine/ResourceManager.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Renderer/RenderWorld.h" Log_SetChannel(BlockMeshBrush); DEFINE_OBJECT_TYPE_INFO(BlockMeshBrush); DEFINE_OBJECT_GENERIC_FACTORY(BlockMeshBrush); BEGIN_OBJECT_PROPERTY_MAP(BlockMeshBrush) PROPERTY_TABLE_MEMBER("BlockMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetBlockMeshName, NULL, PropertyCallbackSetBlockMeshName, NULL, NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(BlockMeshBrush, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(BlockMeshBrush, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(BlockMeshBrush, m_shadowFlags), NULL, NULL) END_OBJECT_PROPERTY_MAP() BlockMeshBrush::BlockMeshBrush(const ObjectTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pBlockMesh(nullptr), m_visible(true), m_shadowFlags(0), m_collidable(false), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } BlockMeshBrush::~BlockMeshBrush() { if (m_pRenderProxy != NULL) m_pRenderProxy->Release(); if (m_pCollisionObject != NULL) m_pCollisionObject->Release(); if (m_pBlockMesh != NULL) m_pBlockMesh->Release(); } bool BlockMeshBrush::Create(const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const BlockMesh *pBlockMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_transform.Set(position, rotation, scale); if (pBlockMesh != nullptr) { m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); } else { m_pBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; // done return Initialize(); } bool BlockMeshBrush::Initialize() { // handle load errors if (m_pBlockMesh == nullptr) m_pBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); // create render proxy if (m_visible) m_pRenderProxy = new BlockMeshRenderProxy(0, m_pBlockMesh, m_transform, m_shadowFlags); // create collision object if (m_collidable && m_pBlockMesh->GetCollisionShape() != nullptr) m_pCollisionObject = new Physics::StaticObject(0, m_pBlockMesh->GetCollisionShape(), m_transform); // calculate bounding box m_boundingBox = m_transform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()); m_boundingSphere = m_transform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()); return true; } void BlockMeshBrush::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void BlockMeshBrush::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } bool BlockMeshBrush::PropertyCallbackGetBlockMeshName(ThisClass *pEntity, const void *pUserData, String *pValue) { pValue->Assign(pEntity->m_pBlockMesh->GetName()); return true; } bool BlockMeshBrush::PropertyCallbackSetBlockMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue) { const BlockMesh *pBlockMesh = g_pResourceManager->GetBlockMesh(*pValue); if (pBlockMesh == NULL) return false; if (pEntity->m_pBlockMesh != NULL) pEntity->m_pBlockMesh->Release(); pEntity->m_pBlockMesh = pBlockMesh; return true; } <file_sep>/Engine/Source/BaseGame/BaseGame.cpp #include "BaseGame/PrecompiledHeader.h" #include "BaseGame/BaseGame.h" #include "Engine/InputManager.h" #include "Engine/EngineCVars.h" #include "Engine/World.h" #include "Engine/ScriptManager.h" #include "Engine/Profiling.h" #include "Renderer/WorldRenderer.h" #include "Renderer/ImGuiBridge.h" #include "YBaseLib/CPUID.h" Log_SetChannel(BaseGame); BaseGame::BaseGame() : m_pOverlayConsole(nullptr) , m_quitFlag(false) , m_restartRendererFlag(false) , m_relativeMouseMovement(false) , m_forcedAbsoluteMouseMovement(0) , m_pGPUContext(nullptr) , m_pWorldRenderer(nullptr) , m_pOutputWindow(nullptr) , m_renderThreadEventsReadyEvent(true) , m_renderThreadFrameCompleteEvent(true) , m_pGameState(nullptr) , m_pNextGameState(nullptr) , m_nextGameStateIsModal(false) , m_gameStateEndModal(false) #ifdef WITH_IMGUI , m_imGuiEnabled(0) , m_showDebugRenderMenu(false) #endif #ifdef WITH_PROFILER , m_profilerInterceptMouseEvents(false) #endif { } BaseGame::~BaseGame() { DebugAssert(m_pNextGameState == nullptr); DebugAssert(m_pGameState == nullptr); DebugAssert(m_pWorldRenderer == nullptr); DebugAssert(m_pOutputWindow == nullptr); DebugAssert(m_pGPUContext == nullptr); } void BaseGame::Quit() { m_quitFlag = true; } void BaseGame::OnRegisterTypes() { } bool BaseGame::OnStart() { // enable resource modification tracking g_pResourceManager->SetResourceModificationDetectionEnabled(true); // create overlay console m_pOverlayConsole = new OverlayConsole(); // register stuff RegisterBaseCommands(); RegisterBaseInputEvents(); BindBaseInputEvents(); return true; } void BaseGame::OnExit() { g_pInputManager->UnregisterEventsWithOwner(this); g_pConsole->UnregisterCommandsWithOwner(this); delete m_pOverlayConsole; m_pOverlayConsole = nullptr; } void BaseGame::OnWindowResized(uint32 width, uint32 height) { Log_DevPrintf("Game window resized: %ux%u", width, height); // check if we lost exclusive fullscreen if (m_pOutputWindow->GetFullscreenState() == RENDERER_FULLSCREEN_STATE_FULLSCREEN && !m_pGPUContext->GetExclusiveFullScreen()) { Log_WarningPrintf("BaseGame::OnWindowResized: Fullscreen state lost outside our control. Updating internal state."); m_pOutputWindow->SetFullscreenState(RENDERER_FULLSCREEN_STATE_WINDOWED); g_pConsole->SetCVar(&CVars::r_fullscreen, false); QueueRendererRestart(); } // resize the output window and buffer m_pOutputWindow->SetDimensions(width, height); m_pGPUContext->ResizeOutputBuffer(width, height); // pass to game state m_pGameState->OnWindowResized(width, height); } void BaseGame::OnWindowFocusGained() { Log_DevPrintf("Game window focus gained."); // pass to game state m_pGameState->OnWindowFocusGained(); } void BaseGame::OnWindowFocusLost() { Log_DevPrintf("Game window focus lost."); // pass to game state m_pGameState->OnWindowFocusLost(); } void BaseGame::OnMainThreadPreFrame(float deltaTime) { // detect any changed resources g_pResourceManager->Update(); // pass to game state m_pGameState->OnMainThreadPreFrame(deltaTime); } void BaseGame::OnMainThreadBeginFrame(float deltaTime) { // pass to game state m_pGameState->OnMainThreadBeginFrame(deltaTime); } void BaseGame::OnMainThreadAsyncTick(float deltaTime) { // pass to game state m_pGameState->OnMainThreadAsyncTick(deltaTime); } void BaseGame::OnMainThreadTick(float deltaTime) { // pass to game state m_pGameState->OnMainThreadTick(deltaTime); } void BaseGame::OnMainThreadEndFrame(float deltaTime) { // pass to game state m_pGameState->OnMainThreadEndFrame(deltaTime); } void BaseGame::OnRenderThreadPreFrame(float deltaTime) { // pass to game state m_pGameState->OnRenderThreadPreFrame(deltaTime); } void BaseGame::OnRenderThreadBeginFrame(float deltaTime) { // pass to game state m_pGameState->OnRenderThreadBeginFrame(deltaTime); } void BaseGame::OnRenderThreadDraw(float deltaTime) { // pass to game state m_pGameState->OnRenderThreadDraw(deltaTime); } void BaseGame::OnRenderThreadEndFrame(float deltaTime) { // pass to game state m_pGameState->OnRenderThreadEndFrame(deltaTime); } void BaseGame::RegisterBaseCommands() { // todo: move console as an argument to command handler g_pConsole->RegisterCommand("quit", Command_Quit_ExecuteHandler, Command_Quit_HelpHandler, this, this); g_pConsole->RegisterCommand("gc", Command_GC_ExecuteHandler, Command_GC_HelpHandler, this, this); g_pConsole->RegisterCommand("debugrendermenu", Command_OpenDebugRenderWindow_ExecuteHandler, Command_OpenDebugRenderWindow_HelpHandler, this, this); g_pConsole->RegisterCommand("profiler", Command_Profiler_ExecuteHandler, Command_Profiler_HelpHandler, this, this); g_pConsole->RegisterCommand("profilerdisplay", Command_ProfilerDisplay_ExecuteHandler, Command_ProfilerDisplay_HelpHandler, this, this); } bool BaseGame::Command_Quit_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { reinterpret_cast<BaseGame *>(userData)->Quit(); return true; } bool BaseGame::Command_Quit_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { Log_InfoPrint(" <CR>"); return true; } bool BaseGame::Command_GC_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { if (argumentCount > 1) { if (Y_stricmp(argumentValues[1], "step") == 0) { Log_InfoPrint("Running GC step..."); g_pScriptManager->RunGCStep(); return true; } } Log_InfoPrint("Running GC full collect..."); g_pScriptManager->RunGCFull(); return true; } bool BaseGame::Command_GC_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { if (argumentCount == 1) Log_InfoPrint(" [step|full] <CR>"); else Log_InfoPrint(" <CR>"); return true; } bool BaseGame::Command_OpenDebugRenderWindow_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { reinterpret_cast<BaseGame *>(userData)->OpenDebugRenderMenu(); return true; } bool BaseGame::Command_OpenDebugRenderWindow_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { Log_InfoPrint(" <CR>"); return true; } bool BaseGame::Command_Profiler_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { #ifdef WITH_PROFILER bool currentState = Profiling::GetProfilerEnabled(); bool newState = currentState; if (argumentCount > 1) { if (Y_stricmp(argumentValues[1], "on") == 0) newState = true; else newState = false; } if (currentState != newState) Profiling::SetProfilerEnabled(newState); Log_InfoPrintf("Profiler is %s%s.", (currentState != newState) ? "now " : "", (newState) ? "enabled" : "disabled"); return true; #else Log_ErrorPrint("Not compiled with profiler support."); return true; #endif } bool BaseGame::Command_Profiler_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { if (argumentCount == 1) Log_InfoPrint(" [off|on] <CR>"); else Log_InfoPrint(" <CR>"); return true; } bool BaseGame::Command_ProfilerDisplay_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { #ifdef WITH_PROFILER if (argumentCount > 1) { static const char *optionsLUT[] = { "off", "bars", "detail", "hidden" }; for (uint32 i = 0; i < countof(optionsLUT); i++) { if (Y_stricmp(optionsLUT[i], argumentValues[1]) == 0) { reinterpret_cast<BaseGame *>(userData)->SetProfilerDisplayMode(i); return true; } } Log_ErrorPrintf("Invalid profiler display mode: '%s'", argumentValues[1]); return true; } reinterpret_cast<BaseGame *>(userData)->ToggleProfilerDisplay(); return true; #else Log_ErrorPrint("Not compiled with profiler support."); return true; #endif } bool BaseGame::Command_ProfilerDisplay_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { if (argumentCount == 1) Log_InfoPrint(" [off|bars|detail|hidden] <CR>"); else Log_InfoPrint(" <CR>"); return true; } void BaseGame::RegisterBaseInputEvents() { g_pInputManager->RegisterActionEvent(this, "PreviousDebugCamera", "Toggle previous debug camera", MakeFunctorClass(this, &BaseGame::InputActionHandler_PreviousDebugCamera)); g_pInputManager->RegisterActionEvent(this, "NextDebugCamera", "Toggle next debug camera", MakeFunctorClass(this, &BaseGame::InputActionHandler_NextDebugCamera)); } void BaseGame::BindBaseInputEvents() { g_pInputManager->BindKeyboardKey("ESC", "exec quit"); g_pInputManager->BindKeyboardKey("F1", "exec debugrendermenu"); g_pInputManager->BindKeyboardKey("F2", "exec profilerdisplay"); } void BaseGame::InputActionHandler_PreviousDebugCamera() { // if (m_pRenderProfiler == nullptr) // return; // // if (m_pRenderProfiler->GetCameraOverrideIndex() <= 0) // m_pRenderProfiler->ClearCameraOverride(); // else // m_pRenderProfiler->SetCameraOverride(m_pRenderProfiler->GetCameraOverrideIndex() - 1); } void BaseGame::InputActionHandler_NextDebugCamera() { // if (m_pRenderProfiler == nullptr) // return; // // m_pRenderProfiler->SetCameraOverride(m_pRenderProfiler->GetCameraOverrideIndex() + 1); } void BaseGame::SetNextGameState(GameState *pGameState) { Log_DevPrintf("BaseGame::SetNextGameState(%p)", pGameState); // queue next game state if (m_pNextGameState != nullptr) { Log_WarningPrintf("BaseGame::SetNextGameState: More than one next game state set in a frame. Deleting previous next game state."); delete m_pNextGameState; } // should not have any modals active Assert(m_gameStateStack.IsEmpty()); m_pNextGameState = pGameState; m_nextGameStateIsModal = false; } void BaseGame::BeginModalGameState(GameState *pGameState) { Log_DevPrintf("BaseGame::BeginModalGameState(%p)", pGameState); // queue next game state if (m_pNextGameState != nullptr) { Log_WarningPrintf("BaseGame::BeginModalGameState: More than one next game state set in a frame. Deleting previous next game state."); delete m_pNextGameState; } m_pNextGameState = pGameState; m_nextGameStateIsModal = true; } void BaseGame::EndModalGameState() { Log_DevPrintf("BaseGame::EndModalGameState()"); Assert(m_gameStateStack.GetSize() > 0); m_gameStateEndModal = true; } void BaseGame::CriticalError(const char *format, ...) { va_list ap; va_start(ap, format); SmallString message; message.FormatVA(format, ap); va_end(ap); Log_ErrorPrint("*** CRITICAL ERROR ***"); Log_ErrorPrint(message); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Critical error", message, nullptr); } void BaseGame::SetRelativeMouseMovement(bool enabled) { QUEUE_RENDERER_LAMBDA_COMMAND([this, enabled]() { if (m_relativeMouseMovement == enabled) return; m_relativeMouseMovement = enabled; if (enabled) { if (!m_forcedAbsoluteMouseMovement) m_pOutputWindow->SetMouseRelativeMovement(enabled); } else { if (!m_forcedAbsoluteMouseMovement) m_pOutputWindow->SetMouseRelativeMovement(enabled); } }); } void BaseGame::PushForcedAbsoluteMouseMovement() { QUEUE_RENDERER_LAMBDA_COMMAND([this]() { if ((m_forcedAbsoluteMouseMovement++) == 0 && m_relativeMouseMovement) m_pOutputWindow->SetMouseRelativeMovement(false); }); } void BaseGame::PopForcedAbsoluteMouseMovement() { QUEUE_RENDERER_LAMBDA_COMMAND([this]() { DebugAssert(m_forcedAbsoluteMouseMovement > 0); if ((--m_forcedAbsoluteMouseMovement) == 0 && m_relativeMouseMovement) m_pOutputWindow->SetMouseRelativeMovement(true); }); } void BaseGame::RenderThreadCollectEvents(float deltaTime) { // get new messages from the underlying subsystem SDL_PumpEvents(); // loop until we have everything for (;;) { // get events SDL_Event events[128]; int nEvents = SDL_PeepEvents(events, countof(events), SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT); if (nEvents <= 0) break; // process them for (int i = 0; i < nEvents; i++) { // there are only a few messages we are interested in const SDL_Event *pEvent = &events[i]; switch (pEvent->type) { case SDL_WINDOWEVENT: { // the window associated with this event should be our output window, if not, skip it if (SDL_GetWindowFromID(pEvent->window.windowID) != m_pOutputWindow->GetSDLWindow()) continue; // handle the event switch (pEvent->window.event) { case SDL_WINDOWEVENT_RESIZED: OnWindowResized(pEvent->window.data1, pEvent->window.data2); m_restartRendererFlag = true; break; case SDL_WINDOWEVENT_CLOSE: m_quitFlag = true; break; case SDL_WINDOWEVENT_FOCUS_GAINED: OnWindowFocusGained(); break; case SDL_WINDOWEVENT_FOCUS_LOST: OnWindowFocusLost(); break; } // don't add it to the main thread's queue, these sorts of messages are of no use to it continue; } break; case SDL_SYSWMEVENT: { // syswmevents are of no use to the main thread continue; } break; // handle alt+enter case SDL_KEYDOWN: case SDL_KEYUP: { if (pEvent->key.keysym.scancode == SDL_SCANCODE_RETURN && SDL_GetModState() & (KMOD_LALT | KMOD_RALT)) { // only toggle on key up if (pEvent->type == SDL_KEYUP) { Log_DevPrintf("Toggling fullscreen."); g_pConsole->SetCVar(&CVars::r_fullscreen, !CVars::r_fullscreen.GetPendingBool()); QueueRendererRestart(); } // skip passing to game continue; } } break; } #ifdef WITH_PROFILER // pass to profiler if (m_profilerInterceptMouseEvents && Profiling::HandleSDLEvent(pEvent)) continue; #endif #ifdef WITH_IMGUI // pass to imgui if (m_imGuiEnabled && ImGui::HandleSDLEvent(pEvent, true)) continue; #endif // append to the main thread's queue for later processing m_pendingEvents.Add(*pEvent); } } } void BaseGame::MainThreadProcessInputEvents(float deltaTime) { MICROPROFILE_SCOPEI("BaseGame", "MainThreadProcessInputEvents", MICROPROFILE_COLOR(100, 255, 255)); for (uint32 i = 0; i < m_pendingEvents.GetSize(); i++) { const SDL_Event *pEvent = &m_pendingEvents[i]; //Log_DevPrintf("Process pending event %u type %04X", i, pEvent->type); // pass to gamestate if (m_pGameState->OnWindowEvent(pEvent)) continue; // pass to overlay console first, it intercepts in front if (m_pOverlayConsole->OnInputEvent(pEvent)) continue; // check if it can be handled by input manager if (g_pInputManager->HandleSDLEvent(pEvent)) continue; // dunno what else to do.. } m_pendingEvents.Clear(); } void BaseGame::MainThreadFrame(float deltaTime) { MICROPROFILE_SCOPEI("BaseGame", "MainThreadFrame", MICROPROFILE_COLOR(50, 127, 127)); // wait for the render thread to fill the event buffer if (Renderer::HasRenderThread()) m_renderThreadEventsReadyEvent.Wait(); // begin frame { MICROPROFILE_SCOPEI("BaseGame", "BeginFrame", MICROPROFILE_COLOR(50, 0, 50)); OnMainThreadBeginFrame(deltaTime); } // process input events { MICROPROFILE_SCOPEI("BaseGame", "ProcesInputEvents", MICROPROFILE_COLOR(50, 127, 0)); MainThreadProcessInputEvents(deltaTime); } // pre-tick hooks { MICROPROFILE_SCOPEI("BaseGame", "BeginFrame", MICROPROFILE_COLOR(0, 127, 0)); OnMainThreadBeginFrame(deltaTime); } // run async tick { MICROPROFILE_SCOPEI("BaseGame", "UpdateAsync", MICROPROFILE_COLOR(0, 50, 127)); OnMainThreadAsyncTick(deltaTime); } // wait for async commands to finish, use the main thread to help them out { MICROPROFILE_SCOPEI("BaseGame", "CompleteAsyncTasks", MICROPROFILE_COLOR(10, 50, 20)); g_pEngine->GetAsyncCommandQueue()->ExecuteQueuedTasks(); } // run any callbacks { MICROPROFILE_SCOPEI("BaseGame", "ExecuteQueuedTasks", MICROPROFILE_COLOR(75, 120, 10)); g_pEngine->GetMainThreadCommandQueue()->ExecuteQueuedTasks(); } // run normal tick { MICROPROFILE_SCOPEI("BaseGame", "Update", MICROPROFILE_COLOR(0, 75, 10)); OnMainThreadTick(deltaTime); } // squish any dead script threads g_pScriptManager->CheckPausedThreadTimeout(deltaTime); // end simulation { MICROPROFILE_SCOPEI("BaseGame", "EndFrame", MICROPROFILE_COLOR(0, 120, 0)); OnMainThreadEndFrame(deltaTime); } // main thread done! m_fpsCounter.EndGameThreadFrame(); } bool BaseGame::RendererStart() { // apply pending renderer cvars g_pConsole->ApplyPendingRenderCVars(); // fill parameters RendererInitializationParameters initParameters; initParameters.EnableThreadedRendering = CVars::r_use_render_thread.GetBool(); initParameters.BackBufferFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; initParameters.DepthStencilBufferFormat = PIXEL_FORMAT_D24_UNORM_S8_UINT; initParameters.HideImplicitSwapChain = false; initParameters.GPUFrameLatency = CVars::r_gpu_latency.GetUInt(); // fill platform if (!NameTable_TranslateType(NameTables::RendererPlatform, CVars::r_platform.GetString(), &initParameters.Platform, true)) { initParameters.Platform = Renderer::GetDefaultPlatform(); Log_ErrorPrintf("Invalid renderer platform: '%s', defaulting to %s", CVars::r_platform.GetString().GetCharArray(), NameTable_GetNameString(NameTables::RendererPlatform, initParameters.Platform)); } // determine w/h to use, windowed fullscreen uses desktop size, ie (0, 0) if (CVars::r_fullscreen.GetBool() && CVars::r_fullscreen_exclusive.GetBool()) { initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_FULLSCREEN; initParameters.ImplicitSwapChainWidth = CVars::r_fullscreen_width.GetUInt(); initParameters.ImplicitSwapChainHeight = CVars::r_fullscreen_height.GetUInt(); } else if (CVars::r_fullscreen.GetBool()) { initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN; initParameters.ImplicitSwapChainWidth = 0; initParameters.ImplicitSwapChainHeight = 0; } else { initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED; initParameters.ImplicitSwapChainWidth = CVars::r_windowed_width.GetUInt(); initParameters.ImplicitSwapChainHeight = CVars::r_windowed_height.GetUInt(); } // todo: vsync initParameters.ImplicitSwapChainVSyncType = RENDERER_VSYNC_TYPE_NONE; // HTML5 does not support threads. // It also has no concept of windows, so force fullscreen. #ifdef Y_PLATFORM_HTML5 int canvasWidth, canvasHeight, canvasFullscreen; emscripten_get_canvas_size(&canvasWidth, &canvasHeight, &canvasFullscreen); initParameters.EnableThreadedRendering = false; initParameters.ImplicitSwapChainWidth = (uint32)canvasWidth; initParameters.ImplicitSwapChainHeight = (uint32)canvasHeight; initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED; #endif // create renderer if (!Renderer::Create(&initParameters)) { // try some sensible defaults Log_ErrorPrintf("Renderer creation failed with specified parameters. Trying fallback."); initParameters.Platform = Renderer::GetDefaultPlatform(); initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED; initParameters.ImplicitSwapChainWidth = 640; initParameters.ImplicitSwapChainHeight = 480; initParameters.ImplicitSwapChainVSyncType = RENDERER_VSYNC_TYPE_NONE; // create again if (!Renderer::Create(&initParameters)) { Panic("Failed to create renderer with fallback parameters."); return false; } } // initialize imgui bool renderThreadResult = false; QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, &renderThreadResult]() { // store variables m_pGPUContext = g_pRenderer->GetGPUContext(); m_pOutputWindow = g_pRenderer->GetImplicitOutputWindow(); // get actual viewport dimensions uint32 bufferWidth = m_pOutputWindow->GetOutputBuffer()->GetWidth(); uint32 bufferHeight = m_pOutputWindow->GetOutputBuffer()->GetHeight(); // initialize remaining resources m_guiContext.SetGPUContext(m_pGPUContext); m_guiContext.SetViewportDimensions(bufferWidth, bufferHeight); m_fpsCounter.SetGPUContext(m_pGPUContext); m_fpsCounter.CreateGPUResources(); // imgui #ifdef WITH_IMGUI if (!ImGui::InitializeBridge()) { Log_ErrorPrintf("Failed to initialize ImGui bridge"); return; } #endif // create world renderer WorldRenderer::Options renderOptions; renderOptions.InitFromCVars(); renderOptions.SetRenderResolution(bufferWidth, bufferHeight); m_pWorldRenderer = WorldRenderer::Create(m_pGPUContext, &renderOptions); if (m_pWorldRenderer == nullptr) { Log_ErrorPrintf("Failed to create world renderer instance."); #ifdef WITH_IMGUI ImGui::FreeResources(); #endif return; } // init world renderer m_pWorldRenderer->SetGUIContext(&m_guiContext); // done renderThreadResult = true; }); if (!renderThreadResult) { m_pOutputWindow = nullptr; m_pGPUContext = nullptr; g_pRenderer->Shutdown(); return false; } // done return true; } void BaseGame::RenderThreadRestartRenderer() { // free existing world renderer delete m_pWorldRenderer; m_pWorldRenderer = nullptr; // get state bool modeChanged = (CVars::r_fullscreen.IsChangePending() | CVars::r_fullscreen_exclusive.IsChangePending() | CVars::r_fullscreen_width.IsChangePending() | CVars::r_fullscreen_height.IsChangePending() | CVars::r_windowed_width.IsChangePending() | CVars::r_windowed_height.IsChangePending()); // apply pending cvars g_pConsole->ApplyPendingRenderCVars(); // was a mode change pending? if (modeChanged) { RENDERER_FULLSCREEN_STATE fullscreenState; uint32 newWidth, newHeight; if (CVars::r_fullscreen.GetBool() && CVars::r_fullscreen_exclusive.GetBool()) { fullscreenState = RENDERER_FULLSCREEN_STATE_FULLSCREEN; newWidth = CVars::r_fullscreen_width.GetUInt(); newHeight = CVars::r_fullscreen_height.GetUInt(); } else if (CVars::r_fullscreen.GetBool()) { fullscreenState = RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN; newWidth = 0; newHeight = 0; } else { fullscreenState = RENDERER_FULLSCREEN_STATE_WINDOWED; newWidth = CVars::r_windowed_width.GetUInt(); newHeight = CVars::r_windowed_height.GetUInt(); } // switch modes if (!g_pRenderer->ChangeResolution(fullscreenState, newWidth, newHeight, 60)) Log_ErrorPrintf("Failed to change resolutions."); } // process any pending events due to window changes RenderThreadCollectEvents(0.0f); // get actual viewport dimensions uint32 bufferWidth = m_pOutputWindow->GetOutputBuffer()->GetWidth(); uint32 bufferHeight = m_pOutputWindow->GetOutputBuffer()->GetHeight(); // set render options WorldRenderer::Options renderOptions; renderOptions.InitFromCVars(); renderOptions.SetRenderResolution(bufferWidth, bufferHeight); // allocate new renderer m_pWorldRenderer = WorldRenderer::Create(m_pGPUContext, &renderOptions); if (m_pWorldRenderer == nullptr) { Panic("Failed to create world renderer instance."); return; } // update gui context dimensions m_guiContext.SetViewportDimensions(bufferWidth, bufferHeight); m_pWorldRenderer->SetGUIContext(&m_guiContext); // update imgui #ifdef WITH_IMGUI ImGui::SetViewportDimensions(bufferWidth, bufferHeight); #endif } void BaseGame::RenderThreadFrame(float deltaTime) { MICROPROFILE_SCOPEI("BaseGame", "RenderThreadFrame", MICROPROFILE_COLOR(50, 50, 180)); MICROPROFILE_SCOPEGPUI("RenderThreadFrame", MICROPROFILE_COLOR(50, 50, 180)); // reset counters g_pRenderer->GetCounters()->ResetPerFrameCounters(); // collect events { MICROPROFILE_SCOPEI("BaseGame", "RenderThreadCollectEvents", MICROPROFILE_COLOR(255, 255, 100)); RenderThreadCollectEvents(deltaTime); } // pre frame { MICROPROFILE_SCOPEI("BaseGame", "OnRenderThreadPreFrame", MICROPROFILE_COLOR(255, 100, 255)); OnRenderThreadPreFrame(deltaTime); } // restart the renderer if a request is queued if (m_restartRendererFlag) { m_restartRendererFlag = false; RenderThreadRestartRenderer(); } // signal to the main thread that events are ready if (Renderer::HasRenderThread()) m_renderThreadEventsReadyEvent.Signal(); // clear the backbuffer/depth buffer, this is mainly as a help to tilers { MICROPROFILE_SCOPEI("BaseGame", "Begin GPU Frame", MICROPROFILE_COLOR(200, 50, 50)); m_pGPUContext->BeginFrame(); } // begin frame helper { MICROPROFILE_SCOPEI("BaseGame", "OnRenderThreadBeginFrame", MICROPROFILE_COLOR(255, 100, 255)); OnRenderThreadBeginFrame(deltaTime); } #ifdef WITH_IMGUI // imgui stuff if (m_imGuiEnabled) ImGui::NewFrame(deltaTime); #endif // call event { MICROPROFILE_SCOPEI("BaseGame", "OnRenderThreadDraw", MICROPROFILE_COLOR(255, 100, 100)); OnRenderThreadDraw(deltaTime); } // draw overlays { MICROPROFILE_SCOPEI("BaseGame", "RenderThreadDrawOverlays", MICROPROFILE_COLOR(100, 200, 100)); RenderThreadDrawOverlays(deltaTime); } // end frame { MICROPROFILE_SCOPEI("BaseGame", "OnRenderThreadEndFrame", MICROPROFILE_COLOR(100, 20, 30)); OnRenderThreadEndFrame(deltaTime); } // clear state of context, and swap buffers { MICROPROFILE_SCOPEI("BaseGame", "SwapBuffers", MICROPROFILE_COLOR(100, 255, 100)); m_pGPUContext->ClearState(true, true, true, true); m_pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); /* @TODO */ } // end of render thread's work m_fpsCounter.EndRenderThreadFrame(); // signal to the main thread that we have completed the frame if (Renderer::HasRenderThread()) m_renderThreadFrameCompleteEvent.Signal(); } void BaseGame::RenderThreadDrawOverlays(float deltaTime) { const int32 PANEL_MARGIN = 4; const int32 viewportWidth = (int32)m_guiContext.GetViewportWidth(); const int32 viewportHeight = (int32)m_guiContext.GetViewportHeight(); MINIGUI_RECT rect; UNREFERENCED_PARAMETER(viewportWidth); UNREFERENCED_PARAMETER(viewportHeight); // fire off any outstanding draw requests using the old state m_guiContext.Flush(); // engine overlays are always drawn over everything else, taking up the whole screen. m_pGPUContext->SetRenderTargets(0, nullptr, nullptr); m_pGPUContext->SetFullViewport(); // batch stuff m_guiContext.PushManualFlush(); // draw fps counter // draw panel outline for fps counter rect.Set(viewportWidth - 380 - PANEL_MARGIN, viewportWidth, 0, 96 + PANEL_MARGIN); m_guiContext.SetAlphaBlendingEnabled(true); m_guiContext.SetAlphaBlendingMode(MiniGUIContext::ALPHABLENDING_MODE_STRAIGHT); m_guiContext.PushRect(&rect); rect.Set(0, rect.right - rect.left, 0, rect.bottom - rect.top); m_guiContext.DrawFilledRect(&rect, MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 100)); m_fpsCounter.DrawDetails(g_pRenderer->GetFixedResources()->GetDebugFont(), &m_guiContext, PANEL_MARGIN, 0); // extended stuff { WorldRenderer::RenderStats rs; m_pWorldRenderer->GetRenderStats(&rs); m_guiContext.DrawFormattedTextAt(PANEL_MARGIN, 48, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), "frame: %u dropped: %u", g_pRenderer->GetCounters()->GetFrameNumber(), g_pRenderer->GetCounters()->GetFramesDroppedCounter()); m_guiContext.DrawFormattedTextAt(PANEL_MARGIN, 64, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), "objects drawn: %u (%u culled)", rs.ObjectCount, rs.ObjectsCulledByOcclusion); m_guiContext.DrawFormattedTextAt(PANEL_MARGIN, 80, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), "dlights: %u (%u shadow maps)", rs.LightCount, rs.ShadowMapCount); m_guiContext.DrawFormattedTextAt(PANEL_MARGIN, 96, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), "buffers: %u (vram: %s)", rs.IntermediateBufferCount, StringConverter::SizeToHumanReadableString(rs.IntermediateBufferMemoryUsage).GetCharArray()); } // done m_guiContext.PopRect(); // update&draw overlay console m_pOverlayConsole->Update(deltaTime); m_pOverlayConsole->Draw(&m_guiContext); // unbatch and reset state m_guiContext.Flush(); m_guiContext.PopManualFlush(); m_guiContext.ClearState(); #ifdef WITH_PROFILER // profiler Profiling::DrawDisplay(); // in case an event killed us if (m_profilerInterceptMouseEvents && !Profiling::IsProfilerDisplayEnabled()) { PopForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = false; } #endif #ifdef WITH_IMGUI if (m_imGuiEnabled) { MICROPROFILE_SCOPEI("ImGui", "Draw", MICROPROFILE_COLOR(128, 50, 75)); // draw imgui RenderThreadDrawImGuiOverlays(); ImGui::Render(); } #endif } void BaseGame::RendererShutdown() { delete m_pWorldRenderer; m_pWorldRenderer = nullptr; #ifdef WITH_IMGUI ImGui::FreeResources(); #endif m_fpsCounter.ReleaseGPUResources(); g_pResourceManager->ReleaseDeviceResources(); m_pOutputWindow = nullptr; m_pGPUContext = nullptr; g_pRenderer->Shutdown(); } void BaseGame::MainThreadGameLoop(bool isModal) { // loop while (!m_quitFlag) MainThreadGameLoopIteration(); // if there's a game state stack, we need to end all modals while (!m_gameStateStack.IsEmpty()) { EndModalGameState(); MainThreadGameLoopIteration(); } // if there was a next game state, nuke it if (m_pNextGameState != nullptr) { m_pNextGameState->OnBeforeDelete(); delete m_pNextGameState; m_pNextGameState = nullptr; } // delete the current game state m_pGameState->OnSwitchedOut(); m_pGameState->OnBeforeDelete(); delete m_pGameState; m_pGameState = nullptr; } void BaseGame::MainThreadGameLoopIteration() { // handle gamestate changes if (m_pNextGameState != nullptr) { // switching to modal? if (m_nextGameStateIsModal) { // can't start modal with no game state. push the current to the modal stack DebugAssert(m_pGameState != nullptr); m_pGameState->OnSwitchedOut(); m_gameStateStack.Add(m_pGameState); // relative mouse movement should be disabled DebugAssert(!m_relativeMouseMovement); // switch to the new modal state Log_DevPrintf("BaseGame::MainThreadGameLoopIteration: Switching to modal game state %p", m_pNextGameState); m_pGameState = m_pNextGameState; m_pNextGameState = nullptr; m_nextGameStateIsModal = false; // run callbacks m_pGameState->OnSwitchedIn(); } else { // currently have a gamestate? if (m_pGameState != nullptr) { // nuke the current game state m_pGameState->OnSwitchedOut(); m_pGameState->OnBeforeDelete(); delete m_pGameState; // relative mouse movement should be disabled DebugAssert(!m_relativeMouseMovement); } // set new game state Log_DevPrintf("BaseGame::MainThreadGameLoopIteration: Switching to game state %p", m_pNextGameState); m_pGameState = m_pNextGameState; m_pNextGameState = nullptr; // run callbacks m_pGameState->OnSwitchedIn(); } } // sanity check here if (m_pGameState == nullptr) Panic("No game state. Unable to continue."); // update stats m_fpsCounter.BeginFrame(); // calculate time since last frame float deltaTime = (float)m_frameTimer.GetTimeSeconds(); m_frameTimer.Reset(); // pre-frame tasks OnMainThreadPreFrame(deltaTime); // using threaded rendering? if (Renderer::HasRenderThread()) { // kick off render thread first QUEUE_RENDERER_LAMBDA_COMMAND([this, deltaTime]() { RenderThreadFrame(deltaTime); }); // run the main thread MainThreadFrame(deltaTime); // wait for the render thread to finish, this is an event so as not to block the render thread as well m_renderThreadFrameCompleteEvent.Wait(); } else { // not using render thread, we run in a different order (process logic, then render, to reduce wait-for-vsync stalls) MainThreadFrame(deltaTime); RenderThreadFrame(deltaTime); Renderer::GetCommandQueue()->ExecuteQueuedTasks(); } // end of this modal state? if (m_gameStateEndModal) { // we should have a game state stack DebugAssert(!m_gameStateStack.IsEmpty()); m_gameStateEndModal = false; // switch out the modal state and nuke it Log_DevPrintf("BaseGame::MainThreadGameLoopIteration: Modal game state %p ending", m_pGameState); m_pGameState->OnSwitchedOut(); m_pGameState->OnBeforeDelete(); delete m_pGameState; // relative mouse movement should be disabled DebugAssert(!m_relativeMouseMovement); // restore the last game state Log_DevPrintf("BaseGame::MainThreadGameLoopIteration: Restoring game state %p", m_gameStateStack.LastElement()); m_pGameState = m_gameStateStack.PopBack(); m_pGameState->OnSwitchedIn(); } // end frame #ifdef WITH_PROFILER Profiling::EndFrame(); #endif } #ifdef Y_PLATFORM_HTML5 void BaseGame::HTML5FrameTrampoline(void *pParam) { BaseGame *pBaseGame = reinterpret_cast<BaseGame *>(pParam); pBaseGame->MainThreadGameLoopIteration(); } #endif int32 BaseGame::MainEntryPoint() { // guard in case something calls this function static bool __mainEntered = false; DebugAssert(__mainEntered == false); __mainEntered = true; // initialization timer Timer initTimer; int32 exitCode = 0; // initialize SDL first if (SDL_Init(0) < 0) { CriticalError("SDL initialization failed: %s", SDL_GetError()); exitCode = -1; goto RETURN_LABEL; } // print version info { Y_CPUID_RESULT CPUIDResult; Y_ReadCPUID(&CPUIDResult); Log_DevPrint("Build Configuration: " Y_BUILD_CONFIG_STR); Log_DevPrint("Build Platform: " Y_PLATFORM_STR); Log_DevPrint("Build Architecture: " Y_CPU_STR Y_CPU_FEATURES_STR); Log_DevPrintf("Running on CPU: %s", CPUIDResult.SummaryString); } // initialize vfs Log_InfoPrint("Initializing virtual file system..."); if (!g_pVirtualFileSystem->Initialize()) { CriticalError("Virtual file system initialization failed. Cannot continue."); exitCode = -2; goto SHUTDOWN_SDL_LABEL; } // add types Log_InfoPrint("Registering types..."); g_pEngine->RegisterEngineTypes(); OnRegisterTypes(); // fix this... if (!g_pEngine->Startup()) { exitCode = -3; goto SHUTDOWN_VFS_LABEL; } // start renderer Log_InfoPrint("Starting renderer..."); if (!RendererStart()) { CriticalError("Failed to start renderer."); exitCode = -4; goto SHUTDOWN_RESOURCES_LABEL; } // start input system Log_InfoPrint("Starting input subsystem..."); if (!g_pInputManager->Startup()) { CriticalError("Failed to start input subsystem."); exitCode = -5; goto SHUTDOWN_RENDERER_LABEL; } // start script subsystem Log_InfoPrint("Starting script subsystem..."); if (!g_pScriptManager->Startup()) { CriticalError("Failed to start script subsystem."); exitCode = -6; goto SHUTDOWN_INPUT_LABEL; } #ifdef WITH_PROFILER // initialize profiler Log_InfoPrintf("Initializing profiler..."); Profiling::Initialize(); Profiling::SetProfilerEnabled(true); #endif // everything started Log_InfoPrintf("All engine subsystems initialized in %.2f msec", initTimer.GetTimeMilliseconds()); // initialize game initTimer.Reset(); Log_InfoPrint("Initializing game..."); if (!OnStart()) { CriticalError("Failed to initialize game."); exitCode = -999; goto SHUTDOWN_SCRIPT_LABEL; } #ifndef Y_PLATFORM_HTML5 // run game loop MainThreadGameLoop(false); #else // kick html5 frame off emscripten_set_main_loop_arg(HTML5FrameTrampoline, this, 0, 1); #endif // shut down game Log_InfoPrint("Shutting down game..."); OnExit(); // begin shutting down Log_InfoPrint("Shutting down all subsystems..."); initTimer.Reset(); SHUTDOWN_SCRIPT_LABEL: // shutdown script subsystem Log_InfoPrint("Shutting down script subsystem..."); g_pScriptManager->Shutdown(); SHUTDOWN_INPUT_LABEL: // shutdown input subsystem Log_InfoPrint("Shutting down input subsystem..."); g_pInputManager->Shutdown(); SHUTDOWN_RENDERER_LABEL: // shutdown renderer Log_InfoPrint("Shutting down renderer..."); RendererShutdown(); SHUTDOWN_RESOURCES_LABEL: // release resources Log_InfoPrint("Unloading resources..."); g_pResourceManager->ReleaseResources(); g_pEngine->Shutdown(); SHUTDOWN_VFS_LABEL: // shutdown vfs g_pVirtualFileSystem->Shutdown(); SHUTDOWN_SDL_LABEL: SDL_Quit(); RETURN_LABEL: if (exitCode == 0) Log_InfoPrintf("All engine subsystems shutdown in %.2f msec", initTimer.GetTimeMilliseconds()); return 0; } #ifdef WITH_IMGUI void BaseGame::ActivateImGui() { QUEUE_RENDERER_LAMBDA_COMMAND([this]() { if ((m_imGuiEnabled++) == 0) { // calls to imgui will fail without this. deliberately not calling our wrapper. PushForcedAbsoluteMouseMovement(); ImGui::NewFrame(); } }); } void BaseGame::DeactivateImGui() { QUEUE_RENDERER_LAMBDA_COMMAND([this]() { DebugAssert(m_imGuiEnabled > 0); if (--m_imGuiEnabled == 0) PopForcedAbsoluteMouseMovement(); }); } void BaseGame::OpenDebugRenderMenu() { QUEUE_RENDERER_LAMBDA_COMMAND([this]() { if (!m_showDebugRenderMenu) { m_showDebugRenderMenu = true; ActivateImGui(); } }); } void BaseGame::RenderThreadDrawImGuiOverlays() { // debug menu if (m_showDebugRenderMenu) { ImGui::SetNextWindowSize(ImVec2(460, 450), ImGuiSetCond_Once); ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiSetCond_Once); bool closed = false; if (ImGui::Begin("Render Debug", &closed, ImGuiWindowFlags_NoCollapse)) { int intValue; bool boolValue; ImGui::PushItemWidth(-140.0f); if (ImGui::CollapsingHeader("Display", nullptr, true, true)) { ImGui::PushItemWidth(160.0f); ImGui::Text("Mode: "); ImGui::SameLine(); intValue = (int)CVars::r_fullscreen.GetPendingBool(); if (intValue) intValue += (int)CVars::r_fullscreen_exclusive.GetPendingBool(); if (ImGui::Combo("##mode", &intValue, "Windowed\0Windowed Fullscreen\0Exclusive Fullscreen\0\0")) { g_pConsole->SetCVar(&CVars::r_fullscreen, intValue != 0); g_pConsole->SetCVar(&CVars::r_fullscreen_exclusive, intValue > 1); } ImGui::PopItemWidth(); if (intValue != 1) { ImGui::PushItemWidth(80.0f); ImGui::Text("Resolution: "); ImGui::SameLine(); if (intValue == 0) { intValue = CVars::r_windowed_width.GetPendingInt(); if (ImGui::InputInt("##windowed_width", &intValue)) g_pConsole->SetCVar(&CVars::r_windowed_width, intValue); ImGui::SameLine(); intValue = CVars::r_windowed_height.GetPendingInt(); if (ImGui::InputInt("##windowed_height", &intValue)) g_pConsole->SetCVar(&CVars::r_windowed_height, intValue); } else if (intValue == 2) { intValue = CVars::r_fullscreen_width.GetPendingInt(); if (ImGui::InputInt("##fullscreen_width", &intValue)) g_pConsole->SetCVar(&CVars::r_fullscreen_width, intValue); ImGui::SameLine(); intValue = CVars::r_fullscreen_height.GetPendingInt(); if (ImGui::InputInt("##fullscreen_height", &intValue)) g_pConsole->SetCVar(&CVars::r_fullscreen_height, intValue); } ImGui::PopItemWidth(); } if (ImGui::Button("Update")) QueueRendererRestart(); } if (ImGui::CollapsingHeader("Render Settings", nullptr, true, true)) { // shadows boolValue = CVars::r_multithreaded_rendering.GetBool(); if (ImGui::Checkbox("Multithreaded Rendering", &boolValue)) { g_pConsole->SetCVar(&CVars::r_multithreaded_rendering, boolValue); QueueRendererRestart(); } // shadows boolValue = CVars::r_deferred_shading.GetBool(); if (ImGui::Checkbox("Deferred Shading", &boolValue)) { g_pConsole->SetCVar(&CVars::r_deferred_shading, boolValue); QueueRendererRestart(); } // shadows intValue = CVars::r_shadows.GetInt(); if (ImGui::Text("Dynamic shadows: "), ImGui::SameLine(), ImGui::Combo("##dynamic_shadows", &intValue, "No shadows\0All shadows\0Directional shadows only\0\0")) { g_pConsole->SetCVar(&CVars::r_shadows, intValue); QueueRendererRestart(); } // shadows intValue = CVars::r_shadow_filtering.GetBool(); if (ImGui::Text("Shadow filtering: "), ImGui::SameLine(), ImGui::Combo("##shadow_filtering", &intValue, "No filtering\0""3x3 filter\0""5x5 filter\0\0")) { g_pConsole->SetCVar(&CVars::r_shadow_filtering, intValue); QueueRendererRestart(); } // shadows boolValue = CVars::r_shadow_use_hardware_pcf.GetBool(); if (ImGui::Checkbox("Use hardware pcf", &boolValue)) { g_pConsole->SetCVar(&CVars::r_shadow_use_hardware_pcf, boolValue); QueueRendererRestart(); } // ssao boolValue = CVars::r_ssao.GetBool(); if (ImGui::Checkbox("SSAO", &boolValue)) { g_pConsole->SetCVar(&CVars::r_ssao, boolValue); QueueRendererRestart(); } // occlusion culling boolValue = CVars::r_occlusion_culling.GetBool(); if (ImGui::Checkbox("Occlusion Culling", &boolValue)) { g_pConsole->SetCVar(&CVars::r_occlusion_culling, boolValue); QueueRendererRestart(); } // wait for results boolValue = CVars::r_occlusion_culling_wait_for_results.GetBool(); if (ImGui::Checkbox("Wait for occlusion results", &boolValue)) { g_pConsole->SetCVar(&CVars::r_occlusion_culling_wait_for_results, boolValue); QueueRendererRestart(); } // predication boolValue = CVars::r_occlusion_prediction.GetBool(); if (ImGui::Checkbox("Occlusion Predication", &boolValue)) { g_pConsole->SetCVar(&CVars::r_occlusion_prediction, boolValue); QueueRendererRestart(); } } if (ImGui::CollapsingHeader("Debugging", nullptr, true, true)) { // wireframe boolValue = CVars::r_wireframe.GetBool(); if (ImGui::Checkbox("Render Wireframe", &boolValue)) { g_pConsole->SetCVar(&CVars::r_wireframe, boolValue); QueueRendererRestart(); } // fullbright boolValue = CVars::r_fullbright.GetBool(); if (ImGui::Checkbox("Render Fullbright", &boolValue)) { g_pConsole->SetCVar(&CVars::r_fullbright, boolValue); QueueRendererRestart(); } // normals boolValue = CVars::r_debug_normals.GetBool(); if (ImGui::Checkbox("Render Normals", &boolValue)) { g_pConsole->SetCVar(&CVars::r_debug_normals, boolValue); QueueRendererRestart(); } // show buffers boolValue = CVars::r_show_buffers.GetBool(); if (ImGui::Checkbox("Show GBuffers", &boolValue)) { g_pConsole->SetCVar(&CVars::r_show_buffers, boolValue); QueueRendererRestart(); } // show cascades boolValue = CVars::r_show_cascades.GetBool(); if (ImGui::Checkbox("Show Cascades", &boolValue)) { g_pConsole->SetCVar(&CVars::r_show_cascades, boolValue); QueueRendererRestart(); } } ImGui::PopItemWidth(); if (ImGui::CollapsingHeader("Frame time history", nullptr, true, true)) { ImGui::PushItemWidth(-120.0f); float frameTimes[60]; m_fpsCounter.GetFrameTimeHistory(frameTimes, countof(frameTimes)); ImGui::PlotLines("", frameTimes, countof(frameTimes), 0, nullptr, FLT_MAX, FLT_MAX, ImVec2(0.0f, 44.0f)); float minTime = Y_FLT_MAX, maxTime = Y_FLT_MIN, avgTime = 0.0f; for (uint32 i = 0; i < countof(frameTimes); i++) { minTime = Min(minTime, frameTimes[i]); maxTime = Max(maxTime, frameTimes[i]); avgTime += frameTimes[i]; } avgTime /= (float)countof(frameTimes); ImGui::SameLine(); ImGui::Text("Min: %.4fms\nMax: %.4fms\nAvg: %.4fms", minTime * 1000.0f, maxTime * 1000.0f, avgTime * 1000.0f); ImGui::PopItemWidth(); } if (closed) { // render debug window closed, only way it could've been activated was from the command, so hide a level of imgui m_showDebugRenderMenu = false; DeactivateImGui(); } } ImGui::End(); } } #endif // WITH_IMGUI #ifdef WITH_PROFILER void BaseGame::SetProfilerDisplayMode(uint32 mode) { Profiling::SetProfilerDisplay(mode); if (Profiling::IsProfilerDisplayEnabled()) { // requires intercepting input events if (!m_profilerInterceptMouseEvents) { PushForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = true; } } else { // remove interception if (m_profilerInterceptMouseEvents) { PopForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = false; } } } void BaseGame::ToggleProfilerDisplay() { Profiling::ToggleProfilerDisplay(); if (Profiling::IsProfilerDisplayEnabled()) { // requires intercepting input events if (!m_profilerInterceptMouseEvents) { PushForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = true; } } else { // remove interception if (m_profilerInterceptMouseEvents) { PopForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = false; } } } void BaseGame::HideProfilerDisplay() { Profiling::SetProfilerDisplay(MP_DRAW_OFF); if (m_profilerInterceptMouseEvents) { PopForcedAbsoluteMouseMovement(); m_profilerInterceptMouseEvents = false; } } #endif // WITH_PROFILER <file_sep>/Engine/Source/ResourceCompiler/FontGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "ResourceCompiler/TextureGenerator.h" #include "Engine/Font.h" #include "Core/PixelFormat.h" #include "Core/Image.h" class ZipArchive; class FontGenerator { public: struct Character { uint32 CodePoint; uint32 PaddingX, PaddingY; int32 DrawOffsetX, DrawOffsetY; float Advance; bool IsWhitespace; Image *pContents; }; // helper to get the storage pixel format for the font type static PIXEL_FORMAT GetFontStoragePixelFormat(FONT_TYPE type); // helper to get the compiled pixel format for the font type static PIXEL_FORMAT GetCompiledPixelFormat(FONT_TYPE type); // helper for maximum texture dimensions static uint32 GetMaximumTextureDimension(); public: FontGenerator(); ~FontGenerator(); // accessors const FONT_TYPE GetType() const { return m_type; } const uint32 GetCharacterHeight() const { return m_characterHeight; } const bool GetUseTextureFiltering() const { return m_useTextureFiltering; } const bool GetGenerateMipmaps() const { return m_generateMipmaps; } // mutators void SetUseTextureFiltering(bool enabled) { m_useTextureFiltering = enabled; } void SetGenerateMipmaps(bool enabled) { m_generateMipmaps = enabled; } // getting character data const uint32 GetCharacterCount() const { return m_characters.GetSize(); } const Character *GetCharacterByIndex(uint32 index) const { return &m_characters[index]; } Character *GetCharacterByIndex(uint32 index) { return &m_characters[index]; } const Character *GetCharacterByCodePoint(uint32 codePoint) const; Character *GetCharacterByCodePoint(uint32 codePoint); // character management bool AddCharacter(uint32 codePoint, uint32 paddingX, uint32 paddingY, int32 drawOffsetX, int32 drawOffsetY, float advance, const Image *pContents); bool AddWhitespaceCharacter(uint32 codePoint, float advance); bool RemoveCharacter(uint32 codePoint); // loading/saving void Create(FONT_TYPE type, uint32 characterHeight); bool Load(const char *fileName, ByteStream *pStream); bool Save(ByteStream *pOutputStream) const; // compiling bool Compile(ByteStream *pOutputStream, TEXTURE_PLATFORM platform) const; private: // loading/saving bool LoadXML(ZipArchive *pArchive); bool LoadCharacters(ZipArchive *pArchive); bool SaveXML(ZipArchive *pArchive) const; bool SaveCharacters(ZipArchive *pArchive) const; FONT_TYPE m_type; uint32 m_characterHeight; bool m_useTextureFiltering; bool m_generateMipmaps; MemArray<Character> m_characters; }; <file_sep>/Engine/Source/Renderer/RendererStateBlock.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RendererStateBlock.h" RendererStateBlock::RendererStateBlock() { m_pGPUDevice = NULL; m_iCaptureFlags = 0; m_pSavedRasterizerState = NULL; m_pSavedDepthStencilState = 0; m_iSavedDepthStencilRef = 0; m_pSavedBlendState = NULL; m_SavedBlendStateBlendFactors.SetZero(); Y_memzero(m_pSavedRenderTargets, sizeof(m_pSavedRenderTargets)); m_nSavedRenderTargets = 0; m_pSavedDepthStencilBuffer = NULL; Y_memzero(m_pSavedVertexBuffers, sizeof(m_pSavedVertexBuffers)); Y_memzero(m_iSavedVertexBufferOffsets, sizeof(m_iSavedVertexBufferOffsets)); Y_memzero(m_iSavedVertexBufferStrides, sizeof(m_iSavedVertexBufferStrides)); m_nSavedVertexBuffers = 0; m_pSavedIndexBuffer = NULL; m_savedIndexFormat = GPU_INDEX_FORMAT_UINT16; m_iSavedIndexBufferOffset = 0; m_eSavedDrawTopology = DRAW_TOPOLOGY_TRIANGLE_LIST; Y_memzero(&m_SavedViewport, sizeof(m_SavedViewport)); Y_memzero(&m_SavedScissorRect, sizeof(m_SavedScissorRect)); m_SavedWorldMatrix.SetZero(); m_SavedViewMatrix.SetZero(); m_SavedProjectionMatrix.SetZero(); m_SavedEyePosition.SetZero(); } RendererStateBlock::~RendererStateBlock() { uint32 i; if (m_pGPUDevice != NULL) { uint32 captureFlags = m_iCaptureFlags; if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE) m_pSavedRasterizerState->Release(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE) m_pSavedDepthStencilState->Release(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE) m_pSavedBlendState->Release(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS) { for (i = 0; i < m_nSavedRenderTargets; i++) { if (m_pSavedRenderTargets[i] != NULL) m_pSavedRenderTargets[i]->Release(); } if (m_pSavedDepthStencilBuffer != NULL) { m_pSavedDepthStencilBuffer->Release(); m_pSavedDepthStencilBuffer = NULL; } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS) { for (i = 0; i < m_nSavedVertexBuffers; i++) { if (m_pSavedVertexBuffers[i] != NULL) m_pSavedVertexBuffers[i]->Release(); } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER) { if (m_pSavedIndexBuffer != NULL) m_pSavedIndexBuffer->Release(); } } } void RendererStateBlock::Capture(GPUContext *pGPUDevice, uint32 captureFlags) { uint32 i; DebugAssert(pGPUDevice != NULL); if (m_pGPUDevice != NULL) Clear(); m_pGPUDevice = pGPUDevice; m_iCaptureFlags = captureFlags; if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE) { if ((m_pSavedRasterizerState = pGPUDevice->GetRasterizerState()) != NULL) m_pSavedRasterizerState->AddRef(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE) { if ((m_pSavedDepthStencilState = pGPUDevice->GetDepthStencilState()) != NULL) m_pSavedDepthStencilState->AddRef(); m_iSavedDepthStencilRef = pGPUDevice->GetDepthStencilStateStencilRef(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE) { if ((m_pSavedBlendState = pGPUDevice->GetBlendState()) != NULL) m_pSavedBlendState->AddRef(); m_SavedBlendStateBlendFactors = pGPUDevice->GetBlendStateBlendFactor(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS) { m_nSavedRenderTargets = pGPUDevice->GetRenderTargets(countof(m_pSavedRenderTargets), m_pSavedRenderTargets, &m_pSavedDepthStencilBuffer); for (i = 0; i < m_nSavedRenderTargets; i++) { if (m_pSavedRenderTargets[i] != NULL) m_pSavedRenderTargets[i]->AddRef(); } if (m_pSavedDepthStencilBuffer != NULL) m_pSavedDepthStencilBuffer->AddRef(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS) { m_nSavedVertexBuffers = pGPUDevice->GetVertexBuffers(0, countof(m_pSavedVertexBuffers), m_pSavedVertexBuffers, m_iSavedVertexBufferOffsets, m_iSavedVertexBufferStrides); for (i = 0; i < m_nSavedVertexBuffers; i++) { if (m_pSavedVertexBuffers[i] != NULL) m_pSavedVertexBuffers[i]->AddRef(); } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER) { pGPUDevice->GetIndexBuffer(&m_pSavedIndexBuffer, &m_savedIndexFormat, &m_iSavedIndexBufferOffset); if (m_pSavedIndexBuffer != NULL) m_pSavedIndexBuffer->AddRef(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY) m_eSavedDrawTopology = pGPUDevice->GetDrawTopology(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS) Y_memcpy(&m_SavedViewport, pGPUDevice->GetViewport(), sizeof(m_SavedViewport)); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS) Y_memcpy(&m_SavedScissorRect, pGPUDevice->GetScissorRect(), sizeof(m_SavedScissorRect)); GPUContextConstants *pGPUConstants = pGPUDevice->GetConstants(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS) m_SavedWorldMatrix = pGPUConstants->GetLocalToWorldMatrix(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS) { m_SavedViewMatrix = pGPUConstants->GetCameraViewMatrix(); m_SavedProjectionMatrix = pGPUConstants->GetCameraProjectionMatrix(); m_SavedEyePosition = pGPUConstants->GetCameraEyePosition(); } } void RendererStateBlock::Restore() { if (m_pGPUDevice == NULL) return; GPUContext *pGPUDevice = m_pGPUDevice; uint32 captureFlags = m_iCaptureFlags; if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE) pGPUDevice->SetRasterizerState(m_pSavedRasterizerState); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE) pGPUDevice->SetDepthStencilState(m_pSavedDepthStencilState, m_iSavedDepthStencilRef); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE) pGPUDevice->SetBlendState(m_pSavedBlendState, m_SavedBlendStateBlendFactors); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS) pGPUDevice->SetRenderTargets(m_nSavedRenderTargets, m_pSavedRenderTargets, m_pSavedDepthStencilBuffer); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS) pGPUDevice->SetVertexBuffers(0, m_nSavedVertexBuffers, m_pSavedVertexBuffers, m_iSavedVertexBufferOffsets, m_iSavedVertexBufferStrides); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER) pGPUDevice->SetIndexBuffer(m_pSavedIndexBuffer, m_savedIndexFormat, m_iSavedIndexBufferOffset); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY) pGPUDevice->SetDrawTopology(m_eSavedDrawTopology); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS) pGPUDevice->SetViewport(&m_SavedViewport); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS) pGPUDevice->SetScissorRect(&m_SavedScissorRect); GPUContextConstants *pGPUConstants = pGPUDevice->GetConstants(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS) pGPUConstants->SetLocalToWorldMatrix(m_SavedWorldMatrix, false); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS) { pGPUConstants->SetCameraViewMatrix(m_SavedViewMatrix, false); pGPUConstants->SetCameraProjectionMatrix(m_SavedProjectionMatrix, false); pGPUConstants->SetCameraEyePosition(m_SavedEyePosition, false); } if (captureFlags & (GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS | GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS)) pGPUConstants->CommitChanges(); } void RendererStateBlock::Clear() { uint32 i; uint32 captureFlags = m_iCaptureFlags; if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE) { if (m_pSavedRasterizerState != NULL) { m_pSavedRasterizerState->Release(); m_pSavedRasterizerState = NULL; } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE) { if (m_pSavedDepthStencilState != NULL) { m_pSavedDepthStencilState->Release(); m_pSavedDepthStencilState = NULL; } m_iSavedDepthStencilRef = 0; } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_BLEND_STATE) { if (m_pSavedBlendState != NULL) { m_pSavedBlendState->Release(); m_pSavedBlendState = NULL; } m_SavedBlendStateBlendFactors.SetZero(); } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_RENDER_TARGETS) { for (i = 0; i < m_nSavedRenderTargets; i++) { if (m_pSavedRenderTargets[i] != NULL) { m_pSavedRenderTargets[i]->Release(); m_pSavedRenderTargets[i] = NULL; } } if (m_pSavedDepthStencilBuffer != NULL) { m_pSavedDepthStencilBuffer->Release(); m_pSavedDepthStencilBuffer = NULL; } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VERTEX_BUFFERS) { for (i = 0; i < m_nSavedVertexBuffers; i++) { if (m_pSavedVertexBuffers[i] != NULL) { m_pSavedVertexBuffers[i]->Release(); m_pSavedVertexBuffers[i] = NULL; m_iSavedVertexBufferOffsets[i] = 0; m_iSavedVertexBufferStrides[i] = 0; } } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_INDEX_BUFFER) { if (m_pSavedIndexBuffer != NULL) { m_pSavedIndexBuffer->Release(); m_pSavedIndexBuffer = NULL; m_savedIndexFormat = GPU_INDEX_FORMAT_UINT16; m_iSavedIndexBufferOffset = 0; } } if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_DRAW_TOPOLOGY) m_eSavedDrawTopology = DRAW_TOPOLOGY_TRIANGLE_LIST; if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_VIEWPORTS) Y_memzero(&m_SavedViewport, sizeof(m_SavedViewport)); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_SCISSOR_RECTS) Y_memzero(&m_SavedScissorRect, sizeof(m_SavedScissorRect)); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_OBJECT_CONSTANTS) m_SavedWorldMatrix.SetZero(); if (captureFlags & GPU_STATE_BLOCK_CAPTURE_FLAG_CAMERA_CONSTANTS) { m_SavedViewMatrix.SetZero(); m_SavedProjectionMatrix.SetZero(); m_SavedEyePosition.SetZero(); } m_pGPUDevice = NULL; m_iCaptureFlags = 0; } // void RendererStateBlock::SetSavedRasterizerState(GPURasterizerState *pRasterizerState) // { // if (m_pSavedRasterizerState == pRasterizerState) // return; // // if (m_pSavedRasterizerState == NULL) // m_pSavedRasterizerState->Release(); // // if ((m_pSavedRasterizerState = pRasterizerState) != NULL) // m_pSavedRasterizerState->AddRef(); // // m_iCaptureFlags |= GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE; // } // // void RendererStateBlock::SetSavedDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) // { // if (m_pSavedDepthStencilState != pDepthStencilState) // { // if (m_pSavedDepthStencilState == NULL) // m_pSavedDepthStencilState->Release(); // // if ((m_pSavedDepthStencilState = pDepthStencilState) != NULL) // m_pSavedDepthStencilState->AddRef(); // // m_iCaptureFlags |= GPU_STATE_BLOCK_CAPTURE_FLAG_RASTERIZER_STATE; // } // // if (m_iSavedDepthStencilRef != stencilRef) // { // m_iSavedDepthStencilRef = stencilRef; // m_iCaptureFlags |= GPU_STATE_BLOCK_CAPTURE_FLAG_DEPTHSTENCIL_STATE; // } // } <file_sep>/Engine/Source/Renderer/VertexFactories/LocalVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" enum LOCAL_VERTEX_FACTORY_FLAGS { LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS = (1 << 0), LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS = (1 << 1), LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS = (1 << 2), LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS = (1 << 3), LOCAL_VERTEX_FACTORY_FLAG_LIGHTMAP_TEXCOORD_STREAM = (1 << 4), LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX = (1 << 5), }; class LocalVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory, VertexFactory); public: struct Vertex { float3 Position; float3 Normal; float3 Tangent; float3 Binormal; float3 TexCoord; uint32 Color; }; struct InstanceTransform { float4 InstanceTransformMatrix0; float4 InstanceTransformMatrix1; float4 InstanceTransformMatrix2; }; public: static uint32 GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static bool CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray); static bool FillVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer); static void ShareVerticesBuffer(VertexBufferBindingArray *pDestinationVertexArray, VertexBufferBindingArray *pSourceVertexArray) { ShareBuffers(pDestinationVertexArray, pSourceVertexArray, 0); } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); }; <file_sep>/Engine/Source/GameFramework/BlockMeshComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/BlockMeshComponent.h" #include "Engine/ResourceManager.h" #include "Engine/Entity.h" #include "Engine/World.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Renderer/RenderWorld.h" DEFINE_COMPONENT_TYPEINFO(BlockMeshComponent); DEFINE_COMPONENT_GENERIC_FACTORY(BlockMeshComponent); BEGIN_COMPONENT_PROPERTIES(BlockMeshComponent) PROPERTY_TABLE_MEMBER("BlockMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetMeshName, NULL, PropertyCallbackSetMeshName, NULL, PropertyCallbackBlockMeshChanged, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(BlockMeshComponent, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(BlockMeshComponent, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(BlockMeshComponent, m_shadowFlags), NULL, NULL) END_COMPONENT_PROPERTIES() BlockMeshComponent::BlockMeshComponent(const ComponentTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pBlockMesh(nullptr), m_visible(true), m_collidable(false), m_shadowFlags(0), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } BlockMeshComponent::~BlockMeshComponent() { if (m_pCollisionObject != nullptr) m_pCollisionObject->Release(); if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pBlockMesh != nullptr) m_pBlockMesh->Release(); } void BlockMeshComponent::SetBlockMesh(const BlockMesh *pBlockMesh) { DebugAssert(pBlockMesh != nullptr); if (m_pBlockMesh == pBlockMesh) return; if (m_pBlockMesh != nullptr) m_pBlockMesh->Release(); m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); PropertyCallbackBlockMeshChanged(this); } void BlockMeshComponent::SetVisible(bool visible) { if (m_visible == visible) return; m_visible = visible; PropertyCallbackVisibleChanged(this); } void BlockMeshComponent::SetShadowFlags(uint32 shadowFlags) { if (m_shadowFlags == shadowFlags) return; m_shadowFlags = shadowFlags; if (m_pRenderProxy != nullptr) m_pRenderProxy->SetShadowFlags(shadowFlags); } void BlockMeshComponent::SetCollidable(bool collidable) { if (m_collidable == collidable) return; m_collidable = collidable; PropertyCallbackCollidableChanged(this); } void BlockMeshComponent::Create(const float3 &localPosition /* = float3::Zero */, const Quaternion &localRotation /* = Quaternion::Identity */, const float3 &localScale /* = float3::One */, const BlockMesh *pBlockMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_localPosition = localPosition; m_localRotation = localRotation; m_localScale = localScale; if (pBlockMesh != nullptr) { m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); } else { m_pBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; Initialize(); } bool BlockMeshComponent::Initialize() { if (!BaseClass::Initialize()) return false; DebugAssert(m_pBlockMesh != nullptr); if (m_visible) m_pRenderProxy = new BlockMeshRenderProxy(0, m_pBlockMesh, Transform::Identity, m_shadowFlags); if (m_collidable && m_pBlockMesh->GetCollisionShape() != nullptr) m_pCollisionObject = new Physics::StaticObject(0, m_pBlockMesh->GetCollisionShape(), Transform::Identity); return true; } void BlockMeshComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // calculate the transform Transform worldTransform(CalculateWorldTransform()); // update entity ids if (m_pRenderProxy != nullptr) { m_pRenderProxy->SetEntityID(pEntity->GetEntityID()); m_pRenderProxy->SetTransform(worldTransform); } if (m_pCollisionObject != nullptr) { m_pCollisionObject->SetEntityID(pEntity->GetEntityID()); m_pCollisionObject->SetTransform(worldTransform); } // add to world if (pEntity->IsInWorld()) { // add to physics + render world if (m_pCollisionObject != nullptr) pEntity->GetWorld()->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pEntity->GetWorld()->GetRenderWorld()->AddRenderable(m_pRenderProxy); } // update bounds, no need to notify the entity as it'll be recalculated when the add is complete SetBounds(worldTransform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()), false); } void BlockMeshComponent::OnRemoveFromEntity(Entity *pEntity) { if (pEntity->IsInWorld()) { if (m_pCollisionObject != nullptr) pEntity->GetWorld()->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pEntity->GetWorld()->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); } if (m_pRenderProxy != nullptr) m_pRenderProxy->SetEntityID(0); if (m_pCollisionObject != nullptr) m_pCollisionObject->SetEntityID(0); BaseClass::OnRemoveFromEntity(pEntity); } void BlockMeshComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void BlockMeshComponent::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } void BlockMeshComponent::OnLocalTransformChange() { BaseClass::OnLocalTransformChange(); // recalculate the world transform Transform worldTransform(CalculateWorldTransform()); // update proxies if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(worldTransform); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(worldTransform); // change bounding box SetBounds(worldTransform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()), true); } void BlockMeshComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // recalculate the world transform Transform worldTransform(CalculateWorldTransform()); // update proxies if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(worldTransform); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(worldTransform); // change bounding box SetBounds(worldTransform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()), true); } bool BlockMeshComponent::PropertyCallbackGetMeshName(ThisClass *pComponent, const void *pUserData, String *pValue) { pValue->Assign(pComponent->m_pBlockMesh->GetName()); return true; } bool BlockMeshComponent::PropertyCallbackSetMeshName(ThisClass *pComponent, const void *pUserData, const String *pValue) { const BlockMesh *pBlockMesh = g_pResourceManager->GetBlockMesh(*pValue); if (pBlockMesh == NULL) return false; if (pComponent->m_pBlockMesh != nullptr) pComponent->m_pBlockMesh->Release(); pComponent->m_pBlockMesh = pBlockMesh; return true; } void BlockMeshComponent::PropertyCallbackBlockMeshChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_visible) { DebugAssert(pComponent->m_pRenderProxy != nullptr); pComponent->m_pRenderProxy->SetBlockMesh(pComponent->m_pBlockMesh); } if (pComponent->m_collidable) { if (pComponent->m_pBlockMesh->GetCollisionShape() != nullptr) { if (pComponent->m_pCollisionObject != nullptr) { pComponent->m_pCollisionObject->SetCollisionShape(pComponent->m_pBlockMesh->GetCollisionShape()); } else { pComponent->m_pCollisionObject = new Physics::StaticObject((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pBlockMesh->GetCollisionShape(), pComponent->CalculateWorldTransform()); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->AddObject(pComponent->m_pCollisionObject); } } else { if (pComponent->m_pCollisionObject != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->RemoveObject(pComponent->m_pCollisionObject); pComponent->m_pCollisionObject->Release(); pComponent->m_pCollisionObject = nullptr; } } } } void BlockMeshComponent::PropertyCallbackVisibleChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_visible) { if (pComponent->m_pRenderProxy == nullptr) { pComponent->m_pRenderProxy = new BlockMeshRenderProxy((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pBlockMesh, pComponent->CalculateWorldTransform(), pComponent->m_shadowFlags); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetRenderWorld()->AddRenderable(pComponent->m_pRenderProxy); } } else { if (pComponent->m_pRenderProxy != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetRenderWorld()->RemoveRenderable(pComponent->m_pRenderProxy); pComponent->m_pRenderProxy->Release(); pComponent->m_pRenderProxy = nullptr; } } } void BlockMeshComponent::PropertyCallbackCollidableChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_collidable) { if (pComponent->m_pCollisionObject == nullptr && pComponent->m_pBlockMesh->GetCollisionShape() != nullptr) { pComponent->m_pCollisionObject = new Physics::StaticObject((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pBlockMesh->GetCollisionShape(), pComponent->CalculateWorldTransform()); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->AddObject(pComponent->m_pCollisionObject); } } else { if (pComponent->m_pCollisionObject != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->RemoveObject(pComponent->m_pCollisionObject); pComponent->m_pCollisionObject->Release(); pComponent->m_pCollisionObject = nullptr; } } } <file_sep>/Engine/Source/Core/ImageCodecBMP.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Log.h" Log_SetChannel(ImageCodecBMP); #pragma pack(push, 1) struct BMPHeader { uint16 Magic; uint32 FileLength; uint16 CreatorSpecific1; uint16 CreatorSpecific2; uint32 DataOffset; uint32 SecondHeaderSize; }; struct BMPHeader2 { int32 Width; int32 Height; uint16 Planes; uint16 BitCount; uint32 Compression; }; #pragma pack(pop) class ImageCodecBMP : public ImageCodec { public: const char *GetCodecName() const { return "BMP"; } bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyTable &decoderOptions = PropertyTable::EmptyPropertyList) { BMPHeader Header; if (pInputStream->Read(&Header, sizeof(BMPHeader)) != sizeof(BMPHeader)) return false; if (Header.SecondHeaderSize < sizeof(BMPHeader2)) return false; BMPHeader2 Header2; if (pInputStream->Read(&Header2, sizeof(BMPHeader2)) != sizeof(BMPHeader2)) return false; if (Header2.Width < 0 || Header2.Height < 0) { Log_ErrorPrintf("ImageCodecBMP::DecodeImage: Bottom-up currently unsupported."); return false; } // select appropriate pixel format PIXEL_FORMAT SelectedFormat; if (Header2.BitCount == 1) SelectedFormat = PIXEL_FORMAT_R8_UNORM; //else if (Header2.BitCount == 4) //else if (Header2.BitCount == 8) else if (Header2.BitCount == 24) SelectedFormat = PIXEL_FORMAT_R8G8B8_UNORM; else { Log_ErrorPrintf("ImageCodecBMP::DecodeImage: Unknown bpp %u", Header2.BitCount); return false; } // check compression format if (Header2.Compression != 0) { Log_ErrorPrintf("ImageCodecBMP::DecodeImage: Unknown compression %u", Header2.Compression); return false; } // seek to position in file if (!pInputStream->SeekAbsolute(sizeof(BMPHeader) + Header.DataOffset)) return false; // create the image pOutputImage->Create(SelectedFormat, Header2.Width, Header2.Height, 1); // calculate pitches uint32 BMPPitch = (Header2.Width * Header2.BitCount + 7) / 8; if (BMPPitch != pOutputImage->GetDataRowPitch()) { Log_ErrorPrintf("ImageCodecBMP::DecodeImage: Pitch mismatch between us and image: %u / %u", pOutputImage->GetDataRowPitch(), BMPPitch); return false; } byte *pOutData = pOutputImage->GetData(); // read rows int32 i; for (i = 0; i < Header2.Height; i++) { if (pInputStream->Read(pOutData, BMPPitch) != BMPPitch) break; pOutData += BMPPitch; } if (i != Header2.Height) Log_WarningPrintf("ImageCodecBMP::DecodeImage: Not all rows read."); return true; } bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyTable &encoderOptions = PropertyTable::EmptyPropertyList) { return false; } }; static ImageCodecBMP g_ImageCodecBMP; ImageCodec *__GetImageCodecBMP() { return &g_ImageCodecBMP; } <file_sep>/Engine/Source/Renderer/DecalManager.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" class Material; class RenderWorld; class GPUBuffer; class StaticDecalRenderProxy; class StaticDecal : private RenderProxy { friend class DecalManager; private: StaticDecal(const AABox &boundingBox, const Sphere &boundingSphere, const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance, float lifetime, uint32 entityID); StaticDecal(const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance, float lifetime, uint32 entityID); public: ~StaticDecal(); const float3 &GetPosition() const { return m_position; } const float3 &GetNormal() const { return m_normal; } const float2 &GetSize() const { return m_size; } const Material *GetMaterial() const { return m_pMaterial; } const float GetDrawDistance() const { return m_drawDistance; } const float GetLifeRemaining() const { return m_lifeRemaining; } private: virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; void Rebuild(const float3 &position, const float3 &normal, const float2 &size); private: float3 m_position; float3 m_normal; float2 m_size; const Material *m_pMaterial; float m_drawDistance; float m_lifeRemaining; typedef MemArray<LocalVertexFactory::Vertex> VertexArray; VertexArray m_vertices; GPUBuffer *m_pVertexBuffer; }; class DecalManager { public: public: DecalManager(RenderWorld *pRenderWorld); ~DecalManager(); // static decals StaticDecal *CreateStaticDecal(const float3 &position, const float3 &normal, const float2 &size, const Material *pMaterial, float drawDistance = Y_FLT_MAX, float lifetime = Y_FLT_INFINITE); void MoveStaticDecal(StaticDecal *pDecal, const float3 &position, const float3 &normal); void ResizeStaticDecal(StaticDecal *pDecal, const float3 &size); void RemoveStaticDecal(StaticDecal *pDecal); // static decal helper function StaticDecal *ProjectStaticDecal(const Ray &ray, const float2 &size, const Material *pMaterial, float drawDistance = Y_FLT_MAX, float lifetime = Y_FLT_INFINITE); // update void Tick(const float timeDifference); private: RenderWorld *m_pRenderWorld; typedef PODArray<StaticDecal *> StaticDecalArray; StaticDecalArray m_staticDecals; }; class DecalMeshGenerator { public: struct Triangle { struct Vertex { float3 Position; float2 TextureCoordinate; }; Vertex Vertices[3]; float3 Normal; }; struct Polygon { struct Vertex { float3 Position; float2 TextureCoordinate; }; MemArray<Vertex> Vertices; float3 Normal; }; public: DecalMeshGenerator(const float3 &position, const float3 &normal, const float width, const float height); ~DecalMeshGenerator(); const AABox &GetDecalBox() const { return m_decalBox; } const MemArray<Triangle> &GetDecalTriangles() const { return m_decalTriangles; } const AABox &GetBoundingBox() const { return m_boundingBox; } uint32 GenerateDecalTriangles(const RenderProxy::IntersectingTriangleArray &inputTriangles); private: void CalculateDecalFrame(); void CalculateDecalBox(); void CalculateBoundingBox(); void CalculateClippingPlanes(); void GenerateClippedTriangles(const RenderProxy::IntersectingTriangleArray &inputTriangles); float3 m_position; float3 m_normal; float m_width; float m_height; float m_depth; float3 m_rightVector; float3 m_upVector; AABox m_decalBox; Plane m_clippingPlanes[6]; MemArray<Polygon> m_clippedPolygons; MemArray<Triangle> m_decalTriangles; AABox m_boundingBox; };<file_sep>/Engine/Source/Engine/EntityTypeInfo.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/EntityTypeInfo.h" #include "Engine/Entity.h" EntityTypeInfo::EntityTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory, uint32 scriptFlags, const SCRIPT_FUNCTION_TABLE_ENTRY *pScriptFunctions) : ScriptObjectTypeInfo(TypeName, pParentTypeInfo, pPropertyDeclarations, pFactory, scriptFlags, pScriptFunctions) { } EntityTypeInfo::~EntityTypeInfo() { } void EntityTypeInfo::RegisterType() { if (m_iTypeIndex != INVALID_TYPE_INDEX) return; // register object stuff ObjectTypeInfo::RegisterType(); } void EntityTypeInfo::UnregisterType() { if (m_iTypeIndex != INVALID_TYPE_INDEX) { ObjectTypeInfo::UnregisterType(); } } <file_sep>/Engine/Source/Renderer/RenderProxies/DirectionalLightRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" DirectionalLightRenderProxy::DirectionalLightRenderProxy(uint32 entityId, bool enabled /* = true */, const float3 &lightColor /* = float3::One */, const float3 &ambientColor /* = float3::Zero */, uint32 shadowFlags /* = 0 */, const float3 &direction /* = float3::NegativeUnitZ */) : RenderProxy(entityId), m_enabled(enabled), m_lightColor(lightColor), m_ambientColor(ambientColor), m_shadowFlags(shadowFlags), m_direction(direction) { // set bounds. this is +/- float max, as a directional light will light *everything* in the level. SetBounds(AABox::MaxSize, Sphere::MaxSize); } DirectionalLightRenderProxy::~DirectionalLightRenderProxy() { } // !!!!!!!!!! // TODO: Move draw into DrawQueueEntry()! // !!!!!!!!!! void DirectionalLightRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // check enabled if (!m_enabled || !pRenderQueue->IsAcceptingLights()) return; RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY rcLight; rcLight.LightColor = PixelFormatHelpers::ConvertSRGBToLinear(m_lightColor); rcLight.AmbientColor = PixelFormatHelpers::ConvertSRGBToLinear(m_ambientColor); rcLight.Direction = m_direction; rcLight.ShadowFlags = m_shadowFlags; rcLight.ShadowMapIndex = -1; rcLight.Static = false; pRenderQueue->AddLight(&rcLight); } void DirectionalLightRenderProxy::SetEnabled(bool newEnabled) { if (!IsInWorld()) { m_enabled = newEnabled; } else { ReferenceCountedHolder<DirectionalLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newEnabled]() { pThis->m_enabled = newEnabled; }); } } void DirectionalLightRenderProxy::SetLightColor(const float3 &newColor) { if (!IsInWorld()) { m_lightColor = newColor; } else { ReferenceCountedHolder<DirectionalLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newColor]() { pThis->m_lightColor = newColor; }); } } void DirectionalLightRenderProxy::SetAmbientColor(const float3 &newColor) { if (!IsInWorld()) { m_ambientColor = newColor; } else { ReferenceCountedHolder<DirectionalLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newColor]() { pThis->m_ambientColor = newColor; }); } } void DirectionalLightRenderProxy::SetShadowFlags(uint32 newShadowFlags) { if (!IsInWorld()) { m_shadowFlags = newShadowFlags; } else { ReferenceCountedHolder<DirectionalLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newShadowFlags]() { pThis->m_shadowFlags = newShadowFlags; }); } } void DirectionalLightRenderProxy::SetDirection(const float3 &newDirection) { if (!IsInWorld()) { m_direction = newDirection; } else { ReferenceCountedHolder<DirectionalLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newDirection]() { pThis->m_direction = newDirection; }); } } <file_sep>/Engine/Source/Core/PropertyTable.cpp #include "Core/PrecompiledHeader.h" #include "Core/PropertyTable.h" #include "Core/PropertyTemplate.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "YBaseLib/StringConverter.h" #include "MathLib/StringConverters.h" PropertyTable::PropertyTable() { } PropertyTable::PropertyTable(const PropertyTable &copy) { for (PropertyHashTable::ConstIterator itr = copy.m_properties.Begin(); !itr.AtEnd(); itr.Forward()) m_properties.Insert(itr->Key, itr->Value); } PropertyTable::~PropertyTable() { } bool PropertyTable::GetPropertyValue(const char *propertyName, String *pValue) const { const PropertyHashTable::Member *pMember = m_properties.Find(propertyName); if (pMember != nullptr) { pValue->Assign(pMember->Value); return true; } return false; } const String *PropertyTable::GetPropertyValuePointer(const char *propertyName) const { const PropertyHashTable::Member *pMember = m_properties.Find(propertyName); return (pMember != nullptr) ? &pMember->Value : nullptr; } const char *PropertyTable::GetPropertyValueDefault(const char *propertyName, const char *defaultValue /*= ""*/) const { const PropertyHashTable::Member *pMember = m_properties.Find(propertyName); return (pMember != nullptr) ? pMember->Value.GetCharArray() : defaultValue; } const String &PropertyTable::GetPropertyValueDefaultString(const char *propertyName, const String &defaultValue /*= EmptyString*/) const { const PropertyHashTable::Member *pMember = m_properties.Find(propertyName); return (pMember != nullptr) ? pMember->Value : defaultValue; } const char *PropertyTable::InternalGetPropertyValue(const char *PropertyName) const { const PropertyHashTable::Member *pMember = m_properties.Find(PropertyName); return (pMember != nullptr) ? pMember->Value.GetCharArray() : nullptr; } String PropertyTable::InternalGetPropertyValueString(const char *PropertyName) const { const PropertyHashTable::Member *pMember = m_properties.Find(PropertyName); return (pMember != nullptr) ? pMember->Value : EmptyString; } void PropertyTable::SetPropertyValue(const char *PropertyName, const char *Value) { PropertyHashTable::Member *pMember = m_properties.Find(PropertyName); if (pMember != nullptr) { pMember->Value = Value; return; } m_properties.Insert(PropertyName, Value); } void PropertyTable::SetPropertyValueString(const char *PropertyName, const String &Value) { PropertyHashTable::Member *pMember = m_properties.Find(PropertyName); if (pMember != nullptr) { pMember->Value = Value; return; } m_properties.Insert(PropertyName, Value); } void PropertyTable::Create() { } void PropertyTable::CreateFromTemplate(const PropertyTemplate *pTemplate) { for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pProperty = pTemplate->GetPropertyDefinition(i); SetPropertyValueString(pProperty->GetName(), pProperty->GetDefaultValue()); } } void PropertyTable::CopyProperties(const PropertyTable *pTable) { for (PropertyHashTable::ConstIterator itr = pTable->m_properties.Begin(); !itr.AtEnd(); itr.Forward()) SetPropertyValueString(itr->Key, itr->Value); } void PropertyTable::Clear() { m_properties.Clear(); } #if defined(HAVE_LIBXML2) bool PropertyTable::LoadFromXML(XMLReader &xmlReader) { // read fields if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; int32 objectSelection; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { objectSelection = xmlReader.Select("property"); if (objectSelection < 0) return false; switch (objectSelection) { // property case 0: { const char *propertyName = xmlReader.FetchAttribute("name"); const char *propertyValue = xmlReader.FetchAttribute("value"); if (propertyName == NULL || propertyValue == NULL) { xmlReader.PrintError("incomplete property definition"); return false; } SetPropertyValue(propertyName, propertyValue); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } } } return true; } void PropertyTable::SaveToXML(XMLWriter &xmlWriter) const { // write properties for (PropertyHashTable::ConstIterator pitr = m_properties.Begin(); !pitr.AtEnd(); pitr.Forward()) { xmlWriter.StartElement("property"); xmlWriter.WriteAttribute("name", pitr->Key); xmlWriter.WriteAttribute("value", pitr->Value); xmlWriter.EndElement(); } } #endif // WITH_LIBXML2 bool PropertyTable::GetPropertyValueBool(const char *propertyName, bool *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToBool(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt8(const char *propertyName, int8 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToInt8(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt16(const char *propertyName, int16 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToInt16(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt32(const char *propertyName, int32 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToInt32(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt64(const char *propertyName, int64 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToInt64(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt8(const char *propertyName, uint8 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToUInt8(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt16(const char *propertyName, uint16 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToUInt16(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt32(const char *propertyName, uint32 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToUInt32(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt64(const char *propertyName, uint64 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToUInt64(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueFloat(const char *propertyName, float *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToFloat(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueDouble(const char *propertyName, double *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToDouble(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueColor(const char *propertyName, uint32 *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToColor(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt2(const char *propertyName, Vector2i *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector2i(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt3(const char *propertyName, Vector3i *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector3i(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueInt4(const char *propertyName, Vector4i *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector4i(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt2(const char *propertyName, Vector2u *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector2u(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt3(const char *propertyName, Vector3u *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector3u(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueUInt4(const char *propertyName, Vector4u *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector4u(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueFloat2(const char *propertyName, Vector2f *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector2f(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueFloat3(const char *propertyName, Vector3f *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector3f(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueFloat4(const char *propertyName, Vector4f *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToVector4f(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueQuaternion(const char *propertyName, Quaternion *pValue) const { const char *propertyValue = InternalGetPropertyValue(propertyName); if (propertyValue != NULL) { *pValue = StringConverter::StringToQuaternion(propertyValue); return true; } return false; } bool PropertyTable::GetPropertyValueDefaultBool(const char *propertyName, bool defaultValue /* = false */) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToBool(propertyValue) : defaultValue; } int8 PropertyTable::GetPropertyValueDefaultInt8(const char *propertyName, int8 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToInt8(propertyValue) : defaultValue; } int16 PropertyTable::GetPropertyValueDefaultInt16(const char *propertyName, int16 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToInt16(propertyValue) : defaultValue; } int32 PropertyTable::GetPropertyValueDefaultInt32(const char *propertyName, int32 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToInt32(propertyValue) : defaultValue; } int64 PropertyTable::GetPropertyValueDefaultInt64(const char *propertyName, int64 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToInt64(propertyValue) : defaultValue; } uint8 PropertyTable::GetPropertyValueDefaultUInt8(const char *propertyName, uint8 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToUInt8(propertyValue) : defaultValue; } uint16 PropertyTable::GetPropertyValueDefaultUInt16(const char *propertyName, uint16 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToUInt16(propertyValue) : defaultValue; } uint32 PropertyTable::GetPropertyValueDefaultUInt32(const char *propertyName, uint32 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToUInt32(propertyValue) : defaultValue; } uint64 PropertyTable::GetPropertyValueDefaultUInt64(const char *propertyName, uint64 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToUInt64(propertyValue) : defaultValue; } float PropertyTable::GetPropertyValueDefaultFloat(const char *propertyName, float defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToFloat(propertyValue) : defaultValue; } double PropertyTable::GetPropertyValueDefaultDouble(const char *propertyName, double defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToDouble(propertyValue) : defaultValue; } uint32 PropertyTable::GetPropertyValueDefaultColor(const char *propertyName, uint32 defaultValue /*= 0*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToColor(propertyValue) : defaultValue; } Vector2i PropertyTable::GetPropertyValueDefaultInt2(const char *propertyName, const Vector2i &defaultValue /*= int2::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector2i(propertyValue) : defaultValue; } Vector3i PropertyTable::GetPropertyValueDefaultInt3(const char *propertyName, const Vector3i &defaultValue /*= int3::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector3i(propertyValue) : defaultValue; } Vector4i PropertyTable::GetPropertyValueDefaultInt4(const char *propertyName, const Vector4i &defaultValue /*= int4::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector4i(propertyValue) : defaultValue; } Vector2u PropertyTable::GetPropertyValueDefaultUInt2(const char *propertyName, const Vector2u &defaultValue /*= uint2::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector2u(propertyValue) : defaultValue; } Vector3u PropertyTable::GetPropertyValueDefaultUInt3(const char *propertyName, const Vector3u &defaultValue /*= uint3::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector3u(propertyValue) : defaultValue; } Vector4u PropertyTable::GetPropertyValueDefaultUInt4(const char *propertyName, const Vector4u &defaultValue /*= uint4::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector4u(propertyValue) : defaultValue; } Vector2f PropertyTable::GetPropertyValueDefaultFloat2(const char *propertyName, const Vector2f &defaultValue /*= float2::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector2f(propertyValue) : defaultValue; } Vector3f PropertyTable::GetPropertyValueDefaultFloat3(const char *propertyName, const Vector3f &defaultValue /*= float3::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector3f(propertyValue) : defaultValue; } Vector4f PropertyTable::GetPropertyValueDefaultFloat4(const char *propertyName, const Vector4f &defaultValue /*= float4::Zero*/) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToVector4f(propertyValue) : defaultValue; } Quaternion PropertyTable::GetPropertyValueDefaultQuaternion(const char *propertyName, const Quaternion &defaultValue /* = Quaternion::Identity */) const { const char *propertyValue = InternalGetPropertyValue(propertyName); return (propertyValue != NULL) ? StringConverter::StringToQuaternion(propertyValue) : defaultValue; } // typed property writers void PropertyTable::SetPropertyValueBool(const char *propertyName, bool propertyValue) { SetPropertyValue(propertyName, StringConverter::BoolToString(propertyValue)); } void PropertyTable::SetPropertyValueInt8(const char *propertyName, int8 propertyValue) { SetPropertyValue(propertyName, StringConverter::Int8ToString(propertyValue)); } void PropertyTable::SetPropertyValueInt16(const char *propertyName, int16 propertyValue) { SetPropertyValue(propertyName, StringConverter::Int16ToString(propertyValue)); } void PropertyTable::SetPropertyValueInt32(const char *propertyName, int32 propertyValue) { SetPropertyValue(propertyName, StringConverter::Int32ToString(propertyValue)); } void PropertyTable::SetPropertyValueInt64(const char *propertyName, int64 propertyValue) { SetPropertyValue(propertyName, StringConverter::Int64ToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt8(const char *propertyName, uint8 propertyValue) { SetPropertyValue(propertyName, StringConverter::UInt8ToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt16(const char *propertyName, uint16 propertyValue) { SetPropertyValue(propertyName, StringConverter::UInt16ToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt32(const char *propertyName, uint32 propertyValue) { SetPropertyValue(propertyName, StringConverter::UInt32ToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt64(const char *propertyName, uint64 propertyValue) { SetPropertyValue(propertyName, StringConverter::UInt64ToString(propertyValue)); } void PropertyTable::SetPropertyValueFloat(const char *propertyName, float propertyValue) { SetPropertyValue(propertyName, StringConverter::FloatToString(propertyValue)); } void PropertyTable::SetPropertyValueDouble(const char *propertyName, double propertyValue) { SetPropertyValue(propertyName, StringConverter::DoubleToString(propertyValue)); } void PropertyTable::SetPropertyValueColor(const char *propertyName, uint32 propertyValue) { SetPropertyValue(propertyName, StringConverter::ColorToString(propertyValue)); } void PropertyTable::SetPropertyValueInt2(const char *propertyName, const Vector2i &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector2iToString(propertyValue)); } void PropertyTable::SetPropertyValueInt3(const char *propertyName, const Vector3i &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector3iToString(propertyValue)); } void PropertyTable::SetPropertyValueInt4(const char *propertyName, const Vector4i &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector4iToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt2(const char *propertyName, const Vector2u &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector2uToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt3(const char *propertyName, const Vector3u &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector3uToString(propertyValue)); } void PropertyTable::SetPropertyValueUInt4(const char *propertyName, const Vector4u &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector4uToString(propertyValue)); } void PropertyTable::SetPropertyValueFloat2(const char *propertyName, const Vector2f &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector2fToString(propertyValue)); } void PropertyTable::SetPropertyValueFloat3(const char *propertyName, const Vector3f &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector3fToString(propertyValue)); } void PropertyTable::SetPropertyValueFloat4(const char *propertyName, const Vector4f &propertyValue) { SetPropertyValue(propertyName, StringConverter::Vector4fToString(propertyValue)); } void PropertyTable::SetPropertyValueQuaternion(const char *propertyName, const Quaternion &propertyValue) { SetPropertyValue(propertyName, StringConverter::QuaternionToString(propertyValue)); } PropertyTable &PropertyTable::operator=(const PropertyTable &copy) { m_properties.Clear(); for (PropertyHashTable::ConstIterator itr = copy.m_properties.Begin(); !itr.AtEnd(); itr.Forward()) m_properties.Insert(itr->Key, itr->Value); return *this; } static PropertyTable s_emptyPropertyList; const PropertyTable &PropertyTable::EmptyPropertyList = s_emptyPropertyList; <file_sep>/Engine/Source/MathLib/Plane.cpp #include "MathLib/Plane.h" #include "MathLib/SIMDVectorf.h" Plane Plane::Normalize() { Plane ret; float Length = Y_sqrtf(a * a + b * b + c * c); ret.a = a / Length; ret.b = b / Length; ret.c = c / Length; ret.d = d / Length; return ret; } Plane Plane::NormalizeEst() { Plane ret; float invLength = Y_rsqrtf(a * a + b * b + c * c); ret.a = a * invLength; ret.b = b * invLength; ret.c = c * invLength; ret.d = d * invLength; return ret; } void Plane::NormalizeInPlace() { float Length = Y_sqrtf(a * a + b * b + c * c); a /= Length; b /= Length; c /= Length; d /= Length; } void Plane::NormalizeEstInPlace() { float invLength = Y_rsqrtf(a * a + b * b + c * c); a *= invLength; b *= invLength; c *= invLength; d *= invLength; } float Plane::Distance(const Vector3f &p) const { return a * p.x + b * p.y + c * p.z + d; } Plane Plane::FromPointAndNormal(const Vector3f &Point, const Vector3f &Normal) { Plane ret; // normal == point ret.a = Point.x; ret.b = Point.y; ret.c = Point.z; // d = -dot(normal, point) ret.d = -(Normal.x * Point.x + Normal.y * Point.y + Normal.z * Point.z); // normalize the plane return ret.Normalize(); } Plane Plane::FromTriangle(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) { Plane ret; ret.Set(v0.y * (v1.z - v2.z) + v1.y * (v2.z - v0.z) + v2.y * (v0.z - v1.z), v0.z * (v1.x - v2.x) + v1.z * (v2.x - v0.x) + v2.z * (v0.x - v1.x), v0.x * (v1.y - v2.y) + v1.x * (v2.y - v0.y) + v2.x * (v0.y - v1.y), -(v0.x * (v1.y * v2.z - v2.y * v1.z) + v1.x * (v2.y * v0.z - v0.y * v2.z) + v2.x * (v0.y * v1.z - v1.y * v0.z))); return ret.Normalize(); } Vector3f Plane::CalculateThreePlaneIntersectionPoint(const Plane &p1, const Plane &p2, const Plane &p3) { SIMDVector3f p1Normal(p1.GetNormal()); SIMDVector3f p2Normal(p2.GetNormal()); SIMDVector3f p3Normal(p3.GetNormal()); float p1Distance = p1.GetDistance(); float p2Distance = p2.GetDistance(); float p3Distance = p3.GetDistance(); return Vector3f(p2Normal.Cross(p3Normal) * -p1Distance / p1Normal.Dot(p2Normal.Cross(p3Normal)) - p3Normal.Cross(p1Normal) * p2Distance / p2Normal.Dot(p3Normal.Cross(p1Normal)) - p1Normal.Cross(p2Normal) * p3Distance / p3Normal.Dot(p1Normal.Cross(p2Normal))); } <file_sep>/Engine/Source/Engine/CommandQueue.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/CommandQueue.h" CommandQueue::CommandQueue() : m_creatorThreadID(0), m_workerThreadExitFlag(true), m_activeThreadPoolTasks(0), m_threadPoolYieldToOtherJobs(false), m_activeWorkerThreads(0), m_commandQueueSize(0), m_barrier(2) { } CommandQueue::~CommandQueue() { // cleanup thread pool tasks if (m_pThreadPool != nullptr) { for (;;) { m_queueLock.Lock(); if (m_activeThreadPoolTasks == 0) break; // loop until empty m_queueLock.Unlock(); Thread::Yield(); continue; } // tasks are now done, so kill off the references while (m_threadPoolTasks.GetSize() > 0) { ThreadPoolTask *pTask = m_threadPoolTasks.PopBack(); pTask->Release(); } // release lock m_queueLock.Unlock(); } // cleanup queue and end threads ExitWorkers(); // the queue should be empty at this point DebugAssert(FifoIsEmpty()); } bool CommandQueue::Initialize(uint32 commandQueueSize /* = DEFAULT_COMMAND_QUEUE_SIZE */, uint32 workerThreadCount /* = 1 */) { DebugAssert(m_workerThreadExitFlag && m_workerThreads.IsEmpty() && m_pThreadPool == nullptr); m_creatorThreadID = Thread::GetCurrentThreadId(); // allocate queue AllocateQueue(commandQueueSize); // create worker threads if (workerThreadCount > 0) { // prevent threads exiting m_workerThreadExitFlag = false; MemoryBarrier(); // create the workers for (uint32 i = 0; i < workerThreadCount; i++) { WorkerThread *pThread = new WorkerThread(this); if (!pThread->Start()) { // cleanup the remaining threads delete pThread; ExitWorkers(); return false; } // store thread m_workerThreads.Add(pThread); } } return true; } bool CommandQueue::Initialize(ThreadPool *pThreadPool, uint32 commandQueueSize /* = DEFAULT_COMMAND_QUEUE_SIZE */, bool yieldToOtherJobs /* = false */) { DebugAssert(m_workerThreadExitFlag && m_workerThreads.IsEmpty() && m_pThreadPool == nullptr); m_creatorThreadID = Thread::GetCurrentThreadId(); m_pThreadPool = pThreadPool; // allocate queue AllocateQueue(commandQueueSize); // allocate thread pool tasks, with a kept reference so that we can re-use them. uint32 taskCount = m_pThreadPool->GetWorkerThreadCount(); m_threadPoolTasks.Resize(taskCount); for (uint32 i = 0; i < taskCount; i++) m_threadPoolTasks[i] = new ThreadPoolTask(this); // all done for now m_threadPoolYieldToOtherJobs = yieldToOtherJobs; return true; } void CommandQueue::AllocateQueue(uint32 size) { m_commandQueueSize = size; if (size > 0) { // todo: allocate fifo } } void CommandQueue::ExitWorkers() { // if there's no workers, just drain the queue if (m_workerThreads.IsEmpty()) { ExecuteQueuedCommands(); return; } // pause the workers, draining the queue PauseWorkers(); // set the worker exit flag, and wake all workers m_workerThreadExitFlag = true; m_conditionVariable.WakeAll(); ResumeWorkers(); // join each thread while (m_workerThreads.GetSize() > 0) { WorkerThread *pThread = m_workerThreads.PopBack(); pThread->Join(); delete pThread; } } void CommandQueue::PauseWorkers() { if (m_workerThreads.IsEmpty()) { ExecuteQueuedCommands(); return; } // drain the queue, then pause the thread by holding the lock for (;;) { m_queueLock.Lock(); // queue has entries? wait for the worker to sleep if (!FifoIsEmpty() || m_activeWorkerThreads > 0) { if (m_activeWorkerThreads == 0) { m_conditionVariable.Wake(); //Log::GetInstance().Write("w", LOGLEVEL_DEV, "Woke CV"); } m_queueLock.Unlock(); Thread::Yield(); continue; } else { // leave the queue locked break; } } } void CommandQueue::ResumeWorkers() { if (m_workerThreads.IsEmpty()) return; // unlock queue, any workers that were woken should be allowed to continue m_queueLock.Unlock(); } void CommandQueue::QueueCommand(CommandBase *pCommand, uint32 commandSize) { if (m_commandQueueSize == 0) { pCommand->Execute(); return; } LockQueueForNewCommand(); void *command = FifoAllocateCommand(commandSize, false); Y_memcpy(command, pCommand, commandSize); UnlockQueueForNewCommand(); } void CommandQueue::QueueBlockingCommand(CommandBase *pCommand, uint32 commandSize) { if (m_commandQueueSize == 0 || m_workerThreads.IsEmpty()) { pCommand->Execute(); return; } // currently blocking events are only supported coming from the main thread DebugAssert(Thread::GetCurrentThreadId() == m_creatorThreadID); // lock before write LockQueueForNewCommand(); // write void *command = FifoAllocateCommand(commandSize, true); Y_memcpy(command, pCommand, commandSize); // unlock UnlockQueueForNewCommand(); // block m_barrier.Wait(); } bool CommandQueue::ExecuteQueuedCommands() { bool result = false; m_queueLock.Lock(); // loop for (;;) { FifoQueueEntryHeader *commandHdr = FifoGetNextCommand(); if (commandHdr == nullptr) { // if there's still outstanding commands, yield and search again if (m_activeWorkerThreads > 0 || m_activeThreadPoolTasks > 0) { m_queueLock.Unlock(); Thread::Yield(); m_queueLock.Lock(); continue; } // all commands done break; } // unlock queue while the command runs m_queueLock.Unlock(); // run command commandHdr->pCommand->Execute(); // re-lock queue m_queueLock.Lock(); // pop the command off the queue FifoReleaseCommand(commandHdr); result = true; } m_queueLock.Unlock(); return result; } CommandQueue::WorkerThread::WorkerThread(CommandQueue *pParent) : m_this(pParent) { } int CommandQueue::WorkerThread::ThreadEntryPoint() { // initialize thread name Thread::SetDebugName(String::FromFormat("Command Queue %p Worker", m_this)); // start with it locked m_this->m_queueLock.Lock(); m_this->m_activeWorkerThreads++; MemoryBarrier(); // loop for (;;) { // get the next command FifoQueueEntryHeader *commandHdr = m_this->FifoGetNextCommand(); if (commandHdr == nullptr) { // no next command, are we exiting? if (m_this->m_workerThreadExitFlag) break; // this thread is now inactive m_this->m_activeWorkerThreads--; MemoryBarrier(); // wait until there is a new event m_this->m_conditionVariable.SleepAndRelease(&m_this->m_queueLock); // this thread is now active m_this->m_activeWorkerThreads++; MemoryBarrier(); continue; } // release queue lock m_this->m_queueLock.Unlock(); // run the command commandHdr->pCommand->Execute(); if (commandHdr->BlockingEvent) m_this->m_barrier.Wait(); // hold lock again m_this->m_queueLock.Lock(); // destruct the command m_this->FifoReleaseCommand(commandHdr); } m_this->m_activeWorkerThreads--; MemoryBarrier(); m_this->m_queueLock.Unlock(); return 0; } CommandQueue::ThreadPoolTask::ThreadPoolTask(CommandQueue *pParent) : ThreadPoolWorkItem(), m_this(pParent), m_active(false) { } int32 CommandQueue::ThreadPoolTask::ProcessWork() { m_this->m_queueLock.Lock(); // loop until there are no tasks left for (;;) { // get the next command FifoQueueEntryHeader *commandHdr = m_this->FifoGetNextCommand(); if (commandHdr == nullptr) break; // release queue lock m_this->m_queueLock.Unlock(); // run the command commandHdr->pCommand->Execute(); if (commandHdr->BlockingEvent) m_this->m_barrier.Wait(); // hold lock again m_this->m_queueLock.Lock(); // destruct the command m_this->FifoReleaseCommand(commandHdr); // check if we should yield if (m_this->m_threadPoolYieldToOtherJobs && m_this->m_pThreadPool->ShouldYieldToOtherTask()) break; } // this task is no longer active DebugAssert(m_this->m_activeThreadPoolTasks > 0); m_this->m_activeThreadPoolTasks--; m_active = false; // end of this task's work m_this->m_queueLock.Unlock(); return 0; } void CommandQueue::LockQueueForNewCommand() { m_queueLock.Lock(); } void CommandQueue::UnlockQueueForNewCommand() { DebugAssert(m_commandQueue.GetSize() > 0); if (m_pThreadPool != nullptr) { bool queueTask = (m_activeThreadPoolTasks < m_threadPoolTasks.GetSize()); if (queueTask) { // find a free task for (uint32 i = 0; i < m_threadPoolTasks.GetSize(); i++) { ThreadPoolTask *pTask = m_threadPoolTasks[i]; if (!pTask->IsActive()) { // enqueue it pTask->SetActive(); m_activeThreadPoolTasks++; m_pThreadPool->EnqueueWorkItem(pTask); break; } } } // release lock m_queueLock.Unlock(); } else { if (m_activeWorkerThreads < m_workerThreads.GetSize()) m_conditionVariable.Wake(); m_queueLock.Unlock(); } } void *CommandQueue::FifoAllocateCommand(uint32 size, bool blockingEvent) { // allocate entry FifoQueueEntryHeader *hdr = (FifoQueueEntryHeader *)Y_malloc(sizeof(FifoQueueEntryHeader) + size); hdr->pCommand = reinterpret_cast<CommandBase *>(hdr + 1); hdr->Size = size; hdr->BlockingEvent = blockingEvent; m_commandQueue.Add(hdr); return hdr->pCommand; } bool CommandQueue::FifoIsEmpty() const { return m_commandQueue.IsEmpty(); } CommandQueue::FifoQueueEntryHeader *CommandQueue::FifoGetNextCommand() { if (m_commandQueue.GetSize() == 0) return nullptr; return m_commandQueue.PopFront(); } void CommandQueue::FifoReleaseCommand(FifoQueueEntryHeader *commandHdr) { // destruct the command commandHdr->pCommand->~CommandBase(); Y_free(commandHdr); } <file_sep>/Engine/Source/ContentConverter/CMakeLists.txt set(HEADER_FILES AssimpCommon.h AssimpMaterialImporter.h AssimpSceneImporter.h AssimpSkeletalAnimationImporter.h AssimpSkeletalMeshImporter.h AssimpSkeletonImporter.h AssimpStaticMeshImporter.h BaseImporter.h Common.h FontImporter.h OBJImporter.h stb_truetype.h TextureImporter.h ) set(SOURCE_FILES AssimpCommon.cpp AssimpSceneImporter.cpp AssimpMaterialImporter.cpp AssimpSkeletalAnimationImporter.cpp AssimpSkeletalMeshImporter.cpp AssimpSkeletonImporter.cpp AssimpStaticMeshImporter.cpp BaseImporter.cpp FontImporter.cpp OBJImporter.cpp TextureImporter.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${FREETYPE_INCLUDE_DIRS}) add_library(EngineContentConverter STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineContentConverter EngineMapCompiler EngineResourceCompiler EngineCore EngineMain assimp ${FREETYPE_LIBRARIES}) <file_sep>/DemoGame/Source/DemoGame/SkeletalAnimationDemo.h #pragma once #include "DemoGame/BaseDemoWorldGameState.h" #include "GameFramework/DirectionalLightEntity.h" #include "Renderer/RenderProxies/SkeletalMeshRenderProxy.h" #include "Engine/SkeletalAnimationPlayer.h" class SkeletalAnimationDemo : public BaseDemoWorldGameState { public: SkeletalAnimationDemo(DemoGame *pDemoGame); virtual ~SkeletalAnimationDemo(); virtual bool Initialize() override final; virtual void Shutdown() override final; protected: virtual bool OnWorldCreated(World *pWorld) override final; virtual void OnWorldDeleted(World *pWorld) override final; virtual void DrawOverlays(float deltaTime) override final; virtual void DrawUI(float deltaTime) override final; virtual bool OnWindowEvent(const union SDL_Event *event) override final; virtual void OnMainThreadTick(float deltaTime) override final; private: bool SetModelIndex(uint32 index); bool SetAnimationIndex(uint32 index); void ResetCamera(); DirectionalLightEntity *m_pSunLightEntity; float3 m_sunLightRotation; SkeletalMeshRenderProxy *m_pSkeletalMeshRenderProxy; SkeletalAnimationPlayer m_skeletalAnimationPlayer; PODArray<const char *> m_animationNames; uint32 m_skeletalMeshIndex; uint32 m_skeletalAnimationIndex; }; <file_sep>/Engine/Source/ResourceCompiler/ShaderCompilerOpenGL.h #pragma once #include "ResourceCompiler/ShaderCompiler.h" #include "OpenGLRenderer/OpenGLShaderCacheEntry.h" #include "glad/glad.h" #include "HLSLTranslator.h" #include "HLSLTranslator_GLSL.h" class ShaderCompilerOpenGL : public ShaderCompiler { public: ShaderCompilerOpenGL(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters); virtual ~ShaderCompilerOpenGL(); protected: // compile virtual bool InternalCompile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream); // helper functions void AddDefinesForStage(SHADER_PROGRAM_STAGE stage, MemArray<HLSLTRANSLATOR_MACRO> &macroArray); bool CompileShaderStage(SHADER_PROGRAM_STAGE stage, uint32 outputGLSLVersion, bool outputGLSLES); bool ReflectShaderStage(SHADER_PROGRAM_STAGE stage); bool WriteOutput(ByteStream *pByteCodeStream); private: HLSLTRANSLATOR_GLSL_OUTPUT *m_pOutputGLSL[SHADER_PROGRAM_STAGE_COUNT]; MemArray<OpenGLShaderCacheEntryVertexAttribute> m_vertexAttributes; MemArray<OpenGLShaderCacheEntryUniformBlock> m_uniformBlocks; MemArray<OpenGLShaderCacheEntryParameter> m_parameters; MemArray<OpenGLShaderCacheEntryFragmentData> m_fragDatas; Array<String> m_vertexAttributeNames; Array<String> m_uniformBlockNames; Array<String> m_parameterNames; Array<String> m_parameterSamplerNames; Array<String> m_fragDataNames; }; // enum GL_SHADER_COMPILE_FLAGS // { // GL_SHADER_COMPILE_FLAG_COMPILE_VERTEX_SHADER = (1 << (SHADER_COMPILE_FLAG_LAST_BIT + 0)), // GL_SHADER_COMPILE_FLAG_COMPILE_TESSELATION_CONTROL_SHADER = (1 << (SHADER_COMPILE_FLAG_LAST_BIT + 1)), // GL_SHADER_COMPILE_FLAG_COMPILE_TESSELATION_EVALUATION_SHADER = (1 << (SHADER_COMPILE_FLAG_LAST_BIT + 2)), // GL_SHADER_COMPILE_FLAG_COMPILE_GEOMETRY_SHADER = (1 << (SHADER_COMPILE_FLAG_LAST_BIT + 3)), // GL_SHADER_COMPILE_FLAG_COMPILE_FRAGMENT_SHADER = (1 << (SHADER_COMPILE_FLAG_LAST_BIT + 4)), // }; // // const BinaryBlob *GLRenderer_CompileShader(const ShaderCompileParameters *pCompileParameters); <file_sep>/Engine/Source/Renderer/Shaders/ForwardShadingShaders.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/ForwardShadingShaders.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderConstantBuffer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(BasePassShader); BEGIN_SHADER_COMPONENT_PARAMETERS(BasePassShader) END_SHADER_COMPONENT_PARAMETERS() bool BasePassShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (baseShaderFlags & WITH_EMISSIVE && pMaterialShader->GetLightingType() != MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool BasePassShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/BasePassShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/BasePassShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_EMISSIVE) pParameters->AddPreprocessorMacro("WITH_EMISSIVE", "1"); if (baseShaderFlags & WITH_LIGHTMAP) pParameters->AddPreprocessorMacro("WITH_LIGHTMAP", "1"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DirectionalLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DirectionalLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("ShadowMapTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbDirectionalLightParameters, "DirectionalLightParameters", "cbDirectionalLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightVector", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("AmbientColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("ShadowMapSize", SHADER_PARAMETER_TYPE_FLOAT4, 1) SHADER_CONSTANT_BUFFER_FIELD("CascadeViewProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, CSMShadowMapRenderer::MaxCascadeCount) SHADER_CONSTANT_BUFFER_FIELD("CascadeSplitDepths", SHADER_PARAMETER_TYPE_FLOAT, CSMShadowMapRenderer::MaxCascadeCount) END_SHADER_CONSTANT_BUFFER(cbDirectionalLightParameters) uint32 DirectionalLightShader::CalculateFlags(bool enableShadows, bool useHardwareShadowFiltering, RENDERER_SHADOW_FILTER shadowFilter, bool showCascades) { uint32 flags = 0; if (enableShadows) { flags |= WITH_SHADOW_MAP; if (useHardwareShadowFiltering) flags |= USE_HARDWARE_PCF; switch (shadowFilter) { case RENDERER_SHADOW_FILTER_3X3: flags |= SHADOW_FILTER_3X3; break; case RENDERER_SHADOW_FILTER_5X5: flags |= SHADOW_FILTER_5X5; break; //case RENDERER_SHADOW_FILTER_1X1: default: flags |= SHADOW_FILTER_1X1; break; } if (showCascades) flags |= SHOW_CASCADES; } return flags; } void DirectionalLightShader::SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData) { cbDirectionalLightParameters.SetFieldFloat3(pCommandList, 0, pLight->Direction, false); cbDirectionalLightParameters.SetFieldFloat3(pCommandList, 1, pLight->LightColor, false); cbDirectionalLightParameters.SetFieldFloat3(pCommandList, 2, pLight->AmbientColor, false); if (pShadowMapData != nullptr) { uint32 shadowMapWidth = pShadowMapData->pShadowMapTexture->GetDesc()->Width; uint32 shadowMapHeight = pShadowMapData->pShadowMapTexture->GetDesc()->Height; float4 shadowMapSize((float)shadowMapWidth, (float)shadowMapHeight, 1.0f / (float)shadowMapWidth, 1.0f / (float)shadowMapHeight); cbDirectionalLightParameters.SetFieldFloat4(pCommandList, 3, shadowMapSize, false); cbDirectionalLightParameters.SetFieldFloat4x4Array(pCommandList, 4, 0, pShadowMapData->CascadeCount, pShadowMapData->ViewProjectionMatrices, false); cbDirectionalLightParameters.SetFieldFloatArray(pCommandList, 5, 0, pShadowMapData->CascadeCount, pShadowMapData->CascadeFrustumEyeSpaceDepths, false); } cbDirectionalLightParameters.CommitChanges(pCommandList); } void DirectionalLightShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData) { if (pShadowMapData != nullptr) pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pShadowMapData->pShadowMapTexture, nullptr); } bool DirectionalLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool DirectionalLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DirectionalLightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DirectionalLightShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_SHADOW_MAP) { pParameters->AddPreprocessorMacro("WITH_SHADOW_MAP", "1"); if (baseShaderFlags & USE_HARDWARE_PCF) pParameters->AddPreprocessorMacro("USE_HARDWARE_PCF", "1"); // filter if (baseShaderFlags & SHADOW_FILTER_3X3) pParameters->AddPreprocessorMacro("SHADOW_FILTER_3X3", "1"); else if (baseShaderFlags & SHADOW_FILTER_5X5) pParameters->AddPreprocessorMacro("SHADOW_FILTER_5X5", "1"); else //if (baseShaderFlags & SHADOW_FILTER_1X1) pParameters->AddPreprocessorMacro("SHADOW_FILTER_1X1", "1"); if (baseShaderFlags & SHOW_CASCADES) pParameters->AddPreprocessorMacro("SHOW_CASCADES", "1"); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(EmissiveShader); BEGIN_SHADER_COMPONENT_PARAMETERS(EmissiveShader) END_SHADER_COMPONENT_PARAMETERS() bool EmissiveShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() != MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool EmissiveShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/EmissiveShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/EmissiveShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(PointLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(PointLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("ShadowMapTexture", SHADER_PARAMETER_TYPE_TEXTURECUBE) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbPointLightParameters, "PointLightParameters", "cbPointLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightRange", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent", SHADER_PARAMETER_TYPE_FLOAT, 1) END_SHADER_CONSTANT_BUFFER(cbPointLightParameters) uint32 PointLightShader::CalculateFlags(bool enableShadows, bool useHardwareShadowFiltering) { uint32 flags = 0; if (enableShadows) { flags |= WITH_SHADOW_MAP; if (useHardwareShadowFiltering) flags |= USE_HARDWARE_PCF; } return flags; } void PointLightShader::SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData) { cbPointLightParameters.SetFieldFloat3(pCommandList, 0, pLight->LightColor, false); cbPointLightParameters.SetFieldFloat3(pCommandList, 1, pLight->Position, false); cbPointLightParameters.SetFieldFloat(pCommandList, 2, pLight->Range, false); cbPointLightParameters.SetFieldFloat(pCommandList, 3, pLight->InverseRange, false); cbPointLightParameters.SetFieldFloat(pCommandList, 4, pLight->FalloffExponent, false); cbPointLightParameters.CommitChanges(pCommandList); } void PointLightShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData) { if (pShadowMapData != nullptr) pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pShadowMapData->pShadowMapTexture, nullptr); } bool PointLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool PointLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/PointLightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/PointLightShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_SHADOW_MAP) { pParameters->AddPreprocessorMacro("WITH_SHADOW_MAP", "1"); if (baseShaderFlags & USE_HARDWARE_PCF) pParameters->AddPreprocessorMacro("USE_HARDWARE_PCF", "1"); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(PointLightListShader); BEGIN_SHADER_COMPONENT_PARAMETERS(PointLightListShader) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbPointLightListParameters, "PointLightListParameters", "cbPointLightListParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightPosition0", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange0", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor0", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent0", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition1", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange1", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor1", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent1", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition2", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange2", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor2", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent2", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition3", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange3", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor3", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent3", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition4", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange4", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor4", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent4", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition5", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange5", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor5", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent5", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition6", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange6", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor6", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent6", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition7", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange7", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor7", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent7", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("ActiveLightCount", SHADER_PARAMETER_TYPE_UINT, 1) END_SHADER_CONSTANT_BUFFER(cbPointLightListParameters) void PointLightListShader::SetLightParameters(GPUCommandList *pCommandList, uint32 lightIndex, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { uint32 baseIndex = lightIndex * 4; DebugAssert(lightIndex < MAX_LIGHTS); cbPointLightListParameters.SetFieldFloat3(pCommandList, baseIndex + 0, pLight->Position, false); cbPointLightListParameters.SetFieldFloat(pCommandList, baseIndex + 1, pLight->InverseRange, false); cbPointLightListParameters.SetFieldFloat3(pCommandList, baseIndex + 2, pLight->LightColor, false); cbPointLightListParameters.SetFieldFloat(pCommandList, baseIndex + 3, pLight->FalloffExponent, false); } void PointLightListShader::SetActiveLightCount(GPUCommandList *pCommandList, uint32 activeLightCount) { cbPointLightListParameters.SetFieldUInt(pCommandList, 32, activeLightCount, false); } void PointLightListShader::CommitParameters(GPUCommandList *pCommandList) { cbPointLightListParameters.CommitChanges(pCommandList); } bool PointLightListShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool PointLightListShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/PointLightListShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/PointLightListShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(VolumetricLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(VolumetricLightShader) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbVolumetricLightShader, "VolumetricLightShader", "cbVolumetricLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloff", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightBoxExtents", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightSphereRadius", SHADER_PARAMETER_TYPE_FLOAT, 1) END_SHADER_CONSTANT_BUFFER(cbVolumetricLightShader) uint32 VolumetricLightShader::GetTypeFlagsForPrimitive(VOLUMETRIC_LIGHT_PRIMITIVE primitive) { switch (primitive) { case VOLUMETRIC_LIGHT_PRIMITIVE_BOX: return Flag_BoxPrimitive; case VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE: return Flag_SpherePrimitive; } UnreachableCode(); return 0; } void VolumetricLightShader::SetLightParameters(GPUCommandList *pCommandList, const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight) { cbVolumetricLightShader.SetFieldFloat3(pCommandList, 0, pLight->LightColor, false); cbVolumetricLightShader.SetFieldFloat3(pCommandList, 1, pLight->Position, false); cbVolumetricLightShader.SetFieldFloat(pCommandList, 2, pLight->FalloffRate, false); cbVolumetricLightShader.SetFieldFloat3(pCommandList, 3, pLight->BoxExtents, false); cbVolumetricLightShader.SetFieldFloat(pCommandList, 4, pLight->SphereRadius, false); cbVolumetricLightShader.CommitChanges(pCommandList); } void VolumetricLightShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight) { } bool VolumetricLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL || pMaterialShader == NULL) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool VolumetricLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/VolumetricLightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/VolumetricLightShader.hlsl", "PSMain"); if (baseShaderFlags & Flag_BoxPrimitive) pParameters->AddPreprocessorMacro("VOLUMETRIC_LIGHT_BOX_PRIMITIVE", "1"); if (baseShaderFlags & Flag_SpherePrimitive) pParameters->AddPreprocessorMacro("VOLUMETRIC_LIGHT_SPHERE_PRIMITIVE", "1"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Editor/Source/Editor/EditorIconLibrary.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" EditorIconLibrary::EditorIconLibrary() { } EditorIconLibrary::~EditorIconLibrary() { } const QIcon &EditorIconLibrary::GetIconByName(const char *key, uint32 size /* = 16 */) const { SmallString realKey; realKey.Format("%s_%u", key, size); const IconTable::Member *pMember = m_iconTable.Find(realKey); if (pMember == NULL) { if (!LoadIcon(key, size)) pMember = m_iconTable.Insert(realKey, m_defaultIcon); else pMember = m_iconTable.Find(realKey); } return pMember->Value; } const QIcon &EditorIconLibrary::GetIconForResourceType(const ResourceTypeInfo *pResourceTypeInfo, uint32 size /* = 16 */) const { SmallString tableKey; tableKey.Format("Resource_%s_%u", pResourceTypeInfo->GetTypeName(), size); const IconTable::Member *pMember = m_iconTable.Find(tableKey); if (pMember == NULL) { SmallString realKey; realKey.Format("Resource_%s", pResourceTypeInfo->GetTypeName()); // replace it with the default resource icon if (!LoadIcon(realKey, size)) pMember = m_iconTable.Insert(tableKey, GetIconByName("Resource", size)); else pMember = m_iconTable.Find(tableKey); } return pMember->Value; } bool EditorIconLibrary::PreloadIcons() { ////////////////////////////////////////////////////////////////////////// // Fixed Icons ////////////////////////////////////////////////////////////////////////// LoadIcon("Directory", 16); ////////////////////////////////////////////////////////////////////////// // Resource Type Icons ////////////////////////////////////////////////////////////////////////// LoadIcon("Resource", 16); LoadIcon("Resource_Texture2D", 16); LoadIcon("Resource_Texture2DArray", 16); LoadIcon("Resource_TextureCube", 16); LoadIcon("Resource_Material", 16); LoadIcon("Resource_MaterialShader", 16); LoadIcon("Resource_StaticMesh", 16); LoadIcon("Resource_StaticBlockMesh", 16); ////////////////////////////////////////////////////////////////////////// return true; } bool EditorIconLibrary::LoadIcon(const char *name, uint32 size) const { PathString resourceFileName; resourceFileName.Format(":/editor/icons/%s_%ux%u.png", name, size, size); QIcon createdIcon(ConvertStringToQString(resourceFileName)); if (createdIcon.isNull() || createdIcon.availableSizes().size() == 0) return false; SmallString key; key.Format("%s_%u", name, size); m_iconTable.Insert(key, createdIcon); return true; } <file_sep>/Engine/Source/ContentConverter/AssimpStaticMeshImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiMesh; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class StaticMeshGenerator; class AssimpStaticMeshImporter : public BaseImporter { public: struct Options { String SourcePath; String OutputResourceName; bool ImportMaterials; String MaterialDirectory; String MaterialPrefix; String DefaultMaterialName; uint32 BuildCollisionShapeType; COORDINATE_SYSTEM CoordinateSystem; bool FlipFaceOrder; float4x4 TransformMatrix; // todo: split into multiple meshes, center mesh, origin, etc. }; public: AssimpStaticMeshImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpStaticMeshImporter(); const StaticMeshGenerator *GetOutputGenerator() const { return m_pOutputGenerator; } // removes ownership of the generator from the importer, ie will not be deleted StaticMeshGenerator *DetachOutputGenerator(); static void SetDefaultOptions(Options *pOptions); static bool GetFileSubMeshNames(const char *filename, Array<String> &meshNames, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool Execute(); private: bool LoadScene(); bool CreateGenerator(); bool CreateMaterials(); bool CreateMesh(); bool ParseMesh(const aiMesh *pMesh, StaticMeshGenerator *pOutputGenerator, uint32 lodIndex, const char *meshName); bool PostProcess(); bool WriteOutput(); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; String m_baseOutputPath; Array<String> m_materialMapping; float4x4 m_globalTransform; StaticMeshGenerator *m_pOutputGenerator; }; <file_sep>/Engine/Source/Engine/ParticleSystemEmitter.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemEmitter.h" #include "Engine/ParticleSystemModule.h" #include "Renderer/Renderer.h" Log_SetChannel(ParticleSystemEmitter); DEFINE_OBJECT_TYPE_INFO(ParticleSystemEmitter); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemEmitter) PROPERTY_TABLE_MEMBER_UINT("MaxActiveParticles", 0, offsetof(ParticleSystemEmitter, m_maxActiveParticles), nullptr, nullptr) PROPERTY_TABLE_MEMBER_UINT("UpdateInterval", 0, offsetof(ParticleSystemEmitter, m_updateInterval), nullptr, nullptr) PROPERTY_TABLE_MEMBER_UINT("SpawnRate", 0, offsetof(ParticleSystemEmitter, m_spawnRate), nullptr, nullptr) PROPERTY_TABLE_MEMBER_UINT("SpawnCount", 0, offsetof(ParticleSystemEmitter, m_spawnCount), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemEmitter::ParticleSystemEmitter(const ObjectTypeInfo *pTypeInfo /* = &s_typeInfo */) : BaseClass(pTypeInfo) { m_maxActiveParticles = 16; m_updateInterval = 1.0f / 60.0f; m_spawnRate = 1.0f; m_spawnCount = 1; } ParticleSystemEmitter::~ParticleSystemEmitter() { for (uint32 i = 0; i < m_modules.GetSize(); i++) delete m_modules[i]; } void ParticleSystemEmitter::AddModule(const ParticleSystemModule *pAffector) { DebugAssert(m_modules.IndexOf(pAffector) < 0); m_modules.Add(pAffector); } void ParticleSystemEmitter::RemoveModule(const ParticleSystemModule *pAffector) { int32 index = m_modules.IndexOf(pAffector); if (index >= 0) m_modules.OrderedRemove(index); } void ParticleSystemEmitter::InitializeInstance(InstanceData *pEmitterData) const { // Allocate particle arrays pEmitterData->ParticlesState[0].Reserve(m_maxActiveParticles); pEmitterData->ParticlesState[1].Reserve(m_maxActiveParticles); pEmitterData->BoundingBox.SetZero(); pEmitterData->TimeUntilNextSpawn = 0.0f; } void ParticleSystemEmitter::CleanupInstance(InstanceData *pEmitterData) const { // Cleanup everything pEmitterData->ParticlesState[0].Obliterate(); pEmitterData->ParticlesState[1].Obliterate(); } void ParticleSystemEmitter::UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const { // Call affector update on everything in array[1] if (pEmitterData->ParticlesState[0].GetSize() > 0) { for (uint32 affectorIndex = 0; affectorIndex < m_modules.GetSize(); affectorIndex++) { const ParticleSystemModule *pAffector = m_modules[affectorIndex]; pAffector->UpdateParticles(this, pBaseTransform, pRNG, pEmitterData->ParticlesState[0].GetBasePointer(), pEmitterData->ParticlesState[0].GetSize(), deltaTime); } } // Clear array[2], Update position, lifetime on existing particles, store in array[2] // Calculate new bounding box along the way AABox particlesBoundingBox; uint32 nActiveParticles = 0; pEmitterData->ParticlesState[1].Clear(); for (uint32 particleIndex = 0; particleIndex < pEmitterData->ParticlesState[0].GetSize(); particleIndex++) { ParticleData *pParticleData = &pEmitterData->ParticlesState[0][particleIndex]; pParticleData->LifeRemaining -= deltaTime; if (pParticleData->LifeRemaining <= 0.0f) continue; pParticleData->Position += pParticleData->Velocity * deltaTime; float maxDimension = Max(pParticleData->Width, pParticleData->Height); if ((nActiveParticles++) == 0) particlesBoundingBox.SetBounds(pParticleData->Position - maxDimension, pParticleData->Position + maxDimension); else particlesBoundingBox.Merge(AABox(pParticleData->Position - maxDimension, pParticleData->Position + maxDimension)); pEmitterData->ParticlesState[1].Add(*pParticleData); } // Spawn new particles, add to array[2] float remainingDeltaTime = deltaTime; while (remainingDeltaTime > 0.0f) { // spawn one? if (remainingDeltaTime >= pEmitterData->TimeUntilNextSpawn) { remainingDeltaTime -= pEmitterData->TimeUntilNextSpawn; // room for another particle? if (pEmitterData->ParticlesState[1].GetSize() < m_maxActiveParticles) { // spawn particles for (uint32 spawnCount = 0; spawnCount < m_spawnCount && pEmitterData->ParticlesState[1].GetSize() < m_maxActiveParticles; spawnCount++) { ParticleData particleData; if (InternalCreateParticle(pEmitterData, pBaseTransform, pRNG, &particleData)) { pEmitterData->ParticlesState[1].Add(particleData); // update bounding box float maxDimension = Max(particleData.Width, particleData.Height); if ((nActiveParticles++) == 0) particlesBoundingBox.SetBounds(particleData.Position - maxDimension, particleData.Position + maxDimension); else particlesBoundingBox.Merge(AABox(particleData.Position - maxDimension, particleData.Position + maxDimension)); } } // reset time remaining pEmitterData->TimeUntilNextSpawn = m_spawnRate; } else { // keep the time remaining to zero so we spawn a particle as soon as possible pEmitterData->TimeUntilNextSpawn = 0.0f; break; } } else { pEmitterData->TimeUntilNextSpawn -= remainingDeltaTime; break; } } // Swap array[2] with array[1] pEmitterData->ParticlesState[0].Swap(pEmitterData->ParticlesState[1]); // Update bounding box if (nActiveParticles > 0) pEmitterData->BoundingBox = particlesBoundingBox; //Log_DevPrintf("num particles %u", nActiveParticles); } bool ParticleSystemEmitter::InternalCreateParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticleData) const { pParticleData->Position = pBaseTransform->TransformPoint(float3::Zero); pParticleData->Velocity.SetZero(); pParticleData->Width = 1.0f; pParticleData->Height = 1.0f; pParticleData->Rotation = 0.0f; pParticleData->Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); pParticleData->MinTextureCoordinates = float2(0.0f, 0.0f); pParticleData->MaxTextureCoordinates = float2(1.0f, 1.0f); pParticleData->LifeSpan = Y_FLT_MAX; pParticleData->LifeRemaining = Y_FLT_MAX; // invoke modules on each particle for (uint32 moduleIndex = 0; moduleIndex < m_modules.GetSize(); moduleIndex++) { if (!m_modules[moduleIndex]->CreateParticle(this, pBaseTransform, pRNG, pParticleData)) return false; } // okay to spawn return true; } ParticleData *ParticleSystemEmitter::InternalSpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG) const { if (pEmitterData->ParticlesState[0].GetSize() > m_maxActiveParticles) return nullptr; ParticleData particleData; if (!InternalCreateParticle(pEmitterData, pBaseTransform, pRNG, &particleData)) return nullptr; // update bounding box float maxDimension = Max(particleData.Width, particleData.Height); if (pEmitterData->ParticlesState[0].IsEmpty()) pEmitterData->BoundingBox.SetBounds(particleData.Position - maxDimension, particleData.Position + maxDimension); else pEmitterData->BoundingBox.Merge(AABox(particleData.Position - maxDimension, particleData.Position + maxDimension)); // add particle pEmitterData->ParticlesState[0].Add(particleData); return &pEmitterData->ParticlesState[0].LastElement(); } bool ParticleSystemEmitter::SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG) const { ParticleData *pParticleData = InternalSpawnParticle(pEmitterData, pBaseTransform, pRNG); if (pEmitterData == nullptr) return false; return true; } bool ParticleSystemEmitter::SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, uint32 emitterSpecificData) const { ParticleData *pParticleData = InternalSpawnParticle(pEmitterData, pBaseTransform, pRNG); if (pEmitterData == nullptr) return false; return true; } bool ParticleSystemEmitter::SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, uint32 emitterSpecificData, const float3 &localPosition, const float3 &spawnDirection) const { ParticleData *pParticleData = InternalSpawnParticle(pEmitterData, pBaseTransform, pRNG); if (pEmitterData == nullptr) return false; pParticleData->Position = pBaseTransform->TransformPoint(localPosition); pParticleData->Velocity = spawnDirection; return true; } void ParticleSystemEmitter::InitializeRenderData(InstanceRenderData *pEmitterRenderData) const { // Start with no GPU staging area, the emitter types can fill these in Y_memzero(pEmitterRenderData, sizeof(InstanceRenderData)); } void ParticleSystemEmitter::CleanupRenderData(InstanceRenderData *pEmitterRenderData) const { Y_free(pEmitterRenderData->pGPUStagingBuffer); pEmitterRenderData->pGPUStagingBuffer = nullptr; pEmitterRenderData->GPUStagingBufferSize = 0; pEmitterRenderData->GPUStagingBufferUsage = 0; if (pEmitterRenderData->pGPUBuffer != nullptr) { pEmitterRenderData->pGPUBuffer->Release(); pEmitterRenderData->pGPUBuffer = nullptr; } } void ParticleSystemEmitter::UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const { // Update the render thread's copy of the bounding box. pEmitterRenderData->BoundingBox = pEmitterData->BoundingBox; } void ParticleSystemEmitter::QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const { } void ParticleSystemEmitter::SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { } void ParticleSystemEmitter::DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunkRenderProxy.h #pragma once #include "BlockEngine/BlockWorldTypes.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/RenderQueue.h" class BlockWorldMesher; class BlockWorldChunkRenderProxy : public RenderProxy { public: // batch info struct RenderBatch { uint32 MaterialIndex; uint32 StartIndex; uint32 IndexCount; RenderBatch(uint32 materialIndex, uint32 startIndex, uint32 indexCount) : MaterialIndex(materialIndex), StartIndex(startIndex), IndexCount(indexCount) {} }; // mesh info struct RenderMeshInstance { uint32 MeshIndex; uint32 InstanceBufferOffset; uint32 InstanceCount; RenderMeshInstance(uint32 meshIndex, uint32 instanceBufferOffset, uint32 instanceCount) : MeshIndex(meshIndex), InstanceBufferOffset(instanceBufferOffset), InstanceCount(instanceCount) {} }; public: BlockWorldChunkRenderProxy(uint32 entityID, const BlockPalette *pPalette, const float4x4 &transformMatrix, int32 lodLevel, BlockWorldMesher *pBuilder); virtual ~BlockWorldChunkRenderProxy(); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual void DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const override; virtual bool CreateDeviceResources() const override; virtual void ReleaseDeviceResources() const override; static BlockWorldMesher *CreateMesher(const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel); static BlockWorldChunkRenderProxy *CreateForChunk(uint32 entityID, const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel, BlockWorldMesher *pBuilder); bool RebuildForChunk(const BlockWorld *pWorld, const BlockWorldSection *pSection, const BlockWorldChunk *pChunk, int32 lodLevel, BlockWorldMesher *pBuilder); // render resources const RenderBatch *GetRenderBatch(uint32 i) const { return &m_renderBatches[i]; } const uint32 GetRenderBatchCount() const { return m_renderBatches.GetSize(); } private: void QueueMeshUpload(BlockWorldMesher *pBuilder); bool UploadMeshToGPU(BlockWorldMesher *pBuilder); // data const BlockPalette *m_pPalette; float4x4 m_transformMatrix; int32 m_lodLevel; // gpu resources mutable bool m_renderResourcesCreated; mutable VertexBufferBindingArray m_vertexBuffers; mutable GPUBuffer *m_pIndexBuffer; mutable GPU_INDEX_FORMAT m_indexFormat; mutable MemArray<RenderBatch> m_renderBatches; mutable GPUBuffer *m_pMeshInstanceBuffer; mutable MemArray<RenderMeshInstance> m_renderMeshInstances; // render resources mutable MemArray<RENDER_QUEUE_POINT_LIGHT_ENTRY> m_lights; }; <file_sep>/Editor/Source/Editor/EditorBlockVolumeRenderProxy.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorBlockVolumeRenderProxy.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/Camera.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" Log_SetChannel(EditorBlockVolumeRenderProxy); EditorBlockVolumeRenderProxy::EditorBlockVolumeRenderProxy(uint32 entityId) : RenderProxy(entityId), m_pPalette(nullptr), m_visibility(true), m_localToWorldMatrix(float4x4::Identity), m_shadowFlags(0), m_tintEnabled(false), m_tintColor(0xFFFFFFFF), m_localBoundingBox(AABox::Zero), m_localBoundingSphere(Sphere::Zero), m_vertexFactoryFlags(0), m_pIndexBuffer(NULL), m_indexFormat(GPU_INDEX_FORMAT_COUNT) { SetBounds(AABox::Zero, Sphere::Zero); } EditorBlockVolumeRenderProxy::~EditorBlockVolumeRenderProxy() { SAFE_RELEASE(m_pPalette); m_vertexBuffers.Clear(); SAFE_RELEASE(m_pIndexBuffer); } void EditorBlockVolumeRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_visibility || m_batches.GetSize() == 0) return; uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOW_MAP; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; float viewDistance = pCamera->CalculateDepthToPoint(GetBoundingBox().GetCenter()); for (uint32 i = 0; i < m_batches.GetSize(); i++) { const RenderBatch &batch = m_batches[i]; // skip batches without shadows if drawing shadow map if (wantedRenderPasses == RENDER_PASS_SHADOW_MAP && !batch.DrawShadows) continue; const Material *pMaterial = m_pPalette->GetMaterial(batch.MaterialIndex); uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(BlockMeshVertexFactory); queueEntry.VertexFactoryFlags = m_vertexFactoryFlags; queueEntry.pMaterial = pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.UserData[0] = i; queueEntry.TintColor = m_tintColor; pRenderQueue->AddRenderable(&queueEntry); } } } void EditorBlockVolumeRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { pCommandList->GetConstants()->SetLocalToWorldMatrix(m_localToWorldMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); m_vertexBuffers.BindBuffers(pCommandList); pCommandList->SetIndexBuffer(m_pIndexBuffer, m_indexFormat, 0); } void EditorBlockVolumeRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { DebugAssert(pQueueEntry->UserData[0] < m_batches.GetSize()); const RenderBatch &batch = m_batches[pQueueEntry->UserData[0]]; pCommandList->DrawIndexed(batch.StartIndex, batch.IndexCount, 0); } bool EditorBlockVolumeRenderProxy::CreateDeviceResources() const { if (m_pPalette != nullptr && !m_pPalette->CreateGPUResources()) return false; return true; } void EditorBlockVolumeRenderProxy::SetTransform(const float4x4 &newLocalToWorldMatrix) { m_localToWorldMatrix = newLocalToWorldMatrix; SetBounds(m_localBoundingBox.GetTransformed(newLocalToWorldMatrix), m_localBoundingSphere.GetTransformed(newLocalToWorldMatrix)); } void EditorBlockVolumeRenderProxy::SetTintColor(bool enabled, uint32 color /*= 0*/) { m_tintEnabled = enabled; m_tintColor = (enabled) ? color : 0xFFFFFFFF; } void EditorBlockVolumeRenderProxy::SetVisibility(bool visible) { m_visibility = visible; } void EditorBlockVolumeRenderProxy::SetShadowFlags(uint32 shadowFlags) { m_shadowFlags = shadowFlags; } void EditorBlockVolumeRenderProxy::BuildMesh(const BlockMeshVolume *pVolume, bool useAmbientOcclusion) { static const uint32 EXTRA_VERTEX_FACTORY_FLAGS = 0; // clear current mesh ClearMesh(); // create mesh BlockMeshBuilder builder; builder.SetPalette(pVolume->GetPalette()); builder.SetFromVolume(pVolume); builder.SetAmbientOcclusionEnabled(useAmbientOcclusion); builder.GenerateMesh(); // no triangles? if (builder.GetOutputBatchCount() == 0) return; // create buffers if (!builder.CreateGPUBuffers(&m_vertexBuffers, &m_vertexFactoryFlags, &m_pIndexBuffer, &m_indexFormat, EXTRA_VERTEX_FACTORY_FLAGS)) return; // fix up palette ref m_pPalette = pVolume->GetPalette(); m_pPalette->AddRef(); // copy batches for (uint32 i = 0; i < builder.GetOutputBatchCount(); i++) { const BlockMeshBuilder::Batch &sourceBatch = builder.GetOutputBatches().GetElement(i); m_batches.Add(RenderBatch(sourceBatch.MaterialIndex, sourceBatch.StartIndex, sourceBatch.NumIndices, sourceBatch.DrawShadows)); } // fix up bounds m_localBoundingBox = builder.GetOutputBoundingBox(); m_localBoundingSphere = builder.GetOutputBoundingSphere(); SetBounds(m_localBoundingBox.GetTransformed(m_localToWorldMatrix), m_localBoundingSphere.GetTransformed(m_localToWorldMatrix)); } void EditorBlockVolumeRenderProxy::ClearMesh() { // release old buffers SAFE_RELEASE(m_pPalette); m_vertexBuffers.Clear(); SAFE_RELEASE(m_pIndexBuffer); m_indexFormat = GPU_INDEX_FORMAT_COUNT; m_batches.Clear(); // fix up bounds m_localBoundingBox = AABox::Zero; m_localBoundingSphere = Sphere::Zero; SetBounds(AABox::Zero, Sphere::Zero); } <file_sep>/Engine/Source/Renderer/ShaderProgramSelector.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderProgramSelector.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Renderer.h" #include "Renderer/RenderQueue.h" #include "Engine/MaterialShader.h" #include "Engine/Material.h" Log_SetChannel(ShaderProgramSelector); ShaderProgramSelector::ShaderProgramSelector(uint32 baseGlobalFlags) : m_pBaseShaderType(nullptr), m_pVertexFactoryType(nullptr), m_pMaterial(nullptr), m_pMaterialShader(nullptr), m_pCurrentProgram(nullptr), m_baseGlobalFlags(baseGlobalFlags), m_globalShaderFlags(0), m_baseShaderFlags(0), m_vertexFactoryFlags(0), m_materialStaticSwitchMask(0), m_dirtyFlags(DirtyGlobalFlags | DirtyBaseShader | DirtyVertexFactory | DirtyMaterialShader | DirtyMaterial) { } void ShaderProgramSelector::SetGlobalFlags(uint32 globalFlags) { uint32 newGlobalFlags = m_baseGlobalFlags | globalFlags; if (newGlobalFlags != m_globalShaderFlags) { m_globalShaderFlags = newGlobalFlags; m_dirtyFlags = DirtyGlobalFlags; } } void ShaderProgramSelector::SetBaseShader(const ShaderComponentTypeInfo *pBaseShaderType, uint32 baseShaderFlags) { if (m_pBaseShaderType != pBaseShaderType || m_baseShaderFlags != baseShaderFlags) { m_pBaseShaderType = pBaseShaderType; m_baseShaderFlags = baseShaderFlags; m_dirtyFlags |= DirtyBaseShader; } } void ShaderProgramSelector::SetVertexFactory(const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags) { if (m_pVertexFactoryType != pVertexFactoryTypeInfo || m_vertexFactoryFlags != vertexFactoryFlags) { m_pVertexFactoryType = pVertexFactoryTypeInfo; m_vertexFactoryFlags = vertexFactoryFlags; m_dirtyFlags |= DirtyVertexFactory; } } void ShaderProgramSelector::SetMaterial(const Material *pMaterial) { if (m_pMaterial != pMaterial) { m_pMaterial = pMaterial; if (pMaterial != nullptr) { if (pMaterial->GetShader() != m_pMaterialShader) { m_pMaterialShader = pMaterial->GetShader(); m_materialStaticSwitchMask = pMaterial->GetShaderStaticSwitchMask(); m_dirtyFlags |= DirtyMaterialShader | DirtyMaterial; } else if (pMaterial->GetShaderStaticSwitchMask() != m_materialStaticSwitchMask) { m_materialStaticSwitchMask = pMaterial->GetShaderStaticSwitchMask(); m_dirtyFlags |= DirtyMaterialShader | DirtyMaterial; } else { m_dirtyFlags |= DirtyMaterial; } } else { m_pMaterialShader = nullptr; m_materialStaticSwitchMask = 0; m_dirtyFlags |= DirtyMaterialShader | DirtyMaterial; } } } void ShaderProgramSelector::SetQueueEntry(const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { uint32 shaderGlobalFlags = 0; if (pQueueEntry->RenderPassMask & RENDER_PASS_TINT) shaderGlobalFlags |= SHADER_GLOBAL_FLAG_MATERIAL_TINT; SetGlobalFlags(shaderGlobalFlags); SetMaterial(pQueueEntry->pMaterial); SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); } ShaderProgram *ShaderProgramSelector::MakeActive(GPUCommandList *pCommandList) { if (m_dirtyFlags == 0) return m_pCurrentProgram; uint32 dirtyFlags = m_dirtyFlags; m_dirtyFlags = 0; if (dirtyFlags & (DirtyGlobalFlags | DirtyBaseShader | DirtyVertexFactory | DirtyMaterialShader)) { m_pCurrentProgram = g_pRenderer->GetShaderProgram(m_globalShaderFlags, m_pBaseShaderType, m_baseShaderFlags, m_pVertexFactoryType, m_vertexFactoryFlags, m_pMaterialShader, m_materialStaticSwitchMask); if (m_pCurrentProgram == nullptr) return nullptr; // bind shader pCommandList->SetShaderProgram(m_pCurrentProgram->GetGPUProgram()); } // bind materials if ((dirtyFlags & DirtyMaterial) && m_pMaterial != nullptr) { if (m_pCurrentProgram == nullptr || !m_pMaterial->BindDeviceResources(pCommandList, m_pCurrentProgram)) return nullptr; } return m_pCurrentProgram; } <file_sep>/Editor/Source/Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.h #pragma once #include "Editor/Common.h" #include "Editor/EditorViewController.h" #include "Renderer/MiniGUIContext.h" #include "Renderer/VertexFactories/PlainVertexFactory.h" #include "Engine/Skeleton.h" class SkeletalAnimationGenerator; class SkeletalAnimation; class SkeletalMesh; class Skeleton; class RenderWorld; class SkeletalMeshRenderProxy; class EditorLightSimulator; class Ui_EditorSkeletalAnimationEditor; class EditorSkeletalAnimationEditor : public QMainWindow { Q_OBJECT public: enum Tool { Tool_Information, Tool_BoneTrack, Tool_RootMotion, Tool_Clipper, Tool_LightManipulator, Tool_Count }; enum State { State_None, State_RotateCamera, State_Count }; public: EditorSkeletalAnimationEditor(); virtual ~EditorSkeletalAnimationEditor(); // render options accessors const EDITOR_CAMERA_MODE GetCameraMode() const { return m_viewController.GetCameraMode(); } const EDITOR_RENDER_MODE GetRenderMode() const { return m_renderMode; } const uint32 GetViewportFlags() const { return m_viewportFlags; } const bool HasViewportFlag(uint32 flag) const { return (m_viewportFlags & flag) != 0; } const Tool GetCurrentTool() const { return m_currentTool; } // mode setters void SetCameraMode(EDITOR_CAMERA_MODE cameraMode); void SetRenderMode(EDITOR_RENDER_MODE renderMode); void SetViewportFlag(uint32 flag); void ClearViewportFlag(uint32 flag); void SetCurrentTool(Tool tool); // creation/loading/saving bool Load(const char *animationName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool Save(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool SaveAs(const char *animationName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void Close(); // generator const SkeletalAnimationGenerator *GetSkeletalAnimationGenerator() const { return m_pGenerator; } // update the preview for a specific frame const uint32 GetFrameCount() const { return m_frameTimes.GetSize(); } bool SetPreviewMeshName(const char *meshName); void SetPreviewFrameNumber(uint32 frameNumber); // flag for redraw void FlagForRedraw() { m_bRedrawPending = true; } private: // resources bool CreateHardwareResources(); void ReleaseHardwareResources(); // validate the animation bool IsValidAnimation() const; // when the file name changes void OnFileNameChanged(); // when the animation changes void UpdateTimeDependantVariables(); // update the hierarchy panel void UpdateHierarchyRecursive(const Skeleton::Bone *pBone, QTreeWidgetItem *pParent); void UpdateHierarchy(); // update the preview mesh transforms void UpdatePreviewBoneTransformRecursive(float time, const Skeleton::Bone *pBone, const Transform *pParentBoneTransform); void UpdatePreviewBoneTransforms(); // update the information tab void UpdateInformationTab(); // draw the scene void Draw(); void DrawGrid(); void DrawView(); void DrawOverlays(GPUContext *pGPUContext, MiniGUIContext *pGUIContext); // --- ui --- Ui_EditorSkeletalAnimationEditor *m_ui; // --- editor info --- EditorViewController m_viewController; EDITOR_RENDER_MODE m_renderMode; uint32 m_viewportFlags; // --- generator --- SkeletalAnimationGenerator *m_pGenerator; String m_animationName; String m_animationFileName; const Skeleton *m_pSkeleton; const SkeletalMesh *m_pPreviewMesh; // --- information generated on demand --- PODArray<float> m_frameTimes; float m_duration; MemArray<Transform> m_previewBoneTransforms; uint32 m_previewFrameNumber; uint32 m_selectedBoneIndex; // --- render mesh --- RenderWorld *m_pRenderWorld; EditorLightSimulator *m_pLightSimulator; SkeletalMeshRenderProxy *m_pPreviewMeshRenderProxy; // --- renderer stuff --- GPUOutputBuffer *m_pSwapChain; WorldRenderer *m_pWorldRenderer; MiniGUIContext m_guiContext; bool m_bHardwareResourcesCreated; bool m_bRedrawPending; // --- state --- int2 m_lastMousePosition; Tool m_currentTool; State m_currentState; //=================================================================================================================================================================== // UI Event Handlers //=================================================================================================================================================================== void ConnectUIEvents(); private: void closeEvent(QCloseEvent *pCloseEvent); private Q_SLOTS: void OnActionOpenMeshClicked(); void OnActionSaveMeshClicked(); void OnActionSaveMeshAsClicked(); void OnActionCloseClicked(); void OnActionCameraPerspectiveTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_PERSPECTIVE); } void OnActionCameraArcballTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_ARCBALL); } void OnActionCameraIsometricTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_ISOMETRIC); } void OnActionViewWireframeTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_WIREFRAME); } void OnActionViewUnlitTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_FULLBRIGHT); } void OnActionViewLitTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_LIT); } void OnActionViewFlagShadowsTriggered(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS); } void OnActionViewFlagWireframeOverlayTriggered(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY); } void OnActionToolInformationTriggered(bool checked) { SetCurrentTool((checked) ? Tool_Information : Tool_Information); } void OnActionToolBoneTrackTriggered(bool checked) { SetCurrentTool((checked) ? Tool_BoneTrack : Tool_Information); } void OnActionToolRootMotionTriggered(bool checked) { SetCurrentTool((checked) ? Tool_RootMotion : Tool_Information); } void OnActionToolClipperTriggered(bool checked) { SetCurrentTool((checked) ? Tool_Clipper : Tool_Information); } void OnActionToolLightManipulatorTriggered(bool checked) { SetCurrentTool((checked) ? Tool_LightManipulator : Tool_Information); } void OnScrubberValueChanged(int value); void OnHierarchyItemClicked(QTreeWidgetItem *pItem, int column); void OnInformationPreviewMeshLinkActivated(const QString &link); void OnClipperSetStartFrameNumberClicked(); void OnClipperSetEndFrameNumberClicked(); void OnClipperClipClicked(); void OnSwapChainWidgetResized(); void OnSwapChainWidgetPaint(); void OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent); void OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent); void OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent); void OnSwapChainWidgetGainedFocusEvent(); void OnFrameExecutionTriggered(float timeSinceLastFrame); }; <file_sep>/Engine/Source/Engine/SDLHeaders.h #pragma once // We disable the preprocessor define to rename main to SDL_main, and do it ourselves #define SDL_MAIN_HANDLED 1 #include <SDL.h> #if Y_COMPILER_MSVC #pragma comment(lib, "SDL2.lib") #endif <file_sep>/Editor/Source/Editor/ResourceBrowser/EditorResourceBrowserWidget.h #pragma once #include "Editor/Common.h" struct Ui_EditorResourceBrowserWidget; class ResourceTypeInfo; class EditorMapWindow; class EditorResourceSelectionDialogModel; class EditorResourceBrowserWidget : public QWidget { Q_OBJECT public: EditorResourceBrowserWidget(EditorMapWindow *pMapWindow, QWidget *parent); virtual ~EditorResourceBrowserWidget(); const String &GetCurrentDirectory() const { return m_currentDirectory; } void NavigateToDirectory(const char *path); private: Ui_EditorResourceBrowserWidget *m_ui; EditorMapWindow *m_pMapWindow; String m_currentDirectory; String m_selectedResourceName; const ResourceTypeInfo *m_pSelectedResourceType; void ConnectUIEvents(); private Q_SLOTS: void OnActionDirectoryBackTriggered(); void OnActionDirectoryUpTriggered(); void OnActionNewDirectoryTriggered(); void OnActionDeleteResourceTriggered(); void OnActionImportStaticMeshTriggered(); void OnActionInsertResourceTriggered(); void OnActionEditBlockMeshTriggered(); void OnActionEditSkeletalMeshTriggered(); void OnActionEditSkeletalAnimationTriggered(); void OnActionEditStaticMeshTriggered(); void OnDirectoryTreeItemClickedOrActivated(const QModelIndex &index); void OnResourceListItemClicked(const QModelIndex &index); void OnResourceListItemActivated(const QModelIndex &index); }; <file_sep>/Engine/Source/Engine/FPSCounter.h #pragma once #include "Engine/Common.h" class Font; class MiniGUIContext; class GPUContext; class FPSCounter { public: static const uint32 KEEP_FRAME_TIME_COUNT = 200; public: FPSCounter(); ~FPSCounter(); // overall average fps const float GetFPS() const { return m_fps; } // frame times are behind one frame const float GetFrameTime() const { return m_lastFrameTime; } // call when starting the frame void BeginFrame(); // call when the game thread finishes and is waiting for the render thread void EndGameThreadFrame(); // call when the render thread finishes and is waiting for the game thread void EndRenderThreadFrame(); // draw a debug message of the current fps to the screen void DrawDetails(const Font *pFont, MiniGUIContext *pGUIContext, int32 startX = -400, int32 startY = 0, uint32 fontSize = 16) const; // resources GPUContext *GetGPUContext() { return m_pGPUContext; } void SetGPUContext(GPUContext *pGPUContext) { m_pGPUContext = pGPUContext; } bool CreateGPUResources(); void ReleaseGPUResources(); // access last frame time void GetFrameTimeHistory(float *pFrameTimes, uint32 frameCount) const; private: GPUContext *m_pGPUContext; Timer m_lastFrameStartTimer; Timer m_gameThreadTimer; Timer m_renderThreadTimer; float m_accumulatedTime; uint32 m_framesRendered; float m_fps; float m_lastFrameTime; float m_lastGameFrameTime; float m_lastRenderFrameTime; float m_lastFrameTimes[KEEP_FRAME_TIME_COUNT]; uint32 m_lastFrameTimesIndex; uint32 m_lastDrawCallCount; size_t m_lastMemoryUsage; size_t m_lastScriptMemoryUsage; }; <file_sep>/Engine/Source/Core/ObjectTypeInfo.h #pragma once #include "Core/Common.h" #include "Core/TypeRegistry.h" #include "Core/Property.h" // Constants. #define INVALID_OBJECT_TYPE_INDEX (0xFFFFFFFF) // Forward declare the factory type. class Object; struct ObjectFactory; // // ObjectTypeInfo // class ObjectTypeInfo { public: // constructors ObjectTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory); virtual ~ObjectTypeInfo(); // accessors const uint32 GetTypeIndex() const { return m_iTypeIndex; } const uint32 GetInheritanceDepth() const { return m_iInheritanceDepth; } const char *GetTypeName() const { return m_strTypeName; } const ObjectTypeInfo *GetParentType() const { return m_pParentType; } ObjectFactory *GetFactory() const { return m_pFactory; } // type information // currently only does single inheritance bool IsDerived(const ObjectTypeInfo *pTypeInfo) const; // properties const PROPERTY_DECLARATION *GetPropertyDeclarationByName(const char *PropertyName) const; const PROPERTY_DECLARATION *GetPropertyDeclarationByIndex(uint32 Index) const { DebugAssert(Index < m_nPropertyDeclarations); return m_ppPropertyDeclarations[Index]; } uint32 GetPropertyCount() const { return m_nPropertyDeclarations; } // only called once. virtual void RegisterType(); virtual void UnregisterType(); protected: uint32 m_iTypeIndex; uint32 m_iInheritanceDepth; const char *m_strTypeName; const ObjectTypeInfo *m_pParentType; ObjectFactory *m_pFactory; // properties const PROPERTY_DECLARATION *m_pSourcePropertyDeclarations; const PROPERTY_DECLARATION **m_ppPropertyDeclarations; uint32 m_nPropertyDeclarations; // TYPE REGISTRY public: typedef TypeRegistry<ObjectTypeInfo> RegistryType; static RegistryType &GetRegistry(); // END TYPE REGISTRY }; // // ObjectFactory // struct ObjectFactory { virtual Object *CreateObject() = 0; virtual void DeleteObject(Object *pObject) = 0; }; // Macros #define DECLARE_OBJECT_TYPE_INFO(Type, ParentType) \ private: \ static ObjectTypeInfo s_typeInfo; \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ObjectTypeInfo *StaticTypeInfo() { return &s_typeInfo; } \ static ObjectTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } #define DECLARE_OBJECT_PROPERTY_MAP(Type) \ private: \ static const PROPERTY_DECLARATION s_propertyDeclarations[]; \ static const PROPERTY_DECLARATION *StaticPropertyMap() { return s_propertyDeclarations; } #define DECLARE_OBJECT_NO_PROPERTIES(Type) \ private: \ static const PROPERTY_DECLARATION *StaticPropertyMap() { return nullptr; } #define DEFINE_OBJECT_TYPE_INFO(Type) \ ObjectTypeInfo Type::s_typeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::StaticPropertyMap(), Type::StaticFactory()) #define DECLARE_OBJECT_NO_FACTORY(Type) \ public: \ static ObjectFactory *StaticFactory() { return nullptr; } #define BEGIN_OBJECT_PROPERTY_MAP(Type) \ const PROPERTY_DECLARATION Type::s_propertyDeclarations[] = { #define END_OBJECT_PROPERTY_MAP() \ PROPERTY_TABLE_MEMBER(NULL, PROPERTY_TYPE_COUNT, 0, NULL, NULL, NULL, NULL, NULL, NULL) \ }; #define OBJECT_TYPEINFO(Type) Type::StaticTypeInfo() #define OBJECT_TYPEINFO_PTR(Ptr) Ptr->StaticTypeInfo() #define OBJECT_MUTABLE_TYPEINFO(Type) Type::StaticMutableTypeInfo() #define OBJECT_MUTABLE_TYPEINFO_PTR(Type) Type->StaticMutableTypeInfo() <file_sep>/Engine/Source/Core/ChunkFileWriter.cpp #include "Core/PrecompiledHeader.h" #include "Core/ChunkFileWriter.h" #include "Core/ChunkDataFormat.h" #include "YBaseLib/ByteStream.h" ChunkFileWriter::ChunkFileWriter() { m_iBaseOffset = 0; m_pStream = NULL; m_pChunkHeaders = NULL; m_nChunks = 0; m_iCurrentChunk = 0xFFFFFFFF; m_iCurrentChunkOffset = 0; m_iCurrentChunkSize = 0; m_pStringData = NULL; m_iStringDataSize = 0; m_iStringDataBufferSize = 0; m_iStringCount = 0; } ChunkFileWriter::~ChunkFileWriter() { if (m_pStream != NULL) Close(); } bool ChunkFileWriter::Initialize(ByteStream *pStream, uint32 NumChunks) { uint32 i; m_iBaseOffset = pStream->GetPosition(); m_pStream = pStream; m_pStream->AddRef(); m_nChunks = NumChunks; m_pChunkHeaders = new Chunk[m_nChunks]; // build empty header DF_CHUNKFILE_HEADER emptyHeader; Y_memzero(&emptyHeader, sizeof(emptyHeader)); emptyHeader.Magic = ~(uint32)DF_CHUNKFILE_HEADER_MAGIC; m_pStream->Write2(&emptyHeader, sizeof(emptyHeader)); DF_CHUNKFILE_CHUNK_HEADER emptyChunkHeader; emptyChunkHeader.ChunkOffset = 0; emptyChunkHeader.ChunkSize = 0; for (i = 0; i < m_nChunks; i++) { // store our version m_pChunkHeaders[i].Offset = 0; m_pChunkHeaders[i].Size = 0; // and write an empty entry to the file m_pStream->Write2(&emptyChunkHeader, sizeof(emptyChunkHeader)); } return !pStream->InErrorState(); } bool ChunkFileWriter::Close() { DebugAssert(m_iCurrentChunk == 0xFFFFFFFF); uint64 chunksEndOffset = m_pStream->GetPosition(); // write the strings, if any if (m_iStringDataSize > 0) m_pStream->Write2(m_pStringData, m_iStringDataSize); // build header DF_CHUNKFILE_HEADER chunkFileHeader; chunkFileHeader.Magic = DF_CHUNKFILE_HEADER_MAGIC; chunkFileHeader.HeaderSize = sizeof(chunkFileHeader); chunkFileHeader.ChunkCount = m_nChunks; chunkFileHeader.TotalSize = (m_pStream->GetPosition() - m_iBaseOffset); chunkFileHeader.StringsOffset = (chunksEndOffset - m_iBaseOffset); chunkFileHeader.StringsSize = m_iStringDataSize; chunkFileHeader.StringsCount = m_iStringCount; // rewrite header m_pStream->SeekAbsolute(m_iBaseOffset); m_pStream->Write2(&chunkFileHeader, sizeof(chunkFileHeader)); // rewrite chunk headers uint32 i; for (i = 0; i < m_nChunks; i++) { DF_CHUNKFILE_CHUNK_HEADER chunkHeader; chunkHeader.ChunkOffset = m_pChunkHeaders[i].Offset; chunkHeader.ChunkSize = m_pChunkHeaders[i].Size; m_pStream->Write2(&chunkHeader, sizeof(chunkHeader)); } // seek back to the end m_pStream->SeekAbsolute(m_iBaseOffset + chunkFileHeader.TotalSize); // get result bool closeResult = !(m_pStream->InErrorState()); // delete data if (m_pStringData != NULL) { Y_free(m_pStringData); m_pStringData = NULL; } m_iStringDataSize = 0; m_iStringDataBufferSize = 0; m_iStringCount = 0; m_iBaseOffset = 0; delete[] m_pChunkHeaders; m_nChunks = 0; m_pStream->Release(); m_pStream = NULL; return closeResult; } uint32 ChunkFileWriter::AddString(const char *str) { uint32 strLength = Y_strlen(str) + 1; if ((strLength + m_iStringDataSize) > m_iStringDataBufferSize) { m_iStringDataBufferSize = Max(m_iStringDataBufferSize * 2, m_iStringDataSize + strLength); m_pStringData = (char *)realloc(m_pStringData, m_iStringDataBufferSize); DebugAssert(m_pStringData != NULL); } Y_memcpy(m_pStringData + m_iStringDataSize, str, strLength); m_iStringDataSize += strLength; return m_iStringCount++; } void ChunkFileWriter::BeginChunk(uint32 ChunkIndex) { DebugAssert(m_iCurrentChunk == 0xFFFFFFFF); m_iCurrentChunk = ChunkIndex; m_iCurrentChunkOffset = m_pStream->GetPosition() - m_iBaseOffset; m_iCurrentChunkSize = 0; } void ChunkFileWriter::WriteChunkData(const void *pData, uint32 cbData) { m_pStream->Write(pData, cbData); m_iCurrentChunkSize += cbData; } void ChunkFileWriter::EndChunk() { DebugAssert(m_iCurrentChunk != 0xFFFFFFFF && m_iCurrentChunk < m_nChunks); DebugAssert(m_iCurrentChunkSize <= 0xFFFFFFFF); m_pChunkHeaders[m_iCurrentChunk].Offset = m_iCurrentChunkOffset; m_pChunkHeaders[m_iCurrentChunk].Size = static_cast<uint32>(m_iCurrentChunkSize); m_iCurrentChunk = 0xFFFFFFFF; m_iCurrentChunkOffset = 0; m_iCurrentChunkSize = 0; } <file_sep>/Engine/Source/Core/Object.cpp #include "Core/PrecompiledHeader.h" #include "Core/Object.h" // Have to define this manually as Object has no parent class. ObjectTypeInfo Object::s_typeInfo("Object", nullptr, nullptr, nullptr); // "borrowed" from ReferenceCounted.cpp static const uint32 ReferenceCountValidValue = 0x11C0FFEE; static const uint32 ReferenceCountInvalidValue = 0xDEADC0DE; Object::Object(const ObjectTypeInfo *pObjectTypeInfo /* = &s_typeInfo */) : m_pObjectTypeInfo(pObjectTypeInfo), m_iReferenceCount(1), m_iReferenceCountValid(ReferenceCountValidValue) { } Object::~Object() { // Flag reference count as invalid, that way any methods on bad pointers will fail in debug builds. m_iReferenceCountValid = ReferenceCountInvalidValue; } void Object::AddRef() const { Y_AtomicIncrement(m_iReferenceCount); } uint32 Object::Release() const { DebugAssert(m_iReferenceCount > 0 && m_iReferenceCountValid == ReferenceCountValidValue); uint32 NewRefCount = Y_AtomicDecrement(m_iReferenceCount); if (NewRefCount == 0) delete this; //m_pObjectTypeInfo->GetFactory()->DeleteObject(const_cast<Object *>(this)); return NewRefCount; } <file_sep>/Engine/Source/Core/ImageCodecDevIL.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "Core/PixelFormat.h" #include "YBaseLib/Memory.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/Log.h" Log_SetChannel(ImageCodecDevIL); #if 0 #define IL_USE_PRAGMA_LIBS 1 #include <IL/il.h> #include <IL/ilu.h> struct ILImageFormatMapping { ILint ilChannels; ILint ilFormat; ILint ilType; PIXEL_FORMAT OurPixelFormat; }; static const ILImageFormatMapping s_ILImageFormatMapping[] = { // chn format type pf { 4, IL_RGBA, IL_UNSIGNED_BYTE, PIXEL_FORMAT_R8G8B8A8_UNORM }, // default { 3, IL_RGB, IL_UNSIGNED_BYTE, PIXEL_FORMAT_R8G8B8_UNORM }, { 4, IL_RGBA, IL_FLOAT, PIXEL_FORMAT_R32G32B32A32_FLOAT }, }; static PIXEL_FORMAT GetPixelFormatforILFormat(ILint ilChannels, ILint ilFormat, ILint ilType) { uint32 i; for (i = 0; i < countof(s_ILImageFormatMapping); i++) { const ILImageFormatMapping *m = &s_ILImageFormatMapping[i]; if (m->ilChannels == ilChannels && m->ilFormat == ilFormat && m->ilType == ilType) return m->OurPixelFormat; } return PIXEL_FORMAT_UNKNOWN; } static bool GetILFormatForPixelFormat(ILint *ilChannels, ILint *ilFormat, ILint *ilType, PIXEL_FORMAT pixelFormat) { uint32 i; for (i = 0; i < countof(s_ILImageFormatMapping); i++) { const ILImageFormatMapping *m = &s_ILImageFormatMapping[i]; if (m->OurPixelFormat == pixelFormat) { *ilChannels = m->ilChannels; *ilFormat = m->ilFormat; *ilType = m->ilType; return true; } } return false; } static void InitializeIL() { static bool ilInitialized = false; if (!ilInitialized) { ilInit(); iluInit(); ilInitialized = true; } } bool __ImageCodecDevIL_ResizeImage(IMAGE_RESIZE_FILTER resizeFilter, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 newWidth, uint32 newHeight, const byte *pInImageData, byte *pOutImageData) { InitializeIL(); ILint ilChannels, ilFormat, ilType; if (!GetILFormatForPixelFormat(&ilChannels, &ilFormat, &ilType, pixelFormat)) { Log_ErrorPrintf("__ImageCodecDevIL_ResizeImage: Unknown pixel format %u (%s)", pixelFormat, PixelFormat_GetPixelFormatInfo(pixelFormat)->Name); return false; } ILuint imageName = 0; imageName = ilGenImage(); if (imageName == 0) return false; ILenum ilResizeFilter; uint32 pixelsCopied; bool result = false; //uint32 srcImageSize = PixelFormat_CalculateImageSize(pixelFormat, width, height, 1); uint32 dstImageSize = PixelFormat_CalculateImageSize(pixelFormat, newWidth, newHeight, 1); // bind image ilBindImage(imageName); // copy image in if (!ilTexImage(width, height, 1, (ILubyte)ilChannels, ilFormat, ilType, (void *)pInImageData)) { Log_ErrorPrintf("__ImageCodecDevIL_ResizeImage: Failed to copy image in: %s (%u)", iluGetString(ilGetError()), ilGetError()); goto CLEANUP; } // resize it switch (resizeFilter) { case IMAGE_RESIZE_FILTER_BOX: ilResizeFilter = ILU_SCALE_BOX; break; case IMAGE_RESIZE_FILTER_BILINEAR: ilResizeFilter = ILU_SCALE_TRIANGLE; break; case IMAGE_RESIZE_FILTER_BICUBIC: ilResizeFilter = ILU_SCALE_MITCHELL; break; case IMAGE_RESIZE_FILTER_BSPLINE: ilResizeFilter = ILU_SCALE_BSPLINE; break; case IMAGE_RESIZE_FILTER_LANCZOS3: ilResizeFilter = ILU_SCALE_LANCZOS3; break; default: { Log_ErrorPrintf("__ImageCodecDevIL_ResizeImage: Unknown resize filter %u.", (uint32)resizeFilter); goto CLEANUP; } break; } // set filter and do resize iluImageParameter(ILU_FILTER, ilResizeFilter); if (!iluScale(newWidth, newHeight, 1)) { Log_ErrorPrintf("__ImageCodecDevIL_ResizeImage: iluScale failed: %s (%u)", iluGetString(ilGetError()), ilGetError()); goto CLEANUP; } // copy pixels out pixelsCopied = ilCopyPixels(0, 0, 0, newWidth, newHeight, 1, ilFormat, ilType, pOutImageData); if (pixelsCopied != dstImageSize) { Log_ErrorPrintf("__ImageCodecDevIL_ResizeImage: Unexpected pixel count (%u vs %u)", pixelsCopied, dstImageSize); goto CLEANUP; } // ok result = true; CLEANUP: ilBindImage(0); if (imageName != 0) ilDeleteImage(imageName); return result; } class ImageCodecDevIL : public ImageCodec { public: const char *GetCodecName() const { return "DevIL"; } bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyList &decoderOptions = PropertyList::EmptyPropertyList) { ILuint imageName = 0; byte *pImageMemory = NULL; bool result = false; InitializeIL(); // get stream length uint32 streamLength = (uint32)pInputStream->GetSize(); if (streamLength == 0) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: Zero image length."); return false; } // allocate memory for the entire stream pImageMemory = new byte[streamLength]; if (!pInputStream->Read2(pImageMemory, streamLength)) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: Failed to read image."); return false; } // gen image name imageName = ilGenImage(); if (imageName == 0) return false; // vars uint32 imageWidth, imageHeight, imageDepth; ILint ilChannels, ilFormat, ilType; PIXEL_FORMAT imagePixelFormat; uint32 pixelsCopied; // bind image ilBindImage(imageName); // load the image if (!ilLoadL(IL_TYPE_UNKNOWN, pImageMemory, streamLength)) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: ilLoadImage failed: %s (%u)", iluGetString(ilGetError()), ilGetError()); goto CLEANUP; } // get image params imageWidth = ilGetInteger(IL_IMAGE_WIDTH); imageHeight = ilGetInteger(IL_IMAGE_HEIGHT); imageDepth = ilGetInteger(IL_IMAGE_DEPTH); ilChannels = ilGetInteger(IL_IMAGE_CHANNELS); ilFormat = ilGetInteger(IL_IMAGE_FORMAT); ilType = ilGetInteger(IL_IMAGE_TYPE); if (imageWidth == 0 || imageHeight == 0 || imageDepth == 0) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: Invalid dimensions (%i, %i, %i)", imageWidth, imageHeight, imageDepth); goto CLEANUP; } // map pixelformat imagePixelFormat = GetPixelFormatforILFormat(ilChannels, ilFormat, ilType); if (imagePixelFormat == PIXEL_FORMAT_UNKNOWN) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: Unknown pixel format (%i, %i, %i)", ilChannels, ilFormat, ilType); goto CLEANUP; } // setup image pOutputImage->Create(imagePixelFormat, imageWidth, imageHeight, imageDepth); // copy pixels pixelsCopied = ilCopyPixels(0, 0, 0, imageWidth, imageHeight, imageDepth, ilFormat, ilType, pOutputImage->GetData()); if (pixelsCopied != pOutputImage->GetDataSize()) { Log_ErrorPrintf("ImageCodecDevIL::DecodeImage: Failed to copy pixels (got %u, expected %u)", pixelsCopied, pOutputImage->GetDataSize()); pOutputImage->Delete(); goto CLEANUP; } // done result = true; CLEANUP: if (pImageMemory != NULL) delete[] pImageMemory; if (imageName != 0) { ilBindImage(0); ilDeleteImage(imageName); } return result; } bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyList &encoderOptions = PropertyList::EmptyPropertyList) { return false; } }; static ImageCodecDevIL s_DevILImageCodec; ImageCodec *__GetImageCodecDevIL() { return &s_DevILImageCodec; } #else ImageCodec *__GetImageCodecDevIL() { return NULL; } #endif <file_sep>/Engine/Source/Core/KDTree.h #ifndef __Y_YMAIN_KDTREE_H #define __Y_YMAIN_KDTREE_H #include "ymain/Common.h" #include "ymain/Vector3.h" #include "ymain/AABox.h" Y_NAMESPACE_BEGIN template<class T> class KDTree { // public methods public: KDTree() { // allocate root node m_root = createNewNode(AABox::infinite); } ~KDTree() { // delete root node, this will delete all other nodes deleteNode(m_root); } // insert a member into the tree void insert(T m, const AABox &bounds) { // find node Node *node = findDeepestNode(bounds); // create member Member member; member.val = m; member.node = node; member.bounds = bounds; // store in m_members m_members.push_back(&member); // small hack to get a pointer to the list's allocated data Member *memberPtr = &(*m_members.back()); // store in the node's members node->members.push_back(memberPtr); } // remove a member from the tree void remove(T m) { // find in the member list MemberList::iterator itr = std::find(m_members.begin(), m_members.end(), m); Y_VerifyMsg(itr != m_members.end(), "Trying to remove a non-member from KDTree"); // dereference the iterator Member &member = *itr; // find in the node list MemberPtrList::iterator pitr = std::find(member.node->members.begin(), member.node->members.end(), &member); Y_VerifyMsg(pitr != member.node->members.end(), "Internal KDTree corruption"); // remove from the node's member list member.node->members.erase(pitr); // remove from the main member list m_members.erase(itr); } // enable/disable automatic splitting. // get the size of the tree inline size_t getSize() const { return m_members.size(); } // private classes private: // forward declare node class class Node; // member type struct Member { T val; // actual member AABox bounds; // we cache the bounds here for faster access Node *node; // node this member is located in }; // list types typedef std::list<Member> MemberList; typedef std::list<Member *> MemberPtrList; // node type struct Node { AABox bounds; // bounds of node MemberPtrList members; // objects in node Node *children[2]; // children of node float splitLocation; // distance along split plane that split occurred uint8 splitAxis; // axis that we split along // quickly determine if the node is a leaf node inline bool isLeaf() const { return (children[0] != NULL); } }; // private methods private: // find the deepest node that would contain the specified box // it may not necessarily return a Node *findDeepestNode(const AABox &box) { Node *node = m_root; while (1) { if (node->isLeaf()) { // node is a leaf node, so we can't go any deeper. return node; } if (box.GetHigh()[node->splitAxis] < node->splitLocation) { // bounds finish before the splitting plane, recurse into this node node = node->children[0]; } else if (box.GetLow()[node->splitAxis] > node->splitLocation) { // bounds start after splitting plane, recurse into right child node = node->children[1]; } else { // bounds are inside this node, but overlap the splitting plane // we will return this node. return node; } } } // create a new node Node *createNewNode(AABox &bounds) { Node *node = new Node; node->splitAxis = 0; node->splitLocation = Y_finf(); node->bounds = bounds; node->children[0] = NULL; node->children[1] = NULL; return node; } // delete a node and all its children recursively Node *deleteNode(Node *node) { if (node->children[0] != NULL) deleteNode(node->children[0]); if (node->children[1] != NULL) deleteNode(node->children[1]); delete node; } // private variables private: Node *m_root; MemberList m_members; bool m_autoSplit; uint32 m_splitThreshold; }; Y_NAMESPACE_END #endif // __Y_YMAIN_KDTREE_H <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphNode.h #pragma once #include "ResourceCompiler/ShaderGraphNodeType.h" class XMLReader; class XMLWriter; class ShaderGraph; class ShaderGraphNode; class ShaderGraphCompiler; enum SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION { SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NONE, SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NORMAL_MAP, SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_COUNT, }; namespace NameTables { Y_Declare_NameTable(ShaderGraphTextureSampleUnpackOperation); } class ShaderGraphNodeInput { public: ShaderGraphNodeInput(); ~ShaderGraphNodeInput(); const ShaderGraphNode *GetNode() const { return m_pNode; } const SHADER_GRAPH_NODE_INPUT *GetInputDesc() const { return m_pInputDesc; } const uint32 GetInputIndex() const { return m_iInputIndex; } const ShaderGraphNode *GetSourceNode() const { return m_pSourceNode; } uint32 GetSourceOutputIndex() const { return m_iSourceOutputIndex; } SHADER_GRAPH_VALUE_SWIZZLE GetSwizzle() const { return m_eSwizzle; } SHADER_GRAPH_VALUE_SWIZZLE GetFixupSwizzle() const { return m_eFixupSwizzle; } SHADER_PARAMETER_TYPE GetValueType() const { return m_eValueType; } bool IsLinked() const { return (m_pSourceNode != NULL); } void Init(ShaderGraphNode *pNode, uint32 InputIndex, const SHADER_GRAPH_NODE_INPUT *pInputDesc); void SetExpectedType(SHADER_PARAMETER_TYPE ExpectedType); bool SetLink(const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle); void ClearLink(); bool SetFixupSwizzle(SHADER_PARAMETER_TYPE expectedOutputType); void ClearFixupSwizzle(); static bool CanSwizzleType(SHADER_PARAMETER_TYPE ValueType, SHADER_GRAPH_VALUE_SWIZZLE Swizzle); static SHADER_PARAMETER_TYPE GetTypeAfterSwizzle(SHADER_PARAMETER_TYPE ValueType, SHADER_GRAPH_VALUE_SWIZZLE Swizzle); static bool CanAutoTruncateType(SHADER_GRAPH_VALUE_SWIZZLE *pSwizzle, SHADER_PARAMETER_TYPE expectedType, SHADER_PARAMETER_TYPE valueType); protected: ShaderGraphNode *m_pNode; uint32 m_iInputIndex; const SHADER_GRAPH_NODE_INPUT *m_pInputDesc; const ShaderGraphNode *m_pSourceNode; uint32 m_iSourceOutputIndex; SHADER_GRAPH_VALUE_SWIZZLE m_eSwizzle; SHADER_GRAPH_VALUE_SWIZZLE m_eFixupSwizzle; SHADER_PARAMETER_TYPE m_eValueType; }; class ShaderGraphNodeOutput { public: ShaderGraphNodeOutput(); ~ShaderGraphNodeOutput(); const SHADER_GRAPH_NODE_OUTPUT *GetOutputDesc() const { return m_pOutputDesc; } const uint32 GetOutputIndex() const { return m_iOutputIndex; } SHADER_PARAMETER_TYPE GetValueType() const { return m_eValueType; } uint32 GetLinkCount() const { return m_iLinkCount; } void Init(ShaderGraphNode *pNode, uint32 OutputIndex, const SHADER_GRAPH_NODE_OUTPUT *pOutputDesc); void SetValueType(SHADER_PARAMETER_TYPE NewValueType); void AddLinkReference() const { m_iLinkCount++; } void RemoveLinkReference() const { DebugAssert(m_iLinkCount > 0); m_iLinkCount--; } protected: ShaderGraphNode *m_pNode; const SHADER_GRAPH_NODE_OUTPUT *m_pOutputDesc; uint32 m_iOutputIndex; SHADER_PARAMETER_TYPE m_eValueType; mutable uint32 m_iLinkCount; }; class ShaderGraphNode : public Object { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode, Object); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode); public: ShaderGraphNode(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ShaderGraphNode(); // Retrieves the type information for this object. const ShaderGraphNodeTypeInfo *GetTypeInfo() const { return m_pTypeInfo; } // Node ID. const uint32 GetID() const { return m_iID; } void SetID(uint32 ID) { m_iID = ID; } // Node name. const String &GetName() const { return m_strName; } void SetName(const char *Name) { m_strName = Name; } // Shader graph editor position. const int2 &GetGraphEditorPosition() const { return m_GraphEditorPosition; } void SetGraphEditorPosition(const int2 &NewPosition) { m_GraphEditorPosition = NewPosition; } // Input nodes. const uint32 GetInputCount() const { return m_nInputs; } const ShaderGraphNodeInput *GetInput(uint32 i) const { DebugAssert(i < m_nInputs); return &m_pInputs[i]; } ShaderGraphNodeInput *GetInput(uint32 i) { DebugAssert(i < m_nInputs); return &m_pInputs[i]; } // Number of nodes that have this node linked to their input. const uint32 GetOutputCount() const { return m_nOutputs; } const ShaderGraphNodeOutput *GetOutput(uint32 i) const { DebugAssert(i < m_nOutputs); return &m_pOutputs[i]; } ShaderGraphNodeOutput *GetOutput(uint32 i) { DebugAssert(i < m_nOutputs); return &m_pOutputs[i]; } // Connection events. virtual bool OnInputConnectionChange(uint32 InputIndex); // Loading/saving to XML. virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader); virtual void SaveToXML(XMLWriter &xmlWriter) const; // For compiler. virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const; // Helper function for looking up type info based on short names // Optimize me at some point static const ShaderGraphNodeTypeInfo *FindTypeInfoForShortName(const char *shortName); protected: const ShaderGraphNodeTypeInfo *m_pTypeInfo; uint32 m_iID; String m_strName; // Inputs. ShaderGraphNodeInput *m_pInputs; uint32 m_nInputs; // Outputs. ShaderGraphNodeOutput *m_pOutputs; uint32 m_nOutputs; // Position in graph editor. int2 m_GraphEditorPosition; }; <file_sep>/Engine/Source/MathLib/SIMDVectorf_sse.cpp #include "MathLib/SIMDVectorf.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #if Y_CPU_SSE_LEVEL >= 1 // should be the same for all vector implementations SIMDVector2f::SIMDVector2f(const Vector2f &v) { Set(v.x, v.y); } SIMDVector3f::SIMDVector3f(const Vector3f &v) { Set(v.x, v.y, v.z); } SIMDVector4f::SIMDVector4f(const Vector4f &v) { Set(v.x, v.y, v.z, v.w); } void SIMDVector2f::Set(const Vector2f &v) { Set(v.x, v.y); } void SIMDVector3f::Set(const Vector3f &v) { Set(v.x, v.y, v.z); } void SIMDVector4f::Set(const Vector4f &v) { Set(v.x, v.y, v.z, v.w); } SIMDVector2f &SIMDVector2f::operator=(const Vector2f &v) { Set(v.x, v.y); return *this; } SIMDVector3f &SIMDVector3f::operator=(const Vector3f &v) { Set(v.x, v.y, v.z); return *this; } SIMDVector4f &SIMDVector4f::operator=(const Vector4f &v) { Set(v.x, v.y, v.z, v.w); return *this; } ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorUnitX[4] = { 1.0f, 0.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorUnitY[4] = { 0.0f, 1.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorUnitZ[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorUnitW[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorNegativeUnitX[4] = { -1.0f, 0.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorNegativeUnitY[4] = { 0.0f, -1.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorNegativeUnitZ[4] = { 0.0f, 0.0f, -1.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __VectorNegativeUnitW[4] = { 0.0f, 0.0f, 0.0f, -1.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector2fZero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector2fOne[4] = { 1.0f, 1.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector2fNegativeOne[4] = { -1.0f, -1.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector2fInfinite[4] = { Y_FLT_INFINITE, Y_FLT_INFINITE, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector2fNegativeInfinite[4] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE, 0.0f, 0.0f }; const SIMDVector2f &SIMDVector2f::Zero = reinterpret_cast<const SIMDVector2f &>(__Vector2fZero); const SIMDVector2f &SIMDVector2f::One = reinterpret_cast<const SIMDVector2f &>(__Vector2fOne); const SIMDVector2f &SIMDVector2f::NegativeOne = reinterpret_cast<const SIMDVector2f &>(__Vector2fNegativeOne); const SIMDVector2f &SIMDVector2f::Infinite = reinterpret_cast<const SIMDVector2f &>(__Vector2fInfinite); const SIMDVector2f &SIMDVector2f::NegativeInfinite = reinterpret_cast<const SIMDVector2f &>(__Vector2fNegativeInfinite); const SIMDVector2f &SIMDVector2f::UnitX = reinterpret_cast<const SIMDVector2f &>(__VectorUnitX); const SIMDVector2f &SIMDVector2f::UnitY = reinterpret_cast<const SIMDVector2f &>(__VectorUnitY); const SIMDVector2f &SIMDVector2f::NegativeUnitX = reinterpret_cast<const SIMDVector2f &>(__VectorNegativeUnitX); const SIMDVector2f &SIMDVector2f::NegativeUnitY = reinterpret_cast<const SIMDVector2f &>(__VectorNegativeUnitY); ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector3fZero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector3fOne[4] = { 1.0f, 1.0f, 1.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector3fNegativeOne[4] = { -1.0f, -1.0f, -1.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector3fInfinite[4] = { Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector3fNegativeInfinite[4] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE, 0.0f }; const SIMDVector3f &SIMDVector3f::Zero = reinterpret_cast<const SIMDVector3f &>(__Vector3fZero); const SIMDVector3f &SIMDVector3f::One = reinterpret_cast<const SIMDVector3f &>(__Vector3fOne); const SIMDVector3f &SIMDVector3f::NegativeOne = reinterpret_cast<const SIMDVector3f &>(__Vector3fNegativeOne); const SIMDVector3f &SIMDVector3f::Infinite = reinterpret_cast<const SIMDVector3f &>(__Vector3fInfinite); const SIMDVector3f &SIMDVector3f::NegativeInfinite = reinterpret_cast<const SIMDVector3f &>(__Vector3fNegativeInfinite); const SIMDVector3f &SIMDVector3f::UnitX = reinterpret_cast<const SIMDVector3f &>(__VectorUnitX); const SIMDVector3f &SIMDVector3f::UnitY = reinterpret_cast<const SIMDVector3f &>(__VectorUnitY); const SIMDVector3f &SIMDVector3f::UnitZ = reinterpret_cast<const SIMDVector3f &>(__VectorUnitZ); const SIMDVector3f &SIMDVector3f::NegativeUnitX = reinterpret_cast<const SIMDVector3f &>(__VectorNegativeUnitX); const SIMDVector3f &SIMDVector3f::NegativeUnitY = reinterpret_cast<const SIMDVector3f &>(__VectorNegativeUnitY); const SIMDVector3f &SIMDVector3f::NegativeUnitZ = reinterpret_cast<const SIMDVector3f &>(__VectorNegativeUnitZ); ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector4fZero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector4fOne[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector4fNegativeOne[4] = { -1.0f, -1.0f, -1.0f, -1.0f }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector4fInfinite[4] = { Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const float __Vector4fNegativeInfinite[4] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE }; const SIMDVector4f &SIMDVector4f::Zero = reinterpret_cast<const SIMDVector4f &>(__Vector4fZero); const SIMDVector4f &SIMDVector4f::One = reinterpret_cast<const SIMDVector4f &>(__Vector4fOne); const SIMDVector4f &SIMDVector4f::NegativeOne = reinterpret_cast<const SIMDVector4f &>(__Vector4fNegativeOne); const SIMDVector4f &SIMDVector4f::Infinite = reinterpret_cast<const SIMDVector4f &>(__Vector4fInfinite); const SIMDVector4f &SIMDVector4f::NegativeInfinite = reinterpret_cast<const SIMDVector4f &>(__Vector4fNegativeInfinite); const SIMDVector4f &SIMDVector4f::UnitX = reinterpret_cast<const SIMDVector4f &>(__VectorUnitX); const SIMDVector4f &SIMDVector4f::UnitY = reinterpret_cast<const SIMDVector4f &>(__VectorUnitY); const SIMDVector4f &SIMDVector4f::UnitZ = reinterpret_cast<const SIMDVector4f &>(__VectorUnitZ); const SIMDVector4f &SIMDVector4f::UnitW = reinterpret_cast<const SIMDVector4f &>(__VectorUnitW); const SIMDVector4f &SIMDVector4f::NegativeUnitX = reinterpret_cast<const SIMDVector4f &>(__VectorNegativeUnitX); const SIMDVector4f &SIMDVector4f::NegativeUnitY = reinterpret_cast<const SIMDVector4f &>(__VectorNegativeUnitY); const SIMDVector4f &SIMDVector4f::NegativeUnitZ = reinterpret_cast<const SIMDVector4f &>(__VectorNegativeUnitZ); const SIMDVector4f &SIMDVector4f::NegativeUnitW = reinterpret_cast<const SIMDVector4f &>(__VectorNegativeUnitW); #endif <file_sep>/Engine/Source/Core/DDSFormat.h #pragma once // adapted from DDS.h //------------------------------------------------------------------------------------------------------------------------------------------------------------- #pragma pack(push,1) #ifndef DDS_MAKEFOURCC #define DDS_MAKEFOURCC(ch0, ch1, ch2, ch3) \ ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) | \ ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24 )) #endif //defined(DDS_MAKEFOURCC) #define DDS_MAGIC 0x20534444 // "DDS " struct DDS_PIXELFORMAT { uint32 dwSize; uint32 dwFlags; uint32 dwFourCC; uint32 dwRGBBitCount; uint32 dwRBitMask; uint32 dwGBitMask; uint32 dwBBitMask; uint32 dwABitMask; }; #define DDS_FOURCC 0x00000004 // DDPF_FOURCC #define DDS_RGB 0x00000040 // DDPF_RGB #define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS #define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE #define DDS_ALPHA 0x00000002 // DDPF_ALPHA /* const DDS_PIXELFORMAT DDSPF_DXT1 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; const DDS_PIXELFORMAT DDSPF_DXT2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 }; const DDS_PIXELFORMAT DDSPF_DXT3 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; const DDS_PIXELFORMAT DDSPF_DXT4 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 }; const DDS_PIXELFORMAT DDSPF_DXT5 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 }; const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 }; const DDS_PIXELFORMAT DDSPF_R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 }; const DDS_PIXELFORMAT DDSPF_R5G6B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 }; // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) const DDS_PIXELFORMAT DDSPF_DX10 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, DDS_MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; // #define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT // #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT // #define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH // #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH // #define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE // // #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE // #define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP // #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX // // #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX // #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX // #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY // #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY // #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ // #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ // // #define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ // DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ // DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) // // #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME */ #define DDSD_CAPS 0x1 // Required in every .dds file. #define DDSD_HEIGHT 0x2 // Required in every .dds file. #define DDSD_WIDTH 0x4 // Required in every .dds file. #define DDSD_PITCH 0x8 // Required when pitch is provided for an uncompressed texture. #define DDSD_PIXELFORMAT 0x1000 // Required in every .dds file. #define DDSD_MIPMAPCOUNT 0x20000 // Required in a mipmapped texture. #define DDSD_LINEARSIZE 0x80000 // Required when pitch is provided for a compressed texture. #define DDSD_DEPTH 0x800000 // Required in a depth texture. #define DDSCAPS_COMPLEX 0x8 // Optional; must be used on any file that contains more than one surface (a mipmap, a cubic environment map, or mipmapped volume texture). #define DDSCAPS_MIPMAP 0x400000 // Optional; should be used for a mipmap. #define DDSCAPS_TEXTURE 0x1000 // Required #define DDSCAPS2_CUBEMAP 0x200 // Required for a cube map. #define DDSCAPS2_CUBEMAP_POSITIVEX 0x400 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_CUBEMAP_NEGATIVEX 0x800 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_CUBEMAP_POSITIVEY 0x1000 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_CUBEMAP_NEGATIVEY 0x2000 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_CUBEMAP_POSITIVEZ 0x4000 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x8000 // Required when these surfaces are stored in a cube map. #define DDSCAPS2_VOLUME 0x200000 // Required for a volume texture. typedef struct { uint32 dwSize; uint32 dwFlags; uint32 dwHeight; uint32 dwWidth; uint32 dwPitchOrLinearSize; uint32 dwDepth; // only if DDS_HEADER_FLAGS_VOLUME is set in dwHeaderFlags uint32 dwMipMapCount; uint32 dwReserved1[11]; DDS_PIXELFORMAT ddspf; uint32 dwCaps; uint32 dwCaps2; uint32 dwCaps3; uint32 dwCaps4; uint32 dwReserved2; } DDS_HEADER; enum DDS_RESOURCE_DIMENSION { DDS_RESOURCE_DIMENSION_TEXTURE1D = 2, DDS_RESOURCE_DIMENSION_TEXTURE2D = 3, DDS_RESOURCE_DIMENSION_TEXTURE3D = 4, }; #define DDS_RESOURCE_MISC_TEXTURECUBE 0x4 enum DDS_DXGI_FORMAT { DDS_DXGI_FORMAT_UNKNOWN = 0, DDS_DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, DDS_DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DDS_DXGI_FORMAT_R32G32B32A32_UINT = 3, DDS_DXGI_FORMAT_R32G32B32A32_SINT = 4, DDS_DXGI_FORMAT_R32G32B32_TYPELESS = 5, DDS_DXGI_FORMAT_R32G32B32_FLOAT = 6, DDS_DXGI_FORMAT_R32G32B32_UINT = 7, DDS_DXGI_FORMAT_R32G32B32_SINT = 8, DDS_DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, DDS_DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DDS_DXGI_FORMAT_R16G16B16A16_UNORM = 11, DDS_DXGI_FORMAT_R16G16B16A16_UINT = 12, DDS_DXGI_FORMAT_R16G16B16A16_SNORM = 13, DDS_DXGI_FORMAT_R16G16B16A16_SINT = 14, DDS_DXGI_FORMAT_R32G32_TYPELESS = 15, DDS_DXGI_FORMAT_R32G32_FLOAT = 16, DDS_DXGI_FORMAT_R32G32_UINT = 17, DDS_DXGI_FORMAT_R32G32_SINT = 18, DDS_DXGI_FORMAT_R32G8X24_TYPELESS = 19, DDS_DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, DDS_DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, DDS_DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, DDS_DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, DDS_DXGI_FORMAT_R10G10B10A2_UNORM = 24, DDS_DXGI_FORMAT_R10G10B10A2_UINT = 25, DDS_DXGI_FORMAT_R11G11B10_FLOAT = 26, DDS_DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, DDS_DXGI_FORMAT_R8G8B8A8_UNORM = 28, DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, DDS_DXGI_FORMAT_R8G8B8A8_UINT = 30, DDS_DXGI_FORMAT_R8G8B8A8_SNORM = 31, DDS_DXGI_FORMAT_R8G8B8A8_SINT = 32, DDS_DXGI_FORMAT_R16G16_TYPELESS = 33, DDS_DXGI_FORMAT_R16G16_FLOAT = 34, DDS_DXGI_FORMAT_R16G16_UNORM = 35, DDS_DXGI_FORMAT_R16G16_UINT = 36, DDS_DXGI_FORMAT_R16G16_SNORM = 37, DDS_DXGI_FORMAT_R16G16_SINT = 38, DDS_DXGI_FORMAT_R32_TYPELESS = 39, DDS_DXGI_FORMAT_D32_FLOAT = 40, DDS_DXGI_FORMAT_R32_FLOAT = 41, DDS_DXGI_FORMAT_R32_UINT = 42, DDS_DXGI_FORMAT_R32_SINT = 43, DDS_DXGI_FORMAT_R24G8_TYPELESS = 44, DDS_DXGI_FORMAT_D24_UNORM_S8_UINT = 45, DDS_DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, DDS_DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, DDS_DXGI_FORMAT_R8G8_TYPELESS = 48, DDS_DXGI_FORMAT_R8G8_UNORM = 49, DDS_DXGI_FORMAT_R8G8_UINT = 50, DDS_DXGI_FORMAT_R8G8_SNORM = 51, DDS_DXGI_FORMAT_R8G8_SINT = 52, DDS_DXGI_FORMAT_R16_TYPELESS = 53, DDS_DXGI_FORMAT_R16_FLOAT = 54, DDS_DXGI_FORMAT_D16_UNORM = 55, DDS_DXGI_FORMAT_R16_UNORM = 56, DDS_DXGI_FORMAT_R16_UINT = 57, DDS_DXGI_FORMAT_R16_SNORM = 58, DDS_DXGI_FORMAT_R16_SINT = 59, DDS_DXGI_FORMAT_R8_TYPELESS = 60, DDS_DXGI_FORMAT_R8_UNORM = 61, DDS_DXGI_FORMAT_R8_UINT = 62, DDS_DXGI_FORMAT_R8_SNORM = 63, DDS_DXGI_FORMAT_R8_SINT = 64, DDS_DXGI_FORMAT_A8_UNORM = 65, DDS_DXGI_FORMAT_R1_UNORM = 66, DDS_DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, DDS_DXGI_FORMAT_R8G8_B8G8_UNORM = 68, DDS_DXGI_FORMAT_G8R8_G8B8_UNORM = 69, DDS_DXGI_FORMAT_BC1_TYPELESS = 70, DDS_DXGI_FORMAT_BC1_UNORM = 71, DDS_DXGI_FORMAT_BC1_UNORM_SRGB = 72, DDS_DXGI_FORMAT_BC2_TYPELESS = 73, DDS_DXGI_FORMAT_BC2_UNORM = 74, DDS_DXGI_FORMAT_BC2_UNORM_SRGB = 75, DDS_DXGI_FORMAT_BC3_TYPELESS = 76, DDS_DXGI_FORMAT_BC3_UNORM = 77, DDS_DXGI_FORMAT_BC3_UNORM_SRGB = 78, DDS_DXGI_FORMAT_BC4_TYPELESS = 79, DDS_DXGI_FORMAT_BC4_UNORM = 80, DDS_DXGI_FORMAT_BC4_SNORM = 81, DDS_DXGI_FORMAT_BC5_TYPELESS = 82, DDS_DXGI_FORMAT_BC5_UNORM = 83, DDS_DXGI_FORMAT_BC5_SNORM = 84, DDS_DXGI_FORMAT_B5G6R5_UNORM = 85, DDS_DXGI_FORMAT_B5G5R5A1_UNORM = 86, DDS_DXGI_FORMAT_B8G8R8A8_UNORM = 87, DDS_DXGI_FORMAT_B8G8R8X8_UNORM = 88, DDS_DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, DDS_DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, DDS_DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, DDS_DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, DDS_DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, DDS_DXGI_FORMAT_BC6H_TYPELESS = 94, DDS_DXGI_FORMAT_BC6H_UF16 = 95, DDS_DXGI_FORMAT_BC6H_SF16 = 96, DDS_DXGI_FORMAT_BC7_TYPELESS = 97, DDS_DXGI_FORMAT_BC7_UNORM = 98, DDS_DXGI_FORMAT_BC7_UNORM_SRGB = 99, DDS_DXGI_FORMAT_COUNT, DDS_DXGI_FORMAT_FORCE_UINT = 0xffffffffUL }; typedef struct { DDS_DXGI_FORMAT dxgiFormat; DDS_RESOURCE_DIMENSION resourceDimension; uint32 miscFlag; uint32 arraySize; uint32 reserved; } DDS_HEADER_DXT10; #pragma pack(pop) // end DDS.h //------------------------------------------------------------------------------------------------------------------------------------------------------------- <file_sep>/Engine/Source/Renderer/ShaderComponentTypeInfo.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" #include "Core/ObjectTypeInfo.h" class VertexFactoryTypeInfo; class MaterialShader; struct ShaderCompilerParameters; struct SHADER_COMPONENT_PARAMETER_BINDING { const char *ParameterName; SHADER_PARAMETER_TYPE ExpectedType; }; class ShaderComponentTypeInfo : public ObjectTypeInfo { public: typedef bool(*IsValidPermutationFunction)(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); typedef bool(*FillShaderCompilerParametersFunction)(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); public: ShaderComponentTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, IsValidPermutationFunction fpIsValidPermutation, FillShaderCompilerParametersFunction fpFillShaderCompilerParameters, const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBindings); ~ShaderComponentTypeInfo(); const SHADER_COMPONENT_PARAMETER_BINDING *GetParameterBindings() const { return m_pParameterBindings; } uint32 GetParameterBindingCount() const { return m_nParameterBindings; } uint32 GetParameterCRC() const { return m_parameterCRC; } // wrappers bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const; bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) const; // parameter crc void SetParameterCRC(uint32 parameterCRC); protected: const SHADER_COMPONENT_PARAMETER_BINDING *m_pParameterBindings; uint32 m_nParameterBindings; uint32 m_parameterCRC; IsValidPermutationFunction m_fpIsValidPermutation; FillShaderCompilerParametersFunction m_fpFillShaderCompilerParameters; }; #define DECLARE_SHADER_COMPONENT_INFO(Type, ParentType) \ private: \ static ShaderComponentTypeInfo s_TypeInfo; \ static const SHADER_COMPONENT_PARAMETER_BINDING s_parameterBindings[]; \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ShaderComponentTypeInfo *StaticTypeInfo() { return &s_TypeInfo; } \ static ShaderComponentTypeInfo *StaticMutableTypeInfo() { return &s_TypeInfo; } #define DEFINE_SHADER_COMPONENT_INFO(Type) \ ShaderComponentTypeInfo Type::s_TypeInfo = ShaderComponentTypeInfo( #Type , OBJECT_TYPEINFO(BaseClass), \ &Type::IsValidPermutation, &Type::FillShaderCompilerParameters, \ Type::s_parameterBindings); #define BEGIN_SHADER_COMPONENT_PARAMETERS(Type) const SHADER_COMPONENT_PARAMETER_BINDING Type::s_parameterBindings[] = { #define DEFINE_SHADER_COMPONENT_PARAMETER(Name, ExpectedType) { Name, ExpectedType }, #define END_SHADER_COMPONENT_PARAMETERS() { NULL, SHADER_PARAMETER_TYPE_COUNT } }; #define SHADER_COMPONENT_INFO(Type) Type::StaticTypeInfo() #define SHADER_COMPONENT_INFO_PTR(Ptr) Ptr->StaticTypeInfo() #define MUTABLE_SHADER_COMPONENT_INFO(Type) Type::StaticMutableTypeInfo() #define MUTABLE_SHADER_COMPONENT_INFO_PTR(Type) Type->StaticMutableTypeInfo() <file_sep>/Editor/Source/Editor/moc_EditorPropertyEditorWidget.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorPropertyEditorWidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorPropertyEditorWidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorPropertyEditorWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorPropertyEditorWidget_t { QByteArrayData data[25]; char stringdata[464]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorPropertyEditorWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorPropertyEditorWidget_t qt_meta_stringdata_EditorPropertyEditorWidget = { { QT_MOC_LITERAL(0, 0, 26), // "EditorPropertyEditorWidget" QT_MOC_LITERAL(1, 27, 21), // "OnPropertyValueChange" QT_MOC_LITERAL(2, 49, 0), // "" QT_MOC_LITERAL(3, 50, 11), // "const char*" QT_MOC_LITERAL(4, 62, 12), // "propertyName" QT_MOC_LITERAL(5, 75, 13), // "propertyValue" QT_MOC_LITERAL(6, 89, 11), // "AddProperty" QT_MOC_LITERAL(7, 101, 31), // "const PropertyTemplateProperty*" QT_MOC_LITERAL(8, 133, 19), // "pPropertyDefinition" QT_MOC_LITERAL(9, 153, 12), // "currentValue" QT_MOC_LITERAL(10, 166, 25), // "AddPropertiesFromTemplate" QT_MOC_LITERAL(11, 192, 23), // "const PropertyTemplate*" QT_MOC_LITERAL(12, 216, 9), // "pTemplate" QT_MOC_LITERAL(13, 226, 15), // "ClearProperties" QT_MOC_LITERAL(14, 242, 27), // "SetDestinationPropertyTable" QT_MOC_LITERAL(15, 270, 14), // "PropertyTable*" QT_MOC_LITERAL(16, 285, 14), // "pPropertyTable" QT_MOC_LITERAL(17, 300, 19), // "UpdatePropertyValue" QT_MOC_LITERAL(18, 320, 28), // "UpdatePropertyValueFromTable" QT_MOC_LITERAL(19, 349, 31), // "OnTreeBrowserCurrentItemChanged" QT_MOC_LITERAL(20, 381, 14), // "QtBrowserItem*" QT_MOC_LITERAL(21, 396, 12), // "pBrowserItem" QT_MOC_LITERAL(22, 409, 32), // "OnPropertyManagerPropertyChanged" QT_MOC_LITERAL(23, 442, 11), // "QtProperty*" QT_MOC_LITERAL(24, 454, 9) // "pProperty" }, "EditorPropertyEditorWidget\0" "OnPropertyValueChange\0\0const char*\0" "propertyName\0propertyValue\0AddProperty\0" "const PropertyTemplateProperty*\0" "pPropertyDefinition\0currentValue\0" "AddPropertiesFromTemplate\0" "const PropertyTemplate*\0pTemplate\0" "ClearProperties\0SetDestinationPropertyTable\0" "PropertyTable*\0pPropertyTable\0" "UpdatePropertyValue\0UpdatePropertyValueFromTable\0" "OnTreeBrowserCurrentItemChanged\0" "QtBrowserItem*\0pBrowserItem\0" "OnPropertyManagerPropertyChanged\0" "QtProperty*\0pProperty" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorPropertyEditorWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 9, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 59, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 6, 2, 64, 2, 0x0a /* Public */, 10, 1, 69, 2, 0x0a /* Public */, 13, 0, 72, 2, 0x0a /* Public */, 14, 1, 73, 2, 0x0a /* Public */, 17, 2, 76, 2, 0x0a /* Public */, 18, 1, 81, 2, 0x0a /* Public */, 19, 1, 84, 2, 0x08 /* Private */, 22, 1, 87, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 0x80000000 | 3, 4, 5, // slots: parameters QMetaType::Bool, 0x80000000 | 7, 0x80000000 | 3, 8, 9, QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, QMetaType::Void, 0x80000000 | 15, 16, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 3, 4, 5, QMetaType::Void, 0x80000000 | 3, 4, QMetaType::Void, 0x80000000 | 20, 21, QMetaType::Void, 0x80000000 | 23, 24, 0 // eod }; void EditorPropertyEditorWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorPropertyEditorWidget *_t = static_cast<EditorPropertyEditorWidget *>(_o); switch (_id) { case 0: _t->OnPropertyValueChange((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< const char*(*)>(_a[2]))); break; case 1: { bool _r = _t->AddProperty((*reinterpret_cast< const PropertyTemplateProperty*(*)>(_a[1])),(*reinterpret_cast< const char*(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 2: _t->AddPropertiesFromTemplate((*reinterpret_cast< const PropertyTemplate*(*)>(_a[1]))); break; case 3: _t->ClearProperties(); break; case 4: _t->SetDestinationPropertyTable((*reinterpret_cast< PropertyTable*(*)>(_a[1]))); break; case 5: _t->UpdatePropertyValue((*reinterpret_cast< const char*(*)>(_a[1])),(*reinterpret_cast< const char*(*)>(_a[2]))); break; case 6: _t->UpdatePropertyValueFromTable((*reinterpret_cast< const char*(*)>(_a[1]))); break; case 7: _t->OnTreeBrowserCurrentItemChanged((*reinterpret_cast< QtBrowserItem*(*)>(_a[1]))); break; case 8: _t->OnPropertyManagerPropertyChanged((*reinterpret_cast< QtProperty*(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (EditorPropertyEditorWidget::*_t)(const char * , const char * ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorPropertyEditorWidget::OnPropertyValueChange)) { *result = 0; } } } } const QMetaObject EditorPropertyEditorWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorPropertyEditorWidget.data, qt_meta_data_EditorPropertyEditorWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorPropertyEditorWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorPropertyEditorWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorPropertyEditorWidget.stringdata)) return static_cast<void*>(const_cast< EditorPropertyEditorWidget*>(this)); return QWidget::qt_metacast(_clname); } int EditorPropertyEditorWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 9) qt_static_metacall(this, _c, _id, _a); _id -= 9; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 9) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 9; } return _id; } // SIGNAL 0 void EditorPropertyEditorWidget::OnPropertyValueChange(const char * _t1, const char * _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager_t { QByteArrayData data[10]; char stringdata[153]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager_t qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager = { { QT_MOC_LITERAL(0, 0, 43), // "EditorPropertyEditorResourceP..." QT_MOC_LITERAL(1, 44, 12), // "valueChanged" QT_MOC_LITERAL(2, 57, 0), // "" QT_MOC_LITERAL(3, 58, 11), // "QtProperty*" QT_MOC_LITERAL(4, 70, 9), // "pProperty" QT_MOC_LITERAL(5, 80, 5), // "value" QT_MOC_LITERAL(6, 86, 8), // "setValue" QT_MOC_LITERAL(7, 95, 15), // "setResourceType" QT_MOC_LITERAL(8, 111, 23), // "const ResourceTypeInfo*" QT_MOC_LITERAL(9, 135, 17) // "pResourceTypeInfo" }, "EditorPropertyEditorResourcePropertyManager\0" "valueChanged\0\0QtProperty*\0pProperty\0" "value\0setValue\0setResourceType\0" "const ResourceTypeInfo*\0pResourceTypeInfo" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorPropertyEditorResourcePropertyManager[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 29, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 6, 2, 34, 2, 0x0a /* Public */, 7, 2, 39, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, QMetaType::QString, 4, 5, // slots: parameters QMetaType::Void, 0x80000000 | 3, QMetaType::QString, 4, 5, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 8, 4, 9, 0 // eod }; void EditorPropertyEditorResourcePropertyManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorPropertyEditorResourcePropertyManager *_t = static_cast<EditorPropertyEditorResourcePropertyManager *>(_o); switch (_id) { case 0: _t->valueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 1: _t->setValue((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 2: _t->setResourceType((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const ResourceTypeInfo*(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (EditorPropertyEditorResourcePropertyManager::*_t)(QtProperty * , const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorPropertyEditorResourcePropertyManager::valueChanged)) { *result = 0; } } } } const QMetaObject EditorPropertyEditorResourcePropertyManager::staticMetaObject = { { &QtAbstractPropertyManager::staticMetaObject, qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager.data, qt_meta_data_EditorPropertyEditorResourcePropertyManager, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorPropertyEditorResourcePropertyManager::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorPropertyEditorResourcePropertyManager::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorPropertyEditorResourcePropertyManager.stringdata)) return static_cast<void*>(const_cast< EditorPropertyEditorResourcePropertyManager*>(this)); return QtAbstractPropertyManager::qt_metacast(_clname); } int EditorPropertyEditorResourcePropertyManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractPropertyManager::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } // SIGNAL 0 void EditorPropertyEditorResourcePropertyManager::valueChanged(QtProperty * _t1, const QString & _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory_t { QByteArrayData data[9]; char stringdata[146]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory_t qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory = { { QT_MOC_LITERAL(0, 0, 41), // "EditorPropertyEditorResourceE..." QT_MOC_LITERAL(1, 42, 23), // "slotManagerValueChanged" QT_MOC_LITERAL(2, 66, 0), // "" QT_MOC_LITERAL(3, 67, 11), // "QtProperty*" QT_MOC_LITERAL(4, 79, 9), // "pProperty" QT_MOC_LITERAL(5, 89, 5), // "value" QT_MOC_LITERAL(6, 95, 22), // "slotEditorValueChanged" QT_MOC_LITERAL(7, 118, 19), // "slotEditorDestroyed" QT_MOC_LITERAL(8, 138, 7) // "pEditor" }, "EditorPropertyEditorResourceEditorFactory\0" "slotManagerValueChanged\0\0QtProperty*\0" "pProperty\0value\0slotEditorValueChanged\0" "slotEditorDestroyed\0pEditor" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorPropertyEditorResourceEditorFactory[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 2, 29, 2, 0x08 /* Private */, 6, 1, 34, 2, 0x08 /* Private */, 7, 1, 37, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0x80000000 | 3, QMetaType::QString, 4, 5, QMetaType::Void, QMetaType::QString, 5, QMetaType::Void, QMetaType::QObjectStar, 8, 0 // eod }; void EditorPropertyEditorResourceEditorFactory::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorPropertyEditorResourceEditorFactory *_t = static_cast<EditorPropertyEditorResourceEditorFactory *>(_o); switch (_id) { case 0: _t->slotManagerValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 1: _t->slotEditorValueChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 2: _t->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorPropertyEditorResourceEditorFactory::staticMetaObject = { { &QtAbstractEditorFactory<EditorPropertyEditorResourcePropertyManager>::staticMetaObject, qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory.data, qt_meta_data_EditorPropertyEditorResourceEditorFactory, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorPropertyEditorResourceEditorFactory::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorPropertyEditorResourceEditorFactory::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorPropertyEditorResourceEditorFactory.stringdata)) return static_cast<void*>(const_cast< EditorPropertyEditorResourceEditorFactory*>(this)); return QtAbstractEditorFactory<EditorPropertyEditorResourcePropertyManager>::qt_metacast(_clname); } int EditorPropertyEditorResourceEditorFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractEditorFactory<EditorPropertyEditorResourcePropertyManager>::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } struct qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager_t { QByteArrayData data[13]; char stringdata[169]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager_t qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager = { { QT_MOC_LITERAL(0, 0, 41), // "EditorPropertyEditorVectorPro..." QT_MOC_LITERAL(1, 42, 12), // "valueChanged" QT_MOC_LITERAL(2, 55, 0), // "" QT_MOC_LITERAL(3, 56, 11), // "QtProperty*" QT_MOC_LITERAL(4, 68, 9), // "pProperty" QT_MOC_LITERAL(5, 78, 6), // "float4" QT_MOC_LITERAL(6, 85, 5), // "value" QT_MOC_LITERAL(7, 91, 16), // "setNumComponents" QT_MOC_LITERAL(8, 108, 6), // "uint32" QT_MOC_LITERAL(9, 115, 11), // "nComponents" QT_MOC_LITERAL(10, 127, 14), // "setValueString" QT_MOC_LITERAL(11, 142, 11), // "const char*" QT_MOC_LITERAL(12, 154, 14) // "setValueVector" }, "EditorPropertyEditorVectorPropertyManager\0" "valueChanged\0\0QtProperty*\0pProperty\0" "float4\0value\0setNumComponents\0uint32\0" "nComponents\0setValueString\0const char*\0" "setValueVector" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorPropertyEditorVectorPropertyManager[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 34, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 7, 2, 39, 2, 0x0a /* Public */, 10, 2, 44, 2, 0x0a /* Public */, 12, 2, 49, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, 4, 6, // slots: parameters QMetaType::Void, 0x80000000 | 3, 0x80000000 | 8, 4, 9, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 11, 4, 6, QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, 4, 6, 0 // eod }; void EditorPropertyEditorVectorPropertyManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorPropertyEditorVectorPropertyManager *_t = static_cast<EditorPropertyEditorVectorPropertyManager *>(_o); switch (_id) { case 0: _t->valueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const float4(*)>(_a[2]))); break; case 1: _t->setNumComponents((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< uint32(*)>(_a[2]))); break; case 2: _t->setValueString((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const char*(*)>(_a[2]))); break; case 3: _t->setValueVector((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const float4(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (EditorPropertyEditorVectorPropertyManager::*_t)(QtProperty * , const float4 & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&EditorPropertyEditorVectorPropertyManager::valueChanged)) { *result = 0; } } } } const QMetaObject EditorPropertyEditorVectorPropertyManager::staticMetaObject = { { &QtAbstractPropertyManager::staticMetaObject, qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager.data, qt_meta_data_EditorPropertyEditorVectorPropertyManager, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorPropertyEditorVectorPropertyManager::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorPropertyEditorVectorPropertyManager::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorPropertyEditorVectorPropertyManager.stringdata)) return static_cast<void*>(const_cast< EditorPropertyEditorVectorPropertyManager*>(this)); return QtAbstractPropertyManager::qt_metacast(_clname); } int EditorPropertyEditorVectorPropertyManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractPropertyManager::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 4) qt_static_metacall(this, _c, _id, _a); _id -= 4; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 4) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 4; } return _id; } // SIGNAL 0 void EditorPropertyEditorVectorPropertyManager::valueChanged(QtProperty * _t1, const float4 & _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_EditorPropertyEditorVectorEditFactory_t { QByteArrayData data[10]; char stringdata[149]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorPropertyEditorVectorEditFactory_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorPropertyEditorVectorEditFactory_t qt_meta_stringdata_EditorPropertyEditorVectorEditFactory = { { QT_MOC_LITERAL(0, 0, 37), // "EditorPropertyEditorVectorEdi..." QT_MOC_LITERAL(1, 38, 23), // "slotManagerValueChanged" QT_MOC_LITERAL(2, 62, 0), // "" QT_MOC_LITERAL(3, 63, 11), // "QtProperty*" QT_MOC_LITERAL(4, 75, 9), // "pProperty" QT_MOC_LITERAL(5, 85, 6), // "float4" QT_MOC_LITERAL(6, 92, 5), // "value" QT_MOC_LITERAL(7, 98, 22), // "slotEditorValueChanged" QT_MOC_LITERAL(8, 121, 19), // "slotEditorDestroyed" QT_MOC_LITERAL(9, 141, 7) // "pEditor" }, "EditorPropertyEditorVectorEditFactory\0" "slotManagerValueChanged\0\0QtProperty*\0" "pProperty\0float4\0value\0slotEditorValueChanged\0" "slotEditorDestroyed\0pEditor" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorPropertyEditorVectorEditFactory[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 2, 29, 2, 0x08 /* Private */, 7, 1, 34, 2, 0x08 /* Private */, 8, 1, 37, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, 4, 6, QMetaType::Void, 0x80000000 | 5, 6, QMetaType::Void, QMetaType::QObjectStar, 9, 0 // eod }; void EditorPropertyEditorVectorEditFactory::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorPropertyEditorVectorEditFactory *_t = static_cast<EditorPropertyEditorVectorEditFactory *>(_o); switch (_id) { case 0: _t->slotManagerValueChanged((*reinterpret_cast< QtProperty*(*)>(_a[1])),(*reinterpret_cast< const float4(*)>(_a[2]))); break; case 1: _t->slotEditorValueChanged((*reinterpret_cast< const float4(*)>(_a[1]))); break; case 2: _t->slotEditorDestroyed((*reinterpret_cast< QObject*(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorPropertyEditorVectorEditFactory::staticMetaObject = { { &QtAbstractEditorFactory<EditorPropertyEditorVectorPropertyManager>::staticMetaObject, qt_meta_stringdata_EditorPropertyEditorVectorEditFactory.data, qt_meta_data_EditorPropertyEditorVectorEditFactory, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorPropertyEditorVectorEditFactory::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorPropertyEditorVectorEditFactory::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorPropertyEditorVectorEditFactory.stringdata)) return static_cast<void*>(const_cast< EditorPropertyEditorVectorEditFactory*>(this)); return QtAbstractEditorFactory<EditorPropertyEditorVectorPropertyManager>::qt_metacast(_clname); } int EditorPropertyEditorVectorEditFactory::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QtAbstractEditorFactory<EditorPropertyEditorVectorPropertyManager>::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/MathLib/Vectorf.cpp #include "MathLib/Vectorf.h" #include "MathLib/Vectorh.h" #include "MathLib/Vectori.h" #include "MathLib/SIMDVectorf.h" #include "MathLib/SIMDVectori.h" Vector2f::Vector2f(const SIMDVector2f &v) { Set(v.x, v.y); } Vector2f::Vector2f(const Vector2i &v) : x((float)v.x), y((float)v.y) {} void Vector2f::Set(const SIMDVector2f &v) { Set(v.x, v.y); } Vector2f &Vector2f::operator=(const SIMDVector2f &v) { Set(v.x, v.y); return *this; } Vector3f::Vector3f(const SIMDVector3f &v) { Set(v.x, v.y, v.z); } Vector3f::Vector3f(const Vector3i &v) : x((float)v.x), y((float)v.y), z((float)v.z) {} void Vector3f::Set(const SIMDVector3f &v) { Set(v.x, v.y, v.z); } Vector3f &Vector3f::operator=(const SIMDVector3f &v) { Set(v.x, v.y, v.z); return *this; } Vector4f::Vector4f(const SIMDVector4f &v) { Set(v.x, v.y, v.z, v.w); } Vector4f::Vector4f(const Vector4i &v) : x((float)v.x), y((float)v.y), z((float)v.z), w((float)v.w) {} void Vector4f::Set(const SIMDVector4f &v) { Set(v.x, v.y, v.z, v.w); } Vector4f &Vector4f::operator=(const SIMDVector4f &v) { Set(v.x, v.y, v.z, v.w); return *this; } static const float __floatUnitX[4] = { 1.0f, 0.0f, 0.0f, 0.0f }; static const float __floatUnitY[4] = { 0.0f, 1.0f, 0.0f, 0.0f }; static const float __floatUnitZ[4] = { 0.0f, 0.0f, 1.0f, 0.0f }; static const float __floatUnitW[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; static const float __floatNegativeUnitX[4] = { -1.0f, 0.0f, 0.0f, 0.0f }; static const float __floatNegativeUnitY[4] = { 0.0f, -1.0f, 0.0f, 0.0f }; static const float __floatNegativeUnitZ[4] = { 0.0f, 0.0f, -1.0f, 0.0f }; static const float __floatNegativeUnitW[4] = { 0.0f, 0.0f, 0.0f, -1.0f }; static const float __float2Zero[2] = { 0.0f, 0.0f }; static const float __float2One[2] = { 1.0f, 1.0f }; static const float __float2NegativeOne[2] = { -1.0f, -1.0f }; static const float __float2Infinite[2] = { Y_FLT_INFINITE, Y_FLT_INFINITE }; static const float __float2NegativeInfinite[2] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE }; const Vector2f &Vector2f::Zero = reinterpret_cast<const Vector2f &>(__float2Zero); const Vector2f &Vector2f::One = reinterpret_cast<const Vector2f &>(__float2One); const Vector2f &Vector2f::NegativeOne = reinterpret_cast<const Vector2f &>(__float2NegativeOne); const Vector2f &Vector2f::Infinite = reinterpret_cast<const Vector2f &>(__float2Infinite); const Vector2f &Vector2f::NegativeInfinite = reinterpret_cast<const Vector2f &>(__float2NegativeInfinite); const Vector2f &Vector2f::UnitX = reinterpret_cast<const Vector2f &>(__floatUnitX); const Vector2f &Vector2f::UnitY = reinterpret_cast<const Vector2f &>(__floatUnitY); const Vector2f &Vector2f::NegativeUnitX = reinterpret_cast<const Vector2f &>(__floatNegativeUnitX); const Vector2f &Vector2f::NegativeUnitY = reinterpret_cast<const Vector2f &>(__floatNegativeUnitY); static const float __float3Zero[3] = { 0.0f, 0.0f, 0.0f }; static const float __float3One[3] = { 1.0f, 1.0f, 1.0f }; static const float __float3NegativeOne[3] = { -1.0f, -1.0f, -1.0f }; static const float __float3Infinite[3] = { Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE }; static const float __float3NegativeInfinite[3] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE }; const Vector3f &Vector3f::Zero = reinterpret_cast<const Vector3f &>(__float3Zero); const Vector3f &Vector3f::One = reinterpret_cast<const Vector3f &>(__float3One); const Vector3f &Vector3f::NegativeOne = reinterpret_cast<const Vector3f &>(__float3NegativeOne); const Vector3f &Vector3f::Infinite = reinterpret_cast<const Vector3f &>(__float3Infinite); const Vector3f &Vector3f::NegativeInfinite = reinterpret_cast<const Vector3f &>(__float3NegativeInfinite); const Vector3f &Vector3f::UnitX = reinterpret_cast<const Vector3f &>(__floatUnitX); const Vector3f &Vector3f::UnitY = reinterpret_cast<const Vector3f &>(__floatUnitY); const Vector3f &Vector3f::UnitZ = reinterpret_cast<const Vector3f &>(__floatUnitZ); const Vector3f &Vector3f::NegativeUnitX = reinterpret_cast<const Vector3f &>(__floatNegativeUnitX); const Vector3f &Vector3f::NegativeUnitY = reinterpret_cast<const Vector3f &>(__floatNegativeUnitY); const Vector3f &Vector3f::NegativeUnitZ = reinterpret_cast<const Vector3f &>(__floatNegativeUnitZ); static const float __float4Zero[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; static const float __float4One[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; static const float __float4NegativeOne[4] = { -1.0f, -1.0f, -1.0f, -1.0f }; static const float __float4Infinite[4] = { Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE, Y_FLT_INFINITE }; static const float __float4NegativeInfinite[4] = { -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE, -Y_FLT_INFINITE }; const Vector4f &Vector4f::Zero = reinterpret_cast<const Vector4f &>(__float4Zero); const Vector4f &Vector4f::One = reinterpret_cast<const Vector4f &>(__float4One); const Vector4f &Vector4f::NegativeOne = reinterpret_cast<const Vector4f &>(__float4NegativeOne); const Vector4f &Vector4f::Infinite = reinterpret_cast<const Vector4f &>(__float4Infinite); const Vector4f &Vector4f::NegativeInfinite = reinterpret_cast<const Vector4f &>(__float4NegativeInfinite); const Vector4f &Vector4f::UnitX = reinterpret_cast<const Vector4f &>(__floatUnitX); const Vector4f &Vector4f::UnitY = reinterpret_cast<const Vector4f &>(__floatUnitY); const Vector4f &Vector4f::UnitZ = reinterpret_cast<const Vector4f &>(__floatUnitZ); const Vector4f &Vector4f::UnitW = reinterpret_cast<const Vector4f &>(__floatUnitW); const Vector4f &Vector4f::NegativeUnitX = reinterpret_cast<const Vector4f &>(__floatNegativeUnitX); const Vector4f &Vector4f::NegativeUnitY = reinterpret_cast<const Vector4f &>(__floatNegativeUnitY); const Vector4f &Vector4f::NegativeUnitZ = reinterpret_cast<const Vector4f &>(__floatNegativeUnitZ); const Vector4f &Vector4f::NegativeUnitW = reinterpret_cast<const Vector4f &>(__floatNegativeUnitW); <file_sep>/Engine/Source/MathLib/Matrixf.cpp #include "MathLib/Matrixf.h" #include "MathLib/SIMDMatrixf.h" #include "MathLib/Quaternion.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Assert.h" Matrix3x3f::Matrix3x3f(const float E00, const float E01, const float E02, const float E10, const float E11, const float E12, const float E20, const float E21, const float E22) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E20; *pv++ = E21; *pv = E22; } Matrix3x3f::Matrix3x3f(const float Diagonal) { float *pv = &m00; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = Diagonal; } Matrix3x3f::Matrix3x3f(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix3x3f::Matrix3x3f(const float p[3][3]) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix3x3f::Matrix3x3f(const Matrix3x3f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); } Matrix3x3f::Matrix3x3f(const SIMDMatrix3x3f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); } Matrix3x3f::Matrix3x3f(const SIMDMatrix4x4f &v) { m00 = v.m00; m01 = v.m01; m02 = v.m02; m10 = v.m10; m11 = v.m11; m12 = v.m12; m20 = v.m20; m21 = v.m21; m22 = v.m22; } Matrix3x3f::Matrix3x3f(const Matrix4x4f &v) { m00 = v.m00; m01 = v.m01; m02 = v.m02; m10 = v.m10; m11 = v.m11; m12 = v.m12; m20 = v.m20; m21 = v.m21; m22 = v.m22; } void Matrix3x3f::Set(const float E00, const float E01, const float E02, const float E10, const float E11, const float E12, const float E20, const float E21, const float E22) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E20; *pv++ = E21; *pv = E22; } void Matrix3x3f::SetZero() { float *pv = &m00; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = 0.0f; } void Matrix3x3f::SetIdentity() { float *pv = &m00; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = 1.0f; } Vector3f Matrix3x3f::GetColumn(uint32 j) const { DebugAssert(j < 3); return Vector3f(Row[0][j], Row[1][j], Row[2][j]); } void Matrix3x3f::SetColumn(uint32 j, const Vector3f &v) { DebugAssert(j < 3); Row[0][j] = v.x; Row[1][j] = v.y; Row[2][j] = v.z; } void Matrix3x3f::SetTranspose(const float *pElements) { float *pv = &m00; *pv++ = pElements[0]; *pv++ = pElements[3]; *pv++ = pElements[6]; *pv++ = pElements[1]; *pv++ = pElements[4]; *pv++ = pElements[7]; *pv++ = pElements[2]; *pv++ = pElements[5]; *pv = pElements[8]; } void Matrix3x3f::GetTranspose(float *pElements) const { float *pv = pElements; *pv++ = Row[0][0]; *pv++ = Row[1][0]; *pv++ = Row[2][0]; *pv++ = Row[0][1]; *pv++ = Row[1][1]; *pv++ = Row[2][1]; *pv++ = Row[0][2]; *pv++ = Row[1][2]; *pv = Row[2][2]; } Matrix3x3f Matrix3x3f::Inverse() const { float invDet = 1.0f / (m00 * (m11 * m22 - m21 * m12) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20)); Matrix3x3f res((m11 * m22 - m12 * m21) * invDet, (m21 * m02 - m01 * m22) * invDet, (m01 * m12 - m11 * m02) * invDet, (m12 * m20 - m10 * m22) * invDet, (m00 * m22 - m20 * m02) * invDet, (m10 * m02 - m00 * m12) * invDet, (m10 * m21 - m20 * m11) * invDet, (m20 * m01 - m00 * m21) * invDet, (m00 * m11 - m01 * m10) * invDet); return res; } Matrix3x3f Matrix3x3f::Transpose() const { Matrix3x3f res; res.m00 = m00; res.m01 = m10; res.m02 = m20; res.m10 = m01; res.m11 = m11; res.m12 = m21; res.m20 = m02; res.m21 = m12; res.m22 = m22; return res; } float Matrix3x3f::Determinant() const { return (m00 * (m11 * m22 - m21 * m12) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20)); } void Matrix3x3f::InvertInPlace() { // rvo should take care of this Matrix3x3f temp(*this); *this = temp.Inverse(); } void Matrix3x3f::TransposeInPlace() { uint32 i, j; for (i = 0; i < 3; i++) { for (j = i + 1; j < 3; j++) { if (i == j) continue; float tmp = Row[j][i]; Row[j][i] = Row[i][j]; Row[i][j] = tmp; } } } SIMDMatrix3x3f Matrix3x3f::GetMatrix3() const { return SIMDMatrix3x3f(&m00); } Matrix3x3f &Matrix3x3f::operator=(const Matrix3x3f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); return *this; } Matrix3x3f &Matrix3x3f::operator=(const float Diagonal) { float *pv = &m00; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = Diagonal; return *this; } Matrix3x3f &Matrix3x3f::operator=(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); return *this; } Matrix3x3f &Matrix3x3f::operator=(const SIMDMatrix3x3f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); return *this; } Matrix3x3f &Matrix3x3f::operator*=(const Matrix3x3f &v) { // again, rvo should fix this up Matrix3x3f temp(*this); *this = temp * v; return *this; } Matrix3x3f &Matrix3x3f::operator*=(const float v) { uint32 i; for (i = 0; i < 9; i++) Elements[i] *= v; return *this; } Matrix3x3f Matrix3x3f::operator*(const Matrix3x3f &v) const { #define mulRC(rw, cl) Row[rw][0] * v.Row[0][cl] + \ Row[rw][1] * v.Row[1][cl] + \ Row[rw][2] * v.Row[2][cl] Matrix3x3f res; res.m00 = mulRC(0, 0); res.m01 = mulRC(0, 1); res.m02 = mulRC(0, 2); res.m10 = mulRC(1, 0); res.m11 = mulRC(1, 1); res.m12 = mulRC(1, 2); res.m20 = mulRC(2, 0); res.m21 = mulRC(2, 1); res.m22 = mulRC(2, 2); return res; #undef mulRC } Matrix3x3f Matrix3x3f::operator*(float v) const { uint32 i; Matrix3x3f res; for (i = 0; i < 9; i++) res.Elements[i] = Elements[i] * v; return res; } Matrix3x3f Matrix3x3f::operator-() const { uint32 i; Matrix3x3f res; for (i = 0; i < 9; i++) res.Elements[i] = -Elements[i]; return res; } Vector3f Matrix3x3f::operator*(const Vector3f &v) const { Vector3f res; res.x = Row[0][0] * v.x + Row[0][1] * v.y + Row[0][2] * v.z; res.y = Row[1][0] * v.x + Row[1][1] * v.y + Row[1][2] * v.z; res.z = Row[2][0] * v.x + Row[2][1] * v.y + Row[2][2] * v.z; return res; } Matrix3x3f &Matrix3x3f::operator+=(const Matrix3x3f &v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v.Elements[i]; return *this; } Matrix3x3f &Matrix3x3f::operator+=(const float v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v; return *this; } Matrix3x3f Matrix3x3f::operator+(const Matrix3x3f &v) const { Matrix3x3f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v.Elements[i]; return ret; } Matrix3x3f Matrix3x3f::operator+(const float v) const { Matrix3x3f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v; return ret; } // constants static const float __float3x3Zero[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; const Matrix3x3f &Matrix3x3f::Zero = reinterpret_cast<const Matrix3x3f &>(__float3x3Zero); static const float __float3x3Identity[9] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; const Matrix3x3f &Matrix3x3f::Identity = reinterpret_cast<const Matrix3x3f &>(__float3x3Identity); //======================================================================================================================================================================================================================== Matrix4x4f::Matrix4x4f(const float E00, const float E01, const float E02, const float E03, const float E10, const float E11, const float E12, const float E13, const float E20, const float E21, const float E22, const float E23, const float E30, const float E31, const float E32, const float E33) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E03; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E13; *pv++ = E20; *pv++ = E21; *pv++ = E22; *pv++ = E23; *pv++ = E30; *pv++ = E31; *pv++ = E32; *pv = E33; } Matrix4x4f::Matrix4x4f(const float Diagonal) { float *pv = &m00; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; } Matrix4x4f::Matrix4x4f(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix4x4f::Matrix4x4f(const float p[4][4]) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix4x4f::Matrix4x4f(const Matrix4x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); } Matrix4x4f::Matrix4x4f(const SIMDMatrix4x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); } Matrix4x4f::Matrix4x4f(const Matrix3x4f &v) { Row[0][0] = v.Row[0][0]; Row[0][1] = v.Row[0][1]; Row[0][2] = v.Row[0][2]; Row[0][3] = v.Row[0][3]; Row[1][0] = v.Row[1][0]; Row[1][1] = v.Row[1][1]; Row[1][2] = v.Row[1][2]; Row[1][3] = v.Row[1][3]; Row[2][0] = v.Row[2][0]; Row[2][1] = v.Row[2][1]; Row[2][2] = v.Row[2][2]; Row[2][3] = v.Row[2][3]; Row[3][0] = 0.0f; Row[3][1] = 0.0f; Row[3][2] = 0.0f; Row[3][3] = 1.0f; } void Matrix4x4f::Set(const float E00, const float E01, const float E02, const float E03, const float E10, const float E11, const float E12, const float E13, const float E20, const float E21, const float E22, const float E23, const float E30, const float E31, const float E32, const float E33) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E03; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E13; *pv++ = E20; *pv++ = E21; *pv++ = E22; *pv++ = E23; *pv++ = E30; *pv++ = E31; *pv++ = E32; *pv = E33; } void Matrix4x4f::SetZero() { float *pv = &m00; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = 0.0f; } void Matrix4x4f::SetIdentity() { float *pv = &m00; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = 1.0f; } Vector4f Matrix4x4f::GetColumn(uint32 j) const { DebugAssert(j < 4); return Vector4f(Row[0][j], Row[1][j], Row[2][j], Row[3][j]); } void Matrix4x4f::SetColumn(uint32 j, const Vector4f &v) { DebugAssert(j < 4); Row[0][j] = v.x; Row[1][j] = v.y; Row[2][j] = v.z; Row[3][j] = v.w; } void Matrix4x4f::SetTranspose(const float *pElements) { float *pv = &m00; *pv++ = pElements[0]; *pv++ = pElements[4]; *pv++ = pElements[8]; *pv++ = pElements[12]; *pv++ = pElements[1]; *pv++ = pElements[5]; *pv++ = pElements[9]; *pv++ = pElements[13]; *pv++ = pElements[2]; *pv++ = pElements[6]; *pv++ = pElements[10]; *pv++ = pElements[14]; *pv++ = pElements[3]; *pv++ = pElements[7]; *pv++ = pElements[11]; *pv = pElements[15]; } void Matrix4x4f::GetTranspose(float *pElements) const { float *pv = pElements; *pv++ = Row[0][0]; *pv++ = Row[1][0]; *pv++ = Row[2][0]; *pv++ = Row[3][0]; *pv++ = Row[0][1]; *pv++ = Row[1][1]; *pv++ = Row[2][1]; *pv++ = Row[3][1]; *pv++ = Row[0][2]; *pv++ = Row[1][2]; *pv++ = Row[2][2]; *pv++ = Row[3][2]; *pv++ = Row[0][3]; *pv++ = Row[1][3]; *pv++ = Row[2][3]; *pv = Row[3][3]; } Matrix4x4f Matrix4x4f::Inverse() const { Matrix4x4f res; float v0 = m20 * m31 - m21 * m30; float v1 = m20 * m32 - m22 * m30; float v2 = m20 * m33 - m23 * m30; float v3 = m21 * m32 - m22 * m31; float v4 = m21 * m33 - m23 * m31; float v5 = m22 * m33 - m23 * m32; float t00 = + (v5 * m11 - v4 * m12 + v3 * m13); float t10 = - (v5 * m10 - v2 * m12 + v1 * m13); float t20 = + (v4 * m10 - v2 * m11 + v0 * m13); float t30 = - (v3 * m10 - v1 * m11 + v0 * m12); float invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03); res.m00 = t00 * invDet; res.m10 = t10 * invDet; res.m20 = t20 * invDet; res.m30 = t30 * invDet; res.m01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; res.m11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; res.m21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; res.m31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; v0 = m10 * m31 - m11 * m30; v1 = m10 * m32 - m12 * m30; v2 = m10 * m33 - m13 * m30; v3 = m11 * m32 - m12 * m31; v4 = m11 * m33 - m13 * m31; v5 = m12 * m33 - m13 * m32; res.m02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet; res.m12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet; res.m22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet; res.m32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet; v0 = m21 * m10 - m20 * m11; v1 = m22 * m10 - m20 * m12; v2 = m23 * m10 - m20 * m13; v3 = m22 * m11 - m21 * m12; v4 = m23 * m11 - m21 * m13; v5 = m23 * m12 - m22 * m13; res.m03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; res.m13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; res.m23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; res.m33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; return res; } Matrix4x4f Matrix4x4f::Transpose() const { Matrix4x4f res; res.m00 = m00; res.m01 = m10; res.m02 = m20; res.m03 = m30; res.m10 = m01; res.m11 = m11; res.m12 = m21; res.m13 = m31; res.m20 = m02; res.m21 = m12; res.m22 = m22; res.m23 = m32; res.m30 = m03; res.m31 = m13; res.m32 = m23; res.m33 = m33; return res; } float Matrix4x4f::Determinant() const { float v0 = m20 * m31 - m21 * m30; float v1 = m20 * m32 - m22 * m30; float v2 = m20 * m33 - m23 * m30; float v3 = m21 * m32 - m22 * m31; float v4 = m21 * m33 - m23 * m31; float v5 = m22 * m33 - m23 * m32; float t00 = + (v5 * m11 - v4 * m12 + v3 * m13); float t10 = - (v5 * m10 - v2 * m12 + v1 * m13); float t20 = + (v4 * m10 - v2 * m11 + v0 * m13); float t30 = - (v3 * m10 - v1 * m11 + v0 * m12); return (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03); } void Matrix4x4f::InvertInPlace() { // rvo should take care of this Matrix4x4f temp(*this); *this = temp.Inverse(); } void Matrix4x4f::TransposeInPlace() { uint32 i, j; for (i = 0; i < 4; i++) { for (j = i + 1; j < 4; j++) { if (i == j) continue; float tmp = Row[j][i]; Row[j][i] = Row[i][j]; Row[i][j] = tmp; } } } SIMDMatrix4x4f Matrix4x4f::GetMatrix4f() const { return SIMDMatrix4x4f(&m00); } Vector3f Matrix4x4f::TransformPoint(const Vector3f &point) const { Vector3f ret; ret.x = Vector3f(Row[0]).Dot(point) + Row[0][3]; ret.y = Vector3f(Row[1]).Dot(point) + Row[1][3]; ret.z = Vector3f(Row[2]).Dot(point) + Row[2][3]; return ret; } Vector3f Matrix4x4f::TransformNormal(const Vector3f &normal, bool normalize /* = true */) const { Vector3f ret; ret.x = Vector3f(Row[0]).Dot(normal); ret.y = Vector3f(Row[1]).Dot(normal); ret.z = Vector3f(Row[2]).Dot(normal); if (normalize && ret.SquaredLength() > 0.0f) ret.NormalizeInPlace(); return ret; } void Matrix4x4f::Decompose(Vector3f &translation, Quaternion &rotation, Vector3f &scale) const { // get translation translation.x = Row[0][3]; translation.y = Row[1][3]; translation.z = Row[2][3]; // get rotation/scale part Vector3f rows3x3[3] = { Vector3f(Row[0]), Vector3f(Row[1]), Vector3f(Row[2]) }; // extract scale scale.x = rows3x3[0].Length(); scale.y = rows3x3[1].Length(); scale.z = rows3x3[2].Length(); // handle sign if (Determinant() < 0) scale = -scale; // remove all scaling from rotation matrix if (scale.x != 0.0f) rows3x3[0] /= scale.x; if (scale.y != 0.0f) rows3x3[1] /= scale.y; if (scale.z != 0.0f) rows3x3[2] /= scale.z; // convert to 3x3 matrix Matrix3x3f rot3x3; rot3x3.SetRow(0, rows3x3[0]); rot3x3.SetRow(1, rows3x3[1]); rot3x3.SetRow(2, rows3x3[2]); // convert to quaternion rotation = Quaternion::FromFloat3x3(rot3x3); } Matrix4x4f &Matrix4x4f::operator=(const Matrix4x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); return *this; } Matrix4x4f &Matrix4x4f::operator=(const float Diagonal) { float *pv = &m00; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = Diagonal; return *this; } Matrix4x4f &Matrix4x4f::operator=(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); return *this; } Matrix4x4f &Matrix4x4f::operator=(const SIMDMatrix4x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); return *this; } Matrix4x4f &Matrix4x4f::operator*=(const Matrix4x4f &v) { // again, rvo should fix this up Matrix4x4f temp(*this); *this = temp * v; return *this; } Matrix4x4f &Matrix4x4f::operator*=(const float v) { uint32 i; for (i = 0; i < 16; i++) Elements[i] *= v; return *this; } Matrix4x4f Matrix4x4f::operator*(const Matrix4x4f &v) const { #define mulRC(rw, cl) Row[rw][0] * v.Row[0][cl] + \ Row[rw][1] * v.Row[1][cl] + \ Row[rw][2] * v.Row[2][cl] + \ Row[rw][3] * v.Row[3][cl] Matrix4x4f res; res.m00 = mulRC(0, 0); res.m01 = mulRC(0, 1); res.m02 = mulRC(0, 2); res.m03 = mulRC(0, 3); res.m10 = mulRC(1, 0); res.m11 = mulRC(1, 1); res.m12 = mulRC(1, 2); res.m13 = mulRC(1, 3); res.m20 = mulRC(2, 0); res.m21 = mulRC(2, 1); res.m22 = mulRC(2, 2); res.m23 = mulRC(2, 3); res.m30 = mulRC(3, 0); res.m31 = mulRC(3, 1); res.m32 = mulRC(3, 2); res.m33 = mulRC(3, 3); return res; #undef mulRC } Matrix4x4f Matrix4x4f::operator*(float v) const { uint32 i; Matrix4x4f res; for (i = 0; i < 16; i++) res.Elements[i] = Elements[i] * v; return res; } Matrix4x4f Matrix4x4f::operator-() const { uint32 i; Matrix4x4f res; for (i = 0; i < 16; i++) res.Elements[i] = -Elements[i]; return res; } Vector4f Matrix4x4f::operator*(const Vector4f &v) const { Vector4f res; // res.x = reinterpret_cast<const float4 &>(row[0]).Dot(v); // res.y = reinterpret_cast<const float4 &>(row[1]).Dot(v); // res.z = reinterpret_cast<const float4 &>(row[2]).Dot(v); // res.w = reinterpret_cast<const float4 &>(row[3]).Dot(v); res.x = Row[0][0] * v.x + Row[0][1] * v.y + Row[0][2] * v.z + Row[0][3] * v.w; res.y = Row[1][0] * v.x + Row[1][1] * v.y + Row[1][2] * v.z + Row[1][3] * v.w; res.z = Row[2][0] * v.x + Row[2][1] * v.y + Row[2][2] * v.z + Row[2][3] * v.w; res.w = Row[3][0] * v.x + Row[3][1] * v.y + Row[3][2] * v.z + Row[3][3] * v.w; return res; } Matrix4x4f &Matrix4x4f::operator+=(const Matrix4x4f &v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v.Elements[i]; return *this; } Matrix4x4f &Matrix4x4f::operator+=(const float v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v; return *this; } Matrix4x4f Matrix4x4f::operator+(const Matrix4x4f &v) const { Matrix4x4f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v.Elements[i]; return ret; } Matrix4x4f Matrix4x4f::operator+(const float v) const { Matrix4x4f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v; return ret; } Matrix4x4f Matrix4x4f::MakeScaleMatrix(float s) { return MakeScaleMatrix(s, s, s); } Matrix4x4f Matrix4x4f::MakeScaleMatrix(const Vector3f &s) { return MakeScaleMatrix(s.x, s.y, s.z); } Matrix4x4f Matrix4x4f::MakeScaleMatrix(float x, float y, float z) { return Matrix4x4f(x, 0.0f, 0.0f, 0.0f, 0.0f, y, 0.0f, 0.0f, 0.0f, 0.0f, z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakeRotationMatrixX(Angle x) { float sinA, cosA; Y_sincosf(x.Radians(), &sinA, &cosA); return Matrix4x4f(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cosA, -sinA, 0.0f, 0.0f, sinA, cosA, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakeRotationMatrixY(Angle y) { float sinA, cosA; Y_sincosf(y.Radians(), &sinA, &cosA); return Matrix4x4f(cosA, 0.0f, sinA, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -sinA, 0.0f, cosA, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakeRotationMatrixZ(Angle z) { float sinA, cosA; Y_sincosf(z.Radians(), &sinA, &cosA); return Matrix4x4f(cosA, -sinA, 0.0f, 0.0f, sinA, cosA, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakeRotationFromEulerAnglesMatrix(const Vector3f &r) { return MakeRotationFromEulerAnglesMatrix(r.x, r.y, r.z); } Matrix4x4f Matrix4x4f::MakeRotationFromEulerAnglesMatrix(Angle x, Angle y, Angle z) { Matrix4x4f xRotation(MakeRotationMatrixX(x)); Matrix4x4f yRotation(MakeRotationMatrixY(y)); Matrix4x4f zRotation(MakeRotationMatrixZ(z)); // remember: right to left return xRotation * yRotation * zRotation; } Matrix4x4f Matrix4x4f::MakeTranslationMatrix(const Vector3f &t) { return MakeTranslationMatrix(t.x, t.y, t.z); } Matrix4x4f Matrix4x4f::MakeTranslationMatrix(float x, float y, float z) { return Matrix4x4f(1.0f, 0.0f, 0.0f, x, 0.0f, 1.0f, 0.0f, y, 0.0f, 0.0f, 1.0f, z, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakePerspectiveProjectionMatrix(float fovY, float aspect, float zNear, float zFar) { // for future: // fovy = 2 * atan(tan(fovw / 2) * (height / width)) // yScale = cot(fovY / 2) float sinHalfFov, cosHalfFov; Y_sincosf(fovY / 2.0f, &sinHalfFov, &cosHalfFov); float yScale = cosHalfFov / sinHalfFov; float xScale = yScale / aspect; return Matrix4x4f(xScale, 0.0f, 0.0f, 0.0f, 0.0f, yScale, 0.0f, 0.0f, 0.0f, 0.0f, zFar / (zNear - zFar), zNear * zFar / (zNear - zFar), 0.0f, 0.0f, -1.0f, 0.0f); } Matrix4x4f Matrix4x4f::MakeOrthographicProjectionMatrix(float width, float height, float zNear, float zFar) { float halfWidth = width / 2.0f; float halfHeight = height / 2.0f; return MakeOrthographicOffCenterProjectionMatrix(-halfWidth, halfWidth, -halfHeight, halfHeight, zNear, zFar); } Matrix4x4f Matrix4x4f::MakeOrthographicOffCenterProjectionMatrix(float left, float right, float bottom, float top, float zNear, float zFar) { return Matrix4x4f(2.0f / (right - left), 0.0f, 0.0f, (left + right) / (left - right), 0.0f, 2.0f / (top - bottom), 0.0f, (top + bottom) / (bottom - top), 0.0f, 0.0f, 1.0f / (zNear - zFar), zNear / (zNear - zFar), 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4f Matrix4x4f::MakeCoordinateSystemConversionMatrix(COORDINATE_SYSTEM fromSystem, COORDINATE_SYSTEM toSystem, bool *pReverseWinding) { Matrix4x4f res; // axischange Matrix4x4f AxisChange; if ((fromSystem == COORDINATE_SYSTEM_Y_UP_LH || fromSystem == COORDINATE_SYSTEM_Y_UP_RH) && (toSystem == COORDINATE_SYSTEM_Z_UP_LH || toSystem == COORDINATE_SYSTEM_Z_UP_RH)) { // going yup -> zup, rotate 90 degrees forward AxisChange = MakeRotationMatrixX(90.0f); } else if ((fromSystem == COORDINATE_SYSTEM_Z_UP_LH || fromSystem == COORDINATE_SYSTEM_Z_UP_RH) && (toSystem == COORDINATE_SYSTEM_Y_UP_LH || toSystem == COORDINATE_SYSTEM_Y_UP_RH)) { // going zup -> yup, rotate 90 degrees backwards AxisChange = MakeRotationMatrixX(-90.0f); } else { // no axis change AxisChange.SetIdentity(); } // handedness change uint32 fromHandedness = (fromSystem == COORDINATE_SYSTEM_Y_UP_LH || fromSystem == COORDINATE_SYSTEM_Z_UP_LH) ? 0 : 1; uint32 toHandedness = (toSystem == COORDINATE_SYSTEM_Y_UP_LH || toSystem == COORDINATE_SYSTEM_Z_UP_LH) ? 0 : 1; if (fromHandedness != toHandedness) { static const Matrix4x4f MirrorYAxis(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); static const Matrix4x4f MirrorZAxis(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1); if (toSystem == COORDINATE_SYSTEM_Y_UP_LH || toSystem == COORDINATE_SYSTEM_Y_UP_RH) res = MirrorZAxis * AxisChange; else res = MirrorYAxis * AxisChange; if (pReverseWinding != NULL) *pReverseWinding = true; } else { res = AxisChange; if (pReverseWinding != NULL) *pReverseWinding = false; } return res; } Matrix4x4f Matrix4x4f::MakeLookAtViewMatrix(const Vector3f &eye, const Vector3f &at, const Vector3f &up) { SIMDVector3f zAxis = (eye - at).SafeNormalize(); SIMDVector3f xAxis = up.Cross(zAxis).SafeNormalize(); SIMDVector3f yAxis = zAxis.Cross(xAxis); return Matrix4x4f(xAxis.x, xAxis.y, xAxis.z, -xAxis.Dot(eye), yAxis.x, yAxis.y, yAxis.z, -yAxis.Dot(eye), zAxis.x, zAxis.y, zAxis.z, -zAxis.Dot(eye), 0.0f, 0.0f, 0.0f, 1.0f); } static const float s_CubeViewMatrices[6][16] = { // +x { 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, // -x { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, // +y { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, // -y { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, // +z { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, // -z { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; Matrix4x4f Matrix4x4f::MakeCubeViewMatrix(uint32 face) { DebugAssert(face < 6); return Matrix4x4f(s_CubeViewMatrices[face]).Transpose(); } Matrix4x4f Matrix4x4f::MakeCubeViewMatrix(uint32 face, const Vector3f &position) { DebugAssert(face < 6); Matrix4x4f ret(s_CubeViewMatrices[face]); ret.SetColumn(3, Vector4f(-ret.GetRow(0).Dot(position), -ret.GetRow(1).Dot(position), -ret.GetRow(2).Dot(position), 1.0f)); return ret; } // constants static const float __float4x4Zero[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; const Matrix4x4f &Matrix4x4f::Zero = reinterpret_cast<const Matrix4x4f &>(__float4x4Zero); static const float __float4x4Identity[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; const Matrix4x4f &Matrix4x4f::Identity = reinterpret_cast<const Matrix4x4f &>(__float4x4Identity); //======================================================================================================================================================================================================================== Matrix3x4f::Matrix3x4f(const float &E00, const float &E01, const float &E02, const float &E03, const float &E10, const float &E11, const float &E12, const float &E13, const float &E20, const float &E21, const float &E22, const float &E23) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E03; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E13; *pv++ = E20; *pv++ = E21; *pv++ = E22; *pv = E23; } Matrix3x4f::Matrix3x4f(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix3x4f::Matrix3x4f(const float p[3][4]) { Y_memcpy(Elements, p, sizeof(Elements)); } Matrix3x4f::Matrix3x4f(const Matrix3x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); } // float3x4::float3x4(const Matrix3x4 &v) // { // Y_memcpy(Elements, v.Elements, sizeof(Elements)); // } Matrix3x4f::Matrix3x4f(const Matrix4x4f &v) { Y_memcpy(Row[0], v.Row[0], sizeof(Row[0])); Y_memcpy(Row[1], v.Row[1], sizeof(Row[1])); Y_memcpy(Row[2], v.Row[2], sizeof(Row[2])); } void Matrix3x4f::Set(const float &E00, const float &E01, const float &E02, const float &E03, const float &E10, const float &E11, const float &E12, const float &E13, const float &E20, const float &E21, const float &E22, const float &E23) { float *pv = &m00; *pv++ = E00; *pv++ = E01; *pv++ = E02; *pv++ = E03; *pv++ = E10; *pv++ = E11; *pv++ = E12; *pv++ = E13; *pv++ = E20; *pv++ = E21; *pv++ = E22; *pv = E23; } void Matrix3x4f::SetZero() { float *pv = &m00; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv = 0.0f; } void Matrix3x4f::SetIdentity() { float *pv = &m00; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 0.0f; *pv++ = 1.0f; *pv = 0.0f; } Vector3f Matrix3x4f::GetColumn(uint32 j) const { DebugAssert(j < 4); return Vector3f(Row[0][j], Row[1][j], Row[2][j]); } void Matrix3x4f::SetColumn(uint32 j, const Vector3f &v) { DebugAssert(j < 4); Row[0][j] = v.x; Row[1][j] = v.y; Row[2][j] = v.z; } void Matrix3x4f::SetTranspose(const float *pElements) { float *pv = &m00; *pv++ = pElements[0]; *pv++ = pElements[3]; *pv++ = pElements[6]; *pv++ = pElements[9]; *pv++ = pElements[1]; *pv++ = pElements[4]; *pv++ = pElements[7]; *pv++ = pElements[10]; *pv++ = pElements[2]; *pv++ = pElements[5]; *pv++ = pElements[8]; *pv = pElements[11]; } void Matrix3x4f::GetTranspose(float *pElements) const { float *pv = pElements; *pv++ = Row[0][0]; *pv++ = Row[1][0]; *pv++ = Row[2][0]; *pv++ = Row[3][0]; *pv++ = Row[0][1]; *pv++ = Row[1][1]; *pv++ = Row[2][1]; *pv++ = Row[3][1]; *pv++ = Row[0][2]; *pv++ = Row[1][2]; *pv++ = Row[2][2]; *pv = Row[3][2]; } Vector3f Matrix3x4f::TransformPoint(const Vector3f &point) const { Vector3f ret; ret.x = Vector3f(Row[0]).Dot(point) + Row[0][3]; ret.y = Vector3f(Row[1]).Dot(point) + Row[1][3]; ret.z = Vector3f(Row[2]).Dot(point) + Row[2][3]; return ret; } Vector3f Matrix3x4f::TransformNormal(const Vector3f &normal, bool normalize /* = true */) const { Vector3f ret; ret.x = Vector3f(Row[0]).Dot(normal); ret.y = Vector3f(Row[1]).Dot(normal); ret.z = Vector3f(Row[2]).Dot(normal); if (normalize && ret.SquaredLength() > 0.0f) ret.NormalizeInPlace(); return ret; } void Matrix3x4f::Load(const float *pValues) { Row[0][0] = pValues[0]; Row[0][1] = pValues[1]; Row[0][2] = pValues[2]; Row[0][3] = pValues[3]; Row[1][0] = pValues[4]; Row[1][1] = pValues[5]; Row[1][2] = pValues[6]; Row[1][3] = pValues[7]; Row[2][0] = pValues[8]; Row[2][1] = pValues[9]; Row[2][2] = pValues[10]; Row[2][3] = pValues[11]; } void Matrix3x4f::Store(float *pValues) { pValues[0] = Row[0][0]; pValues[1] = Row[0][1]; pValues[2] = Row[0][2]; pValues[3] = Row[0][3]; pValues[4] = Row[1][0]; pValues[5] = Row[1][1]; pValues[6] = Row[1][2]; pValues[7] = Row[1][3]; pValues[8] = Row[2][0]; pValues[9] = Row[2][1]; pValues[10] = Row[2][2]; pValues[11] = Row[2][3]; } // Matrix3x4 float3x4::GetMatrix3x4() const // { // return Matrix3x4(&m00); // } Matrix3x4f &Matrix3x4f::operator=(const Matrix3x4f &v) { Y_memcpy(Elements, v.Elements, sizeof(Elements)); return *this; } Matrix3x4f &Matrix3x4f::operator=(const float *p) { Y_memcpy(Elements, p, sizeof(Elements)); return *this; } // float3x4 &float3x4::operator=(const Matrix3x4 &v) // { // Y_memcpy(Elements, v.Elements, sizeof(Elements)); // return *this; // } Matrix3x4f &Matrix3x4f::operator*=(const Matrix3x4f &v) { // again, rvo should fix this up Matrix3x4f temp(*this); *this = temp * v; return *this; } Matrix3x4f &Matrix3x4f::operator*=(const float v) { uint32 i; for (i = 0; i < 16; i++) Elements[i] *= v; return *this; } Matrix3x4f Matrix3x4f::operator*(const Matrix3x4f &v) const { static const float lastRow[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; #define mulRC(rw, cl) Row[rw][0] * v.Row[0][cl] + \ Row[rw][1] * v.Row[1][cl] + \ Row[rw][2] * v.Row[2][cl] + \ Row[rw][3] * lastRow[cl] Matrix3x4f res; res.m00 = mulRC(0, 0); res.m01 = mulRC(0, 1); res.m02 = mulRC(0, 2); res.m03 = mulRC(0, 3); res.m10 = mulRC(1, 0); res.m11 = mulRC(1, 1); res.m12 = mulRC(1, 2); res.m13 = mulRC(1, 3); res.m20 = mulRC(2, 0); res.m21 = mulRC(2, 1); res.m22 = mulRC(2, 2); res.m23 = mulRC(2, 3); return res; #undef mulRC } Matrix3x4f Matrix3x4f::operator*(float v) const { uint32 i; Matrix3x4f res; for (i = 0; i < 12; i++) res.Elements[i] = Elements[i] * v; return res; } Matrix3x4f Matrix3x4f::operator-() const { uint32 i; Matrix3x4f res; for (i = 0; i < 12; i++) res.Elements[i] = -Elements[i]; return res; } Vector3f Matrix3x4f::operator*(const Vector3f &v) const { Vector3f res; res.x = Row[0][0] * v.x + Row[0][1] * v.y + Row[0][2] * v.z + Row[0][3]; res.y = Row[1][0] * v.x + Row[1][1] * v.y + Row[1][2] * v.z + Row[1][3]; res.z = Row[2][0] * v.x + Row[2][1] * v.y + Row[2][2] * v.z + Row[2][3]; return res; } Matrix3x4f &Matrix3x4f::operator+=(const Matrix3x4f &v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v.Elements[i]; return *this; } Matrix3x4f &Matrix3x4f::operator+=(const float v) { for (uint32 i = 0; i < countof(Elements); i++) Elements[i] += v; return *this; } Matrix3x4f Matrix3x4f::operator+(const Matrix3x4f &v) const { Matrix3x4f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v.Elements[i]; return ret; } Matrix3x4f Matrix3x4f::operator+(const float v) const { Matrix3x4f ret; for (uint32 i = 0; i < countof(Elements); i++) ret.Elements[i] = Elements[i] + v; return ret; } // constants static const float __float3x4Zero[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; const Matrix3x4f &Matrix3x4f::Zero = reinterpret_cast<const Matrix3x4f &>(__float3x4Zero); static const float __float3x4Identity[12] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }; const Matrix3x4f &Matrix3x4f::Identity = reinterpret_cast<const Matrix3x4f &>(__float3x4Identity); <file_sep>/Engine/Source/Renderer/Shaders/DownsampleShader.h #pragma once #include "Renderer/ShaderComponent.h" class ShaderProgram; class DownsampleShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(DownsampleShader, ShaderComponent); public: DownsampleShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pInputTexture, uint32 mipLevel); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/Engine/ScriptProxyFunctions.h #include "Engine/ScriptManager.h" #include "lua.hpp" ////////////////////////////////////////////////////////////////////////// // Wrapper macros - this as a value type // TODO: REPLACE ALL THIS WITH VARIADIC TEMPLATES ////////////////////////////////////////////////////////////////////////// #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL(wrapperName, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ thisVal.function(); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_P1(wrapperName, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ thisVal.function(p1Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_P2(wrapperName, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ thisVal.function(p1Val, p2Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_P3(wrapperName, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ thisVal.function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_P4(wrapperName, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ thisVal.function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_RET(wrapperName, retType, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ retType retVal = thisVal.function(); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(wrapperName, retType, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ retType retVal = thisVal.function(p1Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(wrapperName, retType, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ retType retVal = thisVal.function(p1Val, p2Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P3(wrapperName, retType, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P4(wrapperName, retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val, p4Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL(thisType, function) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ thisVal.function(); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_P1(thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ thisVal.function(p1Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_P2(thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ thisVal.function(p1Val, p2Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_P3(thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ thisVal.function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ thisVal.function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_RET(retType, thisType, function) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ retType retVal = thisVal.function(); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P1(retType, thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ retType retVal = thisVal.function(p1Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P2(retType, thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ retType retVal = thisVal.function(p1Val, p2Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptArg<thisType>::Get(L, 1); \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val, p4Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } ////////////////////////////////////////////////////////////////////////// // Wrapper macros -- this value as pointer type with checks ////////////////////////////////////////////////////////////////////////// #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR(thisType, function) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ thisVal->function(); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_P1(thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ thisVal->function(p1Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_P2(thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ thisVal->function(p1Val, p2Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_P3(thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ thisVal->function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ thisVal->function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_RET(retType, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ retType retVal = thisVal->function(); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P1(retType, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ retType retVal = thisVal->function(p1Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P2(retType, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ retType retVal = thisVal->function(p1Val, p2Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val, p4Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR(thisType, function) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ thisVal->function(); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P1(thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ thisVal->function(p1Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P2(thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ thisVal->function(p1Val, p2Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P3(thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ thisVal->function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ thisVal->function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(retType, thisType, function) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ retType retVal = thisVal->function(); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P1(retType, thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ retType retVal = thisVal->function(p1Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P2(retType, thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ retType retVal = thisVal->function(p1Val, p2Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptArg<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptArg<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptArg<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptArg<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptArg<p4Type>::Get(L, 5); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val, p4Val); \ ScriptArg<retType>::Push(L, retVal); \ return 1; \ } ////////////////////////////////////////////////////////////////////////// // Wrapper macros - this as a value type // TODO: REPLACE ALL THIS WITH VARIADIC TEMPLATES ////////////////////////////////////////////////////////////////////////// #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(wrapperName, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ thisVal.function(); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P1(wrapperName, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ thisVal.function(p1Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P2(wrapperName, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ thisVal.function(p1Val, p2Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P3(wrapperName, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ thisVal.function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P4(wrapperName, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ thisVal.function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(wrapperName, retType, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ retType retVal = thisVal.function(); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(wrapperName, retType, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ retType retVal = thisVal.function(p1Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(wrapperName, retType, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ retType retVal = thisVal.function(p1Val, p2Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P3(wrapperName, retType, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P4(wrapperName, retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val, p4Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL(thisType, function) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ thisVal.function(); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_P1(thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ thisVal.function(p1Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_P2(thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ thisVal.function(p1Val, p2Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_P3(thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ thisVal.function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ thisVal.function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_RET(retType, thisType, function) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ retType retVal = thisVal.function(); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P1(retType, thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ retType retVal = thisVal.function(p1Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P2(retType, thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ retType retVal = thisVal.function(p1Val, p2Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISVAL_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType thisVal = ScriptComplexType<thisType>::Get(L, 1); \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ retType retVal = thisVal.function(p1Val, p2Val, p3Val, p4Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } ////////////////////////////////////////////////////////////////////////// // Wrapper macros -- this value as pointer type with checks ////////////////////////////////////////////////////////////////////////// #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR(thisType, function) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ thisVal->function(); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_P1(thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ thisVal->function(p1Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_P2(thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ thisVal->function(p1Val, p2Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_P3(thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ thisVal->function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ thisVal->function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_RET(retType, thisType, function) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ retType retVal = thisVal->function(); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P1(retType, thisType, function, p1Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ retType retVal = thisVal->function(p1Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P2(retType, thisType, function, p1Type, p2Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ retType retVal = thisVal->function(p1Val, p2Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISPTR_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ static int wrapperName(lua_State *L) { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val, p4Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR(thisType, function) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ thisVal->function(); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_P1(thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ thisVal->function(p1Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_P2(thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ thisVal->function(p1Val, p2Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_P3(thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ thisVal->function(p1Val, p2Val, p3Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_P4(thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ thisVal->function(p1Val, p2Val, p3Val, p4Val); \ return 0; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_RET(retType, thisType, function) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ retType retVal = thisVal->function(); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P1(retType, thisType, function, p1Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ retType retVal = thisVal->function(p1Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P2(retType, thisType, function, p1Type, p2Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ retType retVal = thisVal->function(p1Val, p2Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P3(retType, thisType, function, p1Type, p2Type, p3Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } #define MAKE_COMPLEX_SCRIPT_PROXY_LAMBDA_THISPTR_RET_P4(retType, thisType, function, p1Type, p2Type, p3Type, p4Type) \ [](lua_State *L) -> int { \ thisType *thisVal = ScriptComplexType<thisType *>::Get(L, 1); \ if (thisVal == nullptr) { luaL_argerror(L, 1, "attempt to call method on null object"); } \ p1Type p1Val = ScriptComplexType<p1Type>::Get(L, 2); \ p2Type p2Val = ScriptComplexType<p2Type>::Get(L, 3); \ p3Type p3Val = ScriptComplexType<p3Type>::Get(L, 4); \ p4Type p4Val = ScriptComplexType<p4Type>::Get(L, 5); \ retType retVal = thisVal->function(p1Val, p2Val, p3Val, p4Val); \ ScriptComplexType<retType>::Push(L, retVal); \ return 1; \ } <file_sep>/Engine/Source/D3D12Renderer/D3D12Helpers.h #pragma once #include "D3D12Renderer/D3D12Common.h" namespace D3D12Helpers { DXGI_FORMAT PixelFormatToDXGIFormat(PIXEL_FORMAT Format); PIXEL_FORMAT DXGIFormatToPixelFormat(DXGI_FORMAT Format); void SetD3D12ObjectName(ID3D12Object *pObject, const char *debugName); bool FillD3D12RasterizerStateDesc(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerState, D3D12_RASTERIZER_DESC *pOutRasterizerDesc); bool FillD3D12DepthStencilStateDesc(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState, D3D12_DEPTH_STENCIL_DESC *pOutDepthStencilDesc); bool FillD3D12BlendStateDesc(const RENDERER_BLEND_STATE_DESC *pBlendState, D3D12_BLEND_DESC *pOutBlendDesc); bool FillD3D12SamplerStateDesc(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, D3D12_SAMPLER_DESC *pOutSamplerStateDesc); D3D12_PRIMITIVE_TOPOLOGY GetD3D12PrimitiveTopology(DRAW_TOPOLOGY topology); D3D12_PRIMITIVE_TOPOLOGY_TYPE GetD3D12PrimitiveTopologyType(DRAW_TOPOLOGY topology); bool GetResourceSRVHandle(GPUResource *pResource, D3D12DescriptorHandle *pHandle); bool GetResourceSamplerHandle(GPUResource *pResource, D3D12DescriptorHandle *pHandle); bool GetOptimizedClearValue(PIXEL_FORMAT format, D3D12_CLEAR_VALUE *pValue); D3D12_RESOURCE_STATES GetResourceDefaultState(GPUResource *pResource); } <file_sep>/Editor/Source/Editor/EditorVectorEditWidget.h #pragma once #include "Editor/Common.h" class EditorVectorEditWidget : public QWidget { Q_OBJECT public: EditorVectorEditWidget(QWidget *pParent = NULL); ~EditorVectorEditWidget(); const uint32 GetNumComponents() const { return m_numComponents; } const float GetValueX() const { return m_x; } const float GetValueY() const { return m_y; } const float GetValueZ() const { return m_z; } const float GetValueW() const { return m_w; } const float2 GetValueFloat2() const { return float2(m_x, m_y); } const float3 GetValueFloat3() const { return float3(m_x, m_y, m_z); } const float4 GetValueFloat4() const { return float4(m_x, m_y, m_z, m_w); } QString GetValueString() const; public Q_SLOTS: void SetNumComponents(uint32 numComponents); void SetValue(float x = 0.0f, float y = 0.0f, float z = 0.0f, float w = 0.0f); Q_SIGNALS: void ValueChangedFloat2(const float2 &value); void ValueChangedFloat3(const float3 &value); void ValueChangedFloat4(const float4 &value); void ValueChangedString(const QString &value); private Q_SLOTS: void OnExpandButtonClicked(); void OnPopupPanelXChanged(double value); void OnPopupPanelYChanged(double value); void OnPopupPanelZChanged(double value); void OnPopupPanelWChanged(double value); void OnPopupPanelNormalizeClicked(); private: void UpdateLineEdit(); void EmitValueChangedSignals(); uint32 m_numComponents; float m_x, m_y, m_z, m_w; QLineEdit *m_pLineEdit; QPushButton *m_pBrowseButton; QWidget *m_pPopupPanel; }; <file_sep>/Engine/Source/Renderer/ShaderProgram.h #pragma once #include "Renderer/RendererTypes.h" class GPUContext; class GPUResource; class GPUSamplerState; class ShaderComponentTypeInfo; class VertexFactoryTypeInfo; class GPUShaderProgram; class MaterialShader; class ShaderProgram { public: ShaderProgram(GPUShaderProgram *pGPUProgram, uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); ~ShaderProgram(); const uint32 GetGlobalShaderFlags() const { return m_globalShaderFlags; } const ShaderComponentTypeInfo *GetBaseShaderTypeInfo() const { return m_pBaseShaderTypeInfo; } const uint32 GetBaseShaderFlags() const { return m_baseShaderFlags; } const VertexFactoryTypeInfo *GetVertexFactoryTypeInfo() const { return m_pVertexFactoryTypeInfo; } const uint32 GetVertexFactoryFlags() const { return m_vertexFactoryFlags; } const MaterialShader *GetMaterialShader() const { return m_pMaterialShader; } const uint32 GetMaterialShaderFlags() const { return m_materialShaderFlags; } GPUShaderProgram *GetGPUProgram() const { return m_pGPUProgram; } // --- parameter tables --- void SetBaseShaderParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const; void SetBaseShaderParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const; void SetBaseShaderParameterStruct(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize) const; void SetBaseShaderParameterStructArray(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) const; void SetBaseShaderParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const; void SetBaseShaderParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const; void SetVertexFactoryParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const; void SetVertexFactoryParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const; void SetVertexFactoryParameterStruct(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize) const; void SetVertexFactoryParameterStructArray(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) const; void SetVertexFactoryParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const; void SetVertexFactoryParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const; void SetMaterialParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const; void SetMaterialParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const; void SetMaterialParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const; void SetMaterialParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const; // comparitor static int32 Compare(const ShaderProgram *a, const ShaderProgram *b); // ordering operators bool operator<(const ShaderProgram &other) const { return (Compare(this, &other) < 0); } private: // parameter map generators void GenerateBaseShaderParameterMap(); void GenerateVertexFactoryParameterMap(); void GenerateMaterialShaderUniformParameterMap(); void GenerateMaterialShaderTextureParameterMap(); // ordered by size, access frequency for lookup, then use const ShaderComponentTypeInfo *m_pBaseShaderTypeInfo; const VertexFactoryTypeInfo *m_pVertexFactoryTypeInfo; const MaterialShader *m_pMaterialShader; uint32 m_globalShaderFlags; uint32 m_baseShaderFlags; uint32 m_vertexFactoryFlags; uint32 m_materialShaderFlags; GPUShaderProgram *m_pGPUProgram; int32 *m_pBaseShaderParameterMap; int32 *m_pVertexFactoryParameterMap; int32 *m_pMaterialShaderUniformParameterMap; int32 *m_pMaterialShaderTextureParameterMap; }; // D3D12 version class ShaderPipeline : public ShaderProgram { public: struct CreationParameters { // TODO: order in the order of most frequently changing -> least, so that searching is faster const GPURasterizerState *pRasterizerState; const GPUDepthStencilState *pDepthStencilState; const GPUBlendState *pBlendState; const ShaderComponentTypeInfo *pBaseShaderTypeInfo; const VertexFactoryTypeInfo *pVertexFactoryTypeInfo; const MaterialShader *pMaterialShader; uint32 GlobalShaderFlags; uint32 BaseShaderFlags; uint32 VertexFactoryFlags; uint32 MaterialShaderFlags; PIXEL_FORMAT OutputColorFormat; PIXEL_FORMAT OutputDepthStencilFormat; }; public: ShaderPipeline(GPUShaderPipeline *pGPUPipeline, const CreationParameters *pCreationParameters); ~ShaderPipeline(); // comparitor static int32 Compare(const ShaderPipeline *a, const ShaderPipeline *b); // ordering operators bool operator<(const ShaderPipeline &other) const { return (Compare(this, &other) < 0); } };<file_sep>/Editor/Source/Editor/MapEditor/EditorMapViewport.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorEditMode.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorCVars.h" #include "Engine/ResourceManager.h" #include "Engine/Entity.h" #include "Engine/Font.h" #include "Renderer/Renderer.h" #include "Renderer/RenderProfiler.h" Log_SetChannel(EditorMapViewport); static const PIXEL_FORMAT SCENE_PIXEL_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; static const PIXEL_FORMAT SCENE_DEPTH_STENCIL_PIXEL_FORMAT = PIXEL_FORMAT_D24_UNORM_S8_UINT; static const PIXEL_FORMAT PICKING_TEXTURE_PIXEL_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; static const PIXEL_FORMAT PICKING_DEPTH_STENCIL_PIXEL_FORMAT = PIXEL_FORMAT_D24_UNORM_S8_UINT; static EditorMapViewport *s_pViewportWithMouseGrab = nullptr; EditorMapViewport::EditorMapViewport(EditorMapWindow *pMapWindow, EditorMap *pMap, uint32 viewportId, EDITOR_CAMERA_MODE cameraMode, EDITOR_RENDER_MODE renderMode, uint32 viewportFlags) : QWidget(pMapWindow), m_ui(new Ui_EditorMapViewport()), m_pMapWindow(pMapWindow), m_pMap(pMap), m_viewportId(viewportId), m_renderMode(renderMode), m_viewportFlags(viewportFlags), m_worldTime(0.0f), m_mousePosition(int2::Zero), m_mouseDelta(int2::Zero), m_mouseGrabbed(false), m_mouseGrabPosition(int2::Zero), m_cursorType(EDITOR_CURSOR_TYPE_ARROW), m_redrawPending(false), m_hardwareResourcesCreated(false), m_pSwapChain(nullptr), m_pPickingRenderTarget(nullptr), m_pPickingRenderTargetView(nullptr), m_pPickingDepthStencilBuffer(nullptr), m_pPickingDepthStencilBufferView(nullptr), m_pWorldRenderer(nullptr), m_pPickingWorldRenderer(nullptr) { // update view ccontroller m_viewController.SetCameraMode(cameraMode); // create ui m_ui->CreateUI(this); m_ui->UpdateUIForCameraMode(cameraMode); m_ui->UpdateUIForRenderMode(renderMode); m_ui->UpdateUIForViewportFlags(viewportFlags); // connect ui events ConnectUIEvents(); // queue a draw FlagForRedraw(); } EditorMapViewport::~EditorMapViewport() { if (s_pViewportWithMouseGrab == this) UnlockMouseCursor(); // if active, unset if (IsActiveViewport()) m_pMapWindow->SetActiveViewport(nullptr); // free everything else ReleaseHardwareResources(); // kill ui delete m_ui; } void EditorMapViewport::SetCameraMode(EDITOR_CAMERA_MODE cameraMode) { m_viewController.SetCameraMode(cameraMode); m_ui->UpdateUIForCameraMode(cameraMode); } void EditorMapViewport::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } // update state m_renderMode = renderMode; delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); FlagForRedraw(); // update ui m_ui->UpdateUIForRenderMode(renderMode); } void EditorMapViewport::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorMapViewport::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } bool EditorMapViewport::CreateHardwareResources() { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == nullptr) return false; m_pSwapChain->AddRef(); } uint32 swapChainWidth = m_pSwapChain->GetWidth(); uint32 swapChainHeight = m_pSwapChain->GetHeight(); //Log_DevPrintf("Creating hardware resources for viewport (%u x %u)", swapChainWidth, swapChainHeight); // create picking render target if (m_pPickingRenderTarget == NULL) { GPU_TEXTURE2D_DESC textureDesc; textureDesc.Width = swapChainWidth; textureDesc.Height = swapChainHeight; textureDesc.Format = PICKING_TEXTURE_PIXEL_FORMAT; textureDesc.Flags = GPU_TEXTURE_FLAG_READABLE | GPU_TEXTURE_FLAG_BIND_RENDER_TARGET; textureDesc.MipLevels = 1; GPU_DEPTH_TEXTURE_DESC depthStencilBufferDesc; depthStencilBufferDesc.Width = swapChainWidth; depthStencilBufferDesc.Height = swapChainHeight; depthStencilBufferDesc.Format = PIXEL_FORMAT_D16_UNORM; depthStencilBufferDesc.Flags = GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER; if ((m_pPickingRenderTarget = g_pRenderer->CreateTexture2D(&textureDesc, nullptr)) == nullptr || (m_pPickingDepthStencilBuffer = g_pRenderer->CreateDepthTexture(&depthStencilBufferDesc)) == nullptr) { Log_ErrorPrintf("Could not create selection render target."); SAFE_RELEASE(m_pPickingDepthStencilBuffer); SAFE_RELEASE(m_pPickingRenderTarget); return false; } GPU_RENDER_TARGET_VIEW_DESC rtvDesc(m_pPickingRenderTarget, 0); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC dsvDesc(m_pPickingDepthStencilBuffer); if ((m_pPickingRenderTargetView = g_pRenderer->CreateRenderTargetView(m_pPickingRenderTarget, &rtvDesc)) == nullptr || (m_pPickingDepthStencilBufferView = g_pRenderer->CreateDepthStencilBufferView(m_pPickingDepthStencilBuffer, &dsvDesc)) == nullptr) { Log_ErrorPrintf("Could not create selection render target view."); SAFE_RELEASE(m_pPickingDepthStencilBufferView); SAFE_RELEASE(m_pPickingDepthStencilBuffer); SAFE_RELEASE(m_pPickingRenderTargetView); SAFE_RELEASE(m_pPickingRenderTarget); return false; } // create picking texture local copy if (!m_PickingTextureCopy.IsValidImage()) { m_PickingTextureCopy.Create(PICKING_TEXTURE_PIXEL_FORMAT, swapChainWidth, swapChainHeight, 1); Y_memzero(m_PickingTextureCopy.GetData(), m_PickingTextureCopy.GetDataSize()); } } // create render context if (m_pWorldRenderer == nullptr) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, swapChainWidth, swapChainHeight); // create picking texture render context if (m_pPickingWorldRenderer == nullptr) m_pPickingWorldRenderer = EditorHelpers::CreatePickingWorldRenderer(pGPUContext, swapChainWidth, swapChainHeight); // update gui context, camera m_guiContext.SetViewportDimensions(swapChainWidth, swapChainHeight); m_guiContext.SetGPUContext(g_pRenderer->GetGPUContext()); m_viewController.SetViewportDimensions(swapChainWidth, swapChainHeight); #ifdef Y_BUILD_CONFIG_DEBUG m_pPickingRenderTarget->SetDebugName("Picking Render Target"); m_pPickingDepthStencilBuffer->SetDebugName("Picking Depth Stencil Buffer"); #endif // cancel any pending draws until the windows are arranged and a paint is requested. m_hardwareResourcesCreated = true; return true; } void EditorMapViewport::ReleaseHardwareResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; delete m_pPickingWorldRenderer; m_PickingTextureCopy.Delete(); SAFE_RELEASE(m_pPickingDepthStencilBufferView); SAFE_RELEASE(m_pPickingDepthStencilBuffer); SAFE_RELEASE(m_pPickingRenderTargetView); SAFE_RELEASE(m_pPickingRenderTarget); SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_hardwareResourcesCreated = false; } const bool EditorMapViewport::IsActiveViewport() const { return (m_pMapWindow->GetActiveViewport() == this); } void EditorMapViewport::SetFocus() { m_pMapWindow->SetActiveViewport(this); m_ui->swapChainWidget->setFocus(); } void EditorMapViewport::SetMouseCursor(EDITOR_CURSOR_TYPE cursorType) { //m_ui->swapChainWidget->setCursor() m_cursorType = cursorType; } void EditorMapViewport::LockMouseCursor() { if (m_mouseGrabbed) return; if (s_pViewportWithMouseGrab != nullptr) s_pViewportWithMouseGrab->UnlockMouseCursor(); // grab mouse and set an empty cursor m_ui->swapChainWidget->grabMouse(QCursor(Qt::BlankCursor)); // get current global mouse position QPoint currentMousePosition(QCursor::pos()); // init grab state m_mouseGrabbed = true; m_mouseGrabPosition.Set(currentMousePosition.x(), currentMousePosition.y()); s_pViewportWithMouseGrab = this; FlagForRedraw(); } void EditorMapViewport::UnlockMouseCursor() { DebugAssert(s_pViewportWithMouseGrab == this); // restore old position QCursor::setPos(m_mouseGrabPosition.x, m_mouseGrabPosition.y); // release grab and cursor at the same time m_ui->swapChainWidget->releaseMouse(); m_mouseGrabbed = false; s_pViewportWithMouseGrab = nullptr; // redraw to remove the crosshairs FlagForRedraw(); } void EditorMapViewport::FlagForRedraw() { if (!m_redrawPending) { m_redrawPending = true; g_pEditor->QueueFrameExecution(); } } bool EditorMapViewport::Draw(const float timeDiff) { // update camera m_viewController.Update(timeDiff); // update time if (HasViewportFlag(EDITOR_VIEWPORT_FLAG_REALTIME)) m_worldTime += timeDiff; // force draw if requested by camera if (m_viewController.IsChanged()) { m_pMapWindow->OnViewportCameraChange(this); if (!HasViewportFlag(EDITOR_VIEWPORT_FLAG_REALTIME)) FlagForRedraw(); } // do draw if (!m_redrawPending && !(m_viewportFlags & EDITOR_VIEWPORT_FLAG_REALTIME)) return false; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // create hardware resources if (!m_hardwareResourcesCreated && !CreateHardwareResources()) return false; // bind output buffer pGPUContext->SetOutputBuffer(m_pSwapChain); // for debugging, we draw the view first, but for release and perf optimization, we draw the view last DrawView(); DrawPickTexture(); // swap swapchain buffers pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // now read the picking texture back. DebugAssert(m_PickingTextureCopy.IsValidImage()); if (!pGPUContext->ReadTexture(m_pPickingRenderTarget, m_PickingTextureCopy.GetData(), m_PickingTextureCopy.GetDataRowPitch(), m_PickingTextureCopy.GetDataSize(), 0, 0, 0, m_PickingTextureCopy.GetWidth(), m_PickingTextureCopy.GetHeight())) { Log_WarningPrintf("Failed to read back picking texture."); Y_memzero(m_PickingTextureCopy.GetData(), m_PickingTextureCopy.GetDataSize()); } // clear context state pGPUContext->ClearState(true, true, true, true); // no draw pending now m_redrawPending = false; return true; } bool EditorMapViewport::GetPickingTextureValues(const int2 &MinCoordinates, const int2 &MaxCoordinates, uint32 *pValues) const { if (m_pPickingRenderTarget == NULL || (uint32)MinCoordinates.x >= m_PickingTextureCopy.GetWidth() || (uint32)MinCoordinates.y >= m_PickingTextureCopy.GetHeight() || (uint32)MaxCoordinates.x >= m_PickingTextureCopy.GetWidth() || (uint32)MaxCoordinates.y >= m_PickingTextureCopy.GetHeight() || MinCoordinates.AnyGreater(MaxCoordinates)) { return false; } // get number of values to read Vector2i coordinateRange = Vector2i(MaxCoordinates) - Vector2i(MinCoordinates) + 1; int32 nValues = (coordinateRange.x) * (coordinateRange.y); DebugAssert(nValues > 0); // read the pixels from the image copy if (!m_PickingTextureCopy.ReadPixels(pValues, sizeof(uint32) * nValues, MinCoordinates.x, MinCoordinates.y, coordinateRange.x, coordinateRange.y)) { // not sure why this would fail return false; } return true; } uint32 EditorMapViewport::GetPickingTextureValue(const int2 &Position) const { uint32 texelValue; if (!GetPickingTextureValues(Position, Position, &texelValue)) return 0; return texelValue; } Ray EditorMapViewport::GetPickRay() const { return m_viewController.GetPickRay(m_mousePosition.x, m_mousePosition.y); } void EditorMapViewport::DrawView() { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); GPUContextConstants *pGPUConstants = pGPUContext->GetConstants(); SmallString tempStr; // set targets pGPUContext->SetOutputBuffer(m_pSwapChain); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetViewport(m_viewController.GetViewport()); pGPUContext->ClearTargets(true, true, true); // setup 3d state pGPUConstants->SetFromCamera(m_viewController.GetCamera(), true); // draw grid if (m_pMap->GetGridLinesVisible()) { static const float gridWidth = 32768.0f * 0.5f; static const float gridHeight = 32768.0f * 0.5f; m_guiContext.Draw3DGrid(Plane(0.0f, 0.0f, 1.0f, 0.0f), float3::Zero, gridWidth, gridHeight, m_pMap->GetGridLinesInterval()); } // callbacks before world m_pMapWindow->GetActiveEditModePointer()->OnViewportDrawBeforeWorld(this); // draw world m_pWorldRenderer->DrawWorld(m_pMap->GetRenderWorld(), m_viewController.GetViewParameters(), nullptr, nullptr); // world renderer can reset the render targets, so set them back again pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetViewport(m_viewController.GetViewport()); // callbacks after world m_pMapWindow->GetActiveEditModePointer()->OnViewportDrawAfterWorld(this); // draw overlays m_pMapWindow->GetActiveEditModePointer()->OnViewportDrawAfterPost(this); DrawAfterPost(); // clear state of everything m_guiContext.ClearState(); } void EditorMapViewport::DrawAfterPost() { m_guiContext.PushManualFlush(); // draw crosshair in widget if grabbed if (m_mouseGrabbed && m_cursorType == EDITOR_CURSOR_TYPE_CROSS) { const RENDERER_VIEWPORT *pRenderViewport = m_viewController.GetViewport(); int32 startX = pRenderViewport->Width / 2; int32 startY = pRenderViewport->Height / 2; m_guiContext.DrawLine(int2(startX - 5, startY), int2(startX + 4, startY), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 150)); m_guiContext.DrawLine(int2(startX, startY - 5), int2(startX, startY + 4), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 150)); } m_guiContext.PopManualFlush(); } void EditorMapViewport::DrawPickTexture() { // setup render targets and constants GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); pGPUContext->GetConstants()->SetFromCamera(m_viewController.GetCamera(), true); // callbacks before world m_pMapWindow->GetActiveEditModePointer()->OnPickingTextureDrawBeforeWorld(this); // draw world m_pPickingWorldRenderer->DrawWorld(m_pMap->GetRenderWorld(), m_viewController.GetViewParameters(), m_pPickingRenderTargetView, m_pPickingDepthStencilBufferView); // world renderer can reset the render targets, so set them back again pGPUContext->SetRenderTargets(1, &m_pPickingRenderTargetView, m_pPickingDepthStencilBufferView); pGPUContext->SetViewport(m_viewController.GetViewport()); // callbacks after world m_pMapWindow->GetActiveEditModePointer()->OnPickingTextureDrawAfterWorld(this); // clear render targets pGPUContext->SetRenderTargets(0, NULL, NULL); } void EditorMapViewport::ConnectUIEvents() { connect(m_ui->toolbarMoreOptions, SIGNAL(clicked()), this, SLOT(OnToolbarMoreOptionsClicked())); connect(m_ui->toolbarRealTime, SIGNAL(clicked(bool)), this, SLOT(OnToolbarRealtimeClicked(bool))); connect(m_ui->toolbarGameView, SIGNAL(clicked(bool)), this, SLOT(OnToolbarGameViewClicked(bool))); connect(m_ui->toolbarCameraFront, SIGNAL(clicked(bool)), this, SLOT(OnToolbarCameraFrontClicked(bool))); connect(m_ui->toolbarCameraSide, SIGNAL(clicked(bool)), this, SLOT(OnToolbarCameraSideClicked(bool))); connect(m_ui->toolbarCameraTop, SIGNAL(clicked(bool)), this, SLOT(OnToolbarCameraTopClicked(bool))); connect(m_ui->toolbarCameraIsometric, SIGNAL(clicked(bool)), this, SLOT(OnToolbarCameraIsometricClicked(bool))); connect(m_ui->toolbarCameraPerspective, SIGNAL(clicked(bool)), this, SLOT(OnToolbarCameraPerspectiveClicked(bool))); connect(m_ui->toolbarViewWireframe, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewWireframeClicked(bool))); connect(m_ui->toolbarViewUnlit, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewUnlitClicked(bool))); connect(m_ui->toolbarViewLit, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewLitClicked(bool))); connect(m_ui->toolbarViewLightingOnly, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewLightingOnlyClicked(bool))); connect(m_ui->toolbarFlagShadows, SIGNAL(clicked(bool)), this, SLOT(OnToolbarFlagShadowsClicked(bool))); connect(m_ui->toolbarFlagWireframeOverlay, SIGNAL(clicked(bool)), this, SLOT(OnToolbarFlagWireframeOverlayClicked(bool))); connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); connect(m_ui->swapChainWidget, SIGNAL(DropEvent(QDropEvent *)), this, SLOT(OnSwapChainWidgetDropEvent(QDropEvent *))); connect(m_ui->swapChainWidget, SIGNAL(GainedFocusEvent()), this, SLOT(OnSwapChainWidgetGainedFocusEvent())); } void EditorMapViewport::focusInEvent(QFocusEvent *pFocusEvent) { if (!IsActiveViewport()) m_pMapWindow->SetActiveViewport(this); } void EditorMapViewport::OnSwapChainWidgetGainedFocusEvent() { if (!IsActiveViewport()) m_pMapWindow->SetActiveViewport(this); } void EditorMapViewport::OnToolbarMoreOptionsClicked() { } void EditorMapViewport::OnSwapChainWidgetResized() { // kill old swapchain refs SAFE_RELEASE(m_pSwapChain); // kill the picking buffers, these will have to be re-created SAFE_RELEASE(m_pPickingRenderTarget); SAFE_RELEASE(m_pPickingRenderTargetView); SAFE_RELEASE(m_pPickingDepthStencilBuffer); SAFE_RELEASE(m_pPickingDepthStencilBufferView); m_PickingTextureCopy.Delete(); // kill renderers delete m_pWorldRenderer; m_pWorldRenderer = nullptr; delete m_pPickingWorldRenderer; m_pPickingWorldRenderer = nullptr; // force recreation of remaining resources m_hardwareResourcesCreated = false; FlagForRedraw(); } void EditorMapViewport::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorMapViewport::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // pass through to edit mode if (!m_pMapWindow->GetActiveEditModePointer()->HandleViewportKeyboardInputEvent(this, pKeyboardEvent)) { } } void EditorMapViewport::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { // update the mouse position from the event if (pMouseEvent->type() == QEvent::MouseMove) { // calculate the delta int2 newMousePosition(pMouseEvent->x(), pMouseEvent->y()); m_mouseDelta = newMousePosition - m_mousePosition; m_mousePosition = newMousePosition; //Log_DevPrintf("mouse pos: %i %i, delta: %i %i", pMouseEvent->x(), pMouseEvent->y(), m_mouseDelta.x, m_mouseDelta.y); } // pass through to edit mode if (!m_pMapWindow->GetActiveEditModePointer()->HandleViewportMouseInputEvent(this, pMouseEvent)) { } } void EditorMapViewport::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { } void EditorMapViewport::OnSwapChainWidgetDropEvent(QDropEvent *pDropEvent) { Log_DevPrintf(""); } <file_sep>/Editor/Source/Editor/EditorViewController.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/EditorViewController.h" #include "Editor/EditorCVars.h" Log_SetChannel(EditorViewController); EditorViewController::EditorViewController() : m_mode(EDITOR_CAMERA_MODE_PERSPECTIVE), m_perspectiveAcceleration(60.0f), m_perspectiveMaxSpeed(5.0f), m_orthographicScale(1.0f), m_yaw(0.0f), m_pitch(0.0f), m_roll(0.0f), m_currentPerspectiveMoveVector(float3::Zero), m_leftKeyState(false), m_rightKeyState(false), m_forwardKeyState(false), m_backKeyState(false), m_upKeyState(false), m_downKeyState(false), m_turboEnabled(false), m_internalChanged(false), m_changed(false) { // initialize view m_viewParameters.ViewCamera.SetPerspectiveFieldOfView(65.0f); m_viewParameters.ViewCamera.SetNearFarPlaneDistances(0.1f, 1000.0f); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE); m_viewParameters.ViewCamera.SetObjectCullDistance((m_viewParameters.ViewCamera.GetFarPlaneDistance() - m_viewParameters.ViewCamera.GetNearPlaneDistance()) * 1.2f); m_viewParameters.MaximumShadowViewDistance = m_viewParameters.ViewCamera.GetObjectCullDistance(); m_viewParameters.Viewport.Set(0, 0, 1, 1, 0.0f, 1.0f); } EditorViewController::~EditorViewController() { } void EditorViewController::SetCameraMode(EDITOR_CAMERA_MODE mode) { DebugAssert(mode < EDITOR_CAMERA_MODE_COUNT); if (m_mode == mode) return; m_mode = mode; Reset(); } void EditorViewController::Reset() { switch (m_mode) { case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT: { m_viewParameters.ViewCamera.SetPosition(float3::Zero); m_viewParameters.ViewCamera.SetRotation(Quaternion::Identity); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); } break; case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_SIDE: { m_viewParameters.ViewCamera.SetPosition(float3::Zero); m_viewParameters.ViewCamera.SetRotation(Quaternion::FromNormalizedAxisAngle(float3::UnitY, 90.0f)); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); } break; case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP: { m_viewParameters.ViewCamera.SetPosition(float3::Zero); m_viewParameters.ViewCamera.SetRotation(Quaternion::FromNormalizedAxisAngle(float3::UnitX, 90.0f)); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); } break; case EDITOR_CAMERA_MODE_ISOMETRIC: { m_viewParameters.ViewCamera.SetPosition(float3::Zero); m_viewParameters.ViewCamera.SetRotation(Quaternion::Identity); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); } break; case EDITOR_CAMERA_MODE_PERSPECTIVE: { m_viewParameters.ViewCamera.SetPosition(float3::Zero); m_viewParameters.ViewCamera.SetRotation(Quaternion::Identity); m_viewParameters.ViewCamera.SetProjectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE); } break; } m_internalChanged = true; } void EditorViewController::LookAt(const float3 &lookAtPosition) { switch (m_mode) { case EDITOR_CAMERA_MODE_PERSPECTIVE: { m_viewParameters.ViewCamera.LookAt(m_viewParameters.ViewCamera.GetPosition(), lookAtPosition, float3::UnitY); m_internalChanged = true; } break; } } void EditorViewController::SetCameraPosition(const float3 &position) { m_viewParameters.ViewCamera.SetPosition(position); m_internalChanged = true; } void EditorViewController::SetCameraRotation(const Quaternion &rotation) { m_viewParameters.ViewCamera.SetRotation(rotation); m_internalChanged = true; } void EditorViewController::Move(const float3 &direction, float distance) { switch (m_mode) { case EDITOR_CAMERA_MODE_ISOMETRIC: case EDITOR_CAMERA_MODE_PERSPECTIVE: { float3 D(direction * distance); if (D.SquaredLength() < Y_FLT_EPSILON) return; m_viewParameters.ViewCamera.SetPosition(m_viewParameters.ViewCamera.GetPosition() + D); m_internalChanged = true; } break; } } void EditorViewController::MoveFromMousePosition(const int2 &mousePositionDiff) { switch (m_mode) { case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT: case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_SIDE: case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP: { const float SCALE = 1.0f; float3 moveVector(float3::Zero); if (mousePositionDiff.x != 0) moveVector += float3::UnitX * ((float)-mousePositionDiff.x * SCALE); if (mousePositionDiff.y != 0) moveVector += float3::UnitY * ((float)mousePositionDiff.y * SCALE); m_viewParameters.ViewCamera.SetPosition(m_viewParameters.ViewCamera.GetPosition() + moveVector); m_internalChanged = true; } break; case EDITOR_CAMERA_MODE_ISOMETRIC: case EDITOR_CAMERA_MODE_PERSPECTIVE: { const float SCALE = 0.5f; float3 moveVector(float3::Zero); if (mousePositionDiff.x != 0) moveVector.x += (float)mousePositionDiff.x * SCALE; if (mousePositionDiff.y != 0) moveVector.y += (float)-mousePositionDiff.y * SCALE; m_viewParameters.ViewCamera.SetPosition(m_viewParameters.ViewCamera.GetPosition() + (m_viewParameters.ViewCamera.GetRotation() * moveVector)); m_internalChanged = true; } break; } } void EditorViewController::ModPitch(float amount) { // rotate around local x axis //Rotate(m_viewParameters.ViewCamera.GetRotation() * Vector3::UnitX, amount); m_pitch = Math::NormalizeAngleDegrees(m_pitch + amount); //m_pitch += amount; UpdateCameraRotation(); } void EditorViewController::ModYaw(float amount) { // rotate around fixed yaw axis //Rotate(m_viewParameters.ViewCamera.GetRotation() * Vector3::UnitZ, amount); m_yaw = Math::NormalizeAngleDegrees(m_yaw + amount); //m_yaw += amount; UpdateCameraRotation(); } void EditorViewController::ModRoll(float amount) { // rotate it //Rotate(m_viewParameters.ViewCamera.GetRotation() * Vector3::UnitY, amount); m_roll = Math::NormalizeAngleDegrees(m_roll + amount); //m_roll += amount; UpdateCameraRotation(); } void EditorViewController::Rotate(const float3 &axis, float angle) { Rotate(Quaternion::FromAxisAngle(axis, angle)); } void EditorViewController::Rotate(const Quaternion &rotation) { switch (m_mode) { case EDITOR_CAMERA_MODE_ISOMETRIC: case EDITOR_CAMERA_MODE_PERSPECTIVE: { Quaternion newRotation(m_viewParameters.ViewCamera.GetRotation() * rotation); newRotation.NormalizeInPlace(); m_viewParameters.ViewCamera.SetRotation(newRotation); m_internalChanged = true; } break; } } void EditorViewController::RotateFromMousePosition(const int2 &mousePositionDiff) { switch (m_mode) { case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT: case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_SIDE: case EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP: { // ortho moves redirect to movement. MoveFromMousePosition(mousePositionDiff); } break; case EDITOR_CAMERA_MODE_ISOMETRIC: case EDITOR_CAMERA_MODE_PERSPECTIVE: { if (mousePositionDiff.x != 0) ModYaw((float)-mousePositionDiff.x); if (mousePositionDiff.y != 0) ModPitch((float)-mousePositionDiff.y); } break; } } void EditorViewController::Update(float dt) { uint32 i; float turboFactor = (m_turboEnabled) ? 10.0f : 1.0f; // no changes m_changed = m_internalChanged; m_internalChanged = false; // depending on mode switch (m_mode) { case EDITOR_CAMERA_MODE_PERSPECTIVE: { // read cvars const float speedGain = dt * turboFactor * m_perspectiveAcceleration; // find direction float3 moveDirection(float3::Zero); if (m_leftKeyState != m_rightKeyState) moveDirection.x = (m_leftKeyState) ? -1.0f : 1.0f; if (m_forwardKeyState != m_backKeyState) moveDirection.y = (m_backKeyState) ? -1.0f : 1.0f; if (m_upKeyState != m_downKeyState) moveDirection.z = (m_downKeyState) ? -1.0f : 1.0f; // update camera speed and direction float3 currentMoveVector(m_currentPerspectiveMoveVector); float3 targetMoveVector(moveDirection * m_perspectiveMaxSpeed); // steer to the vector for (i = 0; i < 3; i++) { if (currentMoveVector[i] > targetMoveVector[i]) currentMoveVector[i] = Max(targetMoveVector[i], currentMoveVector[i] - speedGain); else if (currentMoveVector[i] < targetMoveVector[i]) currentMoveVector[i] = Min(targetMoveVector[i], currentMoveVector[i] + speedGain); } // move camera if (currentMoveVector.SquaredLength() > Y_FLT_EPSILON) { m_viewParameters.ViewCamera.SetPosition(m_viewParameters.ViewCamera.GetPosition() + ((m_viewParameters.ViewCamera.GetRotation() * currentMoveVector) * turboFactor * dt)); m_changed = true; } // store move vector m_currentPerspectiveMoveVector = currentMoveVector; } break; } } Ray EditorViewController::GetPickRay(int32 x, int32 y) const { return m_viewParameters.ViewCamera.GetPickRay(x, y, &m_viewParameters.Viewport); } float3 EditorViewController::Project(const float3 &worldCoordindates) const { return m_viewParameters.ViewCamera.Project(worldCoordindates, &m_viewParameters.Viewport); } float3 EditorViewController::Unproject(const float3 &windowCoordinates) const { return m_viewParameters.ViewCamera.Unproject(windowCoordinates, &m_viewParameters.Viewport); } void EditorViewController::SetDrawDistance(float v) { m_viewParameters.ViewCamera.SetObjectCullDistance(v); m_viewParameters.ViewCamera.SetFarPlaneDistance(v * 1.2f); m_internalChanged = true; } void EditorViewController::SetShadowDistance(float v) { m_viewParameters.MaximumShadowViewDistance = v; m_internalChanged = true; } void EditorViewController::SetNearPlaneDistance(float v) { m_viewParameters.ViewCamera.SetNearPlaneDistance(v); m_internalChanged = true; } void EditorViewController::SetPerspectiveFieldOfView(float fov) { m_viewParameters.ViewCamera.SetPerspectiveFieldOfView(fov); m_internalChanged = true; } void EditorViewController::SetPerspectiveAcceleration(float v) { m_perspectiveAcceleration = v; } void EditorViewController::SetPerspectiveMaxSpeed(float v) { m_perspectiveMaxSpeed = v; } void EditorViewController::SetOrthographicScale(float v) { m_orthographicScale = v; UpdateViewportDependancies(); } void EditorViewController::SetViewportDimensions(uint32 width, uint32 height) { m_viewParameters.Viewport.Width = width; m_viewParameters.Viewport.Height = height; UpdateViewportDependancies(); } void EditorViewController::UpdateCameraRotation() { Quaternion newRotation(Quaternion::FromEulerAngles(m_pitch, m_roll, m_yaw)); // Quaternion newRotation; // newRotation = Quaternion::FromAxisAngle(float3::UnitZ, Math::DegreesToRadians(m_yaw)); // newRotation *= Quaternion::FromAxisAngle(float3::UnitX, Math::DegreesToRadians(m_pitch)); // newRotation *= Quaternion::FromAxisAngle(float3::UnitY, Math::DegreesToRadians(m_roll)); // Log_DevPrintf("pitch %f yaw %f roll %f", m_pitch, m_yaw, m_roll); m_viewParameters.ViewCamera.SetRotation(newRotation); m_internalChanged = true; } void EditorViewController::UpdateViewportDependancies() { // update perspective aspect float perspectiveAspect = (float)m_viewParameters.Viewport.Width / (float)m_viewParameters.Viewport.Height; m_viewParameters.ViewCamera.SetPerspectiveAspect(perspectiveAspect); // update ortho window float orthoWindowWidth = (float)m_viewParameters.Viewport.Width * m_orthographicScale; float orthoWindowHeight = (float)m_viewParameters.Viewport.Height * m_orthographicScale; m_viewParameters.ViewCamera.SetOrthographicWindow(orthoWindowWidth, orthoWindowHeight); // internal state has changed m_internalChanged = true; } void EditorViewController::SetTurboEnabled(bool enabled) { m_turboEnabled = enabled; } bool EditorViewController::HandleKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // we handle camera movement via the keyboard in the viewport, not the edit mode. bool isKeyDownEvent = (pKeyboardEvent->type() == QEvent::KeyPress); bool isKeyUpEvent = (pKeyboardEvent->type() == QEvent::KeyRelease); if ((isKeyDownEvent | isKeyUpEvent)) { // handle perspective camera movement if (!IsOrthoView()) { switch (pKeyboardEvent->key()) { case Qt::Key_W: case Qt::Key_Up: m_forwardKeyState = isKeyDownEvent; return true; case Qt::Key_S: case Qt::Key_Down: m_backKeyState = isKeyDownEvent; return true; case Qt::Key_A: case Qt::Key_Left: m_leftKeyState = isKeyDownEvent; return true; case Qt::Key_D: case Qt::Key_Right: m_rightKeyState = isKeyDownEvent; return true; case Qt::Key_Q: m_upKeyState = isKeyDownEvent; return true; case Qt::Key_E: m_downKeyState = isKeyDownEvent; return true; case Qt::Key_Shift: m_turboEnabled = isKeyDownEvent; return true; } } } return false; } <file_sep>/Engine/Source/BlockEngine/BlockEngineCVars.h #pragma once #include "Engine/Common.h" namespace CVars { // Block world cvars extern CVar r_block_world_visible_radius; extern CVar r_block_world_section_load_radius; extern CVar r_block_world_chunk_remove_delay; extern CVar r_block_world_parallel_chunk_build; extern CVar r_block_world_max_chunks_per_frame; extern CVar r_block_world_max_sections_per_frame; extern CVar r_block_world_occlusion; extern CVar r_block_world_show_lods; extern CVar r_block_world_use_lightmaps; } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUBuffer.h #pragma once #include "D3D11Renderer/D3D11Common.h" class D3D11GPUBuffer : public GPUBuffer { public: D3D11GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, ID3D11Buffer *pD3DBuffer, ID3D11Buffer *pD3DStagingBuffer); virtual ~D3D11GPUBuffer(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *debugName) override; ID3D11Buffer *GetD3DBuffer() { return m_pD3DBuffer; } ID3D11Buffer *GetD3DStagingBuffer() { return m_pD3DStagingBuffer; } D3D11GPUContext *GetMappedContext() const { return m_pMappedContext; } void *GetMappedPointer() const { return m_pMappedPointer; } void SetMappedContextPointer(D3D11GPUContext *pContext, void *pPointer) { m_pMappedContext = pContext; m_pMappedPointer = pPointer; } private: ID3D11Buffer *m_pD3DBuffer; ID3D11Buffer *m_pD3DStagingBuffer; D3D11GPUContext *m_pMappedContext; void *m_pMappedPointer; }; <file_sep>/Editor/Source/Editor/MapEditor/moc_EditorMapEditMode.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorMapEditMode.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorMapEditMode.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorMapEditMode.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorMapEditMode_t { QByteArrayData data[5]; char stringdata[65]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorMapEditMode_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorMapEditMode_t qt_meta_stringdata_EditorMapEditMode = { { QT_MOC_LITERAL(0, 0, 17), // "EditorMapEditMode" QT_MOC_LITERAL(1, 18, 18), // "OnUIShowSkyChanged" QT_MOC_LITERAL(2, 37, 0), // "" QT_MOC_LITERAL(3, 38, 7), // "checked" QT_MOC_LITERAL(4, 46, 18) // "OnUIShowSunChanged" }, "EditorMapEditMode\0OnUIShowSkyChanged\0" "\0checked\0OnUIShowSunChanged" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorMapEditMode[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x08 /* Private */, 4, 1, 27, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, 0 // eod }; void EditorMapEditMode::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorMapEditMode *_t = static_cast<EditorMapEditMode *>(_o); switch (_id) { case 0: _t->OnUIShowSkyChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->OnUIShowSunChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorMapEditMode::staticMetaObject = { { &EditorEditMode::staticMetaObject, qt_meta_stringdata_EditorMapEditMode.data, qt_meta_data_EditorMapEditMode, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorMapEditMode::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorMapEditMode::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorMapEditMode.stringdata)) return static_cast<void*>(const_cast< EditorMapEditMode*>(this)); return EditorEditMode::qt_metacast(_clname); } int EditorMapEditMode::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = EditorEditMode::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/Core/ResourceTypeInfo.h #pragma once #include "Core/ObjectTypeInfo.h" class ResourceTypeInfo : public ObjectTypeInfo { public: ResourceTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory); virtual ~ResourceTypeInfo(); }; // Macros #define DECLARE_RESOURCE_TYPE_INFO(Type, ParentType) \ private: \ static ResourceTypeInfo s_TypeInfo; \ static const PROPERTY_DECLARATION *StaticPropertyMap() { return nullptr; } \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ResourceTypeInfo *StaticTypeInfo() { return &s_TypeInfo; } \ static ResourceTypeInfo *StaticMutableTypeInfo() { return &s_TypeInfo; } #define DECLARE_RESOURCE_GENERIC_FACTORY(Type) DECLARE_OBJECT_GENERIC_FACTORY(Type) #define DECLARE_RESOURCE_NO_FACTORY(Type) DECLARE_OBJECT_NO_FACTORY(Type) #define DEFINE_RESOURCE_TYPE_INFO(Type) \ ResourceTypeInfo Type::s_TypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::StaticPropertyMap(), Type::StaticFactory()) #define DEFINE_RESOURCE_GENERIC_FACTORY(Type) DEFINE_OBJECT_GENERIC_FACTORY(Type) #define BEGIN_RESOURCE_PROPERTIES(Type) \ const PROPERTY_DECLARATION Type::s_propertyDeclarations[] = { #define END_RESOURCE_PROPERTIES() \ PROPERTY_TABLE_MEMBER(NULL, PROPERTY_TYPE_COUNT, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL) \ }; <file_sep>/Engine/Source/Core/Resource.h #pragma once #include "Core/ResourceTypeInfo.h" #include "Core/Object.h" class Resource : public Object { DECLARE_RESOURCE_TYPE_INFO(Resource, Object); DECLARE_RESOURCE_NO_FACTORY(Resource); public: Resource(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); virtual ~Resource(); // Override type info accessors. const ResourceTypeInfo *GetResourceTypeInfo() const { return static_cast<const ResourceTypeInfo *>(m_pObjectTypeInfo); } // Resource name accessor. const String &GetName() const { return m_strName; } // Helper function to sanitize a resource name. static void SanitizeResourceName(String &resourceName, bool stripSlashes = true); protected: // Resource name. String m_strName; }; <file_sep>/Engine/Source/Core/ObjectSerializer.h #pragma once #include "Core/Common.h" #include "Core/Property.h" #include "YBaseLib/ByteStream.h" class ObjectSerializer { public: static bool SerializePropertyValueString(PROPERTY_TYPE propertyType, const char *propertyValueString, ByteStream *pOutputStream, uint32 *pWrittenBytes); };<file_sep>/Engine/Source/GameFramework/StaticMeshBrush.h #pragma once #include "Engine/Brush.h" class StaticMesh; namespace Physics { class StaticObject; } class StaticMeshRenderProxy; class StaticMeshBrush : public Brush { DECLARE_OBJECT_TYPE_INFO(StaticMeshBrush, Brush); DECLARE_OBJECT_PROPERTY_MAP(StaticMeshBrush); DECLARE_OBJECT_GENERIC_FACTORY(StaticMeshBrush); public: StaticMeshBrush(const ObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~StaticMeshBrush(); // External creation method bool Create(const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const StaticMesh *pStaticMesh = nullptr, bool visible = true, bool collidable = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // Virtual creation method virtual bool Initialize() override; // Events virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; // property accessors const StaticMesh *GetStaticMesh() const { return m_pStaticMesh; } const bool IsVisible() const { return m_visible; } const uint32 GetShadowFlags() const { return m_shadowFlags; } const bool IsCollidable() const { return m_collidable; } private: // property callbacks static bool PropertyCallbackGetStaticMeshName(ThisClass *pEntity, const void *pUserData, String *pValue); static bool PropertyCallbackSetStaticMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue); // vars const StaticMesh *m_pStaticMesh; bool m_visible; uint32 m_shadowFlags; bool m_collidable; // render proxy StaticMeshRenderProxy *m_pRenderProxy; // physics proxy Physics::StaticObject *m_pCollisionObject; }; <file_sep>/Engine/Source/Renderer/VertexFactories/BlockMeshVertexFactory.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(BlockMeshVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(BlockMeshVertexFactory) END_SHADER_COMPONENT_PARAMETERS() uint32 BlockMeshVertexFactory::GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { // calculate vertices buffer size // base vertex size - position + tangent + binormal + normal + color uint32 vertexSize = sizeof(float3); // add texcoords if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD) { if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY) vertexSize += sizeof(float3); else vertexSize += sizeof(float2); // add atlas texcoords if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS) vertexSize += sizeof(float4); } // add tangents if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) vertexSize += sizeof(float3) * 3; // add colour if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) vertexSize += sizeof(uint32); // add face index if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX) vertexSize += sizeof(byte) * 4; // set it return vertexSize; } void BlockMeshVertexFactory::FillVertices(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const BlockMeshBuilder::Vertex *pVertices, uint32 nVertices, void *pOutputVertices, uint32 cbOutputVertices) { DebugAssert((GetVertexSize(platform, featureLevel, flags) * nVertices) <= cbOutputVertices); // fill buffer { uint32 i; const BlockMeshBuilder::Vertex *pVertex = pVertices; byte *pOutVertexPtr = reinterpret_cast<byte *>(pOutputVertices); for (i = 0; i < nVertices; i++, pVertex++) { // position Y_memcpy(pOutVertexPtr, &pVertex->Position, sizeof(float3)); pOutVertexPtr += sizeof(float3); if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD) { // texcoord if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY) { Y_memcpy(pOutVertexPtr, &pVertex->TexCoord, sizeof(float3)); pOutVertexPtr += sizeof(float3); } else { Y_memcpy(pOutVertexPtr, &pVertex->TexCoord, sizeof(float2)); pOutVertexPtr += sizeof(float2); } // atlas texcoord if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS) { Y_memcpy(pOutVertexPtr, &pVertex->AtlasTexCoord, sizeof(float4)); pOutVertexPtr += sizeof(float4); } } if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) { // todo: hardcoded tangent vectors pOutVertexPtr += sizeof(float3); pOutVertexPtr += sizeof(float3); pOutVertexPtr += sizeof(float3); } if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { // color *(uint32 *)pOutVertexPtr = pVertex->Color; pOutVertexPtr += sizeof(uint32); } if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX) { // data *(uint32 *)pOutVertexPtr = (uint32)pVertex->FaceIndex | (uint32)pVertex->FaceIndex << 8 | (uint32)pVertex->FaceIndex << 16 | (uint32)pVertex->FaceIndex << 24; pOutVertexPtr += sizeof(uint32); } } } } bool BlockMeshVertexFactory::CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const BlockMeshBuilder::Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); uint32 bufferSize = vertexSize * nVertices; byte *pBuffer = new byte[bufferSize]; FillVertices(platform, featureLevel, flags, pVertices, nVertices, pBuffer, bufferSize); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, bufferSize); GPUBuffer *pVertexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pBuffer); delete[] pBuffer; if (pVertexBuffer == NULL) return false; pVertexBufferBindingArray->SetBuffer(0, pVertexBuffer, 0, vertexSize); pVertexBuffer->Release(); return true; } bool BlockMeshVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool BlockMeshVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/BlockMeshVertexFactory.hlsl"); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD) { pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD", "1"); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY) pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY", "1"); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS) pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS", "1"); } if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS", "1"); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS", "1"); if (vertexFactoryFlags & BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX) pParameters->AddPreprocessorMacro("BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX", "1"); return true; } uint32 BlockMeshVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { // create format declaration GPU_VERTEX_ELEMENT_DESC *pElementDesc = pElementsDesc; uint32 streamOffset; uint32 nElements = 0; uint32 nStreams = 0; // build stream 0 { streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD) { // texcoord if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; } else { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; } // atlas texcoord if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 1; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float4); pElementDesc++; nElements++; } } if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; } // color if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } // data if (flags & BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BLENDINDICES; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UBYTE4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(byte) * 4; pElementDesc++; nElements++; } // end of stream nStreams++; } // done return nElements; } uint32 BlockMeshVertexFactory::GetVertexFlagsForCurrentRenderer() { uint32 outFlags = BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD | BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS; if (g_pRenderer->GetCapabilities().SupportsTextureArrays) { outFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY; } else { outFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS; } outFlags |= BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX; return outFlags; } <file_sep>/Engine/Source/Renderer/WorldRenderer.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" #include "Renderer/RenderQueue.h" #include "Renderer/Renderer.h" #include "Engine/Camera.h" class Material; class MaterialShader; class RenderWorld; class ShaderProgram; class MiniGUIContext; struct RENDER_QUEUE_RENDERABLE_ENTRY; class ShaderComponentTypeInfo; class VertexFactoryTypeInfo; class WorldRenderer { DeclareNonCopyable(WorldRenderer); public: struct Options { Options(); Options(const Options &options); void InitFromCVars(); void SetRenderResolution(uint32 width, uint32 height); void DisableUnsupportedFeatures(); uint32 EnableDepthPrepass : 1; uint32 EnableShadows : 1; uint32 EnablePointLightShadows : 1; uint32 EnableHardwareShadowFiltering : 1; uint32 EnableOcclusionCulling : 1; uint32 EnableOcclusionPredication : 1; uint32 WaitForOcclusionResults : 1; uint32 EnablePostProcessing : 1; uint32 EnableSSAO : 1; uint32 EnableBloom : 1; uint32 ShowDebugInfo : 1; uint32 ShowShadowMapCascades : 1; uint32 ShowIntermediateBuffers : 1; uint32 ShowWireframeOverlay : 1; uint32 RenderModeFullbright : 1; uint32 RenderModeNormals : 1; uint32 RenderModeLightingOnly : 1; uint32 EmulateMobile : 1; uint32 EnableMultithreadedRendering : 1; uint32 RenderWidth; uint32 RenderHeight; uint32 OcclusionCullingObjectsPerBatch; PIXEL_FORMAT ShadowMapPixelFormat; uint32 DirectionalShadowMapResolution; uint32 PointShadowMapResolution; uint32 SpotShadowMapResolution; RENDERER_SHADOW_FILTER ShadowMapFiltering; uint32 ShadowMapCascadeCount; }; struct ViewParameters { ViewParameters(); ViewParameters(const ViewParameters &parameters); void SetCamera(const Camera *pCamera); // to save indirection we copy the camera to here Camera ViewCamera; float MaximumShadowViewDistance; RENDERER_VIEWPORT Viewport; float WorldTime; RENDERER_FOG_MODE FogMode; float FogStartDistance; float FogEndDistance; float FogDensity; float3 FogColor; bool EnableManualExposure; float ManualExposure; float MaximumExposure; bool EnableBloom; float BloomThreshold; float BloomMagnitude; }; struct RenderStats { uint32 ObjectCount; uint32 LightCount; uint32 ShadowMapCount; uint32 ObjectsCulledByOcclusion; uint32 IntermediateBufferCount; uint32 IntermediateBufferMemoryUsage; }; public: WorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~WorldRenderer(); // options const Options *GetOptions() const { return &m_options; } // context GPUContext *GetGPUContext() const { return m_pGPUContext; } void SetGPUContext(GPUContext *pGPUContext) { m_pGPUContext = pGPUContext; } // gui context MiniGUIContext *GetGUIContext() const { return m_pGUIContext; } void SetGUIContext(MiniGUIContext *pGUIContext) { m_pGUIContext = pGUIContext; } // create renderer resources virtual bool Initialize(); // Draws the world. virtual void DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView); // Get render stats. virtual void GetRenderStats(RenderStats *pRenderStats) const; // On completion of frame. virtual void OnFrameComplete(); // create a world renderer based on cvar state static WorldRenderer *Create(GPUContext *pGPUContext, const Options *pCreationParameters); protected: // intermediate buffer struct IntermediateBuffer { GPUTexture2D *pTexture; GPURenderTargetView *pRTV; GPUDepthStencilBufferView *pDSV; uint32 Width; uint32 Height; PIXEL_FORMAT PixelFormat; uint32 MipLevels; }; // occlusion culling. the render proxy is used as a key, never dereferenced. struct PendingOcclusionCullingQuery { const RenderProxy *pRenderProxy; bool MatchUserData; uint32 UserData[4]; void *UserDataPointer[2]; GPUQuery *pQuery; bool Visible; }; // named intermediate buffers - used for debug drawing struct DebugBufferView { GPUTexture *pTexture; IntermediateBuffer *pBuffer; const char *Name; }; // helper functions static ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pAttributes, uint32 nAttributes); static ShaderProgram *GetShaderProgram(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialStaticSwitchMask); static ShaderProgram *GetShaderProgram(const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); static ShaderProgram *GetShaderProgram(const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags); static void SetBlendingModeForMaterial(GPUCommandList *pCommandList, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); static void SetAdditiveBlendingModeForMaterial(GPUCommandList *pCommandList, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); // queue filling + sorting void FillRenderQueue(const Camera *pCamera, const RenderWorld *pRenderWorld); // debug drawing void DrawDebugInfo(const Camera *pCamera); // wireframe overlay drawing void DrawWireframeOverlay(GPUCommandList *pCommandList, const Camera *pCamera, const RenderQueue::RenderableArray *pRenderables); // upscale/downsample one texture to another, using hardware bilinear filtering void ScaleTexture(GPUCommandList *pCommandList, GPUTexture2D *pSourceTexture, GPURenderTargetView *pDestinationRTV, bool restoreViewport = true, bool restoreTargets = true); // intermediate buffer requests/releases IntermediateBuffer *RequestIntermediateBuffer(uint32 width, uint32 height, PIXEL_FORMAT pixelFormat, uint32 mipLevels); IntermediateBuffer *RequestIntermediateBufferMatching(const IntermediateBuffer *pIntermediateBuffer); void ReleaseIntermediateBuffer(IntermediateBuffer *pIntermediateBuffer); // occlusion culling, draw method assumes depth buffer is bound void DrawOcclusionCullingProxies(GPUCommandList *pCommandList, const Camera *pCamera); void CollectOcclusionCullingResults(); void BindOcclusionQueriesToQueueEntries(); // queue a buffer for showing in debug mode void AddDebugBufferView(GPUTexture *pTexture, const char *name); void AddDebugBufferView(IntermediateBuffer *pBuffer, const char *name, bool autoRelease); // draw intermediate buffers void DrawIntermediateBuffers(); // common parameters GPUContext *m_pGPUContext; MiniGUIContext *m_pGUIContext; Options m_options; uint32 m_globalShaderFlags; // render queue RenderQueue m_renderQueue; // intermediate buffer variables PODArray<IntermediateBuffer *> m_allIntermediateBuffers; PODArray<IntermediateBuffer *> m_freeIntermediateBuffers; MemArray<DebugBufferView> m_debugBufferViews; // occlusion culling variables PODArray<GPUQuery *> m_occlusionCullingQueryCacheArray; MemArray<PendingOcclusionCullingQuery> m_occlusionCullingPendingQueries; GPUBuffer *m_pOcclusionCullingCubeVertexBuffer; GPUBuffer *m_pOcclusionCullingCubeIndexBuffer; ShaderProgram *m_pOcclusionCullingProgram; // multithreaded rendering HANDLE m_hQueueingCommandsSemaphore; PODArray<GPUCommandList *> m_readyPrimaryCommandLists; PODArray<GPUCommandList *> m_readySecondaryCommandLists; uint32 m_commandListsPending; Mutex m_commandListLock; // begin multithreaded rendering template<class T> void QueuePrimaryRenderPass(T callback) { // find a command queue GPUCommandList *pCommandList = (m_options.EnableMultithreadedRendering) ? g_pRenderer->AllocateCommandList() : nullptr; if (pCommandList == nullptr) { callback(m_pGPUContext); return; } // open command list if (!m_pGPUContext->OpenCommandList(pCommandList)) { callback(m_pGPUContext); return; } // queue it m_commandListLock.Lock(); m_commandListsPending++; m_commandListLock.Unlock(); QUEUE_RENDERER_WORKER_LAMBDA_COMMAND([this, pCommandList, callback]() { callback(pCommandList); bool closeResult = m_pGPUContext->CloseCommandList(pCommandList); m_commandListLock.Lock(); m_commandListsPending--; if (closeResult) m_readyPrimaryCommandLists.Add(pCommandList); else g_pRenderer->ReleaseCommandList(pCommandList); m_commandListLock.Unlock(); ReleaseSemaphore(m_hQueueingCommandsSemaphore, 1, nullptr); }); } template<class T> void QueueSecondaryRenderPass(T callback) { // find a command queue GPUCommandList *pCommandList = (m_options.EnableMultithreadedRendering) ? g_pRenderer->AllocateCommandList() : nullptr; if (pCommandList == nullptr) { callback(m_pGPUContext); return; } // open command list if (!m_pGPUContext->OpenCommandList(pCommandList)) { callback(m_pGPUContext); return; } // queue it m_commandListLock.Lock(); m_commandListsPending++; m_commandListLock.Unlock(); QUEUE_RENDERER_WORKER_LAMBDA_COMMAND([this, pCommandList, callback]() { callback(pCommandList); bool closeResult = m_pGPUContext->CloseCommandList(pCommandList); m_commandListLock.Lock(); m_commandListsPending--; if (closeResult) m_readySecondaryCommandLists.Add(pCommandList); else g_pRenderer->ReleaseCommandList(pCommandList); m_commandListLock.Unlock(); ReleaseSemaphore(m_hQueueingCommandsSemaphore, 1, nullptr); }); } void ExecuteRenderPasses(); }; <file_sep>/Engine/Source/Core/DefinitionFile.cpp #include "Core/PrecompiledHeader.h" #include "Core/DefinitionFile.h" #include "YBaseLib/Assert.h" #include "YBaseLib/CString.h" #include "YBaseLib/Log.h" Log_SetChannel(DefinitionFile); DefinitionFileParser::DefinitionFileParser(ByteStream *pStream, const char *FileName) : m_Reader(pStream), m_szFileName(FileName) { m_uCharacter = 0; m_uLine = 0; m_bAtEOF = false; } DefinitionFileParser::~DefinitionFileParser() { } bool DefinitionFileParser::NextLine() { for (;;) { m_uCharacter = 0; m_uLine++; if (!m_Reader.ReadLine(&m_szLine)) { m_bAtEOF = true; return false; } // remove whitespace characters m_szLine.Strip(" \t\r\n"); // check length if (m_szLine.GetLength() == 0) continue; // skip comment lines if (m_szLine[0] == '#') continue; // line is good return true; } } bool DefinitionFileParser::NextToken(bool AllowEOF /* = false */, const char *TokenSeperatorCharacters /* = " " */) { uint32 i; if (m_bAtEOF) { if (!AllowEOF) PrintError("reached EOF while searching for token"); return false; } if (m_uCharacter == m_szLine.GetLength()) { // read another line if (!NextLine()) { if (!AllowEOF) PrintError("reached EOF while searching for token"); return false; } } uint32 nTokenSeperatorCharacters = Y_strlen(TokenSeperatorCharacters); DebugAssert(nTokenSeperatorCharacters > 0); // skip till the start of the token while (m_uCharacter < m_szLine.GetLength()) { for (i = 0; i < nTokenSeperatorCharacters; i++) { if (m_szLine[m_uCharacter] == TokenSeperatorCharacters[i]) break; } if (i == nTokenSeperatorCharacters) break; else m_uCharacter++; } // no token? if (m_uCharacter == m_szLine.GetLength()) return NextToken(AllowEOF); // append characters char QuotedStringCharacter = 0; m_szToken.Clear(); while (m_uCharacter < m_szLine.GetLength()) { char chCharacter = m_szLine[m_uCharacter]; if (chCharacter == QuotedStringCharacter) { QuotedStringCharacter = 0; m_uCharacter++; continue; } else if (chCharacter == '\"' || chCharacter == '\'') { QuotedStringCharacter = chCharacter; m_uCharacter++; continue; } else { if (QuotedStringCharacter == 0) { for (i = 0; i < nTokenSeperatorCharacters; i++) { if (chCharacter == TokenSeperatorCharacters[i]) { // token complete return true; } } } m_szToken.AppendCharacter(chCharacter); m_uCharacter++; } } if (QuotedStringCharacter != 0) { PrintError("reached EOF while reading quoted string"); return false; } // should be at least one //DebugAssert(m_szToken.GetLength() > 0); return true; } int32 DefinitionFileParser::InternalSelect(const char *SelectTokens) { uint32 len = Y_strlen(SelectTokens); uint32 i = 0; uint32 start = 0; uint32 TokenIndex = 0; for (; i < len; i++) { if (SelectTokens[i] == '|') { if ((i - start) == m_szToken.GetLength() && Y_strnicmp(SelectTokens + start, m_szToken.GetCharArray(), i - start) == 0) return TokenIndex; start = i + 1; TokenIndex++; } } if (start < len) { if ((len - start) == m_szToken.GetLength() &&Y_strnicmp(SelectTokens + start, m_szToken.GetCharArray(), len - start) == 0) return TokenIndex; } return -1; } bool DefinitionFileParser::Expect(const char *ExpectTokens) { if (InternalSelect(ExpectTokens) < 0) { PrintError("got '%s', expecting '%s'", m_szToken.GetCharArray(), ExpectTokens); return false; } return true; } bool DefinitionFileParser::ExpectNot(const char *NotExpectTokens) { if (InternalSelect(NotExpectTokens) >= 0) { PrintError("unexpected '%s', expecting anything but '%s'", m_szToken.GetCharArray(), NotExpectTokens); return false; } return true; } int32 DefinitionFileParser::Select(const char *SelectTokens) { int32 ReturnValue = InternalSelect(SelectTokens); if (ReturnValue < 0) { PrintError("got '%s', expecting '%s'", m_szToken.GetCharArray(), SelectTokens); return -1; } return ReturnValue; } void DefinitionFileParser::PrintError(const char *Format, ...) { va_list ap; va_start(ap, Format); char buf[256]; Y_vsnprintf(buf, countof(buf), Format, ap); va_end(ap); Log_ErrorPrintf("%s:%u:%u: %s", m_szFileName.GetCharArray(), m_uLine + 1, m_uCharacter + 1, buf); } void DefinitionFileParser::PrintWarning(const char *Format, ...) { va_list ap; va_start(ap, Format); char buf[256]; Y_vsnprintf(buf, countof(buf), Format, ap); va_end(ap); Log_WarningPrintf("%s:%u:%u: %s", m_szFileName.GetCharArray(), m_uLine + 1, m_uCharacter + 1, buf); } <file_sep>/Engine/Source/Core/PrecompiledHeader.h #pragma once #include "Core/Common.h" <file_sep>/Engine/Source/BaseGame/GameState.h #pragma once #include "BaseGame/Common.h" class GameState { public: virtual ~GameState() {} //================================================================================================================================================================================================= // Events //================================================================================================================================================================================================= virtual void OnSwitchedIn() = 0; virtual void OnSwitchedOut() = 0; virtual void OnBeforeDelete() = 0; virtual void OnWindowResized(uint32 width, uint32 height) = 0; virtual void OnWindowFocusGained() = 0; virtual void OnWindowFocusLost() = 0; virtual bool OnWindowEvent(const union SDL_Event *event) = 0; virtual void OnMainThreadPreFrame(float deltaTime) = 0; virtual void OnMainThreadBeginFrame(float deltaTime) = 0; virtual void OnMainThreadAsyncTick(float deltaTime) = 0; virtual void OnMainThreadTick(float deltaTime) = 0; virtual void OnMainThreadEndFrame(float deltaTime) = 0; virtual void OnRenderThreadPreFrame(float deltaTime) = 0; virtual void OnRenderThreadBeginFrame(float deltaTime) = 0; virtual void OnRenderThreadDraw(float deltaTime) = 0; virtual void OnRenderThreadEndFrame(float deltaTime) = 0; }; <file_sep>/Editor/Source/Editor/moc_EditorResourceSelectionDialog.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorResourceSelectionDialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorResourceSelectionDialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorResourceSelectionDialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorResourceSelectionDialog_t { QByteArrayData data[12]; char stringdata[237]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorResourceSelectionDialog_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorResourceSelectionDialog_t qt_meta_stringdata_EditorResourceSelectionDialog = { { QT_MOC_LITERAL(0, 0, 29), // "EditorResourceSelectionDialog" QT_MOC_LITERAL(1, 30, 28), // "OnDirectoryComboBoxActivated" QT_MOC_LITERAL(2, 59, 0), // "" QT_MOC_LITERAL(3, 60, 4), // "text" QT_MOC_LITERAL(4, 65, 19), // "OnBackButtonPressed" QT_MOC_LITERAL(5, 85, 26), // "OnUpDirectoryButtonPressed" QT_MOC_LITERAL(6, 112, 28), // "OnMakeDirectoryButtonPressed" QT_MOC_LITERAL(7, 141, 23), // "OnTreeViewItemActivated" QT_MOC_LITERAL(8, 165, 5), // "index" QT_MOC_LITERAL(9, 171, 21), // "OnTreeViewItemClicked" QT_MOC_LITERAL(10, 193, 21), // "OnSelectButtonClicked" QT_MOC_LITERAL(11, 215, 21) // "OnCancelButtonClicked" }, "EditorResourceSelectionDialog\0" "OnDirectoryComboBoxActivated\0\0text\0" "OnBackButtonPressed\0OnUpDirectoryButtonPressed\0" "OnMakeDirectoryButtonPressed\0" "OnTreeViewItemActivated\0index\0" "OnTreeViewItemClicked\0OnSelectButtonClicked\0" "OnCancelButtonClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorResourceSelectionDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 8, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 54, 2, 0x08 /* Private */, 4, 0, 57, 2, 0x08 /* Private */, 5, 0, 58, 2, 0x08 /* Private */, 6, 0, 59, 2, 0x08 /* Private */, 7, 1, 60, 2, 0x08 /* Private */, 9, 1, 63, 2, 0x08 /* Private */, 10, 0, 66, 2, 0x08 /* Private */, 11, 0, 67, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QString, 3, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QModelIndex, 8, QMetaType::Void, QMetaType::QModelIndex, 8, QMetaType::Void, QMetaType::Void, 0 // eod }; void EditorResourceSelectionDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorResourceSelectionDialog *_t = static_cast<EditorResourceSelectionDialog *>(_o); switch (_id) { case 0: _t->OnDirectoryComboBoxActivated((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->OnBackButtonPressed(); break; case 2: _t->OnUpDirectoryButtonPressed(); break; case 3: _t->OnMakeDirectoryButtonPressed(); break; case 4: _t->OnTreeViewItemActivated((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 5: _t->OnTreeViewItemClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 6: _t->OnSelectButtonClicked(); break; case 7: _t->OnCancelButtonClicked(); break; default: ; } } } const QMetaObject EditorResourceSelectionDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_EditorResourceSelectionDialog.data, qt_meta_data_EditorResourceSelectionDialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorResourceSelectionDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorResourceSelectionDialog::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorResourceSelectionDialog.stringdata)) return static_cast<void*>(const_cast< EditorResourceSelectionDialog*>(this)); return QDialog::qt_metacast(_clname); } int EditorResourceSelectionDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 8) qt_static_metacall(this, _c, _id, _a); _id -= 8; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 8) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 8; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ContentConverter/AssimpSkeletalMeshImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpSkeletalMeshImporter.h" #include "ContentConverter/AssimpMaterialImporter.h" #include "ContentConverter/AssimpCommon.h" #include "ResourceCompiler/SkeletalMeshGenerator.h" AssimpSkeletalMeshImporter::AssimpSkeletalMeshImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(NULL), m_pLogStream(NULL), m_pScene(NULL), m_pOutputGenerator(NULL) { } AssimpSkeletalMeshImporter::~AssimpSkeletalMeshImporter() { delete m_pOutputGenerator; delete m_pLogStream; delete m_pImporter; } void AssimpSkeletalMeshImporter::SetDefaultOptions(Options *pOptions) { pOptions->ImportMaterials = false; pOptions->DefaultMaterialName = "materials/engine/default"; pOptions->CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; pOptions->FlipFaceOrder = false; pOptions->CollisionShapeType = "Box"; } bool AssimpSkeletalMeshImporter::Execute() { Timer timer; if (m_pOptions->SourcePath.IsEmpty() || m_pOptions->SkeletonName.IsEmpty() || m_pOptions->OutputResourceName.IsEmpty() || m_pOptions->DefaultMaterialName.IsEmpty() || (m_pOptions->ImportMaterials && m_pOptions->MaterialDirectory.IsEmpty())) { m_pProgressCallbacks->ModalError("Missing parameters"); return false; } // ensure assimp is initialized if (!AssimpHelpers::InitializeAssimp()) { m_pProgressCallbacks->ModalError("assimp initialization failed"); return false; } // determine base output path { int32 lastSlashPosition = m_pOptions->OutputResourceName.RFind('/'); if (lastSlashPosition >= 0) m_baseOutputPath = m_pOptions->OutputResourceName.SubString(0, lastSlashPosition); } timer.Reset(); if (!LoadScene()) { m_pProgressCallbacks->ModalError("LoadScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("LoadScene(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateGenerator()) { m_pProgressCallbacks->ModalError("CreateGenerator() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateGenerator(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateMaterials()) { m_pProgressCallbacks->ModalError("CreateMaterials() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateMaterials(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateMesh()) { m_pProgressCallbacks->ModalError("CreateMesh() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateMesh(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!PostProcess()) { m_pProgressCallbacks->ModalError("PostProcess() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("PostProcess(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateCollisionShape()) { m_pProgressCallbacks->ModalError("CreateCollisionShape() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateCollisionShape(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!WriteOutput()) { m_pProgressCallbacks->ModalError("WriteOutput() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("WriteOutput(): %.4f ms", timer.GetTimeMilliseconds()); return true; } bool AssimpSkeletalMeshImporter::LoadScene() { // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // get post process flags uint32 postProcessFlags = AssimpHelpers::GetAssimpSkeletalMeshImportPostProcessingFlags(); // get coordinate system transform bool reverseWinding; float4x4::MakeCoordinateSystemConversionMatrix(m_pOptions->CoordinateSystem, COORDINATE_SYSTEM_Z_UP_RH, &reverseWinding); if (m_pOptions->FlipFaceOrder) reverseWinding = !reverseWinding; if (reverseWinding) postProcessFlags |= aiProcess_FlipWindingOrder; // // create global transform // m_globalTransform = m_pOptions->TransformMatrix * coordinateSystemTransform; // m_inverseGlobalTransform = m_globalTransform.Inverse(); // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(postProcessFlags); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // flip normals if flipping faces, assimp doesn't do this /*if (reverseWinding) { m_pProgressCallbacks->DisplayDebugMessage("Flipping normals..."); for (uint32 meshIndex = 0; meshIndex < m_pScene->mNumMeshes; meshIndex++) { aiMesh *pMesh = m_pScene->mMeshes[meshIndex]; for (uint32 vertexIndex = 0; vertexIndex < pMesh->mNumVertices; vertexIndex++) { if (pMesh->HasTangentsAndBitangents()) { if (pMesh->mTangents[vertexIndex].SquareLength() > 0.0f) pMesh->mTangents[vertexIndex] = -pMesh->mTangents[vertexIndex]; if (pMesh->mBitangents[vertexIndex].SquareLength() > 0.0f) pMesh->mBitangents[vertexIndex] = -pMesh->mBitangents[vertexIndex]; if (pMesh->mNormals[vertexIndex].SquareLength() > 0.0f) pMesh->mNormals[vertexIndex] = -pMesh->mNormals[vertexIndex]; } else if (pMesh->HasNormals()) { if (pMesh->mNormals[vertexIndex].SquareLength() > 0.0f) pMesh->mNormals[vertexIndex] = -pMesh->mNormals[vertexIndex]; } } } }*/ // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } bool AssimpSkeletalMeshImporter::CreateGenerator() { // create generator m_pOutputGenerator = new SkeletalMeshGenerator(); m_pOutputGenerator->SetSkeletonName(m_pOptions->SkeletonName); return true; } bool AssimpSkeletalMeshImporter::CreateMaterials() { if (!m_pOptions->ImportMaterials) { for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { m_materialMapping.Add(m_pOutputGenerator->AddMaterialName(m_pOptions->DefaultMaterialName)); } return true; } for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { const aiMaterial *pAIMaterial = m_pScene->mMaterials[i]; aiString aiMaterialName; if (!aiGetMaterialString(pAIMaterial, AI_MATKEY_NAME, &aiMaterialName) || aiMaterialName.length == 0) aiMaterialName.Set(String::FromFormat("material%u", i)); SmallString sanitizedMaterialName; FileSystem::SanitizeFileName(sanitizedMaterialName, aiMaterialName.C_Str()); PathString materialResourceName; PathString fileName; materialResourceName.Format("%s/%s%s", m_pOptions->MaterialDirectory.GetCharArray(), m_pOptions->MaterialPrefix.GetCharArray(), sanitizedMaterialName.GetCharArray()); m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' -> '%s'", aiMaterialName.C_Str(), materialResourceName.GetCharArray()); // does this material exist? fileName.Format("%s.mtl.xml", materialResourceName.GetCharArray()); if (g_pVirtualFileSystem->FileExists(fileName)) { m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' already exists, skipping import...", materialResourceName.GetCharArray()); m_materialMapping.Add(m_pOutputGenerator->AddMaterialName(materialResourceName)); continue; } // import the material if (!AssimpMaterialImporter::ImportMaterial(pAIMaterial, m_pOptions->SourcePath, m_pOptions->MaterialDirectory, m_pOptions->MaterialPrefix, materialResourceName, m_pProgressCallbacks)) { m_pProgressCallbacks->DisplayFormattedWarning("Material '%s' failed import, using default material.", materialResourceName.GetCharArray()); m_materialMapping.Add(m_pOutputGenerator->AddMaterialName(m_pOptions->DefaultMaterialName)); continue; } // add it m_materialMapping.Add(m_pOutputGenerator->AddMaterialName(materialResourceName)); } return true; } bool AssimpSkeletalMeshImporter::CreateMesh() { // todo: global transform const aiNode *pRootNode = m_pScene->mRootNode; // parse root node if (!ParseNode(pRootNode)) return false; // ok return true; } bool AssimpSkeletalMeshImporter::ParseNode(const aiNode *pNode) { // parse node children for (uint32 childIndex = 0; childIndex < pNode->mNumChildren; childIndex++) { if (!ParseNode(pNode->mChildren[childIndex])) return false; } // CS transform //const aiMatrix4x4 CSTransformMatrix(AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4()); // for each mesh... uint64 smoothingGroupMask = (1 << 0); for (uint32 meshIndex = 0; meshIndex < pNode->mNumMeshes; meshIndex++) { const aiMesh *pMesh = m_pScene->mMeshes[pNode->mMeshes[meshIndex]]; DebugAssert(pMesh != NULL); // get mesh name SmallString meshName; if (pMesh->mName.length == 0) meshName.Format("__submesh-%u__", meshIndex); else meshName = pMesh->mName.C_Str(); // create output mesh, using max nweights for now DebugAssert(pMesh->mMaterialIndex < m_materialMapping.GetSize()); m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] using material %s", meshName.GetCharArray(), m_pOutputGenerator->GetMaterialNameByIndex(m_materialMapping[pMesh->mMaterialIndex]).GetCharArray()); // fixup flags if (pMesh->GetNumUVChannels() > 0) m_pOutputGenerator->SetProvideVertexTextureCoordinates(true); if (pMesh->GetNumColorChannels() > 0) m_pOutputGenerator->SetProvideVertexColors(true); // for this mesh MemArray<SkeletalMeshGenerator::Vertex> meshVertices; // create vertices without any weights in them for (uint32 vertexIndex = 0; vertexIndex < pMesh->mNumVertices; vertexIndex++) { SkeletalMeshGenerator::Vertex vertex; //vertex.Position = (AssimpHelpers::AssimpVector3ToFloat3(CSTransformMatrix * pMesh->mVertices[vertexIndex])); //vertex.Position = m_globalTransform.TransformPoint(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mVertices[vertexIndex])); vertex.Position = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mVertices[vertexIndex])); vertex.TextureCoordinates = ((pMesh->GetNumUVChannels() > 0) ? AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTextureCoords[0][vertexIndex]).xy() : float2::Zero); vertex.Color = ((pMesh->GetNumColorChannels() > 0) ? AssimpHelpers::AssimpColor4ToColor(pMesh->mColors[0][vertexIndex]) : MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); if (pMesh->HasTangentsAndBitangents()) { //vertex.Tangent = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTangents[vertexIndex])); //vertex.Binormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mBitangents[vertexIndex])); //vertex.Normal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); vertex.Tangent = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTangents[vertexIndex])); vertex.Binormal = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mBitangents[vertexIndex])); vertex.Normal = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else if (pMesh->HasNormals()) { vertex.Tangent = float3::UnitX; vertex.Binormal = float3::UnitY; //vertex.Normal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); vertex.Normal = (AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else { vertex.Tangent = float3::UnitX; vertex.Binormal = float3::UnitY; vertex.Normal = float3::UnitZ; } // no weights for now for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) { vertex.BoneIndices[weightIndex] = -1; vertex.BoneWeights[weightIndex] = 0.0f; } meshVertices.Add(vertex); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u vertices", meshName.GetCharArray(), pMesh->mNumVertices); // read bones uint32 maxBonesPerVertex = 0; m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] references %u bones", meshName.GetCharArray(), pMesh->mNumBones); for (uint32 boneIndex = 0; boneIndex < pMesh->mNumBones; boneIndex++) { const aiBone *pBone = pMesh->mBones[boneIndex]; DebugAssert(pBone != NULL); int32 outputBoneIndex = m_pOutputGenerator->FindBoneIndexByName(pBone->mName.C_Str()); if (outputBoneIndex < 0) { aiVector3D scaling; aiQuaternion rotation; aiVector3D translation; //aiMatrix4x4 correctedMatrix(AssimpHelpers::Float4x4ToAssimpMatrix4x4(m_inverseGlobalTransform) * pBone->mOffsetMatrix * AssimpHelpers::Float4x4ToAssimpMatrix4x4(m_globalTransform)); //correctedMatrix.Decompose(scaling, rotation, translation); pBone->mOffsetMatrix.Decompose(scaling, rotation, translation); SkeletalMeshGenerator::Bone *pGeneratorBone = m_pOutputGenerator->AddBone(pBone->mName.C_Str(), Transform(AssimpHelpers::AssimpVector3ToFloat3(translation), AssimpHelpers::AssimpQuaternionToQuaternion(rotation).Normalize(), AssimpHelpers::AssimpVector3ToFloat3(scaling))); outputBoneIndex = (int32)pGeneratorBone->Index; } else { aiVector3D scaling; aiQuaternion rotation; aiVector3D translation; pBone->mOffsetMatrix.Decompose(scaling, rotation, translation); // should be equal const SkeletalMeshGenerator::Bone *pGeneratorBone = m_pOutputGenerator->GetBoneByIndex(outputBoneIndex); DebugAssert(AssimpHelpers::AssimpVector3ToFloat3(translation) == pGeneratorBone->LocalToBoneTransform.GetPosition()); DebugAssert(AssimpHelpers::AssimpQuaternionToQuaternion(rotation).Normalize() == pGeneratorBone->LocalToBoneTransform.GetRotation()); DebugAssert(AssimpHelpers::AssimpVector3ToFloat3(scaling) == pGeneratorBone->LocalToBoneTransform.GetScale()); } // read weights for this bone for (uint32 weightIndex = 0; weightIndex < pBone->mNumWeights; weightIndex++) { const aiVertexWeight *pWeight = &pBone->mWeights[weightIndex]; // get vertex DebugAssert(pWeight->mVertexId < meshVertices.GetSize()); SkeletalMeshGenerator::Vertex *pOutputVertex = &meshVertices[pWeight->mVertexId]; // find the first free bone in the vertex's weights uint32 freeBoneIndex; for (freeBoneIndex = 0; freeBoneIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; freeBoneIndex++) { if (pOutputVertex->BoneIndices[freeBoneIndex] == -1) break; } if (freeBoneIndex == SKELETAL_MESH_MAX_BONES_PER_VERTEX) { m_pProgressCallbacks->DisplayFormattedError("in mesh %s: vertex %u references more than SKELETAL_MESH_MAX_BONES_PER_VERTEX (%u) bones", pMesh->mName.C_Str(), pWeight->mVertexId, (uint32)SKELETAL_MESH_MAX_BONES_PER_VERTEX); return false; } // add to the vertex pOutputVertex->BoneIndices[freeBoneIndex] = outputBoneIndex; pOutputVertex->BoneWeights[freeBoneIndex] = pWeight->mWeight; maxBonesPerVertex = Max(maxBonesPerVertex, freeBoneIndex + 1); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] bone %s references %u vertices", meshName.GetCharArray(), pBone->mName.C_Str(), pBone->mNumWeights); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] maximum bone count per vertex: %u", meshName.GetCharArray(), maxBonesPerVertex); //pOutputMesh->SetWeightCount(maxBonesPerVertex); // add vertices to the generator PODArray<uint32> vertexMapping; vertexMapping.Reserve(meshVertices.GetSize()); for (uint32 vertexIndex = 0; vertexIndex < meshVertices.GetSize(); vertexIndex++) { // normalize weights float weightTotal = 0.0f; for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) weightTotal += meshVertices[vertexIndex].BoneWeights[weightIndex]; // should be 1 if (!Math::NearEqual(weightTotal, 1.0f, Y_FLT_EPSILON)) { m_pProgressCallbacks->DisplayFormattedWarning("[mesh %s] vertex %u weights do not sum to 1 (%.3f), fixing.", meshName.GetCharArray(), vertexIndex, weightTotal); for (uint32 weightIndex = 0; weightIndex < SKELETAL_MESH_MAX_BONES_PER_VERTEX; weightIndex++) meshVertices[vertexIndex].BoneWeights[weightIndex] *= 1.0f / weightTotal; } uint32 realVertexIndex = m_pOutputGenerator->AddVertex(meshVertices[vertexIndex]); vertexMapping.Add(realVertexIndex); } // read triangles for (uint32 faceIndex = 0; faceIndex < pMesh->mNumFaces; faceIndex++) { const aiFace *pFace = &pMesh->mFaces[faceIndex]; if (pFace->mNumIndices != 3) { m_pProgressCallbacks->DisplayFormattedError("in mesh %s: face %u does not have 3 indices", meshName.GetCharArray(), faceIndex); return false; } DebugAssert(pFace->mIndices[0] < vertexMapping.GetSize() && pFace->mIndices[1] < vertexMapping.GetSize() && pFace->mIndices[2] < vertexMapping.GetSize()); m_pOutputGenerator->AddTriangle(m_materialMapping[pMesh->mMaterialIndex], smoothingGroupMask, vertexMapping[pFace->mIndices[0]], vertexMapping[pFace->mIndices[1]], vertexMapping[pFace->mIndices[2]]); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u faces/triangles", meshName.GetCharArray(), pMesh->mNumFaces); // set next smoothing group smoothingGroupMask <<= 1; } return true; } bool AssimpSkeletalMeshImporter::PostProcess() { //m_pOutputGenerator->CalculateTangentVectorsAndNormals(); return true; } bool AssimpSkeletalMeshImporter::CreateCollisionShape() { bool result = false; if (m_pOptions->CollisionShapeType.Compare("none")) return true; else if (m_pOptions->CollisionShapeType.CompareInsensitive("Box")) result = m_pOutputGenerator->BuildBoxCollisionShape(); else if (m_pOptions->CollisionShapeType.CompareInsensitive("Sphere")) result = m_pOutputGenerator->BuildSphereCollisionShape(); else if (m_pOptions->CollisionShapeType.CompareInsensitive("TriangleMesh")) result = m_pOutputGenerator->BuildTriangleMeshCollisionShape(); else if (m_pOptions->CollisionShapeType.CompareInsensitive("ConvexHull")) result = m_pOutputGenerator->BuildConvexHullCollisionShape(); else { m_pProgressCallbacks->DisplayFormattedError("Unknown collision shape type '%s'", m_pOptions->CollisionShapeType.GetCharArray()); return false; } if (!result) { m_pProgressCallbacks->DisplayFormattedError("failed to build collision shape"); return false; } return true; } bool AssimpSkeletalMeshImporter::WriteOutput() { PathString outputResourceFileName; outputResourceFileName.Format("%s.skm.xml", m_pOptions->OutputResourceName.GetCharArray()); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputResourceFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not open file '%s'", outputResourceFileName.GetCharArray()); return false; } if (!m_pOutputGenerator->SaveToXML(pStream)) { m_pProgressCallbacks->DisplayError("failed to save xml file"); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); return true; } <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphCompilerHLSL.h #pragma once #include "ResourceCompiler/ShaderGraphCompiler.h" class ShaderGraphNode_ShaderOutputs; class ShaderGraphCompilerHLSL : public ShaderGraphCompiler { public: ShaderGraphCompilerHLSL(const ShaderGraph *pShaderGraph); ~ShaderGraphCompilerHLSL(); virtual bool Compile(ByteStream *pOutputStream) override; // emitters virtual bool EmitAdd(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) override; virtual bool EmitSubtract(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) override; virtual bool EmitMultiply(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) override; virtual bool EmitDivide(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) override; virtual bool EmitDot(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) override; virtual bool EmitNormalize(const ShaderGraphNodeInput *pNode) override; virtual bool EmitNegate(const ShaderGraphNodeInput *pNode) override; virtual bool EmitFractionalPart(const ShaderGraphNodeInput *pNode) override; virtual void EmitConstant(SHADER_PARAMETER_TYPE ValueType, const void *pValue) override; virtual void EmitConstantBool(bool Value) override; virtual void EmitConstantInt(int32 Value) override; virtual void EmitConstantInt2(const int2 &Value) override; virtual void EmitConstantInt3(const int3 &Value) override; virtual void EmitConstantInt4(const int4 &Value) override; virtual void EmitConstantFloat(const float &Value) override; virtual void EmitConstantFloat2(const float2 &Value) override; virtual void EmitConstantFloat3(const float3 &Value) override; virtual void EmitConstantFloat4(const float4 &Value) override; virtual bool EmitAccessShaderGlobal(const char *GlobalName) override; virtual bool EmitAccessShaderInput(const char *InputName) override; virtual bool EmitAccessExternalParameter(const ExternalParameter *pExternalParameter) override; virtual bool EmitTextureSample(const ShaderGraphNodeInput *pTextureNodeLink, const ShaderGraphNodeInput *pTexCoordNodeLink, SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION unpackOperation) override; virtual bool EmitConstructPrimitive(SHADER_PARAMETER_TYPE primitiveType, const ShaderGraphNodeInput **ppInputNodes, uint32 nInputNodes) override; virtual void EmitSwizzle(SHADER_GRAPH_VALUE_SWIZZLE Swizzle) override; virtual bool EvaluateNode(const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle, SHADER_GRAPH_VALUE_SWIZZLE FixupSwizzle) override; virtual bool EvaluateNode(const ShaderGraphNodeInput *pNodeLink) override; protected: typedef KeyValuePair<const ShaderGraphNode *, String> NodeStringPair; typedef KeyValuePair<String, String> DefinePair; typedef LinkedList<NodeStringPair> GlobalsMap; typedef LinkedList<DefinePair> CompileDefineMap; static void CleanString(String &str); static const char *GetTypeNameString(SHADER_PARAMETER_TYPE ValueType); bool AddCompileDefine(const char *Name, const char *Value); bool AddBufferedCompileDefine(const char *Name, const char *Value); bool InternalCompile(); bool InternalCompileDefaultValue(SHADER_PARAMETER_TYPE Type, const char *DefaultValue); bool InternalCompileOutput(uint32 outputIndex); SHADER_PROGRAM_STAGE m_currentStage; GlobalsMap m_globals; CompileDefineMap m_defines; String m_externsCode; String m_globalsCode; String m_methodsCode; String m_currentScope; String m_buffer; CompileDefineMap m_bufferedDefines; }; <file_sep>/Engine/Source/ContentConverter/OBJImporter.h #pragma once #include "ContentConverter/BaseImporter.h" #include "ContentConverter/TextureImporter.h" #define OBJIMPORTER_MAX_VERTICES_PER_FACE 16 struct OBJImporterOptions { String InputFileName; String MeshDirectory; String MeshPrefix; bool ImportMaterials; String MaterialDirectory; String MaterialPrefix; String DefaultMaterialName; String BuildCollisionShapeType; bool UseSmoothingGroups; float4x4 TransformMatrix; COORDINATE_SYSTEM CoordinateSystem; bool FlipWinding; uint32 CenterMeshes; bool MergeGroups; String OutputMapName; }; class OBJImporter : public BaseImporter { public: OBJImporter(ProgressCallbacks *pProgressCallbacks); ~OBJImporter(); static void SetDefaultOptions(OBJImporterOptions *pOptions); bool Execute(const OBJImporterOptions *pOptions); private: const OBJImporterOptions *m_pOptions; //------------------------------------------------------------------------- typedef MemArray<float3> SourceVertexArray; typedef MemArray<float2> SourceTexCoordArray; typedef PODArray<String *> SourceMaterialLibraryArray; typedef PODArray<String *> SourceMaterialNameArray; struct SourceFace { int32 VertexIndicies[OBJIMPORTER_MAX_VERTICES_PER_FACE]; int32 TexCoordIndices[OBJIMPORTER_MAX_VERTICES_PER_FACE]; uint32 NumVertices; uint32 SmoothingGroups; uint32 MaterialIndex; }; typedef MemArray<SourceFace> SourceFaceArray; struct SourceGroup { String Name; SourceFaceArray Faces; }; typedef PODArray<SourceGroup *> SourceGroupArray; // SourceVertexArray m_arrSourceVertices; SourceTexCoordArray m_arrSourceTexCoords; SourceMaterialLibraryArray m_arrSourceMaterialLibraries; SourceMaterialNameArray m_arrSourceMaterialNames; SourceGroupArray m_arrSourceGroups; uint32 m_uSourceLineNumber; // bool ParseSource(); void PrintSourceError(const char *Format, ...); void PrintSourceWarning(const char *Format, ...); //------------------------------------------------------------------------- struct SourceMaterial { String Name; String OutputName; float3 AmbientColor; float3 DiffuseColor; float3 SpecularColor; float Shininess; float3 EmissiveColor; float AlphaColor; uint32 Illum; String AmbientMap; String DiffuseMap; String SpecularMap; String AlphaMap; String BumpMap; }; // typedef PODArray<SourceMaterial *> SourceMaterialArray; SourceMaterialArray m_arrSourceMaterials; // bool ParseMaterials(); void PrintMaterialError(uint32 i, const char *Format, ...); void PrintMaterialWarning(uint32 i, const char *Format, ...); bool ImportMaterialTexture(const String &inputFileName, String &outputFullName, TEXTURE_USAGE usage, const String &maskTexture = EmptyString); bool GenerateMaterials(); //------------------------------------------------------------------------- struct OutputVertex { float3 Position; float2 TexCoord; }; struct OutputTriangle { uint32 Indices[3]; uint32 MaterialIndex; }; typedef MemArray<OutputVertex> OutputVertexArray; typedef MemArray<OutputTriangle> OutputTriangleArray; typedef Array<String> OutputMaterialArray; struct OutputMesh { String Name; OutputVertexArray Vertices; OutputTriangleArray Triangles; float3 Translation; }; typedef PODArray<OutputMesh *> OutputMeshArray; OutputMeshArray m_arrOutputMeshes; OutputMaterialArray m_arrOutputMaterials; // void MergeGroups(); bool GenerateTriangles(); bool WriteOutput(); // bool WriteMap(); }; <file_sep>/Engine/Source/Renderer/RenderProfiler.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProfiler.h" #include "Renderer/Renderer.h" #include "Renderer/MiniGUIContext.h" Log_SetChannel(RenderProfiler); RenderProfiler::RenderProfiler(GPUContext *pGPUContext) : m_pGPUContext(pGPUContext), m_gpuTimingEnabled(false), m_rendererResourcesCreated(false), m_pRootSection(NULL), m_pCurrentSection(NULL), m_pPreviousFrameRootSection(NULL), m_cameraOverrideIndex(-1) { } RenderProfiler::~RenderProfiler() { ReleaseRendererResources(); while (m_sectionCache.GetSize() > 0) { delete m_sectionCache[m_sectionCache.GetSize() - 1]; m_sectionCache.PopBack(); } } RenderProfiler::Section::Section() : m_elapsedTime(0.0f), m_hasGPUStats(false), m_gpuTime(0.0f), m_gpuWaitTime(0.0f), m_drawCallCount(0), m_pGPUTimeQuery(NULL), m_pParent(NULL) { } RenderProfiler::Section::~Section() { DebugAssert(m_pGPUTimeQuery == NULL); } void RenderProfiler::Section::Clear() { m_sectionName.Clear(); m_elapsedTime = 0.0f; m_hasGPUStats = false; m_gpuTime = 0.0f; m_gpuWaitTime = 0.0f; m_drawCallCount = 0; m_pGPUTimeQuery = NULL; m_pParent = NULL; m_children.Clear(); } void RenderProfiler::Section::Begin(Section *pParentSection, const char *sectionName, bool enableGPUStats, GPUContext *pGPUContext, GPUQuery *pGPUTimeQuery) { m_sectionName = sectionName; m_hasGPUStats = enableGPUStats; //m_startingDrawCallCount = pGPUContext->GetDrawCallCounter(); m_startingDrawCallCount = 0; m_timer.Reset(); m_pParent = pParentSection; // start time query if ((m_pGPUTimeQuery = pGPUTimeQuery) != NULL) { if (!pGPUContext->BeginQuery(m_pGPUTimeQuery)) m_pGPUTimeQuery = NULL; } } void RenderProfiler::Section::End(GPUContext *pGPUContext) { // gpu stats if (m_hasGPUStats) { // store draw calls //m_drawCallCount = pGPUContext->GetDrawCallCounter() - m_startingDrawCallCount; m_drawCallCount = 0; // gpu time if (m_pGPUTimeQuery != NULL) { Timer blockingTime; double gpuTime; if (pGPUContext->EndQuery(m_pGPUTimeQuery) && pGPUContext->GetQueryData(m_pGPUTimeQuery, &gpuTime, sizeof(gpuTime), 0) == GPU_QUERY_GETDATA_RESULT_OK) m_gpuTime = (float)(gpuTime * 1000.0); else m_gpuTime = 0.0f; // blocking time m_gpuWaitTime = (float)blockingTime.GetTimeMilliseconds(); } else { m_gpuTime = 0.0f; m_gpuWaitTime = 0.0f; } } else { m_drawCallCount = 0; m_gpuTime = 0.0f; m_gpuWaitTime = 0.0f; } // overall time m_elapsedTime = (float)m_timer.GetTimeMilliseconds(); } void RenderProfiler::BeginSection(const char *sectionName, bool enableGPUStats) { DebugAssert(m_pCurrentSection != NULL); // create section Section *pSection = GetNewSection(); pSection->Begin(m_pCurrentSection, sectionName, enableGPUStats, m_pGPUContext, (enableGPUStats) ? GetNewGPUTimeQuery() : NULL); // add to current node m_pCurrentSection->m_children.Add(pSection); // switch out m_pCurrentSection = pSection; } void RenderProfiler::EndSection() { DebugAssert(m_pCurrentSection != NULL); // end section m_pCurrentSection->End(m_pGPUContext); // release query back to context if (m_pCurrentSection->m_pGPUTimeQuery != NULL) { m_freeGPUTimeQueries.Add(m_pCurrentSection->m_pGPUTimeQuery); m_pCurrentSection->m_pGPUTimeQuery = NULL; } // swap pointer to parent m_pCurrentSection = m_pCurrentSection->m_pParent; } void RenderProfiler::BeginFrame() { // should not have a current frame DebugAssert(m_pRootSection == NULL && m_pCurrentSection == NULL); // if this fails, ehh, we just won't time it if (!m_rendererResourcesCreated) CreateRendererResources(); // create the root section Section *pSection = GetNewSection(); pSection->Begin(NULL, "<<<Frame>>>", true, m_pGPUContext, GetNewGPUTimeQuery()); m_pRootSection = pSection; m_pCurrentSection = pSection; } void RenderProfiler::EndFrame() { Assert(m_pCurrentSection != NULL && m_pCurrentSection == m_pRootSection); m_pCurrentSection->End(m_pGPUContext); // release query back to context if (m_pCurrentSection->m_pGPUTimeQuery != NULL) { m_freeGPUTimeQueries.Add(m_pCurrentSection->m_pGPUTimeQuery); m_pCurrentSection->m_pGPUTimeQuery = NULL; } // if there is a previous frame, clear it out if (m_pPreviousFrameRootSection != NULL) { CleanupSectionAndChildren(m_pPreviousFrameRootSection); m_pPreviousFrameRootSection = NULL; } // set this frame to be the new previous frame m_pPreviousFrameRootSection = m_pRootSection; m_pCurrentSection = NULL; m_pRootSection = NULL; // cleanup the camera list m_cameraArray.Clear(); } bool RenderProfiler::CreateRendererResources() { if (m_rendererResourcesCreated) return true; //if (m_pGPUTimeQuery == NULL && (m_pGPUTimeQuery = g_pRenderer->CreateQuery(GPU_QUERY_TYPE_TIME_ELAPSED)) == NULL) //Log_WarningPrintf("RenderProfiler::CreateRendererResources: Could not create GPU time query."); m_rendererResourcesCreated = true; return true; } void RenderProfiler::ReleaseRendererResources() { //SAFE_RELEASE(m_pGPUTimeQuery); while (m_gpuTimeQueryCache.GetSize() > 0) { m_gpuTimeQueryCache[m_gpuTimeQueryCache.GetSize() - 1]->Release(); m_gpuTimeQueryCache.PopBack(); } m_freeGPUTimeQueries.Clear(); // todo: clean from sections? m_rendererResourcesCreated = false; } void RenderProfiler::DrawThisFrameSummary(MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions) { if (m_pRootSection != NULL) DrawFrameSummary(m_pRootSection, pGUIContext, pDrawOptions); } void RenderProfiler::DrawPreviousFrameSummary(MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions) { if (m_pPreviousFrameRootSection != NULL) DrawFrameSummary(m_pPreviousFrameRootSection, pGUIContext, pDrawOptions); } void RenderProfiler::DrawFrameSummary(const Section *pRootSection, MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions) { DrawSummaryOptions defaultDrawOptions; if (pDrawOptions == NULL) { defaultDrawOptions.RedThresholdMs = 16.0f; defaultDrawOptions.YellowThresholdMs = 8.0f; defaultDrawOptions.pFont = g_pRenderer->GetFixedResources()->GetDebugFont(); defaultDrawOptions.FontSize = 16; //defaultDrawOptions.DrawAreaStartX = 20; //defaultDrawOptions.DrawAreaStartY = 20; //defaultDrawOptions.DrawAreaWidth = pGUIContext->GetTopRect().right - 40; //defaultDrawOptions.DrawAreaHeight = pGUIContext->GetTopRect().bottom - 40; defaultDrawOptions.DrawAreaStartX = pGUIContext->GetTopRect().right - 600; defaultDrawOptions.DrawAreaStartY = 20; defaultDrawOptions.DrawAreaWidth = 600; //defaultDrawOptions.DrawAreaHeight = 690; defaultDrawOptions.DrawAreaHeight = 1000; defaultDrawOptions.DrawAreaBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(30, 30, 30, 200); defaultDrawOptions.DrawAreaBorderColor = MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255); pDrawOptions = &defaultDrawOptions; } MINIGUI_RECT rect, bgRect; //Log_DevPrintf("total time: %.4f ms", pRootSection->GetElapsedTime()); // set rect to the draw area rect.Set(pDrawOptions->DrawAreaStartX, pDrawOptions->DrawAreaStartX + pDrawOptions->DrawAreaWidth, pDrawOptions->DrawAreaStartY, pDrawOptions->DrawAreaStartY + pDrawOptions->DrawAreaHeight); // manual flushing pGUIContext->PushManualFlush(); pGUIContext->SetAlphaBlendingEnabled(true); pGUIContext->SetAlphaBlendingMode(MiniGUIContext::ALPHABLENDING_MODE_STRAIGHT); // draw the background pGUIContext->DrawFilledRect(&rect, pDrawOptions->DrawAreaBackgroundColor); // and the outline pGUIContext->DrawRect(&rect, pDrawOptions->DrawAreaBorderColor); // push the full rectangle //pGUIContext->PushRectAndClipRect(&rect); pGUIContext->PushRect(&rect); // background and line bgRect.Set(2, (rect.right - rect.left) - 2, 2 + pDrawOptions->FontSize + 2 + 2 + 2, 2 + pDrawOptions->FontSize + 2 + 2 + 2 + pDrawOptions->FontSize + 2); pGUIContext->DrawFilledRect(&bgRect, MAKE_COLOR_R8G8B8A8_UNORM(180, 180, 180, 255)); //pGUIContext->DrawLine(int2(2, 2 + pDrawOptions->FontSize + 2 + 2 + 2 + pDrawOptions->FontSize + 2), int2((rect.right - rect.left) - 2, 2 + pDrawOptions->FontSize + 2 + 2 + 2 + pDrawOptions->FontSize + 2), MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); // draw headings pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, 2, 2, "Render Profiler", MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, 2, 2 + pDrawOptions->FontSize + 2 + 2 + 2, "Section", MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -240, 2 + pDrawOptions->FontSize + 2 + 2 + 2, "Total", MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -180, 2 + pDrawOptions->FontSize + 2 + 2 + 2, "CPU", MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -120, 2 + pDrawOptions->FontSize + 2 + 2 + 2, "GPU", MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -60, 2 + pDrawOptions->FontSize + 2 + 2 + 2, "Draws", MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); // add content margins rect.Set(2, (rect.right - rect.left) - 2, 2 + pDrawOptions->FontSize + 2 + 2 + 2 + pDrawOptions->FontSize + 2, pDrawOptions->DrawAreaHeight - (2 + pDrawOptions->FontSize + 2 + 2 + 2 + pDrawOptions->FontSize + 2) - 2); //pGUIContext->PushRectAndClipRect(&rect); pGUIContext->PushRect(&rect); // draw all nodes DrawFrameSummaryRecursive(pRootSection, pGUIContext, pDrawOptions); // pop rect //pGUIContext->PopRectAndClipRect(); //pGUIContext->PopRectAndClipRect(); pGUIContext->PopRect(); pGUIContext->PopRect(); pGUIContext->PopManualFlush(); } uint32 RenderProfiler::DrawFrameSummaryRecursive(const Section *pCurrentSection, MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions) { const uint32 spacing = 2; const uint32 indent = 10; SmallString message; uint32 currentPos = 0; uint32 textColor; if (pCurrentSection->GetElapsedTime() >= pDrawOptions->RedThresholdMs) textColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 20, 20, 255); else if (pCurrentSection->GetElapsedTime() >= pDrawOptions->YellowThresholdMs) textColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 20, 255); else textColor = MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255); // section name pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, 0, currentPos, pCurrentSection->GetSectionName(), textColor); // total time message.Format("%.2fms", pCurrentSection->GetElapsedTime()); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -240, currentPos, message, textColor); // cpu time message.Format("%.2fms", pCurrentSection->GetCPUTime()); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -180, currentPos, message, textColor); if (pCurrentSection->HasGPUStats()) { if (m_gpuTimingEnabled) { message.Format("%.2fms", pCurrentSection->GetGPUTime()); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -120, currentPos, message, textColor); } else { pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -120, currentPos, "-", textColor); } message.Format("%u", pCurrentSection->GetDrawCallCount()); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -60, currentPos, message, textColor); } else { pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -120, currentPos, "-", textColor); pGUIContext->DrawText(pDrawOptions->pFont, pDrawOptions->FontSize, -60, currentPos, "-", textColor); } currentPos += pDrawOptions->FontSize + spacing; // draw children for (uint32 i = 0; i < pCurrentSection->GetChildCount(); i++) { // create rect for next level down MINIGUI_RECT rect; rect.Set(indent, pGUIContext->GetTopRect().right - pGUIContext->GetTopRect().left, currentPos, pGUIContext->GetTopRect().bottom - pGUIContext->GetTopRect().top); //pGUIContext->PushRectAndClipRect(&rect); pGUIContext->PushRect(&rect); // draw it currentPos += DrawFrameSummaryRecursive(pCurrentSection->GetChild(i), pGUIContext, pDrawOptions); // pop rect //pGUIContext->PopRectAndClipRect(); pGUIContext->PopRect(); } return currentPos; } RenderProfiler::Section *RenderProfiler::GetNewSection() { RenderProfiler::Section *pSection; if (m_freeSections.GetSize() > 0) { pSection = m_freeSections[0]; m_freeSections.PopFront(); } else { pSection = new RenderProfiler::Section(); m_sectionCache.Add(pSection); } return pSection; } GPUQuery *RenderProfiler::GetNewGPUTimeQuery() { if (!m_gpuTimingEnabled) return NULL; GPUQuery *pQuery; if (m_freeGPUTimeQueries.GetSize() > 0) { pQuery = m_freeGPUTimeQueries[0]; m_freeGPUTimeQueries.PopFront(); } else { pQuery = g_pRenderer->CreateQuery(GPU_QUERY_TYPE_TIMESTAMP); m_gpuTimeQueryCache.Add(pQuery); } return pQuery; } void RenderProfiler::CleanupSectionAndChildren(Section *pSection) { DebugAssert(pSection->m_pGPUTimeQuery == NULL); // clean children for (uint32 i = 0; i < pSection->m_children.GetSize(); i++) CleanupSectionAndChildren(pSection->m_children[i]); // clean section pSection->Clear(); // add to free list m_freeSections.Add(pSection); } void RenderProfiler::AddCamera(const Camera *pCamera, const char *cameraName) { m_cameraArray.Add(KeyValuePair<String, Camera>(cameraName, *pCamera)); } <file_sep>/Engine/Source/Core/PixelFormatConverters.cpp #include "Core/PrecompiledHeader.h" #include "Core/PixelFormat.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Log.h" Log_SetChannel(PixelFormatConverters); // kinda a crappy converter, but basically we just convert each pixel to a R32G32B32A32 pixel, then back to the destination format /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void DecodeR8G8B8A8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j * 4 + 0]) / 255.0f; pOutRow[j * 4 + 1] = float(pInBytes[j * 4 + 1]) / 255.0f; pOutRow[j * 4 + 2] = float(pInBytes[j * 4 + 2]) / 255.0f; pOutRow[j * 4 + 3] = float(pInBytes[j * 4 + 3]) / 255.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR8G8B8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j * 3 + 0]) / 255.0f; pOutRow[j * 4 + 1] = float(pInBytes[j * 3 + 1]) / 255.0f; pOutRow[j * 4 + 2] = float(pInBytes[j * 3 + 2]) / 255.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeB8G8R8A8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j * 4 + 3]) / 255.0f; pOutRow[j * 4 + 1] = float(pInBytes[j * 4 + 2]) / 255.0f; pOutRow[j * 4 + 2] = float(pInBytes[j * 4 + 1]) / 255.0f; pOutRow[j * 4 + 3] = float(pInBytes[j * 4 + 0]) / 255.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeB8G8R8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j * 3 + 3]) / 255.0f; pOutRow[j * 4 + 1] = float(pInBytes[j * 3 + 2]) / 255.0f; pOutRow[j * 4 + 2] = float(pInBytes[j * 3 + 1]) / 255.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeB8G8R8X8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j * 4 + 3]) / 255.0f; pOutRow[j * 4 + 1] = float(pInBytes[j * 4 + 2]) / 255.0f; pOutRow[j * 4 + 2] = float(pInBytes[j * 4 + 1]) / 255.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR8(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = float(pInBytes[j]) / 255.0f; pOutRow[j * 4 + 1] = 1.0f; pOutRow[j * 4 + 2] = 1.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR32G32B32A32F(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = *(const float *)(&pInBytes[j * 16 + 0]); pOutRow[j * 4 + 1] = *(const float *)(&pInBytes[j * 16 + 4]); pOutRow[j * 4 + 2] = *(const float *)(&pInBytes[j * 16 + 8]); pOutRow[j * 4 + 3] = *(const float *)(&pInBytes[j * 16 + 12]); } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR16G16B16A16F(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = Math::HalfToFloat(*(const uint16 *)(&pInBytes[j * 8 + 0])); pOutRow[j * 4 + 1] = Math::HalfToFloat(*(const uint16 *)(&pInBytes[j * 8 + 2])); pOutRow[j * 4 + 2] = Math::HalfToFloat(*(const uint16 *)(&pInBytes[j * 8 + 4])); pOutRow[j * 4 + 3] = Math::HalfToFloat(*(const uint16 *)(&pInBytes[j * 8 + 6])); } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR32F(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = *(const float *)(&pInBytes[j * 4]); pOutRow[j * 4 + 1] = 1.0f; pOutRow[j * 4 + 2] = 1.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } static void DecodeR16F(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) { const byte *pInBytes = (const byte *)pInPixels; float *pOutRow = pOutPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutRow[j * 4 + 0] = Math::HalfToFloat(*(const uint16 *)(&pInBytes[j * 2])); pOutRow[j * 4 + 1] = 1.0f; pOutRow[j * 4 + 2] = 1.0f; pOutRow[j * 4 + 3] = 1.0f; } pInBytes += SourcePitch; pOutRow += Width * 4; } } // // static void Decode8BitChannel(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat) // { // PIXEL_FORMAT_INFO *pFormatInfo = PixelFormat_GetPixelFormatInfo(SourceFormat); // DebugAssert(pFormatInfo->BitsPerPixel <= 32); // // const byte *pInBytes = (const byte *)pInPixels; // float *pOutRow = pOutPixels; // uint32 i, j; // // uint32 ShiftRed // // for (i = 0; i < Height; i++) // { // const byte *pInThisRow = pInBytes; // float *pOutThisRow = pOutRow; // for (j = 0; j < Width; j++) // { // uint32 InInt = 0; // if (pFormatInfo->BitsPerPixel >= 8) // { // InInt |= (((uint32)*pInThisRow++) << 24); // if (pFormatInfo->BitsPerPixel >= 16) // { // InInt |= (((uint32)*pInThisRow++) << 16); // if (pFormatInfo->BitsPerPixel >= 24) // { // InInt |= (((uint32)*pInThisRow++) << 8); // if (pFormatInfo->BitsPerPixel >= 32) // InInt |= (((uint32)*pInThisRow++)); // } // } // } // // // splat the value across all 4 components, then mask it out // if (pFormatInfo->ColorMaskRed != 0) // *pOutThisRow++ = (InInt & pFormatInfo->ColorMaskRed) // // // // pOutRow[j * 4 + 0] = float(pInBytes[j * 3 + 0]) * 255.0f; // pOutRow[j * 4 + 1] = float(pInBytes[j * 3 + 1]) * 255.0f; // pOutRow[j * 4 + 2] = float(pInBytes[j * 3 + 2]) * 255.0f; // pOutRow[j * 4 + 3] = 1.0f; // } // pInBytes += SourcePitch; // pOutRow += Width * 4; // } // } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void EncodeR8G8B8A8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j * 4 + 0] = (byte)(pInRow[j * 4 + 0] * 255.0f); pOutBytes[j * 4 + 1] = (byte)(pInRow[j * 4 + 1] * 255.0f); pOutBytes[j * 4 + 2] = (byte)(pInRow[j * 4 + 2] * 255.0f); pOutBytes[j * 4 + 3] = (byte)(pInRow[j * 4 + 3] * 255.0f); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR8G8B8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j * 3 + 0] = (byte)(pInRow[j * 4 + 0] * 255.0f); pOutBytes[j * 3 + 1] = (byte)(pInRow[j * 4 + 1] * 255.0f); pOutBytes[j * 3 + 2] = (byte)(pInRow[j * 4 + 2] * 255.0f); // drop alpha } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeB8G8R8A8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j * 4 + 2] = (byte)(pInRow[j * 4 + 0] * 255.0f); pOutBytes[j * 4 + 1] = (byte)(pInRow[j * 4 + 1] * 255.0f); pOutBytes[j * 4 + 0] = (byte)(pInRow[j * 4 + 2] * 255.0f); pOutBytes[j * 4 + 3] = (byte)(pInRow[j * 4 + 3] * 255.0f); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeB8G8R8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j * 3 + 2] = (byte)(pInRow[j * 4 + 0] * 255.0f); pOutBytes[j * 3 + 1] = (byte)(pInRow[j * 4 + 1] * 255.0f); pOutBytes[j * 3 + 0] = (byte)(pInRow[j * 4 + 2] * 255.0f); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeB8G8R8X8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j * 4 + 2] = (byte)(pInRow[j * 4 + 0] * 255.0f); pOutBytes[j * 4 + 1] = (byte)(pInRow[j * 4 + 1] * 255.0f); pOutBytes[j * 4 + 0] = (byte)(pInRow[j * 4 + 2] * 255.0f); pOutBytes[j * 4 + 3] = 0; } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR8(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { pOutBytes[j] = (byte)(pInRow[j * 4 + 0] * 255.0f); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR32G32B32A32F(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { *(float *)(&pOutBytes[j * 16 + 0]) = pInRow[j * 4 + 0]; *(float *)(&pOutBytes[j * 16 + 4]) = pInRow[j * 4 + 1]; *(float *)(&pOutBytes[j * 16 + 8]) = pInRow[j * 4 + 2]; *(float *)(&pOutBytes[j * 16 + 12]) = pInRow[j * 4 + 3]; } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR16G16B16A16F(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { *(uint16 *)(&pOutBytes[j * 8 + 0]) = Math::FloatToHalf(pInRow[j * 4 + 0]); *(uint16 *)(&pOutBytes[j * 8 + 2]) = Math::FloatToHalf(pInRow[j * 4 + 1]); *(uint16 *)(&pOutBytes[j * 8 + 4]) = Math::FloatToHalf(pInRow[j * 4 + 2]); *(uint16 *)(&pOutBytes[j * 8 + 6]) = Math::FloatToHalf(pInRow[j * 4 + 3]); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR32F(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { *(float *)(&pOutBytes[j * 4]) = pInRow[j * 4 + 0]; } pOutBytes += DestinationPitch; pInRow += Width * 4; } } static void EncodeR16F(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { byte *pOutBytes = (byte *)pOutPixels; const float *pInRow = pInPixels; uint32 i, j; for (i = 0; i < Height; i++) { for (j = 0; j < Width; j++) { *(uint16 *)(&pOutBytes[j * 2]) = Math::FloatToHalf(pInRow[j * 4 + 0]); } pOutBytes += DestinationPitch; pInRow += Width * 4; } } // static void EncodeGetPixelRGBA8(const float *pInPixels, uint32 Width, uint32 Height, uint32 x, uint32 y, uint32 *Out) // { // byte *pByteOut = (byte *)Out; // if (x >= Width || y >= Height) // { // pByteOut[0] = 0; // pByteOut[1] = 0; // pByteOut[2] = 0; // pByteOut[3] = 255; // } // else // { // const float *pPixel = &pInPixels[y * Width + x]; // pByteOut[0] = (byte)(pPixel[0] * 255.0f); // pByteOut[1] = (byte)(pPixel[1] * 255.0f); // pByteOut[2] = (byte)(pPixel[2] * 255.0f); // pByteOut[3] = (byte)(pPixel[3] * 255.0f); // } // } #ifdef HAVE_SQUISH #include <squish.h> static void EncodeBC123(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat) { // static const float *ZeroPixel = { 0, 0, 0, 0 }; //#define GETPIXEL(row, col) ((row < Width && col < Height) ? ((float *)(((byte *)pInPixels) + ((row * Width) + col) * DestinationPitch)) : ZeroPixel; //static const uint32 *ZeroPixel = { 0, 0, 0, 0xFF }; const PIXEL_FORMAT_INFO *pFormatInfo = PixelFormat_GetPixelFormatInfo(DestinationFormat); uint32 BlocksWide = Max((uint32)1, Width / pFormatInfo->BlockSize); uint32 BlocksHigh = Max((uint32)1, Height / pFormatInfo->BlockSize); byte *pOutBytes = (byte *)pOutPixels; uint32 BlockIn[16]; //uint32 Flags = squish::kColourRangeFit; uint32 Flags = squish::kColourIterativeClusterFit; if (DestinationFormat == PIXEL_FORMAT_BC1_UNORM) Flags |= squish::kDxt1; else if (DestinationFormat == PIXEL_FORMAT_BC2_UNORM) Flags |= squish::kDxt3; else if (DestinationFormat == PIXEL_FORMAT_BC3_UNORM) Flags |= squish::kDxt5; for (uint32 i = 0; i < BlocksHigh; i++) { for (uint32 j = 0; j < BlocksWide; j++) { uint32 mask = 0; uint32 maskPos = 0; for (uint32 y = 0; y < 4; y++) { for (uint32 x = 0; x < 4; x++) { uint32 rx = j * pFormatInfo->BlockSize + x; uint32 ry = i * pFormatInfo->BlockSize + y; if (rx < Width && ry < Height) { const float *pSrcPixel = &pInPixels[(ry * Width + rx) * 4]; byte *pDstPixel = (byte *)&BlockIn[y * 4 + x]; pDstPixel[0] = Min((byte)255, (byte)(pSrcPixel[0] * 255.0f)); pDstPixel[1] = Min((byte)255, (byte)(pSrcPixel[1] * 255.0f)); pDstPixel[2] = Min((byte)255, (byte)(pSrcPixel[2] * 255.0f)); pDstPixel[3] = Min((byte)255, (byte)(pSrcPixel[3] * 255.0f)); mask |= 1 << maskPos; } maskPos++; } } byte *BlockOut = pOutBytes + (j * pFormatInfo->BytesPerBlock); //squish::Compress((const squish::u8 *)BlockIn, (squish::u8 *)BlockOut, Flags); squish::CompressMasked((const squish::u8 *)BlockIn, mask, (squish::u8 *)BlockOut, Flags); } pOutBytes += DestinationPitch; } } static void DecodeBC123(const void *pInPixels, float *pOutPixels, uint32 width, uint32 height, uint32 sourcePitch, PIXEL_FORMAT sourceFormat) { const PIXEL_FORMAT_INFO *pFormatInfo = PixelFormat_GetPixelFormatInfo(sourceFormat); uint32 blockSize = pFormatInfo->BlockSize; uint32 blocksWide = Max((uint32)1, width / blockSize); uint32 blocksHigh = Max((uint32)1, height / blockSize); uint32 flags = 0; if (sourceFormat == PIXEL_FORMAT_BC1_UNORM) flags |= squish::kDxt1; else if (sourceFormat == PIXEL_FORMAT_BC2_UNORM) flags |= squish::kDxt3; else if (sourceFormat == PIXEL_FORMAT_BC3_UNORM) flags |= squish::kDxt5; // decode each block for (uint32 by = 0; by < blocksHigh; by++) { const byte *pSourcePointer = reinterpret_cast<const byte *>(pInPixels) + (sourcePitch * by); for (uint32 bx = 0; bx < blocksWide; bx++) { byte blockRGBA[16 * 4]; squish::Decompress(blockRGBA, pSourcePointer, flags); uint32 startX = bx * blockSize; uint32 startY = by * blockSize; uint32 endX = startX + blockSize; uint32 endY = startY + blockSize; const byte *pBlockPtr = blockRGBA; for (uint32 y = startY; y < endY; y++) { if (y >= height) break; const byte *pNextBlockPtr = pBlockPtr + blockSize * 4; float *pDstPixel = &pOutPixels[(y * width + startX) * 4]; for (uint32 x = startX; x < endX; x++) { if (x >= width) break; *(pDstPixel++) = (float)*(pBlockPtr++) * 255.0f; *(pDstPixel++) = (float)*(pBlockPtr++) * 255.0f; *(pDstPixel++) = (float)*(pBlockPtr++) * 255.0f; *(pDstPixel++) = (float)*(pBlockPtr++) * 255.0f; } DebugAssert(pNextBlockPtr >= pBlockPtr); pBlockPtr = pNextBlockPtr; } pSourcePointer += pFormatInfo->BytesPerBlock; } } } #endif // HAVE_SQUISH /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct PixelFormatEncodeDecode { typedef void(*EncodeFunctionType)(const float *pInPixels, void *pOutPixels, uint32 Width, uint32 Height, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat); typedef void(*DecodeFunctionType)(const void *pInPixels, float *pOutPixels, uint32 Width, uint32 Height, uint32 SourcePitch, PIXEL_FORMAT SourceFormat); PIXEL_FORMAT Format; EncodeFunctionType EncodeFunction; DecodeFunctionType DecodeFunction; }; static const PixelFormatEncodeDecode g_PixelFormatEncodeDecode[] = { { PIXEL_FORMAT_R8G8B8A8_UNORM, EncodeR8G8B8A8, DecodeR8G8B8A8 }, { PIXEL_FORMAT_R8G8B8_UNORM, EncodeR8G8B8, DecodeR8G8B8 }, { PIXEL_FORMAT_B8G8R8A8_UNORM, EncodeB8G8R8A8, DecodeB8G8R8A8 }, { PIXEL_FORMAT_B8G8R8X8_UNORM, EncodeB8G8R8X8, DecodeB8G8R8X8 }, { PIXEL_FORMAT_B8G8R8_UNORM, EncodeB8G8R8, DecodeB8G8R8 }, { PIXEL_FORMAT_R8_UNORM, EncodeR8, DecodeR8 }, { PIXEL_FORMAT_R32G32B32A32_FLOAT, EncodeR32G32B32A32F, DecodeR32G32B32A32F }, { PIXEL_FORMAT_R16G16B16A16_FLOAT, EncodeR16G16B16A16F, DecodeR16G16B16A16F }, { PIXEL_FORMAT_R32_FLOAT, EncodeR32F, DecodeR32F }, { PIXEL_FORMAT_R16_FLOAT, EncodeR16F, DecodeR16F }, #ifdef HAVE_SQUISH { PIXEL_FORMAT_BC1_UNORM, EncodeBC123, DecodeBC123 }, { PIXEL_FORMAT_BC2_UNORM, EncodeBC123, DecodeBC123 }, { PIXEL_FORMAT_BC3_UNORM, EncodeBC123, DecodeBC123 }, #endif }; bool PixelFormat_ConvertPixels(uint32 Width, uint32 Height, const void *SourcePixels, uint32 SourcePitch, PIXEL_FORMAT SourceFormat, void *DestinationPixels, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat, uint32 *DestinationPixelSize) { uint32 i; DebugAssert(SourceFormat < PIXEL_FORMAT_COUNT && DestinationFormat < PIXEL_FORMAT_COUNT); DebugAssert(SourceFormat != DestinationFormat); //Log_DevPrintf("PixelFormat_ConvertPixels: Converting %ux%u image from %s to %s...", Width, Height, PixelFormat_GetPixelFormatInfo(SourceFormat)->Name, PixelFormat_GetPixelFormatInfo(DestinationFormat)->Name); PixelFormatEncodeDecode::DecodeFunctionType DecodeFunction = NULL; PixelFormatEncodeDecode::EncodeFunctionType EncodeFunction = NULL; for (i = 0; i < countof(g_PixelFormatEncodeDecode); i++) { if (g_PixelFormatEncodeDecode[i].Format == SourceFormat) DecodeFunction = g_PixelFormatEncodeDecode[i].DecodeFunction; if (g_PixelFormatEncodeDecode[i].Format == DestinationFormat) EncodeFunction = g_PixelFormatEncodeDecode[i].EncodeFunction; } if (DecodeFunction == NULL) { Log_ErrorPrintf("PixelFormat_ConvertPixels: No Decode function for %s.", PixelFormat_GetPixelFormatInfo(SourceFormat)->Name); return false; } if (EncodeFunction == NULL) { Log_ErrorPrintf("PixelFormat_ConvertPixels: No Encode function for %s.", PixelFormat_GetPixelFormatInfo(DestinationFormat)->Name); return false; } uint32 CalculatedDestinationPixelSize = PixelFormat_CalculateImageSize(DestinationFormat, Width, Height, 1); if (*DestinationPixelSize < CalculatedDestinationPixelSize) { Log_ErrorPrintf("PixelFormat_ConvertPixels: DestinationPixelSize too small (%u), %u required.", *DestinationPixelSize, CalculatedDestinationPixelSize); return false; } // allocate memory for temp pixels (ouch) //Log_DevPrintf("PixelFormat_ConvertPixels: Temporary array consumes %u bytes of memory...", sizeof(float) * Width * Height * 4); float *pTempPixels = Y_mallocT<float>(Width * Height * 4); // decode pixels to 32f DecodeFunction(SourcePixels, pTempPixels, Width, Height, SourcePitch, SourceFormat); // now encode them to the dest format EncodeFunction(pTempPixels, DestinationPixels, Width, Height, DestinationPitch, DestinationFormat); // log/free/return Y_free(pTempPixels); *DestinationPixelSize = CalculatedDestinationPixelSize; return true; } <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUTexture.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" class D3D12GPUTexture2D : public GPUTexture2D { public: D3D12GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, const D3D12DescriptorHandle &srvHandle, const D3D12DescriptorHandle &samplerHandle, D3D12_RESOURCE_STATES defaultResourceState); virtual ~D3D12GPUTexture2D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D12Resource *GetD3DResource() const { return m_pD3DResource; } const D3D12DescriptorHandle &GetSRVHandle() const { return m_srvHandle; } const D3D12DescriptorHandle &GetSamplerHandle() const { return m_samplerHandle; } D3D12_RESOURCE_STATES GetDefaultResourceState() const { return m_defaultResourceState; } protected: D3D12GPUDevice *m_pDevice; ID3D12Resource *m_pD3DResource; D3D12DescriptorHandle m_srvHandle; D3D12DescriptorHandle m_samplerHandle; D3D12_RESOURCE_STATES m_defaultResourceState; }; class D3D12GPUTexture2DArray : public GPUTexture2DArray { public: D3D12GPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, const D3D12DescriptorHandle &srvHandle, const D3D12DescriptorHandle &samplerHandle, D3D12_RESOURCE_STATES defaultResourceState); virtual ~D3D12GPUTexture2DArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D12Resource *GetD3DResource() const { return m_pD3DResource; } const D3D12DescriptorHandle &GetSRVHandle() const { return m_srvHandle; } const D3D12DescriptorHandle &GetSamplerHandle() const { return m_samplerHandle; } D3D12_RESOURCE_STATES GetDefaultResourceState() const { return m_defaultResourceState; } protected: D3D12GPUDevice *m_pDevice; ID3D12Resource *m_pD3DResource; D3D12DescriptorHandle m_srvHandle; D3D12DescriptorHandle m_samplerHandle; D3D12_RESOURCE_STATES m_defaultResourceState; }; class D3D12GPURenderTargetView : public GPURenderTargetView { public: D3D12GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource); virtual ~D3D12GPURenderTargetView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12DescriptorHandle &GetDescriptorHandle() const { return m_descriptorHandle; } ID3D12Resource *GetD3DResource() const { return m_pD3DResource; } protected: D3D12GPUDevice *m_pDevice; D3D12DescriptorHandle m_descriptorHandle; ID3D12Resource *m_pD3DResource; }; class D3D12GPUDepthStencilBufferView : public GPUDepthStencilBufferView { public: D3D12GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource); virtual ~D3D12GPUDepthStencilBufferView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12DescriptorHandle &GetDescriptorHandle() const { return m_descriptorHandle; } ID3D12Resource *GetD3DResource() const { return m_pD3DResource; } protected: D3D12GPUDevice *m_pDevice; D3D12DescriptorHandle m_descriptorHandle; ID3D12Resource *m_pD3DResource; }; class D3D12GPUComputeView : public GPUComputeView { public: D3D12GPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &descriptorHandle, ID3D12Resource *pD3DResource); virtual ~D3D12GPUComputeView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const D3D12DescriptorHandle &GetDescriptorHandle() const { return m_descriptorHandle; } ID3D12Resource *GetD3DResource() const { return m_pD3DResource; } protected: D3D12GPUDevice *m_pDevice; D3D12DescriptorHandle m_descriptorHandle; ID3D12Resource *m_pD3DResource; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUDevice.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" #include "OpenGLRenderer/OpenGLGPUOutputBuffer.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUTexture.h" #include "OpenGLRenderer/OpenGLGPUBuffer.h" class OpenGLGPUSamplerState : public GPUSamplerState { public: OpenGLGPUSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, GLuint samplerID); virtual ~OpenGLGPUSamplerState(); const GLuint GetGLSamplerID() const { return m_GLSamplerID; } virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; private: GLuint m_GLSamplerID; }; class OpenGLGPURasterizerState : public GPURasterizerState { public: OpenGLGPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc); virtual ~OpenGLGPURasterizerState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLenum GetGLPolygonMode() const { return m_GLPolygonMode; } const GLenum GetGLCullFace() const { return m_GLCullFace; } const GLenum GetGLFrontFace() const { return m_GLFrontFace; } const bool GetGLScissorTestEnable() const { return m_GLScissorTestEnable; } void Apply(); void Unapply(); private: GLenum m_GLPolygonMode; GLenum m_GLCullFace; bool m_GLCullEnabled; GLenum m_GLFrontFace; bool m_GLScissorTestEnable; bool m_GLDepthClampEnable; }; class OpenGLGPUDepthStencilState : public GPUDepthStencilState { public: OpenGLGPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc); virtual ~OpenGLGPUDepthStencilState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const bool GetGLDepthTestEnable() const { return m_GLDepthTestEnable; } const GLboolean GetGLDepthMask() const { return m_GLDepthMask; } const GLenum GetGLDepthFunc() const { return m_GLDepthFunc; } const bool GetGLStencilTestEnable() const { return m_GLDepthTestEnable; } const GLuint GetGLStencilReadMask() const { return m_GLStencilReadMask; } const GLuint GetGLStencilWriteMask() const { return m_GLStencilWriteMask; } const GLenum GetGLStencilFuncFront() const { return m_GLStencilFuncFront; } const GLenum GetGLStencilFuncBack() const { return m_GLStencilFuncBack; } void Apply(uint8 StencilRef); void Unapply(); private: bool m_GLDepthTestEnable; GLboolean m_GLDepthMask; GLenum m_GLDepthFunc; bool m_GLStencilTestEnable; GLuint m_GLStencilReadMask; GLuint m_GLStencilWriteMask; GLenum m_GLStencilFuncFront; GLenum m_GLStencilOpFrontFail; GLenum m_GLStencilOpFrontDepthFail; GLenum m_GLStencilOpFrontPass; GLenum m_GLStencilFuncBack; GLenum m_GLStencilOpBackFail; GLenum m_GLStencilOpBackDepthFail; GLenum m_GLStencilOpBackPass; }; class OpenGLGPUBlendState : public GPUBlendState { public: OpenGLGPUBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc); virtual ~OpenGLGPUBlendState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const bool GetGLBlendEnable() const { return m_GLBlendEnable; } const GLenum GetGLBlendEquationRGB() const { return m_GLBlendEquationRGB; } const GLenum GetGLBlendEquationAlpha() const { return m_GLBlendEquationAlpha; } const GLenum GetGLBlendFuncSrcRGB() const { return m_GLBlendFuncSrcRGB; } const GLenum GetGLBlendFuncDstRGB() const { return m_GLBlendFuncSrcRGB; } const GLenum GetGLBlendFuncSrcAlpha() const { return m_GLBlendFuncSrcAlpha; } const GLenum GetGLBlendFuncDstAlpha() const { return m_GLBlendFuncDstAlpha; } const bool GetGLColorWritesEnabled() const { return m_GLColorWritesEnabled; } void Apply(); void Unapply(); private: bool m_GLBlendEnable; GLenum m_GLBlendEquationRGB; GLenum m_GLBlendEquationAlpha; GLenum m_GLBlendFuncSrcRGB; GLenum m_GLBlendFuncDstRGB; GLenum m_GLBlendFuncSrcAlpha; GLenum m_GLBlendFuncDstAlpha; bool m_GLColorWritesEnabled; }; class OpenGLGPUDevice : public GPUDevice { public: struct UploadContextReference { UploadContextReference(OpenGLGPUDevice *pDevice); ~UploadContextReference(); bool HasContext() const; OpenGLGPUDevice *pDevice; bool ContextNeedsRelease; }; public: OpenGLGPUDevice(SDL_GLContext pMainGLContext, SDL_GLContext pOffThreadGLContext, OpenGLGPUOutputBuffer *pImplicitOutputBuffer, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, PIXEL_FORMAT outputBackBufferFormat, PIXEL_FORMAT outputDepthStencilFormat); ~OpenGLGPUDevice(); // Device queries. virtual RENDERER_PLATFORM GetPlatform() const override final; virtual RENDERER_FEATURE_LEVEL GetFeatureLevel() const override final; virtual TEXTURE_PLATFORM GetTexturePlatform() const override final; virtual void GetCapabilities(RendererCapabilities *pCapabilities) const override final; virtual bool CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat = nullptr) const override final; virtual void CorrectProjectionMatrix(float4x4 &projectionMatrix) const override final; virtual float GetTexelOffset() const override final; // Creates a swap chain on an existing window. virtual GPUOutputBuffer *CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) override final; virtual GPUOutputBuffer *CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) override final; // Resource creation virtual GPUQuery *CreateQuery(GPU_QUERY_TYPE type) override final; virtual GPUBuffer *CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData = nullptr) override final; virtual GPUTexture1D *CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture1DArray *CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2D *CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2DArray *CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture3D *CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr, const uint32 *pInitialDataSlicePitch = nullptr) override final; virtual GPUTextureCube *CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTextureCubeArray *CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUDepthTexture *CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) override final; virtual GPUSamplerState *CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) override final; virtual GPURenderTargetView *CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilBufferView *CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) override final; virtual GPUComputeView *CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilState *CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) override final; virtual GPURasterizerState *CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) override final; virtual GPUBlendState *CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) override final; virtual GPUShaderProgram *CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) override final; virtual GPUShaderProgram *CreateComputeProgram(ByteStream *pByteCodeStream) override final; // off-thread resource creation virtual void BeginResourceBatchUpload() override final; virtual void EndResourceBatchUpload() override final; // helper methods SDL_GLContext GetGLContext() { return m_pMainGLContext; } SDL_GLContext GetOffThreadGLContext(); void ReleaseOffThreadGLContext(); OpenGLGPUContext *GetImmediateContext() { return m_pImmediateContext; } void SetImmediateContext(OpenGLGPUContext *pContext) { m_pImmediateContext = pContext; } void BindMutatorTextureUnit(); void RestoreMutatorTextureUnit(); private: SDL_GLContext m_pMainGLContext; SDL_GLContext m_pOffThreadGLContext; Mutex m_offThreadGLContextLock; OpenGLGPUContext *m_pImmediateContext; OpenGLGPUOutputBuffer *m_pImplicitOutputBuffer; RENDERER_FEATURE_LEVEL m_featureLevel; TEXTURE_PLATFORM m_texturePlatform; PIXEL_FORMAT m_outputBackBufferFormat; PIXEL_FORMAT m_outputDepthStencilFormat; }; <file_sep>/Engine/Source/Core/ClassTableDataFormat.h #pragma once #include "Core/Common.h" #pragma pack(push, 4) #ifdef Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable:4200) // warning C4200: nonstandard extension used : zero-sized array in struct/union #pragma warning(disable:4510) // warning C4510: 'DF_PROPERTY_MAPPING_HEADER' : default constructor could not be generated #pragma warning(disable:4512) // warning C4512: 'DF_PROPERTY_MAPPING_HEADER' : assignment operator could not be generated #pragma warning(disable:4610) // warning C4610: struct 'DF_PROPERTY_MAPPING_HEADER' can never be instantiated - user defined constructor required #endif // Type serialization union DF_STRUCT_FLOAT2 { struct { float x; float y; }; float components[2]; }; union DF_STRUCT_FLOAT3 { struct { float x; float y; float z; }; float components[3]; }; union DF_STRUCT_FLOAT4 { struct { float x; float y; float z; float w; }; float components[4]; }; union DF_STRUCT_INT2 { struct { int32 x; int32 y; }; int32 components[2]; }; union DF_STRUCT_INT3 { struct { int32 x; int32 y; int32 z; }; int32 components[3]; }; union DF_STRUCT_INT4 { struct { int32 x; int32 y; int32 z; int32 w; }; int32 components[4]; }; union DF_STRUCT_UINT2 { struct { uint32 x; uint32 y; }; uint32 components[2]; }; union DF_STRUCT_UINT3 { struct { uint32 x; uint32 y; uint32 z; }; uint32 components[3]; }; union DF_STRUCT_UINT4 { struct { uint32 x; uint32 y; uint32 z; uint32 w; }; uint32 components[4]; }; union DF_STRUCT_QUATERNION { struct { float x; float y; float z; float w; }; float components[4]; }; struct DF_STRUCT_TRANSFORM { DF_STRUCT_FLOAT3 Position; DF_STRUCT_QUATERNION Rotation; DF_STRUCT_FLOAT3 Scale; }; // ----------------------------------------- object serialization ------------------------------------------ #define DF_CLASS_TABLE_HEADER_MAGIC 0xAB8123DF struct DF_CLASS_TABLE_HEADER { uint32 Magic; uint32 TotalSize; uint32 HeaderSize; uint32 TypeCount; }; struct DF_CLASS_TABLE_TYPE { uint32 TotalSize; uint32 PropertyCount; uint32 TypeNameLength; char TypeName[]; }; struct DF_CLASS_TABLE_TYPE_PROPERTY { uint32 PropertyType; uint32 PropertyNameLength; char PropertyName[]; }; struct DF_SERIALIZED_OBJECT_HEADER { uint32 TotalSize; uint32 TypeIndex; }; struct DF_SERIALIZED_OBJECT_PROPERTY { uint32 DataSize; byte Data[]; }; #ifdef Y_COMPILER_MSVC #pragma warning(pop) #endif #pragma pack(pop) <file_sep>/Engine/Source/ResourceCompiler/CMakeLists.txt set(HEADER_FILES BlockMeshGenerator.h BlockPaletteGenerator.h ClassTableGenerator.h CollisionShapeGenerator.h Common.h FontGenerator.h MaterialGenerator.h MaterialShaderGenerator.h ObjectTemplate.h ObjectTemplateManager.h ParticleSystemGenerator.h ResourceCompilerCallbacks.h ResourceCompiler.h ShaderCompilerD3D.h ShaderCompiler.h ShaderCompilerOpenGL.h ShaderGraphBuiltinNodes.h ShaderGraphCompiler.h ShaderGraphCompilerHLSL.h ShaderGraph.h ShaderGraphNode.h ShaderGraphNodeType.h ShaderGraphSchema.h SkeletalAnimationGenerator.h SkeletalMeshGenerator.h SkeletonGenerator.h StaticMeshGenerator.h TerrainLayerListGenerator.h TextureGenerator.h ) set(SOURCE_FILES BlockMeshGenerator.cpp BlockPaletteGenerator.cpp ClassTableGenerator.cpp CollisionShapeGenerator.cpp FontGenerator.cpp MaterialGenerator.cpp MaterialShaderGenerator.cpp ObjectTemplate.cpp ObjectTemplateManager.cpp ParticleSystemGenerator.cpp ResourceCompiler.cpp ResourceCompilerInterfaceIntegrated.cpp ResourceCompilerInterfaceRemoteServer.cpp ShaderCompiler.cpp ShaderCompilerD3D.cpp ShaderCompilerOpenGL.cpp ShaderGraphBuiltinNodes.cpp ShaderGraphCompiler.cpp ShaderGraphCompilerHLSL.cpp ShaderGraph.cpp ShaderGraphNode.cpp ShaderGraphNodeType.cpp ShaderGraphSchema.cpp SkeletalAnimationGenerator.cpp SkeletalMeshGenerator.cpp SkeletonGenerator.cpp StaticMeshGenerator.cpp TerrainLayerListGenerator.cpp TextureGenerator.cpp ) include_directories(${ENGINE_BASE_DIRECTORY}) set(EXTRA_LIBRARIES "") if(HAVE_HLSLTRANSLATOR) LIST(APPEND EXTRA_LIBRARIES HLSLTranslator) endif() add_library(EngineResourceCompiler STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineResourceCompiler ${EXTRA_LIBRARIES} EngineMain EngineCore) <file_sep>/Editor/Source/Editor/Defines.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Common.h" <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUBuffer.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUBuffer.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" Log_SetChannel(OpenGLRenderBackend); OpenGLGPUBuffer::OpenGLGPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, GLuint glBufferId, GLenum glBufferUsage) : GPUBuffer(pBufferDesc), m_glBufferId(glBufferId), m_glBufferUsage(glBufferUsage), m_pMappedContext(NULL), m_pMappedPointer(NULL) { } OpenGLGPUBuffer::~OpenGLGPUBuffer() { DebugAssert(m_pMappedContext == NULL); glDeleteBuffers(1, &m_glBufferId); } void OpenGLGPUBuffer::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = m_desc.Size; } void OpenGLGPUBuffer::SetDebugName(const char *debugName) { OpenGLHelpers::SetObjectDebugName(GL_BUFFER, m_glBufferId, debugName); } GPUBuffer *OpenGLGPUDevice::CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData /* = NULL */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; GL_CHECKED_SECTION_BEGIN(); GLuint bufferId = 0; glGenBuffers(1, &bufferId); if (bufferId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateBuffer: Buffer allocation failed."); return NULL; } GLenum bufferUsage; if (pDesc->Flags & GPU_BUFFER_FLAG_MAPPABLE) { bufferUsage = GL_DYNAMIC_DRAW; } else if (pDesc->Flags & (GPU_BUFFER_FLAG_READABLE | GPU_BUFFER_FLAG_WRITABLE)) { bufferUsage = GL_STREAM_DRAW; } else { DebugAssert(pInitialData != NULL); bufferUsage = GL_STATIC_DRAW; } // allocate buffer storage glBindBuffer(GL_ARRAY_BUFFER, bufferId); glBufferData(GL_ARRAY_BUFFER, pDesc->Size, pInitialData, bufferUsage); glBindBuffer(GL_ARRAY_BUFFER, 0); // check error state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateBuffer: One or more GL calls failed."); if (bufferId != 0) glDeleteBuffers(1, &bufferId); return NULL; } // create object return new OpenGLGPUBuffer(pDesc, bufferId, bufferUsage); } bool OpenGLGPUContext::ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) { OpenGLGPUBuffer *pOpenGLBuffer = static_cast<OpenGLGPUBuffer *>(pBuffer); DebugAssert((start + count) <= pOpenGLBuffer->GetDesc()->Size); DebugAssert(pOpenGLBuffer->GetMappedPointer() == NULL); GL_CHECKED_SECTION_BEGIN(); glBindBuffer(GL_ARRAY_BUFFER, pOpenGLBuffer->GetGLBufferId()); glGetBufferSubData(GL_ARRAY_BUFFER, start, count, pDestination); glBindBuffer(GL_ARRAY_BUFFER, 0); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("D3D11GPUContext::ReadBuffer: One or more GL calls failed."); return false; } return true; } bool OpenGLGPUContext::WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) { OpenGLGPUBuffer *pOpenGLBuffer = static_cast<OpenGLGPUBuffer *>(pBuffer); DebugAssert((start + count) <= pOpenGLBuffer->GetDesc()->Size); DebugAssert(pOpenGLBuffer->GetMappedPointer() == NULL); GL_CHECKED_SECTION_BEGIN(); if (GLAD_GL_EXT_direct_state_access) { glNamedBufferSubDataEXT(pOpenGLBuffer->GetGLBufferId(), start, count, pSource); } else { glBindBuffer(GL_ARRAY_BUFFER, pOpenGLBuffer->GetGLBufferId()); glBufferSubData(GL_ARRAY_BUFFER, start, count, pSource); glBindBuffer(GL_ARRAY_BUFFER, 0); } if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("D3D11GPUContext::ReadBuffer: One or more GL calls failed."); return false; } return true; } bool OpenGLGPUContext::MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) { OpenGLGPUBuffer *pOpenGLBuffer = static_cast<OpenGLGPUBuffer *>(pBuffer); DebugAssert(pOpenGLBuffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pOpenGLBuffer->GetMappedContext() == NULL && pOpenGLBuffer->GetMappedPointer() == NULL); GLbitfield access = 0; switch(mapType) { case GPU_MAP_TYPE_READ: access = GL_MAP_READ_BIT; break; case GPU_MAP_TYPE_READ_WRITE: access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break; case GPU_MAP_TYPE_WRITE: access = GL_MAP_WRITE_BIT; break; case GPU_MAP_TYPE_WRITE_DISCARD: access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; break; case GPU_MAP_TYPE_WRITE_NO_OVERWRITE: access = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; break; default: UnreachableCode(); break; } GL_CHECKED_SECTION_BEGIN(); void *pMappedPointer; if (GLAD_GL_EXT_direct_state_access) { pMappedPointer = glMapNamedBufferRangeEXT(pOpenGLBuffer->GetGLBufferId(), 0, pOpenGLBuffer->GetDesc()->Size, access); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUContext::Unmapbuffer: glMapNamedBufferRange failed: "); if (pMappedPointer != NULL) glUnmapNamedBufferEXT(pOpenGLBuffer->GetGLBufferId()); } } else { glBindBuffer(GL_ARRAY_BUFFER, pOpenGLBuffer->GetGLBufferId()); pMappedPointer = glMapBufferRange(GL_ARRAY_BUFFER, 0, pOpenGLBuffer->GetDesc()->Size, access); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUContext::MapBuffer: One or more GL calls failed."); if (pMappedPointer != NULL) glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return false; } glBindBuffer(GL_ARRAY_BUFFER, 0); } pOpenGLBuffer->SetMappedContextPointer(this, pMappedPointer); *ppPointer = pMappedPointer; return true; } void OpenGLGPUContext::Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) { OpenGLGPUBuffer *pOpenGLBuffer = static_cast<OpenGLGPUBuffer *>(pBuffer); DebugAssert(pOpenGLBuffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pOpenGLBuffer->GetMappedContext() == this && pOpenGLBuffer->GetMappedPointer() == pPointer); GL_CHECKED_SECTION_BEGIN(); if (GLAD_GL_EXT_direct_state_access) { if (glUnmapNamedBufferEXT(pOpenGLBuffer->GetGLBufferId()) != GL_TRUE) GL_PRINT_ERROR("OpenGLGPUContext::Unmapbuffer: glUnmapNamedBuffer failed: "); } else { glBindBuffer(GL_ARRAY_BUFFER, pOpenGLBuffer->GetGLBufferId()); GLboolean unmapResult = glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); if (unmapResult != GL_TRUE) GL_PRINT_ERROR("OpenGLGPUContext::Unmapbuffer: glUnmapBuffer failed: "); } pOpenGLBuffer->SetMappedContextPointer(NULL, NULL); } <file_sep>/Engine/Source/MathLib/SIMDVectorf_sse.h #pragma once #include "Core/Math.h" #include "Core/SIMD/Vector_shuffles.h" #include "Core/Memory.h" #include <intrin.h> #if Y_CPU_SSE_LEVEL < 1 #error SSE must be enabled. #endif struct Vector2f; struct Vector3f; struct Vector4f; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector2f { // constructors inline SIMDVector2f() {} inline SIMDVector2f(const float x_, const float y_) { m128 = _mm_set_ps(0.0f, 0.0f, y_, x_); } inline SIMDVector2f(const float *p) { m128 = _mm_set_ps(0.0f, 0.0f, p[1], p[0]); } inline SIMDVector2f(const SIMDVector2f &v) : m128(v.m128) {} inline SIMDVector2f(const Vector2i v) { m128 = _mm_set_ps(0.0f, 0.0f, (float)v.y, (float)v.x); } SIMDVector2f(const Vector2f &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(const float x_, const float y_) { m128 = _mm_set_ps(0.0f, 0.0f, y_, x_); } void Set(const SIMDVector2f v) { m128 = v.m128; } void Set(const Vector2f &v); void SetZero() { m128 = _mm_setzero_ps(); } // load/store void Load(const float *v) { m128 = _mm_set_ps(0.0f, 0.0f, v[1], v[0]); } void Store(float *v) const { v[0] = m128.m128_f32[0]; v[1] = m128.m128_f32[1]; v[2] = m128.m128_f32[2]; } // new vector inline SIMDVector2f operator+(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_add_ps(m128, v.m128); return r; } inline SIMDVector2f operator-(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_sub_ps(m128, v.m128); return r; } inline SIMDVector2f operator*(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_mul_ps(m128, v.m128); return r; } inline SIMDVector2f operator/(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_div_ps(m128, v.m128); return r; } inline SIMDVector2f operator%(const SIMDVector2f v) const { return SIMDVector2f(Y_fmodf(x, v.x), Y_fmodf(y, v.y)); } inline SIMDVector2f operator-() const { SIMDVector2f r; r.m128 = _mm_sub_ps(_mm_setzero_ps(), m128); return r; } // scalar operators inline SIMDVector2f operator+(const float v) const { SIMDVector2f r; r.m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector2f operator-(const float v) const { SIMDVector2f r; r.m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector2f operator*(const float v) const { SIMDVector2f r; r.m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector2f operator/(const float v) const { SIMDVector2f r; r.m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector2f operator%(const float v) const { return SIMDVector2f(Y_fmodf(x, v), Y_fmodf(y, v)); } // comparison operators inline bool operator==(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpeq_ps(m128, v.m128)) & 0x3) == 0x3; } inline bool operator!=(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpneq_ps(m128, v.m128)) & 0x3) != 0x0; } inline bool operator<=(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) & 0x3) == 0x3; } inline bool operator>=(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) & 0x3) == 0x3; } inline bool operator<(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) & 0x3) == 0x3; } inline bool operator>(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) & 0x3) == 0x3; } // modifies this vector inline SIMDVector2f &operator+=(const SIMDVector2f v) { m128 = _mm_add_ps(m128, v.m128); return *this; } inline SIMDVector2f &operator-=(const SIMDVector2f v) { m128 = _mm_sub_ps(m128, v.m128); return *this; } inline SIMDVector2f &operator*=(const SIMDVector2f v) { m128 = _mm_mul_ps(m128, v.m128); return *this; } inline SIMDVector2f &operator/=(const SIMDVector2f v) { m128 = _mm_div_ps(m128, v.m128); return *this; } inline SIMDVector2f &operator%=(const SIMDVector2f v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); return *this; } inline SIMDVector2f &operator=(const SIMDVector2f v) { m128 = v.m128; return *this; } SIMDVector2f &operator=(const Vector2f &v); // scalar operators inline SIMDVector2f &operator+=(const float v) { m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector2f &operator-=(const float v) { m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector2f &operator*=(const float v) { m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector2f &operator/=(const float v) { m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector2f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // to floatx const Vector2f &GetFloat2() const { return reinterpret_cast<const Vector2f &>(*this); } Vector2f &GetFloat2() { return reinterpret_cast<Vector2f &>(*this); } operator const Vector2f &() const { return reinterpret_cast<const Vector2f &>(*this); } operator Vector2f &() { return reinterpret_cast<Vector2f &>(*this); } // partial comparisons bool AnyLess(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) & 0x3) != 0x0; } bool AnyLessEqual(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) & 0x3) != 0x0; } bool AnyGreater(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) & 0x3) != 0x0; } bool AnyGreaterEqual(const SIMDVector2f v) const { return (_mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) & 0x3) != 0x0; } bool NearEqual(const SIMDVector2f v) const { return (*this - v).Abs() < Epsilon; } bool NearEqual(const SIMDVector2f v, const float fEpsilon) const { return (*this - v).Abs() < SIMDVector2f(fEpsilon, fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps SIMDVector2f Min(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_min_ps(m128, v.m128); return r; } SIMDVector2f Max(const SIMDVector2f v) const { SIMDVector2f r; r.m128 = _mm_max_ps(m128, v.m128); return r; } SIMDVector2f Clamp(const SIMDVector2f lBounds, const SIMDVector2f uBounds) const { SIMDVector2f r; r.m128 = _mm_max_ps(lBounds.m128, _mm_min_ps(uBounds.m128, m128)); return r; } SIMDVector2f Abs() const { SIMDVector2f r; r.m128 = _mm_max_ps(m128, _mm_sub_ps(_mm_setzero_ps(), m128)); return r; } SIMDVector2f Saturate() const { SIMDVector2f r; r.m128 = _mm_max_ps(One.m128, _mm_min_ps(_mm_setzero_ps(), m128)); return r; } // swap void Swap(SIMDVector2f v) { __m128 temp = m128; m128 = v.m128; v.m128 = temp; } // internal dot product, uses dp on sse4, hadd on sse3, shuffle+add on sse #if Y_CPU_SSE_LEVEL >= 4 inline __m128 __Dot(const SIMDVector2f v) const { return _mm_dp_ps(m128, v.m128, 0xC1); } #elif Y_CPU_SSE_LEVEL >= 3 __m128 __Dot(const SIMDVector2f v) const { __m128 tmp = _mm_mul_ps(m128, v.m128); tmp = _mm_hadd_ps(tmp, tmp); return tmp; } #else __m128 __Dot(const SIMDVector2f v) const { // wastes registers, can be optimized still, least the 3 shuffles can be executed in parallel __m128 m, tmp1; m = _mm_mul_ps(m128, v.m128); tmp1 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1)); return _mm_add_ss(m, tmp1); } #endif // actual dot product float Dot(const SIMDVector2f v) const { return _mm_cvtss_f32(__Dot(v)); } // lerp SIMDVector2f Lerp(const SIMDVector2f v, const float f) const { SIMDVector2f r; r.m128 = _mm_add_ps(m128, _mm_mul_ps(_mm_sub_ps(v.m128, m128), _mm_set_ps1(f))); return r; } // length inline float SquaredLength() const { return _mm_cvtss_f32(__Dot(*this)); } float Length() const { return _mm_cvtss_f32(_mm_sqrt_ss(__Dot(*this))); } // normalize SIMDVector2f Normalize() const { SIMDVector2f r; __m128 length = _mm_sqrt_ss(__Dot(*this)); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // fast normalize SIMDVector2f NormalizeEst() const { SIMDVector2f r; __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // in-place normalize void NormalizeInPlace() { __m128 length = _mm_sqrt_ss(__Dot(*this)); m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); } // fast normalize void NormalizeEstInPlace() { __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); } // safe normalize SIMDVector2f SafeNormalize() const { SIMDVector2f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } SIMDVector2f SafeNormalizeEst() const { SIMDVector2f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } void SafeNormalizeInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } void SafeNormalizeEstInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } // reciprocal SIMDVector2f Reciprocal() const { SIMDVector2f r; r.m128 = _mm_div_ps(One.m128, m128); return r; } // not sse yet SIMDVector2f Cross(const SIMDVector2f v) const { SIMDVector2f r; r.x = (x * v.y) - (y * v.x); r.y = (x * v.y) - (y * v.x); return r; } // shuffles - todo fix return types on these template<int V0, int V1> SIMDVector2f Shuffle2() const { SIMDVector2f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(0, 0, V1, V0)); return r; } VECTOR2_SHUFFLE_FUNCTIONS(SIMDVector2f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128 m128; struct { float x; float y; }; struct { float r; float g; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector2f &Zero, &One, &NegativeOne; static const SIMDVector2f &Infinite, &NegativeInfinite; static const SIMDVector2f &UnitX, &UnitY, &UnitZ, &UnitW, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ, &NegativeUnitW; static const SIMDVector2f &Epsilon; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector3f { // constructors inline SIMDVector3f() {} inline SIMDVector3f(const float x_, const float y_, const float z_) { m128 = _mm_set_ps(0.0f, z_, y_, x_); } inline SIMDVector3f(const float *p) { m128 = _mm_set_ps(0.0f, p[2], p[1], p[0]); } inline SIMDVector3f(const SIMDVector2f v, const float z_ = 0.0f) { m128 = _mm_set_ps(0.0f, z_, v.y, v.x); } inline SIMDVector3f(const SIMDVector3f &v) : m128(v.m128) {} inline SIMDVector3f(const Vector3i v) { m128 = _mm_set_ps(0.0f, (float)v.z, (float)v.y, (float)v.x); } SIMDVector3f(const Vector3f &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(const float x_, const float y_, const float z_) { m128 = _mm_set_ps(0.0f, z_, y_, x_); } void Set(const SIMDVector2f v, const float z_ = 0.0f) { m128 = _mm_set_ps(0.0f, z_, v.y, v.x); } void Set(const SIMDVector3f v) { m128 = v.m128; } void Set(const Vector3f &v); void SetZero() { m128 = _mm_setzero_ps(); } // load/store void Load(const float *v) { m128 = _mm_set_ps(0.0f, v[2], v[1], v[0]); } void Store(float *v) const { v[0] = m128.m128_f32[0]; v[1] = m128.m128_f32[1]; v[2] = m128.m128_f32[2]; v[3] = m128.m128_f32[3]; } // new vector inline SIMDVector3f operator+(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_add_ps(m128, v.m128); return r; } inline SIMDVector3f operator-(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_sub_ps(m128, v.m128); return r; } inline SIMDVector3f operator*(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_mul_ps(m128, v.m128); return r; } inline SIMDVector3f operator/(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_div_ps(m128, v.m128); return r; } inline SIMDVector3f operator%(const SIMDVector3f v) const { return SIMDVector3f(Y_fmodf(x, v.x), Y_fmodf(y, v.y), Y_fmodf(z, v.z)); } inline SIMDVector3f operator-() const { SIMDVector3f r; r.m128 = _mm_sub_ps(_mm_setzero_ps(), m128); return r; } // scalar operators inline SIMDVector3f operator+(const float v) const { SIMDVector3f r; r.m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector3f operator-(const float v) const { SIMDVector3f r; r.m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector3f operator*(const float v) const { SIMDVector3f r; r.m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector3f operator/(const float v) const { SIMDVector3f r; r.m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector3f operator%(const float v) const { return SIMDVector3f(Y_fmodf(x, v), Y_fmodf(y, v), Y_fmodf(z, v)); } // comparison operators inline bool operator==(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpeq_ps(m128, v.m128)) & 0x7) == 0x7; } inline bool operator!=(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpneq_ps(m128, v.m128)) & 0x7) != 0x0; } inline bool operator<=(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) & 0x7) == 0x7; } inline bool operator>=(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) & 0x7) == 0x7; } inline bool operator<(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) & 0x7) == 0x7; } inline bool operator>(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) & 0x7) == 0x7; } // modifies this vector inline SIMDVector3f &operator+=(const SIMDVector3f v) { m128 = _mm_add_ps(m128, v.m128); return *this; } inline SIMDVector3f &operator-=(const SIMDVector3f v) { m128 = _mm_sub_ps(m128, v.m128); return *this; } inline SIMDVector3f &operator*=(const SIMDVector3f v) { m128 = _mm_mul_ps(m128, v.m128); return *this; } inline SIMDVector3f &operator/=(const SIMDVector3f v) { m128 = _mm_div_ps(m128, v.m128); return *this; } inline SIMDVector3f &operator%=(const SIMDVector3f v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); z = Y_fmodf(z, v.z); return *this; } inline SIMDVector3f &operator=(const SIMDVector3f v) { m128 = v.m128; return *this; } SIMDVector3f &operator=(const Vector3f &v); // scalar operators inline SIMDVector3f &operator+=(const float v) { m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector3f &operator-=(const float v) { m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector3f &operator*=(const float v) { m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector3f &operator/=(const float v) { m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector3f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); z = Y_fmodf(z, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // to floatx const Vector3f &GetFloat3() const { return reinterpret_cast<const Vector3f &>(*this); } Vector3f &GetFloat3() { return reinterpret_cast<Vector3f &>(*this); } operator const Vector3f &() const { return reinterpret_cast<const Vector3f &>(*this); } operator Vector3f &() { return reinterpret_cast<Vector3f &>(*this); } // partial comparisons bool AnyLess(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) & 0x7) != 0x0; } bool AnyLessEqual(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) & 0x7) != 0x0; } bool AnyGreater(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) & 0x7) != 0x0; } bool AnyGreaterEqual(const SIMDVector3f v) const { return (_mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) & 0x7) != 0x0; } bool NearEqual(const SIMDVector3f v) const { return (*this - v).Abs() < Epsilon; } bool NearEqual(const SIMDVector3f v, const float fEpsilon) const { return (*this - v).Abs() < SIMDVector3f(fEpsilon, fEpsilon, fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps SIMDVector3f Min(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_min_ps(m128, v.m128); return r; } SIMDVector3f Max(const SIMDVector3f v) const { SIMDVector3f r; r.m128 = _mm_max_ps(m128, v.m128); return r; } SIMDVector3f Clamp(const SIMDVector3f lBounds, const SIMDVector3f uBounds) const { SIMDVector3f r; r.m128 = _mm_max_ps(lBounds.m128, _mm_min_ps(uBounds.m128, m128)); return r; } SIMDVector3f Abs() const { SIMDVector3f r; r.m128 = _mm_max_ps(m128, _mm_sub_ps(_mm_setzero_ps(), m128)); return r; } SIMDVector3f Saturate() const { static const __m128 ones = _mm_set_ps1(1.0f); SIMDVector3f r; r.m128 = _mm_max_ps(ones, _mm_min_ps(_mm_setzero_ps(), m128)); return r; } // swap void Swap(SIMDVector3f v) { __m128 temp = m128; m128 = v.m128; v.m128 = temp; } // internal dot product, uses dp on sse4, hadd on sse3, shuffle+add on sse #if Y_CPU_SSE_LEVEL >= 4 inline __m128 __Dot(const SIMDVector3f v) const { return _mm_dp_ps(m128, v.m128, 0xF1); } #elif Y_CPU_SSE_LEVEL >= 3 __m128 __Dot(const SIMDVector3f v) const { __m128 tmp = _mm_mul_ps(m128, v.m128); // w1*w2, z1*z2, y1*y2, x1*x2 tmp = _mm_hadd_ps(tmp, tmp); // w1*w2+z1*z2, y1*y2+x1*x2, w1*w2+z1*z2, y1*y2+x1*x2 tmp = _mm_hadd_ps(tmp, tmp); // w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2 return tmp; } #else __m128 __Dot(const SIMDVector3f v) const { // wastes registers, can be optimized still, least the 3 shuffles can be executed in parallel __m128 m, tmp1, tmp2; m = _mm_mul_ps(m128, v.m128); tmp1 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1)); tmp2 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2)); return _mm_add_ss(m, _mm_add_ss(tmp1, tmp2)); } #endif // actual dot product float Dot(const SIMDVector3f v) const { return _mm_cvtss_f32(__Dot(v)); } // lerp SIMDVector3f Lerp(const SIMDVector3f v, const float f) const { SIMDVector3f r; r.m128 = _mm_add_ps(m128, _mm_mul_ps(_mm_sub_ps(v.m128, m128), _mm_set_ps1(f))); return r; } // length inline float SquaredLength() const { return _mm_cvtss_f32(__Dot(*this)); } float Length() const { return _mm_cvtss_f32(_mm_sqrt_ss(__Dot(*this))); } // normalize SIMDVector3f Normalize() const { SIMDVector3f r; __m128 length = _mm_sqrt_ss(__Dot(*this)); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // fast normalize SIMDVector3f NormalizeEst() const { SIMDVector3f r; __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // in-place normalize void NormalizeInPlace() { __m128 length = _mm_sqrt_ss(__Dot(*this)); m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); } // fast normalize void NormalizeEstInPlace() { __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); } // safe normalize SIMDVector3f SafeNormalize() const { SIMDVector3f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } SIMDVector3f SafeNormalizeEst() const { SIMDVector3f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } void SafeNormalizeInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } void SafeNormalizeEstInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } // reciprocal SIMDVector3f Reciprocal() const { SIMDVector3f r; r.m128 = _mm_div_ps(One.m128, m128); return r; } // not sse yet SIMDVector3f Cross(const SIMDVector3f &v) const { SIMDVector3f r; r.x = (y * v.z) - (z * v.y); r.y = (z * v.x) - (x * v.z); r.z = (x * v.y) - (y * v.x); return r; } // shuffles - todo fix return types on these template<int V0, int V1> SIMDVector2f Shuffle2() const { SIMDVector2f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(0, 0, V1, V0)); return r; } template<int V0, int V1, int V2> SIMDVector3f Shuffle3() const { SIMDVector3f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(0, V2, V1, V0)); return r; } VECTOR3_SHUFFLE_FUNCTIONS(SIMDVector2f, SIMDVector3f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128 m128; struct { float x; float y; float z; }; struct { float r; float g; float b; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector3f &Zero, &One, &NegativeOne; static const SIMDVector3f &Infinite, &NegativeInfinite; static const SIMDVector3f &UnitX, &UnitY, &UnitZ, &UnitW, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ, &NegativeUnitW; static const SIMDVector3f &Epsilon; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ALIGN_DECL(Y_SSE_ALIGNMENT) struct SIMDVector4f { // constructors inline SIMDVector4f() {} inline SIMDVector4f(const float x_, const float y_, const float z_, const float w_) { m128 = _mm_set_ps(w_, z_, y_, x_); } inline SIMDVector4f(const float *p) { m128 = _mm_loadu_ps(p); } inline SIMDVector4f(const SIMDVector2f &v, const float z_ = 0.0f, const float w_ = 0.0f) { m128 = _mm_set_ps(w_, z_, v.y, v.x); } inline SIMDVector4f(const SIMDVector3f &v, const float w_ = 0.0f) { m128 = _mm_set_ps(w_, v.z, v.y, v.x); } inline SIMDVector4f(const SIMDVector4f &v) : m128(v.m128) {} inline SIMDVector4f(const Vector4i &v) { m128 = _mm_set_ps((float)v.w, (float)v.z, (float)v.y, (float)v.x); } SIMDVector4f(const Vector4f &v); // new/delete, we overload these so that vectors allocated on the heap are guaranteed to be aligned correctly void *operator new[](size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void *operator new(size_t c) { return Y_aligned_malloc(c, Y_SSE_ALIGNMENT); } void operator delete[](void *pMemory) { return Y_aligned_free(pMemory); } void operator delete(void *pMemory) { return Y_aligned_free(pMemory); } // setters void Set(const float x_, const float y_, const float z_, const float w_) { m128 = _mm_set_ps(w_, z_, y_, x_); } void Set(const SIMDVector2f &v, const float z_ = 0.0f, const float w_ = 0.0f) { m128 = _mm_set_ps(w_, z_, v.y, v.x); } void Set(const SIMDVector3f &v, const float w_ = 0.0f) { m128 = _mm_set_ps(w_, v.z, v.y, v.x); } void Set(const SIMDVector4f &v) { m128 = v.m128; } void Set(const Vector4f &v); void SetZero() { m128 = _mm_setzero_ps(); } // load/store void Load(const float *v) { m128 = _mm_loadu_ps(v); } void Store(float *v) const { _mm_storeu_ps(v, m128); } // new vector inline SIMDVector4f operator+(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_add_ps(m128, v.m128); return r; } inline SIMDVector4f operator-(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_sub_ps(m128, v.m128); return r; } inline SIMDVector4f operator*(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_mul_ps(m128, v.m128); return r; } inline SIMDVector4f operator/(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_div_ps(m128, v.m128); return r; } inline SIMDVector4f operator%(const SIMDVector4f &v) const { return SIMDVector4f(Y_fmodf(x, v.x), Y_fmodf(y, v.y), Y_fmodf(z, v.z), Y_fmodf(w, v.w)); } inline SIMDVector4f operator-() const { SIMDVector4f r; r.m128 = _mm_sub_ps(_mm_setzero_ps(), m128); return r; } // scalar operators inline SIMDVector4f operator+(const float v) const { SIMDVector4f r; r.m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector4f operator-(const float v) const { SIMDVector4f r; r.m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector4f operator*(const float v) const { SIMDVector4f r; r.m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector4f operator/(const float v) const { SIMDVector4f r; r.m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return r; } inline SIMDVector4f operator%(const float v) const { return SIMDVector4f(Y_fmodf(x, v), Y_fmodf(y, v), Y_fmodf(z, v), Y_fmodf(w, v)); } // comparison operators inline bool operator==(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpeq_ps(m128, v.m128)) == 0xF; } inline bool operator!=(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpneq_ps(m128, v.m128)) != 0x0; } inline bool operator<=(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) == 0xF; } inline bool operator>=(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) == 0xF; } inline bool operator<(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) == 0xF; } inline bool operator>(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) == 0xF; } // modifies this vector inline SIMDVector4f &operator+=(const SIMDVector4f &v) { m128 = _mm_add_ps(m128, v.m128); return *this; } inline SIMDVector4f &operator-=(const SIMDVector4f &v) { m128 = _mm_sub_ps(m128, v.m128); return *this; } inline SIMDVector4f &operator*=(const SIMDVector4f &v) { m128 = _mm_mul_ps(m128, v.m128); return *this; } inline SIMDVector4f &operator/=(const SIMDVector4f &v) { m128 = _mm_div_ps(m128, v.m128); return *this; } inline SIMDVector4f &operator%=(const SIMDVector4f &v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); z = Y_fmodf(z, v.z); w = Y_fmodf(w, v.w); return *this; } inline SIMDVector4f &operator=(const SIMDVector4f &v) { m128 = v.m128; return *this; } SIMDVector4f &operator=(const Vector4f &v); // scalar operators inline SIMDVector4f &operator+=(const float v) { m128 = _mm_add_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector4f &operator-=(const float v) { m128 = _mm_sub_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector4f &operator*=(const float v) { m128 = _mm_mul_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector4f &operator/=(const float v) { m128 = _mm_div_ps(m128, _mm_set_ps1(v)); return *this; } inline SIMDVector4f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); z = Y_fmodf(z, v); w = Y_fmodf(w, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // to floatx const Vector4f &GetFloat4() const { return reinterpret_cast<const Vector4f &>(*this); } Vector4f &GetFloat4() { return reinterpret_cast<Vector4f &>(*this); } operator const Vector4f &() const { return reinterpret_cast<const Vector4f &>(*this); } operator Vector4f &() { return reinterpret_cast<Vector4f &>(*this); } // partial comparisons bool AnyLess(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmplt_ps(m128, v.m128)) != 0x00; } bool AnyLessEqual(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmple_ps(m128, v.m128)) != 0x00; } bool AnyGreater(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpgt_ps(m128, v.m128)) != 0x00; } bool AnyGreaterEqual(const SIMDVector4f &v) const { return _mm_movemask_ps(_mm_cmpge_ps(m128, v.m128)) != 0x00; } bool NearEqual(const SIMDVector4f &v) const { return (*this - v).Abs() < Epsilon; } bool NearEqual(const SIMDVector4f &v, const float &fEpsilon) const { SIMDVector4f tmp = (*this - v).Abs(); return (tmp.x <= fEpsilon && tmp.y <= fEpsilon && tmp.z <= fEpsilon && tmp.w <= fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps SIMDVector4f Min(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_min_ps(m128, v.m128); return r; } SIMDVector4f Max(const SIMDVector4f &v) const { SIMDVector4f r; r.m128 = _mm_max_ps(m128, v.m128); return r; } SIMDVector4f Clamp(const SIMDVector4f &lBounds, const SIMDVector4f &uBounds) const { SIMDVector4f r; r.m128 = _mm_max_ps(lBounds.m128, _mm_min_ps(uBounds.m128, m128)); return r; } SIMDVector4f Abs() const { SIMDVector4f r; r.m128 = _mm_max_ps(m128, _mm_sub_ps(_mm_setzero_ps(), m128)); return r; } SIMDVector4f Saturate() const { static const __m128 ones = _mm_set_ps1(1.0f); SIMDVector4f r; r.m128 = _mm_max_ps(ones, _mm_min_ps(_mm_setzero_ps(), m128)); return r; } // swap void Swap(SIMDVector4f &v) { __m128 temp = m128; m128 = v.m128; v.m128 = temp; } // internal dot product, uses dp on sse4, hadd on sse3, shuffle+add on sse #if Y_CPU_SSE_LEVEL >= 4 inline __m128 __Dot(const SIMDVector4f &v) const { return _mm_dp_ps(m128, v.m128, 0xF1); } #elif Y_CPU_SSE_LEVEL >= 3 __m128 __Dot(const SIMDVector4f &v) const { __m128 tmp = _mm_mul_ps(m128, v.m128); // w1*w2, z1*z2, y1*y2, x1*x2 tmp = _mm_hadd_ps(tmp, tmp); // w1*w2+z1*z2, y1*y2+x1*x2, w1*w2+z1*z2, y1*y2+x1*x2 tmp = _mm_hadd_ps(tmp, tmp); // w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2, w1*w2+z1*z2+y1*y2+x1*x2 return tmp; } #else __m128 __Dot(const SIMDVector4f &v) const { // wastes registers, can be optimized still, least the 3 shuffles can be executed in parallel //__m128 m, tmp1, tmp2, tmp3; //m = _mm_mul_ps(m128, v.m128); //tmp1 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1)); //tmp2 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2)); //tmp3 = _mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3)); //return _mm_add_ss(m, _mm_add_ss(tmp1, _mm_add_ss(tmp2, tmp3))); __m128 m, tmp1; m = _mm_mul_ps(m128, v.m128); tmp1 = _mm_movehl_ps(m, m); tmp1 = _mm_add_ps(tmp1, m); m = _mm_shuffle_ps(m, tmp1, _MM_SHUFFLE(0, 0, 0, 1)); return _mm_add_ss(m, tmp1); } #endif // actual dot product float Dot(const SIMDVector4f &v) const { return _mm_cvtss_f32(__Dot(v)); } // lerp SIMDVector4f Lerp(const SIMDVector4f &v, const float f) const { SIMDVector4f r; r.m128 = _mm_add_ps(m128, _mm_mul_ps(_mm_sub_ps(v.m128, m128), _mm_set_ps1(f))); return r; } // length inline float SquaredLength() const { return _mm_cvtss_f32(__Dot(*this)); } float Length() const { return _mm_cvtss_f32(_mm_sqrt_ss(__Dot(*this))); } // normalize SIMDVector4f Normalize() const { SIMDVector4f r; __m128 length = _mm_sqrt_ss(__Dot(*this)); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // fast normalize SIMDVector4f NormalizeEst() const { SIMDVector4f r; __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); return r; } // in-place normalize void NormalizeInPlace() { __m128 length = _mm_sqrt_ss(__Dot(*this)); m128 = _mm_div_ps(m128, _mm_shuffle_ps(length, length, _MM_SHUFFLE(0, 0, 0, 0))); } // fast normalize void NormalizeEstInPlace() { __m128 invLength = _mm_rsqrt_ss(__Dot(*this)); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(invLength, invLength, _MM_SHUFFLE(0, 0, 0, 0))); } // safe normalize SIMDVector4f SafeNormalize() const { SIMDVector4f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); r.m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } SIMDVector4f SafeNormalizeEst() const { SIMDVector4f r; __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); r.m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } else { r.m128 = m128; } return r; } void SafeNormalizeInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_sqrt_ss(len); m128 = _mm_div_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } void SafeNormalizeEstInPlace() { __m128 len = __Dot(*this); if ((_mm_movemask_ps(_mm_cmpneq_ss(len, Zero.m128)) & 0x1)) { len = _mm_rsqrt_ss(len); m128 = _mm_mul_ps(m128, _mm_shuffle_ps(len, len, _MM_SHUFFLE(0, 0, 0, 0))); } } // reciprocal SIMDVector4f Reciprocal() const { SIMDVector4f r; r.m128 = _mm_div_ps(One.m128, m128); return r; } // not sse yet SIMDVector4f Cross(const SIMDVector4f &v1, const SIMDVector4f &v2) const { SIMDVector4f r; r.x = (((v1.z * v2.w) - (v1.w * v2.z)) * y) - (((v1.y * v2.w) - (v1.w * v2.y)) * z) + (((v1.y * v2.z) - (v1.z * v2.y)) * w); r.y = (((v1.w * v2.z) - (v1.z * v2.w)) * x) - (((v1.w * v2.x) - (v1.x * v2.w)) * z) + (((v1.z * v2.x) - (v1.x * v2.z)) * w); r.z = (((v1.y * v2.w) - (v1.w * v2.y)) * x) - (((v1.x * v2.w) - (v1.w * v2.x)) * y) + (((v1.x * v2.y) - (v1.y * v2.x)) * w); r.w = (((v1.z * v2.y) - (v1.y * v2.z)) * x) - (((v1.z * v2.x) - (v1.x * v2.z)) * y) + (((v1.y * v2.x) - (v1.x * v2.y)) * z); return r; } // shuffles - todo fix return types on these template<int V0, int V1> SIMDVector2f Shuffle2() const { SIMDVector2f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(0, 0, V1, V0)); return r; } template<int V0, int V1, int V2> SIMDVector3f Shuffle3() const { SIMDVector3f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(0, V2, V1, V0)); return r; } template<int V0, int V1, int V2, int V3> SIMDVector4f Shuffle4() const { SIMDVector4f r; r.m128 = _mm_shuffle_ps(m128, m128, _MM_SHUFFLE(V3, V2, V1, V0)); return r; } VECTOR4_SHUFFLE_FUNCTIONS(SIMDVector2f, SIMDVector3f, SIMDVector4f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { __m128 m128; struct { float x; float y; float z; float w; }; struct { float r; float g; float b; float a; }; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector4f &Zero, &One, &NegativeOne; static const SIMDVector4f &Infinite, &NegativeInfinite; static const SIMDVector4f &UnitX, &UnitY, &UnitZ, &UnitW, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ, &NegativeUnitW; static const SIMDVector4f &Epsilon; }; <file_sep>/Engine/Source/Core/Image.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Log.h" Log_SetChannel(Image); namespace NameTables { Y_Define_NameTable(ImageResizeFilter) Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_BOX, "Box") Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_BILINEAR, "Bilinear") Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_BICUBIC, "Bicubic") Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_BSPLINE, "BSpline") Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_CATMULLROM, "Catmullrom") Y_NameTable_VEntry(IMAGE_RESIZE_FILTER_LANCZOS3, "Lanczos3") Y_NameTable_End() } Image::Image() { m_ePixelFormat = PIXEL_FORMAT_UNKNOWN; m_uWidth = 0; m_uHeight = 0; m_uDepth = 0; m_pData = NULL; m_uDataSize = 0; m_uDataRowPitch = 0; m_uDataSlicePitch = 0; } Image::Image(const Image &copy) : Image() { Copy(copy); } Image::~Image() { if (m_pData != NULL) Delete(); } Image &Image::operator=(const Image &copy) { Delete(); Copy(copy); return *this; } void Image::Create(PIXEL_FORMAT PixelFormat, uint32 uWidth, uint32 uHeight, uint32 uDepth) { if (m_pData != NULL) Delete(); DebugAssert(uWidth > 0 && uHeight > 0); uint32 uRowPitch = PixelFormat_CalculateRowPitch(PixelFormat, uWidth); uint32 uSlicePitch = PixelFormat_CalculateSlicePitch(PixelFormat, uWidth, uHeight); uint32 uImageSize = PixelFormat_CalculateImageSize(PixelFormat, uWidth, uHeight, uDepth); DebugAssert(uImageSize > 0 && uRowPitch > 0 && uSlicePitch > 0); // Allocate the bytes for the image. m_pData = (byte *)Y_malloc(uImageSize); m_uDataSize = uImageSize; m_uDataRowPitch = uRowPitch; m_uDataSlicePitch = uSlicePitch; m_ePixelFormat = PixelFormat; m_uWidth = uWidth; m_uHeight = uHeight; m_uDepth = uDepth; } void Image::Copy(const Image &rCopy) { if (!rCopy.IsValidImage()) { Delete(); return; } if (!IsValidImage() || m_uWidth != rCopy.m_uWidth || m_uHeight != rCopy.m_uHeight || m_uDepth != rCopy.m_uDepth || m_ePixelFormat != rCopy.m_ePixelFormat) { Create(rCopy.GetPixelFormat(), rCopy.GetWidth(), rCopy.GetHeight(), rCopy.GetDepth()); } DebugAssert(m_uDataRowPitch == rCopy.m_uDataRowPitch); DebugAssert(m_uDataSlicePitch == rCopy.m_uDataSlicePitch); DebugAssert(m_uDataSize == rCopy.m_uDataSize); // Copy the data across. Y_memcpy(m_pData, rCopy.m_pData, rCopy.m_uDataSize); } bool Image::IsValidImage() const { if (m_uWidth == 0 || m_uHeight == 0 || m_uDepth == 0) return false; const PIXEL_FORMAT_INFO *pPFInfo; if (m_ePixelFormat == PIXEL_FORMAT_UNKNOWN || ((pPFInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat)) == NULL) || !pPFInfo->IsImageFormat) { return false; } return true; } void Image::Delete() { if (m_pData != NULL) { m_uWidth = m_uHeight = m_uDepth = 0; Y_free(m_pData); m_pData = NULL; m_uDataSize = 0; m_uDataRowPitch = 0; m_uDataSlicePitch = 0; } } bool Image::ConvertPixelFormat(PIXEL_FORMAT NewFormat) { if (!IsValidImage() || NewFormat == PIXEL_FORMAT_UNKNOWN || m_uDepth != 1) return false; if (NewFormat != m_ePixelFormat) { const PIXEL_FORMAT_INFO *pOldFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); const PIXEL_FORMAT_INFO *pNewFormatInfo = PixelFormat_GetPixelFormatInfo(NewFormat); uint32 newFormatRowPitch = PixelFormat_CalculateRowPitch(NewFormat, m_uWidth); uint32 newFormatSlicePitch = PixelFormat_CalculateSlicePitch(NewFormat, m_uWidth, m_uHeight); uint32 newFormatSize = PixelFormat_CalculateImageSize(NewFormat, m_uWidth, m_uHeight, m_uDepth); DebugAssert(newFormatSize > 0 && newFormatRowPitch > 0); byte *pNewData = (byte *)Y_malloc(newFormatSize); if (!PixelFormat_ConvertPixels(m_uWidth, m_uHeight, m_pData, m_uDataRowPitch, m_ePixelFormat, pNewData, newFormatRowPitch, NewFormat, &newFormatSize)) { Log_ErrorPrintf("Could not convert image from %s to %s, PixelFormat_ConvertPixels returned false.", pOldFormatInfo->Name, pNewFormatInfo->Name); Y_free(pNewData); return false; } Y_free(m_pData); m_pData = pNewData; m_uDataSize = newFormatSize; m_uDataRowPitch = newFormatRowPitch; m_uDataSlicePitch = newFormatSlicePitch; m_ePixelFormat = NewFormat; } return true; } bool Image::CopyAndConvertPixelFormat(const Image &rCopy, PIXEL_FORMAT NewFormat) { // todo: optimize me Image tempImage; tempImage.Copy(rCopy); if (!tempImage.ConvertPixelFormat(NewFormat)) return false; Copy(tempImage); return true; } bool Image::CopyAndResize(const Image &rCopy, IMAGE_RESIZE_FILTER resizeFilter, uint32 newWidth, uint32 newHeight, uint32 newDepth) { // todo: optimize me Image tempImage; tempImage.Copy(rCopy); if (!tempImage.Resize(resizeFilter, newWidth, newHeight, newDepth)) return false; Copy(tempImage); return true; } #ifdef HAVE_FREEIMAGE extern bool __ImageCodecFreeImage_ResizeImage(IMAGE_RESIZE_FILTER resizeFilter, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 newWidth, uint32 newHeight, const byte *pInImageData, byte *pOutImageData); #endif bool Image::Resize(IMAGE_RESIZE_FILTER resizeFilter, uint32 newWidth, uint32 newHeight, uint32 newDepth) { #ifdef HAVE_FREEIMAGE DebugAssert(m_uDepth == 1); DebugAssert(IsValidImage()); Image tempImage; tempImage.Create(m_ePixelFormat, newWidth, newHeight, newDepth); //if (!__ImageCodecDevIL_ResizeImage(resizeFilter, m_ePixelFormat, m_uWidth, m_uHeight, newWidth, newHeight, m_pData, tempImage.GetData())) if (!__ImageCodecFreeImage_ResizeImage(resizeFilter, m_ePixelFormat, m_uWidth, m_uHeight, newWidth, newHeight, m_pData, tempImage.GetData())) return false; Copy(tempImage); return true; #else Log_ErrorPrintf("Image::Resize: Not compiled with FreeImage support."); return false; #endif } bool Image::Blit(uint32 dx, uint32 dy, const Image &sourceImage, uint32 sx, uint32 sy, uint32 width, uint32 height) { DebugAssert(sourceImage.IsValidImage()); if (sourceImage.GetPixelFormat() != m_ePixelFormat || (dx + width) > m_uWidth || (dy + height) > m_uHeight || (sx + width) > sourceImage.GetWidth() || (sy + height) > sourceImage.GetHeight()) { return false; } // can't blit compressed formats, or non-byte-aligned formats const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->IsBlockCompressed || (pPixelFormatInfo->BitsPerPixel % 8) != 0) return false; // calculate bytes per pixel uint32 bytesPerPixel = pPixelFormatInfo->BitsPerPixel / 8; // work out the pointer to the first pixel we are copying from const byte *pSourcePointer = sourceImage.GetData() + (sy * sourceImage.GetDataRowPitch()) + sx * bytesPerPixel; // work out the pointer to the first pixel we are copying to byte *pDestinationPointer = m_pData + (dy * m_uDataRowPitch) + dx * bytesPerPixel; // blit each row uint32 i; for (i = 0; i < height; i++) { DebugAssert(((pSourcePointer + width * bytesPerPixel) - sourceImage.GetData()) <= (ptrdiff_t)sourceImage.GetDataSize()); DebugAssert(((pDestinationPointer + width * bytesPerPixel) - m_pData) <= (ptrdiff_t)m_uDataSize); Y_memcpy(pDestinationPointer, pSourcePointer, width * bytesPerPixel); pSourcePointer += sourceImage.GetDataRowPitch(); pDestinationPointer += m_uDataRowPitch; } return true; } // bool Image::Pad(uint32 top, uint32 right, uint32 bottom, uint32 left, float r /* = 1.0f */, float g /* = 1.0f */, float b /* = 1.0f */, float a /* = 1.0f */) // { // // } // // bool Image::Clip(uint32 startX, uint32 startY, uint32 endX, uint32 endY) // { // // } bool Image::ReadPixels(void *pBuffer, uint32 cbBuffer, uint32 x, uint32 y, uint32 width, uint32 height) const { DebugAssert(IsValidImage()); const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->IsBlockCompressed || (pPixelFormatInfo->BitsPerPixel % 8) != 0) return false; // work out each (copied) row length const uint32 bytesPerPixel = pPixelFormatInfo->BitsPerPixel / 8; const uint32 rowOffset = bytesPerPixel * x; const uint32 rowLength = bytesPerPixel * width; // check size if ((rowLength * height) > cbBuffer) return false; // get base pointer const byte *pSourcePointer = m_pData + (y * m_uDataRowPitch) + rowOffset; byte *pDestinationPointer = (byte *)pBuffer; // copy rows uint32 i; for (i = 0; i < height; i++) { Y_memcpy(pDestinationPointer, pSourcePointer, rowLength); pSourcePointer += m_uDataRowPitch; pDestinationPointer += rowLength; } return true; } bool Image::WritePixels(const void *pBuffer, uint32 cbBuffer, uint32 x, uint32 y, uint32 width, uint32 height) { DebugAssert(IsValidImage()); const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->IsBlockCompressed || (pPixelFormatInfo->BitsPerPixel % 8) != 0) return false; // work out each (copied) row length const uint32 bytesPerPixel = pPixelFormatInfo->BitsPerPixel / 8; const uint32 rowOffset = bytesPerPixel * x; const uint32 rowLength = bytesPerPixel * width; // check size if ((rowLength * height) > cbBuffer) return false; // get base pointer const byte *pSourcePointer = (const byte *)pBuffer; byte *pDestinationPointer = m_pData + (y * m_uDataRowPitch) + rowOffset; // copy rows uint32 i; for (i = 0; i < height; i++) { Y_memcpy(pDestinationPointer, pSourcePointer, rowLength); pSourcePointer += m_uDataRowPitch; pDestinationPointer += rowLength; } return true; } bool Image::FlipVertical() { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->IsBlockCompressed || m_uDepth != 1) return false; uint32 flipCount = m_uHeight / 2; for (uint32 flipRow = 0; flipRow < flipCount; flipRow++) { uint32 row1 = flipRow; uint32 row2 = m_uHeight - 1 - flipRow; if (row1 == row2) continue; byte *pRow1 = m_pData + (row1 * m_uDataRowPitch); byte *pRow2 = m_pData + (row2 * m_uDataRowPitch); for (uint32 flipColumn = 0; flipColumn < m_uWidth; flipColumn++) Swap(pRow1[flipColumn], pRow2[flipColumn]); } return true; } bool Image::FlipHorizontal() { const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); if (pPixelFormatInfo->IsBlockCompressed || m_uDepth != 1) return false; // fixme Panic("fixme"); return false; } bool Image::SetPixelFormatWithoutConversion(PIXEL_FORMAT newFormat) { const PIXEL_FORMAT_INFO *pOldPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); const PIXEL_FORMAT_INFO *pNewPixelFormatInfo = PixelFormat_GetPixelFormatInfo(newFormat); if (pOldPixelFormatInfo->IsBlockCompressed != pNewPixelFormatInfo->IsBlockCompressed || pOldPixelFormatInfo->BytesPerBlock != pNewPixelFormatInfo->BytesPerBlock || pOldPixelFormatInfo->BlockSize != pNewPixelFormatInfo->BlockSize || pOldPixelFormatInfo->BitsPerPixel != pNewPixelFormatInfo->BitsPerPixel) { return false; } // simply change the format DebugAssert(PixelFormat_CalculateImageSize(m_ePixelFormat, m_uWidth, m_uHeight, m_uDepth) == PixelFormat_CalculateImageSize(newFormat, m_uWidth, m_uHeight, m_uDepth)); m_ePixelFormat = newFormat; return true; } <file_sep>/Editor/Source/Editor/EditorResourcePreviewWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorResourcePreviewWidget.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorLightSimulator.h" #include "Engine/ResourceManager.h" #include "Engine/Material.h" #include "Engine/MaterialShader.h" #include "Engine/Texture.h" #include "Engine/StaticMesh.h" #include "Engine/BlockMesh.h" #include "Engine/Font.h" #include "Renderer/Renderer.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" Log_SetChannel(EditorResourcePreviewWidget); EditorResourcePreviewWidget::EditorResourcePreviewWidget(QWidget *pParent /* = NULL */) : QWidget(pParent), m_ui(new Ui_EditorResourcePreviewWidget()), m_renderMode(EDITOR_RENDER_MODE_FULLBRIGHT), m_viewportFlags(0), m_ePreviewType(PREVIEW_TYPE_NONE), m_bRedrawPending(true), m_renderTargetWidth(1), m_renderTargetHeight(1), m_bHardwareResourcesCreated(false), m_pSwapChain(nullptr), m_pWorldRenderer(nullptr), m_fZoomScale(1.0f), m_pOverlayTextFont(nullptr), m_pRenderWorld(nullptr), m_pResourceRenderProxy(nullptr), m_pLightSimulator(nullptr), m_eCurrentState(STATE_NONE), m_iStateData(0), m_LastMousePosition(int2::Zero) { m_Resource.asResource = NULL; // create ui m_ui->CreateUI(this); m_ui->UpdateUIForRenderMode(m_renderMode); m_ui->UpdateUIForViewportFlags(m_viewportFlags); ConnectUIEvents(); // setup camera ResetCamera(); // create world, and light entity m_pRenderWorld = new RenderWorld(); m_pLightSimulator = new EditorLightSimulator(0, m_pRenderWorld); m_pLightSimulator->SetShowIndicator(false); // add to tick manager connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); } EditorResourcePreviewWidget::~EditorResourcePreviewWidget() { ClearPreview(); delete m_pLightSimulator; m_pRenderWorld->Release(); SAFE_RELEASE(m_pResourceRenderProxy); SAFE_RELEASE(m_pOverlayTextFont); ReleaseGPUResources(); } void EditorResourcePreviewWidget::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } m_renderMode = renderMode; m_ui->UpdateUIForRenderMode(renderMode); delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_viewParameters.Viewport.Width, m_viewParameters.Viewport.Height); FlagForRedraw(); } void EditorResourcePreviewWidget::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorResourcePreviewWidget::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } bool EditorResourcePreviewWidget::CreateGPUResources() { if (m_bHardwareResourcesCreated) return true; Log_DevPrintf("Creating hardware resources for preview widget (%u x %u)", m_renderTargetWidth, m_renderTargetHeight); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == NULL) return false; m_pSwapChain->AddRef(); } // create render context if (m_pWorldRenderer == NULL) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_viewParameters.Viewport.Width, m_viewParameters.Viewport.Height); // update gui context, camera m_ArcBallCamera.SetPerspectiveAspect((float)m_renderTargetWidth, (float)m_renderTargetHeight); m_guiContext.SetViewportDimensions(m_renderTargetWidth, m_renderTargetHeight); m_guiContext.SetGPUContext(g_pRenderer->GetGPUContext()); m_viewParameters.Viewport.Set(0, 0, m_renderTargetWidth, m_renderTargetHeight, 0.0f, 1.0f); // done m_bHardwareResourcesCreated = true; return true; } void EditorResourcePreviewWidget::ReleaseGPUResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; m_pWorldRenderer = NULL; SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_bHardwareResourcesCreated = false; } void EditorResourcePreviewWidget::Draw() { GPUContext *pGPUDevice = g_pRenderer->GetGPUContext(); GPUContextConstants *pGPUConstants = pGPUDevice->GetConstants(); // create hardware resources if (!m_bHardwareResourcesCreated && !CreateGPUResources()) return; // update view parameters m_viewParameters.ViewCamera = m_ArcBallCamera; m_viewParameters.ViewCamera.SetObjectCullDistance(m_ArcBallCamera.GetFarPlaneDistance() - m_ArcBallCamera.GetNearPlaneDistance()); m_viewParameters.MaximumShadowViewDistance = m_viewParameters.ViewCamera.GetObjectCullDistance(); // clear target pGPUDevice->SetOutputBuffer(m_pSwapChain); pGPUDevice->SetRenderTargets(0, NULL, NULL); pGPUDevice->SetViewport(&m_viewParameters.Viewport); pGPUDevice->ClearTargets(true, true, true); // setup constants pGPUConstants->SetLocalToWorldMatrix(float4x4::Identity, false); pGPUConstants->SetFromCamera(m_viewParameters.ViewCamera, true); // do nothing if preview type is none if (m_ePreviewType != PREVIEW_TYPE_NONE) DrawPreview(); // draw overlays DrawPreviewOverlays(); // clear state pGPUDevice->ClearState(true, true, true, true); // end draw calls, flip buffers pGPUDevice->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // no draw pending now m_bRedrawPending = false; } void EditorResourcePreviewWidget::OnFrameExecutionTriggered(float timeSinceLastFrame) { // update camera m_ArcBallCamera.Update(timeSinceLastFrame); //// force draw if requested by camera //if (m_ArcBallCamera.IsDirty()) //FlagForRedraw(); // draw if (m_bRedrawPending || (m_viewportFlags & EDITOR_VIEWPORT_FLAG_REALTIME)) Draw(); } void EditorResourcePreviewWidget::SetPreviewErrorMessage(const char *message) { if (m_pResourceRenderProxy != NULL) { m_pRenderWorld->RemoveRenderable(m_pResourceRenderProxy); m_pResourceRenderProxy->Release(); m_pResourceRenderProxy = NULL; } SAFE_RELEASE(m_Resource.asResource); m_ePreviewType = PREVIEW_TYPE_NONE; m_errorMessage = message; UpdateZoomScale(); ResetCamera(); FlagForRedraw(); } void EditorResourcePreviewWidget::ClearPreview() { if (m_pResourceRenderProxy != NULL) { m_pRenderWorld->RemoveRenderable(m_pResourceRenderProxy); m_pResourceRenderProxy->Release(); m_pResourceRenderProxy = NULL; } SAFE_RELEASE(m_Resource.asResource); m_ePreviewType = PREVIEW_TYPE_NONE; m_errorMessage = "No resource selected."; UpdateZoomScale(); ResetCamera(); FlagForRedraw(); } void EditorResourcePreviewWidget::UpdateZoomScale() { m_fZoomScale = 1.0f; if (m_pResourceRenderProxy != NULL) { // determine size of object AABox renderProxyBounds = m_pResourceRenderProxy->GetBoundingBox(); float3 objectSize(renderProxyBounds.GetExtents()); // halve it, then tune each mouse wheel click to one fourth of the size float maxComponent = Max(objectSize.x, Max(objectSize.y, objectSize.z)); m_fZoomScale = Max(maxComponent / 8.0f, 1.0f); Log_DevPrintf("EditorResourcePreviewWidget::UpdateZoomScale: Max component: %f, zoom scale = %f", maxComponent, m_fZoomScale); } FlagForRedraw(); } void EditorResourcePreviewWidget::ResetCamera() { m_ArcBallCamera.Reset(); m_ArcBallCamera.SetEyeDistance(1.0f); if (m_pResourceRenderProxy != NULL) { // determine size of object AABox renderProxyBounds = m_pResourceRenderProxy->GetBoundingBox(); float3 objectSize(renderProxyBounds.GetExtents()); // zoom it so that the object fits on the screen float maxComponent = Max(objectSize.x, Max(objectSize.y, objectSize.z)); m_ArcBallCamera.SetEyeDistance(-maxComponent * 3.0f); // update far z m_ArcBallCamera.SetFarPlaneDistance(Max(100.0f, maxComponent * 10.0f)); // update target m_ArcBallCamera.SetTarget(renderProxyBounds.GetCenter()); // debugging Log_DevPrintf("EditorResourcePreviewWidget::ResetCamera: Max component: %f, starting eye distance = %f, far plane distance = %f, target = %s", maxComponent, m_ArcBallCamera.GetEyeDistance(), m_ArcBallCamera.GetFarPlaneDistance(), StringConverter::Float3ToString(m_ArcBallCamera.GetTarget()).GetCharArray()); } FlagForRedraw(); } bool EditorResourcePreviewWidget::SetPreviewResource(const Resource *pResource) { if (pResource != NULL) { if (pResource->GetResourceTypeInfo() == Material::StaticTypeInfo()) SetPreviewMaterial(pResource->Cast<Material>()); else if (pResource->GetResourceTypeInfo() == MaterialShader::StaticTypeInfo()) SetPreviewMaterialShader(pResource->Cast<MaterialShader>()); else if (pResource->GetResourceTypeInfo()->IsDerived(Texture::StaticTypeInfo())) SetPreviewTexture(pResource->Cast<Texture>()); else if (pResource->GetResourceTypeInfo() == StaticMesh::StaticTypeInfo()) SetPreviewStaticMesh(pResource->Cast<StaticMesh>()); else if (pResource->GetResourceTypeInfo() == BlockMesh::StaticTypeInfo()) SetPreviewStaticBlockMesh(pResource->Cast<BlockMesh>()); else { SmallString error; error.Format("Error: Unhandled resource type: '%s' for '%s'.", pResource->GetResourceTypeInfo()->GetTypeName(), pResource->GetName().GetCharArray()); SetPreviewErrorMessage(error); return false; } } else { ClearPreview(); } return true; } bool EditorResourcePreviewWidget::SetPreviewResourceByName(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName) { // load the resource AutoReleasePtr<const Resource> pResource = g_pResourceManager->UncachedGetResource(pResourceTypeInfo, resourceName); if (pResource == NULL) { SmallString error; error.Format("Could not load '%s' as a '%s'.", resourceName, pResourceTypeInfo->GetTypeName()); SetPreviewErrorMessage(error); return false; } return SetPreviewResource(pResource); } void EditorResourcePreviewWidget::SetPreviewMaterial(const Material *pMaterial) { ClearPreview(); m_ePreviewType = PREVIEW_TYPE_MATERIAL; m_Resource.asMaterial = pMaterial; m_Resource.asMaterial->AddRef(); SetupStaticMesh(NULL, pMaterial); UpdateZoomScale(); ResetCamera(); } void EditorResourcePreviewWidget::SetPreviewMaterialShader(const MaterialShader *pMaterialShader) { ClearPreview(); m_ePreviewType = PREVIEW_TYPE_MATERIALSHADER; m_Resource.asMaterialShader = pMaterialShader; m_Resource.asMaterialShader->AddRef(); Material *pTempMaterial = new Material(); pTempMaterial->Create("", pMaterialShader); SetupStaticMesh(NULL, pTempMaterial); UpdateZoomScale(); ResetCamera(); pTempMaterial->Release(); } void EditorResourcePreviewWidget::SetPreviewTexture(const Texture *pTexture) { ClearPreview(); m_ePreviewType = PREVIEW_TYPE_TEXTURE2D; m_Resource.asTexture = pTexture; m_Resource.asTexture->AddRef(); UpdateZoomScale(); ResetCamera(); } void EditorResourcePreviewWidget::SetPreviewStaticMesh(const StaticMesh *pStaticMesh) { ClearPreview(); m_ePreviewType = PREVIEW_TYPE_STATICMESH; m_Resource.asStaticMesh = pStaticMesh; m_Resource.asStaticMesh->AddRef(); SetupStaticMesh(pStaticMesh, NULL); UpdateZoomScale(); ResetCamera(); } void EditorResourcePreviewWidget::SetPreviewStaticBlockMesh(const BlockMesh *pStaticBlockMesh) { ClearPreview(); m_ePreviewType = PREVIEW_TYPE_STATICBLOCKMESH; m_Resource.asStaticBlockMesh = pStaticBlockMesh; m_Resource.asStaticBlockMesh->AddRef(); // create the render proxy { BlockMeshRenderProxy *pRenderProxy = new BlockMeshRenderProxy(0, pStaticBlockMesh, Transform::Identity, 0); DebugAssert(m_pResourceRenderProxy == NULL); m_pResourceRenderProxy = pRenderProxy; m_pRenderWorld->AddRenderable(pRenderProxy); FlagForRedraw(); } UpdateZoomScale(); ResetCamera(); } void EditorResourcePreviewWidget::SetupStaticMesh(const StaticMesh *pStaticMeshToRender, const Material *pMaterialOverride) { //uint32 i; if (pStaticMeshToRender == NULL) { pStaticMeshToRender = g_pResourceManager->GetStaticMesh("models/engine/unit_sphere"); if (pStaticMeshToRender == NULL) pStaticMeshToRender = g_pResourceManager->GetDefaultStaticMesh(); } StaticMeshRenderProxy *pRenderProxy = new StaticMeshRenderProxy(0, pStaticMeshToRender, Transform::Identity, 0); if (pMaterialOverride != NULL) { for (uint32 i = 0; i < pStaticMeshToRender->GetMaterialCount(); i++) pRenderProxy->SetMaterial(i, pMaterialOverride); } DebugAssert(m_pResourceRenderProxy == NULL); m_pResourceRenderProxy = pRenderProxy; m_pRenderWorld->AddRenderable(pRenderProxy); FlagForRedraw(); } void EditorResourcePreviewWidget::DrawPreview() { switch (m_ePreviewType) { case PREVIEW_TYPE_MATERIAL: case PREVIEW_TYPE_MATERIALSHADER: case PREVIEW_TYPE_STATICMESH: case PREVIEW_TYPE_STATICBLOCKMESH: { // all of these use a world m_pWorldRenderer->DrawWorld(m_pRenderWorld, &m_viewParameters, NULL, NULL); } break; case PREVIEW_TYPE_TEXTURE2D: { // handle texture drawing const Texture2D *pTexture2D = m_Resource.asTexture->SafeCast<Texture2D>(); DebugAssert(pTexture2D != NULL); // setup rect MINIGUI_RECT drawRect; SET_MINIGUI_RECT(&drawRect, 0, m_renderTargetWidth, 0, m_renderTargetHeight); m_guiContext.SetAlphaBlendingEnabled(false); m_guiContext.DrawTexturedRect(&drawRect, &MINIGUI_UV_RECT::FULL_RECT, pTexture2D); } break; } } void EditorResourcePreviewWidget::DrawPreviewOverlays() { SmallString tempStr; if (m_pOverlayTextFont == NULL) { m_pOverlayTextFont = g_pResourceManager->GetFont("resources/engine/fonts/fixedsyse_16"); if (m_pOverlayTextFont == NULL) return; } m_guiContext.PushManualFlush(); if (m_ePreviewType != PREVIEW_TYPE_NONE) { tempStr.Format("'%s'", m_Resource.asResource->GetName().GetCharArray()); m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 2, tempStr); switch (m_ePreviewType) { case PREVIEW_TYPE_MATERIAL: { } break; case PREVIEW_TYPE_MATERIALSHADER: { } break; case PREVIEW_TYPE_STATICMESH: { float3 meshExtents(m_Resource.asStaticMesh->GetBoundingBox().GetExtents()); tempStr.Format("Size: %f x %f x %f", meshExtents.x, meshExtents.y, meshExtents.z); m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 18, tempStr); tempStr.Format("LODs: %u", m_Resource.asStaticMesh->GetLODCount()); m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 34, tempStr); tempStr.Format("Batches: %u", m_Resource.asStaticMesh->GetLOD(0)->GetBatchCount()); m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 50, tempStr); uint32 triangleCount = 0; for (uint32 i = 0; i < m_Resource.asStaticMesh->GetLOD(0)->GetBatchCount(); i++) triangleCount += m_Resource.asStaticMesh->GetLOD(0)->GetBatch(i)->NumIndices / 3; tempStr.Format("Triangles: %u", triangleCount); m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 66, tempStr); } break; case PREVIEW_TYPE_STATICBLOCKMESH: { } break; case PREVIEW_TYPE_TEXTURE2D: { } break; } } else { m_guiContext.DrawText(m_pOverlayTextFont, 16, 2, 2, m_errorMessage); } m_guiContext.PopManualFlush(); } void EditorResourcePreviewWidget::ConnectUIEvents() { //connect(this, SIGNAL(), this, SLOT(OnFocusGained())); //connect(this, SIGNAL(), this, SLOT(OnFocusLost())); connect(m_ui->toolbarViewWireframe, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewWireframeClicked(bool))); connect(m_ui->toolbarViewUnlit, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewUnlitClicked(bool))); connect(m_ui->toolbarViewLit, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewLitClicked(bool))); connect(m_ui->toolbarViewLightingOnly, SIGNAL(clicked(bool)), this, SLOT(OnToolbarViewLightingOnlyClicked(bool))); connect(m_ui->toolbarFlagShadows, SIGNAL(clicked(bool)), this, SLOT(OnToolbarFlagShadowsClicked(bool))); connect(m_ui->toolbarFlagWireframeOverlay, SIGNAL(clicked(bool)), this, SLOT(OnToolbarFlagWireframeOverlayClicked(bool))); connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); } void EditorResourcePreviewWidget::OnFocusGained() { } void EditorResourcePreviewWidget::OnFocusLost() { } void EditorResourcePreviewWidget::OnSwapChainWidgetResized() { uint32 newWidth = (uint32)m_ui->swapChainWidget->size().width(); uint32 newHeight = (uint32)m_ui->swapChainWidget->size().height(); // update dimensions m_renderTargetWidth = newWidth; m_renderTargetHeight = newHeight; // kill old swapchain refs if (m_pSwapChain != NULL) { m_pSwapChain->Release(); m_pSwapChain = NULL; } // skip full recreation if we can just do the resize if (m_bHardwareResourcesCreated && (m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) != NULL) { m_pSwapChain->AddRef(); m_ArcBallCamera.SetPerspectiveAspect((float)newWidth, (float)newHeight); m_guiContext.SetViewportDimensions(newWidth, newHeight); m_viewParameters.Viewport.Set(0, 0, m_renderTargetWidth, m_renderTargetHeight, 0.0f, 1.0f); delete m_pWorldRenderer; m_pWorldRenderer = nullptr; m_bHardwareResourcesCreated = false; FlagForRedraw(); } else { ReleaseGPUResources(); FlagForRedraw(); } } void EditorResourcePreviewWidget::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorResourcePreviewWidget::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { } void EditorResourcePreviewWidget::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { if ((pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) || (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton)) { // if not currently in any state, determine which state to transition to if (m_eCurrentState == STATE_NONE) { m_eCurrentState = STATE_ROTATE_CAMERA; FlagForRedraw(); } } else if ((pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) || (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton)) { switch (m_eCurrentState) { case STATE_ROTATE_CAMERA: { m_eCurrentState = STATE_NONE; FlagForRedraw(); } break; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pMouseEvent->x(), pMouseEvent->y()); int2 lastMousePosition(m_LastMousePosition); int2 mousePositionDiff(currentMousePosition - lastMousePosition); m_LastMousePosition = currentMousePosition; // handle mouse movement based on state switch (m_eCurrentState) { case STATE_NONE: { } break; case STATE_ROTATE_CAMERA: { m_ArcBallCamera.RotateFromMouseMovement(mousePositionDiff.x, mousePositionDiff.y); FlagForRedraw(); } break; } } } void EditorResourcePreviewWidget::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { if (pWheelEvent->orientation() == Qt::Vertical) { float wheelDelta = (float)pWheelEvent->delta() / 120.0f; m_ArcBallCamera.SetEyeDistance(m_ArcBallCamera.GetEyeDistance() + m_fZoomScale * -wheelDelta); Log_DevPrintf("new eye distance: %s", StringConverter::FloatToString(m_ArcBallCamera.GetEyeDistance()).GetCharArray()); FlagForRedraw(); } } <file_sep>/Engine/Source/Engine/Physics/TriangleMeshCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/TriangleMeshCollisionShape.h" #include "Engine/Physics/ScaledTriangleMeshCollisionShape.h" #include "Engine/Physics/BulletHeaders.h" Log_SetChannel(TriangleMeshCollisionShape); #include "btBulletWorldImporter.h" namespace Physics { TriangleMeshCollisionShape::TriangleMeshCollisionShape() : CollisionShape(), m_localBoundingBox(AABox::Zero), m_pTriangleMeshShape(NULL) { } TriangleMeshCollisionShape::~TriangleMeshCollisionShape() { btOptimizedBvh *pBvh = m_pTriangleMeshShape->getOptimizedBvh(); btStridingMeshInterface *pMeshInterface = m_pTriangleMeshShape->getMeshInterface(); delete m_pTriangleMeshShape; delete pBvh; delete pMeshInterface; } const COLLISION_SHAPE_TYPE TriangleMeshCollisionShape::GetType() const { return COLLISION_SHAPE_TYPE_TRIANGLE_MESH; } const AABox &TriangleMeshCollisionShape::GetLocalBoundingBox() const { return m_localBoundingBox; } bool TriangleMeshCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { byte *pBuffer = new byte[dataSize]; if (!pStream->Read2(pBuffer, dataSize)) return false; bool result = LoadFromData(pBuffer, dataSize); delete[] pBuffer; return result; } bool TriangleMeshCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { btBulletWorldImporter worldImporter; if (!worldImporter.loadFileFromMemory(reinterpret_cast<char *>(const_cast<void *>(pData)), dataSize)) { Log_ErrorPrintf("TriangleMeshCollisionShape::LoadFromData: Failed to parse data"); worldImporter.deleteAllData(); return false; } if (worldImporter.getNumCollisionShapes() != 1) { Log_ErrorPrintf("TriangleMeshCollisionShape::LoadFromData: Bullet file does not contain correct number of collision shapes (%u)", (uint32)worldImporter.getNumCollisionShapes()); worldImporter.deleteAllData(); return false; } btCollisionShape *pCollisionShape = worldImporter.getCollisionShapeByIndex(0); if (pCollisionShape->getShapeType() != TRIANGLE_MESH_SHAPE_PROXYTYPE) { Log_ErrorPrintf("TriangleMeshCollisionShape::LoadFromData: Collision shape is of incorrect type (%i)", pCollisionShape->getShapeType()); worldImporter.deleteAllData(); return false; } m_pTriangleMeshShape = static_cast<btBvhTriangleMeshShape *>(pCollisionShape); // get bounds btVector3 minBounds, maxBounds; m_pTriangleMeshShape->getAabb(btTransform::getIdentity(), minBounds, maxBounds); m_localBoundingBox.SetBounds(BulletVector3ToFloat3(minBounds), BulletVector3ToFloat3(maxBounds)); return true; } CollisionShape *TriangleMeshCollisionShape::CreateScaledShape(const float3 &scale) const { return new ScaledTriangleMeshCollisionShape(this, scale); } void TriangleMeshCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { } void TriangleMeshCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { } btCollisionShape *TriangleMeshCollisionShape::GetBulletShape() const { return m_pTriangleMeshShape; } } // namespace Physics <file_sep>/Engine/Source/GameFramework/BlockMeshEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/BlockMeshEntity.h" #include "Engine/BlockMesh.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Engine/World.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/KinematicObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Renderer/RenderWorld.h" #include "Engine/ResourceManager.h" Log_SetChannel(BlockMeshEntity); DEFINE_ENTITY_TYPEINFO(BlockMeshEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(BlockMeshEntity); BEGIN_ENTITY_PROPERTIES(BlockMeshEntity) PROPERTY_TABLE_MEMBER("BlockMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetBlockMeshName, NULL, PropertyCallbackSetBlockMeshName, NULL, PropertyCallbackBlockMeshChanged, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(BlockMeshEntity, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(BlockMeshEntity, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(BlockMeshEntity, m_shadowFlags), NULL, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(BlockMeshEntity) END_ENTITY_SCRIPT_FUNCTIONS() BlockMeshEntity::BlockMeshEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pBlockMesh(nullptr), m_visible(true), m_collidable(false), m_shadowFlags(0), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } BlockMeshEntity::~BlockMeshEntity() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pCollisionObject != nullptr) m_pCollisionObject->Release(); if (m_pBlockMesh != nullptr) m_pBlockMesh->Release(); } void BlockMeshEntity::SetBlockMesh(const BlockMesh *pBlockMesh) { DebugAssert(pBlockMesh != nullptr); if (m_pBlockMesh == pBlockMesh) return; if (m_pBlockMesh != nullptr) m_pBlockMesh->Release(); m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); PropertyCallbackBlockMeshChanged(this); } void BlockMeshEntity::SetVisible(bool visible) { if (m_visible == visible) return; m_visible = visible; PropertyCallbackVisibleChanged(this); } void BlockMeshEntity::SetShadowFlags(uint32 shadowFlags) { if (m_shadowFlags == shadowFlags) return; m_shadowFlags = shadowFlags; if (m_pRenderProxy != nullptr) m_pRenderProxy->SetShadowFlags(shadowFlags); } void BlockMeshEntity::SetCollidable(bool collidable) { if (m_collidable == collidable) return; m_collidable = collidable; PropertyCallbackCollidableChanged(this); } void BlockMeshEntity::Create(uint32 entityID, ENTITY_MOBILITY mobility /* = ENTITY_MOBILITY_MOVABLE */, const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const BlockMesh *pBlockMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_mobility = mobility; m_transform.Set(position, rotation, scale); if (pBlockMesh != nullptr) { m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); } else { m_pBlockMesh = g_pResourceManager->GetDefaultBlockMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; Initialize(entityID, EmptyString); } bool BlockMeshEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; DebugAssert(m_pBlockMesh != nullptr); UpdateRenderProxy(); UpdateCollisionObject(); // determine bounds m_boundingBox = m_transform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()); m_boundingSphere = m_transform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()); return true; } void BlockMeshEntity::UpdateRenderProxy() { if (m_visible) { if (m_pRenderProxy == nullptr) { m_pRenderProxy = new BlockMeshRenderProxy(m_entityID, m_pBlockMesh, m_transform, m_shadowFlags); if (IsInWorld()) m_pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } else { m_pRenderProxy->SetBlockMesh(m_pBlockMesh); } } else { if (m_pRenderProxy != nullptr) { if (IsInWorld()) m_pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); m_pRenderProxy->Release(); m_pRenderProxy = nullptr; } } } void BlockMeshEntity::UpdateCollisionObject() { if (m_collidable && m_pBlockMesh->GetCollisionShape() != nullptr) { if (m_pCollisionObject == nullptr) { // create collision object based on mobility if (m_mobility == ENTITY_MOBILITY_STATIC) m_pCollisionObject = new Physics::StaticObject(m_entityID, m_pBlockMesh->GetCollisionShape(), m_transform); else m_pCollisionObject = new Physics::KinematicObject(m_entityID, m_pBlockMesh->GetCollisionShape(), m_transform); if (IsInWorld()) m_pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); } else { m_pCollisionObject->SetCollisionShape(m_pBlockMesh->GetCollisionShape()); } } else { if (m_pCollisionObject != nullptr) { if (IsInWorld()) m_pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); m_pCollisionObject->Release(); m_pCollisionObject = nullptr; } } } void BlockMeshEntity::UpdateBounds() { // call entity set bounds with the transformed bounds, this will merge with components (if any) Entity::SetBounds(m_transform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere()), true); } void BlockMeshEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != NULL) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != NULL) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void BlockMeshEntity::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != NULL) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != NULL) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } void BlockMeshEntity::OnTransformChange() { BaseClass::OnTransformChange(); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(m_transform); if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(m_transform); UpdateBounds(); } void BlockMeshEntity::OnComponentBoundsChange() { UpdateBounds(); } bool BlockMeshEntity::PropertyCallbackGetBlockMeshName(ThisClass *pEntity, const void *pUserData, String *pValue) { pValue->Assign(pEntity->m_pBlockMesh->GetName()); return true; } bool BlockMeshEntity::PropertyCallbackSetBlockMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue) { const BlockMesh *pBlockMesh = g_pResourceManager->GetBlockMesh(*pValue); if (pBlockMesh == NULL) return false; if (pEntity->m_pBlockMesh != NULL) pEntity->m_pBlockMesh->Release(); pEntity->m_pBlockMesh = pBlockMesh; return true; } void BlockMeshEntity::PropertyCallbackBlockMeshChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateRenderProxy(); pEntity->UpdateCollisionObject(); pEntity->UpdateBounds(); } void BlockMeshEntity::PropertyCallbackVisibleChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateRenderProxy(); } void BlockMeshEntity::PropertyCallbackCollidableChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateCollisionObject(); } <file_sep>/Engine/Source/Renderer/WorldRenderers/CubeMapShadowMapRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" #include "Renderer/Shaders/ShadowMapShader.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderQueue.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Engine/Camera.h" #include "Engine/Material.h" #include "Engine/EngineCVars.h" #include "Engine/Profiling.h" Log_SetChannel(CubeMapShadowMapRenderer); CubeMapShadowMapRenderer::CubeMapShadowMapRenderer(uint32 shadowMapResolution /* = 256 */, PIXEL_FORMAT shadowMapFormat /* = PIXEL_FORMAT_D16_UNORM */) : m_shadowMapResolution(shadowMapResolution), m_shadowMapFormat(shadowMapFormat) { m_renderQueue.SetAcceptingLights(false); m_renderQueue.SetAcceptingRenderPassMask(RENDER_PASS_SHADOW_MAP); m_renderQueue.SetAcceptingOccluders(false); m_renderQueue.SetAcceptingDebugObjects(false); } CubeMapShadowMapRenderer::~CubeMapShadowMapRenderer() { } void CubeMapShadowMapRenderer::BuildCubeMapCamera(Camera *pCamera, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight, CUBE_FACE face) { // cube faces and where they should point: // Positive-X = Right // Negative-X = Left // Positive-Y = Up // Negative-Y = Down // Positive-Z = Forward // Negative-Z = Backwards // remember normal camera faces down the y axis static const float cameraRotations[CUBE_FACE_COUNT][3] = { { 0.0f, 0.0f, -90.0f }, // looking to the right { 0.0f, 0.0f, 90.0f }, // looking to the left { 90.0f, 0.0f, 0.0f }, // looking up { -90.0f, 0.0f, 0.0f }, // looking down { 0.0f, 0.0f, 0.0f }, // looking forwards { 0.0f, 0.0f, 180.0f }, // looking backwards }; // create a look at orthographic camera DebugAssert(face < CUBE_FACE_COUNT); pCamera->SetPosition(pLight->Position); pCamera->SetRotation(Quaternion::FromEulerAngles(cameraRotations[face][0], cameraRotations[face][1], cameraRotations[face][2])); pCamera->SetProjectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE); pCamera->SetPerspectiveFieldOfView(90.0f); pCamera->SetNearFarPlaneDistances(0.1f, pLight->Range); //pCamera->SetNearFarPlaneDistances(0.1f, 100.0f); } bool CubeMapShadowMapRenderer::AllocateShadowMap(ShadowMapData *pShadowMapData) { // store vars pShadowMapData->IsActive = false; // allocate texture GPU_TEXTURECUBE_DESC textureDesc(m_shadowMapResolution, m_shadowMapResolution, m_shadowMapFormat, GPU_TEXTURE_FLAG_SHADER_BINDABLE | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_CLAMP, float4::One, 0, 0, 0, 0, GPU_COMPARISON_FUNC_NEVER); // hardware pcf? if (CVars::r_shadow_use_hardware_pcf.GetBool()) { samplerStateDesc.Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_LESS; } Log_PerfPrintf("CubeMapShadowMapRenderer::AllocateShadowMap: Creating new %u x %u %s texture", m_shadowMapResolution, m_shadowMapResolution, NameTable_GetNameString(NameTables::PixelFormat, m_shadowMapFormat)); pShadowMapData->pShadowMapTexture = g_pRenderer->CreateTextureCube(&textureDesc, &samplerStateDesc); if (pShadowMapData->pShadowMapTexture == nullptr) return false; // create dsv for (uint32 cubeFace = 0; cubeFace < CUBE_FACE_COUNT; cubeFace++) { GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC dsvDesc(pShadowMapData->pShadowMapTexture, 0, (CUBE_FACE)cubeFace); pShadowMapData->pShadowMapDSV[cubeFace] = g_pRenderer->CreateDepthStencilBufferView(pShadowMapData->pShadowMapTexture, &dsvDesc); if (pShadowMapData->pShadowMapDSV[cubeFace] == nullptr) { for (uint32 i = 0; i < cubeFace; i++) { pShadowMapData->pShadowMapDSV[i]->Release(); pShadowMapData->pShadowMapDSV[i] = nullptr; } pShadowMapData->pShadowMapTexture->Release(); pShadowMapData->pShadowMapTexture = nullptr; return false; } } // ok return true; } void CubeMapShadowMapRenderer::FreeShadowMap(ShadowMapData *pShadowMapData) { for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) pShadowMapData->pShadowMapDSV[i]->Release(); pShadowMapData->pShadowMapTexture->Release(); } void CubeMapShadowMapRenderer::DrawShadowMap(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { // get shadow distance shadowDistance = Min(shadowDistance, pViewCamera->GetFarPlaneDistance() - pViewCamera->GetNearPlaneDistance()); // common device parameters RENDERER_VIEWPORT shadowMapViewport(0, 0, m_shadowMapResolution, m_shadowMapResolution, 0.0f, 1.0f); pCommandList->SetViewport(&shadowMapViewport); // for each cube face for (uint32 cubeFaceIndex = 0; cubeFaceIndex < CUBE_FACE_COUNT; cubeFaceIndex++) { CUBE_FACE cubeFace = (CUBE_FACE)cubeFaceIndex; // build camera Camera lightCamera; BuildCubeMapCamera(&lightCamera, pLight, cubeFace); // add camera //RENDER_PROFILER_ADD_CAMERA(pRenderProfiler, &lightCamera, String::FromFormat("Point Shadow Camera Face %u", cubeFaceIndex)); // set+clear the shadow map pCommandList->SetRenderTargets(0, nullptr, pShadowMapData->pShadowMapDSV[cubeFaceIndex]); pCommandList->ClearTargets(false, true, false, float4::Zero, 1.0f); // clear render queue m_renderQueue.Clear(); // find renderables { MICROPROFILE_SCOPEI("CubeMapShadowMapRenderer", "EnumerateRenerables", MICROPROFILE_COLOR(50, 150, 100)); // enumerate everything in frustum pRenderWorld->EnumerateRenderablesInFrustum(lightCamera.GetFrustum(), [this, &lightCamera](const RenderProxy *pRenderProxy) { // add to render queue pRenderProxy->QueueForRender(&lightCamera, &m_renderQueue); }); } // no renderables? if (m_renderQueue.GetQueueSize() == 0) continue; // set render targets, for pipelining we do this before sorting pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // set up view-dependent constants pCommandList->GetConstants()->SetFromCamera(lightCamera, true); // sort renderables m_renderQueue.Sort(); // opaque { RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); MICROPROFILE_SCOPEI("CubeMapShadowMapRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(150, 50, 100)); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { // Select appropriate shader // For now, only masked materials are drawn with clipping if (pQueueEntry->pMaterial->GetShader()->GetBlendMode() == MATERIAL_BLENDING_MODE_MASKED) { ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(ShadowMapShader), 0, pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags, pQueueEntry->pMaterial->GetShader(), pQueueEntry->pMaterial->GetShaderStaticSwitchMask()); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); pQueueEntry->pMaterial->BindDeviceResources(pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pCommandList); } } else { // Otherwise, use shadowmap shader without material ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(ShadowMapShader), 0, pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags, NULL, 0); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pCommandList); } } } } // translucent { RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); MICROPROFILE_SCOPEI("CubeMapShadowMapRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(150, 100, 50)); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & RENDER_PASS_SHADOW_MAP) { // For now, only masked materials are drawn with clipping, so just use the regular shader here ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(ShadowMapShader), 0, pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags, NULL, 0); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pCommandList); } } } } } } <file_sep>/Engine/Source/D3D11Renderer/D3D11Common.h #pragma once #include "Renderer/Common.h" #include "Renderer/Renderer.h" #define INITGUID 1 #include <d3d11.h> #include <d3d11_1.h> #include <D3Dcompiler.h> #include <dxgidebug.h> #include <Uxtheme.h> #include <VersionHelpers.h> // Forward declare all our types class D3D11GPUBuffer; class D3D11GPUConstants; class D3D11GPUContext; class D3D11GPUQuery; class D3D11GPUShaderProgram; class D3D11GPUOutputBuffer; class D3D11GPUTexture1D; class D3D11GPUTexture1DArray; class D3D11GPUTexture2D; class D3D11GPUTexture2DArray; class D3D11GPUTexture3D; class D3D11GPUTextureCube; class D3D11GPUTextureCubeArray; class D3D11GPUDepthTexture; class D3D11GPUDepthTextureArray; class D3D11GPUDevice; class D3D11SamplerState; #include "D3D11Renderer/D3D11Defines.h" #include "D3D11Renderer/D3D11CVars.h" <file_sep>/Engine/Source/Core/MeshUtilties.h #pragma once #include "Core/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/Matrixf.h" #include "MathLib/Plane.h" namespace MeshUtilites { // Generate normal information for the specified vertices. // Vertices are assumed to be packed tightly and have three elements (x, y, z) // Normals are packed the same. // Indices are assumed to be 32-bit integers. // If indices is NULL, it is assumed that it is a non-indexed mesh. void CalculateNormals(const void *pInVertices, uint32 uVertexStride, uint32 nVertices, const void *pInTriangles, uint32 uTriangleStride, uint32 nTriangles, void *pOutNormals, uint32 uNormalStride); // Calculate the normal of a triangle face. Vector3f CalculateFaceNormal(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2); // Calculate the plane of a triangle. Plane CalculateTrianglePlane(const Vector3f &p0, const Vector3f &p1, const Vector3f &p2); Plane CalculateTrianglePlane(const Vector3f &TriangleNormal, const Vector3f &FirstVertex); // Calculate tangent space vectors for specified vertices and texture coordinates. // Resultant vectors are not guaranteed to be unit length. void CalculateTangentSpaceVectors(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector2f &uv0, const Vector2f &uv1, const Vector2f &uv2, Vector3f &OutTangent, Vector3f &OutBinormal, Vector3f &OutNormal); // Generate indices for a triangle-strip based mesh. // pOutIndices should be equal to nVertices - 2, and 32-bit integer. // Returns the number of triangles (indices / 3) for the mesh. uint32 GenerateTriangleStripIndices(const void *pInVertices, uint32 uVertexStride, uint32 nVertices, void *pOutTriangles, uint32 uTriangleStride); // Reverse the winding order for the specified set of indices. void ReverseTriangleWinding(void *pInOutTriangles, uint32 uTriangleStride, uint32 nTriangles); // Optimize the specified indices so that all the indices that use the same material are grouped together. void OptimizeIndicesForBatching(void *pInIndices, uint32 IndexStride, const void *pInMaterialIndices, uint32 MaterialIndexStride, uint32 nIndices); // Creates a sphere. The returned memory should be freed with Y_free. void CreateSphere(Vector3f **ppVertices, uint32 *pNumVertices, uint32 SubDivLevel = 3, float Scale = 1.0f); float InterpolateVector(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const float &c0, const float &c1, const float &c2, const Vector3f &p); bool PointInTriangle(const Vector3f &p, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &normal); void OrthogonalizeTangent(const Vector3f &inTangent, const Vector3f &inBinormal, const Vector3f &inNormal, Vector3f &outTangent, float &outBinormalSign); } <file_sep>/Engine/Source/ContentConverterStandalone/AssimpSkeletalAnimationImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintAssimpSkeletalAnimationImporterSyntax() { Log_InfoPrint("Assimp Skeletal Animation Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -listanim: List animations, don't import anything"); Log_InfoPrint(" -createskeleton <path>: Create skeleton from this animation."); Log_InfoPrint(" -skeleton <path>: Specify skeleton resource name. Required if not using -createskeleton."); Log_InfoPrint(" -oname <path>: Output resource name. Required if not using -all."); Log_InfoPrint(" -odir <path>: Output resource directory. Required if using -all."); Log_InfoPrint(" -oprefix <prefix>: Output resource prefix. Used for -all."); Log_InfoPrint(" -tps <tps>: Number of animation ticks per second if not specified in file. Default of 30."); Log_InfoPrint(" -forcetps <tps>: Force this number of ticks per second irregardless of what is specified in file."); Log_InfoPrint(" -all: Import all animations from file."); Log_InfoPrint(" -animname <name>: Import single animation, specify the name."); Log_InfoPrint(" -clip start:end: Clip animation to these frame numbers."); Log_InfoPrint(""); } bool ParseAssimpSkeletalAnimationImporterOption(AssimpSkeletalAnimationImporter::Options &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.SourcePath = argv[++i]; else if (CHECK_ARG("-listanim")) Options.ListOnly = true; else if (CHECK_ARG_PARAM("-createskeleton")) { Options.SkeletonName = argv[++i]; Options.CreateSkeleton = true; } else if (CHECK_ARG_PARAM("-skeleton")) { Options.SkeletonName = argv[++i]; Options.CreateSkeleton = false; } else if (CHECK_ARG_PARAM("-oname")) Options.OutputResourceName = argv[++i]; else if (CHECK_ARG_PARAM("-odir")) Options.OutputResourceDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-oprefix")) Options.OutputResourcePrefix = argv[++i]; else if (CHECK_ARG_PARAM("-tps")) Options.DefaultAnimationTicksPerSecond = StringConverter::StringToFloat(argv[++i]); else if (CHECK_ARG_PARAM("-forcetps")) Options.OverrideTicksPerSecond = StringConverter::StringToFloat(argv[++i]); else if (CHECK_ARG("-all")) Options.AllAnimations = true; else if (CHECK_ARG_PARAM("-animname")) Options.SingleAnimationName = argv[++i]; else if (CHECK_ARG_PARAM("-clip")) { Options.ClipAnimation = true; if (Y_sscanf(argv[++i], "%u:%u", &Options.ClipRangeStart, &Options.ClipRangeEnd) != 2) { Log_ErrorPrint("Invalid clip range specified: must be in format 'start:end'"); return false; } } else if (CHECK_ARG("-optimize")) Options.OptimizeAnimation = true; else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintAssimpSkeletalAnimationImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunAssimpSkeletalAnimationImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintAssimpSkeletalAnimationImporterSyntax(); return 0; } AssimpSkeletalAnimationImporter::Options options; AssimpSkeletalAnimationImporter::SetDefaultOptions(&options); for (i = 0; i < argc; i++) { if (!ParseAssimpSkeletalAnimationImporterOption(options, i, argc, argv)) return 1; } if (options.SourcePath.IsEmpty() || options.OutputResourceName.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; AssimpSkeletalAnimationImporter importer(&options, &progressCallbacks); if (!importer.Execute()) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Source/D3D11Renderer/D3D11CVars.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11Common.h" namespace CVars { // D3D11 cvars CVar r_d3d11_force_ref("r_d3d11_force_ref", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "force reference renderer for Direct3D 11", "bool"); CVar r_d3d11_force_warp("r_d3d11_force_warp", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "force WARP renderer for Direct3D 11", "bool"); CVar r_d3d11_use_11_1("r_d3d11_use_11_1", CVAR_FLAG_REQUIRE_APP_RESTART, "1", "use Direct3D 11.1 enhancements if available", "bool"); } <file_sep>/Editor/Source/Editor/Common.h #pragma once #include <QtCore/QVariant> // engine includes #include "Engine/Common.h" #include "Engine/Engine.h" #include "Renderer/RendererTypes.h" // disable warnings that qt files inflict #if Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable: 4127) // warning C4127: conditional expression is constant #pragma warning(disable: 4512) // warning C4512: 'QtPrivate::QSlotObjectBase' : assignment operator could not be generated #pragma warning(disable: 4389) // warning C4389: '==' : signed/unsigned mismatch #endif // qt includes #define QT_NO_SIGNALS_SLOTS_KEYWORDS 1 #define QT_NO_EMIT 1 #include <QtCore/QEvent> #include <QtCore/QStack> #include <QtCore/QTimer> #include <QtCore/QVariant> #include <QtGui/QKeyEvent> #include <QtGui/QMouseEvent> #include <QtGui/QStandardItemModel> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QColumnView> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QDockWidget> #include <QtWidgets/QFileDialog> #include <QtWidgets/QFormLayout> #include <QtWidgets/QFrame> #include <QtWidgets/QGridLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHeaderView> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QListView> #include <QtWidgets/QListWidget> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QMessageBox> #include <QtWidgets/QPlainTextEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QProgressBar> #include <QtWidgets/QScrollArea> #include <QtWidgets/QSlider> #include <QtWidgets/QStatusBar> #include <QtWidgets/QSpinBox> #include <QtWidgets/QSplitter> #include <QtWidgets/QStackedLayout> #include <QtWidgets/QStackedWidget> #include <QtWidgets/QTimeEdit> #include <QtWidgets/QTextEdit> #include <QtWidgets/QToolBar> #include <QtWidgets/QToolButton> #include <QtWidgets/QTreeView> #include <QtWidgets/QTreeWidget> #include <QtWidgets/QRadioButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> #include <QtWidgets/QWidgetAction> // property browser #include <QtPropertyBrowser/qtpropertymanager.h> #include <QtPropertyBrowser/qtpropertybrowser.h> #include <QtPropertyBrowser/qttreepropertybrowser.h> #include <QtPropertyBrowser/qteditorfactory.h> #include <QtPropertyBrowser/qtvariantproperty.h> #if Y_COMPILER_MSVC #pragma warning(pop) #endif //#if !defined(Q_NO_TEMPLATE_FRIENDS) && !defined(Q_CC_MSVC) //#error moo //#endif // signal blocker helper #include "SignalBlocker.h" // editor includes #include "Editor/Defines.h" // flow layout #include "Editor/FlowLayout.h" <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUQuery.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUQuery.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUDevice.h" Log_SetChannel(D3D11GPUContext); D3D11GPUQuery::D3D11GPUQuery(GPU_QUERY_TYPE type, ID3D11Query *pQuery, ID3D11Predicate *pPredicate) : m_eType(type) , m_pD3DQuery(pQuery) , m_pD3DPredicate(pPredicate) , m_pOwningContext(nullptr) { } D3D11GPUQuery::~D3D11GPUQuery() { SAFE_RELEASE(m_pD3DQuery); DebugAssert(m_pOwningContext == nullptr); } void D3D11GPUQuery::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11Query); // estimation... if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11GPUQuery::SetDebugName(const char *name) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DQuery, name); } bool D3D11GPUContext::BeginQuery(GPUQuery *pQuery) { D3D11GPUQuery *pD3DQuery = static_cast<D3D11GPUQuery *>(pQuery); DebugAssert(pD3DQuery->GetOwningContext() == nullptr); pD3DQuery->SetOwningContext(this); m_pD3DContext->Begin(pD3DQuery->GetD3DQuery()); return true; } bool D3D11GPUContext::EndQuery(GPUQuery *pQuery) { D3D11GPUQuery *pD3DQuery = static_cast<D3D11GPUQuery *>(pQuery); DebugAssert(pD3DQuery->GetOwningContext() == this); m_pD3DContext->End(pD3DQuery->GetD3DQuery()); pD3DQuery->SetOwningContext(nullptr); return true; } GPU_QUERY_GETDATA_RESULT D3D11GPUContext::GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) { D3D11GPUQuery *pD3DQuery = static_cast<D3D11GPUQuery *>(pQuery); DebugAssert(pD3DQuery->GetOwningContext() == nullptr); uint32 D3DGetDataFlags = 0; if (flags & GPU_QUERY_GETDATA_FLAG_NOFLUSH) D3DGetDataFlags = D3D11_ASYNC_GETDATA_DONOTFLUSH; HRESULT hResult; switch (pD3DQuery->GetQueryType()) { case GPU_QUERY_TYPE_SAMPLES_PASSED: { // uint64 DebugAssert(cbData == sizeof(uint64)); hResult = m_pD3DContext->GetData(pD3DQuery->GetD3DQuery(), pData, sizeof(uint64), D3DGetDataFlags); if (hResult == S_FALSE) return GPU_QUERY_GETDATA_RESULT_NOT_READY; else if (FAILED(hResult)) return GPU_QUERY_GETDATA_RESULT_ERROR; else return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_OCCLUSION: { // BOOL -> bool BOOL tempQueryData; hResult = m_pD3DContext->GetData(pD3DQuery->GetD3DQuery(), &tempQueryData, sizeof(tempQueryData), D3DGetDataFlags); if (hResult == S_FALSE) return GPU_QUERY_GETDATA_RESULT_NOT_READY; else if (FAILED(hResult)) return GPU_QUERY_GETDATA_RESULT_ERROR; DebugAssert(cbData == sizeof(bool)); *reinterpret_cast<bool *>(pData) = (tempQueryData == TRUE); return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: { // struct -> uint64 D3D11_QUERY_DATA_PIPELINE_STATISTICS pipelineStatistics; hResult = m_pD3DContext->GetData(pD3DQuery->GetD3DQuery(), &pipelineStatistics, sizeof(pipelineStatistics), D3DGetDataFlags); if (hResult == S_FALSE) return GPU_QUERY_GETDATA_RESULT_NOT_READY; else if (FAILED(hResult)) return GPU_QUERY_GETDATA_RESULT_ERROR; // pull from field DebugAssert(cbData == sizeof(uint64)); *reinterpret_cast<uint64 *>(pData) = pipelineStatistics.CInvocations; return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_TIMESTAMP: { // uint64 DebugAssert(cbData == sizeof(uint64)); hResult = m_pD3DContext->GetData(pD3DQuery->GetD3DQuery(), pData, sizeof(uint64), D3DGetDataFlags); if (hResult == S_FALSE) return GPU_QUERY_GETDATA_RESULT_NOT_READY; else if (FAILED(hResult)) return GPU_QUERY_GETDATA_RESULT_ERROR; else return GPU_QUERY_GETDATA_RESULT_OK; } case GPU_QUERY_TYPE_FREQUENCY: { // struct -> uint64 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT tsDisjoint; hResult = m_pD3DContext->GetData(pD3DQuery->GetD3DQuery(), &tsDisjoint, sizeof(tsDisjoint), D3DGetDataFlags); if (hResult == S_FALSE) return GPU_QUERY_GETDATA_RESULT_NOT_READY; else if (FAILED(hResult)) return GPU_QUERY_GETDATA_RESULT_ERROR; // if disjoint, return zero DebugAssert(cbData == sizeof(uint64)); *reinterpret_cast<uint64 *>(pData) = (tsDisjoint.Disjoint) ? 0 : tsDisjoint.Frequency; return GPU_QUERY_GETDATA_RESULT_OK; } default: UnreachableCode(); return GPU_QUERY_GETDATA_RESULT_ERROR; } } GPUQuery *D3D11GPUDevice::CreateQuery(GPU_QUERY_TYPE type) { ID3D11Query *pD3DQuery = nullptr; ID3D11Predicate *pD3DPredicate = nullptr; // create occlusion as predicates if (type == GPU_QUERY_TYPE_OCCLUSION) { D3D11_QUERY_DESC D3DQueryDesc; D3DQueryDesc.Query = D3D11_QUERY_OCCLUSION_PREDICATE; D3DQueryDesc.MiscFlags = 0; HRESULT hResult = m_pD3DDevice->CreatePredicate(&D3DQueryDesc, &pD3DPredicate); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateQuery: CreatePredicate failed with hResult %08X", hResult); return false; } // also the query field pD3DQuery = pD3DPredicate; } else { D3D11_QUERY_DESC D3DQueryDesc; switch (type) { case GPU_QUERY_TYPE_SAMPLES_PASSED: D3DQueryDesc.Query = D3D11_QUERY_OCCLUSION; D3DQueryDesc.MiscFlags = 0; break; case GPU_QUERY_TYPE_PRIMITIVES_GENERATED: D3DQueryDesc.Query = D3D11_QUERY_PIPELINE_STATISTICS; D3DQueryDesc.MiscFlags = 0; break; case GPU_QUERY_TYPE_TIMESTAMP: D3DQueryDesc.Query = D3D11_QUERY_TIMESTAMP; D3DQueryDesc.MiscFlags = 0; break; case GPU_QUERY_TYPE_FREQUENCY: D3DQueryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT; D3DQueryDesc.MiscFlags = 0; break; default: UnreachableCode(); break; } HRESULT hResult = m_pD3DDevice->CreateQuery(&D3DQueryDesc, &pD3DQuery); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateQuery: CreateQuery failed with hResult %08X", hResult); return false; } } return new D3D11GPUQuery(type, pD3DQuery, pD3DPredicate); } void D3D11GPUContext::SetPredication(GPUQuery *pQuery) { if (m_pCurrentPredicate == pQuery) return; if (pQuery != nullptr) m_pCurrentPredicateD3D = static_cast<D3D11GPUQuery *>(pQuery)->GetD3DPredicate(); else m_pCurrentPredicateD3D = nullptr; // switch in d3d if (m_predicateBypassCount == 0) m_pD3DContext->SetPredication(m_pCurrentPredicateD3D, FALSE); // update pointer if (m_pCurrentPredicate != nullptr) m_pCurrentPredicate->Release(); if ((m_pCurrentPredicate = pQuery) != nullptr) m_pCurrentPredicate->AddRef(); } void D3D11GPUContext::BypassPredication() { if ((m_predicateBypassCount++) == 0 && m_pCurrentPredicateD3D != nullptr) m_pD3DContext->SetPredication(nullptr, FALSE); } void D3D11GPUContext::RestorePredication() { DebugAssert(m_predicateBypassCount > 0); if ((--m_predicateBypassCount) == 0 && m_pCurrentPredicateD3D != nullptr) m_pD3DContext->SetPredication(m_pCurrentPredicateD3D, FALSE); } <file_sep>/Engine/Source/OpenGLES2Renderer/PrecompiledHeader.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" <file_sep>/Engine/Source/Renderer/RenderProxies/StaticMeshRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/Camera.h" #include "Engine/Material.h" StaticMeshRenderProxy::StaticMeshRenderProxy(uint32 entityId, const StaticMesh *pStaticMesh, const Transform &transform, uint32 shadowFlags) : RenderProxy(entityId), m_visibility(true), m_pStaticMesh(nullptr), m_shadowFlags(shadowFlags), m_tintEnabled(false), m_tintColor(0xFFFFFFFF), m_bGPUResourcesCreated(false) { uint32 i; DebugAssert(pStaticMesh != nullptr); m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); // allocate materials m_materials.Resize(pStaticMesh->GetMaterialCount()); for (i = 0; i < pStaticMesh->GetMaterialCount(); i++) { m_materials[i] = pStaticMesh->GetMaterial(i); DebugAssert(m_materials[i] != nullptr); m_materials[i]->AddRef(); } // update bounds SetTransform(transform); } StaticMeshRenderProxy::~StaticMeshRenderProxy() { uint32 i; ReleaseDeviceResources(); m_pStaticMesh->Release(); for (i = 0; i < m_materials.GetSize(); i++) m_materials[i]->Release(); } void StaticMeshRenderProxy::SetStaticMesh(const StaticMesh *pStaticMesh) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetStaticMesh(pStaticMesh); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); ReferenceCountedHolder<const StaticMesh> pStaticMeshHolder(pStaticMesh); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, pStaticMeshHolder]() { pThisHolder->RealSetStaticMesh(pStaticMeshHolder); }); } } void StaticMeshRenderProxy::RealSetStaticMesh(const StaticMesh *pStaticMesh) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pStaticMesh != nullptr); if (m_pStaticMesh == pStaticMesh) return; // not yet owned by render thread, so no need to do async modifications ReleaseDeviceResources(); // release materials for (uint32 i = 0; i < m_materials.GetSize(); i++) { m_materials[i]->Release(); m_materials[i] = NULL; } // release mesh m_pStaticMesh->Release(); // set new mesh m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); // reallocate materials m_materials.Resize(m_pStaticMesh->GetMaterialCount()); m_materials.Shrink(); for (uint32 i = 0; i < m_pStaticMesh->GetMaterialCount(); i++) { m_materials[i] = m_pStaticMesh->GetMaterial(i); DebugAssert(m_materials[i] != nullptr); m_materials[i]->AddRef(); } // fix up bounds SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere())); } void StaticMeshRenderProxy::SetMaterial(uint32 i, const Material *pMaterialOverride) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetMaterial(i, pMaterialOverride); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); ReferenceCountedHolder<const Material> pMaterialHolder(pMaterialOverride); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, i, pMaterialHolder]() { pThisHolder->RealSetMaterial(i, pMaterialHolder); }); } } void StaticMeshRenderProxy::RealSetMaterial(uint32 i, const Material *pMaterialOverride) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pMaterialOverride != nullptr); // not yet owned by render thread, so no need to do async modifications DebugAssert(i < m_materials.GetSize()); m_materials[i]->Release(); m_materials[i] = pMaterialOverride; m_materials[i]->AddRef(); } void StaticMeshRenderProxy::SetTransform(const Transform &transform) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTransform(transform); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, transform]() { pThisHolder->RealSetTransform(transform); }); } } void StaticMeshRenderProxy::RealSetTransform(const Transform &transform) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_transform = transform; m_localToWorldMatrix = m_transform.GetTransformMatrix4x4(); SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere())); } void StaticMeshRenderProxy::SetTintColor(bool enabled, uint32 color /* = 0 */) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTintColor(enabled, color); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, enabled, color]() { pThisHolder->RealSetTintColor(enabled, color); }); } } void StaticMeshRenderProxy::RealSetTintColor(bool enabled, uint32 color /*= 0*/) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_tintEnabled = enabled; m_tintColor = (enabled) ? color : 0xFFFFFFFF; } void StaticMeshRenderProxy::SetVisibility(bool visible) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetVisibility(visible); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, visible]() { pThisHolder->RealSetVisibility(visible); }); } } void StaticMeshRenderProxy::RealSetVisibility(bool visible) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_visibility = visible; } void StaticMeshRenderProxy::SetShadowFlags(uint32 shadowFlags) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetShadowFlags(shadowFlags); } else { ReferenceCountedHolder<StaticMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, shadowFlags]() { pThisHolder->RealSetShadowFlags(shadowFlags); }); } } void StaticMeshRenderProxy::RealSetShadowFlags(uint32 shadowFlags) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_shadowFlags = shadowFlags; } void StaticMeshRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_visibility) return; // check gpu resources if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; // Select the LOD index we are drawing for. uint32 selectedLOD = 0; DebugAssert(selectedLOD < m_pStaticMesh->GetLODCount()); // Store the requested render passes. uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOW_MAP; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; // if (hasLightMaps && (availableRenderPassMask & RENDER_PASS_LIGHTMAP)) // wantedRenderPasses = (wantedRenderPasses & ~(RENDER_PASS_STATIC_OPAQUE_LIGHTING | RENDER_PASS_STATIC_TRANSPARENT_LIGHTING)) | RENDER_PASS_LIGHTMAP; if (m_tintEnabled) wantedRenderPasses |= RENDER_PASS_TINT; // skip for no passes if ((pRenderQueue->GetAcceptingRenderPassMask() & wantedRenderPasses) == 0) return; // Calculate view distance float viewDistance = pCamera->CalculateDepthToPoint(GetBoundingSphere().GetCenter()); // Draw this LOD. const StaticMesh::LOD *pLOD = m_pStaticMesh->GetLOD(selectedLOD); for (uint32 i = 0; i < pLOD->GetBatchCount(); i++) { // Get batch info. const StaticMesh::Batch *pBatch = pLOD->GetBatch(i); // Get material. const Material *pMaterial = m_materials[pBatch->MaterialIndex]; // Determine render passes. There isn't really any passes that a static mesh can't handle, so we only remove the material ones. uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); // Add to render queue if we have any render passes. if (renderPassMask != 0) { RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); queueEntry.VertexFactoryFlags = m_pStaticMesh->GetVertexFactoryFlags(); queueEntry.pMaterial = pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.UserData[0] = selectedLOD; queueEntry.UserData[1] = i; queueEntry.TintColor = m_tintColor; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } void StaticMeshRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { uint32 lodIndex = pQueueEntry->UserData[0]; const StaticMesh::LOD *pLOD = m_pStaticMesh->GetLOD(lodIndex); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_localToWorldMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pLOD->GetVertexBuffers()->BindBuffers(pCommandList); pCommandList->SetIndexBuffer(pLOD->GetIndexBuffer(), pLOD->GetIndexFormat(), 0); } void StaticMeshRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { uint32 lodIndex = pQueueEntry->UserData[0]; uint32 batchIndex = pQueueEntry->UserData[1]; const StaticMesh::Batch *pBatch = m_pStaticMesh->GetLOD(lodIndex)->GetBatch(batchIndex); pCommandList->DrawIndexed(pBatch->StartIndex, pBatch->NumIndices, 0); } bool StaticMeshRenderProxy::CreateDeviceResources() const { uint32 i; if (m_bGPUResourcesCreated) return true; if (!m_pStaticMesh->CreateGPUResources()) return false; for (i = 0; i < m_materials.GetSize(); i++) { if (!m_materials[i]->CreateDeviceResources()) return false; } //if (m_VertexBuffers.GetInputLayout() == nullptr) //m_VertexBuffers.SetInputLayout(m_pStaticMesh->GetVertexBuffers()->GetInputLayout()); //if (m_VertexBuffers.GetBuffer(0) == nullptr) //LocalVertexFactory::ShareVerticesBuffer(&m_VertexBuffers, m_pStaticMesh->GetVertexBuffers()); m_bGPUResourcesCreated = true; return true; } void StaticMeshRenderProxy::ReleaseDeviceResources() const { //m_VertexBuffers.Clear(); m_bGPUResourcesCreated = false; } <file_sep>/Engine/Source/Core/TexturePacker.cpp #include "Core/PrecompiledHeader.h" #include "Core/TexturePacker.h" #include "YBaseLib/Log.h" Log_SetChannel(TexturePacker); TexturePacker::TexturePacker(PIXEL_FORMAT pixelFormat) : m_pixelFormat(pixelFormat) { } TexturePacker::~TexturePacker() { for (uint32 i = 0; i < m_images.GetSize(); i++) delete m_images[i].pImage; } bool TexturePacker::AddImage(const Image *pImage, uint32 paddingAmount, void *pReferenceData) { if (pImage->GetPixelFormat() != m_pixelFormat) return false; ImageToPack itp; itp.pImage = new Image(*pImage); itp.PaddingAmount = paddingAmount; itp.TotalArea = (pImage->GetWidth() + (paddingAmount * 2)) + (pImage->GetHeight() + (paddingAmount * 2)); itp.pReferenceData = pReferenceData; m_images.Add(itp); return true; } void TexturePacker::GuessPackedImageDimensions(uint32 *pWidth, uint32 *pHeight) { // get the total area of all images uint32 areaSum = 0; for (uint32 i = 0; i < m_images.GetSize(); i++) areaSum += m_images[i].TotalArea; // shouldn't be zero.. areaSum = Max(areaSum, (uint32)1); // assume a square texture, sqrt() the area, and select the next power of 2 uint32 textureDimensions = Y_nextpow2((uint32)Math::Truncate(Math::Round(Math::Sqrt((float)areaSum)))); *pWidth = textureDimensions; *pHeight = textureDimensions; } bool TexturePacker::Pack(uint32 textureWidth, uint32 textureHeight, float paddingR /* = 0.0f */, float paddingG /* = 0.0f */, float paddingB /* = 0.0f */, float paddingA /* = 0.0f */) { Log_DevPrintf("TexturePacker::Pack: Packing %u images to %ux%u texture", m_images.GetSize(), textureWidth, textureHeight); // sort images, largest -> smallest m_images.Sort([](const ImageToPack *pLeft, const ImageToPack *pRight) { return static_cast<int32>(pLeft->TotalArea) - static_cast<int32>(pRight->TotalArea); }); // create one node encompassing the entire texture m_nodes.Add(Node(0, 0, textureWidth, textureHeight)); // try to pack each image for (uint32 i = 0; i < m_images.GetSize(); i++) { const ImageToPack &img = m_images[i]; int32 nodeIndex = TryInsertIntoNode(0, img.pImage->GetWidth() + (img.PaddingAmount * 2), img.pImage->GetHeight() + (img.PaddingAmount * 2)); if (nodeIndex == -1) { // pack failed Log_ErrorPrintf("failed to pack image %u %ux%u", i, img.pImage->GetWidth(), img.pImage->GetHeight()); m_nodes.Clear(); return false; } //Log_DevPrintf("img[%u, %ux%u] -> %i (%u %u)", i, img.pImage->GetWidth(), img.pImage->GetHeight(), nodeIndex, m_nodes[nodeIndex].Left, m_nodes[nodeIndex].Top); DebugAssert(m_nodes[nodeIndex].pImage == nullptr); m_nodes[nodeIndex].pImage = &img; m_nodes[nodeIndex].pReferenceData = img.pReferenceData; } // create the output image, and zero all pixels m_packedImage.Create(m_pixelFormat, textureWidth, textureHeight, 1); // allocate a 1x1 image of the padding colour { uint32 paddingImageSize = PixelFormat_CalculateImageSize(m_pixelFormat, 1, 1, 1); byte *pPaddingPixel = new byte[paddingImageSize]; float sourcePixel[4] = { paddingR, paddingG, paddingB, paddingA }; if (!PixelFormat_ConvertPixels(1, 1, sourcePixel, sizeof(sourcePixel), PIXEL_FORMAT_R32G32B32A32_FLOAT, pPaddingPixel, paddingImageSize, m_pixelFormat, &paddingImageSize)) { Log_ErrorPrintf("failed to allocate padding pixel"); delete[] pPaddingPixel; m_nodes.Clear(); return false; } // replace every pixel in the image with the padding pixel [slowww] for (uint32 y = 0; y < textureHeight; y++) { byte *pDestRow = m_packedImage.GetData() + (m_packedImage.GetDataRowPitch() * y); for (uint32 x = 0; x < textureWidth; x++) { Y_memcpy(pDestRow, pPaddingPixel, paddingImageSize); pDestRow += paddingImageSize; } DebugAssert(pDestRow <= m_packedImage.GetData() + (m_packedImage.GetDataRowPitch() * (y + 1))); } delete[] pPaddingPixel; } // pack each node into the texture for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; // skip branch nodes, or leaf nodes with no data if (!node.IsLeaf || node.pImage == nullptr) continue; // get the image const ImageToPack *img = node.pImage; // blit it into place if (!m_packedImage.Blit(node.Left + img->PaddingAmount, node.Top + img->PaddingAmount, *img->pImage, 0, 0, img->pImage->GetWidth(), img->pImage->GetHeight())) { Log_ErrorPrintf("failed to blit image"); m_nodes.Clear(); return false; } } // all done return true; } int32 TexturePacker::TryInsertIntoNode(int32 nodeIndex, uint32 neededWidth, uint32 neededHeight) { int32 insertedID; if (!m_nodes[nodeIndex].IsLeaf) { // try first child insertedID = TryInsertIntoNode(m_nodes[nodeIndex].ChildIndices[0], neededWidth, neededHeight); if (insertedID != -1) return insertedID; // try second child insertedID = TryInsertIntoNode(m_nodes[nodeIndex].ChildIndices[1], neededWidth, neededHeight); if (insertedID != -1) return insertedID; // nope return -1; } else { // leaf node // skip nodes that are used if (m_nodes[nodeIndex].IsUsed) return -1; // do we fit into this leaf? uint32 nodeLeft = m_nodes[nodeIndex].Left; uint32 nodeTop = m_nodes[nodeIndex].Top; uint32 nodeWidth = m_nodes[nodeIndex].Width; uint32 nodeHeight = m_nodes[nodeIndex].Height; if (nodeWidth < neededWidth || nodeHeight < neededHeight) return -1; // perfect fit? if (nodeWidth == neededWidth && nodeHeight == neededHeight) { m_nodes[nodeIndex].IsUsed = true; return nodeIndex; } // determine split direction and split the node uint32 dw = nodeWidth - neededWidth; uint32 dh = nodeHeight - neededHeight; if (dw > dh) { // split horizontally Node child0(nodeLeft, nodeTop, neededWidth, nodeHeight); Node child1(nodeLeft + neededWidth, nodeTop, dw - 1, nodeHeight); m_nodes[nodeIndex].ChildIndices[0] = (int32)m_nodes.GetSize(); m_nodes.Add(child0); m_nodes[nodeIndex].ChildIndices[1] = (int32)m_nodes.GetSize(); m_nodes.Add(child1); m_nodes[nodeIndex].IsLeaf = false; } else { // split vertically Node child0(nodeLeft, nodeTop, nodeWidth, neededHeight); Node child1(nodeLeft, nodeTop + neededHeight, nodeWidth, dh - 1); m_nodes[nodeIndex].ChildIndices[0] = (int32)m_nodes.GetSize(); m_nodes.Add(child0); m_nodes[nodeIndex].ChildIndices[1] = (int32)m_nodes.GetSize(); m_nodes.Add(child1); m_nodes[nodeIndex].IsLeaf = false; } // reinsert into this node, this should go into the first child return TryInsertIntoNode(m_nodes[nodeIndex].ChildIndices[0], neededWidth, neededHeight); } } bool TexturePacker::GetImageLocation(void *pReferenceData, uint32 *pLeft, uint32 *pRight, uint32 *pTop, uint32 *pBottom) { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; if (node.pReferenceData == pReferenceData) { DebugAssert(node.pImage != nullptr); uint32 paddingAmount = node.pImage->PaddingAmount; DebugAssert(node.Width > (paddingAmount * 2)); *pLeft = node.Left + paddingAmount; *pRight = node.Left + paddingAmount + node.Width - 1 - paddingAmount; *pTop = node.Top + paddingAmount; *pBottom = node.Top + paddingAmount + node.Height - 1 - paddingAmount; return true; } } return false; } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunk.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldChunk.h" #include "BlockEngine/BlockWorldSection.h" #include "BlockEngine/BlockWorldMesher.h" #include "BlockEngine/BlockWorldChunkRenderProxy.h" #include "BlockEngine/BlockWorldChunkCollisionShape.h" #include "BlockEngine/BlockWorld.h" #include "Engine/Physics/StaticObject.h" #include "Renderer/Renderer.h" Log_SetChannel(BlockWorldChunk); BlockWorldChunk::BlockWorldChunk(BlockWorldSection *pSection, int32 relativeChunkX, int32 relativeChunkY, int32 relativeChunkZ) : m_pSection(pSection), m_chunkSize(pSection->GetChunkSize()), m_loadedLODLevel(pSection->GetWorld()->GetLODLevels()), m_renderLODLevel(pSection->GetWorld()->GetLODLevels()), m_relativeChunkX(relativeChunkX), m_relativeChunkY(relativeChunkY), m_relativeChunkZ(relativeChunkZ), m_globalChunkX(pSection->GetBaseChunkX() + relativeChunkX), m_globalChunkY(pSection->GetBaseChunkY() + relativeChunkY), m_globalChunkZ(relativeChunkZ), m_pCollisionShape(nullptr), m_pCollisionObject(nullptr), m_pRenderProxy(nullptr), m_meshState(MeshState_Idle) { // calculate base position, or translation m_basePosition.Set(static_cast<float>((pSection->GetBaseChunkX() + relativeChunkX) * m_chunkSize), static_cast<float>((pSection->GetBaseChunkY() + relativeChunkY) * m_chunkSize), static_cast<float>(relativeChunkZ * m_chunkSize)); // calculate bounding box -- fixme for LOD m_boundingBox = BlockWorld::CalculateChunkBoundingBox(m_chunkSize, m_globalChunkX, m_globalChunkY, m_globalChunkZ); // combine into one allocation Y_memzero(m_pBlockValues, sizeof(m_pBlockValues)); Y_memzero(m_pBlockData, sizeof(m_pBlockData)); Y_memzero(m_zStride, sizeof(m_zStride)); // allocate collision shape and object m_pCollisionShape = new BlockWorldChunkCollisionShape(pSection->GetWorld()->GetPalette(), m_chunkSize, this); m_pCollisionObject = new Physics::StaticObject(0, m_pCollisionShape, Transform(m_basePosition, Quaternion::Identity, float3::One)); } BlockWorldChunk::~BlockWorldChunk() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); // kill all data levels for (int32 i = BLOCK_WORLD_MAX_LOD_LEVELS - 1; i >= 0; i--) { delete[] m_pBlockData[i]; delete[] m_pBlockValues[i]; } m_pCollisionObject->Release(); m_pCollisionShape->Release(); } void BlockWorldChunk::Create() { int32 lodLevels = m_pSection->GetWorld()->GetLODLevels(); for (int32 lodLevel = 0; lodLevel < lodLevels; lodLevel++) { // allocate block values, data and set z stride int32 blockCount = (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel); m_pBlockValues[lodLevel] = new BlockWorldBlockType[blockCount]; Y_memzero(m_pBlockValues[lodLevel], sizeof(BlockWorldBlockType) * blockCount); m_pBlockData[lodLevel] = new BlockWorldBlockDataType[blockCount]; Y_memzero(m_pBlockData[lodLevel], sizeof(BlockWorldBlockDataType) * blockCount); m_zStride[lodLevel] = (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel); } // has everything loaded to start with m_loadedLODLevel = 0; } bool BlockWorldChunk::LoadFromStream(int32 lodLevel, ByteStream *pStream) { // allocate block values, data and set z stride int32 blockCount = (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel); if (m_pBlockValues[lodLevel] == nullptr) { DebugAssert(m_pBlockData[lodLevel] == nullptr && m_zStride[lodLevel] == 0); m_pBlockValues[lodLevel] = new BlockWorldBlockType[blockCount]; m_pBlockData[lodLevel] = new BlockWorldBlockDataType[blockCount]; m_zStride[lodLevel] = (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel); } // read in block values, then data if (!pStream->Read2(m_pBlockValues[lodLevel], sizeof(BlockWorldBlockType) * blockCount) || !pStream->Read2(m_pBlockData[lodLevel], sizeof(BlockWorldBlockDataType) * blockCount)) { //delete[] m_pBlockData[lodLevel]; //m_pBlockData[lodLevel] = nullptr; //delete[] m_pBlockValues[lodLevel]; //m_pBlockValues[lodLevel] = nullptr; //m_zStride[lodLevel] = 0; return false; } // update loaded level m_loadedLODLevel = Min(m_loadedLODLevel, lodLevel); return true; } bool BlockWorldChunk::SaveToStream(int32 lodLevel, ByteStream *pStream) { int32 blockCount = (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel) * (m_chunkSize >> lodLevel); DebugAssert(m_pBlockValues[lodLevel] != nullptr); // write block values, then data if (!pStream->Write2(m_pBlockValues[lodLevel], sizeof(BlockWorldBlockType) * blockCount) || !pStream->Write2(m_pBlockData[lodLevel], sizeof(BlockWorldBlockDataType) * blockCount)) { return false; } return true; } void BlockWorldChunk::UnloadLODLevel(int32 lodLevel) { delete[] m_pBlockData[lodLevel]; m_pBlockData[lodLevel] = nullptr; delete[] m_pBlockValues[lodLevel]; m_pBlockValues[lodLevel] = nullptr; m_zStride[lodLevel] = 0; // is this the highest lod level? update the loaded level if (lodLevel == m_loadedLODLevel) { int32 lodLevels = m_pSection->GetWorld()->GetLODLevels(); for (m_loadedLODLevel = lodLevel + 1; m_loadedLODLevel < lodLevels; m_loadedLODLevel++) { if (m_pBlockValues[m_loadedLODLevel] != nullptr) break; } } } bool BlockWorldChunk::IsAirChunk() const { uint32 blockCount = m_chunkSize * m_chunkSize * m_chunkSize; for (uint32 i = 0; i < blockCount; i++) { if (m_pBlockValues[i] != 0) return false; } return true; } BlockWorldBlockType BlockWorldChunk::GetBlock(int32 lodLevel, int32 bx, int32 by, int32 bz) const { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); return m_pBlockValues[lodLevel][(bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx]; } void BlockWorldChunk::SetBlock(int32 lodLevel, int32 bx, int32 by, int32 bz, BlockWorldBlockType blockType) { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); DebugAssert((blockType & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) != 0 || blockType < BLOCK_MESH_MAX_BLOCK_TYPES); uint32 index = (bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx; if (m_pBlockValues[lodLevel][index] == blockType) return; m_pBlockValues[lodLevel][index] = blockType; } BlockWorldBlockDataType BlockWorldChunk::GetBlockData(int32 lodLevel, int32 bx, int32 by, int32 bz) const { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); return m_pBlockData[lodLevel][(bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx]; } void BlockWorldChunk::SetBlockData(int32 lodLevel, int32 bx, int32 by, int32 bz, BlockWorldBlockDataType blockType) { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); uint32 index = (bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx; if (m_pBlockData[lodLevel][index] == blockType) return; m_pBlockData[lodLevel][index] = blockType; } uint8 BlockWorldChunk::GetBlockLight(int32 lodLevel, int32 bx, int32 by, int32 bz) const { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); return BLOCK_WORLD_BLOCK_DATA_GET_LIGHTING(m_pBlockData[lodLevel][(bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx]); } void BlockWorldChunk::SetBlockLight(int32 lodLevel, int32 bx, int32 by, int32 bz, uint8 lightLevel) { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); uint32 index = (bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx; uint8 data = m_pBlockData[lodLevel][index]; if (BLOCK_WORLD_BLOCK_DATA_GET_LIGHTING(data) == lightLevel) return; m_pBlockData[lodLevel][index] = BLOCK_WORLD_BLOCK_DATA_SET_LIGHTING(data, lightLevel); } uint8 BlockWorldChunk::GetBlockRotation(int32 lodLevel, int32 bx, int32 by, int32 bz) const { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); return BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(m_pBlockData[lodLevel][(bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx]); } void BlockWorldChunk::SetBlockRotation(int32 lodLevel, int32 bx, int32 by, int32 bz, uint8 rotation) { DebugAssert(bx < (m_chunkSize >> lodLevel) && by < (m_chunkSize >> lodLevel) && bz < (m_chunkSize >> lodLevel)); uint32 index = (bz * m_zStride[lodLevel]) + (by * (m_chunkSize >> lodLevel)) + bx; uint8 data = m_pBlockData[lodLevel][index]; if (BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(data) == rotation) return; m_pBlockData[lodLevel][index] = BLOCK_WORLD_BLOCK_DATA_SET_ROTATION(data, rotation); } void BlockWorldChunk::UpdateLODs(int32 lodLevel, int32 blockX, int32 blockY, int32 blockZ) { // should be at lod 0 int32 lodLevels = m_pSection->GetWorld()->GetLODLevels(); DebugAssert(m_loadedLODLevel == 0); // skip if the next level is this level if (lodLevel == (lodLevels - 1)) return; // gather the 8 blocks int32 baseBlockX = blockX & ~1; int32 baseBlockY = blockY & ~1; int32 baseBlockZ = blockZ & ~1; BlockWorldBlockType blocks[8]; blocks[0] = GetBlock(lodLevel, baseBlockX + 0, baseBlockY + 0, baseBlockZ + 0); blocks[1] = GetBlock(lodLevel, baseBlockX + 1, baseBlockY + 0, baseBlockZ + 0); blocks[2] = GetBlock(lodLevel, baseBlockX + 0, baseBlockY + 1, baseBlockZ + 0); blocks[3] = GetBlock(lodLevel, baseBlockX + 1, baseBlockY + 1, baseBlockZ + 0); blocks[4] = GetBlock(lodLevel, baseBlockX + 0, baseBlockY + 0, baseBlockZ + 1); blocks[5] = GetBlock(lodLevel, baseBlockX + 1, baseBlockY + 0, baseBlockZ + 1); blocks[6] = GetBlock(lodLevel, baseBlockX + 0, baseBlockY + 1, baseBlockZ + 1); blocks[7] = GetBlock(lodLevel, baseBlockX + 1, baseBlockY + 1, baseBlockZ + 1); BlockWorldBlockDataType blockData[8]; blockData[0] = GetBlockData(lodLevel, baseBlockX + 0, baseBlockY + 0, baseBlockZ + 0); blockData[1] = GetBlockData(lodLevel, baseBlockX + 1, baseBlockY + 0, baseBlockZ + 0); blockData[2] = GetBlockData(lodLevel, baseBlockX + 0, baseBlockY + 1, baseBlockZ + 0); blockData[3] = GetBlockData(lodLevel, baseBlockX + 1, baseBlockY + 1, baseBlockZ + 0); blockData[4] = GetBlockData(lodLevel, baseBlockX + 0, baseBlockY + 0, baseBlockZ + 1); blockData[5] = GetBlockData(lodLevel, baseBlockX + 1, baseBlockY + 0, baseBlockZ + 1); blockData[6] = GetBlockData(lodLevel, baseBlockX + 0, baseBlockY + 1, baseBlockZ + 1); blockData[7] = GetBlockData(lodLevel, baseBlockX + 1, baseBlockY + 1, baseBlockZ + 1); //Log_DevPrintf("BLOCK SET %i [%i,%i,%i] (base %i %i %i) [[[%u]]]", lodLevel, blockX, blockY, blockZ, baseBlockX, baseBlockY, baseBlockZ, pChunk->GetBlock(blockX, blockY, blockZ)); // do average operation fixme BlockWorldBlockType lodBlockValue = blocks[0]; BlockWorldBlockDataType lodBlockData = blockData[0]; for (uint32 i = 0; i < 8; i++) { if (blocks[i] != 0) { lodBlockValue = blocks[i]; lodBlockData = blockData[i]; break; } } //if (lodBlockValue == 0) //Log_WarningPrintf("no block found"); // get next level chunk coordinates int32 nextLevel = lodLevel + 1; int32 nextLevelBlockX = baseBlockX / 2; int32 nextLevelBlockY = baseBlockY / 2; int32 nextLevelBlockZ = baseBlockZ / 2; //Log_DevPrintf(" SET LOD %i BLOCK %i,%i,%i -> %u", lodLevel + 1, nextLevelBlockX, nextLevelBlockY, nextLevelBlockZ, lodBlockValue); // set the next level block SetBlock(nextLevel, nextLevelBlockX, nextLevelBlockY, nextLevelBlockZ, lodBlockValue); SetBlockData(nextLevel, nextLevelBlockX, nextLevelBlockY, nextLevelBlockZ, lodBlockData); // update the next level of detail UpdateLODs(lodLevel + 1, nextLevelBlockX, nextLevelBlockY, nextLevelBlockZ); } <file_sep>/DemoGame/Source/DemoGame/LaunchpadGameState.h #pragma once #include "BaseGame/BaseGame.h" class DemoGame; class BaseDemoGameState; class LaunchpadGameState : public GameState { public: LaunchpadGameState(DemoGame *pDemoGame); virtual ~LaunchpadGameState(); protected: // implemented events virtual void OnSwitchedIn() override final; virtual void OnSwitchedOut() override final; virtual void OnBeforeDelete() override final; virtual void OnWindowResized(uint32 width, uint32 height) override final; virtual void OnWindowFocusGained() override final; virtual void OnWindowFocusLost() override final; virtual bool OnWindowEvent(const union SDL_Event *event) override final; virtual void OnMainThreadPreFrame(float deltaTime) override final; virtual void OnMainThreadBeginFrame(float deltaTime) override final; virtual void OnMainThreadAsyncTick(float deltaTime) override final; virtual void OnMainThreadTick(float deltaTime) override final; virtual void OnMainThreadEndFrame(float deltaTime) override final; virtual void OnRenderThreadPreFrame(float deltaTime) override final; virtual void OnRenderThreadBeginFrame(float deltaTime) override final; virtual void OnRenderThreadDraw(float deltaTime) override final; virtual void OnRenderThreadEndFrame(float deltaTime) override final; private: DemoGame *m_pDemoGame; // demo runner bool RunDemo(BaseDemoGameState *pGameState); // demo runner bool InvokeSkeletalAnimationDemo(); bool InvokeImGuiDemo(); bool InvokeDrawCallStressDemo(); }; <file_sep>/Engine/Source/Engine/Physics/PhysicsProxy.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/PhysicsProxy.h" namespace Physics { PhysicsProxy::PhysicsProxy(uint32 entityID) : m_entityID(entityID), m_boundingBox(AABox::Zero), m_pPhysicsWorld(nullptr) { } PhysicsProxy::~PhysicsProxy() { DebugAssert(m_pPhysicsWorld == nullptr); } void PhysicsProxy::OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) { DebugAssert(m_pPhysicsWorld == nullptr); m_pPhysicsWorld = pPhysicsWorld; } void PhysicsProxy::OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) { DebugAssert(m_pPhysicsWorld == pPhysicsWorld); m_pPhysicsWorld = nullptr; } void PhysicsProxy::OnSynchronize() { } } // namespace Physics <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUContext.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12CommandQueue.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" #include "D3D12Renderer/D3D12LinearHeaps.h" class D3D12GPUContext : public GPUContext { public: D3D12GPUContext(D3D12GPUDevice *pDevice, ID3D12Device *pD3DDevice, D3D12CommandQueue *pGraphicsCommandQueue); ~D3D12GPUContext(); // Start of frame virtual void BeginFrame() override final; // Ensure all queued commands are sent to the GPU. virtual void Flush() override final; // Ensure all commands have been completed by the GPU. virtual void Finish() override final; // State clearing virtual void ClearState(bool clearShaders = true, bool clearBuffers = true, bool clearStates = true, bool clearRenderTargets = true) override final; // Retrieve RendererVariables interface. virtual GPUContextConstants *GetConstants() override final { return m_pConstants; } // State Management (D3D12RenderSystem.cpp) virtual GPURasterizerState *GetRasterizerState() override final; virtual void SetRasterizerState(GPURasterizerState *pRasterizerState) override final; virtual GPUDepthStencilState *GetDepthStencilState() override final; virtual uint8 GetDepthStencilStateStencilRef() override final; virtual void SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) override final; virtual GPUBlendState *GetBlendState() override final; virtual const float4 &GetBlendStateBlendFactor() override final; virtual void SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor = float4::One) override final; // Viewport Management (D3D12RenderSystem.cpp) virtual const RENDERER_VIEWPORT *GetViewport() override final; virtual void SetViewport(const RENDERER_VIEWPORT *pNewViewport) override final; virtual void SetFullViewport(GPUTexture *pForRenderTarget = NULL) override final; // Scissor Rect Management (D3D12RenderSystem.cpp) virtual const RENDERER_SCISSOR_RECT *GetScissorRect() override final; virtual void SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) override final; // Buffer mapping/reading/writing virtual bool ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) override final; virtual bool WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) override final; virtual bool MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) override final; virtual void Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) override final; // Texture reading/writing virtual bool ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) override final; virtual bool ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) override final; virtual bool WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; // Texture copying virtual bool CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) override final; virtual bool CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) override final; // Blit (copy) a texture to the currently bound framebuffer. If this texture is a different size, it'll be resized virtual void BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter = RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST) override final; // Mip generation virtual void GenerateMips(GPUTexture *pTexture) override final; // Query accessing virtual bool BeginQuery(GPUQuery *pQuery) override final; virtual bool EndQuery(GPUQuery *pQuery) override final; virtual GPU_QUERY_GETDATA_RESULT GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) override final; // Predicated drawing virtual void SetPredication(GPUQuery *pQuery) override final; // RT Clearing virtual void ClearTargets(bool clearColor = true, bool clearDepth = true, bool clearStencil = true, const float4 &clearColorValue = float4::Zero, float clearDepthValue = 1.0f, uint8 clearStencilValue = 0) override final; virtual void DiscardTargets(bool discardColor = true, bool discardDepth = true, bool discardStencil = true) override final; // Swap chain virtual GPUOutputBuffer *GetOutputBuffer() override final; virtual void SetOutputBuffer(GPUOutputBuffer *pSwapChain) override final; virtual bool GetExclusiveFullScreen() override final; virtual bool SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) override final; virtual bool ResizeOutputBuffer(uint32 width = 0, uint32 height = 0) override final; virtual void PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) override final; // RT Changing virtual uint32 GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) override final; virtual void SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) override final; // Drawing Setup virtual DRAW_TOPOLOGY GetDrawTopology() override final; virtual void SetDrawTopology(DRAW_TOPOLOGY topology) override final; // Vertex Buffer Setup virtual uint32 GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) override final; virtual void SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) override final; virtual void SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) override final; virtual void GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) override final; virtual void SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) override final; // Shader Setup virtual void SetShaderProgram(GPUShaderProgram *pShaderProgram) override final; virtual void SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) override final; virtual void SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) override final; virtual void SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) override final; virtual void SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) override final; virtual void SetShaderParameterResource(uint32 index, GPUResource *pResource) override final; virtual void SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) override final; // constant buffer management virtual void WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit = false) override final; virtual void WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit = false) override final; virtual void CommitConstantBuffer(uint32 bufferIndex) override final; // Draw calls virtual void Draw(uint32 firstVertex, uint32 nVertices) override final; virtual void DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) override final; virtual void DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) override final; virtual void DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) override final; // Draw calls with user-space buffer virtual void DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) override final; // Compute shaders virtual void Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) override final; // Command list execution virtual GPUCommandList *CreateCommandList() override final; virtual bool OpenCommandList(GPUCommandList *pCommandList) override final; virtual bool CloseCommandList(GPUCommandList *pCommandList) override final; virtual void ExecuteCommandList(GPUCommandList *pCommandList) override final; // --- our methods --- // accessors ID3D12Device *GetD3DDevice() const { return m_pD3DDevice; } ID3D12GraphicsCommandList *GetCurrentCommandList() const { return m_pCommandList; } D3D12GPUShaderProgram *GetD3D12ShaderProgram() const { return m_pCurrentShaderProgram; } // create device bool Create(); // access the gpu virtual address for a constant buffer bool GetPerDrawConstantBufferGPUAddress(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS *pAddress); // access to shader states for the shader mutators to modify void SetShaderConstantBuffers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle); void SetShaderResources(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle); void SetShaderSamplers(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle); void SetShaderUAVs(SHADER_PROGRAM_STAGE stage, uint32 index, const D3D12DescriptorHandle &handle); void SetPerDrawConstantBuffer(uint32 index, D3D12_GPU_VIRTUAL_ADDRESS address); // synchronize the states with the d3d context void SynchronizeRenderTargetsAndUAVs(); // temporarily disable predication to force a call to go through void BypassPredication(); void RestorePredication(); // create a resource barrier on the current command list void ResourceBarrier(ID3D12Resource *pResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState); void ResourceBarrier(ID3D12Resource *pResource, uint32 subResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState); // allocate from scratch buffer bool AllocateScratchBufferMemory(uint32 size, uint32 alignment, ID3D12Resource **ppScratchBufferResource, uint32 *pScratchBufferOffset, void **ppCPUPointer, D3D12_GPU_VIRTUAL_ADDRESS *pGPUAddress); bool AllocateScratchView(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle); bool AllocateScratchSamplers(uint32 count, D3D12_CPU_DESCRIPTOR_HANDLE *pOutCPUHandle, D3D12_GPU_DESCRIPTOR_HANDLE *pOutGPUHandle); private: // preallocate constant buffers void CreateConstantBuffers(); bool CreateInternalCommandList(); void CloseAndExecuteCommandList(bool waitForCompletion, bool forceWithoutDrawCommands); void ResetCommandList(bool restoreState, bool refreshAllocators); void GetNewAllocators(uint64 fenceValue); void UpdateShaderDescriptorHeaps(); bool UpdatePipelineState(bool force); void GetCurrentRenderTargetDimensions(uint32 *width, uint32 *height); D3D12_RESOURCE_STATES GetCurrentResourceState(GPUResource *pResource); bool IsBoundAsRenderTarget(GPUTexture *pTexture); bool IsBoundAsDepthBuffer(GPUTexture *pTexture); bool IsBoundAsUnorderedAccess(GPUResource *pResource); void UpdateScissorRect(); D3D12GPUDevice *m_pDevice; ID3D12Device *m_pD3DDevice; D3D12CommandQueue *m_pGraphicsCommandQueue; GPUContextConstants *m_pConstants; // Created once ID3D12GraphicsCommandList *m_pCommandList; // Current allocators ID3D12CommandAllocator *m_pCurrentCommandAllocator; D3D12LinearBufferHeap *m_pCurrentScratchBuffer; D3D12LinearDescriptorHeap *m_pCurrentScratchViewHeap; D3D12LinearDescriptorHeap *m_pCurrentScratchSamplerHeap; // number of commands queued to command list uint32 m_commandCounter; // state RENDERER_VIEWPORT m_currentViewport; RENDERER_SCISSOR_RECT m_scissorRect; DRAW_TOPOLOGY m_currentTopology; D3D12_PRIMITIVE_TOPOLOGY_TYPE m_currentD3DTopologyType; D3D12GPUBuffer *m_pCurrentVertexBuffers[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; uint32 m_currentVertexBufferOffsets[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; uint32 m_currentVertexBufferStrides[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; uint32 m_currentVertexBufferBindCount; D3D12GPUBuffer *m_pCurrentIndexBuffer; GPU_INDEX_FORMAT m_currentIndexFormat; uint32 m_currentIndexBufferOffset; D3D12GPUShaderProgram *m_pCurrentShaderProgram; // constant buffers struct ConstantBuffer { byte *pLocalMemory; uint32 Size; int32 DirtyLowerBounds; int32 DirtyUpperBounds; D3D12_GPU_VIRTUAL_ADDRESS LastAddress; bool PerDraw; }; MemArray<ConstantBuffer> m_constantBuffers; // shader stage state struct ShaderStageState { bool ConstantBuffersDirty; bool ResourcesDirty; bool SamplersDirty; bool UAVsDirty; D3D12_CPU_DESCRIPTOR_HANDLE CBVTableCPUHandle; D3D12_CPU_DESCRIPTOR_HANDLE SRVTableCPUHandle; D3D12_CPU_DESCRIPTOR_HANDLE SamplerTableCPUHandle; D3D12_CPU_DESCRIPTOR_HANDLE UAVTableCPUHandle; D3D12_GPU_DESCRIPTOR_HANDLE CBVTableGPUHandle; D3D12_GPU_DESCRIPTOR_HANDLE SRVTableGPUHandle; D3D12_GPU_DESCRIPTOR_HANDLE SamplerTableGPUHandle; D3D12_GPU_DESCRIPTOR_HANDLE UAVTableGPUHandle; D3D12DescriptorHandle ConstantBuffers[D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS]; uint32 ConstantBufferBindCount; D3D12DescriptorHandle Resources[D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS]; uint32 ResourceBindCount; D3D12DescriptorHandle Samplers[D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS]; uint32 SamplerBindCount; // @TODO move, since it's shared between stages D3D12DescriptorHandle UAVs[D3D12_PS_CS_UAV_REGISTER_COUNT]; uint32 UAVBindCount; }; MemArray<ShaderStageState> m_shaderStates; MemArray<D3D12_GPU_VIRTUAL_ADDRESS> m_perDrawConstantBuffers; uint32 m_perDrawConstantBufferCount; bool m_perDrawConstantBuffersDirty; D3D12GPURasterizerState *m_pCurrentRasterizerState; D3D12GPUDepthStencilState *m_pCurrentDepthStencilState; uint8 m_currentDepthStencilRef; D3D12GPUBlendState *m_pCurrentBlendState; float4 m_currentBlendStateBlendFactors; bool m_pipelineChanged; D3D12GPUOutputBuffer *m_pCurrentSwapChain; D3D12GPURenderTargetView *m_pCurrentRenderTargetViews[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; D3D12GPUDepthStencilBufferView *m_pCurrentDepthBufferView; uint32 m_nCurrentRenderTargets; // predication GPUQuery *m_pCurrentPredicate; //ID3D12Predicate *m_pCurrentPredicateD3D; uint32 m_predicateBypassCount; // declare device as friend for copy command queuing friend D3D12GPUDevice; }; <file_sep>/Engine/Source/Engine/ScriptObjectTypeInfo.h #pragma once #include "Engine/Common.h" #include "Engine/ScriptManager.h" #include "Engine/ScriptProxyFunctions.h" enum SCRIPT_OBJECT_FLAG { SCRIPT_OBJECT_FLAG_UNEXPOSED = (1 << 0), // Don't expose the object to script. SCRIPT_OBJECT_FLAG_TABLED = (1 << 1), // Declare this type as a tabled type, allowing custom script properties to be set. }; class ScriptObjectTypeInfo : public ObjectTypeInfo { public: ScriptObjectTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory, uint32 scriptFlags, const SCRIPT_FUNCTION_TABLE_ENTRY *pScriptFunctions); virtual ~ScriptObjectTypeInfo(); const uint32 GetScriptFlags() const { return m_scriptFlags; } const ScriptReferenceType GetMetaTableReference() const { return m_metaTableReference; } // script type registration bool RegisterScriptType(); void UnregisterScriptType(); // type registration virtual void RegisterType() override; virtual void UnregisterType() override; // register all types in script engine static void RegisterAllScriptTypes(); static void UnregisterAllScriptTypes(); // // pushes object from arguments // static void PushObject(lua_State *L, const ScriptObject *pObject); // // // gets typed object from arguments // template<typename T> // static T *CheckObject(lua_State *L, int arg) // { // ScriptObject *pObject = CheckObject(L, T::StaticTypeInfo(), arg); // return (pObject != nullptr) ? pObject->Cast<T>() : nullptr; // } // // // gets the object from arguments // static ScriptObject *CheckObject(lua_State *L, const ScriptObjectTypeInfo *pTypeInfo, int arg); private: const SCRIPT_FUNCTION_TABLE_ENTRY *m_pScriptFunctions; uint32 m_scriptFlags; uint32 m_nScriptFunctions; ScriptReferenceType m_metaTableReference; }; // Macros #define DECLARE_SCRIPT_OBJECT_TYPEINFO(Type, ParentType) \ private: \ static ScriptObjectTypeInfo s_typeInfo; \ static const PROPERTY_DECLARATION s_propertyDeclarations[]; \ static const SCRIPT_FUNCTION_TABLE_ENTRY *__TypeScriptFunctionTable(); \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ScriptObjectTypeInfo *StaticTypeInfo() { return &s_typeInfo; } \ static ScriptObjectTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } /* // #define DEFINE_SCRIPT_ARG_WRAPPERS(Type) \ // template<> struct ScriptArg<Type *> { \ // static Type *Get(lua_State *L, int arg) { \ // return (lua_isnil(L, arg)) ? nullptr : (Type *)ScriptManager::CheckObjectType(L, arg, OBJECT_TYPEINFO(Type)->GetMetaTableReference()); \ // } \ // static void Push(lua_State *L, const Type *&arg) { \ // if (arg->HasPersistentScriptObjectReference()) { \ // lua_rawgeti(L, LUA_REGISTRYINDEX, arg->GetPersistentScriptObjectReference()); \ // } else { \ // ScriptManager::PushNewObjectReference(L, OBJECT_TYPEINFO(Type)->GetMetaTableReference(), arg); \ // } \ // } \ // }; */ #define DEFINE_SCRIPT_ARG_WRAPPERS(Type) \ template<> const Type *ScriptArg<const Type *>::Get(lua_State *L, int arg) { \ const ScriptObject *pScriptObject = (lua_isnil(L, arg)) ? nullptr : reinterpret_cast<const ScriptObject *>(ScriptManager::CheckObjectTypeByTag(L, ScriptUserDataTag_ScriptObject, arg)); \ return (pScriptObject != nullptr) ? pScriptObject->SafeCast<Type>() : nullptr; \ } \ template<> Type *ScriptArg<Type *>::Get(lua_State *L, int arg) { \ ScriptObject *pScriptObject = (lua_isnil(L, arg)) ? nullptr : reinterpret_cast<ScriptObject *>(ScriptManager::CheckObjectTypeByTag(L, ScriptUserDataTag_ScriptObject, arg)); \ return (pScriptObject != nullptr) ? pScriptObject->SafeCast<Type>() : nullptr; \ } \ template<> void ScriptArg<const Type *>::Push(lua_State *L, const Type *const &arg) { \ ScriptReferenceType argRef = arg->GetPersistentScriptObjectReference(); \ if (argRef != INVALID_SCRIPT_REFERENCE) \ lua_rawgeti(L, LUA_REGISTRYINDEX, arg->GetPersistentScriptObjectReference()); \ else \ lua_pushnil(L); \ } \ template<> void ScriptArg<Type *>::Push(lua_State *L, Type *const &arg) { \ ScriptReferenceType argRef = arg->GetPersistentScriptObjectReference(); \ if (argRef != INVALID_SCRIPT_REFERENCE) \ lua_rawgeti(L, LUA_REGISTRYINDEX, arg->GetPersistentScriptObjectReference()); \ else \ lua_pushnil(L); \ } #define DEFINE_SCRIPT_OBJECT_TYPEINFO(Type, ScriptFlags) \ ScriptObjectTypeInfo Type::s_typeInfo = ScriptObjectTypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::s_propertyDeclarations, Type::StaticFactory(), ScriptFlags, Type::__TypeScriptFunctionTable()); \ DEFINE_SCRIPT_ARG_WRAPPERS(type) #define DEFINE_UNEXPOSED_SCRIPT_OBJECT_TYPEINFO(Type, ScriptFlags) \ ScriptObjectTypeInfo Type::s_typeInfo = ScriptObjectTypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::s_propertyDeclarations, Type::StaticFactory(), ScriptFlags | SCRIPT_OBJECT_FLAG_UNEXPOSED, nullptr); \ const SCRIPT_FUNCTION_TABLE_ENTRY *Type::__TypeScriptFunctionTable() { return nullptr; } #define BEGIN_SCRIPT_OBJECT_FUNCTIONS(Type) const SCRIPT_FUNCTION_TABLE_ENTRY *Type::__TypeScriptFunctionTable() { static const SCRIPT_FUNCTION_TABLE_ENTRY table[] = { #define DEFINE_SCRIPT_OBJECT_FUNCTION(FunctionName, FunctionPointer) { FunctionName, FunctionPointer }, #define END_SCRIPT_OBJECT_FUNCTIONS() { nullptr, nullptr } }; return table; } <file_sep>/Engine/Source/Engine/Physics/CollisionShape.h #pragma once #include "Engine/Common.h" class btCollisionShape; class btTransform; namespace Physics { enum COLLISION_SHAPE_TYPE { COLLISION_SHAPE_TYPE_NONE, COLLISION_SHAPE_TYPE_BOX, COLLISION_SHAPE_TYPE_SPHERE, COLLISION_SHAPE_TYPE_TRIANGLE_MESH, COLLISION_SHAPE_TYPE_SCALED_TRIANGLE_MESH, COLLISION_SHAPE_TYPE_CONVEX_HULL, COLLISION_SHAPE_TYPE_TERRAIN, COLLISION_SHAPE_TYPE_BLOCK_MESH, COLLISION_SHAPE_TYPE_BLOCK_TERRAIN, COLLISION_SHAPE_TYPE_CUSTOM, COLLISION_SHAPE_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(CollisionShapeType); } class CollisionShape : public ReferenceCounted { public: CollisionShape() {} virtual ~CollisionShape() {} // Gets type of collision shape. virtual const COLLISION_SHAPE_TYPE GetType() const = 0; // Bounds in local space virtual const AABox &GetLocalBoundingBox() const = 0; // Loading the shape from precompiled data. virtual bool LoadFromData(const void *pData, uint32 dataSize) = 0; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) = 0; // Creates a scaled version of this collision shape, sharing as much data as possible. virtual CollisionShape *CreateScaledShape(const float3 &scale) const = 0; // Applies any local transforms contained in the shape itself, before passing it to bullet. virtual void ApplyShapeTransform(btTransform &worldTransform) const = 0; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const = 0; // Bullet object handle virtual btCollisionShape *GetBulletShape() const = 0; public: // Creates a collision shape from precompiled data. static CollisionShape *CreateFromData(const void *pData, uint32 dataSize); static CollisionShape *CreateFromStream(ByteStream *pStream, uint32 dataSize); }; } // namespace Physics <file_sep>/Engine/Source/MathLib/SIMDVectori.h #pragma once #include "MathLib/Common.h" // Integer vector classes only available with SSE2. #if Y_CPU_SSE_LEVEL >= 2 #include "MathLib/SIMDVectori_sse.h" #else #include "MathLib/SIMDVectori_scalar.h" #endif <file_sep>/Engine/Source/MathLib/SIMDVectorf_scalar.h #pragma once #include "MathLib/Vectorf.h" // basically a massive hack, since we forward declare the simd types, we can't typedef them // so we just inherit them instead.. struct SIMDVector2i; struct SIMDVector3i; struct SIMDVector4i; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector2f : public Vector2f { // constructors inline SIMDVector2f() {} inline SIMDVector2f(const float val) : Vector2f(val) {} inline SIMDVector2f(const float x_, const float y_) : Vector2f(x_, y_) {} inline SIMDVector2f(const float *p) : Vector2f(p) {} inline SIMDVector2f(const SIMDVector2f &v) : Vector2f(v) {} inline SIMDVector2f(const Vector2f &v) : Vector2f(v) {} inline SIMDVector2f(const Vector2i &v) : Vector2f(v) {} // new vector inline SIMDVector2f operator+(const SIMDVector2f &v) const { return Vector2f::operator+(v); } inline SIMDVector2f operator-(const SIMDVector2f &v) const { return Vector2f::operator-(v); } inline SIMDVector2f operator*(const SIMDVector2f &v) const { return Vector2f::operator*(v); } inline SIMDVector2f operator/(const SIMDVector2f &v) const { return Vector2f::operator/(v); } inline SIMDVector2f operator%(const SIMDVector2f &v) const { return Vector2f::operator%(v); } inline SIMDVector2f operator-() const { return Vector2f::operator-(); } // scalar operators inline SIMDVector2f operator+(const float v) const { return Vector2f::operator+(v); } inline SIMDVector2f operator-(const float v) const { return Vector2f::operator-(v); } inline SIMDVector2f operator*(const float v) const { return Vector2f::operator*(v); } inline SIMDVector2f operator/(const float v) const { return Vector2f::operator/(v); } inline SIMDVector2f operator%(const float v) const { return Vector2f::operator%(v); } // comparison operators inline bool operator==(const SIMDVector2f &v) const { return Vector2f::operator==(v); } inline bool operator!=(const SIMDVector2f &v) const { return Vector2f::operator!=(v); } inline bool operator<=(const SIMDVector2f &v) const { return Vector2f::operator<=(v); } inline bool operator>=(const SIMDVector2f &v) const { return Vector2f::operator>=(v); } inline bool operator<(const SIMDVector2f &v) const { return Vector2f::operator<(v); } inline bool operator>(const SIMDVector2f &v) const { return Vector2f::operator>(v); } // modifies this vector inline SIMDVector2f &operator+=(const SIMDVector2f &v) { Vector2f::operator+=(v); return *this; } inline SIMDVector2f &operator-=(const SIMDVector2f &v) { Vector2f::operator-=(v); return *this; } inline SIMDVector2f &operator*=(const SIMDVector2f &v) { Vector2f::operator*=(v); return *this; } inline SIMDVector2f &operator/=(const SIMDVector2f &v) { Vector2f::operator/=(v); return *this; } inline SIMDVector2f &operator%=(const SIMDVector2f &v) { Vector2f::operator%=(v); return *this; } inline SIMDVector2f &operator=(const SIMDVector2f &v) { Vector2f::operator=(v); return *this; } inline SIMDVector2f &operator=(const Vector2f &v) { Vector2f::operator=(v); return *this; } // scalar operators inline SIMDVector2f &operator+=(const float v) { Vector2f::operator+=(v); return *this; } inline SIMDVector2f &operator-=(const float v) { Vector2f::operator-=(v); return *this; } inline SIMDVector2f &operator*=(const float v) { Vector2f::operator*=(v); return *this; } inline SIMDVector2f &operator/=(const float v) { Vector2f::operator/=(v); return *this; } inline SIMDVector2f &operator%=(const float v) { Vector2f::operator%=(v); return *this; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector2f &Zero, &One, &NegativeOne; static const SIMDVector2f &Infinite, &NegativeInfinite; static const SIMDVector2f &UnitX, &UnitY, &NegativeUnitX, &NegativeUnitY; static const SIMDVector2f &Epsilon; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector3f : public Vector3f { // constructors inline SIMDVector3f() {} inline SIMDVector3f(const float val) : Vector3f(val) {} inline SIMDVector3f(const float x_, const float y_, const float z_) : Vector3f(x_, y_, z_) {} inline SIMDVector3f(const float *p) : Vector3f(p) {} inline SIMDVector3f(const SIMDVector2f &v, const float &z_ = 0.0f) : Vector3f(v, z_) {} inline SIMDVector3f(const SIMDVector3f &v) : Vector3f(v) {} inline SIMDVector3f(const Vector3i &v) : Vector3f(v) {} inline SIMDVector3f(const Vector3f &v) : Vector3f(v) {} // new vector inline SIMDVector3f operator+(const SIMDVector3f &v) const { return Vector3f::operator+(v); } inline SIMDVector3f operator-(const SIMDVector3f &v) const { return Vector3f::operator-(v); } inline SIMDVector3f operator*(const SIMDVector3f &v) const { return Vector3f::operator*(v); } inline SIMDVector3f operator/(const SIMDVector3f &v) const { return Vector3f::operator/(v); } inline SIMDVector3f operator%(const SIMDVector3f &v) const { return Vector3f::operator%(v); } inline SIMDVector3f operator-() const { return Vector3f::operator-(); } // scalar operators inline SIMDVector3f operator+(const float v) const { return Vector3f::operator+(v); } inline SIMDVector3f operator-(const float v) const { return Vector3f::operator-(v); } inline SIMDVector3f operator*(const float v) const { return Vector3f::operator*(v); } inline SIMDVector3f operator/(const float v) const { return Vector3f::operator/(v); } inline SIMDVector3f operator%(const float v) const { return Vector3f::operator%(v); } // comparison operators inline bool operator==(const SIMDVector3f &v) const { return Vector3f::operator==(v); } inline bool operator!=(const SIMDVector3f &v) const { return Vector3f::operator!=(v); } inline bool operator<=(const SIMDVector3f &v) const { return Vector3f::operator<=(v); } inline bool operator>=(const SIMDVector3f &v) const { return Vector3f::operator>=(v); } inline bool operator<(const SIMDVector3f &v) const { return Vector3f::operator<(v); } inline bool operator>(const SIMDVector3f &v) const { return Vector3f::operator>(v); } // modifies this vector inline SIMDVector3f &operator+=(const SIMDVector3f &v) { Vector3f::operator+=(v); return *this; } inline SIMDVector3f &operator-=(const SIMDVector3f &v) { Vector3f::operator-=(v); return *this; } inline SIMDVector3f &operator*=(const SIMDVector3f &v) { Vector3f::operator*=(v); return *this; } inline SIMDVector3f &operator/=(const SIMDVector3f &v) { Vector3f::operator/=(v); return *this; } inline SIMDVector3f &operator%=(const SIMDVector3f &v) { Vector3f::operator%=(v); return *this; } inline SIMDVector3f &operator=(const SIMDVector3f &v) { Vector3f::operator=(v); return *this; } inline SIMDVector3f &operator=(const Vector3f &v) { Vector3f::operator=(v); return *this; } // scalar operators inline SIMDVector3f &operator+=(const float v) { Vector3f::operator+=(v); return *this; } inline SIMDVector3f &operator-=(const float v) { Vector3f::operator-=(v); return *this; } inline SIMDVector3f &operator*=(const float v) { Vector3f::operator*=(v); return *this; } inline SIMDVector3f &operator/=(const float v) { Vector3f::operator/=(v); return *this; } inline SIMDVector3f &operator%=(const float v) { Vector3f::operator%=(v); return *this; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector3f &Zero, &One, &NegativeOne; static const SIMDVector3f &Infinite, &NegativeInfinite; static const SIMDVector3f &UnitX, &UnitY, &UnitZ, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ; static const SIMDVector3f &Epsilon; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector4f : public Vector4f { // constructors inline SIMDVector4f() {} inline SIMDVector4f(const float val) : Vector4f(val) {} inline SIMDVector4f(const float x_, const float y_, const float z_, const float w_) : Vector4f(x_, y_, z_, w_) {} inline SIMDVector4f(const float *p) : Vector4f(p) {} inline SIMDVector4f(const SIMDVector2f &v, const float z_ = 0.0f, const float w_ = 0.0f) : Vector4f(v, z_, w_) {} inline SIMDVector4f(const SIMDVector3f &v, const float w_ = 0.0f) : Vector4f(v, w_) {} inline SIMDVector4f(const SIMDVector4f &v) : Vector4f(v) {} inline SIMDVector4f(const Vector4i &v) : Vector4f(v) {} inline SIMDVector4f(const Vector4f &v) : Vector4f(v) {} // new vector inline SIMDVector4f operator+(const SIMDVector4f &v) const { return Vector4f::operator+(v); } inline SIMDVector4f operator-(const SIMDVector4f &v) const { return Vector4f::operator-(v); } inline SIMDVector4f operator*(const SIMDVector4f &v) const { return Vector4f::operator*(v); } inline SIMDVector4f operator/(const SIMDVector4f &v) const { return Vector4f::operator/(v); } inline SIMDVector4f operator%(const SIMDVector4f &v) const { return Vector4f::operator%(v); } inline SIMDVector4f operator-() const { return Vector4f::operator-(); } // scalar operators inline SIMDVector4f operator+(const float v) const { return Vector4f::operator+(v); } inline SIMDVector4f operator-(const float v) const { return Vector4f::operator-(v); } inline SIMDVector4f operator*(const float v) const { return Vector4f::operator*(v); } inline SIMDVector4f operator/(const float v) const { return Vector4f::operator/(v); } inline SIMDVector4f operator%(const float v) const { return Vector4f::operator%(v); } // comparison operators inline bool operator==(const SIMDVector4f &v) const { return Vector4f::operator==(v); } inline bool operator!=(const SIMDVector4f &v) const { return Vector4f::operator!=(v); } inline bool operator<=(const SIMDVector4f &v) const { return Vector4f::operator<=(v); } inline bool operator>=(const SIMDVector4f &v) const { return Vector4f::operator>=(v); } inline bool operator<(const SIMDVector4f &v) const { return Vector4f::operator<(v); } inline bool operator>(const SIMDVector4f &v) const { return Vector4f::operator>(v); } // modifies this vector inline SIMDVector4f &operator+=(const SIMDVector4f &v) { Vector4f::operator+=(v); return *this; } inline SIMDVector4f &operator-=(const SIMDVector4f &v) { Vector4f::operator-=(v); return *this; } inline SIMDVector4f &operator*=(const SIMDVector4f &v) { Vector4f::operator*=(v); return *this; } inline SIMDVector4f &operator/=(const SIMDVector4f &v) { Vector4f::operator/=(v); return *this; } inline SIMDVector4f &operator%=(const SIMDVector4f &v) { Vector4f::operator%=(v); return *this; } inline SIMDVector4f &operator=(const SIMDVector4f &v) { Vector4f::operator=(v); return *this; } inline SIMDVector4f &operator=(const Vector4f &v) { Vector4f::operator=(v); return *this; } // scalar operators inline SIMDVector4f &operator+=(const float v) { Vector4f::operator+=(v); return *this; } inline SIMDVector4f &operator-=(const float v) { Vector4f::operator-=(v); return *this; } inline SIMDVector4f &operator*=(const float v) { Vector4f::operator*=(v); return *this; } inline SIMDVector4f &operator/=(const float v) { Vector4f::operator/=(v); return *this; } inline SIMDVector4f &operator%=(const float v) { Vector4f::operator%=(v); return *this; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const SIMDVector4f &Zero, &One, &NegativeOne; static const SIMDVector4f &Infinite, &NegativeInfinite; static const SIMDVector4f &UnitX, &UnitY, &UnitZ, &UnitW, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ, &NegativeUnitW; static const SIMDVector4f &Epsilon; }; <file_sep>/Engine/Source/Renderer/ShaderMap.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" class ShaderComponentTypeInfo; class VertexFactoryTypeInfo; class MaterialShader; class ShaderProgram; class ShaderMap { struct Key { Key() {} Key(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) : pBaseShaderTypeInfo(pBaseShaderTypeInfo), pVertexFactoryTypeInfo(pVertexFactoryTypeInfo), pMaterialShader(pMaterialShader), GlobalShaderFlags(globalShaderFlags), BaseShaderFlags(baseShaderFlags), VertexFactoryFlags(vertexFactoryFlags), MaterialShaderFlags(materialShaderFlags) {} const ShaderComponentTypeInfo *pBaseShaderTypeInfo; const VertexFactoryTypeInfo *pVertexFactoryTypeInfo; const MaterialShader *pMaterialShader; uint32 GlobalShaderFlags; uint32 BaseShaderFlags; uint32 VertexFactoryFlags; uint32 MaterialShaderFlags; static int32 Compare(const Key *a, const Key *b); bool operator<(const Key &other) const { return (Compare(this, &other) < 0); } }; public: ShaderMap(); ~ShaderMap(); ShaderProgram *GetShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const; ShaderProgram *GetShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const; void ReleaseGPUResources(); private: ShaderProgram *LoadShaderPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes) const; typedef KeyValuePair<Key, ShaderProgram *> ProgramEntry; typedef MemArray<ProgramEntry> LoadedShaderArray; mutable LoadedShaderArray m_arrLoadedShaders; }; <file_sep>/Editor/Source/Editor/MapEditor/ui_EditorMapViewport.h #pragma once class Ui_EditorMapViewport { public: QGridLayout *gridLayout; // toolbar QToolButton *toolbarMoreOptions; QToolButton *toolbarRealTime; QToolButton *toolbarGameView; QToolButton *toolbarCameraFront; QToolButton *toolbarCameraSide; QToolButton *toolbarCameraTop; QToolButton *toolbarCameraIsometric; QToolButton *toolbarCameraPerspective; QToolButton *toolbarViewWireframe; QToolButton *toolbarViewUnlit; QToolButton *toolbarViewLit; QToolButton *toolbarViewLightingOnly; QToolButton *toolbarFlagShadows; QToolButton *toolbarFlagWireframeOverlay; // swap chain EditorRendererSwapChainWidget *swapChainWidget; void CreateUI(QWidget *pViewport) { QHBoxLayout *horizontalLayout; QSpacerItem *horizontalSpacer; gridLayout = new QGridLayout(pViewport); gridLayout->setSpacing(0); gridLayout->setContentsMargins(0, 0, 0, 0); gridLayout->setMargin(0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(0); toolbarMoreOptions = new QToolButton(pViewport); toolbarMoreOptions->setMinimumSize(QSize(24, 24)); toolbarMoreOptions->setMaximumSize(QSize(24, 24)); toolbarMoreOptions->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_OtherOptions.png"))); toolbarMoreOptions->setAutoRaise(false); horizontalLayout->addWidget(toolbarMoreOptions); horizontalSpacer = new QSpacerItem(4, 24, QSizePolicy::Fixed, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); toolbarRealTime = new QToolButton(pViewport); toolbarRealTime->setMinimumSize(QSize(24, 24)); toolbarRealTime->setMaximumSize(QSize(24, 24)); toolbarRealTime->setIcon(QIcon(QStringLiteral(":/editor/icons/PlayHS.png"))); toolbarRealTime->setCheckable(true); toolbarRealTime->setChecked(false); toolbarRealTime->setAutoRaise(true); horizontalLayout->addWidget(toolbarRealTime); toolbarGameView = new QToolButton(pViewport); toolbarGameView->setMinimumSize(QSize(24, 24)); toolbarGameView->setMaximumSize(QSize(24, 24)); toolbarGameView->setIcon(QIcon(QStringLiteral(":/editor/icons/AnimateHS.png"))); toolbarGameView->setCheckable(true); toolbarGameView->setChecked(false); toolbarGameView->setAutoRaise(true); horizontalLayout->addWidget(toolbarGameView); horizontalSpacer = new QSpacerItem(4, 24, QSizePolicy::Fixed, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); toolbarCameraFront = new QToolButton(pViewport); toolbarCameraFront->setMinimumSize(QSize(24, 24)); toolbarCameraFront->setMaximumSize(QSize(24, 24)); toolbarCameraFront->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Front.png"))); toolbarCameraFront->setCheckable(true); toolbarCameraFront->setChecked(false); toolbarCameraFront->setAutoRaise(true); horizontalLayout->addWidget(toolbarCameraFront); toolbarCameraSide = new QToolButton(pViewport); toolbarCameraSide->setMinimumSize(QSize(24, 24)); toolbarCameraSide->setMaximumSize(QSize(24, 24)); toolbarCameraSide->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Side.png"))); toolbarCameraSide->setCheckable(true); toolbarCameraSide->setAutoRaise(true); horizontalLayout->addWidget(toolbarCameraSide); toolbarCameraTop = new QToolButton(pViewport); toolbarCameraTop->setMinimumSize(QSize(24, 24)); toolbarCameraTop->setMaximumSize(QSize(24, 24)); toolbarCameraTop->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Top.png"))); toolbarCameraTop->setCheckable(true); toolbarCameraTop->setAutoRaise(true); horizontalLayout->addWidget(toolbarCameraTop); toolbarCameraIsometric = new QToolButton(pViewport); toolbarCameraIsometric->setMinimumSize(QSize(24, 24)); toolbarCameraIsometric->setMaximumSize(QSize(24, 24)); toolbarCameraIsometric->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Isometric.png"))); toolbarCameraIsometric->setCheckable(true); toolbarCameraIsometric->setAutoRaise(true); horizontalLayout->addWidget(toolbarCameraIsometric); toolbarCameraPerspective = new QToolButton(pViewport); toolbarCameraPerspective->setMinimumSize(QSize(24, 24)); toolbarCameraPerspective->setMaximumSize(QSize(24, 24)); toolbarCameraPerspective->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Perspective.png"))); toolbarCameraPerspective->setCheckable(true); toolbarCameraPerspective->setAutoRaise(true); horizontalLayout->addWidget(toolbarCameraPerspective); horizontalSpacer = new QSpacerItem(4, 24, QSizePolicy::Fixed, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); toolbarViewWireframe = new QToolButton(pViewport); toolbarViewWireframe->setMinimumSize(QSize(24, 24)); toolbarViewWireframe->setMaximumSize(QSize(24, 24)); toolbarViewWireframe->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Wireframe.png"))); toolbarViewWireframe->setCheckable(true); toolbarViewWireframe->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewWireframe); toolbarViewUnlit = new QToolButton(pViewport); toolbarViewUnlit->setMinimumSize(QSize(24, 24)); toolbarViewUnlit->setMaximumSize(QSize(24, 24)); toolbarViewUnlit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Unlit.png"))); toolbarViewUnlit->setCheckable(true); toolbarViewUnlit->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewUnlit); toolbarViewLit = new QToolButton(pViewport); toolbarViewLit->setMinimumSize(QSize(24, 24)); toolbarViewLit->setMaximumSize(QSize(24, 24)); toolbarViewLit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Lit.png"))); toolbarViewLit->setCheckable(true); toolbarViewLit->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewLit); toolbarViewLightingOnly = new QToolButton(pViewport); toolbarViewLightingOnly->setMinimumSize(QSize(24, 24)); toolbarViewLightingOnly->setMaximumSize(QSize(24, 24)); toolbarViewLightingOnly->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_LightingOnly.png"))); toolbarViewLightingOnly->setCheckable(true); toolbarViewLightingOnly->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewLightingOnly); horizontalSpacer = new QSpacerItem(4, 24, QSizePolicy::Fixed, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); toolbarFlagShadows = new QToolButton(pViewport); toolbarFlagShadows->setMinimumSize(QSize(24, 24)); toolbarFlagShadows->setMaximumSize(QSize(24, 24)); toolbarFlagShadows->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_Shadows.png"))); toolbarFlagShadows->setCheckable(true); toolbarFlagShadows->setAutoRaise(true); horizontalLayout->addWidget(toolbarFlagShadows); toolbarFlagWireframeOverlay = new QToolButton(pViewport); toolbarFlagWireframeOverlay->setMinimumSize(QSize(24, 24)); toolbarFlagWireframeOverlay->setMaximumSize(QSize(24, 24)); toolbarFlagWireframeOverlay->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_WireframeOverlay.png"))); toolbarFlagWireframeOverlay->setCheckable(true); toolbarFlagWireframeOverlay->setAutoRaise(true); horizontalLayout->addWidget(toolbarFlagWireframeOverlay); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); gridLayout->addLayout(horizontalLayout, 0, 0, 1, 1); swapChainWidget = new EditorRendererSwapChainWidget(pViewport); swapChainWidget->setObjectName(QStringLiteral("swapChainWidget")); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(swapChainWidget->sizePolicy().hasHeightForWidth()); swapChainWidget->setSizePolicy(sizePolicy); swapChainWidget->setMaximumSize(QSize(16777215, 16777215)); swapChainWidget->setMouseTracking(true); swapChainWidget->setFocusPolicy(Qt::FocusPolicy(Qt::TabFocus | Qt::ClickFocus)); swapChainWidget->setAcceptDrops(true); gridLayout->addWidget(swapChainWidget, 1, 0, 1, 1); } void UpdateUIForCameraMode(EDITOR_CAMERA_MODE cameraMode) { toolbarCameraFront->setChecked((cameraMode == EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT)); toolbarCameraSide->setChecked((cameraMode == EDITOR_CAMERA_MODE_ORTHOGRAPHIC_SIDE)); toolbarCameraTop->setChecked((cameraMode == EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP)); toolbarCameraIsometric->setChecked((cameraMode == EDITOR_CAMERA_MODE_ISOMETRIC)); toolbarCameraPerspective->setChecked((cameraMode == EDITOR_CAMERA_MODE_PERSPECTIVE)); } void UpdateUIForRenderMode(EDITOR_RENDER_MODE renderMode) { toolbarViewWireframe->setChecked((renderMode == EDITOR_RENDER_MODE_WIREFRAME)); toolbarViewUnlit->setChecked((renderMode == EDITOR_RENDER_MODE_FULLBRIGHT)); toolbarViewLit->setChecked((renderMode == EDITOR_RENDER_MODE_LIT)); toolbarViewLightingOnly->setChecked((renderMode == EDITOR_RENDER_MODE_LIGHTING_ONLY)); } void UpdateUIForViewportFlags(uint32 viewportFlags) { toolbarFlagShadows->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) != 0); toolbarFlagWireframeOverlay->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) != 0); } }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUBuffer.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" class OpenGLGPUBuffer : public GPUBuffer { public: OpenGLGPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, GLuint glBufferId, GLenum glBufferUsage); virtual ~OpenGLGPUBuffer(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *debugName) override; const GLuint GetGLBufferId() const { return m_glBufferId; } const GLenum GetGLBufferUsage() const { return m_glBufferUsage; } OpenGLGPUContext *GetMappedContext() const { return m_pMappedContext; } void *GetMappedPointer() const { return m_pMappedPointer; } void SetMappedContextPointer(OpenGLGPUContext *pContext, void *pPointer) { m_pMappedContext = pContext; m_pMappedPointer = pPointer; } private: GLuint m_glBufferId; GLenum m_glBufferUsage; OpenGLGPUContext *m_pMappedContext; void *m_pMappedPointer; }; <file_sep>/Engine/Source/BaseGame/LivingEntity.h #pragma once #include "BaseGame/GameEntity.h" class LivingEntity : public GameEntity { DECLARE_ENTITY_TYPEINFO(LivingEntity, GameEntity); DECLARE_ENTITY_NO_FACTORY(Entity); public: LivingEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~LivingEntity(); const bool IsAlive() const { return (m_health > 0); } const uint32 GetHealth() const { return m_health; } void SetHealth(uint32 health); const uint32 GetMaxHealth() const { return m_maxHealth; } void SetMaxHealth(uint32 maxHealth); protected: // callbacks virtual void OnHealthChanged(); // events virtual void OnDeath(); virtual void OnRevive(); // behavior variables uint32 m_health; uint32 m_maxHealth; // skeletal mesh, attachment points? private: // hidden trampolines for property system static void __PS_OnHealthChanged(LivingEntity *pThis, const void *pUserData) { pThis->OnHealthChanged(); } }; <file_sep>/Engine/Source/ResourceCompiler/MaterialShaderGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/MaterialShaderGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "ResourceCompiler/ShaderGraph.h" #include "Engine/Engine.h" #include "Engine/DataFormats.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "YBaseLib/CRC32.h" Log_SetChannel(MaterialShaderGenerator); MaterialShaderGenerator::MaterialShaderGenerator() { m_blendingMode = MATERIAL_BLENDING_MODE_NONE; m_lightingType = MATERIAL_LIGHTING_TYPE_REFLECTIVE; m_lightingModel = MATERIAL_LIGHTING_MODEL_PHONG; m_lightingNormalSpace = MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE; m_renderMode = MATERIAL_RENDER_MODE_NORMAL; m_renderLayer = MATERIAL_RENDER_LAYER_NORMAL; m_twoSided = false; m_depthClamping = false; m_depthTests = true; m_depthWrites = true; m_castShadows = true; m_receiveShadows = true; Y_memzero(m_pShaderCodes, sizeof(m_pShaderCodes)); Y_memzero(m_pShaderGraphs, sizeof(m_pShaderGraphs)); } MaterialShaderGenerator::~MaterialShaderGenerator() { uint32 i; for (i = 0; i < RENDERER_PLATFORM_COUNT; i++) delete m_pShaderCodes[i]; for (i = 0; i < RENDERER_FEATURE_LEVEL_COUNT; i++) delete m_pShaderGraphs[i]; } void MaterialShaderGenerator::Create(ResourceCompilerCallbacks *pCallbacks) { m_blendingMode = MATERIAL_BLENDING_MODE_NONE; m_lightingType = MATERIAL_LIGHTING_TYPE_REFLECTIVE; m_lightingModel = MATERIAL_LIGHTING_MODEL_PHONG; m_lightingNormalSpace = MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE; m_renderMode = MATERIAL_RENDER_MODE_NORMAL; m_renderLayer = MATERIAL_RENDER_LAYER_NORMAL; m_twoSided = false; m_depthClamping = false; m_depthTests = true; m_depthWrites = true; m_castShadows = true; m_receiveShadows = true; CreateShaderGraph(pCallbacks, RENDERER_FEATURE_LEVEL_ES2); } bool MaterialShaderGenerator::LoadFromXML(ResourceCompilerCallbacks *pCallbacks, const char *FileName, ByteStream *pStream) { const char *pAttributeStr; bool loadResult = false; // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { Log_ErrorPrintf("Could not load material shader '%s': Failed to create XML reader.", FileName); goto CLEANUP; } // skip to correct node if (!xmlReader.SkipToElement("shader")) { Log_ErrorPrintf("Could not load material shader '%s': Failed to skip to shader element.", FileName); goto CLEANUP; } // start looping for (;;) { if (!xmlReader.NextToken()) goto CLEANUP; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 shaderSelection = xmlReader.Select("blending|lighting|render|parameters|sources"); if (shaderSelection < 0) goto CLEANUP; switch (shaderSelection) { // blending case 0: { // blend mode pAttributeStr = xmlReader.FetchAttributeDefault("mode", "none"); if (!NameTable_TranslateType(NameTables::MaterialBlendingMode, pAttributeStr, &m_blendingMode, true)) { xmlReader.PrintError("unknown blending mode '%s'", pAttributeStr); goto CLEANUP; } if (!xmlReader.SkipCurrentElement()) goto CLEANUP; } break; // lighting case 1: { // lighting type pAttributeStr = xmlReader.FetchAttributeDefault("type", "Reflective"); if (!NameTable_TranslateType(NameTables::MaterialLightingType, pAttributeStr, &m_lightingType, true)) { xmlReader.PrintError("unknown lighting type '%s'", pAttributeStr); goto CLEANUP; } // lighting model pAttributeStr = xmlReader.FetchAttributeDefault("model", "LambertBlinnPhong"); if (!NameTable_TranslateType(NameTables::MaterialLightingModel, pAttributeStr, &m_lightingModel, true)) { xmlReader.PrintError("unknown lighting model '%s'", pAttributeStr); goto CLEANUP; } // normal space pAttributeStr = xmlReader.FetchAttributeDefault("normal-space", "World"); if (!NameTable_TranslateType(NameTables::MaterialLightingNormalSpace, pAttributeStr, &m_lightingNormalSpace, true)) { xmlReader.PrintError("unknown lighting normal space '%s'", pAttributeStr); goto CLEANUP; } // two-sided pAttributeStr = xmlReader.FetchAttributeDefault("two-sided", "true"); m_twoSided = StringConverter::StringToBool(pAttributeStr); // cast-shadows pAttributeStr = xmlReader.FetchAttributeDefault("cast-shadows", "true"); m_castShadows = StringConverter::StringToBool(pAttributeStr); // recieve-shadows pAttributeStr = xmlReader.FetchAttributeDefault("receive-shadows", "true"); m_receiveShadows = StringConverter::StringToBool(pAttributeStr); if (!xmlReader.SkipCurrentElement()) goto CLEANUP; } break; // render case 2: { pAttributeStr = xmlReader.FetchAttributeDefault("mode", "Normal"); if (!NameTable_TranslateType(NameTables::MaterialRenderMode, pAttributeStr, &m_renderMode, true)) { xmlReader.PrintError("unknown render mode '%s'", pAttributeStr); goto CLEANUP; } pAttributeStr = xmlReader.FetchAttributeDefault("layer", "Normal"); if (!NameTable_TranslateType(NameTables::MaterialRenderLayer, pAttributeStr, &m_renderLayer, true)) { xmlReader.PrintError("unknown render layer '%s'", pAttributeStr); goto CLEANUP; } m_depthClamping = StringConverter::StringToBool(xmlReader.FetchAttributeDefault("depth-clamping", "false")); m_depthTests = StringConverter::StringToBool(xmlReader.FetchAttributeDefault("depth-tests", "true")); m_depthWrites = StringConverter::StringToBool(xmlReader.FetchAttributeDefault("depth-writes", "true")); if (!xmlReader.SkipCurrentElement()) goto CLEANUP; } break; // parameters case 3: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) goto CLEANUP; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 parameterSelection = xmlReader.Select("uniform|texture|staticswitch"); if (parameterSelection < 0) goto CLEANUP; switch (parameterSelection) { // uniform case 0: { UniformParameter uniformParameter; // get name if ((pAttributeStr = xmlReader.FetchAttribute("name")) == NULL) { xmlReader.PrintError("missing name attribute"); goto CLEANUP; } uniformParameter.Name = pAttributeStr; // get type if (!NameTable_TranslateType(NameTables::ShaderParameterType, xmlReader.FetchAttributeString("type"), &uniformParameter.Type, true)) { xmlReader.PrintError("unknown uniform type '%s'", xmlReader.FetchAttributeString("type")); goto CLEANUP; } // get default value Y_memzero(&uniformParameter.DefaultValue, sizeof(uniformParameter.DefaultValue)); if ((pAttributeStr = xmlReader.FetchAttribute("default")) != NULL) ShaderParameterTypeFromString(uniformParameter.Type, &uniformParameter.DefaultValue, pAttributeStr); // add to list m_UniformParameters.Add(uniformParameter); } break; // texture case 1: { TextureParameter textureParameter; // get name if ((pAttributeStr = xmlReader.FetchAttribute("name")) == NULL) { xmlReader.PrintError("missing name attribute"); goto CLEANUP; } textureParameter.Name = pAttributeStr; // get type if (!NameTable_TranslateType(NameTables::TextureClassNames, xmlReader.FetchAttributeString("type"), &textureParameter.Type, true)) { xmlReader.PrintError("unknown texture type '%s'", xmlReader.FetchAttributeString("type")); goto CLEANUP; } // get default value pAttributeStr = xmlReader.FetchAttribute("default"); if (pAttributeStr != NULL) textureParameter.DefaultValue = pAttributeStr; // add to list m_TextureParameters.Add(textureParameter); } break; // staticswitch case 2: { StaticSwitchParameter staticSwitchParameter; // check count if (m_StaticSwitchParameters.GetSize() == MATERIAL_MAX_STATIC_SWITCH_COUNT) { xmlReader.PrintError("too many static switches defined, maximum is %u", (uint32)MATERIAL_MAX_STATIC_SWITCH_COUNT); goto CLEANUP; } // get name if ((pAttributeStr = xmlReader.FetchAttribute("name")) == NULL) { xmlReader.PrintError("missing name attribute"); goto CLEANUP; } staticSwitchParameter.Name = pAttributeStr; // get default value staticSwitchParameter.DefaultValue = StringConverter::StringToBool(xmlReader.FetchAttributeString("default")); // add to list m_StaticSwitchParameters.Add(staticSwitchParameter); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "parameters")); break; } } } } break; // sources case 4: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) goto CLEANUP; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 sourceSelection = xmlReader.Select("code|graph"); if (sourceSelection < 0) goto CLEANUP; switch (sourceSelection) { // code case 0: { RENDERER_FEATURE_LEVEL featureLevel; const char *featureLevelStr = xmlReader.FetchAttributeString("featurelevel"); if (!NameTable_TranslateType(NameTables::RendererFeatureLevel, featureLevelStr, &featureLevel, true)) { xmlReader.PrintError("invalid feature level '%s'", featureLevelStr); goto CLEANUP; } if (m_pShaderCodes[featureLevel] != NULL) { xmlReader.PrintError("code for '%s' already defined", featureLevel); goto CLEANUP; } m_pShaderCodes[featureLevel] = new String(xmlReader.GetElementText()); if (!xmlReader.SkipCurrentElement()) goto CLEANUP; } break; // graph case 1: { RENDERER_FEATURE_LEVEL featureLevel; const char *featureLevelStr = xmlReader.FetchAttributeString("featurelevel"); if (!NameTable_TranslateType(NameTables::RendererFeatureLevel, featureLevelStr, &featureLevel, true)) { xmlReader.PrintError("invalid feature level '%s'", featureLevelStr); goto CLEANUP; } if (m_pShaderGraphs[featureLevel] != NULL) { xmlReader.PrintError("graph for feature level '%s' already defined", featureLevelStr); goto CLEANUP; } // get schema const ShaderGraphSchema *pSchema = ShaderGraphSchema::GetSchemaForFeatureLevel(pCallbacks, featureLevel); if (pSchema == NULL) { xmlReader.PrintError("could not load shader graph schema."); goto CLEANUP; } // create graph ShaderGraph *pShaderGraph = new ShaderGraph(); if (!pShaderGraph->LoadFromXML(pSchema, xmlReader)) { xmlReader.PrintError("failed to load shader graph."); pSchema->Release(); delete pShaderGraph; goto CLEANUP; } // set and release m_pShaderGraphs[featureLevel] = pShaderGraph; pSchema->Release(); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "sources")); break; } } } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "shader")); break; } } // load ok loadResult = true; CLEANUP: return loadResult; } bool MaterialShaderGenerator::SaveToXML(ByteStream *pStream) { uint32 i; SmallString tempString; XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; // shader xmlWriter.StartElement("shader"); { // blending xmlWriter.StartElement("blending"); { // mode xmlWriter.WriteAttribute("mode", NameTable_GetNameString(NameTables::MaterialBlendingMode, m_blendingMode)); } xmlWriter.EndElement(); // lighting xmlWriter.StartElement("lighting"); { // type xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::MaterialLightingType, m_lightingType)); // model xmlWriter.WriteAttribute("model", NameTable_GetNameString(NameTables::MaterialLightingModel, m_lightingModel)); // two-sided StringConverter::BoolToString(tempString, m_twoSided); xmlWriter.WriteAttribute("two-sided", tempString); } xmlWriter.EndElement(); // render xmlWriter.StartElement("render"); { xmlWriter.WriteAttribute("mode", NameTable_GetNameString(NameTables::MaterialRenderMode, m_renderMode)); } xmlWriter.EndElement(); // parameters xmlWriter.StartElement("parameters"); { for (i = 0; i < m_UniformParameters.GetSize(); i++) { const UniformParameter &uniformParameter = m_UniformParameters[i]; xmlWriter.StartElement("uniform"); { xmlWriter.WriteAttribute("name", uniformParameter.Name); xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::ShaderParameterType, uniformParameter.Type)); ShaderParameterTypeToString(tempString, uniformParameter.Type, &uniformParameter.DefaultValue); xmlWriter.WriteAttribute("default", tempString); } xmlWriter.EndElement(); } for (i = 0; i < m_TextureParameters.GetSize(); i++) { const TextureParameter &textureParameter = m_TextureParameters[i]; xmlWriter.StartElement("texture"); { xmlWriter.WriteAttribute("name", textureParameter.Name); xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::TextureClassNames, textureParameter.Type)); xmlWriter.WriteAttribute("default", textureParameter.DefaultValue); } xmlWriter.EndElement(); } for (i = 0; i < m_StaticSwitchParameters.GetSize(); i++) { const StaticSwitchParameter &staticSwitchParameter = m_StaticSwitchParameters[i]; xmlWriter.StartElement("staticswitch"); { xmlWriter.WriteAttribute("name", staticSwitchParameter.Name); StringConverter::BoolToString(tempString, staticSwitchParameter.DefaultValue); xmlWriter.WriteAttribute("default", tempString); } xmlWriter.EndElement(); } } xmlWriter.EndElement(); // sources xmlWriter.StartElement("sources"); { for (i = 0; i < RENDERER_FEATURE_LEVEL_COUNT; i++) { if (m_pShaderCodes[i] != NULL) { xmlWriter.StartElement("code"); xmlWriter.WriteAttribute("featurelevel", NameTable_GetNameString(NameTables::RendererFeatureLevel, i)); xmlWriter.WriteCDATA(m_pShaderCodes[i]->GetCharArray()); xmlWriter.EndElement(); } } for (i = 0; i < RENDERER_FEATURE_LEVEL_COUNT; i++) { if (m_pShaderGraphs[i] != NULL) { xmlWriter.StartElement("graph"); xmlWriter.WriteAttribute("featurelevel", NameTable_GetNameString(NameTables::RendererFeatureLevel, i)); if (!m_pShaderGraphs[i]->SaveToXML(xmlWriter)) return false; xmlWriter.EndElement(); } } } xmlWriter.EndElement(); } xmlWriter.EndElement(); return !pStream->InErrorState() && !xmlWriter.InErrorState(); } bool MaterialShaderGenerator::CreateUniformParameter(const char *Name, SHADER_PARAMETER_TYPE Type) { if (FindUniformParameter(Name) >= 0) return false; UniformParameter uniformParameter; uniformParameter.Name = Name; uniformParameter.Type = Type; Y_memzero(&uniformParameter.DefaultValue, sizeof(uniformParameter.DefaultValue)); m_UniformParameters.Add(uniformParameter); return true; } bool MaterialShaderGenerator::CreateTextureParameter(const char *Name, TEXTURE_TYPE Type) { if (FindTextureParameter(Name) >= 0) return false; TextureParameter textureParameter; textureParameter.Name = Name; textureParameter.Type = Type; m_TextureParameters.Add(textureParameter); return true; } bool MaterialShaderGenerator::CreateStaticSwitchParameter(const char *Name, const char *DefineName) { if (FindStaticSwitchParameter(Name) >= 0) return false; StaticSwitchParameter staticSwitchParameter; staticSwitchParameter.Name = Name; staticSwitchParameter.DefaultValue = true; m_StaticSwitchParameters.Add(staticSwitchParameter); return true; } int32 MaterialShaderGenerator::FindUniformParameter(const char *Name) { uint32 i; for (i = 0; i < m_UniformParameters.GetSize(); i++) { if (m_UniformParameters[i].Name.CompareInsensitive(Name)) return (int32)i; } return -1; } int32 MaterialShaderGenerator::FindTextureParameter(const char *Name) { uint32 i; for (i = 0; i < m_TextureParameters.GetSize(); i++) { if (m_TextureParameters[i].Name.CompareInsensitive(Name)) return (int32)i; } return -1; } int32 MaterialShaderGenerator::FindStaticSwitchParameter(const char *Name) { uint32 i; for (i = 0; i < m_StaticSwitchParameters.GetSize(); i++) { if (m_StaticSwitchParameters[i].Name.CompareInsensitive(Name)) return (int32)i; } return -1; } void MaterialShaderGenerator::RemoveUniformParameter(uint32 Index) { DebugAssert(Index < m_UniformParameters.GetSize()); m_UniformParameters.OrderedRemove(Index); } void MaterialShaderGenerator::RemoveTextureParameter(uint32 Index) { DebugAssert(Index < m_UniformParameters.GetSize()); m_TextureParameters.OrderedRemove(Index); } void MaterialShaderGenerator::RemoveStaticSwitchParameter(uint32 Index) { DebugAssert(Index < m_UniformParameters.GetSize()); m_StaticSwitchParameters.OrderedRemove(Index); } // MaterialShaderGenerator &MaterialShaderGenerator::operator=(const MaterialShaderGenerator &copyFrom) // { // m_eBlendingMode = copyFrom.m_eBlendingMode; // m_eLightingModel = copyFrom.m_eLightingModel; // m_bTwoSided = copyFrom.m_bTwoSided; // m_UniformParameters = copyFrom.m_UniformParameters; // m_TextureParameters = copyFrom.m_TextureParameters; // m_StaticSwitchParameters = copyFrom.m_StaticSwitchParameters; // // uint32 i; // for (i = 0; i < RENDERER_PLATFORM_COUNT; i++) // { // delete m_pShaderCodes[i]; // m_pShaderCodes[i] = (copyFrom.m_pShaderCodes[i] != NULL) ? new String(*copyFrom.m_pShaderCodes[i]) : NULL; // } // for (i = 0; i < SHADER_GRAPH_FEATURE_LEVEL_COUNT; i++) // { // delete m_pShaderGraphs[i]; // //m_pShaderGraphs[i] = (copyFrom.m_pShaderGraphs[i] != NULL) ? new ShaderGraph(*copyFrom.m_pShaderGraphs[i]) : NULL; // } // // return *this; // } String *MaterialShaderGenerator::CreateShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); Assert(m_pShaderCodes[featureLevel] == NULL); m_pShaderCodes[featureLevel] = new String(); return m_pShaderCodes[featureLevel]; } void MaterialShaderGenerator::DeleteShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); Assert(m_pShaderCodes[featureLevel] != NULL); delete m_pShaderCodes[featureLevel]; m_pShaderCodes[featureLevel] = NULL; } ShaderGraph *MaterialShaderGenerator::CreateShaderGraph(ResourceCompilerCallbacks *pCallbacks, RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); Assert(m_pShaderGraphs[featureLevel] == NULL); const ShaderGraphSchema *pSchema = ShaderGraphSchema::GetSchemaForFeatureLevel(pCallbacks, featureLevel); if (pSchema == NULL) return NULL; ShaderGraph *pShaderGraph = new ShaderGraph(); if (!pShaderGraph->Create(pSchema)) { delete pShaderGraph; pSchema->Release(); return NULL; } m_pShaderGraphs[featureLevel] = pShaderGraph; pSchema->Release(); return pShaderGraph; } void MaterialShaderGenerator::DeleteShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); Assert(m_pShaderGraphs[featureLevel] == NULL); delete m_pShaderGraphs[featureLevel]; m_pShaderGraphs[featureLevel] = NULL; } // Compiler bool MaterialShaderGenerator::Compile(ByteStream *pOutputStream, uint32 sourceCRC) { BinaryWriter binaryWriter(pOutputStream); // Create header DF_MATERIAL_SHADER_HEADER header; header.Magic = DF_MATERIAL_SHADER_HEADER_MAGIC; header.HeaderSize = sizeof(header); header.BlendingMode = (uint32)m_blendingMode; header.LightingType = (uint32)m_lightingType; header.LightingModel = (uint32)m_lightingModel; header.LightingNormalSpace = (uint32)m_lightingNormalSpace; header.RenderMode = (uint32)m_renderMode; header.RenderLayer = (uint32)m_renderLayer; header.TwoSided = m_twoSided; header.DepthClamping = m_depthClamping; header.DepthTests = m_depthTests; header.DepthWrites = m_depthWrites; header.CastShadows = m_castShadows; header.ReceiveShadows = m_receiveShadows; header.SourceCRC = sourceCRC; header.UniformParameterCount = (uint32)m_UniformParameters.GetSize(); header.TextureParameterCount = (uint32)m_TextureParameters.GetSize(); header.StaticSwitchParameterCount = (uint32)m_StaticSwitchParameters.GetSize(); // Perform overrides: translucent materials can't cast or receive shadows, nor write to the depth buffer if (m_blendingMode == MATERIAL_BLENDING_MODE_STRAIGHT || m_blendingMode == MATERIAL_BLENDING_MODE_PREMULTIPLIED) header.CastShadows = header.ReceiveShadows = header.DepthWrites = false; // Write header binaryWriter.WriteBytes(&header, sizeof(header)); // Write uniforms for (uint32 i = 0; i < m_UniformParameters.GetSize(); i++) { const UniformParameter &inParameter = m_UniformParameters[i]; DF_MATERIAL_SHADER_UNIFORM_PARAMETER outParameter; outParameter.NameLength = inParameter.Name.GetLength(); outParameter.Type = (uint32)inParameter.Type; Y_memcpy(&outParameter.DefaultValue, &inParameter.DefaultValue, sizeof(outParameter.DefaultValue)); binaryWriter.WriteBytes(&outParameter, sizeof(outParameter)); binaryWriter.WriteFixedString(inParameter.Name, outParameter.NameLength); } // Write textures for (uint32 i = 0; i < m_TextureParameters.GetSize(); i++) { const TextureParameter &inParameter = m_TextureParameters[i]; DF_MATERIAL_SHADER_TEXTURE_PARAMETER outParameter; outParameter.NameLength = inParameter.Name.GetLength(); outParameter.Type = (uint32)inParameter.Type; outParameter.DefaultValueLength = inParameter.DefaultValue.GetLength(); binaryWriter.WriteBytes(&outParameter, sizeof(outParameter)); binaryWriter.WriteFixedString(inParameter.Name, outParameter.NameLength); binaryWriter.WriteFixedString(inParameter.DefaultValue, outParameter.DefaultValueLength); } // Write static switches for (uint32 i = 0; i < m_StaticSwitchParameters.GetSize(); i++) { const StaticSwitchParameter &inParameter = m_StaticSwitchParameters[i]; DF_MATERIAL_SHADER_STATIC_SWITCH_PARAMETER outParameter; outParameter.NameLength = inParameter.Name.GetLength(); outParameter.Mask = (uint32)1 << i; outParameter.DefaultValue = inParameter.DefaultValue; binaryWriter.WriteBytes(&outParameter, sizeof(outParameter)); binaryWriter.WriteFixedString(inParameter.Name, outParameter.NameLength); } // Done return !binaryWriter.InErrorState(); } // Interface BinaryBlob *ResourceCompiler::CompileMaterialShader(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.msh.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileMaterialShader: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); MaterialShaderGenerator *pGenerator = new MaterialShaderGenerator(); if (!pGenerator->LoadFromXML(pCallbacks, sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } // calculate CRC32 of source before we nuke it CRC32 sourceCRC; sourceCRC.HashBytes(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); // release memory pStream->Release(); pSourceData->Release(); // compile shader ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream, sourceCRC.GetCRC())) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Editor/Source/Editor/MapEditor/EditorMap.h #pragma once #include "Editor/Common.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "MapCompiler/MapSource.h" #include "Engine/TerrainTypes.h" class EntityTypeInfo; class ObjectTemplate; class EditorMapWindow; class EditorMapViewport; class GPUOutputBuffer; class MapSource; class RenderWorld; class TerrainManager; class TerrainEntity; class BlockTerrainManager; class BlockTerrainRenderProxy; class EditorMapEditMode; class EditorEntityEditMode; class EditorGeometryEditMode; class EditorTerrainEditMode; class StaticMeshRenderProxy; class DirectionalLightRenderProxy; class AmbientLightRenderProxy; class EditorMap { public: EditorMap(EditorMapWindow *pMapWindow); ~EditorMap(); // current map accessors const EditorMapWindow *GetMapWindow() const { return m_pMapWindow; } const String &GetMapFileName() const { return m_strMapFileName; } const MapSource *GetMapSource() const { return m_pMapSource; } const RenderWorld *GetRenderWorld() const { return m_pRenderWorld; } const AABox &GetMapBoundingBox() const { return m_mapBoundingBox; } EditorMapWindow *GetMapWindow() { return m_pMapWindow; } MapSource *GetMapSource() { return m_pMapSource; } RenderWorld *GetRenderWorld() { return m_pRenderWorld; } // grid options const bool GetGridLinesVisible() const { return m_gridLinesVisible; } const float GetGridLinesInterval() const { return m_gridLinesInterval; } const bool GetGridSnapEnabled() const { return m_gridSnapEnabled; } const float GetGridSnapInterval() const { return m_gridSnapInterval; } void SetGridLinesVisible(bool visible) { m_gridLinesVisible = visible; RedrawAllViewports(); } void SetGridLinesInterval(float interval) { m_gridLinesInterval = interval; RedrawAllViewports(); } void SetGridSnapEnabled(bool enabled) { m_gridSnapEnabled = enabled; } void SetGridSnapInterval(float interval) { m_gridSnapInterval = interval; } // creates a map with the specified name in the specified location. bool CreateMap(); // open a map. bool OpenMap(const char *FileName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // saves the currently open map. if NewFileName is null, the existing filename is used. bool SaveMap(const char *NewFileName = NULL, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // map properties const String &GetMapProperty(const char *propertyName); void SetMapProperty(const char *propertyName, const char *propertyValue); // adding/removing entities EditorMapEntity *CreateEntity(const ObjectTemplate *pTemplate, const char *entityName = nullptr); EditorMapEntity *CreateEntity(const char *entityTypeName, const char *entityName = nullptr); void DeleteEntity(EditorMapEntity *pEntity); // copy an entity EditorMapEntity *CopyEntity(const EditorMapEntity *pEntity, const char *newName = nullptr); // map entity access const EditorMapEntity *GetEntityByArrayIndex(uint32 indexID) const; const EditorMapEntity *GetEntityByName(const char *entityName) const; EditorMapEntity *GetEntityByArrayIndex(uint32 indexID); EditorMapEntity *GetEntityByName(const char *entityName); uint32 GetEntityArraySize() const { return m_entities.GetSize(); } // when an entity property changes void OnEntityPropertyChanged(const EditorMapEntity *pEntity, const char *propertyName, const char *propertyValue); // when an entity transform changes void OnEntityBoundsChanged(const EditorMapEntity *pEntity); // merge map bounds with the specified bounds void MergeMapBoundingBox(const AABox &box); // when the map bounds change void OnMapBoundingBoxChange(); // entity enumeration template<typename T> void EnumerateEntities(T callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr) callback(m_entities[i]); } } template<typename T> void EnumerateEntitiesWithVisuals(T callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr && m_entities[i]->IsVisualCreated()) callback(m_entities[i]); } } // entity enumeration in space template<typename T> void EnumerateEntitiesInAABox(const AABox &box, T callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr && m_entities[i]->GetBoundingBox().AABoxIntersection(box)) callback(m_entities[i]); } } template<typename T> void EnumerateEntitiesInSphere(const Sphere &sphere, T callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr && m_entities[i]->GetBoundingSphere().SphereIntersection(sphere)) callback(m_entities[i]); } } // // entity properties // const MapSourceEntityData *GetEntityData(uint32 entityId) const; // String GetEntityPropertyValue(uint32 entityId, const char *propertyName) const; // bool SetEntityPropertyValue(uint32 entityId, const char *propertyName, const char *propertyValue); // edit mode const EditorMapEditMode *GetMapEditMode() const { return m_pMapEditMode; } const EditorEntityEditMode *GetEntityEditMode() const { return m_pEntityEditMode; } const EditorGeometryEditMode *GetGeometryEditMode() const { return m_pGeometryEditMode; } const EditorTerrainEditMode *GetTerrainEditMode() const { return m_pTerrainEditMode; } EditorMapEditMode *GetMapEditMode() { return m_pMapEditMode; } EditorEntityEditMode *GetEntityEditMode() { return m_pEntityEditMode; } EditorGeometryEditMode *GetGeometryEditMode() { return m_pGeometryEditMode; } EditorTerrainEditMode *GetTerrainEditMode() { return m_pTerrainEditMode; } // update, call every frame void Update(float timeSinceLastUpdate); // queue refresh of visible entities void OnViewportCameraChange() { m_entityVisualUpdatePending = true; } // queue redraw of all attached viewports void RedrawAllViewports(); // terrain accessors const bool HasTerrain() const { return (m_pTerrainEditMode != nullptr); } // terrain creation bool CreateTerrain(const char *importLayerListName, TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat, uint32 scale, uint32 sectionSize, uint32 renderLODCount, int32 minHeight, int32 maxHeight, int32 baseHeight); void DeleteTerrain(); // skybox accessors const bool GetSkyVisibility() const { return m_skyVisibility; } void SetSkyVisibility(bool enabled); // sun accessors const bool GetSunVisibility() const { return m_sunVisibility; } void SetSunVisibility(bool enabled); private: bool Initialize(ProgressCallbacks *pProgressCallbacks); // create the visual entiies bool InitializeEntities(ProgressCallbacks *pProgressCallbacks); bool InitializeTerrain(ProgressCallbacks *pProgressCallbacks); // visual creator EditorMapEntity *CreateInternalEntity(MapSourceEntityData *pEntityData); // test whether an entity is in visual range bool IsEntityInVisibleRange(const EditorMapEntity *pEntity) const; // update entity visuals streaming void UpdateEntityVisuals(); // hook for map property changing void OnMapPropertyChange(const char *propertyName, const char *propertyValue); // update skybox variables void UpdateSkyVariables(); void UpdateSkyTransform(); // update sun variables void UpdateSunVariables(); // currently open map EditorMapWindow *m_pMapWindow; String m_strMapFileName; MapSource *m_pMapSource; // grid options float m_gridLinesInterval; float m_gridSnapInterval; bool m_gridLinesVisible; bool m_gridSnapEnabled; // visual world RenderWorld *m_pRenderWorld; // map bounds, not necessarily accurate AABox m_mapBoundingBox; // visuals MemArray<EditorMapEntity *> m_entities; bool m_entityVisualUpdatePending; // edit mode instances EditorMapEditMode *m_pMapEditMode; EditorEntityEditMode *m_pEntityEditMode; EditorGeometryEditMode *m_pGeometryEditMode; // terrain EditorTerrainEditMode *m_pTerrainEditMode; // skybox bool m_skyVisibility; bool m_skyAutoSize; float m_skySize; float m_skyGroundHeight; StaticMeshRenderProxy *m_pSkyRenderProxy; // sun bool m_sunVisibility; DirectionalLightRenderProxy *m_pSunRenderProxy; AmbientLightRenderProxy *m_pSunAmbientRenderProxy; }; <file_sep>/Engine/Source/BaseGame/BaseGame.h #pragma once #include "BaseGame/Common.h" #include "BaseGame/GameState.h" #include "Renderer/Renderer.h" #include "Renderer/WorldRenderer.h" #include "Renderer/MiniGUIContext.h" #include "Engine/FPSCounter.h" #include "Engine/OverlayConsole.h" #include "Engine/SDLHeaders.h" class BaseGame { public: BaseGame(); virtual ~BaseGame(); //================================================================================================================================================================================================= // Startup/shutdown //================================================================================================================================================================================================= bool IsQuitPending() const { return m_quitFlag; } void CriticalError(const char *format, ...); int32 MainEntryPoint(); void Quit(); //================================================================================================================================================================================================= // GameState functions //================================================================================================================================================================================================= // Access the current game state GameState *GetGameState() const { return m_pGameState; } // Queue a game state for execution, deleting the current game beforehand. void SetNextGameState(GameState *pGameState); // Start a modal game state, saving the current state beforehand, and returning after EndModalGameState. void BeginModalGameState(GameState *pGameState); // End a modal game state, restoring the previous state. void EndModalGameState(); //================================================================================================================================================================================================= // Render functions, all these pointers are owned by the render thread //================================================================================================================================================================================================= GPUContext *GetGPUContext() { return m_pGPUContext; } RendererOutputWindow *GetOutputWindow() { return m_pOutputWindow; } WorldRenderer *GetWorldRenderer() { return m_pWorldRenderer; } MiniGUIContext *GetGUIContext() { return &m_guiContext; } void QueueRendererRestart() { m_restartRendererFlag = true; } void SetRelativeMouseMovement(bool enabled); void PushForcedAbsoluteMouseMovement(); void PopForcedAbsoluteMouseMovement(); protected: //================================================================================================================================================================================================= // Events //================================================================================================================================================================================================= virtual void OnRegisterTypes(); virtual bool OnStart(); virtual void OnWindowResized(uint32 width, uint32 height); virtual void OnWindowFocusGained(); virtual void OnWindowFocusLost(); virtual void OnMainThreadPreFrame(float deltaTime); virtual void OnMainThreadBeginFrame(float deltaTime); virtual void OnMainThreadAsyncTick(float deltaTime); virtual void OnMainThreadTick(float deltaTime); virtual void OnMainThreadEndFrame(float deltaTime); virtual void OnRenderThreadPreFrame(float deltaTime); virtual void OnRenderThreadBeginFrame(float deltaTime); virtual void OnRenderThreadDraw(float deltaTime); virtual void OnRenderThreadEndFrame(float deltaTime); virtual void OnExit(); protected: //================================================================================================================================================================================================= // Utility/subsystem-independent //================================================================================================================================================================================================= FPSCounter m_fpsCounter; OverlayConsole *m_pOverlayConsole; // flags bool m_quitFlag; bool m_restartRendererFlag; bool m_relativeMouseMovement; uint32 m_forcedAbsoluteMouseMovement; //================================================================================================================================================================================================= // Renderer Subsystem //================================================================================================================================================================================================= GPUContext *m_pGPUContext; RendererOutputWindow *m_pOutputWindow; WorldRenderer *m_pWorldRenderer; MiniGUIContext m_guiContext; Event m_renderThreadEventsReadyEvent; Event m_renderThreadFrameCompleteEvent; //================================================================================================================================================================================================= // GameState //================================================================================================================================================================================================= GameState *m_pGameState; GameState *m_pNextGameState; bool m_nextGameStateIsModal; bool m_gameStateEndModal; private: //================================================================================================================================================================================================= // Commands //================================================================================================================================================================================================= void RegisterBaseCommands(); // command entry points static bool Command_Quit_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_Quit_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_GC_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_GC_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_OpenDebugRenderWindow_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_OpenDebugRenderWindow_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_Profiler_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_Profiler_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_ProfilerDisplay_ExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool Command_ProfilerDisplay_HelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); //================================================================================================================================================================================================= // Input subsystem //================================================================================================================================================================================================= void RegisterBaseInputEvents(); void BindBaseInputEvents(); // input events void InputActionHandler_PreviousDebugCamera(); void InputActionHandler_NextDebugCamera(); // input variables MemArray<SDL_Event> m_pendingEvents; // game state stack PODArray<GameState *> m_gameStateStack; // time between frames Timer m_frameTimer; //================================================================================================================================================================================================= // Tasks //================================================================================================================================================================================================= // main thread tasks void MainThreadGameLoop(bool isModal); void MainThreadGameLoopIteration(); void MainThreadProcessInputEvents(float deltaTime); void MainThreadFrame(float deltaTime); // render thread tasks bool RendererStart(); void RenderThreadRestartRenderer(); void RenderThreadCollectEvents(float deltaTime); void RenderThreadFrame(float deltaTime); void RenderThreadDrawOverlays(float deltaTime); void RendererShutdown(); #ifdef Y_PLATFORM_HTML5 // frame trampoline callback for html5 static void HTML5FrameTrampoline(void *pParam); #endif #ifdef WITH_IMGUI //================================================================================================================================================================================================= // ImGui Stuff //================================================================================================================================================================================================= public: bool IsImGuiActivated() const { return (m_imGuiEnabled != 0); } void OpenDebugRenderMenu(); void ActivateImGui(); void DeactivateImGui(); private: // imgui overlay drawer void RenderThreadDrawImGuiOverlays(); // imgui vars uint32 m_imGuiEnabled; bool m_showDebugRenderMenu; #else // stubs when compiling without imgui bool IsImGuiActivated() const { return false; } void OpenDebugRenderMenu() {} void ActivateImGui() {} void DeactivateImGui() {} #endif #ifdef WITH_PROFILER //================================================================================================================================================================================================= // Profiler Stuff //================================================================================================================================================================================================= public: void SetProfilerDisplayMode(uint32 mode); void ToggleProfilerDisplay(); void HideProfilerDisplay(); private: bool m_profilerInterceptMouseEvents; #else // stubs when compiling without profiler void SetProfilerDisplayMode(uint32 mode) {} void ToggleProfilerDisplay() {} void HideProfilerDisplay() {} #endif public: //================================================================================================================================================================================================= // Helpers //================================================================================================================================================================================================= }; <file_sep>/Engine/Source/ResourceCompiler/ShaderGraph.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraph.h" #include "ResourceCompiler/ShaderGraphBuiltinNodes.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(ShaderGraph); static bool typesRegistered = false; ShaderGraph::ShaderGraph() : m_pSchema(NULL), m_iNextNodeId(1), m_pShaderInputsNode(NULL), m_pShaderOutputsNode(NULL) { // ensure types are registered if (!typesRegistered) { RegisterBuiltinTypes(); typesRegistered = true; } } ShaderGraph::~ShaderGraph() { int32 i; // clear the links in reverse order for (i = (int32)m_Links.GetSize() - 1; i >= 0; i--) RemoveLink(m_Links[i]); m_Links.Obliterate(); // clear the nodes in reverse order for (i = (int32)m_Nodes.GetSize() - 1; i >= 0; i--) delete m_Nodes[i]; m_Nodes.Obliterate(); SAFE_RELEASE(m_pSchema); } const ShaderGraphNode *ShaderGraph::GetNodeByID(uint32 NodeID) const { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { const ShaderGraphNode *pNode = m_Nodes[i]; if (pNode->GetID() == NodeID) return pNode; } return NULL; } const ShaderGraphNode *ShaderGraph::GetNodeByName(const char *Name) const { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { const ShaderGraphNode *pNode = m_Nodes[i]; if (pNode->GetName().CompareInsensitive(Name)) return pNode; } return NULL; } ShaderGraphNode *ShaderGraph::GetNodeByID(uint32 NodeID) { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { ShaderGraphNode *pNode = m_Nodes[i]; if (pNode->GetID() == NodeID) return pNode; } return NULL; } ShaderGraphNode *ShaderGraph::GetNodeByName(const char *Name) { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { ShaderGraphNode *pNode = m_Nodes[i]; if (pNode->GetName().CompareInsensitive(Name)) return pNode; } return NULL; } bool ShaderGraph::AddNode(ShaderGraphNode *pNode) { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { ShaderGraphNode *pCurNode = m_Nodes[i]; if (pCurNode->GetName().CompareInsensitive(pNode->GetName())) return false; } pNode->SetID(m_iNextNodeId++); m_Nodes.Add(pNode); //Log_DevPrintf("ShaderGraph: Add node '%s' (%s)", pNode->GetName().GetCharArray(), pNode->GetTypeInfo()->GetName()); return true; } bool ShaderGraph::RemoveNode(ShaderGraphNode *pNode) { uint32 i; for (i = 0; i < pNode->GetOutputCount(); i++) { if (pNode->GetOutput(i)->GetLinkCount() > 0) return false; } for (i = 0; i < m_Nodes.GetSize(); i++) { if (m_Nodes[i] == pNode) { pNode->SetID(0xFFFFFFFF); m_Nodes.OrderedRemove(i); delete pNode; return true; } } Panic("Attempting to remove node from shader graph that is not tracked."); return false; } bool ShaderGraph::AddLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { uint32 i; if (OutputIndex >= pSourceNode->GetOutputCount() || InputIndex >= pTargetNode->GetInputCount()) return false; ShaderGraphNodeInput *pInput = pTargetNode->GetInput(InputIndex); if (pInput->IsLinked()) return false; if (!pInput->SetLink(pSourceNode, OutputIndex, Swizzle)) return false; for (i = 0; i < m_Links.GetSize(); i++) { if (m_Links[i] == pInput) Panic("Double inserting input node."); } m_Links.Add(pInput); return true; } bool ShaderGraph::RemoveLink(ShaderGraphNode *pTargetNode, uint32 InputIndex) { if (InputIndex >= pTargetNode->GetInputCount()) return false; return RemoveLink(pTargetNode->GetInput(InputIndex)); } bool ShaderGraph::RemoveLink(ShaderGraphNodeInput *pInput) { uint32 i; pInput->ClearLink(); for (i = 0; i < m_Links.GetSize(); i++) { if (m_Links[i] == pInput) { m_Links.OrderedRemove(i); return true; } } Panic("Attempting to remove a non-tracked link."); return false; } bool ShaderGraph::Create(const ShaderGraphSchema *pSchema) { // set schema m_pSchema = pSchema; m_pSchema->AddRef(); // create the inputs node ShaderGraphNode_ShaderInputs *pInputsNode = new ShaderGraphNode_ShaderInputs(m_pSchema->GetInputDeclarations(), m_pSchema->GetInputDeclarationCount()); pInputsNode->SetName("SHADER_INPUTS"); if (!AddNode(pInputsNode)) { Log_ErrorPrintf("ShaderGraph: Unable to add shader inputs node to graph."); delete pInputsNode; return false; } // create the outputs node ShaderGraphNode_ShaderOutputs *pOutputsNode = new ShaderGraphNode_ShaderOutputs(m_pSchema->GetOutputDeclarations(), m_pSchema->GetOutputDeclarationCount()); pOutputsNode->SetName("SHADER_OUTPUTS"); if (!AddNode(pOutputsNode)) { Log_ErrorPrintf("ShaderGraph: Unable to add shader outputs node to graph."); delete pOutputsNode; return false; } m_pShaderInputsNode = pInputsNode; m_pShaderOutputsNode = pOutputsNode; return true; } bool ShaderGraph::LoadFromXML(const ShaderGraphSchema *pSchema, XMLReader &xmlReader) { // set schema and create inout nodes if (!Create(pSchema)) return false; // expected to be in the appropriate element if (!xmlReader.IsEmptyElement()) { // load nodes for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT && !xmlReader.IsEmptyElement()) { int32 shaderGraphSelection = xmlReader.Select("nodes|links"); if (shaderGraphSelection < 0) return false; switch (shaderGraphSelection) { // nodes case 0: { if (!ParseXMLNodes(xmlReader)) return false; } break; // links case 1: { if (!ParseXMLLinks(xmlReader)) return false; } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } } } return true; } //DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "shadergraph")); bool ShaderGraph::ParseXMLNodes(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("node") != 0) return false; const char *nodeType = xmlReader.FetchAttributeString("type"); if (nodeType == NULL) { xmlReader.PrintError("Incomplete node definition."); return false; } // lookup node type //const ShaderGraphNodeTypeInfo *pTypeInfo = ShaderGraphNode::FindTypeInfoForShortName(nodeType); //if (pTypeInfo == nullptr || pTypeInfo->GetFactory() == nullptr) const ObjectTypeInfo *pTypeInfo = ObjectTypeInfo::GetRegistry().GetTypeInfoByName(nodeType); if (pTypeInfo == nullptr || !pTypeInfo->IsDerived(OBJECT_TYPEINFO(ShaderGraphNode)) || pTypeInfo->GetFactory() == nullptr) { xmlReader.PrintError("Unknown node type '%s', or the type is uncreateable.", nodeType); return false; } // create it Object *pNodeObject = pTypeInfo->GetFactory()->CreateObject(); DebugAssert(pNodeObject != nullptr); // cast it ShaderGraphNode *pNode = pNodeObject->Cast<ShaderGraphNode>(); // load it if (!pNode->LoadFromXML(this, xmlReader)) { delete pNode; return false; } // add to graph if (!AddNode(pNode)) { xmlReader.PrintError("Failed to add node to graph."); delete pNode; return false; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "nodes")); break; } else { UnreachableCode(); } } } return true; } bool ShaderGraph::ParseXMLLinks(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("link") != 0) return false; const char *linkTarget = xmlReader.FetchAttribute("target"); const char *linkInputName = xmlReader.FetchAttribute("input"); const char *linkSourceName = xmlReader.FetchAttribute("source"); const char *linkOutputName = xmlReader.FetchAttribute("output"); const char *linkSwizzleStr = xmlReader.FetchAttribute("swizzle"); if (linkSourceName == NULL || linkOutputName == NULL || linkTarget == NULL || linkInputName == NULL) { xmlReader.PrintError("Incomplete link definition."); return false; } // Parse swizzle. SHADER_GRAPH_VALUE_SWIZZLE linkSwizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; if (linkSwizzleStr != NULL && !GetValueSwizzleFromString(&linkSwizzle, linkSwizzleStr)) { xmlReader.PrintError("Unknown swizzle: '%s'", linkSwizzleStr); return false; } // Find source node. ShaderGraphNode *pSourceNode = GetNodeByName(linkSourceName); if (pSourceNode == NULL) { xmlReader.PrintError("Could not find source node '%s' in graph.", linkSourceName); return false; } // Find target node. ShaderGraphNode *pTargetNode = GetNodeByName(linkTarget); if (pTargetNode == NULL) { xmlReader.PrintError("Could not find target node '%s' in graph.", linkTarget); return false; } // Search for the output index based on name. uint32 linkOutputIndex; for (linkOutputIndex = 0; linkOutputIndex < pSourceNode->GetOutputCount(); linkOutputIndex++) { if (Y_stricmp(linkOutputName, pSourceNode->GetOutput(linkOutputIndex)->GetOutputDesc()->Name) == 0) break; } if (linkOutputIndex == pSourceNode->GetOutputCount()) { xmlReader.PrintError("Could not find an output named '%s' in '%s' (%s)", linkOutputName, pSourceNode->GetName().GetCharArray(), pSourceNode->GetTypeInfo()->GetTypeName()); return false; } // repeat for input. uint32 linkInputIndex; for (linkInputIndex = 0; linkInputIndex < pTargetNode->GetInputCount(); linkInputIndex++) { if (Y_stricmp(linkInputName, pTargetNode->GetInput(linkInputIndex)->GetInputDesc()->Name) == 0) break; } if (linkInputIndex == pTargetNode->GetInputCount()) { xmlReader.PrintError("Could not find an input named '%s' in '%s' (%s)", linkInputName, pTargetNode->GetName().GetCharArray(), pTargetNode->GetTypeInfo()->GetTypeName()); return false; } // Create the link. //if (!pTargetNode->GetInput(linkTargetIndex)->SetLink(pSourceNode, linkSourceIndex, linkSwizzle)) if (!AddLink(pTargetNode, linkInputIndex, pSourceNode, linkOutputIndex, linkSwizzle)) { xmlReader.PrintError("Could not link node '%s' output '%s' to node '%s' input '%s' (swizzle: %s)", pSourceNode->GetName().GetCharArray(), pSourceNode->GetOutput(linkOutputIndex)->GetOutputDesc()->Name, pTargetNode->GetName().GetCharArray(), pTargetNode->GetInput(linkInputIndex)->GetInputDesc()->Name, (linkSwizzleStr != NULL) ? linkSwizzleStr : "none"); return false; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "links")); break; } else { UnreachableCode(); } } } return true; } static uint32 GetNodeInputDepth(const ShaderGraphNodeInput *pInput, uint32 currentDepth) { const ShaderGraphNode *pSourceNode = pInput->GetSourceNode(); if (pSourceNode == NULL) return currentDepth; uint32 i; uint32 passDepth = currentDepth + 1; uint32 maxDepth = 0; for (i = 0; i < pSourceNode->GetInputCount(); i++) { const ShaderGraphNodeInput *pNodeInput = pSourceNode->GetInput(i); maxDepth = Max(maxDepth, GetNodeInputDepth(pNodeInput, passDepth)); } return maxDepth; } bool ShaderGraph::SaveToXML(XMLWriter &xmlWriter) const { // save nodes xmlWriter.StartElement("nodes"); if (m_Nodes.GetSize() > 0) { uint32 i; for (i = 0; i < m_Nodes.GetSize(); i++) { const ShaderGraphNode *pNode = m_Nodes[i]; // don't write input/output nodes if (m_pShaderInputsNode == pNode || m_pShaderOutputsNode == pNode) continue; // create the node element xmlWriter.StartElement("node"); xmlWriter.WriteAttribute("type", pNode->GetTypeInfo()->GetShortName()); // save the node pNode->SaveToXML(xmlWriter); // end node element xmlWriter.EndElement(); } } xmlWriter.EndElement(); // save links xmlWriter.StartElement("links"); if (m_Nodes.GetSize() > 0) { // algo: // determine max depth // for i = max depth, i >= 0, i-- // save all links for nodes at this depth uint32 i, j, k; uint32 *pNodeMaxLinkDepths = new uint32[m_Nodes.GetSize()]; uint32 maxOverallInputDepth = 0; // determine max link depth of each node for (i = 0; i < m_Nodes.GetSize(); i++) { const ShaderGraphNode *pNode = m_Nodes[i]; uint32 nodeMaxInputDepth = 0; for (j = 0; j < pNode->GetInputCount(); j++) { uint32 nodeInputDepth = GetNodeInputDepth(pNode->GetInput(j), 0); nodeMaxInputDepth = Max(nodeMaxInputDepth, nodeInputDepth); } // store pNodeMaxLinkDepths[i] = nodeMaxInputDepth; } // save links at each node at each link depth level for (i = 0; i <= maxOverallInputDepth; i++) { for (j = 0; j < m_Nodes.GetSize(); j++) { if (pNodeMaxLinkDepths[j] != i) continue; const ShaderGraphNode *pNode = m_Nodes[j]; for (k = 0; k < pNode->GetInputCount(); k++) { const ShaderGraphNodeInput *pInput = pNode->GetInput(k); const ShaderGraphNode *pSourceNode = pInput->GetSourceNode(); if (pSourceNode != NULL) { char swizzleStr[5]; if (!GetStringForValueSwizzle(swizzleStr, pInput->GetSwizzle())) { Log_ErrorPrintf("Corrupted swizzle value in shader graph"); delete[] pNodeMaxLinkDepths; return false; } xmlWriter.StartElement("link"); xmlWriter.WriteAttribute("target", pNode->GetName()); xmlWriter.WriteAttribute("input", pInput->GetInputDesc()->Name); xmlWriter.WriteAttribute("source", pSourceNode->GetName()); xmlWriter.WriteAttribute("output", pSourceNode->GetOutput(pInput->GetSourceOutputIndex())->GetOutputDesc()->Name); xmlWriter.WriteAttribute("swizzle", swizzleStr); xmlWriter.EndElement(); } } } } delete[] pNodeMaxLinkDepths; } return true; } bool ShaderGraph::GetValueSwizzleFromString(SHADER_GRAPH_VALUE_SWIZZLE *pSwizzle, const char *str) { uint8 components[4] = { 255, 255, 255, 255 }; for (uint32 i = 0; i < 4; i++) { if (str[i] == '\0') break; char ch = str[i]; if (ch == 'R' || ch == 'r') components[i] = 0; else if (ch == 'G' || ch == 'g') components[i] = 1; else if (ch == 'B' || ch == 'b') components[i] = 2; else if (ch == 'A' || ch == 'a') components[i] = 3; else return false; } *pSwizzle = ((uint32)components[0] << 24) | ((uint32)components[1] << 16) | ((uint32)components[2] << 8) | ((uint32)components[3]); return true; } bool ShaderGraph::GetStringForValueSwizzle(char outString[5], SHADER_GRAPH_VALUE_SWIZZLE swizzle) { uint32 i; for (i = 0; i < 4; i++) { uint32 componentIndex = (swizzle >> ((3 - i) * 8)) & 0xFF; if (componentIndex == 255) break; if (componentIndex >= 4) return false; static const char componentNames[4] = { 'r', 'g', 'b', 'a' }; outString[i] = componentNames[componentIndex]; } outString[i] = '\0'; return true; } uint32 ShaderGraph::GetValueSwizzleComponentCount(SHADER_GRAPH_VALUE_SWIZZLE swizzle) { if (((swizzle >> 24) & 0xFF) < 4) { if (((swizzle >> 16) & 0xFF) < 4) { if (((swizzle >> 8) & 0xFF) < 4) { if (((swizzle) & 0xFF) < 4) { return 4; } else { return 3; } } else { return 2; } } else { return 1; } } else { return 0; } } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUOutputBuffer.h #pragma once #include "D3D11Renderer/D3D11Common.h" #include "D3D11Renderer/D3D11GPUTexture.h" class D3D11GPUOutputBuffer; class D3D11RendererOutputWindow; union SDL_Event; class D3D11GPUOutputBuffer : public GPUOutputBuffer { friend class D3D11RendererOutputWindow; public: virtual ~D3D11GPUOutputBuffer(); // virtual methods virtual uint32 GetWidth() const override { return m_width; } virtual uint32 GetHeight() const override { return m_height; } virtual void SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) override; // creation static D3D11GPUOutputBuffer *Create(IDXGIFactory *pDXGIFactory, ID3D11Device *pD3DDevice, HWND hWnd, DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType); // views HWND GetHWND() const { return m_hWnd; } ID3D11Device *GetD3DDevice() const { return m_pD3DDevice; } IDXGISwapChain *GetDXGISwapChain() const { return m_pDXGISwapChain; } ID3D11Texture2D *GetBackBufferTexture() const { return m_pBackBufferTexture; } ID3D11RenderTargetView *GetRenderTargetView() const { return m_pRenderTargetView; } ID3D11Texture2D *GetDepthStencilBuffer() const { return m_pDepthStencilBuffer; } ID3D11DepthStencilView *GetDepthStencilView() const { return m_pDepthStencilView; } DXGI_FORMAT GetBackBufferFormat() const { return m_backBufferFormat; } DXGI_FORMAT GetDepthStencilBufferFormat() const { return m_depthStencilBufferFormat; } void InternalResizeBuffers(uint32 width, uint32 height, RENDERER_VSYNC_TYPE vsyncType); bool InternalCreateBuffers(); void InternalReleaseBuffers(); private: D3D11GPUOutputBuffer(ID3D11Device *pD3DDevice, IDXGISwapChain *pDXGISwapChain, HWND hWnd, uint32 width, uint32 height, DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType); ID3D11Device *m_pD3DDevice; IDXGISwapChain *m_pDXGISwapChain; HWND m_hWnd; uint32 m_width; uint32 m_height; DXGI_FORMAT m_backBufferFormat; DXGI_FORMAT m_depthStencilBufferFormat; ID3D11Texture2D *m_pBackBufferTexture; ID3D11RenderTargetView *m_pRenderTargetView; ID3D11Texture2D *m_pDepthStencilBuffer; ID3D11DepthStencilView *m_pDepthStencilView; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUDevice.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" #include "Engine/EngineCVars.h" Log_SetChannel(OpenGLRenderBackend); Y_DECLARE_THREAD_LOCAL(SDL_GLContext) s_currentThreadGLContext = nullptr; Y_DECLARE_THREAD_LOCAL(uint32) s_currentThreadUploadBatchCount = 0; OpenGLGPUDevice::UploadContextReference::UploadContextReference(OpenGLGPUDevice *pDevice) : pDevice(pDevice) { // Check if we have a context already. If not, use the off-thread context. if (s_currentThreadGLContext != nullptr) { ContextNeedsRelease = false; return; } else if (pDevice->GetOffThreadGLContext() != nullptr) { ContextNeedsRelease = true; return; } // Flag us as not getting a context. ContextNeedsRelease = false; pDevice = nullptr; } OpenGLGPUDevice::UploadContextReference::~UploadContextReference() { if (ContextNeedsRelease) pDevice->ReleaseOffThreadGLContext(); } bool OpenGLGPUDevice::UploadContextReference::HasContext() const { return (pDevice != nullptr); } OpenGLGPUDevice::OpenGLGPUDevice(SDL_GLContext pMainGLContext, SDL_GLContext pOffThreadGLContext, OpenGLGPUOutputBuffer *pImplicitOutputBuffer, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, PIXEL_FORMAT outputBackBufferFormat, PIXEL_FORMAT outputDepthStencilFormat) : m_pMainGLContext(pMainGLContext) , m_pOffThreadGLContext(pOffThreadGLContext) , m_pImmediateContext(nullptr) , m_pImplicitOutputBuffer(pImplicitOutputBuffer) , m_featureLevel(featureLevel) , m_texturePlatform(texturePlatform) , m_outputBackBufferFormat(outputBackBufferFormat) , m_outputDepthStencilFormat(outputDepthStencilFormat) { m_pImplicitOutputBuffer->AddRef(); } OpenGLGPUDevice::~OpenGLGPUDevice() { DebugAssert(m_pImmediateContext == nullptr); // clear current context SDL_GL_MakeCurrent(nullptr, nullptr); // nuke off-thread gl context SDL_GL_DeleteContext(m_pOffThreadGLContext); // nuke main GL context SDL_GL_DeleteContext(m_pMainGLContext); // now the window/buffer can go m_pImplicitOutputBuffer->Release(); } RENDERER_PLATFORM OpenGLGPUDevice::GetPlatform() const { return RENDERER_PLATFORM_OPENGL; } RENDERER_FEATURE_LEVEL OpenGLGPUDevice::GetFeatureLevel() const { return m_featureLevel; } TEXTURE_PLATFORM OpenGLGPUDevice::GetTexturePlatform() const { return m_texturePlatform; } void OpenGLGPUDevice::GetCapabilities(RendererCapabilities *pCapabilities) const { // run glget calls uint32 maxTextureAnisotropy = 0; uint32 maxVertexAttributes = 0; uint32 maxColorAttachments = 0; uint32 maxUniformBufferBindings = 0; uint32 maxTextureUnits = 0; uint32 maxRenderTargets = 0; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, reinterpret_cast<GLint *>(&maxTextureAnisotropy)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, reinterpret_cast<GLint *>(&maxColorAttachments)); glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, reinterpret_cast<GLint *>(&maxUniformBufferBindings)); glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, reinterpret_cast<GLint *>(&maxTextureUnits)); glGetIntegerv(GL_MAX_DRAW_BUFFERS, reinterpret_cast<GLint *>(&maxRenderTargets)); pCapabilities->MaxTextureAnisotropy = maxTextureAnisotropy; pCapabilities->MaximumVertexBuffers = maxVertexAttributes; pCapabilities->MaximumConstantBuffers = maxUniformBufferBindings; pCapabilities->MaximumTextureUnits = maxTextureUnits; pCapabilities->MaximumSamplers = maxTextureUnits; pCapabilities->MaximumRenderTargets = maxRenderTargets; pCapabilities->MaxTextureAnisotropy = maxTextureAnisotropy; pCapabilities->SupportsCommandLists = false; //pCapabilities->SupportsMultithreadedResourceCreation = true; pCapabilities->SupportsMultithreadedResourceCreation = false; pCapabilities->SupportsDrawBaseVertex = true; // @TODO pCapabilities->SupportsDepthTextures = (GLAD_GL_ARB_depth_texture == GL_TRUE); pCapabilities->SupportsTextureArrays = (GLAD_GL_EXT_texture_array == GL_TRUE); pCapabilities->SupportsCubeMapTextureArrays = (GLAD_GL_ARB_texture_cube_map_array == GL_TRUE); pCapabilities->SupportsGeometryShaders = (GLAD_GL_EXT_geometry_shader4 == GL_TRUE); pCapabilities->SupportsSinglePassCubeMaps = (GLAD_GL_EXT_geometry_shader4 == GL_TRUE && GLAD_GL_ARB_viewport_array == GL_TRUE); pCapabilities->SupportsInstancing = (GLAD_GL_EXT_draw_instanced == GL_TRUE); } bool OpenGLGPUDevice::CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat /*= NULL*/) const { // @TODO return true; } void OpenGLGPUDevice::CorrectProjectionMatrix(float4x4 &projectionMatrix) const { float4x4 scaleMatrix(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); float4x4 biasMatrix(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); projectionMatrix = biasMatrix * scaleMatrix * projectionMatrix; } float OpenGLGPUDevice::GetTexelOffset() const { return 0.0f; } SDL_GLContext OpenGLGPUDevice::GetOffThreadGLContext() { DebugAssert(s_currentThreadGLContext == nullptr); m_offThreadGLContextLock.Lock(); SDL_GL_MakeCurrent(m_pImplicitOutputBuffer->GetSDLWindow(), m_pOffThreadGLContext); s_currentThreadGLContext = m_pOffThreadGLContext; return m_pOffThreadGLContext; } void OpenGLGPUDevice::ReleaseOffThreadGLContext() { DebugAssert(s_currentThreadGLContext == m_pOffThreadGLContext); // glFlush() or glFinish() for shared lists? glFinish(); s_currentThreadGLContext = nullptr; SDL_GL_MakeCurrent(nullptr, nullptr); m_offThreadGLContextLock.Unlock(); } void OpenGLGPUDevice::BindMutatorTextureUnit() { if (m_pImmediateContext != nullptr) m_pImmediateContext->BindMutatorTextureUnit(); } void OpenGLGPUDevice::RestoreMutatorTextureUnit() { if (m_pImmediateContext != nullptr) m_pImmediateContext->RestoreMutatorTextureUnit(); } void OpenGLGPUDevice::BeginResourceBatchUpload() { // First time? if ((s_currentThreadUploadBatchCount++) == 0) { // Either on main thread or no upload begun. DebugAssert(s_currentThreadGLContext == m_pMainGLContext || s_currentThreadGLContext == nullptr); // If off-thread, get a context. if (s_currentThreadGLContext == nullptr) GetOffThreadGLContext(); } } void OpenGLGPUDevice::EndResourceBatchUpload() { DebugAssert(s_currentThreadUploadBatchCount > 0); if ((--s_currentThreadUploadBatchCount) == 0) { DebugAssert(s_currentThreadGLContext != nullptr); // Are we on an off thread? if (s_currentThreadGLContext != m_pMainGLContext) { // Release context. ReleaseOffThreadGLContext(); } } } // ------------------ OpenGLGPUSamplerState::OpenGLGPUSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, GLuint samplerID) : GPUSamplerState(pSamplerStateDesc), m_GLSamplerID(samplerID) { } OpenGLGPUSamplerState::~OpenGLGPUSamplerState() { glDeleteSamplers(1, &m_GLSamplerID); } void OpenGLGPUSamplerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void OpenGLGPUSamplerState::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_SAMPLER, m_GLSamplerID, name); } GPUSamplerState *OpenGLGPUDevice::CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; GL_CHECKED_SECTION_BEGIN(); GLuint samplerID = 0; glGenSamplers(1, &samplerID); if (samplerID == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateSamplerState: Sampler allocation failed: "); return nullptr; } glSamplerParameterfv(samplerID, GL_TEXTURE_BORDER_COLOR, pSamplerStateDesc->BorderColor); glSamplerParameteri(samplerID, GL_TEXTURE_COMPARE_FUNC, OpenGLTypeConversion::GetOpenGLComparisonFunc(pSamplerStateDesc->ComparisonFunc)); glSamplerParameteri(samplerID, GL_TEXTURE_COMPARE_MODE, OpenGLTypeConversion::GetOpenGLComparisonMode(pSamplerStateDesc->Filter)); glSamplerParameterf(samplerID, GL_TEXTURE_LOD_BIAS, pSamplerStateDesc->LODBias); glSamplerParameteri(samplerID, GL_TEXTURE_MIN_FILTER, OpenGLTypeConversion::GetOpenGLTextureMinFilter(pSamplerStateDesc->Filter)); glSamplerParameteri(samplerID, GL_TEXTURE_MAG_FILTER, OpenGLTypeConversion::GetOpenGLTextureMagFilter(pSamplerStateDesc->Filter)); glSamplerParameterf(samplerID, GL_TEXTURE_MIN_LOD, (float)pSamplerStateDesc->MinLOD); glSamplerParameterf(samplerID, GL_TEXTURE_MAX_LOD, (float)pSamplerStateDesc->MaxLOD); glSamplerParameteri(samplerID, GL_TEXTURE_WRAP_S, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressU)); glSamplerParameteri(samplerID, GL_TEXTURE_WRAP_T, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressV)); glSamplerParameteri(samplerID, GL_TEXTURE_WRAP_R, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressW)); if (pSamplerStateDesc->Filter == TEXTURE_FILTER_ANISOTROPIC || pSamplerStateDesc->Filter == TEXTURE_FILTER_COMPARISON_ANISOTROPIC) glSamplerParameterf(samplerID, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)pSamplerStateDesc->MaxAnisotropy); else glSamplerParameterf(samplerID, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); return new OpenGLGPUSamplerState(pSamplerStateDesc, samplerID); } OpenGLGPURasterizerState::OpenGLGPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) : GPURasterizerState(pRasterizerStateDesc) { m_GLPolygonMode = OpenGLTypeConversion::GetOpenGLPolygonMode(pRasterizerStateDesc->FillMode); m_GLCullFace = OpenGLTypeConversion::GetOpenGLCullFace(pRasterizerStateDesc->CullMode); m_GLCullEnabled = (pRasterizerStateDesc->CullMode != RENDERER_CULL_NONE) ? true : false; m_GLFrontFace = (pRasterizerStateDesc->FrontCounterClockwise) ? GL_CCW : GL_CW; m_GLScissorTestEnable = pRasterizerStateDesc->ScissorEnable; m_GLDepthClampEnable = !pRasterizerStateDesc->DepthClipEnable; } OpenGLGPURasterizerState::~OpenGLGPURasterizerState() { } void OpenGLGPURasterizerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLGPURasterizerState::SetDebugName(const char *name) { } void OpenGLGPURasterizerState::Apply() { glPolygonMode(GL_FRONT_AND_BACK, m_GLPolygonMode); glCullFace(m_GLCullFace); (m_GLCullEnabled) ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); glFrontFace(m_GLFrontFace); (m_GLScissorTestEnable) ? glEnable(GL_SCISSOR_TEST) : glDisable(GL_SCISSOR_TEST); (m_GLDepthClampEnable) ? glEnable(GL_DEPTH_CLAMP) : glDisable(GL_DEPTH_CLAMP); } void OpenGLGPURasterizerState::Unapply() { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glDisable(GL_SCISSOR_TEST); glDisable(GL_DEPTH_CLAMP); } GPURasterizerState *OpenGLGPUDevice::CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) { return new OpenGLGPURasterizerState(pRasterizerStateDesc); } OpenGLGPUDepthStencilState::OpenGLGPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) : GPUDepthStencilState(pDepthStencilStateDesc) { m_GLDepthTestEnable = pDepthStencilStateDesc->DepthTestEnable; m_GLDepthMask = (pDepthStencilStateDesc->DepthWriteEnable) ? GL_TRUE : GL_FALSE; m_GLDepthFunc = OpenGLTypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->DepthFunc); m_GLStencilTestEnable = pDepthStencilStateDesc->StencilTestEnable; m_GLStencilReadMask = pDepthStencilStateDesc->StencilReadMask; m_GLStencilWriteMask = pDepthStencilStateDesc->StencilWriteMask; m_GLStencilFuncFront = OpenGLTypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->StencilFrontFace.CompareFunc); m_GLStencilOpFrontFail = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.FailOp); m_GLStencilOpFrontDepthFail = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.DepthFailOp); m_GLStencilOpFrontPass = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.PassOp); m_GLStencilFuncBack = OpenGLTypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->StencilBackFace.CompareFunc); m_GLStencilOpBackFail = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.FailOp); m_GLStencilOpBackDepthFail = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.DepthFailOp); m_GLStencilOpBackPass = OpenGLTypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.PassOp); } OpenGLGPUDepthStencilState::~OpenGLGPUDepthStencilState() { } void OpenGLGPUDepthStencilState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLGPUDepthStencilState::SetDebugName(const char *name) { } void OpenGLGPUDepthStencilState::Apply(uint8 StencilRef) { (m_GLDepthTestEnable) ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glDepthMask(m_GLDepthMask); glDepthFunc(m_GLDepthFunc); (m_GLStencilTestEnable) ? glEnable(GL_STENCIL_TEST) : glDisable(GL_STENCIL_TEST); glStencilFuncSeparate(GL_FRONT, m_GLStencilFuncFront, StencilRef, m_GLStencilReadMask); glStencilOpSeparate(GL_FRONT, m_GLStencilOpFrontFail, m_GLStencilOpFrontDepthFail, m_GLStencilOpFrontPass); glStencilFuncSeparate(GL_BACK, m_GLStencilFuncBack, StencilRef, m_GLStencilReadMask); glStencilOpSeparate(GL_BACK, m_GLStencilOpBackFail, m_GLStencilOpBackDepthFail, m_GLStencilOpBackPass); glStencilMask(m_GLStencilWriteMask); } void OpenGLGPUDepthStencilState::Unapply() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); glDisable(GL_STENCIL_TEST); glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, 0, 0xFF); glStencilOpSeparate(GL_FRONT_AND_BACK, GL_KEEP, GL_KEEP, GL_KEEP); glStencilMask(0xFF); } GPUDepthStencilState *OpenGLGPUDevice::CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) { return new OpenGLGPUDepthStencilState(pDepthStencilStateDesc); } OpenGLGPUBlendState::OpenGLGPUBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) : GPUBlendState(pBlendStateDesc) { m_GLBlendEnable = pBlendStateDesc->BlendEnable; m_GLBlendEquationRGB = OpenGLTypeConversion::GetOpenGLBlendEquation(pBlendStateDesc->BlendOp); m_GLBlendEquationAlpha = OpenGLTypeConversion::GetOpenGLBlendEquation(pBlendStateDesc->BlendOpAlpha); m_GLBlendFuncSrcRGB = OpenGLTypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->SrcBlend); m_GLBlendFuncSrcAlpha = OpenGLTypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->SrcBlendAlpha); m_GLBlendFuncDstRGB = OpenGLTypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->DestBlend); m_GLBlendFuncDstAlpha = OpenGLTypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->DestBlendAlpha); m_GLColorWritesEnabled = pBlendStateDesc->ColorWriteEnable; } OpenGLGPUBlendState::~OpenGLGPUBlendState() { } void OpenGLGPUBlendState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLGPUBlendState::SetDebugName(const char *name) { } void OpenGLGPUBlendState::Apply() { (m_GLBlendEnable) ? glEnable(GL_BLEND) : glDisable(GL_BLEND); glBlendEquationSeparate(m_GLBlendEquationRGB, m_GLBlendEquationAlpha); glBlendFuncSeparate(m_GLBlendFuncSrcRGB, m_GLBlendFuncDstRGB, m_GLBlendFuncSrcAlpha, m_GLBlendFuncDstAlpha); (m_GLColorWritesEnabled) ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } void OpenGLGPUBlendState::Unapply() { glDisable(GL_BLEND); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } GPUBlendState *OpenGLGPUDevice::CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) { return new OpenGLGPUBlendState(pBlendStateDesc); } <file_sep>/Engine/Source/Renderer/WorldRenderers/SingleShaderWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/SingleShaderWorldRenderer.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderQueue.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Engine/Material.h" #include "Engine/ResourceManager.h" #include "Engine/Texture.h" #include "Engine/EngineCVars.h" #include "Engine/Profiling.h" SingleShaderWorldRenderer::SingleShaderWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : WorldRenderer(pGPUContext, pOptions) { const uint32 availableRenderPassMask = RENDER_PASS_LIGHTMAP | RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING | RENDER_PASS_TINT; // initialize render queues m_renderQueue.SetAcceptingLights(false); m_renderQueue.SetAcceptingRenderPassMask(availableRenderPassMask); m_renderQueue.SetAcceptingOccluders(false); m_renderQueue.SetAcceptingDebugObjects(CVars::r_show_debug_info.GetBool()); } SingleShaderWorldRenderer::~SingleShaderWorldRenderer() { } void SingleShaderWorldRenderer::DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) { MICROPROFILE_SCOPEI("SingleShaderWorldRenderer", "DrawWorld", MICROPROFILE_COLOR(47, 85, 200)); // initialize and clear render targets, kick this off first { MICROPROFILE_SCOPEI("SingleShaderWorldRenderer", "Prepare", MICROPROFILE_COLOR(45, 75, 200)); // set render targets, for pipelining we do this before sorting m_pGPUContext->SetRenderTargets(1, &pRenderTargetView, pDepthStencilBufferView); m_pGPUContext->SetViewport(&pViewParameters->Viewport); // clear targets m_pGPUContext->ClearTargets(true, true, true, pViewParameters->FogColor); // set up view-dependent constants GPUContextConstants *pConstants = m_pGPUContext->GetConstants(); pConstants->SetFromCamera(pViewParameters->ViewCamera, false); pConstants->SetWorldTime(pViewParameters->WorldTime, false); pConstants->CommitChanges(); } // fill render queue FillRenderQueue(&pViewParameters->ViewCamera, pRenderWorld); // no renderables? if (m_renderQueue.GetQueueSize() == 0) return; // opaque { PreDraw(pViewParameters); DrawOpqaueObjects(pViewParameters); PostDraw(pViewParameters); if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetOpaqueRenderables()); } // postprocess { PreDraw(pViewParameters); DrawPostProcessObjects(pViewParameters); PostDraw(pViewParameters); } // translucent { PreDraw(pViewParameters); DrawTranslucentObjects(pViewParameters); PostDraw(pViewParameters); } // debug info if (m_options.ShowDebugInfo && m_pGUIContext != nullptr) DrawDebugInfo(&pViewParameters->ViewCamera); // clear targets and shaders m_pGPUContext->ClearState(true, true, true, true); OnFrameComplete(); } void SingleShaderWorldRenderer::DrawOpqaueObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("SingleShaderWorldRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(200, 75, 200)); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) DrawQueueEntry(pViewParameters, pQueueEntry); } if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetOpaqueRenderables()); } void SingleShaderWorldRenderer::DrawPostProcessObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("SingleShaderWorldRenderer", "DrawPostProcessObjects", MICROPROFILE_COLOR(45, 200, 75)); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetPostProcessRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetPostProcessRenderables().GetBasePointer() + m_renderQueue.GetPostProcessRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) DrawQueueEntry(pViewParameters, pQueueEntry); } if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetPostProcessRenderables()); } void SingleShaderWorldRenderer::DrawTranslucentObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("SingleShaderWorldRenderer", "DrawTranslucentObjects", MICROPROFILE_COLOR(75, 45, 200)); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) DrawQueueEntry(pViewParameters, pQueueEntry); } if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetTranslucentRenderables()); } void SingleShaderWorldRenderer::SetCommonShaderProgramParameters(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram) { pQueueEntry->pMaterial->BindDeviceResources(m_pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext, pShaderProgram); // post process material? const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); if (pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) { // set post process textures const uint32 BASE_INDEX = pMaterialShader->GetTextureParameterCount(); pShaderProgram->SetMaterialParameterTexture(m_pGPUContext, BASE_INDEX + 0, g_pResourceManager->GetDefaultTexture2D()->GetGPUTexture(), nullptr); // fixme pShaderProgram->SetMaterialParameterTexture(m_pGPUContext, BASE_INDEX + 1, g_pResourceManager->GetDefaultTexture2D()->GetGPUTexture(), nullptr); // fixme } } void SingleShaderWorldRenderer::PreDraw(const ViewParameters *pViewParameters) { } void SingleShaderWorldRenderer::DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { } void SingleShaderWorldRenderer::PostDraw(const ViewParameters *pViewParameters) { } <file_sep>/Engine/Source/Engine/Skeleton.h #pragma once #include "Engine/Common.h" class Skeleton : public Resource { DECLARE_RESOURCE_TYPE_INFO(Skeleton, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(Skeleton); public: class Bone { friend class Skeleton; public: Bone() : m_index(0xFFFFFFFF), m_pParentBone(nullptr) {} const uint32 GetIndex() const { return m_index; } const String &GetName() const { return m_name; } const Bone *GetParentBone() const { return m_pParentBone; } const Transform &GetRelativeBaseFrameTransform() const { return m_relativeBaseFrameTransform; } const Transform &GetAbsoluteBaseFrameTransform() const { return m_absoluteBaseFrameTransform; } const Bone *GetChildBone(uint32 childIndex) const { return m_childBones[childIndex]; } const uint32 GetChildBoneCount() const { return m_childBones.GetSize(); } private: uint32 m_index; const Bone *m_pParentBone; String m_name; Transform m_relativeBaseFrameTransform; Transform m_absoluteBaseFrameTransform; PODArray<const Bone *> m_childBones; }; public: Skeleton(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); virtual ~Skeleton(); // bone info const uint32 GetBoneCount() const { return m_bones.GetSize(); } const Bone *GetRootBone() const { return &m_bones[0]; } const Bone *GetBoneByIndex(uint32 boneIndex) const { return &m_bones[boneIndex]; } const Bone *GetBoneByName(const char *boneName) const; // initialization bool LoadFromStream(const char *name, ByteStream *pStream); private: Array<Bone> m_bones; }; <file_sep>/Engine/Source/GameFramework/PointLightComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/PointLightComponent.h" #include "Engine/Entity.h" #include "Engine/World.h" #include "Renderer/RenderProxies/PointLightRenderProxy.h" #include "Renderer/RenderWorld.h" DEFINE_COMPONENT_TYPEINFO(PointLightComponent); DEFINE_COMPONENT_GENERIC_FACTORY(PointLightComponent); BEGIN_COMPONENT_PROPERTIES(PointLightComponent) PROPERTY_TABLE_MEMBER_BOOL("Enabled", 0, offsetof(PointLightComponent, m_enabled), OnEnabledPropertyChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("Range", 0, offsetof(PointLightComponent, m_range), OnRangePropertyChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT3("Color", 0, offsetof(PointLightComponent, m_color), OnColorOrBrightnessPropertyChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("Brightness", 0, offsetof(PointLightComponent, m_brightness), OnColorOrBrightnessPropertyChange, nullptr) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(PointLightComponent, m_shadowFlags), OnShadowPropertyChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("FalloffExponent", 0, offsetof(PointLightComponent, m_falloffExponent), OnFalloffExponentChange, nullptr) END_COMPONENT_PROPERTIES() PointLightComponent::PointLightComponent(const ComponentTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_enabled(true), m_range(8.0f), m_color(float3::One), m_brightness(1.0f), m_shadowFlags(0), m_falloffExponent(1.0f), m_pRenderProxy(nullptr) { } PointLightComponent::~PointLightComponent() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); } void PointLightComponent::SetEnabled(bool enabled) { m_enabled = enabled; OnEnabledPropertyChange(this); } void PointLightComponent::SetRange(float range) { m_range = range; OnRangePropertyChange(this); } void PointLightComponent::SetColor(const float3 &color) { m_color = color; OnColorOrBrightnessPropertyChange(this); } void PointLightComponent::SetBrightness(float brightness) { m_brightness = brightness; OnColorOrBrightnessPropertyChange(this); } void PointLightComponent::SetShadowFlags(uint32 lightShadowFlags) { m_shadowFlags = lightShadowFlags; OnShadowPropertyChange(this); } void PointLightComponent::SetFalloffExponent(float falloffExponent) { m_falloffExponent = falloffExponent; OnFalloffExponentChange(this); } void PointLightComponent::Create(const float3 &localPosition /*= float3::Zero*/, bool enabled /*= true*/, float range /*= 8.0f*/, const float3 &color /*= float3::One*/, float brightness /*= 1.0f*/, uint32 shadowFlags /*= 0*/, float falloffExponent /*= 1.0f*/) { // easy enough m_localPosition = localPosition; m_enabled = enabled; m_range = range; m_color = color; m_brightness = brightness; m_shadowFlags = shadowFlags; m_falloffExponent = falloffExponent; Initialize(); } bool PointLightComponent::Initialize() { if (!BaseClass::Initialize()) return false; // create the render proxy m_pRenderProxy = new PointLightRenderProxy(0, m_localPosition, m_range, m_color, m_shadowFlags, m_falloffExponent); return true; } void PointLightComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // extract position from entity float3 lightPosition(CalculateLightPosition()); m_pRenderProxy->SetPosition(lightPosition); m_pRenderProxy->SetEntityID(pEntity->GetEntityID()); // update bounds SetBounds(PointLightRenderProxy::CalculatePointLightBoundingBox(lightPosition, m_range), PointLightRenderProxy::CalculatePointLightBoundingSphere(lightPosition, m_range), true); } void PointLightComponent::OnRemoveFromEntity(Entity *pEntity) { m_pRenderProxy->SetEntityID(0); BaseClass::OnRemoveFromEntity(pEntity); } void PointLightComponent::OnLocalTransformChange() { // update position and bounds float3 lightPosition(CalculateLightPosition()); m_pRenderProxy->SetPosition(lightPosition); SetBounds(PointLightRenderProxy::CalculatePointLightBoundingBox(lightPosition, m_range), PointLightRenderProxy::CalculatePointLightBoundingSphere(lightPosition, m_range), true); } void PointLightComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // update position and bounds float3 lightPosition(CalculateLightPosition()); m_pRenderProxy->SetPosition(lightPosition); SetBounds(PointLightRenderProxy::CalculatePointLightBoundingBox(lightPosition, m_range), PointLightRenderProxy::CalculatePointLightBoundingSphere(lightPosition, m_range), true); } void PointLightComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void PointLightComponent::OnRemoveFromWorld(World *pWorld) { pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); BaseClass::OnRemoveFromWorld(pWorld); } float3 PointLightComponent::CalculateLightPosition() const { return (m_pEntity != nullptr) ? (m_pEntity->GetPosition() + m_localPosition) : (m_localPosition); } float3 PointLightComponent::CalculateLightColor() const { return m_color * m_brightness; } void PointLightComponent::OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetEnabled(pEntity->m_enabled); } void PointLightComponent::OnRangePropertyChange(ThisClass *pEntity, const void *pUserData) { // update bounds float3 lightPosition(pEntity->CalculateLightPosition()); pEntity->SetBounds(PointLightRenderProxy::CalculatePointLightBoundingBox(lightPosition, pEntity->m_range), PointLightRenderProxy::CalculatePointLightBoundingSphere(lightPosition, pEntity->m_range), true); } void PointLightComponent::OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetColor(pEntity->CalculateLightColor()); } void PointLightComponent::OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetShadowFlags(pEntity->m_shadowFlags); } void PointLightComponent::OnFalloffExponentChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetFalloffExponent(pEntity->GetFalloffExponent()); } <file_sep>/DemoGame/Source/DemoGame/DemoUtilities.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/DemoUtilities.h" #include "Engine/World.h" #include "Engine/StaticMesh.h" #include "Engine/ResourceManager.h" #include "GameFramework/DirectionalLightEntity.h" #include "GameFramework/StaticMeshEntity.h" #include "ResourceCompiler/StaticMeshGenerator.h" Log_SetChannel(DemoUtilities); DirectionalLightEntity *DemoUtilities::CreateSunLight(World *pWorld, const float3 &color /*= float3(1.0f, 1.0f, 1.0f)*/, const float brightness /*= 1.0f*/, const float ambientContribution /*= 0.2f*/, const float3 &rotation /*= float3(45.0f, 0.0f, 0.0f)*/) { Quaternion rotationQuat(Quaternion::FromEulerAngles(rotation.x, rotation.y, rotation.z)); DirectionalLightEntity *pEntity = new DirectionalLightEntity(); pEntity->Create(pWorld->AllocateEntityID(), ENTITY_MOBILITY_MOVABLE, rotationQuat, true, color, brightness, LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS, ambientContribution); pWorld->AddEntity(pEntity); return pEntity; } Entity *DemoUtilities::CreatePlaneShape(World *pWorld, const float3 &normal, const float3 &origin, float size, const Material *pMaterial, float textureRepeatInterval /* = 1.0f */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { #if 0 // find rotation vector from ground Quaternion shapeRotation(Quaternion::FromTwoUnitVectors(float3::UnitZ, normal).Normalize()); // generate shape StaticMeshGenerator staticMeshGenerator; staticMeshGenerator.SetVertexTextureCoordinatesEnabled(true); // create lod + batch uint32 lodIndex = staticMeshGenerator.AddLOD(); uint32 batchIndex = staticMeshGenerator.AddBatch(lodIndex, pMaterial->GetName()); // work out last texture coord float startTextureCoord = 0.0f; float endTextureCoord = size / textureRepeatInterval; // generate vertices staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(-size, size, 1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(startTextureCoord, startTextureCoord)); // 0 top-back-left staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(size, size, 1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(endTextureCoord, startTextureCoord)); // 1 top-back-right staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(-size, -size, 1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(startTextureCoord, endTextureCoord)); // 2 top-front-left staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(size, -size, 1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(endTextureCoord, endTextureCoord)); // 3 top-front-right staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(-size, size, -1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(startTextureCoord, startTextureCoord)); // 4 bottom-back-left staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(size, size, -1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(endTextureCoord, startTextureCoord)); // 5 bottom-back-right staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(-size, -size, -1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(startTextureCoord, endTextureCoord)); // 6 bottom-front-left staticMeshGenerator.AddVertex(lodIndex, (shapeRotation * float3(size, -size, -1.0f)), float3::UnitX, float3::UnitY, float3::UnitZ, float2(endTextureCoord, endTextureCoord)); // 7 bottom-front-right // generate triangles staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 2, 3, 0); // top staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 0, 3, 1); // top staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 6, 4, 7); // bottom staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 7, 4, 5); // bottom staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 6, 7, 2); // front staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 2, 7, 3); // front staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 4, 0, 5); // back staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 5, 0, 4); // back staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 4, 0, 6); // left staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 6, 0, 2); // left staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 5, 7, 1); // right staticMeshGenerator.AddTriangle(lodIndex, batchIndex, 1, 7, 3); // right // build batches staticMeshGenerator.GenerateTangents(0); staticMeshGenerator.CalculateBounds(); staticMeshGenerator.BuildBoxCollisionShape(); // create staticmesh from this AutoReleasePtr<StaticMesh> pStaticMesh = new StaticMesh(); if (!pStaticMesh->Create("__planeshape__", &staticMeshGenerator)) { Log_ErrorPrintf("DemoUtilities::CreatePlaneShape: Staticmesh creation failed"); return nullptr; } float3 scale(float3::One); #else // fixme AutoReleasePtr<const StaticMesh> pStaticMesh = g_pResourceManager->GetStaticMesh("models/engine/unit_cube"); float3 scale(size, size, 0.01f); #endif // create entity StaticMeshEntity *pStaticMeshEntity = new StaticMeshEntity(); pStaticMeshEntity->Create(pWorld->AllocateEntityID(), ENTITY_MOBILITY_STATIC, origin, Quaternion::Identity, scale, pStaticMesh, true, true, shadowFlags); pWorld->AddEntity(pStaticMeshEntity); return pStaticMeshEntity; } <file_sep>/Editor/Source/Editor/EditorShaderGraphEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorShaderGraphEditor.h" #include "Engine/Entity.h" #include "Engine/Font.h" #include "Engine/ResourceManager.h" #include "Renderer/Renderer.h" #include "ResourceCompiler/ShaderGraph.h" Log_SetChannel(EditorShaderGraphEditor); static const uint32 s_iTextPaddingX = 4; static const uint32 s_iTextPaddingY = 4; static const uint32 s_iIOConnectorWidth = 8; EditorShaderGraphEditor::EditorShaderGraphEditor(EditorShaderGraphEditorCallbacks *pCallbacks, ShaderGraph *pShaderGraph) { m_pCallbacks = pCallbacks; m_pShaderGraph = pShaderGraph; m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; m_LastMousePosition.SetZero(); m_MouseSelectionRegion[0].SetZero(); m_MouseSelectionRegion[1].SetZero(); m_pCreateLinkTarget = NULL; m_iCreateLinkTargetInputIndex = 0xFFFFFFFF; m_pCreateLinkSource = NULL; m_iCreateLinkSourceOutputIndex = 0xFFFFFFFF; m_bRendererResourcesCreated = false; m_pRenderTarget = NULL; m_pRenderTargetView = NULL; m_pPickingTexture = NULL; m_pPickingTextureView = NULL; m_pFontData = g_pResourceManager->GetFont("resources/engine/medium_font"); m_iTextHeight = 12; m_ViewTranslation.SetZero(); // we manually flush when necessary m_mGUICtx.PushManualFlush(); } EditorShaderGraphEditor::~EditorShaderGraphEditor() { ReleaseRendererResources(); ClearNodeSelection(); ClearLinkSelection(); SAFE_RELEASE(m_pFontData); } bool EditorShaderGraphEditor::CreateNode(const ShaderGraphNodeTypeInfo *pTypeInfo, const int2 &Position) { if (pTypeInfo->GetFactory() == nullptr) return false; // using the factory, create the node Object *pNodeObject = pTypeInfo->GetFactory()->CreateObject(); if (pNodeObject == nullptr) return false; // cast to node ShaderGraphNode *pNode = pNodeObject->Cast<ShaderGraphNode>(); // calc node bounds uint32 nodeBoundsWidth, nodeBoundsHeight; CalculateNodeDimensions(pNode, &nodeBoundsWidth, &nodeBoundsHeight); // offset the position by half the bounds int2 offsetPosition = Position; offsetPosition.x -= nodeBoundsWidth / 2; offsetPosition.y -= nodeBoundsHeight / 2; // set node name, position SmallString nodeName; nodeName.Format("%s_%u", pTypeInfo->GetTypeName(), m_pShaderGraph->GetNextNodeId()); pNode->SetName(nodeName); pNode->SetGraphEditorPosition(offsetPosition); if (!m_pShaderGraph->AddNode(pNode)) { delete pNode; return false; } m_pCallbacks->OnNodeAdded(); FlagForRedraw(); return true; } bool EditorShaderGraphEditor::CreateLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, const ShaderGraphNode *pSourceNode, uint32 OutputIndex) { //uint32 i; if (InputIndex >= pTargetNode->GetInputCount() || OutputIndex >= pSourceNode->GetOutputCount()) return false; const ShaderGraphNodeInput *pInput = pTargetNode->GetInput(InputIndex); const ShaderGraphNodeOutput *pOutput = pSourceNode->GetOutput(OutputIndex); // check input if (pInput->IsLinked()) { Log_ErrorPrint("Could not create link: Input already linked."); return false; } // check the output type if (pOutput->GetValueType() == SHADER_PARAMETER_TYPE_COUNT) { Log_ErrorPrint("Could not create link: Output value type unknown."); return false; } // // find a compatible swizzle // SHADER_GRAPH_VALUE_SWIZZLE Swizzle = SHADER_GRAPH_VALUE_SWIZZLE_NONE; // if (pInput->GetValueType() != SHADER_GRAPH_VALUE_TYPE_UNKNOWN) // { // for (i = 0; i < SHADER_GRAPH_VALUE_SWIZZLE_COUNT; i++) // { // SHADER_GRAPH_VALUE_SWIZZLE curSwizzle = (SHADER_GRAPH_VALUE_SWIZZLE)i; // if (ShaderGraphNodeInput::GetTypeAfterSwizzle(pOutput->GetValueType(), curSwizzle)) // { // Swizzle = curSwizzle; // break; // } // } // // if (i == SHADER_GRAPH_VALUE_SWIZZLE_COUNT) // { // Log_ErrorPrint("Could not create link: Could not find compatible swizzle."); // return false; // } // } return CreateLink(pTargetNode, InputIndex, pSourceNode, OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE_NONE); } bool EditorShaderGraphEditor::CreateLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { if (InputIndex >= pTargetNode->GetInputCount() || OutputIndex >= pSourceNode->GetOutputCount()) return false; ShaderGraphNodeInput *pInput = pTargetNode->GetInput(InputIndex); const ShaderGraphNodeOutput *pOutput = pSourceNode->GetOutput(OutputIndex); // check input if (pInput->IsLinked()) { Log_ErrorPrint("Could not create link: Input already linked."); return false; } // check the output type if (pOutput->GetValueType() == SHADER_PARAMETER_TYPE_COUNT) { Log_ErrorPrint("Could not create link: Output value type unknown."); return false; } // check input type if (pInput->GetValueType() != SHADER_PARAMETER_TYPE_COUNT && ShaderGraphNodeInput::GetTypeAfterSwizzle(pOutput->GetValueType(), Swizzle) != pInput->GetValueType()) { Log_ErrorPrint("Could not create link: Swizzle type does not convert to valid input type."); return false; } // do link FlagForRedraw(); return pInput->SetLink(pSourceNode, OutputIndex, Swizzle); } // void EditorShaderGraphEditor::SetRenderTarget(GPUTexture2D *pRenderTarget) // { // m_pRenderTarget = pRenderTarget; // SAFE_RELEASE(m_pPickingTexture); // m_bRendererResourcesCreated = false; // } bool EditorShaderGraphEditor::CreateRendererResources() { if (m_bRendererResourcesCreated) return true; // not going anywhere without a RT if (m_pRenderTarget == NULL) return false; // get RT desc const GPU_TEXTURE2D_DESC *pRenderTargetDesc = m_pRenderTarget->GetDesc(); // picking texture if (m_pPickingTexture == NULL) { GPU_TEXTURE2D_DESC textureDesc; textureDesc.Width = pRenderTargetDesc->Width; textureDesc.Height = pRenderTargetDesc->Height; textureDesc.Format = PIXEL_FORMAT_R8G8B8A8_UNORM; textureDesc.Flags = GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_READABLE; textureDesc.MipLevels = 1; if ((m_pPickingTexture = g_pRenderer->CreateTexture2D(&textureDesc, NULL, NULL, NULL)) == NULL) return false; m_PickingTextureCopy.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, pRenderTargetDesc->Width, pRenderTargetDesc->Height, 1); } // update gui m_mGUICtx.SetViewportDimensions(pRenderTargetDesc->Width, pRenderTargetDesc->Height); m_bRendererResourcesCreated = true; m_bRedrawPending = true; return true; } void EditorShaderGraphEditor::ReleaseRendererResources() { m_pRenderTarget = NULL; SAFE_RELEASE(m_pPickingTexture); m_bRendererResourcesCreated = false; } bool EditorShaderGraphEditor::IsNodeSelected(const ShaderGraphNode *pNode) const { uint32 i; for (i = 0; i < m_SelectedGraphNodes.GetSize(); i++) { if (m_SelectedGraphNodes[i] == pNode) return true; } return false; } bool EditorShaderGraphEditor::IsLinkSelected(const ShaderGraphNodeInput *pNodeInput) const { uint32 i; for (i = 0; i < m_SelectedGraphLinks.GetSize(); i++) { if (m_SelectedGraphLinks[i] == pNodeInput) return true; } return false; } void EditorShaderGraphEditor::ClearNodeSelection() { m_SelectedGraphNodes.Clear(); } void EditorShaderGraphEditor::ClearLinkSelection() { m_SelectedGraphLinks.Clear(); } Vector2i EditorShaderGraphEditor::GetNodeInputPosition(const ShaderGraphNode *pNode, uint32 InputIndex) { uint32 connectorVerticalSpacing = (m_iTextHeight - (m_iTextHeight / 2)); // calc node bounds uint32 nodeBoundsWidth, nodeBoundsHeight; CalculateNodeDimensions(pNode, &nodeBoundsWidth, &nodeBoundsHeight); // calc node position Vector2i nodePosition = m_ViewTranslation + pNode->GetGraphEditorPosition(); nodePosition.x += (nodeBoundsWidth - (s_iIOConnectorWidth / 2)); nodePosition.y += (m_iTextHeight + s_iTextPaddingY + s_iTextPaddingY + (m_iTextHeight - connectorVerticalSpacing) + ((m_iTextHeight + s_iTextPaddingY) * InputIndex)); return nodePosition; } Vector2i EditorShaderGraphEditor::GetNodeOutputPosition(const ShaderGraphNode *pNode, uint32 OutputIndex) { uint32 connectorVerticalSpacing = (m_iTextHeight - (m_iTextHeight / 2)); Vector2i nodePosition = m_ViewTranslation + pNode->GetGraphEditorPosition(); nodePosition.x += (s_iIOConnectorWidth / 2) - 1; nodePosition.y += (m_iTextHeight + s_iTextPaddingY + s_iTextPaddingY + (m_iTextHeight - connectorVerticalSpacing) + ((m_iTextHeight + s_iTextPaddingY) * OutputIndex)); return nodePosition; } void EditorShaderGraphEditor::DrawNodeVisual(const ShaderGraphNode *pNode) { uint32 i; MINIGUI_RECT rect; bool nodeIsSelected = IsNodeSelected(pNode); // colors const uint32 borderColor = nodeIsSelected ? MAKE_COLOR_R8G8B8A8_UNORM(204, 0, 0, 255) : MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255); const uint32 headingBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255); const uint32 headingTextColor = MAKE_COLOR_R8G8B8A8_UNORM(230, 230, 26, 255); const uint32 detailBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(192, 192, 192, 255); const uint32 detailTextColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255); const uint32 outputConnectorFillColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 102, 0, 255); const uint32 inputConnectorFillColor = MAKE_COLOR_R8G8B8A8_UNORM(102, 0, 0, 255); // get bounds uint32 nodeBoundsWidth, nodeBoundsHeight; CalculateNodeDimensions(pNode, &nodeBoundsWidth, &nodeBoundsHeight); // // halve it // uint32 nodeBoundsHalfWidth, nodeBoundsHalfHeight; // nodeBoundsHalfWidth = (uint32)Y_ceilf((float)nodeBoundsWidth * 0.5f); // nodeBoundsHalfHeight = (uint32)Y_ceilf((float)nodeBoundsHeight * 0.5f); // // // create the rect // const Vector2i &graphEditorPosition = pNode->GetGraphEditorPosition(); // rect.left = graphEditorPosition.x - nodeBoundsHalfWidth; // rect.right = graphEditorPosition.x + nodeBoundsHalfWidth; // rect.top = graphEditorPosition.y - nodeBoundsHalfHeight; // rect.bottom = graphEditorPosition.y + nodeBoundsHalfHeight; // create the rect int2 graphEditorPosition = pNode->GetGraphEditorPosition() + m_ViewTranslation; rect.left = graphEditorPosition.x; rect.right = graphEditorPosition.x + nodeBoundsWidth; rect.top = graphEditorPosition.y; rect.bottom = graphEditorPosition.y + nodeBoundsHeight; // calculate connector sizes uint32 outputConnectorWidth = (pNode->GetOutputCount() > 0) ? s_iIOConnectorWidth : 0; uint32 inputConnectorWidth = (pNode->GetInputCount() > 0) ? s_iIOConnectorWidth : 0; uint32 connectorVerticalSpacing = (m_iTextHeight - (m_iTextHeight / 2)) / 2; // push it in the gui context m_mGUICtx.PushRect(&rect); // current Y position uint32 curY; // heading SET_MINIGUI_RECT(&rect, outputConnectorWidth, nodeBoundsWidth - inputConnectorWidth, 0, m_iTextHeight + s_iTextPaddingY); m_mGUICtx.DrawFilledRect(&rect, headingBackgroundColor); m_mGUICtx.DrawRect(&rect, borderColor); m_mGUICtx.DrawText(m_pFontData, m_iTextHeight, &rect, pNode->GetTypeInfo()->GetShortName(), headingTextColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_CENTER, MINIGUI_VERTICAL_ALIGNMENT_CENTER); // draw background for text curY = m_iTextHeight + s_iTextPaddingY; SET_MINIGUI_RECT(&rect, outputConnectorWidth, nodeBoundsWidth - inputConnectorWidth, curY, nodeBoundsHeight); m_mGUICtx.DrawFilledRect(&rect, detailBackgroundColor); m_mGUICtx.DrawRect(&rect, borderColor); // spacing between heading and detail curY += s_iTextPaddingY; rect.top = curY; // outputs SET_MINIGUI_RECT(&rect, outputConnectorWidth + s_iTextPaddingX, nodeBoundsWidth - inputConnectorWidth - s_iTextPaddingX, curY, nodeBoundsHeight); for (i = 0; i < pNode->GetOutputCount(); i++) { m_mGUICtx.DrawText(m_pFontData, m_iTextHeight, &rect, pNode->GetOutput(i)->GetOutputDesc()->Name, detailTextColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); rect.top += m_iTextHeight + s_iTextPaddingY; } // inputs SET_MINIGUI_RECT(&rect, outputConnectorWidth + s_iTextPaddingX, nodeBoundsWidth - inputConnectorWidth - s_iTextPaddingX, curY, nodeBoundsHeight); for (i = 0; i < pNode->GetInputCount(); i++) { m_mGUICtx.DrawText(m_pFontData, m_iTextHeight, &rect, pNode->GetInput(i)->GetInputDesc()->Name, detailTextColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT, MINIGUI_VERTICAL_ALIGNMENT_TOP); rect.top += m_iTextHeight + s_iTextPaddingY; } // output connectors SET_MINIGUI_RECT(&rect, 0, outputConnectorWidth - 1, curY + connectorVerticalSpacing, curY + (m_iTextHeight - connectorVerticalSpacing)); for (i = 0; i < pNode->GetOutputCount(); i++) { m_mGUICtx.DrawFilledRect(&rect, outputConnectorFillColor); rect.top += m_iTextHeight + s_iTextPaddingY; rect.bottom += m_iTextHeight + s_iTextPaddingY; } // input connectors SET_MINIGUI_RECT(&rect, nodeBoundsWidth - inputConnectorWidth - 1, nodeBoundsWidth, curY + connectorVerticalSpacing, curY + (m_iTextHeight - connectorVerticalSpacing)); for (i = 0; i < pNode->GetInputCount(); i++) { m_mGUICtx.DrawFilledRect(&rect, inputConnectorFillColor); rect.top += m_iTextHeight + s_iTextPaddingY; rect.bottom += m_iTextHeight + s_iTextPaddingY; } // pop rect m_mGUICtx.PopRect(); } void EditorShaderGraphEditor::DrawNodeID(const ShaderGraphNode *pNode) { uint32 i; MINIGUI_RECT rect; // for the id, we are just drawing the bounds of the node uint32 nodeBoundsWidth, nodeBoundsHeight; CalculateNodeDimensions(pNode, &nodeBoundsWidth, &nodeBoundsHeight); // // halve it // uint32 nodeBoundsHalfWidth, nodeBoundsHalfHeight; // nodeBoundsHalfWidth = (uint32)Y_ceilf((float)nodeBoundsWidth * 0.5f); // nodeBoundsHalfHeight = (uint32)Y_ceilf((float)nodeBoundsHeight * 0.5f); // // // create the rect // const Vector2i &graphEditorPosition = pNode->GetGraphEditorPosition(); // rect.left = graphEditorPosition.x - nodeBoundsHalfWidth; // rect.right = graphEditorPosition.x + nodeBoundsHalfWidth; // rect.top = graphEditorPosition.y - nodeBoundsHalfHeight; // rect.bottom = graphEditorPosition.y + nodeBoundsHalfHeight; // create the rect int2 graphEditorPosition = pNode->GetGraphEditorPosition() + m_ViewTranslation; SET_MINIGUI_RECT(&rect, graphEditorPosition.x, graphEditorPosition.x + nodeBoundsWidth, graphEditorPosition.y, graphEditorPosition.y + nodeBoundsHeight); // calculate connector sizes uint32 outputConnectorWidth = (pNode->GetOutputCount() > 0) ? s_iIOConnectorWidth : 0; uint32 inputConnectorWidth = (pNode->GetInputCount() > 0) ? s_iIOConnectorWidth : 0; uint32 connectorVerticalSpacing = (m_iTextHeight - (m_iTextHeight / 2)) / 2; // push it in the gui context m_mGUICtx.PushRect(&rect); // draw a filled rect over the detail part with the last byte set to zero uint32 encodedValue = ((pNode->GetID() & 0xFFFFFF) << 8); SET_MINIGUI_RECT(&rect, outputConnectorWidth, nodeBoundsWidth - inputConnectorWidth, 0, nodeBoundsHeight); m_mGUICtx.DrawFilledRect(&rect, encodedValue); // determine detail start uint32 curY = m_iTextHeight + s_iTextPaddingY + s_iTextPaddingY; uint32 n = 1; // draw input connectors SET_MINIGUI_RECT(&rect, nodeBoundsWidth - inputConnectorWidth - 1, nodeBoundsWidth, curY + connectorVerticalSpacing, curY + (m_iTextHeight - connectorVerticalSpacing)); for (i = 0; i < pNode->GetInputCount(); i++) { m_mGUICtx.DrawFilledRect(&rect, encodedValue | (n & 0x7F)); rect.top += m_iTextHeight + s_iTextPaddingY; rect.bottom += m_iTextHeight + s_iTextPaddingY; n++; } // draw output connectors SET_MINIGUI_RECT(&rect, 0, outputConnectorWidth - 1, curY + connectorVerticalSpacing, curY + (m_iTextHeight - connectorVerticalSpacing)); for (i = 0; i < pNode->GetOutputCount(); i++) { m_mGUICtx.DrawFilledRect(&rect, encodedValue | (n & 0x7F)); rect.top += m_iTextHeight + s_iTextPaddingY; rect.bottom += m_iTextHeight + s_iTextPaddingY; n++; } // pop rect m_mGUICtx.PopRect(); DebugAssert(n <= 0x7F); } void EditorShaderGraphEditor::DrawNodeVisualLink(const ShaderGraphNodeInput *pNodeInput) { const ShaderGraphNode *pInputNode = pNodeInput->GetNode(); uint32 inputIndex = pNodeInput->GetInputIndex(); const ShaderGraphNode *pOutputNode = pNodeInput->GetSourceNode(); uint32 outputIndex = pNodeInput->GetSourceOutputIndex(); if (pOutputNode == NULL) return; const uint32 lineColor = IsLinkSelected(pNodeInput) ? MAKE_COLOR_R8G8B8A8_UNORM(204, 0, 0, 255) : MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255); const Vector2i lineVertex1 = GetNodeOutputPosition(pOutputNode, outputIndex); const Vector2i lineVertex2 = GetNodeInputPosition(pInputNode, inputIndex); // draw line m_mGUICtx.DrawLine(lineVertex1, lineVertex2, lineColor); } void EditorShaderGraphEditor::DrawNodeIDLink(const ShaderGraphNodeInput *pNodeInput) { const ShaderGraphNode *pInputNode = pNodeInput->GetNode(); uint32 inputIndex = pNodeInput->GetInputIndex(); const ShaderGraphNode *pOutputNode = pNodeInput->GetSourceNode(); uint32 outputIndex = pNodeInput->GetSourceOutputIndex(); if (pOutputNode == NULL) return; // get position const Vector2i lineVertex1 = GetNodeOutputPosition(pOutputNode, outputIndex); const Vector2i lineVertex2 = GetNodeInputPosition(pInputNode, inputIndex); // draw line m_mGUICtx.DrawLine(lineVertex1, lineVertex2, ((pInputNode->GetID() & 0xFFFFFF) << 8) | (inputIndex | 0x80)); } void EditorShaderGraphEditor::CalculateNodeDimensions(const ShaderGraphNode *pNode, uint32 *pWidth, uint32 *pHeight) { uint32 i; uint32 curWidth = 0; uint32 curHeight = 0; uint32 inputsWidth = 0; uint32 inputsHeight = 0; uint32 inputsConnectorWidth = 0; uint32 outputsWidth = 0; uint32 outputsHeight = 0; uint32 outputsConnectorWidth = 0; uint32 textWidth; float Scale; // calc scale Scale = (float)m_iTextHeight / (float)m_pFontData->GetHeight(); // calc heading width textWidth = m_pFontData->GetTextWidth(pNode->GetTypeInfo()->GetShortName(), Y_strlen(pNode->GetTypeInfo()->GetShortName()), Scale); curWidth = textWidth + s_iTextPaddingX; curHeight = m_iTextHeight + s_iTextPaddingY; // spacing before input/output text curHeight += s_iTextPaddingY; // add outputs outputsWidth = s_iTextPaddingX; outputsConnectorWidth = (pNode->GetOutputCount() > 0) ? s_iIOConnectorWidth : 0; for (i = 0; i < pNode->GetOutputCount(); i++) { textWidth = m_pFontData->GetTextWidth(pNode->GetOutput(i)->GetOutputDesc()->Name, Y_strlen(pNode->GetOutput(i)->GetOutputDesc()->Name), Scale); outputsWidth = Max(outputsWidth, textWidth + s_iTextPaddingX); outputsHeight += m_iTextHeight + s_iTextPaddingY; } // add inputs inputsWidth = s_iTextPaddingX; inputsConnectorWidth = (pNode->GetInputCount() > 0) ? s_iIOConnectorWidth : 0; for (i = 0; i < pNode->GetInputCount(); i++) { textWidth = m_pFontData->GetTextWidth(pNode->GetInput(i)->GetInputDesc()->Name, Y_strlen(pNode->GetInput(i)->GetInputDesc()->Name), Scale); inputsWidth = Max(inputsWidth, textWidth + s_iTextPaddingX); inputsHeight += m_iTextHeight + s_iTextPaddingY; } // spacing after inputs/outputs curHeight += s_iTextPaddingY; // max them curWidth = Max(curWidth, outputsConnectorWidth + outputsWidth + inputsWidth + inputsConnectorWidth); curHeight += Max(inputsHeight, outputsHeight); // write to pointers *pWidth = curWidth; *pHeight = curHeight; } void EditorShaderGraphEditor::Draw(bool forceDrawVisual /* = false */, bool forceDrawPickingTexture /* = false */) { uint32 i, j; const ShaderGraphNode *pNode; const ShaderGraphNodeInput *pNodeInput; uint32 nodeCount; if (!(forceDrawVisual | forceDrawPickingTexture | m_bRedrawPending)) return; if (!m_bRendererResourcesCreated && !CreateRendererResources()) return; GPUContext *pGPUDevice = g_pRenderer->GetGPUContext(); if ((forceDrawVisual | m_bRedrawPending)) { // clear RT pGPUDevice->SetRenderTargets(1, &m_pRenderTargetView, nullptr); pGPUDevice->ClearTargets(true, false, false, float4(0.875f, 0.875f, 0.875f, 1.0f)); pGPUDevice->SetFullViewport(); // enable batching of gui draws m_mGUICtx.PushManualFlush(); // draw nodes nodeCount = m_pShaderGraph->GetNodeCount(); for (i = 0; i < nodeCount; i++) { pNode = m_pShaderGraph->GetNodeByArrayIndex(i); DrawNodeVisual(pNode); for (j = 0; j < pNode->GetInputCount(); j++) { pNodeInput = pNode->GetInput(j); if (pNodeInput->IsLinked()) DrawNodeVisualLink(pNodeInput); } } // draw the selection rect (if present) if (m_eGraphWindowState == EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING) { MINIGUI_RECT selectionRect; SET_MINIGUI_RECT(&selectionRect, Min(m_MouseSelectionRegion[0].x, m_MouseSelectionRegion[1].x), Max(m_MouseSelectionRegion[0].x, m_MouseSelectionRegion[1].x), Min(m_MouseSelectionRegion[0].y, m_MouseSelectionRegion[1].y), Max(m_MouseSelectionRegion[0].y, m_MouseSelectionRegion[1].y)); m_mGUICtx.DrawRect(&selectionRect, MAKE_COLOR_R8G8B8A8_UNORM(51, 153, 255, 255)); } // draw the creation-in-progress line else if (m_eGraphWindowState == EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK) { if (m_pCreateLinkSource != NULL) m_mGUICtx.DrawLine(GetNodeOutputPosition(m_pCreateLinkSource, m_iCreateLinkSourceOutputIndex), m_LastMousePosition, MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); else m_mGUICtx.DrawLine(m_LastMousePosition, GetNodeInputPosition(m_pCreateLinkTarget, m_iCreateLinkTargetInputIndex), MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255)); } // flush gui ctx m_mGUICtx.Flush(); m_mGUICtx.PopManualFlush(); } // update picking texture if requested if ((forceDrawPickingTexture | m_bRedrawPending)) { pGPUDevice->SetRenderTargets(1, &m_pPickingTextureView, nullptr); pGPUDevice->ClearTargets(true, false, false); pGPUDevice->SetFullViewport(); // enable batching of gui draws m_mGUICtx.PushManualFlush(); m_mGUICtx.SetAlphaBlendingEnabled(false); // draw nodes nodeCount = m_pShaderGraph->GetNodeCount(); for (i = 0; i < nodeCount; i++) { pNode = m_pShaderGraph->GetNodeByArrayIndex(i); DrawNodeID(pNode); } // draw node links for (i = 0; i < nodeCount; i++) { pNode = m_pShaderGraph->GetNodeByArrayIndex(i); for (j = 0; j < pNode->GetInputCount(); j++) { pNodeInput = pNode->GetInput(j); if (pNodeInput->IsLinked()) DrawNodeIDLink(pNodeInput); } } // clear RT m_mGUICtx.Flush(); m_mGUICtx.PopManualFlush(); m_mGUICtx.SetAlphaBlendingEnabled(true); // read back picking texture DebugAssert(m_PickingTextureCopy.IsValidImage()); if (!pGPUDevice->ReadTexture(m_pPickingTexture, m_PickingTextureCopy.GetData(), m_PickingTextureCopy.GetDataRowPitch(), m_PickingTextureCopy.GetDataSize(), 0, 0, 0, m_PickingTextureCopy.GetWidth(), m_PickingTextureCopy.GetHeight())) { Log_WarningPrintf("Failed to read back picking texture."); Y_memzero(m_PickingTextureCopy.GetData(), m_PickingTextureCopy.GetDataSize()); } } // no longer pending m_bRedrawPending = false; } bool EditorShaderGraphEditor::GetPickingTextureValues(const int2 &MinCoordinates, const int2 &MaxCoordinates, uint32 *pValues) { DebugAssert((uint32)MinCoordinates.x < m_PickingTextureCopy.GetWidth() && (uint32)MinCoordinates.y < m_PickingTextureCopy.GetHeight()); DebugAssert((uint32)MaxCoordinates.x < m_PickingTextureCopy.GetWidth() && (uint32)MaxCoordinates.y < m_PickingTextureCopy.GetHeight()); // get number of values to read int2 coordinateRange = MaxCoordinates - MinCoordinates + 1; int32 nValues = (coordinateRange.x) * (coordinateRange.y); DebugAssert(nValues > 0); // read the pixels from the image copy if (!m_PickingTextureCopy.ReadPixels(pValues, sizeof(uint32) * nValues, MinCoordinates.x, MinCoordinates.y, coordinateRange.x, coordinateRange.y)) { // not sure why this would fail return false; } return true; } uint32 EditorShaderGraphEditor::GetPickingTextureValue(const int2 &Position) { uint32 texelValue; if (!GetPickingTextureValues(Position, Position, &texelValue)) texelValue = 0; return texelValue; } void EditorShaderGraphEditor::ProcessGraphWindowMouseEvent(const QMouseEvent *pEvent) { uint32 i, n; if (pEvent->type() == QEvent::MouseButtonPress || pEvent->type() == QEvent::MouseButtonRelease) { switch (pEvent->button()) { case Qt::LeftButton: { if (pEvent->type() == QEvent::MouseButtonPress) { switch (m_eGraphWindowState) { case EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE: { uint32 pickingTextureValue = GetPickingTextureValue(m_LastMousePosition); if (pickingTextureValue != 0) { // retrieve the node under the cursor ShaderGraphNode *pCursorNode = m_pShaderGraph->GetNodeByID(pickingTextureValue >> 8); if (pCursorNode == NULL) return; if (pickingTextureValue & 0x80) { // enter selection mode m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING; m_MouseSelectionRegion[0] = m_MouseSelectionRegion[1] = m_LastMousePosition; UpdateSelections(); } else if (pickingTextureValue & 0x7F) { // selecting an input/output ClearNodeSelection(); ClearLinkSelection(); uint32 searchIndex = (pickingTextureValue & 0x7F) - 1; for (i = 0, n = 0; i < pCursorNode->GetInputCount(); i++, n++) { if (n == searchIndex) { // mouse is over an input DebugAssert(m_pCreateLinkSource == NULL && m_pCreateLinkTarget == NULL); // change state m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK; m_pCreateLinkTarget = pCursorNode; m_iCreateLinkTargetInputIndex = i; break; } } if (i == pCursorNode->GetInputCount()) { for (i = 0; i < pCursorNode->GetOutputCount(); i++, n++) { if (n == searchIndex) { // mouse is over an output DebugAssert(m_pCreateLinkSource == NULL && m_pCreateLinkTarget == NULL); // change state m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK; m_pCreateLinkSource = pCursorNode; m_iCreateLinkSourceOutputIndex = i; break; } } } } else { // if it is part of the current selection, move the current selection, otherwise clear it and move the cursor node if (!IsNodeSelected(pCursorNode)) { // enter selection mode m_MouseSelectionRegion[0] = m_MouseSelectionRegion[1] = m_LastMousePosition; UpdateSelections(); } m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_MOVING_NODE; } FlagForRedraw(); } else { // enter selection mode m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING; m_MouseSelectionRegion[0] = m_MouseSelectionRegion[1] = m_LastMousePosition; UpdateSelections(); } } break; } } else if (pEvent->type() == QEvent::MouseButtonRelease) { switch (m_eGraphWindowState) { case EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING: { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; m_MouseSelectionRegion[0].SetZero(); m_MouseSelectionRegion[1].SetZero(); FlagForRedraw(); } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_SCROLLING: { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_MOVING_NODE: { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK: { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; uint32 pickingTextureValue = GetPickingTextureValue(m_LastMousePosition); if (pickingTextureValue != 0) { // retrieve the node under the cursor ShaderGraphNode *pCursorNode = m_pShaderGraph->GetNodeByID(pickingTextureValue >> 8); if (pCursorNode != NULL) { uint32 ioIndex = 0xFFFFFFFF; bool isInput = false; uint32 searchIndex = (pickingTextureValue & 0x7F) - 1; for (i = 0, n = 0; i < pCursorNode->GetInputCount(); i++, n++) { if (n == searchIndex) { ioIndex = i; isInput = true; break; } } if (i == pCursorNode->GetInputCount()) { for (i = 0; i < pCursorNode->GetOutputCount(); i++, n++) { if (n == searchIndex) { ioIndex = i; isInput = false; break; } } } // already have a target? if (m_pCreateLinkTarget != NULL) { // node must be source DebugAssert(m_pCreateLinkSource == NULL); if (!isInput) { DebugAssert(ioIndex < pCursorNode->GetOutputCount()); m_pCreateLinkSource = pCursorNode; m_iCreateLinkSourceOutputIndex = ioIndex; } } else { // node must be target if (isInput) { DebugAssert(ioIndex < pCursorNode->GetInputCount()); m_pCreateLinkTarget = pCursorNode; m_iCreateLinkTargetInputIndex = ioIndex; } } } } if (m_pCreateLinkSource != NULL && m_pCreateLinkTarget != NULL) { CreateLink(m_pCreateLinkTarget, m_iCreateLinkTargetInputIndex, m_pCreateLinkSource, m_iCreateLinkSourceOutputIndex); } m_pCreateLinkSource = m_pCreateLinkTarget = NULL; m_iCreateLinkSourceOutputIndex = m_iCreateLinkTargetInputIndex = 0xFFFFFFFF; FlagForRedraw(); } break; } } } break; case Qt::MiddleButton: { if (pEvent->type() == QEvent::MouseButtonRelease) { uint32 pickingTextureValue = GetPickingTextureValue(m_LastMousePosition); Log_DevPrintf("Picking texture value: %08X %02X %02X %02X %02X", pickingTextureValue, pickingTextureValue >> 24, (pickingTextureValue >> 16) & 0xFF, (pickingTextureValue >> 8) & 0xFF, pickingTextureValue & 0xFF); } } break; case Qt::RightButton: { if (pEvent->type() == QEvent::MouseButtonPress) { if (m_eGraphWindowState == EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE) { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_SCROLLING; } } else if (pEvent->type() == QEvent::MouseButtonRelease) { if (m_eGraphWindowState == EDITOR_SHADER_GRAPH_EDITOR_STATE_SCROLLING) { m_eGraphWindowState = EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE; } } } break; } } else if (pEvent->type() == QEvent::MouseMove) { Vector2i currentPosition(pEvent->x(), pEvent->y()); // handle mouse movement based on graph state switch (m_eGraphWindowState) { case EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE: break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING: { m_MouseSelectionRegion[1] = m_LastMousePosition; UpdateSelections(); FlagForRedraw(); } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_SCROLLING: { // calculate delta Vector2i deltaPosition(currentPosition - m_LastMousePosition); // translate graph window m_ViewTranslation += deltaPosition; FlagForRedraw(); } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_MOVING_NODE: { // calculate delta Vector2i deltaPosition(currentPosition - m_LastMousePosition); // translate nodes for (i = 0; i < m_SelectedGraphNodes.GetSize(); i++) m_SelectedGraphNodes[i]->SetGraphEditorPosition(m_SelectedGraphNodes[i]->GetGraphEditorPosition() + deltaPosition); // redraw window FlagForRedraw(); } break; case EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK: { // queue redraw FlagForRedraw(); } break; } // update position m_LastMousePosition = currentPosition; } } void EditorShaderGraphEditor::UpdateSelections() { uint32 i; // determine min/max coordinates int2 minCoordinates = m_MouseSelectionRegion[0].Min(m_MouseSelectionRegion[1]); int2 maxCoordinates = m_MouseSelectionRegion[0].Max(m_MouseSelectionRegion[1]); //Log_DevPrintf("New selection: [%d-%d] [%d-%d]", m_MouseSelectionRegion[0].x, m_MouseSelectionRegion[1].x, m_MouseSelectionRegion[0].y, m_MouseSelectionRegion[1].y); // allocate memory for receiving entity ids uint32 nTexelValues = (maxCoordinates.x - minCoordinates.x + 1) * (maxCoordinates.y - minCoordinates.y + 1); uint32 *pTexelValues = new uint32[nTexelValues]; uint32 *pCurrentTexelValue = pTexelValues; // read texel values GetPickingTextureValues(minCoordinates, maxCoordinates, pTexelValues); // clear selections ClearNodeSelection(); ClearLinkSelection(); // iterate each pixel that is selected, determining which render target was hit on the screen int2 currentPosition = minCoordinates; for (; currentPosition.y <= maxCoordinates.y; currentPosition.y++) { for (currentPosition.x = minCoordinates.x; currentPosition.x <= maxCoordinates.x; currentPosition.x++) { uint32 texelValue = *pCurrentTexelValue++; if (texelValue == 0) continue; ShaderGraphNode *pNode = m_pShaderGraph->GetNodeByID(texelValue >> 8); if (pNode == NULL) continue; if (texelValue & 0x80) { uint32 inputLinkIndex = (texelValue & 0x7F); ShaderGraphNodeInput *pNodeInput = pNode->GetInput(inputLinkIndex); DebugAssert(pNodeInput->IsLinked()); for (i = 0; i < m_SelectedGraphLinks.GetSize(); i++) { if (m_SelectedGraphLinks[i] == pNodeInput) break; } if (i == m_SelectedGraphLinks.GetSize()) { Log_DevPrintf("add link node %u %u (%s)", pNode->GetID(), inputLinkIndex, pNode->GetName().GetCharArray()); m_SelectedGraphLinks.Add(pNodeInput); } } else { for (i = 0; i < m_SelectedGraphNodes.GetSize(); i++) { if (m_SelectedGraphNodes[i] == pNode) break; } if (i == m_SelectedGraphNodes.GetSize()) { Log_DevPrintf("add selection node %u (%s)", pNode->GetID(), pNode->GetName().GetCharArray()); m_SelectedGraphNodes.Add(pNode); } } } } // leak, doh delete[] pTexelValues; // update selections m_pCallbacks->OnNodeSelectionChange(); FlagForRedraw(); } <file_sep>/Engine/Source/Engine/ResourceManager.h #pragma once #include "Engine/Common.h" class Resource; class Texture; class Texture2D; class Texture2DArray; class TextureCube; class MaterialShader; class Material; class StaticMesh; class Font; class BlockPalette; class TerrainLayerList; class BlockMesh; class Skeleton; class SkeletalMesh; class SkeletalAnimation; class ShaderGraphSchema; class ShaderGraph; class ParticleSystem; class ResourceCompilerInterface; class ResourceManager { public: ResourceManager(); ~ResourceManager(); static const ResourceTypeInfo *GetResourceTypeForFile(const char *FileName); static const ResourceTypeInfo *GetResourceTypeForStream(const char *FileName, ByteStream *pStream); static const ResourceTypeInfo *GetResourceTypeForFile(const char *FileName, String &resourceName); static const ResourceTypeInfo *GetResourceTypeForStream(const char *FileName, ByteStream *pStream, String &resourceName); const Resource *GetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *name); const Texture *GetTexture(const char *name); const Texture2D *GetTexture2D(const char *name); const Texture2DArray *GetTexture2DArray(const char *name); const TextureCube *GetTextureCube(const char *name); const MaterialShader *GetMaterialShader(const char *name); const Material *GetMaterial(const char *name); const Font *GetFont(const char *name); const BlockPalette *GetBlockPalette(const char *name); const TerrainLayerList *GetTerrainLayerList(const char *name); const StaticMesh *GetStaticMesh(const char *name); const BlockMesh *GetBlockMesh(const char *name); const Skeleton *GetSkeleton(const char *name); const SkeletalMesh *GetSkeletalMesh(const char *name); const SkeletalAnimation *GetSkeletalAnimation(const char *name); const ParticleSystem *GetParticleSystem(const char *name); // safe resource getters, that return the default value if the resource is not found const Resource *SafeGetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *name); const Texture2D *SafeGetTexture2D(const char *name); const Texture2DArray *SafeGetTexture2DArray(const char *name); const TextureCube *SafeGetTextureCube(const char *name); const MaterialShader *SafeGetMaterialShader(const char *name); const Material *SafeGetMaterial(const char *name); const StaticMesh *SafeGetStaticMesh(const char *name); const BlockMesh *SafeGetBlockMesh(const char *name); const SkeletalMesh *SafeGetSkeletalMesh(const char *name); // don't cache the resource when returning it, if it wasn't already loaded const Resource *UncachedGetResource(const ResourceTypeInfo *pResourceTypeInfo, const char *name); const Texture *UncachedGetTexture(const char *name); const Material *UncachedGetMaterial(const char *name); const MaterialShader *UncachedGetMaterialShader(const char *name); const Font *UncachedGetFont(const char *name); const BlockPalette *UncachedGetBlockPalette(const char *name); const TerrainLayerList *UncachedGetTerrainLayerList(const char *name); const StaticMesh *UncachedGetStaticMesh(const char *name); const BlockMesh *UncachedGetBlockMesh(const char *name); const Skeleton *UncachedGetSkeleton(const char *name); const SkeletalMesh *UncachedGetSkeletalMesh(const char *name); const SkeletalAnimation *UncachedGetSkeletalAnimation(const char *name); const ParticleSystem *UncachedGetParticleSystem(const char *name); void CreateDeviceResources(); void ReleaseDeviceResources(); void CompactResources(); void ReleaseResources(); const Texture *GetDefaultTexture(TEXTURE_TYPE TextureType); const Texture2D *GetDefaultTexture2D(); const Texture2DArray *GetDefaultTexture2DArray(); const TextureCube *GetDefaultTextureCube(); const MaterialShader *GetDefaultMaterialShader(); const Material *GetDefaultMaterial(); const StaticMesh *GetDefaultStaticMesh(); const BlockMesh *GetDefaultBlockMesh(); const SkeletalMesh *GetDefaultSkeletalMesh(); // resource modification detection bool IsResourceModificationDetectionEnabled() const { return (m_pResourceModificationChangeNotifier != nullptr); } void SetResourceModificationDetectionEnabled(bool enabled); void CheckForModifiedResources(); // resource compiler interface ResourceCompilerInterface *GetResourceCompilerInterface(); void ReleaseResourceCompilerInterface(ResourceCompilerInterface *pInterface); // resource maintenance, call every frame, or something close to that void Update(); private: // resource loaders Texture *LoadTexture(const char *name); Material *LoadMaterial(const char *name); MaterialShader *LoadMaterialShader(const char *name); Font *LoadFont(const char *name); BlockPalette *LoadBlockPalette(const char *name); TerrainLayerList *LoadTerrainLayerList(const char *name); StaticMesh *LoadStaticMesh(const char *name); BlockMesh *LoadBlockMesh(const char *name); Skeleton *LoadSkeleton(const char *name); SkeletalMesh *LoadSkeletalMesh(const char *name); SkeletalAnimation *LoadSkeletalAnimation(const char *name); ParticleSystem *LoadParticleSystem(const char *name); // resource lock ReadWriteLock m_resourceLock; // resource storage typedef CIStringHashTable<Texture *> TextureTable; TextureTable m_htTextures; typedef CIStringHashTable<MaterialShader *> MaterialShaderTable; MaterialShaderTable m_htMaterialShaders; typedef CIStringHashTable<Material *> MaterialTable; MaterialTable m_htMaterials; typedef CIStringHashTable<StaticMesh *> StaticMeshTable; StaticMeshTable m_htStaticMeshes; typedef CIStringHashTable<Font *> FontTable; FontTable m_htFonts; typedef CIStringHashTable<BlockPalette *> BlockPaletteTable; BlockPaletteTable m_htBlockPalette; typedef CIStringHashTable<TerrainLayerList *> TerrainLayerListTable; TerrainLayerListTable m_htTerrainLayerList; typedef CIStringHashTable<BlockMesh *> BlockMeshTable; BlockMeshTable m_htBlockMesh; typedef CIStringHashTable<Skeleton *> SkeletonTable; SkeletonTable m_htSkeleton; typedef CIStringHashTable<SkeletalMesh *> SkeletalMeshTable; SkeletalMeshTable m_htSkeletalMesh; typedef CIStringHashTable<SkeletalAnimation *> SkeletalAnimationTable; SkeletalAnimationTable m_htSkeletalAnimation; typedef CIStringHashTable<ParticleSystem *> ParticleSystemTable; ParticleSystemTable m_htParticleSystem; // default resources const Texture2D *m_pDefaultTexture2D; const Texture2DArray *m_pDefaultTexture2DArray; const TextureCube *m_pDefaultTextureCube; const MaterialShader *m_pDefaultMaterialShader; const Material *m_pDefaultMaterial; const StaticMesh *m_pDefaultStaticMesh; const BlockMesh *m_pDefaultBlockMesh; const SkeletalMesh *m_pDefaultSkeletalMesh; // maintenance timer Timer m_lastMaintenanceTime; // resource modification detection FileSystem::ChangeNotifier *m_pResourceModificationChangeNotifier; // resource compiler interface ResourceCompilerInterface *m_pResourceCompilerInterface; Timer m_resourceCompilerSpawnTime; RecursiveMutex m_resourceCompilerLock; bool m_resourceCompilerInUse; }; extern ResourceManager *g_pResourceManager; <file_sep>/Engine/Source/Renderer/Shaders/TextureBlitShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/TextureBlitShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(TextureBlitShader); BEGIN_SHADER_COMPONENT_PARAMETERS(TextureBlitShader) DEFINE_SHADER_COMPONENT_PARAMETER("SourceTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("SourceLevel", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_COMPONENT_PARAMETERS() void TextureBlitShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture *pSourceTexture, GPUSamplerState *pSamplerState, uint32 sourceLevel) { float fSourceLevel = (float)sourceLevel; pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pSourceTexture, pSamplerState); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT, &fSourceLevel); } bool TextureBlitShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool TextureBlitShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/TextureBlitShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/TextureBlitShader.hlsl", "PSMain"); if (baseShaderFlags & USE_TEXTURE_LOD) pParameters->AddPreprocessorMacro(StaticString("USE_TEXTURE_LOD"), StaticString("1")); return true; } <file_sep>/Editor/Source/Editor/EditorShaderGraphEditor.h #pragma once #include "Editor/Common.h" #include "Renderer/MiniGUIContext.h" #include "ResourceCompiler/ShaderGraph.h" #include "Core/Image.h" class Font; struct EditorShaderGraphEditorCallbacks; enum EDITOR_SHADER_GRAPH_EDITOR_STATE { EDITOR_SHADER_GRAPH_EDITOR_STATE_NONE, EDITOR_SHADER_GRAPH_EDITOR_STATE_SELECTING, EDITOR_SHADER_GRAPH_EDITOR_STATE_SCROLLING, EDITOR_SHADER_GRAPH_EDITOR_STATE_MOVING_NODE, EDITOR_SHADER_GRAPH_EDITOR_STATE_CREATING_LINK, EDITOR_SHADER_GRAPH_EDITOR_STATE_COUNT, }; class EditorShaderGraphEditor { public: EditorShaderGraphEditor(EditorShaderGraphEditorCallbacks *pCallbacks, ShaderGraph *pShaderGraph); ~EditorShaderGraphEditor(); // accessors const ShaderGraph *GetShaderGraph() const { return m_pShaderGraph; } const int2 &GetViewTranslation() const { return m_ViewTranslation; } bool CreateNode(const ShaderGraphNodeTypeInfo *pTypeInfo, const int2 &Position); bool CreateLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, const ShaderGraphNode *pSourceNode, uint32 OutputIndex); bool CreateLink(ShaderGraphNode *pTargetNode, uint32 InputIndex, const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle); // renderer resources const bool PendingRedraw() const { return m_bRedrawPending; } void FlagForRedraw() { m_bRedrawPending = true; } //void SetRenderTarget(GPUTexture2D *pRenderTarget); bool CreateRendererResources(); void ReleaseRendererResources(); // selections const ShaderGraphNode *GetNodeSelection(uint32 i) const { return m_SelectedGraphNodes[i]; } const ShaderGraphNodeInput *GetLinkSelection(uint32 i) const { return m_SelectedGraphLinks[i]; } ShaderGraphNode *GetNodeSelection(uint32 i) { return m_SelectedGraphNodes[i]; } ShaderGraphNodeInput *GetLinkSelection(uint32 i) { return m_SelectedGraphLinks[i]; } uint32 GetNodeSelectionCount() const { return m_SelectedGraphNodes.GetSize(); } uint32 GetLinkSelectionCount() const { return m_SelectedGraphLinks.GetSize(); } bool IsNodeSelected(const ShaderGraphNode *pNode) const; bool IsLinkSelected(const ShaderGraphNodeInput *pNodeInput) const; void ClearNodeSelection(); void ClearLinkSelection(); // drawing methods void Draw(bool forceDrawVisual = false, bool forceDrawPickingTexture = false); // input handlers void ProcessGraphWindowMouseEvent(const QMouseEvent *pEvent); private: EditorShaderGraphEditorCallbacks *m_pCallbacks; ShaderGraph *m_pShaderGraph; // graph window state EDITOR_SHADER_GRAPH_EDITOR_STATE m_eGraphWindowState; int2 m_LastMousePosition; int2 m_MouseSelectionRegion[2]; // selection PODArray<ShaderGraphNode *> m_SelectedGraphNodes; PODArray<ShaderGraphNodeInput *> m_SelectedGraphLinks; ShaderGraphNode *m_pCreateLinkTarget; uint32 m_iCreateLinkTargetInputIndex; ShaderGraphNode *m_pCreateLinkSource; uint32 m_iCreateLinkSourceOutputIndex; // hardware resources bool m_bRendererResourcesCreated; GPUTexture2D *m_pRenderTarget; GPURenderTargetView *m_pRenderTargetView; GPUTexture2D *m_pPickingTexture; GPURenderTargetView *m_pPickingTextureView; Image m_PickingTextureCopy; bool m_bRedrawPending; // renderer resources not in hardware const Font *m_pFontData; MiniGUIContext m_mGUICtx; uint32 m_iTextHeight; int2 m_ViewTranslation; // drawing subcalls Vector2i GetNodeInputPosition(const ShaderGraphNode *pNode, uint32 InputIndex); Vector2i GetNodeOutputPosition(const ShaderGraphNode *pNode, uint32 OutputIndex); void DrawNodeVisual(const ShaderGraphNode *pNode); void DrawNodeVisualLink(const ShaderGraphNodeInput *pNodeInput); void DrawNodeID(const ShaderGraphNode *pNode); void DrawNodeIDLink(const ShaderGraphNodeInput *pNodeInput); void CalculateNodeDimensions(const ShaderGraphNode *pNode, uint32 *pWidth, uint32 *pHeight); // updates the picking texture bool GetPickingTextureValues(const int2 &MinCoordinates, const int2 &MaxCoordinates, uint32 *pValues); uint32 GetPickingTextureValue(const int2 &Position); void UpdateSelections(); }; struct EditorShaderGraphEditorCallbacks { virtual void OnNodeAdded() { } virtual void OnNodeRemoved() { } virtual void OnNodeSelectionChange() { } }; <file_sep>/Engine/Source/BaseGame/Common.h #pragma once #include "Engine/Common.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" #include "Engine/Material.h" <file_sep>/Engine/Source/OpenGLRenderer/OpenGLCommon.h #pragma once #include "Renderer/Common.h" #include "Renderer/Renderer.h" // include sdl before GLEW #include "Engine/SDLHeaders.h" #include "glad/glad.h" // Forward declare all our types class OpenGLGPUBuffer; class OpenGLGPUConstants; class OpenGLGPUContext; class OpenGLGPUQuery; class OpenGLGPUShaderProgram; class OpenGLGPUTexture1D; class OpenGLGPUTexture1DArray; class OpenGLGPUTexture2D; class OpenGLGPUTexture2DArray; class OpenGLGPUTexture3D; class OpenGLGPUTextureCube; class OpenGLGPUTextureCubeArray; class OpenGLGPUDepthTexture; class OpenGLGPUDevice; class OpenGLShaderCompiler; class OpenGLGPUSamplerState; class OpenGLGPURasterizerState; class OpenGLGPUDepthStencilState; class OpenGLGPUBlendState; #include "OpenGLRenderer/OpenGLDefines.h" #include "OpenGLRenderer/OpenGLCVars.h" <file_sep>/Engine/Source/Renderer/VertexFactories/SkeletalMeshVertexFactory.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactories/SkeletalMeshVertexFactory.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/ShaderProgram.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(SkeletalMeshVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(SkeletalMeshVertexFactory) DEFINE_SHADER_COMPONENT_PARAMETER("BoneMatrices", SHADER_PARAMETER_TYPE_FLOAT3X4) DEFINE_SHADER_COMPONENT_PARAMETER("BoneMatrices4x4", SHADER_PARAMETER_TYPE_FLOAT4X4) END_SHADER_COMPONENT_PARAMETERS() void SkeletalMeshVertexFactory::SetBoneMatrices(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, uint32 firstBoneIndex, uint32 boneCount, const float3x4 *pBoneMatrices) { pShaderProgram->SetVertexFactoryParameterValueArray(pCommandList, 0, SHADER_PARAMETER_TYPE_FLOAT3X4, pBoneMatrices, firstBoneIndex, boneCount); if (g_pRenderer->GetFeatureLevel() == RENDERER_FEATURE_LEVEL_ES2) { // Fixme, please, this is disgusting. for (uint32 i = 0; i < boneCount; i++) { float4x4 bm44(pBoneMatrices[i]); pShaderProgram->SetVertexFactoryParameterValueArray(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT4X4, &bm44, firstBoneIndex + i, 1); } } } uint32 SkeletalMeshVertexFactory::GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { // calculate vertices buffer size // base vertex size - position + tangents uint32 vertexSize = sizeof(float3) + sizeof(float3) + sizeof(float3) + sizeof(float3); // add texcoords if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS) vertexSize += sizeof(float2); // add colors if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) vertexSize += sizeof(uint32); // add gpu skinning if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING) vertexSize += sizeof(uint8) * 4 + sizeof(float) * 4; // set it return vertexSize; } bool SkeletalMeshVertexFactory::CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); uint32 bufferSize = vertexSize * nVertices; byte *pBuffer = new byte[bufferSize]; FillVerticesBuffer(platform, featureLevel, flags, pVertices, nVertices, pBuffer, bufferSize); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, bufferSize); GPUBuffer *pVertexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pBuffer); delete[] pBuffer; if (pVertexBuffer == NULL) return false; pVertexBufferBindingArray->SetBuffer(0, pVertexBuffer, 0, vertexSize); pVertexBuffer->Release(); return true; } bool SkeletalMeshVertexFactory::FillVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); if (cbBuffer < (vertexSize * nVertices)) return false; uint32 i; byte *pOutVertexPtr = reinterpret_cast<byte *>(pBuffer); for (i = 0; i < nVertices; i++) { const Vertex *pVertex = &pVertices[i]; // position Y_memcpy(pOutVertexPtr, &pVertex->Position, sizeof(float3)); pOutVertexPtr += sizeof(float3); // tangentx Y_memcpy(pOutVertexPtr, &pVertex->TangentX, sizeof(float3)); pOutVertexPtr += sizeof(float3); // tangenty Y_memcpy(pOutVertexPtr, &pVertex->TangentY, sizeof(float3)); pOutVertexPtr += sizeof(float3); // tangentz Y_memcpy(pOutVertexPtr, &pVertex->TangentZ, sizeof(float3)); pOutVertexPtr += sizeof(float3); // texcoord if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS) { Y_memcpy(pOutVertexPtr, &pVertex->TexCoord, sizeof(float2)); pOutVertexPtr += sizeof(float2); } // color if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { Y_memcpy(pOutVertexPtr, &pVertex->Color, sizeof(uint32)); pOutVertexPtr += sizeof(uint32); } if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING) { Y_memcpy(pOutVertexPtr, pVertex->BoneIndices, sizeof(uint8) * 4); pOutVertexPtr += sizeof(uint8) * 4; Y_memcpy(pOutVertexPtr, pVertex->BoneWeights, sizeof(float) * 4); pOutVertexPtr += sizeof(float) * 4; } } return true; } bool SkeletalMeshVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool SkeletalMeshVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/SkeletalMeshVertexFactory.hlsl"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_0_ENABLED) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_0_ENABLED", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_1_ENABLED) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_1_ENABLED", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_2_ENABLED) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_2_ENABLED", "1"); if (vertexFactoryFlags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_3_ENABLED) pParameters->AddPreprocessorMacro("SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_3_ENABLED", "1"); return true; } uint32 SkeletalMeshVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { // create format declaration GPU_VERTEX_ELEMENT_DESC *pElementDesc = pElementsDesc; uint32 streamOffset; uint32 nElements = 0; uint32 nStreams = 0; // build stream 0 { streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // tangentx pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // tangenty pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // tangentz pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // texcoord if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; } // color if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } // color if (flags & SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BLENDINDICES; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UBYTE4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint8) * 4; pElementDesc++; nElements++; pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BLENDWEIGHTS; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float) * 4; pElementDesc++; nElements++; } // end of stream nStreams++; } // done return nElements; } <file_sep>/Engine/Source/Renderer/ShaderCompilerFrontend.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" class ResourceCompilerInterface; class ShaderComponentTypeInfo; class VertexFactoryTypeInfo; class MaterialShader; enum SHADER_COMPILER_FLAGS { SHADER_COMPILER_FLAG_ENABLE_DEBUG_INFO = (1 << 0), SHADER_COMPILER_FLAG_DISABLE_OPTIMIZATIONS = (1 << 1), }; struct ShaderCompilerParameters { RENDERER_PLATFORM Platform; RENDERER_FEATURE_LEVEL FeatureLevel; uint32 CompilerFlags; String StageFileNames[SHADER_PROGRAM_STAGE_COUNT]; String StageEntryPoints[SHADER_PROGRAM_STAGE_COUNT]; String VertexFactoryFileName; String MaterialShaderName; uint32 MaterialShaderFlags; bool EnableVerboseInfoLog; typedef KeyValuePair<String, String> PreprocessorMacro; Array<PreprocessorMacro> PreprocessorMacros; /*typedef KeyValuePair<String, SHADER_PARAMETER_TYPE> ParameterBinding; Array<ParameterBinding> BaseShaderParameters; Array<ParameterBinding> VertexFactoryParameters; Array<ParameterBinding> MaterialShaderUniformParameters; Array<ParameterBinding> MaterialShaderTextureParameters;*/ void SetStageEntryPoint(SHADER_PROGRAM_STAGE stage, const char *filename, const char *entryPoint) { StageFileNames[stage] = filename; StageEntryPoints[stage] = entryPoint; } void SetStageEntryPoint(SHADER_PROGRAM_STAGE stage, const String &filename, const String &entryPoint) { StageFileNames[stage] = filename; StageEntryPoints[stage] = entryPoint; } void SetVertexFactoryFileName(const char *filename) { VertexFactoryFileName = filename; } void SetVertexFactoryFileName(const String &filename) { VertexFactoryFileName = filename; } void AddPreprocessorMacro(const char *define, const char *value) { PreprocessorMacros.Add(PreprocessorMacro(define, value)); } void AddPreprocessorMacro(const String &define, const String &value) { PreprocessorMacros.Add(PreprocessorMacro(define, value)); } }; class ShaderCompilerFrontend { public: // hash code generator static void GenerateShaderHashCode(uint8 HashCode[16], uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); // shader compiler static bool CompileShader(ResourceCompilerInterface *pCompilerInterface, uint32 globalShaderFlags, RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags, bool enableDebugInfo, ByteStream *pOutByteCodeStream, ByteStream *pOutInfoLogStream); // current shader store hash static uint32 GetShaderStoreHash(); // initializing compile support static void InitializeShaderCompilerSupport(); // compile shaders for a material -- move to resource compiler //static bool CompileShadersForMaterial(const MaterialShader *pMaterialShader, uint32 *pNumShadersCompiled); // support for reloading base shaders, returns true if it changed static bool RecalculateShaderStoreHash(); }; <file_sep>/Editor/Source/Editor/MapEditor/EditorMap.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "Editor/MapEditor/EditorEditMode.h" #include "Editor/MapEditor/EditorMapEditMode.h" #include "Editor/MapEditor/EditorEntityEditMode.h" #include "Editor/MapEditor/EditorGeometryEditMode.h" #include "Editor/MapEditor/EditorTerrainEditMode.h" #include "Editor/MapEditor/EditorCreateTerrainDialog.h" #include "Editor/MapEditor/ui_EditorMapWindow.h" #include "Editor/EditorVisual.h" #include "Editor/EditorSettings.h" #include "Editor/EditorProgressDialog.h" #include "Engine/ResourceManager.h" #include "Engine/Entity.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "ResourceCompiler/TerrainLayerListGenerator.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" Log_SetChannel(EditorMap); EditorMap::EditorMap(EditorMapWindow *pMapWindow) : m_pMapWindow(pMapWindow), m_pMapSource(nullptr), m_pRenderWorld(nullptr), m_mapBoundingBox(AABox::Zero), m_entityVisualUpdatePending(false), m_pMapEditMode(nullptr), m_pEntityEditMode(nullptr), m_pGeometryEditMode(nullptr), m_pTerrainEditMode(nullptr), m_gridLinesInterval(1.0f), m_gridSnapInterval(0.25f), m_gridLinesVisible(true), m_gridSnapEnabled(true), m_skyVisibility(true), m_skyAutoSize(true), m_skySize(1.0f), m_skyGroundHeight(0.0f), m_pSkyRenderProxy(nullptr), m_sunVisibility(true), m_pSunRenderProxy(nullptr), m_pSunAmbientRenderProxy(nullptr) { } EditorMap::~EditorMap() { // delete edit modes delete m_pTerrainEditMode; delete m_pGeometryEditMode; delete m_pEntityEditMode; delete m_pMapEditMode; for (uint32 i = 0; i < m_entities.GetSize(); i++) delete m_entities[i]; SAFE_RELEASE(m_pSunRenderProxy); SAFE_RELEASE(m_pSkyRenderProxy); // release other objects m_pRenderWorld->Release(); delete m_pMapSource; // compact resource manager resources (unload as many as possible) g_pResourceManager->CompactResources(); } bool EditorMap::CreateMap() { // setup progress dialog EditorProgressDialog progressDialog(m_pMapWindow); progressDialog.show(); m_pRenderWorld = new RenderWorld(); m_pMapSource = new MapSource(); // create empty map m_pMapSource->Create(); // initialize return Initialize(&progressDialog); } bool EditorMap::OpenMap(const char *FileName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { #define LOAD_ERROR(str) { QMessageBox::information(m_pMapWindow, "Map load error", "Map load error: " str, QMessageBox::Ok); } // create objects m_strMapFileName = FileName; m_pRenderWorld = new RenderWorld(); m_pMapSource = new MapSource(); // read in the map source if (!m_pMapSource->Load(FileName, pProgressCallbacks)) { LOAD_ERROR("Could not parse map file."); return false; } // initialize return Initialize(pProgressCallbacks); #undef LOAD_ERROR } bool EditorMap::Initialize(ProgressCallbacks *pProgressCallbacks) { // camera edit mode m_pMapEditMode = new EditorMapEditMode(this); if (!m_pMapEditMode->Initialize(pProgressCallbacks)) return false; // entity edit mode m_pEntityEditMode = new EditorEntityEditMode(this); if (!m_pEntityEditMode->Initialize(pProgressCallbacks)) return false; // geometry edit mode m_pGeometryEditMode = new EditorGeometryEditMode(this); if (!m_pGeometryEditMode->Initialize(pProgressCallbacks)) return false; // initialize entities if (!InitializeEntities(pProgressCallbacks)) return false; // create terrain if (m_pMapSource->HasTerrain() && !InitializeTerrain(pProgressCallbacks)) { Log_ErrorPrintf("EditorMap::Initialize: Failed to initialize terrain."); return false; } // update visuals on first frame m_entityVisualUpdatePending = true; // update sky + sun UpdateSkyVariables(); UpdateSunVariables(); // ok return true; } bool EditorMap::SaveMap(const char *NewFileName /* = NULL */, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { #define SAVE_ERROR(str) { QMessageBox::information(m_pMapWindow, "Map save error", "Map save error: " str, QMessageBox::Ok); } // do the save bool saveResult = (NewFileName != NULL) ? m_pMapSource->SaveAs(NewFileName, pProgressCallbacks) : m_pMapSource->Save(pProgressCallbacks); if (!saveResult) SAVE_ERROR("Could not save map file."); return saveResult; #undef SAVE_ERROR } const String &EditorMap::GetMapProperty(const char *propertyName) { const String *pValue = m_pMapSource->GetProperties()->GetPropertyValuePointer(propertyName); if (pValue != nullptr) return *pValue; const PropertyTemplateProperty *pPropertyDefinition = m_pMapSource->GetObjectTemplate()->GetPropertyDefinitionByName(propertyName); if (pPropertyDefinition == nullptr) return EmptyString; return pPropertyDefinition->GetDefaultValue(); } void EditorMap::SetMapProperty(const char *propertyName, const char *propertyValue) { // try to use proper capitalization const PropertyTemplateProperty *pPropertyDefinition = m_pMapSource->GetObjectTemplate()->GetPropertyDefinitionByName(propertyName); if (pPropertyDefinition != nullptr) { m_pMapSource->GetProperties()->SetPropertyValueString(pPropertyDefinition->GetName(), propertyValue); OnMapPropertyChange(pPropertyDefinition->GetName(), propertyValue); } else { m_pMapSource->GetProperties()->SetPropertyValueString(propertyName, propertyValue); OnMapPropertyChange(propertyName, propertyValue); } // redraw everything RedrawAllViewports(); } EditorMapEntity *EditorMap::CreateEntity(const ObjectTemplate *pTemplate, const char *entityName /* = nullptr */) { if (!pTemplate->CanCreate()) return nullptr; MapSourceEntityData *pEntityData = m_pMapSource->CreateEntityFromTemplate(pTemplate, entityName); if (pEntityData == nullptr) return nullptr; EditorMapEntity *pEntity = CreateInternalEntity(pEntityData); DebugAssert(pEntity != nullptr); // update summary m_pMapEditMode->UpdateSummary(); // redraw everything RedrawAllViewports(); return pEntity; } EditorMapEntity *EditorMap::CreateEntity(const char *entityTypeName, const char *entityName /* = nullptr */) { const ObjectTemplate *pTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(entityTypeName); if (pTemplate == nullptr) return nullptr; return CreateEntity(pTemplate, entityName); } void EditorMap::DeleteEntity(EditorMapEntity *pEntity) { // find in source MapSourceEntityData *pEntityData = const_cast<MapSourceEntityData *>(pEntity->GetEntityData()); DebugAssert(pEntityData != nullptr); // is it selected? if (m_pEntityEditMode->IsSelected(pEntity)) m_pEntityEditMode->RemoveSelection(pEntity); // remove from outliner m_pMapWindow->GetUI()->worldOutliner->RemoveEntity(pEntity); // cleanup the internal structure DebugAssert(m_entities[pEntity->GetArrayIndex()] == pEntity); m_entities[pEntity->GetArrayIndex()] = nullptr; delete pEntity; // remove from source m_pMapSource->RemoveEntity(pEntityData); // update summary m_pMapEditMode->UpdateSummary(); // redraw everything RedrawAllViewports(); } EditorMapEntity *EditorMap::CopyEntity(const EditorMapEntity *pEntity, const char *newName /* = nullptr */) { // create new entity from existing entity MapSourceEntityData *pNewEntityData = m_pMapSource->CopyEntity(pEntity->GetEntityData(), newName); // create internal structure EditorMapEntity *pNewEntity = CreateInternalEntity(pNewEntityData); DebugAssert(pNewEntity != nullptr); // update summary m_pMapEditMode->UpdateSummary(); // redraw everything RedrawAllViewports(); return pNewEntity; } const EditorMapEntity *EditorMap::GetEntityByArrayIndex(uint32 indexID) const { return (indexID < m_entities.GetSize()) ? m_entities[indexID] : nullptr; } EditorMapEntity *EditorMap::GetEntityByArrayIndex(uint32 indexID) { return (indexID < m_entities.GetSize()) ? m_entities[indexID] : nullptr; } const EditorMapEntity *EditorMap::GetEntityByName(const char *entityName) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr && m_entities[i]->GetEntityData()->GetEntityName().Compare(entityName)) return m_entities[i]; } return nullptr; } EditorMapEntity *EditorMap::GetEntityByName(const char *entityName) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i] != nullptr && m_entities[i]->GetEntityData()->GetEntityName().Compare(entityName)) return m_entities[i]; } return nullptr; } void EditorMap::OnEntityPropertyChanged(const EditorMapEntity *pEntity, const char *propertyName, const char *propertyValue) { // handle base position + rotation if (Y_stricmp(propertyName, "Position") == 0) { OnEntityBoundsChanged(pEntity); // update world outliner m_pMapWindow->GetUI()->worldOutliner->OnEntityPositionChanged(pEntity); } else if (Y_stricmp(propertyName, "Rotation") == 0 || Y_stricmp(propertyName, "Scale") == 0) { OnEntityBoundsChanged(pEntity); } // if the active edit mode is entity, notify this if (m_pMapWindow->GetEditMode() == EDITOR_EDIT_MODE_ENTITY) m_pEntityEditMode->OnEntityPropertyChanged(pEntity, propertyName, propertyValue); // queue viewport redraw RedrawAllViewports(); } void EditorMap::OnEntityBoundsChanged(const EditorMapEntity *pEntity) { MergeMapBoundingBox(pEntity->GetBoundingBox()); } void EditorMap::MergeMapBoundingBox(const AABox &box) { float3 mapMinBounds(m_mapBoundingBox.GetMinBounds()); float3 mapMaxBounds(m_mapBoundingBox.GetMaxBounds()); float3 boxMinBounds(box.GetMinBounds()); float3 boxMaxBounds(box.GetMaxBounds()); bool changed = false; // handle those pesky infinites for (uint32 i = 0; i < 3; i++) { if (boxMinBounds[i] != Y_FLT_INFINITE && boxMinBounds[i] < mapMinBounds[i]) { mapMinBounds[i] = boxMinBounds[i]; changed = true; } if (boxMaxBounds[i] != Y_FLT_INFINITE && boxMaxBounds[i] > mapMaxBounds[i]) { mapMaxBounds[i] = boxMaxBounds[i]; changed = true; } } if (changed) { m_mapBoundingBox.SetBounds(mapMinBounds, mapMaxBounds); OnMapBoundingBoxChange(); } // // does this change the bounding box of the map? // if (box.GetMinBounds().AnyLess(m_mapBoundingBox.GetMinBounds()) || // box.GetMaxBounds().AnyGreater(m_mapBoundingBox.GetMaxBounds())) // { // m_mapBoundingBox.Merge(box); // OnMapBoundingBoxChange(); // } } void EditorMap::OnMapBoundingBoxChange() { Log_DevPrintf("Map bounds change: (%s) - (%s)", StringConverter::Float3ToString(m_mapBoundingBox.GetMinBounds()).GetCharArray(), StringConverter::Float3ToString(m_mapBoundingBox.GetMaxBounds()).GetCharArray()); // update sky transform UpdateSkyTransform(); } // const MapSourceEntityData *EditorMap::GetEntityData(uint32 entityId) const // { // return m_pMapSource->GetEntityData(entityId); // } // // String EditorMap::GetEntityPropertyValue(uint32 entityId, const char *propertyName) const // { // const EditorMapEntity *pEntity = GetEntityByID(entityId); // if (pEntity == nullptr) // return EmptyString; // // return pEntity->GetEntityPropertyValue(propertyName); // } // // bool EditorMap::SetEntityPropertyValue(uint32 entityId, const char *propertyName, const char *propertyValue) // { // EditorMapEntity *pEntity = GetEntityByID(entityId); // if (pEntity == NULL) // { // Log_WarningPrintf("Attempting to set property '%s' on untracked entity %u to '%s'.", propertyName, entityId, propertyValue); // return false; // } // // return m_pEntityEditMode->SetEntityPropertyValue(pEntity, propertyName, propertyValue); // } bool EditorMap::InitializeEntities(ProgressCallbacks *pProgressCallbacks) { pProgressCallbacks->SetStatusText("Creating entities..."); pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetProgressRange(m_pMapSource->GetEntityCount()); pProgressCallbacks->SetProgressValue(0); m_pMapSource->EnumerateEntities([this, pProgressCallbacks](MapSourceEntityData *pEntityData) { CreateInternalEntity(pEntityData); pProgressCallbacks->IncrementProgressValue(); }); return true; } EditorMapEntity *EditorMap::CreateInternalEntity(MapSourceEntityData *pEntityData) { // find a free slot uint32 arrayIndex; for (arrayIndex = 0; arrayIndex < m_entities.GetSize(); arrayIndex++) { if (m_entities[arrayIndex] == nullptr) break; } if (arrayIndex == m_entities.GetSize()) m_entities.Add(nullptr); // create the visual EditorMapEntity *pEntity = EditorMapEntity::Create(this, arrayIndex, pEntityData); if (pEntity == nullptr) { Log_WarningPrintf("Could not create visual entity for entity '%s' (%s)", pEntityData->GetEntityName().GetCharArray(), pEntityData->GetTypeName().GetCharArray()); return nullptr; } // store it m_entities[arrayIndex] = pEntity; // add to outliner m_pMapWindow->GetUI()->worldOutliner->AddEntity(pEntity); // merge with bounds OnEntityBoundsChanged(pEntity); // done return pEntity; } bool EditorMap::IsEntityInVisibleRange(const EditorMapEntity *pEntity) const { // uint32 i; // float2 *cameraPositions = (float2 *)alloca(sizeof(float2) * m_viewports.GetSize()); // uint32 nCameraPositions = 0; // // for (i = 0; i < m_viewports.GetSize(); i++) // { // const EditorMapViewport *pViewport = m_viewports[i]; // if (pViewport != NULL) // { // const float3 &realCameraPosition(pViewport->GetViewController().GetCameraPosition()); // cameraPositions[nCameraPositions++] = float2(realCameraPosition.x, realCameraPosition.y); // } // } return true; } void EditorMap::UpdateEntityVisuals() { for (uint32 i = 0; i < m_entities.GetSize(); i++) { EditorMapEntity *pEntity = m_entities[i]; if (pEntity == nullptr) continue; // in visual range? bool inVisualRange = IsEntityInVisibleRange(pEntity); // currently visible? if (inVisualRange) { if (!pEntity->IsVisualCreated()) pEntity->CreateVisual(); } else { if (pEntity->IsVisualCreated()) pEntity->DeleteVisual(); } } } bool EditorMap::CreateTerrain(const char *importLayerListName, TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat, uint32 scale, uint32 sectionSize, uint32 renderLODCount, int32 minHeight, int32 maxHeight, int32 baseHeight) { EditorProgressDialog progressDialog(m_pMapWindow); progressDialog.show(); // create the layer list TerrainLayerListGenerator *pLayerListGenerator; if (importLayerListName != nullptr) { // load from this file PathString importFileName; importFileName.Format("%s.layerlist.zip", importLayerListName); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(importLayerListName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) { progressDialog.DisplayFormattedError("Failed to open '%s'", importFileName.GetCharArray()); return false; } pLayerListGenerator = new TerrainLayerListGenerator(); if (!pLayerListGenerator->Load(importLayerListName, pStream, &progressDialog)) { progressDialog.DisplayFormattedError("Failed to load layerlist at '%s'", importFileName.GetCharArray()); delete pLayerListGenerator; pStream->Release(); return false; } } else { // create the default one pLayerListGenerator = EditorTerrainEditMode::CreateEmptyLayerList(); if (pLayerListGenerator == nullptr) return false; } // create the terrain data MapSourceTerrainData *pTerrainData = m_pMapSource->CreateTerrainData(pLayerListGenerator, heightStorageFormat, scale, sectionSize, renderLODCount, minHeight, maxHeight, baseHeight, &progressDialog); if (pTerrainData == nullptr) { delete pLayerListGenerator; return false; } // init it if (!InitializeTerrain(&progressDialog)) { DeleteTerrain(); return false; } // update ui //m_pMapWindow->GetUI()->OnMapTerrainCreatedOrDeleted(this); Panic("Fixme UI update"); return true; } bool EditorMap::InitializeTerrain(ProgressCallbacks *pProgressCallbacks) { // Create edit mode DebugAssert(m_pTerrainEditMode == nullptr); m_pTerrainEditMode = new EditorTerrainEditMode(this); if (!m_pTerrainEditMode->Initialize(pProgressCallbacks)) return false; // merge bounding box MergeMapBoundingBox(m_pMapSource->GetTerrainData()->CalculateTerrainBoundingBox()); // store return true; } void EditorMap::DeleteTerrain() { if (m_pTerrainEditMode != nullptr) { delete m_pTerrainEditMode; m_pTerrainEditMode = nullptr; } if (m_pMapSource->HasTerrain()) m_pMapSource->DeleteTerrainData(); Panic("Fixme UI update"); } void EditorMap::Update(float timeSinceLastUpdate) { // update edit modes m_pMapEditMode->Update(timeSinceLastUpdate); m_pEntityEditMode->Update(timeSinceLastUpdate); m_pGeometryEditMode->Update(timeSinceLastUpdate); if (m_pTerrainEditMode != nullptr) m_pTerrainEditMode->Update(timeSinceLastUpdate); // update visual entities if prompted if (m_entityVisualUpdatePending) { UpdateEntityVisuals(); m_entityVisualUpdatePending = true; } } void EditorMap::RedrawAllViewports() { m_pMapWindow->RedrawAllViewports(); } void EditorMap::OnMapPropertyChange(const char *propertyName, const char *propertyValue) { #define PROPERTY_IS(pname) ((Y_stricmp(pname, propertyName) == 0)) if (PROPERTY_IS("SkyEnabled") || PROPERTY_IS("SkyType") || PROPERTY_IS("SkyMaterial") || PROPERTY_IS("SkySize") || PROPERTY_IS("SkyGroundLevel")) { UpdateSkyVariables(); } #undef PROPERTY_IS // update map edit mode m_pMapEditMode->OnMapPropertyChanged(propertyName, propertyValue); } void EditorMap::SetSkyVisibility(bool enabled) { m_skyVisibility = enabled; if (m_pSkyRenderProxy != nullptr) m_pSkyRenderProxy->SetVisibility(enabled); } void EditorMap::SetSunVisibility(bool enabled) { m_sunVisibility = enabled; if (m_pSunRenderProxy != nullptr) m_pSunRenderProxy->SetEnabled(enabled); } void EditorMap::UpdateSkyVariables() { bool skyEnabled = StringConverter::StringToBool(GetMapProperty("SkyEnabled")); uint32 skyType = StringConverter::StringToUInt32(GetMapProperty("SkyType")); const char *skyMaterial = GetMapProperty("SkyMaterial"); float skySize = StringConverter::StringToFloat(GetMapProperty("SkySize")); float skyGroundLevel = StringConverter::StringToFloat(GetMapProperty("SkyGroundLevel")); if (!skyEnabled) { if (m_pSkyRenderProxy != nullptr) { m_pRenderWorld->RemoveRenderable(m_pSkyRenderProxy); m_pSkyRenderProxy->Release(); m_pSkyRenderProxy = nullptr; } return; } static const char *skyMeshNames[MAP_SKY_TYPE_COUNT] = { "models/engine/skybox", "models/engine/skysphere", "models/engine/skydome" }; DebugAssert(skyType < MAP_SKY_TYPE_COUNT); AutoReleasePtr<const StaticMesh> pStaticMesh = g_pResourceManager->GetStaticMesh(skyMeshNames[skyType]); if (pStaticMesh == nullptr) { if (m_pSkyRenderProxy != nullptr) { m_pRenderWorld->RemoveRenderable(m_pSkyRenderProxy); m_pSkyRenderProxy->Release(); m_pSkyRenderProxy = nullptr; } return; } AutoReleasePtr<const Material> pMaterial = g_pResourceManager->GetMaterial(skyMaterial); if (pMaterial == nullptr) pMaterial = g_pResourceManager->GetDefaultMaterial(); if (m_pSkyRenderProxy == nullptr) { m_pSkyRenderProxy = new StaticMeshRenderProxy(0, pStaticMesh, Transform::Identity, 0); m_pRenderWorld->AddRenderable(m_pSkyRenderProxy); } m_pSkyRenderProxy->SetStaticMesh(pStaticMesh); m_pSkyRenderProxy->SetMaterial(0, pMaterial); m_skyGroundHeight = skyGroundLevel; m_skySize = skySize; UpdateSkyTransform(); } void EditorMap::UpdateSkyTransform() { if (m_pSkyRenderProxy == nullptr) return; float skySize; if (m_skyAutoSize) { const float MINIMUM_SIZE = 128.0f; const float SCALE_DOWN = 1000.0f; const float SCALE_UP = 2.0f; float3 maxDimensions(m_mapBoundingBox.GetMinBounds().Abs().Max(m_mapBoundingBox.GetMaxBounds().Abs())); skySize = Max(MINIMUM_SIZE, Max(maxDimensions.x, Max(maxDimensions.y, maxDimensions.z))); skySize /= SCALE_DOWN; skySize *= SCALE_UP; } else { skySize = m_skySize; } // work out sky position float3 skyPosition(float3(m_skyGroundHeight, m_skyGroundHeight, m_skyGroundHeight) * -skySize); m_pSkyRenderProxy->SetTransform(Transform(skyPosition, Quaternion::Identity, float3(skySize, skySize, skySize))); RedrawAllViewports(); } void EditorMap::UpdateSunVariables() { } <file_sep>/Engine/Source/Engine/ScriptBuiltinFunctions.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptManager.h" Log_SetChannel(ScriptManager); static void lua_Log_Write(lua_State *L, LOGLEVEL level) { const char *msg = lua_tostring(L, 1); const char *funcname = ""; // @TODO Log::GetInstance().Write("Script", "", level, (msg != nullptr) ? msg : "(null)"); } static int lua_Log_Error(lua_State *L) { lua_Log_Write(L, LOGLEVEL_ERROR); return 0; } static int lua_Log_Warning(lua_State *L) { lua_Log_Write(L, LOGLEVEL_WARNING); return 0; } static int lua_Log_Info(lua_State *L) { lua_Log_Write(L, LOGLEVEL_INFO); return 0; } static int lua_Log_Perf(lua_State *L) { lua_Log_Write(L, LOGLEVEL_PERF); return 0; } static int lua_Log_Dev(lua_State *L) { lua_Log_Write(L, LOGLEVEL_DEV); return 0; } static int lua_Log_Profile(lua_State *L) { lua_Log_Write(L, LOGLEVEL_PROFILE); return 0; } static int lua_Log_Trace(lua_State *L) { lua_Log_Write(L, LOGLEVEL_TRACE); return 0; } static const luaL_Reg lua_Log[] = { { "Error", lua_Log_Error }, { "Warning", lua_Log_Warning }, { "Info", lua_Log_Info }, { "Perf", lua_Log_Perf }, { "Dev", lua_Log_Dev }, { "Profile", lua_Log_Profile }, { "Trace", lua_Log_Trace }, { nullptr, nullptr } }; static void RegisterFunctionLibrary(lua_State *L, const char *name, const luaL_Reg *reg) { luaBackupStack(L); luaL_newlib(L, reg); lua_setglobal(L, name); luaVerifyStack(L, 0); } void ScriptManager::RegisterBuiltinFunctions() { luaBackupStack(m_state); // Log RegisterFunctionLibrary(m_state, "Log", lua_Log); luaVerifyStack(m_state, 0); } <file_sep>/Engine/Source/Renderer/Shaders/OverlayShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/OverlayShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" #include "Engine/Texture.h" DEFINE_SHADER_COMPONENT_INFO(OverlayShader); BEGIN_SHADER_COMPONENT_PARAMETERS(OverlayShader) DEFINE_SHADER_COMPONENT_PARAMETER("DrawTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void OverlayShader::SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture *pTexture) { pShaderProgram->SetBaseShaderParameterResource(pContext, 0, pTexture); } void OverlayShader::SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, Texture *pTexture) { pShaderProgram->SetBaseShaderParameterResource(pContext, 0, (pTexture != nullptr) ? pTexture->GetGPUTexture() : nullptr); } bool OverlayShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr) return false; if (pMaterialShader != nullptr) return false; return true; } bool OverlayShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { if (baseShaderFlags & WITH_3D_VERTEX) pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/OverlayShader.hlsl", "WorldVS"); else pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/OverlayShader.hlsl", "ScreenVS"); if (baseShaderFlags & WITH_TEXTURE) pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/OverlayShader.hlsl", "TexturedPS"); else pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/OverlayShader.hlsl", "ColoredPS"); return true; } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2ConstantLibrary.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2ConstantLibrary.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(OpenGLES2RenderBackend); const OpenGLES2ConstantLibrary::ConstantID OpenGLES2ConstantLibrary::ConstantIndexInvalid = 0xFFFFFFFF; const uint32 OpenGLES2ConstantLibrary::BufferOffsetInvalid = 0xFFFFFFFF; OpenGLES2ConstantLibrary::OpenGLES2ConstantLibrary(RENDERER_FEATURE_LEVEL featureLevel) : m_allConstantsSize(0) { GenerateConstantData(featureLevel); } OpenGLES2ConstantLibrary::~OpenGLES2ConstantLibrary() { } OpenGLES2ConstantLibrary::ConstantID OpenGLES2ConstantLibrary::LookupConstantID(const char *fullyQualifiedName) const { const CIStringHashTable<ConstantID>::Member *pMember = m_nameToIDMap.Find(fullyQualifiedName); if (pMember == nullptr) return ConstantIndexInvalid; return pMember->Value; } OpenGLES2ConstantLibrary::ConstantID OpenGLES2ConstantLibrary::LookupConstantID(uint32 bufferIndex, uint32 fieldIndex) const { ConstantID startingConstantID = m_constantBufferStartingIndices[bufferIndex]; if (startingConstantID == ConstantIndexInvalid) return ConstantIndexInvalid; return startingConstantID + fieldIndex; } bool OpenGLES2ConstantLibrary::FindConstantsAtOffset(uint32 bufferIndex, uint32 startOffset, uint32 endOffset, ConstantID *pFirstConstant, ConstantID *pLastConstant) const { ConstantID bufferStartingConstantID = m_constantBufferStartingOffsets[bufferIndex]; ConstantID firstConstantID = ConstantIndexInvalid; ConstantID lastConstantID = ConstantIndexInvalid; for (ConstantID currentConstantID = bufferStartingConstantID; currentConstantID < m_constantData.GetSize(); currentConstantID++) { const ConstantInfo &constantInfo = m_constantData[currentConstantID]; if (constantInfo.BufferIndex != bufferIndex) break; if (startOffset >= constantInfo.LocalBufferOffset) { if (firstConstantID == ConstantIndexInvalid) { firstConstantID = currentConstantID; lastConstantID = currentConstantID; } } if (endOffset > constantInfo.LocalBufferOffset) lastConstantID = currentConstantID; else break; } if (firstConstantID != ConstantIndexInvalid) { *pFirstConstant = firstConstantID; *pLastConstant = lastConstantID; return true; } else { return false; } } uint32 OpenGLES2ConstantLibrary::GetBufferStartOffset(uint32 bufferIndex) const { return m_constantBufferStartingOffsets[bufferIndex]; } const OpenGLES2ConstantLibrary::ConstantInfo *OpenGLES2ConstantLibrary::GetConstantInfo(ConstantID constantID) const { return &m_constantData[constantID]; } void OpenGLES2ConstantLibrary::UpdateProgramConstant(const byte *pGlobalBuffer, ConstantID constantID, GLuint programLocation) const { const ConstantInfo &info = m_constantData[constantID]; OpenGLES2Helpers::GLUniformWrapper(info.Type, programLocation, info.ArraySize, pGlobalBuffer + info.GlobalBufferOffset); } void OpenGLES2ConstantLibrary::GenerateConstantData(RENDERER_FEATURE_LEVEL featureLevel) { const ShaderConstantBuffer::RegistryType *pRegistry = ShaderConstantBuffer::GetRegistry(); // reserve space m_constantBufferStartingIndices.Reserve(pRegistry->GetNumTypes()); m_constantBufferStartingOffsets.Reserve(pRegistry->GetNumTypes()); // iterate buffers uint32 totalBufferSize = 0; for (uint32 registryIndex = 0; registryIndex < pRegistry->GetNumTypes(); registryIndex++) { // lookup const ShaderConstantBuffer *pBuffer = pRegistry->GetTypeInfoByIndex(registryIndex); if (pBuffer == nullptr) { m_constantBufferStartingIndices.Add(ConstantIndexInvalid); m_constantBufferStartingOffsets.Add(BufferOffsetInvalid); continue; } // check platform requirement if (pBuffer->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && pBuffer->GetPlatformRequirement() != RENDERER_PLATFORM_OPENGLES2) { m_constantBufferStartingIndices.Add(ConstantIndexInvalid); m_constantBufferStartingOffsets.Add(BufferOffsetInvalid); continue; } // check feature level requirement if (pBuffer->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && pBuffer->GetMinimumFeatureLevel() > featureLevel) { m_constantBufferStartingIndices.Add(ConstantIndexInvalid); m_constantBufferStartingOffsets.Add(BufferOffsetInvalid); continue; } // we can't handle struct buffers right now if (pBuffer->GetFieldCount() == 0) { m_constantBufferStartingIndices.Add(ConstantIndexInvalid); m_constantBufferStartingOffsets.Add(BufferOffsetInvalid); continue; } // add our starting constant index m_constantBufferStartingIndices.Add(m_constantData.GetSize()); // add our starting offset m_constantBufferStartingOffsets.Add(totalBufferSize); // retrieve constants for (uint32 fieldIndex = 0; fieldIndex < pBuffer->GetFieldCount(); fieldIndex++) { const SHADER_CONSTANT_BUFFER_FIELD_DECLARATION *pDeclaration = pBuffer->GetFieldDeclaration(fieldIndex); // generate fully-qualified name SmallString fullyQualifiedName; fullyQualifiedName.Format("%s.%s", pBuffer->GetInstanceName(), pDeclaration->FieldName); // insert to name map, this shouldn't exist if (m_nameToIDMap.Find(fullyQualifiedName) != nullptr) Log_WarningPrintf("OpenGLES2ConstantLibrary::GenerateConstantData: Duplicate fully-qualified name: %s", fullyQualifiedName.GetCharArray()); else m_nameToIDMap.Insert(fullyQualifiedName, m_constantData.GetSize()); // generate constant info ConstantInfo data; data.BufferIndex = registryIndex; data.FieldIndex = fieldIndex; data.ArraySize = pDeclaration->ArraySize; data.Type = pDeclaration->FieldType; data.LocalBufferOffset = pDeclaration->BufferOffset; //data.GlobalBufferOffset = totalBufferSize; data.GlobalBufferOffset = totalBufferSize + pDeclaration->BufferOffset; m_constantData.Add(data); // add our field size, ES data is tightly packed ignoring register alignment DebugAssert(pDeclaration->ArraySize > 0); //totalBufferSize += ShaderParameterValueTypeSize(pDeclaration->FieldType) * pDeclaration->ArraySize; // can't pack, because we're updated via WriteConstantBuffer which uses the GPU-register offset // if we wrote by constant id this would be different, though //totalBufferSize += pDeclaration->ArraySize * pDeclaration->BufferArrayStride; } totalBufferSize += pBuffer->GetBufferSize(); } // allocate the constant storage Log_DevPrintf("OpenGLES2ConstantLibrary::GenerateConstantData: Total constant memory usage: %u bytes", totalBufferSize); DebugAssert(totalBufferSize > 0); m_allConstantsSize = totalBufferSize; } <file_sep>/Engine/Source/BaseGame/PrecompiledHeader.cpp #include "BaseGame/PrecompiledHeader.h" <file_sep>/Engine/Source/MathLib/SIMDVectorf_scalar.cpp #include "MathLib/SIMDVectorf.h" #if Y_CPU_SSE_LEVEL == 0 const SIMDVector2f &SIMDVector2f::Zero = reinterpret_cast<const SIMDVector2f &>(Vector2f::Zero); const SIMDVector2f &SIMDVector2f::One = reinterpret_cast<const SIMDVector2f &>(Vector2f::One); const SIMDVector2f &SIMDVector2f::NegativeOne = reinterpret_cast<const SIMDVector2f &>(Vector2f::NegativeOne); const SIMDVector2f &SIMDVector2f::Infinite = reinterpret_cast<const SIMDVector2f &>(Vector2f::Infinite); const SIMDVector2f &SIMDVector2f::NegativeInfinite = reinterpret_cast<const SIMDVector2f &>(Vector2f::NegativeInfinite); const SIMDVector2f &SIMDVector2f::UnitX = reinterpret_cast<const SIMDVector2f &>(Vector2f::UnitX); const SIMDVector2f &SIMDVector2f::UnitY = reinterpret_cast<const SIMDVector2f &>(Vector2f::UnitY); const SIMDVector2f &SIMDVector2f::NegativeUnitX = reinterpret_cast<const SIMDVector2f &>(Vector2f::NegativeUnitX); const SIMDVector2f &SIMDVector2f::NegativeUnitY = reinterpret_cast<const SIMDVector2f &>(Vector2f::NegativeUnitY); const SIMDVector3f &SIMDVector3f::Zero = reinterpret_cast<const SIMDVector3f &>(Vector3f::Zero); const SIMDVector3f &SIMDVector3f::One = reinterpret_cast<const SIMDVector3f &>(Vector3f::One); const SIMDVector3f &SIMDVector3f::NegativeOne = reinterpret_cast<const SIMDVector3f &>(Vector3f::NegativeOne); const SIMDVector3f &SIMDVector3f::Infinite = reinterpret_cast<const SIMDVector3f &>(Vector3f::Infinite); const SIMDVector3f &SIMDVector3f::NegativeInfinite = reinterpret_cast<const SIMDVector3f &>(Vector3f::NegativeInfinite); const SIMDVector3f &SIMDVector3f::UnitX = reinterpret_cast<const SIMDVector3f &>(Vector3f::UnitX); const SIMDVector3f &SIMDVector3f::UnitY = reinterpret_cast<const SIMDVector3f &>(Vector3f::UnitY); const SIMDVector3f &SIMDVector3f::UnitZ = reinterpret_cast<const SIMDVector3f &>(Vector3f::UnitZ); const SIMDVector3f &SIMDVector3f::NegativeUnitX = reinterpret_cast<const SIMDVector3f &>(Vector3f::NegativeUnitX); const SIMDVector3f &SIMDVector3f::NegativeUnitY = reinterpret_cast<const SIMDVector3f &>(Vector3f::NegativeUnitY); const SIMDVector3f &SIMDVector3f::NegativeUnitZ = reinterpret_cast<const SIMDVector3f &>(Vector3f::NegativeUnitZ); const SIMDVector4f &SIMDVector4f::Zero = reinterpret_cast<const SIMDVector4f &>(Vector4f::Zero); const SIMDVector4f &SIMDVector4f::One = reinterpret_cast<const SIMDVector4f &>(Vector4f::One); const SIMDVector4f &SIMDVector4f::NegativeOne = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeOne); const SIMDVector4f &SIMDVector4f::Infinite = reinterpret_cast<const SIMDVector4f &>(Vector4f::Infinite); const SIMDVector4f &SIMDVector4f::NegativeInfinite = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeInfinite); const SIMDVector4f &SIMDVector4f::UnitX = reinterpret_cast<const SIMDVector4f &>(Vector4f::UnitX); const SIMDVector4f &SIMDVector4f::UnitY = reinterpret_cast<const SIMDVector4f &>(Vector4f::UnitY); const SIMDVector4f &SIMDVector4f::UnitZ = reinterpret_cast<const SIMDVector4f &>(Vector4f::UnitZ); const SIMDVector4f &SIMDVector4f::UnitW = reinterpret_cast<const SIMDVector4f &>(Vector4f::UnitW); const SIMDVector4f &SIMDVector4f::NegativeUnitX = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeUnitX); const SIMDVector4f &SIMDVector4f::NegativeUnitY = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeUnitY); const SIMDVector4f &SIMDVector4f::NegativeUnitZ = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeUnitZ); const SIMDVector4f &SIMDVector4f::NegativeUnitW = reinterpret_cast<const SIMDVector4f &>(Vector4f::NegativeUnitW); #endif <file_sep>/Engine/Source/MathLib/Line.h #pragma once #include "MathLib/Vectorf.h" #include "MathLib/Plane.h" // Line is a line in 3D space, with a point, spanning infinite distance in +/- directions of Direction. struct Line { Line() {} Line(const Vector3f &Point_, const Vector3f &Direction_) : Point(Point_), Direction(Direction_) {} Line(const Line &v) : Point(v.Point), Direction(v.Direction) {} // Set from a point and direction. void Set(const Vector3f &Point_, const Vector3f &Direction_) { Point = Point_; Direction = Direction_; } // Set from two points. void SetFromTwoPoints(const Vector3f &Point1, const Vector3f &Point2) { Point = Point1; Direction = (Point2 - Point1).SafeNormalize(); } // Compute line<->line intersection. If an intersection cannot be found, an infinite vector is returned. Vector3f LineIntersection(const Line &LineB, const float epsilon = Y_FLT_EPSILON) const { const Vector3f &dir1 = this->Direction; const Vector3f &dir2 = LineB.Direction; const Vector3f &point1 = this->Point; const Vector3f &point2 = LineB.Point; float t; if (Y_fabs(dir1.y * dir2.x - dir1.x * dir2.y) > epsilon) { t = (-point1.y * dir2.x + point2.y * dir2.x + dir2.y * point1.x-dir2.y * point2.x) / (dir1.y * dir2.x - dir1.x * dir2.y); } else if (Y_fabs(-dir1.x * dir2.z + dir1.z * dir2.x) > epsilon) { t=-(-dir2.z * point1.x + dir2.z * point2.x + dir2.x * point1.z - dir2.x * point2.z) / (-dir1.x * dir2.z + dir1.z * dir2.x); } else if (Y_fabs(-dir1.z * dir2.y + dir1.y * dir2.z) > epsilon) { t = (point1.z * dir2.y - point2.z * dir2.y - dir2.z * point1.y + dir2.z * point2.y) / (-dir1.z * dir2.y + dir1.y * dir2.z); } else { return Vector3f::Infinite; } return dir1 * t + point1; } // Compute line<->plane intersection. If an intersection cannot be found, an infinite vector is returned. Vector3f PlaneIntersection(const Plane &plane, const float epsilon = Y_FLT_EPSILON) const { const float &A = plane.a; const float &B = plane.b; const float &C = plane.c; const float &D = plane.d; float numerator = A * this->Point.x + B * this->Point.y + C * this->Point.z + D; float denominator = A * this->Direction.x + B * this->Direction.y + C * this->Direction.z; //if line is parallel to the plane... if (Y_fabs(denominator) < epsilon) { // if line is contained in the plane... if (Y_fabs(numerator) < epsilon) return this->Point; else return Vector3f::Infinite; } else { // if line intercepts the plane float t = -numerator / denominator; return this->Direction * t + Point; } } // Compute point to point distance. float PointToPointDistance(const Line &l) const { return PointToPointDistance(l.Point); } float PointToPointDistance(const Vector3f &v) const { Vector3f temp = v - this->Point; float length = temp.Length(); if (length == 0.0f) return 0.0f; // normalize temp temp /= length; if (temp.Dot(this->Direction) < 0.0f) return -length; else return length; } // Finds closest point from line to point. //Vector3 ClosestPointOnLine(const MLVECTOR3 &Point) const; // Finds the distance from point to line. //float DistanceFromPoint(const MLVECTOR3 &Point) const; // operators bool operator==(const Line &v) const { return (Point == v.Point && Direction == v.Direction); } bool operator!=(const Line &v) const { return (Point != v.Point || Direction != v.Direction); } Line &operator=(const Line &v) { Point = v.Point; Direction = v.Direction; return *this; } public: Vector3f Point; Vector3f Direction; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLCVars.h #pragma once #include "Engine/Common.h" namespace CVars { // OpenGL CVars extern CVar r_opengl_disable_vertex_attrib_binding; extern CVar r_opengl_disable_direct_state_access; extern CVar r_opengl_disable_multi_bind; } <file_sep>/Engine/Source/BlockEngine/BlockDrawTemplate.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockDrawTemplate.h" #include "BlockEngine/BlockWorldMesher.h" #include "Engine/Camera.h" Log_SetChannel(BlockDrawTemplate); BlockDrawTemplate::BlockDrawTemplate(const BlockPalette *pPalette) : m_pBlockPalette(pPalette), m_pVertexBuffer(nullptr), m_pIndexBuffer(nullptr) { m_pBlockPalette->AddRef(); } BlockDrawTemplate::~BlockDrawTemplate() { SAFE_RELEASE(m_pIndexBuffer); SAFE_RELEASE(m_pVertexBuffer); SAFE_RELEASE(m_pBlockPalette); } bool BlockDrawTemplate::Initialize() { // allocate block draw info m_blockDrawInfo.Resize(BLOCK_MESH_MAX_BLOCK_TYPES); m_blockDrawInfo.ZeroContents(); // temporary buffers BlockWorldMesher::Output mesherOutput; MemArray<BlockWorldVertexFactory::Vertex> vertexArray; MemArray<uint16> indexArray; MemArray<float3x4> instanceArray; // for each block type, mesh it, and store to buffers for (uint32 blockTypeIndex = 0; blockTypeIndex < BLOCK_MESH_MAX_BLOCK_TYPES; blockTypeIndex++) { const BlockPalette::BlockType *pBlockType = m_pBlockPalette->GetBlockType(blockTypeIndex); if (!pBlockType->IsAllocated || !(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE)) continue; // stuff we've output uint32 baseBatch = m_batches.GetSize(); uint32 batchCount = 0; // handle triangle meshes if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { // save old state uint32 baseVertex = vertexArray.GetSize(); uint32 baseIndex = indexArray.GetSize(); // clear mesher output mesherOutput.Vertices.Clear(); mesherOutput.Triangles.Clear(); mesherOutput.Batches.Clear(); mesherOutput.Instances.Clear(); // mesh this block type if (!BlockWorldMesher::MeshSingleBlock(m_pBlockPalette, (BlockWorldBlockType)blockTypeIndex, mesherOutput)) continue; // add triangle batches if (!mesherOutput.Batches.IsEmpty()) { // append vertices vertexArray.AddArray(mesherOutput.Vertices); // append indices for (const BlockWorldMesher::Triangle &inTriangle : mesherOutput.Triangles) { uint16 indices[3] = { (uint16)inTriangle.Indices[0], (uint16)inTriangle.Indices[1], (uint16)inTriangle.Indices[2] }; indexArray.AddRange(indices, countof(indices)); } // append batches for (const BlockWorldMesher::Batch &inBatch : mesherOutput.Batches) { Batch outBatch(pBlockType, nullptr, m_pBlockPalette->GetMaterial(inBatch.MaterialIndex), baseVertex, baseIndex, inBatch.StartIndex, inBatch.NumIndices); m_batches.Add(outBatch); batchCount++; } } } else { // handle mesh instances. each block type only has a single mesh const StaticMesh *pMesh = m_pBlockPalette->GetMesh(pBlockType->MeshShapeSettings.MeshIndex); const StaticMesh::LOD *pMeshLOD = pMesh->GetLOD(0); // create batches for each of the mesh's batches for (uint32 meshBatchIndex = 0; meshBatchIndex < pMeshLOD->GetBatchCount(); meshBatchIndex++) { const StaticMesh::Batch *pMeshBatch = pMeshLOD->GetBatch(meshBatchIndex); // copy stuff in Batch outBatch(pBlockType, pMesh, pMesh->GetMaterial(pMeshBatch->MaterialIndex), 0, 0, pMeshBatch->StartIndex, pMeshBatch->NumIndices); m_batches.Add(outBatch); batchCount++; } } // store information m_blockDrawInfo[blockTypeIndex].StartBatch = baseBatch; m_blockDrawInfo[blockTypeIndex].BatchCount = batchCount; } // create buffers if (!vertexArray.IsEmpty()) { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this, &vertexArray, &indexArray]() { GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, vertexArray.GetStorageSizeInBytes()); m_pVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, vertexArray.GetBasePointer()); GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, indexArray.GetStorageSizeInBytes()); m_pIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, indexArray.GetBasePointer()); }); if (m_pVertexBuffer == nullptr || m_pIndexBuffer == nullptr) { Log_ErrorPrintf("BlockPaletteDrawTemplate::Initialize: Failed to allocate vertex or index buffers."); return false; } } Log_InfoPrintf("BlockPaletteDrawTemplate::Initialize: %u vertices, %u indices, %u batches", vertexArray.GetSize(), indexArray.GetSize(), m_batches.GetSize()); return true; } bool BlockDrawTemplate::GetBatchRangeForBlock(BlockWorldBlockType blockType, uint32 *startBatch, uint32 *batchCount) const { DebugAssert(blockType < m_blockDrawInfo.GetSize()); if (m_blockDrawInfo[blockType].BatchCount == 0) return false; *startBatch = m_blockDrawInfo[blockType].StartBatch; *batchCount = m_blockDrawInfo[blockType].BatchCount; return true; } const Material *BlockDrawTemplate::GetBatchMaterial(uint32 batchIndex) const { DebugAssert(batchIndex < m_batches.GetSize()); const Batch &batchInfo = m_batches[batchIndex]; return batchInfo.pMaterial; } const VertexFactoryTypeInfo *BlockDrawTemplate::GetBatchVertexFactoryType(uint32 batchIndex) const { DebugAssert(batchIndex < m_batches.GetSize()); const Batch &batchInfo = m_batches[batchIndex]; if (batchInfo.pMesh != nullptr) return VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); else return VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory); } const uint32 BlockDrawTemplate::GetBatchVertexFactoryFlags(uint32 batchIndex) const { DebugAssert(batchIndex < m_batches.GetSize()); const Batch &batchInfo = m_batches[batchIndex]; if (batchInfo.pMesh != nullptr) return batchInfo.pMesh->GetVertexFactoryFlags(); else return 0; } void BlockDrawTemplate::DrawBatch(GPUContext *pContext, ShaderProgram *pShaderProgram, uint32 batchIndex) const { const Batch &batchInfo = m_batches[batchIndex]; if (batchInfo.pMesh != nullptr) { const StaticMesh::LOD *pMeshLOD = batchInfo.pMesh->GetLOD(0); if (!pMeshLOD->CreateGPUResources()) return; // bind the mesh buffers pMeshLOD->GetVertexBuffers()->BindBuffers(pContext); pContext->SetIndexBuffer(pMeshLOD->GetIndexBuffer(), pMeshLOD->GetIndexFormat(), 0); pContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // bit of a hack, we just fudge the world matrix to push the mesh to the right location.. float scale = batchInfo.pBlockType->MeshShapeSettings.Scale; float4x4 worldMatrixOffset(scale, 0.0f, 0.0f, 0.5f, 0.0f, scale, 0.0f, 0.5f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); float4x4 oldWorldMatrix(pContext->GetConstants()->GetLocalToWorldMatrix()); float4x4 newWorldMatrix(oldWorldMatrix * worldMatrixOffset); pContext->GetConstants()->SetLocalToWorldMatrix(newWorldMatrix, false); pContext->GetConstants()->CommitChanges(); // draw the mesh batch pContext->DrawIndexed(batchInfo.FirstIndex, batchInfo.IndexCount, 0); // restore the old world matrix pContext->GetConstants()->SetLocalToWorldMatrix(newWorldMatrix, false); pContext->GetConstants()->CommitChanges(); } else { // draw normally pContext->SetVertexBuffer(0, m_pVertexBuffer, 0, sizeof(BlockWorldVertexFactory::Vertex)); pContext->SetIndexBuffer(m_pIndexBuffer, GPU_INDEX_FORMAT_UINT16, 0); pContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pContext->DrawIndexed(batchInfo.BaseIndex + batchInfo.FirstIndex, batchInfo.IndexCount, batchInfo.BaseVertex); } } BlockDrawTemplate::BlockRenderProxy::BlockRenderProxy(uint32 entityID, const BlockDrawTemplate *pDrawTemplate, uint32 startBatch, uint32 batchCount, const float4x4 &transformMatrix, uint32 tintColor) : RenderProxy(entityID), m_pDrawTemplate(pDrawTemplate), m_startBatch(startBatch), m_batchCount(batchCount), m_transformMatrix(transformMatrix), m_tintColor(tintColor), m_visible(true) { m_pDrawTemplate->AddRef(); UpdateBounds(); } BlockDrawTemplate::BlockRenderProxy::BlockRenderProxy(uint32 entityID, const BlockDrawTemplate *pDrawTemplate, BlockWorldBlockType blockType, const float4x4 &transformMatrix, uint32 tintColor) : RenderProxy(entityID), m_pDrawTemplate(pDrawTemplate), m_transformMatrix(transformMatrix), m_tintColor(tintColor), m_visible(true) { if (!pDrawTemplate->GetBatchRangeForBlock(blockType, &m_startBatch, &m_batchCount)) m_startBatch = m_batchCount = 0; m_pDrawTemplate->AddRef(); UpdateBounds(); } BlockDrawTemplate::BlockRenderProxy::~BlockRenderProxy() { m_pDrawTemplate->Release(); } void BlockDrawTemplate::BlockRenderProxy::SetBlockType(BlockWorldBlockType blockType) { uint32 startBatch, batchCount; if (!m_pDrawTemplate->GetBatchRangeForBlock(blockType, &startBatch, &batchCount)) startBatch = batchCount = 0; ReferenceCountedHolder<BlockRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, startBatch, batchCount]() { pThis->m_startBatch = startBatch; pThis->m_batchCount = batchCount; pThis->UpdateBounds(); }); } void BlockDrawTemplate::BlockRenderProxy::SetTransform(const float4x4 &transformMatrix) { ReferenceCountedHolder<BlockRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, transformMatrix]() { pThis->m_transformMatrix = transformMatrix; pThis->UpdateBounds(); }); } void BlockDrawTemplate::BlockRenderProxy::SetTintColor(uint32 tintColor) { ReferenceCountedHolder<BlockRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, tintColor]() { pThis->m_tintColor = tintColor; }); } void BlockDrawTemplate::BlockRenderProxy::SetVisible(bool visible) { ReferenceCountedHolder<BlockRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, visible]() { pThis->m_visible = visible; }); } void BlockDrawTemplate::BlockRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // not visible? if (!m_visible) return; // add batches uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (m_tintColor != 0) { // tinted can't cast shadows.. it looks weird :S wantedRenderPasses |= RENDER_PASS_TINT; wantedRenderPasses &= ~(RENDER_PASS_SHADOW_MAP); } // fix up passes wantedRenderPasses &= pRenderQueue->GetAcceptingRenderPassMask(); if (wantedRenderPasses == 0) return; // get batches for (uint32 batchAdd = 0; batchAdd < m_batchCount; batchAdd++) { uint32 batchIndex = m_startBatch + batchAdd; const Batch &batchInfo = m_pDrawTemplate->m_batches[batchIndex]; // get view distance float viewDistance = pCamera->CalculateDepthToBox(GetBoundingBox()); if (viewDistance > pCamera->GetObjectCullDistance()) continue; // get pass mask uint32 renderPassMask = batchInfo.pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { // create queue entry for base layer RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; // add local or mesh vertex factory if (batchInfo.pMesh != nullptr) { queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); queueEntry.VertexFactoryFlags = batchInfo.pMesh->GetVertexFactoryFlags(); } else { queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory); queueEntry.VertexFactoryFlags = 0; } // remaining fields queueEntry.pMaterial = batchInfo.pMaterial; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.RenderPassMask = renderPassMask; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = m_tintColor; queueEntry.UserData[0] = batchIndex; queueEntry.Layer = queueEntry.pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } void BlockDrawTemplate::BlockRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { const Batch &batchInfo = m_pDrawTemplate->m_batches[pQueueEntry->UserData[0]]; if (batchInfo.pMesh != nullptr) { const StaticMesh::LOD *pMeshLOD = batchInfo.pMesh->GetLOD(0); if (!pMeshLOD->CreateGPUResources()) return; // bind the mesh buffers pMeshLOD->GetVertexBuffers()->BindBuffers(pCommandList); pCommandList->SetIndexBuffer(pMeshLOD->GetIndexBuffer(), pMeshLOD->GetIndexFormat(), 0); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // bit of a hack, we just fudge the world matrix to push the mesh to the right location.. float scale = batchInfo.pBlockType->MeshShapeSettings.Scale; float4x4 worldMatrixOffset(scale, 0.0f, 0.0f, 0.5f, 0.0f, scale, 0.0f, 0.5f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_transformMatrix * worldMatrixOffset, true); } else { pCommandList->SetVertexBuffer(0, m_pDrawTemplate->m_pVertexBuffer, 0, sizeof(BlockWorldVertexFactory::Vertex)); pCommandList->SetIndexBuffer(m_pDrawTemplate->m_pIndexBuffer, GPU_INDEX_FORMAT_UINT16, 0); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_transformMatrix, true); } } void BlockDrawTemplate::BlockRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { const Batch &batchInfo = m_pDrawTemplate->m_batches[pQueueEntry->UserData[0]]; pCommandList->DrawIndexed(batchInfo.BaseIndex + batchInfo.FirstIndex, batchInfo.IndexCount, batchInfo.BaseVertex); } void BlockDrawTemplate::BlockRenderProxy::UpdateBounds() { AABox cubeBox(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); AABox transformedBox(cubeBox.GetTransformed(m_transformMatrix)); SetBounds(transformedBox, Sphere::FromAABox(transformedBox)); } BlockDrawTemplate::BlockRenderProxy *BlockDrawTemplate::CreateBlockRenderProxy(BlockWorldBlockType blockType, uint32 entityID, const float4x4 &transformMatrix, uint32 tintColor /* = 0 */) const { uint32 startBatch, batchCount; if (!GetBatchRangeForBlock(blockType, &startBatch, &batchCount)) return nullptr; return new BlockRenderProxy(entityID, this, startBatch, batchCount, transformMatrix, tintColor); } <file_sep>/DemoGame/Source/DemoGame/DrawCallStressDemo.h #pragma once #include "DemoGame/BaseDemoWorldGameState.h" #include "GameFramework/DirectionalLightEntity.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Engine/StaticMesh.h" class DrawCallStressDemo : public BaseDemoWorldGameState { public: DrawCallStressDemo(DemoGame *pDemoGame); virtual ~DrawCallStressDemo(); virtual bool Initialize() override final; virtual void Shutdown() override final; protected: virtual bool OnWorldCreated(World *pWorld) override final; virtual void OnWorldDeleted(World *pWorld) override final; virtual void DrawOverlays(float deltaTime) override final; virtual void DrawUI(float deltaTime) override final; virtual bool OnWindowEvent(const union SDL_Event *event) override final; virtual void OnMainThreadTick(float deltaTime) override final; private: void CreateObjects(uint32 count, bool useInstancing, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); DirectionalLightEntity *m_pSunLightEntity; float3 m_sunLightRotation; const StaticMesh *m_pMeshToRender; PODArray<StaticMeshRenderProxy *> m_meshProxies; uint32 m_newObjectCount; }; <file_sep>/Engine/Source/Core/ObjectSerializer.cpp #include "Core/PrecompiledHeader.h" #include "Core/ObjectSerializer.h" #include "Core/ClassTableDataFormat.h" #include "YBaseLib/StringConverter.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Quaternion.h" #include "MathLib/Transform.h" #include "MathLib/StringConverters.h" bool ObjectSerializer::SerializePropertyValueString(PROPERTY_TYPE propertyType, const char *propertyValueString, ByteStream *pOutputStream, uint32 *pWrittenBytes) { if (propertyType == PROPERTY_TYPE_STRING) { // Write out the structure individually uint32 stringLength = Y_strlen(propertyValueString); if (pWrittenBytes != nullptr) *pWrittenBytes = sizeof(uint32) + stringLength; return (pOutputStream->Write2(&stringLength, sizeof(stringLength)) && pOutputStream->Write2(propertyValueString, stringLength)); } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte tempBuffer[4 + 32]; DF_SERIALIZED_OBJECT_PROPERTY *propData = reinterpret_cast<DF_SERIALIZED_OBJECT_PROPERTY *>(tempBuffer); // Un-stringize based on type. switch (propertyType) { case PROPERTY_TYPE_BOOL: { bool value = StringConverter::StringToBool(propertyValueString); propData->DataSize = 1; propData->Data[0] = (value ? 1 : 0); } break; case PROPERTY_TYPE_UINT: { uint32 value = StringConverter::StringToUInt32(propertyValueString); uint32 *dest = reinterpret_cast<uint32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_INT: { int32 value = StringConverter::StringToInt32(propertyValueString); int32 *dest = reinterpret_cast<int32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_INT2: { Vector2i value(StringConverter::StringToVector2i(propertyValueString)); DF_STRUCT_INT2 *dest = reinterpret_cast<DF_STRUCT_INT2 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; } break; case PROPERTY_TYPE_INT3: { Vector3i value(StringConverter::StringToVector3i(propertyValueString)); DF_STRUCT_INT3 *dest = reinterpret_cast<DF_STRUCT_INT3 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; } break; case PROPERTY_TYPE_INT4: { Vector4i value(StringConverter::StringToVector4i(propertyValueString)); DF_STRUCT_INT4 *dest = reinterpret_cast<DF_STRUCT_INT4 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_FLOAT: { float value = StringConverter::StringToFloat(propertyValueString); float *dest = reinterpret_cast<float *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_FLOAT2: { Vector2f value(StringConverter::StringToVector2f(propertyValueString)); DF_STRUCT_FLOAT2 *dest = reinterpret_cast<DF_STRUCT_FLOAT2 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; } break; case PROPERTY_TYPE_FLOAT3: { Vector3f value(StringConverter::StringToVector3f(propertyValueString)); DF_STRUCT_FLOAT3 *dest = reinterpret_cast<DF_STRUCT_FLOAT3 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; } break; case PROPERTY_TYPE_FLOAT4: { Vector4f value(StringConverter::StringToVector4f(propertyValueString)); DF_STRUCT_FLOAT4 *dest = reinterpret_cast<DF_STRUCT_FLOAT4 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_QUATERNION: { Quaternion value(StringConverter::StringToQuaternion(propertyValueString)); DF_STRUCT_QUATERNION *dest = reinterpret_cast<DF_STRUCT_QUATERNION *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_TRANSFORM: { Transform value(StringConverter::StringToTranform(propertyValueString)); DF_STRUCT_TRANSFORM *dest = reinterpret_cast<DF_STRUCT_TRANSFORM *>(propData->Data); propData->DataSize = sizeof(*dest); dest->Position.x = value.GetPosition().x; dest->Position.y = value.GetPosition().y; dest->Position.z = value.GetPosition().z; dest->Rotation.x = value.GetRotation().x; dest->Rotation.y = value.GetRotation().y; dest->Rotation.z = value.GetRotation().z; dest->Rotation.w = value.GetRotation().w; dest->Scale.x = value.GetScale().x; dest->Scale.y = value.GetScale().y; dest->Scale.z = value.GetScale().z; } break; case PROPERTY_TYPE_COLOR: { uint32 value = StringConverter::StringToColor(propertyValueString); uint32 *dest = reinterpret_cast<uint32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; default: UnreachableCode(); break; } // Write to the stream if (pWrittenBytes != nullptr) *pWrittenBytes = sizeof(DF_SERIALIZED_OBJECT_PROPERTY) + propData->DataSize; DebugAssert(propData->DataSize < (sizeof(tempBuffer) - sizeof(DF_SERIALIZED_OBJECT_PROPERTY))); return pOutputStream->Write2(tempBuffer, sizeof(DF_SERIALIZED_OBJECT_PROPERTY) + propData->DataSize); } } <file_sep>/DemoGame/Source/DemoGame/BaseDemoWorldGameState.h #pragma once #include "DemoGame/DemoGame.h" #include "DemoGame/DemoCamera.h" #include "DemoGame/BaseDemoGameState.h" class BaseDemoWorldGameState : public BaseDemoGameState { public: BaseDemoWorldGameState(DemoGame *pDemoGame); virtual ~BaseDemoWorldGameState(); // initialization virtual bool Initialize(); // shutdown virtual void Shutdown(); // public events virtual bool CreateGPUResources(); virtual void ReleaseGPUResources(); protected: virtual bool OnWorldCreated(World *pWorld); virtual void OnWorldDeleted(World *pWorld); virtual void DrawOverlays(float deltaTime) override; virtual void DrawUI(float deltaTime) override; virtual void OnUIToggled(bool enabled) override; // implemented events virtual void OnSwitchedIn() override; virtual void OnSwitchedOut() override; virtual void OnBeforeDelete() override; virtual void OnWindowResized(uint32 width, uint32 height) override; virtual void OnWindowFocusGained() override; virtual void OnWindowFocusLost() override; virtual bool OnWindowEvent(const union SDL_Event *event) override; virtual void OnMainThreadPreFrame(float deltaTime) override; virtual void OnMainThreadBeginFrame(float deltaTime) override; virtual void OnMainThreadAsyncTick(float deltaTime) override; virtual void OnMainThreadTick(float deltaTime) override; virtual void OnMainThreadEndFrame(float deltaTime) override; virtual void OnRenderThreadPreFrame(float deltaTime) override; virtual void OnRenderThreadBeginFrame(float deltaTime) override; virtual void OnRenderThreadDraw(float deltaTime) override; virtual void OnRenderThreadEndFrame(float deltaTime) override; protected: // helper function for creating dynamic world bool CreateDynamicWorld(); // world pointer, set by derived classes World *m_pWorld; // camera DemoCamera m_camera; // ---- render thread ---- WorldRenderer::ViewParameters m_viewParameters; private: bool m_dynamicWorldFlag; }; <file_sep>/Engine/Source/Core/ImageCodec.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/CString.h" namespace ImageCodecEncoderOptions { const char *JPEG_QUALITY_LEVEL = "JPEG_QUALITYLEVEL"; const char *PNG_COMPRESSION_LEVEL = "PNG_COMPRESSION_LEVEL"; } namespace ImageCodecDecoderOptions { } // functions for retrieving interfaces extern ImageCodec *__GetImageCodecDevIL(); extern ImageCodec *__GetImageCodecFreeImage(); //extern ImageCodec *__GetImageCodecJPEG(); //extern ImageCodec *__GetImageCodecDDS(); //extern ImageCodec *__GetImageCodecBMP(); ImageCodec *ImageCodec::GetImageCodecForFileName(const char *fileName) { // find the extension const char *pExtension = Y_strrchr(fileName, '.'); if (pExtension == NULL) //return __GetImageCodecDevIL(); return __GetImageCodecFreeImage(); pExtension++; // jpeg // if (Y_stricmp(pExtension, "jpg") == 0 || Y_stricmp(pExtension, "jpeg") == 0) // return __GetImageCodecJPEG(); // else if (Y_stricmp(pExtension, "dds") == 0) // return __GetImageCodecDDS(); // else if (Y_stricmp(pExtension, "bmp") == 0) // return __GetImageCodecBMP(); //return __GetImageCodecDevIL(); return __GetImageCodecFreeImage(); } ImageCodec *ImageCodec::GetImageCodecForStream(const char *fileName, ByteStream *pStream) { return GetImageCodecForFileName(fileName); } <file_sep>/Engine/Source/BlockEngine/BlockWorldVertexFactory.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldVertexFactory.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/Renderer.h" #include "Core/MeshUtilties.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(BlockWorldVertexFactory) END_SHADER_COMPONENT_PARAMETERS() bool BlockWorldVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool BlockWorldVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/BlockWorldVertexFactory.hlsl"); return true; } uint32 BlockWorldVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { // create format declaration GPU_VERTEX_ELEMENT_DESC *pElementDesc = pElementsDesc; uint32 streamOffset; uint32 nElements = 0; uint32 nStreams = 0; // build stream 0 { streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // texcoord pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // color pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; // tangent pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_SNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; // normal pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_SNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; // end of stream nStreams++; } // done return nElements; } BlockWorldVertexFactory::Vertex::Vertex(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal) { Set(position, texcoord, color, tangent, binormal, normal); } BlockWorldVertexFactory::Vertex::Vertex(const float3 &position, const float3 &texcoord, uint32 color, uint32 packedTangentAndSign, uint32 packedNormal) { Set(position, texcoord, color, packedTangentAndSign, packedNormal); } void BlockWorldVertexFactory::Vertex::Set(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal) { Position = position; TexCoord = texcoord; Color = color; //Tangent = tangent; //Binormal = binormal; //Normal = normal; //float3x3 temp; //temp.SetRow(0, tangent); //temp.SetRow(1, binormal); //temp.SetRow(2, normal); //float det = temp.Determinant(); float3 orthonormalizedTangent; float binormalSign; MeshUtilites::OrthogonalizeTangent(tangent, binormal, normal, orthonormalizedTangent, binormalSign); //TangentAndSign = PixelFormatHelpers::ConvertFloat4ToRGBA(float4(tangent * 0.5f + 0.5f, Math::Sign(det) * 0.5f + 0.5f)); //TangentAndSign = PixelFormatHelpers::ConvertFloat4ToRGBA(float4(orthonormalizedTangent, Math::Sign(binormalSign)) * 0.5f + 0.5f); //Normal = PixelFormatHelpers::ConvertFloat4ToRGBA(float4(normal * 0.5f + 0.5f, 0.0f)); union { uint32 asUInt32; int8 asInt8[4]; } converter; converter.asInt8[0] = (int8)Math::Clamp(tangent.x * 127.0f, -127.0f, 127.0f); converter.asInt8[1] = (int8)Math::Clamp(tangent.y * 127.0f, -127.0f, 127.0f); converter.asInt8[2] = (int8)Math::Clamp(tangent.z * 127.0f, -127.0f, 127.0f); converter.asInt8[3] = (int8)Math::Clamp(binormalSign * 127.0f, -127.0f, 127.0f); TangentAndSign = converter.asUInt32; converter.asInt8[0] = (int8)Math::Clamp(normal.x * 127.0f, -127.0f, 127.0f); converter.asInt8[1] = (int8)Math::Clamp(normal.y * 127.0f, -127.0f, 127.0f); converter.asInt8[2] = (int8)Math::Clamp(normal.z * 127.0f, -127.0f, 127.0f); converter.asInt8[3] = (int8)0; Normal = converter.asUInt32; } void BlockWorldVertexFactory::Vertex::Set(const float3 &position, const float3 &texcoord, uint32 color, uint32 packedTangentAndSign, uint32 packedNormal) { Position = position; TexCoord = texcoord; Color = color; TangentAndSign = packedTangentAndSign; Normal = packedNormal; } <file_sep>/Engine/Source/Engine/ScriptTypes.h #pragma once #include "Engine/Common.h" // Reference type typedef int ScriptReferenceType; const ScriptReferenceType INVALID_SCRIPT_REFERENCE = (ScriptReferenceType)-1; // Userdata tag type typedef unsigned int ScriptUserDataTagType; // Other defines const float DEFAULT_SCRIPT_TIMEOUT = 60.0f; // Native function type typedef int(*ScriptNativeFunctionType)(struct lua_State *); // Call results enum ScriptCallResult { ScriptCallResult_Success, // Normal success error code ScriptCallResult_Yielded, // Script has yielded execution and can be resumed later ScriptCallResult_ParseError, // Parse error encountered when compiling the script ScriptCallResult_RuntimeError, // Generic error encountered during execution ScriptCallResult_NotInThread, // Script attempted to yield, but the call was not invoked in a coroutine thread ScriptCallResult_MethodNotFound, // Table call was issued, but the method was not found in the method table ScriptCallResult_NoObject, // A method call was attempted on a non-object }; // Script thread timeout actions enum ScriptThreadTimeoutAction { ScriptThreadTimeoutAction_Abort, // Abort script execution of the thread when the timeout is reached. ScriptThreadTimeoutAction_Resume, // Resume script execution of the thread when the timeout is reached. ScriptThreadTimeoutAction_ReturnNil, // Resume script execution, returning nil when the timeout is reached. ScriptThreadTimeoutAction_Count, }; // call result -> string namespace NameTables { Y_Declare_NameTable(ScriptCallResults); Y_Declare_NameTable(ScriptThreadTimeoutActions); }; // mapping entity functions -> proxy functions // todo: cached list of available entity methods? struct SCRIPT_FUNCTION_TABLE_ENTRY { const char *FunctionName; ScriptNativeFunctionType FunctionPointer; }; // script userdata tags enum ScriptUserDataTag { ScriptUserDataTag_None, ScriptUserDataTag_ScriptObject, ScriptUserDataTag_Count, }; // Forward declarations of script classes. class ScriptManager; class ScriptThread; class ScriptObject; <file_sep>/Engine/Source/Engine/TerrainTypes.h #pragma once #include "Engine/Common.h" enum TERRAIN_RENDERER_TYPE { TERRAIN_RENDERER_TYPE_NULL, TERRAIN_RENDERER_TYPE_CDLOD, TERRAIN_RENDERER_TYPE_COUNT, }; enum TERRAIN_HEIGHT_STORAGE_FORMAT { TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8, TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, TERRAIN_HEIGHT_STORAGE_FORMAT_COUNT, }; namespace NameTables { Y_Declare_NameTable(TerrainRendererType); Y_Declare_NameTable(TerrainHeightStorageFormat); } #define TERRAIN_MAX_LAYERS (64) #define TERRAIN_MAX_STORAGE_LODS (4) #define TERRAIN_MAX_RENDER_LODS (10) struct TerrainParameters { TerrainParameters() {} TerrainParameters(TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat, int32 minHeight, int32 maxHeight, int32 baseHeight, uint32 scale, uint32 sectionSize, uint32 lodCount) : HeightStorageFormat(heightStorageFormat), MinHeight(minHeight), MaxHeight(maxHeight), BaseHeight(baseHeight), Scale(scale), SectionSize(sectionSize), LODCount(lodCount) {} // Height storage format TERRAIN_HEIGHT_STORAGE_FORMAT HeightStorageFormat; // Required for integer height formats, minimum/maximum heights int32 MinHeight; int32 MaxHeight; // Default [base] height int32 BaseHeight; // Scale of the terrain, i.e. number of world units (meters) per heightmap point uint32 Scale; // Size of each terrain page in quads uint32 SectionSize; // Number of levels of details at the highest storage level that is possible to render // Each storage level will decrement this number by one when that level is loaded uint32 LODCount; }; namespace TerrainUtilities { // validate terrain parameters bool IsValidParameters(const TerrainParameters *pParameters); // get the size of each point's height data uint32 GetHeightElementStorageSize(TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat); // get the corresponding pixel format for a height map storage format PIXEL_FORMAT GetHeightStoragePixelFormat(TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat); // helper function to calculate tile bounds AABox CalculateSectionBoundingBox(const TerrainParameters *pTerrainParameters, int32 sectionX, int32 sectionY); // helper function to calculate the section of the specified global indices int2 CalculateSectionForPoint(const TerrainParameters *pTerrainParameters, int32 globalX, int32 globalY); // helper function to calculate the section of a specified position int2 CalculateSectionForPosition(const TerrainParameters *pTerrainParameters, const float3 &position); // helper function to calculate the section and indexed position of the specified global indices void CalculateSectionAndOffsetForPoint(const TerrainParameters *pTerrainParameters, int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, int32 globalX, int32 globalY); // helper function to calculate the section and index position closest to the specified position void CalculateSectionAndOffsetForPosition(const TerrainParameters *pTerrainParameters, int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, const float3 &position); // helper function to calculate a global point from a position int2 CalculatePointForPosition(const TerrainParameters *pTerrainParameters, const float3 &position); // helper function for going from point to position float3 CalculatePositionForPoint(const TerrainParameters *pTerrainParameters, int32 globalX, int32 globalY); // helper function to calculate global coordinates from the specified section and offsets void CalculatePointForSectionAndOffset(const TerrainParameters *pTerrainParameters, int32 *pGlobalX, int32 *pGlobalY, int32 sectionX, int32 sectionY, uint32 offsetX, uint32 offsetY); } <file_sep>/Engine/Source/Renderer/Shaders/MobileShaders.h #pragma once #include "Renderer/ShaderComponent.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" class MobileBasePassShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(MobileBasePassShader, ShaderComponent); public: enum FLAGS { WITH_EMISSIVE = (1 << 0), WITH_LIGHTMAP = (1 << 1), }; public: MobileBasePassShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class MobileDirectionalLightShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(MobileDirectionalLightShader, ShaderComponent); public: enum FLAGS { WITH_SHADOW_MAP = (1 << 0), SHADOW_FILTER_1X1 = (1 << 3), SHADOW_FILTER_3X3 = (1 << 4), SHADOW_FILTER_5X5 = (1 << 5), SHADOW_BITS_MASK = WITH_SHADOW_MAP | SHADOW_FILTER_1X1 | SHADOW_FILTER_3X3 | SHADOW_FILTER_5X5 }; public: MobileDirectionalLightShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } // get flags based on cvar values static uint32 CalculateFlags(bool enableShadows, RENDERER_SHADOW_FILTER shadowFilter); // light params static void SetLightParameters(GPUContext *pContext, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const SSMShadowMapRenderer::ShadowMapData *pShadowMapData); static void SetProgramParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight, const SSMShadowMapRenderer::ShadowMapData *pShadowMapData); // common functions static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class MobileFinalCompositeShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(MobileFinalCompositeShader, ShaderComponent); public: MobileFinalCompositeShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetInputParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pSceneTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/Renderer/WorldRenderers/CompositingWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/CompositingWorldRenderer.h" #include "Renderer/ShaderComponent.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/Renderer.h" #include "Renderer/RenderProxy.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderProgramSelector.h" #include "Engine/Camera.h" #include "Engine/EngineCVars.h" #include "Engine/Material.h" #include "Engine/Profiling.h" Log_SetChannel(CompositingWorldRenderer); class GaussianBlurShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(GaussianBlurShader, ShaderComponent); public: GaussianBlurShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pProgram, GPUTexture2D *pSourceTexture, const float2 &blurDirection, float blurSigma); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; DEFINE_SHADER_COMPONENT_INFO(GaussianBlurShader); BEGIN_SHADER_COMPONENT_PARAMETERS(GaussianBlurShader) DEFINE_SHADER_COMPONENT_PARAMETER("SourceTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("BlurDirection", SHADER_PARAMETER_TYPE_FLOAT2) DEFINE_SHADER_COMPONENT_PARAMETER("BlurSigma", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_COMPONENT_PARAMETERS() void GaussianBlurShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pProgram, GPUTexture2D *pSourceTexture, const float2 &blurDirection, float blurSigma) { pProgram->SetBaseShaderParameterTexture(pCommandList, 0, pSourceTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); pProgram->SetBaseShaderParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT2, &blurDirection); pProgram->SetBaseShaderParameterValue(pCommandList, 2, SHADER_PARAMETER_TYPE_FLOAT, &blurSigma); } bool GaussianBlurShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == nullptr || pMaterialShader == nullptr) return false; return true; } bool GaussianBlurShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/GaussianBlurPixelShader.hlsl", "Main"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ExtractLuminanceShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(ExtractLuminanceShader, ShaderComponent); public: ExtractLuminanceShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pSceneTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; DEFINE_SHADER_COMPONENT_INFO(ExtractLuminanceShader); BEGIN_SHADER_COMPONENT_PARAMETERS(ExtractLuminanceShader) DEFINE_SHADER_COMPONENT_PARAMETER("SceneTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void ExtractLuminanceShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pSceneTexture) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pSceneTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); } bool ExtractLuminanceShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool ExtractLuminanceShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/ExtractLuminancePixelShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class BloomShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(BloomShader, ShaderComponent); public: BloomShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pSceneTexture, float bloomThreshold = 0.3f); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; DEFINE_SHADER_COMPONENT_INFO(BloomShader); BEGIN_SHADER_COMPONENT_PARAMETERS(BloomShader) DEFINE_SHADER_COMPONENT_PARAMETER("HDRTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("BloomThreshold", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_COMPONENT_PARAMETERS() void BloomShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pSceneTexture, float bloomThreshold /* = 0.3f */) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pSceneTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT, &bloomThreshold); } bool BloomShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool BloomShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/BloomPixelShader.hlsl", "Main"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ToneMapShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(ToneMapShader, ShaderComponent); public: ToneMapShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetInputParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pHDRTexture); static void SetToneMapParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pAverageLuminanceTexture, float whiteLevel = 4.0f, float luminanceSaturation = 1.0f, bool useManualExposure = false, float manualExposure = 1.0f, float maximumExposure = 4.0f); static void SetBloomParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pBloomTexture, bool enableBloom = true, float bloomMagnitude = 1.0f); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; DEFINE_SHADER_COMPONENT_INFO(ToneMapShader); BEGIN_SHADER_COMPONENT_PARAMETERS(ToneMapShader) DEFINE_SHADER_COMPONENT_PARAMETER("HDRTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("AverageLuminanceTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("AverageLuminanceTextureMip", SHADER_PARAMETER_TYPE_UINT) DEFINE_SHADER_COMPONENT_PARAMETER("WhiteLevel", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("LuminanceSaturation", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("ManualExposure", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("MaximumExposure", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("UseManualExposure", SHADER_PARAMETER_TYPE_BOOL) DEFINE_SHADER_COMPONENT_PARAMETER("BloomTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("BloomMagnitude", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("EnableBloom", SHADER_PARAMETER_TYPE_BOOL) END_SHADER_COMPONENT_PARAMETERS() void ToneMapShader::SetInputParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pHDRTexture) { pShaderProgram->SetBaseShaderParameterTexture(pContext, 0, pHDRTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); } void ToneMapShader::SetToneMapParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pAverageLuminanceTexture, float whiteLevel /* = 4.0f */, float luminanceSaturation /* = 1.0f */, bool useManualExposure /* = false */, float manualExposure /* = 1.0f */, float maximumExposure /* = 4.0f */) { uint32 avgLuminanceMipLevel = pAverageLuminanceTexture->GetDesc()->MipLevels - 1; uint32 useManualExposureValue = (uint32)useManualExposure; pShaderProgram->SetBaseShaderParameterTexture(pContext, 1, pAverageLuminanceTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); pShaderProgram->SetBaseShaderParameterValue(pContext, 2, SHADER_PARAMETER_TYPE_UINT, &avgLuminanceMipLevel); pShaderProgram->SetBaseShaderParameterValue(pContext, 3, SHADER_PARAMETER_TYPE_FLOAT, &whiteLevel); pShaderProgram->SetBaseShaderParameterValue(pContext, 4, SHADER_PARAMETER_TYPE_FLOAT, &luminanceSaturation); pShaderProgram->SetBaseShaderParameterValue(pContext, 5, SHADER_PARAMETER_TYPE_FLOAT, &manualExposure); pShaderProgram->SetBaseShaderParameterValue(pContext, 6, SHADER_PARAMETER_TYPE_FLOAT, &maximumExposure); pShaderProgram->SetBaseShaderParameterValue(pContext, 7, SHADER_PARAMETER_TYPE_BOOL, &useManualExposureValue); } void ToneMapShader::SetBloomParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pBloomTexture, bool enableBloom /* = true */, float bloomMagnitude /* = 1.0f */) { uint32 enableBloomValue = (uint32)enableBloom; pShaderProgram->SetBaseShaderParameterTexture(pContext, 8, pBloomTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); pShaderProgram->SetBaseShaderParameterValue(pContext, 9, SHADER_PARAMETER_TYPE_FLOAT, &bloomMagnitude); pShaderProgram->SetBaseShaderParameterValue(pContext, 10, SHADER_PARAMETER_TYPE_BOOL, &enableBloomValue); } bool ToneMapShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool ToneMapShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/ToneMapShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CompositingWorldRenderer::CompositingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : WorldRenderer(pGPUContext, pOptions), m_pExtractLuminanceProgram(nullptr), m_pBloomProgram(nullptr), m_pToneMappingProgram(nullptr), m_pGaussianBlurProgram(nullptr) { } CompositingWorldRenderer::~CompositingWorldRenderer() { } bool CompositingWorldRenderer::Initialize() { if (!WorldRenderer::Initialize()) return false; // load programs if ((m_pExtractLuminanceProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(ExtractLuminanceShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr || (m_pBloomProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(BloomShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr || (m_pToneMappingProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(ToneMapShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr || (m_pGaussianBlurProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(GaussianBlurShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr) { return false; } return true; } void CompositingWorldRenderer::GetRenderStats(RenderStats *pRenderStats) const { WorldRenderer::GetRenderStats(pRenderStats); } void CompositingWorldRenderer::OnFrameComplete() { WorldRenderer::OnFrameComplete(); } void CompositingWorldRenderer::DrawDebugInfo(const Camera *pCamera) { WorldRenderer::DrawDebugInfo(pCamera); } void CompositingWorldRenderer::BlurTexture(GPUCommandList *pCommandList, GPUTexture2D *pBlurTexture, GPURenderTargetView *pBlurTextureRTV, float blurSigma /* = 0.8f */, bool restoreViewport /* = true */) { // request matching intermediate buffer IntermediateBuffer *pTempBuffer = RequestIntermediateBuffer(pBlurTexture->GetDesc()->Width, pBlurTexture->GetDesc()->Height, pBlurTexture->GetDesc()->Format, pBlurTexture->GetDesc()->MipLevels); if (pTempBuffer == nullptr) return; // save old viewport RENDERER_VIEWPORT oldViewport; if (restoreViewport) Y_memcpy(&oldViewport, pCommandList->GetViewport(), sizeof(oldViewport)); // setup common stuff pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); pCommandList->SetFullViewport(pBlurTexture); pCommandList->SetShaderProgram(m_pGaussianBlurProgram->GetGPUProgram()); // horizontal blur pCommandList->SetRenderTargets(1, &pTempBuffer->pRTV, nullptr); pCommandList->DiscardTargets(true, false, false); GaussianBlurShader::SetProgramParameters(pCommandList, m_pGaussianBlurProgram, pBlurTexture, float2::UnitX, blurSigma); g_pRenderer->DrawFullScreenQuad(pCommandList); // necessary since the textures will be swapped for inputs/outputs pCommandList->ClearState(false, false, false, true); // vertical blur GaussianBlurShader::SetProgramParameters(pCommandList, m_pGaussianBlurProgram, pTempBuffer->pTexture, float2::UnitY, blurSigma); pCommandList->SetRenderTargets(1, &pBlurTextureRTV, nullptr); pCommandList->DiscardTargets(true, false, false); g_pRenderer->DrawFullScreenQuad(pCommandList); // restore viewport if (restoreViewport) pCommandList->SetViewport(&oldViewport); // release int buffer ReleaseIntermediateBuffer(pTempBuffer); } void CompositingWorldRenderer::ApplyFinalCompositePostProcess(const ViewParameters *pViewParameters, GPUTexture2D *pSceneColorTexture, GPURenderTargetView *pOutputRTV) { MICROPROFILE_SCOPEI("CompositingWorldRenderer", "ApplyFinalCompositePostProcess", MICROPROFILE_COLOR(42, 20, 90)); // common setup m_pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); m_pGPUContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); m_pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); // create luminance texture IntermediateBuffer *pLuminanceBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, PIXEL_FORMAT_R16_FLOAT, Renderer::CalculateMipCount(m_options.RenderWidth, m_options.RenderHeight)); if (pLuminanceBuffer == nullptr) return; // run extract shader, generate mipmaps on luminance buffer if (!pViewParameters->EnableManualExposure) { MICROPROFILE_SCOPEI("CompositingWorldRenderer", "Generate Luminance Buffer", MICROPROFILE_COLOR(100, 100, 100)); m_pGPUContext->SetRenderTargets(1, &pLuminanceBuffer->pRTV, nullptr); m_pGPUContext->SetFullViewport(pLuminanceBuffer->pTexture); m_pGPUContext->SetShaderProgram(m_pExtractLuminanceProgram->GetGPUProgram()); ExtractLuminanceShader::SetProgramParameters(m_pGPUContext, m_pExtractLuminanceProgram, pSceneColorTexture); g_pRenderer->DrawFullScreenQuad(m_pGPUContext); m_pGPUContext->GenerateMips(pLuminanceBuffer->pTexture); m_pGPUContext->ClearState(true, false, false, true); } // bloom buffer IntermediateBuffer *pBloomBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, PIXEL_FORMAT_R8G8B8A8_UNORM, 1); if (pBloomBuffer == nullptr) return; // only fill bloom buffer when enabled if (pViewParameters->EnableBloom) { MICROPROFILE_SCOPEI("CompositingWorldRenderer", "Generate Bloom Buffer", MICROPROFILE_COLOR(100, 20, 20)); // generate bloom texture m_pGPUContext->SetRenderTargets(1, &pBloomBuffer->pRTV, nullptr); m_pGPUContext->SetFullViewport(pBloomBuffer->pTexture); m_pGPUContext->SetShaderProgram(m_pBloomProgram->GetGPUProgram()); BloomShader::SetProgramParameters(m_pGPUContext, m_pBloomProgram, pSceneColorTexture, pViewParameters->BloomThreshold); g_pRenderer->DrawFullScreenQuad(m_pGPUContext); m_pGPUContext->ClearState(true, false, false, true); // allocate downsampled buffers IntermediateBuffer *pDownsampledBloomBuffer2 = RequestIntermediateBuffer(pBloomBuffer->Width / 2, pBloomBuffer->Height / 2, pBloomBuffer->PixelFormat, pBloomBuffer->MipLevels); IntermediateBuffer *pDownsampledBloomBuffer4 = RequestIntermediateBuffer(pBloomBuffer->Width / 4, pBloomBuffer->Height / 4, pBloomBuffer->PixelFormat, pBloomBuffer->MipLevels); IntermediateBuffer *pDownsampledBloomBuffer8 = RequestIntermediateBuffer(pBloomBuffer->Width / 8, pBloomBuffer->Height / 8, pBloomBuffer->PixelFormat, pBloomBuffer->MipLevels); if (pDownsampledBloomBuffer2 == nullptr || pDownsampledBloomBuffer4 == nullptr || pDownsampledBloomBuffer8 == nullptr) { ReleaseIntermediateBuffer(pDownsampledBloomBuffer8); ReleaseIntermediateBuffer(pDownsampledBloomBuffer4); ReleaseIntermediateBuffer(pDownsampledBloomBuffer2); ReleaseIntermediateBuffer(pBloomBuffer); ReleaseIntermediateBuffer(pLuminanceBuffer); return; } // downsample to /8 ScaleTexture(m_pGPUContext, pBloomBuffer->pTexture, pDownsampledBloomBuffer2->pRTV, false, false); ScaleTexture(m_pGPUContext, pDownsampledBloomBuffer2->pTexture, pDownsampledBloomBuffer4->pRTV, false, false); ScaleTexture(m_pGPUContext, pDownsampledBloomBuffer4->pTexture, pDownsampledBloomBuffer8->pRTV, false, false); // run blur passes BlurTexture(m_pGPUContext, pDownsampledBloomBuffer8->pTexture, pDownsampledBloomBuffer8->pRTV, 0.8f, false); // upscale back to full size ScaleTexture(m_pGPUContext, pDownsampledBloomBuffer8->pTexture, pDownsampledBloomBuffer4->pRTV, false, false); ScaleTexture(m_pGPUContext, pDownsampledBloomBuffer4->pTexture, pDownsampledBloomBuffer2->pRTV, false, false); ScaleTexture(m_pGPUContext, pDownsampledBloomBuffer2->pTexture, pBloomBuffer->pRTV, false, false); // release temporary downsampling buffers ReleaseIntermediateBuffer(pDownsampledBloomBuffer8); ReleaseIntermediateBuffer(pDownsampledBloomBuffer4); ReleaseIntermediateBuffer(pDownsampledBloomBuffer2); } // run tonemapping shader, output to destination (this requires destination viewport) m_pGPUContext->SetRenderTargets(1, &pOutputRTV, nullptr); m_pGPUContext->SetShaderProgram(m_pToneMappingProgram->GetGPUProgram()); m_pGPUContext->SetViewport(&pViewParameters->Viewport); ToneMapShader::SetInputParameters(m_pGPUContext, m_pToneMappingProgram, pSceneColorTexture); ToneMapShader::SetToneMapParameters(m_pGPUContext, m_pToneMappingProgram, pLuminanceBuffer->pTexture, 4.0f, 1.0f, pViewParameters->EnableManualExposure, pViewParameters->ManualExposure, pViewParameters->MaximumExposure); ToneMapShader::SetBloomParameters(m_pGPUContext, m_pToneMappingProgram, pBloomBuffer->pTexture, pViewParameters->EnableBloom, pViewParameters->BloomMagnitude); g_pRenderer->DrawFullScreenQuad(m_pGPUContext); m_pGPUContext->ClearState(true, false, false, false); // todo: AddIntermediateBuffer for debugging AddDebugBufferView(pLuminanceBuffer, "Luminance", true); AddDebugBufferView(pBloomBuffer, "Bloom", true); } <file_sep>/Engine/Source/Engine/DynamicWorld.h #pragma once #include "Engine/World.h" #include "Engine/Entity.h" class DynamicWorld : public World { public: DynamicWorld(); virtual ~DynamicWorld(); virtual void AddBrush(Brush *pObject) override; virtual void RemoveBrush(Brush *pObject) override; virtual const Entity *GetEntityByID(uint32 EntityId) const override; virtual Entity *GetEntityByID(uint32 EntityId) override; virtual void AddEntity(Entity *pEntity) override; virtual void MoveEntity(Entity *pEntity) override; virtual void UpdateEntity(Entity *pEntity) override; virtual void RemoveEntity(Entity *pEntity) override; virtual void BeginFrame(float deltaTime) override; virtual void UpdateAsync(float deltaTime) override; virtual void Update(float deltaTime) override; virtual void EndFrame() override; private: // data we track for entiites struct EntityData { Entity *pEntity; uint32 EntityID; AABox BoundingBox; Sphere BoundingSphere; }; // array types typedef PODArray<Brush *> StaticObjectArray; typedef MemArray<EntityData> EntityDataArray; typedef PODArray<Entity *> EntityArray; // get object data for a specified entity EntityData *GetEntityData(const Entity *pEntity); // we could probably binary sort these with the uint32 id StaticObjectArray m_brushes; EntityDataArray m_entities; public: // Finds all entity in the world. template<typename T> void EnumerateEntities(T Callback) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0) Callback(m_entities[i].pEntity->Cast<Entity>()); } } template<typename T> void EnumerateEntities(T Callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0) Callback(m_entities[i].pEntity->Cast<Entity>()); } } // Finds objects inside the specified frustum. template<typename T> void EnumerateEntitiesInFrustum(const Frustum &frustum, T Callback) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && frustum.AABoxIntersection(m_entities[i].BoundingBox)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } template<typename T> void EnumerateEntitiesInFrustum(const Frustum &frustum, T Callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && frustum.AABoxIntersection(m_entities[i].BoundingBox)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } // Finds objects inside the specified axis-aligned box. template<typename T> void EnumerateEntitiesInAABox(const AABox &box, T Callback) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && box.AABoxIntersection(m_entities[i].BoundingBox)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } template<typename T> void EnumerateEntitiesInAABox(const AABox &box, T Callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && box.AABoxIntersection(m_entities[i].BoundingBox)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } // Finds objects inside the specified sphere. template<typename T> void EnumerateEntitiesInSphere(const Sphere &sphere, T Callback) { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && sphere.SphereIntersection(m_entities[i].BoundingSphere)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } template<typename T> void EnumerateEntitiesInSphere(const Sphere &sphere, T Callback) const { for (uint32 i = 0; i < m_entities.GetSize(); i++) { if (m_entities[i].EntityID != 0 && sphere.SphereIntersection(m_entities[i].BoundingSphere)) Callback(m_entities[i].pEntity->Cast<Entity>()); } } }; <file_sep>/Engine/Source/Renderer/RenderProxies/SpriteRenderProxy.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderProxy.h" class Texture2D; class Material; class SpriteRenderProxy : public RenderProxy { public: SpriteRenderProxy(uint32 entityId, const Texture2D *pTexture = nullptr, const float3 &position = float3::Zero); ~SpriteRenderProxy(); // update functions, can be called from game thread safely after adding to render world. void SetTexture(const Texture2D *pTexture); void SetPosition(const float3 &position); void SetSizeByTextureScale(float textureScale); void SetSizeByDimensions(float width, float height); void SetTintColor(bool enabled, uint32 color = 0); void SetVisibility(bool visible); void SetShadowFlags(uint32 shadowFlags); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual bool CreateDeviceResources() const override; virtual void ReleaseDeviceResources() const override; private: // real methods void RealSetTexture(const Texture2D *pTexture); void RealSetPosition(const float3 &position); void RealSetSizeByTextureScale(float textureScale); void RealSetSizeByDimensions(float width, float height); void RealSetTintColor(bool enabled, uint32 color = 0); void RealSetVisibility(bool visible); void RealSetShadowFlags(uint32 shadowFlags); // update bounds, call when setting a new transform. void UpdateBounds(); //void UpdateVertexBuffer(); // material that we are rendering with Material *m_pMaterial; // read/write from render thread. no access from game thread. bool m_visibility; const Texture2D *m_pTexture; float3 m_position; float m_width; float m_height; uint32 m_shadowFlags; bool m_tintEnabled; uint32 m_tintColor; // gpu resources, also owned by render thread. mutable bool m_bGPUResourcesCreated; //mutable GPUVertexArray *m_pVertexArray; }; <file_sep>/Engine/Source/ResourceCompiler/SkeletonGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/SkeletonGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/DataFormats.h" #include "Core/ChunkFileWriter.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(SkeletonGenerator); SkeletonGenerator::Bone::Bone(uint32 index, const char *name, Bone *pParent, const Transform &baseFrameTransform) : m_index(index), m_name(name), m_pParent(pParent), m_baseFrameTransform(baseFrameTransform) { } SkeletonGenerator::Bone::~Bone() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SkeletonGenerator::SkeletonGenerator() { } SkeletonGenerator::~SkeletonGenerator() { for (uint32 i = 0; i < m_bones.GetSize(); i++) delete m_bones[i]; } const SkeletonGenerator::Bone *SkeletonGenerator::GetBoneByName(const char *name) const { for (uint32 i = 0; i < m_bones.GetSize(); i++) { if (m_bones[i]->GetName().Compare(name)) return m_bones[i]; } return NULL; } SkeletonGenerator::Bone *SkeletonGenerator::GetBoneByName(const char *name) { for (uint32 i = 0; i < m_bones.GetSize(); i++) { if (m_bones[i]->GetName().Compare(name)) return m_bones[i]; } return NULL; } SkeletonGenerator::Bone *SkeletonGenerator::CreateBone(const char *name, Bone *pParent, const Transform &baseFrameTransform) { if (GetBoneByName(name) != NULL) return NULL; Bone *pBone = new Bone(m_bones.GetSize(), name, pParent, baseFrameTransform); m_bones.Add(pBone); // add to parent's children if (pParent != NULL) pParent->m_children.Add(pBone); return pBone; } bool SkeletonGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) return false; if (!xmlReader.SkipToElement("skeleton")) { xmlReader.PrintError("could not skip to skeleton element."); return false; } // process xml nodes for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 skeletalMeshSelection = xmlReader.Select("properties|bones"); if (skeletalMeshSelection < 0) return false; switch (skeletalMeshSelection) { // properties case 0: { if (!xmlReader.IsEmptyElement()) { if (!m_properties.LoadFromXML(xmlReader)) return false; if (!xmlReader.ExpectEndOfElementName("properties")) return false; } } break; // bones case 1: { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 bonesSelection = xmlReader.Select("bone"); if (bonesSelection < 0) return false; const char *boneNameStr = xmlReader.FetchAttribute("name"); const char *parentStr = xmlReader.FetchAttribute("parent"); const char *baseFramePositionStr = xmlReader.FetchAttribute("baseframe-position"); const char *baseFrameRotationStr = xmlReader.FetchAttribute("baseframe-rotation"); const char *baseFrameScaleStr = xmlReader.FetchAttribute("baseframe-scale"); if (boneNameStr == NULL || baseFramePositionStr == NULL || baseFrameRotationStr == NULL || baseFrameScaleStr == NULL) { xmlReader.PrintError("missing bone fields"); return false; } float3 baseFramePosition = StringConverter::StringToFloat3(baseFramePositionStr); Quaternion baseFrameRotation = StringConverter::StringToQuaternion(baseFrameRotationStr); float3 baseFrameScale = StringConverter::StringToFloat3(baseFrameScaleStr); Bone *pParentBone = NULL; if (parentStr != NULL && (pParentBone = GetBoneByName(parentStr)) == NULL) { xmlReader.PrintError("bone '%s' has nonexistant parent '%s'", boneNameStr, parentStr); return false; } Bone *pBone = new Bone(m_bones.GetSize(), boneNameStr, pParentBone, Transform(baseFramePosition, baseFrameRotation, baseFrameScale)); m_bones.Add(pBone); if (pParentBone != NULL) pParentBone->m_children.Add(pBone); if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "bones") == 0); break; } else { xmlReader.PrintError("parse error"); break; } } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "skeleton") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } return true; } bool SkeletonGenerator::SaveToXML(ByteStream *pStream) const { XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("skeleton"); { // write properties xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); // write bones xmlWriter.StartElement("bones"); { for (uint32 i = 0; i < m_bones.GetSize(); i++) { const Bone *pBone = m_bones[i]; if (pBone == NULL) continue; xmlWriter.StartElement("bone"); { xmlWriter.WriteAttribute("name", pBone->GetName()); if (pBone->GetParent() != NULL) xmlWriter.WriteAttribute("parent", pBone->GetParent()->GetName()); xmlWriter.WriteAttribute("baseframe-position", StringConverter::Float3ToString(pBone->GetBaseFrameTransform().GetPosition())); xmlWriter.WriteAttribute("baseframe-rotation", StringConverter::QuaternionToString(pBone->GetBaseFrameTransform().GetRotation())); xmlWriter.WriteAttribute("baseframe-scale", StringConverter::Float3ToString(pBone->GetBaseFrameTransform().GetScale())); } xmlWriter.EndElement(); // </bone> } } xmlWriter.EndElement(); // </bones> } xmlWriter.EndElement(); // </skeleton> return (!xmlWriter.InErrorState() && !pStream->InErrorState()); } // we use recursion-based transform concatenation to preserve as much floating-point accuracy as possible // static Transform CalculateAbsoluteBoneBaseFrameTransform(const SkeletonGenerator::Bone *pBone) // { // if (pBone->GetParent() == nullptr) // return pBone->GetBaseFrameTransform(); // // return Transform::ConcatenateTransforms(CalculateAbsoluteBoneBaseFrameTransform(pBone->GetParent()), pBone->GetBaseFrameTransform()); // } static float4x4 CalculateAbsoluteBoneBaseFrameTransform(const SkeletonGenerator::Bone *pBone) { if (pBone->GetParent() == nullptr) return pBone->GetBaseFrameTransform().GetTransformMatrix4x4(); else return CalculateAbsoluteBoneBaseFrameTransform(pBone->GetParent()) * pBone->GetBaseFrameTransform().GetTransformMatrix4x4(); } bool SkeletonGenerator::Compile(ByteStream *pStream) const { // build header DF_SKELETON_HEADER fileHeader; fileHeader.Magic = DF_SKELETON_HEADER_MAGIC; fileHeader.HeaderSize = sizeof(fileHeader); fileHeader.BoneCount = 0; fileHeader.BonesOffset = 0; // write header uint64 headerOffset = pStream->GetPosition(); pStream->Write2(&fileHeader, sizeof(fileHeader)); // write bones { // initialize an array for storing child bones uint32 *pChildBones = (uint32 *)alloca(sizeof(uint32) * m_bones.GetSize()); uint32 nChildBones = 0; // set start offset fileHeader.BonesOffset = (uint32)(pStream->GetPosition() - headerOffset); for (uint32 boneIndex = 0; boneIndex < m_bones.GetSize(); boneIndex++) { const Bone *pBone = m_bones[boneIndex]; // find child bones nChildBones = 0; for (uint32 subBoneIndex = 0; subBoneIndex < m_bones.GetSize(); subBoneIndex++) { if (m_bones[subBoneIndex]->GetParent() == pBone) pChildBones[nChildBones++] = subBoneIndex; } DF_SKELETON_BONE fileBone; fileBone.BoneSize = sizeof(fileBone) + pBone->GetName().GetLength() + (sizeof(uint32) * nChildBones); fileBone.BoneNameLength = pBone->GetName().GetLength(); fileBone.ParentBoneIndex = (pBone->GetParent() != nullptr) ? pBone->GetParent()->GetIndex() : 0xFFFFFFFF; fileBone.ChildBoneCount = nChildBones; // store relative transform const Transform &relativeBaseFrameTransform = pBone->GetBaseFrameTransform(); relativeBaseFrameTransform.GetPosition().Store(fileBone.RelativeBaseFrameTransformPosition); relativeBaseFrameTransform.GetRotation().Store(fileBone.RelativeBaseFrameTransformRotation); relativeBaseFrameTransform.GetScale().Store(fileBone.RelativeBaseFrameTransformScale); // // calculate absolute transform // Transform absoluteBaseFrameTransform(CalculateAbsoluteBoneBaseFrameTransform(pBone)); // absoluteBaseFrameTransform.GetPosition().Store(fileBone.AbsoluteBaseFrameTransformPosition); // absoluteBaseFrameTransform.GetRotation().Store(fileBone.AbsoluteBaseFrameTransformRotation); // absoluteBaseFrameTransform.GetScale().Store(fileBone.AbsoluteBaseFrameTransformScale); // calculate absolute transform float4x4 absoluteBaseFrameTransformMatrix(CalculateAbsoluteBoneBaseFrameTransform(pBone)); Transform absoluteBaseFrameTransform(absoluteBaseFrameTransformMatrix); absoluteBaseFrameTransform.GetPosition().Store(fileBone.AbsoluteBaseFrameTransformPosition); absoluteBaseFrameTransform.GetRotation().Store(fileBone.AbsoluteBaseFrameTransformRotation); absoluteBaseFrameTransform.GetScale().Store(fileBone.AbsoluteBaseFrameTransformScale); // write bone header, and bone name if (!pStream->Write2(&fileBone, sizeof(fileBone)) || !pStream->Write2(pBone->GetName().GetCharArray(), pBone->GetName().GetLength())) return false; // write child bones if (nChildBones > 0 && !pStream->Write2(pChildBones, sizeof(uint32) * nChildBones)) return false; // increment bone count fileHeader.BoneCount++; } } // rewrite the file header uint64 endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(headerOffset) || !pStream->Write2(&fileHeader, sizeof(fileHeader)) || !pStream->SeekAbsolute(endOffset)) return false; // ok return true; } // Interface BinaryBlob *ResourceCompiler::CompileSkeleton(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.skl.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileSkeleton: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); SkeletonGenerator *pGenerator = new SkeletonGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Engine/Texture.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Texture.h" #include "Engine/DataFormats.h" #include "Renderer/Renderer.h" #include "Core/Image.h" Log_SetChannel(Texture); Y_Define_NameTable(NameTables::TextureType) Y_NameTable_Entry("1D", TEXTURE_TYPE_1D) Y_NameTable_Entry("2D", TEXTURE_TYPE_2D) Y_NameTable_Entry("3D", TEXTURE_TYPE_3D) Y_NameTable_Entry("Cube", TEXTURE_TYPE_CUBE) Y_NameTable_Entry("1DArray", TEXTURE_TYPE_1D_ARRAY) Y_NameTable_Entry("2DArray", TEXTURE_TYPE_2D_ARRAY) Y_NameTable_Entry("CubeArray", TEXTURE_TYPE_CUBE_ARRAY) Y_NameTable_End() Y_Define_NameTable(NameTables::TextureClassNames) Y_NameTable_Entry("Texture1D", TEXTURE_TYPE_1D) Y_NameTable_Entry("Texture2D", TEXTURE_TYPE_2D) Y_NameTable_Entry("Texture3D", TEXTURE_TYPE_3D) Y_NameTable_Entry("TextureCube", TEXTURE_TYPE_CUBE) Y_NameTable_Entry("Texture1DArray", TEXTURE_TYPE_1D_ARRAY) Y_NameTable_Entry("Texture2DArray", TEXTURE_TYPE_2D_ARRAY) Y_NameTable_Entry("TextureCubeArray", TEXTURE_TYPE_CUBE_ARRAY) Y_NameTable_End() Y_Define_NameTable(NameTables::TextureUsage) Y_NameTable_Entry("None", TEXTURE_USAGE_NONE) Y_NameTable_Entry("ColorMap", TEXTURE_USAGE_COLOR_MAP) Y_NameTable_Entry("GlossMap", TEXTURE_USAGE_GLOSS_MAP) Y_NameTable_Entry("AlphaMap", TEXTURE_USAGE_ALPHA_MAP) Y_NameTable_Entry("NormalMap", TEXTURE_USAGE_NORMAL_MAP) Y_NameTable_Entry("HeightMap", TEXTURE_USAGE_HEIGHT_MAP) Y_NameTable_Entry("UIAsset", TEXTURE_USAGE_UI_ASSET) Y_NameTable_Entry("UILuminanceAsset", TEXTURE_USAGE_UI_LUMINANCE_ASSET) Y_NameTable_End() Y_Define_NameTable(NameTables::TextureFilter) Y_NameTable_Entry("MinMagMipPoint", TEXTURE_FILTER_MIN_MAG_MIP_POINT) Y_NameTable_Entry("MinMagPointMipLinear", TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR) Y_NameTable_Entry("MinPointMagLinearMipPoint", TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT) Y_NameTable_Entry("MinPointMagMipLinear", TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR) Y_NameTable_Entry("MinLinearMagMipPoint", TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT) Y_NameTable_Entry("MinLinearMagPointMipLinear", TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR) Y_NameTable_Entry("MinMagLinearMipPoint", TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT) Y_NameTable_Entry("MinMagMipLinear", TEXTURE_FILTER_MIN_MAG_MIP_LINEAR) Y_NameTable_Entry("Anisotropic", TEXTURE_FILTER_ANISOTROPIC) Y_NameTable_Entry("ComparisonMinMagMipPoint", TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT) Y_NameTable_Entry("ComparisonMinMagPointMipLinear", TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR) Y_NameTable_Entry("ComparisonMinPointMagLinearMipPoint", TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT) Y_NameTable_Entry("ComparisonMinPointMagMipLinear", TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR) Y_NameTable_Entry("ComparisonMinLinearMagMipPoint", TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT) Y_NameTable_Entry("ComparisonMinLinearMagPointMipLinear", TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR) Y_NameTable_Entry("ComparisonMinMagLinearMipPoint", TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT) Y_NameTable_Entry("ComparisonMinMagMipLinear", TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR) Y_NameTable_Entry("ComparisonAnisotropic", TEXTURE_FILTER_COMPARISON_ANISOTROPIC) Y_NameTable_End() Y_Define_NameTable(NameTables::TextureAddressMode) Y_NameTable_Entry("Wrap", TEXTURE_ADDRESS_MODE_WRAP) Y_NameTable_Entry("Mirror", TEXTURE_ADDRESS_MODE_MIRROR) Y_NameTable_Entry("Clamp", TEXTURE_ADDRESS_MODE_CLAMP) Y_NameTable_Entry("Border", TEXTURE_ADDRESS_MODE_BORDER) Y_NameTable_Entry("MirrorOnce", TEXTURE_ADDRESS_MODE_MIRROR_ONCE) Y_NameTable_End() Y_Define_NameTable(NameTables::TexturePlatform) Y_NameTable_Entry("DXTC", TEXTURE_PLATFORM_DXTC) Y_NameTable_Entry("PVRTC", TEXTURE_PLATFORM_PVRTC) Y_NameTable_Entry("ATC", TEXTURE_PLATFORM_ATC) Y_NameTable_Entry("ETC", TEXTURE_PLATFORM_ETC) Y_NameTable_Entry("ES2_NOTC", TEXTURE_PLATFORM_ES2_NOTC) Y_NameTable_Entry("ES2_DXTC", TEXTURE_PLATFORM_ES2_DXTC) Y_NameTable_End() Y_Define_NameTable(NameTables::TexturePlatformFileExtension) Y_NameTable_Entry("dxtc", TEXTURE_PLATFORM_DXTC) Y_NameTable_Entry("pvrtc", TEXTURE_PLATFORM_PVRTC) Y_NameTable_Entry("atc", TEXTURE_PLATFORM_ATC) Y_NameTable_Entry("etc", TEXTURE_PLATFORM_ETC) Y_NameTable_Entry("es2notc", TEXTURE_PLATFORM_ES2_NOTC) Y_NameTable_Entry("es2dxtc", TEXTURE_PLATFORM_ES2_DXTC) Y_NameTable_End() DEFINE_RESOURCE_TYPE_INFO(Texture); Texture::Texture(TEXTURE_TYPE TextureType, const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(pResourceTypeInfo), m_eTextureType(TextureType), m_eTexturePlatform(NUM_TEXTURE_PLATFORMS), m_ePixelFormat(PIXEL_FORMAT_UNKNOWN), m_eTextureUsage(TEXTURE_USAGE_NONE), m_eTextureFilter(TEXTURE_FILTER_COUNT), m_eBlendingMode(MATERIAL_BLENDING_MODE_COUNT), m_iMinLOD(Y_INT32_MIN), m_iMaxLOD(Y_INT32_MAX), m_nMipLevels(0), m_nImages(0), m_pImages(NULL), m_pDeviceTexture(NULL), m_bDeviceResourcesCreated(false) { } Texture::~Texture() { uint32 i; if (m_pDeviceTexture != NULL) m_pDeviceTexture->Release(); if (m_pImages != NULL) { for (i = 0; i < m_nImages; i++) delete[] m_pImages[i].pPixels; delete[] m_pImages; } } GPUTexture *Texture::GetGPUTexture() const { if (!m_bDeviceResourcesCreated) CreateDeviceResources(); return m_pDeviceTexture; } bool Texture::CreateDeviceResources() const { m_bDeviceResourcesCreated = true; return true; } void Texture::ReleaseDeviceResources() const { m_bDeviceResourcesCreated = false; } TEXTURE_TYPE Texture::GetTextureTypeForStream(const char *FileName, ByteStream *pStream) { // in lack of a peek, we have to save the offset and re-seek it uint64 currentOffset = pStream->GetPosition(); // read header DF_TEXTURE_HEADER textureHeader; if (!pStream->Read2(&textureHeader, sizeof(textureHeader)) || textureHeader.Magic != DF_TEXTURE_HEADER_MAGIC || textureHeader.HeaderSize < sizeof(textureHeader)) { pStream->SeekAbsolute(currentOffset); return TEXTURE_TYPE_COUNT; } pStream->SeekAbsolute(currentOffset); if (textureHeader.TextureType < TEXTURE_TYPE_COUNT) return (TEXTURE_TYPE)textureHeader.TextureType; else return TEXTURE_TYPE_COUNT; } Texture *Texture::CreateTextureObjectForType(TEXTURE_TYPE textureType) { switch (textureType) { case TEXTURE_TYPE_2D: return new Texture2D(); case TEXTURE_TYPE_2D_ARRAY: return new Texture2DArray(); case TEXTURE_TYPE_CUBE: return new TextureCube(); } return NULL; } const ResourceTypeInfo *Texture::GetResourceTypeInfoForTextureType(TEXTURE_TYPE textureType) { switch (textureType) { case TEXTURE_TYPE_2D: return Texture2D::StaticTypeInfo(); case TEXTURE_TYPE_2D_ARRAY: return Texture2DArray::StaticTypeInfo(); case TEXTURE_TYPE_CUBE: return TextureCube::StaticTypeInfo(); } return NULL; } uint3 Texture::GetTextureDimensions(const Texture *pTexture) { DebugAssert(pTexture != NULL); switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_2D: { const Texture2D *pTexture2D = pTexture->Cast<Texture2D>(); return uint3(pTexture2D->GetWidth(), pTexture2D->GetHeight(), 1); } break; case TEXTURE_TYPE_CUBE: { const TextureCube *pTextureCube = pTexture->Cast<TextureCube>(); return uint3(pTextureCube->GetWidth(), pTextureCube->GetHeight(), 1); } break; } UnreachableCode(); return uint3::Zero; } DEFINE_RESOURCE_TYPE_INFO(Texture2D); DEFINE_RESOURCE_GENERIC_FACTORY(Texture2D); Texture2D::Texture2D(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(TEXTURE_TYPE_2D, pResourceTypeInfo), m_eAddressModeU(TEXTURE_ADDRESS_MODE_WRAP), m_eAddressModeV(TEXTURE_ADDRESS_MODE_WRAP), m_iWidth(0), m_iHeight(0) { } Texture2D::~Texture2D() { } bool Texture2D::Create(const char *Name, TEXTURE_PLATFORM texturePlatform, TEXTURE_USAGE textureUsage, TEXTURE_FILTER textureFilter, MATERIAL_BLENDING_MODE blendingMode, TEXTURE_ADDRESS_MODE addressModeU, TEXTURE_ADDRESS_MODE addressModeV, int32 minLOD, int32 maxLOD, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 mipLevels) { DebugAssert(mipLevels > 0 && mipLevels < TEXTURE_MAX_MIPMAP_COUNT); m_strName = Name; m_eTextureUsage = textureUsage; m_eTexturePlatform = texturePlatform; m_eTextureFilter = textureFilter; m_eBlendingMode = blendingMode; m_eAddressModeU = addressModeU; m_eAddressModeV = addressModeV; m_iMinLOD = minLOD; m_iMaxLOD = maxLOD; m_ePixelFormat = pixelFormat; m_nMipLevels = mipLevels; m_iWidth = width; m_iHeight = height; m_nImages = mipLevels; m_pImages = new ImageData[m_nImages]; uint32 imageWidth = width; uint32 imageHeight = height; for (uint32 i = 0; i < m_nMipLevels; i++) { ImageData &image = m_pImages[i]; image.Size = PixelFormat_CalculateImageSize(pixelFormat, width, height, 1); image.RowPitch = PixelFormat_CalculateRowPitch(pixelFormat, width); image.SlicePitch = image.Size; image.FileOffset = 0; image.pPixels = new byte[image.Size]; if (imageWidth > 1) imageWidth /= 2; if (imageHeight > 1) imageHeight /= 2; } return true; } bool Texture2D::Load(const char *name, ByteStream *pStream) { uint32 i; uint64 startOffset = pStream->GetPosition(); // assign name, remove extension m_strName = name; // read in texture header DF_TEXTURE_HEADER textureHeader; if (!pStream->Read2(&textureHeader, sizeof(textureHeader)) || textureHeader.Magic != DF_TEXTURE_HEADER_MAGIC || textureHeader.HeaderSize < sizeof(textureHeader)) { return false; } // check it's the correct type if (textureHeader.TextureType != TEXTURE_TYPE_2D || textureHeader.ArraySize > 1) return false; // check fields if (textureHeader.TextureUsage >= TEXTURE_USAGE_COUNT || textureHeader.TexturePlatform >= NUM_TEXTURE_PLATFORMS || textureHeader.TextureFilter >= TEXTURE_FILTER_COUNT || textureHeader.PixelFormat >= PIXEL_FORMAT_COUNT || textureHeader.PixelFormat == PIXEL_FORMAT_UNKNOWN || textureHeader.BlendingMode >= MATERIAL_BLENDING_MODE_COUNT || textureHeader.AddressModeU >= TEXTURE_ADDRESS_MODE_COUNT || textureHeader.AddressModeV >= TEXTURE_ADDRESS_MODE_COUNT) { return false; } // check dimensions if (textureHeader.Width < 1 || textureHeader.Height < 1 || textureHeader.Depth != 1) return false; // check image count if (textureHeader.ImageCount != (textureHeader.ArraySize * textureHeader.MipLevels)) return false; // ok, bring in the data m_eTextureUsage = (TEXTURE_USAGE)textureHeader.TextureUsage; m_eTexturePlatform = (TEXTURE_PLATFORM)textureHeader.TexturePlatform; m_eTextureFilter = (TEXTURE_FILTER)textureHeader.TextureFilter; m_ePixelFormat = (PIXEL_FORMAT)textureHeader.PixelFormat; m_eBlendingMode = (MATERIAL_BLENDING_MODE)textureHeader.BlendingMode; m_eAddressModeU = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeU; m_eAddressModeV = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeV; m_iMinLOD = (int32)textureHeader.MinLOD; m_iMaxLOD = (int32)textureHeader.MaxLOD; m_iWidth = textureHeader.Width; m_iHeight = textureHeader.Height; m_nMipLevels = textureHeader.MipLevels; m_nImages = textureHeader.ImageCount; // allocate image data m_pImages = new ImageData[m_nImages]; Y_memzero(m_pImages, sizeof(ImageData) * m_nImages); // read in image offsets uint32 *imageOffsets = (uint32 *)alloca(sizeof(uint32) * textureHeader.ImageCount); if (!pStream->SeekAbsolute(startOffset + (uint64)textureHeader.HeaderSize) || !pStream->Read2(imageOffsets, sizeof(uint32) * textureHeader.ImageCount)) return false; // bring in each mip level (todo streaming) for (i = 0; i < m_nImages; i++) { ImageData &dstImage = m_pImages[i]; if (!pStream->SeekAbsolute(startOffset + (uint64)imageOffsets[i])) return false; DF_TEXTURE_IMAGE_HEADER textureImageHeader; if (!pStream->Read2(&textureImageHeader, sizeof(textureImageHeader))) return false; dstImage.FileOffset = imageOffsets[i]; dstImage.Size = textureImageHeader.Size; dstImage.RowPitch = textureImageHeader.RowPitch; dstImage.SlicePitch = textureImageHeader.SlicePitch; dstImage.pPixels = new byte[dstImage.Size]; if (!pStream->Read2(dstImage.pPixels, dstImage.Size)) return false; } // create on gpu if (g_pRenderer != nullptr && !CreateDeviceResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool Texture2D::CreateDeviceResources() const { if (m_bDeviceResourcesCreated) return true; // create texture objects if (m_pDeviceTexture == NULL) { // allocate temp arrays const void **ppImageData = (const void **)alloca(sizeof(const void *) * m_nImages); uint32 *pRowPitches = (uint32 *)alloca(sizeof(uint32) * m_nImages); uint32 i; // fill temp arrays for (i = 0; i < m_nImages; i++) { ppImageData[i] = m_pImages[i].pPixels; pRowPitches[i] = m_pImages[i].RowPitch; } // fill texture desc GPU_TEXTURE2D_DESC textureDesc; textureDesc.Width = m_iWidth; textureDesc.Height = m_iHeight; textureDesc.Format = m_ePixelFormat; textureDesc.Flags = GPU_TEXTURE_FLAG_SHADER_BINDABLE; textureDesc.MipLevels = m_nMipLevels; // fill sampler desc GPU_SAMPLER_STATE_DESC samplerStateDesc; samplerStateDesc.Filter = m_eTextureFilter; Renderer::CorrectTextureFilter(&samplerStateDesc); samplerStateDesc.AddressU = m_eAddressModeU; samplerStateDesc.AddressV = m_eAddressModeV; samplerStateDesc.AddressW = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.BorderColor.SetZero(); samplerStateDesc.LODBias = 0.0f; samplerStateDesc.MinLOD = m_iMinLOD; samplerStateDesc.MaxLOD = m_iMaxLOD; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_NEVER; // create texture m_pDeviceTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, ppImageData, pRowPitches); // set debug name #ifdef Y_BUILD_CONFIG_DEBUG if (m_pDeviceTexture != NULL) m_pDeviceTexture->SetDebugName(m_strName); #endif } return BaseClass::CreateDeviceResources(); } void Texture2D::ReleaseDeviceResources() const { SAFE_RELEASE(m_pDeviceTexture); return BaseClass::ReleaseDeviceResources(); } bool Texture2D::ExportToImage(uint32 mipIndex, Image *pOutputImage) const { DebugAssert(mipIndex < m_nMipLevels); uint32 imageWidth = m_iWidth >> mipIndex; uint32 imageHeight = m_iHeight >> mipIndex; if (imageWidth == 0) imageWidth = 1; if (imageHeight == 0) imageHeight = 1; // create image pOutputImage->Create(m_ePixelFormat, imageWidth, imageHeight, 1); // work out rows const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); uint32 nRows = Max((uint32)1, (pPixelFormatInfo->IsBlockCompressed) ? (m_iHeight / pPixelFormatInfo->BlockSize) : (m_iHeight)); // copy the data const ImageData *pImageData = GetMipLevelData(mipIndex); Y_memcpy_stride(pOutputImage->GetData(), pOutputImage->GetDataRowPitch(), pImageData->pPixels, pImageData->RowPitch, pOutputImage->GetDataRowPitch(), nRows); // done return true; } DEFINE_RESOURCE_TYPE_INFO(Texture2DArray); DEFINE_RESOURCE_GENERIC_FACTORY(Texture2DArray); Texture2DArray::Texture2DArray(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(TEXTURE_TYPE_2D_ARRAY, pResourceTypeInfo), m_eAddressModeU(TEXTURE_ADDRESS_MODE_WRAP), m_eAddressModeV(TEXTURE_ADDRESS_MODE_WRAP), m_iWidth(0), m_iHeight(0) { } Texture2DArray::~Texture2DArray() { } bool Texture2DArray::Create(const char *Name, TEXTURE_PLATFORM texturePlatform, TEXTURE_USAGE textureUsage, TEXTURE_FILTER textureFilter, MATERIAL_BLENDING_MODE blendingMode, TEXTURE_ADDRESS_MODE addressModeU, TEXTURE_ADDRESS_MODE addressModeV, int32 minLOD, int32 maxLOD, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 arraySize, uint32 mipLevels) { DebugAssert(mipLevels > 0 && mipLevels < TEXTURE_MAX_MIPMAP_COUNT); m_strName = Name; m_eTextureUsage = textureUsage; m_eTexturePlatform = texturePlatform; m_eTextureFilter = textureFilter; m_eBlendingMode = blendingMode; m_eAddressModeU = addressModeU; m_eAddressModeV = addressModeV; m_iMinLOD = minLOD; m_iMaxLOD = maxLOD; m_ePixelFormat = pixelFormat; m_nMipLevels = mipLevels; m_iWidth = width; m_iHeight = height; m_nImages = arraySize * mipLevels; m_pImages = new ImageData[m_nImages]; uint32 imageWidth = width; uint32 imageHeight = height; for (uint32 i = 0; i < m_nMipLevels; i++) { for (uint32 j = 0; j < arraySize; j++) { ImageData &image = m_pImages[i * arraySize + j]; image.Size = PixelFormat_CalculateImageSize(pixelFormat, width, height, 1); image.RowPitch = PixelFormat_CalculateRowPitch(pixelFormat, width); image.SlicePitch = image.Size; image.FileOffset = 0; image.pPixels = new byte[image.Size]; } if (imageWidth > 1) imageWidth /= 2; if (imageHeight > 1) imageHeight /= 2; } return true; } bool Texture2DArray::Load(const char *name, ByteStream *pStream) { uint32 i; uint64 startOffset = pStream->GetPosition(); // assign name, remove extension m_strName = name; // read in texture header DF_TEXTURE_HEADER textureHeader; if (!pStream->Read2(&textureHeader, sizeof(textureHeader)) || textureHeader.Magic != DF_TEXTURE_HEADER_MAGIC || textureHeader.HeaderSize < sizeof(textureHeader)) { return false; } // check it's the correct type if (textureHeader.TextureType != TEXTURE_TYPE_2D_ARRAY || textureHeader.ArraySize == 0) return false; // check fields if (textureHeader.TextureUsage >= TEXTURE_USAGE_COUNT || textureHeader.TexturePlatform >= NUM_TEXTURE_PLATFORMS || textureHeader.TextureFilter > TEXTURE_FILTER_COUNT || textureHeader.AddressModeU >= TEXTURE_ADDRESS_MODE_COUNT || textureHeader.AddressModeV >= TEXTURE_ADDRESS_MODE_COUNT || textureHeader.PixelFormat >= PIXEL_FORMAT_COUNT || textureHeader.PixelFormat == PIXEL_FORMAT_UNKNOWN) { return false; } // check dimensions if (textureHeader.Width < 1 || textureHeader.Height < 1 || textureHeader.Depth != 1) return false; // check image count if (textureHeader.ImageCount != (textureHeader.ArraySize * textureHeader.MipLevels)) return false; // ok, bring in the data m_eTextureUsage = (TEXTURE_USAGE)textureHeader.TextureUsage; m_eTexturePlatform = (TEXTURE_PLATFORM)textureHeader.TexturePlatform; m_eTextureFilter = (TEXTURE_FILTER)textureHeader.TextureFilter; m_ePixelFormat = (PIXEL_FORMAT)textureHeader.PixelFormat; m_eAddressModeU = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeU; m_eAddressModeV = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeV; m_iMinLOD = (int32)textureHeader.MinLOD; m_iMaxLOD = (int32)textureHeader.MaxLOD; m_iWidth = textureHeader.Width; m_iHeight = textureHeader.Height; m_iArraySize = textureHeader.ArraySize; m_nMipLevels = textureHeader.MipLevels; m_nImages = textureHeader.ImageCount; // allocate image data m_pImages = new ImageData[m_nImages]; Y_memzero(m_pImages, sizeof(ImageData) * m_nImages); // read in image offsets uint32 *imageOffsets = (uint32 *)alloca(sizeof(uint32) * textureHeader.ImageCount); if (!pStream->SeekAbsolute(startOffset + (uint64)textureHeader.HeaderSize) || !pStream->Read2(imageOffsets, sizeof(uint32) * textureHeader.ImageCount)) return false; // bring in each mip level (todo streaming) for (i = 0; i < m_nImages; i++) { ImageData &dstImage = m_pImages[i]; if (!pStream->SeekAbsolute(startOffset + (uint64)imageOffsets[i])) return false; DF_TEXTURE_IMAGE_HEADER textureImageHeader; if (!pStream->Read2(&textureImageHeader, sizeof(textureImageHeader))) return false; dstImage.FileOffset = imageOffsets[i]; dstImage.Size = textureImageHeader.Size; dstImage.RowPitch = textureImageHeader.RowPitch; dstImage.SlicePitch = textureImageHeader.SlicePitch; dstImage.pPixels = new byte[dstImage.Size]; if (!pStream->Read2(dstImage.pPixels, dstImage.Size)) return false; } // create on gpu if (g_pRenderer != nullptr && !CreateDeviceResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool Texture2DArray::CreateDeviceResources() const { if (m_bDeviceResourcesCreated) return true; // create texture objects if (m_pDeviceTexture == NULL) { // allocate temp arrays const void **ppImageData = (const void **)alloca(sizeof(const void *) * m_nImages); uint32 *pRowPitches = (uint32 *)alloca(sizeof(uint32) * m_nImages); uint32 i; // fill temp arrays for (i = 0; i < m_nImages; i++) { ppImageData[i] = m_pImages[i].pPixels; pRowPitches[i] = m_pImages[i].RowPitch; } // fill texture desc GPU_TEXTURE2DARRAY_DESC textureDesc; textureDesc.Width = m_iWidth; textureDesc.Height = m_iHeight; textureDesc.Format = m_ePixelFormat; textureDesc.Flags = GPU_TEXTURE_FLAG_SHADER_BINDABLE; textureDesc.MipLevels = m_nMipLevels; textureDesc.ArraySize = m_iArraySize; // fill sampler desc GPU_SAMPLER_STATE_DESC samplerStateDesc; samplerStateDesc.Filter = m_eTextureFilter; Renderer::CorrectTextureFilter(&samplerStateDesc); samplerStateDesc.AddressU = m_eAddressModeU; samplerStateDesc.AddressV = m_eAddressModeV; samplerStateDesc.AddressW = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.BorderColor.SetZero(); samplerStateDesc.LODBias = 0.0f; samplerStateDesc.MinLOD = m_iMinLOD; samplerStateDesc.MaxLOD = m_iMaxLOD; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_NEVER; // create texture m_pDeviceTexture = g_pRenderer->CreateTexture2DArray(&textureDesc, &samplerStateDesc, ppImageData, pRowPitches); #ifdef Y_BUILD_CONFIG_DEBUG // set debug name if (m_pDeviceTexture != NULL) m_pDeviceTexture->SetDebugName(m_strName); #endif } return BaseClass::CreateDeviceResources(); } void Texture2DArray::ReleaseDeviceResources() const { SAFE_RELEASE(m_pDeviceTexture); return BaseClass::ReleaseDeviceResources(); } bool Texture2DArray::ExportToImage(uint32 mipIndex, uint32 arrayIndex, Image *pOutputImage) const { DebugAssert(arrayIndex < m_iArraySize && mipIndex < m_nMipLevels); uint32 imageWidth = m_iWidth >> mipIndex; uint32 imageHeight = m_iHeight >> mipIndex; if (imageWidth == 0) imageWidth = 1; if (imageHeight == 0) imageHeight = 1; // create image pOutputImage->Create(m_ePixelFormat, imageWidth, imageHeight, 1); // work out rows const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); uint32 nRows = Max((uint32)1, (pPixelFormatInfo->IsBlockCompressed) ? (m_iHeight / pPixelFormatInfo->BlockSize) : (m_iHeight)); // copy the data const ImageData *pImageData = GetMipLevelData(mipIndex, arrayIndex); Y_memcpy_stride(pOutputImage->GetData(), pOutputImage->GetDataRowPitch(), pImageData->pPixels, pImageData->RowPitch, pOutputImage->GetDataRowPitch(), nRows); // done return true; } DEFINE_RESOURCE_TYPE_INFO(TextureCube); DEFINE_RESOURCE_GENERIC_FACTORY(TextureCube); TextureCube::TextureCube(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(TEXTURE_TYPE_CUBE, pResourceTypeInfo), m_eAddressModeU(TEXTURE_ADDRESS_MODE_WRAP), m_eAddressModeV(TEXTURE_ADDRESS_MODE_WRAP), m_iWidth(0), m_iHeight(0) { } TextureCube::~TextureCube() { } bool TextureCube::Load(const char *name, ByteStream *pStream) { uint32 i; uint64 startOffset = pStream->GetPosition(); // assign name, remove extension m_strName = name; // read in texture header DF_TEXTURE_HEADER textureHeader; if (!pStream->Read2(&textureHeader, sizeof(textureHeader)) || textureHeader.Magic != DF_TEXTURE_HEADER_MAGIC || textureHeader.HeaderSize < sizeof(textureHeader)) { return false; } // check it's the correct type if (textureHeader.TextureType != TEXTURE_TYPE_CUBE || textureHeader.ArraySize != CUBEMAP_FACE_COUNT) return false; // check fields if (textureHeader.TextureUsage >= TEXTURE_USAGE_COUNT || textureHeader.TexturePlatform >= NUM_TEXTURE_PLATFORMS || textureHeader.TextureFilter > TEXTURE_FILTER_COUNT || textureHeader.AddressModeU >= TEXTURE_ADDRESS_MODE_COUNT || textureHeader.AddressModeV >= TEXTURE_ADDRESS_MODE_COUNT) { return false; } // check dimensions if (textureHeader.Width < 1 || textureHeader.Height < 1 || textureHeader.Depth != 1) return false; // check image count if (textureHeader.ImageCount != (textureHeader.ArraySize * textureHeader.MipLevels)) return false; // ok, bring in the data m_ePixelFormat = (PIXEL_FORMAT)textureHeader.PixelFormat; m_eTexturePlatform = (TEXTURE_PLATFORM)textureHeader.TexturePlatform; m_eTextureUsage = (TEXTURE_USAGE)textureHeader.TextureUsage; m_eTextureFilter = (TEXTURE_FILTER)textureHeader.TextureFilter; m_eAddressModeU = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeU; m_eAddressModeV = (TEXTURE_ADDRESS_MODE)textureHeader.AddressModeV; m_iMinLOD = textureHeader.MinLOD; m_iMaxLOD = textureHeader.MaxLOD; m_iWidth = textureHeader.Width; m_iHeight = textureHeader.Height; m_nMipLevels = textureHeader.MipLevels; m_nImages = textureHeader.ImageCount; // allocate image data m_pImages = new ImageData[m_nImages]; Y_memzero(m_pImages, sizeof(ImageData) * m_nImages); // read in image offsets uint32 *imageOffsets = (uint32 *)alloca(sizeof(uint32) * textureHeader.ImageCount); if (!pStream->SeekAbsolute(startOffset + (uint64)textureHeader.HeaderSize) || !pStream->Read2(imageOffsets, sizeof(uint32) * textureHeader.ImageCount)) return false; // bring in each mip level (todo streaming) for (i = 0; i < m_nImages; i++) { ImageData &dstImage = m_pImages[i]; if (!pStream->SeekAbsolute(startOffset + (uint64)imageOffsets[i])) return false; DF_TEXTURE_IMAGE_HEADER textureImageHeader; if (!pStream->Read2(&textureImageHeader, sizeof(textureImageHeader))) return false; dstImage.FileOffset = imageOffsets[i]; dstImage.Size = textureImageHeader.Size; dstImage.RowPitch = textureImageHeader.RowPitch; dstImage.SlicePitch = textureImageHeader.SlicePitch; dstImage.pPixels = new byte[dstImage.Size]; if (!pStream->Read2(dstImage.pPixels, dstImage.Size)) return false; } // create on gpu if (!CreateDeviceResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool TextureCube::CreateDeviceResources() const { if (m_bDeviceResourcesCreated) return true; // create texture objects if (m_pDeviceTexture == NULL) { // allocate temp arrays DebugAssert(m_nImages > 0 && m_nImages == m_nMipLevels * CUBEMAP_FACE_COUNT); const void **ppImageData = (const void **)alloca(sizeof(const void *) * m_nImages); uint32 *pRowPitches = (uint32 *)alloca(sizeof(uint32) * m_nImages); uint32 i; // fill temp arrays for (i = 0; i < m_nImages; i++) { ppImageData[i] = m_pImages[i].pPixels; pRowPitches[i] = m_pImages[i].RowPitch; } // fill desc GPU_TEXTURECUBE_DESC textureDesc; textureDesc.Width = m_iWidth; textureDesc.Height = m_iHeight; textureDesc.Format = m_ePixelFormat; textureDesc.Flags = GPU_TEXTURE_FLAG_SHADER_BINDABLE; textureDesc.MipLevels = m_nMipLevels; // fill sampler desc GPU_SAMPLER_STATE_DESC samplerStateDesc; samplerStateDesc.Filter = m_eTextureFilter; Renderer::CorrectTextureFilter(&samplerStateDesc); samplerStateDesc.AddressU = m_eAddressModeU; samplerStateDesc.AddressV = m_eAddressModeV; samplerStateDesc.AddressW = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.BorderColor.SetZero(); samplerStateDesc.LODBias = 0.0f; samplerStateDesc.MinLOD = m_iMinLOD; samplerStateDesc.MaxLOD = m_iMaxLOD; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_NEVER; // create texture m_pDeviceTexture = g_pRenderer->CreateTextureCube(&textureDesc, &samplerStateDesc, ppImageData, pRowPitches); #ifdef Y_BUILD_CONFIG_DEBUG // set debug name if (m_pDeviceTexture != NULL) m_pDeviceTexture->SetDebugName(m_strName); #endif } return BaseClass::CreateDeviceResources(); } void TextureCube::ReleaseDeviceResources() const { SAFE_RELEASE(m_pDeviceTexture); return BaseClass::ReleaseDeviceResources(); } bool TextureCube::ExportToImage(uint32 cubeFace, uint32 mipIndex, Image *pOutputImage) const { DebugAssert(cubeFace < CUBE_FACE_COUNT && mipIndex < m_nMipLevels); uint32 imageWidth = m_iWidth >> mipIndex; uint32 imageHeight = m_iHeight >> mipIndex; if (imageWidth == 0) imageWidth = 1; if (imageHeight == 0) imageHeight = 1; // create image pOutputImage->Create(m_ePixelFormat, imageWidth, imageHeight, 1); // work out rows const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(m_ePixelFormat); uint32 nRows = Max((uint32)1, (pPixelFormatInfo->IsBlockCompressed) ? (m_iHeight / pPixelFormatInfo->BlockSize) : (m_iHeight)); // copy the data const ImageData *pImageData = GetMipLevelData(cubeFace, mipIndex); Y_memcpy_stride(pOutputImage->GetData(), pOutputImage->GetDataRowPitch(), pImageData->pPixels, pImageData->RowPitch, pOutputImage->GetDataRowPitch(), nRows); // done return true; } <file_sep>/Engine/Source/GameFramework/RotationInterpolatorComponent.h #pragma once #include "Engine/Component.h" class RotationInterpolatorComponent : public Component { DECLARE_COMPONENT_TYPEINFO(RotationInterpolatorComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(RotationInterpolatorComponent); public: RotationInterpolatorComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~RotationInterpolatorComponent(); // Property accessors const float GetMoveDuration() const { return m_moveDuration; } const float GetPauseDuration() const { return m_pauseDuration; } const bool GetReverseCycle() const { return m_reverseCycle; } const uint32 GetRepeatCount() const { return m_repeatCount; } const EasingFunction::Type GetEasingFunction() const { return (EasingFunction::Type)m_easingFunction; } const bool GetAutoActivate() const { return m_autoActivate; } // Property mutators void SetMoveDuration(float moveDuration); void SetPauseDuration(float pauseDuration); void SetReverseCycle(bool autoReverse); void SetRepeatCount(uint32 repeatCount); void SetEasingFunction(EasingFunction::Type easingFunction); void SetAutoActivate(bool autoActivate); // Creator void Create(const Quaternion &rotationAmount = Quaternion::Identity, float moveDuration = 1.0f, float pauseDuration = 0.0f, bool reverseCycle = true, uint32 repeatCount = 0, EasingFunction::Type easingFunction = EasingFunction::Linear, bool autoActivate = true); // Reset to the initial state void Reset(); // Activate/resume the mover void Activate(); // Deactivate/pause the mover void Deactivate(); // Events virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; virtual void Update(float timeSinceLastUpdate) override; private: float m_moveDuration; float m_pauseDuration; bool m_reverseCycle; uint32 m_repeatCount; uint32 m_easingFunction; bool m_autoActivate; bool m_active; Interpolator<Quaternion> m_interpolator; // property callbacks static void PropertyCallbackOnMoveDurationChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnPauseDurationChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnReverseCycleChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnRepeatCountChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnEasingFunctionChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnAutoActivateChange(RotationInterpolatorComponent *pComponent, const void *pUserData = nullptr); };<file_sep>/Editor/Source/Editor/EditorCVars.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorCVars.h" namespace CVars { CVar e_camera_max_speed("e_camera_max_speed", 0, "15", "Maximum editor camera speed", "float:1-100"); CVar e_camera_acceleration("e_camera_acceleration", 0, "60", "Velocity gained with camera movement per second", "float:1-100"); CVar e_max_fps("e_max_fps", 0, "60", "Maximum FPS that the editor will run at", "float:1-9999"); CVar e_max_fps_unfocused("e_max_fps_unfocused", 0, "15", "Maximum FPS that the editor will run at when alt-tabbed to another window", "float:1-9999"); } <file_sep>/Engine/Source/Engine/ComponentTypeInfo.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ComponentTypeInfo.h" #include "Engine/Component.h" ComponentTypeInfo::ComponentTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory) : ObjectTypeInfo(TypeName, pParentTypeInfo, pPropertyDeclarations, pFactory) { } ComponentTypeInfo::~ComponentTypeInfo() { } void ComponentTypeInfo::RegisterType() { if (m_iTypeIndex != INVALID_TYPE_INDEX) return; ObjectTypeInfo::RegisterType(); } void ComponentTypeInfo::UnregisterType() { if (m_iTypeIndex != INVALID_TYPE_INDEX) { ObjectTypeInfo::UnregisterType(); } } <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphCompiler.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphCompiler.h" ShaderGraphCompiler::ShaderGraphCompiler(const ShaderGraph *pShaderGraph) : m_pShaderGraph(pShaderGraph) { } ShaderGraphCompiler::~ShaderGraphCompiler() { } const ShaderGraphCompiler::ExternalParameter *ShaderGraphCompiler::GetExternalUniformParameter(const char *uniformName) const { for (ExternalParameterList::ConstIterator itr = m_ExternalUniforms.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Name.Compare(uniformName)) return &(*itr); } return NULL; } const ShaderGraphCompiler::ExternalParameter *ShaderGraphCompiler::GetExternalTextureParameter(const char *textureName) const { for (ExternalParameterList::ConstIterator itr = m_ExternalTextures.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Name.Compare(textureName)) return &(*itr); } return NULL; } const bool ShaderGraphCompiler::GetExternalStaticSwitchParameter(const char *staticSwitchName) const { for (StaticSwitchList::ConstIterator itr = m_ExternalStaticSwitches.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Left.Compare(staticSwitchName)) return itr->Right; } return false; } void ShaderGraphCompiler::AddExternalUniformParameter(const char *uniformName, SHADER_PARAMETER_TYPE uniformType, const char *bindingName) { for (ExternalParameterList::Iterator itr = m_ExternalUniforms.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Name.Compare(uniformName)) { DebugAssert(itr->Type == uniformType); return; } } ExternalParameter ep; ep.Name = uniformName; ep.Type = uniformType; ep.BindingName = bindingName; m_ExternalUniforms.PushBack(ep); } void ShaderGraphCompiler::AddExternalTextureParameter(const char *textureName, TEXTURE_TYPE textureType, const char *bindingName) { SHADER_PARAMETER_TYPE mappedType = SHADER_PARAMETER_TYPE_COUNT; switch (textureType) { case TEXTURE_TYPE_1D: mappedType = SHADER_PARAMETER_TYPE_TEXTURE1D; break; case TEXTURE_TYPE_1D_ARRAY: mappedType = SHADER_PARAMETER_TYPE_TEXTURE1DARRAY; break; case TEXTURE_TYPE_2D: mappedType = SHADER_PARAMETER_TYPE_TEXTURE2D; break; case TEXTURE_TYPE_2D_ARRAY: mappedType = SHADER_PARAMETER_TYPE_TEXTURE2DARRAY; break; case TEXTURE_TYPE_3D: mappedType = SHADER_PARAMETER_TYPE_TEXTURE3D; break; case TEXTURE_TYPE_CUBE: mappedType = SHADER_PARAMETER_TYPE_TEXTURECUBE; break; case TEXTURE_TYPE_CUBE_ARRAY: mappedType = SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY; break; default: UnreachableCode(); break; } for (ExternalParameterList::Iterator itr = m_ExternalTextures.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Name.Compare(textureName)) { DebugAssert(itr->Type == mappedType); return; } } ExternalParameter ep; ep.Name = textureName; ep.Type = mappedType; ep.BindingName = bindingName; m_ExternalTextures.PushBack(ep); } void ShaderGraphCompiler::AddExternalStaticSwitchParameter(const char *staticSwitchName, bool enabled) { for (StaticSwitchList::Iterator itr = m_ExternalStaticSwitches.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Left.Compare(staticSwitchName)) { itr->Right = enabled; return; } } m_ExternalStaticSwitches.PushBack(Pair<String, bool>(staticSwitchName, enabled)); } <file_sep>/Editor/Source/Editor/SkeletalMeshEditor/ui_EditorSkeletalMeshEditor.h #pragma once #include "Editor/EditorRendererSwapChainWidget.h" #include "Editor/ToolMenuWidget.h" #include "Editor/EditorVectorEditWidget.h" class Ui_EditorSkeletalMeshEditor { public: QMainWindow *mainWindow; // actions QAction *actionOpenMesh; QAction *actionSaveMesh; QAction *actionSaveMeshAs; QAction *actionClose; QAction *actionCameraPerspective; QAction *actionCameraArcball; QAction *actionCameraIsometric; QAction *actionViewWireframe; QAction *actionViewUnlit; QAction *actionViewLit; QAction *actionViewFlagShadows; QAction *actionViewFlagWireframeOverlay; QAction *actionToolInformation; QAction *actionToolOperations; QAction *actionToolMaterials; QAction *actionToolLOD; QAction *actionToolCollision; QAction *actionToolImport; QAction *actionToolLightManipulator; // menus QMenu *menuMesh; QMenu *menuCamera; QMenu *menuView; QMenu *menuTools; QMenu *menuHelp; // widgets QMenuBar *menubar; QToolBar *toolbar; QStatusBar *statusBar; // left pane EditorRendererSwapChainWidget *swapChainWidget; // right pane QDockWidget *rightDockWidget; QWidget *rightDockContainer; // mode panel ToolMenuWidget *rightToolMenu; // stuff for each mode QWidget *toolContainer; QScrollArea *toolContainerScrollArea; // information QWidget *toolInformationContainer; QLabel *toolInformationMinBounds; QLabel *toolInformationMaxBounds; QLabel *toolInformationVertexCount; QLabel *toolInformationTriangleCount; QLabel *toolInformationMaterialCount; QLabel *toolInformationBatchCount; QCheckBox *toolInformationEnableTextureCoordinates; QCheckBox *toolInformationEnableVertexColors; // operations QWidget *toolOperationsContainer; QPushButton *toolOperationsGenerateTangents; QPushButton *toolOperationsCenterMesh; QPushButton *toolOperationsRemoveUnusedVertices; QPushButton *toolOperationsRemoveUnusedTriangles; // materials QWidget *toolMaterialsContainer; // lods QWidget *toolLODContainer; // collision QWidget *toolCollisionContainer; QLabel *toolCollisionInformation; QRadioButton *toolCollisionGenerateBox; QRadioButton *toolCollisionGenerateSphere; QRadioButton *toolCollisionGenerateTriangleMesh; QRadioButton *toolCollisionGenerateConvexHull; QPushButton *toolCollisionGenerate; // import QWidget *toolImportContainer; QPushButton *toolImportSelectFileName; QComboBox *toolImportSubMeshName; QComboBox *toolImportCoordinateSystem; QComboBox *toolImportFaceWinding; QCheckBox *toolImportGenerateTangents; EditorVectorEditWidget *toolImportScale; QCheckBox *toolImportMaterials; QLineEdit *toolImportMaterialDirectory; QLineEdit *toolImportMaterialPrefix; QPushButton *toolImportImport; // light manipulator QWidget *toolLightManipulatorContainer; void CreateUI(QMainWindow *pMainWindow) { mainWindow = pMainWindow; mainWindow->resize(800, 600); actionOpenMesh = new QAction(pMainWindow); actionOpenMesh->setIcon(QIcon(QStringLiteral(":/editor/icons/openHS.png"))); actionOpenMesh->setText(mainWindow->tr("&Open Mesh")); actionSaveMesh = new QAction(pMainWindow); actionSaveMesh->setIcon(QIcon(QStringLiteral(":/editor/icons/saveHS.png"))); actionSaveMesh->setText(mainWindow->tr("&Save Mesh")); actionSaveMeshAs = new QAction(pMainWindow); actionSaveMeshAs->setText(mainWindow->tr("Save Mesh &As")); actionClose = new QAction(pMainWindow); actionClose->setText(mainWindow->tr("&Close")); actionCameraPerspective = new QAction(pMainWindow); actionCameraPerspective->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Perspective.png"))); actionCameraPerspective->setText(mainWindow->tr("&Perspective Camera")); actionCameraPerspective->setCheckable(true); actionCameraArcball = new QAction(pMainWindow); actionCameraArcball->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Side.png"))); actionCameraArcball->setText(mainWindow->tr("&Arcball Camera")); actionCameraArcball->setCheckable(true); actionCameraIsometric = new QAction(pMainWindow); actionCameraIsometric->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Isometric.png"))); actionCameraIsometric->setText(mainWindow->tr("&Isometric Camera")); actionCameraIsometric->setCheckable(true); actionViewWireframe = new QAction(pMainWindow); actionViewWireframe->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Wireframe.png"))); actionViewWireframe->setText(mainWindow->tr("&Wireframe View")); actionViewWireframe->setCheckable(true); actionViewUnlit = new QAction(pMainWindow); actionViewUnlit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Unlit.png"))); actionViewUnlit->setText(mainWindow->tr("&Unlit View")); actionViewUnlit->setCheckable(true); actionViewLit = new QAction(pMainWindow); actionViewLit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Lit.png"))); actionViewLit->setText(mainWindow->tr("&Lit View")); actionViewLit->setCheckable(true); actionViewFlagShadows = new QAction(pMainWindow); actionViewFlagShadows->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_Shadows.png"))); actionViewFlagShadows->setText(mainWindow->tr("Enable &Shadows")); actionViewFlagShadows->setCheckable(true); actionViewFlagWireframeOverlay = new QAction(pMainWindow); actionViewFlagWireframeOverlay->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_WireframeOverlay.png"))); actionViewFlagWireframeOverlay->setText(mainWindow->tr("Enable Wireframe &Overlay")); actionViewFlagWireframeOverlay->setCheckable(true); actionToolInformation = new QAction(pMainWindow); actionToolInformation->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolInformation->setText(pMainWindow->tr("Mesh Information")); actionToolInformation->setCheckable(true); actionToolOperations = new QAction(pMainWindow); actionToolOperations->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolOperations->setText(pMainWindow->tr("Operations")); actionToolOperations->setCheckable(true); actionToolMaterials = new QAction(pMainWindow); actionToolMaterials->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolMaterials->setText(pMainWindow->tr("Materials")); actionToolMaterials->setCheckable(true); actionToolLOD = new QAction(pMainWindow); actionToolLOD->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolLOD->setText(pMainWindow->tr("LOD Generator")); actionToolLOD->setCheckable(true); actionToolCollision = new QAction(pMainWindow); actionToolCollision->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolCollision->setText(pMainWindow->tr("Collision Mesh")); actionToolCollision->setCheckable(true); actionToolImport = new QAction(pMainWindow); actionToolImport->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolImport->setText(pMainWindow->tr("Import Mesh")); actionToolImport->setCheckable(true); actionToolLightManipulator = new QAction(pMainWindow); actionToolLightManipulator->setIcon(QIcon(QStringLiteral(":/editor/icons/Alerts.png"))); actionToolLightManipulator->setText(pMainWindow->tr("Light Manipulator")); actionToolLightManipulator->setCheckable(true); menuMesh = new QMenu(pMainWindow); menuMesh->setTitle(mainWindow->tr("&Mesh")); menuMesh->addAction(actionOpenMesh); menuMesh->addAction(actionSaveMesh); menuMesh->addAction(actionSaveMeshAs); menuMesh->addSeparator(); menuMesh->addAction(actionClose); menuCamera = new QMenu(pMainWindow); menuCamera->setTitle(mainWindow->tr("&Camera")); menuCamera->addAction(actionCameraPerspective); menuCamera->addAction(actionCameraArcball); menuCamera->addAction(actionCameraIsometric); menuView = new QMenu(pMainWindow); menuView->setTitle(mainWindow->tr("&View")); menuView->addAction(actionViewWireframe); menuView->addAction(actionViewUnlit); menuView->addAction(actionViewLit); menuView->addSeparator(); menuView->addAction(actionViewFlagShadows); menuView->addAction(actionViewFlagWireframeOverlay); menuTools = new QMenu(pMainWindow); menuTools->setTitle(mainWindow->tr("&Tools")); menuTools->addAction(actionToolInformation); menuTools->addAction(actionToolOperations); menuTools->addAction(actionToolMaterials); menuTools->addAction(actionToolLOD); menuTools->addAction(actionToolCollision); menuTools->addAction(actionToolImport); menuTools->addAction(actionToolLightManipulator); menuHelp = new QMenu(pMainWindow); menuHelp->setTitle(mainWindow->tr("&Help")); menubar = new QMenuBar(pMainWindow); menubar->addMenu(menuMesh); menubar->addMenu(menuCamera); menubar->addMenu(menuView); menubar->addMenu(menuTools); menubar->addMenu(menuHelp); pMainWindow->setMenuBar(menubar); toolbar = new QToolBar(pMainWindow); toolbar->setIconSize(QSize(16, 16)); toolbar->addAction(actionOpenMesh); toolbar->addAction(actionSaveMesh); toolbar->addSeparator(); toolbar->addAction(actionCameraPerspective); toolbar->addAction(actionCameraArcball); toolbar->addAction(actionCameraIsometric); toolbar->addSeparator(); toolbar->addAction(actionViewWireframe); toolbar->addAction(actionViewUnlit); toolbar->addAction(actionViewLit); toolbar->addSeparator(); toolbar->addAction(actionViewFlagShadows); toolbar->addAction(actionViewFlagWireframeOverlay); toolbar->addSeparator(); toolbar->addAction(actionToolInformation); toolbar->addAction(actionToolOperations); toolbar->addAction(actionToolMaterials); toolbar->addAction(actionToolLOD); toolbar->addAction(actionToolCollision); toolbar->addAction(actionToolImport); toolbar->addAction(actionToolLightManipulator); pMainWindow->addToolBar(toolbar); statusBar = new QStatusBar(pMainWindow); pMainWindow->setStatusBar(statusBar); // left pane swapChainWidget = new EditorRendererSwapChainWidget(pMainWindow); swapChainWidget->setFocusPolicy(Qt::FocusPolicy(Qt::TabFocus | Qt::ClickFocus)); swapChainWidget->setMouseTracking(true); pMainWindow->setCentralWidget(swapChainWidget); // right pane container rightDockWidget = new QDockWidget(pMainWindow); rightDockWidget->setWindowTitle(pMainWindow->tr("Toolbox")); rightDockWidget->setMinimumSize(320, 400); rightDockContainer = new QWidget(rightDockWidget); { QVBoxLayout *rightDockContainerLayout = new QVBoxLayout(rightDockContainer); rightDockContainerLayout->setContentsMargins(0, 0, 0, 0); // mode toolbar { //rightToolMenu = new QToolBar(rightDockContainer); //rightToolBar->setMovable(false); //rightToolBar->setFloatable(false); //rightToolBar->setOrientation(Qt::Vertical); //rightToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); rightToolMenu = new ToolMenuWidget(rightDockContainer); rightToolMenu->addAction(actionToolInformation); rightToolMenu->addAction(actionToolOperations); rightToolMenu->addAction(actionToolMaterials); rightToolMenu->addAction(actionToolLOD); rightToolMenu->addAction(actionToolCollision); rightToolMenu->addAction(actionToolImport); rightToolMenu->addAction(actionToolLightManipulator); rightToolMenu->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); rightDockContainerLayout->addWidget(rightToolMenu); } // create scroll area for the container toolContainerScrollArea = new QScrollArea(rightDockContainer); toolContainerScrollArea->setBackgroundRole(QPalette::Background); toolContainerScrollArea->setFrameStyle(0); toolContainerScrollArea->setWidgetResizable(true); // tool container toolContainer = new QWidget(toolContainerScrollArea); { QVBoxLayout *toolContainerLayout = new QVBoxLayout(toolContainer); toolContainerLayout->setContentsMargins(0, 0, 0, 0); toolContainerLayout->setMargin(0); toolContainerLayout->setSpacing(0); // information tool { toolInformationContainer = new QWidget(toolContainer); { QFormLayout *formLayout = new QFormLayout(toolInformationContainer); //formLayout->setContentsMargins(2, 2, 2, 2); //formLayout->setMargin(0); //formLayout->setSpacing(0); toolInformationMinBounds = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Min Bounds: "), toolInformationMinBounds); toolInformationMaxBounds = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Max Bounds: "), toolInformationMaxBounds); toolInformationVertexCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Vertex Count: "), toolInformationVertexCount); toolInformationTriangleCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Triangle Count: "), toolInformationTriangleCount); toolInformationMaterialCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Material Count: "), toolInformationMaterialCount); toolInformationBatchCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Batch Count: "), toolInformationBatchCount); toolInformationEnableTextureCoordinates = new QCheckBox(pMainWindow->tr("Enable Texture Coordinates"), toolInformationContainer); formLayout->addRow(toolInformationEnableTextureCoordinates); toolInformationEnableVertexColors = new QCheckBox(pMainWindow->tr("Enable Vertex Colors"), toolInformationContainer); formLayout->addRow(toolInformationEnableVertexColors); toolInformationContainer->setLayout(formLayout); } toolInformationContainer->hide(); toolContainerLayout->addWidget(toolInformationContainer); } // operations tool { toolOperationsContainer = new QWidget(toolContainer); { QVBoxLayout *boxLayout = new QVBoxLayout(toolOperationsContainer); toolOperationsGenerateTangents = new QPushButton(pMainWindow->tr("Generate Tangents"), toolOperationsContainer); boxLayout->addWidget(toolOperationsGenerateTangents); toolOperationsCenterMesh = new QPushButton(pMainWindow->tr("Center Mesh..."), toolOperationsContainer); boxLayout->addWidget(toolOperationsCenterMesh); toolOperationsRemoveUnusedVertices = new QPushButton(pMainWindow->tr("Remove Unused Vertices"), toolOperationsContainer); boxLayout->addWidget(toolOperationsRemoveUnusedVertices); toolOperationsRemoveUnusedTriangles = new QPushButton(pMainWindow->tr("Remove Unused Triangles"), toolOperationsContainer); boxLayout->addWidget(toolOperationsRemoveUnusedTriangles); toolOperationsContainer->setLayout(boxLayout); } toolOperationsContainer->hide(); toolContainerLayout->addWidget(toolOperationsContainer); } // materials tool { toolMaterialsContainer = new QWidget(toolContainer); toolMaterialsContainer->hide(); toolContainerLayout->addWidget(toolMaterialsContainer); } // lods tool { toolLODContainer = new QWidget(toolContainer); toolLODContainer->hide(); toolContainerLayout->addWidget(toolLODContainer); } // collision tool { toolCollisionContainer = new QWidget(toolContainer); { QVBoxLayout *boxLayout = new QVBoxLayout(toolCollisionContainer); toolCollisionInformation = new QLabel(toolCollisionContainer); boxLayout->addWidget(toolCollisionInformation); { QGroupBox *groupBox = new QGroupBox(pMainWindow->tr("Build Shape"), toolCollisionContainer); QVBoxLayout *groupBoxLayout = new QVBoxLayout(groupBox); toolCollisionGenerateBox = new QRadioButton(pMainWindow->tr("Box"), groupBox); groupBoxLayout->addWidget(toolCollisionGenerateBox); toolCollisionGenerateSphere = new QRadioButton(pMainWindow->tr("Sphere"), groupBox); groupBoxLayout->addWidget(toolCollisionGenerateSphere); toolCollisionGenerateTriangleMesh = new QRadioButton(pMainWindow->tr("Triangle Mesh"), groupBox); groupBoxLayout->addWidget(toolCollisionGenerateTriangleMesh); toolCollisionGenerateConvexHull = new QRadioButton(pMainWindow->tr("Convex Hull"), groupBox); groupBoxLayout->addWidget(toolCollisionGenerateConvexHull); toolCollisionGenerate = new QPushButton(pMainWindow->tr("Rebuild..."), groupBox); groupBoxLayout->addWidget(toolCollisionGenerate); boxLayout->addWidget(groupBox); } toolCollisionContainer->setLayout(boxLayout); } toolCollisionContainer->hide(); toolContainerLayout->addWidget(toolCollisionContainer); } // import tool { toolImportContainer = new QWidget(toolContainer); { QFormLayout *formLayout = new QFormLayout(toolImportContainer); formLayout->setLabelAlignment(Qt::AlignTop); toolImportSelectFileName = new QPushButton(pMainWindow->tr("Select File..."), toolImportContainer); formLayout->addRow(toolImportSelectFileName); toolImportSubMeshName = new QComboBox(toolImportContainer); formLayout->addRow(pMainWindow->tr("Sub Mesh: "), toolImportSubMeshName); toolImportCoordinateSystem = new QComboBox(toolImportContainer); toolImportCoordinateSystem->addItem(pMainWindow->tr("Y-Up Left Handed")); toolImportCoordinateSystem->addItem(pMainWindow->tr("Y-Up Right Handed")); toolImportCoordinateSystem->addItem(pMainWindow->tr("Z-Up Left Handed")); toolImportCoordinateSystem->addItem(pMainWindow->tr("Z-Up Right Handed")); formLayout->addRow(pMainWindow->tr("Coordinate System: "), toolImportCoordinateSystem); toolImportFaceWinding = new QComboBox(toolImportContainer); toolImportFaceWinding->addItem(pMainWindow->tr("Counter-Clockwise")); toolImportFaceWinding->addItem(pMainWindow->tr("Clockwise")); formLayout->addRow(pMainWindow->tr("Face Winding: "), toolImportFaceWinding); toolImportGenerateTangents = new QCheckBox(pMainWindow->tr("Generate Tangents"), toolImportContainer); toolImportGenerateTangents->setChecked(true); formLayout->addRow(toolImportGenerateTangents); toolImportScale = new EditorVectorEditWidget(toolImportContainer); toolImportScale->SetNumComponents(3); toolImportScale->SetValue(1.0f, 1.0f, 1.0f); formLayout->addRow(pMainWindow->tr("Scale: "), toolImportScale); toolImportMaterials = new QCheckBox(pMainWindow->tr("Import Materials"), toolImportContainer); toolImportMaterials->setChecked(true); formLayout->addRow(toolImportMaterials); toolImportMaterialDirectory = new QLineEdit(toolImportContainer); formLayout->addRow(pMainWindow->tr("Material Directory"), toolImportMaterialDirectory); toolImportMaterialPrefix = new QLineEdit(toolImportContainer); formLayout->addRow(pMainWindow->tr("Material Prefix"), toolImportMaterialPrefix); toolImportImport = new QPushButton(pMainWindow->tr("Import..."), toolImportContainer); toolImportImport->setEnabled(false); formLayout->addRow(toolImportImport); toolImportContainer->setLayout(formLayout); } toolImportContainer->hide(); toolContainerLayout->addWidget(toolImportContainer); } // light manipulator tool { toolLightManipulatorContainer = new QWidget(toolContainer); { } toolLightManipulatorContainer->hide(); toolContainerLayout->addWidget(toolLightManipulatorContainer); } toolContainerLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding)); toolContainer->setLayout(toolContainerLayout); } toolContainerScrollArea->setWidget(toolContainer); // complete container setup rightDockContainerLayout->addWidget(toolContainerScrollArea, 1); rightDockContainer->setLayout(rightDockContainerLayout); } rightDockWidget->setWidget(rightDockContainer); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, rightDockWidget); } void UpdateUIForCameraMode(EDITOR_CAMERA_MODE cameraMode) { actionCameraPerspective->setChecked((cameraMode == EDITOR_CAMERA_MODE_PERSPECTIVE)); actionCameraArcball->setChecked((cameraMode == EDITOR_CAMERA_MODE_ARCBALL)); actionCameraIsometric->setChecked((cameraMode == EDITOR_CAMERA_MODE_ISOMETRIC)); } void UpdateUIForRenderMode(EDITOR_RENDER_MODE renderMode) { actionViewWireframe->setChecked((renderMode == EDITOR_RENDER_MODE_WIREFRAME)); actionViewUnlit->setChecked((renderMode == EDITOR_RENDER_MODE_FULLBRIGHT)); actionViewLit->setChecked((renderMode == EDITOR_RENDER_MODE_LIT)); } void UpdateUIForViewportFlags(uint32 viewportFlags) { actionViewFlagShadows->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) != 0); actionViewFlagWireframeOverlay->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) != 0); } void UpdateUIForTool(EditorSkeletalMeshEditor::Tool tool) { (tool == EditorSkeletalMeshEditor::Tool_Information) ? toolInformationContainer->show() : toolInformationContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_Operations) ? toolOperationsContainer->show() : toolOperationsContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_Materials) ? toolMaterialsContainer->show() : toolMaterialsContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_LOD) ? toolLODContainer->show() : toolLODContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_Collision) ? toolCollisionContainer->show() : toolCollisionContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_Import) ? toolImportContainer->show() : toolImportContainer->hide(); (tool == EditorSkeletalMeshEditor::Tool_LightManipulator) ? toolLightManipulatorContainer->show() : toolLightManipulatorContainer->hide(); actionToolInformation->setChecked((tool == EditorSkeletalMeshEditor::Tool_Information)); actionToolOperations->setChecked((tool == EditorSkeletalMeshEditor::Tool_Operations)); actionToolMaterials->setChecked((tool == EditorSkeletalMeshEditor::Tool_Materials)); actionToolLOD->setChecked((tool == EditorSkeletalMeshEditor::Tool_LOD)); actionToolCollision->setChecked((tool == EditorSkeletalMeshEditor::Tool_Collision)); actionToolImport->setChecked((tool == EditorSkeletalMeshEditor::Tool_Import)); actionToolLightManipulator->setChecked((tool == EditorSkeletalMeshEditor::Tool_LightManipulator)); } }; <file_sep>/Engine/Source/ResourceCompilerStandalone/CMakeLists.txt set(HEADER_FILES ) set(SOURCE_FILES Main.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/ResourceCompilerStandalone) add_executable(ResourceCompiler ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(ResourceCompiler EngineResourceCompiler EngineMain EngineCore) install(TARGETS ResourceCompiler DESTINATION ${INSTALL_BINARIES_DIRECTORY}) <file_sep>/Engine/Source/Engine/MaterialShader.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/MaterialShader.h" #include "Engine/Material.h" #include "Engine/Texture.h" #include "Engine/DataFormats.h" #include "Renderer/VertexFactory.h" #include "Renderer/Renderer.h" #include "Renderer/RenderQueue.h" Log_SetChannel(MaterialShader); DEFINE_RESOURCE_TYPE_INFO(MaterialShader); DEFINE_RESOURCE_GENERIC_FACTORY(MaterialShader); MaterialShader::MaterialShader(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(pResourceTypeInfo) { m_blendingMode = MATERIAL_BLENDING_MODE_NONE; m_lightingType = MATERIAL_LIGHTING_TYPE_REFLECTIVE; m_lightingModel = MATERIAL_LIGHTING_MODEL_PHONG; m_lightingNormalSpace = MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE; m_renderMode = MATERIAL_RENDER_MODE_NORMAL; m_renderLayer = MATERIAL_RENDER_LAYER_NORMAL; m_twoSided = false; m_depthClamping = false; m_depthTests = true; m_depthWrites = true; m_castShadows = true; m_receiveShadows = true; } MaterialShader::~MaterialShader() { ReleaseDeviceResources(); } bool MaterialShader::Load(const char *resourceName, ByteStream *pStream) { BinaryReader binaryReader(pStream); // set name m_strName = resourceName; // read header DF_MATERIAL_SHADER_HEADER header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Magic != DF_MATERIAL_SHADER_HEADER_MAGIC || header.HeaderSize != sizeof(header)) return false; // copy properties m_blendingMode = (MATERIAL_BLENDING_MODE)header.BlendingMode; m_lightingType = (MATERIAL_LIGHTING_TYPE)header.LightingType; m_lightingModel = (MATERIAL_LIGHTING_MODEL)header.LightingModel; m_lightingNormalSpace = (MATERIAL_LIGHTING_NORMAL_SPACE)header.LightingNormalSpace; m_renderMode = (MATERIAL_RENDER_MODE)header.RenderMode; m_renderLayer = (MATERIAL_RENDER_LAYER)header.RenderLayer; m_twoSided = header.TwoSided; m_depthClamping = header.DepthClamping; m_depthTests = header.DepthTests; m_depthWrites = header.DepthWrites; m_castShadows = header.CastShadows; m_receiveShadows = header.ReceiveShadows; m_sourceCRC = header.SourceCRC; // copy uniforms m_UniformParameters.Resize(header.UniformParameterCount); for (uint32 i = 0; i < m_UniformParameters.GetSize(); i++) { DF_MATERIAL_SHADER_UNIFORM_PARAMETER uniformHeader; if (!binaryReader.SafeReadBytes(&uniformHeader, sizeof(uniformHeader))) return false; UniformParameter *pDestinationUniformParameter = &m_UniformParameters[i]; pDestinationUniformParameter->Index = i; pDestinationUniformParameter->Type = (SHADER_PARAMETER_TYPE)uniformHeader.Type; Y_memcpy(&pDestinationUniformParameter->DefaultValue, &uniformHeader.DefaultValue, sizeof(pDestinationUniformParameter->DefaultValue)); if (!binaryReader.SafeReadFixedString(uniformHeader.NameLength, &pDestinationUniformParameter->Name)) return false; } // copy textures m_TextureParameters.Resize(header.TextureParameterCount); for (uint32 i = 0; i < m_TextureParameters.GetSize(); i++) { DF_MATERIAL_SHADER_TEXTURE_PARAMETER textureHeader; if (!binaryReader.SafeReadBytes(&textureHeader, sizeof(textureHeader))) return false; TextureParameter *pDestinationTextureParameter = &m_TextureParameters[i]; pDestinationTextureParameter->Index = i; pDestinationTextureParameter->Type = (TEXTURE_TYPE)textureHeader.Type; if (!binaryReader.SafeReadFixedString(textureHeader.NameLength, &pDestinationTextureParameter->Name) || !binaryReader.SafeReadFixedString(textureHeader.DefaultValueLength, &pDestinationTextureParameter->DefaultValue)) { return false; } } // copy static switches m_StaticSwitchParameters.Resize(header.StaticSwitchParameterCount); for (uint32 i = 0; i < m_StaticSwitchParameters.GetSize(); i++) { DF_MATERIAL_SHADER_STATIC_SWITCH_PARAMETER staticSwitchHeader; if (!binaryReader.SafeReadBytes(&staticSwitchHeader, sizeof(staticSwitchHeader))) return false; StaticSwitchParameter *pDestinationStaticSwitchParameter = &m_StaticSwitchParameters[i]; pDestinationStaticSwitchParameter->Index = i; pDestinationStaticSwitchParameter->Mask = staticSwitchHeader.Mask; pDestinationStaticSwitchParameter->DefaultValue = staticSwitchHeader.DefaultValue; if (!binaryReader.SafeReadFixedString(staticSwitchHeader.NameLength, &pDestinationStaticSwitchParameter->Name)) return false; } // create on gpu if (!CreateDeviceResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } // ok return true; } int32 MaterialShader::FindUniformParameter(const char *Name) const { uint32 i; for (i = 0; i < m_UniformParameters.GetSize(); i++) { if (m_UniformParameters[i].Name.Compare(Name)) return (int32)i; } return -1; } int32 MaterialShader::FindTextureParameter(const char *Name) const { uint32 i; for (i = 0; i < m_TextureParameters.GetSize(); i++) { if (m_TextureParameters[i].Name.Compare(Name)) return (int32)i; } return -1; } int32 MaterialShader::FindStaticSwitchParameter(const char *Name) const { uint32 i; for (i = 0; i < m_StaticSwitchParameters.GetSize(); i++) { if (m_StaticSwitchParameters[i].Name.Compare(Name)) return (int32)i; } return -1; } bool MaterialShader::CreateDeviceResources() const { return true; } void MaterialShader::ReleaseDeviceResources() const { m_ShaderMap.ReleaseGPUResources(); } uint32 MaterialShader::SelectRenderPassMask(uint32 wantedPassMask) const { uint32 newPassMask = wantedPassMask; // // for blended objects, we need to disable the base pass, as we don't write depth values // switch (m_eBlendingMode) // { // case MATERIAL_BLENDING_MODE_STRAIGHT: // case MATERIAL_BLENDING_MODE_PREMULTIPLIED: // newPassMask &= ~RENDER_PASS_Z_PREPASS; // break; // } switch (m_lightingType) { case MATERIAL_LIGHTING_TYPE_EMISSIVE: newPassMask &= ~(RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING); break; case MATERIAL_LIGHTING_TYPE_REFLECTIVE: case MATERIAL_LIGHTING_TYPE_REFLECTIVE_TWO_SIDED: newPassMask &= ~(RENDER_PASS_EMISSIVE); break; case MATERIAL_LIGHTING_TYPE_REFLECTIVE_EMISSIVE: break; } // custom lighting cannot use lightmaps if (m_lightingModel == MATERIAL_LIGHTING_MODEL_CUSTOM) newPassMask &= ~(RENDER_PASS_LIGHTMAP); if (!m_castShadows) newPassMask &= ~(RENDER_PASS_SHADOW_MAP); if (!m_receiveShadows) newPassMask &= ~(RENDER_PASS_SHADOWED_LIGHTING); return newPassMask; } uint8 MaterialShader::SelectRenderQueueLayer() const { switch (m_renderLayer) { case MATERIAL_RENDER_LAYER_SKYBOX: return RENDER_QUEUE_LAYER_SKYBOX; } return RENDER_QUEUE_LAYER_NONE; } GPUBlendState *MaterialShader::SelectBlendState() const { switch (m_blendingMode) { case MATERIAL_BLENDING_MODE_ADDITIVE: return g_pRenderer->GetFixedResources()->GetBlendStateAdditive(); case MATERIAL_BLENDING_MODE_STRAIGHT: return g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending(); case MATERIAL_BLENDING_MODE_PREMULTIPLIED: return g_pRenderer->GetFixedResources()->GetBlendStatePremultipliedAlpha(); case MATERIAL_BLENDING_MODE_SOFTMASKED: return g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending(); //case MATERIAL_BLENDING_MODE_NONE: //case MATERIAL_BLENDING_MODE_MASKED: <-- alphakill will take care of this default: return g_pRenderer->GetFixedResources()->GetBlendStateNoBlending(); } } GPURasterizerState *MaterialShader::SelectRasterizerState(RENDERER_FILL_MODE fillMode /* = RENDERER_FILL_SOLID */, RENDERER_CULL_MODE cullMode /* = RENDERER_CULL_BACK */, bool depthBias /* = false */, bool scissorTest /* = false */) const { return g_pRenderer->GetFixedResources()->GetRasterizerState((m_renderMode == MATERIAL_RENDER_MODE_WIREFRAME) ? RENDERER_FILL_WIREFRAME : fillMode, (m_twoSided) ? RENDERER_CULL_NONE : cullMode, depthBias, m_depthClamping, scissorTest); } GPUDepthStencilState *MaterialShader::SelectDepthStencilState(bool depthTests /*= true*/, bool depthWrites /*= true*/, GPU_COMPARISON_FUNC comparisonFunc /*= GPU_COMPARISON_FUNC_LESS*/) const { return g_pRenderer->GetFixedResources()->GetDepthStencilState(depthTests & m_depthTests, depthWrites & m_depthWrites, comparisonFunc); } <file_sep>/Engine/Source/MathLib/Vectori.h #pragma once #include "MathLib/Common.h" #include "MathLib/VectorShuffles.h" // interoperability between int/vector types struct Vector2i; struct Vector3i; struct Vector4i; struct SIMDVector2i; struct SIMDVector3i; struct SIMDVector4i; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector2i { // constructors inline Vector2i() {} inline Vector2i(int32 x_, int32 y_) : x(x_), y(y_) {} inline Vector2i(int32 *p) : x(p[0]), y(p[1]) {} inline Vector2i(const Vector2i &v) : x(v.x), y(v.y) {} Vector2i(const SIMDVector2i &v); // setters void Set(int32 x_, int32 y_) { x = x_; y = y_; } void Set(const Vector2i &v) { x = v.x; y = v.y; } void Set(const SIMDVector2i &v); void SetZero() { x = y = 0; } // load/store void Load(const int32 *v) { x = v[0]; y = v[1]; } void Store(int32 *v) const { v[0] = x; v[1] = y; } // new vector Vector2i operator+(const Vector2i &v) const { return Vector2i(x + v.x, y + v.y); } Vector2i operator-(const Vector2i &v) const { return Vector2i(x - v.x, y - v.y); } Vector2i operator*(const Vector2i &v) const { return Vector2i(x * v.x, y * v.y); } Vector2i operator/(const Vector2i &v) const { return Vector2i(x / v.x, y / v.y); } Vector2i operator%(const Vector2i &v) const { return Vector2i(x % v.x, y % v.y); } Vector2i operator&(const Vector2i &v) const { return Vector2i(x & v.x, y & v.y); } Vector2i operator|(const Vector2i &v) const { return Vector2i(x | v.x, y | v.y); } Vector2i operator^(const Vector2i &v) const { return Vector2i(x ^ v.x, y ^ v.y); } // scalar operators Vector2i operator+(const int32 v) const { return Vector2i(x + v, y + v); } Vector2i operator-(const int32 v) const { return Vector2i(x - v, y - v); } Vector2i operator*(const int32 v) const { return Vector2i(x * v, y * v); } Vector2i operator/(const int32 v) const { return Vector2i(x / v, y / v); } Vector2i operator%(const int32 v) const { return Vector2i(x % v, y % v); } Vector2i operator&(const int32 v) const { return Vector2i(x & v, y & v); } Vector2i operator|(const int32 v) const { return Vector2i(x | v, y | v); } Vector2i operator^(const int32 v) const { return Vector2i(x ^ v, y ^ v); } // no params Vector2i operator~() const { return Vector2i(~x, ~y); } Vector2i operator-() const { return Vector2i(-x, -y); } // comparison operators bool operator==(const Vector2i &v) const { return (x == v.x && y == v.y); } bool operator!=(const Vector2i &v) const { return (x != v.x || y != v.y); } bool operator<=(const Vector2i &v) const { return (x <= v.x && y <= v.y); } bool operator>=(const Vector2i &v) const { return (x >= v.x && y >= v.y); } bool operator<(const Vector2i &v) const { return (x < v.x && y < v.y); } bool operator>(const Vector2i &v) const { return (x > v.x && y > v.y); } // modifies this vector Vector2i &operator+=(const Vector2i &v) { x += v.x; y += v.y; return *this; } Vector2i &operator-=(const Vector2i &v) { x -= v.x; y -= v.y; return *this; } Vector2i &operator*=(const Vector2i &v) { x *= v.x; y *= v.y; return *this; } Vector2i &operator/=(const Vector2i &v) { x /= v.x; y /= v.y; return *this; } Vector2i &operator%=(const Vector2i &v) { x %= v.x; y %= v.y; return *this; } Vector2i &operator&=(const Vector2i &v) { x &= v.x; y &= v.y; return *this; } Vector2i &operator|=(const Vector2i &v) { x |= v.x; y |= v.y; return *this; } Vector2i &operator^=(const Vector2i &v) { x ^= v.x; y ^= v.y; return *this; } Vector2i &operator=(const Vector2i &v) { x = v.x; y = v.y; return *this; } // scalar operators Vector2i &operator+=(const int32 v) { x += v; y += v; return *this; } Vector2i &operator-=(const int32 v) { x -= v; y -= v; return *this; } Vector2i &operator*=(const int32 v) { x *= v; y *= v; return *this; } Vector2i &operator/=(const int32 v) { x /= v; y /= v; return *this; } Vector2i &operator%=(const int32 v) { x %= v; y %= v; return *this; } Vector2i &operator&=(const int32 v) { x &= v; y &= v; return *this; } Vector2i &operator|=(const int32 v) { x |= v; y |= v; return *this; } Vector2i &operator^=(const int32 v) { x ^= v; y ^= v; return *this; } Vector2i &operator=(const int32 v) { x = v; y = v; return *this; } // vector2i Vector2i &operator=(const SIMDVector2i &v); // index accessors const int32 &operator[](uint32 i) const { return (&x)[i]; } int32 &operator[](uint32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // partial comparisons bool AnyLess(const Vector2i &v) const { return (x < v.x || y < v.y); } bool AnyLessEqual(const Vector2i &v) const { return (x <= v.x || y <= v.y); } bool AnyGreater(const Vector2i &v) const { return (x > v.x || y > v.y); } bool AnyGreaterEqual(const Vector2i &v) const { return (x >= v.x || y >= v.y); } //bool NearEqual(const int2 &v, int32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon); } // modification functions Vector2i Min(const Vector2i &v) const { return Vector2i((x > v.x) ? v.x : x, (y > v.y) ? v.y : y); } Vector2i Max(const Vector2i &v) const { return Vector2i((x < v.x) ? v.x : x, (y < v.y) ? v.y : y); } Vector2i Clamp(const Vector2i &lBounds, const Vector2i &uBounds) const { return Min(uBounds).Max(lBounds); } Vector2i Abs() const { return Vector2i((x < 0) ? -x : x, (y < 0) ? -y : y); } Vector2i Saturate() const { return Clamp(Zero, One); } Vector2i Snap(const Vector2i &v) const { return Vector2i(Math::Snap(x, v.x), Math::Snap(y, v.y)); } // swap void Swap(Vector2i &v) { int32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; } // maximum of all components int32 MinOfComponents() const { return ::Min(x, y); } int32 MaxOfComponents() const { return ::Max(x, y); } // shuffles template<int V0, int V1> Vector2i Shuffle2() const { const int32 *pv = (const int32 *)&x; Vector2i result; result.x = pv[V0]; result.y = pv[V1]; return result; } VECTOR2_SHUFFLE_FUNCTIONS(Vector2i); //---------------------------------------------------------------------- union { struct { int32 x, y; }; struct { int32 r, g; }; int32 ele[2]; }; //---------------------------------------------------------------------- static const Vector2i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector3i { // constructors inline Vector3i() {} inline Vector3i(int32 x_, int32 y_, int32 z_) : x(x_), y(y_), z(z_) {} inline Vector3i(int32 *p) : x(p[0]), y(p[1]), z(p[2]) {} inline Vector3i(const Vector2i &v, int32 z_ = 0) : x(v.x), y(v.y), z(z_) {} inline Vector3i(const Vector3i &v) : x(v.x), y(v.y), z(v.z) {} Vector3i(const SIMDVector3i &v); // setters void Set(int32 x_, int32 y_, int32 z_) { x = x_; y = y_; z = z_; } void Set(const Vector2i &v, int32 z_ = 0) { x = v.x; y = v.y; z = z_; } void Set(const Vector3i &v) { x = v.x; y = v.y; z = v.z; } void Set(const SIMDVector3i &v); void SetZero() { x = y = z = 0; } // load/store void Load(const int32 *v) { x = v[0]; y = v[1]; z = v[2]; } void Store(int32 *v) const { v[0] = x; v[1] = y; v[2] = z;} // new vector Vector3i operator+(const Vector3i &v) const { return Vector3i(x + v.x, y + v.y, z + v.z); } Vector3i operator-(const Vector3i &v) const { return Vector3i(x - v.x, y - v.y, z - v.z); } Vector3i operator*(const Vector3i &v) const { return Vector3i(x * v.x, y * v.y, z * v.z); } Vector3i operator/(const Vector3i &v) const { return Vector3i(x / v.x, y / v.y, z / v.z); } Vector3i operator%(const Vector3i &v) const { return Vector3i(x % v.x, y % v.y, z % v.z); } Vector3i operator&(const Vector3i &v) const { return Vector3i(x & v.x, y & v.y, z & v.z); } Vector3i operator|(const Vector3i &v) const { return Vector3i(x | v.x, y | v.y, z | v.z); } Vector3i operator^(const Vector3i &v) const { return Vector3i(x ^ v.x, y ^ v.y, z ^ v.z); } // scalar operators Vector3i operator+(const int32 v) const { return Vector3i(x + v, y + v, z + v); } Vector3i operator-(const int32 v) const { return Vector3i(x - v, y - v, z - v); } Vector3i operator*(const int32 v) const { return Vector3i(x * v, y * v, z * v); } Vector3i operator/(const int32 v) const { return Vector3i(x / v, y / v, z / v); } Vector3i operator%(const int32 v) const { return Vector3i(x % v, y % v, z % v); } Vector3i operator&(const int32 v) const { return Vector3i(x & v, y & v, z & v); } Vector3i operator|(const int32 v) const { return Vector3i(x | v, y | v, z | v); } Vector3i operator^(const int32 v) const { return Vector3i(x ^ v, y ^ v, z ^ v); } // no params Vector3i operator~() const { return Vector3i(~x, ~y, ~z); } Vector3i operator-() const { return Vector3i(-x, -y, -z); } // comparison operators bool operator==(const Vector3i &v) const { return (x == v.x && y == v.y && z == v.z); } bool operator!=(const Vector3i &v) const { return (x != v.x || y != v.y || z != v.z); } bool operator<=(const Vector3i &v) const { return (x <= v.x && y <= v.y && z <= v.z); } bool operator>=(const Vector3i &v) const { return (x >= v.x && y >= v.y && z >= v.z); } bool operator<(const Vector3i &v) const { return (x < v.x && y < v.y && z < v.z); } bool operator>(const Vector3i &v) const { return (x > v.x && y > v.y && z > v.z); } // modifies this vector Vector3i &operator+=(const Vector3i &v) { x += v.x; y += v.y; z += v.z; return *this; } Vector3i &operator-=(const Vector3i &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3i &operator*=(const Vector3i &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } Vector3i &operator/=(const Vector3i &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } Vector3i &operator%=(const Vector3i &v) { x %= v.x; y %= v.y; z %= v.z; return *this; } Vector3i &operator&=(const Vector3i &v) { x &= v.x; y &= v.y; z &= v.z; return *this; } Vector3i &operator|=(const Vector3i &v) { x |= v.x; y |= v.y; z |= v.z; return *this; } Vector3i &operator^=(const Vector3i &v) { x ^= v.x; y ^= v.y; z ^= v.z; return *this; } Vector3i &operator=(const Vector3i &v) { x = v.x; y = v.y; z = v.z; return *this; } // scalar operators Vector3i &operator+=(const int32 v) { x += v; y += v; z += v; return *this; } Vector3i &operator-=(const int32 v) { x -= v; y -= v; z -= v; return *this; } Vector3i &operator*=(const int32 v) { x *= v; y *= v; z *= v; return *this; } Vector3i &operator/=(const int32 v) { x /= v; y /= v; z /= v; return *this; } Vector3i &operator%=(const int32 v) { x %= v; y %= v; z %= v; return *this; } Vector3i &operator&=(const int32 v) { x &= v; y &= v; z &= v; return *this; } Vector3i &operator|=(const int32 v) { x |= v; y |= v; z |= v; return *this; } Vector3i &operator^=(const int32 v) { x ^= v; y ^= v; z ^= v; return *this; } Vector3i &operator=(const int32 v) { x = v; y = v; z = v; return *this; } // vector3i Vector3i &operator=(const SIMDVector3i &v); // index accessors const int32 &operator[](uint32 i) const { return (&x)[i]; } int32 &operator[](uint32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // partial comparisons bool AnyLess(const Vector3i &v) const { return (x < v.x || y < v.y || z < v.z); } bool AnyLessEqual(const Vector3i &v) const { return (x <= v.x || y <= v.y || z <= v.z); } bool AnyGreater(const Vector3i &v) const { return (x > v.x || y > v.y || z > v.z); } bool AnyGreaterEqual(const Vector3i &v) const { return (x >= v.x || y >= v.y || z >= v.z); } //bool NearEqual(const int3 &v, int32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon || abs(z - v.z) <= Epsilon); } // modification functions Vector3i Min(const Vector3i &v) const { return Vector3i((x > v.x) ? v.x : x, (y > v.y) ? v.y : y, (z > v.z) ? v.z : z); } Vector3i Max(const Vector3i &v) const { return Vector3i((x < v.x) ? v.x : x, (y < v.y) ? v.y : y, (z < v.z) ? v.z : z); } Vector3i Clamp(const Vector3i &lBounds, const Vector3i &uBounds) const { return Min(uBounds).Max(lBounds); } Vector3i Abs() const { return Vector3i((x < 0) ? -x : x, (y < 0) ? -y : y, (z < 0) ? -z : z); } Vector3i Saturate() const { return Clamp(Zero, One); } Vector3i Snap(const Vector3i &v) const { return Vector3i(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z)); } // swap void Swap(Vector3i &v) { int32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; tmp = v.z; v.z = z; z = tmp; } // maximum of all components int32 MinOfComponents() const { return ::Min(x, ::Min(y, z)); } int32 MaxOfComponents() const { return ::Max(x, ::Max(y, z)); } // shuffles template<int V0, int V1> Vector2i Shuffle2() const { const int32 *pv = (const int32 *)&x; Vector2i result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3i Shuffle3() const { const int32 *pv = (const int32 *)&x; Vector3i result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } VECTOR3_SHUFFLE_FUNCTIONS(Vector2i, Vector3i); //---------------------------------------------------------------------- union { struct { int32 x, y, z; }; struct { int32 r, g, b; }; int32 ele[3]; }; //---------------------------------------------------------------------- static const Vector3i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector4i { // constructors inline Vector4i() {} inline Vector4i(int32 x_, int32 y_, int32 z_, int32 w_) : x(x_), y(y_), z(z_), w(w_) {} inline Vector4i(int32 *p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) {} inline Vector4i(const Vector2i &v, int32 z_ = 0, int32 w_ = 0) : x(v.x), y(v.y), z(z_), w(w_) {} inline Vector4i(const Vector3i &v, int32 w_ = 0) : x(v.x), y(v.y), z(v.z), w(w_) {} inline Vector4i(const Vector4i &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} Vector4i(const SIMDVector4i &v); // setters void Set(int32 x_, int32 y_, int32 z_, int32 w_) { x = x_; y = y_; z = z_; w = w_; } void Set(const Vector2i &v, int32 z_ = 0, int32 w_ = 0) { x = v.x; y = v.y; z = z_; w = w_; } void Set(const Vector3i &v, int32 w_ = 0) { x = v.x; y = v.y; z = v.z; w = w_; } void Set(const Vector4i &v) { x = v.x; y = v.y; z = v.z; w = v.w; } void Set(const SIMDVector4i &v); void SetZero() { x = y = z = w = 0; } // load/store void Load(const int32 *v) { x = v[0]; y = v[1]; z = v[2]; w = v[3]; } void Store(int32 *v) const { v[0] = x; v[1] = y; v[2] = z; v[3] = w; } // new vector Vector4i operator+(const Vector4i &v) const { return Vector4i(x + v.x, y + v.y, z + v.z, w + v.w); } Vector4i operator-(const Vector4i &v) const { return Vector4i(x - v.x, y - v.y, z - v.z, w - v.w); } Vector4i operator*(const Vector4i &v) const { return Vector4i(x * v.x, y * v.y, z * v.z, w * v.w); } Vector4i operator/(const Vector4i &v) const { return Vector4i(x / v.x, y / v.y, z / v.z, w / v.w); } Vector4i operator%(const Vector4i &v) const { return Vector4i(x % v.x, y % v.y, z % v.z, w % v.w); } Vector4i operator&(const Vector4i &v) const { return Vector4i(x & v.x, y & v.y, z & v.z, w & v.w); } Vector4i operator|(const Vector4i &v) const { return Vector4i(x | v.x, y | v.y, z | v.z, w | v.w); } Vector4i operator^(const Vector4i &v) const { return Vector4i(x ^ v.x, y ^ v.y, z ^ v.z, w ^ v.w); } // scalar operators Vector4i operator+(const int32 v) const { return Vector4i(x + v, y + v, z + v, w + v); } Vector4i operator-(const int32 v) const { return Vector4i(x - v, y - v, z - v, w - v); } Vector4i operator*(const int32 v) const { return Vector4i(x * v, y * v, z * v, w * v); } Vector4i operator/(const int32 v) const { return Vector4i(x / v, y / v, z / v, w / v); } Vector4i operator%(const int32 v) const { return Vector4i(x % v, y % v, z % v, w % v); } Vector4i operator&(const int32 v) const { return Vector4i(x & v, y & v, z & v, w & v); } Vector4i operator|(const int32 v) const { return Vector4i(x | v, y | v, z | v, w | v); } Vector4i operator^(const int32 v) const { return Vector4i(x ^ v, y ^ v, z ^ v, w ^ v); } // no params Vector4i operator~() const { return Vector4i(~x, ~y, ~z, ~w); } Vector4i operator-() const { return Vector4i(-x, -y, -z, ~w); } // comparison operators bool operator==(const Vector4i &v) const { return (x == v.x && y == v.y && z == v.z && w == v.w); } bool operator!=(const Vector4i &v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); } bool operator<=(const Vector4i &v) const { return (x <= v.x && y <= v.y && z <= v.z && w <= v.w); } bool operator>=(const Vector4i &v) const { return (x >= v.x && y >= v.y && z >= v.z && w >= v.w); } bool operator<(const Vector4i &v) const { return (x < v.x && y < v.y && z < v.z && w < v.w); } bool operator>(const Vector4i &v) const { return (x > v.x && y > v.y && z > v.z && w > v.w); } // modifies this vector Vector4i &operator+=(const Vector4i &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } Vector4i &operator-=(const Vector4i &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } Vector4i &operator*=(const Vector4i &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } Vector4i &operator/=(const Vector4i &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } Vector4i &operator%=(const Vector4i &v) { x %= v.x; y %= v.y; z %= v.z; w %= v.w; return *this; } Vector4i &operator&=(const Vector4i &v) { x &= v.x; y &= v.y; z &= v.z; w &= v.w; return *this; } Vector4i &operator|=(const Vector4i &v) { x |= v.x; y |= v.y; z |= v.z; w |= v.w; return *this; } Vector4i &operator^=(const Vector4i &v) { x ^= v.x; y ^= v.y; z ^= v.z; w ^= v.w; return *this; } Vector4i &operator=(const Vector4i &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } // scalar operators Vector4i &operator+=(const int32 v) { x += v; y += v; z += v; w += v; return *this; } Vector4i &operator-=(const int32 v) { x -= v; y -= v; z -= v; w -= v; return *this; } Vector4i &operator*=(const int32 v) { x *= v; y *= v; z *= v; w *= v; return *this; } Vector4i &operator/=(const int32 v) { x /= v; y /= v; z /= v; w /= v; return *this; } Vector4i &operator%=(const int32 v) { x %= v; y %= v; z %= v; w %= v; return *this; } Vector4i &operator&=(const int32 v) { x &= v; y &= v; z &= v; w &= v; return *this; } Vector4i &operator|=(const int32 v) { x |= v; y |= v; z |= v; w |= v; return *this; } Vector4i &operator^=(const int32 v) { x ^= v; y ^= v; z ^= v; w ^= v; return *this; } Vector4i &operator=(const int32 v) { x = v; y = v; z = v; w = v; return *this; } // vector4i Vector4i &operator=(const SIMDVector4i &v); // index accessors const int32 &operator[](uint32 i) const { return (&x)[i]; } int32 &operator[](uint32 i) { return (&x)[i]; } operator const int32 *() const { return &x; } operator int32 *() { return &x; } // partial comparisons bool AnyLess(const Vector4i &v) const { return (x < v.x || y < v.y || z < v.z || w < v.w); } bool AnyLessEqual(const Vector4i &v) const { return (x <= v.x || y <= v.y || z <= v.z || w <= v.w); } bool AnyGreater(const Vector4i &v) const { return (x > v.x || y > v.y || z > v.z || w > v.w); } bool AnyGreaterEqual(const Vector4i &v) const { return (x >= v.x || y >= v.y || z >= v.z || w >= v.w); } //bool NearEqual(const int4 &v, int32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon || abs(z - v.z) <= Epsilon || abs(w - v.w) < Epsilon); } // modification functions Vector4i Min(const Vector4i &v) const { return Vector4i((x > v.x) ? v.x : x, (y > v.y) ? v.y : y, (z > v.z) ? v.z : z, (w > v.w) ? v.w : w); } Vector4i Max(const Vector4i &v) const { return Vector4i((x < v.x) ? v.x : x, (y < v.y) ? v.y : y, (z < v.z) ? v.z : z, (w < v.w) ? v.w : w); } Vector4i Clamp(const Vector4i &lBounds, const Vector4i &uBounds) const { return Min(uBounds).Max(lBounds); } Vector4i Abs() const { return Vector4i((x < 0) ? -x : x, (y < 0) ? -y : y, (z < 0) ? -z : z, (w < 0) ? -w : w); } Vector4i Saturate() const { return Clamp(Zero, One); } Vector4i Snap(const Vector4i &v) const { return Vector4i(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z), Math::Snap(w, v.w)); } // swap void Swap(Vector4i &v) { int32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; tmp = v.z; v.z = z; z = tmp; tmp = v.w; v.w = w; w = tmp; } // maximum of all components int32 MinOfComponents() const { return ::Min(x, ::Min(y, ::Min(z, w))); } int32 MaxOfComponents() const { return ::Max(x, ::Max(y, ::Max(z, w))); } // shuffles template<int V0, int V1> Vector2i Shuffle2() const { const int32 *pv = (const int32 *)&x; Vector2i result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3i Shuffle3() const { const int32 *pv = (const int32 *)&x; Vector3i result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } template<int V0, int V1, int V2, int V3> Vector4i Shuffle4() const { const int32 *pv = (const int32 *)&x; Vector4i result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; result.w = pv[V3]; return result; } VECTOR4_SHUFFLE_FUNCTIONS(Vector2i, Vector3i, Vector4i); //---------------------------------------------------------------------- union { struct { int32 x, y, z, w; }; struct { int32 r, g, b, a; }; int32 ele[4]; }; //---------------------------------------------------------------------- static const Vector4i &Zero, &One, &NegativeOne; }; <file_sep>/Engine/Source/Core/DDSReader.h #pragma once #include "Core/Common.h" #include "Core/PixelFormat.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/String.h" enum DDS_TEXTURE_TYPE { DDS_TEXTURE_TYPE_UNKNOWN, DDS_TEXTURE_TYPE_1D, DDS_TEXTURE_TYPE_2D, DDS_TEXTURE_TYPE_3D, DDS_TEXTURE_TYPE_CUBE, DDS_TEXTURE_TYPE_COUNT, }; class DDSReader { public: DDSReader(); ~DDSReader(); static DDS_TEXTURE_TYPE GetStreamDDSTextureType(const char *FileName, ByteStream *pStream); bool Open(const char *FileName, ByteStream *pStream); bool LoadMipLevel(uint32 MipLevel); bool LoadAllMipLevels(); void Close(); DDS_TEXTURE_TYPE GetType() const { return m_eTextureType; } uint32 GetWidth() const { return m_iWidth; } uint32 GetHeight() const { return m_iHeight; } uint32 GetDepth() const { return m_iDepth; } uint32 GetNumMipLevels() const { return m_nMipLevels; } uint32 GetArraySize() const { return m_iArraySize; } PIXEL_FORMAT GetPixelFormat() const { return m_ePixelFormat; } uint32 GetMipSize(uint32 ArrayIndex, uint32 MipLevel) const { return _GetMipLevel(ArrayIndex, MipLevel)->Size; } uint32 GetMipPitch(uint32 ArrayIndex, uint32 MipLevel) const { return _GetMipLevel(ArrayIndex, MipLevel)->Pitch; } const byte *GetMipLevelData(uint32 ArrayIndex, uint32 MipLevel) const { return _GetMipLevel(ArrayIndex, MipLevel)->pData; } private: struct MipLevelData { uint32 Size; uint32 Pitch; uint32 OffsetInFile; byte *pData; }; const MipLevelData *_GetMipLevel(uint32 ArrayIndex, uint32 MipLevel) const; void FreeMipLevels(); String m_strFileName; ByteStream *m_pStream; DDS_TEXTURE_TYPE m_eTextureType; uint32 m_iWidth, m_iHeight, m_iDepth; uint32 m_nMipLevels; uint32 m_iArraySize; PIXEL_FORMAT m_ePixelFormat; MipLevelData *m_pMipLevels; }; <file_sep>/Engine/Source/ResourceCompiler/MaterialShaderGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/MaterialShader.h" struct ResourceCompilerCallbacks; class ShaderGraph; class MaterialShaderGenerator { public: struct UniformParameter { String Name; SHADER_PARAMETER_TYPE Type; MaterialShader::UniformParameter::Value DefaultValue; }; struct TextureParameter { String Name; TEXTURE_TYPE Type; String DefaultValue; }; struct StaticSwitchParameter { String Name; bool DefaultValue; }; public: MaterialShaderGenerator(); ~MaterialShaderGenerator(); void Create(ResourceCompilerCallbacks *pCallbacks); bool LoadFromXML(ResourceCompilerCallbacks *pCallbacks, const char *FileName, ByteStream *pStream); bool SaveToXML(ByteStream *pStream); bool Compile(ByteStream *pOutputStream, uint32 sourceCRC); // getters MATERIAL_BLENDING_MODE GetBlendMode() const { return m_blendingMode; } MATERIAL_LIGHTING_TYPE GetLightingType() const { return m_lightingType; } MATERIAL_LIGHTING_MODEL GetLightingModel() const { return m_lightingModel; } MATERIAL_LIGHTING_NORMAL_SPACE GetLightingNormalSpace() const { return m_lightingNormalSpace; } MATERIAL_RENDER_MODE GetRenderMode() const { return m_renderMode; } MATERIAL_RENDER_LAYER GetRenderLayer() const { return m_renderLayer; } bool GetTwoSided() const { return m_twoSided; } bool GetDepthClamping() const { return m_depthClamping; } bool GetDepthTests() const { return m_depthTests; } bool GetDepthWrites() const { return m_depthWrites; } bool GetCastShadows() const { return m_castShadows; } bool GetReceiveShadows() const { return m_receiveShadows; } // setters void SetBlendMode(MATERIAL_BLENDING_MODE BlendMode) { m_blendingMode = BlendMode; } void SetLightingModel(MATERIAL_LIGHTING_MODEL LightingModel) { m_lightingModel = LightingModel; } void SetRenderMode(MATERIAL_RENDER_MODE renderMode) { m_renderMode = renderMode; } void SetRenderLayer(MATERIAL_RENDER_LAYER renderLayer) { m_renderLayer = renderLayer; } void SetTwoSided(bool Enabled) { m_twoSided = Enabled; } void SetDepthClamping(bool enabled) { m_depthClamping = enabled; } void SetDepthTests(bool enabled) { m_depthTests = enabled; } void SetDepthWrites(bool enabled) { m_depthWrites = enabled; } void SetCastShadows(bool enabled) { m_castShadows = enabled; } // ---- parameters ---- // query parameters const uint32 GetUniformParameterCount() const { return m_UniformParameters.GetSize(); } const uint32 GetTextureParameterCount() const { return m_TextureParameters.GetSize(); } const uint32 GetStaticSwitchParameterCount() const { return m_StaticSwitchParameters.GetSize(); } const UniformParameter *GetUniformParameter(uint32 Index) const { return &m_UniformParameters.GetElement(Index); } const TextureParameter *GetTextureParameter(uint32 Index) const { return &m_TextureParameters.GetElement(Index); } const StaticSwitchParameter *GetStaticSwitchParameter(uint32 Index) const { return &m_StaticSwitchParameters.GetElement(Index); } // create parameters bool CreateUniformParameter(const char *Name, SHADER_PARAMETER_TYPE Type); bool CreateTextureParameter(const char *Name, TEXTURE_TYPE Type); bool CreateStaticSwitchParameter(const char *Name, const char *DefineName); // find parameters int32 FindUniformParameter(const char *Name); int32 FindTextureParameter(const char *Name); int32 FindStaticSwitchParameter(const char *Name); // modify parameters UniformParameter *GetUniformParameter(uint32 Index) { return &m_UniformParameters.GetElement(Index); } TextureParameter *GetTextureParameter(uint32 Index) { return &m_TextureParameters.GetElement(Index); } StaticSwitchParameter *GetStaticSwitchParameter(uint32 Index) { return &m_StaticSwitchParameters.GetElement(Index); } // remove parameters void RemoveUniformParameter(uint32 Index); void RemoveTextureParameter(uint32 Index); void RemoveStaticSwitchParameter(uint32 Index); // ---- sources ---- const bool GetShaderCodeAvailability(RENDERER_FEATURE_LEVEL featureLevel) const { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return (m_pShaderCodes[featureLevel] != nullptr); } const String *GetShaderCode(RENDERER_FEATURE_LEVEL featureLevel) const { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return m_pShaderCodes[featureLevel]; } String *GetShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return m_pShaderCodes[featureLevel]; } String *CreateShaderCode(RENDERER_FEATURE_LEVEL featureLevel); void DeleteShaderCode(RENDERER_FEATURE_LEVEL featureLevel); const bool GetShaderGraphAvailability(RENDERER_FEATURE_LEVEL featureLevel) const { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return (m_pShaderGraphs[featureLevel] != nullptr); } const ShaderGraph *GetShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) const { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return m_pShaderGraphs[featureLevel]; } ShaderGraph *GetShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) { DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); return m_pShaderGraphs[featureLevel]; } ShaderGraph *CreateShaderGraph(ResourceCompilerCallbacks *pCallbacks, RENDERER_FEATURE_LEVEL featureLevel); void DeleteShaderGraph(RENDERER_FEATURE_LEVEL featureLevel); private: // settings MATERIAL_BLENDING_MODE m_blendingMode; MATERIAL_LIGHTING_TYPE m_lightingType; MATERIAL_LIGHTING_MODEL m_lightingModel; MATERIAL_LIGHTING_NORMAL_SPACE m_lightingNormalSpace; MATERIAL_RENDER_MODE m_renderMode; MATERIAL_RENDER_LAYER m_renderLayer; bool m_twoSided; bool m_depthClamping; bool m_depthTests; bool m_depthWrites; bool m_castShadows; bool m_receiveShadows; // parameters Array<UniformParameter> m_UniformParameters; Array<TextureParameter> m_TextureParameters; Array<StaticSwitchParameter> m_StaticSwitchParameters; // present shaders String *m_pShaderCodes[RENDERER_FEATURE_LEVEL_COUNT]; ShaderGraph *m_pShaderGraphs[RENDERER_FEATURE_LEVEL_COUNT]; private: MaterialShaderGenerator(const MaterialShaderGenerator &); MaterialShaderGenerator &operator=(const MaterialShaderGenerator &); }; <file_sep>/Editor/Source/Editor/EditorVirtualFileSystemModel.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorVirtualFileSystemModel.h" EditorVirtualFileSystemModel::EditorVirtualFileSystemModel(QWidget *pParent /*= NULL*/) : QAbstractItemModel(pParent) { } EditorVirtualFileSystemModel::~EditorVirtualFileSystemModel() { } QModelIndex EditorVirtualFileSystemModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex( ) */) const { return QModelIndex(); } QModelIndex EditorVirtualFileSystemModel::parent(const QModelIndex &child) const { return QModelIndex(); } int EditorVirtualFileSystemModel::rowCount(const QModelIndex &parent /*= QModelIndex( ) */) const { return 0; } int EditorVirtualFileSystemModel::columnCount(const QModelIndex &parent /*= QModelIndex( ) */) const { return 0; } bool EditorVirtualFileSystemModel::hasChildren(const QModelIndex &parent /*= QModelIndex( ) */) const { return false; } QVariant EditorVirtualFileSystemModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole */) const { return QVariant(); } QVariant EditorVirtualFileSystemModel::headerData(int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole */) const { return QVariant(); } <file_sep>/Engine/Source/Core/DDSWriter.cpp #include "Core/PrecompiledHeader.h" #include "Core/DDSWriter.h" #include "Core/DDSFormat.h" #include "Core/PixelFormat.h" #include "YBaseLib/Log.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Memory.h" Log_SetChannel(DDSWriter); DDSWriter::DDSWriter() { m_pOutputStream = NULL; m_pfFormat = PIXEL_FORMAT_UNKNOWN; m_uWidth = m_uHeight = m_uDepth = 0; m_uArraySize = m_uMipCount = 0; m_uCurrentMipLevel = 0; m_uCurrentWidth = m_uCurrentHeight = m_uCurrentDepth = 0; } DDSWriter::~DDSWriter() { } void DDSWriter::Initialize(ByteStream *pOutputStream) { m_pOutputStream = pOutputStream; m_eType = DDS_TEXTURE_TYPE_COUNT; m_pfFormat = PIXEL_FORMAT_UNKNOWN; m_uWidth = m_uHeight = m_uDepth = 0; m_uArraySize = m_uMipCount = 0; m_uCurrentMipLevel = 0; m_uCurrentWidth = m_uCurrentHeight = m_uCurrentDepth = 0; } bool DDSWriter::WriteHeader(DDS_TEXTURE_TYPE Type, PIXEL_FORMAT Format, uint32 Width, uint32 Height, uint32 DepthOrArraySize, uint32 MipCount) { DebugAssert(Type < DDS_TEXTURE_TYPE_COUNT && Format < PIXEL_FORMAT_COUNT && DepthOrArraySize > 0 && MipCount > 0); DebugAssert(m_pfFormat == PIXEL_FORMAT_UNKNOWN); // fix dimensions DebugAssert(Width > 0); if (Type == DDS_TEXTURE_TYPE_1D) { Height = 0; } else if (Type == DDS_TEXTURE_TYPE_2D) { DebugAssert(Height > 0); } else if (Type == DDS_TEXTURE_TYPE_3D) { DebugAssert(Height > 0 && DepthOrArraySize > 0); } else if (Type == DDS_TEXTURE_TYPE_CUBE) { DebugAssert(Height > 0); DebugAssert(DepthOrArraySize == 1); } DDS_HEADER Header; Y_memzero(&Header, sizeof(Header)); Header.dwSize = sizeof(DDS_HEADER); Header.dwFlags = DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH; if (MipCount > 1) Header.dwFlags |= DDSD_MIPMAPCOUNT; if (Type != DDS_TEXTURE_TYPE_1D) Header.dwFlags |= DDSD_HEIGHT; if (Type == DDS_TEXTURE_TYPE_3D) Header.dwFlags |= DDSD_DEPTH; Header.dwHeight = Width; Header.dwWidth = (Type != DDS_TEXTURE_TYPE_1D) ? Height : 0; Header.dwDepth = (Type == DDS_TEXTURE_TYPE_3D) ? DepthOrArraySize : 0; Header.dwPitchOrLinearSize = 0; Header.dwMipMapCount = MipCount; Header.dwCaps = DDSCAPS_TEXTURE; if (MipCount > 1) Header.dwCaps |= DDSCAPS_MIPMAP; if (MipCount > 1 || (DepthOrArraySize > 1 || Type == DDS_TEXTURE_TYPE_3D)) Header.dwCaps |= DDSCAPS_COMPLEX; // get output pf info const PIXEL_FORMAT_INFO *ppfInfo = PixelFormat_GetPixelFormatInfo(Format); DebugAssert(ppfInfo != NULL); // fill in ddspf Header.ddspf.dwSize = sizeof(DDS_PIXELFORMAT); if (ppfInfo->IsBlockCompressed) { switch (Format) { case PIXEL_FORMAT_BC1_UNORM: Header.ddspf.dwFourCC = DDS_MAKEFOURCC('D', 'X', 'T', '1'); Header.ddspf.dwFlags = DDS_FOURCC; break; case PIXEL_FORMAT_BC2_UNORM: Header.ddspf.dwFourCC = DDS_MAKEFOURCC('D', 'X', 'T', '3'); Header.ddspf.dwFlags = DDS_FOURCC; break; case PIXEL_FORMAT_BC3_UNORM: Header.ddspf.dwFourCC = DDS_MAKEFOURCC('D', 'X', 'T', '5'); Header.ddspf.dwFlags = DDS_FOURCC; break; } } else { Header.ddspf.dwRGBBitCount = ppfInfo->BitsPerPixel; Header.ddspf.dwRBitMask = ppfInfo->ColorMaskRed; Header.ddspf.dwGBitMask = ppfInfo->ColorMaskGreen; Header.ddspf.dwBBitMask = ppfInfo->ColorMaskBlue; Header.ddspf.dwABitMask = ppfInfo->ColorMaskAlpha; if (ppfInfo->ColorMaskAlpha != 0 && ppfInfo->ColorMaskRed != 0 && ppfInfo->ColorMaskGreen != 0 && ppfInfo->ColorMaskBlue != 0) Header.ddspf.dwFlags = DDS_RGBA; else if (ppfInfo->ColorMaskAlpha == 0 && ppfInfo->ColorMaskRed != 0 && ppfInfo->ColorMaskGreen != 0 && ppfInfo->ColorMaskBlue != 0) Header.ddspf.dwFlags = DDS_RGB; else if (ppfInfo->ColorMaskAlpha == 0 && ppfInfo->ColorMaskRed != 0 && ppfInfo->ColorMaskGreen == 0 && ppfInfo->ColorMaskBlue == 0) Header.ddspf.dwFlags = DDS_LUMINANCE; else if (ppfInfo->ColorMaskAlpha != 0 && ppfInfo->ColorMaskRed == 0 && ppfInfo->ColorMaskGreen == 0 && ppfInfo->ColorMaskBlue == 0) Header.ddspf.dwFlags = DDS_ALPHA; } if (Header.ddspf.dwFlags == 0) { Log_ErrorPrintf("DDSWriter::WriteHeader: Could not determine ddspf for pixel format %s", ppfInfo->Name); return false; } // write the header static const uint32 DDSMagic = DDS_MAGIC; if (m_pOutputStream->Write(&DDSMagic, sizeof(DDSMagic)) != sizeof(DDSMagic) || m_pOutputStream->Write(&Header, sizeof(Header)) != sizeof(Header)) { goto WRITEERROR; } m_eType = Type; m_pfFormat = Format; m_uWidth = m_uCurrentWidth = Width; m_uHeight = m_uCurrentHeight = (Type != DDS_TEXTURE_TYPE_1D) ? Height : 1; m_uDepth = m_uCurrentDepth = (Type == DDS_TEXTURE_TYPE_3D) ? DepthOrArraySize : 1; m_uArraySize = (Type != DDS_TEXTURE_TYPE_3D) ? DepthOrArraySize : 1; m_uMipCount = MipCount; m_uCurrentMipLevel = 0; return true; WRITEERROR: Log_ErrorPrintf("DDSWriter::WriteHeader: Write error at stream position %u size %u", (uint32)m_pOutputStream->GetPosition(), (uint32)m_pOutputStream->GetSize()); return false; } bool DDSWriter::WriteMipLevel(uint32 MipLevel, const void *pData, uint32 cbData) { DebugAssert(m_pfFormat != PIXEL_FORMAT_UNKNOWN); DebugAssert(MipLevel == m_uCurrentMipLevel); DebugAssert(m_uCurrentMipLevel < m_uMipCount); // calc miplevel size uint32 WriteSize = 0; if (m_eType == DDS_TEXTURE_TYPE_1D) WriteSize = PixelFormat_CalculateRowPitch(m_pfFormat, m_uCurrentWidth) * m_uArraySize; else if (m_eType == DDS_TEXTURE_TYPE_2D) WriteSize = PixelFormat_CalculateImageSize(m_pfFormat, m_uCurrentWidth, m_uCurrentHeight, 1) * m_uArraySize; else if (m_eType == DDS_TEXTURE_TYPE_3D) WriteSize = PixelFormat_CalculateImageSize(m_pfFormat, m_uCurrentWidth, m_uCurrentHeight, m_uCurrentDepth); else if (m_eType == DDS_TEXTURE_TYPE_CUBE) WriteSize = PixelFormat_CalculateImageSize(m_pfFormat, m_uCurrentWidth, m_uCurrentHeight, 1) * 6; // should be >= if (WriteSize > cbData) { Log_ErrorPrintf("DDSWriter::WriteMipLevel(%u): Not enough data provided (%u, %u required).", MipLevel, cbData, WriteSize); return false; } // write it if (!m_pOutputStream->Write2(pData, WriteSize)) { Log_ErrorPrintf("DDSWriter::WriteHeader: Write error at stream position %u size %u", (uint32)m_pOutputStream->GetPosition(), (uint32)m_pOutputStream->GetSize()); return false; } m_uCurrentMipLevel++; if (m_uCurrentWidth > 1) m_uCurrentWidth /= 2; if (m_uCurrentHeight > 1) m_uCurrentHeight /= 2; if (m_uCurrentDepth > 1) m_uCurrentDepth /= 2; return true; } bool DDSWriter::Finalize() { DebugAssert(m_pfFormat != PIXEL_FORMAT_UNKNOWN); if (m_uCurrentMipLevel != m_uMipCount) return false; return true; } <file_sep>/config-msvc.h #pragma once // Config header for MSVC platforms // Core defines #define HAVE_LIBXML2 1 #define HAVE_SQUISH 1 #define HAVE_ZLIB 1 #define HAVE_SFMT 1 #define HAVE_FREEIMAGE 1 #define HAVE_HLSLTRANSLATOR 1 // Engine defines #define WITH_PROFILER 1 #define WITH_RENDERER_D3D11 1 #define WITH_RENDERER_D3D12 1 #define WITH_RENDERER_OPENGL 1 #define WITH_RENDERER_OPENGLES2 1 #define WITH_RESOURCECOMPILER 1 //#define WITH_RESOURCECOMPILER_EMBEDDED 1 #define WITH_RESOURCECOMPILER_SUBPROCESS 1 #define WITH_RESOURCECOMPILER_STANDALONE 1 #define WITH_MAPCOMPILER 1 #define WITH_MAPCOMPILER_STANDALONE 1 #define WITH_CONTENTCONVERTER 1 #define WITH_CONTENTCONVERTER_STANDALONE 1 #define WITH_IMGUI 1 #define WITH_BASEGAME 1 #define WITH_EDITOR 1 #define WITH_BLOCKENGINE 1 <file_sep>/Editor/Source/Editor/SignalBlocker.h #pragma once #include <QtCore/QObject> template<class T> class SignalBlocker { public: SignalBlocker(T *pBlocked) : m_pBlocked(pBlocked), m_prevState(pBlocked->blockSignals(true)) { } ~SignalBlocker() { m_pBlocked->blockSignals(m_prevState); } T *operator->() { return m_pBlocked; } private: T *m_pBlocked; bool m_prevState; }; template<class T> static inline SignalBlocker<T> BlockSignalsForCall(T *pBlocked) { return SignalBlocker<T>(pBlocked); } <file_sep>/Engine/Source/Engine/EngineTypes.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Engine.h" #include "Engine/Entity.h" #include "Renderer/VertexFactory.h" // Engine Resource Types #include "Engine/Texture.h" #include "Engine/MaterialShader.h" #include "Engine/Material.h" #include "Engine/StaticMesh.h" #include "Engine/Font.h" #include "Engine/BlockPalette.h" #include "Engine/BlockMesh.h" #include "Engine/Skeleton.h" #include "Engine/SkeletalMesh.h" #include "Engine/SkeletalAnimation.h" // Components #include "Engine/Component.h" #include "GameFramework/StaticMeshComponent.h" #include "GameFramework/BlockMeshComponent.h" #include "GameFramework/PointLightComponent.h" #include "GameFramework/PositionInterpolatorComponent.h" #include "GameFramework/RotationInterpolatorComponent.h" #include "GameFramework/InterpolatorComponent.h" #include "GameFramework/ParticleEmitterComponent.h" // Entities #include "Engine/Entity.h" #include "GameFramework/StaticMeshBrush.h" #include "GameFramework/BlockMeshBrush.h" #include "GameFramework/DirectionalLightEntity.h" #include "GameFramework/PointLightEntity.h" #include "GameFramework/SpriteEntity.h" #include "GameFramework/StaticMeshEntity.h" #include "GameFramework/BlockMeshEntity.h" #include "GameFramework/StaticMeshRigidBodyEntity.h" #include "GameFramework/ParticleEmitterEntity.h" // Particle system #include "Engine/ParticleSystem.h" #include "Engine/ParticleSystemBuiltinEmitters.h" #include "Engine/ParticleSystemBuiltinModules.h" // Macro for type registration #define REGISTER_TYPE(Type) Type::StaticMutableTypeInfo()->RegisterType() void Engine::RegisterEngineResourceTypes() { REGISTER_TYPE(Material); REGISTER_TYPE(MaterialShader); REGISTER_TYPE(Texture); REGISTER_TYPE(Texture2D); REGISTER_TYPE(Texture2DArray); REGISTER_TYPE(TextureCube); REGISTER_TYPE(StaticMesh); REGISTER_TYPE(Font); REGISTER_TYPE(BlockPalette); REGISTER_TYPE(BlockMesh); REGISTER_TYPE(Skeleton); REGISTER_TYPE(SkeletalMesh); REGISTER_TYPE(SkeletalAnimation); } void Engine::RegisterEngineComponentTypes() { REGISTER_TYPE(Component); REGISTER_TYPE(StaticMeshComponent); REGISTER_TYPE(BlockMeshComponent); REGISTER_TYPE(PointLightComponent); REGISTER_TYPE(PositionInterpolatorComponent); REGISTER_TYPE(RotationInterpolatorComponent); REGISTER_TYPE(InterpolatorComponent); REGISTER_TYPE(ParticleEmitterComponent); } void Engine::RegisterEngineEntityTypes() { REGISTER_TYPE(Entity); // TODO REMOVE REFERENCE TO GAMEFRAMEWORK AFTER THIS CRUD CLEANUP REGISTER_TYPE(StaticMeshBrush); REGISTER_TYPE(BlockMeshBrush); REGISTER_TYPE(DirectionalLightEntity); REGISTER_TYPE(PointLightEntity); REGISTER_TYPE(SpriteEntity); REGISTER_TYPE(StaticMeshEntity); REGISTER_TYPE(BlockMeshEntity); REGISTER_TYPE(StaticMeshRigidBodyEntity); REGISTER_TYPE(ParticleEmitterEntity); } void Engine::RegisterExternalTypes() { } void Engine::RegisterEngineTypes() { // base object type, kinda necessary REGISTER_TYPE(Object); // engine types RegisterEngineResourceTypes(); RegisterEngineComponentTypes(); RegisterEngineEntityTypes(); RegisterExternalTypes(); // particle system REGISTER_TYPE(ParticleSystem); REGISTER_TYPE(ParticleSystemEmitter); REGISTER_TYPE(ParticleSystemModule); ParticleSystemEmitter::RegisterBuiltinEmitters(); ParticleSystemModule::RegisterBuiltinModules(); } void Engine::UnregisterTypes() { // objects { ObjectTypeInfo::RegistryType &typeRegistry = ShaderComponentTypeInfo::GetRegistry(); for (uint32 i = 0; i < typeRegistry.GetNumTypes(); i++) { ObjectTypeInfo *pTypeInfo = typeRegistry.GetRegisteredTypeInfoByIndex(i).pTypeInfo; if (pTypeInfo != NULL) pTypeInfo->UnregisterType(); } } } <file_sep>/Editor/Source/Editor/PrecompiledHeader.h #pragma once #include "Editor/Common.h" <file_sep>/Engine/Source/BlockEngine/BlockEngineCVars.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockEngineCVars.h" namespace CVars { CVar r_block_world_visible_radius("r_block_world_visible_radius", 0, "10", "Number of visible chunks around observer", "uint:4-256"); CVar r_block_world_section_load_radius("r_block_world_section_load_radius", 0, "4", "Number of sections around player to load", "uint:1-256"); CVar r_block_world_chunk_remove_delay("r_block_world_chunk_remove_delay", 0, "10", "Number of seconds to delay removing a previously visible chunk", "float:0-60"); CVar r_block_world_parallel_chunk_build("r_block_world_parallel_chunk_build", CVAR_FLAG_REQUIRE_MAP_RESTART, "true", "Enable parallel chunk building", "bool"); CVar r_block_world_max_chunks_per_frame("r_block_world_max_chunks_per_frame", 0, "100", "Maximum number of triangulation passes to perform each frame", "uint:1-256"); CVar r_block_world_max_sections_per_frame("r_block_world_max_sections_per_frame", 0, "1", "Maximum number of sections to load/generate per frame", "uint:1-256"); CVar r_block_world_occlusion("r_block_world_occlusion", 0, "1", "Use occlusion queries for block terrain chunks", "bool"); CVar r_block_world_show_lods("r_block_world_show_lods", 0, "0", "Show lod via colours", "bool"); CVar r_block_world_use_lightmaps("r_block_world_use_lightmaps", 0, "false", "Use lightmaps instead of dynamic lighting", "bool"); } <file_sep>/DemoGame/Source/DemoGame/DemoGame.h #pragma once #include "BaseGame/BaseGame.h" #include "DemoGame/LaunchpadGameState.h" // game class class DemoGame : public BaseGame { public: DemoGame(); virtual ~DemoGame(); protected: // events virtual void OnRegisterTypes() override final; virtual bool OnStart() override final; virtual void OnExit() override final; // bind input events void BindInputEvents(); private: LaunchpadGameState *m_pLaunchpadGameState; }; <file_sep>/Engine/Source/Renderer/VertexFactories/PlainVertexFactory.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactories/PlainVertexFactory.h" #include "Renderer/ShaderCompilerFrontend.h" void PlainVertexFactory::Vertex::SetUV(float x_, float y_, float z_, float u_, float v_) { this->Position.Set(x_, y_, z_); this->TexCoord.Set(u_, v_); this->Color = 0x00000000; } void PlainVertexFactory::Vertex::SetUVColor(float x_, float y_, float z_, float u_, float v_, uint32 color) { this->Position.Set(x_, y_, z_); this->TexCoord.Set(u_, v_); this->Color = color; } void PlainVertexFactory::Vertex::SetUVColorFloat(float x_, float y_, float z_, float u_, float v_, float r_, float g_, float b_, float a_) { this->Position.Set(x_, y_, z_); this->TexCoord.Set(u_, v_); this->Color = static_cast<uint32>(Y_fclamp(r_ * 255.0f, 0.0f, 255.0f)) | static_cast<uint32>(Y_fclamp(g_ * 255.0f, 0.0f, 255.0f)) << 8 | static_cast<uint32>(Y_fclamp(b_ * 255.0f, 0.0f, 255.0f)) << 16 | static_cast<uint32>(Y_fclamp(a_ * 255.0f, 0.0f, 255.0f)) << 24; } void PlainVertexFactory::Vertex::SetUVColorByte(float x_, float y_, float z_, float u_, float v_, uint8 r_, uint8 g_, uint8 b_, uint8 a_) { this->Position.Set(x_, y_, z_); this->TexCoord.Set(u_, v_); this->Color = static_cast<uint32>(r_) | static_cast<uint32>(g_) << 8 | static_cast<uint32>(b_) << 16 | static_cast<uint32>(a_) << 24; } void PlainVertexFactory::Vertex::SetColor(float x_, float y_, float z_, uint32 color) { this->Position.Set(x_, y_, z_); this->TexCoord.SetZero(); this->Color = color; } void PlainVertexFactory::Vertex::SetColorFloat(float x_, float y_, float z_, float r_, float g_, float b_, float a_) { this->Position.Set(x_, y_, z_); this->TexCoord.SetZero(); this->Color = static_cast<uint32>(Y_fclamp(r_ * 255.0f, 0.0f, 255.0f)) | static_cast<uint32>(Y_fclamp(g_ * 255.0f, 0.0f, 255.0f)) << 8 | static_cast<uint32>(Y_fclamp(b_ * 255.0f, 0.0f, 255.0f)) << 16 | static_cast<uint32>(Y_fclamp(a_ * 255.0f, 0.0f, 255.0f)) << 24; } void PlainVertexFactory::Vertex::SetColorByte(float x_, float y_, float z_, uint8 r_, uint8 g_, uint8 b_, uint8 a_) { this->Position.Set(x_, y_, z_); this->TexCoord.SetZero(); this->Color = static_cast<uint32>(r_) | static_cast<uint32>(g_) << 8 | static_cast<uint32>(b_) << 16 | static_cast<uint32>(a_) << 24; } void PlainVertexFactory::Vertex::Set(const float3 &Position_, const float2 &TexCoord_, const float4 &Color_) { this->Position = Position_; this->TexCoord = TexCoord_; this->Color = static_cast<uint32>(Y_fclamp(Color_.r * 255.0f, 0.0f, 255.0f)) | static_cast<uint32>(Y_fclamp(Color_.g * 255.0f, 0.0f, 255.0f)) << 8 | static_cast<uint32>(Y_fclamp(Color_.b * 255.0f, 0.0f, 255.0f)) << 16 | static_cast<uint32>(Y_fclamp(Color_.a * 255.0f, 0.0f, 255.0f)) << 24; } void PlainVertexFactory::Vertex::Set(const float3 &Position_, const float2 &TexCoord_, const uint32 Color_) { this->Position = Position_; this->TexCoord = TexCoord_; this->Color = Color_; } bool operator==(const PlainVertexFactory::Vertex &v1, const PlainVertexFactory::Vertex &v2) { return (v1.Position == v2.Position && v1.TexCoord == v2.TexCoord && v1.Color == v2.Color); } bool operator!=(const PlainVertexFactory::Vertex &v1, const PlainVertexFactory::Vertex &v2) { return (v1.Position != v2.Position || v1.TexCoord != v2.TexCoord || v1.Color != v2.Color); } DEFINE_VERTEX_FACTORY_TYPE_INFO(PlainVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(PlainVertexFactory) END_SHADER_COMPONENT_PARAMETERS() uint32 PlainVertexFactory::GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { uint32 vertexSize = sizeof(float3); if (flags & PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD) vertexSize += sizeof(float2); if (flags & PLAIN_VERTEX_FACTORY_FLAG_COLOR) vertexSize += sizeof(uint32); return vertexSize; } bool PlainVertexFactory::FillBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); if (cbBuffer < (nVertices * vertexSize)) return false; uint32 i; const Vertex *pInVertexPtr = pVertices; byte *pOutVertexPtr = reinterpret_cast<byte *>(pBuffer); for (i = 0; i < nVertices; i++) { Y_memcpy(pOutVertexPtr, &pInVertexPtr->Position, sizeof(float3)); pOutVertexPtr += sizeof(float3); if (flags & PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD) { Y_memcpy(pOutVertexPtr, &pInVertexPtr->TexCoord, sizeof(float2)); pOutVertexPtr += sizeof(float2); } if (flags & PLAIN_VERTEX_FACTORY_FLAG_COLOR) { // todo: d3d9: reverse byte order *(uint32 *)pOutVertexPtr = pInVertexPtr->Color; pOutVertexPtr += sizeof(uint32); } pInVertexPtr++; } return true; } bool PlainVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool PlainVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/PlainVertexFactory.hlsl"); if (vertexFactoryFlags & PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD) pParameters->AddPreprocessorMacro("PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD", "1"); if (vertexFactoryFlags & PLAIN_VERTEX_FACTORY_FLAG_COLOR) pParameters->AddPreprocessorMacro("PLAIN_VERTEX_FACTORY_FLAG_COLOR", "1"); return true; } uint32 PlainVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { GPU_VERTEX_ELEMENT_DESC *pElementDesc = &pElementsDesc[0]; uint32 nElements = 0; uint32 streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // texcoord if (flags & PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; } // color if (flags & PLAIN_VERTEX_FACTORY_FLAG_COLOR) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } return nElements; } <file_sep>/Engine/Source/ContentConverterStandalone/TextureImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" #include "ContentConverter/TextureImporter.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintTextureImporterSyntax() { Log_InfoPrint("Texture Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -o <path>: Output file name."); Log_InfoPrint(" -append: append to the texture instead of creating a new one. usage/mip/format options will be reused"); Log_InfoPrint(" -rebuild: rebuild the texture using the specified options"); Log_InfoPrint(" -type <1D | 1DArray | 2D | 2DArray | Cube | CubeArray>: texture type"); Log_InfoPrint(" -usage <diffuse, diffuseextra, decal, normalmap, normalmapextra, bumpmap, alphamap, specularmap>: Texture usage,"); Log_InfoPrint(" used to determine format in automatic cases. Alphamap and bumpmap result in conversion to those formats."); Log_InfoPrint(" -filter <nearest | bilinear | trilinear | anisotropic>: set maximum allowed texture filter"); Log_InfoPrint(" -address[uvw] <clamp|wrap>: texture address mode"); Log_InfoPrint(" -resize <w>x<h>: resize the image"); Log_InfoPrint(" -resizefilter <box | bilinear | bicubic | bspline | catmullrom | lanczos3>: texture filter for resize operations"); Log_InfoPrint(" -[no]genmipmaps: Automatically generate mipmaps, default on"); Log_InfoPrint(" -[no]sourcepremultipliedalpha: specifiy whether the source has premultiplied alpha channel"); Log_InfoPrint(" -[no]premultipliedalpha: allow conversion to premultiplied alpha"); Log_InfoPrint(" -oformat <format>: Explicit output pixel format."); Log_InfoPrint(" -[no]compress: Enable/disable texture compression, default on"); Log_InfoPrint(" -[no]compile: Enable compilation after generation, default on"); Log_InfoPrint(""); } bool ParseTextureImporterOption(TextureImporterOptions &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.InputFileNames.Add(argv[++i]); else if (CHECK_ARG_PARAM("-o")) Options.OutputName = argv[++i]; else if (CHECK_ARG("-append")) Options.AppendTexture = true; else if (CHECK_ARG("-rebuild")) Options.RebuildTexture = true; else if (CHECK_ARG_PARAM("-type")) { if (!NameTable_TranslateType(NameTables::TextureType, argv[++i], &Options.Type, true)) { Log_ErrorPrintf("Invalid texture type '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-usage")) { if (!NameTable_TranslateType(NameTables::TextureUsage, argv[++i], &Options.Usage, true)) { Log_ErrorPrintf("Invalid texture usage '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-filter")) { ++i; if (!Y_stricmp(argv[i], "nearest")) Options.Filter = TEXTURE_FILTER_MIN_MAG_MIP_POINT; else if (!Y_stricmp(argv[i], "bilinear")) Options.Filter = TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT; else if (!Y_stricmp(argv[i], "trilinear")) Options.Filter = TEXTURE_FILTER_MIN_MAG_MIP_LINEAR; else if (!Y_stricmp(argv[i], "anisotropic")) Options.Filter = TEXTURE_FILTER_ANISOTROPIC; else { Log_ErrorPrintf("unknown texture filter: %s", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-addressu")) { if (!NameTable_TranslateType(NameTables::TextureAddressMode, argv[++i], &Options.AddressU, true)) { Log_ErrorPrintf("Invalid texture address mode '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-addressv")) { if (!NameTable_TranslateType(NameTables::TextureAddressMode, argv[++i], &Options.AddressV, true)) { Log_ErrorPrintf("Invalid texture address mode '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-addressw")) { if (NameTable_TranslateType(NameTables::TextureAddressMode, argv[++i], &Options.AddressW, true)) { Log_ErrorPrintf("Invalid texture address mode '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-resize")) { ++i; uint32 len = Y_strlen(argv[i]); char *temp = new char[len + 1]; Y_memcpy(temp, argv[i], len + 1); char *dimensions[2]; uint32 width; uint32 height; if (Y_strsplit(temp, 'x', dimensions, 2) != 2 || (width = StringConverter::StringToUInt32(dimensions[0])) == 0 || (height = StringConverter::StringToUInt32(dimensions[1])) == 0) { Log_ErrorPrintf("invalid dimensions: %s", argv[i]); delete[] temp; return false; } delete[] temp; Options.ResizeWidth = width; Options.ResizeHeight = height; } else if (CHECK_ARG_PARAM("-resizefilter")) { if (!NameTable_TranslateType(NameTables::ImageResizeFilter, argv[++i], &Options.ResizeFilter, true)) { Log_ErrorPrintf("Invalid image resize filter '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG("-genmipmaps")) Options.GenerateMipMaps = true; else if (CHECK_ARG("-nogenmipmaps")) Options.GenerateMipMaps = false; else if (CHECK_ARG("-sourcepremultipliedalpha")) Options.SourcePremultipliedAlpha = true; else if (CHECK_ARG("-nosourcepremultipliedalpha")) Options.SourcePremultipliedAlpha = false; else if (CHECK_ARG("-premultipliedalpha")) Options.EnablePremultipliedAlpha = true; else if (CHECK_ARG("-nopremultipliedalpha")) Options.EnablePremultipliedAlpha = false; else if (CHECK_ARG("-compress")) Options.EnableTextureCompression = true; else if (CHECK_ARG("-nocompress")) Options.EnableTextureCompression = false; else if (CHECK_ARG_PARAM("-oformat")) { if (!NameTable_TranslateType(NameTables::PixelFormat, argv[++i], &Options.OutputFormat, true)) { Log_ErrorPrintf("Invalid output pixel format '%s' specified.", argv[i]); return false; } } else if (CHECK_ARG("-optimize")) Options.Optimize = true; else if (CHECK_ARG("-nooptimize")) Options.Optimize = false; else if (CHECK_ARG("-compile")) Options.Compile = true; else if (CHECK_ARG("-nocompile")) Options.Compile = false; else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintTextureImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunTextureImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintTextureImporterSyntax(); return 0; } TextureImporterOptions Options; TextureImporter::SetDefaultOptions(&Options); for (i = 0; i < argc; i++) { if (!ParseTextureImporterOption(Options, i, argc, argv)) return 1; } if (Options.InputFileNames.GetSize() == 0 || Options.OutputName.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output package/name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; TextureImporter Importer(&progressCallbacks); if (!Importer.Execute(&Options)) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Source/GameFramework/ParticleEmitterEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/ParticleEmitterEntity.h" #include "Engine/ParticleSystemRenderProxy.h" #include "Engine/Entity.h" #include "Engine/World.h" #include "Renderer/RenderWorld.h" DEFINE_ENTITY_TYPEINFO(ParticleEmitterEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(ParticleEmitterEntity); BEGIN_ENTITY_PROPERTIES(ParticleEmitterEntity) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(ParticleEmitterEntity) END_ENTITY_SCRIPT_FUNCTIONS() ParticleEmitterEntity::ParticleEmitterEntity(const EntityTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_pParticleSystem(nullptr), m_autoStart(true), m_pRenderProxy(nullptr), m_active(false) { } ParticleEmitterEntity::~ParticleEmitterEntity() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pParticleSystem != nullptr) m_pParticleSystem->Release(); } void ParticleEmitterEntity::SetParticleSystem(const ParticleSystem *pParticleSystem) { if (m_pParticleSystem != pParticleSystem) { m_pParticleSystem->Release(); m_pParticleSystem = pParticleSystem; m_pParticleSystem->AddRef(); m_pRenderProxy->SetParticleSystem(pParticleSystem); if (IsInWorld()) RegisterForUpdates(m_pParticleSystem->GetUpdateInterval()); } else { m_pRenderProxy->Reset(); } } void ParticleEmitterEntity::Create(uint32 entityID, const ParticleSystem *pParticleSystem, const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */) { DebugAssert(m_pParticleSystem == nullptr && pParticleSystem != nullptr); m_transform.Set(position, rotation, scale); m_pParticleSystem = pParticleSystem; m_pParticleSystem->AddRef(); m_active = false; Initialize(entityID, EmptyString); } void ParticleEmitterEntity::Activate() { if (m_active) return; m_active = true; if (IsInWorld()) RegisterForUpdates(m_pParticleSystem->GetUpdateInterval()); } void ParticleEmitterEntity::Deactivate() { if (!m_active) return; m_active = false; if (IsInWorld()) UnregisterForUpdates(); } bool ParticleEmitterEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; // create render proxy DebugAssert(m_pRenderProxy == nullptr); m_pRenderProxy = new ParticleSystemRenderProxy(m_pParticleSystem, 0); return true; } void ParticleEmitterEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // add render proxy to world pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoStart) m_active = true; if (m_active) RegisterForUpdates(0.0f); } void ParticleEmitterEntity::OnRemoveFromWorld(World *pWorld) { BaseClass::OnRemoveFromWorld(pWorld); // remove render proxy from world pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); } void ParticleEmitterEntity::OnTransformChange() { // pass through BaseClass::OnTransformChange(); } void ParticleEmitterEntity::OnComponentBoundsChange() { // fix up bounds BaseClass::SetBounds(m_pRenderProxy->GetParticleSystemBoundingBox(), Sphere::FromAABox(m_pRenderProxy->GetParticleSystemBoundingBox()), true); } void ParticleEmitterEntity::Update(float timeSinceLastUpdate) { // update the particle system m_pRenderProxy->Update(&m_transform, timeSinceLastUpdate); // update bounding box AABox systemBoundingBox(m_pRenderProxy->GetParticleSystemBoundingBox()); if (systemBoundingBox != m_boundingBox) BaseClass::SetBounds(systemBoundingBox, Sphere::FromAABox(systemBoundingBox)); } <file_sep>/Engine/Source/Engine/ScriptTypes.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptTypes.h" Y_Define_NameTable(NameTables::ScriptCallResults) Y_NameTable_Entry("Success", ScriptCallResult_Success) Y_NameTable_Entry("Yielded", ScriptCallResult_Yielded) Y_NameTable_Entry("ParseError", ScriptCallResult_ParseError) Y_NameTable_Entry("RuntimeError", ScriptCallResult_RuntimeError) Y_NameTable_Entry("NotInThread", ScriptCallResult_NotInThread) Y_NameTable_Entry("MethodNotFound", ScriptCallResult_MethodNotFound) Y_NameTable_Entry("NoObject", ScriptCallResult_NoObject) Y_NameTable_End() Y_Define_NameTable(NameTables::ScriptThreadTimeoutActions) Y_NameTable_Entry("Abort", ScriptThreadTimeoutAction_Abort) Y_NameTable_Entry("Resume", ScriptThreadTimeoutAction_Resume) Y_NameTable_Entry("ReturnNil", ScriptThreadTimeoutAction_ReturnNil) Y_NameTable_End() <file_sep>/Engine/Source/Renderer/Common.h #pragma once #include "Engine/Common.h" <file_sep>/Editor/Source/Editor/SkeletalAnimationEditor/ui_EditorSkeletalAnimationEditor.h #pragma once #include "Editor/EditorRendererSwapChainWidget.h" #include "Editor/ToolMenuWidget.h" #include "Editor/EditorVectorEditWidget.h" class Ui_EditorSkeletalAnimationEditor { public: QMainWindow *mainWindow; // actions QAction *actionOpen; QAction *actionSave; QAction *actionSaveAs; QAction *actionClose; QAction *actionCameraPerspective; QAction *actionCameraArcball; QAction *actionCameraIsometric; QAction *actionViewWireframe; QAction *actionViewUnlit; QAction *actionViewLit; QAction *actionViewFlagShadows; QAction *actionViewFlagWireframeOverlay; QAction *actionToolInformation; QAction *actionToolBoneTrack; QAction *actionToolRootMotion; QAction *actionToolClipper; QAction *actionToolLightManipulator; // menus QMenu *menuAnimation; QMenu *menuCamera; QMenu *menuView; QMenu *menuTools; QMenu *menuHelp; // widgets QMenuBar *menubar; QToolBar *toolbar; QStatusBar *statusBar; // left pane EditorRendererSwapChainWidget *swapChainWidget; // scrubber QDockWidget *scrubberDockWidget; QSlider *scrubberSlider; // hierarchy QDockWidget *hierarchyDockWidget; QTreeWidget *hierarchyTreeWidget; // toolbox QDockWidget *toolBoxDockWidget; QWidget *toolBoxContainer; // mode panel ToolMenuWidget *rightToolMenu; // stuff for each mode QWidget *toolContainer; QScrollArea *toolContainerScrollArea; // information QWidget *toolInformationContainer; QLabel *toolInformationSkeletonName; QLabel *toolInformationFrameCount; QLabel *toolInformationDuration; QLabel *toolInformationBoneTrackCount; QLabel *toolInformationRootMotion; QLabel *toolInformationPreviewMesh; // bone tracks QWidget *toolBoneTrackContainer; QListWidget *toolBoneTrackKeyframeList; EditorVectorEditWidget *toolBoneTrackTransformPosition; EditorVectorEditWidget *toolBoneTrackTransformRotation; EditorVectorEditWidget *toolBoneTrackTransformScale; // root motion QWidget *toolRootMotionContainer; // import QWidget *toolClipperContainer; QSpinBox *toolClipperStartFrameNumber; QPushButton *toolClipperSetStartFrameNumber; QSpinBox *toolClipperEndFrameNumber; QPushButton *toolClipperSetEndFrameNumber; QPushButton *toolClipperClip; // light manipulator QWidget *toolLightManipulatorContainer; void CreateUI(QMainWindow *pMainWindow) { mainWindow = pMainWindow; mainWindow->resize(800, 600); actionOpen = new QAction(pMainWindow); actionOpen->setIcon(QIcon(QStringLiteral(":/editor/icons/openHS.png"))); actionOpen->setText(mainWindow->tr("&Open")); actionSave = new QAction(pMainWindow); actionSave->setIcon(QIcon(QStringLiteral(":/editor/icons/saveHS.png"))); actionSave->setText(mainWindow->tr("&Save")); actionSaveAs = new QAction(pMainWindow); actionSaveAs->setText(mainWindow->tr("Save &As")); actionClose = new QAction(pMainWindow); actionClose->setText(mainWindow->tr("&Close")); actionCameraPerspective = new QAction(pMainWindow); actionCameraPerspective->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Perspective.png"))); actionCameraPerspective->setText(mainWindow->tr("&Perspective Camera")); actionCameraPerspective->setCheckable(true); actionCameraArcball = new QAction(pMainWindow); actionCameraArcball->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Side.png"))); actionCameraArcball->setText(mainWindow->tr("&Arcball Camera")); actionCameraArcball->setCheckable(true); actionCameraIsometric = new QAction(pMainWindow); actionCameraIsometric->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Isometric.png"))); actionCameraIsometric->setText(mainWindow->tr("&Isometric Camera")); actionCameraIsometric->setCheckable(true); actionViewWireframe = new QAction(pMainWindow); actionViewWireframe->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Wireframe.png"))); actionViewWireframe->setText(mainWindow->tr("&Wireframe View")); actionViewWireframe->setCheckable(true); actionViewUnlit = new QAction(pMainWindow); actionViewUnlit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Unlit.png"))); actionViewUnlit->setText(mainWindow->tr("&Unlit View")); actionViewUnlit->setCheckable(true); actionViewLit = new QAction(pMainWindow); actionViewLit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Lit.png"))); actionViewLit->setText(mainWindow->tr("&Lit View")); actionViewLit->setCheckable(true); actionViewFlagShadows = new QAction(pMainWindow); actionViewFlagShadows->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_Shadows.png"))); actionViewFlagShadows->setText(mainWindow->tr("Enable &Shadows")); actionViewFlagShadows->setCheckable(true); actionViewFlagWireframeOverlay = new QAction(pMainWindow); actionViewFlagWireframeOverlay->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_WireframeOverlay.png"))); actionViewFlagWireframeOverlay->setText(mainWindow->tr("Enable Wireframe &Overlay")); actionViewFlagWireframeOverlay->setCheckable(true); actionToolInformation = new QAction(pMainWindow); actionToolInformation->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolInformation->setText(pMainWindow->tr("Information")); actionToolInformation->setCheckable(true); actionToolBoneTrack = new QAction(pMainWindow); actionToolBoneTrack->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolBoneTrack->setText(pMainWindow->tr("Bone Tracks")); actionToolBoneTrack->setCheckable(true); actionToolRootMotion = new QAction(pMainWindow); actionToolRootMotion->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolRootMotion->setText(pMainWindow->tr("Root Motion")); actionToolRootMotion->setCheckable(true); actionToolClipper = new QAction(pMainWindow); actionToolClipper->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionToolClipper->setText(pMainWindow->tr("Clipping")); actionToolClipper->setCheckable(true); actionToolLightManipulator = new QAction(pMainWindow); actionToolLightManipulator->setIcon(QIcon(QStringLiteral(":/editor/icons/Alerts.png"))); actionToolLightManipulator->setText(pMainWindow->tr("Light Manipulator")); actionToolLightManipulator->setCheckable(true); menuAnimation = new QMenu(pMainWindow); menuAnimation->setTitle(mainWindow->tr("&Animation")); menuAnimation->addAction(actionOpen); menuAnimation->addAction(actionSave); menuAnimation->addAction(actionSaveAs); menuAnimation->addSeparator(); menuAnimation->addAction(actionClose); menuCamera = new QMenu(pMainWindow); menuCamera->setTitle(mainWindow->tr("&Camera")); menuCamera->addAction(actionCameraPerspective); menuCamera->addAction(actionCameraArcball); menuCamera->addAction(actionCameraIsometric); menuView = new QMenu(pMainWindow); menuView->setTitle(mainWindow->tr("&View")); menuView->addAction(actionViewWireframe); menuView->addAction(actionViewUnlit); menuView->addAction(actionViewLit); menuView->addSeparator(); menuView->addAction(actionViewFlagShadows); menuView->addAction(actionViewFlagWireframeOverlay); menuTools = new QMenu(pMainWindow); menuTools->setTitle(mainWindow->tr("&Tools")); menuTools->addAction(actionToolInformation); menuTools->addAction(actionToolBoneTrack); menuTools->addAction(actionToolRootMotion); menuTools->addAction(actionToolClipper); menuTools->addAction(actionToolLightManipulator); menuHelp = new QMenu(pMainWindow); menuHelp->setTitle(mainWindow->tr("&Help")); menubar = new QMenuBar(pMainWindow); menubar->addMenu(menuAnimation); menubar->addMenu(menuCamera); menubar->addMenu(menuView); menubar->addMenu(menuTools); menubar->addMenu(menuHelp); pMainWindow->setMenuBar(menubar); toolbar = new QToolBar(pMainWindow); toolbar->setIconSize(QSize(16, 16)); toolbar->addAction(actionOpen); toolbar->addAction(actionSave); toolbar->addSeparator(); toolbar->addAction(actionCameraPerspective); toolbar->addAction(actionCameraArcball); toolbar->addAction(actionCameraIsometric); toolbar->addSeparator(); toolbar->addAction(actionViewWireframe); toolbar->addAction(actionViewUnlit); toolbar->addAction(actionViewLit); toolbar->addSeparator(); toolbar->addAction(actionViewFlagShadows); toolbar->addAction(actionViewFlagWireframeOverlay); toolbar->addSeparator(); toolbar->addAction(actionToolInformation); toolbar->addAction(actionToolBoneTrack); toolbar->addAction(actionToolRootMotion); toolbar->addAction(actionToolClipper); toolbar->addAction(actionToolLightManipulator); pMainWindow->addToolBar(toolbar); statusBar = new QStatusBar(pMainWindow); pMainWindow->setStatusBar(statusBar); // left pane swapChainWidget = new EditorRendererSwapChainWidget(pMainWindow); swapChainWidget->setFocusPolicy(Qt::FocusPolicy(Qt::TabFocus | Qt::ClickFocus)); swapChainWidget->setMouseTracking(true); pMainWindow->setCentralWidget(swapChainWidget); // scrubber scrubberDockWidget = new QDockWidget(pMainWindow); scrubberDockWidget->setFeatures(0); scrubberSlider = new QSlider(Qt::Horizontal, scrubberDockWidget); scrubberSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); scrubberSlider->setFixedHeight(32); scrubberSlider->setMinimum(0); scrubberSlider->setMaximum(16); scrubberSlider->setTickInterval(1); scrubberSlider->setTickPosition(QSlider::TicksBothSides); scrubberDockWidget->setWidget(scrubberSlider); pMainWindow->addDockWidget(Qt::BottomDockWidgetArea, scrubberDockWidget); // heirarchy hierarchyDockWidget = new QDockWidget(pMainWindow); hierarchyDockWidget->setWindowTitle("Hierarchy"); hierarchyTreeWidget = new QTreeWidget(hierarchyDockWidget); hierarchyTreeWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); hierarchyDockWidget->setWidget(hierarchyTreeWidget); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, hierarchyDockWidget); // right pane container toolBoxDockWidget = new QDockWidget(pMainWindow); toolBoxDockWidget->setWindowTitle(pMainWindow->tr("Toolbox")); toolBoxDockWidget->setMinimumSize(320, 400); toolBoxContainer = new QWidget(toolBoxDockWidget); { QVBoxLayout *rightDockContainerLayout = new QVBoxLayout(toolBoxContainer); rightDockContainerLayout->setContentsMargins(0, 0, 0, 0); // mode toolbar { rightToolMenu = new ToolMenuWidget(toolBoxContainer); rightToolMenu->addAction(actionToolInformation); rightToolMenu->addAction(actionToolBoneTrack); rightToolMenu->addAction(actionToolRootMotion); rightToolMenu->addAction(actionToolClipper); rightToolMenu->addAction(actionToolLightManipulator); rightToolMenu->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); rightDockContainerLayout->addWidget(rightToolMenu); } // create scroll area for the container toolContainerScrollArea = new QScrollArea(toolBoxContainer); toolContainerScrollArea->setBackgroundRole(QPalette::Background); toolContainerScrollArea->setFrameStyle(0); toolContainerScrollArea->setWidgetResizable(true); // tool container toolContainer = new QWidget(toolContainerScrollArea); { QVBoxLayout *toolContainerLayout = new QVBoxLayout(toolContainer); toolContainerLayout->setContentsMargins(0, 0, 0, 0); toolContainerLayout->setMargin(0); toolContainerLayout->setSpacing(0); // information tool { toolInformationContainer = new QWidget(toolContainer); { QFormLayout *formLayout = new QFormLayout(toolInformationContainer); //formLayout->setContentsMargins(2, 2, 2, 2); //formLayout->setMargin(0); //formLayout->setSpacing(0); toolInformationSkeletonName = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Skeleton Name: "), toolInformationSkeletonName); toolInformationFrameCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Frame Count: "), toolInformationFrameCount); toolInformationDuration = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Duration: "), toolInformationDuration); toolInformationBoneTrackCount = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Bone Track Count: "), toolInformationBoneTrackCount); toolInformationRootMotion = new QLabel(toolInformationContainer); formLayout->addRow(pMainWindow->tr("Root Motion: "), toolInformationRootMotion); toolInformationPreviewMesh = new QLabel(toolInformationContainer); toolInformationPreviewMesh->setTextFormat(Qt::RichText); formLayout->addRow(pMainWindow->tr("Preview Mesh: "), toolInformationPreviewMesh); toolInformationContainer->setLayout(formLayout); } toolInformationContainer->hide(); toolContainerLayout->addWidget(toolInformationContainer); } // operations tool { toolBoneTrackContainer = new QWidget(toolContainer); { QVBoxLayout *boxLayout = new QVBoxLayout(toolBoneTrackContainer); toolBoneTrackKeyframeList = new QListWidget(toolBoneTrackContainer); boxLayout->addWidget(toolBoneTrackKeyframeList, 1); QGroupBox *keyframeInfoGroupBox = new QGroupBox(pMainWindow->tr("Bone Transform"), toolBoneTrackContainer); { QFormLayout *keyframeInfoFormLayout = new QFormLayout(keyframeInfoGroupBox); toolBoneTrackTransformPosition = new EditorVectorEditWidget(keyframeInfoGroupBox); keyframeInfoFormLayout->addRow(pMainWindow->tr("Position: "), toolBoneTrackTransformPosition); toolBoneTrackTransformRotation = new EditorVectorEditWidget(keyframeInfoGroupBox); keyframeInfoFormLayout->addRow(pMainWindow->tr("Rotation: "), toolBoneTrackTransformRotation); toolBoneTrackTransformScale = new EditorVectorEditWidget(keyframeInfoGroupBox); keyframeInfoFormLayout->addRow(pMainWindow->tr("Scale: "), toolBoneTrackTransformScale); keyframeInfoGroupBox->setLayout(keyframeInfoFormLayout); } boxLayout->addWidget(keyframeInfoGroupBox); toolBoneTrackContainer->setLayout(boxLayout); } toolBoneTrackContainer->hide(); toolContainerLayout->addWidget(toolBoneTrackContainer); } // root motion tool { toolRootMotionContainer = new QWidget(toolContainer); toolRootMotionContainer->hide(); toolContainerLayout->addWidget(toolRootMotionContainer); } // clipping tool { toolClipperContainer = new QWidget(toolContainer); { QFormLayout *formLayout = new QFormLayout(toolClipperContainer); QHBoxLayout *innerBoxLayout; innerBoxLayout = new QHBoxLayout(toolClipperContainer); toolClipperStartFrameNumber = new QSpinBox(toolClipperContainer); innerBoxLayout->addWidget(toolClipperStartFrameNumber, 1); toolClipperSetStartFrameNumber = new QPushButton(pMainWindow->tr("Set"), toolClipperContainer); innerBoxLayout->addWidget(toolClipperSetStartFrameNumber); formLayout->addRow(pMainWindow->tr("Start Frame: "), innerBoxLayout); innerBoxLayout = new QHBoxLayout(toolClipperContainer); toolClipperEndFrameNumber = new QSpinBox(toolClipperContainer); innerBoxLayout->addWidget(toolClipperEndFrameNumber, 1); toolClipperSetEndFrameNumber = new QPushButton(pMainWindow->tr("Set"), toolClipperContainer); innerBoxLayout->addWidget(toolClipperSetEndFrameNumber); formLayout->addRow(pMainWindow->tr("End Frame: "), innerBoxLayout); toolClipperClip = new QPushButton(pMainWindow->tr("Clip"), toolClipperContainer); formLayout->addRow(toolClipperClip); toolClipperContainer->setLayout(formLayout); } toolClipperContainer->hide(); toolContainerLayout->addWidget(toolClipperContainer); } // light manipulator tool { toolLightManipulatorContainer = new QWidget(toolContainer); { } toolLightManipulatorContainer->hide(); toolContainerLayout->addWidget(toolLightManipulatorContainer); } toolContainerLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding)); toolContainer->setLayout(toolContainerLayout); } toolContainerScrollArea->setWidget(toolContainer); // complete container setup rightDockContainerLayout->addWidget(toolContainerScrollArea, 1); toolBoxContainer->setLayout(rightDockContainerLayout); } toolBoxDockWidget->setWidget(toolBoxContainer); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, toolBoxDockWidget); } void UpdateUIForCameraMode(EDITOR_CAMERA_MODE cameraMode) { actionCameraPerspective->setChecked((cameraMode == EDITOR_CAMERA_MODE_PERSPECTIVE)); actionCameraArcball->setChecked((cameraMode == EDITOR_CAMERA_MODE_ARCBALL)); actionCameraIsometric->setChecked((cameraMode == EDITOR_CAMERA_MODE_ISOMETRIC)); } void UpdateUIForRenderMode(EDITOR_RENDER_MODE renderMode) { actionViewWireframe->setChecked((renderMode == EDITOR_RENDER_MODE_WIREFRAME)); actionViewUnlit->setChecked((renderMode == EDITOR_RENDER_MODE_FULLBRIGHT)); actionViewLit->setChecked((renderMode == EDITOR_RENDER_MODE_LIT)); } void UpdateUIForViewportFlags(uint32 viewportFlags) { actionViewFlagShadows->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) != 0); actionViewFlagWireframeOverlay->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) != 0); } void UpdateUIForTool(EditorSkeletalAnimationEditor::Tool tool) { (tool == EditorSkeletalAnimationEditor::Tool_Information) ? toolInformationContainer->show() : toolInformationContainer->hide(); (tool == EditorSkeletalAnimationEditor::Tool_BoneTrack) ? toolBoneTrackContainer->show() : toolBoneTrackContainer->hide(); (tool == EditorSkeletalAnimationEditor::Tool_RootMotion) ? toolRootMotionContainer->show() : toolRootMotionContainer->hide(); (tool == EditorSkeletalAnimationEditor::Tool_Clipper) ? toolClipperContainer->show() : toolClipperContainer->hide(); (tool == EditorSkeletalAnimationEditor::Tool_LightManipulator) ? toolLightManipulatorContainer->show() : toolLightManipulatorContainer->hide(); actionToolInformation->setChecked((tool == EditorSkeletalAnimationEditor::Tool_Information)); actionToolBoneTrack->setChecked((tool == EditorSkeletalAnimationEditor::Tool_BoneTrack)); actionToolRootMotion->setChecked((tool == EditorSkeletalAnimationEditor::Tool_RootMotion)); actionToolClipper->setChecked((tool == EditorSkeletalAnimationEditor::Tool_Clipper)); actionToolLightManipulator->setChecked((tool == EditorSkeletalAnimationEditor::Tool_LightManipulator)); } }; <file_sep>/Engine/Source/Core/TexturePacker.h #pragma once #include "Core/Common.h" #include "Core/Image.h" #include "YBaseLib/MemArray.h" #include "YBaseLib/PODArray.h" class TexturePacker { public: TexturePacker(PIXEL_FORMAT pixelFormat); ~TexturePacker(); // add an image bool AddImage(const Image *pImage, uint32 paddingAmount, void *pReferenceData); // guess image dimensions that may be sufficient for packing void GuessPackedImageDimensions(uint32 *pWidth, uint32 *pHeight); // pack to texture bool Pack(uint32 textureWidth, uint32 textureHeight, float paddingR = 0.0f, float paddingG = 0.0f, float paddingB = 0.0f, float paddingA = 0.0f); // get result image const Image *GetPackedImage() const { return &m_packedImage; } // get result pack location bool GetImageLocation(void *pReferenceData, uint32 *pLeft, uint32 *pRight, uint32 *pTop, uint32 *pBottom); private: struct ImageToPack { uint32 PaddingAmount; uint32 TotalArea; Image *pImage; void *pReferenceData; }; struct Node { int32 ChildIndices[2]; bool IsLeaf; bool IsUsed; uint32 Left, Top; uint32 Width, Height; const ImageToPack *pImage; void *pReferenceData; Node(uint32 left, uint32 top, uint32 width, uint32 height) { ChildIndices[0] = -1; ChildIndices[1] = -1; IsLeaf = true; IsUsed = false; Left = left; Top = top; Width = width; Height = height; pImage = nullptr; pReferenceData = nullptr; } }; typedef MemArray<Node> NodeArray; typedef MemArray<ImageToPack> ImageArray; // we have to use indices here as it's possible the array will get reallocated and addresses change int32 TryInsertIntoNode(int32 nodeIndex, uint32 neededWidth, uint32 neededHeight); PIXEL_FORMAT m_pixelFormat; NodeArray m_nodes; ImageArray m_images; Image m_packedImage; }; <file_sep>/Engine/Source/Engine/Physics/CollisionObject.h #pragma once #include "Engine/Physics/PhysicsProxy.h" #include "Engine/Physics/CollisionShape.h" class PhysicsWorld; class btTransform; namespace Physics { class CollisionObject : public PhysicsProxy { friend PhysicsWorld; public: CollisionObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform); virtual ~CollisionObject(); // getters const CollisionShape *GetCollisionShape() const { return m_pCollisionShape; } const Transform &GetTransform() const { return m_transform; } const float GetFriction() const; const float GetRollingFriction() const; const float3 GetAnisotropicFriction() const; const float GetRestitution() const; // setters void SetCollisionShape(const CollisionShape *pCollisionShape); void SetTransform(const Transform &transform); void SetFriction(float friction); void SetRollingFriction(float rollingFriction); void SetAnisotropicFriction(const float3 &anisotropicFriction); void SetRestitution(float restitution); // helper methods void ConvertWorldTransformToBulletTransform(const Transform &worldTransform, btTransform *pBulletTransform); void ConvertBulletTransformToWorldTransform(const btTransform &bulletTransform, Transform *pWorldTransform); protected: virtual btCollisionObject *GetBulletCollisionObject() const = 0; virtual void OnCollisionShapeChanged() = 0; virtual void OnTransformChanged() = 0; void UpdateBoundingBox(); const CollisionShape *m_pCollisionShape; const CollisionShape *m_pOriginalCollisionShape; Transform m_transform; }; } // namespace Physics <file_sep>/Engine/Source/Engine/DataFormats.h #pragma once #include "Engine/Common.h" #pragma pack(push, 4) #ifdef Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable:4200) // warning C4200: nonstandard extension used : zero-sized array in struct/union #pragma warning(disable:4510) // warning C4510: 'DF_PROPERTY_MAPPING_HEADER' : default constructor could not be generated #pragma warning(disable:4512) // warning C4512: 'DF_PROPERTY_MAPPING_HEADER' : assignment operator could not be generated #pragma warning(disable:4610) // warning C4610: struct 'DF_PROPERTY_MAPPING_HEADER' can never be instantiated - user defined constructor required #endif //----------------------------------------- .font file ------------------------------------------ #define DF_FONT_HEADER_MAGIC ((uint32)'FNT2') struct DF_FONT_HEADER { uint32 Magic; uint32 Size; uint32 Type; uint32 BestRenderingSize; uint32 CharacterDataCount; uint32 CharacterDataOffset; uint32 TextureCount; uint32 TextureOffset; }; struct DF_FONT_CHARACTER { uint32 CodePoint; float StartU; float EndU; float StartV; float EndV; int32 DrawOffsetX; int32 DrawOffsetY; uint32 DrawWidth; uint32 DrawHeight; float Advance; uint32 TextureIndex; bool IsWhiteSpace; }; struct DF_FONT_TEXTURE { uint32 TextureSize; uint32 TextureType; }; //--------------------------------------- .staticmesh file ------------------------------------- #define DF_STATICMESH_HEADER_MAGIC ((uint32)'STM2') enum DF_STATICMESH_VERTEX_FLAGS { DF_STATICMESH_VERTEX_FLAG_COLOR = (1 << 0), DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT2 = (1 << 1), DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT3 = (1 << 2), }; struct DF_STATICMESH_HEADER { uint32 Magic; uint32 Size; uint64 CreationTime; float3 BoundingBoxMin; float3 BoundingBoxMax; float3 BoundingSphereCenter; float BoundingSphereRadius; uint32 CollisionShapeType; uint32 CollisionShapeSize; uint32 CollisionShapeOffset; uint32 VertexFlags; uint32 MaterialCount; uint32 MaterialNamesOffset; uint32 LODCount; uint32 LODOffsetsOffset; }; struct DF_STATICMESH_LOD_HEADER { uint32 VertexCount; uint32 VerticesOffset; uint32 IndexCount; uint32 IndexFormat; uint32 IndicesOffset; uint32 BatchCount; uint32 BatchesOffset; }; struct DF_STATICMESH_VERTEX { float Position[3]; float Tangent[3]; float Binormal[3]; float Normal[3]; float TexCoord[3]; uint32 Color; }; struct DF_STATICMESH_BATCH { uint32 MaterialIndex; uint32 StartIndex; uint32 NumIndices; }; //--------------------------------------- .skl file ------------------------------------- #define DF_SKELETON_HEADER_MAGIC ((uint32)'SKL2') struct DF_SKELETON_HEADER { uint32 Magic; uint32 HeaderSize; uint32 BoneCount; uint32 BonesOffset; }; struct DF_SKELETON_BONE { uint32 BoneSize; uint32 BoneNameLength; uint32 ParentBoneIndex; float RelativeBaseFrameTransformPosition[3]; float RelativeBaseFrameTransformRotation[4]; float RelativeBaseFrameTransformScale[3]; float AbsoluteBaseFrameTransformPosition[3]; float AbsoluteBaseFrameTransformRotation[4]; float AbsoluteBaseFrameTransformScale[3]; uint32 ChildBoneCount; // <uint32> * ChildBoneCount follows }; //--------------------------------------- .skm file ------------------------------------- #define DF_SKELETALMESH_HEADER_MAGIC ((uint32)'SKM1') // YTEX enum DF_SKELETALMESH_CHUNK { DF_SKELETALMESH_CHUNK_HEADER, DF_SKELETALMESH_CHUNK_SKELETON, DF_SKELETALMESH_CHUNK_BONES, DF_SKELETALMESH_CHUNK_BONE_REFS, DF_SKELETALMESH_CHUNK_MATERIALS, DF_SKELETALMESH_CHUNK_VERTICES, DF_SKELETALMESH_CHUNK_INDICES, DF_SKELETALMESH_CHUNK_BATCHES, DF_SKELETALMESH_CHUNK_COLLISION_SHAPE, DF_SKELETALMESH_CHUNK_COUNT, }; enum DF_SKELETALMESH_FLAGS { DF_SKELETALMESH_FLAG_USE_TEXTURE_COORDINATES = (1 << 0), DF_SKELETALMESH_FLAG_USE_VERTEX_COLORS = (1 << 1), }; struct DF_SKELETALMESH_HEADER { uint32 Magic; uint32 HeaderSize; uint32 Flags; float BoundingBoxMin[3]; float BoundingBoxMax[3]; float BoundingSphereCenter[3]; float BoundingSphereRadius; uint32 MaterialCount; uint32 SkeletonBoneCount; uint32 BoneCount; uint32 BoneRefCount; uint32 VertexCount; uint32 IndexCount; uint32 BatchCount; uint32 CollisionShapeType; }; struct DF_SKELETALMESH_SKELETON { uint32 SkeletonNameStringIndex; }; struct DF_SKELETALMESH_MATERIAL { uint32 MaterialNameStringIndex; }; struct DF_SKELETALMESH_VERTEX { float Position[3]; float Tangent[3]; float Binormal[3]; float Normal[3]; float TextureCoordinates[3]; uint32 Color; uint8 BoneIndices[4]; float BoneWeights[4]; }; struct DF_SKELETALMESH_BONE { uint32 SkeletonBoneIndex; float LocalToBonePosition[3]; float LocalToBoneRotation[4]; float LocalToBoneScale[3]; }; struct DF_SKELETALMESH_BATCH { uint32 MaterialIndex; uint32 WeightCount; uint32 BaseBoneRef; uint32 BoneRefCount; uint32 BaseVertex; uint32 VertexCount; uint32 StartIndex; uint32 IndexCount; }; //--------------------------------------- .ska file ------------------------------------- #define DF_SKELETALANIMATION_HEADER_MAGIC ((uint32)'ANM3') struct DF_SKELETALANIMATION_HEADER { uint32 Magic; uint32 HeaderSize; uint32 Flags; uint32 SkeletonNameLength; uint32 SkeletonNameOffset; uint32 SkeletonBoneCount; float Duration; uint32 BoneTrackCount; uint32 BoneTrackOffset; uint32 RootMotionOffset; }; struct DF_SKELETALANIMATION_TRANSFORM_TRACK_KEYFRAME { float Time; float Position[3]; float Rotation[4]; float Scale[3]; }; struct DF_SKELETALANIMATION_BONE_TRACK_HEADER { uint32 BoneIndex; float Duration; uint32 KeyFrameCount; }; struct DF_SKELETALANIMATION_ROOT_MOTION_TRACK_HEADER { float Duration; uint32 KeyFrameCount; }; //--------------------------------------- .tex file ------------------------------------- #define DF_TEXTURE_HEADER_MAGIC 0x58455459 // YTEX struct DF_TEXTURE_HEADER { uint32 Magic; uint32 HeaderSize; uint32 TextureType; uint32 TexturePlatform; uint32 TextureUsage; uint32 TextureFilter; uint32 BlendingMode; uint32 AddressModeU; uint32 AddressModeV; uint32 AddressModeW; int32 MinLOD; int32 MaxLOD; uint32 PixelFormat; uint32 ArraySize; uint32 Width; uint32 Height; uint32 Depth; uint32 MipLevels; uint32 ImageCount; }; struct DF_TEXTURE_IMAGE_HEADER { uint32 Size; uint32 RowPitch; uint32 SlicePitch; }; //--------------------------------------- .mtl file --------------------------------------- #define DF_MATERIAL_HEADER_MAGIC ((uint32)'MTL1') struct DF_MATERIAL_HEADER { uint32 Magic; uint32 HeaderSize; uint32 ShaderNameLength; uint32 UniformParameterCount; uint32 TextureParameterCount; uint32 StaticSwitchMask; // <char> * ShaderNameLength immediately follows }; struct DF_MATERIAL_UNIFORM_PARAMETER { uint32 UniformType; byte UniformValue[16]; // needs to be as large as MaterialShader::UniformParameter::Value }; struct DF_MATERIAL_TEXTURE_PARAMETER { uint32 TextureType; uint32 TextureNameLength; // <char> * TextureNameLength immediately follows }; //--------------------------------------- .msh file --------------------------------------- #define DF_MATERIAL_SHADER_HEADER_MAGIC ((uint32)'MSH1') struct DF_MATERIAL_SHADER_HEADER { uint32 Magic; uint32 HeaderSize; uint32 BlendingMode; uint32 LightingType; uint32 LightingModel; uint32 LightingNormalSpace; uint32 RenderMode; uint32 RenderLayer; bool TwoSided; bool DepthClamping; bool DepthTests; bool DepthWrites; bool CastShadows; bool ReceiveShadows; uint32 SourceCRC; uint32 UniformParameterCount; uint32 TextureParameterCount; uint32 StaticSwitchParameterCount; }; struct DF_MATERIAL_SHADER_UNIFORM_PARAMETER { uint32 NameLength; uint32 Type; byte DefaultValue[16]; // needs to be as large as MaterialShader::UniformParameter::Value // <char> * NameLength immediately follows }; struct DF_MATERIAL_SHADER_TEXTURE_PARAMETER { uint32 NameLength; uint32 Type; uint32 DefaultValueLength; // <char> * NameLength immediately follows // <char> * DefaultValueLength immediately follows }; struct DF_MATERIAL_SHADER_STATIC_SWITCH_PARAMETER { uint32 NameLength; uint32 Mask; bool DefaultValue; // <char> * NameLength immediately follows }; //--------------------------------------- .shg file --------------------------------------- #define DF_SHADER_GRAPH_HEADER_MAGIC ((uint32)'SHG1') //------------------------------------ .blp file ------------------------------------ #define DF_BLOCK_PALETTE_HEADER_MAGIC 0x4C425659 // YSHG enum DF_BLOCK_PALETTE_CHUNK_TYPE { DF_BLOCK_PALETTE_CHUNK_BLOCK_TYPES, DF_BLOCK_PALETTE_CHUNK_TEXTURES, DF_BLOCK_PALETTE_CHUNK_MATERIALS, DF_BLOCK_PALETTE_CHUNK_MESHES, DF_BLOCK_PALETTE_CHUNK_COUNT, }; struct DF_BLOCK_PALETTE_LIST_HEADER { uint32 Magic; uint32 HeaderSize; uint32 BlockTypeCount; uint32 TextureCount; uint32 MaterialCount; uint32 MeshCount; }; struct DF_BLOCK_PALETTE_BLOCK_TYPE { uint32 BlockTypeIndex; uint32 NameStringIndex; uint32 Flags; uint32 ShapeType; struct VisualParameters { uint32 Type; uint32 MaterialIndex; uint32 Color; float MinUV[3]; float MaxUV[3]; float AtlasUVRange[4]; }; struct CubeShapeFace { VisualParameters Visual; }; struct SlabShape { float Height; }; struct PlaneShape { VisualParameters Visual; float OffsetX; float OffsetY; float Width; float Height; float BaseRotation; uint32 RepeatCount; float RepeatRotation; }; struct MeshShape { uint32 MeshIndex; float Scale; }; struct BlockLightEmitter { uint32 Radius; }; struct PointLightEmitter { float Offset[3]; uint32 Color; float Brightness; float Range; float Falloff; }; CubeShapeFace CubeShapeFaces[CUBE_FACE_COUNT]; SlabShape SlabSettings; PlaneShape PlaneSettings; MeshShape MeshSettings; BlockLightEmitter BlockLightEmitterSettings; PointLightEmitter PointLightEmitterSettings; }; struct DF_BLOCK_PALETTE_TEXTURE { uint32 TextureOffset; // relative to this chunk uint32 TextureSize; }; enum DF_BLOCK_PALETTE_MATERIAL_TYPE { DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL, DF_BLOCK_PALETTE_MATERIAL_TYPE_COLOR, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_COLOR, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS_WITH_NORMAL_MAP, DF_BLOCK_PALETTE_MATERIAL_TYPE_COUNT, }; enum DF_BLOCK_PALETTE_MATERIAL_FLAGS { DF_BLOCK_PALETTE_MATERIAL_FLAG_SCROLLED_TEXTURE = (1 << 0), DF_BLOCK_PALETTE_MATERIAL_FLAG_ANIMATED_TEXTURE = (1 << 1), }; struct DF_BLOCK_PALETTE_MATERIAL { uint32 MaterialType; uint32 MaterialFlags; uint32 MaterialNameStringIndex; uint32 DiffuseMapTextureIndex; uint32 SpecularMapTextureIndex; uint32 NormalMapTextureIndex; float TextureScrollVector[2]; }; struct DF_BLOCK_PALETTE_MESH { uint32 MeshNameStringIndex; }; //------------------------------------ .blocklist file ------------------------------------ #define DF_BLOCK_TERRAIN_BLOCK_LIST_HEADER_MAGIC 0x4C425660 // YSHG enum DF_BLOCK_TERRAIN_BLOCK_LIST_CHUNK_TYPE { DF_BLOCK_TERRAIN_BLOCK_LIST_CHUNK_BLOCK_TYPES, DF_BLOCK_TERRAIN_BLOCK_LIST_CHUNK_TEXTURES, DF_BLOCK_TERRAIN_BLOCK_LIST_CHUNK_MATERIALS, DF_BLOCK_TERRAIN_BLOCK_LIST_CHUNK_COUNT, }; struct DF_BLOCK_TERRAIN_BLOCK_LIST_HEADER { uint32 Magic; uint32 HeaderSize; float BlockScale; uint32 BlockTypeCount; uint32 TextureCount; uint32 MaterialCount; }; struct DF_BLOCK_TERRAIN_BLOCK_LIST_BLOCK_TYPE { uint32 BlockTypeIndex; uint32 NameStringIndex; uint32 Flags; uint32 ShapeType; struct CubeShapeFace { uint32 VisualType; uint32 MaterialIndex; uint32 SilhouetteMaterialIndex; uint32 Color; float MinUV[3]; float MaxUV[3]; float AtlasUVRange[4]; }; CubeShapeFace CubeShapeFaces[CUBE_FACE_COUNT]; }; struct DF_BLOCK_TERRAIN_BLOCK_LIST_TEXTURE { uint32 TextureNameStringIndex; uint32 TextureOffset; // relative to this chunk uint32 TextureSize; }; enum DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE { DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_EXTERNAL, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_STATIC_COLOR, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_STATIC_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_STATIC_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_STATIC_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_SCROLLED_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_SCROLLED_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_SCROLLED_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_SILHOUETTE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_COLOR, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SCROLLED_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SCROLLED_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SCROLLED_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_STATIC_COLOR, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_STATIC_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_STATIC_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_STATIC_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_SCROLLED_TEXTURE, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_SCROLLED_TEXTURE_ARRAY, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SILHOUETTE_SCROLLED_TEXTURE_ATLAS, DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL_TYPE_COUNT, }; struct DF_BLOCK_TERRAIN_BLOCK_LIST_MATERIAL { uint32 MaterialNameStringIndex; uint32 MaterialType; uint32 AutoGenDiffuseMapTextureIndex; uint32 AutoGenSpecularMapTextureIndex; uint32 AutoGenNormalMapTextureIndex; float AutoGenTextureScrollVector[2]; }; //------------------------------------ .blocklist file ------------------------------------ #define DF_TERRAIN_LAYER_LIST_HEADER_MAGIC 0x4C425660 // YSHG enum DF_TERRAIN_LAYER_LIST_CHUNK_TYPE { DF_TERRAIN_LAYER_LIST_CHUNK_TEXTURES, DF_TERRAIN_LAYER_LIST_CHUNK_MATERIALS, DF_TERRAIN_LAYER_LIST_CHUNK_BASE_LAYERS, DF_TERRAIN_LAYER_LIST_CHUNK_COUNT, }; struct DF_TERRAIN_LAYER_LIST_HEADER { uint32 Magic; uint32 HeaderSize; uint32 TextureCount; uint32 BaseLayerArraySize; uint32 BaseLayerCount; int32 CombinedBaseLayerBaseTextureIndex; int32 CombinedBaseLayerNormalTextureIndex; }; struct DF_TERRAIN_LAYER_LIST_TEXTURE { uint32 TextureOffset; // relative to this chunk uint32 TextureSize; }; struct DF_TERRAIN_LAYER_LIST_BASE_LAYER { uint32 LayerIndex; uint32 NameStringIndex; uint32 TextureRepeatInterval; int32 BaseTextureIndex; int32 BaseTextureArrayIndex; int32 NormalTextureIndex; int32 NormalTextureArrayIndex; }; #define DF_TERRAIN_SECTION_HEADER_MAGIC 0x4C425660 struct DF_TERRAIN_SECTION_HEADER { uint32 Magic; uint32 HeaderSize; uint32 PointCount; uint32 HeightMapValueSize; uint32 HeightMapRowPitch; uint32 SplatMapCount; }; struct DF_TERRAIN_SECTION_SPLAT_MAP_HEADER { uint8 Layers[4]; uint32 LayerCount; uint32 ChannelCount; uint32 RowPitch; }; #define DF_TERRAIN_QUADTREE_HEADER_MAGIC 0x4C425680 struct DF_TERRAIN_QUADTREE_HEADER { uint32 Magic; uint32 HeaderSize; uint32 LODCount; uint32 NodeCount; }; struct DF_TERRAIN_QUADTREE_NODE { uint32 LODLevel; uint32 StartQuadX; uint32 StartQuadY; uint32 NodeSize; float BoundingBoxMin[3]; float BoundingBoxMax[3]; float BoundingSphereCenter[3]; float BoundingSphereRadius; uint8 IsLeafNode; uint8 IsFlat; int32 ChildNodeIndices[4]; }; //--------------------------------- .staticblockmesh file --------------------------------- #define DF_BLOCK_MESH_HEADER_MAGIC ((uint32)'BLM1') enum DF_STATIC_BLOCK_MESH_CHUNK_TYPE { DF_STATIC_BLOCK_MESH_CHUNK_EMBEDDED_BLOCKLIST, DF_STATIC_BLOCK_MESH_CHUNK_BLOCK_DATA, DF_STATIC_BLOCK_MESH_CHUNK_VERTICES, DF_STATIC_BLOCK_MESH_CHUNK_INDICES, DF_STATIC_BLOCK_MESH_CHUNK_BATCHES, DF_STATIC_BLOCK_MESH_CHUNK_COUNT, }; struct DF_STATIC_BLOCK_MESH_HEADER { uint32 Magic; uint32 HeaderSize; uint32 BlockListNameStringIndex; int32 MinCoordinates[3]; int32 MaxCoordinates[3]; uint32 WidthInBlocks; uint32 LengthInBlocks; uint32 HeightInBlocks; float MinBounds[3]; float MaxBounds[3]; uint32 VertexCount; uint32 IndexCount; uint32 IndexSize; uint32 BatchCount; }; struct DF_STATIC_BLOCK_MESH_VERTEX { float Position[3]; float Tangent[3]; float Binormal[3]; float Normal[3]; float TexCoord[3]; float AtlasTexCoord[4]; uint32 Color; }; struct DF_STATIC_BLOCK_MESH_BATCH { uint32 MaterialIndex; uint32 StartIndex; uint32 IndexCount; uint32 MinVertexIndex; uint32 MaxVertexIndex; }; //--------------------------------- .particlesystem file --------------------------------- #define DF_PARTICLE_SYSTEM_HEADER_MAGIC ((uint32)'PTS1') struct DF_PARTICLE_SYSTEM_HEADER { uint32 Magic; uint32 HeaderSize; uint32 ClassTableOffset; uint32 ClassTableSize; uint32 EmitterOffset; uint32 EmitterCount; }; struct DF_PARTICLE_SYSTEM_EMITTER_HEADER { uint32 TotalSize; uint32 TypeIndex; uint32 PropertiesOffset; uint32 ModuleOffset; uint32 ModuleCount; }; struct DF_PARTICLE_SYSTEM_MODULE_HEADER { uint32 TotalSize; uint32 TypeIndex; }; //--------------------------------- shader program --------------------------------- #define DF_SHADER_PROGRAM_COMMON_HEADER_MAGIC 0x45454545 struct DF_SHADER_PROGRAM_COMMON_HEADER { uint32 Magic; uint32 ShaderStoreCRC; uint32 BaseShaderParameterCRC; uint32 VertexFactoryParameterCRC; uint32 MaterialShaderCRC; }; //--------------------------------- .map file --------------------------------- //#define DF_MAP_HEADER_MAGIC 0x50414D59 // YMAP //#define DF_MAP_TERRAIN_HEADER_MAGIC 0x50414D60 // YMAP //#define DF_MAP_BLOCK_TERRAIN_HEADER_MAGIC 0x50414D61 // YMAP #define DF_MAP_HEADER_FILENAME "map.dat" #define DF_MAP_HEADER_VERSION 7 #define DF_MAP_REGIONS_HEADER_FILENAME "regions.dat" #define DF_MAP_TERRAIN_HEADER_FILENAME "terrain.dat" #define DF_MAP_TERRAIN_LAYERS_FILENAME_PREFIX "terrain.layers" #define DF_MAP_BLOCK_TERRAIN_HEADER_FILENAME "block_terrain.dat" #define DF_MAP_GLOBAL_ENTITIES_FILENAME "global_entities.dat" #define DF_MAP_CLASS_TABLE_FILENAME "class_table.dat" // lives in 'map.dat' struct DF_MAP_HEADER { uint32 HeaderSize; uint32 Version; uint32 RegionSize; uint32 RegionLODLevels; uint32 RegionLoadRadius; uint32 RegionActivationRadius; float WorldBoundingBoxMin[3]; float WorldBoundingBoxMax[3]; uint32 HasRegions; uint32 HasTerrain; uint32 HasGlobalEntities; // if HasTerrain // DF_MAP_TERRAIN_HEADER x 1 // <int2> x RegionCount // <byte> x GlobalEntityDataSize }; struct DF_MAP_REGIONS_HEADER { uint32 HeaderSize; uint32 RegionCount; }; struct DF_MAP_TERRAIN_HEADER { uint32 HeaderSize; uint32 HeightStorageFormat; int32 MinHeight; int32 MaxHeight; int32 BaseHeight; uint32 Scale; uint32 SectionSize; uint32 LODCount; }; struct DF_MAP_BLOCK_TERRAIN_HEADER { uint32 HeaderSize; uint32 PaletteNameLength; uint32 Scale; uint32 SectionSize; uint32 ChunkSize; uint32 StorageLODCount; int32 MinSectionX; int32 MinSectionY; int32 MaxSectionX; int32 MaxSectionY; uint32 SectionCount; // <char> x PaletteNameLength follows immediately after, then // <int2> x SectionCount }; struct DF_MAP_GLOBAL_ENTITIES_HEADER { uint32 HeaderSize; uint32 EntityCount; uint32 EntityDataSize; }; struct DF_MAP_REGION_HEADER { uint32 HeaderSize; uint32 LODLevel; int32 RegionX; int32 RegionY; uint32 TerrainSectionCount; uint32 TerrainDataSize; uint32 EntityCount; uint32 EntityDataSize; }; struct DF_MAP_REGION_TERRAIN_SECTION_HEADER { int32 SectionX; int32 SectionY; uint32 LODLevel; uint32 DataSize; // <byte> x DataSize follows }; struct DF_MAP_ENTITY_HEADER { uint32 HeaderSize; uint32 EntityNameLength; uint32 EntityTypeIndex; uint32 EntitySize; uint32 ComponentsSize; uint32 ComponentCount; }; struct DF_MAP_ENTITY_COMPONENT_HEADER { uint32 ComponentSize; uint32 ComponentNameLength; uint32 ComponentTypeIndex; }; #ifdef Y_COMPILER_MSVC #pragma warning(pop) #endif #pragma pack(pop) <file_sep>/Engine/Source/ResourceCompilerInterface/ResourceCompilerInterfaceRemote.h #pragma once #include "ResourceCompilerInterface/ResourceCompilerInterface.h" #include "ResourceCompiler/ResourceCompilerCallbacks.h" #include "YBaseLib/Subprocess.h" enum REMOTE_COMMAND { REMOTE_COMMAND_EXIT, REMOTE_COMMAND_COMPILE_TEXTURE, REMOTE_COMMAND_COMPILE_MATERIAL_SHADER, REMOTE_COMMAND_COMPILE_MATERIAL, REMOTE_COMMAND_COMPILE_FONT, REMOTE_COMMAND_COMPILE_BLOCK_PALETTE, REMOTE_COMMAND_COMPILE_STATIC_MESH, REMOTE_COMMAND_COMPILE_BLOCK_MESH, REMOTE_COMMAND_COMPILE_SKELETON, REMOTE_COMMAND_COMPILE_SKELETAL_ANIMATION, REMOTE_COMMAND_COMPILE_SKELETAL_MESH, REMOTE_COMMAND_COMPILE_PARTICLE_SYSTEM, REMOTE_COMMAND_COMPILE_TERRAIN_LAYER_LIST, REMOTE_COMMAND_COMPILE_SHADER, REMOTE_COMMAND_GET_FILE_CONTENTS, REMOTE_COMMAND_GET_COMPILED_MATERIAL_SHADER, REMOTE_COMMAND_GET_COMPILED_SKELETON, REMOTE_COMMAND_SUCCESS, REMOTE_COMMAND_FAILURE, NUM_REMOTE_COMMANDS }; #pragma pack(push, 4) struct REMOTE_COMMAND_HEADER { uint32 Command; uint32 PayloadSize; }; #pragma pack(pop) class ResourceCompilerInterfaceRemote : public ResourceCompilerInterface { public: ResourceCompilerInterfaceRemote(Subprocess *pSubProcess, Subprocess::Connection *pConnection); virtual ~ResourceCompilerInterfaceRemote(); virtual BinaryBlob *CompileTexture(uint32 texturePlatform, const char *name) override; virtual BinaryBlob *CompileMaterialShader(const char *name) override; virtual BinaryBlob *CompileMaterial(const char *name) override; virtual BinaryBlob *CompileFont(uint32 texturePlatform, const char *name) override; virtual BinaryBlob *CompileBlockPalette(uint32 texturePlatform, const char *name) override; virtual BinaryBlob *CompileStaticMesh(const char *name) override; virtual BinaryBlob *CompileBlockMesh(const char *name) override; virtual BinaryBlob *CompileSkeleton(const char *name) override; virtual BinaryBlob *CompileSkeletalMesh(const char *name) override; virtual BinaryBlob *CompileSkeletalAnimation(const char *name) override; virtual BinaryBlob *CompileParticleSystem(const char *name) override; virtual BinaryBlob *CompileTerrainLayerList(const char *name) override; virtual bool CompileShader(const ShaderCompilerParameters *pParameters, ByteStream *pOutByteCodeStream, ByteStream *pOutInfoLogStream) override; static void RemoteProcessLoop(); private: Subprocess *m_pRemoteProcess; Subprocess::Connection *m_pRemoteConnection; }; <file_sep>/Tests/Source/TestRenderer.cpp #include "Engine/InputManager.h" #include "Engine/ScriptManager.h" #include "Engine/FPSCounter.h" #include "Engine/EngineCVars.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" #include "Engine/SDLHeaders.h" #include "Engine/Camera.h" #include "Renderer/Renderer.h" #include "Renderer/ImGuiBridge.h" #include "YBaseLib/CPUID.h" Log_SetChannel(TestRenderer); static FPSCounter g_fpsCounter; static MiniGUIContext g_guiContext; static RendererOutputWindow *g_pOutputWindow = nullptr; static GPUContext *g_pMainGPUContext = nullptr; static bool g_quitFlag = false; static bool RendererStart() { // apply pending renderer cvars g_pConsole->ApplyPendingRenderCVars(); // fill parameters RendererInitializationParameters initParameters; initParameters.EnableThreadedRendering = false; initParameters.BackBufferFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; initParameters.DepthStencilBufferFormat = PIXEL_FORMAT_D24_UNORM_S8_UINT; initParameters.HideImplicitSwapChain = false; // fill platform if (!NameTable_TranslateType(NameTables::RendererPlatform, CVars::r_platform.GetString(), &initParameters.Platform, true)) { initParameters.Platform = Renderer::GetDefaultPlatform(); Log_ErrorPrintf("Invalid renderer platform: '%s', defaulting to %s", CVars::r_platform.GetString().GetCharArray(), NameTable_GetNameString(NameTables::RendererPlatform, initParameters.Platform)); } // determine w/h to use, windowed fullscreen uses desktop size, ie (0, 0) if (CVars::r_fullscreen.GetBool()) initParameters.ImplicitSwapChainFullScreen = (CVars::r_fullscreen_exclusive.GetBool()) ? RENDERER_FULLSCREEN_STATE_FULLSCREEN : RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN; else initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED; if (initParameters.ImplicitSwapChainFullScreen == RENDERER_FULLSCREEN_STATE_FULLSCREEN) { initParameters.ImplicitSwapChainWidth = CVars::r_fullscreen_width.GetUInt(); initParameters.ImplicitSwapChainHeight = CVars::r_fullscreen_height.GetUInt(); } else if (initParameters.ImplicitSwapChainFullScreen == RENDERER_FULLSCREEN_STATE_WINDOWED) { initParameters.ImplicitSwapChainWidth = CVars::r_windowed_width.GetUInt(); initParameters.ImplicitSwapChainHeight = CVars::r_windowed_height.GetUInt(); } // todo: vsync initParameters.ImplicitSwapChainVSyncType = RENDERER_VSYNC_TYPE_NONE; // create renderer if (!Renderer::Create(&initParameters)) { // try some sensible defaults Log_ErrorPrintf("Renderer creation failed with specified parameters. Trying fallback."); initParameters.Platform = Renderer::GetDefaultPlatform(); initParameters.ImplicitSwapChainFullScreen = RENDERER_FULLSCREEN_STATE_WINDOWED; initParameters.ImplicitSwapChainWidth = 640; initParameters.ImplicitSwapChainHeight = 480; initParameters.ImplicitSwapChainVSyncType = RENDERER_VSYNC_TYPE_NONE; // create again if (!Renderer::Create(&initParameters)) { Panic("Failed to create renderer with fallback parameters."); return false; } } // store variables g_pMainGPUContext = g_pRenderer->GetGPUContext(); g_pOutputWindow = g_pRenderer->GetImplicitOutputWindow(); // get actual viewport dimensions uint32 bufferWidth = g_pOutputWindow->GetOutputBuffer()->GetWidth(); uint32 bufferHeight = g_pOutputWindow->GetOutputBuffer()->GetHeight(); // initialize remaining resources g_fpsCounter.SetGPUContext(g_pMainGPUContext); g_fpsCounter.CreateGPUResources(); g_guiContext.SetViewportDimensions(bufferWidth, bufferHeight); g_guiContext.SetGPUContext(g_pMainGPUContext); // init imgui ImGui::InitializeBridge(); // done return true; } static bool Boot(void(*RunCallback)()) { // guard in case something calls this function static bool __mainEntered = false; DebugAssert(__mainEntered == false); __mainEntered = true; // initialization timer Timer initTimer; int32 exitCode = 0; // initialize SDL first if (SDL_Init(0) < 0) { Log_ErrorPrintf("SDL initialization failed: %s", SDL_GetError()); exitCode = -1; goto RETURN_LABEL; } // print version info { Y_CPUID_RESULT CPUIDResult; Y_ReadCPUID(&CPUIDResult); Log_DevPrint("Build Configuration: " Y_BUILD_CONFIG_STR); Log_DevPrint("Build Platform: " Y_PLATFORM_STR); Log_DevPrint("Build Architecture: " Y_CPU_STR Y_CPU_FEATURES_STR); Log_DevPrintf("Running on CPU: %s", CPUIDResult.SummaryString); } // initialize vfs Log_InfoPrint("Initializing virtual file system..."); if (!g_pVirtualFileSystem->Initialize()) { Log_InfoPrint("Virtual file system initialization failed. Cannot continue."); exitCode = -2; goto SHUTDOWN_SDL_LABEL; } // add types Log_InfoPrint("Registering types..."); g_pEngine->RegisterEngineTypes(); // start renderer Log_InfoPrint("Starting renderer..."); if (!RendererStart()) { Log_ErrorPrint("Failed to start renderer."); exitCode = -3; goto SHUTDOWN_VFS_LABEL; } // start input system Log_InfoPrint("Starting input subsystem..."); if (!g_pInputManager->Startup()) { Log_ErrorPrint("Failed to start input subsystem."); exitCode = -4; goto SHUTDOWN_RENDERER_LABEL; } // start script subsystem Log_InfoPrint("Starting script subsystem..."); if (!g_pScriptManager->Startup()) { Log_ErrorPrint("Failed to start script subsystem."); exitCode = -5; goto SHUTDOWN_INPUT_LABEL; } // fix this... if (!g_pEngine->Startup()) { exitCode = -6; goto SHUTDOWN_SCRIPT_LABEL; } // everything started Log_InfoPrintf("All engine subsystems initialized in %.2f msec", initTimer.GetTimeMilliseconds()); // run RunCallback(); //SHUTDOWN_RESOURCES_LABEL: // release resources Log_InfoPrint("Unloading resources..."); //g_pResourceManager->ReleaseResources(); g_pEngine->Shutdown(); // begin shutting down Log_InfoPrint("Shutting down all subsystems..."); initTimer.Reset(); SHUTDOWN_SCRIPT_LABEL: // shutdown script subsystem Log_InfoPrint("Shutting down script subsystem..."); g_pScriptManager->Shutdown(); SHUTDOWN_INPUT_LABEL: // shutdown input subsystem Log_InfoPrint("Shutting down input subsystem..."); g_pInputManager->Shutdown(); SHUTDOWN_RENDERER_LABEL: // shutdown renderer Log_InfoPrint("Shutting down renderer..."); ImGui::FreeResources(); g_pResourceManager->ReleaseDeviceResources(); g_pRenderer->Shutdown(); g_pResourceManager->ReleaseResources(); SHUTDOWN_VFS_LABEL: // shutdown vfs g_pVirtualFileSystem->Shutdown(); SHUTDOWN_SDL_LABEL: SDL_Quit(); RETURN_LABEL: if (exitCode == 0) Log_InfoPrintf("All engine subsystems shutdown in %.2f msec", initTimer.GetTimeMilliseconds()); return 0; } static void CheckEvents() { // get new messages from the underlying subsystem SDL_PumpEvents(); // loop until we have everything for (;;) { // get events SDL_Event events[128]; int nEvents = SDL_PeepEvents(events, countof(events), SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT); if (nEvents <= 0) break; // process them for (int i = 0; i < nEvents; i++) { // there are only a few messages we are interested in const SDL_Event *pEvent = &events[i]; switch (pEvent->type) { case SDL_WINDOWEVENT: { // the window associated with this event should be our output window, if not, skip it if (SDL_GetWindowFromID(pEvent->window.windowID) != g_pOutputWindow->GetSDLWindow()) continue; // handle the event switch (pEvent->window.event) { case SDL_WINDOWEVENT_RESIZED: //OnWindowResized(pEvent->window.data1, pEvent->window.data2); //m_restartRendererFlag = true; break; case SDL_WINDOWEVENT_CLOSE: g_quitFlag = true; break; case SDL_WINDOWEVENT_FOCUS_GAINED: //OnWindowFocusGained(); break; case SDL_WINDOWEVENT_FOCUS_LOST: //OnWindowFocusLost(); break; } // don't add it to the main thread's queue, these sorts of messages are of no use to it continue; } break; case SDL_SYSWMEVENT: { // syswmevents are of no use to the main thread continue; } break; } // append to the main thread's queue for later processing //m_pendingEvents.Add(*pEvent); ImGui::HandleSDLEvent(pEvent, true); } } } static Timer s_frameTimer; static void Frame() { float deltaTime = (float)s_frameTimer.GetTimeSeconds(); s_frameTimer.Reset(); // update stats g_fpsCounter.BeginFrame(); CheckEvents(); // imgui ImGui::NewFrame(deltaTime); // do stuff { g_pMainGPUContext->BeginFrame(); g_pMainGPUContext->SetRenderTargets(0, nullptr, nullptr); g_pMainGPUContext->SetFullViewport(); g_pMainGPUContext->ClearTargets(true, true, true, Vector4f(0.5f, 0.2f, 0.8f, 0.0f)); Camera camera; camera.SetPosition(float3::Zero); camera.SetProjectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE); g_pMainGPUContext->GetConstants()->SetFromCamera(camera, true); MINIGUI_RECT rect(40, 140, 40, 140); g_guiContext.PushManualFlush(); g_guiContext.DrawFilledRect(&rect, MAKE_COLOR_R8G8B8_UNORM(255, 200, 150)); rect.Set(200, 240, 40, 140); g_guiContext.DrawFilledRect(&rect, MAKE_COLOR_R8G8B8_UNORM(150, 255, 200)); g_guiContext.DrawTextAt(40, 160, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255), "Hello world"); g_guiContext.Draw3DBox(AABox(0.0f, 3.0f, 0.0f, 1.0f, 4.0f, 1.0f), MAKE_COLOR_R8G8B8_UNORM(255, 255, 255)); g_guiContext.PopManualFlush(); g_guiContext.Flush(); // draw imgui { ImGui::ShowTestWindow(nullptr); } // render imgui ImGui::Render(); g_fpsCounter.DrawDetails(g_pRenderer->GetFixedResources()->GetDebugFont(), &g_guiContext); g_pMainGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); } // end g_fpsCounter.EndGameThreadFrame(); } static void Run() { #ifdef Y_PLATFORM_HTML5 emscripten_set_main_loop(Frame, 0, true); #else while (!g_quitFlag) { Frame(); } #endif } int main(int argc, char *argv[]) { // change gamename g_pConsole->SetCVarByName("vfs_gamedir", "TestGame", true); g_pConsole->ApplyPendingAppCVars(); // set log flags Log::GetInstance().SetConsoleOutputParams(true); Log::GetInstance().SetDebugOutputParams(true); // parse command line g_pConsole->ParseCommandLine(argc, (const char **)argv); g_pConsole->ApplyPendingAppCVars(); // force multithreaded rendering off g_pConsole->SetCVarByName("r_use_render_thread", "false"); g_pConsole->ApplyPendingAppCVars(); return (Boot(Run)) ? 0 : -1; } <file_sep>/Engine/Source/ResourceCompiler/TerrainLayerListGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/TerrainLayerList.h" class Image; class ZipArchive; class XMLReader; class XMLWriter; class TerrainLayerListGenerator { friend class TerrainLayerListCompiler; public: struct BaseLayer { uint32 Index; bool Allocated; String Name; uint32 TextureRepeatInterval; Image *pBaseMap; Image *pNormalMap; }; public: TerrainLayerListGenerator(); ~TerrainLayerListGenerator(); // creation void Create(uint32 diffuseMapSize, uint32 normalMapSize); void CreateCopy(const TerrainLayerListGenerator *pGenerator); bool Load(const char *FileName, ByteStream *pStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // output bool Save(ByteStream *pStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback) const; // accessors const uint32 GetBaseLayerBaseMapResolution() const { return m_baseLayerBaseMapResolution; } const uint32 GetBaseLayerNormalMapResolution() const { return m_baseLayerNormalMapResolution; } // base layer normal mapping bool IsBaseLayerNormalMappingEnabled() const { return m_baseLayerNormalMapping; } void SetBaseLayerNormalMappingEnabled(bool enabled) { m_baseLayerNormalMapping = enabled; } // base layers const BaseLayer *GetBaseLayer(uint32 index) const { DebugAssert(index < TERRAIN_MAX_LAYERS); return (m_baseLayers[index].Allocated) ? &m_baseLayers[index] : nullptr; } BaseLayer *GetBaseLayer(uint32 index) { DebugAssert(index < TERRAIN_MAX_LAYERS); return (m_baseLayers[index].Allocated) ? &m_baseLayers[index] : nullptr; } int32 GetBaseLayerIndexByName(const char *layerName) const; const BaseLayer *GetBaseLayerByName(const char *layerName) const; BaseLayer *GetBaseLayerByName(const char *layerName); BaseLayer *CreateBaseLayer(const char *layerName); void DeleteBaseLayer(uint32 index); // base layer manipulation bool SetBaseLayerBaseMap(uint32 index, const Image *pImage); bool SetBaseLayerNormalMap(uint32 index, const Image *pImage); // compiler bool Compile(ByteStream *pOutputStream) const; private: BaseLayer m_baseLayers[TERRAIN_MAX_LAYERS]; bool m_baseLayerNormalMapping; uint32 m_baseLayerBaseMapResolution; uint32 m_baseLayerNormalMapResolution; bool LoadBaseLayers(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks); bool LoadBaseLayerTextures(ZipArchive *pArchive, BaseLayer *pBaseLayer, ProgressCallbacks *pProgressCallbacks); bool SaveBaseLayers(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const; bool SaveBaseLayerTextures(ZipArchive *pArchive, const BaseLayer *pBaseLayer, ProgressCallbacks *pProgressCallbacks) const; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUOutputBuffer.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12Helpers.h" #include "Engine/SDLHeaders.h" Log_SetChannel(D3D12GPUOutputBuffer); // fix up a warning #ifdef SDL_VIDEO_DRIVER_WINDOWS #undef WIN32_LEAN_AND_MEAN #endif #include <SDL/SDL_syswm.h> static const char *SDL_D3D11_RENDERER_OUTPUT_WINDOW_POINTER_STRING = "D3D12RendererOutputBufferPtr"; static uint32 CalculateDXGISwapChainBufferCount(uint32 frameLatency, bool exclusiveFullscreen, RENDERER_VSYNC_TYPE vsyncType) { //DebugAssert(frameLatency > 0); //return 2 + (frameLatency - 1) + ((vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING) ? 1 : 0); return 2 + (frameLatency - 1) + ((vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING) ? 1 : 0); } D3D12GPUOutputBuffer::D3D12GPUOutputBuffer(D3D12GPUDevice *pDevice, ID3D12Device *pD3DDevice, IDXGISwapChain3 *pDXGISwapChain, HWND hWnd, uint32 width, uint32 height, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilFormat, DXGI_FORMAT backBufferDXGIFormat, DXGI_FORMAT depthStencilDXGIFormat, RENDERER_VSYNC_TYPE vsyncType) : GPUOutputBuffer(vsyncType) , m_pDevice(pDevice) , m_pD3DDevice(pD3DDevice) , m_pDXGISwapChain(pDXGISwapChain) , m_hWnd(hWnd) , m_width(width) , m_height(height) , m_backBufferFormat(backBufferFormat) , m_depthStencilFormat(depthStencilFormat) , m_backBufferDXGIFormat(backBufferDXGIFormat) , m_depthStencilDXGIFormat(depthStencilDXGIFormat) , m_currentBackBufferIndex(0xFFFFFFFF) , m_pDepthStencilBuffer(nullptr) { m_pDevice->AddRef(); } D3D12GPUOutputBuffer::~D3D12GPUOutputBuffer() { InternalReleaseBuffers(); SAFE_RELEASE(m_pDXGISwapChain); m_pDevice->Release(); } D3D12GPUOutputBuffer *D3D12GPUOutputBuffer::Create(D3D12GPUDevice *pDevice, IDXGIFactory4 *pDXGIFactory, ID3D12Device *pD3DDevice, ID3D12CommandQueue *pCommandQueue, HWND hWnd, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilFormat, RENDERER_VSYNC_TYPE vsyncType) { HRESULT hResult; // select formats DXGI_FORMAT backBufferDXGIFormat = D3D12Helpers::PixelFormatToDXGIFormat(backBufferFormat); DXGI_FORMAT depthStencilDXGIFormat = (depthStencilFormat != PIXEL_FORMAT_UNKNOWN) ? D3D12Helpers::PixelFormatToDXGIFormat(depthStencilFormat) : DXGI_FORMAT_UNKNOWN; if (backBufferDXGIFormat == DXGI_FORMAT_UNKNOWN || (depthStencilFormat != PIXEL_FORMAT_UNKNOWN && depthStencilDXGIFormat == DXGI_FORMAT_UNKNOWN)) { Log_ErrorPrintf("Invalid swap chain format (%s / %s)", NameTable_GetNameString(NameTables::PixelFormat, backBufferFormat), NameTable_GetNameString(NameTables::PixelFormat, depthStencilFormat)); return false; } // get client rect of the window RECT clientRect; GetClientRect(hWnd, &clientRect); uint32 width = Max(clientRect.right - clientRect.left, (LONG)1); uint32 height = Max(clientRect.bottom - clientRect.top, (LONG)1); #if 0 // setup swap chain desc DXGI_SWAP_CHAIN_DESC1 swapChainDesc; Y_memzero(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.Width = width; swapChainDesc.Height = height; swapChainDesc.Format = backBufferDXGIFormat; swapChainDesc.Stereo = FALSE; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = CalculateDXGISwapChainBufferCount(false, vsyncType); swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; swapChainDesc.Scaling = DXGI_SCALING_STRETCH; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; swapChainDesc.Flags = 0; // create the swapchain IDXGISwapChain1 *pDXGISwapChain1; hResult = pDXGIFactory->CreateSwapChainForHwnd(pCommandQueue, hWnd, &swapChainDesc, nullptr, nullptr, &pDXGISwapChain1); if (FAILED(hResult)) { Log_ErrorPrintf("CreateSwapChainForHwnd failed with hResult %08X.", hResult); return nullptr; } #else DXGI_SWAP_CHAIN_DESC swapChainDesc; Y_memzero(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = backBufferDXGIFormat; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = CalculateDXGISwapChainBufferCount(pDevice->GetFrameLatency(), false, vsyncType); swapChainDesc.Flags = 0; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT | DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; swapChainDesc.OutputWindow = hWnd; swapChainDesc.Windowed = TRUE; IDXGISwapChain *pDXGISwapChain1; hResult = pDXGIFactory->CreateSwapChain(pCommandQueue, &swapChainDesc, &pDXGISwapChain1); if (FAILED(hResult)) { Log_ErrorPrintf("CreateSwapChain failed with hResult %08X.", hResult); return nullptr; } #endif // disable alt+enter, we handle it elsewhere hResult = pDXGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); if (FAILED(hResult)) { Log_ErrorPrintf("MakeWindowAssociation failed with hResult %08X.", hResult); pDXGISwapChain1->Release(); return nullptr; } // query IDXGISwapChain3 IDXGISwapChain3 *pDXGISwapChain; hResult = pDXGISwapChain1->QueryInterface(__uuidof(IDXGISwapChain3), (void **)&pDXGISwapChain); if (FAILED(hResult)) { Log_ErrorPrintf("IDXGISwapChain1::QueryInterface failed with hResult %08X.", hResult); pDXGISwapChain1->Release(); return nullptr; } // reference to version 1 not needed pDXGISwapChain1->Release(); //hResult = pDXGISwapChain->SetMaximumFrameLatency(3); // create object D3D12GPUOutputBuffer *pOutputBuffer = new D3D12GPUOutputBuffer(pDevice, pD3DDevice, pDXGISwapChain, hWnd, width, height, backBufferFormat, depthStencilFormat, backBufferDXGIFormat, depthStencilDXGIFormat, vsyncType); // create buffers if (!pOutputBuffer->InternalCreateBuffers()) { pOutputBuffer->Release(); return nullptr; } // done return pOutputBuffer; } ID3D12Resource *D3D12GPUOutputBuffer::GetCurrentBackBufferResource() const { DebugAssert(m_currentBackBufferIndex < m_backBuffers.GetSize()); return m_backBuffers[m_currentBackBufferIndex]; } D3D12_CPU_DESCRIPTOR_HANDLE D3D12GPUOutputBuffer::GetCurrentBackBufferViewDescriptorCPUHandle() const { return m_renderTargetViewsDescriptorStart.GetOffsetCPUHandle(m_currentBackBufferIndex); } bool D3D12GPUOutputBuffer::UpdateCurrentBackBuffer() { uint32 newBackBufferIndex = m_pDXGISwapChain->GetCurrentBackBufferIndex(); DebugAssert(newBackBufferIndex < m_backBuffers.GetSize()); if (newBackBufferIndex != m_currentBackBufferIndex) { //Log_DevPrintf("Update backbuffer index = %u", newBackBufferIndex); m_currentBackBufferIndex = newBackBufferIndex; return true; } else { return false; } } void D3D12GPUOutputBuffer::InternalResizeBuffers(uint32 width, uint32 height, RENDERER_VSYNC_TYPE vsyncType) { HRESULT hResult; // check if fullscreen state was lost BOOL newFullscreenState; hResult = m_pDXGISwapChain->GetFullscreenState(&newFullscreenState, nullptr); if (FAILED(hResult)) newFullscreenState = FALSE; // release resources InternalReleaseBuffers(); // calculate buffer count uint32 bufferCount = CalculateDXGISwapChainBufferCount(m_pDevice->GetFrameLatency(), (newFullscreenState == TRUE), m_vsyncType); Log_DevPrintf("New swap chain buffer count = %u", bufferCount); // invoke resize hResult = m_pDXGISwapChain->ResizeBuffers(bufferCount, width, height, m_backBufferDXGIFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); if (FAILED(hResult)) Panic("IDXGISwapChain::ResizeBuffers failed."); // update attributes m_width = width; m_height = height; m_vsyncType = vsyncType; // recreate textures if (!InternalCreateBuffers()) Panic("Failed to recreate texture objects on resized swap chain."); } bool D3D12GPUOutputBuffer::InternalCreateBuffers() { HRESULT hResult; // get descriptor DXGI_SWAP_CHAIN_DESC1 swapChainDesc; m_pDXGISwapChain->GetDesc1(&swapChainDesc); // find the current backbuffer index m_currentBackBufferIndex = 0xFFFFFFFF; m_backBuffers.Reserve(swapChainDesc.BufferCount); // allocate RTV descriptors if (!m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->AllocateRange(swapChainDesc.BufferCount, &m_renderTargetViewsDescriptorStart)) { Log_ErrorPrintf("Failed to allocate RTV descriptors."); return false; } // create render target views D3D12_RENDER_TARGET_VIEW_DESC rtvDesc; rtvDesc.Format = m_backBufferDXGIFormat; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; rtvDesc.Texture2D.PlaneSlice = 0; for (uint32 i = 0; i < swapChainDesc.BufferCount; i++) { // get a pointer to this backbuffer ID3D12Resource *pBackBuffer; hResult = m_pDXGISwapChain->GetBuffer(i, __uuidof(ID3D12Resource), (void **)&pBackBuffer); if (FAILED(hResult)) { Log_ErrorPrintf("IDXGISwapChain::GetBuffer failed with hResult %08X", hResult); m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->Free(m_renderTargetViewsDescriptorStart); return false; } // pass through m_pD3DDevice->CreateRenderTargetView(pBackBuffer, &rtvDesc, m_renderTargetViewsDescriptorStart.GetOffsetCPUHandle(i)); m_backBuffers.Add(pBackBuffer); } // allocate depth stencil buffer if (m_depthStencilDXGIFormat != DXGI_FORMAT_UNKNOWN) { // clear value D3D12_CLEAR_VALUE optimizedClearValue; D3D12_CLEAR_VALUE *pOptimizedClearValue; if (D3D12Helpers::GetOptimizedClearValue(m_depthStencilFormat, &optimizedClearValue)) pOptimizedClearValue = &optimizedClearValue; else pOptimizedClearValue = nullptr; // create resource D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, m_width, m_height, 1, 1, m_depthStencilDXGIFormat,{ 1, 0 }, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL }; hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_DEPTH_WRITE, pOptimizedClearValue, __uuidof(ID3D12Resource), (void **)&m_pDepthStencilBuffer); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommittedResource for DepthStencil failed with hResult %08X", hResult); m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->Free(m_renderTargetViewsDescriptorStart); return false; } // allocate DSV descriptor if (!m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)->Allocate(&m_depthStencilViewDescriptor)) { Log_ErrorPrintf("Failed to allocate DSV descriptors."); m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->Free(m_renderTargetViewsDescriptorStart); SAFE_RELEASE(m_pDepthStencilBuffer); return false; } // create depth stencil buffer views D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Format = m_depthStencilDXGIFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.Texture2D.MipSlice = 0; m_pD3DDevice->CreateDepthStencilView(m_pDepthStencilBuffer, &dsvDesc, m_depthStencilViewDescriptor); } return true; } void D3D12GPUOutputBuffer::InternalReleaseBuffers() { m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)->Free(m_renderTargetViewsDescriptorStart); m_pDevice->GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)->Free(m_depthStencilViewDescriptor); for (uint32 i = 0; i < m_backBuffers.GetSize(); i++) m_backBuffers[i]->Release(); m_backBuffers.Clear(); SAFE_RELEASE(m_pDepthStencilBuffer); } void D3D12GPUOutputBuffer::SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) { if (m_vsyncType == vsyncType) return; if (vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING || m_vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING) InternalResizeBuffers(m_width, m_height, vsyncType); else m_vsyncType = vsyncType; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GPUOutputBuffer *D3D12GPUDevice::CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) { // can only be done on the render thread return D3D12GPUOutputBuffer::Create(this, m_pDXGIFactory, m_pD3DDevice, m_pGraphicsCommandQueue->GetD3DCommandQueue(), (HWND)hWnd, m_outputBackBufferFormat, m_outputDepthStencilFormat, vsyncType); } GPUOutputBuffer *D3D12GPUDevice::CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) { // retreive the hwnd from the sdl window SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(pSDLWindow, &info)) { Log_ErrorPrintf("SDL_GetWindowWMInfo failed: %s", SDL_GetError()); return false; } return CreateOutputBuffer((RenderSystemWindowHandle)info.info.win.window, vsyncType); } <file_sep>/DemoGame/Source/DemoGame/BaseDemoWorldGameState.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/BaseDemoWorldGameState.h" #include "Engine/Engine.h" #include "Engine/EngineCVars.h" #include "Engine/InputManager.h" #include "Engine/DynamicWorld.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(BaseDemoWorldGameState); BaseDemoWorldGameState::BaseDemoWorldGameState(DemoGame *pDemoGame) : BaseDemoGameState(pDemoGame) , m_pWorld(nullptr) , m_dynamicWorldFlag(false) { } BaseDemoWorldGameState::~BaseDemoWorldGameState() { } bool BaseDemoWorldGameState::Initialize() { if (!BaseDemoGameState::Initialize()) return false; // get window width/height uint32 windowWidth = m_pDemoGame->GetOutputWindow()->GetWidth(); uint32 windowHeight = m_pDemoGame->GetOutputWindow()->GetHeight(); // initialize camera m_camera.SetProjectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE); m_camera.SetNearFarPlaneDistances(0.1f, 1000.0f); m_camera.SetObjectCullDistanceFromNearFar(); m_camera.SetClippingEnabled(false); m_camera.SetPerspectiveAspect((float)windowWidth, (float)windowHeight); // initialize view parameters m_viewParameters.Viewport.Set(0, 0, windowWidth, windowHeight, 0.0f, 1.0f); m_viewParameters.MaximumShadowViewDistance = m_camera.GetObjectCullDistance(); m_viewParameters.SetCamera(&m_camera); return true; } void BaseDemoWorldGameState::Shutdown() { if (m_dynamicWorldFlag) { World *pWorld = m_pWorld; OnWorldDeleted(pWorld); delete pWorld; m_pWorld = nullptr; } BaseDemoGameState::Shutdown(); } bool BaseDemoWorldGameState::CreateGPUResources() { if (!BaseDemoGameState::CreateGPUResources()) return false; return true; } void BaseDemoWorldGameState::ReleaseGPUResources() { BaseDemoGameState::ReleaseGPUResources(); } bool BaseDemoWorldGameState::OnWorldCreated(World *pWorld) { m_camera.SetWorld(pWorld); m_pWorld->AddObserver(&m_camera, m_camera.GetPosition()); return true; } void BaseDemoWorldGameState::OnWorldDeleted(World *pWorld) { m_camera.SetWorld(nullptr); } void BaseDemoWorldGameState::DrawOverlays(float deltaTime) { BaseDemoGameState::DrawOverlays(deltaTime); MiniGUIContext *guiContext = m_pDemoGame->GetGUIContext(); // draw camera position/rotation if (!m_uiActive) { guiContext->DrawFormattedTextAt(10, 26, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255), "Camera Position: %s", StringConverter::Float3ToString(m_viewParameters.ViewCamera.GetPosition()).GetCharArray()); guiContext->DrawFormattedTextAt(10, 42, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255), "Camera Direction: %s", StringConverter::Float3ToString(m_viewParameters.ViewCamera.GetRotation() * float3::UnitY).GetCharArray()); guiContext->DrawFormattedTextAt(10, 10, g_pRenderer->GetFixedResources()->GetDebugFont(), 16, MAKE_COLOR_R8G8B8_UNORM(255, 255, 255), "UI hidden, use WSAD to move camera, ESC to re-open UI"); } } void BaseDemoWorldGameState::DrawUI(float deltaTime) { BaseDemoGameState::DrawUI(deltaTime); // light options? } void BaseDemoWorldGameState::OnSwitchedIn() { BaseDemoGameState::OnSwitchedIn(); if (!m_uiActive) m_pDemoGame->SetRelativeMouseMovement(true); } void BaseDemoWorldGameState::OnSwitchedOut() { BaseDemoGameState::OnSwitchedOut(); if (!m_uiActive) m_pDemoGame->SetRelativeMouseMovement(false); } void BaseDemoWorldGameState::OnUIToggled(bool enabled) { BaseDemoGameState::OnUIToggled(enabled); if (enabled) m_pDemoGame->SetRelativeMouseMovement(false); else m_pDemoGame->SetRelativeMouseMovement(true); } void BaseDemoWorldGameState::OnBeforeDelete() { BaseDemoGameState::OnBeforeDelete(); } void BaseDemoWorldGameState::OnWindowResized(uint32 width, uint32 height) { BaseDemoGameState::OnWindowResized(width, height); m_viewParameters.Viewport.Set(0, 0, width, height, 0.0f, 1.0f); m_camera.SetPerspectiveAspect((float)width, (float)height); } void BaseDemoWorldGameState::OnWindowFocusGained() { BaseDemoGameState::OnWindowFocusGained(); } void BaseDemoWorldGameState::OnWindowFocusLost() { BaseDemoGameState::OnWindowFocusLost(); } bool BaseDemoWorldGameState::OnWindowEvent(const union SDL_Event *event) { if (BaseDemoGameState::OnWindowEvent(event)) return true; // only pass to camera if gui isn't activated if (!m_pDemoGame->IsImGuiActivated()) return m_camera.HandleSDLEvent(event); return false; } void BaseDemoWorldGameState::OnMainThreadPreFrame(float deltaTime) { BaseDemoGameState::OnMainThreadPreFrame(deltaTime); // update camera m_camera.Update(deltaTime); // update view parameters m_viewParameters.WorldTime = m_pWorld->GetGameTime(); m_viewParameters.ViewCamera = m_camera; } void BaseDemoWorldGameState::OnMainThreadBeginFrame(float deltaTime) { BaseDemoGameState::OnMainThreadBeginFrame(deltaTime); // update observer before the frame, that way the frame can ensure the correct stuff is loaded before it executes m_pWorld->UpdateObserver(&m_camera, m_camera.GetPosition()); m_pWorld->BeginFrame(deltaTime); } void BaseDemoWorldGameState::OnMainThreadAsyncTick(float deltaTime) { BaseDemoGameState::OnMainThreadAsyncTick(deltaTime); m_pWorld->UpdateAsync(deltaTime); } void BaseDemoWorldGameState::OnMainThreadTick(float deltaTime) { BaseDemoGameState::OnMainThreadTick(deltaTime); m_pWorld->Update(deltaTime); } void BaseDemoWorldGameState::OnMainThreadEndFrame(float deltaTime) { BaseDemoGameState::OnMainThreadEndFrame(deltaTime); m_pWorld->EndFrame(); } void BaseDemoWorldGameState::OnRenderThreadPreFrame(float deltaTime) { BaseDemoGameState::OnRenderThreadPreFrame(deltaTime); // copy camera from main thread to render thread before the main thread changes it m_viewParameters.SetCamera(&m_camera); } void BaseDemoWorldGameState::OnRenderThreadBeginFrame(float deltaTime) { BaseDemoGameState::OnRenderThreadPreFrame(deltaTime); } void BaseDemoWorldGameState::OnRenderThreadDraw(float deltaTime) { // draw world m_pDemoGame->GetWorldRenderer()->DrawWorld(m_pWorld->GetRenderWorld(), &m_viewParameters, nullptr, nullptr); // setup overlay draws m_pDemoGame->GetGPUContext()->SetRenderTargets(0, nullptr, nullptr); m_pDemoGame->GetGPUContext()->SetFullViewport(); m_pDemoGame->GetGPUContext()->GetConstants()->SetFromCamera(m_viewParameters.ViewCamera, false); m_pDemoGame->GetGPUContext()->GetConstants()->CommitChanges(); // draw overlays m_pDemoGame->GetGUIContext()->PushManualFlush(); DrawOverlays(deltaTime); m_pDemoGame->GetGUIContext()->PopManualFlush(); } void BaseDemoWorldGameState::OnRenderThreadEndFrame(float deltaTime) { BaseDemoGameState::OnRenderThreadEndFrame(deltaTime); } bool BaseDemoWorldGameState::CreateDynamicWorld() { DynamicWorld *pWorld = new DynamicWorld(); m_pWorld = pWorld; m_dynamicWorldFlag = true; if (!OnWorldCreated(pWorld)) { m_pWorld = nullptr; delete pWorld; return false; } return true; } <file_sep>/Engine/Source/Renderer/WorldRenderers/ForwardShadingWorldRenderer.h #pragma once #include "Renderer/WorldRenderers/CompositingWorldRenderer.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" #include "Renderer/RenderQueue.h" #include "Renderer/MiniGUIContext.h" class ForwardShadingWorldRenderer : public CompositingWorldRenderer { public: // aliased renderer types typedef CSMShadowMapRenderer DirectionalShadowMapRenderer; typedef CubeMapShadowMapRenderer PointShadowMapRenderer; typedef SSMShadowMapRenderer SpotShadowMapRenderer; // render target formats static const PIXEL_FORMAT SCENE_COLOR_PIXEL_FORMAT = PIXEL_FORMAT_R10G10B10A2_UNORM; static const PIXEL_FORMAT SCENE_DEPTH_PIXEL_FORMAT = PIXEL_FORMAT_D24_UNORM_S8_UINT; public: ForwardShadingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~ForwardShadingWorldRenderer(); virtual bool Initialize() override; virtual void DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) override; virtual void OnFrameComplete() override; private: // draw shadow maps from needed lights void DrawShadowMaps(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters); bool DrawDirectionalShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); bool DrawPointShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); bool DrawSpotShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight); // set shader program parameters for queue entry void SetCommonShaderProgramParameters(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram); // draw base pass for an object (emissive/lightmap/ambient light/main directional light) uint32 DrawBasePassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw forward light passes for an object uint32 DrawForwardLightPassesForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool useAdditiveBlending, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw a clear pass to set depth for an object void DrawEmptyPassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); // draw z prepass void DrawDepthPrepass(const ViewParameters *pViewParameters); // draw opaque objects void DrawOpaqueObjects(const ViewParameters *pViewParameters); // draw lit/unlit translucent objects void DrawTranslucentObjects(const ViewParameters *pViewParameters); // draw post process passes void DrawPostProcessObjects(const ViewParameters *pViewParameters); // scene colour/depth textures IntermediateBuffer *m_pSceneColorBuffer; IntermediateBuffer *m_pSceneDepthBuffer; // copy of scene colour/depth - used for rendering post materials IntermediateBuffer *m_pSceneColorBufferCopy; IntermediateBuffer *m_pSceneDepthBufferCopy; // shadow map renderers -- remove from heap DirectionalShadowMapRenderer *m_pDirectionalShadowMapRenderer; PointShadowMapRenderer *m_pPointShadowMapRenderer; SpotShadowMapRenderer *m_pSpotShadowMapRenderer; // shadow map cache MemArray<DirectionalShadowMapRenderer::ShadowMapData> m_directionalShadowMaps; MemArray<PointShadowMapRenderer::ShadowMapData> m_pointShadowMaps; MemArray<SpotShadowMapRenderer::ShadowMapData> m_spotShadowMaps; // last rendered light indices, used to avoid buffer updates when not needed uint32 m_lastDirectionalLightIndex; uint32 m_lastPointLightIndex; uint32 m_lastSpotLightIndex; uint32 m_lastVolumetricLightIndex; // shader flags uint32 m_directionalLightShaderFlags; uint32 m_pointLightShaderFlags; uint32 m_spotLightShaderFlags; }; <file_sep>/Engine/Source/Engine/ParticleSystemVertexFactory.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemVertexFactory.h" #include "Engine/Camera.h" #include "Engine/MaterialShader.h" #include "Renderer/ShaderCompilerFrontend.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(ParticleSystemSpriteVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(ParticleSystemSpriteVertexFactory) END_SHADER_COMPONENT_PARAMETERS() uint32 ParticleSystemSpriteVertexFactory::GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { if (flags & Flag_RenderBasic) { // position + texture coordinates + color for now return sizeof(float3) + sizeof(float2) + sizeof(uint32); } if (flags & Flag_RenderInstancedQuads) { // position/rotation + texture coordinate range in float4 + color return sizeof(float4) + sizeof(float4) + sizeof(float2) + sizeof(uint32); } // error Panic("Invalid flags"); return 0; } uint32 ParticleSystemSpriteVertexFactory::GetVerticesPerSprite(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { if (flags & Flag_RenderBasic) return 6; if (flags & Flag_RenderInstancedQuads) return 1; // error Panic("Invalid flags"); return 0; } DRAW_TOPOLOGY ParticleSystemSpriteVertexFactory::GetDrawTopology(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { if (flags & Flag_RenderBasic) return DRAW_TOPOLOGY_TRIANGLE_LIST; if (flags & Flag_RenderInstancedQuads) return DRAW_TOPOLOGY_TRIANGLE_STRIP; // error Panic("Invalid flags"); return DRAW_TOPOLOGY_COUNT; } static inline void AppendSpriteVertexBasic(byte *&pCurrentPointer, const float3 &position, const float2 &texcoord, uint32 color) { #pragma pack(push, 1) struct Vertex { float Position[3]; float TexCoord[2]; uint32 Color; }; #pragma pack(pop) Vertex *v = reinterpret_cast<Vertex *>(pCurrentPointer); position.Store(v->Position); texcoord.Store(v->TexCoord); v->Color = color; pCurrentPointer += sizeof(Vertex); } static inline void AppendSpriteVertexInstancedQuads(byte *&pCurrentPointer, const float3 &position, float rotation, const float2 &minTextureCoordinates, const float2 &textureCoordinateRange, float halfWidth, float halfHeight, uint32 color) { #pragma pack(push, 1) struct Vertex { float Position[4]; float TexCoordRange[4]; float HalfSize[2]; uint32 Color; }; #pragma pack(pop) Vertex *v = reinterpret_cast<Vertex *>(pCurrentPointer); position.Store(&v->Position[0]); v->Position[3] = rotation; minTextureCoordinates.Store(&v->TexCoordRange[0]); textureCoordinateRange.Store(&v->TexCoordRange[2]); v->HalfSize[0] = halfWidth; v->HalfSize[1] = halfHeight; v->Color = color; pCurrentPointer += sizeof(Vertex); } bool ParticleSystemSpriteVertexFactory::FillVertexBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Camera *pCamera, const ParticleData *pParticles, uint32 nParticles, void *pBuffer, uint32 bufferSize) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); if (bufferSize < (vertexSize * nParticles * GetVerticesPerSprite(platform, featureLevel, flags))) return false; // basic type if (flags & Flag_RenderBasic) { // calculate inverse rotation matrix float3x3 inverseViewMatrixRotation(pCamera->GetInverseViewMatrix()); // loop each sprite byte *pCurrentPointer = reinterpret_cast<byte *>(pBuffer); for (uint32 spriteIndex = 0; spriteIndex < nParticles; spriteIndex++) { const ParticleData *pParticleData = &pParticles[spriteIndex]; // find half width/height float halfWidth = pParticleData->Width * 0.5f; float halfHeight = pParticleData->Height * 0.5f; // find the four vertex positions // these coordinates have to be in y-up coordinate system, as we are working with the view matrix float3 vertexPositions[4]; if (pParticleData->Rotation != 0.0f) { float theta = Math::DegreesToRadians(pParticleData->Rotation); float sinTheta, cosTheta; Math::SinCos(theta, &sinTheta, &cosTheta); vertexPositions[0] = inverseViewMatrixRotation * float3(-halfWidth * cosTheta + -halfHeight * sinTheta, -halfWidth * sinTheta + halfHeight * cosTheta, 0.0f) + pParticleData->Position; vertexPositions[1] = inverseViewMatrixRotation * float3(-halfWidth * cosTheta + halfHeight * sinTheta, -halfWidth * sinTheta + -halfHeight * cosTheta, 0.0f) + pParticleData->Position; vertexPositions[2] = inverseViewMatrixRotation * float3(halfWidth * cosTheta + -halfHeight * sinTheta, halfWidth * sinTheta + halfHeight * cosTheta, 0.0f) + pParticleData->Position; vertexPositions[3] = inverseViewMatrixRotation * float3(halfWidth * cosTheta + halfHeight * sinTheta, halfWidth * sinTheta + -halfHeight * cosTheta, 0.0f) + pParticleData->Position; } else { vertexPositions[0] = inverseViewMatrixRotation * float3(-halfWidth, halfHeight, 0.0f) + pParticleData->Position; vertexPositions[1] = inverseViewMatrixRotation * float3(-halfWidth, -halfHeight, 0.0f) + pParticleData->Position; vertexPositions[2] = inverseViewMatrixRotation * float3(halfWidth, halfHeight, 0.0f) + pParticleData->Position; vertexPositions[3] = inverseViewMatrixRotation * float3(halfWidth, -halfHeight, 0.0f) + pParticleData->Position; } // same for texture coordinates float2 vertexTextureCoordinates[4]; vertexTextureCoordinates[0].Set(pParticleData->MinTextureCoordinates); vertexTextureCoordinates[1].Set(pParticleData->MinTextureCoordinates.x, pParticleData->MaxTextureCoordinates.y); vertexTextureCoordinates[2].Set(pParticleData->MaxTextureCoordinates.x, pParticleData->MinTextureCoordinates.y); vertexTextureCoordinates[3].Set(pParticleData->MaxTextureCoordinates.x, pParticleData->MaxTextureCoordinates.y); // first triangle AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[0], vertexTextureCoordinates[0], pParticleData->Color); AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[1], vertexTextureCoordinates[1], pParticleData->Color); AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[2], vertexTextureCoordinates[2], pParticleData->Color); // second triangle AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[2], vertexTextureCoordinates[2], pParticleData->Color); AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[1], vertexTextureCoordinates[1], pParticleData->Color); AppendSpriteVertexBasic(pCurrentPointer, vertexPositions[3], vertexTextureCoordinates[3], pParticleData->Color); } return true; } else if (flags & Flag_RenderInstancedQuads) { // loop each sprite byte *pCurrentPointer = reinterpret_cast<byte *>(pBuffer); for (uint32 spriteIndex = 0; spriteIndex < nParticles; spriteIndex++) { const ParticleData *pParticleData = &pParticles[spriteIndex]; // find half width/height //float halfWidth = pParticleData->Width * 0.5f; //float halfHeight = pParticleData->Height * 0.5f; // find texture coordinate range float2 textureCoordinateRange(pParticleData->MaxTextureCoordinates - pParticleData->MinTextureCoordinates); // generate vertex AppendSpriteVertexInstancedQuads(pCurrentPointer, pParticleData->Position, Math::DegreesToRadians(pParticleData->Rotation), pParticleData->MinTextureCoordinates, textureCoordinateRange, pParticleData->Width, pParticleData->Height, pParticleData->Color); } // done return true; } return false; } bool ParticleSystemSpriteVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { // needs a material to go with it if (pMaterialShader == nullptr) return false; // can't handle normal mapped materials - eek if (pMaterialShader->GetLightingNormalSpace() == MATERIAL_LIGHTING_NORMAL_SPACE_TANGENT_SPACE) return false; // only support emissive materials if (pMaterialShader->GetLightingType() != MATERIAL_LIGHTING_TYPE_EMISSIVE) return false; return true; } bool ParticleSystemSpriteVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/ParticleSystemSpriteVertexFactory.hlsl"); if (vertexFactoryFlags & Flag_RenderBasic) pParameters->AddPreprocessorMacro("PARTICLE_SYSTEM_SPRITE_VERTEX_FACTORY_RENDER_BASIC", "1"); if (vertexFactoryFlags & Flag_RenderInstancedQuads) pParameters->AddPreprocessorMacro("PARTICLE_SYSTEM_SPRITE_VERTEX_FACTORY_RENDER_INSTANCED_QUADS", "1"); if (vertexFactoryFlags & Flag_UseWorldTransform) pParameters->AddPreprocessorMacro("PARTICLE_SYSTEM_SPRITE_VERTEX_FACTORY_USE_WORLD_TRANSFORM", "1"); return true; } uint32 ParticleSystemSpriteVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { GPU_VERTEX_ELEMENT_DESC *pElementDesc = &pElementsDesc[0]; uint32 nElements = 0; uint32 streamOffset = 0; if (flags & Flag_RenderBasic) { // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // texcoord pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; // color pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } else if (flags & Flag_RenderInstancedQuads) { // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float4); pElementDesc++; nElements++; // texcoord range pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float4); pElementDesc++; nElements++; // half size pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 1; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float2); pElementDesc++; nElements++; // color pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = 0; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } return nElements; } <file_sep>/Engine/Source/Renderer/WorldRenderers/DeferredShadingWorldRenderer.h #pragma once #include "Renderer/WorldRenderers/CompositingWorldRenderer.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" #include "Renderer/RenderQueue.h" #include "Renderer/MiniGUIContext.h" #include "Renderer/Shaders/DeferredShadingShaders.h" class DeferredShadingWorldRenderer : public CompositingWorldRenderer { public: // aliased renderer types typedef CSMShadowMapRenderer DirectionalShadowMapRenderer; typedef CubeMapShadowMapRenderer PointShadowMapRenderer; typedef SSMShadowMapRenderer SpotShadowMapRenderer; // buffer formats const PIXEL_FORMAT DEPTHBUFFER_FORMAT = PIXEL_FORMAT_D24_UNORM_S8_UINT; // Depth //const PIXEL_FORMAT DEPTHBUFFER_FORMAT = PIXEL_FORMAT_D32_FLOAT; // Depth //const PIXEL_FORMAT GBUFFER0_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // Diffuse RGB, (Spec Factor, Spec Power / Metallic, Specular) //const PIXEL_FORMAT GBUFFER1_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // XY Normal, Normal Sign + Roughness, (Shadow Mask, Shading Model) //const PIXEL_FORMAT GBUFFER2_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // const PIXEL_FORMAT GBUFFER0_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // Diffuse RGB, Shadow Mask const PIXEL_FORMAT GBUFFER1_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // XYZ Normal, Roughness const PIXEL_FORMAT GBUFFER2_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; // Spec Factor / Metallic, Spec Power / Specular, Shading Model, TwoSided const PIXEL_FORMAT AOBUFFER_FORMAT = PIXEL_FORMAT_R8_UNORM; // AO buffer const PIXEL_FORMAT LIGHTBUFFER_FORMAT = PIXEL_FORMAT_R11G11B10_FLOAT; // Light accumulation buffer const PIXEL_FORMAT AUXBUFFER_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; const PIXEL_FORMAT LUMINANCEBUFFER_FORMAT = PIXEL_FORMAT_R32_FLOAT; public: DeferredShadingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~DeferredShadingWorldRenderer(); virtual bool Initialize() override; virtual void DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) override; virtual void GetRenderStats(RenderStats *pRenderStats) const override; virtual void OnFrameComplete() override; private: // draw shadow maps from needed lights void DrawShadowMaps(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters); bool DrawDirectionalShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); bool DrawPointShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight); bool DrawSpotShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight); // set shader program parameters for queue entry void SetCommonShaderProgramParameters(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram); // draw base pass for an object (emissive/lightmap/ambient light/main directional light) uint32 DrawBasePassForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw forward light passes for an object uint32 DrawForwardLightPassesForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool useAdditiveBlending, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw a clear pass to set depth for an object void DrawEmptyPassForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); // draw z prepass (Overwrites render targets) void DrawDepthPrepass(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // draw emissive objects (Overwrites render targets) void DrawUnlitObjects(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // draw opaque objects (Overwrites render targets) void DrawGBuffers(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // draw lights (Overwrites render targets) void DrawLights(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); void DrawLights_DirectionalLights(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); void DrawLights_PointLights_ByLightVolumes(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); void DrawLights_PointLights_Tiled(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // build ambient occlusion terms (Overwrites render targets) void ApplyAmbientOcclusion(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // apply fog post-process void ApplyFog(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // draw post process passes (Overwrites render targets) void DrawPostProcessAndTranslucentObjects(GPUCommandList *pCommandList, const ViewParameters *pViewParameters); // draw any object debug info void DrawDebugInfo(const Camera *pCamera); // shadow map renderers DirectionalShadowMapRenderer *m_pDirectionalShadowMapRenderer; PointShadowMapRenderer *m_pPointShadowMapRenderer; SpotShadowMapRenderer *m_pSpotShadowMapRenderer; // shadow map cache MemArray<DirectionalShadowMapRenderer::ShadowMapData *> m_directionalShadowMaps; MemArray<PointShadowMapRenderer::ShadowMapData *> m_pointShadowMaps; MemArray<SpotShadowMapRenderer::ShadowMapData *> m_spotShadowMaps; // last rendered light indices, used to avoid buffer updates when not needed uint32 m_lastDirectionalLightIndex; uint32 m_lastPointLightIndex; uint32 m_lastSpotLightIndex; uint32 m_lastVolumetricLightIndex; // shader flags uint32 m_directionalLightShaderFlags; uint32 m_pointLightShaderFlags; uint32 m_spotLightShaderFlags; // buffers IntermediateBuffer *m_pSceneColorBuffer; IntermediateBuffer *m_pSceneColorBufferCopy; IntermediateBuffer *m_pSceneDepthBuffer; IntermediateBuffer *m_pSceneDepthBufferCopy; IntermediateBuffer *m_pGBuffer0; IntermediateBuffer *m_pGBuffer1; IntermediateBuffer *m_pGBuffer2; // light volume vertex buffers GPUBuffer *m_pPointLightVolumeVertexBuffer; GPUBuffer *m_pSpotLightVolumeVertexBuffer; uint32 m_pointLightVolumeVertexCount; // tiled point light info MemArray<DeferredTiledPointLightShader::Light> m_tiledPointLights; // programs ShaderProgram *m_pSSAOProgram; ShaderProgram *m_pSSAOApplyProgram; }; <file_sep>/Engine/Dependancies/imgui/examples/allegro5_example/imgui_impl_a5.h // ImGui Allegro 5 bindings // https://github.com/ocornut/imgui // by @birthggd #pragma once struct ALLEGRO_DISPLAY; union ALLEGRO_EVENT; bool ImGui_ImplA5_Init(ALLEGRO_DISPLAY* display); void ImGui_ImplA5_Shutdown(); void ImGui_ImplA5_NewFrame(); bool ImGui_ImplA5_ProcessEvent(ALLEGRO_EVENT* event); // Use if you want to reset your rendering device without losing ImGui state. bool Imgui_ImplA5_CreateDeviceObjects(); void ImGui_ImplA5_InvalidateDeviceObjects(); <file_sep>/Engine/Source/ContentConverter/AssimpCommon.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpCommon.h" #include "Core/PixelFormat.h" // Include the .lib #if Y_PLATFORM_WINDOWS #if Y_BUILD_CONFIG_DEBUG #pragma comment(lib, "assimp-vc130-mtd.lib") #else #pragma comment(lib, "assimp-vc130-mt.lib") #endif #endif // Y_PLATFORM_WINDOWS float4x4 AssimpHelpers::AssimpMatrix4x4ToFloat4x4(const aiMatrix4x4 &mat) { float4x4 out(mat.a1, mat.a2, mat.a3, mat.a4, mat.b1, mat.b2, mat.b3, mat.b4, mat.c1, mat.c2, mat.c3, mat.c4, mat.d1, mat.d2, mat.d3, mat.d4); return out; } Quaternion AssimpHelpers::AssimpQuaternionToQuaternion(const aiQuaternion &quat) { Quaternion out(quat.x, quat.y, quat.z, quat.w); return out; } float2 AssimpHelpers::AssimpVector2ToFloat2(const aiVector2D &vec) { return float2(vec.x, vec.y); } float3 AssimpHelpers::AssimpVector3ToFloat3(const aiVector3D &vec) { return float3(vec.x, vec.y, vec.z); } uint32 AssimpHelpers::AssimpColor3ToColor(const aiColor3D &vec) { uint32 r = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.r * 255.0f)), 0, 255); uint32 g = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.g * 255.0f)), 0, 255); uint32 b = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.b * 255.0f)), 0, 255); return MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, 255); } uint32 AssimpHelpers::AssimpColor4ToColor(const aiColor4D &vec) { uint32 r = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.r * 255.0f)), 0, 255); uint32 g = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.g * 255.0f)), 0, 255); uint32 b = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.b * 255.0f)), 0, 255); uint32 a = (uint32)Math::Clamp(Math::Truncate(Math::Round(vec.a * 255.0f)), 0, 255); return MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a); } aiMatrix4x4 AssimpHelpers::Float4x4ToAssimpMatrix4x4(const float4x4 &mat) { aiMatrix4x4 out(mat.m00, mat.m01, mat.m02, mat.m03, mat.m10, mat.m11, mat.m12, mat.m13, mat.m20, mat.m21, mat.m22, mat.m23, mat.m30, mat.m31, mat.m32, mat.m33); return out; } static bool s_assimpInitialized = false; static void DeinitializeAssimp() { if (!s_assimpInitialized) return; Assimp::DefaultLogger::kill(); s_assimpInitialized = false; } bool AssimpHelpers::InitializeAssimp() { if (s_assimpInitialized) return true; Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, 0, NULL); s_assimpInitialized = true; atexit(DeinitializeAssimp); return true; } int AssimpHelpers::GetAssimpStaticMeshImportPostProcessingFlags() { // determine postprocess flags int postProcessingFlags = 0; // we want tangent vectors postProcessingFlags |= aiProcess_GenSmoothNormals; postProcessingFlags |= aiProcess_CalcTangentSpace; // join identical vertices postProcessingFlags |= aiProcess_JoinIdenticalVertices; // force triangles postProcessingFlags |= aiProcess_Triangulate; // improve cache locality postProcessingFlags |= aiProcess_ImproveCacheLocality; // remove unused materials postProcessingFlags |= aiProcess_RemoveRedundantMaterials; // improve overall scene postProcessingFlags |= aiProcess_OptimizeMeshes; postProcessingFlags |= aiProcess_OptimizeGraph; // use d3d convention for texcoords postProcessingFlags |= aiProcess_FlipUVs; // sort by prim type postProcessingFlags |= aiProcess_SortByPType; return postProcessingFlags; } int AssimpHelpers::GetAssimpSkeletonImportPostProcessingFlags() { // determine postprocess flags int postProcessingFlags = 0; // improve overall scene postProcessingFlags |= aiProcess_OptimizeMeshes; postProcessingFlags |= aiProcess_OptimizeGraph; // minimum of 4 weights postProcessingFlags |= aiProcess_LimitBoneWeights; return postProcessingFlags; } int AssimpHelpers::GetAssimpSkeletalAnimationImportPostProcessingFlags() { // determine postprocess flags int postProcessingFlags = 0; // improve overall scene postProcessingFlags |= aiProcess_OptimizeMeshes; postProcessingFlags |= aiProcess_OptimizeGraph; // minimum of 4 weights postProcessingFlags |= aiProcess_LimitBoneWeights; return postProcessingFlags; } int AssimpHelpers::GetAssimpSkeletalMeshImportPostProcessingFlags() { // determine postprocess flags int postProcessingFlags = 0; // we want tangent vectors postProcessingFlags |= aiProcess_GenSmoothNormals; postProcessingFlags |= aiProcess_CalcTangentSpace; // join identical vertices postProcessingFlags |= aiProcess_JoinIdenticalVertices; // force triangles postProcessingFlags |= aiProcess_Triangulate; // improve cache locality postProcessingFlags |= aiProcess_ImproveCacheLocality; // remove unused materials postProcessingFlags |= aiProcess_RemoveRedundantMaterials; // improve overall scene postProcessingFlags |= aiProcess_OptimizeMeshes; postProcessingFlags |= aiProcess_OptimizeGraph; // use d3d convention for texcoords postProcessingFlags |= aiProcess_FlipUVs; // minimum of 4 weights postProcessingFlags |= aiProcess_LimitBoneWeights; return postProcessingFlags; } float4x4 AssimpHelpers::GetAssimpToWorldCoordinateSystemFloat4x4() { return float4x4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } aiMatrix4x4 AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4() { return aiMatrix4x4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } AssimpHelpers::ProgressCallbacksLogStream::ProgressCallbacksLogStream(ProgressCallbacks *pProgressCallbacks) : m_pProgressCallbacks(pProgressCallbacks) { Assimp::DefaultLogger::get()->attachStream(this, Assimp::Logger::Debugging | Assimp::Logger::Info | Assimp::Logger::Warn | Assimp::Logger::Err); } AssimpHelpers::ProgressCallbacksLogStream::~ProgressCallbacksLogStream() { Assimp::DefaultLogger::get()->detatchStream(this, Assimp::Logger::Debugging | Assimp::Logger::Info | Assimp::Logger::Warn | Assimp::Logger::Err); } /* bool AssimpHelpers::ProgressCallbacksLogStream::attachStream(Assimp::LogStream *pStream, unsigned int severity) { return false; } bool AssimpHelpers::ProgressCallbacksLogStream::detatchStream(Assimp::LogStream *pStream, unsigned int severity) { return false; } void AssimpHelpers::ProgressCallbacksLogStream::OnDebug(const char* message) { m_pProgressCallbacks->DisplayFormattedDebugMessage("[Assimp] %s", message); } void AssimpHelpers::ProgressCallbacksLogStream::OnInfo(const char* message) { m_pProgressCallbacks->DisplayFormattedInformation("[Assimp] %s", message); } void AssimpHelpers::ProgressCallbacksLogStream::OnWarn(const char* essage) { m_pProgressCallbacks->DisplayFormattedWarning("[Assimp] %s", essage); } void AssimpHelpers::ProgressCallbacksLogStream::OnError(const char* message) { m_pProgressCallbacks->DisplayFormattedError("[Assimp] %s", message); } */ void AssimpHelpers::ProgressCallbacksLogStream::write(const char* message) { SmallString echoMessage; echoMessage.Format("[Assimp] %s", message); echoMessage.RStrip(); m_pProgressCallbacks->DisplayDebugMessage(echoMessage); } <file_sep>/Engine/Source/ResourceCompiler/BlockMeshGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/BlockMesh.h" #include "Engine/BlockMeshVolume.h" #include "Engine/Physics/CollisionShape.h" class BlockPalette; class XMLReader; class XMLWriter; class BlockMeshGenerator { DeclareNonCopyable(BlockMeshGenerator); public: BlockMeshGenerator(); ~BlockMeshGenerator(); const bool IsChanged() const { return m_changed; } const BlockPalette *GetBlockList() const { return m_pPalette; } const float GetScale() const { return m_scale; } const bool GetUseAmbientOcclusion() const { return m_useAmbientOcclusion; } const uint32 GetLODCount() const { return m_nLODLevels; } void SetScale(float scale); void SetUseAmbientOcclusion(bool enabled) { m_useAmbientOcclusion = enabled; } void SetCollisionShapeType(Physics::COLLISION_SHAPE_TYPE type) { m_collisionShapeType = type; } const BlockMeshVolume &GetMeshVolume(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD]; } const int3 &GetMeshMinCoordinates(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetMinCoordinates(); } const int3 &GetMeshMaxCoordinates(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetMaxCoordinates(); } const uint32 GetMeshWidth(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetWidth(); } const uint32 GetMeshLength(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetLength(); } const uint32 GetMeshHeight(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetHeight(); } const uint8 *GetMeshData(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].GetData(); } // calculate the bounding box for an lod AABox CalculateBoundingBox(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].CalculateBoundingBox(); } AABox CalculateActiveBoundingBox(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].CalculateActiveBoundingBox(); } bool Create(const BlockPalette *pPalette, float scale = 1.0f, Physics::COLLISION_SHAPE_TYPE collisionShapeType = Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH); bool Compile(ByteStream *pOutputStream) const; bool LoadFromXML(const char *FileName, ByteStream *pStream); bool SaveToXML(ByteStream *pStream); // clear (set all blocks to default) void Clear(); void Clear(uint32 LOD); // resize void Resize(uint32 LOD, const int3 &newMinCoordinates, const int3 &newMaxCoordinates); // centers the mesh void Center(); void Center(uint32 LOD); // shrinks the mesh to the minimum size possible void Shrink(); void Shrink(uint32 LOD); // move blocks void MoveBlock(uint32 LOD, const int3 &blockCoordinates, const int3 &moveDelta); void MoveBlocks(uint32 LOD, const int3 &selectionMin, const int3 &selectionMax, const int3 &moveDelta); // block management inline uint8 GetBlock(uint32 LOD, int32 x, int32 y, int32 z) const { return GetBlock(LOD, int3(x, y, z)); } inline void SetBlock(uint32 LOD, int32 x, int32 y, int32 z, BlockVolumeBlockType v) { SetBlock(LOD, int3(x, y, z), v); } uint8 GetBlock(uint32 LOD, const int3 &coords) const; void SetBlock(uint32 LOD, const int3 &coords, BlockVolumeBlockType v); // block list management void SetPalette(const BlockPalette *pPalette); private: bool GetActiveCoordinatesRange(uint32 LOD, int3 *pMinActiveCoordinates, int3 *pMaxActiveCoordinates); bool m_changed; const BlockPalette *m_pPalette; float m_scale; bool m_useAmbientOcclusion; Physics::COLLISION_SHAPE_TYPE m_collisionShapeType; BlockMeshVolume *m_pLODLevels; uint32 m_nLODLevels; }; <file_sep>/Editor/Source/Editor/EditorSettings.h #pragma once #include "Editor/Common.h" class EditorSettings { public: EditorSettings(); ~EditorSettings(); // getters const String &GetBuilderBrushWireframeMaterialName() const { return m_strBuilderBrushWireframeMaterialName; } const String &GetBrushWireframeMaterialName() const { return m_strBrushWireframeMaterialName; } const String &GetVolumeWireframeMaterialName() const { return m_strVolumeWireframeMaterialName; } const String &GetAxisMeshName() const { return m_strAxisMeshName; } EDITOR_VIEWPORT_LAYOUT GetViewportLayout() const { return m_eViewportLayout; } // setters void SetViewportLayout(EDITOR_VIEWPORT_LAYOUT ViewportLayout) { m_eViewportLayout = ViewportLayout; } private: String m_strBuilderBrushWireframeMaterialName; String m_strBrushWireframeMaterialName; String m_strVolumeWireframeMaterialName; String m_strAxisMeshName; EDITOR_VIEWPORT_LAYOUT m_eViewportLayout; }; extern EditorSettings *g_pEditorSettings; <file_sep>/Editor/Source/Editor/EditorResourceSelectionDialogModel.h #pragma once #include "Editor/Common.h" class EditorResourceSelectionDialogModel : public QAbstractItemModel { Q_OBJECT public: class DirectoryNode { public: DirectoryNode(EditorResourceSelectionDialogModel *pModel, const String &rootPath); DirectoryNode(EditorResourceSelectionDialogModel *pModel, DirectoryNode *pParent); ~DirectoryNode(); DirectoryNode *GetParent() { return m_pParent; } const DirectoryNode *GetParent() const { return m_pParent; } const String &GetDisplayName() const { return m_displayName; } const String &GetFullName() const { return m_fullName; } const ResourceTypeInfo *GetResourceTypeInfo() const { return m_pResourceType; } const bool IsDirectory() const { return (m_pResourceType == NULL); } const Timestamp &GetModifiedTime() const { return m_modifiedTime; } const PODArray<DirectoryNode *> &GetChildren() const { return m_children; } const bool IsPopulated() const { return m_populated; } void Populate(); private: EditorResourceSelectionDialogModel *m_pModel; DirectoryNode *m_pParent; String m_displayName; String m_fullName; const ResourceTypeInfo *m_pResourceType; Timestamp m_modifiedTime; PODArray<DirectoryNode *> m_children; bool m_populated; }; public: EditorResourceSelectionDialogModel(const String &rootPath, bool includeDirectories = true, bool includeResources = true, uint32 previewIconSize = 0, QWidget *pParent = NULL); ~EditorResourceSelectionDialogModel(); // root path const String &GetRootPath() const { return m_rootPath; } const bool GetIncludeDirectories() const { return m_includeDirectories; } const bool GetIncludeResources() const { return m_includeResources; } // resource filters void SetResourceFilter(const ResourceTypeInfo **pResourceTypeInfo, uint32 nResourceTypeInfos); bool ShouldIncludeResourceType(const ResourceTypeInfo *pResourceTypeInfo); // get the directory node for a model index const DirectoryNode *GetDirectoryNodeForIndex(const QModelIndex &index) const; // implemented functions virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; virtual QModelIndex parent(const QModelIndex &child) const; virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; private: DirectoryNode *InternalGetDirectoryNode(const QModelIndex &index) const; String m_rootPath; bool m_includeDirectories; bool m_includeResources; uint32 m_previewIconSize; const ResourceTypeInfo **m_ppResourceTypeInfoFilter; uint32 m_nResourceTypeInfoFilters; DirectoryNode *m_pRootNode; }; <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) # handle clang if("${CMAKE_CXX_COMPILER}" MATCHES "clang(\\+\\+)?$" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR APPLE) set(CMAKE_COMPILER_IS_CLANGXX 1) endif() # pull in modules set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMakeModules/") # set the install directory to the build directory #SET(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}" CACHE STRING "Foo" INTERNAL "") # set project project(GameEngineDev CXX C) # compile os-dependant dependancies, this can't be done with a CMakeLists in dependancies # due to how the variables are exported back to us through set(... PARENT_SCOPE) if(ANDROID) add_subdirectory(Dependancies/Android) endif() # determine 32bit vs 64bit build if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(BITNESS 64) else() set(BITNESS 32) endif() # we don't want SDLmain by default if(NOT ANDROID) SET(SDL2_BUILDING_LIBRARY TRUE) endif() # find system dependancies if(EMSCRIPTEN) # emscripten libraries SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s USE_SDL=2 -s USE_ZLIB=1") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s USE_SDL=2 -s USE_ZLIB=1") elseif(ANDROID) # android libraries else() find_package(ZLIB REQUIRED) find_package(Threads REQUIRED) find_package(LibXml2 REQUIRED) find_package(PCRE REQUIRED) find_package(ZLIB REQUIRED) find_package(OpenGL REQUIRED) find_package(SDL2 REQUIRED) find_package(Freetype REQUIRED) endif() # platform-specific stuff if(APPLE) include_directories("${CMAKE_SOURCE_DIR}/Dependancies/OSX/include") link_directories("${CMAKE_SOURCE_DIR}/Dependancies/OSX/lib") set(QT5_BASE_DIR "${CMAKE_SOURCE_DIR}/Dependancies/OSX/qt") # include frameworks find_library(CARBON_LIBRARY Carbon) find_library(APPKIT_LIBRARY AppKit) elseif(UNIX AND NOT ANDROID) include_directories("${CMAKE_SOURCE_DIR}/Dependancies/Linux/include") if(BITNESS EQUAL 64) link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Linux/lib64") # set(QT5_BASE_DIR "${CMAKE_SOURCE_DIR}/Dependancies/Linux/qt64") else() link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Linux/lib32") # set(QT5_BASE_DIR "${CMAKE_SOURCE_DIR}/Dependancies/Linux/qt32") endif() # needs X11 find_package(X11) elseif(WIN32) include_directories("${CMAKE_SOURCE_DIR}/Dependancies/Windows/include") if(BITNESS EQUAL 64) if(CMAKE_BUILD_TYPE EQUAL "Debug") link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Windows/lib64-debug") else() link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Windows/lib64") endif() set(QT5_BASE_DIR "${CMAKE_SOURCE_DIR}/Dependancies/Windows/qt64") else() if(CMAKE_BUILD_TYPE EQUAL "Debug") link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Windows/lib32-debug") else() link_directories("${CMAKE_SOURCE_DIR}/Dependancies/Windows/lib32") endif() set(QT5_BASE_DIR "${CMAKE_SOURCE_DIR}/Dependancies/Windows/qt32") endif() endif() # set up install directory if(BITNESS EQUAL 64) if(CMAKE_BUILD_TYPE EQUAL "Debug") set(INSTALL_BINARIES_DIRECTORY "bin64-debug") else() set(INSTALL_BINARIES_DIRECTORY "bin64") endif() else() if(CMAKE_BUILD_TYPE EQUAL "Debug") set(INSTALL_BINARIES_DIRECTORY "bin32-debug") else() set(INSTALL_BINARIES_DIRECTORY "bin32") endif() endif() # use bundled qt if(DEFINED QT5_BASE_DIR) set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${QT5_BASE_DIR}/lib/cmake") set(Qt5Core_DIR "${QT5_BASE_DIR}/lib/cmake/Qt5Core") set(Qt5Gui_DIR "${QT5_BASE_DIR}/lib/cmake/Qt5Gui") set(Qt5Widgets_DIR "${QT5_BASE_DIR}/lib/cmake/Qt5Widgets") endif() # pull in qt dependancies if(NOT EMSCRIPTEN AND NOT ANDROID) find_package(Qt5Core REQUIRED) find_package(Qt5Gui COMPONENTS Private REQUIRED) find_package(Qt5Widgets REQUIRED) endif() # enable c99/ c++11 if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANGXX OR EMSCRIPTEN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") endif() # set cflags that are common to dependancies add_definitions(-D_FILE_OFFSET_BITS=64) add_definitions(-D_GNU_SOURCE) # update cflags for debug build if(CMAKE_BUILD_TYPE MATCHES "Debug") add_definitions(-D_DEBUG) message("Building debug executable.") endif() # build options if(EMSCRIPTEN OR ANDROID) unset(HAVE_LIBXML2) unset(HAVE_SQUISH) set(HAVE_ZLIB "1") set(HAVE_SFMT "1") unset(HAVE_FREEIMAGE) unset(HAVE_HLSLTRANSLATOR) set(WITH_PROFILER "1" CACHE STRING "Foo") set(WITH_IMGUI "1" CACHE STRING "Foo") unset(WITH_RENDERER_D3D11) unset(WITH_RENDERER_OPENGL) set(WITH_RENDERER_OPENGLES2 "1" CACHE STRING "Foo") unset(WITH_RESOURCECOMPILER) unset(WITH_RESOURCECOMPILER_EMBEDDED) unset(WITH_RESOURCECOMPILER_SUBPROCESS) unset(WITH_RESOURCECOMPILER_STANDALONE) unset(WITH_MAPCOMPILER) unset(WITH_MAPCOMPILER_STANDALONE) unset(WITH_CONTENTCONVERTER) unset(WITH_CONTENTCONVERTER_STANDALONE) set(WITH_BASEGAME "1" CACHE STRING "Foo") unset(WITH_EDITOR) unset(WITH_BLOCKENGINE) else() set(HAVE_LIBXML2 "1") set(HAVE_SQUISH "1") set(HAVE_ZLIB "1") set(HAVE_SFMT "1") set(HAVE_FREEIMAGE "1") set(HAVE_HLSLTRANSLATOR "1") set(WITH_PROFILER "1" CACHE STRING "Foo") set(WITH_IMGUI "1" CACHE STRING "Foo") set(WITH_RENDERER_D3D11 "0" CACHE STRING "Foo") set(WITH_RENDERER_OPENGL "1" CACHE STRING "Foo") set(WITH_RENDERER_OPENGLES2 "1" CACHE STRING "Foo") set(WITH_RESOURCECOMPILER "1" CACHE STRING "Foo") set(WITH_RESOURCECOMPILER_EMBEDDED "0" CACHE STRING "Foo") set(WITH_RESOURCECOMPILER_SUBPROCESS "1" CACHE STRING "Foo") set(WITH_RESOURCECOMPILER_STANDALONE "1" CACHE STRING "Foo") set(WITH_MAPCOMPILER "1" CACHE STRING "Foo") set(WITH_MAPCOMPILER_STANDALONE "1" CACHE STRING "Foo") set(WITH_CONTENTCONVERTER "1" CACHE STRING "Foo") set(WITH_CONTENTCONVERTER_STANDALONE "1" CACHE STRING "Foo") set(WITH_BASEGAME "1" CACHE STRING "Foo") set(WITH_EDITOR "1" CACHE STRING "Foo") set(WITH_BLOCKENGINE "1" CACHE STRING "Foo") endif() # kill annoying clang warnings if(CMAKE_COMPILER_IS_CLANGXX) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Qunused-arguments") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments") endif() # same for clang/emscripten if(EMSCRIPTEN) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-warn-absolute-paths") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-warn-absolute-paths") endif() # compile dependancies without cflags set add_subdirectory(Engine/Dependancies) # set up common variables set(ENGINE_BASE_DIRECTORY "${CMAKE_SOURCE_DIR}/Engine/Source") # set up cflags if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANGXX OR EMSCRIPTEN) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic") # kill annoying warnings set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-offsetof") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-switch") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-switch-enum") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable") endif() # pull in include directories include_directories("${CMAKE_BINARY_DIR}") # generate config.h CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/config.h.in ${CMAKE_BINARY_DIR}/config.h) add_definitions(-DHAVE_CONFIG_H) # engine add_subdirectory(Engine) # editor add_subdirectory(Editor) # demogame add_subdirectory(DemoGame) # TestGame add_subdirectory(TestGame) # BlockGame if(NOT EMSCRIPTEN AND NOT ANDROID) add_subdirectory(BlockGame) endif() <file_sep>/Editor/Source/Editor/EditorResourceSelectionDialog.h #pragma once #include "Editor/Common.h" #include "Editor/EditorResourceSelectionDialogModel.h" class EditorResourcePreviewWidget; class EditorResourceSelectionDialog : public QDialog { Q_OBJECT public: EditorResourceSelectionDialog(QWidget *pParent); ~EditorResourceSelectionDialog(); const ResourceTypeInfo *GetReturnValueResourceType() const { return m_pReturnValueResourceType; } const String &GetReturnValueResourceName() const { return m_returnValueResourceName; } void AddResourceFilter(const ResourceTypeInfo *pResourceTypeInfo); bool NavigateToDirectory(const char *directory, bool addToHistory = true); private Q_SLOTS: void OnDirectoryComboBoxActivated(const QString &text); void OnBackButtonPressed(); void OnUpDirectoryButtonPressed(); void OnMakeDirectoryButtonPressed(); void OnTreeViewItemActivated(const QModelIndex &index); void OnTreeViewItemClicked(const QModelIndex &index); void OnSelectButtonClicked(); void OnCancelButtonClicked(); private: void CreateUI(); PODArray<const ResourceTypeInfo *> m_resourceFilters; EditorResourceSelectionDialogModel *m_pModel; QStack<QString> m_history; const ResourceTypeInfo *m_pReturnValueResourceType; String m_returnValueResourceName; QComboBox *m_pDirectoryComboBox; QToolButton *m_pBackButton; QToolButton *m_pUpDirectoryButton; QTreeView *m_pTreeView; QLabel *m_pFilterTextLabel; QPushButton *m_pSelectButton; EditorResourcePreviewWidget *m_pPreviewWidget; };<file_sep>/cmake_emscripten.sh #!/bin/sh cmake -DCMAKE_TOOLCHAIN_FILE=./CMakeModules/Emscripten.cmake -DCMAKE_BUILD_TYPE=Debug -G "Unix Makefiles" . <file_sep>/Engine/Source/Renderer/ImGuiBridge.h #pragma once #include "Renderer/Common.h" #include "imgui.h" union SDL_Event; // NOTE: All ImGui functions must be called on the render thread. namespace ImGui { // Ready engine and imgui for drawing bool InitializeBridge(); // Alter the viewport dimensions void SetViewportDimensions(uint32 width, uint32 height); // On new frame, pass delta-time void NewFrame(float deltaTime); // Process a SDL event bool HandleSDLEvent(const SDL_Event *pEvent, bool forceCapture = false); // Release everything void FreeResources(); } <file_sep>/Engine/Source/Core/ChunkFileReader.cpp #include "Core/PrecompiledHeader.h" #include "Core/ChunkFileReader.h" #include "Core/ChunkDataFormat.h" #include "YBaseLib/ByteStream.h" ChunkFileReader::ChunkFileReader() : m_pStream(NULL), m_bOwnsStream(false), m_iBaseOffset(0), m_iTotalSize(0), m_pChunks(NULL), m_nChunks(0), m_uMaximumChunkSize(0), m_iStringCount(0), m_pStringData(NULL), m_pStringPointers(NULL), m_pChunkData(NULL), m_uCurrentChunkSize(0) { } ChunkFileReader::~ChunkFileReader() { Reset(); } void ChunkFileReader::Reset() { if (m_bOwnsStream) m_pStream->Release(); m_pStream = NULL; m_bOwnsStream = false; m_iBaseOffset = 0; m_iTotalSize = 0; if (m_pChunks != NULL) { delete[] m_pChunks; m_pChunks = NULL; } m_nChunks = 0; m_uMaximumChunkSize = 0; m_iStringCount = 0; if (m_pStringPointers != NULL) { delete[] m_pStringPointers; m_pStringPointers = NULL; } if (m_pStringData != NULL) { Y_free(m_pStringData); m_pStringData = NULL; } if (m_pChunkData != NULL) { delete[] m_pChunkData; m_pChunkData = NULL; } m_uCurrentChunkSize = 0; } bool ChunkFileReader::Initialize(ByteStream *pStream) { Reset(); m_pStream = pStream; return InternalInitialize(); } bool ChunkFileReader::InitializeFromMemory(const byte *pData, uint32 DataSize, bool RequiresOwnCopy) { Reset(); if (RequiresOwnCopy) { m_pStream = ByteStream_CreateGrowableMemoryStream(NULL, DataSize); m_pStream->Write(pData, DataSize); m_pStream->SeekAbsolute(0); m_bOwnsStream = true; } else { m_pStream = ByteStream_CreateMemoryStream((void *)pData, DataSize); m_bOwnsStream = true; } return InternalInitialize(); } void ChunkFileReader::Close() { Reset(); } bool ChunkFileReader::InternalInitialize() { uint32 i; // work out base offset m_iBaseOffset = m_pStream->GetPosition(); // read in chunk header DF_CHUNKFILE_HEADER chunkFileHeader; if (!m_pStream->Read2(&chunkFileHeader, sizeof(chunkFileHeader))) goto FAILURE; // validate header if (chunkFileHeader.Magic != DF_CHUNKFILE_HEADER_MAGIC || chunkFileHeader.HeaderSize != sizeof(chunkFileHeader)) { goto FAILURE; } // work out offset to chunks m_nChunks = chunkFileHeader.ChunkCount; m_iTotalSize = chunkFileHeader.TotalSize; // read in chunk headers m_pChunks = new Chunk[m_nChunks]; for (i = 0; i < m_nChunks; i++) { DF_CHUNKFILE_CHUNK_HEADER chunkHeader; if (!m_pStream->Read2(&chunkHeader, sizeof(chunkHeader))) goto FAILURE; m_pChunks[i].Offset = m_iBaseOffset + chunkHeader.ChunkOffset; m_pChunks[i].Size = chunkHeader.ChunkSize; } // alloc space for (i = 0; i < m_nChunks; i++) m_uMaximumChunkSize = Max(m_uMaximumChunkSize, m_pChunks[i].Size); if (m_uMaximumChunkSize > 0) m_pChunkData = new byte[(size_t)m_uMaximumChunkSize]; // read in strings if (chunkFileHeader.StringsSize > 0) { if (!m_pStream->SeekAbsolute(m_iBaseOffset + chunkFileHeader.StringsOffset)) goto FAILURE; if (!LoadStrings(chunkFileHeader.StringsSize, chunkFileHeader.StringsCount)) goto FAILURE; } return true; FAILURE: Reset(); return false; } uint64 ChunkFileReader::GetTotalSize() const { return m_iTotalSize; } uint32 ChunkFileReader::GetChunkSize(uint32 ChunkIndex) const { if (ChunkIndex >= m_nChunks) return 0; return m_pChunks[ChunkIndex].Size; } bool ChunkFileReader::LoadChunk(uint32 ChunkIndex) { if (ChunkIndex >= m_nChunks || m_pChunks[ChunkIndex].Size == 0) return false; m_uCurrentChunkSize = m_pChunks[ChunkIndex].Size; if (!m_pStream->SeekAbsolute(m_pChunks[ChunkIndex].Offset) || !m_pStream->Read2(m_pChunkData, (size_t)m_uCurrentChunkSize)) return false; return true; } const byte *ChunkFileReader::GetCurrentChunkPointer() const { DebugAssert(m_uCurrentChunkSize > 0); return m_pChunkData; } uint32 ChunkFileReader::GetCurrentChunkSize() const { DebugAssert(m_uCurrentChunkSize > 0); return m_uCurrentChunkSize; } bool ChunkFileReader::LoadStrings(uint32 stringDataSize, uint32 expectedStringCount) { uint32 i, j; DebugAssert(stringDataSize > 0); m_pStringData = (char *)malloc(stringDataSize); if (!m_pStream->Read2(m_pStringData, stringDataSize)) return false; // last character should be a zero. if not, bad data if (m_pStringData[stringDataSize - 1] != 0) return false; // first pass: determine count of strings for (i = 0; i < stringDataSize; i++) { if (m_pStringData[i] == 0) m_iStringCount++; } // should be >0 due to check above DebugAssert(m_iStringCount > 0); if (m_iStringCount != expectedStringCount) return false; // second pass: allocate string count, store pointers m_pStringPointers = new const char *[m_iStringCount]; const char *pStringStart = (const char *)m_pStringData; for (i = 0, j = 0; i < stringDataSize; i++) { if (m_pStringData[i] == 0) { DebugAssert(j < m_iStringCount); m_pStringPointers[j++] = pStringStart; pStringStart = ((const char *)m_pStringData) + i + 1; } } // should be equal DebugAssert(m_iStringCount == j); return true; } uint32 ChunkFileReader::GetStringCount() const { return m_iStringCount; } const char *ChunkFileReader::GetStringByIndex(uint32 StringIndex) const { if (StringIndex >= m_iStringCount) return NULL; return m_pStringPointers[StringIndex]; } <file_sep>/Engine/Source/Renderer/RenderProxies/BlockMeshRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/BlockMeshRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/Camera.h" #include "Engine/Material.h" BlockMeshRenderProxy::BlockMeshRenderProxy(uint32 entityId, const BlockMesh *pStaticBlockMesh, const Transform &transform, uint32 shadowFlags) : RenderProxy(entityId), m_visibility(true), m_pBlockMesh(NULL), m_shadowFlags(shadowFlags), m_tintEnabled(false), m_tintColor(0xFFFFFFFF), m_bGPUResourcesCreated(false) { DebugAssert(pStaticBlockMesh != NULL); m_pBlockMesh = pStaticBlockMesh; m_pBlockMesh->AddRef(); SetTransform(transform); } BlockMeshRenderProxy::~BlockMeshRenderProxy() { ReleaseDeviceResources(); m_pBlockMesh->Release(); } void BlockMeshRenderProxy::SetBlockMesh(const BlockMesh *pBlockMesh) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetBlockMesh(pBlockMesh); } else { ReferenceCountedHolder<BlockMeshRenderProxy> pThisHolder(this); ReferenceCountedHolder<const BlockMesh> pBlockMeshHolder(pBlockMesh); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, pBlockMeshHolder]() { pThisHolder->RealSetBlockMesh(pBlockMeshHolder); }); } } void BlockMeshRenderProxy::RealSetBlockMesh(const BlockMesh *pBlockMesh) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pBlockMesh != nullptr); if (m_pBlockMesh == pBlockMesh) return; // not yet owned by render thread, so no need to do async modifications ReleaseDeviceResources(); // release mesh m_pBlockMesh->Release(); // set new mesh m_pBlockMesh = pBlockMesh; m_pBlockMesh->AddRef(); // fix up bounds SetBounds(m_transform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere())); } void BlockMeshRenderProxy::SetTransform(const Transform &transform) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTransform(transform); } else { ReferenceCountedHolder<BlockMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, transform]() { pThisHolder->RealSetTransform(transform); }); } } void BlockMeshRenderProxy::RealSetTransform(const Transform &transform) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_transform = transform; m_localToWorldMatrix = m_transform.GetTransformMatrix4x4(); SetBounds(m_transform.TransformBoundingBox(m_pBlockMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pBlockMesh->GetBoundingSphere())); } void BlockMeshRenderProxy::SetTintColor(bool enabled, uint32 color /* = 0 */) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTintColor(enabled, color); } else { ReferenceCountedHolder<BlockMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, enabled, color]() { pThisHolder->RealSetTintColor(enabled, color); }); } } void BlockMeshRenderProxy::RealSetTintColor(bool enabled, uint32 color /*= 0*/) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_tintEnabled = enabled; m_tintColor = (enabled) ? color : 0xFFFFFFFF; } void BlockMeshRenderProxy::SetVisibility(bool visible) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetVisibility(visible); } else { ReferenceCountedHolder<BlockMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, visible]() { pThisHolder->RealSetVisibility(visible); }); } } void BlockMeshRenderProxy::RealSetVisibility(bool visible) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_visibility = visible; } void BlockMeshRenderProxy::SetShadowFlags(uint32 shadowFlags) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetShadowFlags(shadowFlags); } else { ReferenceCountedHolder<BlockMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, shadowFlags]() { pThisHolder->RealSetShadowFlags(shadowFlags); }); } } void BlockMeshRenderProxy::RealSetShadowFlags(uint32 shadowFlags) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_shadowFlags = shadowFlags; } void BlockMeshRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { uint32 i; if (!m_visibility) return; // check gpu resources if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; // Store the requested render passes. uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) wantedRenderPasses |= RENDER_PASS_SHADOW_MAP; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; // if (hasLightMaps && (availableRenderPassMask & RENDER_PASS_LIGHTMAP)) // wantedRenderPasses = (wantedRenderPasses & ~(RENDER_PASS_STATIC_OPAQUE_LIGHTING | RENDER_PASS_STATIC_TRANSPARENT_LIGHTING)) | RENDER_PASS_LIGHTMAP; // Calculate view distance float viewDistance = pCamera->CalculateDepthToPoint(GetBoundingSphere().GetCenter()); uint32 selectedLOD = 0; // Draw this LOD. DebugAssert(selectedLOD < m_pBlockMesh->GetLODCount()); for (i = 0; i < m_pBlockMesh->GetBatchCount(selectedLOD); i++) { // Get batch info. const BlockMesh::Batch *pBatch = m_pBlockMesh->GetBatch(selectedLOD, i); // Get material. const Material *pMaterial = m_pBlockMesh->GetBlockList()->GetMaterial(pBatch->MaterialIndex); // Determine render passes. There isn't really any passes that a static mesh can't handle, so we only remove the material ones. uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); // Add to render queue if we have any render passes. if (renderPassMask != 0) { RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(BlockMeshVertexFactory); queueEntry.VertexFactoryFlags = m_pBlockMesh->GetVertexFactoryFlags(); queueEntry.pMaterial = pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.UserData[0] = selectedLOD; queueEntry.UserData[1] = i; queueEntry.TintColor = m_tintColor; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } void BlockMeshRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { uint32 selectedLOD = pQueueEntry->UserData[0]; pCommandList->GetConstants()->SetLocalToWorldMatrix(m_localToWorldMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); m_pBlockMesh->GetVertexBuffers(selectedLOD)->BindBuffers(pCommandList); pCommandList->SetIndexBuffer(m_pBlockMesh->GetIndexBuffer(selectedLOD), m_pBlockMesh->GetIndexFormat(selectedLOD), 0); } void BlockMeshRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { uint32 selectedLOD = pQueueEntry->UserData[0]; uint32 batchIndex = pQueueEntry->UserData[1]; const BlockMesh::Batch *pBatch = m_pBlockMesh->GetBatch(selectedLOD, batchIndex); pCommandList->DrawIndexed(pBatch->StartIndex, pBatch->IndexCount, 0); } bool BlockMeshRenderProxy::CreateDeviceResources() const { if (m_bGPUResourcesCreated) return true; if (!m_pBlockMesh->CreateGPUResources()) return false; //if (m_VertexBuffers.GetBuffer(0) == NULL) //BlockMeshVertexFactory::ShareVerticesBuffer(&m_VertexBuffers, m_pStaticBlockMesh->GetVertexBuffers()); m_bGPUResourcesCreated = true; return true; } void BlockMeshRenderProxy::ReleaseDeviceResources() const { //m_VertexBuffers.ClearBuffers(); m_bGPUResourcesCreated = false; } <file_sep>/Engine/Source/Renderer/WorldRenderers/CompositingWorldRenderer.h #pragma once #include "Renderer/WorldRenderer.h" class CompositingWorldRenderer : public WorldRenderer { public: CompositingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~CompositingWorldRenderer(); // create renderer resources virtual bool Initialize(); // Get render stats. virtual void GetRenderStats(RenderStats *pRenderStats) const; // On completion of frame. virtual void OnFrameComplete(); protected: // applies a guassian blur to a texture. uses intermediate buffer. void BlurTexture(GPUCommandList *pCommandList, GPUTexture2D *pBlurTexture, GPURenderTargetView *pBlurTextureRTV, float blurSigma = 0.8f, bool restoreViewport = true); // apply tone mapping. NOTE: Will overwrite the current viewport with the view parameters viewport, and render target. void ApplyFinalCompositePostProcess(const ViewParameters *pViewParameters, GPUTexture2D *pSceneColorTexture, GPURenderTargetView *pOutputRTV); // debug drawing void DrawDebugInfo(const Camera *pCamera); // composite programs ShaderProgram *m_pExtractLuminanceProgram; ShaderProgram *m_pBloomProgram; ShaderProgram *m_pToneMappingProgram; // blur programs ShaderProgram *m_pGaussianBlurProgram; }; <file_sep>/Engine/Source/GameFramework/BlockMeshEntity.h #pragma once #include "Engine/Entity.h" class BlockMesh; namespace Physics { class CollisionObject; } class BlockMeshRenderProxy; class BlockMeshEntity : public Entity { DECLARE_ENTITY_TYPEINFO(BlockMeshEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(BlockMeshEntity); public: BlockMeshEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~BlockMeshEntity(); // property accessors const BlockMesh *GetBlockMesh() const { return m_pBlockMesh; } const bool IsVisible() const { return m_visible; } const uint32 GetShadowFlags() const { return m_shadowFlags; } const bool IsCollidable() const { return m_collidable; } // property setters void SetBlockMesh(const BlockMesh *pBlockMesh); void SetVisible(bool visible); void SetCollidable(bool collidable); void SetShadowFlags(uint32 shadowFlags); // External creation method void Create(uint32 entityID, ENTITY_MOBILITY mobility = ENTITY_MOBILITY_MOVABLE, const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const BlockMesh *pBlockMesh = nullptr, bool visible = true, bool collidable = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // implemented methods virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; virtual void OnComponentBoundsChange() override; private: // property callbacks static bool PropertyCallbackGetBlockMeshName(ThisClass *pEntity, const void *pUserData, String *pValue); static bool PropertyCallbackSetBlockMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue); static void PropertyCallbackBlockMeshChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackVisibleChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackCollidableChanged(ThisClass *pEntity, const void *pUserData = nullptr); // update methods void UpdateRenderProxy(); void UpdateCollisionObject(); void UpdateBounds(); // vars const BlockMesh *m_pBlockMesh; bool m_visible; bool m_collidable; uint32 m_shadowFlags; // render proxy BlockMeshRenderProxy *m_pRenderProxy; // physics proxy Physics::CollisionObject *m_pCollisionObject; }; <file_sep>/Engine/Source/GameFramework/SpriteEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/SpriteEntity.h" DEFINE_ENTITY_TYPEINFO(SpriteEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(SpriteEntity); BEGIN_ENTITY_PROPERTIES(SpriteEntity) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(SpriteEntity) END_ENTITY_SCRIPT_FUNCTIONS() SpriteEntity::SpriteEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo) { } SpriteEntity::~SpriteEntity() { } <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUBuffer.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUBuffer.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12Helpers.h" Log_SetChannel(D3D12RenderBackend); D3D12GPUBuffer::D3D12GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, D3D12_RESOURCE_STATES defaultResourceState) : GPUBuffer(pBufferDesc) , m_pDevice(pDevice) , m_pD3DResource(pD3DResource) , m_pD3DMapResource(nullptr) , m_defaultResourceState(defaultResourceState) , m_mapType(GPU_MAP_TYPE_COUNT) { g_pRenderer->GetCounters()->OnResourceCreated(this); pDevice->AddRef(); } D3D12GPUBuffer::~D3D12GPUBuffer() { DebugAssert(m_pD3DMapResource == nullptr); g_pRenderer->GetCounters()->OnResourceDeleted(this); m_pDevice->ScheduleResourceForDeletion(m_pD3DResource); m_pDevice->Release(); } void D3D12GPUBuffer::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = m_desc.Size; } void D3D12GPUBuffer::SetDebugName(const char *debugName) { D3D12Helpers::SetD3D12ObjectName(m_pD3DResource, debugName); } GPUBuffer *D3D12GPUDevice::CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData /* = NULL */) { // work out the default resource state D3D12_RESOURCE_STATES defaultResourceState = D3D12_RESOURCE_STATE_GENERIC_READ; if (pDesc->Flags & (GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER | GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER)) defaultResourceState |= D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_INDEX_BUFFER) defaultResourceState |= D3D12_RESOURCE_STATE_INDEX_BUFFER; // initial resource state D3D12_RESOURCE_STATES initialResourceState = defaultResourceState; if (pInitialData != nullptr) initialResourceState = D3D12_RESOURCE_STATE_COPY_DEST; // create main resource ID3D12Resource *pResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, pDesc->Size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; HRESULT hResult = m_pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, initialResourceState, nullptr, IID_PPV_ARGS(&pResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommitedResource for main resource failed with hResult %08X", hResult); return false; } // create instance D3D12GPUBuffer *pBuffer = new D3D12GPUBuffer(pDesc, this, pResource, defaultResourceState); // handle uploads if (pInitialData != nullptr) { // create an upload resource ID3D12Resource *pUploadResource = pBuffer->CreateUploadResource(m_pD3DDevice, pDesc->Size); if (pUploadResource == nullptr) { pBuffer->Release(); return nullptr; } // get a copy queue CopyQueueReference queueReference(this); if (!queueReference.HasContext()) { pBuffer->Release(); return nullptr; } // map the upload resource D3D12_RANGE readRange = { 0, 0 }; void *pMappedPointer; hResult = pUploadResource->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), &pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Map for upload resource failed with hResult %08X", hResult); pUploadResource->Release(); pResource->Release(); return false; } // fill it D3D12_RANGE writeRange = { 0, pDesc->Size }; Y_memcpy(pMappedPointer, pInitialData, pDesc->Size); pUploadResource->Unmap(0, D3D12_MAP_RANGE_PARAM(&writeRange)); // copy from the upload buffer to the real buffer GetCurrentCopyCommandList()->CopyBufferRegion(pResource, 0, pUploadResource, 0, pDesc->Size); // transition to the real resource state ResourceBarrier(pResource, D3D12_RESOURCE_STATE_COPY_DEST, defaultResourceState); // free upload resource ScheduleCopyResourceForDeletion(pUploadResource); } // done, return the pointer from before return pBuffer; } ID3D12Resource *D3D12GPUBuffer::CreateUploadResource(ID3D12Device *pD3DDevice, uint32 size) const { ID3D12Resource *pResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE }; HRESULT hResult = pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&pResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommitedResource for upload resource failed with hResult %08X", hResult); return nullptr; } return pResource; } ID3D12Resource *D3D12GPUBuffer::CreateReadbackResource(ID3D12Device *pD3DDevice, uint32 size) const { ID3D12Resource *pResource; D3D12_HEAP_PROPERTIES heapProperties = { D3D12_HEAP_TYPE_READBACK, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, 0, size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE }; HRESULT hResult = pD3DDevice->CreateCommittedResource(&heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pResource)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateCommitedResource for readback resource failed with hResult %08X", hResult); return nullptr; } return pResource; } bool D3D12GPUContext::ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) { D3D12GPUBuffer *pD3D12Buffer = static_cast<D3D12GPUBuffer *>(pBuffer); DebugAssert(count > 0 && (start + count) <= pD3D12Buffer->GetDesc()->Size); // create a readback buffer ID3D12Resource *pReadbackBuffer = pD3D12Buffer->CreateReadbackResource(m_pD3DDevice, count); if (pReadbackBuffer == nullptr) return false; // transition to copy state, and queue a copy to the readback buffer (the transition back is placed on the next command list) ResourceBarrier(pD3D12Buffer->GetD3DResource(), pD3D12Buffer->GetDefaultResourceState(), D3D12_RESOURCE_STATE_COPY_SOURCE); m_pCommandList->CopyBufferRegion(pReadbackBuffer, 0, pD3D12Buffer->GetD3DResource(), start, count); m_commandCounter++; // flush + finish the command queue (slow!) D3D12GPUContext::Finish(); // now we can transition back ResourceBarrier(pD3D12Buffer->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_SOURCE, pD3D12Buffer->GetDefaultResourceState()); // map the readback buffer void *pMappedPointer; D3D12_RANGE readRange = { start, start + count }; HRESULT hResult = pReadbackBuffer->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), &pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to map readback buffer: %08X", hResult); pReadbackBuffer->Release(); return false; } // copy the contents over, and unmap the buffer D3D12_RANGE writeRange = { 0, 0 }; Y_memcpy(pDestination, pMappedPointer, count); pReadbackBuffer->Unmap(0, D3D12_MAP_RANGE_PARAM(&writeRange)); pReadbackBuffer->Release(); return true; } bool D3D12GPUContext::WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) { D3D12GPUBuffer *pD3D12Buffer = static_cast<D3D12GPUBuffer *>(pBuffer); DebugAssert(pD3D12Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_WRITABLE); DebugAssert(count > 0 && (start + count) <= pD3D12Buffer->GetDesc()->Size); // can we use the scratch buffer? if (count <= D3D12_BUFFER_WRITE_SCRATCH_BUFFER_THRESHOLD) { // allocate scratch buffer space ID3D12Resource *pScratchBufferResource; void *pScratchBufferCPUPointer; uint32 scratchBufferOffset; if (AllocateScratchBufferMemory(count, 0, &pScratchBufferResource, &scratchBufferOffset, &pScratchBufferCPUPointer, nullptr)) { // copy to scratch buffer Y_memcpy(pScratchBufferCPUPointer, pSource, count); // queue a copy from scratch buffer -> buffer ResourceBarrier(pD3D12Buffer->GetD3DResource(), pD3D12Buffer->GetDefaultResourceState(), D3D12_RESOURCE_STATE_COPY_DEST); m_pCommandList->CopyBufferRegion(pD3D12Buffer->GetD3DResource(), start, pScratchBufferResource, scratchBufferOffset, count); m_commandCounter++; ResourceBarrier(pD3D12Buffer->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_DEST, pD3D12Buffer->GetDefaultResourceState()); return true; } // failed to alloc Log_WarningPrintf("Failed to allocate scratch buffer storage, falling back to slow path."); } // allocate an upload buffer ID3D12Resource *pUploadBuffer = pD3D12Buffer->CreateUploadResource(m_pD3DDevice, count); if (pUploadBuffer == nullptr) return false; // map the upload buffer void *pMappedPointer; D3D12_RANGE readRange = { 0, 0 }; HRESULT hResult = pUploadBuffer->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), &pMappedPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to map upload buffer: %08X", hResult); pUploadBuffer->Release(); return false; } // copy the contents over, and unmap the buffer D3D12_RANGE writeRange = { start, start + count }; Y_memcpy(pMappedPointer, pSource, count); pUploadBuffer->Unmap(0, D3D12_MAP_RANGE_PARAM(&writeRange)); // transition to copy state, and queue a copy from the upload buffer ResourceBarrier(pD3D12Buffer->GetD3DResource(), pD3D12Buffer->GetDefaultResourceState(), D3D12_RESOURCE_STATE_COPY_DEST); m_pCommandList->CopyBufferRegion(pD3D12Buffer->GetD3DResource(), start, pUploadBuffer, 0, count); m_commandCounter++; ResourceBarrier(pD3D12Buffer->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_DEST, pD3D12Buffer->GetDefaultResourceState()); // release the upload buffer later m_pDevice->ScheduleResourceForDeletion(pUploadBuffer); return true; } bool D3D12GPUContext::MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) { D3D12GPUBuffer *pD3D12Buffer = static_cast<D3D12GPUBuffer *>(pBuffer); DebugAssert(pD3D12Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pD3D12Buffer->GetMapResource() == nullptr); // get buffer size uint32 bufferSize = pD3D12Buffer->GetDesc()->Size; // create a mapping buffer based on the initial state (read/write) // @TODO handle WRITE_NO_OVERWRITE and optimizations for this case.. // @TODO use scratch buffer for small maps (this would need a mapbufferrange call though) ID3D12Resource *pMapBuffer; if (mapType == GPU_MAP_TYPE_READ || mapType == GPU_MAP_TYPE_READ_WRITE) { // create readback buffer pMapBuffer = pD3D12Buffer->CreateReadbackResource(m_pD3DDevice, bufferSize); if (pMapBuffer == nullptr) return false; // copy the contents from the gpu buffer to the readback buffer ResourceBarrier(pD3D12Buffer->GetD3DResource(), pD3D12Buffer->GetDefaultResourceState(), D3D12_RESOURCE_STATE_COPY_SOURCE); m_pCommandList->CopyBufferRegion(pMapBuffer, 0, pD3D12Buffer->GetD3DResource(), 0, bufferSize); m_commandCounter++; // flush + finish the command queue (slow!) D3D12GPUContext::Finish(); // now we can transition back ResourceBarrier(pD3D12Buffer->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_SOURCE, pD3D12Buffer->GetDefaultResourceState()); // read the whole resource D3D12_RANGE readRange = { 0, pD3D12Buffer->GetDesc()->Size }; HRESULT hResult = pMapBuffer->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), ppPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to map buffer: %08X", hResult); pMapBuffer->Release(); return false; } } else { // write-only, so create upload buffer pMapBuffer = pD3D12Buffer->CreateUploadResource(m_pD3DDevice, bufferSize); if (pMapBuffer == nullptr) return false; // not reading anything D3D12_RANGE readRange = { 0, 0 }; HRESULT hResult = pMapBuffer->Map(0, D3D12_MAP_RANGE_PARAM(&readRange), ppPointer); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to map buffer: %08X", hResult); pMapBuffer->Release(); return false; } } // wait for the unmap call. pD3D12Buffer->SetMapResource(pMapBuffer, mapType); return true; } void D3D12GPUContext::Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) { D3D12GPUBuffer *pD3D12Buffer = static_cast<D3D12GPUBuffer *>(pBuffer); DebugAssert(pD3D12Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pD3D12Buffer->GetMapResource() != nullptr); // if we're in any write mode, we have to copy from the map buffer back to the gpu buffer ID3D12Resource *pMapBuffer = pD3D12Buffer->GetMapResource(); GPU_MAP_TYPE mapMode = pD3D12Buffer->GetMapType(); if (mapMode == GPU_MAP_TYPE_READ_WRITE || mapMode == GPU_MAP_TYPE_WRITE || mapMode == GPU_MAP_TYPE_WRITE_DISCARD || mapMode == GPU_MAP_TYPE_WRITE_NO_OVERWRITE) { // unmap, assume the entire range was written D3D12_RANGE writtenRange = { 0, pD3D12Buffer->GetDesc()->Size }; pMapBuffer->Unmap(0, D3D12_MAP_RANGE_PARAM(&writtenRange)); // read/write has to be transitioned if (mapMode == GPU_MAP_TYPE_READ_WRITE) ResourceBarrier(pMapBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); // copy to the gpu buffer ResourceBarrier(pD3D12Buffer->GetD3DResource(), pD3D12Buffer->GetDefaultResourceState(), D3D12_RESOURCE_STATE_COPY_DEST); m_pCommandList->CopyBufferRegion(pD3D12Buffer->GetD3DResource(), 0, pMapBuffer, 0, pD3D12Buffer->GetDesc()->Size); m_commandCounter++; ResourceBarrier(pD3D12Buffer->GetD3DResource(), D3D12_RESOURCE_STATE_COPY_DEST, pD3D12Buffer->GetDefaultResourceState()); // have to wait until the gpu is finished with it before releasing the buffer m_pDevice->ScheduleResourceForDeletion(pMapBuffer); } else { // unmap, nothing was written D3D12_RANGE writtenRange = { 0, 0 }; pMapBuffer->Unmap(0, D3D12_MAP_RANGE_PARAM(&writtenRange)); // this was only a read mapping, so we can just nuke the resource right now (the gpu won't touch it) pMapBuffer->Release(); } // clear pointer pD3D12Buffer->SetMapResource(nullptr, GPU_MAP_TYPE_COUNT); } <file_sep>/Editor/Source/Editor/ResourceBrowser/ui_EditorStaticMeshImportDialog.h /******************************************************************************** ** Form generated from reading UI file 'EditorStaticMeshImportDialog.ui' ** ** Created by: Qt User Interface Compiler version 5.4.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_EDITORSTATICMESHIMPORTDIALOG_H #define UI_EDITORSTATICMESHIMPORTDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QFormLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QListWidget> #include <QtWidgets/QProgressBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QVBoxLayout> #include "Editor/EditorVectorEditWidget.h" QT_BEGIN_NAMESPACE class Ui_EditorStaticMeshImportDialog { public: QVBoxLayout *verticalLayout; QLabel *mainHeading; QGroupBox *groupBox; QFormLayout *formLayout; QLabel *fileNameLabel; QHBoxLayout *horizontalLayout; QLineEdit *fileNameLineEdit; QPushButton *fileNameBrowseButton; QLabel *subObjectLabel; QComboBox *subObjectComboBox; QLabel *coordinateSystemLabel; QComboBox *coordinateSystemComboBox; QLabel *flipWindingLabel; QCheckBox *flipWindingCheckBox; QGroupBox *groupBox_2; QFormLayout *formLayout_2; QLabel *generateTangentsLabel; QCheckBox *generateTangentsCheckBox; QLabel *importMaterialsLabel; QCheckBox *importMaterialsCheckBox; QLabel *materialPrefixLabel; QLineEdit *materialPrefixLineEdit; QLabel *scaleLabel; EditorVectorEditWidget *scaleVectorEdit; QLabel *materialDirectoryLabel; QLineEdit *materialDirectoryLineEdit; QLabel *collisionShapeTypeLabel; QComboBox *collisionShapeTypeComboBox; QLabel *importerMessagesLabel; QListWidget *importerMessagesListWidget; QProgressBar *progressBar; QHBoxLayout *horizontalLayout_2; QCheckBox *keepOpenAfterImportingCheckBox; QSpacerItem *horizontalSpacer; QPushButton *importButton; QPushButton *closeButton; void setupUi(QDialog *EditorStaticMeshImportDialog) { if (EditorStaticMeshImportDialog->objectName().isEmpty()) EditorStaticMeshImportDialog->setObjectName(QStringLiteral("EditorStaticMeshImportDialog")); EditorStaticMeshImportDialog->resize(476, 605); EditorStaticMeshImportDialog->setSizeGripEnabled(true); verticalLayout = new QVBoxLayout(EditorStaticMeshImportDialog); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); mainHeading = new QLabel(EditorStaticMeshImportDialog); mainHeading->setObjectName(QStringLiteral("mainHeading")); mainHeading->setTextFormat(Qt::RichText); mainHeading->setWordWrap(true); verticalLayout->addWidget(mainHeading); groupBox = new QGroupBox(EditorStaticMeshImportDialog); groupBox->setObjectName(QStringLiteral("groupBox")); formLayout = new QFormLayout(groupBox); formLayout->setObjectName(QStringLiteral("formLayout")); fileNameLabel = new QLabel(groupBox); fileNameLabel->setObjectName(QStringLiteral("fileNameLabel")); formLayout->setWidget(0, QFormLayout::LabelRole, fileNameLabel); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); fileNameLineEdit = new QLineEdit(groupBox); fileNameLineEdit->setObjectName(QStringLiteral("fileNameLineEdit")); horizontalLayout->addWidget(fileNameLineEdit); fileNameBrowseButton = new QPushButton(groupBox); fileNameBrowseButton->setObjectName(QStringLiteral("fileNameBrowseButton")); horizontalLayout->addWidget(fileNameBrowseButton); formLayout->setLayout(0, QFormLayout::FieldRole, horizontalLayout); subObjectLabel = new QLabel(groupBox); subObjectLabel->setObjectName(QStringLiteral("subObjectLabel")); formLayout->setWidget(1, QFormLayout::LabelRole, subObjectLabel); subObjectComboBox = new QComboBox(groupBox); subObjectComboBox->setObjectName(QStringLiteral("subObjectComboBox")); formLayout->setWidget(1, QFormLayout::FieldRole, subObjectComboBox); coordinateSystemLabel = new QLabel(groupBox); coordinateSystemLabel->setObjectName(QStringLiteral("coordinateSystemLabel")); formLayout->setWidget(2, QFormLayout::LabelRole, coordinateSystemLabel); coordinateSystemComboBox = new QComboBox(groupBox); coordinateSystemComboBox->setObjectName(QStringLiteral("coordinateSystemComboBox")); formLayout->setWidget(2, QFormLayout::FieldRole, coordinateSystemComboBox); flipWindingLabel = new QLabel(groupBox); flipWindingLabel->setObjectName(QStringLiteral("flipWindingLabel")); formLayout->setWidget(3, QFormLayout::LabelRole, flipWindingLabel); flipWindingCheckBox = new QCheckBox(groupBox); flipWindingCheckBox->setObjectName(QStringLiteral("flipWindingCheckBox")); formLayout->setWidget(3, QFormLayout::FieldRole, flipWindingCheckBox); verticalLayout->addWidget(groupBox); groupBox_2 = new QGroupBox(EditorStaticMeshImportDialog); groupBox_2->setObjectName(QStringLiteral("groupBox_2")); formLayout_2 = new QFormLayout(groupBox_2); formLayout_2->setObjectName(QStringLiteral("formLayout_2")); formLayout_2->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); generateTangentsLabel = new QLabel(groupBox_2); generateTangentsLabel->setObjectName(QStringLiteral("generateTangentsLabel")); formLayout_2->setWidget(0, QFormLayout::LabelRole, generateTangentsLabel); generateTangentsCheckBox = new QCheckBox(groupBox_2); generateTangentsCheckBox->setObjectName(QStringLiteral("generateTangentsCheckBox")); generateTangentsCheckBox->setChecked(true); formLayout_2->setWidget(0, QFormLayout::FieldRole, generateTangentsCheckBox); importMaterialsLabel = new QLabel(groupBox_2); importMaterialsLabel->setObjectName(QStringLiteral("importMaterialsLabel")); formLayout_2->setWidget(1, QFormLayout::LabelRole, importMaterialsLabel); importMaterialsCheckBox = new QCheckBox(groupBox_2); importMaterialsCheckBox->setObjectName(QStringLiteral("importMaterialsCheckBox")); formLayout_2->setWidget(1, QFormLayout::FieldRole, importMaterialsCheckBox); materialPrefixLabel = new QLabel(groupBox_2); materialPrefixLabel->setObjectName(QStringLiteral("materialPrefixLabel")); formLayout_2->setWidget(3, QFormLayout::LabelRole, materialPrefixLabel); materialPrefixLineEdit = new QLineEdit(groupBox_2); materialPrefixLineEdit->setObjectName(QStringLiteral("materialPrefixLineEdit")); formLayout_2->setWidget(3, QFormLayout::FieldRole, materialPrefixLineEdit); scaleLabel = new QLabel(groupBox_2); scaleLabel->setObjectName(QStringLiteral("scaleLabel")); formLayout_2->setWidget(4, QFormLayout::LabelRole, scaleLabel); scaleVectorEdit = new EditorVectorEditWidget(groupBox_2); scaleVectorEdit->setObjectName(QStringLiteral("scaleVectorEdit")); formLayout_2->setWidget(4, QFormLayout::FieldRole, scaleVectorEdit); materialDirectoryLabel = new QLabel(groupBox_2); materialDirectoryLabel->setObjectName(QStringLiteral("materialDirectoryLabel")); formLayout_2->setWidget(2, QFormLayout::LabelRole, materialDirectoryLabel); materialDirectoryLineEdit = new QLineEdit(groupBox_2); materialDirectoryLineEdit->setObjectName(QStringLiteral("materialDirectoryLineEdit")); formLayout_2->setWidget(2, QFormLayout::FieldRole, materialDirectoryLineEdit); collisionShapeTypeLabel = new QLabel(groupBox_2); collisionShapeTypeLabel->setObjectName(QStringLiteral("collisionShapeTypeLabel")); formLayout_2->setWidget(5, QFormLayout::LabelRole, collisionShapeTypeLabel); collisionShapeTypeComboBox = new QComboBox(groupBox_2); collisionShapeTypeComboBox->setObjectName(QStringLiteral("collisionShapeTypeComboBox")); formLayout_2->setWidget(5, QFormLayout::FieldRole, collisionShapeTypeComboBox); verticalLayout->addWidget(groupBox_2); importerMessagesLabel = new QLabel(EditorStaticMeshImportDialog); importerMessagesLabel->setObjectName(QStringLiteral("importerMessagesLabel")); verticalLayout->addWidget(importerMessagesLabel); importerMessagesListWidget = new QListWidget(EditorStaticMeshImportDialog); importerMessagesListWidget->setObjectName(QStringLiteral("importerMessagesListWidget")); verticalLayout->addWidget(importerMessagesListWidget); progressBar = new QProgressBar(EditorStaticMeshImportDialog); progressBar->setObjectName(QStringLiteral("progressBar")); progressBar->setValue(0); progressBar->setTextVisible(false); verticalLayout->addWidget(progressBar); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); keepOpenAfterImportingCheckBox = new QCheckBox(EditorStaticMeshImportDialog); keepOpenAfterImportingCheckBox->setObjectName(QStringLiteral("keepOpenAfterImportingCheckBox")); horizontalLayout_2->addWidget(keepOpenAfterImportingCheckBox); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); importButton = new QPushButton(EditorStaticMeshImportDialog); importButton->setObjectName(QStringLiteral("importButton")); importButton->setDefault(true); importButton->setFlat(false); horizontalLayout_2->addWidget(importButton); closeButton = new QPushButton(EditorStaticMeshImportDialog); closeButton->setObjectName(QStringLiteral("closeButton")); horizontalLayout_2->addWidget(closeButton); verticalLayout->addLayout(horizontalLayout_2); retranslateUi(EditorStaticMeshImportDialog); coordinateSystemComboBox->setCurrentIndex(1); collisionShapeTypeComboBox->setCurrentIndex(0); QMetaObject::connectSlotsByName(EditorStaticMeshImportDialog); } // setupUi void retranslateUi(QDialog *EditorStaticMeshImportDialog) { EditorStaticMeshImportDialog->setWindowTitle(QApplication::translate("EditorStaticMeshImportDialog", "Static Mesh Importer", 0)); mainHeading->setText(QApplication::translate("EditorStaticMeshImportDialog", "<html><head/><body><p><span style=\" font-size:16pt; font-weight:600;\">Static Mesh Importer</span></p><p>Fill out this form to import an object, or multiple objects into the engine. After importing is complete, an editor window will open with the imported mesh.</p></body></html>", 0)); groupBox->setTitle(QApplication::translate("EditorStaticMeshImportDialog", "Source File", 0)); fileNameLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "File Name: ", 0)); fileNameBrowseButton->setText(QApplication::translate("EditorStaticMeshImportDialog", "Browse...", 0)); subObjectLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Sub Object: ", 0)); coordinateSystemLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Coordinate System: ", 0)); coordinateSystemComboBox->clear(); coordinateSystemComboBox->insertItems(0, QStringList() << QApplication::translate("EditorStaticMeshImportDialog", "Y-Up Left Handed", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Y-Up Right Handed", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Z-Up Left Handed", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Z-Up Right Handed", 0) ); flipWindingLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Flip Faces: ", 0)); groupBox_2->setTitle(QApplication::translate("EditorStaticMeshImportDialog", "Post Processing Options", 0)); generateTangentsLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Generate Tangents: ", 0)); importMaterialsLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Import Materials: ", 0)); materialPrefixLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Material Prefix: ", 0)); scaleLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Scale: ", 0)); materialDirectoryLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Material Directory: ", 0)); collisionShapeTypeLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Collision Shape Type: ", 0)); collisionShapeTypeComboBox->clear(); collisionShapeTypeComboBox->insertItems(0, QStringList() << QApplication::translate("EditorStaticMeshImportDialog", "None", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Box", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Sphere", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Triangle Mesh", 0) << QApplication::translate("EditorStaticMeshImportDialog", "Convex Hull", 0) ); importerMessagesLabel->setText(QApplication::translate("EditorStaticMeshImportDialog", "Importer Messages: ", 0)); keepOpenAfterImportingCheckBox->setText(QApplication::translate("EditorStaticMeshImportDialog", "Keep Open After Importing", 0)); importButton->setText(QApplication::translate("EditorStaticMeshImportDialog", "Import", 0)); closeButton->setText(QApplication::translate("EditorStaticMeshImportDialog", "Close", 0)); } // retranslateUi }; namespace Ui { class EditorStaticMeshImportDialog: public Ui_EditorStaticMeshImportDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_EDITORSTATICMESHIMPORTDIALOG_H <file_sep>/Engine/Source/BlockEngine/BlockAnimation.h #pragma once #include "Engine/Entity.h" #include "BlockEngine/BlockWorld.h" #include "BlockEngine/BlockWorldMesher.h" #include "Engine/Physics/CollisionObject.h" #include "Engine/Physics/CollisionShape.h" class BlockAnimationBlockRenderProxy; class BlockAnimation : public Entity { DECLARE_ENTITY_TYPEINFO(BlockAnimation, Entity); DECLARE_OBJECT_NO_FACTORY(BlockAnimation); public: BlockAnimation(const EntityTypeInfo *pTypeInfo = &s_typeInfo); ~BlockAnimation(); // Creation method also specifies block world. static BlockAnimation *Create(BlockWorld *pBlockWorld, bool autoDespawn = true); // Create an animated block 'explosion'-type effect. bool CreatePhysicsBlock(const float3 &basePosition, BlockWorldBlockType blockValue, const float3 &forceVector, float despawnTime = 5.0f); bool CreatePhysicsBlock(int32 x, int32 y, int32 z, const float3 &forceVector, bool removeBlock = true, float despawnTime = 5.0f); // Create an animated block spawn event void CreateSpawnBlock(const float3 &sourcePosition, int32 x, int32 y, int32 z, BlockWorldBlockType blockValue, float spawnTime = 1.0f, bool setAfterSpawn = true); // events virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; // Update event virtual void Update(float timeSinceLastUpdate) override; private: // rebuild all vertex arrays and recalculate bounds void RebuildRenderData(); // properties const BlockPalette *m_pBlockPalette; BlockWorld *m_pBlockWorld; bool m_autoDespawn; bool m_renderDataUpdatePending; // block render proxy BlockAnimationBlockRenderProxy *m_pBlockRenderProxy; // physics block info struct PhysicsBlock { BlockWorldBlockType SourceValue; Transform LastTransform; float TimeRemaining; AABox BoundingBox; Physics::CollisionObject *pCollisionObject; }; // physics block instances PODArray<PhysicsBlock *> m_physicsBlocks; // spawning block struct SpawningBlock { float3 SourcePosition; int32 BlockX, BlockY, BlockZ; BlockWorldBlockType BlockValue; float TimeRemaining; bool SetAfterSpawn; }; // spawning block instances MemArray<SpawningBlock> m_spawningBlocks; }; <file_sep>/Engine/Source/BaseGame/GameEntity.cpp #include "BaseGame/PrecompiledHeader.h" #include "BaseGame/GameEntity.h" DEFINE_ENTITY_TYPEINFO(GameEntity, 0); BEGIN_ENTITY_PROPERTIES(GameEntity) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(GameEntity, m_visible), __PS_OnVisibilityChanged, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("Opacity", 0, offsetof(GameEntity, m_opacity), __PS_OnOpacityChanged, nullptr) PROPERTY_TABLE_MEMBER_COLOR("TintColor", 0, offsetof(GameEntity, m_tintColor), __PS_OnTintColorChanged, nullptr) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(GameEntity) END_ENTITY_SCRIPT_FUNCTIONS() GameEntity::GameEntity(const EntityTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_visible(true), m_opacity(1.0f), m_tintColor(0xFFFFFFFF), m_fadeDuration(0.0f), m_fadeStartValue(0.0f), m_fadeTimeRemaining(0.0f) { } GameEntity::~GameEntity() { } void GameEntity::SetVisible(bool visible) { if (visible == m_visible) return; m_visible = visible; OnVisibilityChanged(); } void GameEntity::OnVisibilityChanged() { } void GameEntity::SetOpacity(float opacity) { DebugAssert(opacity >= 0.0f); if (opacity == m_opacity) return; m_opacity = opacity; SetTintColor((m_tintColor & 0x00FFFFFF) | ((uint32)Math::Clamp(m_opacity * 255.0f, 0.0f, 255.0f) << 24)); OnOpacityChanged(); } void GameEntity::OnOpacityChanged() { } void GameEntity::SetTintColor(uint32 tintColor) { m_tintColor = tintColor; OnTintColorChanged(); } void GameEntity::OnTintColorChanged() { } void GameEntity::FadeIn(float duration /* = 1.0f */) { if (m_fadeDuration == 0.0f) RegisterForUpdates(); m_fadeDuration = duration; m_fadeTimeRemaining = duration; m_fadeStartValue = m_opacity; } void GameEntity::FadeOut(float duration /* = 1.0f */) { if (m_fadeDuration == 0.0f) RegisterForUpdates(); m_fadeDuration = duration; m_fadeTimeRemaining = duration; if (m_opacity == 0.0f) m_fadeStartValue = -Y_FLT_EPSILON; else m_fadeStartValue = -m_opacity; } void GameEntity::Update(float timeSinceLastUpdate) { BaseClass::Update(timeSinceLastUpdate); if (m_fadeTimeRemaining > 0.0f) { m_fadeTimeRemaining -= timeSinceLastUpdate; if (m_fadeTimeRemaining <= 0.0f) m_fadeTimeRemaining = 0.0f; // some trickery to hide the direction in the starting value float start = Math::Abs(m_fadeStartValue); float end = (m_fadeStartValue < 0.0f) ? 0.0f : 1.0f; float opacity = Math::Lerp(end, start, m_fadeTimeRemaining / m_fadeDuration); SetOpacity(opacity); // end of it? if (m_fadeTimeRemaining == 0.0f) { m_fadeDuration = 0.0f; m_fadeStartValue = 0.0f; UnregisterForUpdates(); } } } <file_sep>/Engine/Source/Engine/ParticleSystemBuiltinEmitters.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemBuiltinEmitters.h" #include "Engine/ParticleSystemVertexFactory.h" #include "Engine/Camera.h" #include "Engine/Material.h" #include "Engine/EngineCVars.h" #include "Engine/ResourceManager.h" #include "Renderer/Renderer.h" Log_SetChannel(ParticleSystemBuiltinEmitters); DEFINE_OBJECT_TYPE_INFO(ParticleSystemEmitter_Sprite); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemEmitter_Sprite); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemEmitter_Sprite) PROPERTY_TABLE_MEMBER("Material", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetMaterial, nullptr, PropertyCallbackSetMaterial, nullptr, nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemEmitter_Sprite::ParticleSystemEmitter_Sprite() : ParticleSystemEmitter() { m_pMaterial = g_pResourceManager->GetDefaultMaterial(); } ParticleSystemEmitter_Sprite::~ParticleSystemEmitter_Sprite() { m_pMaterial->Release(); } void ParticleSystemEmitter_Sprite::SetMaterial(const Material *pMaterial) { if (m_pMaterial == pMaterial) return; m_pMaterial->Release(); m_pMaterial = pMaterial; m_pMaterial->AddRef(); } void ParticleSystemEmitter_Sprite::InitializeInstance(InstanceData *pEmitterData) const { ParticleSystemEmitter::InitializeInstance(pEmitterData); } void ParticleSystemEmitter_Sprite::CleanupInstance(InstanceData *pEmitterData) const { ParticleSystemEmitter::CleanupInstance(pEmitterData); } void ParticleSystemEmitter_Sprite::UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const { // Do normal system update ParticleSystemEmitter::UpdateInstance(pEmitterData, pBaseTransform, pRNG, deltaTime); } void ParticleSystemEmitter_Sprite::QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const { // Check particle count, don't render anything if there aren't any. if (pEmitterRenderData->ParticleCount > 0) { // Determine render pass mask, remove shadowing passes uint32 renderPassMask = RENDER_PASSES_DEFAULT & ~(RENDER_PASS_SHADOW_MAP | RENDER_PASS_SHADOWED_LIGHTING); renderPassMask = m_pMaterial->GetShader()->SelectRenderPassMask(renderPassMask & pRenderQueue->GetAcceptingRenderPassMask()); if (renderPassMask == 0) return; // Create a single queue entry for this material RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = pRenderProxy; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(ParticleSystemSpriteVertexFactory); queueEntry.VertexFactoryFlags = pEmitterRenderData->VertexFactoryFlags; queueEntry.pMaterial = m_pMaterial; queueEntry.BoundingBox = pEmitterRenderData->BoundingBox; queueEntry.RenderPassMask = renderPassMask; queueEntry.ViewDistance = pCamera->CalculateDepthToBox(pEmitterRenderData->BoundingBox); queueEntry.Layer = m_pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } void ParticleSystemEmitter_Sprite::SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { pCommandList->SetDrawTopology(ParticleSystemSpriteVertexFactory::GetDrawTopology(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags)); pCommandList->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); // set up vertex buffer for instanced quads if (pEmitterRenderData->VertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderInstancedQuads) { uint32 vertexBufferOffset = 0; uint32 vertexBufferStride = ParticleSystemSpriteVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags); pCommandList->SetVertexBuffers(0, 1, &pEmitterRenderData->pGPUBuffer, &vertexBufferOffset, &vertexBufferStride); } } void ParticleSystemEmitter_Sprite::DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { // branch out if (pEmitterRenderData->VertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderBasic) { uint32 nVertices = pEmitterRenderData->ParticleCount * ParticleSystemSpriteVertexFactory::GetVerticesPerSprite(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags); uint32 vertexSize = ParticleSystemSpriteVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags); uint32 bufferSize = nVertices * vertexSize; DebugAssert(bufferSize > 0); // ehh whatever fix me later please byte *pBuffer = new byte[bufferSize]; ParticleSystemSpriteVertexFactory::FillVertexBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags, pCamera, reinterpret_cast<const ParticleData *>(pEmitterRenderData->pGPUStagingBuffer), pEmitterRenderData->ParticleCount, pBuffer, bufferSize); pCommandList->DrawUserPointer(pBuffer, vertexSize, nVertices); delete[] pBuffer; } else if (pEmitterRenderData->VertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderInstancedQuads) { // invoke instanced draw DebugAssert(pEmitterRenderData->ParticleCount > 0); pCommandList->DrawInstanced(0, 4, pEmitterRenderData->ParticleCount); } } void ParticleSystemEmitter_Sprite::InitializeRenderData(InstanceRenderData *pEmitterRenderData) const { ParticleSystemEmitter::InitializeRenderData(pEmitterRenderData); // determine vertex factory flags uint32 vertexFactoryFlags = 0; // ParticleSystemSpriteVertexFactory::Flag_UseWorldTransform if (CVars::r_sprite_draw_instanced_quads.GetBool()) vertexFactoryFlags |= ParticleSystemSpriteVertexFactory::Flag_RenderInstancedQuads; else vertexFactoryFlags |= ParticleSystemSpriteVertexFactory::Flag_RenderBasic; // set flags pEmitterRenderData->VertexFactoryFlags = vertexFactoryFlags; // initialize stuff based on flags if (vertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderBasic) { // create 'staging' buffer pEmitterRenderData->GPUStagingBufferSize = sizeof(ParticleData) * m_maxActiveParticles; pEmitterRenderData->pGPUStagingBuffer = reinterpret_cast<byte *>(Y_malloc(pEmitterRenderData->GPUStagingBufferSize)); } else if (vertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderInstancedQuads) { // Create dynamic buffer for streaming uint32 vertexSize = ParticleSystemSpriteVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER | GPU_BUFFER_FLAG_MAPPABLE, vertexSize * m_maxActiveParticles); pEmitterRenderData->pGPUBuffer = g_pRenderer->CreateBuffer(&bufferDesc, nullptr); } } void ParticleSystemEmitter_Sprite::CleanupRenderData(InstanceRenderData *pEmitterRenderData) const { ParticleSystemEmitter::CleanupRenderData(pEmitterRenderData); } void ParticleSystemEmitter_Sprite::UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const { // parent update ParticleSystemEmitter::UpdateRenderData(pEmitterData, pEmitterRenderData); // count active particles uint32 nActiveParticles = pEmitterData->ParticlesState[0].GetSize(); pEmitterRenderData->ParticleCount = nActiveParticles; if (nActiveParticles == 0) { pEmitterRenderData->ParticleCount = 0; return; } // render type specific if (pEmitterRenderData->VertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderBasic) { // Write to GPU staging buffer DebugAssert(pEmitterRenderData->GPUStagingBufferSize >= (sizeof(ParticleData) * nActiveParticles)); Y_memcpy(pEmitterRenderData->pGPUStagingBuffer, pEmitterData->ParticlesState[0].GetBasePointer(), sizeof(ParticleData) * nActiveParticles); pEmitterRenderData->GPUStagingBufferUsage = sizeof(ParticleData) * nActiveParticles; } else if (pEmitterRenderData->VertexFactoryFlags & ParticleSystemSpriteVertexFactory::Flag_RenderInstancedQuads) { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); DebugAssert(pEmitterRenderData->pGPUBuffer != nullptr); // map the gpu buffer void *pMappedPointer; if (!pGPUContext->MapBuffer(pEmitterRenderData->pGPUBuffer, GPU_MAP_TYPE_WRITE_DISCARD, &pMappedPointer)) { Log_ErrorPrintf("ParticleSystemEmitter_Sprite::UpdateRenderData: Failed to map GPU buffer"); pEmitterRenderData->ParticleCount = 0; return; } // write to it if (!ParticleSystemSpriteVertexFactory::FillVertexBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), pEmitterRenderData->VertexFactoryFlags, nullptr, pEmitterData->ParticlesState[0].GetBasePointer(), nActiveParticles, pMappedPointer, pEmitterRenderData->pGPUBuffer->GetDesc()->Size)) { Log_ErrorPrintf("ParticleSystemEmitter_Sprite::UpdateRenderData: Failed to write to GPU buffer"); pEmitterRenderData->ParticleCount = 0; return; } // unmap buffer again pGPUContext->Unmapbuffer(pEmitterRenderData->pGPUBuffer, pMappedPointer); } } bool ParticleSystemEmitter_Sprite::PropertyCallbackGetMaterial(ThisClass *pParticleSystem, const void *pUserData, String *pValue) { *pValue = pParticleSystem->m_pMaterial->GetName(); return true; } bool ParticleSystemEmitter_Sprite::PropertyCallbackSetMaterial(ThisClass *pParticleSystem, const void *pUserData, const String *pValue) { const Material *pMaterial = g_pResourceManager->GetMaterial(pValue->GetCharArray()); if (pMaterial == nullptr) return false; pParticleSystem->m_pMaterial->Release(); pParticleSystem->m_pMaterial = pMaterial; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ParticleSystemEmitter_StaticMesh::ParticleSystemEmitter_StaticMesh() { } ParticleSystemEmitter_StaticMesh::~ParticleSystemEmitter_StaticMesh() { } void ParticleSystemEmitter_StaticMesh::SetMesh(uint32 index, const StaticMesh *pMesh) { } void ParticleSystemEmitter_StaticMesh::AddMesh(const StaticMesh *pMesh) { } void ParticleSystemEmitter_StaticMesh::RemoveMesh(uint32 index) { } void ParticleSystemEmitter_StaticMesh::InitializeInstance(InstanceData *pEmitterData) const { } void ParticleSystemEmitter_StaticMesh::CleanupInstance(InstanceData *pEmitterData) const { } void ParticleSystemEmitter_StaticMesh::UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const { } void ParticleSystemEmitter_StaticMesh::InitializeRenderData(InstanceRenderData *pEmitterRenderData) const { } void ParticleSystemEmitter_StaticMesh::CleanupRenderData(InstanceRenderData *pEmitterRenderData) const { } void ParticleSystemEmitter_StaticMesh::UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const { } void ParticleSystemEmitter_StaticMesh::QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const { } void ParticleSystemEmitter_StaticMesh::SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { } void ParticleSystemEmitter_StaticMesh::DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ParticleSystemEmitter::RegisterBuiltinEmitters() { static bool called = false; DebugAssert(!called); called = true; #define REGISTER_TYPE(Type) Type::StaticMutableTypeInfo()->RegisterType() REGISTER_TYPE(ParticleSystemEmitter_Sprite); #undef REGISTER_TYPE } <file_sep>/Engine/Source/MathLib/SIMDVectori_scalar.cpp #include "MathLib/SIMDVectori.h" #if Y_CPU_SSE_LEVEL == 0 const SIMDVector2i &SIMDVector2i::Zero = reinterpret_cast<const SIMDVector2i &>(Vector2i::Zero); const SIMDVector2i &SIMDVector2i::One = reinterpret_cast<const SIMDVector2i &>(Vector2i::One); const SIMDVector2i &SIMDVector2i::NegativeOne = reinterpret_cast<const SIMDVector2i &>(Vector2i::NegativeOne); const SIMDVector3i &SIMDVector3i::Zero = reinterpret_cast<const SIMDVector3i &>(Vector3i::Zero); const SIMDVector3i &SIMDVector3i::One = reinterpret_cast<const SIMDVector3i &>(Vector3i::One); const SIMDVector3i &SIMDVector3i::NegativeOne = reinterpret_cast<const SIMDVector3i &>(Vector3i::NegativeOne); const SIMDVector4i &SIMDVector4i::Zero = reinterpret_cast<const SIMDVector4i &>(Vector4i::Zero); const SIMDVector4i &SIMDVector4i::One = reinterpret_cast<const SIMDVector4i &>(Vector4i::One); const SIMDVector4i &SIMDVector4i::NegativeOne = reinterpret_cast<const SIMDVector4i &>(Vector4i::NegativeOne); #endif <file_sep>/Engine/Source/Renderer/RenderProfiler.h #pragma once #include "Renderer/Common.h" #include "Renderer/RendererTypes.h" #include "Engine/Camera.h" class Font; class MiniGUIContext; // helper macros #define RENDER_PROFILER_BEGIN_SECTION(profilerVariable, sectionName, enableGPUStats) MULTI_STATEMENT_MACRO_BEGIN \ if (profilerVariable != nullptr) { \ profilerVariable->BeginSection(sectionName, enableGPUStats); \ } \ MULTI_STATEMENT_MACRO_END #define RENDER_PROFILER_END_SECTION(profilerVariable) MULTI_STATEMENT_MACRO_BEGIN \ if (profilerVariable != nullptr) { \ profilerVariable->EndSection(); \ } \ MULTI_STATEMENT_MACRO_END #define RENDER_PROFILER_ADD_CAMERA(profilerVariable, cameraPtr, cameraName) MULTI_STATEMENT_MACRO_BEGIN \ if (profilerVariable != nullptr) { \ profilerVariable->AddCamera(cameraPtr, cameraName); \ } \ MULTI_STATEMENT_MACRO_END class RenderProfiler { public: class Section { friend class RenderProfiler; public: Section(); ~Section(); const String &GetSectionName() const { return m_sectionName; } const float GetElapsedTime() const { return m_elapsedTime; } const bool HasGPUStats() const { return m_hasGPUStats; } const float GetCPUTime() const { return (m_elapsedTime - m_gpuWaitTime); } const float GetGPUTime() const { return m_gpuTime; } const float GetGPUWaitTime() const { return m_gpuWaitTime; } const uint32 GetDrawCallCount() const { return m_drawCallCount; } const Section *GetParent() const { return m_pParent; } const Section *GetChild(uint32 i) const { return m_children[i]; } const uint32 GetChildCount() const { return m_children.GetSize(); } private: void Clear(); void Begin(Section *pParentSection, const char *sectionName, bool enableGPUStats, GPUContext *pGPUContext, GPUQuery *pGPUTimeQuery); void End(GPUContext *pGPUContext); String m_sectionName; float m_elapsedTime; bool m_hasGPUStats; float m_gpuTime; float m_gpuWaitTime; uint32 m_drawCallCount; uint32 m_startingDrawCallCount; Timer m_timer; GPUQuery *m_pGPUTimeQuery; Section *m_pParent; PODArray<Section *> m_children; }; struct DrawSummaryOptions { float RedThresholdMs; float YellowThresholdMs; const Font *pFont; uint32 FontSize; uint32 DrawAreaStartX; uint32 DrawAreaStartY; uint32 DrawAreaWidth; uint32 DrawAreaHeight; uint32 DrawAreaBackgroundColor; uint32 DrawAreaBorderColor; }; public: RenderProfiler(GPUContext *pGPUContext); ~RenderProfiler(); // enable/disable frame timing bool GetGPUStatsEnabled() const { return m_gpuTimingEnabled; } void SetGPUStatsEnabled(bool enabled) { m_gpuTimingEnabled = enabled; } // begin section void BeginSection(const char *sectionName, bool enableGPUStats); void EndSection(); // begin camera const uint32 GetCameraCount() const { return m_cameraArray.GetSize(); } const Camera *GetCamera(uint32 index) { return &m_cameraArray[index].Value; } const String &GetCameraName(uint32 index) { return m_cameraArray[index].Key; } void AddCamera(const Camera *pCamera, const char *cameraName); // camera override, used by renderers const bool HasCameraOverride() const { return (m_cameraOverrideIndex >= 0 && (uint32)m_cameraOverrideIndex < m_cameraArray.GetSize()); } const Camera *GetCameraOverrideCamera() const { return (m_cameraOverrideIndex >= 0 && (uint32)m_cameraOverrideIndex < m_cameraArray.GetSize()) ? &m_cameraArray[m_cameraOverrideIndex].Value : nullptr; } const char *GetCameraOverrideName() const { return (m_cameraOverrideIndex >= 0 && (uint32)m_cameraOverrideIndex < m_cameraArray.GetSize()) ? m_cameraArray[m_cameraOverrideIndex].Key.GetCharArray() : nullptr; } const int32 GetCameraOverrideIndex() const { return m_cameraOverrideIndex; } void SetCameraOverride(uint32 cameraOverrideIndex) { m_cameraOverrideIndex = (int32)cameraOverrideIndex; } void ClearCameraOverride() { m_cameraOverrideIndex = -1; } // call when starting/ending the frame void BeginFrame(); void EndFrame(); // gpu resources void SetGPUContext(GPUContext *pGPUContext) { m_pGPUContext = pGPUContext; } bool CreateRendererResources(); void ReleaseRendererResources(); // draw void DrawPreviousFrameSummary(MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions); void DrawThisFrameSummary(MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions); private: // get a new section object Section *GetNewSection(); // get a gpu time query object GPUQuery *GetNewGPUTimeQuery(); // recursive cleanup of section void CleanupSectionAndChildren(Section *pSection); // draw a frame summary recursively void DrawFrameSummary(const Section *pRootSection, MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions); uint32 DrawFrameSummaryRecursive(const Section *pCurrentSection, MiniGUIContext *pGUIContext, const DrawSummaryOptions *pDrawOptions); // vars GPUContext *m_pGPUContext; bool m_gpuTimingEnabled; // resources bool m_rendererResourcesCreated; // cache of gpu time query objects PODArray<GPUQuery *> m_gpuTimeQueryCache; PODArray<GPUQuery *> m_freeGPUTimeQueries; // cache of section objects PODArray<Section *> m_sectionCache; PODArray<Section *> m_freeSections; // root section for this frame Section *m_pRootSection; // current section for this frame Section *m_pCurrentSection; // root section for previous frame Section *m_pPreviousFrameRootSection; // camera list, only accessible until the end of the frame Array< KeyValuePair<String, Camera> > m_cameraArray; int32 m_cameraOverrideIndex; }; <file_sep>/Engine/Source/Core/ChunkFileWriter.h #pragma once #include "Core/Common.h" class ByteStream; class ChunkFileWriter { public: ChunkFileWriter(); ~ChunkFileWriter(); bool Initialize(ByteStream *pStream, uint32 NumChunks); bool Close(); uint32 AddString(const char *str); void BeginChunk(uint32 ChunkIndex); void WriteChunkData(const void *pData, uint32 cbData); void EndChunk(); private: struct Chunk { uint64 Offset; uint32 Size; }; ByteStream *m_pStream; uint64 m_iBaseOffset; Chunk *m_pChunkHeaders; uint32 m_nChunks; uint32 m_iCurrentChunk; uint64 m_iCurrentChunkOffset; uint64 m_iCurrentChunkSize; char *m_pStringData; uint32 m_iStringDataSize; uint32 m_iStringDataBufferSize; uint32 m_iStringCount; };<file_sep>/Engine/Source/MathLib/Vectoru.cpp #include "MathLib/Vectoru.h" static const uint32 __uint2Zero[2] = { 0, 0 }; static const uint32 __uint2One[2] = { 1, 1 }; const Vector2u &Vector2u::Zero = reinterpret_cast<const Vector2u &>(__uint2Zero); const Vector2u &Vector2u::One = reinterpret_cast<const Vector2u &>(__uint2One); static const uint32 __uint3Zero[3] = { 0, 0, 0 }; static const uint32 __uint3One[3] = { 1, 1, 1 }; const Vector3u &Vector3u::Zero = reinterpret_cast<const Vector3u &>(__uint3Zero); const Vector3u &Vector3u::One = reinterpret_cast<const Vector3u &>(__uint3One); static const uint32 __uint4Zero[4] = { 0, 0, 0, 0 }; static const uint32 __uint4One[4] = { 1, 1, 1, 1 }; const Vector4u &Vector4u::Zero = reinterpret_cast<const Vector4u &>(__uint4Zero); const Vector4u &Vector4u::One = reinterpret_cast<const Vector4u &>(__uint4One); <file_sep>/Engine/Source/MathLib/CMakeLists.txt set(HEADER_FILES AABox.h Angle.h CollisionDetection.h Common.h Frustum.h HashTraits.h Interpolator.h Line.h Matrixf.h Plane.h Quaternion.h Ray.h SIMDMatrixf.h SIMDMatrixf_scalar.h SIMDMatrixi.h SIMDMatrixi_scalar.h SIMDVectorf.h SIMDVectorf_scalar.h SIMDVectorf_sse.h SIMDVectori.h SIMDVectori_scalar.h SIMDVectori_sse.h Sphere.h StreamOperators.h StringConverters.h Transform.h Vectorf.h Vectorh.h Vectori.h VectorShuffles.h Vectoru.h ) set(SOURCE_FILES AABox.cpp Angle.cpp CollisionDetection.cpp Frustum.cpp HashTraits.cpp Interpolator.cpp Matrixf.cpp Plane.cpp Quaternion.cpp Ray.cpp SIMDMatrixf_scalar.cpp SIMDVectorf_scalar.cpp SIMDVectorf_sse.cpp SIMDVectori_scalar.cpp SIMDVectori_sse.cpp Sphere.cpp StreamOperators.cpp StringConverters.cpp Transform.cpp Vectorf.cpp Vectorh.cpp Vectori.cpp Vectoru.cpp ) include_directories(${ENGINE_BASE_DIRECTORY}) add_library(EngineMathLib STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineMathLib YBaseLib) <file_sep>/Engine/Source/GameFramework/DirectionalLightEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/DirectionalLightEntity.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Engine/World.h" DEFINE_ENTITY_TYPEINFO(DirectionalLightEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(DirectionalLightEntity); BEGIN_ENTITY_PROPERTIES(DirectionalLightEntity) PROPERTY_TABLE_MEMBER_BOOL("Enabled", 0, offsetof(DirectionalLightEntity, m_bEnabled), OnEnabledPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT3("Color", 0, offsetof(DirectionalLightEntity, m_Color), OnColorOrBrightnessPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT("Brightness", 0, offsetof(DirectionalLightEntity, m_fBrightness), OnColorOrBrightnessPropertyChange, NULL) PROPERTY_TABLE_MEMBER_UINT("LightShadowFlags", 0, offsetof(DirectionalLightEntity, m_iLightShadowFlags), OnShadowPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT("AmbientFactor", 0, offsetof(DirectionalLightEntity, m_fAmbientFactor), OnColorOrBrightnessPropertyChange, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(DirectionalLightEntity) END_ENTITY_SCRIPT_FUNCTIONS() DirectionalLightEntity::DirectionalLightEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_bEnabled(true), m_Color(float3::One), m_fBrightness(1.0f), m_fAmbientFactor(0.2f), m_iLightShadowFlags(LIGHT_SHADOW_FLAG_CAST_STATIC_SHADOWS | LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS), m_pRenderProxy(nullptr) { // create the render proxies m_pRenderProxy = new DirectionalLightRenderProxy(GetEntityID(), m_bEnabled, float3::One, float3::Zero, m_iLightShadowFlags, CalculateLightDirection()); // setup the object bounds SetBounds(AABox::MaxSize, Sphere::MaxSize); // update colors UpdateColors(); } DirectionalLightEntity::~DirectionalLightEntity() { m_pRenderProxy->Release(); } void DirectionalLightEntity::SetEnabled(bool enabled) { m_bEnabled = enabled; OnEnabledPropertyChange(this); } void DirectionalLightEntity::SetColor(const float3 &color) { m_Color = color; OnColorOrBrightnessPropertyChange(this); } void DirectionalLightEntity::SetBrightness(float brightness) { m_fBrightness = brightness; OnColorOrBrightnessPropertyChange(this); } void DirectionalLightEntity::SetAmbientFactor(float ambientContribution) { m_fAmbientFactor = ambientContribution; UpdateColors(); } void DirectionalLightEntity::SetLightShadowFlags(uint32 lightShadowFlags) { m_iLightShadowFlags = lightShadowFlags; OnShadowPropertyChange(this); } void DirectionalLightEntity::Create(uint32 entityID, ENTITY_MOBILITY mobility /*= ENTITY_MOBILITY_MOVABLE*/, const Quaternion &rotation /*= Quaternion::Identity*/, const bool enabled /*= true*/, const float3 &color /*= float3::One*/, float brightness /*= 1.0f*/, uint32 shadowFlags /*= LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS*/, float ambientFactor /*= 0.2f*/) { m_mobility = mobility; m_transform.SetRotation(rotation); m_bEnabled = enabled; m_Color = color; m_fBrightness = brightness; m_iLightShadowFlags = shadowFlags; m_fAmbientFactor = ambientFactor; Initialize(entityID, EmptyString); } bool DirectionalLightEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; UpdateColors(); m_pRenderProxy->SetDirection(CalculateLightDirection()); return true; } void DirectionalLightEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // add render proxy to world pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void DirectionalLightEntity::OnRemoveFromWorld(World *pWorld) { // remove render proxy from world pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); BaseClass::OnRemoveFromWorld(pWorld); } void DirectionalLightEntity::OnTransformChange() { BaseClass::OnTransformChange(); m_pRenderProxy->SetDirection(CalculateLightDirection()); } float3 DirectionalLightEntity::CalculateLightDirection() { // default direction of a directional light is pointing directly down. // rotate this by the specified rotation. return m_transform.GetRotation() * float3::NegativeUnitZ; } void DirectionalLightEntity::OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetEnabled(pEntity->m_bEnabled); } void DirectionalLightEntity::OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->UpdateColors(); } void DirectionalLightEntity::OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetShadowFlags(pEntity->m_iLightShadowFlags); } void DirectionalLightEntity::UpdateColors() { float3 lightColor(m_Color); float3 directionalLightColor(lightColor * (m_fBrightness * (1.0f - m_fAmbientFactor))); float3 ambientLightColor(lightColor * (m_fBrightness * m_fAmbientFactor)); m_pRenderProxy->SetLightColor(directionalLightColor); m_pRenderProxy->SetAmbientColor(ambientLightColor); } <file_sep>/Engine/Source/MathLib/CollisionDetection.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" namespace CollisionDetection { // Tests if a point is located inside a triangle. Must provide a point, the first vertex of the triangle, the other 2 edges of the triangle, and a normal. bool PointInTriangle(const Vector3f &p, const Vector3f &v0, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal); // Ray intersection tests // Ray<->Box intersection. bool RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds); // Ray<->Box intersection with contact point. bool RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint); // Ray<->Box intersection with contact face. bool RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &inverseRayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds, float *pContactTime, CUBE_FACE *pContactFace); // Ray<->Sphere intersection with contact point. bool RayIntersectsSphere(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &sphereCenter, const float sphereRadius); bool RayIntersectsSphere(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &sphereCenter, const float sphereRadius, Vector3f &contactNormal, Vector3f &contactPoint); bool RayIntersectsPlane(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &planeNormal, const float planeDistance); bool RayIntersectsPlane(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint); bool RayIntersectsTriangle(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1); bool RayIntersectsTriangle(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, Vector3f &contactNormal, Vector3f &contactPoint); // Axis-aligned box intersection tests bool AABoxIntersectsAABox(const Vector3f &AMinBounds, const Vector3f &AMaxBounds, const Vector3f &BMinBounds, const Vector3f &BMaxBounds); bool AABoxIntersectsAABox(const Vector3f &AMinBounds, const Vector3f &AMaxBounds, const Vector3f &BMinBounds, const Vector3f &BMaxBounds, Vector3f &contactNormal, Vector3f &contactPoint); bool AABoxIntersectsSphere(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &sphereCenter, const float sphereRadius); bool AABoxIntersectsSphere(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &sphereCenter, const float sphereRadius, Vector3f &contactNormal, Vector3f &contactPoint); bool AABoxIntersectsPlane(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &planeNormal, const float planeDistance); bool AABoxIntersectsPlane(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint); bool AABoxIntersectsTriangle(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal); bool AABoxIntersectsTriangle(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal, Vector3f &contactNormal, Vector3f &contactPoint); // Sphere intersection tests bool SphereIntersectsBox(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &minBounds, const Vector3f &maxBounds); bool SphereIntersectsBox(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint); bool SphereIntersectsSphere(const Vector3f &ACenter, const float ARadius, const Vector3f &BCenter, const float BRadius); bool SphereIntersectsSphere(const Vector3f &ACenter, const float ARadius, const Vector3f &BCenter, const float BRadius, Vector3f &contactNormal, Vector3f &contactPoint); bool SphereIntersectsPlane(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &planeNormal, const float planeDistance); bool SphereIntersectsPlane(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint); bool SphereIntersectsTriangle(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal); bool SphereIntersectsTriangle(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal, Vector3f &contactNormal, Vector3f &contactPoint); // AABB Sweep float AABoxSweep(const Vector3f &movingBoxMinBounds, const Vector3f &movingBoxMaxBounds, const Vector3f &movingBoxDisplacement, const Vector3f &staticBoxMinBounds, const Vector3f &staticBoxMaxBounds); // Sphere Sweep //TODO } <file_sep>/Engine/Source/Engine/ParticleSystemModule.h #pragma once #include "Engine/ParticleSystemCommon.h" class RandomNumberGenerator; // Base affector/module type class ParticleSystemModule : public Object { DECLARE_OBJECT_TYPE_INFO(ParticleSystemModule, Object); DECLARE_OBJECT_NO_FACTORY(ParticleSystemModule); DECLARE_OBJECT_NO_PROPERTIES(ParticleSystemModule); public: ParticleSystemModule(const ObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ParticleSystemModule(); // Set properties on a new particle virtual bool CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const; // Update a list of particles virtual void UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const; // Type registration static void RegisterBuiltinModules(); }; <file_sep>/Engine/Source/Core/RandomNumberGenerator.cpp #include "Core/PrecompiledHeader.h" #include "Core/RandomNumberGenerator.h" #ifdef HAVE_SFMT #include "YBaseLib/Memory.h" #include "YBaseLib/Assert.h" #include <ctime> #include <cmath> // Pull in SFMT stuff #define SFMT_MEXP 19937 #if Y_CPU_SSE_LEVEL > 0 #define HAVE_SSE2 #endif #include "SFMT.h" static uint32 GetInitSeed() { // fixme: better seed return (uint32_t)time(NULL); } RandomNumberGenerator::RandomNumberGenerator() { AllocateState(); sfmt_init_gen_rand(m_state, GetInitSeed()); } RandomNumberGenerator::RandomNumberGenerator(uint32 seed) { AllocateState(); sfmt_init_gen_rand(m_state, seed); } RandomNumberGenerator::RandomNumberGenerator(const byte *pKey, uint32 keyLength) { AllocateState(); sfmt_init_by_array(m_state, const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(pKey)), keyLength / 4); } RandomNumberGenerator::RandomNumberGenerator(const RandomNumberGenerator &copy) { AllocateState(); Y_memcpy(m_state, copy.m_state, sizeof(sfmt_t)); } RandomNumberGenerator::~RandomNumberGenerator() { FreeState(); } void RandomNumberGenerator::AllocateState() { #if Y_CPU_SSE_LEVEL > 0 m_state = (sfmt_t *)Y_aligned_malloc(sizeof(sfmt_t), Y_SSE_ALIGNMENT); #else m_state = (sfmt_t *)Y_malloc(sizeof(sfmt_t)); #endif } void RandomNumberGenerator::FreeState() { #if Y_CPU_SSE_LEVEL > 0 Y_aligned_free(m_state); #else Y_free(m_state); #endif } void RandomNumberGenerator::Reseed() { sfmt_init_gen_rand(m_state, GetInitSeed()); } void RandomNumberGenerator::Reseed(uint32 seed) { sfmt_init_gen_rand(m_state, seed); } void RandomNumberGenerator::Reseed(const byte *pKey, uint32 keyLength) { sfmt_init_by_array(m_state, const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(pKey)), keyLength / 4); } RandomNumberGenerator &RandomNumberGenerator::operator=(const RandomNumberGenerator &copy) { Y_memcpy(m_state, copy.m_state, sizeof(sfmt_t)); return *this; } uint32 RandomNumberGenerator::NextUInt() { return sfmt_genrand_uint32(m_state); } float RandomNumberGenerator::NextUniformFloat() { return (float)sfmt_genrand_real1(m_state); } double RandomNumberGenerator::NextUniformDouble() { return sfmt_genrand_real1(m_state); } float RandomNumberGenerator::NextGaussianFloat() { float v1, v2, s; do { v1 = 2.0f * NextUniformFloat() - 1.0f; v2 = 2.0f * NextUniformFloat() - 1.0f; s = v1 * v1 + v2 * v2; } while (s >= 1.0f || s == 0.0f); float multiplier = sqrtf(-2.0f * logf(s) / s); return v1 * multiplier; } double RandomNumberGenerator::NextGaussianDouble() { double v1, v2, s; do { v1 = 2.0 * NextUniformDouble() - 1.0; v2 = 2.0 * NextUniformDouble() - 1.0; s = v1 * v1 + v2 * v2; } while (s >= 1.0 || s == 0.0); double multiplier = sqrt(-2.0 * log(s) / s); return v1 * multiplier; } int32 RandomNumberGenerator::NextRangeInt(int32 min, int32 max) { uint32 range = (uint32)(max - min); DebugAssert(range > 0); uint32 val = NextUInt() % range; return (int32)val + min; } uint32 RandomNumberGenerator::NextRangeUInt(uint32 min, uint32 max) { uint32 range = (uint32)(max - min); DebugAssert(range > 0); uint32 val = NextUInt() % range; return val + min; } float RandomNumberGenerator::NextRangeFloat(float min, float max) { return NextUniformFloat() * (max - min) + min; } double RandomNumberGenerator::NextRangeDouble(double min, double max) { return NextUniformDouble() * (max - min) + min; } bool RandomNumberGenerator::NextBoolean(float chance) { double val = NextUniformDouble(); return (val >= 0.5); } #endif // HAVE_SFMT <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphSchema.h #pragma once #include "ResourceCompiler/Common.h" #include "ResourceCompiler/ShaderGraphNode.h" struct ResourceCompilerCallbacks; class ShaderGraphSchema : public ReferenceCounted { public: // keep in mind: these declarations are in the opposite order. inputs to the shader have outputs, // and outputs from the shader have inputs from the point of the graph. // shader global declaration struct GlobalDeclaration { String Name; String DisplayName; SHADER_PARAMETER_TYPE Type; String VariableName; SHADER_GRAPH_NODE_OUTPUT OutputDesc; }; // shader input declaration struct InputDeclaration { String Name; String DisplayName; SHADER_PARAMETER_TYPE Type; struct AccessInfo { String DefineName; String VariableName; }; AccessInfo Access[SHADER_PROGRAM_STAGE_COUNT]; SHADER_GRAPH_NODE_OUTPUT OutputDesc; }; // shader output declaration struct OutputDeclaration { String Name; String DisplayName; SHADER_PROGRAM_STAGE Stage; SHADER_PARAMETER_TYPE Type; String FunctionSignature; String DefineName; String DefaultValue; SHADER_GRAPH_NODE_INPUT InputDesc; }; public: ShaderGraphSchema(); ~ShaderGraphSchema(); bool LoadFromXML(const char *FileName, ByteStream *pStream); const GlobalDeclaration *const *GetGlobalDeclarations() const { return m_globalDeclarations.GetBasePointer(); } const InputDeclaration *const *GetInputDeclarations() const { return m_inputDeclarations.GetBasePointer(); } const OutputDeclaration *const *GetOutputDeclarations() const { return m_outputDeclarations.GetBasePointer(); } const GlobalDeclaration *GetGlobalDeclaration(uint32 i) const { DebugAssert(i < m_globalDeclarations.GetSize()); return m_globalDeclarations[i]; } const InputDeclaration *GetInputDeclaration(uint32 i) const { DebugAssert(i < m_inputDeclarations.GetSize()); return m_inputDeclarations[i]; } const OutputDeclaration *GetOutputDeclaration(uint32 i) const { DebugAssert(i < m_outputDeclarations.GetSize()); return m_outputDeclarations[i]; } uint32 GetGlobalDeclarationCount() const { return m_globalDeclarations.GetSize(); } uint32 GetInputDeclarationCount() const { return m_inputDeclarations.GetSize(); } uint32 GetOutputDeclarationCount() const { return m_outputDeclarations.GetSize(); } static ShaderGraphSchema *GetSchemaForFeatureLevel(ResourceCompilerCallbacks *pCallbacks, RENDERER_FEATURE_LEVEL featureLevel); private: typedef PODArray<GlobalDeclaration *> GlobalDeclarationArray; typedef PODArray<InputDeclaration *> InputDeclarationArray; typedef PODArray<OutputDeclaration *> OutputDeclarationArray; GlobalDeclarationArray m_globalDeclarations; InputDeclarationArray m_inputDeclarations; OutputDeclarationArray m_outputDeclarations; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLDefines.h #pragma once namespace NameTables { Y_Declare_NameTable(GLErrors); } namespace OpenGLTypeConversion { void GetOpenGLVersionForRendererFeatureLevel(RENDERER_FEATURE_LEVEL featureLevel, uint32 *pMajorVersion, uint32 *pMinorVersion); RENDERER_FEATURE_LEVEL GetRendererFeatureLevelForOpenGLVersion(uint32 majorVersion, uint32 minorVersion); // shader stuff void GetOpenGLVAOTypeAndSizeForVertexElementType(GPU_VERTEX_ELEMENT_TYPE elementType, bool *pIntegerType, GLenum *pGLType, GLint *pGLSize, GLboolean *pGLNormalized); // state stuff GLenum GetOpenGLComparisonFunc(GPU_COMPARISON_FUNC ComparisonFunc); GLenum GetOpenGLComparisonMode(TEXTURE_FILTER Filter); GLenum GetOpenGLTextureMinFilter(TEXTURE_FILTER Filter); GLenum GetOpenGLTextureMagFilter(TEXTURE_FILTER Filter); GLenum GetOpenGLTextureWrap(TEXTURE_ADDRESS_MODE AddressMode); GLenum GetOpenGLPolygonMode(RENDERER_FILL_MODE FillMode); GLenum GetOpenGLCullFace(RENDERER_CULL_MODE CullMode); GLenum GetOpenGLStencilOp(RENDERER_STENCIL_OP StencilOp); GLenum GetOpenGLBlendEquation(RENDERER_BLEND_OP BlendOp); GLenum GetOpenGLBlendFunc(RENDERER_BLEND_OPTION BlendFactor); GLenum GetOpenGLTextureTarget(TEXTURE_TYPE textureType); // Convert pixel format to GL texture internalFormat, format, type bool GetOpenGLTextureFormat(PIXEL_FORMAT PixelFormat, GLint *pGLInternalFormat, GLenum *pGLFormat, GLenum *pGLType); } namespace OpenGLHelpers { GLenum GetOpenGLTextureTarget(GPUTexture *pGPUTexture); GLuint GetOpenGLTextureId(GPUTexture *pGPUTexture); void BindOpenGLTexture(GPUTexture *pGPUTexture); //void OpenGLSetUniform(GLint Location, GLsizei ArraySize, SHADER_UNIFORM_TYPE UniformType, const void *pData); void ApplySamplerStateToTexture(GLenum target, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc); void SetObjectDebugName(GLenum type, GLuint id, const char *debugName); // GL error handling void ClearLastGLError(); GLenum CheckForGLError(); GLenum GetLastGLError(); void PrintLastGLError(const char *format, ...); } // shorter macros #define GL_CHECKED_SECTION_BEGIN() (OpenGLHelpers::ClearLastGLError()) #define GL_CHECK_ERROR_STATE() (OpenGLHelpers::CheckForGLError() != GL_NO_ERROR) #define GL_PRINT_ERROR(...) OpenGLHelpers::PrintLastGLError(__VA_ARGS__) <file_sep>/Engine/Source/BaseGame/LivingEntity.cpp #include "BaseGame/PrecompiledHeader.h" #include "BaseGame/LivingEntity.h" DEFINE_ENTITY_TYPEINFO(LivingEntity, 0); BEGIN_ENTITY_PROPERTIES(LivingEntity) PROPERTY_TABLE_MEMBER_UINT("Health", 0, offsetof(LivingEntity, m_health), __PS_OnHealthChanged, nullptr) PROPERTY_TABLE_MEMBER_UINT("MaxHealth", 0, offsetof(LivingEntity, m_maxHealth), nullptr, nullptr) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(LivingEntity) END_ENTITY_SCRIPT_FUNCTIONS() LivingEntity::LivingEntity(const EntityTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_health(1), m_maxHealth(1) { } LivingEntity::~LivingEntity() { } void LivingEntity::SetHealth(uint32 health) { m_health = health; OnHealthChanged(); } void LivingEntity::SetMaxHealth(uint32 maxHealth) { m_maxHealth = maxHealth; OnHealthChanged(); } void LivingEntity::OnHealthChanged() { } void LivingEntity::OnDeath() { } void LivingEntity::OnRevive() { } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunkCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" #include "BlockEngine/BlockWorldTypes.h" class btBlockWorldChunkCollisionShape; class BlockWorldChunkCollisionShape : public Physics::CollisionShape { public: BlockWorldChunkCollisionShape(const BlockPalette *pPalette, uint32 chunkSize, const BlockWorldChunk *pChunk); virtual ~BlockWorldChunkCollisionShape(); // Virtual methods virtual const Physics::COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual Physics::CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: btBlockWorldChunkCollisionShape *m_pBulletShape; AABox m_boundingBox; }; <file_sep>/Engine/Source/ResourceCompiler/SkeletalAnimationGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/SkeletalAnimationGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/DataFormats.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(SkeletalAnimationGenerator); SkeletalAnimationGenerator::TransformTrack::TransformTrack() { } SkeletalAnimationGenerator::TransformTrack::~TransformTrack() { } const SkeletalAnimationGenerator::TransformTrack::KeyFrame *SkeletalAnimationGenerator::TransformTrack::GetKeyFrame(uint32 index) const { return (index < m_keyFrames.GetSize()) ? &m_keyFrames[index] : nullptr; } SkeletalAnimationGenerator::TransformTrack::KeyFrame *SkeletalAnimationGenerator::TransformTrack::GetKeyFrame(uint32 index) { return (index < m_keyFrames.GetSize()) ? &m_keyFrames[index] : nullptr; } SkeletalAnimationGenerator::TransformTrack::KeyFrame *SkeletalAnimationGenerator::TransformTrack::AddKeyFrame(float time, const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */) { DebugAssert(time >= 0.0f); // update duration m_duration = Max(m_duration, time); // find the position to insert at uint32 insertPosition; for (insertPosition = 0; insertPosition < m_keyFrames.GetSize(); insertPosition++) { if (time < m_keyFrames[insertPosition].GetTime()) break; } // insert at position KeyFrame newKeyFrame(time, position, rotation, scale); m_keyFrames.Insert(newKeyFrame, insertPosition); return &m_keyFrames[insertPosition]; } void SkeletalAnimationGenerator::TransformTrack::DeleteKeyFrame(uint32 index) { DebugAssert(index < m_keyFrames.GetSize()); m_keyFrames.OrderedRemove(index); } static int KeyFrameCompareFunction(const SkeletalAnimationGenerator::TransformTrack::KeyFrame *pLeft, const SkeletalAnimationGenerator::TransformTrack::KeyFrame *pRight) { return Math::CompareResult(pLeft->GetTime(), pRight->GetTime()); } void SkeletalAnimationGenerator::TransformTrack::SortKeyFrames() { m_keyFrames.Sort(KeyFrameCompareFunction); } void SkeletalAnimationGenerator::TransformTrack::UpdateDuration() { m_duration = 0.0f; for (uint32 keyFrameIndex = 0; keyFrameIndex < m_keyFrames.GetSize(); keyFrameIndex++) m_duration = Max(m_duration, m_keyFrames[keyFrameIndex].GetTime()); } const SkeletalAnimationGenerator::BoneTrack::KeyFrame *SkeletalAnimationGenerator::TransformTrack::GetKeyFrameForTime(float time) const { if (m_keyFrames.GetSize() == 1 || time < m_keyFrames[0].GetTime()) { // use first and only position return &m_keyFrames[0]; } // find the key that we reside in with a time of <= t uint32 keyIndex; for (keyIndex = 0; keyIndex < (m_keyFrames.GetSize() - 1); keyIndex++) { if (time < m_keyFrames[keyIndex + 1].GetTime()) break; } // is this the last key? uint32 nextKeyIndex = keyIndex + 1; if (nextKeyIndex == m_keyFrames.GetSize()) { // use this (last) key return &m_keyFrames[keyIndex]; } // get factor const double thisKeyTime = m_keyFrames[keyIndex].GetTime(); const double nextKeyTime = m_keyFrames[nextKeyIndex].GetTime(); const double factor = (time - thisKeyTime) / (nextKeyTime - thisKeyTime); DebugAssert(factor >= 0.0 && factor <= 1.0); // return appropriate frame if (factor < 0.5) return &m_keyFrames[keyIndex]; else return &m_keyFrames[nextKeyIndex]; } void SkeletalAnimationGenerator::TransformTrack::InterpolateKeyFrameAtTime(float time, KeyFrame *pOutKeyFrame) const { if (m_keyFrames.GetSize() == 1 || time < m_keyFrames[0].GetTime()) { // use first and only position *pOutKeyFrame = m_keyFrames[0]; return; } // find the key that we reside in with a time of <= t uint32 keyIndex; for (keyIndex = 0; keyIndex < (m_keyFrames.GetSize() - 1); keyIndex++) { if (time < m_keyFrames[keyIndex + 1].GetTime()) break; } // is this the last key? uint32 nextKeyIndex = keyIndex + 1; if (nextKeyIndex == m_keyFrames.GetSize()) { // use this (last) key *pOutKeyFrame = m_keyFrames[keyIndex]; return; } // get factor const double thisKeyTime = m_keyFrames[keyIndex].GetTime(); const KeyFrame &thisKeyFrame = m_keyFrames[keyIndex]; const double nextKeyTime = m_keyFrames[nextKeyIndex].GetTime(); const KeyFrame &nextKeyFrame = m_keyFrames[nextKeyIndex]; const float factor = static_cast<float>((time - thisKeyTime) / (nextKeyTime - thisKeyTime)); DebugAssert(factor >= 0.0 && factor <= 1.0); // factor == 0 or 1? if (Math::NearEqual(factor, 0.0f, Y_FLT_EPSILON)) { *pOutKeyFrame = m_keyFrames[keyIndex]; } else if (Math::NearEqual(factor, 1.0f, Y_FLT_EPSILON)) { *pOutKeyFrame = m_keyFrames[nextKeyIndex]; } else { pOutKeyFrame->SetTime(time); pOutKeyFrame->SetPosition(thisKeyFrame.GetPosition().Lerp(nextKeyFrame.GetPosition(), factor)); pOutKeyFrame->SetRotation(Quaternion::LinearInterpolate(thisKeyFrame.GetRotation(), nextKeyFrame.GetRotation(), factor)); pOutKeyFrame->SetScale(thisKeyFrame.GetScale().Lerp(nextKeyFrame.GetScale(), factor)); } } void SkeletalAnimationGenerator::TransformTrack::ClipKeyFrames(float startTime, float endTime) { MemArray<KeyFrame> newKeyFrames; KeyFrame newKeyFrame; // is there a frame with an exact match on the start time? bool foundExactStartFrame = false; for (uint32 i = 0; i < m_keyFrames.GetSize(); i++) { if (m_keyFrames[i].GetTime() == startTime) { foundExactStartFrame = true; break; } } // if not found, calculate the key frame at the specified start time if (!foundExactStartFrame) { InterpolateKeyFrameAtTime(startTime, &newKeyFrame); newKeyFrame.SetTime(0.0f); newKeyFrames.Add(newKeyFrame); } // add any key frames within the range to the new frame list for (uint32 i = 0; i < m_keyFrames.GetSize(); i++) { const KeyFrame &sourceKeyFrame = m_keyFrames[i]; float kfTime = sourceKeyFrame.GetTime(); if (kfTime >= startTime && kfTime <= endTime) { // calculate new time kfTime -= startTime; DebugAssert(kfTime >= 0.0f); // create new keyframe newKeyFrame.SetTime(kfTime); newKeyFrame.SetPosition(sourceKeyFrame.GetPosition()); newKeyFrame.SetRotation(sourceKeyFrame.GetRotation()); newKeyFrame.SetScale(sourceKeyFrame.GetScale()); newKeyFrames.Add(newKeyFrame); } } // swap out the arrays newKeyFrames.Shrink(); m_keyFrames.Swap(newKeyFrames); } void SkeletalAnimationGenerator::TransformTrack::Optimize() { SortKeyFrames(); // remove any frames that are doubling up on everything uint32 groupStart = 0; uint32 groupCount = 1; for (uint32 keyFrameIndex = 1; keyFrameIndex < m_keyFrames.GetSize(); ) { // same as group? if (m_keyFrames[keyFrameIndex].GetPosition().NearEqual(m_keyFrames[groupStart].GetPosition(), Y_FLT_EPSILON) && m_keyFrames[keyFrameIndex].GetRotation() == m_keyFrames[groupStart].GetRotation() && m_keyFrames[keyFrameIndex].GetScale().NearEqual(m_keyFrames[groupStart].GetScale(), Y_FLT_EPSILON)) { // increment group count groupCount++; keyFrameIndex++; continue; } // start of a new group // was the previous group large enough to clip? if (groupCount > 2) { uint32 removeCount = groupCount - 2; Log_DevPrintf("SkeletalAnimationGenerator::TransformTrack::Optimize: removing %u frames starting at %u (%.2f)", removeCount, groupStart, m_keyFrames[groupStart].GetTime()); for (uint32 i = 0; i < removeCount; i++) m_keyFrames.OrderedRemove(groupStart + 1); // reset counter back to start groupStart = 0; groupCount = 1; keyFrameIndex = 1; continue; } // update group state groupStart = keyFrameIndex; groupCount = 1; keyFrameIndex++; continue; } // was this a group that didn't end? if (groupCount > 2) { uint32 removeCount = groupCount - 2; Log_DevPrintf("SkeletalAnimationGenerator::TransformTrack::Optimize: removing %u frames starting at %u (%.2f)", removeCount, groupStart, m_keyFrames[groupStart].GetTime()); for (uint32 i = 0; i < removeCount; i++) m_keyFrames.OrderedRemove(groupStart + 1); } } SkeletalAnimationGenerator::BoneTrack::BoneTrack(const char *boneName) : TransformTrack(), m_boneName(boneName) { } SkeletalAnimationGenerator::BoneTrack::~BoneTrack() { } SkeletalAnimationGenerator::RootMotionTrack::RootMotionTrack() : TransformTrack() { } SkeletalAnimationGenerator::RootMotionTrack::~RootMotionTrack() { } SkeletalAnimationGenerator::SkeletalAnimationGenerator() : m_pRootMotionTrack(nullptr) { } SkeletalAnimationGenerator::~SkeletalAnimationGenerator() { delete m_pRootMotionTrack; for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) delete m_boneTracks[i]; } const String &SkeletalAnimationGenerator::GetPreviewMeshName() const { return m_properties.GetPropertyValueDefaultString("PreviewMeshName"); } void SkeletalAnimationGenerator::SetPreviewMeshName(const char *previewMeshName) { m_properties.SetPropertyValue("PreviewMeshName", previewMeshName); } void SkeletalAnimationGenerator::UpdateDuration() { m_duration = 0.0f; for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) m_duration = Max(m_duration, m_boneTracks[i]->GetDuration()); } const SkeletalAnimationGenerator::BoneTrack *SkeletalAnimationGenerator::GetBoneTrackByName(const char *boneName) const { for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { if (m_boneTracks[i]->GetBoneName().Compare(boneName)) return m_boneTracks[i]; } return nullptr; } SkeletalAnimationGenerator::BoneTrack *SkeletalAnimationGenerator::GetBoneTrackByName(const char *boneName) { for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { if (m_boneTracks[i]->GetBoneName().Compare(boneName)) return m_boneTracks[i]; } return nullptr; } void SkeletalAnimationGenerator::AddBoneTrack(BoneTrack *boneTrack) { Assert(GetBoneTrackByName(boneTrack->GetBoneName()) == nullptr); m_boneTracks.Add(boneTrack); m_duration = Max(m_duration, boneTrack->GetDuration()); } SkeletalAnimationGenerator::BoneTrack *SkeletalAnimationGenerator::CreateBoneTrack(const char *boneName) { for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { if (m_boneTracks[i]->GetBoneName().Compare(boneName)) return nullptr; } BoneTrack *track = new BoneTrack(boneName); m_boneTracks.Add(track); return track; } void SkeletalAnimationGenerator::RemoveBoneTrack(BoneTrack *boneTrack) { int32 index = m_boneTracks.IndexOf(boneTrack); Assert(index >= 0); m_boneTracks.OrderedRemove((uint32)index); } SkeletalAnimationGenerator::RootMotionTrack *SkeletalAnimationGenerator::AddRootMotionTrack() { delete m_pRootMotionTrack; m_pRootMotionTrack = new RootMotionTrack(); return m_pRootMotionTrack; } void SkeletalAnimationGenerator::DeleteRootMotionTrack() { delete m_pRootMotionTrack; m_pRootMotionTrack = nullptr; } void SkeletalAnimationGenerator::ClipAnimation(float startTime, float endTime) { // clip bone tracks for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) m_boneTracks[i]->ClipKeyFrames(startTime, endTime); // clip root motion track if (m_pRootMotionTrack != nullptr) m_pRootMotionTrack->ClipKeyFrames(startTime, endTime); } void SkeletalAnimationGenerator::Optimize(bool removeEmptyTracks /* = true */, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { pProgressCallbacks->SetProgressRange(m_boneTracks.GetSize()); pProgressCallbacks->SetProgressValue(0); for (uint32 i = 0; i < m_boneTracks.GetSize();) { pProgressCallbacks->SetProgressValue(i); BoneTrack *track = m_boneTracks[i]; uint32 oldKeyFrameCount = track->GetKeyFrameCount(); track->Optimize(); track->UpdateDuration(); uint32 newKeyFrameCount = track->GetKeyFrameCount(); pProgressCallbacks->DisplayFormattedInformation("SkeletalAnimationGenerator::Optimize: Bone '%s' from %u frames to %u frames", track->GetBoneName().GetCharArray(), oldKeyFrameCount, newKeyFrameCount); if (newKeyFrameCount == 0 && removeEmptyTracks) { m_boneTracks.OrderedRemove(i); delete track; continue; } else { i++; continue; } } if (m_pRootMotionTrack != nullptr) m_pRootMotionTrack->Optimize(); UpdateDuration(); } bool SkeletalAnimationGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) return false; if (!xmlReader.SkipToElement("skeletal-animation")) { xmlReader.PrintError("could not skip to skeletal-animation element."); return false; } // get skeleton name const char *skeletonNameStr = xmlReader.FetchAttribute("skeleton"); if (skeletonNameStr == nullptr) { xmlReader.PrintError("missing attributes"); return false; } // set skeleton name m_skeletonName = skeletonNameStr; // move to element if (!xmlReader.MoveToElement()) return false; // process xml nodes for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 skeletalAnimationSelection = xmlReader.Select("properties|bone-track|root-motion-track"); if (skeletalAnimationSelection < 0) return false; switch (skeletalAnimationSelection) { // properties case 0: { if (!xmlReader.IsEmptyElement()) { if (!m_properties.LoadFromXML(xmlReader)) return false; if (!xmlReader.ExpectEndOfElementName("properties")) return false; } } break; // bone-track case 1: { const char *boneName = xmlReader.FetchAttribute("bone"); if (boneName == nullptr) { xmlReader.PrintError("missing attributes for bone track"); return false; } if (GetBoneTrackByName(boneName) != nullptr) { xmlReader.PrintError("duplicate bone track: %s", boneName); return false; } // create it BoneTrack *boneTrack = new BoneTrack(boneName); m_boneTracks.Add(boneTrack); // add bones if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 keyframesSelection = xmlReader.Select("keyframe"); if (keyframesSelection < 0) return false; switch (keyframesSelection) { // keyframe case 0: { const char *timeStr = xmlReader.FetchAttribute("time"); const char *positionStr = xmlReader.FetchAttribute("position"); const char *rotationStr = xmlReader.FetchAttribute("rotation"); const char *scaleStr = xmlReader.FetchAttribute("scale"); if (timeStr == nullptr || positionStr == nullptr || rotationStr == nullptr || scaleStr == nullptr) { xmlReader.PrintError("missing keyframe attributes"); return false; } // parse it float kfTime = StringConverter::StringToFloat(timeStr); float3 kfPosition(StringConverter::StringToFloat3(positionStr)); Quaternion kfRotation(StringConverter::StringToQuaternion(rotationStr)); float3 kfScale(StringConverter::StringToFloat3(scaleStr)); // validate it if (kfTime < 0.0f) { xmlReader.PrintError("invalid keyframe"); return false; } // create keyframe and add it to the list BoneTrack::KeyFrame keyFrame(kfTime, kfPosition, kfRotation, kfScale); boneTrack->m_keyFrames.Add(keyFrame); // skip element if it has contents if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "bone-track") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } // sort keyframes, and update the duration boneTrack->SortKeyFrames(); boneTrack->UpdateDuration(); } break; // root-motion-track case 2: { if (m_pRootMotionTrack != nullptr) { xmlReader.PrintError("duplicate root motion track"); return false; } // create it RootMotionTrack *rootMotionTrack = new RootMotionTrack(); m_pRootMotionTrack = rootMotionTrack; // add bones if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 keyframesSelection = xmlReader.Select("keyframe"); if (keyframesSelection < 0) return false; switch (keyframesSelection) { // keyframe case 0: { const char *timeStr = xmlReader.FetchAttribute("time"); const char *positionStr = xmlReader.FetchAttribute("position"); const char *rotationStr = xmlReader.FetchAttribute("rotation"); const char *scaleStr = xmlReader.FetchAttribute("scale"); if (timeStr == nullptr || positionStr == nullptr || rotationStr == nullptr || scaleStr == nullptr) { xmlReader.PrintError("missing keyframe attributes"); return false; } // parse it float kfTime = StringConverter::StringToFloat(timeStr); float3 kfPosition(StringConverter::StringToFloat3(positionStr)); Quaternion kfRotation(StringConverter::StringToQuaternion(rotationStr)); float3 kfScale(StringConverter::StringToFloat3(scaleStr)); // validate it if (kfTime < 0.0f) { xmlReader.PrintError("invalid keyframe"); return false; } // create keyframe and add it to the list BoneTrack::KeyFrame keyFrame(kfTime, kfPosition, kfRotation, kfScale); rootMotionTrack->m_keyFrames.Add(keyFrame); // skip element if it has contents if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "root-motion-track") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } // sort keyframes, and update the duration rootMotionTrack->SortKeyFrames(); rootMotionTrack->UpdateDuration(); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "skeletal-animation") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } UpdateDuration(); return true; } bool SkeletalAnimationGenerator::SaveToXML(ByteStream *pStream) const { XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("skeletal-animation"); xmlWriter.WriteAttribute("skeleton", m_skeletonName); // write properties xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); // write bone tracks for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { const BoneTrack *boneTrack = m_boneTracks[i]; xmlWriter.StartElement("bone-track"); xmlWriter.WriteAttribute("bone", boneTrack->GetBoneName()); { // keyframes for (uint32 j = 0; j < boneTrack->m_keyFrames.GetSize(); j++) { const BoneTrack::KeyFrame *keyFrame = &boneTrack->m_keyFrames[j]; xmlWriter.StartElement("keyframe"); { xmlWriter.WriteAttribute("time", StringConverter::FloatToString(keyFrame->GetTime())); xmlWriter.WriteAttribute("position", StringConverter::Float3ToString(keyFrame->GetPosition())); xmlWriter.WriteAttribute("rotation", StringConverter::QuaternionToString(keyFrame->GetRotation())); xmlWriter.WriteAttribute("scale", StringConverter::Float3ToString(keyFrame->GetScale())); } xmlWriter.EndElement(); // </keyframe> } } xmlWriter.EndElement(); // </bone-track> } // write root motion track if (m_pRootMotionTrack != nullptr) { xmlWriter.StartElement("root-motion-track"); { // keyframes for (uint32 i = 0; i < m_pRootMotionTrack->m_keyFrames.GetSize(); i++) { const BoneTrack::KeyFrame *keyFrame = &m_pRootMotionTrack->m_keyFrames[i]; xmlWriter.StartElement("keyframe"); { xmlWriter.WriteAttribute("time", StringConverter::FloatToString(keyFrame->GetTime())); xmlWriter.WriteAttribute("position", StringConverter::Float3ToString(keyFrame->GetPosition())); xmlWriter.WriteAttribute("rotation", StringConverter::QuaternionToString(keyFrame->GetRotation())); xmlWriter.WriteAttribute("scale", StringConverter::Float3ToString(keyFrame->GetScale())); } xmlWriter.EndElement(); // </keyframe> } } xmlWriter.EndElement(); // </root-motion-track> } xmlWriter.EndElement(); // </skeletal-animation> return (!xmlWriter.InErrorState() && !pStream->InErrorState()); } void SkeletalAnimationGenerator::Copy(const SkeletalAnimationGenerator *pCopy) { for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) delete m_boneTracks[i]; m_boneTracks.Obliterate(); delete m_pRootMotionTrack; m_pRootMotionTrack = nullptr; m_skeletonName = pCopy->m_skeletonName; m_duration = pCopy->m_duration; for (uint32 i = 0; i < pCopy->m_boneTracks.GetSize(); i++) { BoneTrack *boneTrack = new BoneTrack(pCopy->m_boneTracks[i]->GetBoneName()); boneTrack->m_duration = pCopy->m_boneTracks[i]->m_duration; boneTrack->m_keyFrames.Assign(pCopy->m_boneTracks[i]->m_keyFrames); m_boneTracks.Add(boneTrack); } if (pCopy->m_pRootMotionTrack != nullptr) { m_pRootMotionTrack = new RootMotionTrack(); m_pRootMotionTrack->m_duration = pCopy->m_pRootMotionTrack->m_duration; m_pRootMotionTrack->m_keyFrames.Assign(pCopy->m_pRootMotionTrack->m_keyFrames); } } // we use recursion-based transform concatenation to preserve as much floating-point accuracy as possible // static Transform CalculateAbsoluteBoneBaseFrameTransform(const Skeleton::Bone *pBone, const Transform *pTransformArray) // { // if (pBone->GetParentBone() == nullptr) // return pTransformArray[pBone->GetIndex()]; // // return Transform::ConcatenateTransforms(CalculateAbsoluteBoneBaseFrameTransform(pBone->GetParentBone()), pTransformArray[pBone->GetIndex()]); // } static float4x4 CalculateAbsoluteBoneBaseFrameTransform(const Skeleton::Bone *pBone, const Transform *pTransformArray) { if (pBone->GetParentBone() == nullptr) return pTransformArray[pBone->GetIndex()].GetTransformMatrix4x4(); else return CalculateAbsoluteBoneBaseFrameTransform(pBone->GetParentBone(), pTransformArray) * pTransformArray[pBone->GetIndex()].GetTransformMatrix4x4(); } bool SkeletalAnimationGenerator::Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream, bool optimize /* = true */) const { if (optimize) { SkeletalAnimationGenerator animationCopy; animationCopy.Copy(this); animationCopy.Optimize(true); return animationCopy.InternalCompile(pCallbacks, pStream); } else { return InternalCompile(pCallbacks, pStream); } } bool SkeletalAnimationGenerator::InternalCompile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const { if (m_skeletonName.IsEmpty() || (m_boneTracks.GetSize() == 0)) { Log_ErrorPrintf("SkeletalAnimationGenerator::InternalCompile: Incomplete animation."); return false; } // load the skeleton we're using AutoReleasePtr<const Skeleton> pSkeleton = pCallbacks->GetCompiledSkeleton(m_skeletonName); if (pSkeleton == nullptr) { Log_ErrorPrintf("SkeletalAnimationGenerator::InternalCompile: Could not load Skeleton '%s'", m_skeletonName.GetCharArray()); return false; } // build header DF_SKELETALANIMATION_HEADER fileHeader; fileHeader.Magic = DF_SKELETALANIMATION_HEADER_MAGIC; fileHeader.HeaderSize = sizeof(fileHeader); fileHeader.Flags = 0; fileHeader.SkeletonNameLength = m_skeletonName.GetLength(); fileHeader.SkeletonNameOffset = 0xFFFFFFFF; fileHeader.SkeletonBoneCount = pSkeleton->GetBoneCount(); fileHeader.Duration = m_duration; fileHeader.BoneTrackCount = 0; fileHeader.BoneTrackOffset = 0; fileHeader.RootMotionOffset = 0; // write header uint64 headerOffset = pStream->GetPosition(); if (!pStream->Write2(&fileHeader, sizeof(fileHeader))) return false; // write skeleton name fileHeader.SkeletonNameOffset = (uint32)(pStream->GetPosition() - headerOffset); if (!pStream->Write2(m_skeletonName.GetCharArray(), m_skeletonName.GetLength())) return false; // write bone tracks if (m_boneTracks.GetSize() > 0) { fileHeader.BoneTrackOffset = (uint32)(pStream->GetPosition() - headerOffset); for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { const BoneTrack *pBoneTrack = m_boneTracks[i]; const Skeleton::Bone *pBone = pSkeleton->GetBoneByName(pBoneTrack->GetBoneName()); if (pBone == nullptr) { Log_ErrorPrintf("SkeletalAnimationGenerator::Compile: Animation references bone '%s' not found in skeleton.", pBoneTrack->GetBoneName().GetCharArray()); return false; } // skip empty tracks if (pBoneTrack->GetKeyFrameCount() == 0) continue; // first keyframe should always have a time of zero if (pBoneTrack->GetKeyFrame(0)->GetTime() != 0.0f) { Log_ErrorPrintf("SkeletalAnimationGenerator::Compile: Bone '%s' does not have a keyframe at 0 seconds.", pBoneTrack->GetBoneName().GetCharArray()); return false; } // create bone track header DF_SKELETALANIMATION_BONE_TRACK_HEADER boneTrackHeader; boneTrackHeader.BoneIndex = pBone->GetIndex(); boneTrackHeader.Duration = pBoneTrack->GetDuration(); boneTrackHeader.KeyFrameCount = pBoneTrack->GetKeyFrameCount(); if (!pStream->Write2(&boneTrackHeader, sizeof(boneTrackHeader))) return false; // write keyframes for (uint32 keyFrameIndex = 0; keyFrameIndex < pBoneTrack->GetKeyFrameCount(); keyFrameIndex++) { const BoneTrack::KeyFrame *pKeyFrame = pBoneTrack->GetKeyFrame(keyFrameIndex); if (!InternalWriteTransformKeyFrame(pStream, pKeyFrame)) return false; } // increment bone track count fileHeader.BoneTrackCount++; } // reset offset if no tracks were written if (fileHeader.BoneTrackCount == 0) fileHeader.BoneTrackOffset = 0; } // write root motion track if (m_pRootMotionTrack != nullptr) { fileHeader.RootMotionOffset = (uint32)(pStream->GetPosition() - headerOffset); DF_SKELETALANIMATION_ROOT_MOTION_TRACK_HEADER rootMotionTrackHeader; rootMotionTrackHeader.Duration = m_pRootMotionTrack->GetDuration(); rootMotionTrackHeader.KeyFrameCount = m_pRootMotionTrack->GetKeyFrameCount(); if (!pStream->Write2(&rootMotionTrackHeader, sizeof(rootMotionTrackHeader))) return false; // write keyframes for (uint32 keyFrameIndex = 0; keyFrameIndex < m_pRootMotionTrack->GetKeyFrameCount(); keyFrameIndex++) { const BoneTrack::KeyFrame *pKeyFrame = m_pRootMotionTrack->GetKeyFrame(keyFrameIndex); if (!InternalWriteTransformKeyFrame(pStream, pKeyFrame)) return false; } } // rewrite header uint64 endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(headerOffset) || !pStream->Write2(&fileHeader, sizeof(fileHeader)) || !pStream->SeekAbsolute(endOffset)) return false; // done return true; } bool SkeletalAnimationGenerator::InternalWriteTransformKeyFrame(ByteStream *pStream, const TransformTrack::KeyFrame *pKeyFrame) { DF_SKELETALANIMATION_TRANSFORM_TRACK_KEYFRAME fileKeyFrame; fileKeyFrame.Time = pKeyFrame->GetTime(); fileKeyFrame.Position[0] = pKeyFrame->GetPosition().x; fileKeyFrame.Position[1] = pKeyFrame->GetPosition().y; fileKeyFrame.Position[2] = pKeyFrame->GetPosition().z; fileKeyFrame.Rotation[0] = pKeyFrame->GetRotation().x; fileKeyFrame.Rotation[1] = pKeyFrame->GetRotation().y; fileKeyFrame.Rotation[2] = pKeyFrame->GetRotation().z; fileKeyFrame.Rotation[3] = pKeyFrame->GetRotation().w; fileKeyFrame.Scale[0] = pKeyFrame->GetScale().x; fileKeyFrame.Scale[1] = pKeyFrame->GetScale().y; fileKeyFrame.Scale[2] = pKeyFrame->GetScale().z; return pStream->Write2(&fileKeyFrame, sizeof(fileKeyFrame)); } void SkeletalAnimationGenerator::GenerateKeyFrameTimeList(PODArray<float> *pKeyFrameTimeArray) const { for (uint32 i = 0; i < m_boneTracks.GetSize(); i++) { const BoneTrack *boneTrack = m_boneTracks[i]; for (uint32 j = 0; j < boneTrack->GetKeyFrameCount(); j++) { float keyFrameTime = boneTrack->GetKeyFrame(j)->GetTime(); if (pKeyFrameTimeArray->IndexOf(keyFrameTime) < 0) pKeyFrameTimeArray->Add(keyFrameTime); } } pKeyFrameTimeArray->SortCB([](float pLeft, float pRight) { return Math::CompareResult(pLeft, pRight); }); } // Interface BinaryBlob *ResourceCompiler::CompileSkeletalAnimation(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.ska.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileSkeletalAnimation: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); SkeletalAnimationGenerator *pGenerator = new SkeletalAnimationGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pCallbacks, pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Editor/Source/Editor/EditorProgressCallbacks.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorProgressCallbacks.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" Log_SetChannel(EditorProgressDialog); EditorProgressCallbacks::EditorProgressCallbacks(QWidget *parentWidgetForPopups) : m_pParentWidgetForPopups(parentWidgetForPopups) { } EditorProgressCallbacks::~EditorProgressCallbacks() { } void EditorProgressCallbacks::ModalError(const char *message) { g_pEditor->BlockFrameExecution(); QMessageBox::critical(m_pParentWidgetForPopups, QStringLiteral("Error"), message, QMessageBox::Ok, QMessageBox::Ok); g_pEditor->UnblockFrameExecution(); g_pEditor->ProcessBackgroundEvents(); } bool EditorProgressCallbacks::ModalConfirmation(const char *message) { g_pEditor->BlockFrameExecution(); bool result = (QMessageBox::question(m_pParentWidgetForPopups, QStringLiteral("Question"), message, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes); g_pEditor->UnblockFrameExecution(); g_pEditor->ProcessBackgroundEvents(); return result; } uint32 EditorProgressCallbacks::ModalPrompt(const char *message, uint32 nOptions, ...) { DebugAssert(nOptions > 0 && nOptions < 5); va_list ap; va_start(ap, nOptions); QMessageBox messageBox(m_pParentWidgetForPopups); switch (nOptions) { case 4: messageBox.addButton(va_arg(ap, const char *), QMessageBox::NoRole); case 3: messageBox.addButton(va_arg(ap, const char *), QMessageBox::NoRole); case 2: messageBox.addButton(va_arg(ap, const char *), QMessageBox::NoRole); case 1: messageBox.addButton(va_arg(ap, const char *), QMessageBox::NoRole); break; } g_pEditor->BlockFrameExecution(); uint32 result = (uint32)messageBox.exec(); g_pEditor->UnblockFrameExecution(); g_pEditor->ProcessBackgroundEvents(); return result; } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUBuffer.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUBuffer.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" Log_SetChannel(OpenGLES2RenderBackend); OpenGLES2GPUBuffer::OpenGLES2GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, GLuint glBufferId, GLenum glBufferTarget, GLenum glBufferUsage) : GPUBuffer(pBufferDesc), m_glBufferId(glBufferId), m_glBufferTarget(glBufferTarget), m_glBufferUsage(glBufferUsage) { } OpenGLES2GPUBuffer::~OpenGLES2GPUBuffer() { glDeleteBuffers(1, &m_glBufferId); } void OpenGLES2GPUBuffer::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = m_desc.Size; } void OpenGLES2GPUBuffer::SetDebugName(const char *debugName) { OpenGLES2Helpers::SetObjectDebugName(GL_BUFFER, m_glBufferId, debugName); } GPUBuffer *OpenGLES2GPUDevice::CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData /* = NULL */) { // find target GLenum bufferTarget; if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER) bufferTarget = GL_ARRAY_BUFFER; else if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_INDEX_BUFFER) bufferTarget = GL_ELEMENT_ARRAY_BUFFER; else { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateBuffer: Buffer target unknown for flags %u", pDesc->Flags); return nullptr; } // find usage GLenum bufferUsage; if (pDesc->Flags & GPU_BUFFER_FLAG_MAPPABLE) { bufferUsage = GL_DYNAMIC_DRAW; } else if (pDesc->Flags & (GPU_BUFFER_FLAG_READABLE | GPU_BUFFER_FLAG_WRITABLE)) { bufferUsage = GL_STREAM_DRAW; } else { DebugAssert(pInitialData != NULL); bufferUsage = GL_STATIC_DRAW; } // allocate buffer GL_CHECKED_SECTION_BEGIN(); GLuint bufferId = 0; glGenBuffers(1, &bufferId); if (bufferId == 0) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateBuffer: Buffer allocation failed."); return NULL; } // allocate buffer storage glBindBuffer(bufferTarget, bufferId); glBufferData(bufferTarget, pDesc->Size, pInitialData, bufferUsage); glBindBuffer(bufferTarget, 0); // check error state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateBuffer: One or more GL calls failed."); if (bufferId != 0) glDeleteBuffers(1, &bufferId); return NULL; } // create object return new OpenGLES2GPUBuffer(pDesc, bufferId, bufferTarget, bufferUsage); } bool OpenGLES2GPUContext::ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) { Log_ErrorPrint("OpenGLES2GPUContext::ReadBuffer: Unsupported on GLES"); return false; } bool OpenGLES2GPUContext::WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) { OpenGLES2GPUBuffer *pOpenGLBuffer = static_cast<OpenGLES2GPUBuffer *>(pBuffer); DebugAssert((start + count) <= pOpenGLBuffer->GetDesc()->Size); GL_CHECKED_SECTION_BEGIN(); glBindBuffer(pOpenGLBuffer->GetGLBufferTarget(), pOpenGLBuffer->GetGLBufferId()); glBufferSubData(pOpenGLBuffer->GetGLBufferTarget(), start, count, pSource); glBindBuffer(pOpenGLBuffer->GetGLBufferTarget(), 0); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("D3D11GPUContext::ReadBuffer: One or more GL calls failed."); return false; } return true; } bool OpenGLES2GPUContext::MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) { Log_ErrorPrint("OpenGLES2GPUContext::MapBuffer: Unsupported on GLES"); return false; } void OpenGLES2GPUContext::Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) { Log_ErrorPrint("OpenGLES2GPUContext::UnmapBuffer: Unsupported on GLES"); } <file_sep>/Engine/Source/MapCompiler/MapSource.cpp #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "YBaseLib/ZipArchive.h" Log_SetChannel(MapSource); static const int32 GLOBAL_REGION_COORDINATE = Y_INT32_MAX; static const int32 UNALLOCATED_REGION_COORDINATE = Y_INT32_MAX - 1; static const char *MAP_CLASS_NAME_FOR_TEMPLATE = "Map"; MapSource::MapSource() : m_pMapArchive(nullptr), m_isChanged(false), m_version(0), m_regionSize(0), m_regionLODLevels(1), m_pObjectTemplate(nullptr), m_nextEntitySuffix(1), m_entityListChanged(false), m_pTerrainData(nullptr) { } MapSource::~MapSource() { delete m_pTerrainData; delete m_pMapArchive; } bool MapSource::IsEntitiesChanged() const { if (m_entityListChanged) return true; for (EntityTable::ConstIterator itr = m_entities.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value->IsChanged()) return true; } return false; } bool MapSource::IsChanged() const { if (m_isChanged) return true; // terrain if (m_pTerrainData != NULL && m_pTerrainData->IsChanged()) return true; // entities if (IsEntitiesChanged()) return true; return false; } void MapSource::Create(uint32 regionSize /* = 1024 */) { SetDefaults(); DebugAssert(regionSize > 0 && regionSize < Y_INT32_MAX); m_regionSize = regionSize; m_isChanged = true; m_nextEntitySuffix = 1; m_entityListChanged = true; // set some default properties m_pObjectTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(MAP_CLASS_NAME_FOR_TEMPLATE); if (m_pObjectTemplate == nullptr) Log_WarningPrintf("MapSource::Create: failed to get map object template"); else m_properties.CreateFromTemplate(m_pObjectTemplate->GetPropertyTemplate()); } bool MapSource::Load(const char *fileName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { m_filename = fileName; FileSystem::BuildOSPath(m_filename); AutoReleasePtr<ByteStream> pStream; pStream = FileSystem::OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == NULL) { Log_ErrorPrintf("MapSource::Load: Could not open '%s'", fileName); return false; } return LoadFromStream(pStream, pProgressCallbacks); } bool MapSource::LoadFromStream(ByteStream *pArchiveStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // init progress pProgressCallbacks->SetStatusText("Reading main file..."); pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetProgressRange(1); pProgressCallbacks->SetProgressValue(0); // open zip if ((m_pMapArchive = ZipArchive::OpenArchiveReadOnly(pArchiveStream)) == NULL) { Log_ErrorPrintf("MapSource::LoadFromStream: Failed to parse zipfile."); return false; } // set defaults SetDefaults(); // set up template m_pObjectTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(MAP_CLASS_NAME_FOR_TEMPLATE); if (m_pObjectTemplate == nullptr) Log_WarningPrintf("MapSource::LoadFromStream: failed to get map object template"); // open up map.xml { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile("map.xml", BYTESTREAM_OPEN_READ); if (pStream == NULL) { Log_ErrorPrintf("Could not create open map.xml"); return false; } // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, "map.xml")) { Log_ErrorPrintf("Could not create xml reader for map.xml"); return false; } // skip to map if (!xmlReader.SkipToElement("map")) { xmlReader.PrintError("could not skip to 'map' element"); return false; } // read version m_version = Y_strtouint32(xmlReader.FetchAttributeDefault("version", "0")); if (m_version != 5) { xmlReader.PrintError("invalid version"); return false; } // region size m_regionSize = StringConverter::StringToUInt32(xmlReader.FetchAttributeDefault("region-size", "0")); if (m_regionSize < 64 || m_regionSize > 16777216) { xmlReader.PrintError("invalid region size"); return false; } // region lod count m_regionLODLevels = StringConverter::StringToUInt32(xmlReader.FetchAttributeDefault("region-lod-levels", "1")); if (m_regionLODLevels < 1 || m_regionLODLevels > 16) { xmlReader.PrintError("invalid region lod levels"); return false; } // read elements if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) break; int32 mapSelection; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { mapSelection = xmlReader.Select("properties|regions|global-entities"); if (mapSelection < 0) return false; switch (mapSelection) { // properties case 0: { if (!xmlReader.IsEmptyElement()) { if (!m_properties.LoadFromXML(xmlReader)) { xmlReader.PrintError("failed to parse properties"); return false; } DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "properties") == 0); } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(!Y_stricmp(xmlReader.GetNodeName(), "map")); break; } } } } // load entities if (!LoadEntities(pProgressCallbacks)) return false; // load terrain if present if (!LoadTerrain(pProgressCallbacks)) return false; pProgressCallbacks->SetProgressValue(1); return true; } bool MapSource::Save(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { PathString fileName; SmallString tempString; bool destroyArchiveOnFailure = false; Assert(m_filename.GetLength() > 0); // setup progress pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetProgressRange(6); pProgressCallbacks->SetProgressValue(0); pProgressCallbacks->SetStatusText("Opening destination map..."); // open this file, using atomic updates the preserve the original for now AutoReleasePtr<ByteStream> pArchiveStream = FileSystem::OpenFile(m_filename, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pArchiveStream == NULL) { Log_ErrorPrintf("MapSource::Save: Could not open '%s'", m_filename.GetCharArray()); return false; } if (m_pMapArchive != NULL) { // upgrade the zip archive to a writable archive if (!m_pMapArchive->UpgradeToWritableArchive(pArchiveStream)) { pArchiveStream->Discard(); return false; } } else { // map has not been saved once yet, so create the archive if ((m_pMapArchive = ZipArchive::CreateArchive(pArchiveStream)) == NULL) { pArchiveStream->Discard(); return false; } // we should destroy it on failure destroyArchiveOnFailure = true; } pProgressCallbacks->SetProgressValue(1); pProgressCallbacks->SetStatusText("Writing map header..."); // save map.xml if anything has changed { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile("map.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE); if (pStream == NULL) goto FAILURE; XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) goto FAILURE; // write header xmlWriter.StartElement("map"); { xmlWriter.WriteAttributef("version", "%u", m_version); xmlWriter.WriteAttributef("region-size", "%u", m_regionSize); xmlWriter.WriteAttributef("region-lod-levels", "%u", m_regionLODLevels); // write properties xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); } xmlWriter.EndElement(); if (xmlWriter.InErrorState()) { xmlWriter.Close(); goto FAILURE; } xmlWriter.Close(); } pProgressCallbacks->SetProgressValue(2); // write entities { pProgressCallbacks->SetStatusText("Writing entities..."); pProgressCallbacks->PushState(); if (IsEntitiesChanged() && !SaveEntities(pProgressCallbacks)) { pProgressCallbacks->PopState(); goto FAILURE; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(3); } // write terrain { pProgressCallbacks->SetStatusText("Writing terrain..."); pProgressCallbacks->PushState(); if (!SaveTerrain(pProgressCallbacks)) { pProgressCallbacks->PopState(); goto FAILURE; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(4); } // commit the changes to zip pProgressCallbacks->SetStatusText("Commiting to archive..."); if (!m_pMapArchive->CommitChanges()) goto FAILURE; // read stream should now be closed, so we can commit the updated zip if (!pArchiveStream->Commit()) { Log_ErrorPrintf("MapSource::Save: Failed to commit the archive stream."); goto FAILURE_DISCARD; } // clear all the flags m_isChanged = false; pProgressCallbacks->SetProgressValue(6); return true; FAILURE: m_pMapArchive->DiscardChanges(); FAILURE_DISCARD: if (destroyArchiveOnFailure) { delete m_pMapArchive; m_pMapArchive = NULL; } pArchiveStream->Discard(); return false; } bool MapSource::SaveAs(const char *newFileName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // preserve old filename String oldFileName = m_filename; // alter it, and save m_filename = newFileName; FileSystem::BuildOSPath(m_filename); if (!Save(pProgressCallbacks)) { // revert to old filename m_filename = oldFileName; return false; } return true; } bool MapSource::LoadEntities(ProgressCallbacks *pProgressCallbacks) { static const char *FILENAME = "entities.xml"; AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { // entities should exist even if there are no entities pProgressCallbacks->DisplayError("Could not open entities.xml"); return false; } // progress pProgressCallbacks->SetStatusText("Loading entities..."); pProgressCallbacks->UpdateProgressFromStream(pStream); // create reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FILENAME)) return false; // skip to map if (!xmlReader.SkipToElement("entities")) { xmlReader.PrintError("could not skip to 'entities' element"); return false; } // load the next suffix attribute const char *nextStuffixStr = xmlReader.FetchAttribute("next-entity-suffix"); if (nextStuffixStr == nullptr) { xmlReader.PrintError("missing next-entity-suffix attribute"); return false; } m_nextEntitySuffix = StringConverter::StringToUInt32(nextStuffixStr); // read elements if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("entity") != 0) return false; MapSourceEntityData *pEntityData = new MapSourceEntityData(); if (!pEntityData->LoadFromXML(xmlReader)) { delete pEntityData; return false; } DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "entity") == 0); // search for entity with this name in map if (m_entities.Find(pEntityData->GetEntityName()) != nullptr) { xmlReader.PrintError("entity with name '%s' already exists", pEntityData->GetEntityName().GetCharArray()); delete pEntityData; return false; } // insert into map m_entities.Insert(pEntityData->GetEntityName(), pEntityData); } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "entities") == 0); break; } pProgressCallbacks->UpdateProgressFromStream(pStream); } } pProgressCallbacks->UpdateProgressFromStream(pStream); return true; } bool MapSource::SaveEntities(ProgressCallbacks *pProgressCallbacks) const { static const char *FILENAME = "entities.xml"; pProgressCallbacks->SetStatusText("Saving entities..."); pProgressCallbacks->SetProgressRange(m_entities.GetMemberCount()); pProgressCallbacks->SetProgressValue(0); ByteStream *pStream = m_pMapArchive->OpenFile(FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { pProgressCallbacks->DisplayError("Could not open entities.xml"); return false; } // create writer XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) { pStream->Release(); return false; } // write out header xmlWriter.StartElement("entities"); xmlWriter.WriteAttribute("next-entity-suffix", StringConverter::UInt32ToString(m_nextEntitySuffix)); // write entities for (EntityTable::ConstIterator itr = m_entities.Begin(); !itr.AtEnd(); itr.Forward()) { const MapSourceEntityData *pEntityData = itr->Value; xmlWriter.StartElement("entity"); pEntityData->SaveToXML(xmlWriter); xmlWriter.EndElement(); } // end document xmlWriter.EndElement(); xmlWriter.Close(); pStream->Release(); // clear saved flags m_entityListChanged = false; return true; } const MapSourceEntityData *MapSource::GetEntityData(const char *entityName) const { const EntityTable::Member *pMember = m_entities.Find(entityName); return (pMember != NULL) ? pMember->Value : NULL; } MapSourceEntityData *MapSource::GetEntityData(const char *entityName) { EntityTable::Member *pMember = m_entities.Find(entityName); return (pMember != NULL) ? pMember->Value : NULL; } String MapSource::GenerateEntityName(const char *typeName) { SmallString entityName; // keep generating names until one is free do { entityName.Clear(); entityName.AppendString(typeName); entityName.AppendFormattedString("_%u", m_nextEntitySuffix++); } while (m_entities.Find(entityName) != nullptr); return entityName; } MapSourceEntityData *MapSource::CreateEntity(const char *typeName, const char *entityName /* = nullptr */) { String newEntityName; // check the name does not exist before using it if (entityName == nullptr || m_entities.Find(entityName) != nullptr) newEntityName = GenerateEntityName(typeName); else newEntityName = entityName; MapSourceEntityData *pEntityData = new MapSourceEntityData(); pEntityData->Create(newEntityName, typeName); m_entities.Insert(pEntityData->GetEntityName(), pEntityData); m_entityListChanged = true; return pEntityData; } MapSourceEntityData *MapSource::CreateEntityFromTemplate(const ObjectTemplate *pTemplate, const char *entityName /* = nullptr */) { String newEntityName; // check the name does not exist before using it if (entityName == nullptr || m_entities.Find(entityName) != nullptr) newEntityName = GenerateEntityName(pTemplate->GetTypeName()); else newEntityName = entityName; MapSourceEntityData *pEntityData = new MapSourceEntityData(); pEntityData->CreateFromTemplate(newEntityName, pTemplate); m_entities.Insert(pEntityData->GetEntityName(), pEntityData); m_entityListChanged = true; return pEntityData; } MapSourceEntityData *MapSource::CopyEntity(const MapSourceEntityData *pEntity, const char *entityName /* = nullptr */) { String newEntityName; // check the name does not exist before using it if (entityName == nullptr || m_entities.Find(entityName) != nullptr) newEntityName = GenerateEntityName(pEntity->GetTypeName()); else newEntityName = entityName; MapSourceEntityData *pNewEntityData = new MapSourceEntityData(); pNewEntityData->Create(newEntityName, pEntity->GetTypeName()); pNewEntityData->m_properties.CopyProperties(pEntity->GetPropertyTable()); m_entities.Insert(pNewEntityData->GetEntityName(), pNewEntityData); m_entityListChanged = true; return pNewEntityData; } bool MapSource::AddEntity(MapSourceEntityData *pEntityData) { if (m_entities.Find(pEntityData->GetEntityName()) != nullptr) return false; // add entity pEntityData->SetChangedFlag(); m_entities.Insert(pEntityData->GetEntityName(), pEntityData); m_entityListChanged = true; return true; } void MapSource::RemoveEntity(MapSourceEntityData *pEntityData) { EntityTable::Member *pMember = nullptr; for (EntityTable::Iterator itr = m_entities.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Value == pEntityData) { pMember = &(*itr); break; } } DebugAssert(pMember != nullptr); m_entities.Remove(pMember); m_entityListChanged = true; } bool MapSource::RemoveEntity(const char *entityName) { EntityTable::Member *pMember = m_entities.Find(entityName); if (pMember == nullptr) return false; // remove entity MapSourceEntityData *pEntityData = pMember->Value; RemoveEntity(pEntityData); delete pEntityData; return true; } void MapSource::SetDefaults() { m_version = 5; m_regionSize = 1024; m_isChanged = true; } const int2 MapSource::GetRegionForPosition(const float3 &position) const { return int2((Math::Truncate(position.x) / (int32)m_regionSize) - ((position.x < 0.0f) ? 1 : 0), (Math::Truncate(position.y) / (int32)m_regionSize) - ((position.y < 0.0f) ? 1 : 0)); } const int2 MapSource::GetRegionForTerrainSection(int32 sectionX, int32 sectionY) const { DebugAssert(m_pTerrainData != nullptr); int32 sectionsPerRegion = (int32)(m_regionSize / m_pTerrainData->GetParameters()->SectionSize); return int2((sectionX >= 0) ? (sectionX / sectionsPerRegion) : (Min(sectionX, -sectionsPerRegion) / sectionsPerRegion), (sectionY >= 0) ? (sectionY / sectionsPerRegion) : (Min(sectionY, -sectionsPerRegion) / sectionsPerRegion)); } MapSourceEntityComponent::MapSourceEntityComponent() : m_changed(false) { } MapSourceEntityComponent::~MapSourceEntityComponent() { } void MapSourceEntityComponent::Create(const String &componentName, const String &typeName) { m_componentName = componentName; m_typeName = typeName; m_changed = true; } void MapSourceEntityComponent::CreateFromTemplate(const String &componentName, const ObjectTemplate *pTemplate) { m_componentName = componentName; m_typeName = pTemplate->GetTypeName(); m_properties.CreateFromTemplate(pTemplate->GetPropertyTemplate()); m_changed = true; } bool MapSourceEntityComponent::LoadFromXML(XMLReader &xmlReader) { const char *componentNameStr = xmlReader.FetchAttribute("name"); const char *componentTypeStr = xmlReader.FetchAttribute("type"); if (componentNameStr == nullptr || componentTypeStr == nullptr) { xmlReader.PrintError("incomplete component definition"); return false; } m_componentName = componentNameStr; m_typeName = componentTypeStr; // read fields if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 objectSelection = xmlReader.Select("properties"); if (objectSelection < 0) return false; switch (objectSelection) { // properties case 0: { if (!xmlReader.IsEmptyElement()) { if (!m_properties.LoadFromXML(xmlReader)) return false; DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "properties") == 0); } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } } } return true; } void MapSourceEntityComponent::SaveToXML(XMLWriter &xmlWriter) const { xmlWriter.WriteAttribute("name", m_componentName); xmlWriter.WriteAttribute("type", m_typeName); // write properties xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); m_changed = false; } const String *MapSourceEntityComponent::GetPropertyValuePointer(const char *propertyName) const { return m_properties.GetPropertyValuePointer(propertyName); } String MapSourceEntityComponent::GetPropertyValueString(const char *propertyName) const { return m_properties.GetPropertyValueDefaultString(propertyName, EmptyString); } void MapSourceEntityComponent::SetPropertyValue(const char *propertyName, const char *propertyValue) { m_properties.SetPropertyValue(propertyName, propertyValue); m_changed = true; } void MapSourceEntityComponent::SetPropertyValue(const char *propertyName, const String &propertyValue) { m_properties.SetPropertyValueString(propertyName, propertyValue); m_changed = true; } MapSourceEntityData::MapSourceEntityData() : m_changed(false) { } MapSourceEntityData::~MapSourceEntityData() { for (uint32 i = 0; i < m_components.GetSize(); i++) delete m_components[i]; } const bool MapSourceEntityData::IsChanged() const { if (m_changed) return true; for (uint32 i = 0; i < m_components.GetSize(); i++) { if (m_components[i]->IsChanged()) return true; } return false; } void MapSourceEntityData::SetChangedFlag() { m_changed = true; } void MapSourceEntityData::ClearChangedFlag() { m_changed = false; for (uint32 i = 0; i < m_components.GetSize(); i++) m_components[i]->ClearChangedFlag(); } const MapSourceEntityComponent *MapSourceEntityData::GetComponentByName(const char *name) const { for (uint32 i = 0; i < m_components.GetSize(); i++) { if (m_components[i]->GetComponentName().CompareInsensitive(name)) return m_components[i]; } return nullptr; } MapSourceEntityComponent *MapSourceEntityData::GetComponentByName(const char *name) { for (uint32 i = 0; i < m_components.GetSize(); i++) { if (m_components[i]->GetComponentName().CompareInsensitive(name)) return m_components[i]; } return nullptr; } MapSourceEntityComponent *MapSourceEntityData::CreateComponent(const char *typeName, const char *componentName /* = nullptr */) { const ObjectTemplate *pTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(typeName); if (pTemplate == nullptr) return nullptr; return CreateComponent(pTemplate, componentName); } MapSourceEntityComponent *MapSourceEntityData::CreateComponent(const ObjectTemplate *pTemplate, const char *componentName /* = nullptr */) { // check the name isn't used if (!pTemplate->CanCreate() || (componentName != nullptr && GetComponentByName(componentName) != nullptr)) return nullptr; // generate a name String componentNameString; if (componentName == nullptr) { uint32 underscoreCount = 0; for (;;) { componentNameString.Format("%s_%u", pTemplate->GetTypeName().GetCharArray(), m_components.GetSize()); for (uint32 i = 0; i < underscoreCount; i++) componentNameString.AppendCharacter('_'); if (GetComponentByName(componentNameString) == nullptr) break; underscoreCount++; } } else { componentNameString = componentName; } // create it MapSourceEntityComponent *pComponentData = new MapSourceEntityComponent(); pComponentData->CreateFromTemplate(componentNameString, pTemplate); m_components.Add(pComponentData); return pComponentData; } void MapSourceEntityData::AddComponent(MapSourceEntityComponent *pComponent) { DebugAssert(m_components.IndexOf(pComponent) < 0); DebugAssert(GetComponentByName(pComponent->GetComponentName()) == nullptr); m_components.Add(pComponent); } void MapSourceEntityData::RemoveComponent(MapSourceEntityComponent *pComponent) { int32 index = m_components.IndexOf(pComponent); Assert(index >= 0); m_components.OrderedRemove(index); } const String *MapSourceEntityData::GetPropertyValuePointer(const char *propertyName) const { return m_properties.GetPropertyValuePointer(propertyName); } String MapSourceEntityData::GetPropertyValueString(const char *propertyName) const { return m_properties.GetPropertyValueDefaultString(propertyName, EmptyString); } void MapSourceEntityData::SetPropertyValue(const char *propertyName, const char *propertyValue) { m_properties.SetPropertyValue(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValue(const char *propertyName, const String &propertyValue) { m_properties.SetPropertyValueString(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::Create(const String &entityName, const String &typeName) { m_entityName = entityName; m_typeName = typeName; m_changed = true; } void MapSourceEntityData::CreateFromTemplate(const String &entityName, const ObjectTemplate *pTemplate) { m_entityName = entityName; m_typeName = pTemplate->GetTypeName(); m_properties.CreateFromTemplate(pTemplate->GetPropertyTemplate()); m_changed = true; } bool MapSourceEntityData::LoadFromXML(XMLReader &xmlReader) { const char *entityNameStr = xmlReader.FetchAttribute("name"); const char *entityTypeStr = xmlReader.FetchAttribute("type"); if (entityNameStr == nullptr || entityTypeStr == nullptr) { xmlReader.PrintError("incomplete entity definition"); return false; } m_entityName = entityNameStr; m_typeName = entityTypeStr; // read fields if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 objectSelection = xmlReader.Select("components|properties|script"); if (objectSelection < 0) return false; switch (objectSelection) { // components case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 componentsSelection = xmlReader.Select("component"); if (componentsSelection < 0 || xmlReader.IsEmptyElement()) return false; MapSourceEntityComponent *pComponent = new MapSourceEntityComponent(); if (!pComponent->LoadFromXML(xmlReader)) { delete pComponent; return false; } if (GetComponentByName(pComponent->GetComponentName()) != nullptr) { xmlReader.PrintError("duplicate component named '%s'", pComponent->GetComponentName().GetCharArray()); delete pComponent; return false; } m_components.Add(pComponent); if (!xmlReader.ExpectEndOfElementName("component")) return false; } else { if (!xmlReader.ExpectEndOfElementName("components")) return false; break; } } } } break; // properties case 1: { if (!xmlReader.IsEmptyElement()) { if (!m_properties.LoadFromXML(xmlReader)) return false; DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "properties") == 0); } } break; // script case 2: { if (!xmlReader.IsEmptyElement()) { if (!xmlReader.MoveToElement()) return false; m_script = xmlReader.GetElementText(); if (!xmlReader.SkipCurrentElement()) return false; } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } } } return true; } void MapSourceEntityData::SaveToXML(XMLWriter &xmlWriter) const { xmlWriter.WriteAttribute("name", m_entityName); xmlWriter.WriteAttribute("type", m_typeName); // write components xmlWriter.StartElement("components"); { for (uint32 i = 0; i < m_components.GetSize(); i++) { xmlWriter.StartElement("component"); m_components[i]->SaveToXML(xmlWriter); xmlWriter.EndElement(); } } xmlWriter.EndElement(); // write properties xmlWriter.StartElement("properties"); m_properties.SaveToXML(xmlWriter); xmlWriter.EndElement(); // write script if (!m_script.IsEmpty()) { xmlWriter.StartElement("script"); xmlWriter.WriteCDATA(m_script); xmlWriter.EndElement(); } m_changed = false; } bool MapSourceEntityData::GetPropertyValueBool(const char *propertyName, bool *pValue) const { return m_properties.GetPropertyValueBool(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt8(const char *propertyName, int8 *pValue) const { return m_properties.GetPropertyValueInt8(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt16(const char *propertyName, int16 *pValue) const { return m_properties.GetPropertyValueInt16(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt32(const char *propertyName, int32 *pValue) const { return m_properties.GetPropertyValueInt32(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt64(const char *propertyName, int64 *pValue) const { return m_properties.GetPropertyValueInt64(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt8(const char *propertyName, uint8 *pValue) const { return m_properties.GetPropertyValueUInt8(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt16(const char *propertyName, uint16 *pValue) const { return m_properties.GetPropertyValueUInt16(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt32(const char *propertyName, uint32 *pValue) const { return m_properties.GetPropertyValueUInt32(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt64(const char *propertyName, uint64 *pValue) const { return m_properties.GetPropertyValueUInt64(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueFloat(const char *propertyName, float *pValue) const { return m_properties.GetPropertyValueFloat(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueDouble(const char *propertyName, double *pValue) const { return m_properties.GetPropertyValueDouble(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueColor(const char *propertyName, uint32 *pValue) const { return m_properties.GetPropertyValueColor(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt2(const char *propertyName, int2 *pValue) const { return m_properties.GetPropertyValueInt2(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt3(const char *propertyName, int3 *pValue) const { return m_properties.GetPropertyValueInt3(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueInt4(const char *propertyName, int4 *pValue) const { return m_properties.GetPropertyValueInt4(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt2(const char *propertyName, uint2 *pValue) const { return m_properties.GetPropertyValueUInt2(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt3(const char *propertyName, uint3 *pValue) const { return m_properties.GetPropertyValueUInt3(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueUInt4(const char *propertyName, uint4 *pValue) const { return m_properties.GetPropertyValueUInt4(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueFloat2(const char *propertyName, float2 *pValue) const { return m_properties.GetPropertyValueFloat2(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueFloat3(const char *propertyName, float3 *pValue) const { return m_properties.GetPropertyValueFloat3(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueFloat4(const char *propertyName, float4 *pValue) const { return m_properties.GetPropertyValueFloat4(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueQuaternion(const char *propertyName, Quaternion *pValue) const { return m_properties.GetPropertyValueQuaternion(propertyName, pValue); } bool MapSourceEntityData::GetPropertyValueDefaultBool(const char *propertyName, bool defaultValue /*= false*/) const { return m_properties.GetPropertyValueDefaultBool(propertyName, defaultValue); } int8 MapSourceEntityData::GetPropertyValueDefaultInt8(const char *propertyName, int8 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultInt8(propertyName, defaultValue); } int16 MapSourceEntityData::GetPropertyValueDefaultInt16(const char *propertyName, int16 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultInt16(propertyName, defaultValue); } int32 MapSourceEntityData::GetPropertyValueDefaultInt32(const char *propertyName, int32 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultInt32(propertyName, defaultValue); } int64 MapSourceEntityData::GetPropertyValueDefaultInt64(const char *propertyName, int64 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultInt64(propertyName, defaultValue); } uint8 MapSourceEntityData::GetPropertyValueDefaultUInt8(const char *propertyName, uint8 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultUInt8(propertyName, defaultValue); } uint16 MapSourceEntityData::GetPropertyValueDefaultUInt16(const char *propertyName, uint16 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultUInt16(propertyName, defaultValue); } uint32 MapSourceEntityData::GetPropertyValueDefaultUInt32(const char *propertyName, uint32 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultUInt32(propertyName, defaultValue); } uint64 MapSourceEntityData::GetPropertyValueDefaultUInt64(const char *propertyName, uint64 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultUInt64(propertyName, defaultValue); } float MapSourceEntityData::GetPropertyValueDefaultFloat(const char *propertyName, float defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultFloat(propertyName, defaultValue); } double MapSourceEntityData::GetPropertyValueDefaultDouble(const char *propertyName, double defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultDouble(propertyName, defaultValue); } uint32 MapSourceEntityData::GetPropertyValueDefaultColor(const char *propertyName, uint32 defaultValue /*= 0*/) const { return m_properties.GetPropertyValueDefaultColor(propertyName, defaultValue); } int2 MapSourceEntityData::GetPropertyValueDefaultInt2(const char *propertyName, const int2 &defaultValue /*= int2::Zero*/) const { return m_properties.GetPropertyValueDefaultInt2(propertyName, defaultValue); } int3 MapSourceEntityData::GetPropertyValueDefaultInt3(const char *propertyName, const int3 &defaultValue /*= int3::Zero*/) const { return m_properties.GetPropertyValueDefaultInt3(propertyName, defaultValue); } int4 MapSourceEntityData::GetPropertyValueDefaultInt4(const char *propertyName, const int4 &defaultValue /*= int4::Zero*/) const { return m_properties.GetPropertyValueDefaultInt4(propertyName, defaultValue); } uint2 MapSourceEntityData::GetPropertyValueDefaultUInt2(const char *propertyName, const uint2 &defaultValue /*= uint2::Zero*/) const { return m_properties.GetPropertyValueDefaultUInt2(propertyName, defaultValue); } uint3 MapSourceEntityData::GetPropertyValueDefaultUInt3(const char *propertyName, const uint3 &defaultValue /*= uint3::Zero*/) const { return m_properties.GetPropertyValueDefaultUInt3(propertyName, defaultValue); } uint4 MapSourceEntityData::GetPropertyValueDefaultUInt4(const char *propertyName, const uint4 &defaultValue /*= uint4::Zero*/) const { return m_properties.GetPropertyValueDefaultUInt4(propertyName, defaultValue); } float2 MapSourceEntityData::GetPropertyValueDefaultFloat2(const char *propertyName, const float2 &defaultValue /*= float2::Zero*/) const { return m_properties.GetPropertyValueDefaultFloat2(propertyName, defaultValue); } float3 MapSourceEntityData::GetPropertyValueDefaultFloat3(const char *propertyName, const float3 &defaultValue /*= float3::Zero*/) const { return m_properties.GetPropertyValueDefaultFloat3(propertyName, defaultValue); } float4 MapSourceEntityData::GetPropertyValueDefaultFloat4(const char *propertyName, const float4 &defaultValue /*= float4::Zero*/) const { return m_properties.GetPropertyValueDefaultFloat4(propertyName, defaultValue); } Quaternion MapSourceEntityData::GetPropertyValueDefaultQuaternion(const char *propertyName, const Quaternion &defaultValue /*= Quaternion::Identity*/) const { return m_properties.GetPropertyValueDefaultQuaternion(propertyName, defaultValue); } void MapSourceEntityData::SetPropertyValueBool(const char *propertyName, bool propertyValue) { m_properties.SetPropertyValueBool(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt8(const char *propertyName, int8 propertyValue) { m_properties.SetPropertyValueInt8(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt16(const char *propertyName, int16 propertyValue) { m_properties.SetPropertyValueInt16(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt32(const char *propertyName, int32 propertyValue) { m_properties.SetPropertyValueInt32(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt64(const char *propertyName, int64 propertyValue) { m_properties.SetPropertyValueInt64(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt8(const char *propertyName, uint8 propertyValue) { m_properties.SetPropertyValueUInt8(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt16(const char *propertyName, uint16 propertyValue) { m_properties.SetPropertyValueUInt16(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt32(const char *propertyName, uint32 propertyValue) { m_properties.SetPropertyValueUInt32(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt64(const char *propertyName, uint64 propertyValue) { m_properties.SetPropertyValueUInt64(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueFloat(const char *propertyName, float propertyValue) { m_properties.SetPropertyValueFloat(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueDouble(const char *propertyName, double propertyValue) { m_properties.SetPropertyValueDouble(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueColor(const char *propertyName, uint32 propertyValue) { m_properties.SetPropertyValueColor(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt2(const char *propertyName, const int2 &propertyValue) { m_properties.SetPropertyValueInt2(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt3(const char *propertyName, const int3 &propertyValue) { m_properties.SetPropertyValueInt3(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueInt4(const char *propertyName, const int4 &propertyValue) { m_properties.SetPropertyValueInt4(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt2(const char *propertyName, const uint2 &propertyValue) { m_properties.SetPropertyValueUInt2(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt3(const char *propertyName, const uint3 &propertyValue) { m_properties.SetPropertyValueUInt3(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueUInt4(const char *propertyName, const uint4 &propertyValue) { m_properties.SetPropertyValueUInt4(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueFloat2(const char *propertyName, const float2 &propertyValue) { m_properties.SetPropertyValueFloat2(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueFloat3(const char *propertyName, const float3 &propertyValue) { m_properties.SetPropertyValueFloat3(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueFloat4(const char *propertyName, const float4 &propertyValue) { m_properties.SetPropertyValueFloat4(propertyName, propertyValue); m_changed = true; } void MapSourceEntityData::SetPropertyValueQuaternion(const char *propertyName, const Quaternion &propertyValue) { m_properties.SetPropertyValueQuaternion(propertyName, propertyValue); m_changed = true; } <file_sep>/Editor/Source/Editor/EditorResourceSaveDialog.h #pragma once #include "Editor/Common.h" #include "Editor/EditorResourceSelectionDialogModel.h" class EditorResourceSaveDialog : public QDialog { Q_OBJECT public: EditorResourceSaveDialog(QWidget *pParent, const ResourceTypeInfo *pResourceTypeInfo); ~EditorResourceSaveDialog(); const ResourceTypeInfo *GetResourceTypeInfo() const { return m_pResourceTypeInfo; } void SetResourceTypeInfo(const ResourceTypeInfo *pResourceTypeInfo) { m_pResourceTypeInfo = pResourceTypeInfo; } const String GetReturnValueResourceName() const { return m_returnValueResourceName; } bool NavigateToDirectory(const char *directory, bool addToHistory = true); private Q_SLOTS: void OnDirectoryComboBoxActivated(const QString &text); void OnBackButtonPressed(); void OnUpDirectoryButtonPressed(); void OnMakeDirectoryButtonPressed(); void OnTreeViewItemActivated(const QModelIndex &index); void OnTreeViewItemClicked(const QModelIndex &index); void OnResourceNameEditTextChanged(const QString &contents); void OnSaveButtonClicked(); void OnCancelButtonClicked(); private: void CreateUI(); void UpdateReturnValue(); const ResourceTypeInfo *m_pResourceTypeInfo; EditorResourceSelectionDialogModel *m_pModel; QStack<QString> m_history; QComboBox *m_pDirectoryComboBox; QToolButton *m_pBackButton; QToolButton *m_pUpDirectoryButton; QTreeView *m_pTreeView; QLabel *m_pFilterTextLabel; QComboBox *m_pResourceNameComboBox; String m_returnValueResourceName; QPushButton *m_pSaveButton; };<file_sep>/Engine/Source/ResourceCompiler/ResourceCompilerCallbacks.h #pragma once #include "ResourceCompiler/Common.h" class MaterialShader; class Skeleton; struct ResourceCompilerCallbacks { // Get the contents of a specific file virtual BinaryBlob *GetFileContents(const char *name) = 0; // Get the blob of a MaterialShader (needed because Material depends on it) virtual const MaterialShader *GetCompiledMaterialShader(const char *name) = 0; // Get the blob of a skeleton (needed because SkeletalMesh/SkeletalAnimation depend on it) virtual const Skeleton *GetCompiledSkeleton(const char *name) = 0; }; <file_sep>/Engine/Source/ResourceCompiler/ShaderCompilerD3D.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderCompilerD3D.h" #ifdef Y_PLATFORM_WINDOWS #include "ResourceCompiler/ShaderGraphCompilerHLSL.h" #include "Renderer/Renderer.h" Log_SetChannel(ShaderCompilerD3D); #pragma comment(lib, "d3dcompiler.lib") struct PlatformProfileInfo { const char *StageProfiles[SHADER_PROGRAM_STAGE_COUNT]; }; static const PlatformProfileInfo s_InternalProfileInfo[RENDERER_FEATURE_LEVEL_COUNT] = { //vs profile hs profile ds profile gs profile ps profile cs profile { "vs_4_0", NULL, NULL, NULL, "ps_4_0", NULL }, // RENDERER_FEATURE_LEVEL_ES2 { "vs_4_0", NULL, NULL, NULL, "ps_4_0", NULL }, // RENDERER_FEATURE_LEVEL_ES3 { "vs_4_0", NULL, NULL, "gs_4_0", "ps_4_0", "cs_4_0" }, // RENDERER_FEATURE_LEVEL_SM4 { "vs_5_0", "hs_5_0", "ds_5_0", "gs_5_0", "ps_5_0", "cs_5_0" }, // RENDERER_FEATURE_LEVEL_SM5 }; // d3d11 include interface struct D3DIncludeInterface : public ID3DInclude { D3DIncludeInterface(ShaderCompilerD3D *pParent) : m_pParent(pParent) {} STDOVERRIDEMETHODIMP Open(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) { return (m_pParent->ReadIncludeFile((IncludeType == D3D_INCLUDE_SYSTEM), pFileName, const_cast<LPVOID *>(ppData), pBytes)) ? S_OK : E_FAIL; } STDOVERRIDEMETHODIMP Close(THIS_ LPCVOID pData) { m_pParent->FreeIncludeFile(const_cast<LPVOID>(pData)); return S_OK; } private: ShaderCompilerD3D *m_pParent; }; ShaderCompilerD3D::ShaderCompilerD3D(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters) : ShaderCompiler(pCallbacks, pParameters) { Y_memzero(m_pStageByteCode, sizeof(m_pStageByteCode)); } ShaderCompilerD3D::~ShaderCompilerD3D() { for (uint32 i = 0; i < countof(m_pStageByteCode); i++) { if (m_pStageByteCode[i] != nullptr) m_pStageByteCode[i]->Release(); } } void ShaderCompilerD3D::BuildD3DDefineList(SHADER_PROGRAM_STAGE stage, MemArray<D3D_SHADER_MACRO> &D3DMacroArray) { #define ADD_D3D_SHADER_MACRO(MacroName, MacroDefinition) MULTI_STATEMENT_MACRO_BEGIN \ Macro.Name = MacroName; \ Macro.Definition = MacroDefinition; \ D3DMacroArray.Add(Macro); \ MULTI_STATEMENT_MACRO_END D3D_SHADER_MACRO Macro; // stage-specific defines switch (stage) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: ADD_D3D_SHADER_MACRO("VERTEX_SHADER", "1"); break; case SHADER_PROGRAM_STAGE_HULL_SHADER: ADD_D3D_SHADER_MACRO("HULL_SHADER", "1"); break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: ADD_D3D_SHADER_MACRO("DOMAIN_SHADER", "1"); break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: ADD_D3D_SHADER_MACRO("GEOMETRY_SHADER", "1"); break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: ADD_D3D_SHADER_MACRO("PIXEL_SHADER", "1"); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: ADD_D3D_SHADER_MACRO("COMPUTE_SHADER", "1"); break; } // build the d3d list uint32 i; for (i = 0; i < m_CompileMacros.GetSize(); i++) ADD_D3D_SHADER_MACRO(m_CompileMacros[i].Key, m_CompileMacros[i].Value); // NULL end-macro ADD_D3D_SHADER_MACRO(NULL, NULL); #undef ADD_D3D_SHADER_MACRO } bool ShaderCompilerD3D::CompileShaderStage(SHADER_PROGRAM_STAGE stage) { D3DIncludeInterface includeInterface(this); HRESULT hResult; // get source filename const PlatformProfileInfo *pPlatformProfileInfo = &s_InternalProfileInfo[m_eRendererFeatureLevel]; if (m_StageFileNames[stage].IsEmpty() || m_StageEntryPoints[stage].IsEmpty()) return false; // open the source file BinaryBlob *pSourceBlob = m_pResourceCompilerCallbacks->GetFileContents(m_StageFileNames[stage]); if (pSourceBlob == nullptr) { Log_ErrorPrintf("ShaderCompilerD3D::CompileShaderStage: Could not open shader source file '%s'.", m_StageFileNames[stage].GetCharArray()); return false; } // get define list MemArray<D3D_SHADER_MACRO> D3DMacroArray; BuildD3DDefineList(stage, D3DMacroArray); // flags uint32 D3DCompileFlags = D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; // debug flags if (m_iShaderCompilerFlags & SHADER_COMPILER_FLAG_ENABLE_DEBUG_INFO) D3DCompileFlags |= D3DCOMPILE_DEBUG; // optimization flags if (m_iShaderCompilerFlags & SHADER_COMPILER_FLAG_DISABLE_OPTIMIZATIONS) D3DCompileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; else D3DCompileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; ID3DBlob *pCodeBlob; ID3DBlob *pErrorBlob; // shader dumping if (m_pDumpWriter != nullptr) { ID3DBlob *pCodeText; hResult = D3DPreprocess(pSourceBlob->GetDataPointer(), pSourceBlob->GetDataSize(), m_StageFileNames[stage], D3DMacroArray.GetBasePointer(), &includeInterface, &pCodeText, &pErrorBlob); if (FAILED(hResult)) { Log_ErrorPrintf("CompileShaderStage: D3DPreprocess failed with HResult %08X", hResult); if (pErrorBlob != NULL) { Log_ErrorPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } pSourceBlob->Release(); return false; } if (pErrorBlob != NULL) { Log_WarningPrintf("CompileShaderStage: Preprocess succeeded with warnings."); Log_WarningPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } m_pDumpWriter->WriteFormattedLine("Preprocessed shader %s:", pPlatformProfileInfo->StageProfiles[stage]); m_pDumpWriter->WriteWithLineNumbers(reinterpret_cast<const char *>(pCodeText->GetBufferPointer()), (uint32)pCodeText->GetBufferSize()); pCodeText->Release(); } // invoke compiler hResult = D3DCompile(pSourceBlob->GetDataPointer(), pSourceBlob->GetDataSize(), m_StageFileNames[stage], D3DMacroArray.GetBasePointer(), &includeInterface, m_StageEntryPoints[stage], pPlatformProfileInfo->StageProfiles[stage], D3DCompileFlags, 0, &pCodeBlob, &pErrorBlob); if (FAILED(hResult)) { Log_ErrorPrintf("CompileShaderStage: D3DCompile for %s failed with HResult %08X", pPlatformProfileInfo->StageProfiles[stage], hResult); if (pErrorBlob != NULL) { if (m_pDumpWriter != NULL) { m_pDumpWriter->WriteFormattedLine("CompileShaderStage: D3DCompile for %s failed with HResult %08X", pPlatformProfileInfo->StageProfiles[stage], hResult); m_pDumpWriter->Write((const char *)pErrorBlob->GetBufferPointer(), (uint32)pErrorBlob->GetBufferSize()); m_pDumpWriter->WriteLine(""); } Log_ErrorPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } pSourceBlob->Release(); return false; } if (pErrorBlob != NULL) { if (m_pDumpWriter != NULL) { m_pDumpWriter->WriteLine("CompileShaderStage: Compile succeeded with warnings."); m_pDumpWriter->Write((const char *)pErrorBlob->GetBufferPointer(), (uint32)pErrorBlob->GetBufferSize()); m_pDumpWriter->WriteLine(""); } Log_WarningPrintf("CompileShaderStage: Compile succeeded with warnings."); Log_WarningPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } if (m_pDumpWriter != NULL) { ID3DBlob *pDisasmBlob; hResult = D3DDisassemble(pCodeBlob->GetBufferPointer(), pCodeBlob->GetBufferSize(), D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING, NULL, &pDisasmBlob); if (FAILED(hResult)) { Log_WarningPrintf("D3DDisassemble failed with hResult %08X", hResult); m_pDumpWriter->WriteFormattedLine("D3DDisassemble failed with hResult %08X", hResult); } else { m_pDumpWriter->WriteFormattedLine("%s shader disassembly:", pPlatformProfileInfo->StageProfiles[stage]); m_pDumpWriter->Write((const char *)pDisasmBlob->GetBufferPointer(), (uint32)pDisasmBlob->GetBufferSize()); pDisasmBlob->Release(); } } // set blob Log_DevPrintf("CompileShaderStage: %s compiled to %u bytes.", pPlatformProfileInfo->StageProfiles[stage], pCodeBlob->GetBufferSize()); m_pStageByteCode[stage] = pCodeBlob; return true; } static bool MapD3D11ShaderTypeDescToParameterType(const D3D11_SHADER_TYPE_DESC *pVariableTypeDesc, SHADER_PARAMETER_TYPE *pParameterType) { struct TypeTranslation { SHADER_PARAMETER_TYPE UniformType; D3D_SHADER_VARIABLE_CLASS D3DClass; D3D_SHADER_VARIABLE_TYPE D3DType; uint32 Rows; uint32 Cols; }; static const TypeTranslation TranslationTable[] = { { SHADER_PARAMETER_TYPE_BOOL, D3D_SVC_SCALAR, D3D_SVT_BOOL, 1, 1 }, { SHADER_PARAMETER_TYPE_INT, D3D_SVC_SCALAR, D3D_SVT_INT, 1, 1 }, { SHADER_PARAMETER_TYPE_INT2, D3D_SVC_SCALAR, D3D_SVT_INT, 1, 2 }, { SHADER_PARAMETER_TYPE_INT3, D3D_SVC_SCALAR, D3D_SVT_INT, 1, 3 }, { SHADER_PARAMETER_TYPE_INT4, D3D_SVC_SCALAR, D3D_SVT_INT, 1, 4 }, { SHADER_PARAMETER_TYPE_UINT, D3D_SVC_SCALAR, D3D_SVT_UINT, 1, 1 }, { SHADER_PARAMETER_TYPE_UINT2, D3D_SVC_SCALAR, D3D_SVT_UINT, 1, 2 }, { SHADER_PARAMETER_TYPE_UINT3, D3D_SVC_SCALAR, D3D_SVT_UINT, 1, 3 }, { SHADER_PARAMETER_TYPE_UINT4, D3D_SVC_SCALAR, D3D_SVT_UINT, 1, 4 }, { SHADER_PARAMETER_TYPE_FLOAT, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 1, 1 }, { SHADER_PARAMETER_TYPE_FLOAT2, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 1, 2 }, { SHADER_PARAMETER_TYPE_FLOAT3, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 1, 3 }, { SHADER_PARAMETER_TYPE_FLOAT4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 1, 4 }, { SHADER_PARAMETER_TYPE_FLOAT2X2, D3D_SVC_MATRIX_ROWS, D3D_SVT_FLOAT, 2, 2 }, { SHADER_PARAMETER_TYPE_FLOAT3X3, D3D_SVC_MATRIX_ROWS, D3D_SVT_FLOAT, 3, 3 }, { SHADER_PARAMETER_TYPE_FLOAT3X4, D3D_SVC_MATRIX_ROWS, D3D_SVT_FLOAT, 3, 4 }, { SHADER_PARAMETER_TYPE_FLOAT4X4, D3D_SVC_MATRIX_ROWS, D3D_SVT_FLOAT, 4, 4 }, }; for (uint32 i = 0; i < countof(TranslationTable); i++) { const TypeTranslation *pCur = &TranslationTable[i]; if (pCur->D3DClass == pVariableTypeDesc->Class && pCur->D3DType == pVariableTypeDesc->Type && pCur->Rows == pVariableTypeDesc->Rows && pCur->Cols == pVariableTypeDesc->Columns) { *pParameterType = pCur->UniformType; return true; } } return false; } static bool MapD3D11ShaderInputBindDescToParameterType(const D3D11_SHADER_INPUT_BIND_DESC *pInputBindDesc, SHADER_PARAMETER_TYPE *pParameterType, D3D_SHADER_BIND_TARGET *pBindTarget) { if (pInputBindDesc->Type == D3D_SIT_CBUFFER) { // map to constant buffer *pParameterType = SHADER_PARAMETER_TYPE_CONSTANT_BUFFER; *pBindTarget = D3D_SHADER_BIND_TARGET_CONSTANT_BUFFER; return true; } else if (pInputBindDesc->Type == D3D_SIT_SAMPLER) { // map to sampler state *pParameterType = SHADER_PARAMETER_TYPE_SAMPLER_STATE; *pBindTarget = D3D_SHADER_BIND_TARGET_SAMPLER; return true; } else { // figure out the dimension switch (pInputBindDesc->Dimension) { case D3D_SRV_DIMENSION_TEXTURE1D: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE1D; break; case D3D_SRV_DIMENSION_TEXTURE1DARRAY: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE1DARRAY; break; case D3D_SRV_DIMENSION_TEXTURE2D: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE2D; break; case D3D_SRV_DIMENSION_TEXTURE2DARRAY: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE2DARRAY; break; case D3D_SRV_DIMENSION_TEXTURE2DMS: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE2DMS; break; case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY; break; case D3D_SRV_DIMENSION_TEXTURE3D: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURE3D; break; case D3D_SRV_DIMENSION_TEXTURECUBE: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURECUBE; break; case D3D_SRV_DIMENSION_TEXTURECUBEARRAY: *pParameterType = SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY; break; case D3D_SRV_DIMENSION_BUFFER: *pParameterType = SHADER_PARAMETER_TYPE_BUFFER; break; case D3D_SRV_DIMENSION_BUFFEREX: *pParameterType = SHADER_PARAMETER_TYPE_BUFFER; break; default: return false; } // work out the binding type if (pInputBindDesc->Type == D3D_SIT_TEXTURE) *pBindTarget = D3D_SHADER_BIND_TARGET_RESOURCE; else if (pInputBindDesc->Type >= D3D_SIT_UAV_RWTYPED && pInputBindDesc->Type <= D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER) *pBindTarget = D3D_SHADER_BIND_TARGET_UNORDERED_ACCESS_VIEW; else return false; // done return true; } } bool ShaderCompilerD3D::ReflectShader(SHADER_PROGRAM_STAGE stage) { DebugAssert(m_pStageByteCode[stage] != nullptr); ID3D11ShaderReflection *pReflectionPointer; HRESULT hResult = D3DReflect(m_pStageByteCode[stage]->GetBufferPointer(), m_pStageByteCode[stage]->GetBufferSize(), IID_ID3D11ShaderReflection, (void **)&pReflectionPointer); if (FAILED(hResult)) { Log_ErrorPrintf("D3DReflect failed with hResult %08X", hResult); return false; } // construct an autorelease to make stuff neater AutoReleasePtr<ID3D11ShaderReflection> pReflection = pReflectionPointer; // get shader descriptor D3D11_SHADER_DESC shaderDesc; hResult = pReflection->GetDesc(&shaderDesc); DebugAssert(SUCCEEDED(hResult)); // ID3DBlob *pDisassembly; // hResult = D3DDisassemble(pByteCode, byteCodeSize, 0, NULL, &pDisassembly); // DebugAssert(hResult == S_OK); // Log_DevPrint("Shader Disassembly"); // Log_DevPrint((const char *)pDisassembly->GetBufferPointer()); // pDisassembly->Release(); // // parse input format if (stage == SHADER_PROGRAM_STAGE_VERTEX_SHADER) { for (uint32 i = 0; i < shaderDesc.InputParameters; i++) { D3D11_SIGNATURE_PARAMETER_DESC signatureParameterDesc; hResult = pReflection->GetInputParameterDesc(i, &signatureParameterDesc); DebugAssert(hResult == S_OK); // skip system values if (signatureParameterDesc.SystemValueType != D3D_NAME_UNDEFINED) continue; D3DShaderCacheEntryVertexAttribute vertexAttribute; if (!NameTable_TranslateType(NameTables::GPUVertexElementSemantic, signatureParameterDesc.SemanticName, &vertexAttribute.SemanticName, true)) { Log_ErrorPrintf("ReflectShader: failed to find mapping of semantic name '%s'", signatureParameterDesc.SemanticName); return false; } vertexAttribute.SemanticIndex = signatureParameterDesc.SemanticIndex; m_outVertexAttributes.Add(vertexAttribute); } } // parse constant buffers if (shaderDesc.ConstantBuffers > 0) { for (uint32 constantBufferIndex = 0; constantBufferIndex < shaderDesc.ConstantBuffers; constantBufferIndex++) { ID3D11ShaderReflectionConstantBuffer *pConstantBufferReflection = pReflection->GetConstantBufferByIndex(constantBufferIndex); DebugAssert(pConstantBufferReflection != NULL); D3D11_SHADER_BUFFER_DESC constantBufferDesc; hResult = pConstantBufferReflection->GetDesc(&constantBufferDesc); DebugAssert(SUCCEEDED(hResult)); // // is the constant buffer used by the shader? // D3D11_SHADER_INPUT_BIND_DESC inputBindDesc; // hResult = pReflection->GetResourceBindingDescByName(constantBufferDesc.Name, &inputBindDesc); // if (FAILED(hResult)) // continue; // do we have an entry for it? uint32 outConstantBufferIndex; for (outConstantBufferIndex = 0; outConstantBufferIndex < m_outConstantBuffers.GetSize(); outConstantBufferIndex++) { if (m_outConstantBufferNames[outConstantBufferIndex].Compare(constantBufferDesc.Name)) { // found it break; } } // not present? if (outConstantBufferIndex == m_outConstantBuffers.GetSize()) { // add the constant buffer entry D3DShaderCacheEntryConstantBuffer cbDecl; cbDecl.NameLength = Y_strlen(constantBufferDesc.Name); cbDecl.MinimumSize = constantBufferDesc.Size; cbDecl.ParameterIndex = 0xFFFFFFFF; m_outConstantBuffers.Add(cbDecl); m_outConstantBufferNames.Add(constantBufferDesc.Name); } // // write the binding point to the output constant buffers // DebugAssert(outConstantBuffers[outConstantBufferIndex].BindPoint[stage] == -1); // outConstantBuffers[outConstantBufferIndex].BindPoint[stage] = inputBindDesc.BindPoint; // add global constants as parameters if (Y_strcmp(constantBufferDesc.Name, "$Globals") == 0) { for (uint32 variableIndex = 0; variableIndex < constantBufferDesc.Variables; variableIndex++) { ID3D11ShaderReflectionVariable *pVariableReflection = pConstantBufferReflection->GetVariableByIndex(variableIndex); // query variable D3D11_SHADER_VARIABLE_DESC variableDesc; hResult = pVariableReflection->GetDesc(&variableDesc); DebugAssert(SUCCEEDED(hResult)); // query variable type ID3D11ShaderReflectionType *pVariableType = pVariableReflection->GetType(); D3D11_SHADER_TYPE_DESC typeDesc; hResult = pVariableType->GetDesc(&typeDesc); DebugAssert(SUCCEEDED(hResult)); // skip over unused variables if (!(variableDesc.uFlags & D3D_SVF_USED)) continue; // have we already done this parameter? uint32 outParameterIndex; for (outParameterIndex = 0; outParameterIndex < m_outParameters.GetSize(); outParameterIndex++) { if (m_outParameterNames[outParameterIndex].Compare(variableDesc.Name)) break; } // skip already-done parameters if (outParameterIndex != m_outParameters.GetSize()) continue; // handle structs SHADER_PARAMETER_TYPE parameterType; uint32 uniformSize; if (typeDesc.Class == D3D_SVC_STRUCT) { // columns == size in floats? parameterType = SHADER_PARAMETER_TYPE_STRUCT; uniformSize = typeDesc.Columns * sizeof(float); } else { // determine type if (!MapD3D11ShaderTypeDescToParameterType(&typeDesc, &parameterType)) { Log_ErrorPrintf("ReflectShader: Failed to map variable type"); return false; } // get type size uniformSize = ShaderParameterValueTypeSize(parameterType); } // determine array size uint32 uniformArraySize = Max((uint32)1, (uint32)typeDesc.Elements); uint32 uniformArrayStride = uniformSize; if ((uniformArrayStride * uniformArraySize) != variableDesc.Size) { // Basically, every row gets aligned to a float4. // However it seems that the last element is not padded. switch (parameterType) { case SHADER_PARAMETER_TYPE_BOOL: uniformArraySize = sizeof(BOOL) * 4; break; case SHADER_PARAMETER_TYPE_INT: case SHADER_PARAMETER_TYPE_INT2: case SHADER_PARAMETER_TYPE_INT3: uniformArrayStride = sizeof(int32) * 4; break; case SHADER_PARAMETER_TYPE_FLOAT: case SHADER_PARAMETER_TYPE_FLOAT2: case SHADER_PARAMETER_TYPE_FLOAT3: uniformArrayStride = sizeof(float) * 4; break; default: UnreachableCode(); break; } // should've fixed it DebugAssert((uniformArrayStride * (uniformArraySize - 1) + ShaderParameterValueTypeSize(parameterType)) == variableDesc.Size); } // create parameter D3DShaderCacheEntryParameter paramDecl; paramDecl.NameLength = Y_strlen(variableDesc.Name); paramDecl.Type = parameterType; paramDecl.ConstantBufferIndex = outConstantBufferIndex; paramDecl.ConstantBufferOffset = variableDesc.StartOffset; paramDecl.ArraySize = uniformArraySize; paramDecl.ArrayStride = uniformArrayStride; paramDecl.BindTarget = D3D_SHADER_BIND_TARGET_COUNT; for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) paramDecl.BindPoint[i] = -1; paramDecl.LinkedSamplerIndex = -1; m_outParameters.Add(paramDecl); m_outParameterNames.Add(variableDesc.Name); } } } } // parse samplers/resources if (shaderDesc.BoundResources > 0) { // work out number of samplers/resources for (uint32 resourceIndex = 0; resourceIndex < shaderDesc.BoundResources; resourceIndex++) { D3D11_SHADER_INPUT_BIND_DESC inputBindDesc; hResult = pReflection->GetResourceBindingDesc(resourceIndex, &inputBindDesc); DebugAssert(SUCCEEDED(hResult)); // map to parameter info SHADER_PARAMETER_TYPE parameterType; D3D_SHADER_BIND_TARGET bindTarget; if (!MapD3D11ShaderInputBindDescToParameterType(&inputBindDesc, &parameterType, &bindTarget)) { Log_ErrorPrintf("ReflectShader: Failed to map resource input type"); return false; } // parameter with this name exists? uint32 outParameterIndex; for (outParameterIndex = 0; outParameterIndex < m_outParameters.GetSize(); outParameterIndex++) { if (m_outParameterNames[outParameterIndex].Compare(inputBindDesc.Name)) break; } // if not, create it if (outParameterIndex == m_outParameters.GetSize()) { D3DShaderCacheEntryParameter paramDecl; paramDecl.NameLength = Y_strlen(inputBindDesc.Name); paramDecl.Type = parameterType; paramDecl.ConstantBufferIndex = -1; paramDecl.ConstantBufferOffset = 0; paramDecl.ArraySize = 0; paramDecl.ArrayStride = 0; paramDecl.BindTarget = bindTarget; for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) paramDecl.BindPoint[i] = -1; paramDecl.LinkedSamplerIndex = -1; m_outParameters.Add(paramDecl); m_outParameterNames.Add(inputBindDesc.Name); } // it would be very concerning if these didn't match... aliased variables with different types DebugAssert(m_outParameters[outParameterIndex].Type == parameterType); DebugAssert(m_outParameters[outParameterIndex].BindTarget == (uint32)bindTarget); // set the bind point DebugAssert(m_outParameters[outParameterIndex].BindPoint[stage] == -1); m_outParameters[outParameterIndex].BindPoint[stage] = inputBindDesc.BindPoint; } } return true; } bool ShaderCompilerD3D::LinkResourceSamplerParameters() { SmallString samplerParameterName; // find any resources with a matching _SamplerState suffix sampler for (uint32 parameterIndex = 0; parameterIndex < m_outParameters.GetSize(); parameterIndex++) { D3DShaderCacheEntryParameter *parameter = &m_outParameters[parameterIndex]; if (parameter->BindTarget == D3D_SHADER_BIND_TARGET_RESOURCE && parameter->Type >= SHADER_PARAMETER_TYPE_TEXTURE1D && parameter->Type <= SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY) { samplerParameterName.Clear(); samplerParameterName.AppendString(m_outParameterNames[parameterIndex]); samplerParameterName.AppendString("_SamplerState"); for (uint32 samplerParameterIndex = 0; samplerParameterIndex < m_outParameters.GetSize(); samplerParameterIndex++) { if (samplerParameterIndex == parameterIndex) continue; const D3DShaderCacheEntryParameter *samplerParameter = &m_outParameters[samplerParameterIndex]; if (samplerParameter->Type == SHADER_PARAMETER_TYPE_SAMPLER_STATE && m_outParameterNames[samplerParameterIndex].Compare(samplerParameterName)) { // found a match m_outParameters[parameterIndex].LinkedSamplerIndex = samplerParameterIndex; Log_DevPrintf("LinkResourceSamplerParameters: Linked '%s' to '%s'", m_outParameterNames[parameterIndex].GetCharArray(), m_outParameterNames[samplerParameterIndex].GetCharArray()); break; } } } } return true; } bool ShaderCompilerD3D::LinkLocalConstantBuffersToParameters() { // match the constant buffers to parameters for (uint32 constantBufferIndex = 0; constantBufferIndex < m_outConstantBuffers.GetSize();) { D3DShaderCacheEntryConstantBuffer *constantBuffer = &m_outConstantBuffers[constantBufferIndex]; uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < m_outParameters.GetSize(); parameterIndex++) { const D3DShaderCacheEntryParameter *parameter = &m_outParameters[parameterIndex]; if (parameter->Type == SHADER_PARAMETER_TYPE_CONSTANT_BUFFER && m_outConstantBufferNames[constantBufferIndex].Compare(m_outParameterNames[parameterIndex])) break; } if (parameterIndex == m_outParameters.GetSize()) { Log_WarningPrintf("LinkLocalConstantBuffersToParameters: Constant buffer '%s' does not map to a parameter, dropping it.", m_outConstantBufferNames[parameterIndex].GetCharArray()); m_outConstantBuffers.OrderedRemove(constantBufferIndex); m_outConstantBufferNames.OrderedRemove(constantBufferIndex); continue; } // map it constantBuffer->ParameterIndex = parameterIndex; constantBufferIndex++; } return true; } bool ShaderCompilerD3D::InternalCompile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) { SmallString tempString; BinaryWriter binaryWriter(pByteCodeStream); Timer compileTimer, stageCompileTimer; float compileTimeCompile, compileTimeReflect; // compile stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (!m_StageEntryPoints[stageIndex].IsEmpty() && !CompileShaderStage((SHADER_PROGRAM_STAGE)stageIndex)) { Log_ErrorPrintf("Failed to compile stage %u.", stageIndex); return false; } } compileTimeCompile = (float)stageCompileTimer.GetTimeMilliseconds(); stageCompileTimer.Reset(); // Reflect each present shader stage. for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (m_pStageByteCode[stageIndex] != nullptr && !ReflectShader((SHADER_PROGRAM_STAGE)stageIndex)) { Log_ErrorPrintf("Failed to reflect stage %u.", stageIndex); return false; } } // Link sampler states to resources if (!LinkResourceSamplerParameters()) return false; // Link local constant buffers to parameters if (!LinkLocalConstantBuffersToParameters()) return false; #if 1 // Dump out variables for (uint32 constantBufferIndex = 0; constantBufferIndex < m_outConstantBuffers.GetSize(); constantBufferIndex++) Log_DevPrintf("Shader Constant Buffer [%u] : %s, %u bytes", constantBufferIndex, m_outConstantBufferNames[constantBufferIndex].GetCharArray(), m_outConstantBuffers[constantBufferIndex].MinimumSize); for (uint32 parameterIndex = 0; parameterIndex < m_outParameters.GetSize(); parameterIndex++) Log_DevPrintf("Shader Parameter [%u] : %s, type %s", parameterIndex, m_outParameterNames[parameterIndex].GetCharArray(), NameTable_GetNameString(NameTables::ShaderParameterType, m_outParameters[parameterIndex].Type)); #endif // Create the header of the shader data. // The zeros on the strings prevent stack memory getting dropped into the output. D3DShaderCacheEntryHeader cacheEntryHeader; Y_memzero(&cacheEntryHeader, sizeof(cacheEntryHeader)); cacheEntryHeader.Signature = D3D_SHADER_CACHE_ENTRY_HEADER; cacheEntryHeader.FeatureLevel = m_eRendererFeatureLevel; // Store shader stage sizes. for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) cacheEntryHeader.StageSize[stageIndex] = (m_pStageByteCode[stageIndex] != nullptr) ? m_pStageByteCode[stageIndex]->GetBufferSize() : 0; // Store counts. cacheEntryHeader.VertexAttributeCount = m_outVertexAttributes.GetSize(); cacheEntryHeader.ConstantBufferCount = m_outConstantBuffers.GetSize(); cacheEntryHeader.ParameterCount = m_outParameters.GetSize(); // Write header. binaryWriter.WriteBytes(&cacheEntryHeader, sizeof(cacheEntryHeader)); // Write each of the shader stage's bytecodes out. for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (m_pStageByteCode[stageIndex] != nullptr) { // write stage bytecode binaryWriter.WriteBytes(m_pStageByteCode[stageIndex]->GetBufferPointer(), m_pStageByteCode[stageIndex]->GetBufferSize()); } } // Write out declarations. for (uint32 i = 0; i < m_outVertexAttributes.GetSize(); i++) binaryWriter.WriteBytes(&m_outVertexAttributes[i], sizeof(D3DShaderCacheEntryVertexAttribute)); for (uint32 i = 0; i < m_outConstantBuffers.GetSize(); i++) { binaryWriter.WriteBytes(&m_outConstantBuffers[i], sizeof(D3DShaderCacheEntryConstantBuffer)); binaryWriter.WriteFixedString(m_outConstantBufferNames[i], m_outConstantBuffers[i].NameLength); } for (uint32 i = 0; i < m_outParameters.GetSize(); i++) { binaryWriter.WriteBytes(&m_outParameters[i], sizeof(D3DShaderCacheEntryParameter)); binaryWriter.WriteFixedString(m_outParameterNames[i], m_outParameters[i].NameLength); } // update timer compileTimeReflect = (float)stageCompileTimer.GetTimeMilliseconds(); // Compile succeded. Log_DevPrintf("Shader successfully compiled. Took %.3f msec (Compile: %.3f msec, Reflect+Write: %.3f msec)", (float)compileTimer.GetTimeMilliseconds(), compileTimeCompile, compileTimeReflect); return true; } ShaderCompiler *ShaderCompiler::CreateD3D11ShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters) { return new ShaderCompilerD3D(pCallbacks, pParameters); } #endif // Y_PLATFORM_WINDOWS <file_sep>/Engine/Source/Engine/BlockMeshCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockMeshCollisionShape.h" #include "Engine/BlockMesh.h" #include "Engine/Physics/BulletHeaders.h" ATTRIBUTE_ALIGNED16(class) btBlockMeshCollisionShape : public btConcaveShape { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btBlockMeshCollisionShape(const BlockMeshVolume *pBlockVolume, const btVector3 &scaling, const AABox &boundingBox) : btConcaveShape(), m_pBlockVolume(pBlockVolume), m_localScaling(scaling), m_boundingBox(boundingBox) { m_shapeType = CUSTOM_CONCAVE_SHAPE_TYPE; } virtual ~btBlockMeshCollisionShape() { } virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; } virtual const btVector3& getLocalScaling() const { return m_localScaling; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual const char* getName() const { return "btBlockMeshCollisionShape"; } private: const BlockMeshVolume *m_pBlockVolume; btVector3 m_localScaling; AABox m_boundingBox; }; BlockMeshCollisionShape::BlockMeshCollisionShape(const BlockMesh *pBlockMesh) : m_pBlockMesh(pBlockMesh), m_pBlockVolume(&pBlockMesh->GetMeshVolume(0)), m_pOriginalShape(NULL), m_pBulletShape(NULL), m_scale(float3::One), m_boundingBox(pBlockMesh->GetMeshVolume(0).CalculateActiveBoundingBox()) { // fixme: shared data! m_pBulletShape = new btBlockMeshCollisionShape(&pBlockMesh->GetMeshVolume(0), btVector3(1.0f, 1.0f, 1.0f), m_boundingBox); } BlockMeshCollisionShape::~BlockMeshCollisionShape() { delete m_pBulletShape; if (m_pOriginalShape != NULL) m_pBlockMesh->Release(); } const Physics::COLLISION_SHAPE_TYPE BlockMeshCollisionShape::GetType() const { return Physics::COLLISION_SHAPE_TYPE_BLOCK_MESH; } const AABox &BlockMeshCollisionShape::GetLocalBoundingBox() const { return m_boundingBox; } bool BlockMeshCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { return false; } bool BlockMeshCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { return false; } Physics::CollisionShape *BlockMeshCollisionShape::CreateScaledShape(const float3 &scale) const { const BlockMeshCollisionShape *pOriginalShape = (m_pOriginalShape != NULL) ? m_pOriginalShape : this; if (scale == float3::One) { pOriginalShape->AddRef(); return const_cast<BlockMeshCollisionShape *>(pOriginalShape); } BlockMeshCollisionShape *pScaledShape = new BlockMeshCollisionShape(m_pBlockMesh); pScaledShape->m_pOriginalShape = pOriginalShape; pScaledShape->m_pBulletShape->setLocalScaling(Physics::Float3ToBulletVector(scale)); pScaledShape->m_scale = scale; return pScaledShape; } void BlockMeshCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { } void BlockMeshCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { } btCollisionShape *BlockMeshCollisionShape::GetBulletShape() const { return static_cast<btCollisionShape *>(m_pBulletShape); } void btBlockMeshCollisionShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const { btVector3 localMinBounds(m_localScaling * aabbMin); btVector3 localMaxBounds(m_localScaling * aabbMax); m_pBlockVolume->EnumerateTrianglesIntersectingBox(AABox(Physics::BulletVector3ToFloat3(localMinBounds), Physics::BulletVector3ToFloat3(localMaxBounds)), [callback](const float3 vertices[3]) { btVector3 bulletVertices[3]; bulletVertices[0] = Physics::Float3ToBulletVector(vertices[0]); bulletVertices[1] = Physics::Float3ToBulletVector(vertices[1]); bulletVertices[2] = Physics::Float3ToBulletVector(vertices[2]); callback->processTriangle(bulletVertices, 0, 0); }); } void btBlockMeshCollisionShape::getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const { AABox transformedBoundingBox(Physics::BulletTransformToTransform(t, float3::One).TransformBoundingBox(m_boundingBox)); aabbMin = Physics::Float3ToBulletVector(transformedBoundingBox.GetMinBounds()) * m_localScaling; aabbMax = Physics::Float3ToBulletVector(transformedBoundingBox.GetMaxBounds()) * m_localScaling; } void btBlockMeshCollisionShape::calculateLocalInertia(btScalar mass, btVector3& inertia) const { //moving concave objects not supported Panic("called"); inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); } <file_sep>/Engine/Source/Engine/Physics/SphereCollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/SphereCollisionShape.h" #include "Engine/Physics/BulletHeaders.h" Log_SetChannel(BoxCollisionShape); namespace Physics { SphereCollisionShape::SphereCollisionShape() : m_bounds(AABox::Zero), m_center(float3::Zero), m_radius(0.0f), m_pBulletShape(nullptr) { } SphereCollisionShape::SphereCollisionShape(const float3 &center, const float radius) { m_center = center; m_radius = radius; m_bounds.SetBounds(float3(-radius, -radius, -radius) + center, float3(radius, radius, radius) + center); m_pBulletShape = new btSphereShape(m_radius); } SphereCollisionShape::~SphereCollisionShape() { delete m_pBulletShape; } const COLLISION_SHAPE_TYPE SphereCollisionShape::GetType() const { return COLLISION_SHAPE_TYPE_SPHERE; } const AABox &SphereCollisionShape::GetLocalBoundingBox() const { return m_bounds; } bool SphereCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { AutoReleasePtr<ByteStream> pStream = ByteStream_CreateReadOnlyMemoryStream(pData, dataSize); return LoadFromStream(pStream, dataSize); } bool SphereCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { // check size if (dataSize != (sizeof(float3) + sizeof(float))) return false; BinaryReader binaryReader(pStream); binaryReader >> m_center >> m_radius; if (binaryReader.GetErrorState()) return false; // calculate bounds m_bounds.SetBounds(float3(-m_radius, -m_radius, -m_radius) + m_center, float3(m_radius, m_radius, m_radius) + m_center); delete m_pBulletShape; m_pBulletShape = new btSphereShape(m_radius); return true; } CollisionShape *SphereCollisionShape::CreateScaledShape(const float3 &scale) const { // straight up create a new shape, memory's gonna be the same anyway return new SphereCollisionShape(m_center, m_radius * Max(scale.x, Max(scale.y, scale.z))); } void SphereCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { // if we have a nonzero center, this has to be transformed prior to the world transform if (m_center.SquaredLength() > 0.0f) //worldTransform = worldTransform * btTransform(btMatrix3x3::getIdentity(), Float3ToBulletVector(m_center)); worldTransform.setOrigin(worldTransform.getOrigin() + Float3ToBulletVector(m_center)); } void SphereCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { // if we have a nonzero center, this has to be transformed prior to the world transform if (m_center.SquaredLength() > 0.0f) //worldTransform = worldTransform * btTransform(btMatrix3x3::getIdentity(), Float3ToBulletVector(m_center)); worldTransform.setOrigin(worldTransform.getOrigin() - Float3ToBulletVector(m_center)); } btCollisionShape *SphereCollisionShape::GetBulletShape() const { DebugAssert(m_pBulletShape != nullptr); return m_pBulletShape; } } // namespace Physics <file_sep>/Engine/Source/Renderer/RenderProxies/DirectionalLightRenderProxy.h #pragma once #include "Renderer/RenderProxy.h" class DirectionalLightRenderProxy : public RenderProxy { public: DirectionalLightRenderProxy(uint32 entityId, bool enabled = true, const float3 &lightColor = float3::One, const float3 &ambientColor = float3::Zero, uint32 shadowFlags = 0, const float3 &direction = float3::NegativeUnitZ); ~DirectionalLightRenderProxy(); // can be called at any time. void SetEnabled(bool newEnabled); void SetLightColor(const float3 &newColor); void SetAmbientColor(const float3 &newColor); void SetShadowFlags(uint32 newShadowFlags); void SetDirection(const float3 &newDirection); // virtual methods virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; protected: // read and write from render thread, no game thread access bool m_enabled; float3 m_lightColor; float3 m_ambientColor; uint32 m_shadowFlags; float3 m_direction; }; <file_sep>/Engine/Dependancies/CMakeLists.txt ################################################################################################### # glad Library ################################################################################################### set(GLAD_HEADER_FILES glad/include/EGL/eglext.h glad/include/EGL/egl.h glad/include/EGL/eglplatform.h glad/include/glad/glad_egl.h glad/include/glad/glad_glx.h glad/include/glad/glad.h glad/include/glad/glad_wgl.h glad/include/KHR/khrplatform.h ) set(GLAD_SOURCE_FILES glad/src/glad.c ) if(ANDROID OR EMSCRIPTEN) LIST(APPEND GLAD_SOURCE_FILES glad/src/glad_egl.c) else() LIST(APPEND GLAD_SOURCE_FILES glad/src/glad_glx.c) endif() # glad/src/glad_wgl.c add_library(glad STATIC ${GLAD_HEADER_FILES} ${GLAD_SOURCE_FILES}) target_include_directories(glad PUBLIC glad/include) #set_property(TARGET glad APPEND PROPERTY COMPILE_DEFINITIONS "SQUISH_USE_SSE=2") target_link_libraries(glad ${CMAKE_DL_LIBS}) ################################################################################################### # libfif Library ################################################################################################### set(FIF_HEADER_FILES libfif/dep/msvc/include/zconf.h libfif/dep/msvc/include/zlib.h libfif/include/libfif/fif.h libfif/include/libfif/fif_io.h libfif/include/libfif/fif_types.h libfif/src/fif_format.h libfif/src/fif_internal.h libfif/src/trace_format.h libfif/src/trace.h libfif/src/trace_stream.h ) set(FIF_SOURCE_FILES libfif/src/block.c libfif/src/compressor.c libfif/src/compressor_zlib.c libfif/src/dir.c libfif/src/file.c libfif/src/inode.c libfif/src/io_local.c libfif/src/io_memory.c libfif/src/log.c libfif/src/mount.c libfif/src/trace.c libfif/src/trace_stream.c libfif/src/util.c ) add_library(fif STATIC ${FIF_HEADER_FILES} ${FIF_SOURCE_FILES}) target_include_directories(fif PUBLIC libfif/include) target_include_directories(fif PRIVATE libfif/include libfif/src ${ZLIB_INCLUDE_DIRS}) target_link_libraries(fif ${ZLIB_LIBRARIES}) ################################################################################################### # lua Library ################################################################################################### set(LUA_HEADER_FILES lua/src/lstring.h lua/src/ltable.h lua/src/ltm.h lua/src/lua.h lua/src/lua.hpp lua/src/luaconf.h lua/src/lualib.h lua/src/lundump.h lua/src/lvm.h lua/src/lzio.h lua/src/lapi.h lua/src/lauxlib.h lua/src/lcode.h lua/src/lctype.h lua/src/ldebug.h lua/src/ldo.h lua/src/lfunc.h lua/src/lgc.h lua/src/llex.h lua/src/llimits.h lua/src/lmem.h lua/src/lobject.h lua/src/lopcodes.h lua/src/lparser.h lua/src/lstate.h lua/src/lprefix.h ) set(LUA_SOURCE_FILES lua/src/lstring.c lua/src/lstrlib.c lua/src/ltable.c lua/src/ltablib.c lua/src/ltm.c lua/src/lundump.c lua/src/lutf8lib.c lua/src/lvm.c lua/src/lzio.c lua/src/lapi.c lua/src/lauxlib.c lua/src/lbaselib.c lua/src/lbitlib.c lua/src/lcode.c lua/src/lcorolib.c lua/src/lctype.c lua/src/ldblib.c lua/src/ldebug.c lua/src/ldo.c lua/src/ldump.c lua/src/lfunc.c lua/src/lgc.c lua/src/linit.c lua/src/liolib.c lua/src/llex.c lua/src/lmathlib.c lua/src/lmem.c lua/src/loadlib.c lua/src/lobject.c lua/src/lopcodes.c lua/src/loslib.c lua/src/lparser.c lua/src/lstate.c ) add_library(lua STATIC ${LUA_HEADER_FILES} ${LUA_SOURCE_FILES}) target_include_directories(lua PUBLIC lua/src) #set_property(TARGET glad APPEND PROPERTY COMPILE_DEFINITIONS "SQUISH_USE_SSE=2") ################################################################################################### # squish Library ################################################################################################### set(SQUISH_HEADER_FILES squish/simd.h squish/squish.h squish/colourfit.h squish/simd_ve.h squish/singlecolourfit.h squish/colourblock.h squish/config.h squish/rangefit.h squish/simd_float.h squish/alpha.h squish/colourset.h squish/maths.h squish/simd_sse.h squish/clusterfit.h ) set(SQUISH_SOURCE_FILES squish/colourfit.cpp squish/colourblock.cpp squish/clusterfit.cpp squish/singlecolourfit.cpp squish/squish.cpp squish/maths.cpp squish/alpha.cpp squish/colourset.cpp squish/rangefit.cpp ) if(HAVE_SQUISH) add_library(squish STATIC ${SQUISH_HEADER_FILES} ${SQUISH_SOURCE_FILES}) target_include_directories(squish PUBLIC squish) set_property(TARGET squish APPEND PROPERTY COMPILE_DEFINITIONS "SQUISH_USE_SSE=2") endif() ################################################################################################### # SFMT Library ################################################################################################### set(SFMT_HEADER_FILES SFMT/SFMT.h SFMT/SFMT-alti.h SFMT/SFMT-common.h SFMT/SFMT-params.h SFMT/SFMT-params607.h SFMT/SFMT-params1279.h SFMT/SFMT-params2281.h SFMT/SFMT-params4253.h SFMT/SFMT-params11213.h SFMT/SFMT-params19937.h SFMT/SFMT-params44497.h SFMT/SFMT-params86243.h SFMT/SFMT-params132049.h SFMT/SFMT-params216091.h SFMT/SFMT-params.h SFMT/SFMT-sse2.h SFMT/SFMT-sse2-msc.h ) set(SFMT_SOURCE_FILES SFMT/SFMT.c ) add_library(SFMT STATIC ${SFMT_HEADER_FILES} ${SFMT_SOURCE_FILES}) target_include_directories(SFMT PUBLIC SFMT) set_property(TARGET SFMT APPEND PROPERTY COMPILE_DEFINITIONS "SFMT_MEXP=19937") if(HAVE_SFMT AND NOT EMSCRIPTEN AND NOT ANDROID) set_property(TARGET SFMT APPEND PROPERTY COMPILE_DEFINITIONS "HAVE_SSE2") endif() ################################################################################################### # Bullet Library ################################################################################################### set(BULLET_HEADER_FILES bullet/src/btBulletCollisionCommon.h bullet/src/btBulletDynamicsCommon.h bullet/src/BulletCollision/Gimpact/gim_box_set.h bullet/src/BulletCollision/Gimpact/btGImpactQuantizedBvh.h bullet/src/BulletCollision/Gimpact/btQuantization.h bullet/src/BulletCollision/Gimpact/gim_geom_types.h bullet/src/BulletCollision/Gimpact/btTriangleShapeEx.h bullet/src/BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h bullet/src/BulletCollision/Gimpact/gim_basic_geometry_operations.h bullet/src/BulletCollision/Gimpact/btContactProcessing.h bullet/src/BulletCollision/Gimpact/gim_clip_polygon.h bullet/src/BulletCollision/Gimpact/gim_radixsort.h bullet/src/BulletCollision/Gimpact/btCompoundFromGimpact.h bullet/src/BulletCollision/Gimpact/btClipPolygon.h bullet/src/BulletCollision/Gimpact/btBoxCollision.h bullet/src/BulletCollision/Gimpact/gim_box_collision.h bullet/src/BulletCollision/Gimpact/btGImpactBvh.h bullet/src/BulletCollision/Gimpact/gim_tri_collision.h bullet/src/BulletCollision/Gimpact/btGImpactMassUtil.h bullet/src/BulletCollision/Gimpact/gim_math.h bullet/src/BulletCollision/Gimpact/gim_contact.h bullet/src/BulletCollision/Gimpact/btGImpactShape.h bullet/src/BulletCollision/Gimpact/btGeometryOperations.h bullet/src/BulletCollision/Gimpact/gim_bitset.h bullet/src/BulletCollision/Gimpact/gim_geometry.h bullet/src/BulletCollision/Gimpact/gim_hash_table.h bullet/src/BulletCollision/Gimpact/btGenericPoolAllocator.h bullet/src/BulletCollision/Gimpact/gim_array.h bullet/src/BulletCollision/Gimpact/gim_linear_math.h bullet/src/BulletCollision/Gimpact/gim_memory.h bullet/src/BulletCollision/CollisionShapes/btSphereShape.h bullet/src/BulletCollision/CollisionShapes/btShapeHull.h bullet/src/BulletCollision/CollisionShapes/btConvexPointCloudShape.h bullet/src/BulletCollision/CollisionShapes/btConvexShape.h bullet/src/BulletCollision/CollisionShapes/btBoxShape.h bullet/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h bullet/src/BulletCollision/CollisionShapes/btConvexInternalShape.h bullet/src/BulletCollision/CollisionShapes/btTetrahedronShape.h bullet/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.h bullet/src/BulletCollision/CollisionShapes/btCollisionShape.h bullet/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h bullet/src/BulletCollision/CollisionShapes/btTriangleShape.h bullet/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h bullet/src/BulletCollision/CollisionShapes/btBox2dShape.h bullet/src/BulletCollision/CollisionShapes/btConvexPolyhedron.h bullet/src/BulletCollision/CollisionShapes/btTriangleCallback.h bullet/src/BulletCollision/CollisionShapes/btTriangleInfoMap.h bullet/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h bullet/src/BulletCollision/CollisionShapes/btTriangleMesh.h bullet/src/BulletCollision/CollisionShapes/btOptimizedBvh.h bullet/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h bullet/src/BulletCollision/CollisionShapes/btCompoundShape.h bullet/src/BulletCollision/CollisionShapes/btConeShape.h bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h bullet/src/BulletCollision/CollisionShapes/btConvex2dShape.h bullet/src/BulletCollision/CollisionShapes/btTriangleBuffer.h bullet/src/BulletCollision/CollisionShapes/btUniformScalingShape.h bullet/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h bullet/src/BulletCollision/CollisionShapes/btConvexHullShape.h bullet/src/BulletCollision/CollisionShapes/btEmptyShape.h bullet/src/BulletCollision/CollisionShapes/btMaterial.h bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h bullet/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h bullet/src/BulletCollision/CollisionShapes/btConcaveShape.h bullet/src/BulletCollision/CollisionShapes/btCapsuleShape.h bullet/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h bullet/src/BulletCollision/CollisionShapes/btStridingMeshInterface.h bullet/src/BulletCollision/CollisionShapes/btCylinderShape.h bullet/src/BulletCollision/CollisionShapes/btCollisionMargin.h bullet/src/BulletCollision/CollisionShapes/btMultiSphereShape.h bullet/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h bullet/src/BulletCollision/BroadphaseCollision/btDispatcher.h bullet/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h bullet/src/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h bullet/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h bullet/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h bullet/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h bullet/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h bullet/src/BulletCollision/BroadphaseCollision/btDbvt.h bullet/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h bullet/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h bullet/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h bullet/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btCollisionCreateFunc.h bullet/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.h bullet/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btUnionFind.h bullet/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h bullet/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h bullet/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btInternalEdgeUtility.h bullet/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h bullet/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.h bullet/src/BulletCollision/CollisionDispatch/btHashedSimplePairCache.h bullet/src/BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btManifoldResult.h bullet/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h bullet/src/BulletCollision/CollisionDispatch/btCollisionObject.h bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.h bullet/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h bullet/src/BulletCollision/CollisionDispatch/btGhostObject.h bullet/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h bullet/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h bullet/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h bullet/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h bullet/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.h bullet/src/BulletCollision/NarrowPhaseCollision/btManifoldPoint.h bullet/src/BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h bullet/src/BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h bullet/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h bullet/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h bullet/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h bullet/src/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h bullet/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h bullet/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h bullet/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h bullet/src/BulletCollision/NarrowPhaseCollision/btPointCollector.h bullet/src/BulletCollision/NarrowPhaseCollision/btConvexCast.h bullet/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h bullet/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h bullet/src/BulletDynamics/Dynamics/btActionInterface.h bullet/src/BulletDynamics/Dynamics/btRigidBody.h bullet/src/BulletDynamics/Dynamics/btDynamicsWorld.h bullet/src/BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.h bullet/src/BulletDynamics/Featherstone/btMultiBodyConstraint.h bullet/src/BulletDynamics/Featherstone/btMultiBodySolverConstraint.h bullet/src/BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h bullet/src/BulletDynamics/Featherstone/btMultiBodyLink.h bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h bullet/src/BulletDynamics/Featherstone/btMultiBodyJointMotor.h bullet/src/BulletDynamics/Featherstone/btMultiBodyLinkCollider.h bullet/src/BulletDynamics/Featherstone/btMultiBody.h bullet/src/BulletDynamics/Featherstone/btMultiBodyPoint2Point.h bullet/src/BulletDynamics/ConstraintSolver/btJacobianEntry.h bullet/src/BulletDynamics/ConstraintSolver/btSolverBody.h bullet/src/BulletDynamics/ConstraintSolver/btContactConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h bullet/src/BulletDynamics/ConstraintSolver/btHingeConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btGeneric6DofSpringConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.h bullet/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btSolverConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h bullet/src/BulletDynamics/ConstraintSolver/btContactSolverInfo.h bullet/src/BulletDynamics/ConstraintSolver/btGearConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h bullet/src/BulletDynamics/ConstraintSolver/btFixedConstraint.h bullet/src/BulletDynamics/Vehicle/btVehicleRaycaster.h bullet/src/BulletDynamics/Vehicle/btWheelInfo.h bullet/src/BulletDynamics/Vehicle/btRaycastVehicle.h bullet/src/BulletDynamics/MLCPSolvers/btMLCPSolverInterface.h bullet/src/BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h bullet/src/BulletDynamics/MLCPSolvers/btPATHSolver.h bullet/src/BulletDynamics/MLCPSolvers/btDantzigLCP.h bullet/src/BulletDynamics/MLCPSolvers/btMLCPSolver.h bullet/src/BulletDynamics/MLCPSolvers/btDantzigSolver.h bullet/src/BulletDynamics/Character/btCharacterControllerInterface.h bullet/src/BulletDynamics/Character/btKinematicCharacterController.h bullet/src/LinearMath/btSerializer.h bullet/src/LinearMath/btAlignedAllocator.h bullet/src/LinearMath/btConvexHull.h bullet/src/LinearMath/btMinMax.h bullet/src/LinearMath/btConvexHullComputer.h bullet/src/LinearMath/btRandom.h bullet/src/LinearMath/btAabbUtil2.h bullet/src/LinearMath/btTransform.h bullet/src/LinearMath/btQuadWord.h bullet/src/LinearMath/btAlignedObjectArray.h bullet/src/LinearMath/btMatrixX.h bullet/src/LinearMath/btMatrix3x3.h bullet/src/LinearMath/btVector3.h bullet/src/LinearMath/btList.h bullet/src/LinearMath/btIDebugDraw.h bullet/src/LinearMath/btMotionState.h bullet/src/LinearMath/btQuaternion.h bullet/src/LinearMath/btGeometryUtil.h bullet/src/LinearMath/btPoolAllocator.h bullet/src/LinearMath/btQuickprof.h bullet/src/LinearMath/btScalar.h bullet/src/LinearMath/btTransformUtil.h bullet/src/LinearMath/btDefaultMotionState.h bullet/src/LinearMath/btHashMap.h bullet/src/LinearMath/btPolarDecomposition.h bullet/src/LinearMath/btStackAlloc.h bullet/src/LinearMath/btGrahamScan2dConvexHull.h bullet/Extras/HACD/hacdCircularList.h bullet/Extras/HACD/hacdVersion.h bullet/Extras/HACD/hacdGraph.h bullet/Extras/HACD/hacdManifoldMesh.h bullet/Extras/HACD/hacdVector.h bullet/Extras/HACD/hacdHACD.h bullet/Extras/HACD/hacdICHull.h bullet/Extras/Serialize/BulletFileLoader/bDefines.h bullet/Extras/Serialize/BulletFileLoader/autogenerated/bullet.h bullet/Extras/Serialize/BulletFileLoader/bDNA.h bullet/Extras/Serialize/BulletFileLoader/btBulletFile.h bullet/Extras/Serialize/BulletFileLoader/bChunk.h bullet/Extras/Serialize/BulletFileLoader/bCommon.h bullet/Extras/Serialize/BulletFileLoader/bFile.h bullet/Extras/Serialize/BulletWorldImporter/btWorldImporter.h bullet/Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.h ) set(BULLET_SOURCE_FILES bullet/src/BulletCollision/Gimpact/btContactProcessing.cpp bullet/src/BulletCollision/Gimpact/gim_tri_collision.cpp bullet/src/BulletCollision/Gimpact/btGImpactQuantizedBvh.cpp bullet/src/BulletCollision/Gimpact/btGImpactBvh.cpp bullet/src/BulletCollision/Gimpact/btGImpactCollisionAlgorithm.cpp bullet/src/BulletCollision/Gimpact/gim_memory.cpp bullet/src/BulletCollision/Gimpact/gim_contact.cpp bullet/src/BulletCollision/Gimpact/btGenericPoolAllocator.cpp bullet/src/BulletCollision/Gimpact/btTriangleShapeEx.cpp bullet/src/BulletCollision/Gimpact/btGImpactShape.cpp bullet/src/BulletCollision/Gimpact/gim_box_set.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleMesh.cpp bullet/src/BulletCollision/CollisionShapes/btCylinderShape.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleBuffer.cpp bullet/src/BulletCollision/CollisionShapes/btConvexHullShape.cpp bullet/src/BulletCollision/CollisionShapes/btEmptyShape.cpp bullet/src/BulletCollision/CollisionShapes/btBox2dShape.cpp bullet/src/BulletCollision/CollisionShapes/btMultiSphereShape.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp bullet/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp bullet/src/BulletCollision/CollisionShapes/btShapeHull.cpp bullet/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.cpp bullet/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp bullet/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp bullet/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp bullet/src/BulletCollision/CollisionShapes/btCompoundShape.cpp bullet/src/BulletCollision/CollisionShapes/btCapsuleShape.cpp bullet/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp bullet/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp bullet/src/BulletCollision/CollisionShapes/btConvexPolyhedron.cpp bullet/src/BulletCollision/CollisionShapes/btBoxShape.cpp bullet/src/BulletCollision/CollisionShapes/btConvex2dShape.cpp bullet/src/BulletCollision/CollisionShapes/btCollisionShape.cpp bullet/src/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp bullet/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.cpp bullet/src/BulletCollision/CollisionShapes/btConcaveShape.cpp bullet/src/BulletCollision/CollisionShapes/btSphereShape.cpp bullet/src/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp bullet/src/BulletCollision/CollisionShapes/btConeShape.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleCallback.cpp bullet/src/BulletCollision/CollisionShapes/btConvexShape.cpp bullet/src/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp bullet/src/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp bullet/src/BulletCollision/CollisionShapes/btConvexPointCloudShape.cpp bullet/src/BulletCollision/CollisionShapes/btOptimizedBvh.cpp bullet/src/BulletCollision/CollisionShapes/btTetrahedronShape.cpp bullet/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp bullet/src/BulletCollision/BroadphaseCollision/btAxisSweep3.cpp bullet/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.cpp bullet/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp bullet/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp bullet/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp bullet/src/BulletCollision/BroadphaseCollision/btDispatcher.cpp bullet/src/BulletCollision/BroadphaseCollision/btDbvt.cpp bullet/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp bullet/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp bullet/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp bullet/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp bullet/src/BulletCollision/CollisionDispatch/btInternalEdgeUtility.cpp bullet/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btBox2dBox2dCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btHashedSimplePairCache.cpp bullet/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp bullet/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btGhostObject.cpp bullet/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btManifoldResult.cpp bullet/src/BulletCollision/CollisionDispatch/btCompoundCompoundCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp bullet/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp bullet/src/BulletCollision/CollisionDispatch/btUnionFind.cpp bullet/src/BulletCollision/CollisionDispatch/btCollisionObject.cpp bullet/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp bullet/src/BulletCollision/CollisionDispatch/btCollisionWorld.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btConvexCast.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp bullet/src/BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.cpp bullet/src/BulletDynamics/Dynamics/Bullet-C-API.cpp bullet/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp bullet/src/BulletDynamics/Dynamics/btRigidBody.cpp bullet/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyConstraint.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyPoint2Point.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyConstraintSolver.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyJointMotor.cpp bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp bullet/src/BulletDynamics/Featherstone/btMultiBody.cpp bullet/src/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btGearConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btFixedConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btHinge2Constraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp bullet/src/BulletDynamics/ConstraintSolver/btGeneric6DofSpringConstraint.cpp bullet/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp bullet/src/BulletDynamics/Vehicle/btWheelInfo.cpp bullet/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp bullet/src/BulletDynamics/MLCPSolvers/btDantzigLCP.cpp bullet/src/BulletDynamics/MLCPSolvers/btMLCPSolver.cpp bullet/src/BulletDynamics/Character/btKinematicCharacterController.cpp bullet/src/LinearMath/btConvexHull.cpp bullet/src/LinearMath/btQuickprof.cpp bullet/src/LinearMath/btVector3.cpp bullet/src/LinearMath/btConvexHullComputer.cpp bullet/src/LinearMath/btAlignedAllocator.cpp bullet/src/LinearMath/btPolarDecomposition.cpp bullet/src/LinearMath/btGeometryUtil.cpp bullet/src/LinearMath/btSerializer.cpp bullet/Extras/HACD/hacdManifoldMesh.cpp bullet/Extras/HACD/hacdGraph.cpp bullet/Extras/HACD/hacdICHull.cpp bullet/Extras/HACD/hacdHACD.cpp bullet/Extras/Serialize/BulletFileLoader/bChunk.cpp bullet/Extras/Serialize/BulletFileLoader/bFile.cpp bullet/Extras/Serialize/BulletFileLoader/btBulletFile.cpp bullet/Extras/Serialize/BulletFileLoader/bDNA.cpp bullet/Extras/Serialize/BulletWorldImporter/btWorldImporter.cpp bullet/Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.cpp ) add_library(bullet STATIC ${BULLET_HEADER_FILES} ${BULLET_SOURCE_FILES}) target_include_directories(bullet PRIVATE bullet/src bullet/Extras/Serialize/BulletWorldImporter bullet/Extras/HACD) target_include_directories(bullet INTERFACE bullet/src bullet/Extras/Serialize/BulletWorldImporter bullet/Extras/HACD) ################################################################################################### # imgui Library ################################################################################################### set(IMGUI_HEADER_FILES imgui/imgui.h imgui/stb_rect_pack.h imgui/stb_textedit.h imgui/stb_truetype.h imgui/imconfig.h ) set(IMGUI_SOURCE_FILES imgui/imgui.cpp ) if(WITH_IMGUI) add_library(imgui STATIC ${IMGUI_HEADER_FILES} ${IMGUI_SOURCE_FILES}) target_include_directories(imgui PUBLIC imgui) #set_property(TARGET imgui APPEND PROPERTY COMPILE_DEFINITIONS "imgui_USE_SSE=2") endif() ################################################################################################### # HLSLTranslator Library ################################################################################################### set(HLSLTRANSLATOR_HEADER_FILES HLSLTranslator/include/HLSLTranslator_GLSL.h HLSLTranslator/include/HLSLTranslator.h HLSLTranslator/src/gallium/auxiliary/util/u_atomic.h HLSLTranslator/src/gallium/auxiliary/util/u_cpu_detect.h HLSLTranslator/src/gallium/auxiliary/util/u_debug.h HLSLTranslator/src/gallium/auxiliary/util/u_math.h HLSLTranslator/src/glsl/ast.h HLSLTranslator/src/glsl/blob.h HLSLTranslator/src/glsl/builtin_type_macros.h HLSLTranslator/src/glsl/glsl_parser_extras.h HLSLTranslator/src/glsl/glsl_symbol_table.h HLSLTranslator/src/glsl/glsl_types.h HLSLTranslator/src/glsl/hlsl_parser.h HLSLTranslator/src/glsl/hlslpp/hlslpp.h HLSLTranslator/src/glsl/hlslpp/hlslpp-parse.h HLSLTranslator/src/glsl/ir_basic_block.h HLSLTranslator/src/glsl/ir_builder.h HLSLTranslator/src/glsl/ir_expression_flattening.h HLSLTranslator/src/glsl/ir_function_inlining.h HLSLTranslator/src/glsl/ir.h HLSLTranslator/src/glsl/ir_hierarchical_visitor.h HLSLTranslator/src/glsl/ir_optimization.h HLSLTranslator/src/glsl/ir_print_visitor.h HLSLTranslator/src/glsl/ir_reader.h HLSLTranslator/src/glsl/ir_rvalue_visitor.h HLSLTranslator/src/glsl/ir_uniform.h HLSLTranslator/src/glsl/ir_variable_refcount.h HLSLTranslator/src/glsl/ir_visitor.h HLSLTranslator/src/glsl/linker.h HLSLTranslator/src/glsl/link_uniform_block_active_visitor.h HLSLTranslator/src/glsl/link_varyings.h HLSLTranslator/src/glsl/list.h HLSLTranslator/src/glsl/loop_analysis.h HLSLTranslator/src/glsl/program.h HLSLTranslator/src/glsl/s_expression.h HLSLTranslator/src/glsl/shader_enums.h HLSLTranslator/src/glsl/standalone_scaffolding.h HLSLTranslator/src/ir_print_glsl_visitor.h HLSLTranslator/src/mesa/program/hash_table.h HLSLTranslator/src/mesa/program/ir_to_mesa.h HLSLTranslator/src/mesa/program/prog_instruction.h HLSLTranslator/src/mesa/program/prog_parameter.h HLSLTranslator/src/mesa/program/prog_statevars.h HLSLTranslator/src/mesa/program/symbol_table.h HLSLTranslator/src/util/hash_table.h HLSLTranslator/src/util/list.h HLSLTranslator/src/util/macros.h HLSLTranslator/src/util/ralloc.h HLSLTranslator/src/util/rounding.h HLSLTranslator/src/util/simple_list.h HLSLTranslator/src/util/strtod.h ) set(HLSLTRANSLATOR_SOURCE_FILES HLSLTranslator/src/gallium/auxiliary/util/u_cpu_detect.c HLSLTranslator/src/gallium/auxiliary/util/u_math.c HLSLTranslator/src/glsl/ast_array_index.cpp HLSLTranslator/src/glsl/ast_expr.cpp HLSLTranslator/src/glsl/ast_function.cpp HLSLTranslator/src/glsl/ast_to_hir.cpp HLSLTranslator/src/glsl/ast_type.cpp HLSLTranslator/src/glsl/blob.c HLSLTranslator/src/glsl/builtin_functions.cpp HLSLTranslator/src/glsl/builtin_types.cpp HLSLTranslator/src/glsl/builtin_variables.cpp HLSLTranslator/src/glsl/glsl_parser_extras.cpp HLSLTranslator/src/glsl/glsl_symbol_table.cpp HLSLTranslator/src/glsl/glsl_types.cpp HLSLTranslator/src/glsl/hir_field_selection.cpp HLSLTranslator/src/glsl/hlsl_conversion.cpp HLSLTranslator/src/glsl/hlsl_lexer.cpp HLSLTranslator/src/glsl/hlsl_parser.cpp HLSLTranslator/src/glsl/hlslpp/hlslpp.c HLSLTranslator/src/glsl/hlslpp/hlslpp-lex.c HLSLTranslator/src/glsl/hlslpp/hlslpp-parse.c HLSLTranslator/src/glsl/ir_basic_block.cpp HLSLTranslator/src/glsl/ir_builder.cpp HLSLTranslator/src/glsl/ir_clone.cpp HLSLTranslator/src/glsl/ir_constant_expression.cpp HLSLTranslator/src/glsl/ir.cpp HLSLTranslator/src/glsl/ir_equals.cpp HLSLTranslator/src/glsl/ir_expression_flattening.cpp HLSLTranslator/src/glsl/ir_function_can_inline.cpp HLSLTranslator/src/glsl/ir_function.cpp HLSLTranslator/src/glsl/ir_function_detect_recursion.cpp HLSLTranslator/src/glsl/ir_hierarchical_visitor.cpp HLSLTranslator/src/glsl/ir_hv_accept.cpp HLSLTranslator/src/glsl/ir_import_prototypes.cpp HLSLTranslator/src/glsl/ir_print_visitor.cpp HLSLTranslator/src/glsl/ir_reader.cpp HLSLTranslator/src/glsl/ir_rvalue_visitor.cpp HLSLTranslator/src/glsl/ir_set_program_inouts.cpp HLSLTranslator/src/glsl/ir_validate.cpp HLSLTranslator/src/glsl/ir_variable_refcount.cpp HLSLTranslator/src/glsl/link_atomics.cpp HLSLTranslator/src/glsl/linker.cpp HLSLTranslator/src/glsl/link_functions.cpp HLSLTranslator/src/glsl/link_interface_blocks.cpp HLSLTranslator/src/glsl/link_uniform_block_active_visitor.cpp HLSLTranslator/src/glsl/link_uniform_blocks.cpp HLSLTranslator/src/glsl/link_uniform_initializers.cpp HLSLTranslator/src/glsl/link_uniforms.cpp HLSLTranslator/src/glsl/link_varyings.cpp HLSLTranslator/src/glsl/loop_analysis.cpp HLSLTranslator/src/glsl/loop_controls.cpp HLSLTranslator/src/glsl/loop_unroll.cpp HLSLTranslator/src/glsl/lower_clip_distance.cpp HLSLTranslator/src/glsl/lower_const_arrays_to_uniforms.cpp HLSLTranslator/src/glsl/lower_discard.cpp HLSLTranslator/src/glsl/lower_discard_flow.cpp HLSLTranslator/src/glsl/lower_if_to_cond_assign.cpp HLSLTranslator/src/glsl/lower_instructions.cpp HLSLTranslator/src/glsl/lower_jumps.cpp HLSLTranslator/src/glsl/lower_mat_op_to_vec.cpp HLSLTranslator/src/glsl/lower_named_interface_blocks.cpp HLSLTranslator/src/glsl/lower_noise.cpp HLSLTranslator/src/glsl/lower_offset_array.cpp HLSLTranslator/src/glsl/lower_output_reads.cpp HLSLTranslator/src/glsl/lower_packed_varyings.cpp HLSLTranslator/src/glsl/lower_packing_builtins.cpp HLSLTranslator/src/glsl/lower_texture_projection.cpp HLSLTranslator/src/glsl/lower_ubo_reference.cpp HLSLTranslator/src/glsl/lower_variable_index_to_cond_assign.cpp HLSLTranslator/src/glsl/lower_vec_index_to_cond_assign.cpp HLSLTranslator/src/glsl/lower_vec_index_to_swizzle.cpp HLSLTranslator/src/glsl/lower_vector.cpp HLSLTranslator/src/glsl/lower_vector_insert.cpp HLSLTranslator/src/glsl/lower_vertex_id.cpp HLSLTranslator/src/glsl/opt_algebraic.cpp HLSLTranslator/src/glsl/opt_array_splitting.cpp HLSLTranslator/src/glsl/opt_conditional_discard.cpp HLSLTranslator/src/glsl/opt_constant_folding.cpp HLSLTranslator/src/glsl/opt_constant_propagation.cpp HLSLTranslator/src/glsl/opt_constant_variable.cpp HLSLTranslator/src/glsl/opt_copy_propagation.cpp HLSLTranslator/src/glsl/opt_copy_propagation_elements.cpp HLSLTranslator/src/glsl/opt_cse.cpp HLSLTranslator/src/glsl/opt_dead_builtin_variables.cpp HLSLTranslator/src/glsl/opt_dead_builtin_varyings.cpp HLSLTranslator/src/glsl/opt_dead_code.cpp HLSLTranslator/src/glsl/opt_dead_code_local.cpp HLSLTranslator/src/glsl/opt_dead_functions.cpp HLSLTranslator/src/glsl/opt_flatten_nested_if_blocks.cpp HLSLTranslator/src/glsl/opt_flip_matrices.cpp HLSLTranslator/src/glsl/opt_function_inlining.cpp HLSLTranslator/src/glsl/opt_if_simplification.cpp HLSLTranslator/src/glsl/opt_minmax.cpp HLSLTranslator/src/glsl/opt_noop_swizzle.cpp HLSLTranslator/src/glsl/opt_rebalance_tree.cpp HLSLTranslator/src/glsl/opt_redundant_jumps.cpp HLSLTranslator/src/glsl/opt_structure_splitting.cpp HLSLTranslator/src/glsl/opt_swizzle_swizzle.cpp HLSLTranslator/src/glsl/opt_tree_grafting.cpp HLSLTranslator/src/glsl/opt_vectorize.cpp HLSLTranslator/src/glsl/s_expression.cpp HLSLTranslator/src/glsl/standalone_scaffolding.cpp HLSLTranslator/src/HLSLTranslator.cpp HLSLTranslator/src/ir_print_glsl_visitor.cpp HLSLTranslator/src/mesa/main/imports.c HLSLTranslator/src/mesa/program/prog_hash_table.c HLSLTranslator/src/mesa/program/symbol_table.c HLSLTranslator/src/util/hash_table.c HLSLTranslator/src/util/ralloc.c HLSLTranslator/src/util/strtod.c ) # TODO: Make shared instead if(HAVE_HLSLTRANSLATOR) add_library(HLSLTranslator STATIC ${HLSLTRANSLATOR_HEADER_FILES} ${HLSLTRANSLATOR_SOURCE_FILES}) target_include_directories(HLSLTranslator PUBLIC HLSLTranslator/include) target_include_directories(HLSLTranslator PRIVATE HLSLTranslator/include HLSLTranslator/src HLSLTranslator/src/glsl HLSLTranslator/src/mesa HLSLTranslator/src/mesa/main HLSLTranslator/src/gallium/auxiliary) target_compile_definitions(HLSLTranslator PRIVATE "HAVE_PTHREAD") endif() ################################################################################################### # YBaseLib Library ################################################################################################### set(YBASELIB_HEADER_FILES YBaseLib/Include/YBaseLib/AlignedMemArray.h YBaseLib/Include/YBaseLib/Android/AndroidBarrier.h YBaseLib/Include/YBaseLib/Android/AndroidConditionVariable.h YBaseLib/Include/YBaseLib/Android/AndroidEvent.h YBaseLib/Include/YBaseLib/Android/AndroidMutex.h YBaseLib/Include/YBaseLib/Android/AndroidReadWriteLock.h YBaseLib/Include/YBaseLib/Android/AndroidRecursiveMutex.h YBaseLib/Include/YBaseLib/Android/AndroidThread.h YBaseLib/Include/YBaseLib/Array.h YBaseLib/Include/YBaseLib/Assert.h YBaseLib/Include/YBaseLib/Atomic.h YBaseLib/Include/YBaseLib/AutoReleasePtr.h YBaseLib/Include/YBaseLib/Barrier.h YBaseLib/Include/YBaseLib/BinaryBlob.h YBaseLib/Include/YBaseLib/BinaryReadBuffer.h YBaseLib/Include/YBaseLib/BinaryReader.h YBaseLib/Include/YBaseLib/BinaryWriteBuffer.h YBaseLib/Include/YBaseLib/BinaryWriter.h YBaseLib/Include/YBaseLib/BitSet.h YBaseLib/Include/YBaseLib/ByteStream.h YBaseLib/Include/YBaseLib/CallbackQueue.h YBaseLib/Include/YBaseLib/CIStringHashTable.h YBaseLib/Include/YBaseLib/Common.h YBaseLib/Include/YBaseLib/ConditionVariable.h YBaseLib/Include/YBaseLib/CPUID.h YBaseLib/Include/YBaseLib/CRC32.h YBaseLib/Include/YBaseLib/CString.h YBaseLib/Include/YBaseLib/Endian.h YBaseLib/Include/YBaseLib/Error.h YBaseLib/Include/YBaseLib/Event.h YBaseLib/Include/YBaseLib/Exception.h YBaseLib/Include/YBaseLib/FileSystem.h YBaseLib/Include/YBaseLib/Functor.h YBaseLib/Include/YBaseLib/HashTable.h YBaseLib/Include/YBaseLib/HashTrait.h YBaseLib/Include/YBaseLib/HTML5/HTML5Barrier.h YBaseLib/Include/YBaseLib/HTML5/HTML5ConditionVariable.h YBaseLib/Include/YBaseLib/HTML5/HTML5Event.h YBaseLib/Include/YBaseLib/HTML5/HTML5Mutex.h YBaseLib/Include/YBaseLib/HTML5/HTML5ReadWriteLock.h YBaseLib/Include/YBaseLib/HTML5/HTML5RecursiveMutex.h YBaseLib/Include/YBaseLib/HTML5/HTML5Thread.h YBaseLib/Include/YBaseLib/IntrusiveLinkedList.h YBaseLib/Include/YBaseLib/KeyValuePair.h YBaseLib/Include/YBaseLib/LinkedList.h YBaseLib/Include/YBaseLib/Log.h YBaseLib/Include/YBaseLib/Math.h YBaseLib/Include/YBaseLib/MD5Digest.h YBaseLib/Include/YBaseLib/MemArray.h YBaseLib/Include/YBaseLib/Memory.h YBaseLib/Include/YBaseLib/Mutex.h YBaseLib/Include/YBaseLib/MutexLock.h YBaseLib/Include/YBaseLib/NameTable.h YBaseLib/Include/YBaseLib/NonCopyable.h YBaseLib/Include/YBaseLib/NumericLimits.h YBaseLib/Include/YBaseLib/Pair.h YBaseLib/Include/YBaseLib/Platform.h YBaseLib/Include/YBaseLib/PODArray.h YBaseLib/Include/YBaseLib/POSIX/POSIXBarrier.h YBaseLib/Include/YBaseLib/POSIX/POSIXConditionVariable.h YBaseLib/Include/YBaseLib/POSIX/POSIXEvent.h YBaseLib/Include/YBaseLib/POSIX/POSIXMutex.h YBaseLib/Include/YBaseLib/POSIX/POSIXReadWriteLock.h YBaseLib/Include/YBaseLib/POSIX/POSIXRecursiveMutex.h YBaseLib/Include/YBaseLib/POSIX/POSIXSubprocess.h YBaseLib/Include/YBaseLib/POSIX/POSIXThread.h YBaseLib/Include/YBaseLib/ProgressCallbacks.h YBaseLib/Include/YBaseLib/ReadWriteLock.h YBaseLib/Include/YBaseLib/RecursiveMutex.h YBaseLib/Include/YBaseLib/RecursiveMutexLock.h YBaseLib/Include/YBaseLib/ReferenceCounted.h YBaseLib/Include/YBaseLib/ReferenceCountedHolder.h YBaseLib/Include/YBaseLib/Singleton.h YBaseLib/Include/YBaseLib/StringConverter.h YBaseLib/Include/YBaseLib/String.h YBaseLib/Include/YBaseLib/StringHashTable.h YBaseLib/Include/YBaseLib/StringParser.h YBaseLib/Include/YBaseLib/Subprocess.h YBaseLib/Include/YBaseLib/TextReader.h YBaseLib/Include/YBaseLib/TextWriter.h YBaseLib/Include/YBaseLib/Thread.h YBaseLib/Include/YBaseLib/ThreadPool.h YBaseLib/Include/YBaseLib/Timer.h YBaseLib/Include/YBaseLib/Timestamp.h YBaseLib/Include/YBaseLib/Windows/WindowsBarrier.h YBaseLib/Include/YBaseLib/Windows/WindowsConditionVariable.h YBaseLib/Include/YBaseLib/Windows/WindowsEvent.h YBaseLib/Include/YBaseLib/Windows/WindowsHeaders.h YBaseLib/Include/YBaseLib/Windows/WindowsMutex.h YBaseLib/Include/YBaseLib/Windows/WindowsReadWriteLock.h YBaseLib/Include/YBaseLib/Windows/WindowsRecursiveMutex.h YBaseLib/Include/YBaseLib/Windows/WindowsSubprocess.h YBaseLib/Include/YBaseLib/Windows/WindowsThread.h YBaseLib/Include/YBaseLib/XMLReader.h YBaseLib/Include/YBaseLib/XMLWriter.h YBaseLib/Include/YBaseLib/ZipArchive.h YBaseLib/Include/YBaseLib/ZLibHelpers.h ) set(YBASELIB_SOURCE_FILES YBaseLib/Source/YBaseLib/Android/AndroidBarrier.cpp YBaseLib/Source/YBaseLib/Android/AndroidConditionVariable.cpp YBaseLib/Source/YBaseLib/Android/AndroidEvent.cpp YBaseLib/Source/YBaseLib/Android/AndroidFileSystem.cpp YBaseLib/Source/YBaseLib/Android/AndroidPlatform.cpp YBaseLib/Source/YBaseLib/Android/AndroidReadWriteLock.cpp YBaseLib/Source/YBaseLib/Android/AndroidThread.cpp YBaseLib/Source/YBaseLib/Assert.cpp YBaseLib/Source/YBaseLib/Atomic.cpp YBaseLib/Source/YBaseLib/BinaryBlob.cpp YBaseLib/Source/YBaseLib/BinaryReadBuffer.cpp YBaseLib/Source/YBaseLib/BinaryReader.cpp YBaseLib/Source/YBaseLib/BinaryWriteBuffer.cpp YBaseLib/Source/YBaseLib/BinaryWriter.cpp YBaseLib/Source/YBaseLib/ByteStream.cpp YBaseLib/Source/YBaseLib/CallbackQueue.cpp YBaseLib/Source/YBaseLib/CPUID.cpp YBaseLib/Source/YBaseLib/CRC32.cpp YBaseLib/Source/YBaseLib/CString.cpp YBaseLib/Source/YBaseLib/Endian.cpp YBaseLib/Source/YBaseLib/Error.cpp YBaseLib/Source/YBaseLib/Exception.cpp YBaseLib/Source/YBaseLib/FileSystem.cpp YBaseLib/Source/YBaseLib/HashTrait.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5Barrier.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5ConditionVariable.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5FileSystem.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5Platform.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5ReadWriteLock.cpp YBaseLib/Source/YBaseLib/HTML5/HTML5Thread.cpp YBaseLib/Source/YBaseLib/Log.cpp YBaseLib/Source/YBaseLib/Math.cpp YBaseLib/Source/YBaseLib/MD5Digest.cpp YBaseLib/Source/YBaseLib/Memory.cpp YBaseLib/Source/YBaseLib/NameTable.cpp YBaseLib/Source/YBaseLib/NumericLimits.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXBarrier.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXConditionVariable.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXFileSystem.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXPlatform.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXReadWriteLock.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXSubprocess.cpp YBaseLib/Source/YBaseLib/POSIX/POSIXThread.cpp YBaseLib/Source/YBaseLib/ProgressCallbacks.cpp YBaseLib/Source/YBaseLib/ReferenceCounted.cpp YBaseLib/Source/YBaseLib/StringConverter.cpp YBaseLib/Source/YBaseLib/String.cpp YBaseLib/Source/YBaseLib/StringParser.cpp YBaseLib/Source/YBaseLib/TextReader.cpp YBaseLib/Source/YBaseLib/TextWriter.cpp YBaseLib/Source/YBaseLib/ThreadPool.cpp YBaseLib/Source/YBaseLib/Timer.cpp YBaseLib/Source/YBaseLib/Timestamp.cpp YBaseLib/Source/YBaseLib/Windows/WindowsBarrier.cpp YBaseLib/Source/YBaseLib/Windows/WindowsConditionVariable.cpp YBaseLib/Source/YBaseLib/Windows/WindowsFileSystem.cpp YBaseLib/Source/YBaseLib/Windows/WindowsPlatform.cpp YBaseLib/Source/YBaseLib/Windows/WindowsReadWriteLock.cpp YBaseLib/Source/YBaseLib/Windows/WindowsSubprocess.cpp YBaseLib/Source/YBaseLib/Windows/WindowsThread.cpp YBaseLib/Source/YBaseLib/XMLReader.cpp YBaseLib/Source/YBaseLib/XMLWriter.cpp YBaseLib/Source/YBaseLib/ZipArchive.cpp YBaseLib/Source/YBaseLib/ZLibHelpers.cpp ) set(YBASELIB_EXTRA_DEFINES "") set(YBASELIB_EXTRA_LIBRARIES "") if(HAVE_LIBXML2) LIST(APPEND YBASELIB_EXTRA_DEFINES "HAVE_LIBXML2") LIST(APPEND YBASELIB_EXTRA_LIBRARIES ${LIBXML2_LIBRARIES}) endif() if(HAVE_ZLIB) LIST(APPEND YBASELIB_EXTRA_DEFINES "HAVE_ZLIB") LIST(APPEND YBASELIB_EXTRA_LIBRARIES ${ZLIB_LIBRARIES}) endif() add_library(YBaseLib STATIC ${YBASELIB_HEADER_FILES} ${YBASELIB_SOURCE_FILES}) target_include_directories(YBaseLib PRIVATE YBaseLib/Include YBaseLib/Source ${LIBXML2_INCLUDE_DIR} ${ZLIB_INCLUDE_DIRS}) target_include_directories(YBaseLib PUBLIC YBaseLib/Include) target_compile_definitions(YBaseLib PRIVATE ${YBASELIB_EXTRA_DEFINES}) target_link_libraries(YBaseLib ${YBASELIB_EXTRA_LIBRARIES}) <file_sep>/Engine/Source/ResourceCompilerInterface/CMakeLists.txt set(HEADER_FILES Common.h ResourceCompilerInterface.h ResourceCompilerInterfaceIntegrated.h ResourceCompilerInterfaceRemote.cpp ResourceCompilerInterfaceRemote.h ) set(SOURCE_FILES ResourceCompilerInterfaceRemote.cpp ) include_directories(${ENGINE_BASE_DIRECTORY}) add_library(EngineResourceCompilerInterface STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineResourceCompilerInterface EngineMain EngineCore) <file_sep>/Engine/Source/D3D11Renderer/D3D11Defines.h #pragma once namespace NameTables { Y_Declare_NameTable(D3DFeatureLevels); } namespace D3D11TypeConversion { const char *D3DFeatureLevelToString(D3D_FEATURE_LEVEL FeatureLevel); DXGI_FORMAT PixelFormatToDXGIFormat(PIXEL_FORMAT Format); PIXEL_FORMAT DXGIFormatToPixelFormat(DXGI_FORMAT Format); D3D11_MAP MapTypetoD3D11MapType(GPU_MAP_TYPE MapType); const char *VertexElementSemanticToString(GPU_VERTEX_ELEMENT_SEMANTIC semantic); const char *VertexElementTypeToShaderTypeString(GPU_VERTEX_ELEMENT_TYPE type); DXGI_FORMAT VertexElementTypeToDXGIFormat(GPU_VERTEX_ELEMENT_TYPE type); } namespace D3D11Helpers { ID3D11RasterizerState *CreateD3D11RasterizerState(ID3D11Device *pD3DDevice, const RENDERER_RASTERIZER_STATE_DESC *pRasterizerState); ID3D11DepthStencilState *CreateD3D11DepthStencilState(ID3D11Device *pD3DDevice, const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState); ID3D11BlendState *CreateD3D11BlendState(ID3D11Device *pD3DDevice, const RENDERER_BLEND_STATE_DESC *pBlendState); ID3D11SamplerState *CreateD3D11SamplerState(ID3D11Device *pD3DDevice, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc); ID3D11ShaderResourceView *GetResourceShaderResourceView(GPUResource *pResource); ID3D11SamplerState *GetResourceSamplerState(GPUResource *pResource); void SetD3D11DeviceChildDebugName(ID3D11DeviceChild *pDeviceChild, const char *debugName); } <file_sep>/Engine/Source/Engine/SkeletalAnimationPlayer.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/SkeletalAnimationPlayer.h" #include "Renderer/RenderProxies/SkeletalMeshRenderProxy.h" Log_SetChannel(SkeletalAnimationPlayer); SkeletalAnimationPlayer::MeshState::MeshState() { } SkeletalAnimationPlayer::MeshState::MeshState(uint32 boneCount) { m_transforms.Resize(boneCount); m_transforms.ZeroContents(); } void SkeletalAnimationPlayer::MeshState::SetBoneCount(uint32 boneCount) { m_transforms.Resize(boneCount); m_transforms.ZeroContents(); } SkeletalAnimationPlayer::MeshState *SkeletalAnimationPlayer::MeshState::Copy() const { MeshState *newState = new MeshState(); newState->m_transforms.Assign(m_transforms); return newState; } void SkeletalAnimationPlayer::MeshState::CopyFrom(const MeshState *state) { m_transforms.Assign(state->m_transforms); } void SkeletalAnimationPlayer::Channel::Clear() { SAFE_RELEASE(m_pAnimation); if (m_pTransitionMeshState != nullptr) { delete m_pTransitionMeshState; m_pTransitionMeshState = nullptr; } m_transitionTime = 0.0f; m_time = 0.0f; m_playing = false; m_playbackSpeed = 0.0f; m_loopCount = 0; } void SkeletalAnimationPlayer::Channel::PlayAnimation(const SkeletalAnimation *pAnimation, float playbackSpeed /* = 1.0f */, int32 loopCount /* = 0 */, float transitionTime /* = 0.0f */, bool resetTime /* = true */) { if (pAnimation == nullptr) { Clear(); return; } if (transitionTime > 0.0f) { // enable a transition if (m_pTransitionMeshState != nullptr) m_pTransitionMeshState->CopyFrom(m_pPlayer->GetMeshState()); else m_pTransitionMeshState = m_pPlayer->GetMeshState()->Copy(); // remove all the local space transforms //for (uint32 boneIndex = 0; boneIndex < m_pTransitionMeshState->GetBoneTransformArraySize(); boneIndex++) //m_pTransitionMeshState->SetBoneTransform(boneIndex, Transform::ConcatenateTransforms(m_pTransitionMeshState->GetBoneTransform(boneIndex), m_pPlayer->GetSkeletalMesh()->GetBone(boneIndex)->LocalToBoneTransform.Inverse())); // set the time for it m_transitionTime = transitionTime; } // remove current animation if (m_pAnimation != nullptr) m_pAnimation->Release(); // set new animation m_pAnimation = pAnimation; m_pAnimation->AddRef(); m_playbackSpeed = playbackSpeed; m_loopCount = loopCount; m_time = (resetTime || pAnimation->GetDuration() == 0.0f) ? 0.0f : Y_fmodf(m_time, pAnimation->GetDuration()); m_playing = true; } void SkeletalAnimationPlayer::Channel::Update(float deltaTime) { // is playing? if (m_pAnimation == nullptr || !m_playing) return; // handle transitions if (m_pTransitionMeshState != nullptr) { // transition complete? if ((m_time + deltaTime) >= m_transitionTime) { // completed, so subtract the time deltaTime -= (m_transitionTime - m_time); m_time = 0.0f; // and clear the transition state delete m_pTransitionMeshState; m_pTransitionMeshState = nullptr; m_transitionTime = 0.0f; } else { // transition still in progress m_time += deltaTime; return; } } // factor in playback speed deltaTime *= Math::Abs(m_playbackSpeed); // loop for (;;) { // animation complete? if ((m_time + deltaTime) >= m_pAnimation->GetDuration()) { // last loop cycle? if (m_loopCount == 1) { // handle wrap modes switch (m_wrapMode) { case WrapMode_None: m_pAnimation->Release(); m_pAnimation = nullptr; m_time = 0.0f; break; case WrapMode_Once: m_time = 0.0f; break; case WrapMode_Hold: m_time = m_pAnimation->GetDuration(); break; case WrapMode_PingPong: m_time = (m_playbackSpeed >= 0.0f) ? m_pAnimation->GetDuration() : 0.0f; break; } m_loopCount = 0; m_playing = false; return; } else { // loop cycles remaining if (m_loopCount > 0) m_loopCount--; // subtract remaining time off deltaTime -= (m_pAnimation->GetDuration() - m_time); m_time = 0.0f; // handle wrap modes if (m_wrapMode == WrapMode_PingPong) m_playbackSpeed = -m_playbackSpeed; // handle pose animations, preventing infinite loop here if (Math::NearEqual(m_pAnimation->GetDuration(), 0.0f, Y_FLT_EPSILON)) break; } } else { // add time m_time += deltaTime; break; } } } SkeletalAnimationPlayer::SkeletalAnimationPlayer() : m_pSkeletalMesh(nullptr) { // initialize a single channel SetChannelCount(1); } SkeletalAnimationPlayer::SkeletalAnimationPlayer(const SkeletalMesh *pSkeletalMesh) : SkeletalAnimationPlayer() { SetSkeletalMesh(pSkeletalMesh); } SkeletalAnimationPlayer::~SkeletalAnimationPlayer() { for (uint32 channelIndex = 0; channelIndex < m_channels.GetSize(); channelIndex++) ClearAnimation(channelIndex); if (m_pSkeletalMesh != nullptr) m_pSkeletalMesh->Release(); } void SkeletalAnimationPlayer::SetChannelCount(uint32 channelCount) { DebugAssert(channelCount > 0); // calculate change amounts uint32 startIndex = m_channels.GetSize(); uint32 clearCount = (channelCount <= m_channels.GetSize()) ? (m_channels.GetSize() - channelCount) : 0; uint32 newCount = (channelCount >= m_channels.GetSize()) ? (channelCount - m_channels.GetSize()) : 0; // clear channels up to channelCount for (uint32 channelIndex = 0; channelIndex < clearCount; channelIndex++) m_channels[channelIndex].Clear(); // add new channels m_channels.Resize(channelCount); for (uint32 channelIndex = 0; channelIndex < newCount; channelIndex++) { Channel *channel = &m_channels[startIndex + channelIndex]; Y_memzero(channel, sizeof(Channel)); channel->m_pPlayer = this; channel->m_index = startIndex + channelIndex; channel->m_weight = 1.0f; channel->m_wrapMode = WrapMode_Once; } } void SkeletalAnimationPlayer::SetSkeletalMesh(const SkeletalMesh *pSkeletalMesh) { if (pSkeletalMesh == nullptr) { if (m_pSkeletalMesh != nullptr) { ClearAllAnimations(); m_pSkeletalMesh->Release(); m_pSkeletalMesh = nullptr; } return; } if (m_pSkeletalMesh != pSkeletalMesh) { if (m_pSkeletalMesh != nullptr) m_pSkeletalMesh->Release(); m_pSkeletalMesh = pSkeletalMesh; m_pSkeletalMesh->AddRef(); } // initalize transform array m_meshState.SetBoneCount(pSkeletalMesh->GetBoneCount()); // set to base frame ResetToBaseFrame(); UpdateMeshState(); } void SkeletalAnimationPlayer::PlayAnimation(const SkeletalAnimation *pAnimation, float playbackSpeed /* = 1.0f */, int32 loopCount /* = 1 */, bool hold /* = false */, uint32 channelIndex /* = 0 */, float weight /* = 1.0f */, float transitionTime /* = 0.3f */) { DebugAssert(m_pSkeletalMesh != nullptr && pAnimation->GetSkeleton() == m_pSkeletalMesh->GetSkeleton()); DebugAssert(channelIndex < m_channels.GetSize()); Channel &channel = m_channels[channelIndex]; if (loopCount < 0) loopCount = 0; if (hold) channel.SetWrapMode(WrapMode_Hold); else channel.SetWrapMode(WrapMode_Once); channel.SetWeight(weight); channel.PlayAnimation(pAnimation, playbackSpeed, loopCount, transitionTime); } void SkeletalAnimationPlayer::PauseAnimation(uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); m_channels[channelIndex].Stop(); } void SkeletalAnimationPlayer::ResumeAnimation(uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); m_channels[channelIndex].Play(); } void SkeletalAnimationPlayer::ClearAnimation(uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); Channel &channel = m_channels[channelIndex]; channel.Clear(); } void SkeletalAnimationPlayer::ClearAllAnimations() { for (uint32 channelIndex = 0; channelIndex < m_channels.GetSize(); channelIndex++) ClearAnimation(channelIndex); } void SkeletalAnimationPlayer::SetPlaybackSpeed(float playbackSpeed, uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); Channel &channel = m_channels[channelIndex]; channel.SetPlaybackSpeed(playbackSpeed); } void SkeletalAnimationPlayer::SetPlaybackLoopCount(int32 loopCount, uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); Channel &channel = m_channels[channelIndex]; if (loopCount < 0) loopCount = 0; channel.SetLoopCount(loopCount); } void SkeletalAnimationPlayer::SetPlaybackHold(bool hold, uint32 channelIndex /* = 0 */) { DebugAssert(channelIndex < m_channels.GetSize()); Channel &channel = m_channels[channelIndex]; if (hold) channel.SetWrapMode(WrapMode_Hold); else channel.SetWrapMode(WrapMode_Once); } void SkeletalAnimationPlayer::UpdateBoneTransform(const Skeleton::Bone *pSkeletonBone, const Transform *parentBoneTransform) { // find index uint32 meshBoneIndex; for (meshBoneIndex = 0; meshBoneIndex < m_pSkeletalMesh->GetBoneCount(); meshBoneIndex++) { if (m_pSkeletalMesh->GetBone(meshBoneIndex)->SkeletonBoneIndex == pSkeletonBone->GetIndex()) break; } // if there was no bone index, and this is a leaf node, skip it entirely if (meshBoneIndex == m_pSkeletalMesh->GetBoneCount() && pSkeletonBone->GetChildBoneCount() == 0) return; // calculate the bone's transform Transform thisBoneTransform; Transform thisBoneTransformForChildren; Transform channelBonePose; Transform channelBonePoseForChildren; bool hasTransform = false; bool hasChildren = (pSkeletonBone->GetChildBoneCount() > 0); // for each channel for (uint32 channelIndex = 0; channelIndex < m_channels.GetSize(); channelIndex++) { const Channel *channel = &m_channels[channelIndex]; // channel has an animation? if (channel->m_pAnimation == nullptr) continue; // channel is transitioning? if (channel->m_pTransitionMeshState != nullptr && meshBoneIndex != m_pSkeletalMesh->GetBoneCount()) { // find the transform we are transitioning to // if we don't have a transform for this bone, and there isn't a current transform, set it to the base frame Transform toTransform; if (channel->m_pAnimation->CalculateRelativeBoneTransform(pSkeletonBone->GetIndex(), 0.0f, &toTransform, false)) { // have to add the parent in here if (parentBoneTransform != nullptr) toTransform = Transform::ConcatenateTransforms(toTransform, *parentBoneTransform); } else { if (hasTransform) toTransform = thisBoneTransform; else toTransform = pSkeletonBone->GetAbsoluteBaseFrameTransform(); } // interpolate them, get from transform from the transition mesh state channelBonePose = Transform::LinearInterpolate(channel->m_pTransitionMeshState->GetBoneTransform(meshBoneIndex), toTransform, channel->m_time / channel->m_transitionTime); channelBonePoseForChildren = toTransform; } else { // reverse playback? float animationTime = channel->m_time; if (channel->m_playbackSpeed < 0.0f) animationTime = channel->m_pAnimation->GetDuration() - animationTime; // get transform if (!channel->m_pAnimation->CalculateRelativeBoneTransform(pSkeletonBone->GetIndex(), animationTime, &channelBonePose, true)) continue; // apply parent transform if (parentBoneTransform != nullptr) channelBonePose = Transform::ConcatenateTransforms(channelBonePose, *parentBoneTransform); channelBonePoseForChildren = channelBonePose; } // handle weighting if (hasTransform) { if (channel->GetWeight() < 1.0f) { // eugh, ugly as hell float4x4 existingPose(thisBoneTransform.GetTransformMatrix3x4()); float4x4 newPose(channelBonePose.GetTransformMatrix4x4()); // weight the transforms existingPose *= (1.0f - channel->GetWeight()); newPose *= channel->GetWeight(); // construct new transform thisBoneTransform = Transform(existingPose + newPose); if (hasChildren) { existingPose = thisBoneTransformForChildren.GetTransformMatrix3x4() * (1.0f - channel->GetWeight()); newPose = channelBonePoseForChildren.GetTransformMatrix3x4() * channel->GetWeight(); thisBoneTransformForChildren = Transform(existingPose + newPose); } } else { thisBoneTransform = channelBonePose; thisBoneTransformForChildren = channelBonePoseForChildren; } } else { // just set the transform thisBoneTransform = channelBonePose; thisBoneTransformForChildren = channelBonePose; hasTransform = true; } } // has a transform? if not, use base frame if (!hasTransform) { if (parentBoneTransform != nullptr) thisBoneTransform = Transform::ConcatenateTransforms(pSkeletonBone->GetRelativeBaseFrameTransform(), *parentBoneTransform); else thisBoneTransform = pSkeletonBone->GetRelativeBaseFrameTransform(); thisBoneTransformForChildren = thisBoneTransform; } // calculate transform from local space if (meshBoneIndex != m_pSkeletalMesh->GetBoneCount()) m_meshState.SetBoneTransform(meshBoneIndex, thisBoneTransform); //m_meshState.SetBoneTransform(meshBoneIndex, Transform::ConcatenateTransforms(m_pSkeletalMesh->GetBone(meshBoneIndex)->LocalToBoneTransform, thisBoneTransform)); // handle any children for (uint32 childIndex = 0; childIndex < pSkeletonBone->GetChildBoneCount(); childIndex++) UpdateBoneTransform(pSkeletonBone->GetChildBone(childIndex), &thisBoneTransformForChildren); } void SkeletalAnimationPlayer::UpdateMeshState() { // transform the root bone, the recusion will take care of the rest UpdateBoneTransform(m_pSkeletalMesh->GetSkeleton()->GetRootBone(), nullptr); } void SkeletalAnimationPlayer::Update(const float deltaTime) { // update time on channels for (uint32 channelIndex = 0; channelIndex < m_channels.GetSize(); channelIndex++) { Channel *channel = &m_channels[channelIndex]; channel->Update(deltaTime); } #if 0 if (m_pCurrentAnimation == nullptr || !m_currentAnimationPlaying) return; // update animation time m_currentAnimationTime += Math::Abs(m_currentAnimationPlaybackSpeed) * deltaTime; // end of animation? if (m_currentAnimationTime >= m_pCurrentAnimation->GetDuration()) { // can we loop? if (m_currentAnimationLoopCount != 0 && (m_currentAnimationLoopCount < 0 || (--m_currentAnimationLoopCount) > 0)) { // fix up the time m_currentAnimationTime = Y_fmodf(m_currentAnimationTime, m_pCurrentAnimation->GetDuration()); } else { if (m_currentAnimationHold) { // ensure transforms are set to the last frame without interpolation SetTransformsForAnimationTime(m_pCurrentAnimation->GetDuration()); } // clear animation references ClearAnimation(!m_currentAnimationHold); // no more work return; } } // interpolate transforms and stuff SetTransformsForAnimationTime(m_currentAnimationTime); #endif } void SkeletalAnimationPlayer::UpdateSkeletalMeshRenderProxy(SkeletalMeshRenderProxy *pRenderProxy) { DebugAssert(pRenderProxy->GetSkeletalMesh() == m_pSkeletalMesh); pRenderProxy->SetBoneTransforms(0, m_meshState.GetBoneTransformArraySize(), m_meshState.GetBoneTransformArray()); } void SkeletalAnimationPlayer::ResetToBaseFrame() { for (uint32 channelIndex = 0; channelIndex < m_channels.GetSize(); channelIndex++) ClearAnimation(channelIndex); } Transform SkeletalAnimationPlayer::GetFullBoneTransform(uint32 boneIndex) const { DebugAssert(boneIndex < m_pSkeletalMesh->GetBoneCount()); return Transform::ConcatenateTransforms(m_pSkeletalMesh->GetBone(boneIndex)->LocalToBoneTransform, m_meshState.GetBoneTransform(boneIndex)); } #if 0 void SkeletalAnimationPlayer::SetTransformsForAnimationTime(float animationTime) { // handle reverse if (m_currentAnimationPlaybackSpeed < 0.0f) animationTime = Max(m_pCurrentAnimation->GetDuration() - animationTime, 0.0f); #if 1 // slow path for (uint32 boneIndex = 0; boneIndex < m_pSkeleton->GetBoneCount(); boneIndex++) { // update transform m_pCurrentAnimation->CalculateAbsoluteBoneTransform(boneIndex, animationTime, &m_boneTransforms[boneIndex]); // update matrix m_boneTransformMatrices[boneIndex] = m_boneTransforms[boneIndex].GetTransformMatrix3x4(); } #endif #if 0 // calculate keyframe index float keyFrameTime = animationTime / (1.0f / m_pCurrentAnimation->GetKeyFramesPerSecond()); uint32 keyFrameIndex = (uint32)Math::Truncate(keyFrameTime); float lerpFactor = Math::FractionalPart(keyFrameTime); bool doLerp = !Math::NearEqual(lerpFactor, 0.0f, Y_FLT_EPSILON); // handle out of range if ((keyFrameIndex + 1) >= m_pCurrentAnimation->GetKeyFrameCount()) { keyFrameIndex = m_pCurrentAnimation->GetKeyFrameCount() - 1; doLerp = false; } //Log_DevPrintf("KF: %u, lerp = %s, lerpFactor = %s", keyFrameIndex, StringConverter::BoolToString(doLerp).GetCharArray(), StringConverter::FloatToString(lerpFactor).GetCharArray()); //doLerp = false; // update bones for (uint32 boneIndex = 0; boneIndex < m_pSkeleton->GetBoneCount(); boneIndex++) { if (doLerp) { // get 2 transforms Transform startTransform(m_pCurrentAnimation->GetKeyFrameBoneTransform(keyFrameIndex, boneIndex)); Transform endTransform(m_pCurrentAnimation->GetKeyFrameBoneTransform(keyFrameIndex + 1, boneIndex)); // lerp between them, and set m_boneTransforms[boneIndex] = Transform::LinearInterpolate(startTransform, endTransform, lerpFactor); } else { // just set to transform m_boneTransforms[boneIndex] = m_pCurrentAnimation->GetKeyFrameBoneTransform(keyFrameIndex, boneIndex); } // update matrix m_boneTransformMatrices[boneIndex] = m_boneTransforms[boneIndex].GetTransformMatrix3x4(); } #endif } #endif <file_sep>/Editor/Source/Editor/EditorResourceSelectionWidget.h #pragma once #include "Editor/Common.h" class EditorResourceSelectionWidget : public QWidget { Q_OBJECT public: EditorResourceSelectionWidget(QWidget *pParent = NULL); ~EditorResourceSelectionWidget(); const ResourceTypeInfo *getResourceTypeInfo() const { return m_pResourceTypeInfo; } const QString getValue() const { return m_pLineEdit->text(); } public Q_SLOTS: void setResourceTypeInfo(const ResourceTypeInfo *pResourceTypeInfo); void setValue(const QString &value); Q_SIGNALS: void valueChanged(const QString &value); private Q_SLOTS: void onBrowseButtonClicked(); void onLineEditEdited(const QString &value); private: const ResourceTypeInfo *m_pResourceTypeInfo; QLineEdit *m_pLineEdit; QPushButton *m_pBrowseButton; QWidget *m_pEditorArea; }; <file_sep>/Engine/Source/Core/ImageCodec.h #pragma once #include "Core/Common.h" #include "Core/PixelFormat.h" #include "Core/Image.h" #include "Core/PropertyTable.h" #include "YBaseLib/ByteStream.h" namespace ImageCodecEncoderOptions { extern const char *JPEG_QUALITY_LEVEL; extern const char *PNG_COMPRESSION_LEVEL; } namespace ImageCodecDecoderOptions { } class ImageCodec { public: // Returns the name of the image codec virtual const char *GetCodecName() const = 0; // Decodes the image. virtual bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyTable &decoderOptions = PropertyTable::EmptyPropertyList) = 0; // Encodes the image. virtual bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyTable &encoderOptions = PropertyTable::EmptyPropertyList) = 0; // Codec getters static ImageCodec *GetImageCodecForFileName(const char *fileName); static ImageCodec *GetImageCodecForStream(const char *fileName, ByteStream *pStream); }; <file_sep>/Engine/Source/MathLib/Vectorf.h #pragma once #include "MathLib/Common.h" #include "MathLib/VectorShuffles.h" // interoperability between float/vector types struct Vector2i; struct Vector3i; struct Vector4i; struct Vector2u; struct Vector3u; struct Vector4u; struct Vector2h; struct Vector3h; struct Vector4h; struct Vector2f; struct Vector3f; struct Vector4f; struct SIMDVector2f; struct SIMDVector3f; struct SIMDVector4f; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector2f { // constructors inline Vector2f() {} inline Vector2f(const float val) : x(val), y(val) {} inline Vector2f(const float x_, const float y_) : x(x_), y(y_) {} inline Vector2f(const float *p) : x(p[0]), y(p[1]) {} inline Vector2f(const Vector2f &v) : x(v.x), y(v.y) {} Vector2f(const Vector2i &v); Vector2f(const SIMDVector2f &v); // setters void Set(const float x_, const float y_) { x = x_; y = y_; } void Set(const Vector2f &v) { x = v.x; y = v.y; } void Set(const SIMDVector2f &v); void SetZero() { x = y = 0.0f; } // load/store void Load(const float *v) { x = v[0]; y = v[1]; } void Store(float *v) const { v[0] = x; v[1] = y; } // new vector Vector2f operator+(const Vector2f &v) const { return Vector2f(x + v.x, y + v.y); } Vector2f operator-(const Vector2f &v) const { return Vector2f(x - v.x, y - v.y); } Vector2f operator*(const Vector2f &v) const { return Vector2f(x * v.x, y * v.y); } Vector2f operator/(const Vector2f &v) const { return Vector2f(x / v.x, y / v.y); } Vector2f operator%(const Vector2f &v) const { return Vector2f(Y_fmodf(x, v.x), Y_fmodf(y, v.y)); } Vector2f operator-() const { return Vector2f(-x, -y); } // scalar operators Vector2f operator+(const float v) const { return Vector2f(x + v, y + v); } Vector2f operator-(const float v) const { return Vector2f(x - v, y - v); } Vector2f operator*(const float v) const { return Vector2f(x * v, y * v); } Vector2f operator/(const float v) const { return Vector2f(x / v, y / v); } Vector2f operator%(const float v) const { return Vector2f(Y_fmodf(x, v), Y_fmodf(y, v)); } // comparison operators bool operator==(const Vector2f &v) const { return x == v.x && y == v.y; } bool operator!=(const Vector2f &v) const { return x != v.x || y != v.y; } bool operator<=(const Vector2f &v) const { return x <= v.x && y <= v.y; } bool operator>=(const Vector2f &v) const { return x >= v.x && y >= v.y; } bool operator<(const Vector2f &v) const { return x < v.x && y < v.y; } bool operator>(const Vector2f &v) const { return x > v.x && y > v.y; } // modifies this vector Vector2f &operator+=(const Vector2f &v) { x += v.x; y += v.y; return *this; } Vector2f &operator-=(const Vector2f &v) { x -= v.x; y -= v.y; return *this; } Vector2f &operator*=(const Vector2f &v) { x *= v.x; y *= v.y; return *this; } Vector2f &operator/=(const Vector2f &v) { x /= v.x; y /= v.y; return *this; } Vector2f &operator%=(const Vector2f &v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); return *this; } Vector2f &operator=(const Vector2f &v) { x = v.x; y = v.y; return *this; } Vector2f &operator=(const SIMDVector2f &v); // scalar operators Vector2f &operator+=(const float v) { x += v; y += v; return *this; } Vector2f &operator-=(const float v) { x -= v; y -= v; return *this; } Vector2f &operator*=(const float v) { x *= v; y *= v; return *this; } Vector2f &operator/=(const float v) { x /= v; y /= v; return *this; } Vector2f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // partial comparisons bool AnyLess(const Vector2f &v) const { return (x < v.x || y < v.y); } bool AnyGreater(const Vector2f &v) const { return (x > v.x || y > v.y); } bool NearEqual(const Vector2f &v, const float fEpsilon) const { return (Y_fabs(x - v.x) <= fEpsilon && Y_fabs(y - v.y) <= fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps Vector2f Min(const Vector2f &v) const { Vector2f result; result.x = (x > v.x) ? v.x : x; result.y = (y > v.y) ? v.y : y; return result; } Vector2f Max(const Vector2f &v) const { Vector2f result; result.x = (x < v.x) ? v.x : x; result.y = (y < v.y) ? v.y : y; return result; } Vector2f Clamp(const Vector2f &lBounds, const Vector2f &uBounds) const { return Min(uBounds).Max(lBounds); } Vector2f Abs() const { Vector2f result; result.x = Y_fabs(x); result.y = Y_fabs(y); return result; } Vector2f Saturate() const { return Clamp(Zero, One); } Vector2f Snap(const Vector2f &v) const { return Vector2f(Y_fsnap(x, v.x), Y_fsnap(y, v.y)); } Vector2f Floor() const { return Vector2f(Y_floorf(x), Y_floorf(y)); } Vector2f Ceil() const { return Vector2f(Y_ceilf(x), Y_ceilf(y)); } Vector2f Round() const { return Vector2f(Y_roundf(x), Y_roundf(y)); } // swap void Swap(Vector2f &v) { float tmp; tmp = x; x = v.x; v.x = tmp; tmp = y; x = v.y; v.y = tmp; } // dot product float Dot(const Vector2f &v) const { return x * v.x + y * v.y; } // lerp Vector2f Lerp(const Vector2f &v, const float f) const { Vector2f result; result.x = x + (v.x - x) * f; result.y = y + (v.y - y) * f; return result; } // length inline float SquaredLength() const { return Dot(*this); } inline float Length() const { return Y_sqrtf(Dot(*this)); } // distance float SquaredDistance(const Vector2f &to) const { return (to - *this).SquaredLength(); } float Distance(const Vector2f &to) const { float sql = (to - *this).SquaredLength(); return (sql != 0.0f) ? Y_sqrtf(sql) : 0.0f; } // normalize Vector2f Normalize() const { return *this / Length(); } Vector2f NormalizeEst() const { return *this * (Y_rsqrtf(SquaredLength())); } // normalize in place void NormalizeInPlace() { *this *= (1.0f / Length()); } void NormalizeEstInPlace() { *this *= Y_rsqrtf(SquaredLength()); } // safe normalize Vector2f SafeNormalize() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this / Y_sqrtf(sqLength); else return Zero; } Vector2f SafeNormalizeEst() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this * Y_rsqrtf(sqLength); else return Zero; } void SafeNormalizeInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this /= Y_sqrtf(sqLength); } void SafeNormalizeEstInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this *= Y_rsqrtf(SquaredLength()); } // reciprocal Vector2f Reciprocal() const { Vector2f result; result.x = 1.0f / x; result.y = 1.0f / y; return result; } // cross product Vector2f Cross(const Vector2f &v) const { Vector2f result; result.x = (x * v.y) - (y * v.x); result.y = (x * v.y) - (y * v.x); return result; } // maximum of all components float MinOfComponents() const { return ::Min(x, y); } float MaxOfComponents() const { return ::Max(x, y); } // shuffles template<int V0, int V1> Vector2f Shuffle2() const { const float *pv = (const float *)&x; Vector2f result; result.x = pv[V0]; result.y = pv[V1]; return result; } VECTOR2_SHUFFLE_FUNCTIONS(Vector2f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { struct { float x; float y; }; struct { float r; float g; }; float ele[2]; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const Vector2f &Zero, &One, &NegativeOne; static const Vector2f &Infinite, &NegativeInfinite; static const Vector2f &UnitX, &UnitY, &NegativeUnitX, &NegativeUnitY; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector3f { // constructors inline Vector3f() {} inline Vector3f(const float val) : x(val), y(val), z(val) {} inline Vector3f(const float x_, const float y_, const float z_) : x(x_), y(y_), z(z_) {} inline Vector3f(const float *p) : x(p[0]), y(p[1]), z(p[2]) {} inline Vector3f(const Vector2f &v, const float z_ = 0.0f) : x(v.x), y(v.y), z(z_) {} inline Vector3f(const Vector3f &v) : x(v.x), y(v.y), z(v.z) {} Vector3f(const Vector3i &v); Vector3f(const SIMDVector3f &v); // setters void Set(const float x_, const float y_, const float z_) { x = x_; y = y_; z = z_; } void Set(const Vector2f &v, const float z_ = 0.0f) { x = v.x; y = v.y; z = z_; } void Set(const Vector3f &v) { x = v.x; y = v.y; z = v.z; } void Set(const SIMDVector3f &v); void SetZero() { x = y = z = 0.0f; } // load/store void Load(const float *v) { x = v[0]; y = v[1]; z = v[2]; } void Store(float *v) const { v[0] = x; v[1] = y; v[2] = z;} // new vector Vector3f operator+(const Vector3f &v) const { return Vector3f(x + v.x, y + v.y, z + v.z); } Vector3f operator-(const Vector3f &v) const { return Vector3f(x - v.x, y - v.y, z - v.z); } Vector3f operator*(const Vector3f &v) const { return Vector3f(x * v.x, y * v.y, z * v.z); } Vector3f operator/(const Vector3f &v) const { return Vector3f(x / v.x, y / v.y, z / v.z); } Vector3f operator%(const Vector3f &v) const { return Vector3f(Y_fmodf(x, v.x), Y_fmodf(y, v.y), Y_fmodf(z, v.z)); } Vector3f operator-() const { return Vector3f(-x, -y, -z); } // scalar operators Vector3f operator+(const float v) const { return Vector3f(x + v, y + v, z + v); } Vector3f operator-(const float v) const { return Vector3f(x - v, y - v, z - v); } Vector3f operator*(const float v) const { return Vector3f(x * v, y * v, z * v); } Vector3f operator/(const float v) const { return Vector3f(x / v, y / v, z / v); } Vector3f operator%(const float v) const { return Vector3f(Y_fmodf(x, v), Y_fmodf(y, v), Y_fmodf(z, v)); } // comparison operators bool operator==(const Vector3f &v) const { return x == v.x && y == v.y && z == v.z; } bool operator!=(const Vector3f &v) const { return x != v.x || y != v.y || z != v.z; } bool operator<=(const Vector3f &v) const { return x <= v.x && y <= v.y && z <= v.z; } bool operator>=(const Vector3f &v) const { return x >= v.x && y >= v.y && z >= v.z; } bool operator<(const Vector3f &v) const { return x < v.x && y < v.y && z < v.z; } bool operator>(const Vector3f &v) const { return x > v.x && y > v.y && z > v.z; } // modifies this vector Vector3f &operator+=(const Vector3f &v) { x += v.x; y += v.y; z += v.z; return *this; } Vector3f &operator-=(const Vector3f &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3f &operator*=(const Vector3f &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } Vector3f &operator/=(const Vector3f &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } Vector3f &operator%=(const Vector3f &v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); z = Y_fmodf(z, v.z); return *this; } Vector3f &operator=(const Vector3f &v) { x = v.x; y = v.y; z = v.z; return *this; } Vector3f &operator=(const SIMDVector3f &v); // scalar operators Vector3f &operator+=(const float v) { x += v; y += v; z += v; return *this; } Vector3f &operator-=(const float v) { x -= v; y -= v; z -= v; return *this; } Vector3f &operator*=(const float v) { x *= v; y *= v; z *= v; return *this; } Vector3f &operator/=(const float v) { x /= v; y /= v; z /= v; return *this; } Vector3f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); z = Y_fmodf(z, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // partial comparisons bool AnyLess(const Vector3f &v) const { return (x < v.x || y < v.y || z < v.z); } bool AnyGreater(const Vector3f &v) const { return (x > v.x || y > v.y || z > v.z); } bool NearEqual(const Vector3f &v, const float fEpsilon) const { return (Y_fabs(x - v.x) <= fEpsilon && Y_fabs(y - v.y) <= fEpsilon && Y_fabs(z - v.z) <= fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps Vector3f Min(const Vector3f &v) const { Vector3f result; result.x = (x > v.x) ? v.x : x; result.y = (y > v.y) ? v.y : y; result.z = (z > v.z) ? v.z : z; return result; } Vector3f Max(const Vector3f &v) const { Vector3f result; result.x = (x < v.x) ? v.x : x; result.y = (y < v.y) ? v.y : y; result.z = (z < v.z) ? v.z : z; return result; } Vector3f Clamp(const Vector3f &lBounds, const Vector3f &uBounds) const { return Min(uBounds).Max(lBounds); } Vector3f Abs() const { Vector3f result; result.x = Y_fabs(x); result.y = Y_fabs(y); result.z = Y_fabs(z); return result; } Vector3f Saturate() const { return Clamp(Zero, One); } Vector3f Snap(const Vector3f &v) const { return Vector3f(Y_fsnap(x, v.x), Y_fsnap(y, v.y), Y_fsnap(z, v.z)); } Vector3f Floor() const { return Vector3f(Y_floorf(x), Y_floorf(y), Y_floorf(z)); } Vector3f Ceil() const { return Vector3f(Y_ceilf(x), Y_ceilf(y), Y_ceilf(z)); } Vector3f Round() const { return Vector3f(Y_roundf(x), Y_roundf(y), Y_roundf(z)); } // swap void Swap(Vector3f &v) { float tmp; tmp = x; x = v.x; v.x = tmp; tmp = y; x = v.y; v.y = tmp; tmp = z; x = v.z; v.z = tmp; } // dot product float Dot(const Vector3f &v) const { return x * v.x + y * v.y + z * v.z; } // lerp Vector3f Lerp(const Vector3f &v, const float f) const { Vector3f result; result.x = x + (v.x - x) * f; result.y = y + (v.y - y) * f; result.z = z + (v.z - z) * f; return result; } // length inline float SquaredLength() const { return Dot(*this); } inline float Length() const { return Y_sqrtf(Dot(*this)); } // distance float SquaredDistance(const Vector3f &to) const { return (to - *this).SquaredLength(); } float Distance(const Vector3f &to) const { float sql = (to - *this).SquaredLength(); return (sql != 0.0f) ? Y_sqrtf(sql) : 0.0f; } // normalize Vector3f Normalize() const { return *this / Length(); } Vector3f NormalizeEst() const { return *this * (Y_rsqrtf(SquaredLength())); } // normalize in place void NormalizeInPlace() { *this *= (1.0f / Length()); } void NormalizeEstInPlace() { *this *= Y_rsqrtf(SquaredLength()); } // safe normalize Vector3f SafeNormalize() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this / Y_sqrtf(sqLength); else return Zero; } Vector3f SafeNormalizeEst() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this * Y_rsqrtf(sqLength); else return Zero; } void SafeNormalizeInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this /= Y_sqrtf(sqLength); } void SafeNormalizeEstInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this *= Y_rsqrtf(SquaredLength()); } // reciprocal Vector3f Reciprocal() const { Vector3f result; result.x = 1.0f / x; result.y = 1.0f / y; result.z = 1.0f / z; return result; } // cross product Vector3f Cross(const Vector3f &v) const { Vector3f result; result.x = (y * v.z) - (z * v.y); result.y = (z * v.x) - (x * v.z); result.z = (x * v.y) - (y * v.x); return result; } // maximum of all components float MinOfComponents() const { return ::Min(x, ::Min(y, z)); } float MaxOfComponents() const { return ::Max(x, ::Max(y, z)); } // shuffles template<int V0, int V1> Vector2f Shuffle2() const { const float *pv = (const float *)&x; Vector2f result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3f Shuffle3() const { const float *pv = (const float *)&x; Vector3f result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } VECTOR3_SHUFFLE_FUNCTIONS(Vector2f, Vector3f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { struct { float x; float y; float z; }; struct { float r; float g; float b; }; float ele[3]; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const Vector3f &Zero, &One, &NegativeOne; static const Vector3f &Infinite, &NegativeInfinite; static const Vector3f &UnitX, &UnitY, &UnitZ, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector4f { // constructors inline Vector4f() {} inline Vector4f(const float val) : x(val), y(val), z(val), w(val) {} inline Vector4f(const float x_, const float y_, const float z_, const float w_) : x(x_), y(y_), z(z_), w(w_) {} inline Vector4f(const float *p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) {} inline Vector4f(const Vector2f &v, const float z_ = 0.0f, const float w_ = 0.0f) : x(v.x), y(v.y), z(z_), w(w_) {} inline Vector4f(const Vector3f &v, const float w_ = 0.0f) : x(v.x), y(v.y), z(v.z), w(w_) {} inline Vector4f(const Vector4f &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} Vector4f(const Vector4i &v); Vector4f(const SIMDVector4f &v); // setters void Set(const float x_, const float y_, const float z_, const float w_) { x = x_; y = y_; z = z_; w = w_; } void Set(const Vector2f &v, const float z_ = 0.0f, const float w_ = 0.0f) { x = v.x; y = v.y; z = z_; w = w_; } void Set(const Vector3f &v, const float w_ = 0.0f) { x = v.x; y = v.y; z = v.z; w = w_; } void Set(const Vector4f &v) { x = v.x; y = v.y; z = v.z; w = v.w; } void Set(const SIMDVector4f &v); void SetZero() { x = y = z = w = 0.0f; } // load/store void Load(const float *v) { x = v[0]; y = v[1]; z = v[2]; w = v[3]; } void Store(float *v) const { v[0] = x; v[1] = y; v[2] = z; v[3] = w; } // new vector Vector4f operator+(const Vector4f &v) const { return Vector4f(x + v.x, y + v.y, z + v.z, w + v.w); } Vector4f operator-(const Vector4f &v) const { return Vector4f(x - v.x, y - v.y, z - v.z, w - v.w); } Vector4f operator*(const Vector4f &v) const { return Vector4f(x * v.x, y * v.y, z * v.z, w * v.w); } Vector4f operator/(const Vector4f &v) const { return Vector4f(x / v.x, y / v.y, z / v.z, w / v.w); } Vector4f operator%(const Vector4f &v) const { return Vector4f(Y_fmodf(x, v.x), Y_fmodf(y, v.y), Y_fmodf(z, v.z), Y_fmodf(w, v.w)); } Vector4f operator-() const { return Vector4f(-x, -y, -z, -w); } // scalar operators Vector4f operator+(const float v) const { return Vector4f(x + v, y + v, z + v, w + v); } Vector4f operator-(const float v) const { return Vector4f(x - v, y - v, z - v, w - v); } Vector4f operator*(const float v) const { return Vector4f(x * v, y * v, z * v, w * v); } Vector4f operator/(const float v) const { return Vector4f(x / v, y / v, z / v, w / v); } Vector4f operator%(const float v) const { return Vector4f(Y_fmodf(x, v), Y_fmodf(y, v), Y_fmodf(z, v), Y_fmodf(w, v)); } // comparison operators bool operator==(const Vector4f &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } bool operator!=(const Vector4f &v) const { return x != v.x || y != v.y || z != v.z || w != v.w; } bool operator<=(const Vector4f &v) const { return x <= v.x && y <= v.y && z <= v.z && w <= v.w; } bool operator>=(const Vector4f &v) const { return x >= v.x && y >= v.y && z >= v.z && w >= v.w; } bool operator<(const Vector4f &v) const { return x < v.x && y < v.y && z < v.z && w < v.w; } bool operator>(const Vector4f &v) const { return x > v.x && y > v.y && z > v.z && w > v.w; } // modifies this vector Vector4f &operator+=(const Vector4f &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } Vector4f &operator-=(const Vector4f &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } Vector4f &operator*=(const Vector4f &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } Vector4f &operator/=(const Vector4f &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } Vector4f &operator%=(const Vector4f &v) { x = Y_fmodf(x, v.x); y = Y_fmodf(y, v.y); z = Y_fmodf(z, v.z); w = Y_fmodf(w, v.w); return *this; } Vector4f &operator=(const Vector4f &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } Vector4f &operator=(const SIMDVector4f &v); // scalar operators Vector4f &operator+=(const float v) { x += v; y += v; z += v; w += v; return *this; } Vector4f &operator-=(const float v) { x -= v; y -= v; z -= v; w -= v; return *this; } Vector4f &operator*=(const float v) { x *= v; y *= v; z *= v; w *= v; return *this; } Vector4f &operator/=(const float v) { x /= v; y /= v; z /= v; w /= v; return *this; } Vector4f &operator%=(const float v) { x = Y_fmodf(x, v); y = Y_fmodf(y, v); z = Y_fmodf(z, v); w = Y_fmodf(w, v); return *this; } // index accessors //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // partial comparisons bool AnyLess(const Vector4f &v) const { return (x < v.x || y < v.y || z < v.z || w < v.w); } bool AnyGreater(const Vector4f &v) const { return (x > v.x || y > v.y || z > v.z || w > v.w); } bool NearEqual(const Vector4f &v, const float fEpsilon) const { return (Y_fabs(x - v.x) <= fEpsilon && Y_fabs(y - v.y) <= fEpsilon && Y_fabs(z - v.z) <= fEpsilon && Y_fabs(w - v.w) < fEpsilon); } bool IsFinite() const { return (*this != Infinite); } // clamps Vector4f Min(const Vector4f &v) const { Vector4f result; result.x = (x > v.x) ? v.x : x; result.y = (y > v.y) ? v.y : y; result.z = (z > v.z) ? v.z : z; result.w = (w > v.w) ? v.w : w; return result; } Vector4f Max(const Vector4f &v) const { Vector4f result; result.x = (x < v.x) ? v.x : x; result.y = (y < v.y) ? v.y : y; result.z = (z < v.z) ? v.z : z; result.w = (w < v.w) ? v.w : w; return result; } Vector4f Clamp(const Vector4f &lBounds, const Vector4f &uBounds) const { return Min(uBounds).Max(lBounds); } Vector4f Abs() const { Vector4f result; result.x = Y_fabs(x); result.y = Y_fabs(y); result.z = Y_fabs(z); result.w = Y_fabs(w); return result; } Vector4f Saturate() const { return Clamp(Zero, One); } Vector4f Snap(const Vector4f &v) const { return Vector4f(Y_fsnap(x, v.x), Y_fsnap(y, v.y), Y_fsnap(z, v.z), Y_fsnap(z, v.z)); } Vector4f Floor() const { return Vector4f(Y_floorf(x), Y_floorf(y), Y_floorf(z), Y_floorf(w)); } Vector4f Ceil() const { return Vector4f(Y_ceilf(x), Y_ceilf(y), Y_ceilf(z), Y_roundf(w)); } Vector4f Round() const { return Vector4f(Y_roundf(x), Y_roundf(y), Y_roundf(z), Y_roundf(w)); } // swap void Swap(Vector4f &v) { float tmp; tmp = x; x = v.x; v.x = tmp; tmp = y; x = v.y; v.y = tmp; tmp = z; x = v.z; v.z = tmp; tmp = w; x = v.w; v.w = tmp; } // dot product float Dot(const Vector4f &v) const { return x * v.x + y * v.y + z * v.z + w * v.w; } // lerp Vector4f Lerp(const Vector4f &v, const float f) const { Vector4f result; result.x = x + (v.x - x) * f; result.y = y + (v.y - y) * f; result.z = z + (v.z - z) * f; result.w = w + (v.w - w) * f; return result; } // length inline float SquaredLength() const { return Dot(*this); } inline float Length() const { return Y_sqrtf(Dot(*this)); } // distance float SquaredDistance(const Vector4f &to) const { return (to - *this).SquaredLength(); } float Distance(const Vector4f &to) const { float sql = (to - *this).SquaredLength(); return (sql != 0.0f) ? Y_sqrtf(sql) : 0.0f; } // normalize Vector4f Normalize() const { return *this / Length(); } Vector4f NormalizeEst() const { return *this * (Y_rsqrtf(SquaredLength())); } // normalize in place void NormalizeInPlace() { *this *= (1.0f / Length()); } void NormalizeEstInPlace() { *this *= Y_rsqrtf(SquaredLength()); } // safe normalize Vector4f SafeNormalize() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this / Y_sqrtf(sqLength); else return Zero; } Vector4f SafeNormalizeEst() const { float sqLength = SquaredLength(); if (sqLength != 0.0f) return *this * Y_rsqrtf(sqLength); else return Zero; } void SafeNormalizeInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this /= Y_sqrtf(sqLength); } void SafeNormalizeEstInPlace() { float sqLength = SquaredLength(); if (sqLength != 0.0f) *this *= Y_rsqrtf(SquaredLength()); } // reciprocal Vector4f Reciprocal() const { Vector4f result; result.x = 1.0f / x; result.y = 1.0f / y; result.z = 1.0f / z; result.w = 1.0f / w; return result; } // cross product Vector4f Cross(const Vector4f &v1, const Vector4f &v2) const { Vector4f result; result.x = (((v1.z * v2.w) - (v1.w * v2.z)) * y) - (((v1.y * v2.w) - (v1.w * v2.y)) * z) + (((v1.y * v2.z) - (v1.z * v2.y)) * w); result.y = (((v1.w * v2.z) - (v1.z * v2.w)) * x) - (((v1.w * v2.x) - (v1.x * v2.w)) * z) + (((v1.z * v2.x) - (v1.x * v2.z)) * w); result.z = (((v1.y * v2.w) - (v1.w * v2.y)) * x) - (((v1.x * v2.w) - (v1.w * v2.x)) * y) + (((v1.x * v2.y) - (v1.y * v2.x)) * w); result.w = (((v1.z * v2.y) - (v1.y * v2.z)) * x) - (((v1.z * v2.x) - (v1.x * v2.z)) * y) + (((v1.y * v2.x) - (v1.x * v2.y)) * z); return result; } // maximum of all components float MinOfComponents() const { return ::Min(x, ::Min(y, ::Min(z, w))); } float MaxOfComponents() const { return ::Max(x, ::Max(y, ::Max(z, w))); } // shuffles template<int V0, int V1> Vector2f Shuffle2() const { const float *pv = (const float *)&x; Vector2f result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3f Shuffle3() const { const float *pv = (const float *)&x; Vector3f result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } template<int V0, int V1, int V2, int V3> Vector4f Shuffle4() const { const float *pv = (const float *)&x; Vector4f result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; result.w = pv[V3]; return result; } VECTOR4_SHUFFLE_FUNCTIONS(Vector2f, Vector3f, Vector4f); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- union { struct { float x; float y; float z; float w; }; struct { float r; float g; float b; float a; }; float ele[4]; }; //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static const Vector4f &Zero, &One, &NegativeOne; static const Vector4f &Infinite, &NegativeInfinite; static const Vector4f &UnitX, &UnitY, &UnitZ, &UnitW, &NegativeUnitX, &NegativeUnitY, &NegativeUnitZ, &NegativeUnitW; }; <file_sep>/Engine/Source/ResourceCompiler/PrecompiledHeader.cpp #include "ResourceCompiler/PrecompiledHeader.h" <file_sep>/Engine/Source/ContentConverter/AssimpSkeletalAnimationImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiNode; struct aiAnimation; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class Skeleton; class SkeletonGenerator; class SkeletalAnimationGenerator; class AssimpSkeletalAnimationImporter : public BaseImporter { public: struct Options { String SourcePath; bool ListOnly; bool CreateSkeleton; String SkeletonName; String OutputResourceName; String OutputResourceDirectory; String OutputResourcePrefix; float DefaultAnimationTicksPerSecond; float OverrideTicksPerSecond; bool AllAnimations; String SingleAnimationName; bool ClipAnimation; uint32 ClipRangeStart; uint32 ClipRangeEnd; bool OptimizeAnimation; }; public: AssimpSkeletalAnimationImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpSkeletalAnimationImporter(); static void SetDefaultOptions(Options *pOptions); bool Execute(); private: bool CreateSkeleton(); bool LoadScene(); void ListAnimations(); bool CreateAnimations(); bool ParseAnimation(const aiAnimation *pAnimation, const char *outputResourceName, bool clipAnimation = false, uint32 clipKeyFrameStart = 0, uint32 clipKeyFrameEnd = 0); bool WriteOutput(const char *resourceName, const SkeletalAnimationGenerator *pOutputAnimation); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; }; <file_sep>/Engine/Source/ResourceCompilerInterface/ResourceCompilerInterface.h #pragma once #include "ResourceCompiler/Common.h" struct ShaderCompilerParameters; class ResourceCompilerInterface : public ReferenceCounted { public: // Resources virtual BinaryBlob *CompileTexture(uint32 texturePlatform, const char *name) = 0; virtual BinaryBlob *CompileMaterialShader(const char *name) = 0; virtual BinaryBlob *CompileMaterial(const char *name) = 0; virtual BinaryBlob *CompileFont(uint32 texturePlatform, const char *name) = 0; virtual BinaryBlob *CompileBlockPalette(uint32 texturePlatform, const char *name) = 0; virtual BinaryBlob *CompileStaticMesh(const char *name) = 0; virtual BinaryBlob *CompileBlockMesh(const char *name) = 0; virtual BinaryBlob *CompileSkeleton(const char *name) = 0; virtual BinaryBlob *CompileSkeletalMesh(const char *name) = 0; virtual BinaryBlob *CompileSkeletalAnimation(const char *name) = 0; virtual BinaryBlob *CompileParticleSystem(const char *name) = 0; virtual BinaryBlob *CompileTerrainLayerList(const char *name) = 0; // Shader Compiler virtual bool CompileShader(const ShaderCompilerParameters *pParameters, ByteStream *pOutByteCodeStream, ByteStream *pOutInfoLogStream) = 0; // Interface creation static ResourceCompilerInterface *CreateIntegratedInterface(); static ResourceCompilerInterface *CreateRemoteInterface(); }; <file_sep>/Engine/Source/BlockEngine/BlockWorldGenerator.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldGenerator.h" BlockWorldGenerator::BlockWorldGenerator(BlockWorld *pBlockWorld) : m_pBlockWorld(pBlockWorld) { } BlockWorldGenerator::~BlockWorldGenerator() { } BlockWorldBlockType BlockWorldGenerator::LookupBlockTypeByName(const char *name) { for (uint32 i = 0; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { const BlockPalette::BlockType *pBlockType = m_pBlockWorld->GetPalette()->GetBlockType(i); if (pBlockType->IsAllocated && pBlockType->Name.CompareInsensitive(name)) return (BlockWorldBlockType)i; } return 0; } bool BlockWorldGenerator::CanGenerateSection(int32 sectionX, int32 sectionY) const { return false; } bool BlockWorldGenerator::GetZRange(int32 startX, int32 startY, int32 endX, int32 endY, int32 *minBlockZ, int32 *maxBlockZ) const { return false; } bool BlockWorldGenerator::GenerateBlocks(int32 startX, int32 startY, int32 endX, int32 endY) const { return false; } <file_sep>/Engine/Source/Renderer/RenderProxies/CompositeRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/CompositeRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/Camera.h" #include "Engine/Material.h" Log_SetChannel(CompositeRenderProxy); CompositeRenderProxy::CompositeRenderProxy(uint32 entityId, const Transform &transform) : RenderProxy(entityId), m_Visibility(true), m_ShadowFlags(0), m_nextObjectId(0), m_bGPUResourcesCreated(false) { SetTransform(transform); } CompositeRenderProxy::~CompositeRenderProxy() { CompositeRenderProxy::ReleaseDeviceResources(); for (uint32 i = 0; i < m_objectRecords.GetSize(); i++) { ObjectRecord &obj = m_objectRecords[i]; for (uint32 j = 0; j < obj.MaterialCount; j++) { if (obj.ppMaterials[j] != NULL) obj.ppMaterials[j]->Release(); } delete[] obj.ppMaterials; delete[] obj.pBatches; } for (uint32 i = 0; i < m_updateObjectRecords.GetSize(); i++) { UpdateObjectRecord &obj = m_updateObjectRecords[i]; Y_free(obj.pVertices); Y_free(obj.pIndices); for (uint32 j = 0; j < obj.MaterialCount; j++) { if (obj.ppMaterials[j] != NULL) obj.ppMaterials[j]->Release(); } delete[] obj.ppMaterials; delete[] obj.pBatches; } } void CompositeRenderProxy::SetTransform(const Transform &transform) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_Transform = transform; m_LocalToWorldMatrix = m_Transform.GetTransformMatrix4x4(); UpdateBounds(); } void CompositeRenderProxy::SetVisibility(bool visible) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_Visibility = visible; } void CompositeRenderProxy::SetShadowFlags(uint32 shadowFlags) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_ShadowFlags = shadowFlags; } uint32 CompositeRenderProxy::AddObject() { UpdateObjectRecord obj; obj.ObjectId = m_nextObjectId++; obj.UpdateFlags = UPDATE_OBJECT_FLAG_CREATE | UPDATE_OBJECT_FLAG_BUFFERS | UPDATE_OBJECT_FLAG_TINT; obj.pVertexFactoryTypeInfo = NULL; obj.VertexFactoryFlags = 0; obj.pVertices = NULL; obj.VertexSize = 0; obj.VertexCount = 0; obj.pIndices = NULL; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.IndexCount = 0; obj.ppMaterials = NULL; obj.MaterialCount = 0; obj.pBatches = NULL; obj.BatchCount = 0; obj.TintEnabled = false; obj.TintColor = 0; obj.BoundingBox = AABox::Zero; obj.BoundingSphere = Sphere::Zero; m_updateObjectRecords.Add(obj); UpdateObjects(); return obj.ObjectId; } void CompositeRenderProxy::UpdateObject(uint32 objectId, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const void *pVertices, uint32 vertexSize, uint32 vertexCount, const void *pIndices, GPU_INDEX_FORMAT indexFormat, uint32 indexCount, const Material **ppMaterials, uint32 materialCount, const Batch *pBatches, uint32 batchCount, const AABox &boundingBox, const Sphere &boundingSphere) { UpdateObjectRecord obj; obj.ObjectId = objectId; obj.UpdateFlags = UPDATE_OBJECT_FLAG_BUFFERS; obj.pVertexFactoryTypeInfo = pVertexFactoryTypeInfo; obj.VertexFactoryFlags = vertexFactoryFlags; obj.pVertices = Y_malloc(vertexSize * vertexCount); Y_memcpy(obj.pVertices, pVertices, vertexSize * vertexCount); obj.VertexSize = vertexSize; obj.VertexCount = vertexCount; obj.pIndices = Y_malloc(((indexFormat == GPU_INDEX_FORMAT_UINT16) ? sizeof(uint16) : sizeof(uint32)) * indexCount); Y_memcpy(obj.pIndices, pIndices, ((indexFormat == GPU_INDEX_FORMAT_UINT16) ? sizeof(uint16) : sizeof(uint32)) * indexCount); obj.IndexFormat = indexFormat; obj.IndexCount = indexCount; obj.ppMaterials = new const Material *[materialCount]; for (uint32 i = 0; i < materialCount; i++) { if ((obj.ppMaterials[i] = ppMaterials[i]) != NULL) obj.ppMaterials[i]->AddRef(); } obj.MaterialCount = materialCount; obj.pBatches = new Batch[batchCount]; Y_memcpy(obj.pBatches, pBatches, sizeof(Batch) * batchCount); obj.BatchCount = batchCount; obj.TintEnabled = false; obj.TintColor = 0; obj.BoundingBox = boundingBox; obj.BoundingSphere = boundingSphere; m_updateObjectRecords.Add(obj); UpdateObjects(); } void CompositeRenderProxy::UpdateObjectTintColor(uint32 objectId, bool tintEnabled, uint32 tintColor) { UpdateObjectRecord obj; obj.ObjectId = objectId; obj.UpdateFlags = UPDATE_OBJECT_FLAG_TINT; obj.pVertexFactoryTypeInfo = NULL; obj.VertexFactoryFlags = 0; obj.pVertices = NULL; obj.pIndices = NULL; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.IndexCount = 0; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.ppMaterials = NULL; obj.MaterialCount = 0; obj.pBatches = NULL; obj.BatchCount = 0; obj.TintEnabled = tintEnabled; obj.TintColor = tintColor; obj.BoundingBox = AABox::Zero; obj.BoundingSphere = Sphere::Zero; m_updateObjectRecords.Add(obj); UpdateObjects(); } void CompositeRenderProxy::ClearObject(uint32 objectId) { UpdateObjectRecord obj; obj.ObjectId = objectId; obj.UpdateFlags = UPDATE_OBJECT_FLAG_BUFFERS; obj.pVertexFactoryTypeInfo = NULL; obj.VertexFactoryFlags = 0; obj.pVertices = NULL; obj.VertexSize = 0; obj.VertexCount = 0; obj.pIndices = NULL; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.IndexCount = 0; obj.ppMaterials = NULL; obj.MaterialCount = 0; obj.pBatches = NULL; obj.BatchCount = 0; obj.TintEnabled = false; obj.TintColor = 0; obj.BoundingBox = AABox::Zero; obj.BoundingSphere = Sphere::Zero; m_updateObjectRecords.Add(obj); UpdateObjects(); } void CompositeRenderProxy::DeleteObject(uint32 objectId) { UpdateObjectRecord obj; obj.ObjectId = objectId; obj.UpdateFlags = UPDATE_OBJECT_FLAG_DELETE; obj.pVertexFactoryTypeInfo = NULL; obj.VertexFactoryFlags = 0; obj.pVertices = NULL; obj.VertexSize = 0; obj.VertexCount = 0; obj.pIndices = NULL; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.IndexCount = 0; obj.ppMaterials = NULL; obj.MaterialCount = 0; obj.pBatches = NULL; obj.BatchCount = 0; obj.TintEnabled = false; obj.TintColor = 0; obj.BoundingBox = AABox::Zero; obj.BoundingSphere = Sphere::Zero; m_updateObjectRecords.Add(obj); UpdateObjects(); } void CompositeRenderProxy::DeleteAllObjects() { for (uint32 i = 0; i < m_objectRecords.GetSize(); i++) DeleteObject(m_objectRecords[i].ObjectId); } void CompositeRenderProxy::UpdateObjects() { bool updateBounds = false; for (uint32 i = 0; i < m_updateObjectRecords.GetSize(); i++) { UpdateObjectRecord &updateObj = m_updateObjectRecords[i]; if (updateObj.UpdateFlags & UPDATE_OBJECT_FLAG_CREATE) { DebugAssert((updateObj.UpdateFlags & UPDATE_OBJECT_FLAG_DELETE) == 0); ObjectRecord obj; obj.ObjectId = updateObj.ObjectId; obj.pVertexFactoryTypeInfo = NULL; obj.VertexFactoryFlags = 0; obj.pVertexBuffer = NULL; obj.VertexStride = 0; obj.pIndexBuffer = NULL; obj.IndexFormat = GPU_INDEX_FORMAT_UINT16; obj.ppMaterials = NULL; obj.MaterialCount = 0; obj.pBatches = NULL; obj.BatchCount = 0; obj.TintEnabled = false; obj.TintColor = 0; obj.BoundingBox = AABox::Zero; obj.BoundingSphere = Sphere::Zero; m_objectRecords.Add(obj); } uint32 objectId = updateObj.ObjectId; uint32 objectIndex = 0; for (; objectIndex < m_objectRecords.GetSize(); objectIndex++) { if (m_objectRecords[objectIndex].ObjectId == objectId) break; } Assert(objectIndex < m_objectRecords.GetSize()); ObjectRecord &obj = m_objectRecords[objectIndex]; if (updateObj.UpdateFlags & UPDATE_OBJECT_FLAG_DELETE) { if (obj.pVertexBuffer != NULL) obj.pVertexBuffer->Release(); if (obj.pIndexBuffer != NULL) obj.pIndexBuffer->Release(); for (uint32 j = 0; j < obj.MaterialCount; j++) { if (obj.ppMaterials[j] != NULL) obj.ppMaterials[j]->Release(); } delete[] obj.ppMaterials; delete[] obj.pBatches; m_objectRecords.OrderedRemove(objectIndex); updateBounds = true; } else { if (updateObj.UpdateFlags & UPDATE_OBJECT_FLAG_BUFFERS) { GPUBuffer *pVertexBuffer = NULL; GPUBuffer *pIndexBuffer = NULL; GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, updateObj.VertexSize * updateObj.VertexCount); GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, ((updateObj.IndexFormat == GPU_INDEX_FORMAT_UINT16) ? sizeof(uint16) : sizeof(uint32)) * updateObj.IndexCount); if (updateObj.VertexCount > 0 && updateObj.IndexCount > 0 && ((pVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, updateObj.pVertices)) == NULL || (pIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, updateObj.pIndices)) == NULL)) { Log_ErrorPrintf("Failed to allocate composite render proxy vertex buffers"); SAFE_RELEASE(pVertexBuffer); SAFE_RELEASE(pIndexBuffer); } else { if (obj.pVertexBuffer != NULL) obj.pVertexBuffer->Release(); if (obj.pIndexBuffer != NULL) obj.pIndexBuffer->Release(); for (uint32 j = 0; j < obj.MaterialCount; j++) { if (obj.ppMaterials[j] != NULL) obj.ppMaterials[j]->Release(); } delete[] obj.ppMaterials; delete[] obj.pBatches; obj.pVertexFactoryTypeInfo = updateObj.pVertexFactoryTypeInfo; obj.VertexFactoryFlags = updateObj.VertexFactoryFlags; obj.pVertexBuffer = pVertexBuffer; obj.VertexStride = updateObj.VertexSize; obj.pIndexBuffer = pIndexBuffer; obj.IndexFormat = updateObj.IndexFormat; obj.ppMaterials = updateObj.ppMaterials; obj.MaterialCount = updateObj.MaterialCount; obj.pBatches = updateObj.pBatches; obj.BatchCount = updateObj.BatchCount; obj.BoundingBox = updateObj.BoundingBox; obj.BoundingSphere = updateObj.BoundingSphere; Y_free(updateObj.pVertices); Y_free(updateObj.pIndices); updateBounds = true; } } if (updateObj.UpdateFlags & UPDATE_OBJECT_FLAG_TINT) { obj.TintEnabled = updateObj.TintEnabled; obj.TintColor = updateObj.TintColor; } } } m_updateObjectRecords.Clear(); if (updateBounds) UpdateBounds(); } void CompositeRenderProxy::UpdateBounds() { AABox boundingBox(AABox::Zero); Sphere boundingSphere(Sphere::Zero); bool first = true; for (uint32 i = 0; i < m_objectRecords.GetSize(); i++) { if (m_objectRecords[i].BatchCount == 0) continue; if (first) { boundingBox = m_objectRecords[i].BoundingBox; boundingSphere = m_objectRecords[i].BoundingSphere; first = false; } else { boundingBox.Merge(m_objectRecords[i].BoundingBox); boundingSphere.Merge(m_objectRecords[i].BoundingSphere); } } SetBounds(m_Transform.TransformBoundingBox(boundingBox), m_Transform.TransformBoundingSphere(boundingSphere)); } void CompositeRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_Visibility) return; // Store the requested render passes. uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (!(m_ShadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOW_MAP; if (!(m_ShadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; // Add objects for (uint32 i = 0; i < m_objectRecords.GetSize(); i++) { const ObjectRecord &obj = m_objectRecords[i]; if (obj.BatchCount == 0) continue; float viewDistance = pCamera->CalculateDepthToPoint(obj.BoundingSphere.GetCenter()); uint32 renderPassMask = wantedRenderPasses; if (obj.TintEnabled) renderPassMask |= RENDER_PASS_TINT; for (uint32 j = 0; j < obj.BatchCount; j++) { uint32 materialIndex = obj.pBatches[j].MaterialIndex; DebugAssert(materialIndex < obj.MaterialCount); const Material *pMaterial = obj.ppMaterials[materialIndex]; renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(renderPassMask); if (renderPassMask != 0) { RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = obj.BoundingBox; queueEntry.pVertexFactoryTypeInfo = obj.pVertexFactoryTypeInfo; queueEntry.VertexFactoryFlags = obj.VertexFactoryFlags; queueEntry.pMaterial = pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.UserData[0] = i; queueEntry.UserData[1] = j; queueEntry.TintColor = obj.TintColor; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } } void CompositeRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { uint32 objectIndex = pQueueEntry->UserData[0]; DebugAssert(objectIndex < m_objectRecords.GetSize()); const ObjectRecord &obj = m_objectRecords[objectIndex]; GPUBuffer *pVertexBuffer = obj.pVertexBuffer; uint32 vertexBufferOffset = 0; uint32 vertexBufferStride = obj.VertexStride; pCommandList->SetVertexBuffers(0, 1, &pVertexBuffer, &vertexBufferOffset, &vertexBufferStride); pCommandList->SetIndexBuffer(obj.pIndexBuffer, obj.IndexFormat, 0); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_LocalToWorldMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); } void CompositeRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { uint32 objectIndex = pQueueEntry->UserData[0]; DebugAssert(objectIndex < m_objectRecords.GetSize()); const ObjectRecord &obj = m_objectRecords[objectIndex]; uint32 batchIndex = pQueueEntry->UserData[1]; DebugAssert(batchIndex < obj.BatchCount); const Batch &batchInfo = obj.pBatches[batchIndex]; pCommandList->DrawIndexed(batchInfo.FirstIndex, batchInfo.IndexCount, 0); } bool CompositeRenderProxy::CreateDeviceResources() const { if (m_bGPUResourcesCreated) return true; m_bGPUResourcesCreated = true; return true; } void CompositeRenderProxy::ReleaseDeviceResources() const { for (uint32 i = 0; i < m_objectRecords.GetSize(); i++) { ObjectRecord &obj = const_cast<ObjectRecord &>(m_objectRecords[i]); SAFE_RELEASE(obj.pVertexBuffer); SAFE_RELEASE(obj.pIndexBuffer); } m_bGPUResourcesCreated = false; } <file_sep>/Engine/Source/ContentConverterStandalone/FontImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" #include "ContentConverter/FontImporter.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintFontImporterSyntax() { Log_InfoPrint("Font Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -o <name>: Output name."); Log_InfoPrint(" -append: Don't create a new font, append to existing"); Log_InfoPrint(" -width <width>: Raster pixel width (ignored for non-bitmap fonts), default is unspecified (uses width)."); Log_InfoPrint(" -height <height>: Raster pixel height, default 16"); Log_InfoPrint(" -bitmap: Generate a bitmap font"); Log_InfoPrint(" -sdf: Generate a signed distance field font"); Log_InfoPrint(" -charset <name>: Add this character set"); Log_InfoPrint(""); } bool ParseFontImporterOption(FontImporterOptions &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.InputFileName = argv[++i]; else if (CHECK_ARG_PARAM("-subfont")) Options.SubFontIndex = StringConverter::StringToUInt32(argv[++i]); else if (CHECK_ARG_PARAM("-o")) Options.OutputName = argv[++i]; else if (CHECK_ARG_PARAM("-width")) { if (!FontImporter::ParseFontSizeString(&Options.RenderWidth, argv[++i])) { Log_ErrorPrintf("Failed to parse font width string: '%s' (must be a digit followed by pt or px)", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-height")) { if (!FontImporter::ParseFontSizeString(&Options.RenderHeight, argv[++i])) { Log_ErrorPrintf("Failed to parse height size string: '%s' (must be a digit followed by pt or px)", argv[i]); return false; } } else if (CHECK_ARG("-listsubfonts")) { if (Options.InputFileName.GetLength() == 0) { Log_ErrorPrintf("Missing font file name"); return false; } ConsoleProgressCallbacks progressCallbacks; FontImporter::ListSubFonts(Options.InputFileName, &progressCallbacks); return false; } else if (CHECK_ARG("-listfontsizes")) { if (Options.InputFileName.GetLength() == 0) { Log_ErrorPrintf("Missing font file name"); return false; } ConsoleProgressCallbacks progressCallbacks; FontImporter::ListFontSizes(Options.InputFileName, Options.SubFontIndex, &progressCallbacks); return false; } else if (CHECK_ARG("-append")) Options.AppendToFile = true; else if (CHECK_ARG("-bitmap")) Options.Type = FONT_TYPE_BITMAP; else if (CHECK_ARG("-sdf")) Options.Type = FONT_TYPE_SIGNED_DISTANCE_FIELD; else if (CHECK_ARG_PARAM("-charset")) { if (!FontImporter::AddCharacterSet(&Options, argv[++i])) { Log_ErrorPrintf("Failed to add character set '%s'", argv[i]); return false; } } else if (CHECK_ARG_PARAM("-codepoint")) { uint32 val = StringConverter::StringToUInt32(argv[++i]); if (val == 0) { Log_ErrorPrintf("Invalid code point: %s", argv[i]); return false; } Options.UnicodeCodePointSet.Add(val); } else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintFontImporterSyntax(); return false; } return true; } int RunFontImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintFontImporterSyntax(); return 0; } FontImporterOptions Options; FontImporter::SetDefaultOptions(&Options); for (i = 0; i < argc; i++) { if (!ParseFontImporterOption(Options, i, argc, argv)) return 1; } if (Options.InputFileName.IsEmpty() || Options.OutputName.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output package/name."); return 1; } if (Options.UnicodeCodePointSet.GetSize() == 0) { Log_WarningPrintf("No code point specified, assuming basic latin1"); FontImporter::AddCharacterSet(&Options, "latin1"); } { ConsoleProgressCallbacks progressCallbacks; FontImporter Importer(&progressCallbacks); if (!Importer.Execute(&Options)) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Dependancies/bullet/Demos/Makefile.am if CONDITIONAL_BUILD_MULTITHREADED SUBDIRS=OpenGL BasicDemo ForkLiftDemo FeatherstoneMultiBodyDemo TerrainDemo VehicleDemo CcdPhysicsDemo MultiThreadedDemo SoftDemo AllBulletDemos else SUBDIRS=OpenGL BasicDemo ForkLiftDemo FeatherstoneMultiBodyDemo TerrainDemo VehicleDemo CcdPhysicsDemo SoftDemo AllBulletDemos endif <file_sep>/Editor/Source/Editor/MapEditor/moc_EditorEntityEditMode.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorEntityEditMode.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorEntityEditMode.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorEntityEditMode.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorEntityEditMode_t { QByteArrayData data[23]; char stringdata[574]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorEntityEditMode_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorEntityEditMode_t qt_meta_stringdata_EditorEntityEditMode = { { QT_MOC_LITERAL(0, 0, 20), // "EditorEntityEditMode" QT_MOC_LITERAL(1, 21, 33), // "OnUIOptionsFilterSelectionCli..." QT_MOC_LITERAL(2, 55, 0), // "" QT_MOC_LITERAL(3, 56, 23), // "OnUIWidgetSelectClicked" QT_MOC_LITERAL(4, 80, 7), // "checked" QT_MOC_LITERAL(5, 88, 21), // "OnUIWidgetMoveClicked" QT_MOC_LITERAL(6, 110, 23), // "OnUIWidgetRotateClicked" QT_MOC_LITERAL(7, 134, 22), // "OnUIWidgetScaleClicked" QT_MOC_LITERAL(8, 157, 19), // "OnUIPushLeftClicked" QT_MOC_LITERAL(9, 177, 20), // "OnUIPushRightClicked" QT_MOC_LITERAL(10, 198, 22), // "OnUIPushForwardClicked" QT_MOC_LITERAL(11, 221, 19), // "OnUIPushBackClicked" QT_MOC_LITERAL(12, 241, 17), // "OnUIPushUpClicked" QT_MOC_LITERAL(13, 259, 19), // "OnUIPushDownClicked" QT_MOC_LITERAL(14, 279, 31), // "OnUIActionCreateEntityTriggered" QT_MOC_LITERAL(15, 311, 31), // "OnUIActionDeleteEntityTriggered" QT_MOC_LITERAL(16, 343, 31), // "OnUIActionEntityLayersTriggered" QT_MOC_LITERAL(17, 375, 38), // "OnUIActionSnapSelectionToGrid..." QT_MOC_LITERAL(18, 414, 34), // "OnUIActionCreateComponentTrig..." QT_MOC_LITERAL(19, 449, 34), // "OnUIActionRemoveComponentTrig..." QT_MOC_LITERAL(20, 484, 34), // "OnUIActionSelectionLayersTrig..." QT_MOC_LITERAL(21, 519, 43), // "OnUISelectionComponentListCur..." QT_MOC_LITERAL(22, 563, 10) // "currentRow" }, "EditorEntityEditMode\0" "OnUIOptionsFilterSelectionClicked\0\0" "OnUIWidgetSelectClicked\0checked\0" "OnUIWidgetMoveClicked\0OnUIWidgetRotateClicked\0" "OnUIWidgetScaleClicked\0OnUIPushLeftClicked\0" "OnUIPushRightClicked\0OnUIPushForwardClicked\0" "OnUIPushBackClicked\0OnUIPushUpClicked\0" "OnUIPushDownClicked\0OnUIActionCreateEntityTriggered\0" "OnUIActionDeleteEntityTriggered\0" "OnUIActionEntityLayersTriggered\0" "OnUIActionSnapSelectionToGridTriggered\0" "OnUIActionCreateComponentTriggered\0" "OnUIActionRemoveComponentTriggered\0" "OnUIActionSelectionLayersTriggered\0" "OnUISelectionComponentListCurrentRowChanged\0" "currentRow" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorEntityEditMode[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 19, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 109, 2, 0x08 /* Private */, 3, 1, 110, 2, 0x08 /* Private */, 5, 1, 113, 2, 0x08 /* Private */, 6, 1, 116, 2, 0x08 /* Private */, 7, 1, 119, 2, 0x08 /* Private */, 8, 0, 122, 2, 0x08 /* Private */, 9, 0, 123, 2, 0x08 /* Private */, 10, 0, 124, 2, 0x08 /* Private */, 11, 0, 125, 2, 0x08 /* Private */, 12, 0, 126, 2, 0x08 /* Private */, 13, 0, 127, 2, 0x08 /* Private */, 14, 0, 128, 2, 0x08 /* Private */, 15, 0, 129, 2, 0x08 /* Private */, 16, 0, 130, 2, 0x08 /* Private */, 17, 0, 131, 2, 0x08 /* Private */, 18, 0, 132, 2, 0x08 /* Private */, 19, 0, 133, 2, 0x08 /* Private */, 20, 0, 134, 2, 0x08 /* Private */, 21, 1, 135, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 22, 0 // eod }; void EditorEntityEditMode::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorEntityEditMode *_t = static_cast<EditorEntityEditMode *>(_o); switch (_id) { case 0: _t->OnUIOptionsFilterSelectionClicked(); break; case 1: _t->OnUIWidgetSelectClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: _t->OnUIWidgetMoveClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 3: _t->OnUIWidgetRotateClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 4: _t->OnUIWidgetScaleClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnUIPushLeftClicked(); break; case 6: _t->OnUIPushRightClicked(); break; case 7: _t->OnUIPushForwardClicked(); break; case 8: _t->OnUIPushBackClicked(); break; case 9: _t->OnUIPushUpClicked(); break; case 10: _t->OnUIPushDownClicked(); break; case 11: _t->OnUIActionCreateEntityTriggered(); break; case 12: _t->OnUIActionDeleteEntityTriggered(); break; case 13: _t->OnUIActionEntityLayersTriggered(); break; case 14: _t->OnUIActionSnapSelectionToGridTriggered(); break; case 15: _t->OnUIActionCreateComponentTriggered(); break; case 16: _t->OnUIActionRemoveComponentTriggered(); break; case 17: _t->OnUIActionSelectionLayersTriggered(); break; case 18: _t->OnUISelectionComponentListCurrentRowChanged((*reinterpret_cast< int(*)>(_a[1]))); break; default: ; } } } const QMetaObject EditorEntityEditMode::staticMetaObject = { { &EditorEditMode::staticMetaObject, qt_meta_stringdata_EditorEntityEditMode.data, qt_meta_data_EditorEntityEditMode, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorEntityEditMode::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorEntityEditMode::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorEntityEditMode.stringdata)) return static_cast<void*>(const_cast< EditorEntityEditMode*>(this)); return EditorEditMode::qt_metacast(_clname); } int EditorEntityEditMode::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = EditorEditMode::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 19) qt_static_metacall(this, _c, _id, _a); _id -= 19; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 19) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 19; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ResourceCompilerInterface/ResourceCompilerInterfaceRemote.cpp #include "ResourceCompilerInterface/ResourceCompilerInterfaceRemote.h" #include "Engine/MaterialShader.h" #include "Engine/Skeleton.h" #include "Engine/ResourceManager.h" #include "Engine/MaterialShader.h" #include "Renderer/ShaderComponentTypeInfo.h" #include "Renderer/VertexFactoryTypeInfo.h" #include "Renderer/ShaderCompilerFrontend.h" #include "YBaseLib/BinaryWriteBuffer.h" #include "YBaseLib/BinaryReadBuffer.h" Log_SetChannel(ResourceCompilerInterfaceRemote); #if defined(Y_PLATFORM_WINDOWS) #if defined(Y_BUILD_CONFIG_DEBUG) static const char *RESOURCE_COMPILER_EXECUTABLE_NAME = "ResourceCompiler-Debug.exe"; #elif defined(Y_BUILD_CONFIG_DEBUGFAST) static const char *RESOURCE_COMPILER_EXECUTABLE_NAME = "ResourceCompiler-DebugFast.exe"; #elif defined(Y_BUILD_CONFIG_RELEASE) static const char *RESOURCE_COMPILER_EXECUTABLE_NAME = "ResourceCompiler-Release.exe"; #elif defined(Y_BUILD_CONFIG_SHIPPING) static const char *RESOURCE_COMPILER_EXECUTABLE_NAME = "ResourceCompiler-Shipping.exe"; #else #error Unknown build config. #endif #elif defined(Y_PLATFORM_LINUX) static const char *RESOURCE_COMPILER_EXECUTABLE_NAME = "ResourceCompiler"; #else #error Unknown platform #endif static bool SendCommandAndPayload(Subprocess::Connection *pConnection, REMOTE_COMMAND command, const void *payload, uint32 payloadSize) { REMOTE_COMMAND_HEADER hdr; hdr.Command = command; hdr.PayloadSize = payloadSize; if (pConnection->WriteData(&hdr, sizeof(hdr)) != sizeof(hdr)) return false; if (payloadSize > 0 && pConnection->WriteData(payload, payloadSize) != payloadSize) return false; return true; } static bool WaitForCommandResult(Subprocess::Connection *pConnection, BinaryBlob **ppResultsBlob) { for (;;) { REMOTE_COMMAND_HEADER hdr; if (pConnection->ReadDataBlocking(&hdr, sizeof(hdr)) != sizeof(hdr)) { *ppResultsBlob = nullptr; return false; } switch (hdr.Command) { case REMOTE_COMMAND_GET_FILE_CONTENTS: { // Read string parameter String fileName; fileName.Resize(hdr.PayloadSize); if (pConnection->ReadDataBlocking(fileName.GetWriteableCharArray(), hdr.PayloadSize) != hdr.PayloadSize) { *ppResultsBlob = nullptr; return false; } // Load file AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_FAILURE, nullptr, 0)) { *ppResultsBlob = nullptr; return false; } continue; } // Copy it into memory AutoReleasePtr<BinaryBlob> pBlob = BinaryBlob::CreateFromStream(pStream); if (pBlob == nullptr) { if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_FAILURE, nullptr, 0)) { *ppResultsBlob = nullptr; return false; } continue; } // Send to the other side if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_SUCCESS, pBlob->GetDataPointer(), pBlob->GetDataSize())) { *ppResultsBlob = nullptr; return false; } // Wait for next command continue; } break; case REMOTE_COMMAND_GET_COMPILED_MATERIAL_SHADER: { // Read string parameter String materialShaderName; materialShaderName.Resize(hdr.PayloadSize); if (pConnection->ReadDataBlocking(materialShaderName.GetWriteableCharArray(), hdr.PayloadSize) != hdr.PayloadSize) { *ppResultsBlob = nullptr; return false; } // force a load of it, this'll ensure the version on-disk is up-to-date. AutoReleasePtr<const MaterialShader> pMaterialShader = g_pResourceManager->UncachedGetMaterialShader(materialShaderName); if (pMaterialShader == nullptr) { Log_WarningPrintf("WaitForCommandResult: Remote requested unavailable material shader '%s'", materialShaderName.GetCharArray()); if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_FAILURE, nullptr, 0)) { *ppResultsBlob = nullptr; return false; } } else { // try searching for a compiled version on-disk String fileName; fileName.Format("%s.msh", materialShaderName.GetCharArray()); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); BinaryBlob *pCompiledBlob; if (pStream == nullptr || (pCompiledBlob = BinaryBlob::CreateFromStream(pStream)) == nullptr) { Log_WarningPrintf("WaitForCommandResult: Remote requested material shader '%s', which loaded, but could not locate the compiled version.", materialShaderName.GetCharArray()); *ppResultsBlob = nullptr; return false; } // send this version back if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_SUCCESS, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize())) { pCompiledBlob->Release(); *ppResultsBlob = nullptr; return false; } pCompiledBlob->Release(); } // wait for next command continue; } break; case REMOTE_COMMAND_GET_COMPILED_SKELETON: { // Read string parameter String skeletonName; skeletonName.Resize(hdr.PayloadSize); if (pConnection->ReadDataBlocking(skeletonName.GetWriteableCharArray(), hdr.PayloadSize) != hdr.PayloadSize) { *ppResultsBlob = nullptr; return false; } // force a load of it, this'll ensure the version on-disk is up-to-date. AutoReleasePtr<const Skeleton> pSkeleton = g_pResourceManager->UncachedGetSkeleton(skeletonName); if (pSkeleton == nullptr) { Log_WarningPrintf("WaitForCommandResult: Remote requested unavailable skeleton '%s'", skeletonName.GetCharArray()); if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_FAILURE, nullptr, 0)) { *ppResultsBlob = nullptr; return false; } } else { // try searching for a compiled version on-disk String fileName; fileName.Format("%s.skl", skeletonName.GetCharArray()); AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); BinaryBlob *pCompiledBlob; if (pStream == nullptr || (pCompiledBlob = BinaryBlob::CreateFromStream(pStream)) == nullptr) { Log_WarningPrintf("WaitForCommandResult: Remote requested skeleton '%s', which loaded, but could not locate the compiled version.", skeletonName.GetCharArray()); *ppResultsBlob = nullptr; return false; } // send this version back if (!SendCommandAndPayload(pConnection, REMOTE_COMMAND_SUCCESS, pCompiledBlob->GetDataPointer(), pCompiledBlob->GetDataSize())) { pCompiledBlob->Release(); *ppResultsBlob = nullptr; return false; } pCompiledBlob->Release(); } // wait for next command continue; } break; case REMOTE_COMMAND_SUCCESS: case REMOTE_COMMAND_FAILURE: { if (hdr.PayloadSize == 0) { *ppResultsBlob = nullptr; } else { BinaryBlob *pBlob = BinaryBlob::Allocate(hdr.PayloadSize); if (pConnection->ReadDataBlocking(pBlob->GetDataPointer(), hdr.PayloadSize) != hdr.PayloadSize) { pBlob->Release(); *ppResultsBlob = nullptr; return false; } *ppResultsBlob = pBlob; } return (hdr.Command == REMOTE_COMMAND_SUCCESS); } break; } } } ResourceCompilerInterfaceRemote::ResourceCompilerInterfaceRemote(Subprocess *pSubProcess, Subprocess::Connection *pConnection) : m_pRemoteProcess(pSubProcess), m_pRemoteConnection(pConnection) { } ResourceCompilerInterfaceRemote::~ResourceCompilerInterfaceRemote() { m_pRemoteProcess->RequestChildToExit(); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_EXIT, nullptr, 0)) m_pRemoteProcess->TerminateChild(); m_pRemoteProcess->WaitForChildToExit(); delete m_pRemoteProcess; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileTexture(uint32 texturePlatform, const char *name) { BinaryWriteBuffer buffer; buffer.WriteUInt32(texturePlatform); buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_TEXTURE, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileMaterialShader(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_MATERIAL_SHADER, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileMaterial(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_MATERIAL, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileFont(uint32 texturePlatform, const char *name) { BinaryWriteBuffer buffer; buffer.WriteUInt32(texturePlatform); buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_FONT, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileBlockPalette(uint32 texturePlatform, const char *name) { BinaryWriteBuffer buffer; buffer.WriteUInt32(texturePlatform); buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_BLOCK_PALETTE, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileStaticMesh(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_STATIC_MESH, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileBlockMesh(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_BLOCK_MESH, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileSkeleton(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_SKELETON, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileSkeletalMesh(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_SKELETAL_MESH, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileSkeletalAnimation(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_SKELETAL_ANIMATION, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileParticleSystem(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_PARTICLE_SYSTEM, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } BinaryBlob *ResourceCompilerInterfaceRemote::CompileTerrainLayerList(const char *name) { BinaryWriteBuffer buffer; buffer.WriteSizePrefixedString(name); if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_TERRAIN_LAYER_LIST, buffer.GetBufferPointer(), buffer.GetBufferSize())) return nullptr; BinaryBlob *pResultBlob; if (!WaitForCommandResult(m_pRemoteConnection, &pResultBlob) && pResultBlob != nullptr) { pResultBlob->Release(); pResultBlob = nullptr; } return pResultBlob; } bool ResourceCompilerInterfaceRemote::CompileShader(const ShaderCompilerParameters *pParameters, ByteStream *pOutByteCodeStream, ByteStream *pOutInfoLogStream) { BinaryWriteBuffer buffer; buffer.WriteUInt32(pParameters->Platform); buffer.WriteUInt32(pParameters->FeatureLevel); buffer.WriteUInt32(pParameters->CompilerFlags); for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { buffer.WriteSizePrefixedString(pParameters->StageFileNames[i]); buffer.WriteSizePrefixedString(pParameters->StageEntryPoints[i]); } buffer.WriteSizePrefixedString(pParameters->VertexFactoryFileName); buffer.WriteSizePrefixedString(pParameters->MaterialShaderName); buffer.WriteUInt32(pParameters->MaterialShaderFlags); buffer.WriteBool(pParameters->EnableVerboseInfoLog); buffer.WriteUInt32(pParameters->PreprocessorMacros.GetSize()); for (uint32 i = 0; i < pParameters->PreprocessorMacros.GetSize(); i++) { buffer.WriteSizePrefixedString(pParameters->PreprocessorMacros[i].Key); buffer.WriteSizePrefixedString(pParameters->PreprocessorMacros[i].Value); } if (!SendCommandAndPayload(m_pRemoteConnection, REMOTE_COMMAND_COMPILE_SHADER, buffer.GetBufferPointer(), buffer.GetBufferSize())) return false; BinaryBlob *pResultBlob; bool result = WaitForCommandResult(m_pRemoteConnection, &pResultBlob); // any results? if (pResultBlob != nullptr) { // copy from blob to streams ByteStream *pStream = pResultBlob->CreateReadOnlyStream(); BinaryReader binaryReader(pStream); uint32 byteCodeLength, infoLogLength; if (binaryReader.SafeReadUInt32(&byteCodeLength) && binaryReader.SafeReadUInt32(&infoLogLength)) { if (ByteStream_CopyBytes(pStream, byteCodeLength, pOutByteCodeStream) == byteCodeLength) result &= (ByteStream_CopyBytes(pStream, infoLogLength, pOutInfoLogStream) == infoLogLength); else result = false; } else { result = false; } pStream->Release(); pResultBlob->Release(); } return result; } ResourceCompilerInterface *ResourceCompilerInterface::CreateRemoteInterface() { Log_DevPrintf("ResourceCompilerInterface::CreateRemoteInterface: Spawning ResourceCompiler process."); SmallString programFileName; SmallString resourceCompilerFileName; Platform::GetProgramFileName(programFileName); FileSystem::BuildPathRelativeToFile(resourceCompilerFileName, programFileName, RESOURCE_COMPILER_EXECUTABLE_NAME, true, true); Subprocess *pRemoteProcess = Subprocess::Create(resourceCompilerFileName, "REMOTE_COMPILER", true, true, true); if (pRemoteProcess == nullptr) { Log_ErrorPrintf("ResourceCompilerInterface::CreateRemoteInterface: Failed to create ResourceCompiler process (path: %s)", resourceCompilerFileName.GetCharArray()); return nullptr; } Subprocess::Connection *pConnection = pRemoteProcess->ConnectToChild(); if (pConnection == nullptr) { Log_ErrorPrint("ResourceCompilerInterface::CreateRemoteInterface: Failed to connect to ResourceCompiler."); pRemoteProcess->TerminateChild(); delete pRemoteProcess; return nullptr; } ResourceCompilerInterfaceRemote *pInterface = new ResourceCompilerInterfaceRemote(pRemoteProcess, pConnection); return pInterface; } <file_sep>/Engine/Source/MapCompiler/MapCompiler.cpp #include "MapCompiler/MapCompiler.h" #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "ResourceCompiler/TerrainLayerListGenerator.h" #include "ResourceCompiler/ClassTableGenerator.h" #include "Engine/TerrainSection.h" #include "Engine/DataFormats.h" #include "Core/ClassTable.h" #include "YBaseLib/ZipArchive.h" Log_SetChannel(MapCompiler); MapCompiler::MapCompiler(MapSource *pMapSource) : m_pMapSource(pMapSource), m_pInputStream(nullptr), m_pOutputStream(nullptr), m_pOutputArchive(nullptr), m_pClassTableGenerator(nullptr), m_regionSize(0), m_regionLODLevels(0), m_worldBoundingBox(float3::NegativeInfinite, float3::Infinite), m_pGlobalEntityData(nullptr) { } MapCompiler::~MapCompiler() { for (uint32 i = 0; i < m_regions.GetSize(); i++) delete m_regions[i]; delete m_pGlobalEntityData; delete m_pClassTableGenerator; delete m_pOutputArchive; SAFE_RELEASE(m_pInputStream); SAFE_RELEASE(m_pOutputStream); } bool MapCompiler::StartFreshCompile(ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { m_pOutputStream = pOutputStream; m_pOutputStream->AddRef(); m_pOutputArchive = ZipArchive::CreateArchive(pOutputStream); if (m_pOutputArchive == nullptr) { pProgressCallbacks->DisplayError("Could not open zip archive"); return false; } // create class table m_pClassTableGenerator = new ClassTableGenerator(); // run prep steps if (!PrepareSourceForCompiling(pProgressCallbacks)) { pProgressCallbacks->DisplayError("Could not prepare source"); return false; } return true; } bool MapCompiler::StartReuseCompile(ByteStream *pInputStream, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { //DF_MAP_HEADER mapHeader; return false; } bool MapCompiler::BuildAll(int32 mapLOD /*= -1*/, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { // if mapLOD < 0, build all lods if (mapLOD < 0) { pProgressCallbacks->SetProgressRange(m_regionLODLevels); pProgressCallbacks->SetProgressValue(0); for (uint32 lodLevel = 0; lodLevel < m_regionLODLevels; lodLevel++) { pProgressCallbacks->SetProgressValue(lodLevel); pProgressCallbacks->PushState(); if (!BuildAll(lodLevel, pProgressCallbacks)) { pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(m_regionLODLevels); return true; } pProgressCallbacks->SetProgressRange(m_regions.GetSize() + 1); pProgressCallbacks->SetProgressValue(0); if (mapLOD == 0) { // build global entities [always done] for level 0 pProgressCallbacks->PushState(); if (!BuildGlobalEntities(pProgressCallbacks)) { pProgressCallbacks->DisplayError("Failed to build global regions"); pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } else { // ensure each region at lod 0 has a corresponding lod region for (uint32 i = 0; i < m_regions.GetSize(); i++) { if (m_regions[i]->RegionLODLevel == 0) { int32 regionX = m_regions[i]->RegionX; int32 regionY = m_regions[i]->RegionY; if (GetRegion(regionX, regionY, (uint32)mapLOD) == nullptr) CreateRegion(regionX, regionY, (uint32)mapLOD); } } pProgressCallbacks->SetProgressRange(m_regions.GetSize() + 1); } pProgressCallbacks->SetProgressValue(1); // build each region for (uint32 i = 0; i < m_regions.GetSize(); i++) { if (m_regions[i]->RegionLODLevel == (uint32)mapLOD) { pProgressCallbacks->PushState(); if (mapLOD == 0) { if (!BuildRegion(m_regions[i]->RegionX, m_regions[i]->RegionY, pProgressCallbacks)) { pProgressCallbacks->DisplayFormattedError("Failed to build region [%i, %i]", m_regions[i]->RegionX, m_regions[i]->RegionY); pProgressCallbacks->PopState(); return false; } } else { if (!BuildRegionLOD(m_regions[i]->RegionX, m_regions[i]->RegionY, (uint32)mapLOD, pProgressCallbacks)) { pProgressCallbacks->DisplayFormattedError("Failed to build generate region [%i, %i] lod level %u", m_regions[i]->RegionX, m_regions[i]->RegionY, (uint32)mapLOD); pProgressCallbacks->PopState(); return false; } } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(i + 1); } // ok return true; } bool MapCompiler::BuildGlobalEntities(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (m_newGlobalEntityRefs.GetSize() == 0) { delete m_pGlobalEntityData; return true; } pProgressCallbacks->SetStatusText("Building global regions..."); // kill old data delete m_pGlobalEntityData; // build new data return CompileEntityData(m_newGlobalEntityRefs.GetBasePointer(), m_newGlobalEntityRefs.GetSize(), &m_pGlobalEntityData, pProgressCallbacks); } bool MapCompiler::BuildRegion(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // load, and build all 3 components to the region pProgressCallbacks->SetProgressRange(3); pProgressCallbacks->SetProgressValue(0); // load if present in old stream Region *pRegion = GetRegion(regionX, regionY, 0); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i]", regionX, regionY); return false; } pProgressCallbacks->SetProgressValue(1); // build entities { pProgressCallbacks->PushState(); if (!BuildRegionEntities(regionX, regionY, pProgressCallbacks)) { pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(2); // build terrain if (m_pMapSource->HasTerrain()) { pProgressCallbacks->PushState(); if (!BuildRegionTerrain(regionX, regionY, pProgressCallbacks)) { pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(3); // ok pProgressCallbacks->DisplayFormattedInformation("Built region [%i, %i]", regionX, regionY); return true; } bool MapCompiler::BuildRegionEntities(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { pProgressCallbacks->SetFormattedStatusText("Building region [%i, %i] entities...", regionX, regionY); // load if present in old stream Region *pRegion = GetRegion(regionX, regionY, 0); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i]", regionX, regionY); return false; } // build entities return pRegion->RecompileEntityData(pProgressCallbacks); } bool MapCompiler::BuildRegionTerrain(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pMapSource->HasTerrain()); pProgressCallbacks->SetFormattedStatusText("Building region [%i, %i] terrain...", regionX, regionY); // load if present in old stream Region *pRegion = GetRegion(regionX, regionY, 0); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i]", regionX, regionY); return false; } // build terrain data return pRegion->RecompileTerrainData(pProgressCallbacks); } bool MapCompiler::FinalizeCompile(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { pProgressCallbacks->SetProgressRange(m_regions.GetSize() + 6); pProgressCallbacks->SetProgressValue(0); // save any unsaved regions pProgressCallbacks->SetStatusText("Writing regions..."); for (uint32 i = 0; i < m_regions.GetSize(); i++) { Region *pRegion = m_regions[i]; // region has been changed but not saved? if (pRegion->RegionChanged && !pRegion->RegionExistsInNewStream && !SaveRegion(pRegion)) { pProgressCallbacks->DisplayFormattedError("Failed to write region [%i, %i, %u]", pRegion->RegionX, pRegion->RegionY, pRegion->RegionLODLevel); return false; } pProgressCallbacks->IncrementProgressValue(); } // rewrite header pProgressCallbacks->SetStatusText("Writing map header..."); if (!SaveMapHeader()) { pProgressCallbacks->DisplayError("Failed to write map header"); return false; } pProgressCallbacks->IncrementProgressValue(); // write regions header if (m_regions.GetSize() > 0) { if (!SaveRegionsHeader()) { pProgressCallbacks->DisplayError("Failed to write regions header"); return false; } } pProgressCallbacks->IncrementProgressValue(); // write terrain header if (m_pMapSource->HasTerrain()) { if (!SaveTerrainHeader()) { pProgressCallbacks->DisplayError("Failed to write terrain header"); return false; } } pProgressCallbacks->IncrementProgressValue(); // write global entities header if (m_pGlobalEntityData != nullptr) { if (!SaveGlobalEntityData()) { pProgressCallbacks->DisplayError("Failed to write global entities data"); return false; } } pProgressCallbacks->IncrementProgressValue(); // write class table if (m_pClassTableGenerator != nullptr) { if (!SaveClassTable()) { pProgressCallbacks->DisplayError("Failed to write class table"); return false; } } pProgressCallbacks->IncrementProgressValue(); // commit the zipfile pProgressCallbacks->SetStatusText("Commiting archive..."); if (!m_pOutputArchive->CommitChanges()) { pProgressCallbacks->DisplayError("Failed to commit zip file"); return false; } pProgressCallbacks->IncrementProgressValue(); // read pointer no longer valid if (m_pInputStream != nullptr) { m_pInputStream->Release(); m_pInputStream = nullptr; } // ok return true; } void MapCompiler::DiscardCompile() { // discard write zip archive m_pOutputArchive->DiscardChanges(); m_pInputStream = nullptr; m_pOutputStream = nullptr; m_pOutputArchive = nullptr; } bool MapCompiler::BuildRegionLOD(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { // load, and build all 3 components to the region pProgressCallbacks->SetProgressRange(4); pProgressCallbacks->SetProgressValue(0); // load if present in old stream Region *pRegion = GetRegion(regionX, regionY, lodLevel); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i, %u]", regionX, regionY, lodLevel); return false; } pProgressCallbacks->SetProgressValue(1); // build entities { pProgressCallbacks->PushState(); if (!BuildRegionLODEntities(regionX, regionY, lodLevel, pProgressCallbacks)) { pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(2); // build terrain if (m_pMapSource->HasTerrain()) { pProgressCallbacks->PushState(); if (!BuildRegionLODTerrain(regionX, regionY, lodLevel, pProgressCallbacks)) { pProgressCallbacks->PopState(); return false; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(3); // ok pProgressCallbacks->DisplayFormattedInformation("Built region [%i, %i, %u]", regionX, regionY, lodLevel); return true; } bool MapCompiler::BuildRegionLODEntities(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { pProgressCallbacks->SetFormattedStatusText("Building region [%i, %i, %u] entities...", regionX, regionY, lodLevel); /* // load if present in old stream Region *pRegion = GetRegion(regionX, regionY, lodLevel); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i, %i]", regionX, regionY, lodLevel); return false; } // build entities return pRegion->RecompileEntityData(pProgressCallbacks); */ return true; } bool MapCompiler::BuildRegionLODTerrain(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { DebugAssert(m_pMapSource->HasTerrain()); pProgressCallbacks->SetFormattedStatusText("Building region [%i, %i, %u] terrain...", regionX, regionY, lodLevel); /*// load if present in old stream Region *pRegion = GetRegion(regionX, regionY); if (pRegion->RegionExistsInCurrentStream && !pRegion->RegionLoaded && !pRegion->LoadData()) { pProgressCallbacks->DisplayFormattedError("Failed to load existing data for region [%i, %i, %u]", regionX, regionY, lodLevel); return false; } // build terrain data return pRegion->RecompileTerrainData(pProgressCallbacks);*/ return true; } void MapCompiler::UpdateWorldBoundingBox(const AABox &boundingBox) { UpdateWorldBoundingBox(boundingBox.GetMinBounds()); UpdateWorldBoundingBox(boundingBox.GetMaxBounds()); } void MapCompiler::UpdateWorldBoundingBox(const float3 &point) { float3 newMinBounds(m_worldBoundingBox.GetMinBounds().Min(point)); float3 newMaxBounds(m_worldBoundingBox.GetMaxBounds().Max(point)); // update all 3 coordinates, if there is currently an infinte value, replace it for (uint32 i = 0; i < 3; i++) { if (newMinBounds[i] == -Y_FLT_INFINITE) newMinBounds[i] = point[i]; if (newMaxBounds[i] == Y_FLT_INFINITE) newMaxBounds[i] = point[i]; } m_worldBoundingBox.SetBounds(newMinBounds, newMaxBounds); } bool MapCompiler::CompileEntityDataSingle(const MapSourceEntityData *pEntityData, const ObjectTemplate *pTemplate, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks) { uint64 reseekOffset; // does the entity exist in the class table? if not, add it if (m_pClassTableGenerator->GetTypeByName(pTemplate->GetTypeName()) == nullptr) m_pClassTableGenerator->CreateTypeFromPropertyTemplate(pTemplate->GetTypeName(), pTemplate->GetPropertyTemplate()); // write entity header BinaryWriter binaryWriter(pOutputStream, ENDIAN_TYPE_LITTLE); uint64 entityHeaderOffset = binaryWriter.GetStreamPosition(); DF_MAP_ENTITY_HEADER entityHeader; entityHeader.HeaderSize = sizeof(entityHeader); entityHeader.EntityNameLength = pEntityData->GetEntityName().GetLength(); entityHeader.EntityTypeIndex = 0xFFFFFFFF; entityHeader.EntitySize = 0; entityHeader.ComponentsSize = 0; entityHeader.ComponentCount = 0; if (!binaryWriter.SafeWriteType(&entityHeader)) return false; // write the entity name if (!binaryWriter.SafeWriteFixedString(pEntityData->GetEntityName(), pEntityData->GetEntityName().GetLength())) return false; // serialize the entity object uint32 writtenBytes; if (!m_pClassTableGenerator->SerializeObjectBinary(pOutputStream, pTemplate->GetTypeName(), pTemplate->GetPropertyTemplate(), pEntityData->GetPropertyTable(), &entityHeader.EntityTypeIndex, &writtenBytes)) return false; // calculate size entityHeader.EntitySize = (uint32)(binaryWriter.GetStreamPosition() - entityHeaderOffset - sizeof(entityHeader)); // write components uint64 componentsStartOffset = binaryWriter.GetStreamPosition(); for (uint32 componentIndex = 0; componentIndex < pEntityData->GetComponentCount(); componentIndex++) { // template exists? const MapSourceEntityComponent *pComponentData = pEntityData->GetComponentByIndex(componentIndex); const ObjectTemplate *pComponentTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pComponentData->GetTypeName()); if (pComponentTemplate == nullptr) { pProgressCallbacks->DisplayFormattedError("Skipping component '%s' of type '%s' in entity '%s' due to it being unknown.", pComponentData->GetComponentName().GetCharArray(), pComponentData->GetTypeName().GetCharArray(), pEntityData->GetEntityName().GetCharArray()); continue; } // ensure it exists in the class table if (m_pClassTableGenerator->GetTypeByName(pComponentTemplate->GetTypeName()) == nullptr) m_pClassTableGenerator->CreateTypeFromPropertyTemplate(pComponentTemplate->GetTypeName(), pComponentTemplate->GetPropertyTemplate()); // write the component header uint64 thisComponentHeaderOffset = binaryWriter.GetStreamPosition(); DF_MAP_ENTITY_COMPONENT_HEADER componentHeader; componentHeader.ComponentSize = 0; componentHeader.ComponentNameLength = pComponentData->GetComponentName().GetLength(); componentHeader.ComponentTypeIndex = 0xFFFFFFFF; if (!binaryWriter.SafeWriteType(&componentHeader)) return false; // write component name if (!binaryWriter.SafeWriteFixedString(pComponentData->GetComponentName(), pComponentData->GetComponentName().GetLength())) return false; // serialize the component object if (!m_pClassTableGenerator->SerializeObjectBinary(pOutputStream, pComponentTemplate->GetTypeName(), pComponentTemplate->GetPropertyTemplate(), pComponentData->GetPropertyTable(), &componentHeader.ComponentTypeIndex, &writtenBytes)) return false; // update the component size componentHeader.ComponentSize = (uint32)(binaryWriter.GetStreamPosition() - thisComponentHeaderOffset - sizeof(componentHeader)); // rewrite the component header reseekOffset = binaryWriter.GetStreamPosition(); if (!binaryWriter.SafeSeekAbsolute(thisComponentHeaderOffset) || !binaryWriter.SafeWriteType(&componentHeader) || !binaryWriter.SafeSeekAbsolute(reseekOffset)) return false; // increment component count entityHeader.ComponentCount++; } // update components size entityHeader.ComponentsSize = (uint32)(binaryWriter.GetStreamPosition() - componentsStartOffset); // rewrite entity header reseekOffset = binaryWriter.GetStreamPosition(); if (!binaryWriter.SafeSeekAbsolute(entityHeaderOffset) || !binaryWriter.SafeWriteType(&entityHeader) || !binaryWriter.SafeSeekAbsolute(reseekOffset)) return false; // done return true; } bool MapCompiler::CompileEntityData(const MapSourceEntityData *const *ppEntities, uint32 entityCount, RegionEntityData **ppOutData, ProgressCallbacks *pProgressCallbacks) { pProgressCallbacks->SetProgressRange(entityCount); pProgressCallbacks->SetProgressValue(0); // create stream AutoReleasePtr<ByteStream> pEntityStream = ByteStream_CreateGrowableMemoryStream(); // compile entities for (uint32 i = 0; i < entityCount; i++) { const MapSourceEntityData *pEntityData = ppEntities[i]; // find the template for it const ObjectTemplate *pObjectTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pEntityData->GetTypeName()); if (pObjectTemplate == nullptr) { pProgressCallbacks->DisplayFormattedWarning("Cannot compile entity '%s': No template found for entity type '%s'", pEntityData->GetEntityName().GetCharArray(), pEntityData->GetTypeName().GetCharArray()); pProgressCallbacks->IncrementProgressValue(); continue; } // compile the entity if (!CompileEntityDataSingle(ppEntities[i], pObjectTemplate, pEntityStream, pProgressCallbacks)) { pProgressCallbacks->DisplayFormattedError("Failed to compile entity '%s' ('%s')", pEntityData->GetEntityName().GetCharArray(), pEntityData->GetTypeName().GetCharArray()); return false; } pProgressCallbacks->IncrementProgressValue(); } // create output data *ppOutData = new RegionEntityData(entityCount, BinaryBlob::CreateFromStream(pEntityStream)); return true; } bool MapCompiler::CompileTerrainSection(int32 sectionX, int32 sectionY, RegionTerrainSectionData **ppOutData) { bool wasLoaded = m_pMapSource->GetTerrainData()->IsSectionLoaded(sectionX, sectionY); if (!wasLoaded && !m_pMapSource->GetTerrainData()->LoadSection(sectionX, sectionY)) return false; // load the section TerrainSection *pSection = m_pMapSource->GetTerrainData()->GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); // optimize the section pSection->RebuildSplatMaps(); if (!pSection->RebuildQuadTree()) { Log_ErrorPrintf("MapCompiler::CompileTerrainSection: Quadtree generation failed [%i, %i]", sectionX, sectionY); delete pSection; return false; } // write it out AutoReleasePtr<ByteStream> pSectionStream = ByteStream_CreateGrowableMemoryStream(); if (!pSection->SaveToStream(pSectionStream)) { Log_ErrorPrintf("MapCompiler::CompileTerrainSection: Section write failed [%i, %i]", sectionX, sectionY); delete pSection; return false; } // if it wasn't loaded, flag it as unchanged and unload it if (!wasLoaded) { pSection->ClearChangedFlag(); m_pMapSource->GetTerrainData()->UnloadSection(sectionX, sectionY); } // create data from it, easy *ppOutData = new RegionTerrainSectionData(sectionX, sectionY, BinaryBlob::CreateFromStream(pSectionStream)); return true; } bool MapCompiler::PrepareSourceForCompiling(ProgressCallbacks *pProgressCallbacks) { pProgressCallbacks->SetProgressRange(3); pProgressCallbacks->SetProgressValue(0); // init fields m_regionSize = m_pMapSource->GetRegionSize(); m_regionLODLevels = m_pMapSource->GetRegionLODLevels(); m_regionLoadRadius = m_pMapSource->GetProperties()->GetPropertyValueDefaultUInt32("RegionLoadRadius", 2); m_regionActivationRadius = m_pMapSource->GetProperties()->GetPropertyValueDefaultUInt32("RegionActivationRadius", 1); pProgressCallbacks->SetStatusText("Allocating regions for entities..."); pProgressCallbacks->PushState(); CreateRegions_Entities(pProgressCallbacks); pProgressCallbacks->PopState(); if (m_pMapSource->HasTerrain()) { pProgressCallbacks->SetStatusText("Allocating regions for terrain..."); pProgressCallbacks->PushState(); CreateRegions_Terrain(pProgressCallbacks); pProgressCallbacks->PopState(); } return true; } MapCompiler::Region::Region(MapCompiler *pMapCompiler, int32 regionX, int32 regionY, uint32 lodLevel) : pMapCompiler(pMapCompiler), RegionX(regionX), RegionY(regionY), RegionLODLevel(lodLevel), RegionExistsInCurrentStream(false), RegionExistsInNewStream(false), RegionLoaded(false), RegionChanged(false), CompiledEntityData(nullptr) { } MapCompiler::Region::~Region() { for (uint32 i = 0; i < CompiledTerrainData.GetSize(); i++) delete CompiledTerrainData[i]; delete CompiledEntityData; } bool MapCompiler::Region::RecompileTerrainData(ProgressCallbacks *pProgressCallbacks) { // delete existing data for (uint32 i = 0; i < CompiledTerrainData.GetSize(); i++) delete CompiledTerrainData[i]; CompiledTerrainData.Clear(); // create new data for (uint32 i = 0; i < NewTerrainSections.GetSize(); i++) { // compile this section RegionTerrainSectionData *pSectionData; if (!pMapCompiler->CompileTerrainSection(NewTerrainSections[i].x, NewTerrainSections[i].y, &pSectionData)) return false; pProgressCallbacks->DisplayFormattedDebugMessage("terrain section %i,%i -> region %i,%i", NewTerrainSections[i].x, NewTerrainSections[i].y, RegionX, RegionY); CompiledTerrainData.Add(pSectionData); } return true; } bool MapCompiler::Region::RecompileEntityData(ProgressCallbacks *pProgressCallbacks) { // delete existing data delete CompiledEntityData; CompiledEntityData = nullptr; // create new data if (NewEntityRefs.GetSize() > 0) { if (!pMapCompiler->CompileEntityData(NewEntityRefs.GetBasePointer(), NewEntityRefs.GetSize(), &CompiledEntityData, pProgressCallbacks)) return false; } return true; } bool MapCompiler::Region::LoadData() { // load everything, nothing should've been written at this point! DebugAssert(CompiledTerrainData.GetSize() == 0); DebugAssert(CompiledEntityData == nullptr); RegionLoaded = true; return true; } MapCompiler::Region *MapCompiler::CreateRegion(int32 regionX, int32 regionY, uint32 lodLevel) { DebugAssert(GetRegion(regionX, regionY, lodLevel) == nullptr); Region *pRegion = new Region(this, regionX, regionY, lodLevel); pRegion->RegionChanged = true; pRegion->RegionLoaded = true; m_regions.Add(pRegion); // calculate the min/max bounds of the region, and update the map bounding box UpdateWorldBoundingBox(float3(static_cast<float>(pRegion->RegionX * (int32)m_pMapSource->GetRegionSize()), static_cast<float>(pRegion->RegionY * (int32)m_pMapSource->GetRegionSize()), -Y_FLT_INFINITE)); UpdateWorldBoundingBox(float3(static_cast<float>((pRegion->RegionX + 1) * (int32)m_pMapSource->GetRegionSize()), static_cast<float>((pRegion->RegionY + 1) * (int32)m_pMapSource->GetRegionSize()), Y_FLT_INFINITE)); // return region return pRegion; } MapCompiler::Region *MapCompiler::GetRegion(int32 regionX, int32 regionY, uint32 lodLevel) { for (uint32 i = 0; i < m_regions.GetSize(); i++) { Region *pRegion = m_regions[i]; if (pRegion->RegionX == regionX && pRegion->RegionY == regionY && pRegion->RegionLODLevel == lodLevel) return pRegion; } return nullptr; } void MapCompiler::CreateRegions_Entities(ProgressCallbacks *pProgressCallbacks) { // iterate through all entities in the map source, find the region for them, create the region if it doesn't exist, and append them to the new list for that section pProgressCallbacks->SetProgressRange(m_pMapSource->GetEntityCount()); pProgressCallbacks->SetProgressValue(0); // find entities m_pMapSource->EnumerateEntities([this, pProgressCallbacks](const MapSourceEntityData *pEntityData) { // is this a global entity? bool entityIsGlobal = pEntityData->GetPropertyTable()->GetPropertyValueDefaultBool("Global", false); if (entityIsGlobal) { // insert into global list m_newGlobalEntityRefs.Add(pEntityData); } else { // get region for this entity float3 entityPosition(pEntityData->GetPropertyTable()->GetPropertyValueDefaultFloat3("Position", float3::Zero)); int2 entityRegion(m_pMapSource->GetRegionForPosition(entityPosition)); // does this region exist? Region *pRegion = GetRegion(entityRegion.x, entityRegion.y, 0); if (pRegion == nullptr) { // create it pRegion = CreateRegion(entityRegion.x, entityRegion.y, 0); } // add new ref to region pRegion->NewEntityRefs.Add(pEntityData); } pProgressCallbacks->IncrementProgressValue(); }); } void MapCompiler::CreateRegions_Terrain(ProgressCallbacks *pProgressCallbacks) { MapSourceTerrainData *pTerrainData = m_pMapSource->GetTerrainData(); DebugAssert(pTerrainData != nullptr); if (pTerrainData == nullptr) return; // iterate through available sections, figure out the region from them, and create if needed pTerrainData->EnumerateAvailableSections([this](int32 sectionX, int32 sectionY) { // get region int2 sectionRegion(m_pMapSource->GetRegionForTerrainSection(sectionX, sectionY)); // does this region exist? Region *pRegion = GetRegion(sectionRegion.x, sectionRegion.y, 0); if (pRegion == nullptr) { // create it pRegion = CreateRegion(sectionRegion.x, sectionRegion.y, 0); } // add new ref to region pRegion->NewTerrainSections.Add(int2(sectionX, sectionY)); }); } bool MapCompiler::SaveRegion(Region *pRegion) { SmallString regionFileName; regionFileName.Format("region_%i_%i.%u", pRegion->RegionX, pRegion->RegionY, pRegion->RegionLODLevel); AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(regionFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // sum up the data size of all terrains/block terrains/entitys uint32 terrainDataSize = 0; for (uint32 i = 0; i < pRegion->CompiledTerrainData.GetSize(); i++) terrainDataSize += sizeof(DF_MAP_REGION_TERRAIN_SECTION_HEADER) + pRegion->CompiledTerrainData[i]->pData->GetDataSize(); // write header DF_MAP_REGION_HEADER regionHeader; regionHeader.HeaderSize = sizeof(regionHeader); regionHeader.LODLevel = pRegion->RegionLODLevel; regionHeader.RegionX = pRegion->RegionX; regionHeader.RegionY = pRegion->RegionY; regionHeader.TerrainSectionCount = pRegion->CompiledTerrainData.GetSize(); regionHeader.TerrainDataSize = terrainDataSize; regionHeader.EntityCount = (pRegion->CompiledEntityData != nullptr) ? pRegion->CompiledEntityData->EntityCount : 0; regionHeader.EntityDataSize = (pRegion->CompiledEntityData != nullptr) ? pRegion->CompiledEntityData->pData->GetDataSize() : 0; if (!pStream->Write2(&regionHeader, sizeof(regionHeader))) return false; // write terrain data for (uint32 i = 0; i < pRegion->CompiledTerrainData.GetSize(); i++) { RegionTerrainSectionData *pData = pRegion->CompiledTerrainData[i]; // write section header DF_MAP_REGION_TERRAIN_SECTION_HEADER sectionHeader; sectionHeader.SectionX = pData->SectionX; sectionHeader.SectionY = pData->SectionY; sectionHeader.LODLevel = 0; sectionHeader.DataSize = pData->pData->GetDataSize(); if (!pStream->Write2(&sectionHeader, sizeof(sectionHeader))) return false; // write section data if (!pStream->Write2(pData->pData->GetDataPointer(), pData->pData->GetDataSize())) return false; } // write entity data if (pRegion->CompiledEntityData != nullptr) { if (!pStream->Write2(pRegion->CompiledEntityData->pData->GetDataPointer(), pRegion->CompiledEntityData->pData->GetDataSize())) return false; } // now exists in new file pRegion->RegionExistsInNewStream = true; // ok return true; } bool MapCompiler::SaveMapHeader() { // open zeh file AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(DF_MAP_HEADER_FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // write header DF_MAP_HEADER mapHeader; mapHeader.HeaderSize = sizeof(mapHeader); mapHeader.Version = DF_MAP_HEADER_VERSION; mapHeader.RegionSize = m_regionSize; mapHeader.RegionLODLevels = m_regionLODLevels; mapHeader.RegionLoadRadius = m_regionLoadRadius; mapHeader.RegionActivationRadius = m_regionActivationRadius; m_worldBoundingBox.GetMinBounds().Store(mapHeader.WorldBoundingBoxMin); m_worldBoundingBox.GetMaxBounds().Store(mapHeader.WorldBoundingBoxMax); mapHeader.HasRegions = (m_regions.GetSize() > 0) ? 1 : 0; mapHeader.HasTerrain = (m_pMapSource->HasTerrain()) ? 1 : 0; mapHeader.HasGlobalEntities = (m_pGlobalEntityData != nullptr) ? 1 : 0; if (!pStream->Write2(&mapHeader, sizeof(mapHeader))) return false; return true; } bool MapCompiler::SaveRegionsHeader() { AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(DF_MAP_REGIONS_HEADER_FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // count regions at lod 0 uint32 regionCount = 0; for (uint32 i = 0; i < m_regions.GetSize(); i++) { if (m_regions[i]->RegionLODLevel == 0) regionCount++; } // write the header DF_MAP_REGIONS_HEADER regionsHeader; regionsHeader.HeaderSize = sizeof(regionsHeader); regionsHeader.RegionCount = regionCount; if (!pStream->Write2(&regionsHeader, sizeof(regionsHeader))) return false; // write region index for (uint32 i = 0; i < m_regions.GetSize(); i++) { if (m_regions[i]->RegionLODLevel != 0) continue; int2 regionCoordinates(m_regions[i]->RegionX, m_regions[i]->RegionY); if (!pStream->Write2(&regionCoordinates, sizeof(int2))) return false; } return true; } bool MapCompiler::SaveTerrainHeader() { PathString fileName; const MapSourceTerrainData *pTerrainData = m_pMapSource->GetTerrainData(); // write the header { AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(DF_MAP_TERRAIN_HEADER_FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // retreive parameters const TerrainParameters *pTerrainParameters = pTerrainData->GetParameters(); // write the header DF_MAP_TERRAIN_HEADER terrainHeader; terrainHeader.HeaderSize = sizeof(terrainHeader); terrainHeader.HeightStorageFormat = (uint32)pTerrainParameters->HeightStorageFormat; terrainHeader.MinHeight = pTerrainParameters->MinHeight; terrainHeader.MaxHeight = pTerrainParameters->MaxHeight; terrainHeader.BaseHeight = pTerrainParameters->BaseHeight; terrainHeader.Scale = pTerrainParameters->Scale; terrainHeader.SectionSize = pTerrainParameters->SectionSize; terrainHeader.LODCount = pTerrainParameters->LODCount; if (!pStream->Write2(&terrainHeader, sizeof(terrainHeader))) return false; } // write the layer list { fileName.Format("%s", DF_MAP_TERRAIN_LAYERS_FILENAME_PREFIX); AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; // compile the layer list AutoReleasePtr<ByteStream> pLayerListStream = ByteStream_CreateGrowableMemoryStream(); if (!pTerrainData->GetLayerListGenerator()->Compile(pStream)) { Log_ErrorPrintf("Failed to compile terrain layers"); return false; } } return true; } bool MapCompiler::SaveClassTable() { DebugAssert(m_pClassTableGenerator != nullptr); AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(DF_MAP_CLASS_TABLE_FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; if (!m_pClassTableGenerator->Compile(pStream)) return false; return true; } bool MapCompiler::LoadGlobalEntityData() { DebugAssert(m_pGlobalEntityData == nullptr); // write to the appropriate file AutoReleasePtr<ByteStream> pStream = m_pOutputArchive->OpenFile(DF_MAP_GLOBAL_ENTITIES_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // read the header DF_MAP_GLOBAL_ENTITIES_HEADER header; if (!pStream->Read2(&header, sizeof(header)) || header.HeaderSize != sizeof(header)) return false; // create data BinaryBlob *pData = BinaryBlob::Allocate(header.EntityDataSize); if (!pStream->Read2(pData->GetDataPointer(), header.EntityDataSize)) { pData->Release(); return false; } // store it m_pGlobalEntityData = new RegionEntityData(header.EntityCount, pData); return true; } bool MapCompiler::CompileGlobalEntityData(ProgressCallbacks *pProgressCallbacks) { // delete old data delete m_pGlobalEntityData; m_pGlobalEntityData = nullptr; // write new data if (m_newGlobalEntityRefs.GetSize() > 0) { if (!CompileEntityData(m_newGlobalEntityRefs.GetBasePointer(), m_newGlobalEntityRefs.GetSize(), &m_pGlobalEntityData, pProgressCallbacks)) return false; } return true; } bool MapCompiler::SaveGlobalEntityData() { if (m_pGlobalEntityData == nullptr) return true; // write to the appropriate file ByteStream *pStream = m_pOutputArchive->OpenFile(DF_MAP_GLOBAL_ENTITIES_FILENAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // write out the header DF_MAP_GLOBAL_ENTITIES_HEADER header; header.HeaderSize = sizeof(header); header.EntityCount = m_pGlobalEntityData->EntityCount; header.EntityDataSize = m_pGlobalEntityData->pData->GetDataSize(); if (!pStream->Write2(&header, sizeof(header))) { pStream->Release(); return false; } // write out the data if (!pStream->Write2(m_pGlobalEntityData->pData->GetDataPointer(), m_pGlobalEntityData->pData->GetDataSize())) { pStream->Release(); return false; } // ok pStream->Release(); return true; } <file_sep>/Engine/Source/ResourceCompiler/ParticleSystemGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Core/PropertyTable.h" struct ResourceCompilerCallbacks; class ParticleSystemGenerator { public: class Module { friend class ParticleSystemGenerator; public: Module(const char *typeName); ~Module(); const String &GetTypeName() const { return m_typeName; } const PropertyTable *GetPropertyTable() const { return &m_properties; } PropertyTable *GetPropertyTable() { return &m_properties; } private: String m_typeName; PropertyTable m_properties; }; class Emitter { class Properties { public: static const char *MaxActiveParticles; static const char *UpdateInterval; static const char *SpawnRate; static const char *SpawnCount; }; friend class ParticleSystemGenerator; public: Emitter(const char *name, const char *typeName); ~Emitter(); const String &GetName() const { return m_name; } const String &GetTypeName() const { return m_typeName; } const PropertyTable *GetPropertyTable() const { return &m_properties; } PropertyTable *GetPropertyTable() { return &m_properties; } const uint32 GetMaxActiveParticles() const; const float GetUpdateInterval() const; const float GetSpawnRate() const; const uint32 GetSpawnCount() const; void SetName(const char *name); void SetMaxActiveParticles(uint32 maxActiveParticles); void SetUpdateInterval(float updateInterval); void SetSpawnRate(float spawnRate); void SetSpawnCount(uint32 spawnCount); const uint32 GetModuleCount() const; const Module *GetModuleByIndex(uint32 index) const; Module *GetModuleByIndex(uint32 index); void AddModule(Module *pModule); void RemoveModule(Module *pModule); private: String m_name; String m_typeName; PropertyTable m_properties; PODArray<Module *> m_modules; }; public: ParticleSystemGenerator(); ~ParticleSystemGenerator(); // creating emitters/modules static Emitter *CreateEmitter(const char *emitterName, const char *typeName); static Module *CreateModule(const char *typeName); // Loading/saving interface bool LoadFromXML(const char *fileName, ByteStream *pStream); bool SaveToXML(ByteStream *pStream); // emitter management const uint32 GetEmitterCount() const; const Emitter *GetEmitterByIndex(uint32 index) const; const Emitter *GetEmitterByName(const char *name) const; Emitter *GetEmitterByIndex(uint32 index); Emitter *GetEmitterByName(const char *name); // compiling bool Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const; private: PODArray<Emitter *> m_emitters; };<file_sep>/Engine/Source/D3D12Renderer/D3D12Defines.h #pragma once #define D3D12_PLACED_CONSTANT_BUFFER_ALIGNMENT (65536) // 64KiB #define D3D12_BUFFER_WRITE_SCRATCH_BUFFER_THRESHOLD (1024) // 1KiB #define D3D12_CONSTANT_BUFFER_ALIGNMENT (256) // 256B #define D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS (4) #define D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS (8) #define D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS (8) #define D3D12_LEGACY_GRAPHICS_ROOT_PER_DRAW_CONSTANT_BUFFER_SLOTS (1) // Since map read/write ranges breaks the hell out of the debugger, this lets us compile it out #ifdef Y_BUILD_CONFIG_DEBUG #define D3D12_MAP_RANGE_PARAM(value) nullptr #else #define D3D12_MAP_RANGE_PARAM(value) value #endif namespace NameTables { // This nametable is actually located in the D3D11 library. Y_Declare_NameTable(D3DFeatureLevels); }<file_sep>/Editor/Source/Editor/EditorPropertyEditorDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorPropertyEditorDialog.h" #include "Editor/Editor.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "Editor/EditorHelpers.h" #include "ResourceCompiler/ObjectTemplate.h" #include "MapCompiler/MapSource.h" EditorPropertyEditorDialog::EditorPropertyEditorDialog(QWidget *pParent) : QDialog(pParent, Qt::WindowStaysOnTopHint | Qt::Tool), m_pPropertyEditor(new EditorPropertyEditorWidget(this)), m_pAttachedMap(nullptr), m_pAttachedEntity(nullptr), m_pAttachedTemplate(nullptr), m_pAttachedTable(nullptr) { m_pPropertyEditor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_pPropertyEditor->setMinimumSize(300, 500); QVBoxLayout *verticalLayout = new QVBoxLayout(this); verticalLayout->setContentsMargins(2, 2, 2, 2); verticalLayout->addWidget(m_pPropertyEditor, 1); setLayout(verticalLayout); } EditorPropertyEditorDialog::~EditorPropertyEditorDialog() { } void EditorPropertyEditorDialog::PopulateForEntity(EditorMap *pMap, EditorMapEntity *pEntity) { m_pAttachedMap = pMap; m_pAttachedEntity = pEntity; // build the title text LargeString titleText; titleText.AppendFormattedString("<strong>%s</strong>&nbsp;(%s)<br>", pEntity->GetEntityData()->GetEntityName().GetCharArray(), pEntity->GetTemplate()->GetTypeName().GetCharArray()); titleText.AppendString(pEntity->GetTemplate()->GetDescription()); //m_pPropertyEditor->SetTitleText(titleText); // add properties and values const ObjectTemplate *pTemplate = pEntity->GetTemplate(); for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pProperty = pTemplate->GetPropertyDefinition(i); const String *propertyValue = pEntity->GetEntityData()->GetPropertyValuePointer(pProperty->GetName()); if (propertyValue == nullptr) propertyValue = &pProperty->GetDefaultValue(); m_pPropertyEditor->AddProperty(pProperty, *propertyValue); } } void EditorPropertyEditorDialog::PopulateForTemplate(const PropertyTemplate *pTemplate) { } void EditorPropertyEditorDialog::PopulateForTable(const PropertyTemplate *pTemplate, PropertyTable *pTable) { for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pProperty = pTemplate->GetPropertyDefinition(i); m_pPropertyEditor->AddProperty(pProperty, pTable->GetPropertyValueDefaultString(pProperty->GetName(), pProperty->GetDefaultValue())); } m_pAttachedTemplate = pTemplate; m_pAttachedTable = pTable; } <file_sep>/Engine/Source/Engine/Physics/ScaledTriangleMeshCollisionShape.h #pragma once #include "Engine/Physics/TriangleMeshCollisionShape.h" class btBvhTriangleMeshShape; class btScaledBvhTriangleMeshShape; namespace Physics { class ScaledTriangleMeshCollisionShape : public CollisionShape { public: ScaledTriangleMeshCollisionShape(const TriangleMeshCollisionShape *pParentShape, const float3 &scale); virtual ~ScaledTriangleMeshCollisionShape(); // Virtual methods virtual const COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: AABox m_Bounds; const TriangleMeshCollisionShape *m_pParentShape; float3 m_scale; btBvhTriangleMeshShape *m_pTriangleMeshShape; btScaledBvhTriangleMeshShape *m_pScaledTriangleMeshShape; }; } // namespace Physics <file_sep>/Engine/Source/ResourceCompiler/ObjectTemplate.h #pragma once #include "ResourceCompiler/Common.h" #include "Core/PropertyTemplate.h" class ByteStream; // this class mirrors EditorEntityDefinition, without a lot of the extra editor-specific stuff class ObjectTemplate { public: ObjectTemplate(); ~ObjectTemplate(); const String &GetTypeName() const { return m_typeName; } const String &GetDisplayName() const { return m_displayName; } const String &GetCategoryName() const { return m_categoryName; } const String &GetDescription() const { return m_description; } const ObjectTemplate *GetBaseClassTemplate() const { return m_pBaseClassTemplate; } const bool CanCreate() const { return m_canCreate; } const PropertyTemplate *GetPropertyTemplate() const { return &m_propertyTableTemplate; } const PropertyTemplateProperty *GetPropertyDefinition(uint32 i) const { return m_propertyTableTemplate.GetPropertyDefinition(i); } const PropertyTemplateProperty *GetPropertyDefinitionByName(const char *propertyName) const { return m_propertyTableTemplate.GetPropertyDefinitionByName(propertyName); } const uint32 GetPropertyDefinitionCount() const { return m_propertyTableTemplate.GetPropertyDefinitionCount(); } bool LoadFromStream(const char *FileName, ByteStream *pStream); // inheritance helper bool IsDerivedFrom(const ObjectTemplate *pTemplate) const; private: String m_typeName; String m_displayName; String m_categoryName; String m_description; const ObjectTemplate *m_pBaseClassTemplate; bool m_canCreate; PropertyTemplate m_propertyTableTemplate; }; <file_sep>/Engine/Source/BaseGame/GameEntity.h #pragma once #include "BaseGame/Common.h" #include "Engine/Entity.h" class GameEntity : public Entity { DECLARE_ENTITY_TYPEINFO(GameEntity, Entity); DECLARE_ENTITY_NO_FACTORY(Entity); public: GameEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~GameEntity(); const bool IsVisible() const { return m_visible; } void SetVisible(bool visible); const float GetOpacity() const { return m_opacity; } void SetOpacity(float opacity); const bool IsTinted() const { return (m_tintColor != 0xFFFFFFFF); } const uint32 GetTintColor() const { return m_tintColor; } void SetTintColor(uint32 tintColor); void FadeIn(float duration = 1.0f); void FadeOut(float duration = 1.0f); virtual void Update(float timeSinceLastUpdate); protected: // callbacks virtual void OnVisibilityChanged(); virtual void OnOpacityChanged(); virtual void OnTintColorChanged(); // rendering variables bool m_visible; float m_opacity; uint32 m_tintColor; private: // fade in/out float m_fadeDuration; float m_fadeStartValue; float m_fadeTimeRemaining; private: // hidden trampolines for property system static void __PS_OnVisibilityChanged(GameEntity *pThis, const void *pUserData) { pThis->OnVisibilityChanged(); } static void __PS_OnOpacityChanged(GameEntity *pThis, const void *pUserData) { pThis->OnOpacityChanged(); } static void __PS_OnTintColorChanged(GameEntity *pThis, const void *pUserData) { pThis->OnTintColorChanged(); } }; <file_sep>/Engine/Source/GameFramework/StaticMeshRigidBodyEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/StaticMeshRigidBodyEntity.h" #include "Engine/StaticMesh.h" #include "Engine/World.h" #include "Engine/Physics/RigidBody.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/ResourceManager.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderWorld.h" Log_SetChannel(StaticMeshRigidBodyEntity); DEFINE_ENTITY_TYPEINFO(StaticMeshRigidBodyEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(StaticMeshRigidBodyEntity); BEGIN_ENTITY_PROPERTIES(StaticMeshRigidBodyEntity) PROPERTY_TABLE_MEMBER("StaticMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetStaticMesh, NULL, PropertyCallbackSetStaticMesh, NULL, NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(StaticMeshRigidBodyEntity, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(StaticMeshRigidBodyEntity, m_shadowFlags), NULL, NULL) PROPERTY_TABLE_MEMBER_FLOAT("Mass", 0, offsetof(StaticMeshRigidBodyEntity, m_mass), PropertyCallbackMassChanged, NULL) PROPERTY_TABLE_MEMBER_FLOAT("Friction", 0, offsetof(StaticMeshRigidBodyEntity, m_friction), PropertyCallbackMassChanged, NULL) PROPERTY_TABLE_MEMBER_FLOAT("RollingFriction", 0, offsetof(StaticMeshRigidBodyEntity, m_rollingFriction), PropertyCallbackMassChanged, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(StaticMeshRigidBodyEntity) END_ENTITY_SCRIPT_FUNCTIONS() StaticMeshRigidBodyEntity::StaticMeshRigidBodyEntity(const EntityTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo), m_visible(true), m_pStaticMesh(nullptr), m_shadowFlags(0), m_mass(1.0f), m_friction(0.5f), m_rollingFriction(1.0f), m_pRigidBody(nullptr), m_pRenderProxy(nullptr) { // force mobility to movable m_mobility = ENTITY_MOBILITY_MOVABLE; } StaticMeshRigidBodyEntity::~StaticMeshRigidBodyEntity() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pRigidBody != nullptr) m_pRigidBody->Release(); m_pStaticMesh->Release(); } void StaticMeshRigidBodyEntity::Create(uint32 entityID, const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const StaticMesh *pStaticMesh /* = nullptr */, bool visible /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */, float mass /* = 1.0f */, float friction /* = 0.5f */, float rollingFriction /* = 1.0f */) { m_transform.Set(position, rotation, scale); if ((m_pStaticMesh = pStaticMesh) != nullptr) m_pStaticMesh->AddRef(); else m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); m_shadowFlags = shadowFlags; m_mass = mass; m_friction = friction; m_rollingFriction = rollingFriction; Initialize(entityID, EmptyString); } bool StaticMeshRigidBodyEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; if (m_pStaticMesh == nullptr) m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); UpdateRenderProxy(); UpdateCollisionObject(); m_boundingBox = m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()); m_boundingSphere = m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()); return true; } void StaticMeshRigidBodyEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pRigidBody != NULL) pWorld->GetPhysicsWorld()->AddObject(m_pRigidBody); if (m_pRenderProxy != NULL) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void StaticMeshRigidBodyEntity::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != NULL) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pRigidBody != NULL) pWorld->GetPhysicsWorld()->RemoveObject(m_pRigidBody); BaseClass::OnRemoveFromWorld(pWorld); } void StaticMeshRigidBodyEntity::OnTransformChange() { BaseClass::OnTransformChange(); if (m_pRigidBody != NULL && m_pRigidBody->GetTransform() != GetTransform()) m_pRigidBody->SetTransform(GetTransform()); if (m_pRenderProxy != NULL) m_pRenderProxy->SetTransform(GetTransform()); // call entity set bounds with the transformed bounds, this will merge with components (if any) Entity::SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshRigidBodyEntity::OnComponentBoundsChange() { // call entity set bounds with the transformed bounds, this will merge with components (if any) Entity::SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshRigidBodyEntity::SetStaticMesh(const StaticMesh *pStaticMesh) { if (m_pStaticMesh == pStaticMesh) return; if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); UpdateCollisionObject(); UpdateRenderProxy(); SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshRigidBodyEntity::SetShadowFlags(uint32 shadowFlags) { m_shadowFlags = shadowFlags; if (m_pRenderProxy != NULL) m_pRenderProxy->SetShadowFlags(shadowFlags); } void StaticMeshRigidBodyEntity::UpdateCollisionObject() { if (m_pStaticMesh->GetCollisionShape() != NULL) { // if does not have collision object and new mesh does if (m_pRigidBody == NULL) { m_pRigidBody = new Physics::RigidBody(m_entityID, m_pStaticMesh->GetCollisionShape(), GetTransform()); m_pRigidBody->SetMass(m_mass); m_pRigidBody->SetFriction(m_friction); m_pRigidBody->SetRollingFriction(m_rollingFriction); m_pRigidBody->SetCallbackFunction(reinterpret_cast<Physics::RigidBody::UpdateTransformCallbackFunction>(&StaticMeshRigidBodyEntity::PhysicsCallbackTransformChanged), reinterpret_cast<void *>(this)); if (IsInWorld()) m_pWorld->GetPhysicsWorld()->AddObject(m_pRigidBody); } // has one already, just update it else { m_pRigidBody->SetCollisionShape(m_pStaticMesh->GetCollisionShape()); } } else { // if has collision object and new mesh does not if (m_pRigidBody != NULL) { if (IsInWorld()) m_pWorld->GetPhysicsWorld()->RemoveObject(m_pRigidBody); m_pRigidBody->Release(); m_pRigidBody = NULL; } } } void StaticMeshRigidBodyEntity::UpdateRenderProxy() { if (m_pRenderProxy != NULL) { m_pRenderProxy->SetStaticMesh(m_pStaticMesh); } else { m_pRenderProxy = new StaticMeshRenderProxy(GetEntityID(), m_pStaticMesh, GetTransform(), m_shadowFlags); m_pRenderProxy->SetShadowFlags(m_shadowFlags); } } bool StaticMeshRigidBodyEntity::PropertyCallbackGetStaticMesh(ThisClass *pEntity, const void *pUserData, String *pValue) { pValue->Assign(pEntity->m_pStaticMesh->GetName()); return true; } bool StaticMeshRigidBodyEntity::PropertyCallbackSetStaticMesh(ThisClass *pEntity, const void *pUserData, const String *pValue) { const StaticMesh *pStaticMesh = g_pResourceManager->GetStaticMesh(*pValue); if (pStaticMesh == NULL) return false; if (pEntity->m_pStaticMesh != nullptr) pEntity->m_pStaticMesh->Release(); pEntity->m_pStaticMesh = pStaticMesh; pEntity->m_pStaticMesh->AddRef(); return true; } void StaticMeshRigidBodyEntity::PropertyCallbackStaticMeshChanged(ThisClass *pEntity, const void *pUserData) { pEntity->UpdateCollisionObject(); pEntity->UpdateRenderProxy(); pEntity->SetBounds(pEntity->m_transform.TransformBoundingBox(pEntity->m_pStaticMesh->GetBoundingBox()), pEntity->m_transform.TransformBoundingSphere(pEntity->m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshRigidBodyEntity::PropertyCallbackEnableCollisionChanged(ThisClass *pEntity, const void *pUserData) { pEntity->UpdateCollisionObject(); } void StaticMeshRigidBodyEntity::PropertyCallbackMassChanged(ThisClass *pEntity, const void *pUserData) { if (pEntity->m_pRigidBody != nullptr) pEntity->m_pRigidBody->SetMass(pEntity->m_mass); } void StaticMeshRigidBodyEntity::PropertyCallbackFrictionChanged(ThisClass *pEntity, const void *pUserData) { if (pEntity->m_pRigidBody != nullptr) pEntity->m_pRigidBody->SetMass(pEntity->m_friction); } void StaticMeshRigidBodyEntity::PropertyCallbackRollingFrictionChanged(ThisClass *pEntity, const void *pUserData) { if (pEntity->m_pRigidBody != nullptr) pEntity->m_pRigidBody->SetMass(pEntity->m_rollingFriction); } void StaticMeshRigidBodyEntity::SetMass(float mass) { m_mass = mass; if (m_pRigidBody != NULL) m_pRigidBody->SetMass(mass); } void StaticMeshRigidBodyEntity::SetFriction(float friction) { m_friction = friction; if (m_pRigidBody != NULL) m_pRigidBody->SetFriction(friction); } void StaticMeshRigidBodyEntity::SetRollingFriction(float rollingFriction) { m_rollingFriction = rollingFriction; if (m_pRigidBody != NULL) m_pRigidBody->SetRollingFriction(rollingFriction); } void StaticMeshRigidBodyEntity::ApplyCentralImpulse(const float3 &direction) { if (m_pRigidBody != NULL) m_pRigidBody->ApplyCentralImpulse(direction); } void StaticMeshRigidBodyEntity::PhysicsCallbackTransformChanged(ThisClass *pEntity, const Transform &physicsTransform) { //Log_DevPrintf("pos update %s", StringConverter::Float3ToString(physicsTransform.GetPosition()).GetCharArray()); //pEntity->SetTransform(physicsTransform); // manually implemented as to not re-call the rigid body pEntity->m_transform = physicsTransform; pEntity->BaseClass::OnTransformChange(); if (pEntity->m_pRenderProxy != nullptr) pEntity->m_pRenderProxy->SetTransform(physicsTransform); pEntity->SetBounds(physicsTransform.TransformBoundingBox(pEntity->m_pStaticMesh->GetBoundingBox()), physicsTransform.TransformBoundingSphere(pEntity->m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshRigidBodyEntity::ResetForces() { if (m_pRigidBody != nullptr) m_pRigidBody->ResetForces(); } void StaticMeshRigidBodyEntity::ResetVelocity() { if (m_pRigidBody != nullptr) m_pRigidBody->ResetVelocity(); } void StaticMeshRigidBodyEntity::ResetForcesAndVelocity() { if (m_pRigidBody != nullptr) { m_pRigidBody->ResetForces(); m_pRigidBody->ResetVelocity(); } } <file_sep>/DemoGame/Source/DemoGame/BaseDemoGameState.h #pragma once #include "DemoGame/DemoGame.h" #include "DemoGame/DemoCamera.h" #include "BaseGame/GameState.h" class BaseDemoGameState : public GameState { public: BaseDemoGameState(DemoGame *pDemoGame); virtual ~BaseDemoGameState(); // initialization virtual bool Initialize(); // shutdown virtual void Shutdown(); // public events virtual bool CreateGPUResources(); virtual void ReleaseGPUResources(); protected: virtual void DrawOverlays(float deltaTime); virtual void DrawUI(float deltaTime); virtual void OnUIToggled(bool enabled); // implemented events virtual void OnSwitchedIn() override; virtual void OnSwitchedOut() override; virtual void OnBeforeDelete() override; virtual void OnWindowResized(uint32 width, uint32 height) override; virtual void OnWindowFocusGained() override; virtual void OnWindowFocusLost() override; virtual bool OnWindowEvent(const union SDL_Event *event) override; virtual void OnMainThreadPreFrame(float deltaTime) override; virtual void OnMainThreadBeginFrame(float deltaTime) override; virtual void OnMainThreadAsyncTick(float deltaTime) override; virtual void OnMainThreadTick(float deltaTime) override; virtual void OnMainThreadEndFrame(float deltaTime) override; virtual void OnRenderThreadPreFrame(float deltaTime) override; virtual void OnRenderThreadBeginFrame(float deltaTime) override; virtual void OnRenderThreadDraw(float deltaTime) override; virtual void OnRenderThreadEndFrame(float deltaTime) override; protected: DemoGame *m_pDemoGame; // hide the ui and enable camera movement void ToggleUI(); // ui active (owned by main thread) bool m_uiActive; }; <file_sep>/Engine/Source/BlockEngine/BlockWorldMesher.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldMesher.h" #include "BlockEngine/BlockWorldVertexFactory.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" #include "Core/MeshUtilties.h" //Log_SetChannel(BlockMeshBuilder); static const float CUBE_FACE_TANGENTS[CUBE_FACE_COUNT][3] = { { 0, -1, 0 }, // RIGHT { 0, -1, 0 }, // LEFT { 1, 0, 0 }, // BACK { 1, 0, 0 }, // FRONT { 1, 0, 0 }, // TOP { 1, 0, 0 }, // BOTTOM }; static const float CUBE_FACE_BINORMALS[CUBE_FACE_COUNT][3] = { { 0, 0, -1 }, // RIGHT { 0, 0, -1 }, // LEFT { 0, 0, -1 }, // BACK { 0, 0, -1 }, // FRONT { 0, -1, 0 }, // TOP { 0, -1, 0 }, // BOTTOM }; static const float CUBE_FACE_NORMALS[CUBE_FACE_COUNT][3] = { { 1, 0, 0 }, // RIGHT { -1, 0, 0 }, // LEFT { 0, 1, 0 }, // BACK { 0, -1, 0 }, // FRONT { 0, 0, 1 }, // TOP { 0, 0, -1 }, // BOTTOM }; static const uint32 CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_COUNT][2] = { // TANGENT NORMAL { 0x7F008100, 0x0000007F }, // RIGHT { 0x81008100, 0x00000081 }, // LEFT { 0x7F00007F, 0x00007F00 }, // BACK { 0x8100007F, 0x00008100 }, // FRONT { 0x8100007F, 0x007F0000 }, // TOP { 0x7F00007F, 0x00810000 } // BOTTOM }; // rotate the cube faces according to block rotation // this doesn't work for uvs.. maybe we need some uv transform matrix? static const CUBE_FACE CUBE_FACE_ROTATION_LUT[NUM_BLOCK_WORLD_BLOCK_ROTATIONS][CUBE_FACE_COUNT] = { // Right Left Back Front Top Bottom { CUBE_FACE_RIGHT, CUBE_FACE_LEFT, CUBE_FACE_BACK, CUBE_FACE_FRONT, CUBE_FACE_TOP, CUBE_FACE_BOTTOM }, // North { CUBE_FACE_FRONT, CUBE_FACE_BACK, CUBE_FACE_RIGHT, CUBE_FACE_LEFT, CUBE_FACE_TOP, CUBE_FACE_BOTTOM }, // East { CUBE_FACE_LEFT, CUBE_FACE_RIGHT, CUBE_FACE_FRONT, CUBE_FACE_BACK, CUBE_FACE_TOP, CUBE_FACE_BOTTOM }, // South { CUBE_FACE_BACK, CUBE_FACE_FRONT, CUBE_FACE_LEFT, CUBE_FACE_RIGHT, CUBE_FACE_TOP, CUBE_FACE_BOTTOM }, // West }; static const float BLOCK_ROTATION_MATRIX_LUT[NUM_BLOCK_WORLD_BLOCK_ROTATIONS][4][4] = { { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }, // North //{ { 1.19249e-008f, 1.0f, 0.0f, 0.0f }, { -1.0f, 1.19249e-008f, 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f, 0.0f } }, // East //{ { -1.0f, 8.74228e-008f, 0.0f, 1.0f }, { -8.74228e-008f, -1.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f, 0.0f } }, // South //{ { -4.37114e-008f, -1.0f, 0.0f, 1.0f }, { 1.0f, -4.37114e-008f, 0.0f, 2.98023e-008f }, { 0.0f, 0.0f, 1.0f, 0.0f } } // West { { 0.000000f, 1.000000f, 0.000000f, 0.000000f }, { -1.000000f, 0.000000f, 0.000000f, 1.000000f }, { 0.000000f, 0.000000f, 1.000000f, 0.000000f } }, // East { { -1.000000f, 0.000000f, 0.000000f, 1.000000f }, { -0.000000f, -1.000000f, 0.000000f, 1.000000f }, { 0.000000f, 0.000000f, 1.000000f, 0.000000f } }, // South { { -0.000000f, -1.000000f, 0.000000f, 1.000000f }, { 1.000000f, -0.000000f, 0.000000f, 0.000000f }, { 0.000000f, 0.000000f, 1.000000f, 0.000000f } } }; BlockWorldMesher::BlockWorldMesher(const BlockPalette *pPalette, uint32 chunkSize, uint32 lodLevel, const float3 &basePosition, bool generateLightMaps) : m_pPalette(pPalette), m_chunkSize(chunkSize), m_lodLevel(lodLevel), m_basePosition(basePosition), m_generateLightMaps(generateLightMaps) { m_pBlockValues = new BlockWorldBlockType[chunkSize * chunkSize * chunkSize]; m_pBlockData = new BlockWorldBlockDataType[chunkSize * chunkSize * chunkSize]; m_pBlockFaceMasks = new uint8[chunkSize * chunkSize * chunkSize]; Y_memzero(m_pBlockFaceMasks, sizeof(uint8) * chunkSize * chunkSize * chunkSize); m_output.BoundingBox = AABox::Zero; m_output.BoundingSphere = Sphere::Zero; } BlockWorldMesher::~BlockWorldMesher() { for (MeshInstances *pMeshInstances : m_output.Instances) delete pMeshInstances; delete[] m_pBlockFaceMasks; delete[] m_pBlockData; delete[] m_pBlockValues; } const BlockWorldBlockType BlockWorldMesher::GetBlockValueAt(uint32 x, uint32 y, uint32 z) const { DebugAssert(x < m_chunkSize && y < m_chunkSize && z < m_chunkSize); return m_pBlockValues[(z * m_chunkSize * m_chunkSize) + (y * m_chunkSize) + x]; } const bool BlockWorldMesher::IsVisibleBlockAt(uint32 x, uint32 y, uint32 z) const { BlockWorldBlockType blockTypeId = GetBlockValueAt(x, y, z); const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockTypeId); return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) != 0; } const bool BlockWorldMesher::IsVisibleNonTransparentBlockAt(uint32 x, uint32 y, uint32 z) const { BlockWorldBlockType blockTypeId = GetBlockValueAt(x, y, z); const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockTypeId); return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE && !(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE)); } const bool BlockWorldMesher::HasCubeLightBlockingBlockAt(uint32 x, uint32 y, uint32 z) const { BlockWorldBlockType blockValue = GetBlockValueAt(x, y, z); if (blockValue == 0) return false; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE) != 0; } const bool BlockWorldMesher::CalculateBlockFaceVisibility(uint32 x, uint32 y, uint32 z, BlockWorldBlockType blockValue, CUBE_FACE face) const { BlockWorldBlockType neighbourBlockValue; switch (face) { case CUBE_FACE_RIGHT: neighbourBlockValue = GetBlockValueAt(x + 1, y, z); break; case CUBE_FACE_LEFT: neighbourBlockValue = GetBlockValueAt(x - 1, y, z); break; case CUBE_FACE_BACK: neighbourBlockValue = GetBlockValueAt(x, y + 1, z); break; case CUBE_FACE_FRONT: neighbourBlockValue = GetBlockValueAt(x, y - 1, z); break; case CUBE_FACE_TOP: neighbourBlockValue = GetBlockValueAt(x, y, z + 1); break; case CUBE_FACE_BOTTOM: neighbourBlockValue = GetBlockValueAt(x, y, z - 1); break; default: neighbourBlockValue = 0; break; } // fastpath for air if (neighbourBlockValue == 0) return true; // coloured blocks are always blocking if (neighbourBlockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) return false; // lookup block type const BlockPalette::BlockType *pNeighbourBlockType = m_pPalette->GetBlockType(neighbourBlockValue); switch (pNeighbourBlockType->ShapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE: { // check for volume blocks here if ((pNeighbourBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) && neighbourBlockValue == blockValue) return false; // transparent blocks can't block visibility, not entirely anyway return !(pNeighbourBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY); } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB: { // check for volume blocks here if ((pNeighbourBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) && neighbourBlockValue == blockValue) return false; // slabs only block on the bottom face (our top face) if (face == CUBE_FACE_TOP) return !(pNeighbourBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY); // all other cases they don't block return true; } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS: { // stairs only block the bottom and back faces which is our top and front faces if (face == CUBE_FACE_TOP || face == CUBE_FACE_FRONT) return !(pNeighbourBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) ; // everything else has to be generated return true; } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH: { // meshes have an unknown shape, therefore they cannot block return true; } break; default: { // everything else.. well there shouldn't be anything else return true; } break; } } const uint32 BlockWorldMesher::CalculateCubeVertexColor(const BlockPalette::BlockType *pBlockType, CUBE_FACE faceIndex, const uint32 blockValue, const uint32 blockLighting) { #if 0 Vector4 outVertexColor; // are we using a typed block? uint32 faceColor; if (pBlockType != nullptr) faceColor = pBlockType->CubeShapeFaces[faceIndex].Visual.Color; else faceColor = MAKE_COLOR_R8G8B8A8_UNORM(((blockValue >> 10) & 0x1F) * 8, ((blockValue >> 5) & 0x1F) * 8, ((blockValue)& 0x1F) * 8, (blockValue & 0x8000) ? 255 : 0); // 1555 to 8888, fixme // start by taking the face colour outVertexColor = Vector4(float(faceColor & 0xFF), float((faceColor >> 8) & 0xFF), float((faceColor >> 16) & 0xFF), float((faceColor >> 24) & 0xFF)) / 255.0f; // factor in block lighting outVertexColor *= Vector4(Vector3((float)blockLighting / 16.0f) /** 0.5f + 0.5f*/, 1.0f); // return vertex colour { uint8 r, g, b, a; r = (uint8)Math::Clamp(outVertexColor.r * 255.0f, 0.0f, 255.0f); g = (uint8)Math::Clamp(outVertexColor.g * 255.0f, 0.0f, 255.0f); b = (uint8)Math::Clamp(outVertexColor.b * 255.0f, 0.0f, 255.0f); a = (uint8)Math::Clamp(outVertexColor.a * 255.0f, 0.0f, 255.0f); return MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a); } #else // are we using a typed block? uint32 faceColor; if (pBlockType != nullptr) faceColor = pBlockType->CubeShapeFaces[faceIndex].Visual.Color; else faceColor = MAKE_COLOR_R8G8B8A8_UNORM(((blockValue >> 10) & 0x1F) * 8, ((blockValue >> 5) & 0x1F) * 8, ((blockValue)& 0x1F) * 8, 0); // 1555 to 8888, fixme return (faceColor & 0x00FFFFFF) | ((blockLighting * 10) << 24); #endif } const uint32 BlockWorldMesher::CalculatePlaneVertexColor(const BlockPalette::BlockType *pBlockType, const uint32 blockValue, const uint32 blockLighting) { // are we using a typed block? uint32 faceColor; if (pBlockType != nullptr) faceColor = pBlockType->PlaneShapeSettings.Visual.Color; else faceColor = MAKE_COLOR_R8G8B8A8_UNORM(((blockValue >> 10) & 0x1F) * 8, ((blockValue >> 5) & 0x1F) * 8, ((blockValue)& 0x1F) * 8, 0); // 1555 to 8888, fixme return (faceColor & 0x00FFFFFF) | ((blockLighting * 10) << 24); } #define BLOCK_VALUE_ARRAY_ACCESS(x, y, z) m_pBlockValues[(z) * zStride + (y) * yStride + (x)] #define BLOCK_DATA_ARRAY_ACCESS(x, y, z) m_pBlockData[(z) * zStride + (y) * yStride + (x)] #define BLOCK_FACEMASK_ARRAY_ACCESS(x, y, z) m_pBlockFaceMasks[(z) * zStride + (y) * yStride + (x)] #define BLOCK_WORLD_COORDINATES(x, y, z) (Vector3(static_cast<float>((x - 1) << m_lodLevel), static_cast<float>((y - 1) << m_lodLevel), static_cast<float>((z - 1) << m_lodLevel)) + basePosition) const uint32 BlockWorldMesher::CalculateCubeFaceLighting(uint32 x, uint32 y, uint32 z, CUBE_FACE faceIndex) { if (!m_generateLightMaps) return 15; const uint32 yStride = m_chunkSize; const uint32 zStride = yStride * m_chunkSize; uint8 lightLevel = 0; switch (faceIndex) { case CUBE_FACE_LEFT: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x - 1, y, z); break; case CUBE_FACE_RIGHT: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x + 1, y, z); break; case CUBE_FACE_FRONT: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x, y - 1, z); break; case CUBE_FACE_BACK: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x, y + 1, z); break; case CUBE_FACE_BOTTOM: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x, y, z - 1); break; case CUBE_FACE_TOP: lightLevel = BLOCK_DATA_ARRAY_ACCESS(x, y, z + 1); break; } return (uint32)BLOCK_WORLD_BLOCK_DATA_GET_LIGHTING(lightLevel); } void BlockWorldMesher::GenerateBlocks(uint3 &minBlockCoordinates, uint3 &maxBlockCoordinates) { const uint32 yStride = m_chunkSize; const uint32 zStride = yStride * m_chunkSize; const uint32 volumeSizeMinusOne = m_chunkSize - 1; // fill in face masks for (uint32 z = 1; z < volumeSizeMinusOne; z++) { for (uint32 y = 1; y < volumeSizeMinusOne; y++) { for (uint32 x = 1; x < volumeSizeMinusOne; x++) { // get block type, test for air blocks BlockWorldBlockType blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0) continue; // lookup rotation //uint8 blockRotation = BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(BLOCK_DATA_ARRAY_ACCESS(x, y, z)); //DebugAssert(blockRotation < NUM_BLOCK_WORLD_BLOCK_ROTATIONS); // cull each direction :: todo only need this for cuboid meshes uint8 faceMask = 0; if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_LEFT)) faceMask |= (1 << CUBE_FACE_LEFT); if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_RIGHT)) faceMask |= (1 << CUBE_FACE_RIGHT); if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_FRONT)) faceMask |= (1 << CUBE_FACE_FRONT); if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_BACK)) faceMask |= (1 << CUBE_FACE_BACK); if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_BOTTOM)) faceMask |= (1 << CUBE_FACE_BOTTOM); if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_TOP)) faceMask |= (1 << CUBE_FACE_TOP); // // cull each direction :: todo only need this for cuboid meshes // uint8 faceMask = 0; // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_LEFT])) // faceMask |= (1 << CUBE_FACE_LEFT); // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_RIGHT])) // faceMask |= (1 << CUBE_FACE_RIGHT); // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_FRONT])) // faceMask |= (1 << CUBE_FACE_FRONT); // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_BACK])) // faceMask |= (1 << CUBE_FACE_BACK); // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_BOTTOM])) // faceMask |= (1 << CUBE_FACE_BOTTOM); // if (CalculateBlockFaceVisibility(x, y, z, blockValue, CUBE_FACE_ROTATION_LUT[blockRotation][CUBE_FACE_TOP])) // faceMask |= (1 << CUBE_FACE_TOP); // handle slabs -- always generate their top face if ((blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) == 0) { const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB && (faceMask & (1 << CUBE_FACE_TOP)) == 0) { if (GetBlockValueAt(x, y, z + 1) != blockValue) faceMask |= (1 << CUBE_FACE_TOP); } // handle stairs - their top faces must always be generated unless they're completely hidden else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS && faceMask != 0) faceMask |= (1 << CUBE_FACE_TOP); } // set face mask BLOCK_FACEMASK_ARRAY_ACCESS(x, y, z) = faceMask; } } } // build mesh for (uint32 z = 1; z < volumeSizeMinusOne; z++) { for (uint32 y = 1; y < volumeSizeMinusOne; y++) { for (uint32 x = 1; x < volumeSizeMinusOne; x++) { // get block type, test for air blocks BlockWorldBlockType blockValue = BLOCK_VALUE_ARRAY_ACCESS(x, y, z); if (blockValue == 0) continue; // read data BlockWorldBlockDataType blockData = BLOCK_DATA_ARRAY_ACCESS(x, y, z); uint8 blockFaceMask = BLOCK_FACEMASK_ARRAY_ACCESS(x, y, z); uint8 blockRotation = BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(blockData); DebugAssert(blockRotation < 4); // get the block type, a null blocktype indicates a coloured block const BlockPalette::BlockType *pBlockType; BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType; if ((blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) == 0) { // typed block pBlockType = m_pPalette->GetBlockType(blockValue); shapeType = pBlockType->ShapeType; } else { // coloured block pBlockType = nullptr; shapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE; } // cube-typed blocks can tile if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB)// || shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { // determine if we can tile in the z direction. bool canTileZ = false; if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // all cubes can tile vertically canTileZ = true; } else if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // slabs have two behaviours, depending on if volume bit is set // if volume bit is set, they are generated like cubes, except the very top block // otherwise, they are generated independantly if (pBlockType->Flags & pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) canTileZ = true; } // generate each face for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { uint8 currentFaceMask = (1 << faceIndex); if ((blockFaceMask & currentFaceMask) == 0) continue; // calculate light colour for face uint32 blockLighting = CalculateCubeFaceLighting(x, y, z, (CUBE_FACE)faceIndex); // block rotation swaps the faces here! // match on data instead of just lighting will fix tiling too // determine which axis to sweep int32 sliceAxis = 0, sweepAxis0 = 0, sweepAxis1 = 0; switch (faceIndex) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: sliceAxis = 0; sweepAxis0 = 1; sweepAxis1 = (canTileZ) ? 2 : -1; break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: sliceAxis = 1; sweepAxis0 = 0; sweepAxis1 = (canTileZ) ? 2 : -1; break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: sliceAxis = 2; sweepAxis0 = 1; sweepAxis1 = 0; break; } // hack for stairs since their rotation is dependant on which ways can tile @todo if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) sweepAxis0 = sweepAxis1 = -1; // determine the quad boundaries by sweeping each axis, then in reverse uint32 baseCoordinates[3]; uint32 blockCoordinates[3]; uint32 quadBoundaries[2][3]; uint32 i, j, k; // base baseCoordinates[0] = x; baseCoordinates[1] = y; baseCoordinates[2] = z; Y_memcpy(&quadBoundaries[0], baseCoordinates, sizeof(quadBoundaries[0])); Y_memcpy(&quadBoundaries[1], baseCoordinates, sizeof(quadBoundaries[1])); // set slice axis blockCoordinates[sliceAxis] = baseCoordinates[sliceAxis]; // forward... if (sweepAxis0 >= 0 && sweepAxis1 >= 0) { { // axis 0 for (i = quadBoundaries[0][sweepAxis0] + 1; i < volumeSizeMinusOne; i++) { blockCoordinates[sweepAxis0] = i; blockCoordinates[sweepAxis1] = baseCoordinates[sweepAxis1]; uint32 searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); uint8 searchBlockRotation = BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2])); uint8 searchFaceMask = BLOCK_FACEMASK_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if (searchBlockValue == blockValue && (searchFaceMask & currentFaceMask) && searchBlockRotation == blockRotation && CalculateCubeFaceLighting(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2], (CUBE_FACE)faceIndex) == blockLighting) { quadBoundaries[1][sweepAxis0]++; continue; } else { break; } } } // axis 1 { for (i = quadBoundaries[0][sweepAxis1] + 1; i < volumeSizeMinusOne; i++) { blockCoordinates[sweepAxis1] = i; // has to match everything on axis 0 bool merge = true; for (j = quadBoundaries[0][sweepAxis0]; j <= quadBoundaries[1][sweepAxis0]; j++) { blockCoordinates[sweepAxis0] = j; uint32 searchBlockValue = BLOCK_VALUE_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); uint8 searchBlockRotation = BLOCK_WORLD_BLOCK_DATA_GET_ROTATION(BLOCK_DATA_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2])); uint8 searchFaceMask = BLOCK_FACEMASK_ARRAY_ACCESS(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2]); if (searchBlockValue == blockValue && (searchFaceMask & currentFaceMask) && searchBlockRotation == blockRotation && CalculateCubeFaceLighting(blockCoordinates[0], blockCoordinates[1], blockCoordinates[2], (CUBE_FACE)faceIndex) == blockLighting) { continue; } else { merge = false; break; } } // ok? if (merge) quadBoundaries[1][sweepAxis1]++; else break; } } } // mark all the faces as generated for (i = quadBoundaries[0][2]; i <= quadBoundaries[1][2]; i++) { for (j = quadBoundaries[0][1]; j <= quadBoundaries[1][1]; j++) { for (k = quadBoundaries[0][0]; k <= quadBoundaries[1][0]; k++) { // mark as allocated BLOCK_FACEMASK_ARRAY_ACCESS(k, j, i) &= ~currentFaceMask; } } } // update the cached data too blockFaceMask &= ~currentFaceMask; // generate meshes switch (shapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE: AddCubeBlockFace(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, quadBoundaries[0][0] - 1, quadBoundaries[0][1] - 1, quadBoundaries[0][2] - 1, quadBoundaries[1][0] - 1, quadBoundaries[1][1] - 1, quadBoundaries[1][2] - 1, (CUBE_FACE)faceIndex, m_output); break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB: AddSlabBlockFace(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, quadBoundaries[0][0] - 1, quadBoundaries[0][1] - 1, quadBoundaries[0][2] - 1, quadBoundaries[1][0] - 1, quadBoundaries[1][1] - 1, quadBoundaries[1][2] - 1, (CUBE_FACE)faceIndex, (GetBlockValueAt(quadBoundaries[1][0], quadBoundaries[1][1], quadBoundaries[1][2] + 1) != blockValue), m_output); break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS: AddStairBlockFace(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, quadBoundaries[0][0] - 1, quadBoundaries[0][1] - 1, quadBoundaries[0][2] - 1, quadBoundaries[1][0] - 1, quadBoundaries[1][1] - 1, quadBoundaries[1][2] - 1, (CUBE_FACE)faceIndex, m_output); break; } } } else if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { // stair's don't tile at the moment, so just treat them separately for now for (uint32 faceIndex = 0; faceIndex < CUBE_FACE_COUNT; faceIndex++) { //uint8 currentFaceMask = (1 << CUBE_FACE_ROTATION_LUT[blockRotation][faceIndex]); //if ((blockFaceMask & currentFaceMask) == 0) //continue; // calculate light colour for face uint32 blockLighting = CalculateCubeFaceLighting(x, y, z, (CUBE_FACE)faceIndex); // update the cached data too //blockFaceMask &= ~currentFaceMask; AddStairBlockFace(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, x - 1, y - 1, z - 1, x - 1, y - 1, z - 1, (CUBE_FACE)faceIndex, m_output); } } else if (shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE || shapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { // cull other shapes that are completely enclosed if (blockFaceMask != 0) { // mark as generated blockFaceMask = 0; BLOCK_FACEMASK_ARRAY_ACCESS(x, y, z) = 0; // calculate light colour for face uint32 blockLighting = CalculateCubeFaceLighting(x, y, z, CUBE_FACE_RIGHT); // generate it switch (shapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE: AddPlaneBlock(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, x - 1, y - 1, z - 1, m_output); break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH: AddMeshBlock(pBlockType, blockValue, blockLighting, blockRotation, m_basePosition, m_lodLevel, x - 1, y - 1, z - 1, m_output); break; } } } // handle point light emitting blocks, currently only at lod0 if (pBlockType != nullptr && (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_POINT_LIGHT_EMITTER) && m_lodLevel == 0) AddLightBlock(pBlockType, m_basePosition, m_lodLevel, x - 1, y - 1, z - 1, m_output); // update block bounds minBlockCoordinates = minBlockCoordinates.Min(uint3(x - 1, y - 1, z - 1)); maxBlockCoordinates = maxBlockCoordinates.Max(uint3(x, y, z)); } } } } #undef BLOCK_VALUE_ARRAY_ACCESS void BlockWorldMesher::GenerateMesh() { // min/max bounds uint3 minBlockCoordinates(Y_UINT32_MAX, Y_UINT32_MAX, Y_UINT32_MAX); uint3 maxBlockCoordinates(0, 0, 0); // generate cube faces GenerateBlocks(minBlockCoordinates, maxBlockCoordinates); // fill bounds if (minBlockCoordinates <= maxBlockCoordinates) { float3 minBounds(float3((float)(minBlockCoordinates.x << m_lodLevel), (float)(minBlockCoordinates.y << m_lodLevel), (float)(minBlockCoordinates.z << m_lodLevel)) + m_basePosition); float3 maxBounds(float3((float)(maxBlockCoordinates.x << m_lodLevel), (float)(maxBlockCoordinates.y << m_lodLevel), (float)(maxBlockCoordinates.z << m_lodLevel)) + m_basePosition); m_output.BoundingBox.SetBounds(minBounds, maxBounds); m_output.BoundingSphere = Sphere::FromAABox(m_output.BoundingBox); } // re-order triangles OptimizeTriangleOrder(m_output); // generate batches GenerateBatches(m_output); } static int TriangleOrderSortFunction(const BlockWorldMesher::Triangle *pLeft, const BlockWorldMesher::Triangle *pRight) { // sort by material index first if (pLeft->MaterialIndex > pRight->MaterialIndex) return 1; else if (pLeft->MaterialIndex < pRight->MaterialIndex) return -1; // then by triangle indices for better use of the cache if (pLeft->Indices[0] > pRight->Indices[0]) return 1; else if (pLeft->Indices[0] < pRight->Indices[0]) return -1; if (pLeft->Indices[1] > pRight->Indices[1]) return 1; else if (pLeft->Indices[1] < pRight->Indices[1]) return -1; if (pLeft->Indices[2] > pRight->Indices[2]) return 1; else if (pLeft->Indices[2] < pRight->Indices[2]) return -1; return 0; } void BlockWorldMesher::OptimizeTriangleOrder(Output &output) { if (output.Triangles.GetSize() > 0) { /* MeshUtilites::OptimizeIndicesForBatching(reinterpret_cast<byte *>(m_outputTriangles.GetBasePointer()) + offsetof(Triangle, Indices[0]), sizeof(Triangle), reinterpret_cast<byte *>(m_outputTriangles.GetBasePointer()) + offsetof(Triangle, MaterialIndex), sizeof(Triangle), m_outputTriangles.GetSize() * 3); */ // use sort method instead output.Triangles.Sort(TriangleOrderSortFunction); } } void BlockWorldMesher::GenerateBatches(Output &output) { uint32 i; DebugAssert(output.Batches.GetSize() == 0); if (output.Triangles.GetSize() > 0) { const Triangle *pTriangle = output.Triangles.GetBasePointer(); Batch batch; batch.StartIndex = 0; batch.NumIndices = 0; batch.MaterialIndex = pTriangle->MaterialIndex; for (i = 0; i < output.Triangles.GetSize(); i++, pTriangle++) { if (pTriangle->MaterialIndex == batch.MaterialIndex) { batch.NumIndices += 3; } else { DebugAssert(batch.NumIndices > 0); output.Batches.Add(batch); batch.StartIndex = i * 3; batch.NumIndices = 3; batch.MaterialIndex = pTriangle->MaterialIndex; } } if (batch.NumIndices > 0) output.Batches.Add(batch); } } bool BlockWorldMesher::CreateGPUBuffers(const Output &output, VertexBufferBindingArray *pVertexBuffers, GPUBuffer **ppIndexBuffer, GPU_INDEX_FORMAT *pIndexFormat, GPUBuffer **ppInstanceTransformBuffer) { if (!output.Vertices.IsEmpty()) { // create buffer directly from data GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, output.Vertices.GetStorageSizeInBytes()); AutoReleasePtr<GPUBuffer> pVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, output.Vertices.GetBasePointer()); if (pVertexBuffer == nullptr) return false; pVertexBuffers->SetBuffer(0, pVertexBuffer, 0, sizeof(Vertex)); } if (!output.Triangles.IsEmpty()) { // generate indices GPUBuffer *pIndexBuffer; GPU_INDEX_FORMAT indexFormat; if (output.Vertices.GetSize() <= 0xFFFF) { uint16 *pIndices = new uint16[output.Vertices.GetSize() * 3]; for (uint32 i = 0, n = 0; i < output.Triangles.GetSize(); i++) { const Triangle &t = output.Triangles[i]; pIndices[n++] = (uint16)t.Indices[0]; pIndices[n++] = (uint16)t.Indices[1]; pIndices[n++] = (uint16)t.Indices[2]; } GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, sizeof(uint16)* output.Triangles.GetSize() * 3); pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pIndices); indexFormat = GPU_INDEX_FORMAT_UINT16; delete[] pIndices; } else { uint32 *pIndices = new uint32[output.Triangles.GetSize() * 3]; for (uint32 i = 0, n = 0; i < output.Triangles.GetSize(); i++) { const Triangle &t = output.Triangles[i]; pIndices[n++] = t.Indices[0]; pIndices[n++] = t.Indices[1]; pIndices[n++] = t.Indices[2]; } GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, sizeof(uint32)* output.Triangles.GetSize() * 3); pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pIndices); indexFormat = GPU_INDEX_FORMAT_UINT32; delete[] pIndices; } if (pIndexBuffer == nullptr) return false; *ppIndexBuffer = pIndexBuffer; *pIndexFormat = indexFormat; } // add mesh instances if (!output.Instances.IsEmpty()) { // create a merged buffer of all instance transforms MemArray<float3x4> allTransformsArray; for (MeshInstances *pMeshInstances : output.Instances) { pMeshInstances->BufferOffset = allTransformsArray.GetStorageSizeInBytes(); allTransformsArray.AddArray(pMeshInstances->Transforms); } // create on gpu GPU_BUFFER_DESC instanceTransformBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, allTransformsArray.GetStorageSizeInBytes()); GPUBuffer *pInstanceTransformBuffer = g_pRenderer->CreateBuffer(&instanceTransformBufferDesc, allTransformsArray.GetBasePointer()); if (pInstanceTransformBuffer == nullptr) return false; *ppInstanceTransformBuffer = pInstanceTransformBuffer; } return true; } bool BlockWorldMesher::MeshSingleBlock(const BlockPalette *pPalette, BlockWorldBlockType blockValue, Output &output) { // get the block type, a null blocktype indicates a coloured block const BlockPalette::BlockType *pBlockType; BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType; if ((blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) == 0) { // typed block pBlockType = pPalette->GetBlockType(blockValue); shapeType = pBlockType->ShapeType; } else { // coloured block pBlockType = nullptr; shapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE; } // generate meshes switch (shapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE: { for (uint32 face = 0; face < CUBE_FACE_COUNT; face++) AddCubeBlockFace(pBlockType, blockValue, 0, 0, float3::Zero, 0, 0, 0, 0, 0, 0, 0, (CUBE_FACE)face, output); } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB: { for (uint32 face = 0; face < CUBE_FACE_COUNT; face++) AddSlabBlockFace(pBlockType, blockValue, 0, 0, float3::Zero, 0, 0, 0, 0, 0, 0, 0, (CUBE_FACE)face, false, output); } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS: { for (uint32 face = 0; face < CUBE_FACE_COUNT; face++) AddStairBlockFace(pBlockType, blockValue, 0, 0, float3::Zero, 0, 0, 0, 0, 0, 0, 0, (CUBE_FACE)face, output); } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE: AddPlaneBlock(pBlockType, blockValue, 0, 0, float3::Zero, 0, 0, 0, 0, output); break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH: AddMeshBlock(pBlockType, blockValue, 0, 0, float3::Zero, 0, 0, 0, 0, output); break; default: // not a recognized shape type return false; } // generate everything OptimizeTriangleOrder(output); GenerateBatches(output); return true; } void BlockWorldMesher::AddCubeBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, Output &output) { // find block counts uint32 blockCountX = (endX - startX) + 1; uint32 blockCountY = (endY - startY) + 1; uint32 blockCountZ = (endZ - startZ) + 1; // get uvs and color uint32 materialIndex; float3 uvTopLeft; float3 uvTopRight; float3 uvBottomRight; float3 uvBottomLeft; // this depends on the face and rotation switch (face) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: case CUBE_FACE_BACK: case CUBE_FACE_FRONT: { // R/L/B/F can just use the reorientated face's uvs const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[CUBE_FACE_ROTATION_LUT[blockRotation][face]]; materialIndex = pFaceDef->Visual.MaterialIndex; uvTopLeft = pFaceDef->Visual.MinUV; uvTopRight.Set(pFaceDef->Visual.MaxUV.x, pFaceDef->Visual.MinUV.y, pFaceDef->Visual.MinUV.z); uvBottomRight = pFaceDef->Visual.MaxUV; uvBottomLeft.Set(pFaceDef->Visual.MinUV.x, pFaceDef->Visual.MaxUV.y, pFaceDef->Visual.MinUV.z); // repeat the texture switch (face) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: uvTopRight.x *= (float)(blockCountY << lodLevel); uvBottomRight.x *= (float)(blockCountY << lodLevel); uvBottomRight.y *= (float)(blockCountZ << lodLevel); uvBottomLeft.y *= (float)(blockCountZ << lodLevel); break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: uvTopRight.x *= (float)(blockCountX << lodLevel); uvBottomRight.x *= (float)(blockCountX << lodLevel); uvBottomRight.y *= (float)(blockCountZ << lodLevel); uvBottomLeft.y *= (float)(blockCountZ << lodLevel); break; } } break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: { // T/B have to have their uvs rotated using the same face const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[face]; materialIndex = pFaceDef->Visual.MaterialIndex; // get the original uvs float3 originalUVs[4]; originalUVs[0] = pFaceDef->Visual.MinUV; originalUVs[1].Set(pFaceDef->Visual.MaxUV.x, pFaceDef->Visual.MinUV.y, pFaceDef->Visual.MinUV.z); originalUVs[2] = pFaceDef->Visual.MaxUV; originalUVs[3].Set(pFaceDef->Visual.MinUV.x, pFaceDef->Visual.MaxUV.y, pFaceDef->Visual.MinUV.z); // repeat the texture switch (blockRotation) { case BLOCK_WORLD_BLOCK_ROTATION_NORTH: case BLOCK_WORLD_BLOCK_ROTATION_SOUTH: originalUVs[1].x *= (float)(blockCountX << lodLevel); originalUVs[2].x *= (float)(blockCountX << lodLevel); originalUVs[2].y *= (float)(blockCountY << lodLevel); originalUVs[3].y *= (float)(blockCountY << lodLevel); break; case BLOCK_WORLD_BLOCK_ROTATION_EAST: case BLOCK_WORLD_BLOCK_ROTATION_WEST: originalUVs[1].x *= (float)(blockCountY << lodLevel); originalUVs[2].x *= (float)(blockCountY << lodLevel); originalUVs[2].y *= (float)(blockCountX << lodLevel); originalUVs[3].y *= (float)(blockCountX << lodLevel); break; } // and reorientate them according to rotation uvTopLeft = originalUVs[(0 + blockRotation) % 4]; uvTopRight = originalUVs[(1 + blockRotation) % 4]; uvBottomRight = originalUVs[(2 + blockRotation) % 4]; uvBottomLeft = originalUVs[(3 + blockRotation) % 4]; } break; default: UnreachableCode(); return; } // macro to generate coordinates #define MAKE_CUBE_VERTEX_POS(x, y, z) ((float3((float)((x) << lodLevel), (float)((y) << lodLevel), (float)((z) << lodLevel))) + basePosition) // generate vertices uint32 baseVertex = output.Vertices.GetSize(); // generate quads switch (face) { case CUBE_FACE_RIGHT: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, endZ + 1), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, endZ + 1), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; case CUBE_FACE_LEFT: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, endZ + 1), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, endZ + 1), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_BACK: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, endZ + 1), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, endZ + 1), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; case CUBE_FACE_FRONT: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, endZ + 1), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, endZ + 1), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_TOP: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, endZ + 1), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, endZ + 1), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, endZ + 1), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, endZ + 1), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_BOTTOM: { output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, endY + 1, startZ), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, endY + 1, startZ), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-right output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(startX, startY, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-left output.Vertices.Emplace(MAKE_CUBE_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; } #undef MAKE_CUBE_VERTEX_POS } void BlockWorldMesher::AddSlabBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, bool isTopSlab, Output &output) { // calculate top slab subtract amount float3 topBlockSubtractAmount(float3::Zero); float sideTopUVAdd = 0.0f; // fix up top slabs of volumes if (!(pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) || isTopSlab) { // bring the side uvs in if (face >= CUBE_FACE_RIGHT && face <= CUBE_FACE_FRONT) sideTopUVAdd = 1.0f - pBlockType->SlabShapeSettings.Height; // adjust the height of the block topBlockSubtractAmount.Set(0.0f, 0.0f, static_cast<float>((uint32)1 << lodLevel) * (1.0f - pBlockType->SlabShapeSettings.Height)); } // find block counts uint32 blockCountX = (endX - startX) + 1; uint32 blockCountY = (endY - startY) + 1; uint32 blockCountZ = (endZ - startZ) + 1; // get uvs and color uint32 materialIndex; float3 uvTopLeft; float3 uvTopRight; float3 uvBottomRight; float3 uvBottomLeft; // this depends on the face and rotation switch (face) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: case CUBE_FACE_BACK: case CUBE_FACE_FRONT: { // R/L/B/F can just use the reorientated face's uvs const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[CUBE_FACE_ROTATION_LUT[blockRotation][face]]; materialIndex = pFaceDef->Visual.MaterialIndex; uvTopLeft.Set(pFaceDef->Visual.MinUV.x, pFaceDef->Visual.MinUV.y - sideTopUVAdd, pFaceDef->Visual.MinUV.z); uvTopRight.Set(pFaceDef->Visual.MaxUV.x, pFaceDef->Visual.MinUV.y - sideTopUVAdd, pFaceDef->Visual.MinUV.z); uvBottomRight = pFaceDef->Visual.MaxUV; uvBottomLeft.Set(pFaceDef->Visual.MinUV.x, pFaceDef->Visual.MaxUV.y, pFaceDef->Visual.MinUV.z); // repeat the texture switch (face) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: uvTopRight.x *= (float)(blockCountY << lodLevel); uvBottomRight.x *= (float)(blockCountY << lodLevel); uvBottomRight.y *= (float)(blockCountZ << lodLevel); uvBottomLeft.y *= (float)(blockCountZ << lodLevel); break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: uvTopRight.x *= (float)(blockCountX << lodLevel); uvBottomRight.x *= (float)(blockCountX << lodLevel); uvBottomRight.y *= (float)(blockCountZ << lodLevel); uvBottomLeft.y *= (float)(blockCountZ << lodLevel); break; } } break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: { // T/B have to have their uvs rotated using the same face const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[face]; materialIndex = pFaceDef->Visual.MaterialIndex; // get the original uvs float3 originalUVs[4]; originalUVs[0] = pFaceDef->Visual.MinUV; originalUVs[1].Set(pFaceDef->Visual.MaxUV.x, pFaceDef->Visual.MinUV.y, pFaceDef->Visual.MinUV.z); originalUVs[2] = pFaceDef->Visual.MaxUV; originalUVs[3].Set(pFaceDef->Visual.MinUV.x, pFaceDef->Visual.MaxUV.y, pFaceDef->Visual.MinUV.z); // repeat the texture switch (blockRotation) { case BLOCK_WORLD_BLOCK_ROTATION_NORTH: case BLOCK_WORLD_BLOCK_ROTATION_SOUTH: originalUVs[1].x *= (float)(blockCountX << lodLevel); originalUVs[2].x *= (float)(blockCountX << lodLevel); originalUVs[2].y *= (float)(blockCountY << lodLevel); originalUVs[3].y *= (float)(blockCountY << lodLevel); break; case BLOCK_WORLD_BLOCK_ROTATION_EAST: case BLOCK_WORLD_BLOCK_ROTATION_WEST: originalUVs[1].x *= (float)(blockCountY << lodLevel); originalUVs[2].x *= (float)(blockCountY << lodLevel); originalUVs[2].y *= (float)(blockCountX << lodLevel); originalUVs[3].y *= (float)(blockCountX << lodLevel); break; } // and reorientate them according to rotation uvTopLeft = originalUVs[(0 + blockRotation) % 4]; uvTopRight = originalUVs[(1 + blockRotation) % 4]; uvBottomRight = originalUVs[(2 + blockRotation) % 4]; uvBottomLeft = originalUVs[(3 + blockRotation) % 4]; } break; default: UnreachableCode(); return; } // macro to generate coordinates #define MAKE_SLAB_VERTEX_POS(x, y, z) (/*transformMatrix.TransformPoint*/(float3((float)((x) << lodLevel), (float)((y) << lodLevel), (float)((z) << lodLevel))) + basePosition) // generate vertices //float4x4 transformMatrix(BLOCK_ROTATION_MATRIX_LUT[blockRotation]); uint32 baseVertex = output.Vertices.GetSize(); // generate quads switch (face) { case CUBE_FACE_RIGHT: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, endZ + 1) - topBlockSubtractAmount, uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; case CUBE_FACE_LEFT: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, endZ + 1) - topBlockSubtractAmount, uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_BACK: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; case CUBE_FACE_FRONT: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, endZ + 1) - topBlockSubtractAmount, uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, endZ + 1) - topBlockSubtractAmount, uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_TOP: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, endZ + 1) - topBlockSubtractAmount, uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, endZ + 1) - topBlockSubtractAmount, uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, endZ + 1) - topBlockSubtractAmount, uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); } break; case CUBE_FACE_BOTTOM: { output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, endY + 1, startZ), uvTopLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, endY + 1, startZ), uvTopRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-right output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(startX, startY, startZ), uvBottomLeft, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-left output.Vertices.Emplace(MAKE_SLAB_VERTEX_POS(endX + 1, startY, startZ), uvBottomRight, CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; } #undef MAKE_SLAB_VERTEX_POS } void BlockWorldMesher::AddStairBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, Output &output) { // stairs should always be one block high DebugAssert(startZ == endZ); // get uvs and color const BlockPalette::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[face]; uint32 materialIndex = pFaceDef->Visual.MaterialIndex; float3 minUV = pFaceDef->Visual.MinUV; float3 halfUV = pFaceDef->Visual.MaxUV - float3(0.5f, 0.5f, 0.0f); float3 maxUV = pFaceDef->Visual.MaxUV; // repeat the texture uint32 blockCountX = (endX - startX) + 1; uint32 blockCountY = (endY - startY) + 1; uint32 blockCountZ = (endZ - startZ) + 1; switch (face) { case CUBE_FACE_RIGHT: case CUBE_FACE_LEFT: halfUV.x *= (float)(blockCountY << lodLevel); halfUV.y *= (float)(blockCountZ << lodLevel); maxUV.x *= (float)(blockCountY << lodLevel); maxUV.y *= (float)(blockCountZ << lodLevel); break; case CUBE_FACE_BACK: case CUBE_FACE_FRONT: halfUV.x *= (float)(blockCountX << lodLevel); halfUV.y *= (float)(blockCountZ << lodLevel); maxUV.x *= (float)(blockCountX << lodLevel); maxUV.y *= (float)(blockCountZ << lodLevel); break; case CUBE_FACE_TOP: case CUBE_FACE_BOTTOM: halfUV.x *= (float)(blockCountX << lodLevel); halfUV.y *= (float)(blockCountY << lodLevel); maxUV.x *= (float)(blockCountX << lodLevel); maxUV.y *= (float)(blockCountY << lodLevel); break; } // macro to generate coordinates #define MAKE_STAIR_VERTEX_POS(x, y, z) ((transformMatrix.TransformPoint(float3(x, y, z)) * scale) + startPos) // generate vertices float4x4 transformMatrix(BLOCK_ROTATION_MATRIX_LUT[blockRotation]); uint32 baseVertex = output.Vertices.GetSize(); float scale = (float)(1 << lodLevel); // convert start/end to floats float fBlockCountX = (float)blockCountX; float fBlockCountY = (float)blockCountY; float fBlockCountZ = (float)blockCountZ; float3 startPos(float3((float)startX * scale, (float)startY * scale, (float)startZ * scale) + basePosition); // generate quads switch (CUBE_FACE_ROTATION_LUT[blockRotation][face]) { case CUBE_FACE_RIGHT: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, 0.5f), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.5f), float3(halfUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, 0.0f), float3(minUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.0f), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, fBlockCountZ), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, fBlockCountZ), float3(maxUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, 0.5f), float3(halfUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, 0.5f), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_RIGHT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_RIGHT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 4, baseVertex + 5, baseVertex + 6); output.Triangles.Emplace(materialIndex, baseVertex + 5, baseVertex + 7, baseVertex + 6); } break; case CUBE_FACE_LEFT: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, 0.5f), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.5f), float3(halfUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, 0.0f), float3(minUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.0f), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, fBlockCountZ), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, fBlockCountZ), float3(maxUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, 0.5f), float3(halfUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, 0.5f), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_LEFT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_LEFT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); output.Triangles.Emplace(materialIndex, baseVertex + 4, baseVertex + 6, baseVertex + 5); output.Triangles.Emplace(materialIndex, baseVertex + 5, baseVertex + 6, baseVertex + 7); } break; case CUBE_FACE_BACK: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, fBlockCountZ), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, fBlockCountZ), float3(maxUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, 0.0f), float3(minUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, 0.0f), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BACK, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BACK][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; case CUBE_FACE_FRONT: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.5f), float3(minUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.5f), float3(maxUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.0f), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.0f), float3(maxUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, fBlockCountZ), float3(minUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, fBlockCountZ), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, 0.5f), float3(minUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, 0.5f), float3(maxUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_FRONT, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_FRONT][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); output.Triangles.Emplace(materialIndex, baseVertex + 4, baseVertex + 6, baseVertex + 5); output.Triangles.Emplace(materialIndex, baseVertex + 5, baseVertex + 6, baseVertex + 7); } break; case CUBE_FACE_TOP: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, 0.5f), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, 0.5f), float3(halfUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.5f), float3(minUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.5f), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, fBlockCountZ), float3(halfUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, fBlockCountZ), float3(maxUV.x, halfUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.5f, fBlockCountZ), float3(halfUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.5f, fBlockCountZ), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_TOP, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_TOP][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 2, baseVertex + 1); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 2, baseVertex + 3); output.Triangles.Emplace(materialIndex, baseVertex + 4, baseVertex + 6, baseVertex + 5); output.Triangles.Emplace(materialIndex, baseVertex + 5, baseVertex + 6, baseVertex + 7); } break; case CUBE_FACE_BOTTOM: { output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, fBlockCountY, 0.0f), float3(minUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, fBlockCountY, 0.0f), float3(maxUV.x, minUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // top-right output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(0.0f, 0.0f, 0.0f), float3(minUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-left output.Vertices.Emplace(MAKE_STAIR_VERTEX_POS(fBlockCountX, 0.0f, 0.0f), float3(maxUV.x, maxUV.y, minUV.z), CalculateCubeVertexColor(pBlockType, CUBE_FACE_BOTTOM, blockValue, blockLighting), CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][0], CUBE_FACE_PACKED_TANGENT_NORMALS[CUBE_FACE_BOTTOM][1]); // bottom-right output.Triangles.Emplace(materialIndex, baseVertex + 0, baseVertex + 1, baseVertex + 2); output.Triangles.Emplace(materialIndex, baseVertex + 1, baseVertex + 3, baseVertex + 2); } break; } #undef MAKE_STAIR_VERTEX_POS } void BlockWorldMesher::AddPlaneBlock(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output) { // get settings const BlockPalette::BlockType::PlaneShape &planeSettings = pBlockType->PlaneShapeSettings; const BlockPalette::BlockType::VisualParameters &visualSettings = pBlockType->PlaneShapeSettings.Visual; float3 faceMinUV = visualSettings.MinUV; float3 faceMaxUV = visualSettings.MaxUV; uint32 faceMaterialIndex = visualSettings.MaterialIndex; // calculate light colour for face, just use the top uint32 vertexColor = CalculatePlaneVertexColor(pBlockType, blockValue, blockLighting); // generate base vertices FullVertex baseVertices[8]; baseVertices[0].Set(float3(-0.5f, 0.0f, 1.0f), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // top-left baseVertices[1].Set(float3(0.5f, 0.0f, 1.0f), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // top-right baseVertices[2].Set(float3(-0.5f, 0.0f, 0.0f), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // bottom-left baseVertices[3].Set(float3(0.5f, 0.0f, 0.0f), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // bottom-right baseVertices[4].Set(float3(-0.5f, 0.0f, 1.0f), float3(faceMinUV.x, faceMinUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // top-left baseVertices[5].Set(float3(0.5f, 0.0f, 1.0f), float3(faceMaxUV.x, faceMinUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // top-right baseVertices[6].Set(float3(-0.5f, 0.0f, 0.0f), float3(faceMinUV.x, faceMaxUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // bottom-left baseVertices[7].Set(float3(0.5f, 0.0f, 0.0f), float3(faceMaxUV.x, faceMaxUV.y, faceMinUV.z), vertexColor, float3::Zero, float3::Zero, float3::Zero); // bottom-right // do plane @todo block rotation float4x4 transformMatrix(BLOCK_ROTATION_MATRIX_LUT[blockRotation]); float currentRotation = pBlockType->PlaneShapeSettings.BaseRotation; for (uint32 i = 0; i < pBlockType->PlaneShapeSettings.RepeatCount; i++, currentRotation += pBlockType->PlaneShapeSettings.RepeatRotation) { // copy base FullVertex planeVertices[8]; Y_memcpy(planeVertices, baseVertices, sizeof(planeVertices)); // create quat for rotation Quaternion planeRotation(Quaternion::FromEulerAngles(0.0f, 0.0f, currentRotation)); // move into world space float scale = (float)(1 << lodLevel); float3 blockPos(float3((float)(x << lodLevel), (float)(y << lodLevel), (float)(z << lodLevel)) + basePosition); // rotate the vertices, and add the offsets for (uint32 j = 0; j < countof(planeVertices); j++) { planeVertices[j].Position = planeRotation * planeVertices[j].Position; planeVertices[j].Position.x *= planeSettings.Width; planeVertices[j].Position.z *= planeSettings.Height; planeVertices[j].Position.x += planeSettings.OffsetX; planeVertices[j].Position.y += planeSettings.OffsetY; // move so that the origin is the middle of the block (translation happens after rotation) planeVertices[j].Position.x += 0.5f; planeVertices[j].Position.y += 0.5f; // move into world-space planeVertices[j].Position = transformMatrix.TransformPoint(planeVertices[j].Position * scale) + blockPos; } // calculate the tangent space vectors for each triangle float3 tangent, binormal, normal; #define GEN_TANGENTS(v0, v1, v2) MULTI_STATEMENT_MACRO_BEGIN \ MeshUtilites::CalculateTangentSpaceVectors(planeVertices[v0].Position, planeVertices[v1].Position, planeVertices[v2].Position, planeVertices[v0].TexCoord.xy(), planeVertices[v1].TexCoord.xy(), planeVertices[v2].TexCoord.xy(), tangent, binormal, normal); \ planeVertices[v0].Tangent += tangent; planeVertices[v0].Binormal += binormal; planeVertices[v0].Normal += normal; \ planeVertices[v1].Tangent += tangent; planeVertices[v1].Binormal += binormal; planeVertices[v1].Normal += normal; \ planeVertices[v2].Tangent += tangent; planeVertices[v2].Binormal += binormal; planeVertices[v2].Normal += normal; \ MULTI_STATEMENT_MACRO_END // for each 4 triangles GEN_TANGENTS(2, 3, 0); GEN_TANGENTS(0, 3, 1); GEN_TANGENTS(6, 4, 7); GEN_TANGENTS(7, 4, 5); // normalize each tangent space vector for (uint32 j = 0; j < countof(planeVertices); j++) { planeVertices[j].Tangent.SafeNormalizeInPlace(); planeVertices[j].Binormal.SafeNormalizeInPlace(); planeVertices[j].Normal.SafeNormalizeInPlace(); } #undef GEN_TANGENTS // add to list uint32 baseVertex = output.Vertices.GetSize(); for (uint32 j = 0; j < countof(planeVertices); j++) { const FullVertex &v = planeVertices[j]; output.Vertices.Emplace(v.Position, v.TexCoord, v.Color, v.Tangent, v.Binormal, v.Normal); } // generate 4 triangles, one for each quad output.Triangles.Emplace(faceMaterialIndex, baseVertex + 2, baseVertex + 3, baseVertex + 0); output.Triangles.Emplace(faceMaterialIndex, baseVertex + 0, baseVertex + 3, baseVertex + 1); output.Triangles.Emplace(faceMaterialIndex, baseVertex + 6, baseVertex + 4, baseVertex + 7); output.Triangles.Emplace(faceMaterialIndex, baseVertex + 7, baseVertex + 4, baseVertex + 5); } } void BlockWorldMesher::AddMeshBlock(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output) { // find scale float scale = (float)(1 << lodLevel); // find translation float3 translation(float3((float)(x << lodLevel), (float)(y << lodLevel), (float)(z << lodLevel)) + basePosition); translation += float3(0.5f, 0.5f, 0.0f) * scale; // calculate transform static const float rotationLUT[4] = { 0.0f, 90.0f, 180.0f, 270.0f }; float3x4 transform(float4x4::MakeTranslationMatrix(translation) * float4x4::MakeRotationMatrixZ(rotationLUT[blockRotation]) * float4x4::MakeScaleMatrix(pBlockType->MeshShapeSettings.Scale * scale)); // find the instances for this mesh uint32 index = 0; for (; index < output.Instances.GetSize(); index++) { if (output.Instances[index]->MeshIndex == pBlockType->MeshShapeSettings.MeshIndex) break; } if (index == output.Instances.GetSize()) { MeshInstances *pMeshInstances = new MeshInstances; pMeshInstances->MeshIndex = pBlockType->MeshShapeSettings.MeshIndex; pMeshInstances->BufferOffset = 0; output.Instances.Add(pMeshInstances); } // add to the transform list for this mesh, @todo fixup bounds output.Instances[index]->Transforms.Add(transform); } void BlockWorldMesher::AddLightBlock(const BlockPalette::BlockType *pBlockType, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output) { // find scale float scale = (float)(1 << lodLevel); // find translation float3 translation(float3((float)(x << lodLevel), (float)(y << lodLevel), (float)(z << lodLevel)) + basePosition); translation += (float3(0.5f, 0.5f, 0.0f) + pBlockType->PointLightEmitterSettings.Offset) * scale; RENDER_QUEUE_POINT_LIGHT_ENTRY lightEntry; lightEntry.Position = translation; lightEntry.Range = pBlockType->PointLightEmitterSettings.Range * scale; lightEntry.InverseRange = 1.0f / (pBlockType->PointLightEmitterSettings.Range * scale); lightEntry.LightColor = PixelFormatHelpers::ConvertRGBAToFloat4(pBlockType->PointLightEmitterSettings.Color).xyz() * pBlockType->PointLightEmitterSettings.Brightness; lightEntry.FalloffExponent = pBlockType->PointLightEmitterSettings.Falloff; lightEntry.ShadowFlags = 0; lightEntry.ShadowMapIndex = -1; lightEntry.Static = false; output.Lights.Add(lightEntry); } <file_sep>/Engine/Source/Engine/ParticleSystemEmitter.h #pragma once #include "Engine/ParticleSystemCommon.h" #include "Renderer/RenderProxy.h" class GPUBuffer; class RandomNumberGenerator; // Base emitter type class ParticleSystemEmitter : public Object { DECLARE_OBJECT_TYPE_INFO(ParticleSystemEmitter, Object); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemEmitter); DECLARE_OBJECT_NO_FACTORY(ParticleSystemEmitter); friend class ParticleSystem; public: // Emitter starting location types enum SpawnLocationType { SpawnLocationType_Point, SpawnLocationType_Box, SpawnLocationType_Sphere, SpawnLocationType_Cylinder, SpawnLocationType_Triangle, SpawnLocationType_Count }; // Emitter starting velocity types enum SpawnVelocityType { SpawnVelocityType_Fixed, SpawnVelocityType_Arc, SpawnVelocityType_Random, SpawnVelocityType_RandomFixedAxis, SpawnVelocityType_Count }; // Particle type definitions typedef MemArray<ParticleData> ParticleDataArray; // Emitter data, created once per emitter. struct InstanceData { // There are two particle arrays, one containing the emitter state at the // start of the frame, and another after the emitter update has completed. ParticleDataArray ParticlesState[2]; // Time remaining until next particle is spawned. float TimeUntilNextSpawn; // Bounding box of the emitter. AABox BoundingBox; }; // Emitter render data, created once per emitter, stored in the Render Proxy struct InstanceRenderData { // Copy of the bounding box of the emitter. AABox BoundingBox; // Copy of the number of particles. uint32 ParticleCount; // Vertex factory flags. uint32 VertexFactoryFlags; // Emitter data. uint32 EmitterData[4]; // Buffer containing the data that is uploaded to the GPU, if needed. // Guaranteed to be valid and race-free once queued until the frame is complete. byte *pGPUStagingBuffer; uint32 GPUStagingBufferSize; uint32 GPUStagingBufferUsage; // Buffer space on GPU. GPUBuffer *pGPUBuffer; uint32 GPUBufferUsage; }; public: ParticleSystemEmitter(const ObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ParticleSystemEmitter(); // Maximum active particles const uint32 GetMaxActiveParticles() const { return m_maxActiveParticles; } void SetMaxActiveParticles(uint32 maxActiveParticles) { m_maxActiveParticles = maxActiveParticles; } // Update interval in milliseconds const float GetUpdateInterval() const { return m_updateInterval; } void SetUpdateInterval(float updateInterval) { m_updateInterval = updateInterval; } // Spawn rate, number of particles per second const float GetSpawnRate() const { return m_spawnRate; } void SetSpawnRate(float particlesPerSecond) { m_spawnRate = particlesPerSecond; } // Spawn rate, i.e. number of particles to spawn in each spawn const uint32 GetSpawnCount() const { return m_spawnCount; } void SetSpawnCount(uint32 particlesPerSpawn) { m_spawnCount = particlesPerSpawn; } // Affector array access const ParticleSystemModule *GetModule(uint32 moduleIndex) const { return m_modules[moduleIndex]; } uint32 GetModuleCount() const { return m_modules.GetSize(); } void AddModule(const ParticleSystemModule *pModule); void RemoveModule(const ParticleSystemModule *pModule); // Manually spawn a particle in an instance. virtual bool SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG) const; virtual bool SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, uint32 emitterSpecificData) const; virtual bool SpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, uint32 emitterSpecificData, const float3 &localPosition, const float3 &spawnDirection) const; // Initialize emitter state. virtual void InitializeInstance(InstanceData *pEmitterData) const; // Cleanup emitter state. virtual void CleanupInstance(InstanceData *pEmitterData) const; // Update the emitter state. virtual void UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const; // Update the render data associated with the emitter state. Call from render thread. virtual void InitializeRenderData(InstanceRenderData *pEmitterRenderData) const; virtual void CleanupRenderData(InstanceRenderData *pEmitterRenderData) const; virtual void UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const; // Draw methods. UserData[0] will always be populated with what is provided here. virtual void QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const; virtual void SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const; virtual void DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const; // Type registration static void RegisterBuiltinEmitters(); protected: // Internally initialize a new particle. virtual bool InternalCreateParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticleData) const; ParticleData *InternalSpawnParticle(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG) const; // Maximum number of particles this emitter can accommodate at once. // Used to determine buffer and array sizes. uint32 m_maxActiveParticles; // Update interval in milliseconds. To update every frame, set to 0. float m_updateInterval; // Spawn rate float m_spawnRate; // Spawn count uint32 m_spawnCount; // Array of affectors PODArray<const ParticleSystemModule *> m_modules; }; <file_sep>/Engine/Source/MathLib/SIMDVectori_sse.cpp #include "MathLib/SIMDVectori.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #if Y_CPU_SSE_LEVEL >= 2 // should be the same for all vector implementations SIMDVector2i::SIMDVector2i(const Vector2i &v) { Set(v.x, v.y); } SIMDVector3i::SIMDVector3i(const Vector3i &v) { Set(v.x, v.y, v.z); } SIMDVector4i::SIMDVector4i(const Vector4i &v) { Set(v.x, v.y, v.z, v.w); } void SIMDVector2i::Set(const Vector2i &v) { Set(v.x, v.y); } void SIMDVector3i::Set(const Vector3i &v) { Set(v.x, v.y, v.z); } void SIMDVector4i::Set(const Vector4i &v) { Set(v.x, v.y, v.z, v.w); } SIMDVector2i &SIMDVector2i::operator=(const Vector2i &v) { Set(v.x, v.y); return *this; } SIMDVector3i &SIMDVector3i::operator=(const Vector3i &v) { Set(v.x, v.y, v.z); return *this; } SIMDVector4i &SIMDVector4i::operator=(const Vector4i &v) { Set(v.x, v.y, v.z, v.w); return *this; } ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector2iZero[4] = { 0, 0, 0, 0 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector2iOne[4] = { 1, 1, 0, 0 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector2iNegativeOne[4] = { -1, -1, 0, 0 }; const SIMDSIMDVector2i &Vector2i::Zero = reinterpret_cast<const SIMDVector2i &>(Vector2iZero); const SIMDSIMDVector2i &Vector2i::One = reinterpret_cast<const SIMDVector2i &>(Vector2iOne); const SIMDSIMDVector2i &Vector2i::NegativeOne = reinterpret_cast<const SIMDVector2i &>(Vector2iNegativeOne); ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector3iZero[4] = { 0, 0, 0, 0 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector3iOne[4] = { 1, 1, 1, 0 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector3iNegativeOne[4] = { -1, -1, -1, 0 }; const SIMDVector3i &SIMDVector3i::Zero = reinterpret_cast<const SIMDVector3i &>(Vector3iZero); const SIMDVector3i &SIMDVector3i::One = reinterpret_cast<const SIMDVector3i &>(Vector3iOne); const SIMDVector3i &SIMDVector3i::NegativeOne = reinterpret_cast<const SIMDVector3i &>(Vector3iNegativeOne); ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector4iZero[4] = { 0, 0, 0, 0 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector4iOne[4] = { 1, 1, 1, 1 }; ALIGN_DECL(Y_SSE_ALIGNMENT) static const int32 Vector4iNegativeOne[4] = { -1, -1, -1, -1 }; const SIMDVector4i &SIMDVector4i::Zero = reinterpret_cast<const SIMDVector4i &>(Vector4iZero); const SIMDVector4i &SIMDVector4i::One = reinterpret_cast<const SIMDVector4i &>(Vector4iOne); const SIMDVector4i &SIMDVector4i::NegativeOne = reinterpret_cast<const SIMDVector4i &>(Vector4iNegativeOne); #endif <file_sep>/Engine/Source/ContentConverterStandalone/AssimpSkeletalMeshImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintAssimpSkeletalMeshImporterSyntax() { Log_InfoPrint("Assimp Skeletal Mesh Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -skeleton <path>: Skeleton to use."); Log_InfoPrint(" -o <path>: Output resource name."); Log_InfoPrint(" -[no]materials: Enable/disable material importing"); Log_InfoPrint(" -materialdir: Directory for writing materials to"); Log_InfoPrint(" -materialprefix: Prefix for material names"); Log_InfoPrint(" -defaultmaterialname: Default material name"); Log_InfoPrint(" -flipwinding: Flip the triangle winding order"); Log_InfoPrint(" -cs <(yup|zup)_(lh|rh)>: OBJ uses specified coordinate system, convert if necessary."); Log_InfoPrint(" -collision: Collision shape type (box|sphere|trianglemesh|convexhull)"); Log_InfoPrint(""); } bool ParseAssimpSkeletalMeshImporterOption(AssimpSkeletalMeshImporter::Options &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.SourcePath = argv[++i]; else if (CHECK_ARG_PARAM("-o")) Options.OutputResourceName = argv[++i]; else if (CHECK_ARG_PARAM("-skeleton")) Options.SkeletonName = argv[++i]; else if (CHECK_ARG("-nomaterials")) Options.ImportMaterials = false; else if (CHECK_ARG("-materials")) Options.ImportMaterials = true; else if (CHECK_ARG_PARAM("-materialdir")) Options.MaterialDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-materialprefix")) Options.MaterialPrefix = argv[++i]; else if (CHECK_ARG_PARAM("-defaultmaterialname")) Options.DefaultMaterialName = argv[++i]; else if (CHECK_ARG("-flipwinding")) Options.FlipFaceOrder = !Options.FlipFaceOrder; else if (CHECK_ARG_PARAM("-collision")) Options.CollisionShapeType = argv[++i]; else if (CHECK_ARG_PARAM("-cs")) { ++i; if (!Y_stricmp(argv[i], "yup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_LH; else if (!Y_stricmp(argv[i], "yup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; else if (!Y_stricmp(argv[i], "zup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_LH; else if (!Y_stricmp(argv[i], "zup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_RH; else { Log_ErrorPrintf("Invalid coordinate system specified."); return false; } } else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintAssimpSkeletalMeshImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunAssimpSkeletalMeshImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintAssimpSkeletalMeshImporterSyntax(); return 0; } AssimpSkeletalMeshImporter::Options options; AssimpSkeletalMeshImporter::SetDefaultOptions(&options); for (i = 0; i < argc; i++) { if (!ParseAssimpSkeletalMeshImporterOption(options, i, argc, argv)) return 1; } if (options.SourcePath.IsEmpty() || options.OutputResourceName.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; AssimpSkeletalMeshImporter importer(&options, &progressCallbacks); if (!importer.Execute()) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Source/Engine/Skeleton.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Skeleton.h" #include "Engine/DataFormats.h" Log_SetChannel(Skeleton); DEFINE_RESOURCE_TYPE_INFO(Skeleton); DEFINE_RESOURCE_GENERIC_FACTORY(Skeleton); Skeleton::Skeleton(const ResourceTypeInfo *pResourceTypeInfo /*= &s_TypeInfo*/) : BaseClass(pResourceTypeInfo) { } Skeleton::~Skeleton() { } const Skeleton::Bone *Skeleton::GetBoneByName(const char *boneName) const { for (uint32 i = 0; i < m_bones.GetSize(); i++) { if (m_bones[i].m_name.Compare(boneName)) return &m_bones[i]; } return nullptr; } bool Skeleton::LoadFromStream(const char *name, ByteStream *pStream) { DF_SKELETON_HEADER fileHeader; if (!pStream->Read2(&fileHeader, sizeof(fileHeader))) return false; if (fileHeader.Magic != DF_SKELETON_HEADER_MAGIC || fileHeader.HeaderSize != sizeof(fileHeader)) return false; // has to have bones if (fileHeader.BoneCount == 0) { Log_ErrorPrintf("Skeleton::LoadFromStream: Skeleton '%s' has no bones", name); return false; } // allocate everything m_strName = name; m_bones.Resize(fileHeader.BoneCount); // read bones { if (!pStream->SeekAbsolute(fileHeader.BonesOffset)) return false; // next bone offset uint64 nextBoneOffset = pStream->GetPosition(); uint32 *pChildBones = (uint32 *)alloca(sizeof(uint32) * fileHeader.BoneCount); // read in each bone for (uint32 boneIndex = 0; boneIndex < m_bones.GetSize(); boneIndex++) { // seek to next bone if (!pStream->SeekAbsolute(nextBoneOffset)) return false; // read in bone hader DF_SKELETON_BONE boneHeader; if (!pStream->Read2(&boneHeader, sizeof(boneHeader)) || boneHeader.BoneNameLength == 0) return false; // init bone structure Bone *pDestinationBone = &m_bones[boneIndex]; pDestinationBone->m_index = boneIndex; pDestinationBone->m_pParentBone = (boneHeader.ParentBoneIndex != 0xFFFFFFFF) ? &m_bones[boneHeader.ParentBoneIndex] : nullptr; pDestinationBone->m_relativeBaseFrameTransform.SetPosition(float3(boneHeader.RelativeBaseFrameTransformPosition)); pDestinationBone->m_relativeBaseFrameTransform.SetRotation(Quaternion(float4(boneHeader.RelativeBaseFrameTransformRotation))); pDestinationBone->m_relativeBaseFrameTransform.SetScale(float3(boneHeader.RelativeBaseFrameTransformScale)); pDestinationBone->m_absoluteBaseFrameTransform.SetPosition(float3(boneHeader.AbsoluteBaseFrameTransformPosition)); pDestinationBone->m_absoluteBaseFrameTransform.SetRotation(Quaternion(float4(boneHeader.AbsoluteBaseFrameTransformRotation))); pDestinationBone->m_absoluteBaseFrameTransform.SetScale(float3(boneHeader.AbsoluteBaseFrameTransformScale)); // read in the name String boneName; boneName.Resize(boneHeader.BoneNameLength); if (!pStream->Read2(boneName.GetWriteableCharArray(), boneHeader.BoneNameLength)) return false; // set name pDestinationBone->m_name = boneName; // initialize child bones if (boneHeader.ChildBoneCount > 0) { // read in child bone indices DebugAssert(boneHeader.ChildBoneCount < fileHeader.BoneCount); if (!pStream->Read2(pChildBones, sizeof(uint32) * boneHeader.ChildBoneCount)) return false; // process them pDestinationBone->m_childBones.Resize(boneHeader.ChildBoneCount); for (uint32 childBoneIndex = 0; childBoneIndex < pDestinationBone->m_childBones.GetSize(); childBoneIndex++) { DebugAssert(pChildBones[childBoneIndex] < m_bones.GetSize()); pDestinationBone->m_childBones[childBoneIndex] = &m_bones[pChildBones[childBoneIndex]]; } } // figure out next bone offset nextBoneOffset += boneHeader.BoneSize; } } return true; } <file_sep>/Engine/Source/Engine/TerrainSection.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainSection.h" #include "Engine/TerrainQuadTree.h" #include "Engine/DataFormats.h" #include "Engine/StaticMesh.h" Log_SetChannel(TerrainSection); static const uint32 MAX_CHANNELS_PER_SPLAT_MAP = 4; TerrainSection::TerrainSection(const TerrainParameters *pParameters, int32 sectionX, int32 sectionY, uint32 LODLevel) : m_parameters(*pParameters), m_sectionX(sectionX), m_sectionY(sectionY), m_LODLevel(LODLevel), m_pointCount(0), m_bounds(TerrainUtilities::CalculateSectionBoundingBox(pParameters, sectionX, sectionY)), m_changed(false), m_pHeightValues(nullptr), m_heightValueSize(0), m_heightMapRowPitch(0), m_pSplatMaps(nullptr), m_nSplatMaps(0), m_pQuadTree(NULL) { DebugAssert((pParameters->SectionSize >> LODLevel) > 0); DebugAssert(m_pHeightValues == NULL); m_pointCount = (pParameters->SectionSize >> LODLevel) + 1; m_heightValueSize = TerrainUtilities::GetHeightElementStorageSize(pParameters->HeightStorageFormat); m_heightMapRowPitch = PixelFormat_CalculateRowPitch(TerrainUtilities::GetHeightStoragePixelFormat(pParameters->HeightStorageFormat), m_pointCount); // allocate memory for height m_pHeightValues = (byte *)Y_malloc(m_heightMapRowPitch * m_pointCount); } TerrainSection::~TerrainSection() { delete m_pQuadTree; for (uint32 i = 0; i < m_nSplatMaps; i++) Y_free(m_pSplatMaps[i].pData); delete[] m_pSplatMaps; Y_free(m_pHeightValues); } void TerrainSection::Create(float createHeight, uint8 createLayer) { DebugAssert(m_LODLevel == 0); // set all heights this section owns to the specified height SetAllHeightMapValues(createHeight); SetAllSplatMapValues(createLayer, 1.0f); // build a quadtree RebuildQuadTree(); } bool TerrainSection::LoadFromStream(ByteStream *pStream) { // read header DF_TERRAIN_SECTION_HEADER sectionHeader; if (!pStream->Read2(&sectionHeader, sizeof(sectionHeader)) || sectionHeader.Magic != DF_TERRAIN_SECTION_HEADER_MAGIC || sectionHeader.HeaderSize != sizeof(sectionHeader)) { return false; } // parse header if (sectionHeader.PointCount != m_pointCount || sectionHeader.HeightMapValueSize != m_heightValueSize || sectionHeader.HeightMapRowPitch != m_heightMapRowPitch) { return false; } // read height data if (!pStream->Read2(m_pHeightValues, m_heightMapRowPitch * m_pointCount)) return false; // read splat maps m_nSplatMaps = sectionHeader.SplatMapCount; if (m_nSplatMaps > 0) { // this will nullany pointers m_pSplatMaps = new SplatMap[m_nSplatMaps]; Y_memzero(m_pSplatMaps, sizeof(SplatMap) * m_nSplatMaps); // read the actual maps for (uint32 splatMapIndex = 0; splatMapIndex < m_nSplatMaps; splatMapIndex++) { SplatMap *pSplatMap = &m_pSplatMaps[splatMapIndex]; DF_TERRAIN_SECTION_SPLAT_MAP_HEADER splatMapHeader; if (!pStream->Read2(&splatMapHeader, sizeof(splatMapHeader))) return false; uint32 splatMapSize = splatMapHeader.RowPitch * m_pointCount; DebugAssert(splatMapHeader.LayerCount < 4 && splatMapHeader.ChannelCount > 0 && splatMapHeader.ChannelCount <= 4); for (uint32 layerIndex = 0; layerIndex < 4; layerIndex++) pSplatMap->Layers[layerIndex] = splatMapHeader.Layers[layerIndex]; pSplatMap->LayerCount = splatMapHeader.LayerCount; pSplatMap->ChannelCount = splatMapHeader.ChannelCount; pSplatMap->pData = (uint8 *)malloc(splatMapSize); pSplatMap->RowPitch = splatMapHeader.RowPitch; if (!pStream->Read2(pSplatMap->pData, splatMapSize)) return false; } } // read quadtree m_pQuadTree = new TerrainSectionQuadTree(this); if (!m_pQuadTree->LoadFromStream(pStream)) return false; return true; } bool TerrainSection::SaveToStream(ByteStream *pStream) const { // write header DF_TERRAIN_SECTION_HEADER sectionHeader; sectionHeader.Magic = DF_TERRAIN_SECTION_HEADER_MAGIC; sectionHeader.HeaderSize = sizeof(sectionHeader); sectionHeader.PointCount = m_pointCount; sectionHeader.HeightMapValueSize = m_heightValueSize; sectionHeader.HeightMapRowPitch = m_heightMapRowPitch; sectionHeader.SplatMapCount = m_nSplatMaps; if (!pStream->Write2(&sectionHeader, sizeof(sectionHeader))) return false; // write heightmap if (!pStream->Write2(m_pHeightValues, m_heightMapRowPitch * m_pointCount)) return false; // write splat maps for (uint32 splatMapIndex = 0; splatMapIndex < m_nSplatMaps; splatMapIndex++) { const SplatMap *pSplatMap = &m_pSplatMaps[splatMapIndex]; uint32 splatMapSize = pSplatMap->RowPitch * m_pointCount; DF_TERRAIN_SECTION_SPLAT_MAP_HEADER splatMapHeader; for (uint32 layerIndex = 0; layerIndex < 4; layerIndex++) splatMapHeader.Layers[layerIndex] = pSplatMap->Layers[layerIndex]; splatMapHeader.LayerCount = pSplatMap->LayerCount; splatMapHeader.ChannelCount = pSplatMap->ChannelCount; splatMapHeader.RowPitch = pSplatMap->RowPitch; // write splatmap header if (!pStream->Write2(&splatMapHeader, sizeof(splatMapHeader))) return false; // write splatmap data if (!pStream->Write2(pSplatMap->pData, splatMapSize)) return false; } // write quadtree if (!m_pQuadTree->SaveToStream(pStream)) return false; // done return true; } void TerrainSection::GetRawHeightMapData(const void **pDataPointer, uint32 *pValueSize, uint32 *pRowPitch) const { *pDataPointer = m_pHeightValues; *pValueSize = m_heightValueSize; *pRowPitch = m_heightMapRowPitch; } void TerrainSection::GetRawSplatMapData(uint32 mapIndex, const void **pDataPointer, uint32 *pValueSize, uint32 *pRowPitch) const { DebugAssert(mapIndex < m_nSplatMaps); *pDataPointer = m_pSplatMaps[mapIndex].pData; *pValueSize = sizeof(uint8) * m_pSplatMaps[mapIndex].ChannelCount; *pRowPitch = m_pSplatMaps[mapIndex].RowPitch; } bool TerrainSection::RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection /*= false*/) const { // best contacts float bestContactTimeSq = Y_FLT_INFINITE; float3 bestContactPoint; float3 bestContactNormal; bool continueSearch = true; // use quadtree to break down search m_pQuadTree->EnumerateNodesIntersectingRay(ray, 0, [this, ray, &bestContactTimeSq, &bestContactPoint, &bestContactNormal, exitAtFirstIntersection, &continueSearch](const TerrainQuadTreeNode *pNode) { if (!continueSearch) return; // vars const float3 &sectionMinBounds = m_bounds.GetMinBounds(); uint32 scale = m_parameters.Scale; // get range uint32 startX = pNode->GetStartQuadX(); uint32 startY = pNode->GetStartQuadY(); uint32 endX = startX + pNode->GetNodeSize(); uint32 endY = startY + pNode->GetNodeSize(); float3 v0, v1, v2, v3; float3 triangleContactPoint, triangleContactNormal; float triangleContactTimeSq; // todo: contract search range to ray bounding box for perf // iterate over points for (uint32 ly = startY; ly < endY; ly++) { for (uint32 lx = startX; lx < endX; lx++) { // first triangle v0.Set(sectionMinBounds.x + (float)((lx)* scale), sectionMinBounds.y + (float)((ly + 1) * scale), GetHeightMapValue(lx, ly + 1)); v1.Set(sectionMinBounds.x + (float)((lx)* scale), sectionMinBounds.y + (float)((ly)* scale), GetHeightMapValue(lx, ly)); v2.Set(sectionMinBounds.x + (float)((lx + 1) * scale), sectionMinBounds.y + (float)((ly + 1) * scale), GetHeightMapValue(lx + 1, ly + 1)); // test first triangle if (ray.TriangleIntersection(v0, v1, v2, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } if (exitAtFirstIntersection) { continueSearch = false; return; } // don't bother testing the other triangle, it's unlikely to hit both? continue; } // fill last vertex v3.Set(sectionMinBounds.x + (float)((lx + 1) * scale), sectionMinBounds.y + (float)((ly)* scale), GetHeightMapValue(lx + 1, ly)); // test second triangle: note reversed first vertices if (ray.TriangleIntersection(v2, v1, v3, triangleContactNormal, triangleContactPoint)) { // success triangleContactTimeSq = (triangleContactPoint - ray.GetOrigin()).SquaredLength(); if (triangleContactTimeSq < bestContactTimeSq) { bestContactTimeSq = triangleContactTimeSq; bestContactNormal = triangleContactNormal; bestContactPoint = triangleContactPoint; } if (exitAtFirstIntersection) { continueSearch = false; return; } } } } }); if (bestContactTimeSq == Y_FLT_INFINITE) return false; contactNormal = bestContactNormal; contactPoint = bestContactPoint; return true; } const float TerrainSection::GetHeightMapValue(uint32 offsetX, uint32 offsetY) const { DebugAssert(offsetX < m_pointCount && offsetY < m_pointCount); uint32 heightMapOffset = offsetY * m_heightMapRowPitch + offsetX * m_heightValueSize; float height; switch (m_parameters.HeightStorageFormat) { case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; const uint8 *pValuePointer = reinterpret_cast<const uint8 *>(m_pHeightValues + heightMapOffset); height = minHeight + (float(*pValuePointer) / 255.0f) * heightRange; } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; const uint16 *pValuePointer = reinterpret_cast<const uint16 *>(m_pHeightValues + heightMapOffset); height = minHeight + (float(*pValuePointer) / 65535.0f) * heightRange; } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32: { // direct mapped const float *pValuePointer = reinterpret_cast<const float *>(m_pHeightValues + heightMapOffset); height = *pValuePointer; } break; default: UnreachableCode(); return 0.0f; } return height; } void TerrainSection::SetHeightMapValue(uint32 offsetX, uint32 offsetY, float height) { DebugAssert(offsetX < m_pointCount && offsetY < m_pointCount); uint32 heightMapOffset = offsetY * m_heightMapRowPitch + offsetX * m_heightValueSize; float oldHeight; switch (m_parameters.HeightStorageFormat) { case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; uint8 newHeightValue = (uint8)Min(Max(((height - minHeight) / heightRange) * 255.0f, 0.0f), 255.0f); uint8 *pValuePointer = reinterpret_cast<uint8 *>(m_pHeightValues + heightMapOffset); if (*pValuePointer == newHeightValue) return; oldHeight = minHeight + (float(*pValuePointer) / 255.0f) * heightRange; *pValuePointer = newHeightValue; } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; uint16 newHeightValue = (uint16)Min(Max(((height - minHeight) / heightRange) * 65535.0f, 0.0f), 65535.0f); uint16 *pValuePointer = reinterpret_cast<uint16 *>(m_pHeightValues + heightMapOffset); if (*pValuePointer == newHeightValue) return; oldHeight = minHeight + (float(*pValuePointer) / 65535.0f) * heightRange; *pValuePointer = newHeightValue; } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32: { float *pValuePointer = reinterpret_cast<float *>(m_pHeightValues + heightMapOffset); if (*pValuePointer == height) return; oldHeight = *pValuePointer; *pValuePointer = height; } break; default: UnreachableCode(); return; } m_changed = true; if (m_pQuadTree != NULL) { bool quadTreeNeedsRebuild = false; m_pQuadTree->UpdateMinMaxHeight(offsetX, offsetY, height, oldHeight, &quadTreeNeedsRebuild); if (quadTreeNeedsRebuild) { Log_PerfPrintf("TerrainSection::SetIndexedHeight: Setting height (%u,%u) %.2f -> %.2f triggered quadtree rebuild.", offsetX, offsetY, oldHeight, height); RebuildQuadTree(); } } } void TerrainSection::SetAllHeightMapValues(float height) { switch (m_parameters.HeightStorageFormat) { case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; uint8 value8 = (uint8)Min(Max(((height - minHeight) / heightRange) * 255.0f, 0.0f), 255.0f); byte *pRowPointer = m_pHeightValues; for (uint32 y = 0; y < m_pointCount; y++) { uint8 *pValuePointer = reinterpret_cast<uint8 *>(pRowPointer); for (uint32 x = 0; x < m_pointCount; x++) *(pValuePointer++) = value8; pRowPointer += m_heightMapRowPitch; } } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16: { float minHeight = (float)m_parameters.MinHeight; float heightRange = (float)m_parameters.MaxHeight - minHeight; uint16 value16 = (uint16)Min(Max(((height - minHeight) / heightRange) * 65535.0f, 0.0f), 65535.0f); byte *pRowPointer = m_pHeightValues; for (uint32 y = 0; y < m_pointCount; y++) { uint16 *pValuePointer = reinterpret_cast<uint16 *>(pRowPointer); for (uint32 x = 0; x < m_pointCount; x++) *(pValuePointer++) = value16; pRowPointer += m_heightMapRowPitch; } } break; case TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32: { byte *pRowPointer = m_pHeightValues; for (uint32 y = 0; y < m_pointCount; y++) { float *pValuePointer = reinterpret_cast<float *>(pRowPointer); for (uint32 x = 0; x < m_pointCount; x++) *(pValuePointer++) = height; pRowPointer += m_heightMapRowPitch; } } break; } m_changed = true; if (m_pQuadTree != NULL) RebuildQuadTree(); } float3 TerrainSection::CalculateNormalAtPoint(uint32 x, uint32 y) const { float val, valU, valV; // get value val = GetHeightMapValue(x, y); // get in direction right if (x == (m_pointCount - 1)) valU = val; else valU = GetHeightMapValue(x + 1, y); // .. down if (y == (m_pointCount - 1)) valV = val; else valV = GetHeightMapValue(x, y + 1); // get direction return float3(val - valU, val - valV, 0.5f).Normalize(); } void TerrainSection::AllocateLayerInSplatMap(uint8 layerIndex, uint32 *pMapIndex, uint32 *pChannelIndex) { static const PIXEL_FORMAT splatMapFormats[MAX_CHANNELS_PER_SPLAT_MAP + 1] = { PIXEL_FORMAT_UNKNOWN, PIXEL_FORMAT_R8_UNORM, PIXEL_FORMAT_R8G8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM }; // shouldn't be allocated DebugAssert(!GetSplatMapLocation(layerIndex, pMapIndex, pChannelIndex)); // find a splat map with an unused channel uint32 mapIndex; for (mapIndex = 0; mapIndex < m_nSplatMaps; mapIndex++) { SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; if (pSplatMap->LayerCount < 4) break; } // no free channels? if (mapIndex < m_nSplatMaps) { // reallocate this splatmap SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; uint32 channelIndex = pSplatMap->LayerCount; uint32 newLayerCount = pSplatMap->LayerCount + 1; DebugAssert(pSplatMap->LayerCount > 0 && pSplatMap->LayerCount < 4); // allocate memory uint32 channelsToAllocate = (newLayerCount >= 3) ? MAX_CHANNELS_PER_SPLAT_MAP : newLayerCount; if (channelsToAllocate != pSplatMap->ChannelCount) { uint32 newSplatMapRowPitch = PixelFormat_CalculateRowPitch(splatMapFormats[channelsToAllocate], m_pointCount); uint32 newSplatMapSize = newSplatMapRowPitch * m_pointCount; uint8 *pNewSplatMap = (uint8 *)malloc(newSplatMapSize); Y_memzero(pNewSplatMap, newSplatMapSize); // copy values in for (uint32 y = 0; y < m_pointCount; y++) { const uint8 *pSourcePointer = pSplatMap->pData + y * pSplatMap->RowPitch; uint8 *pDestinationPointer = pNewSplatMap + y * newSplatMapRowPitch; for (uint32 x = 0; x < m_pointCount; x++) { uint8 *pWritePointer = pDestinationPointer; switch (pSplatMap->LayerCount) { case 3: *(pWritePointer++) = *(pSourcePointer++); case 2: *(pWritePointer++) = *(pSourcePointer++); case 1: *(pWritePointer++) = *(pSourcePointer++); } pDestinationPointer += channelsToAllocate; } } // free old data Y_free(pSplatMap->pData); // update data pSplatMap->ChannelCount = channelsToAllocate; pSplatMap->pData = pNewSplatMap; pSplatMap->RowPitch = newSplatMapRowPitch; } // update struct pSplatMap->Layers[channelIndex] = layerIndex; pSplatMap->LayerCount = newLayerCount; // set pointers Log_DevPrintf("TerrainSection::AllocateLayerInSplatMap: For layer %i, reusing splat map %u channel %u", (uint32)layerIndex, mapIndex, channelIndex); *pMapIndex = mapIndex; *pChannelIndex = channelIndex; } else { // resize splatmap array SplatMap *pNewSplatMapArray = new SplatMap[m_nSplatMaps + 1]; if (m_nSplatMaps > 0) { Y_memcpy(pNewSplatMapArray, m_pSplatMaps, sizeof(SplatMap) * m_nSplatMaps); delete[] m_pSplatMaps; } m_pSplatMaps = pNewSplatMapArray; m_nSplatMaps++; // allocate memory uint32 channelsToAllocate = 1; uint32 newSplatMapRowPitch = PixelFormat_CalculateRowPitch(splatMapFormats[channelsToAllocate], m_pointCount); uint32 newSplatMapSize = newSplatMapRowPitch * m_pointCount; uint8 *pNewSplatMap = (uint8 *)malloc(newSplatMapSize); Y_memzero(pNewSplatMap, newSplatMapSize); // fill the data SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; pSplatMap->Layers[0] = layerIndex; pSplatMap->Layers[1] = 0xFF; pSplatMap->Layers[2] = 0xFF; pSplatMap->Layers[3] = 0xFF; pSplatMap->LayerCount = 1; pSplatMap->ChannelCount = 1; pSplatMap->pData = pNewSplatMap; pSplatMap->RowPitch = newSplatMapRowPitch; // set pointers Log_DevPrintf("TerrainSection::AllocateLayerInSplatMap: For layer %i, allocating new splat map %u", (uint32)layerIndex, mapIndex); *pMapIndex = mapIndex; *pChannelIndex = 0; } } bool TerrainSection::GetSplatMapLocation(uint8 layerIndex, uint32 *pMapIndex, uint32 *pChannelIndex) const { for (uint32 mapIndex = 0; mapIndex < m_nSplatMaps; mapIndex++) { const SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; for (uint32 channelIndex = 0; channelIndex < pSplatMap->LayerCount; channelIndex++) { if (pSplatMap->Layers[channelIndex] == layerIndex) { *pMapIndex = mapIndex; *pChannelIndex = channelIndex; return true; } } } return false; } const bool TerrainSection::HasSplatMapForLayer(uint8 layerIndex) const { for (uint32 mapIndex = 0; mapIndex < m_nSplatMaps; mapIndex++) { const SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; for (uint32 channelIndex = 0; channelIndex < pSplatMap->LayerCount; channelIndex++) { if (pSplatMap->Layers[channelIndex] == layerIndex) return true; } } return false; } const uint8 TerrainSection::GetSplatMapDominantLayer(uint32 offsetX, uint32 offsetY) const { uint8 bestLayer = 0xFF; uint8 bestLayerValue = 0; for (uint32 mapIndex = 0; mapIndex < m_nSplatMaps; mapIndex++) { const SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; const uint8 *pBasePointer = pSplatMap->pData + (offsetY * pSplatMap->RowPitch) + (offsetX * pSplatMap->ChannelCount); for (uint32 channelIndex = 0; channelIndex < pSplatMap->LayerCount; channelIndex++) { if (bestLayer == 0xFF || pBasePointer[channelIndex] > bestLayerValue) { bestLayer = pSplatMap->Layers[channelIndex]; bestLayerValue = pBasePointer[channelIndex]; } } } return bestLayer; } const uint32 TerrainSection::GetSplatMapValues(uint32 offsetX, uint32 offsetY, uint8 *outLayers, float *outLayerWeights, uint32 maxLayers) const { uint32 layerCount = 0; for (uint32 mapIndex = 0; mapIndex < m_nSplatMaps && layerCount < maxLayers; mapIndex++) { const SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; const uint8 *pBasePointer = pSplatMap->pData + (offsetY * pSplatMap->RowPitch) + (offsetX * pSplatMap->ChannelCount); for (uint32 channelIndex = 0; channelIndex < pSplatMap->LayerCount && layerCount < maxLayers; channelIndex++) { if (pBasePointer[channelIndex] != 0) { outLayers[layerCount] = pSplatMap->Layers[channelIndex]; outLayerWeights[layerCount] = (float)pBasePointer[channelIndex] / 255.0f; layerCount++; } } } return layerCount; } uint8 TerrainSection::GetSplatMapValue(uint32 mapIndex, uint32 channelIndex, uint32 offsetX, uint32 offsetY) const { DebugAssert(mapIndex < m_nSplatMaps && channelIndex < m_pSplatMaps[mapIndex].LayerCount); const SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; const uint8 *pValuePointer = pSplatMap->pData + (offsetY * pSplatMap->RowPitch) + (offsetX * pSplatMap->ChannelCount) + channelIndex; return *pValuePointer; } void TerrainSection::SetSplatMapValue(uint32 mapIndex, uint32 channelIndex, uint32 offsetX, uint32 offsetY, uint8 value) { DebugAssert(mapIndex < m_nSplatMaps && channelIndex < m_pSplatMaps[mapIndex].LayerCount); SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; uint8 *pValuePointer = pSplatMap->pData + (offsetY * pSplatMap->RowPitch) + (offsetX * pSplatMap->ChannelCount) + channelIndex; *pValuePointer = value; } const float TerrainSection::GetSplatMapValue(uint32 offsetX, uint32 offsetY, uint8 layer) const { // find the map/channel index uint32 mapIndex, channelIndex; if (!GetSplatMapLocation(layer, &mapIndex, &channelIndex)) return 0.0f; // get the value return (float)GetSplatMapValue(mapIndex, channelIndex, offsetX, offsetY) / 255.0f; } void TerrainSection::SetSplatMapValue(uint32 offsetX, uint32 offsetY, uint8 layer, float value, bool renormalize /*= true*/) { // find the map/channel index uint32 mapIndex, channelIndex; if (!GetSplatMapLocation(layer, &mapIndex, &channelIndex)) { // allocate one AllocateLayerInSplatMap(layer, &mapIndex, &channelIndex); } // get the current weights if (renormalize) { float remainingWeight = 1.0f - value; if (Math::NearEqual(remainingWeight, 0.0f, Y_FLT_EPSILON)) { // just clear everything ClearSplatMapValues(offsetX, offsetY); } else { // find the length of all current splatmap values float currentSplatMapLength = 0.0f; for (uint32 normalizeMapIndex = 0; normalizeMapIndex < m_nSplatMaps; normalizeMapIndex++) { SplatMap *pNormalizeSplatMap = &m_pSplatMaps[normalizeMapIndex]; for (uint32 normalizeChannelIndex = 0; normalizeChannelIndex < pNormalizeSplatMap->LayerCount; normalizeChannelIndex++) { if (normalizeMapIndex != mapIndex || normalizeChannelIndex != channelIndex) currentSplatMapLength += (float)GetSplatMapValue(normalizeMapIndex, normalizeChannelIndex, offsetX, offsetY) / 255.0f; } } // has length? if (!Math::NearEqual(currentSplatMapLength, 0.0f, Y_FLT_EPSILON)) { // mod everything for (uint32 normalizeMapIndex = 0; normalizeMapIndex < m_nSplatMaps; normalizeMapIndex++) { SplatMap *pNormalizeSplatMap = &m_pSplatMaps[normalizeMapIndex]; for (uint32 normalizeChannelIndex = 0; normalizeChannelIndex < pNormalizeSplatMap->LayerCount; normalizeChannelIndex++) { if (normalizeMapIndex != mapIndex || normalizeChannelIndex != channelIndex) { // cram it into the remaining range float newWeight = (float)GetSplatMapValue(normalizeMapIndex, normalizeChannelIndex, offsetX, offsetY) / 255.0f; newWeight /= currentSplatMapLength; newWeight *= remainingWeight; SetSplatMapValue(normalizeMapIndex, normalizeChannelIndex, offsetX, offsetY, (uint8)(Math::Clamp(newWeight, 0.0f, 1.0f) * 255.0f)); } } } } else { // just clear everything ClearSplatMapValues(offsetX, offsetY); } } } // set the value SetSplatMapValue(mapIndex, channelIndex, offsetX, offsetY, (uint8)(Math::Clamp(value, 0.0f, 1.0f) * 255.0f)); } void TerrainSection::ClearSplatMapValues(uint32 offsetX, uint32 offsetY) { for (uint32 mapIndex = 0; mapIndex < m_nSplatMaps; mapIndex++) { SplatMap *pSplatMap = &m_pSplatMaps[mapIndex]; for (uint32 channelIndex = 0; channelIndex < pSplatMap->LayerCount; channelIndex++) SetSplatMapValue(mapIndex, channelIndex, offsetX, offsetY, 0); } } void TerrainSection::SetAllSplatMapValues(uint8 layer, float value /*= 1.0f*/) { for (uint32 y = 0; y < m_pointCount; y++) { for (uint32 x = 0; x < m_pointCount; x++) { if (value == 1.0f) ClearSplatMapValues(x, y); SetSplatMapValue(x, y, layer, value); } } } void TerrainSection::CopySplatMapValue(const TerrainSection *pSourceSection, uint32 sourceOffsetX, uint32 sourceOffsetY, uint32 destinationOffsetX, uint32 destinationOffsetY) { // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = pSourceSection->GetSplatMapValues(sourceOffsetX, sourceOffsetY, layerIndices, layerWeights, countof(layerIndices)); // clear from the other section ClearSplatMapValues(destinationOffsetX, destinationOffsetY); // and copy weights in for (uint32 i = 0; i < nLayers; i++) SetSplatMapValue(destinationOffsetX, destinationOffsetY, layerIndices[i], layerWeights[i]); } void TerrainSection::NormalizeSplatMapValue(uint32 offsetX, uint32 offsetY) { // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = GetSplatMapValues(offsetX, offsetY, layerIndices, layerWeights, countof(layerIndices)); // get the total length of all weights float weightLength = 0.0f; for (uint32 i = 0; i < nLayers; i++) weightLength += layerWeights[i]; // no weights or zero length? if (nLayers == 0 || Math::NearEqual(weightLength, 0.0f, Y_FLT_EPSILON)) return; // divide all weights by this length for (uint32 i = 0; i < nLayers; i++) { float newWeight = layerWeights[i] / weightLength; if (layerWeights[i] != newWeight) SetSplatMapValue(offsetX, offsetY, layerIndices[i], newWeight); } } void TerrainSection::FilterSplatMapValues(uint32 offsetX, uint32 offsetY, float threshold /*= 0.1f*/, bool normalizeAfterRemove /*= true*/) { // get a list of layers and weights from the section uint8 layerIndices[TERRAIN_MAX_LAYERS]; float layerWeights[TERRAIN_MAX_LAYERS]; uint32 nLayers = GetSplatMapValues(offsetX, offsetY, layerIndices, layerWeights, countof(layerIndices)); // new layer indices/weights uint8 newLayerIndices[TERRAIN_MAX_LAYERS]; float newLayerWeights[TERRAIN_MAX_LAYERS]; float newLayerWeightLength = 0.0f; uint32 nNewLayers = 0; // has layers? if (nLayers > 0) { // process each layer for (uint32 i = 0; i < nLayers; i++) { if (layerWeights[i] >= threshold) { newLayerIndices[nNewLayers] = layerIndices[i]; newLayerWeights[nNewLayers] = layerWeights[i]; newLayerWeightLength += layerWeights[i]; nNewLayers++; } } } // normalize? if (normalizeAfterRemove && nNewLayers > 0 && Math::NearEqual(newLayerWeightLength, 0.0f, Y_FLT_EPSILON)) { // normalize each weight for (uint32 i = 0; i < nNewLayers; i++) newLayerWeights[i] = newLayerWeights[i] / newLayerWeightLength; } // set them ClearSplatMapValues(offsetX, offsetY); for (uint32 i = 0; i < nNewLayers; i++) SetSplatMapValue(offsetX, offsetY, newLayerIndices[i], newLayerWeights[i]); } bool TerrainSection::RebuildQuadTree(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_LODLevel == 0); #ifdef PROFILE_TERRAIN_QUADTREE_REBUILD_TIMES Timer rebuildTimer; #endif AutoReleasePtr<ByteStream> pTemporaryStream = ByteStream_CreateGrowableMemoryStream(); if (!TerrainSectionQuadTree::Build(&m_parameters, this, pTemporaryStream, pProgressCallbacks)) return false; pTemporaryStream->SeekAbsolute(0); TerrainSectionQuadTree *pQuadTree = new TerrainSectionQuadTree(this); if (!pQuadTree->LoadFromStream(pTemporaryStream)) { delete pQuadTree; return false; } delete m_pQuadTree; m_pQuadTree = pQuadTree; m_changed = true; #ifdef PROFILE_SHADER_COMPILE_TIMES Log_ProfilePrintf("TerrainSection::RebuildQuadTree: Rebuild took %.4f msec for section (%i, %i)", rebuildTimer.GetTimeMilliseconds(), m_sectionX, m_sectionY); #endif return true; } void TerrainSection::RebuildSplatMaps(bool filterValues /* = true */, float filterThreshold /* = 0.1f */) { // filter first? if (filterValues) { for (uint32 y = 0; y < m_pointCount; y++) { for (uint32 x = 0; x < m_pointCount; x++) { FilterSplatMapValues(x, y, filterThreshold, true); } } } // TODO // generate a new list of used layers // regenerate all splat maps taking into account unused stuff } float TerrainSection::SampleHeightMap(float normalizedX, float normalizedY) const { // convert normalized coordinates to offsets :: TODO check the -1 here float offsetXF = normalizedX * (float)(m_pointCount - 1); float offsetYF = normalizedY * (float)(m_pointCount - 1); // get fractional offset float offsetXFrac = Math::FractionalPart(offsetXF); float offsetYFrac = Math::FractionalPart(offsetYF); // get the 4 offsets uint32 offsetXL = (uint32)Math::Truncate(Math::Floor(offsetXF)); uint32 offsetXR = (uint32)offsetXL + 1; uint32 offsetYT = (uint32)Math::Truncate(Math::Floor(offsetYF)); uint32 offsetYB = (uint32)offsetYT + 1; // get 4 heights float heightTL(GetHeightMapValue(offsetXL, offsetYT)); float heightTR(GetHeightMapValue(offsetXR, offsetYT)); float heightBL(GetHeightMapValue(offsetXL, offsetYB)); float heightBR(GetHeightMapValue(offsetXR, offsetYB)); // bilinear interpolate between them float R1(heightTL + (heightTR - heightTL) * offsetXFrac); float R2(heightBL + (heightBR - heightBL) * offsetXFrac); float height = (R1 + (R2 - R1) * offsetYFrac); return height; } float3 TerrainSection::SampleNormal(float normalizedX, float normalizedY) const { // convert normalized coordinates to offsets :: TODO check the -1 here float offsetXF = normalizedX * (float)(m_pointCount - 1); float offsetYF = normalizedY * (float)(m_pointCount - 1); // get fractional offset float offsetXFrac = Math::FractionalPart(offsetXF); float offsetYFrac = Math::FractionalPart(offsetYF); // get the 4 offsets uint32 offsetXL = (uint32)Math::Truncate(Math::Floor(offsetXF)); uint32 offsetXR = (uint32)offsetXL + 1; uint32 offsetYT = (uint32)Math::Truncate(Math::Floor(offsetYF)); uint32 offsetYB = (uint32)offsetYT + 1; // get 4 normals float3 normalTL(CalculateNormalAtPoint(offsetXL, offsetYT)); float3 normalTR(CalculateNormalAtPoint(offsetXR, offsetYT)); float3 normalBL(CalculateNormalAtPoint(offsetXL, offsetYB)); float3 normalBR(CalculateNormalAtPoint(offsetXR, offsetYB)); // bilinear interpolate between them float3 R1(normalTL + (normalTR - normalTL) * offsetXFrac); float3 R2(normalBL + (normalBR - normalBL) * offsetXFrac); float3 normal(R1 + (R2 - R1) * offsetYFrac); return normal.Normalize(); } int32 TerrainSection::GetDetailMeshIndex(const StaticMesh *pStaticMesh) const { for (const DetailMesh &detailMesh : m_detailMeshes) { if (detailMesh.pStaticMesh == pStaticMesh) return (int32)detailMesh.MeshIndex; } return -1; } int32 TerrainSection::AddDetailMesh(const StaticMesh *pStaticMesh, float drawDistance) { uint32 maxIndex = 0; for (const DetailMesh &detailMesh : m_detailMeshes) { if (detailMesh.pStaticMesh == pStaticMesh) return (int32)detailMesh.MeshIndex; maxIndex = Max(maxIndex, detailMesh.MeshIndex); } DetailMesh detailMesh; detailMesh.MeshIndex = (m_detailMeshes.IsEmpty()) ? 0 : (maxIndex + 1); detailMesh.pStaticMesh = pStaticMesh; pStaticMesh->AddRef(); detailMesh.DrawDistance = drawDistance; m_detailMeshes.Add(detailMesh); return detailMesh.MeshIndex; } void TerrainSection::SetDetailMeshDrawDistance(const StaticMesh *pStaticMesh, float drawDistance) { for (DetailMesh &detailMesh : m_detailMeshes) { if (detailMesh.pStaticMesh == pStaticMesh) { detailMesh.DrawDistance = drawDistance; return; } } } void TerrainSection::AddDetailMeshInstance(uint32 meshIndex, float normalizedX, float normalizedY, float scale, float rotationZ) { DetailMeshInstance meshInstance; meshInstance.MeshIndex = meshIndex; meshInstance.NormalizedX = normalizedX; meshInstance.NormalizedY = normalizedY; meshInstance.RotationZ = rotationZ; float3 meshPosition; Quaternion meshRotation; GetDetailMeshLocation(normalizedX, normalizedY, rotationZ, &meshPosition, &meshRotation); // calculate matrix meshInstance.Position = meshPosition; meshInstance.TransformMatrix = float3x4(float4x4::MakeTranslationMatrix(meshPosition) * meshRotation.GetMatrix4x4() * float4x4::MakeScaleMatrix(scale)); // sort the list m_detailMeshInstances.Add(meshInstance); m_detailMeshInstances.Sort([](const DetailMeshInstance *left, const DetailMeshInstance *right) -> int { return static_cast<int32>(left->MeshIndex) - static_cast<int32>(right->MeshIndex); }); //Log_DevPrintf("mesh instance %u %.3f %.3f -> %s %s", meshIndex, normalizedX, normalizedY, StringConverter::Float3ToString(meshPosition).GetCharArray(), StringConverter::Float3ToString(meshRotation.GetEulerAngles()).GetCharArray()); } void TerrainSection::RemoveDetailMeshInstancesBox(float normalizedXStart, float normalizedXEnd, float normalizedYStart, float normalizedYEnd) { } void TerrainSection::RemoveDetailMeshInstancesCircle(float normalizedX, float normalizedY, float radius) { } void TerrainSection::UpdateDetailMeshLocations(uint32 offsetX, uint32 offsetY) { } void TerrainSection::GetDetailMeshLocation(float normalizedX, float normalizedY, float rotationZ, float3 *pOutPosition, Quaternion *pOutRotation) { // sample height and normal at this position float height = SampleHeightMap(normalizedX, normalizedY); float3 normal(SampleNormal(normalizedX, normalizedY)); // set position *pOutPosition = float3(m_bounds.GetMinBounds().xy() + float2(normalizedX * (m_pointCount - 1), normalizedY * (m_pointCount - 1)), height); // set rotation *pOutRotation = (Quaternion::FromTwoUnitVectors(float3::UnitZ, normal) * Quaternion::MakeRotationZ(rotationZ)).Normalize(); } /* bool TerrainSection::GetLayerIndex(uint8 layer, uint32 *pLayerIndex) const { for (uint32 i = 0; i < m_nUsedLayers; i++) { if (m_usedLayers[i] == layer) { *pLayerIndex = i; return true; } } return false; } uint8 TerrainSection::GetLayerValue(uint32 ix, uint32 iy, uint32 layerIndex) const { DebugAssert(layerIndex < m_nUsedLayers); return m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix]; } void TerrainSection::SetLayerValue(uint32 ix, uint32 iy, uint32 layerIndex, uint8 value) { DebugAssert(layerIndex < m_nUsedLayers); m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix] = value; m_changed = true; } void TerrainSection::ExtendLayerArray(uint32 newLayerCount) { DebugAssert(newLayerCount > m_nUsedLayers); uint32 newWeightArrayCount = (newLayerCount + 3) / 4; DebugAssert(newWeightArrayCount > 0); if (newWeightArrayCount > m_nLayerWeightArrays) { uint8 *pNewLayerWeightValues = new uint8[newWeightArrayCount * m_layerWeightValuesStride]; if (m_nLayerWeightArrays > 0) Y_memcpy(pNewLayerWeightValues, m_pLayerWeightValues, sizeof(uint8) * m_layerWeightValuesStride * m_nLayerWeightArrays); Y_memzero(pNewLayerWeightValues + m_layerWeightValuesStride * m_nLayerWeightArrays, sizeof(uint8) * m_layerWeightValuesStride * (newWeightArrayCount - m_nLayerWeightArrays)); delete[] m_pLayerWeightValues; m_pLayerWeightValues = pNewLayerWeightValues; m_nLayerWeightArrays = newWeightArrayCount; } uint8 *pNewLayerIndices = new uint8[newLayerCount]; if (m_nUsedLayers > 0) Y_memcpy(pNewLayerIndices, m_pLayerIndices, sizeof(uint8) * m_nUsedLayers); Y_memset(pNewLayerIndices + m_nUsedLayers, 0xFF, sizeof(uint8) * (newLayerCount - m_nUsedLayers)); delete[] m_pLayerIndices; m_pLayerIndices = pNewLayerIndices; m_nUsedLayers = newLayerCount; m_changed = true; } uint32 TerrainSection::AddLayer(uint8 layer) { uint32 layerIndex; DebugAssert(!GetLayerIndex(layer, &layerIndex)); layerIndex = m_nUsedLayers++; m_usedLayers[layerIndex] = layer; m_pLayerWeightValues = (uint8 *)realloc(m_pLayerWeightValues, sizeof(uint8) * m_layerWeightValuesStride * m_nUsedLayers); Y_memzero(m_pLayerWeightValues + (layerIndex * m_layerWeightValuesStride), m_layerWeightValuesStride); m_changed = true; return layerIndex; } float TerrainSection::GetIndexedBaseLayerWeight(uint32 ix, uint32 iy, uint8 layer) const { uint32 layerIndex; if (!GetLayerIndex(layer, &layerIndex)) return 0.0f; return (float)GetLayerValue(ix, iy, layerIndex) / 255.0f; } uint32 TerrainSection::GetIndexedBaseLayers(uint32 ix, uint32 iy, uint8 *outLayers, float *outLayerWeights, uint32 maxLayers) const { uint32 writtenLayers = 0; for (uint32 i = 0; i < m_nUsedLayers && writtenLayers < maxLayers; i++) { uint8 value = m_pLayerWeightValues[i * m_layerWeightValuesStride + iy * m_pointCount + ix]; if (value != 0) { outLayers[writtenLayers] = m_usedLayers[i]; outLayerWeights[writtenLayers] = (float)value / 255.0f; writtenLayers++; } } return writtenLayers; } uint8 TerrainSection::GetIndexedDominantBaseLayer(uint32 ix, uint32 iy) const { uint8 bestLayer = 0; uint8 bestValue = 0; for (uint32 i = 0; i < m_nUsedLayers; i++) { uint8 value = m_pLayerWeightValues[i * m_layerWeightValuesStride + iy * m_pointCount + ix]; if (value != 0 && value > bestValue) { bestLayer = m_usedLayers[i]; bestValue = value; } } return bestLayer; } void TerrainSection::AddIndexedBaseLayerWeight(uint32 ix, uint32 iy, uint8 layer, float amount) { DebugAssert(layer < TERRAIN_MAX_LAYERS); uint32 layerIndex; if (!GetLayerIndex(layer, &layerIndex)) layerIndex = AddLayer(layer); uint32 changeLayerIndices[TERRAIN_MAX_LAYERS]; float changeLayerWeights[TERRAIN_MAX_LAYERS]; uint32 changeLayerCount = 0; // collect layers for this texel for (uint32 i = 0; i < m_nUsedLayers; i++) { if (i != layerIndex) { uint8 value = m_pLayerWeightValues[i * m_layerWeightValuesStride + iy * m_pointCount + ix]; if (value != 0) { changeLayerIndices[changeLayerCount] = i; changeLayerWeights[changeLayerCount] = (float)value / 255.0f; changeLayerCount++; } } } // subtract the amount off the other layers if (changeLayerCount > 0) { float subtractAmount = amount / (float)changeLayerCount; for (uint32 i = 0; i < changeLayerCount; i++) { float value = changeLayerWeights[i] - subtractAmount; m_pLayerWeightValues[changeLayerIndices[i] * m_layerWeightValuesStride + iy * m_pointCount + ix] = (uint8)Math::Truncate(Math::Clamp(value * 255.0f, 0.0f, 255.0f)); } } // set it on the layer float value = ((float)m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix] / 255.0f) + amount; m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix] = (uint8)Math::Truncate(Math::Clamp(value * 255.0f, 0.0f, 255.0f)); m_changed = true; } void TerrainSection::SetIndexedBaseLayerWeight(uint32 ix, uint32 iy, uint8 layer, float weight) { DebugAssert(layer < TERRAIN_MAX_LAYERS); uint32 layerIndex; if (!GetLayerIndex(layer, &layerIndex)) layerIndex = AddLayer(layer); uint8 value = (uint8)Math::Truncate(Math::Clamp(weight * 255.0f, 0.0f, 255.0f)); if (m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix] == value) return; // update data m_pLayerWeightValues[layerIndex * m_layerWeightValuesStride + iy * m_pointCount + ix] = value; m_changed = true; } void TerrainSection::SetAndWeightIndexedBaseLayerWeight(uint32 ix, uint32 iy, uint8 layer, float weight) { DebugAssert(layer < TERRAIN_MAX_LAYERS && weight <= 1.0f); // retreive current weights bool hadThisLayer = (GetIndexedBaseLayerWeight(ix, iy, layer) != 0.0f); float currentWeights[TERRAIN_MAX_LAYERS]; uint8 currentLayers[TERRAIN_MAX_LAYERS]; uint32 layerCount = GetIndexedBaseLayers(ix, iy, currentLayers, currentWeights, TERRAIN_MAX_LAYERS); // get this layer's weight float currentWeight = GetIndexedBaseLayerWeight(ix, iy, layer); float diffWeight = currentWeight - weight; if ((hadThisLayer && layerCount > 1) || (!hadThisLayer && layerCount > 0)) { // fraction of available weight float diffPerLayer = diffWeight / (float)((hadThisLayer) ? (layerCount - 1) : (layerCount)); for (uint32 i = 0; i < layerCount; i++) { if (currentLayers[i] != layer) SetIndexedBaseLayerWeight(ix, iy, currentLayers[i], currentWeights[i] + diffPerLayer); } } // set layer weight SetIndexedBaseLayerWeight(ix, iy, layer, weight); } void TerrainSection::ClearIndexedBaseLayerWeights(uint32 ix, uint32 iy) { for (uint32 i = 0; i < m_nUsedLayers; i++) SetLayerValue(ix, iy, i, 0); } void TerrainSection::SetAllBaseLayerWeights(uint8 layer, float weight) { DebugAssert(layer < TERRAIN_MAX_LAYERS); uint32 layerIndex; if (!GetLayerIndex(layer, &layerIndex)) layerIndex = AddLayer(layer); uint8 value = (uint8)Math::Truncate(Math::Clamp(weight * 255.0f, 0.0f, 255.0f)); for (uint32 iy = 0; iy < m_pointCount; iy++) { for (uint32 ix = 0; ix < m_pointCount; ix++) { SetLayerValue(ix, iy, layerIndex, value); } } } void TerrainSection::ClearAllBaseLayerWeights() { Y_free(m_pLayerWeightValues); m_pLayerWeightValues = NULL; Y_memset(m_usedLayers, 0xFF, sizeof(m_usedLayers)); m_nUsedLayers = 0; m_changed = true; } */ <file_sep>/Engine/Dependancies/microprofile/src/microprofile.h #pragma once // This is free and unencumbered software released into the public domain. // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // For more information, please refer to <http://unlicense.org/> // // *********************************************************************** // // // // // Howto: // Call these functions from your code: // MicroProfileOnThreadCreate // MicroProfileMouseButton // MicroProfileMousePosition // MicroProfileModKey // MicroProfileFlip <-- Call this once per frame // MicroProfileDraw <-- Call this once per frame // MicroProfileToggleDisplayMode <-- Bind to a key to toggle profiling // MicroProfileTogglePause <-- Bind to a key to toggle pause // // Use these macros in your code in blocks you want to time: // // MICROPROFILE_DECLARE // MICROPROFILE_DEFINE // MICROPROFILE_DECLARE_GPU // MICROPROFILE_DEFINE_GPU // MICROPROFILE_SCOPE // MICROPROFILE_SCOPEI // MICROPROFILE_SCOPEGPU // MICROPROFILE_SCOPEGPUI // MICROPROFILE_META // // // Usage: // // { // MICROPROFILE_SCOPEI("GroupName", "TimerName", nColorRgb): // ..Code to be timed.. // } // // MICROPROFILE_DECLARE / MICROPROFILE_DEFINE allows defining groups in a shared place, to ensure sorting of the timers // // (in global scope) // MICROPROFILE_DEFINE(g_ProfileFisk, "Fisk", "Skalle", nSomeColorRgb); // // (in some other file) // MICROPROFILE_DECLARE(g_ProfileFisk); // // void foo(){ // MICROPROFILE_SCOPE(g_ProfileFisk); // } // // Once code is instrumented the gui is activeted by calling MicroProfileToggleDisplayMode or by clicking in the upper left corner of // the screen // // The following functions must be implemented before the profiler is usable // debug render: // void MicroProfileDrawText(int nX, int nY, uint32_t nColor, const char* pText, uint32_t nNumCharacters); // void MicroProfileDrawBox(int nX, int nY, int nX1, int nY1, uint32_t nColor, MicroProfileBoxType = MicroProfileBoxTypeFlat); // void MicroProfileDrawLine2D(uint32_t nVertices, float* pVertices, uint32_t nColor); // Gpu time stamps: (See below for d3d/opengl helper) // uint32_t MicroProfileGpuInsertTimeStamp(); // uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey); // uint64_t MicroProfileTicksPerSecondGpu(); // threading: // const char* MicroProfileGetThreadName(); Threadnames in detailed view // // Default implementations of Gpu timestamp functions: // Opengl: // in .c file where MICROPROFILE_IMPL is defined: // #define MICROPROFILE_GPU_TIMERS_GL // call MicroProfileGpuInitGL() on startup // D3D11: // in .c file where MICROPROFILE_IMPL is defined: // #define MICROPROFILE_GPU_TIMERS_D3D11 // call MICROPROFILE_GPU_TIMERS_D3D11(). Pass Device & ImmediateContext // // Limitations: // GPU timestamps can only be inserted from one thread. #ifndef MICROPROFILE_ENABLED #define MICROPROFILE_ENABLED 1 #endif #include <stdint.h> typedef uint64_t MicroProfileToken; typedef uint16_t MicroProfileGroupId; #if 0 == MICROPROFILE_ENABLED #define MICROPROFILE_DECLARE(var) #define MICROPROFILE_DEFINE(var, group, name, color) #define MICROPROFILE_REGISTER_GROUP(group, color, category) #define MICROPROFILE_DECLARE_GPU(var) #define MICROPROFILE_DEFINE_GPU(var, name, color) #define MICROPROFILE_SCOPE(var) do{}while(0) #define MICROPROFILE_SCOPEI(group, name, color) do{}while(0) #define MICROPROFILE_SCOPEGPU(var) do{}while(0) #define MICROPROFILE_SCOPEGPUI( name, color) do{}while(0) #define MICROPROFILE_META_CPU(name, count) #define MICROPROFILE_META_GPU(name, count) #define MICROPROFILE_FORCEENABLECPUGROUP(s) do{} while(0) #define MICROPROFILE_FORCEDISABLECPUGROUP(s) do{} while(0) #define MICROPROFILE_FORCEENABLEGPUGROUP(s) do{} while(0) #define MICROPROFILE_FORCEDISABLEGPUGROUP(s) do{} while(0) #define MICROPROFILE_SCOPE_TOKEN(token) #define MicroProfileGetTime(group, name) 0.f #define MicroProfileOnThreadCreate(foo) do{}while(0) #define MicroProfileFlip() do{}while(0) #define MicroProfileSetAggregateFrames(a) do{}while(0) #define MicroProfileGetAggregateFrames() 0 #define MicroProfileGetCurrentAggregateFrames() 0 #define MicroProfileTogglePause() do{}while(0) #define MicroProfileToggleAllGroups() do{} while(0) #define MicroProfileDumpTimers() do{}while(0) #define MicroProfileShutdown() do{}while(0) #define MicroProfileSetForceEnable(a) do{} while(0) #define MicroProfileGetForceEnable() false #define MicroProfileSetEnableAllGroups(a) do{} while(0) #define MicroProfileEnableCategory(a) do{} while(0) #define MicroProfileDisableCategory(a) do{} while(0) #define MicroProfileGetEnableAllGroups() false #define MicroProfileSetForceMetaCounters(a) #define MicroProfileGetForceMetaCounters() 0 #define MicroProfileEnableMetaCounter(c) do{}while(0) #define MicroProfileDisableMetaCounter(c) do{}while(0) #define MicroProfileDumpFile(html,csv) do{} while(0) #define MicroProfileWebServerPort() ((uint32_t)-1) #else #include <stdint.h> #include <string.h> #include <thread> #include <mutex> #include <atomic> #ifndef MICROPROFILE_API #define MICROPROFILE_API #endif MICROPROFILE_API int64_t MicroProfileTicksPerSecondCpu(); #if defined(__APPLE__) #include <mach/mach.h> #include <mach/mach_time.h> #include <unistd.h> #include <libkern/OSAtomic.h> #include <TargetConditionals.h> #if TARGET_OS_IPHONE #define MICROPROFILE_IOS #endif #define MP_TICK() mach_absolute_time() inline int64_t MicroProfileTicksPerSecondCpu() { static int64_t nTicksPerSecond = 0; if(nTicksPerSecond == 0) { mach_timebase_info_data_t sTimebaseInfo; mach_timebase_info(&sTimebaseInfo); nTicksPerSecond = 1000000000ll * sTimebaseInfo.denom / sTimebaseInfo.numer; } return nTicksPerSecond; } inline uint64_t MicroProfileGetCurrentThreadId() { uint64_t tid; pthread_threadid_np(pthread_self(), &tid); return tid; } #define MP_BREAK() __builtin_trap() #define MP_THREAD_LOCAL __thread #define MP_STRCASECMP strcasecmp #define MP_GETCURRENTTHREADID() MicroProfileGetCurrentThreadId() typedef uint64_t ThreadIdType; #elif defined(_WIN32) int64_t MicroProfileGetTick(); #define MP_TICK() MicroProfileGetTick() #define MP_BREAK() __debugbreak() #define MP_THREAD_LOCAL __declspec(thread) #define MP_STRCASECMP _stricmp #define MP_GETCURRENTTHREADID() GetCurrentThreadId() typedef uint32_t ThreadIdType; #elif defined(__linux__) #include <unistd.h> #include <time.h> inline int64_t MicroProfileTicksPerSecondCpu() { return 1000000000ll; } inline int64_t MicroProfileGetTick() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return 1000000000ll * ts.tv_sec + ts.tv_nsec; } #define MP_TICK() MicroProfileGetTick() #define MP_BREAK() __builtin_trap() #define MP_THREAD_LOCAL __thread #define MP_STRCASECMP strcasecmp #define MP_GETCURRENTTHREADID() (uint64_t)pthread_self() typedef uint64_t ThreadIdType; #endif #ifndef MP_GETCURRENTTHREADID #define MP_GETCURRENTTHREADID() 0 typedef uint32_t ThreadIdType; #endif #define MP_ASSERT(a) do{if(!(a)){MP_BREAK();} }while(0) #define MICROPROFILE_DECLARE(var) extern MicroProfileToken g_mp_##var #define MICROPROFILE_DEFINE(var, group, name, color) MicroProfileToken g_mp_##var = MicroProfileGetToken(group, name, color, MicroProfileTokenTypeCpu) #define MICROPROFILE_REGISTER_GROUP(group, category, color) MicroProfileRegisterGroup(group, category, color) #define MICROPROFILE_DECLARE_GPU(var) extern MicroProfileToken g_mp_##var #define MICROPROFILE_DEFINE_GPU(var, name, color) MicroProfileToken g_mp_##var = MicroProfileGetToken("GPU", name, color, MicroProfileTokenTypeGpu) #define MICROPROFILE_TOKEN_PASTE0(a, b) a ## b #define MICROPROFILE_TOKEN_PASTE(a, b) MICROPROFILE_TOKEN_PASTE0(a,b) #define MICROPROFILE_SCOPE(var) MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(g_mp_##var) #define MICROPROFILE_SCOPE_TOKEN(token) MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(token) #define MICROPROFILE_SCOPEI(group, name, color) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__) = MicroProfileGetToken(group, name, color, MicroProfileTokenTypeCpu); MicroProfileScopeHandler MICROPROFILE_TOKEN_PASTE(foo,__LINE__)( MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__)) #define MICROPROFILE_SCOPEGPU(var) MicroProfileScopeGpuHandler MICROPROFILE_TOKEN_PASTE(foo, __LINE__)(g_mp_##var) #define MICROPROFILE_SCOPEGPUI(name, color) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__) = MicroProfileGetToken("GPU", name, color, MicroProfileTokenTypeGpu); MicroProfileScopeGpuHandler MICROPROFILE_TOKEN_PASTE(foo,__LINE__)( MICROPROFILE_TOKEN_PASTE(g_mp,__LINE__)) #define MICROPROFILE_META_CPU(name, count) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__) = MicroProfileGetMetaToken(name); MicroProfileMetaUpdate(MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__), count, MicroProfileTokenTypeCpu) #define MICROPROFILE_META_GPU(name, count) static MicroProfileToken MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__) = MicroProfileGetMetaToken(name); MicroProfileMetaUpdate(MICROPROFILE_TOKEN_PASTE(g_mp_meta,__LINE__), count, MicroProfileTokenTypeGpu) #ifndef MICROPROFILE_USE_THREAD_NAME_CALLBACK #define MICROPROFILE_USE_THREAD_NAME_CALLBACK 0 #endif #ifndef MICROPROFILE_PER_THREAD_BUFFER_SIZE #define MICROPROFILE_PER_THREAD_BUFFER_SIZE (2048<<10) #endif #ifndef MICROPROFILE_MAX_FRAME_HISTORY #define MICROPROFILE_MAX_FRAME_HISTORY 512 #endif #ifndef MICROPROFILE_PRINTF #define MICROPROFILE_PRINTF printf #endif #ifndef MICROPROFILE_META_MAX #define MICROPROFILE_META_MAX 8 #endif #ifndef MICROPROFILE_WEBSERVER_PORT #define MICROPROFILE_WEBSERVER_PORT 1338 #endif #ifndef MICROPROFILE_WEBSERVER #define MICROPROFILE_WEBSERVER 1 #endif #ifndef MICROPROFILE_WEBSERVER_MAXFRAMES #define MICROPROFILE_WEBSERVER_MAXFRAMES 30 #endif #ifndef MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE #define MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE (16<<10) #endif #ifndef MICROPROFILE_GPU_TIMERS #define MICROPROFILE_GPU_TIMERS 1 #endif #ifndef MICROPROFILE_GPU_FRAME_DELAY #define MICROPROFILE_GPU_FRAME_DELAY 3 //must be > 0 #endif #ifndef MICROPROFILE_NAME_MAX_LEN #define MICROPROFILE_NAME_MAX_LEN 64 #endif #define MICROPROFILE_FORCEENABLECPUGROUP(s) MicroProfileForceEnableGroup(s, MicroProfileTokenTypeCpu) #define MICROPROFILE_FORCEDISABLECPUGROUP(s) MicroProfileForceDisableGroup(s, MicroProfileTokenTypeCpu) #define MICROPROFILE_FORCEENABLEGPUGROUP(s) MicroProfileForceEnableGroup(s, MicroProfileTokenTypeGpu) #define MICROPROFILE_FORCEDISABLEGPUGROUP(s) MicroProfileForceDisableGroup(s, MicroProfileTokenTypeGpu) #define MICROPROFILE_INVALID_TICK ((uint64_t)-1) #define MICROPROFILE_GROUP_MASK_ALL 0xffffffffffff #define MICROPROFILE_INVALID_TOKEN (uint64_t)-1 enum MicroProfileTokenType { MicroProfileTokenTypeCpu, MicroProfileTokenTypeGpu, }; enum MicroProfileBoxType { MicroProfileBoxTypeBar, MicroProfileBoxTypeFlat, }; struct MicroProfile; MICROPROFILE_API void MicroProfileInit(); MICROPROFILE_API void MicroProfileShutdown(); MICROPROFILE_API MicroProfileToken MicroProfileFindToken(const char* sGroup, const char* sName); MICROPROFILE_API MicroProfileToken MicroProfileGetToken(const char* sGroup, const char* sName, uint32_t nColor, MicroProfileTokenType Token = MicroProfileTokenTypeCpu); MICROPROFILE_API MicroProfileToken MicroProfileGetMetaToken(const char* pName); MICROPROFILE_API void MicroProfileMetaUpdate(MicroProfileToken, int nCount, MicroProfileTokenType eTokenType); MICROPROFILE_API uint64_t MicroProfileEnter(MicroProfileToken nToken); MICROPROFILE_API void MicroProfileLeave(MicroProfileToken nToken, uint64_t nTick); MICROPROFILE_API uint64_t MicroProfileGpuEnter(MicroProfileToken nToken); MICROPROFILE_API void MicroProfileGpuLeave(MicroProfileToken nToken, uint64_t nTick); inline uint16_t MicroProfileGetTimerIndex(MicroProfileToken t){ return (t&0xffff); } inline uint64_t MicroProfileGetGroupMask(MicroProfileToken t){ return ((t>>16)&MICROPROFILE_GROUP_MASK_ALL);} inline MicroProfileToken MicroProfileMakeToken(uint64_t nGroupMask, uint16_t nTimer){ return (nGroupMask<<16) | nTimer;} MICROPROFILE_API void MicroProfileFlip(); //! call once per frame. MICROPROFILE_API void MicroProfileTogglePause(); MICROPROFILE_API void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type); MICROPROFILE_API void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type); MICROPROFILE_API float MicroProfileGetTime(const char* pGroup, const char* pName); MICROPROFILE_API void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu); MICROPROFILE_API void MicroProfileOnThreadCreate(const char* pThreadName); //should be called from newly created threads MICROPROFILE_API void MicroProfileOnThreadExit(); //call on exit to reuse log MICROPROFILE_API void MicroProfileInitThreadLog(); MICROPROFILE_API void MicroProfileSetForceEnable(bool bForceEnable); MICROPROFILE_API bool MicroProfileGetForceEnable(); MICROPROFILE_API void MicroProfileSetEnableAllGroups(bool bEnable); MICROPROFILE_API void MicroProfileEnableCategory(const char* pCategory); MICROPROFILE_API void MicroProfileDisableCategory(const char* pCategory); MICROPROFILE_API bool MicroProfileGetEnableAllGroups(); MICROPROFILE_API void MicroProfileSetForceMetaCounters(bool bEnable); MICROPROFILE_API bool MicroProfileGetForceMetaCounters(); MICROPROFILE_API void MicroProfileEnableMetaCounter(const char* pMet); MICROPROFILE_API void MicroProfileDisableMetaCounter(const char* pMet); MICROPROFILE_API void MicroProfileSetAggregateFrames(int frames); MICROPROFILE_API int MicroProfileGetAggregateFrames(); MICROPROFILE_API int MicroProfileGetCurrentAggregateFrames(); MICROPROFILE_API MicroProfile* MicroProfileGet(); MICROPROFILE_API void MicroProfileGetRange(uint32_t nPut, uint32_t nGet, uint32_t nRange[2][2]); MICROPROFILE_API std::recursive_mutex& MicroProfileGetMutex(); MICROPROFILE_API void MicroProfileStartContextSwitchTrace(); MICROPROFILE_API void MicroProfileStopContextSwitchTrace(); MICROPROFILE_API bool MicroProfileIsLocalThread(uint32_t nThreadId); #if MICROPROFILE_WEBSERVER MICROPROFILE_API void MicroProfileDumpFile(const char* pHtml, const char* pCsv); MICROPROFILE_API uint32_t MicroProfileWebServerPort(); #else #define MicroProfileDumpFile(c) do{} while(0) #define MicroProfileWebServerPort() ((uint32_t)-1) #endif #if MICROPROFILE_GPU_TIMERS MICROPROFILE_API uint32_t MicroProfileGpuInsertTimeStamp(); MICROPROFILE_API uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey); MICROPROFILE_API uint64_t MicroProfileTicksPerSecondGpu(); #else #define MicroProfileGpuInsertTimeStamp() 1 #define MicroProfileGpuGetTimeStamp(a) 0 #define MicroProfileTicksPerSecondGpu() 1 #endif #if MICROPROFILE_GPU_TIMERS_D3D11 #define MICROPROFILE_D3D_MAX_QUERIES (8<<10) MICROPROFILE_API void MicroProfileGpuInitD3D11(void* pDevice, void* pDeviceContext); #endif #if MICROPROFILE_GPU_TIMERS_GL #define MICROPROFILE_GL_MAX_QUERIES (8<<10) MICROPROFILE_API void MicroProfileGpuInitGL(); #endif #if MICROPROFILE_USE_THREAD_NAME_CALLBACK MICROPROFILE_API const char* MicroProfileGetThreadName(); #else #define MicroProfileGetThreadName() "<implement MicroProfileGetThreadName to get threadnames>" #endif #if !defined(MICROPROFILE_THREAD_NAME_FROM_ID) #define MICROPROFILE_THREAD_NAME_FROM_ID(a) "" #endif struct MicroProfileScopeHandler { MicroProfileToken nToken; uint64_t nTick; MicroProfileScopeHandler(MicroProfileToken Token):nToken(Token) { nTick = MicroProfileEnter(nToken); } ~MicroProfileScopeHandler() { MicroProfileLeave(nToken, nTick); } }; struct MicroProfileScopeGpuHandler { MicroProfileToken nToken; uint64_t nTick; MicroProfileScopeGpuHandler(MicroProfileToken Token):nToken(Token) { nTick = MicroProfileGpuEnter(nToken); } ~MicroProfileScopeGpuHandler() { MicroProfileGpuLeave(nToken, nTick); } }; #define MICROPROFILE_MAX_TIMERS 1024 #define MICROPROFILE_MAX_GROUPS 48 //dont bump! no. of bits used it bitmask #define MICROPROFILE_MAX_CATEGORIES 16 #define MICROPROFILE_MAX_GRAPHS 5 #define MICROPROFILE_GRAPH_HISTORY 128 #define MICROPROFILE_BUFFER_SIZE ((MICROPROFILE_PER_THREAD_BUFFER_SIZE)/sizeof(MicroProfileLogEntry)) #define MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS 256 #define MICROPROFILE_STACK_MAX 32 //#define MICROPROFILE_MAX_PRESETS 5 #define MICROPROFILE_ANIM_DELAY_PRC 0.5f #define MICROPROFILE_GAP_TIME 50 //extra ms to fetch to close timers from earlier frames #ifndef MICROPROFILE_MAX_THREADS #define MICROPROFILE_MAX_THREADS 32 #endif #ifndef MICROPROFILE_UNPACK_RED #define MICROPROFILE_UNPACK_RED(c) ((c)>>16) #endif #ifndef MICROPROFILE_UNPACK_GREEN #define MICROPROFILE_UNPACK_GREEN(c) ((c)>>8) #endif #ifndef MICROPROFILE_UNPACK_BLUE #define MICROPROFILE_UNPACK_BLUE(c) ((c)) #endif #ifndef MICROPROFILE_DEFAULT_PRESET #define MICROPROFILE_DEFAULT_PRESET "Default" #endif #ifndef MICROPROFILE_CONTEXT_SWITCH_TRACE #if defined(_WIN32) #define MICROPROFILE_CONTEXT_SWITCH_TRACE 1 #elif defined(__APPLE__) #define MICROPROFILE_CONTEXT_SWITCH_TRACE 0 //disabled until dtrace script is working. #else #define MICROPROFILE_CONTEXT_SWITCH_TRACE 0 #endif #endif #if MICROPROFILE_CONTEXT_SWITCH_TRACE #define MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE (128*1024) //2mb with 16 byte entry size #else #define MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE (1) #endif #ifndef MICROPROFILE_MINIZ #define MICROPROFILE_MINIZ 0 #endif #ifdef _WIN32 #include <basetsd.h> typedef UINT_PTR MpSocket; #else typedef int MpSocket; #endif #if defined(__APPLE__) || defined(__linux__) typedef pthread_t MicroProfileThread; #elif defined(_WIN32) typedef HANDLE MicroProfileThread; #else typedef std::thread* MicroProfileThread; #endif enum MicroProfileDrawMask { MP_DRAW_OFF = 0x0, MP_DRAW_BARS = 0x1, MP_DRAW_DETAILED = 0x2, MP_DRAW_HIDDEN = 0x3, }; enum MicroProfileDrawBarsMask { MP_DRAW_TIMERS = 0x1, MP_DRAW_AVERAGE = 0x2, MP_DRAW_MAX = 0x4, MP_DRAW_CALL_COUNT = 0x8, MP_DRAW_TIMERS_EXCLUSIVE = 0x10, MP_DRAW_AVERAGE_EXCLUSIVE = 0x20, MP_DRAW_MAX_EXCLUSIVE = 0x40, MP_DRAW_META_FIRST = 0x80, MP_DRAW_ALL = 0xffffffff, }; typedef uint64_t MicroProfileLogEntry; struct MicroProfileTimer { uint64_t nTicks; uint32_t nCount; }; struct MicroProfileCategory { char pName[MICROPROFILE_NAME_MAX_LEN]; uint64_t nGroupMask; }; struct MicroProfileGroupInfo { char pName[MICROPROFILE_NAME_MAX_LEN]; uint32_t nNameLen; uint32_t nGroupIndex; uint32_t nNumTimers; uint32_t nMaxTimerNameLen; uint32_t nColor; uint32_t nCategory; MicroProfileTokenType Type; }; struct MicroProfileTimerInfo { MicroProfileToken nToken; uint32_t nTimerIndex; uint32_t nGroupIndex; char pName[MICROPROFILE_NAME_MAX_LEN]; uint32_t nNameLen; uint32_t nColor; bool bGraph; }; struct MicroProfileGraphState { int64_t nHistory[MICROPROFILE_GRAPH_HISTORY]; MicroProfileToken nToken; int32_t nKey; }; struct MicroProfileContextSwitch { ThreadIdType nThreadOut; ThreadIdType nThreadIn; int64_t nCpu : 8; int64_t nTicks : 56; }; struct MicroProfileFrameState { int64_t nFrameStartCpu; int64_t nFrameStartGpu; uint32_t nLogStart[MICROPROFILE_MAX_THREADS]; }; struct MicroProfileThreadLog { MicroProfileLogEntry Log[MICROPROFILE_BUFFER_SIZE]; std::atomic<uint32_t> nPut; std::atomic<uint32_t> nGet; uint32_t nActive; uint32_t nGpu; ThreadIdType nThreadId; uint32_t nStack[MICROPROFILE_STACK_MAX]; int64_t nChildTickStack[MICROPROFILE_STACK_MAX]; uint32_t nStackPos; uint8_t nGroupStackPos[MICROPROFILE_MAX_GROUPS]; int64_t nGroupTicks[MICROPROFILE_MAX_GROUPS]; int64_t nAggregateGroupTicks[MICROPROFILE_MAX_GROUPS]; enum { THREAD_MAX_LEN = 64, }; char ThreadName[64]; int nFreeListNext; }; #if MICROPROFILE_GPU_TIMERS_D3D11 struct MicroProfileD3D11Frame { uint32_t m_nQueryStart; uint32_t m_nQueryCount; uint32_t m_nRateQueryStarted; void* m_pRateQuery; }; struct MicroProfileGpuTimerState { uint32_t bInitialized; void* m_pDevice; void* m_pDeviceContext; void* m_pQueries[MICROPROFILE_D3D_MAX_QUERIES]; int64_t m_nQueryResults[MICROPROFILE_D3D_MAX_QUERIES]; uint32_t m_nQueryPut; uint32_t m_nQueryGet; uint32_t m_nQueryFrame; int64_t m_nQueryFrequency; MicroProfileD3D11Frame m_QueryFrames[MICROPROFILE_GPU_FRAME_DELAY]; }; #elif MICROPROFILE_GPU_TIMERS_GL struct MicroProfileGpuTimerState { uint32_t GLTimers[MICROPROFILE_GL_MAX_QUERIES]; uint32_t GLTimerPos; }; #else struct MicroProfileGpuTimerState{}; #endif struct MicroProfile { uint32_t nTotalTimers; uint32_t nGroupCount; uint32_t nCategoryCount; uint32_t nAggregateClear; uint32_t nAggregateFlip; uint32_t nAggregateFlipCount; uint32_t nAggregateFrames; uint64_t nAggregateFlipTick; uint32_t nDisplay; uint32_t nBars; uint64_t nActiveGroup; uint32_t nActiveBars; uint64_t nForceGroup; uint32_t nForceEnable; uint32_t nForceMetaCounters; uint64_t nActiveGroupWanted; uint32_t nAllGroupsWanted; uint32_t nAllThreadsWanted; uint32_t nOverflow; uint64_t nGroupMask; uint32_t nRunning; uint32_t nToggleRunning; uint32_t nMaxGroupSize; uint32_t nDumpFileNextFrame; uint32_t nAutoClearFrames; char HtmlDumpPath[512]; char CsvDumpPath[512]; int64_t nPauseTicks; float fReferenceTime; float fRcpReferenceTime; MicroProfileCategory CategoryInfo[MICROPROFILE_MAX_CATEGORIES]; MicroProfileGroupInfo GroupInfo[MICROPROFILE_MAX_GROUPS]; MicroProfileTimerInfo TimerInfo[MICROPROFILE_MAX_TIMERS]; uint8_t TimerToGroup[MICROPROFILE_MAX_TIMERS]; MicroProfileTimer AccumTimers[MICROPROFILE_MAX_TIMERS]; uint64_t AccumMaxTimers[MICROPROFILE_MAX_TIMERS]; uint64_t AccumTimersExclusive[MICROPROFILE_MAX_TIMERS]; uint64_t AccumMaxTimersExclusive[MICROPROFILE_MAX_TIMERS]; MicroProfileTimer Frame[MICROPROFILE_MAX_TIMERS]; uint64_t FrameExclusive[MICROPROFILE_MAX_TIMERS]; MicroProfileTimer Aggregate[MICROPROFILE_MAX_TIMERS]; uint64_t AggregateMax[MICROPROFILE_MAX_TIMERS]; uint64_t AggregateExclusive[MICROPROFILE_MAX_TIMERS]; uint64_t AggregateMaxExclusive[MICROPROFILE_MAX_TIMERS]; uint64_t FrameGroup[MICROPROFILE_MAX_GROUPS]; uint64_t AccumGroup[MICROPROFILE_MAX_GROUPS]; uint64_t AccumGroupMax[MICROPROFILE_MAX_GROUPS]; uint64_t AggregateGroup[MICROPROFILE_MAX_GROUPS]; uint64_t AggregateGroupMax[MICROPROFILE_MAX_GROUPS]; struct { uint64_t nCounters[MICROPROFILE_MAX_TIMERS]; uint64_t nAccum[MICROPROFILE_MAX_TIMERS]; uint64_t nAccumMax[MICROPROFILE_MAX_TIMERS]; uint64_t nAggregate[MICROPROFILE_MAX_TIMERS]; uint64_t nAggregateMax[MICROPROFILE_MAX_TIMERS]; uint64_t nSum; uint64_t nSumAccum; uint64_t nSumAccumMax; uint64_t nSumAggregate; uint64_t nSumAggregateMax; const char* pName; } MetaCounters[MICROPROFILE_META_MAX]; MicroProfileGraphState Graph[MICROPROFILE_MAX_GRAPHS]; uint32_t nGraphPut; uint32_t nThreadActive[MICROPROFILE_MAX_THREADS]; MicroProfileThreadLog* Pool[MICROPROFILE_MAX_THREADS]; uint32_t nNumLogs; uint32_t nMemUsage; int nFreeListHead; uint32_t nFrameCurrent; uint32_t nFrameCurrentIndex; uint32_t nFramePut; uint64_t nFramePutIndex; MicroProfileFrameState Frames[MICROPROFILE_MAX_FRAME_HISTORY]; uint64_t nFlipTicks; uint64_t nFlipAggregate; uint64_t nFlipMax; uint64_t nFlipAggregateDisplay; uint64_t nFlipMaxDisplay; MicroProfileThread ContextSwitchThread; bool bContextSwitchRunning; bool bContextSwitchStop; bool bContextSwitchAllThreads; bool bContextSwitchNoBars; uint32_t nContextSwitchUsage; uint32_t nContextSwitchLastPut; int64_t nContextSwitchHoverTickIn; int64_t nContextSwitchHoverTickOut; uint32_t nContextSwitchHoverThread; uint32_t nContextSwitchHoverThreadBefore; uint32_t nContextSwitchHoverThreadAfter; uint8_t nContextSwitchHoverCpu; uint8_t nContextSwitchHoverCpuNext; uint32_t nContextSwitchPut; MicroProfileContextSwitch ContextSwitch[MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE]; MpSocket ListenerSocket; uint32_t nWebServerPort; char WebServerBuffer[MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE]; uint32_t WebServerPut; uint64_t nWebServerDataSent; MicroProfileGpuTimerState GPU; }; #define MP_LOG_TICK_MASK 0x0000ffffffffffff #define MP_LOG_INDEX_MASK 0x3fff000000000000 #define MP_LOG_BEGIN_MASK 0xc000000000000000 #define MP_LOG_META 0x2 #define MP_LOG_ENTER 0x1 #define MP_LOG_LEAVE 0x0 inline int MicroProfileLogType(MicroProfileLogEntry Index) { return ((MP_LOG_BEGIN_MASK & Index)>>62) & 0x3; } inline uint64_t MicroProfileLogTimerIndex(MicroProfileLogEntry Index) { return (0x3fff&(Index>>48)); } inline MicroProfileLogEntry MicroProfileMakeLogIndex(uint64_t nBegin, MicroProfileToken nToken, int64_t nTick) { MicroProfileLogEntry Entry = (nBegin<<62) | ((0x3fff&nToken)<<48) | (MP_LOG_TICK_MASK&nTick); int t = MicroProfileLogType(Entry); uint64_t nTimerIndex = MicroProfileLogTimerIndex(Entry); MP_ASSERT(t == nBegin); MP_ASSERT(nTimerIndex == (nToken&0x3fff)); return Entry; } inline int64_t MicroProfileLogTickDifference(MicroProfileLogEntry Start, MicroProfileLogEntry End) { uint64_t nStart = Start; uint64_t nEnd = End; int64_t nDifference = ((nEnd<<16) - (nStart<<16)); return nDifference >> 16; } inline int64_t MicroProfileLogGetTick(MicroProfileLogEntry e) { return MP_LOG_TICK_MASK & e; } inline int64_t MicroProfileLogSetTick(MicroProfileLogEntry e, int64_t nTick) { return (MP_LOG_TICK_MASK & nTick) | (e & ~MP_LOG_TICK_MASK); } template<typename T> T MicroProfileMin(T a, T b) { return a < b ? a : b; } template<typename T> T MicroProfileMax(T a, T b) { return a > b ? a : b; } inline int64_t MicroProfileMsToTick(float fMs, int64_t nTicksPerSecond) { return (int64_t)(fMs*0.001f*nTicksPerSecond); } inline float MicroProfileTickToMsMultiplier(int64_t nTicksPerSecond) { return 1000.f / nTicksPerSecond; } inline uint16_t MicroProfileGetGroupIndex(MicroProfileToken t) { return (uint16_t)MicroProfileGet()->TimerToGroup[MicroProfileGetTimerIndex(t)]; } #ifdef MICROPROFILE_IMPL #ifdef _WIN32 #include <windows.h> #define snprintf _snprintf #pragma warning(push) #pragma warning(disable: 4244) int64_t MicroProfileTicksPerSecondCpu() { static int64_t nTicksPerSecond = 0; if(nTicksPerSecond == 0) { QueryPerformanceFrequency((LARGE_INTEGER*)&nTicksPerSecond); } return nTicksPerSecond; } int64_t MicroProfileGetTick() { int64_t ticks; QueryPerformanceCounter((LARGE_INTEGER*)&ticks); return ticks; } #endif #if MICROPROFILE_WEBSERVER #ifdef _WIN32 #define MP_INVALID_SOCKET(f) (f == INVALID_SOCKET) #endif #if defined(__APPLE__) #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #define MP_INVALID_SOCKET(f) (f < 0) #endif typedef void* (*MicroProfileThreadFunc)(void*); #if defined(__APPLE__) || defined(__linux__) typedef pthread_t MicroProfileThread; void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func) { pthread_attr_t Attr; int r = pthread_attr_init(&Attr); MP_ASSERT(r == 0); pthread_create(pThread, &Attr, Func, 0); } void MicroProfileThreadJoin(MicroProfileThread* pThread) { int r = pthread_join(*pThread, 0); MP_ASSERT(r == 0); } #elif defined(_WIN32) typedef HANDLE MicroProfileThread; DWORD _stdcall ThreadTrampoline(void* pFunc) { MicroProfileThreadFunc F = (MicroProfileThreadFunc)pFunc; return (uint32_t)F(0); } void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func) { *pThread = CreateThread(0, 0, ThreadTrampoline, Func, 0, 0); } void MicroProfileThreadJoin(MicroProfileThread* pThread) { WaitForSingleObject(*pThread, INFINITE); CloseHandle(*pThread); } #else #include <thread> typedef std::thread* MicroProfileThread; inline void MicroProfileThreadStart(MicroProfileThread* pThread, MicroProfileThreadFunc Func) { *pThread = new std::thread(Func, nullptr); } inline void MicroProfileThreadJoin(MicroProfileThread* pThread) { (*pThread)->join(); delete *pThread; } #endif void MicroProfileWebServerStart(); void MicroProfileWebServerStop(); bool MicroProfileWebServerUpdate(); void MicroProfileDumpToFile(); #else #define MicroProfileWebServerStart() do{}while(0) #define MicroProfileWebServerStop() do{}while(0) #define MicroProfileWebServerUpdate() false #define MicroProfileDumpToFile() do{} while(0) #endif #if MICROPROFILE_GPU_TIMERS_D3D11 void MicroProfileGpuFlip(); void MicroProfileGpuShutdown(); #else #define MicroProfileGpuFlip() do{}while(0) #define MicroProfileGpuShutdown() do{}while(0) #endif #include <stdlib.h> #include <stdio.h> #include <math.h> #include <algorithm> #ifndef MICROPROFILE_DEBUG #define MICROPROFILE_DEBUG 0 #endif #define S g_MicroProfile MicroProfile g_MicroProfile; MicroProfileThreadLog* g_MicroProfileGpuLog = 0; #ifdef MICROPROFILE_IOS // iOS doesn't support __thread static pthread_key_t g_MicroProfileThreadLogKey; static pthread_once_t g_MicroProfileThreadLogKeyOnce = PTHREAD_ONCE_INIT; static void MicroProfileCreateThreadLogKey() { pthread_key_create(&g_MicroProfileThreadLogKey, NULL); } #else MP_THREAD_LOCAL MicroProfileThreadLog* g_MicroProfileThreadLog = 0; #endif static bool g_bUseLock = false; /// This is used because windows does not support using mutexes under dll init(which is where global initialization is handled) MICROPROFILE_DEFINE(g_MicroProfileFlip, "MicroProfile", "MicroProfileFlip", 0x3355ee); MICROPROFILE_DEFINE(g_MicroProfileThreadLoop, "MicroProfile", "ThreadLoop", 0x3355ee); MICROPROFILE_DEFINE(g_MicroProfileClear, "MicroProfile", "Clear", 0x3355ee); MICROPROFILE_DEFINE(g_MicroProfileAccumulate, "MicroProfile", "Accumulate", 0x3355ee); MICROPROFILE_DEFINE(g_MicroProfileContextSwitchSearch,"MicroProfile", "ContextSwitchSearch", 0xDD7300); inline std::recursive_mutex& MicroProfileMutex() { static std::recursive_mutex Mutex; return Mutex; } std::recursive_mutex& MicroProfileGetMutex() { return MicroProfileMutex(); } MICROPROFILE_API MicroProfile* MicroProfileGet() { return &g_MicroProfile; } MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName); void MicroProfileInit() { std::recursive_mutex& mutex = MicroProfileMutex(); bool bUseLock = g_bUseLock; if(bUseLock) mutex.lock(); static bool bOnce = true; if(bOnce) { S.nMemUsage += sizeof(S); bOnce = false; memset(&S, 0, sizeof(S)); for(int i = 0; i < MICROPROFILE_MAX_GROUPS; ++i) { S.GroupInfo[i].pName[0] = '\0'; } for(int i = 0; i < MICROPROFILE_MAX_CATEGORIES; ++i) { S.CategoryInfo[i].pName[0] = '\0'; S.CategoryInfo[i].nGroupMask = 0; } strcpy(&S.CategoryInfo[0].pName[0], "default"); S.nCategoryCount = 1; for(int i = 0; i < MICROPROFILE_MAX_TIMERS; ++i) { S.TimerInfo[i].pName[0] = '\0'; } S.nGroupCount = 0; S.nAggregateFlipTick = MP_TICK(); S.nActiveGroup = 0; S.nActiveBars = 0; S.nForceGroup = 0; S.nAllGroupsWanted = 0; S.nActiveGroupWanted = 0; S.nAllThreadsWanted = 1; S.nAggregateFlip = 0; S.nTotalTimers = 0; for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i) { S.Graph[i].nToken = MICROPROFILE_INVALID_TOKEN; } S.nRunning = 1; S.fReferenceTime = 33.33f; S.fRcpReferenceTime = 1.f / S.fReferenceTime; S.nFreeListHead = -1; int64_t nTick = MP_TICK(); for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i) { S.Frames[i].nFrameStartCpu = nTick; S.Frames[i].nFrameStartGpu = -1; } MicroProfileThreadLog* pGpu = MicroProfileCreateThreadLog("GPU"); g_MicroProfileGpuLog = pGpu; MP_ASSERT(S.Pool[0] == pGpu); pGpu->nGpu = 1; pGpu->nThreadId = 0; S.nWebServerDataSent = (uint64_t)-1; } if(bUseLock) mutex.unlock(); } void MicroProfileShutdown() { std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); MicroProfileWebServerStop(); MicroProfileStopContextSwitchTrace(); MicroProfileGpuShutdown(); } #ifdef MICROPROFILE_IOS inline MicroProfileThreadLog* MicroProfileGetThreadLog() { pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey); return (MicroProfileThreadLog*)pthread_getspecific(g_MicroProfileThreadLogKey); } inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog) { pthread_once(&g_MicroProfileThreadLogKeyOnce, MicroProfileCreateThreadLogKey); pthread_setspecific(g_MicroProfileThreadLogKey, pLog); } #else MicroProfileThreadLog* MicroProfileGetThreadLog() { return g_MicroProfileThreadLog; } inline void MicroProfileSetThreadLog(MicroProfileThreadLog* pLog) { g_MicroProfileThreadLog = pLog; } #endif MicroProfileThreadLog* MicroProfileCreateThreadLog(const char* pName) { MicroProfileThreadLog* pLog = 0; if(S.nFreeListHead != -1) { pLog = S.Pool[S.nFreeListHead]; MP_ASSERT(pLog->nPut.load() == 0); MP_ASSERT(pLog->nGet.load() == 0); S.nFreeListHead = S.Pool[S.nFreeListHead]->nFreeListNext; } else { pLog = new MicroProfileThreadLog; S.nMemUsage += sizeof(MicroProfileThreadLog); S.Pool[S.nNumLogs++] = pLog; } memset(pLog, 0, sizeof(*pLog)); int len = (int)strlen(pName); int maxlen = sizeof(pLog->ThreadName)-1; len = len < maxlen ? len : maxlen; memcpy(&pLog->ThreadName[0], pName, len); pLog->ThreadName[len] = '\0'; pLog->nThreadId = MP_GETCURRENTTHREADID(); pLog->nFreeListNext = -1; pLog->nActive = 1; return pLog; } void MicroProfileOnThreadCreate(const char* pThreadName) { g_bUseLock = true; MicroProfileInit(); std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); MP_ASSERT(MicroProfileGetThreadLog() == 0); MicroProfileThreadLog* pLog = MicroProfileCreateThreadLog(pThreadName ? pThreadName : MicroProfileGetThreadName()); MP_ASSERT(pLog); MicroProfileSetThreadLog(pLog); } void MicroProfileOnThreadExit() { std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); MicroProfileThreadLog* pLog = MicroProfileGetThreadLog(); if(pLog) { int32_t nLogIndex = -1; for(int i = 0; i < MICROPROFILE_MAX_THREADS; ++i) { if(pLog == S.Pool[i]) { nLogIndex = i; break; } } MP_ASSERT(nLogIndex < MICROPROFILE_MAX_THREADS && nLogIndex > 0); pLog->nFreeListNext = S.nFreeListHead; pLog->nActive = 0; pLog->nPut.store(0); pLog->nGet.store(0); S.nFreeListHead = nLogIndex; for(int i = 0; i < MICROPROFILE_MAX_FRAME_HISTORY; ++i) { S.Frames[i].nLogStart[nLogIndex] = 0; } memset(pLog->nGroupStackPos, 0, sizeof(pLog->nGroupStackPos)); memset(pLog->nGroupTicks, 0, sizeof(pLog->nGroupTicks)); } } void MicroProfileInitThreadLog() { MicroProfileOnThreadCreate(nullptr); } struct MicroProfileScopeLock { bool bUseLock; std::recursive_mutex& m; MicroProfileScopeLock(std::recursive_mutex& m) : bUseLock(g_bUseLock), m(m) { if(bUseLock) m.lock(); } ~MicroProfileScopeLock() { if(bUseLock) m.unlock(); } }; MicroProfileToken MicroProfileFindToken(const char* pGroup, const char* pName) { MicroProfileInit(); MicroProfileScopeLock L(MicroProfileMutex()); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { if(!MP_STRCASECMP(pName, S.TimerInfo[i].pName) && !MP_STRCASECMP(pGroup, S.GroupInfo[S.TimerToGroup[i]].pName)) { return S.TimerInfo[i].nToken; } } return MICROPROFILE_INVALID_TOKEN; } uint16_t MicroProfileGetGroup(const char* pGroup, MicroProfileTokenType Type) { for(uint32_t i = 0; i < S.nGroupCount; ++i) { if(!MP_STRCASECMP(pGroup, S.GroupInfo[i].pName)) { return i; } } uint16_t nGroupIndex = 0xffff; uint32_t nLen = (uint32_t)strlen(pGroup); if(nLen > MICROPROFILE_NAME_MAX_LEN-1) nLen = MICROPROFILE_NAME_MAX_LEN-1; memcpy(&S.GroupInfo[S.nGroupCount].pName[0], pGroup, nLen); S.GroupInfo[S.nGroupCount].pName[nLen] = '\0'; S.GroupInfo[S.nGroupCount].nNameLen = nLen; S.GroupInfo[S.nGroupCount].nNumTimers = 0; S.GroupInfo[S.nGroupCount].nGroupIndex = S.nGroupCount; S.GroupInfo[S.nGroupCount].Type = Type; S.GroupInfo[S.nGroupCount].nMaxTimerNameLen = 0; S.GroupInfo[S.nGroupCount].nColor = 0x88888888; S.GroupInfo[S.nGroupCount].nCategory = 0; S.CategoryInfo[0].nGroupMask |= (1ll << (uint64_t)S.nGroupCount); nGroupIndex = S.nGroupCount++; S.nGroupMask = (S.nGroupMask<<1)|1; MP_ASSERT(nGroupIndex < MICROPROFILE_MAX_GROUPS); return nGroupIndex; } void MicroProfileRegisterGroup(const char* pGroup, const char* pCategory, uint32_t nColor) { int nCategoryIndex = -1; for(uint32_t i = 0; i < S.nCategoryCount; ++i) { if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName)) { nCategoryIndex = (int)i; break; } } if(-1 == nCategoryIndex && S.nCategoryCount < MICROPROFILE_MAX_CATEGORIES) { MP_ASSERT(S.CategoryInfo[S.nCategoryCount].pName[0] == '\0'); nCategoryIndex = (int)S.nCategoryCount++; uint32_t nLen = (uint32_t)strlen(pCategory); if(nLen > MICROPROFILE_NAME_MAX_LEN-1) nLen = MICROPROFILE_NAME_MAX_LEN-1; memcpy(&S.CategoryInfo[nCategoryIndex].pName[0], pCategory, nLen); S.CategoryInfo[nCategoryIndex].pName[nLen] = '\0'; } uint16_t nGroup = MicroProfileGetGroup(pGroup, 0 != MP_STRCASECMP(pGroup, "gpu")?MicroProfileTokenTypeCpu : MicroProfileTokenTypeGpu); S.GroupInfo[nGroup].nColor = nColor; if(nCategoryIndex >= 0) { uint64_t nBit = 1ll << nGroup; uint32_t nOldCategory = S.GroupInfo[nGroup].nCategory; S.CategoryInfo[nOldCategory].nGroupMask &= ~nBit; S.CategoryInfo[nCategoryIndex].nGroupMask |= nBit; S.GroupInfo[nGroup].nCategory = nCategoryIndex; } } MicroProfileToken MicroProfileGetToken(const char* pGroup, const char* pName, uint32_t nColor, MicroProfileTokenType Type) { MicroProfileInit(); MicroProfileScopeLock L(MicroProfileMutex()); MicroProfileToken ret = MicroProfileFindToken(pGroup, pName); if(ret != MICROPROFILE_INVALID_TOKEN) return ret; uint16_t nGroupIndex = MicroProfileGetGroup(pGroup, Type); uint16_t nTimerIndex = (uint16_t)(S.nTotalTimers++); uint64_t nGroupMask = 1ll << nGroupIndex; MicroProfileToken nToken = MicroProfileMakeToken(nGroupMask, nTimerIndex); S.GroupInfo[nGroupIndex].nNumTimers++; S.GroupInfo[nGroupIndex].nMaxTimerNameLen = MicroProfileMax(S.GroupInfo[nGroupIndex].nMaxTimerNameLen, (uint32_t)strlen(pName)); MP_ASSERT(S.GroupInfo[nGroupIndex].Type == Type); //dont mix cpu & gpu timers in the same group S.nMaxGroupSize = MicroProfileMax(S.nMaxGroupSize, S.GroupInfo[nGroupIndex].nNumTimers); S.TimerInfo[nTimerIndex].nToken = nToken; uint32_t nLen = (uint32_t)strlen(pName); if(nLen > MICROPROFILE_NAME_MAX_LEN-1) nLen = MICROPROFILE_NAME_MAX_LEN-1; memcpy(&S.TimerInfo[nTimerIndex].pName, pName, nLen); S.TimerInfo[nTimerIndex].pName[nLen] = '\0'; S.TimerInfo[nTimerIndex].nNameLen = nLen; S.TimerInfo[nTimerIndex].nColor = nColor&0xffffff; S.TimerInfo[nTimerIndex].nGroupIndex = nGroupIndex; S.TimerInfo[nTimerIndex].nTimerIndex = nTimerIndex; S.TimerToGroup[nTimerIndex] = nGroupIndex; return nToken; } MicroProfileToken MicroProfileGetMetaToken(const char* pName) { MicroProfileInit(); MicroProfileScopeLock L(MicroProfileMutex()); for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i) { if(!S.MetaCounters[i].pName) { S.MetaCounters[i].pName = pName; return i; } else if(!MP_STRCASECMP(pName, S.MetaCounters[i].pName)) { return i; } } MP_ASSERT(0);//out of slots, increase MICROPROFILE_META_MAX return (MicroProfileToken)-1; } inline void MicroProfileLogPut(MicroProfileToken nToken_, uint64_t nTick, uint64_t nBegin, MicroProfileThreadLog* pLog) { MP_ASSERT(pLog != 0); //this assert is hit if MicroProfileOnCreateThread is not called MP_ASSERT(pLog->nActive); uint32_t nPos = pLog->nPut.load(std::memory_order_relaxed); uint32_t nNextPos = (nPos+1) % MICROPROFILE_BUFFER_SIZE; if(nNextPos == pLog->nGet.load(std::memory_order_relaxed)) { S.nOverflow = 100; } else { pLog->Log[nPos] = MicroProfileMakeLogIndex(nBegin, nToken_, nTick); pLog->nPut.store(nNextPos, std::memory_order_release); } } uint64_t MicroProfileEnter(MicroProfileToken nToken_) { if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup) { if(!MicroProfileGetThreadLog()) { MicroProfileInitThreadLog(); } uint64_t nTick = MP_TICK(); MicroProfileLogPut(nToken_, nTick, MP_LOG_ENTER, MicroProfileGetThreadLog()); return nTick; } return MICROPROFILE_INVALID_TICK; } void MicroProfileMetaUpdate(MicroProfileToken nToken, int nCount, MicroProfileTokenType eTokenType) { if((MP_DRAW_META_FIRST<<nToken) & S.nActiveBars) { MicroProfileThreadLog* pLog = MicroProfileTokenTypeCpu == eTokenType ? MicroProfileGetThreadLog() : g_MicroProfileGpuLog; if(pLog) { MP_ASSERT(nToken < MICROPROFILE_META_MAX); MicroProfileLogPut(nToken, nCount, MP_LOG_META, pLog); } } } void MicroProfileLeave(MicroProfileToken nToken_, uint64_t nTickStart) { if(MICROPROFILE_INVALID_TICK != nTickStart) { if(!MicroProfileGetThreadLog()) { MicroProfileInitThreadLog(); } uint64_t nTick = MP_TICK(); MicroProfileThreadLog* pLog = MicroProfileGetThreadLog(); MicroProfileLogPut(nToken_, nTick, MP_LOG_LEAVE, pLog); } } uint64_t MicroProfileGpuEnter(MicroProfileToken nToken_) { if(MicroProfileGetGroupMask(nToken_) & S.nActiveGroup) { uint64_t nTimer = MicroProfileGpuInsertTimeStamp(); MicroProfileLogPut(nToken_, nTimer, MP_LOG_ENTER, g_MicroProfileGpuLog); return 1; } return 0; } void MicroProfileGpuLeave(MicroProfileToken nToken_, uint64_t nTickStart) { if(nTickStart) { uint64_t nTimer = MicroProfileGpuInsertTimeStamp(); MicroProfileLogPut(nToken_, nTimer, MP_LOG_LEAVE, g_MicroProfileGpuLog); } } void MicroProfileContextSwitchPut(MicroProfileContextSwitch* pContextSwitch) { if(S.nRunning || pContextSwitch->nTicks <= S.nPauseTicks) { uint32_t nPut = S.nContextSwitchPut; S.ContextSwitch[nPut] = *pContextSwitch; S.nContextSwitchPut = (S.nContextSwitchPut+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; } } void MicroProfileGetRange(uint32_t nPut, uint32_t nGet, uint32_t nRange[2][2]) { if(nPut > nGet) { nRange[0][0] = nGet; nRange[0][1] = nPut; nRange[1][0] = nRange[1][1] = 0; } else if(nPut != nGet) { MP_ASSERT(nGet != MICROPROFILE_BUFFER_SIZE); uint32_t nCountEnd = MICROPROFILE_BUFFER_SIZE - nGet; nRange[0][0] = nGet; nRange[0][1] = nGet + nCountEnd; nRange[1][0] = 0; nRange[1][1] = nPut; } } void MicroProfileFlip() { #if 0 //verify LogEntry wraps correctly MicroProfileLogEntry c = MP_LOG_TICK_MASK-5000; for(int i = 0; i < 10000; ++i, c += 1) { MicroProfileLogEntry l2 = (c+2500) & MP_LOG_TICK_MASK; MP_ASSERT(2500 == MicroProfileLogTickDifference(c, l2)); } #endif MICROPROFILE_SCOPE(g_MicroProfileFlip); std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); MicroProfileGpuFlip(); if(S.nToggleRunning) { S.nRunning = !S.nRunning; if(!S.nRunning) S.nPauseTicks = MP_TICK(); S.nToggleRunning = 0; for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i) { MicroProfileThreadLog* pLog = S.Pool[i]; if(pLog) { pLog->nStackPos = 0; } } } uint32_t nAggregateClear = S.nAggregateClear || S.nAutoClearFrames, nAggregateFlip = 0; if(S.nDumpFileNextFrame) { MicroProfileDumpToFile(); S.nDumpFileNextFrame = 0; S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage } if(S.nWebServerDataSent == (uint64_t)-1) { MicroProfileWebServerStart(); S.nWebServerDataSent = 0; } if(MicroProfileWebServerUpdate()) { S.nAutoClearFrames = MICROPROFILE_GPU_FRAME_DELAY + 3; //hide spike from dumping webpage } if(S.nAutoClearFrames) { nAggregateClear = 1; nAggregateFlip = 1; S.nAutoClearFrames -= 1; } if(S.nRunning || S.nForceEnable) { S.nFramePutIndex++; S.nFramePut = (S.nFramePut+1) % MICROPROFILE_MAX_FRAME_HISTORY; MP_ASSERT((S.nFramePutIndex % MICROPROFILE_MAX_FRAME_HISTORY) == S.nFramePut); S.nFrameCurrent = (S.nFramePut + MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 1) % MICROPROFILE_MAX_FRAME_HISTORY; S.nFrameCurrentIndex++; uint32_t nFrameNext = (S.nFrameCurrent+1) % MICROPROFILE_MAX_FRAME_HISTORY; uint32_t nContextSwitchPut = S.nContextSwitchPut; if(S.nContextSwitchLastPut < nContextSwitchPut) { S.nContextSwitchUsage = (nContextSwitchPut - S.nContextSwitchLastPut); } else { S.nContextSwitchUsage = MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - S.nContextSwitchLastPut + nContextSwitchPut; } S.nContextSwitchLastPut = nContextSwitchPut; MicroProfileFrameState* pFramePut = &S.Frames[S.nFramePut]; MicroProfileFrameState* pFrameCurrent = &S.Frames[S.nFrameCurrent]; MicroProfileFrameState* pFrameNext = &S.Frames[nFrameNext]; pFramePut->nFrameStartCpu = MP_TICK(); pFramePut->nFrameStartGpu = (uint32_t)MicroProfileGpuInsertTimeStamp(); if(pFrameNext->nFrameStartGpu != (uint64_t)-1) pFrameNext->nFrameStartGpu = MicroProfileGpuGetTimeStamp((uint32_t)pFrameNext->nFrameStartGpu); if(pFrameCurrent->nFrameStartGpu == (uint64_t)-1) pFrameCurrent->nFrameStartGpu = pFrameNext->nFrameStartGpu + 1; uint64_t nFrameStartCpu = pFrameCurrent->nFrameStartCpu; uint64_t nFrameEndCpu = pFrameNext->nFrameStartCpu; { uint64_t nTick = nFrameEndCpu - nFrameStartCpu; S.nFlipTicks = nTick; S.nFlipAggregate += nTick; S.nFlipMax = MicroProfileMax(S.nFlipMax, nTick); } uint8_t* pTimerToGroup = &S.TimerToGroup[0]; for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i) { MicroProfileThreadLog* pLog = S.Pool[i]; if(!pLog) { pFramePut->nLogStart[i] = 0; } else { uint32_t nPut = pLog->nPut.load(std::memory_order_acquire); pFramePut->nLogStart[i] = nPut; MP_ASSERT(nPut< MICROPROFILE_BUFFER_SIZE); //need to keep last frame around to close timers. timers more than 1 frame old is ditched. pLog->nGet.store(nPut, std::memory_order_relaxed); } } if(S.nRunning) { uint64_t* pFrameGroup = &S.FrameGroup[0]; { MICROPROFILE_SCOPE(g_MicroProfileClear); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { S.Frame[i].nTicks = 0; S.Frame[i].nCount = 0; S.FrameExclusive[i] = 0; } for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i) { pFrameGroup[i] = 0; } for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j))) { auto& Meta = S.MetaCounters[j]; for(uint32_t i = 0; i < S.nTotalTimers; ++i) { Meta.nCounters[i] = 0; } } } } { MICROPROFILE_SCOPE(g_MicroProfileThreadLoop); for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i) { MicroProfileThreadLog* pLog = S.Pool[i]; if(!pLog) continue; uint8_t* pGroupStackPos = &pLog->nGroupStackPos[0]; int64_t nGroupTicks[MICROPROFILE_MAX_GROUPS] = {0}; uint32_t nPut = pFrameNext->nLogStart[i]; uint32_t nGet = pFrameCurrent->nLogStart[i]; uint32_t nRange[2][2] = { {0, 0}, {0, 0}, }; MicroProfileGetRange(nPut, nGet, nRange); //fetch gpu results. if(pLog->nGpu) { for(uint32_t j = 0; j < 2; ++j) { uint32_t nStart = nRange[j][0]; uint32_t nEnd = nRange[j][1]; for(uint32_t k = nStart; k < nEnd; ++k) { MicroProfileLogEntry L = pLog->Log[k]; pLog->Log[k] = MicroProfileLogSetTick(L, MicroProfileGpuGetTimeStamp((uint32_t)MicroProfileLogGetTick(L))); } } } uint32_t* pStack = &pLog->nStack[0]; int64_t* pChildTickStack = &pLog->nChildTickStack[0]; uint32_t nStackPos = pLog->nStackPos; for(uint32_t j = 0; j < 2; ++j) { uint32_t nStart = nRange[j][0]; uint32_t nEnd = nRange[j][1]; for(uint32_t k = nStart; k < nEnd; ++k) { MicroProfileLogEntry LE = pLog->Log[k]; int nType = MicroProfileLogType(LE); if(MP_LOG_ENTER == nType) { int nTimer = MicroProfileLogTimerIndex(LE); uint8_t nGroup = pTimerToGroup[nTimer]; MP_ASSERT(nStackPos < MICROPROFILE_STACK_MAX); MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS); pGroupStackPos[nGroup]++; pStack[nStackPos++] = k; pChildTickStack[nStackPos] = 0; } else if(MP_LOG_META == nType) { if(nStackPos) { int64_t nMetaIndex = MicroProfileLogTimerIndex(LE); int64_t nMetaCount = MicroProfileLogGetTick(LE); MP_ASSERT(nMetaIndex < MICROPROFILE_META_MAX); int64_t nCounter = MicroProfileLogTimerIndex(pLog->Log[pStack[nStackPos-1]]); S.MetaCounters[nMetaIndex].nCounters[nCounter] += nMetaCount; } } else { int nTimer = MicroProfileLogTimerIndex(LE); uint8_t nGroup = pTimerToGroup[nTimer]; MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS); MP_ASSERT(nType == MP_LOG_LEAVE); if(nStackPos) { int64_t nTickStart = pLog->Log[pStack[nStackPos-1]]; int64_t nTicks = MicroProfileLogTickDifference(nTickStart, LE); int64_t nChildTicks = pChildTickStack[nStackPos]; nStackPos--; pChildTickStack[nStackPos] += nTicks; uint32_t nTimerIndex = MicroProfileLogTimerIndex(LE); S.Frame[nTimerIndex].nTicks += nTicks; S.FrameExclusive[nTimerIndex] += (nTicks-nChildTicks); S.Frame[nTimerIndex].nCount += 1; MP_ASSERT(nGroup < MICROPROFILE_MAX_GROUPS); uint8_t nGroupStackPos = pGroupStackPos[nGroup]; if(nGroupStackPos) { nGroupStackPos--; if(0 == nGroupStackPos) { nGroupTicks[nGroup] += nTicks; } pGroupStackPos[nGroup] = nGroupStackPos; } } } } } for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i) { pLog->nGroupTicks[i] += nGroupTicks[i]; pFrameGroup[i] += nGroupTicks[i]; } pLog->nStackPos = nStackPos; } } { MICROPROFILE_SCOPE(g_MicroProfileAccumulate); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { S.AccumTimers[i].nTicks += S.Frame[i].nTicks; S.AccumTimers[i].nCount += S.Frame[i].nCount; S.AccumMaxTimers[i] = MicroProfileMax(S.AccumMaxTimers[i], S.Frame[i].nTicks); S.AccumTimersExclusive[i] += S.FrameExclusive[i]; S.AccumMaxTimersExclusive[i] = MicroProfileMax(S.AccumMaxTimersExclusive[i], S.FrameExclusive[i]); } for(uint32_t i = 0; i < MICROPROFILE_MAX_GROUPS; ++i) { S.AccumGroup[i] += pFrameGroup[i]; S.AccumGroupMax[i] = MicroProfileMax(S.AccumGroupMax[i], pFrameGroup[i]); } for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j))) { auto& Meta = S.MetaCounters[j]; uint64_t nSum = 0;; for(uint32_t i = 0; i < S.nTotalTimers; ++i) { uint64_t nCounter = Meta.nCounters[i]; Meta.nAccumMax[i] = MicroProfileMax(Meta.nAccumMax[i], nCounter); Meta.nAccum[i] += nCounter; nSum += nCounter; } Meta.nSumAccum += nSum; Meta.nSumAccumMax = MicroProfileMax(Meta.nSumAccumMax, nSum); } } } for(uint32_t i = 0; i < MICROPROFILE_MAX_GRAPHS; ++i) { if(S.Graph[i].nToken != MICROPROFILE_INVALID_TOKEN) { MicroProfileToken nToken = S.Graph[i].nToken; S.Graph[i].nHistory[S.nGraphPut] = S.Frame[MicroProfileGetTimerIndex(nToken)].nTicks; } } S.nGraphPut = (S.nGraphPut+1) % MICROPROFILE_GRAPH_HISTORY; } if(S.nRunning && S.nAggregateFlip <= ++S.nAggregateFlipCount) { nAggregateFlip = 1; if(S.nAggregateFlip) // if 0 accumulate indefinitely { nAggregateClear = 1; } } } if(nAggregateFlip) { memcpy(&S.Aggregate[0], &S.AccumTimers[0], sizeof(S.Aggregate[0]) * S.nTotalTimers); memcpy(&S.AggregateMax[0], &S.AccumMaxTimers[0], sizeof(S.AggregateMax[0]) * S.nTotalTimers); memcpy(&S.AggregateExclusive[0], &S.AccumTimersExclusive[0], sizeof(S.AggregateExclusive[0]) * S.nTotalTimers); memcpy(&S.AggregateMaxExclusive[0], &S.AccumMaxTimersExclusive[0], sizeof(S.AggregateMaxExclusive[0]) * S.nTotalTimers); memcpy(&S.AggregateGroup[0], &S.AccumGroup[0], sizeof(S.AggregateGroup)); memcpy(&S.AggregateGroupMax[0], &S.AccumGroupMax[0], sizeof(S.AggregateGroup)); for(uint32_t i = 0; i < MICROPROFILE_MAX_THREADS; ++i) { MicroProfileThreadLog* pLog = S.Pool[i]; if(!pLog) continue; memcpy(&pLog->nAggregateGroupTicks[0], &pLog->nGroupTicks[0], sizeof(pLog->nAggregateGroupTicks)); if(nAggregateClear) { memset(&pLog->nGroupTicks[0], 0, sizeof(pLog->nGroupTicks)); } } for(uint32_t j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName && 0 != (S.nActiveBars & (MP_DRAW_META_FIRST<<j))) { auto& Meta = S.MetaCounters[j]; memcpy(&Meta.nAggregateMax[0], &Meta.nAccumMax[0], sizeof(Meta.nAggregateMax[0]) * S.nTotalTimers); memcpy(&Meta.nAggregate[0], &Meta.nAccum[0], sizeof(Meta.nAggregate[0]) * S.nTotalTimers); Meta.nSumAggregate = Meta.nSumAccum; Meta.nSumAggregateMax = Meta.nSumAccumMax; if(nAggregateClear) { memset(&Meta.nAccumMax[0], 0, sizeof(Meta.nAccumMax[0]) * S.nTotalTimers); memset(&Meta.nAccum[0], 0, sizeof(Meta.nAccum[0]) * S.nTotalTimers); Meta.nSumAccum = 0; Meta.nSumAccumMax = 0; } } } S.nAggregateFrames = S.nAggregateFlipCount; S.nFlipAggregateDisplay = S.nFlipAggregate; S.nFlipMaxDisplay = S.nFlipMax; if(nAggregateClear) { memset(&S.AccumTimers[0], 0, sizeof(S.Aggregate[0]) * S.nTotalTimers); memset(&S.AccumMaxTimers[0], 0, sizeof(S.AccumMaxTimers[0]) * S.nTotalTimers); memset(&S.AccumTimersExclusive[0], 0, sizeof(S.AggregateExclusive[0]) * S.nTotalTimers); memset(&S.AccumMaxTimersExclusive[0], 0, sizeof(S.AccumMaxTimersExclusive[0]) * S.nTotalTimers); memset(&S.AccumGroup[0], 0, sizeof(S.AggregateGroup)); memset(&S.AccumGroupMax[0], 0, sizeof(S.AggregateGroup)); S.nAggregateFlipCount = 0; S.nFlipAggregate = 0; S.nFlipMax = 0; S.nAggregateFlipTick = MP_TICK(); } } S.nAggregateClear = 0; uint64_t nNewActiveGroup = 0; if(S.nForceEnable || (S.nDisplay && S.nRunning)) nNewActiveGroup = S.nAllGroupsWanted ? S.nGroupMask : S.nActiveGroupWanted; nNewActiveGroup |= S.nForceGroup; if(S.nActiveGroup != nNewActiveGroup) S.nActiveGroup = nNewActiveGroup; uint32_t nNewActiveBars = 0; if(S.nDisplay && S.nRunning) nNewActiveBars = S.nBars; if(S.nForceMetaCounters) { for(int i = 0; i < MICROPROFILE_META_MAX; ++i) { if(S.MetaCounters[i].pName) { nNewActiveBars |= (MP_DRAW_META_FIRST<<i); } } } if(nNewActiveBars != S.nActiveBars) S.nActiveBars = nNewActiveBars; } void MicroProfileSetForceEnable(bool bEnable) { S.nForceEnable = bEnable ? 1 : 0; } bool MicroProfileGetForceEnable() { return S.nForceEnable != 0; } void MicroProfileSetEnableAllGroups(bool bEnableAllGroups) { S.nAllGroupsWanted = bEnableAllGroups ? 1 : 0; } void MicroProfileEnableCategory(const char* pCategory, bool bEnabled) { int nCategoryIndex = -1; for(uint32_t i = 0; i < S.nCategoryCount; ++i) { if(!MP_STRCASECMP(pCategory, S.CategoryInfo[i].pName)) { nCategoryIndex = (int)i; break; } } if(nCategoryIndex >= 0) { if(bEnabled) { S.nActiveGroupWanted |= S.CategoryInfo[nCategoryIndex].nGroupMask; } else { S.nActiveGroupWanted &= ~S.CategoryInfo[nCategoryIndex].nGroupMask; } } } void MicroProfileEnableCategory(const char* pCategory) { MicroProfileEnableCategory(pCategory, true); } void MicroProfileDisableCategory(const char* pCategory) { MicroProfileEnableCategory(pCategory, false); } bool MicroProfileGetEnableAllGroups() { return 0 != S.nAllGroupsWanted; } void MicroProfileSetForceMetaCounters(bool bForce) { S.nForceMetaCounters = bForce ? 1 : 0; } bool MicroProfileGetForceMetaCounters() { return 0 != S.nForceMetaCounters; } void MicroProfileEnableMetaCounter(const char* pMeta) { for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i) { if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta)) { S.nBars |= (MP_DRAW_META_FIRST<<i); return; } } } void MicroProfileDisableMetaCounter(const char* pMeta) { for(uint32_t i = 0; i < MICROPROFILE_META_MAX; ++i) { if(S.MetaCounters[i].pName && 0 == MP_STRCASECMP(S.MetaCounters[i].pName, pMeta)) { S.nBars &= ~(MP_DRAW_META_FIRST<<i); return; } } } void MicroProfileSetAggregateFrames(int nFrames) { S.nAggregateFlip = (uint32_t)nFrames; if(0 == nFrames) { S.nAggregateClear = 1; } } int MicroProfileGetAggregateFrames() { return S.nAggregateFlip; } int MicroProfileGetCurrentAggregateFrames() { return int(S.nAggregateFlip ? S.nAggregateFlip : S.nAggregateFlipCount); } void MicroProfileForceEnableGroup(const char* pGroup, MicroProfileTokenType Type) { MicroProfileInit(); std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); uint16_t nGroup = MicroProfileGetGroup(pGroup, Type); S.nForceGroup |= (1ll << nGroup); } void MicroProfileForceDisableGroup(const char* pGroup, MicroProfileTokenType Type) { MicroProfileInit(); std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); uint16_t nGroup = MicroProfileGetGroup(pGroup, Type); S.nForceGroup &= ~(1ll << nGroup); } void MicroProfileCalcAllTimers(float* pTimers, float* pAverage, float* pMax, float* pCallAverage, float* pExclusive, float* pAverageExclusive, float* pMaxExclusive, float* pTotal, uint32_t nSize) { for(uint32_t i = 0; i < S.nTotalTimers && i < nSize; ++i) { const uint32_t nGroupId = S.TimerInfo[i].nGroupIndex; const float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupId].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu()); uint32_t nTimer = i; uint32_t nIdx = i * 2; uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1; uint32_t nAggregateCount = S.Aggregate[nTimer].nCount ? S.Aggregate[nTimer].nCount : 1; float fToPrc = S.fRcpReferenceTime; float fMs = fToMs * (S.Frame[nTimer].nTicks); float fPrc = MicroProfileMin(fMs * fToPrc, 1.f); float fAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateFrames); float fAveragePrc = MicroProfileMin(fAverageMs * fToPrc, 1.f); float fMaxMs = fToMs * (S.AggregateMax[nTimer]); float fMaxPrc = MicroProfileMin(fMaxMs * fToPrc, 1.f); float fCallAverageMs = fToMs * (S.Aggregate[nTimer].nTicks / nAggregateCount); float fCallAveragePrc = MicroProfileMin(fCallAverageMs * fToPrc, 1.f); float fMsExclusive = fToMs * (S.FrameExclusive[nTimer]); float fPrcExclusive = MicroProfileMin(fMsExclusive * fToPrc, 1.f); float fAverageMsExclusive = fToMs * (S.AggregateExclusive[nTimer] / nAggregateFrames); float fAveragePrcExclusive = MicroProfileMin(fAverageMsExclusive * fToPrc, 1.f); float fMaxMsExclusive = fToMs * (S.AggregateMaxExclusive[nTimer]); float fMaxPrcExclusive = MicroProfileMin(fMaxMsExclusive * fToPrc, 1.f); float fTotalMs = fToMs * S.Aggregate[nTimer].nTicks; pTimers[nIdx] = fMs; pTimers[nIdx+1] = fPrc; pAverage[nIdx] = fAverageMs; pAverage[nIdx+1] = fAveragePrc; pMax[nIdx] = fMaxMs; pMax[nIdx+1] = fMaxPrc; pCallAverage[nIdx] = fCallAverageMs; pCallAverage[nIdx+1] = fCallAveragePrc; pExclusive[nIdx] = fMsExclusive; pExclusive[nIdx+1] = fPrcExclusive; pAverageExclusive[nIdx] = fAverageMsExclusive; pAverageExclusive[nIdx+1] = fAveragePrcExclusive; pMaxExclusive[nIdx] = fMaxMsExclusive; pMaxExclusive[nIdx+1] = fMaxPrcExclusive; pTotal[nIdx] = fTotalMs; pTotal[nIdx+1] = 0.f; } } void MicroProfileTogglePause() { S.nToggleRunning = 1; } float MicroProfileGetTime(const char* pGroup, const char* pName) { MicroProfileToken nToken = MicroProfileFindToken(pGroup, pName); if(nToken == MICROPROFILE_INVALID_TOKEN) { return 0.f; } uint32_t nTimerIndex = MicroProfileGetTimerIndex(nToken); uint32_t nGroupIndex = MicroProfileGetGroupIndex(nToken); float fToMs = MicroProfileTickToMsMultiplier(S.GroupInfo[nGroupIndex].Type == MicroProfileTokenTypeGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu()); return S.Frame[nTimerIndex].nTicks * fToMs; } void MicroProfileContextSwitchSearch(uint32_t* pContextSwitchStart, uint32_t* pContextSwitchEnd, uint64_t nBaseTicksCpu, uint64_t nBaseTicksEndCpu) { MICROPROFILE_SCOPE(g_MicroProfileContextSwitchSearch); uint32_t nContextSwitchPut = S.nContextSwitchPut; uint64_t nContextSwitchStart, nContextSwitchEnd; nContextSwitchStart = nContextSwitchEnd = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - 1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; int64_t nSearchEnd = nBaseTicksEndCpu + MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu()); int64_t nSearchBegin = nBaseTicksCpu - MicroProfileMsToTick(30.f, MicroProfileTicksPerSecondCpu()); for(uint32_t i = 0; i < MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; ++i) { uint32_t nIndex = (nContextSwitchPut + MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE - (i+1)) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE; MicroProfileContextSwitch& CS = S.ContextSwitch[nIndex]; if(CS.nTicks > nSearchEnd) { nContextSwitchEnd = nIndex; } if(CS.nTicks > nSearchBegin) { nContextSwitchStart = nIndex; } } *pContextSwitchStart = nContextSwitchStart; *pContextSwitchEnd = nContextSwitchEnd; } #if MICROPROFILE_WEBSERVER #define MICROPROFILE_EMBED_HTML extern const char* g_MicroProfileHtml_begin[]; extern size_t g_MicroProfileHtml_begin_sizes[]; extern size_t g_MicroProfileHtml_begin_count; extern const char* g_MicroProfileHtml_end[]; extern size_t g_MicroProfileHtml_end_sizes[]; extern size_t g_MicroProfileHtml_end_count; typedef void MicroProfileWriteCallback(void* Handle, size_t size, const char* pData); uint32_t MicroProfileWebServerPort() { return S.nWebServerPort; } void MicroProfileDumpFile(const char* pHtml, const char* pCsv) { S.nDumpFileNextFrame = 0; if(pHtml) { uint32_t nLen = strlen(pHtml); if(nLen > sizeof(S.HtmlDumpPath)-1) { return; } memcpy(S.HtmlDumpPath, pHtml, nLen+1); S.nDumpFileNextFrame |= 1; } if(pCsv) { uint32_t nLen = strlen(pCsv); if(nLen > sizeof(S.CsvDumpPath)-1) { return; } memcpy(S.CsvDumpPath, pCsv, nLen+1); S.nDumpFileNextFrame |= 2; } } void MicroProfilePrintf(MicroProfileWriteCallback CB, void* Handle, const char* pFmt, ...) { char buffer[32*1024]; va_list args; va_start (args, pFmt); #ifdef _WIN32 size_t size = vsprintf_s(buffer, pFmt, args); #else size_t size = vsnprintf(buffer, sizeof(buffer)-1, pFmt, args); #endif CB(Handle, size, &buffer[0]); va_end (args); } #define printf(...) MicroProfilePrintf(CB, Handle, __VA_ARGS__) void MicroProfileDumpCsv(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames) { uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1; float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()); float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu()); printf("frames,%d\n", nAggregateFrames); printf("group,name,average,max,callaverage\n"); uint32_t nNumTimers = S.nTotalTimers; uint32_t nBlockSize = 2 * nNumTimers; float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float)); float* pAverage = pTimers + nBlockSize; float* pMax = pTimers + 2 * nBlockSize; float* pCallAverage = pTimers + 3 * nBlockSize; float* pTimersExclusive = pTimers + 4 * nBlockSize; float* pAverageExclusive = pTimers + 5 * nBlockSize; float* pMaxExclusive = pTimers + 6 * nBlockSize; float* pTotal = pTimers + 7 * nBlockSize; MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { uint32_t nIdx = i * 2; printf("\"%s\",\"%s\",%f,%f,%f\n", S.TimerInfo[i].pName, S.GroupInfo[S.TimerInfo[i].nGroupIndex].pName, pAverage[nIdx], pMax[nIdx], pCallAverage[nIdx]); } printf("\n\n"); printf("group,average,max,total\n"); for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j) { const char* pGroupName = S.GroupInfo[j].pName; float fToMs = S.GroupInfo[j].Type == MicroProfileTokenTypeGpu ? fToMsGPU : fToMsCPU; if(pGroupName[0] != '\0') { printf("\"%s\",%.3f,%.3f,%.3f\n", pGroupName, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j] / nAggregateFrames, fToMs * S.AggregateGroup[j]); } } printf("\n\n"); printf("group,thread,average,total\n"); for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j) { for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { const char* pThreadName = &S.Pool[i]->ThreadName[0]; // MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i); float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU; { uint64_t nTicks = S.Pool[i]->nAggregateGroupTicks[j]; float fTime = nTicks / nAggregateFrames * fToMs; float fTimeTotal = nTicks * fToMs; if(fTimeTotal > 0.01f) { const char* pGroupName = S.GroupInfo[j].pName; printf("\"%s\",\"%s\",%.3f,%.3f\n", pGroupName, pThreadName, fTime, fTimeTotal); } } } } } printf("\n\n"); printf("frametimecpu\n"); const uint32_t nCount = MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3; const uint32_t nStart = S.nFrameCurrent; for(uint32_t i = nCount; i > 0; i--) { uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY; uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY; uint64_t nTicks = S.Frames[nFrameNext].nFrameStartCpu - S.Frames[nFrame].nFrameStartCpu; printf("%f,", nTicks * fToMsCPU); } printf("\n"); printf("\n\n"); printf("frametimegpu\n"); for(uint32_t i = nCount; i > 0; i--) { uint32_t nFrame = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i) % MICROPROFILE_MAX_FRAME_HISTORY; uint32_t nFrameNext = (nStart + MICROPROFILE_MAX_FRAME_HISTORY - i + 1) % MICROPROFILE_MAX_FRAME_HISTORY; uint64_t nTicks = S.Frames[nFrameNext].nFrameStartGpu - S.Frames[nFrame].nFrameStartGpu; printf("%f,", nTicks * fToMsGPU); } printf("\n\n"); printf("Meta\n");//only single frame snapshot printf("name,average,max,total\n"); for(int j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName) { printf("\"%s\",%f,%lld,%lld\n",S.MetaCounters[j].pName, S.MetaCounters[j].nSumAggregate / (float)nAggregateFrames, S.MetaCounters[j].nSumAggregateMax,S.MetaCounters[j].nSumAggregate); } } } #undef printf void MicroProfileDumpHtml(MicroProfileWriteCallback CB, void* Handle, int nMaxFrames, const char* pHost) { uint32_t nRunning = S.nRunning; S.nRunning = 0; //stall pushing of timers uint64_t nActiveGroup = S.nActiveGroup; S.nActiveGroup = 0; S.nPauseTicks = MP_TICK(); for(size_t i = 0; i < g_MicroProfileHtml_begin_count; ++i) { CB(Handle, g_MicroProfileHtml_begin_sizes[i]-1, g_MicroProfileHtml_begin[i]); } //dump info uint64_t nTicks = MP_TICK(); float fToMsCPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()); float fToMsGPU = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondGpu()); float fAggregateMs = fToMsCPU * (nTicks - S.nAggregateFlipTick); MicroProfilePrintf(CB, Handle, "var DumpHost = '%s';\n", pHost ? pHost : ""); time_t CaptureTime; time(&CaptureTime); MicroProfilePrintf(CB, Handle, "var DumpUtcCaptureTime = %ld;\n", CaptureTime); MicroProfilePrintf(CB, Handle, "var AggregateInfo = {'Frames':%d, 'Time':%f};\n", S.nAggregateFrames, fAggregateMs); //categories MicroProfilePrintf(CB, Handle, "var CategoryInfo = Array(%d);\n",S.nCategoryCount); for(uint32_t i = 0; i < S.nCategoryCount; ++i) { MicroProfilePrintf(CB, Handle, "CategoryInfo[%d] = \"%s\";\n", i, S.CategoryInfo[i].pName); } //groups MicroProfilePrintf(CB, Handle, "var GroupInfo = Array(%d);\n\n",S.nGroupCount); uint32_t nAggregateFrames = S.nAggregateFrames ? S.nAggregateFrames : 1; float fRcpAggregateFrames = 1.f / nAggregateFrames; for(uint32_t i = 0; i < S.nGroupCount; ++i) { MP_ASSERT(i == S.GroupInfo[i].nGroupIndex); float fToMs = S.GroupInfo[i].Type == MicroProfileTokenTypeCpu ? fToMsCPU : fToMsGPU; MicroProfilePrintf(CB, Handle, "GroupInfo[%d] = MakeGroup(%d, \"%s\", %d, %d, %d, %f, %f, %f, '#%02x%02x%02x');\n", S.GroupInfo[i].nGroupIndex, S.GroupInfo[i].nGroupIndex, S.GroupInfo[i].pName, S.GroupInfo[i].nCategory, S.GroupInfo[i].nNumTimers, S.GroupInfo[i].Type == MicroProfileTokenTypeGpu?1:0, fToMs * S.AggregateGroup[i], fToMs * S.AggregateGroup[i] / nAggregateFrames, fToMs * S.AggregateGroupMax[i], MICROPROFILE_UNPACK_RED(S.GroupInfo[i].nColor) & 0xff, MICROPROFILE_UNPACK_GREEN(S.GroupInfo[i].nColor) & 0xff, MICROPROFILE_UNPACK_BLUE(S.GroupInfo[i].nColor) & 0xff); } //timers uint32_t nNumTimers = S.nTotalTimers; uint32_t nBlockSize = 2 * nNumTimers; float* pTimers = (float*)alloca(nBlockSize * 8 * sizeof(float)); float* pAverage = pTimers + nBlockSize; float* pMax = pTimers + 2 * nBlockSize; float* pCallAverage = pTimers + 3 * nBlockSize; float* pTimersExclusive = pTimers + 4 * nBlockSize; float* pAverageExclusive = pTimers + 5 * nBlockSize; float* pMaxExclusive = pTimers + 6 * nBlockSize; float* pTotal = pTimers + 7 * nBlockSize; MicroProfileCalcAllTimers(pTimers, pAverage, pMax, pCallAverage, pTimersExclusive, pAverageExclusive, pMaxExclusive, pTotal, nNumTimers); MicroProfilePrintf(CB, Handle, "\nvar TimerInfo = Array(%d);\n\n", S.nTotalTimers); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { uint32_t nIdx = i * 2; MP_ASSERT(i == S.TimerInfo[i].nTimerIndex); MicroProfilePrintf(CB, Handle, "var Meta%d = [", i); bool bOnce = true; for(int j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName) { uint32_t lala = S.MetaCounters[j].nCounters[i]; MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", lala); bOnce = false; } } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var MetaAvg%d = [", i); bOnce = true; for(int j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName) { MicroProfilePrintf(CB, Handle, bOnce ? "%f" : ",%f", fRcpAggregateFrames * S.MetaCounters[j].nAggregate[i]); bOnce = false; } } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var MetaMax%d = [", i); bOnce = true; for(int j = 0; j < MICROPROFILE_META_MAX; ++j) { if(S.MetaCounters[j].pName) { MicroProfilePrintf(CB, Handle, bOnce ? "%d" : ",%d", S.MetaCounters[j].nAggregateMax[i]); bOnce = false; } } MicroProfilePrintf(CB, Handle, "];\n"); uint32_t nColor = S.TimerInfo[i].nColor; uint32_t nColorDark = (nColor >> 1) & ~0x80808080; MicroProfilePrintf(CB, Handle, "TimerInfo[%d] = MakeTimer(%d, \"%s\", %d, '#%02x%02x%02x','#%02x%02x%02x', %f, %f, %f, %f, %f, %d, %f, Meta%d, MetaAvg%d, MetaMax%d);\n", S.TimerInfo[i].nTimerIndex, S.TimerInfo[i].nTimerIndex, S.TimerInfo[i].pName, S.TimerInfo[i].nGroupIndex, MICROPROFILE_UNPACK_RED(nColor) & 0xff, MICROPROFILE_UNPACK_GREEN(nColor) & 0xff, MICROPROFILE_UNPACK_BLUE(nColor) & 0xff, MICROPROFILE_UNPACK_RED(nColorDark) & 0xff, MICROPROFILE_UNPACK_GREEN(nColorDark) & 0xff, MICROPROFILE_UNPACK_BLUE(nColorDark) & 0xff, pAverage[nIdx], pMax[nIdx], pAverageExclusive[nIdx], pMaxExclusive[nIdx], pCallAverage[nIdx], S.Aggregate[i].nCount, pTotal[nIdx], i,i,i); } MicroProfilePrintf(CB, Handle, "\nvar ThreadNames = ["); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { MicroProfilePrintf(CB, Handle, "'%s',", S.Pool[i]->ThreadName); } else { MicroProfilePrintf(CB, Handle, "'Thread %d',", i); } } MicroProfilePrintf(CB, Handle, "];\n\n"); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { MicroProfilePrintf(CB, Handle, "var ThreadGroupTime%d = [", i); float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU; for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j) { MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j]/nAggregateFrames * fToMs); } MicroProfilePrintf(CB, Handle, "];\n"); } } MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeArray = ["); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { MicroProfilePrintf(CB, Handle, "ThreadGroupTime%d,", i); } } MicroProfilePrintf(CB, Handle, "];\n"); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { MicroProfilePrintf(CB, Handle, "var ThreadGroupTimeTotal%d = [", i); float fToMs = S.Pool[i]->nGpu ? fToMsGPU : fToMsCPU; for(uint32_t j = 0; j < MICROPROFILE_MAX_GROUPS; ++j) { MicroProfilePrintf(CB, Handle, "%f,", S.Pool[i]->nAggregateGroupTicks[j] * fToMs); } MicroProfilePrintf(CB, Handle, "];\n"); } } MicroProfilePrintf(CB, Handle, "\nvar ThreadGroupTimeTotalArray = ["); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { MicroProfilePrintf(CB, Handle, "ThreadGroupTimeTotal%d,", i); } } MicroProfilePrintf(CB, Handle, "];"); MicroProfilePrintf(CB, Handle, "\nvar ThreadIds = ["); for(uint32_t i = 0; i < S.nNumLogs; ++i) { if(S.Pool[i]) { ThreadIdType ThreadId = S.Pool[i]->nThreadId; if(!ThreadId) { ThreadId = (ThreadIdType)-1; } MicroProfilePrintf(CB, Handle, "%d,", ThreadId); } else { MicroProfilePrintf(CB, Handle, "-1,", i); } } MicroProfilePrintf(CB, Handle, "];\n\n"); MicroProfilePrintf(CB, Handle, "\nvar MetaNames = ["); for(int i = 0; i < MICROPROFILE_META_MAX; ++i) { if(S.MetaCounters[i].pName) { MicroProfilePrintf(CB, Handle, "'%s',", S.MetaCounters[i].pName); } } MicroProfilePrintf(CB, Handle, "];\n\n"); uint32_t nNumFrames = (MICROPROFILE_MAX_FRAME_HISTORY - MICROPROFILE_GPU_FRAME_DELAY - 3); //leave a few to not overwrite nNumFrames = MicroProfileMin(nNumFrames, (uint32_t)nMaxFrames); uint32_t nFirstFrame = (S.nFrameCurrent + MICROPROFILE_MAX_FRAME_HISTORY - nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY; uint32_t nLastFrame = (nFirstFrame + nNumFrames) % MICROPROFILE_MAX_FRAME_HISTORY; MP_ASSERT(nLastFrame == (S.nFrameCurrent % MICROPROFILE_MAX_FRAME_HISTORY)); MP_ASSERT(nFirstFrame < MICROPROFILE_MAX_FRAME_HISTORY); MP_ASSERT(nLastFrame < MICROPROFILE_MAX_FRAME_HISTORY); const int64_t nTickStart = S.Frames[nFirstFrame].nFrameStartCpu; const int64_t nTickEnd = S.Frames[nLastFrame].nFrameStartCpu; int64_t nTickStartGpu = S.Frames[nFirstFrame].nFrameStartGpu; #if MICROPROFILE_DEBUG printf("dumping %d frames\n", nNumFrames); printf("dumping frame %d to %d\n", nFirstFrame, nLastFrame); #endif uint32_t* nTimerCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers); memset(nTimerCounter, 0, sizeof(uint32_t) * S.nTotalTimers); MicroProfilePrintf(CB, Handle, "var Frames = Array(%d);\n", nNumFrames); for(uint32_t i = 0; i < nNumFrames; ++i) { uint32_t nFrameIndex = (nFirstFrame + i) % MICROPROFILE_MAX_FRAME_HISTORY; uint32_t nFrameIndexNext = (nFrameIndex + 1) % MICROPROFILE_MAX_FRAME_HISTORY; for(uint32_t j = 0; j < S.nNumLogs; ++j) { MicroProfileThreadLog* pLog = S.Pool[j]; int64_t nStartTick = pLog->nGpu ? nTickStartGpu : nTickStart; uint32_t nLogStart = S.Frames[nFrameIndex].nLogStart[j]; uint32_t nLogEnd = S.Frames[nFrameIndexNext].nLogStart[j]; float fToMs = MicroProfileTickToMsMultiplier(pLog->nGpu ? MicroProfileTicksPerSecondGpu() : MicroProfileTicksPerSecondCpu()); MicroProfilePrintf(CB, Handle, "var ts_%d_%d = [", i, j); if(nLogStart != nLogEnd) { uint32_t k = nLogStart; uint32_t nLogType = MicroProfileLogType(pLog->Log[k]); float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs; MicroProfilePrintf(CB, Handle, "%f", fTime); for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE) { uint32_t nLogType = MicroProfileLogType(pLog->Log[k]); float fTime = nLogType == MP_LOG_META ? 0.f : MicroProfileLogTickDifference(nStartTick, pLog->Log[k]) * fToMs; MicroProfilePrintf(CB, Handle, ",%f", fTime); } } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var tt_%d_%d = [", i, j); if(nLogStart != nLogEnd) { uint32_t k = nLogStart; MicroProfilePrintf(CB, Handle, "%d", MicroProfileLogType(pLog->Log[k])); for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE) { uint32_t nLogType = MicroProfileLogType(pLog->Log[k]); if(nLogType == MP_LOG_META) { //for meta, store the count + 2, which is the tick part nLogType = 2 + MicroProfileLogGetTick(pLog->Log[k]); } MicroProfilePrintf(CB, Handle, ",%d", nLogType); } } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var ti_%d_%d = [", i, j); if(nLogStart != nLogEnd) { uint32_t k = nLogStart; MicroProfilePrintf(CB, Handle, "%d", (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k])); for(k = (k+1) % MICROPROFILE_BUFFER_SIZE; k != nLogEnd; k = (k+1) % MICROPROFILE_BUFFER_SIZE) { uint32_t nTimerIndex = (uint32_t)MicroProfileLogTimerIndex(pLog->Log[k]); MicroProfilePrintf(CB, Handle, ",%d", nTimerIndex); nTimerCounter[nTimerIndex]++; } } MicroProfilePrintf(CB, Handle, "];\n"); } MicroProfilePrintf(CB, Handle, "var ts%d = [", i); for(uint32_t j = 0; j < S.nNumLogs; ++j) { MicroProfilePrintf(CB, Handle, "ts_%d_%d,", i, j); } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var tt%d = [", i); for(uint32_t j = 0; j < S.nNumLogs; ++j) { MicroProfilePrintf(CB, Handle, "tt_%d_%d,", i, j); } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var ti%d = [", i); for(uint32_t j = 0; j < S.nNumLogs; ++j) { MicroProfilePrintf(CB, Handle, "ti_%d_%d,", i, j); } MicroProfilePrintf(CB, Handle, "];\n"); int64_t nFrameStart = S.Frames[nFrameIndex].nFrameStartCpu; int64_t nFrameEnd = S.Frames[nFrameIndexNext].nFrameStartCpu; float fToMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()); float fFrameMs = MicroProfileLogTickDifference(nTickStart, nFrameStart) * fToMs; float fFrameEndMs = MicroProfileLogTickDifference(nTickStart, nFrameEnd) * fToMs; MicroProfilePrintf(CB, Handle, "Frames[%d] = MakeFrame(%d, %f, %f, ts%d, tt%d, ti%d);\n", i, 0, fFrameMs, fFrameEndMs, i, i, i); } uint32_t nContextSwitchStart = 0; uint32_t nContextSwitchEnd = 0; MicroProfileContextSwitchSearch(&nContextSwitchStart, &nContextSwitchEnd, nTickStart, nTickEnd); uint32_t nWrittenBefore = S.nWebServerDataSent; MicroProfilePrintf(CB, Handle, "var CSwitchThreadInOutCpu = ["); for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE) { MicroProfileContextSwitch CS = S.ContextSwitch[j]; int nCpu = CS.nCpu; MicroProfilePrintf(CB, Handle, "%d,%d,%d,", CS.nThreadIn, CS.nThreadOut, nCpu); } MicroProfilePrintf(CB, Handle, "];\n"); MicroProfilePrintf(CB, Handle, "var CSwitchTime = ["); float fToMsCpu = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()); for(uint32_t j = nContextSwitchStart; j != nContextSwitchEnd; j = (j+1) % MICROPROFILE_CONTEXT_SWITCH_BUFFER_SIZE) { MicroProfileContextSwitch CS = S.ContextSwitch[j]; float fTime = MicroProfileLogTickDifference(nTickStart, CS.nTicks) * fToMsCpu; MicroProfilePrintf(CB, Handle, "%f,", fTime); } MicroProfilePrintf(CB, Handle, "];\n"); uint32_t nWrittenAfter = S.nWebServerDataSent; MicroProfilePrintf(CB, Handle, "//CSwitch Size %d\n", nWrittenAfter - nWrittenBefore); for(size_t i = 0; i < g_MicroProfileHtml_end_count; ++i) { CB(Handle, g_MicroProfileHtml_end_sizes[i]-1, g_MicroProfileHtml_end[i]); } uint32_t* nGroupCounter = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount); memset(nGroupCounter, 0, sizeof(uint32_t) * S.nGroupCount); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { uint32_t nGroupIndex = S.TimerInfo[i].nGroupIndex; nGroupCounter[nGroupIndex] += nTimerCounter[i]; } uint32_t* nGroupCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nGroupCount); uint32_t* nTimerCounterSort = (uint32_t*)alloca(sizeof(uint32_t)* S.nTotalTimers); for(uint32_t i = 0; i < S.nGroupCount; ++i) { nGroupCounterSort[i] = i; } for(uint32_t i = 0; i < S.nTotalTimers; ++i) { nTimerCounterSort[i] = i; } std::sort(nGroupCounterSort, nGroupCounterSort + S.nGroupCount, [nGroupCounter](const uint32_t l, const uint32_t r) { return nGroupCounter[l] > nGroupCounter[r]; } ); std::sort(nTimerCounterSort, nTimerCounterSort + S.nTotalTimers, [nTimerCounter](const uint32_t l, const uint32_t r) { return nTimerCounter[l] > nTimerCounter[r]; } ); MicroProfilePrintf(CB, Handle, "\n<!--\nMarker Per Group\n"); for(uint32_t i = 0; i < S.nGroupCount; ++i) { uint32_t idx = nGroupCounterSort[i]; MicroProfilePrintf(CB, Handle, "%8d:%s\n", nGroupCounter[idx], S.GroupInfo[idx].pName); } MicroProfilePrintf(CB, Handle, "Marker Per Timer\n"); for(uint32_t i = 0; i < S.nTotalTimers; ++i) { uint32_t idx = nTimerCounterSort[i]; MicroProfilePrintf(CB, Handle, "%8d:%s(%s)\n", nTimerCounter[idx], S.TimerInfo[idx].pName, S.GroupInfo[S.TimerInfo[idx].nGroupIndex].pName); } MicroProfilePrintf(CB, Handle, "\n-->\n"); S.nActiveGroup = nActiveGroup; S.nRunning = nRunning; #if MICROPROFILE_DEBUG int64_t nTicksEnd = MP_TICK(); float fMs = fToMsCpu * (nTicksEnd - S.nPauseTicks); printf("html dump took %6.2fms\n", fMs); #endif } void MicroProfileWriteFile(void* Handle, size_t nSize, const char* pData) { fwrite(pData, nSize, 1, (FILE*)Handle); } void MicroProfileDumpToFile() { std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); if(S.nDumpFileNextFrame&1) { FILE* F = fopen(S.HtmlDumpPath, "w"); if(F) { MicroProfileDumpHtml(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES, S.HtmlDumpPath); fclose(F); } } if(S.nDumpFileNextFrame&2) { FILE* F = fopen(S.CsvDumpPath, "w"); if(F) { MicroProfileDumpCsv(MicroProfileWriteFile, F, MICROPROFILE_WEBSERVER_MAXFRAMES); fclose(F); } } } void MicroProfileFlushSocket(MpSocket Socket) { send(Socket, &S.WebServerBuffer[0], S.WebServerPut, 0); S.WebServerPut = 0; } void MicroProfileWriteSocket(void* Handle, size_t nSize, const char* pData) { S.nWebServerDataSent += nSize; MpSocket Socket = *(MpSocket*)Handle; if(nSize > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE / 2) { MicroProfileFlushSocket(Socket); send(Socket, pData, nSize, 0); } else { memcpy(&S.WebServerBuffer[S.WebServerPut], pData, nSize); S.WebServerPut += nSize; if(S.WebServerPut > MICROPROFILE_WEBSERVER_SOCKET_BUFFER_SIZE/2) { MicroProfileFlushSocket(Socket); } } } #if MICROPROFILE_MINIZ #ifndef MICROPROFILE_COMPRESS_BUFFER_SIZE #define MICROPROFILE_COMPRESS_BUFFER_SIZE (256<<10) #endif #define MICROPROFILE_COMPRESS_CHUNK (MICROPROFILE_COMPRESS_BUFFER_SIZE/2) struct MicroProfileCompressedSocketState { unsigned char DeflateOut[MICROPROFILE_COMPRESS_CHUNK]; unsigned char DeflateIn[MICROPROFILE_COMPRESS_CHUNK]; mz_stream Stream; MpSocket Socket; uint32_t nSize; uint32_t nCompressedSize; uint32_t nFlushes; uint32_t nMemmoveBytes; }; void MicroProfileCompressedSocketFlush(MicroProfileCompressedSocketState* pState) { mz_stream& Stream = pState->Stream; unsigned char* pSendStart = &pState->DeflateOut[0]; unsigned char* pSendEnd = &pState->DeflateOut[MICROPROFILE_COMPRESS_CHUNK - Stream.avail_out]; if(pSendStart != pSendEnd) { send(pState->Socket, (const char*)pSendStart, pSendEnd - pSendStart, 0); pState->nCompressedSize += pSendEnd - pSendStart; } Stream.next_out = &pState->DeflateOut[0]; Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK; } void MicroProfileCompressedSocketStart(MicroProfileCompressedSocketState* pState, MpSocket Socket) { mz_stream& Stream = pState->Stream; memset(&Stream, 0, sizeof(Stream)); Stream.next_out = &pState->DeflateOut[0]; Stream.avail_out = MICROPROFILE_COMPRESS_CHUNK; Stream.next_in = &pState->DeflateIn[0]; Stream.avail_in = 0; mz_deflateInit(&Stream, Z_DEFAULT_COMPRESSION); pState->Socket = Socket; pState->nSize = 0; pState->nCompressedSize = 0; pState->nFlushes = 0; pState->nMemmoveBytes = 0; } void MicroProfileCompressedSocketFinish(MicroProfileCompressedSocketState* pState) { mz_stream& Stream = pState->Stream; MicroProfileCompressedSocketFlush(pState); int r = mz_deflate(&Stream, MZ_FINISH); MP_ASSERT(r == MZ_STREAM_END); MicroProfileCompressedSocketFlush(pState); r = mz_deflateEnd(&Stream); MP_ASSERT(r == MZ_OK); } void MicroProfileCompressedWriteSocket(void* Handle, size_t nSize, const char* pData) { MicroProfileCompressedSocketState* pState = (MicroProfileCompressedSocketState*)Handle; mz_stream& Stream = pState->Stream; const unsigned char* pDeflateInEnd = Stream.next_in + Stream.avail_in; const unsigned char* pDeflateInStart = &pState->DeflateIn[0]; const unsigned char* pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK]; pState->nSize += nSize; if(nSize <= pDeflateInRealEnd - pDeflateInEnd) { memcpy((void*)pDeflateInEnd, pData, nSize); Stream.avail_in += nSize; MP_ASSERT(Stream.next_in + Stream.avail_in <= pDeflateInRealEnd); return; } int Flush = 0; while(nSize) { pDeflateInEnd = Stream.next_in + Stream.avail_in; if(Flush) { pState->nFlushes++; MicroProfileCompressedSocketFlush(pState); pDeflateInRealEnd = &pState->DeflateIn[MICROPROFILE_COMPRESS_CHUNK]; if(pDeflateInEnd == pDeflateInRealEnd) { if(Stream.avail_in) { MP_ASSERT(pDeflateInStart != Stream.next_in); memmove((void*)pDeflateInStart, Stream.next_in, Stream.avail_in); pState->nMemmoveBytes += Stream.avail_in; } Stream.next_in = pDeflateInStart; pDeflateInEnd = Stream.next_in + Stream.avail_in; } } size_t nSpace = pDeflateInRealEnd - pDeflateInEnd; size_t nBytes = MicroProfileMin(nSpace, nSize); MP_ASSERT(nBytes + pDeflateInEnd <= pDeflateInRealEnd); memcpy((void*)pDeflateInEnd, pData, nBytes); Stream.avail_in += nBytes; nSize -= nBytes; pData += nBytes; int r = mz_deflate(&Stream, MZ_NO_FLUSH); Flush = r == MZ_BUF_ERROR || nBytes == 0 || Stream.avail_out == 0 ? 1 : 0; MP_ASSERT(r == MZ_BUF_ERROR || r == MZ_OK); if(r == MZ_BUF_ERROR) { r = mz_deflate(&Stream, MZ_SYNC_FLUSH); } } } #endif #ifndef MicroProfileSetNonBlocking //fcntl doesnt work on a some unix like platforms.. void MicroProfileSetNonBlocking(MpSocket Socket, int NonBlocking) { #ifdef _WIN32 u_long nonBlocking = NonBlocking ? 1 : 0; ioctlsocket(Socket, FIONBIO, &nonBlocking); #else int Options = fcntl(Socket, F_GETFL); if(NonBlocking) { fcntl(Socket, F_SETFL, Options|O_NONBLOCK); } else { fcntl(Socket, F_SETFL, Options&(~O_NONBLOCK)); } #endif } #endif void MicroProfileWebServerStart() { #ifdef _WIN32 WSADATA wsa; if(WSAStartup(MAKEWORD(2, 2), &wsa)) { S.ListenerSocket = -1; return; } #endif S.ListenerSocket = socket(PF_INET, SOCK_STREAM, 6); MP_ASSERT(!MP_INVALID_SOCKET(S.ListenerSocket)); MicroProfileSetNonBlocking(S.ListenerSocket, 1); S.nWebServerPort = (uint32_t)-1; struct sockaddr_in Addr; Addr.sin_family = AF_INET; Addr.sin_addr.s_addr = INADDR_ANY; for(int i = 0; i < 20; ++i) { Addr.sin_port = htons(MICROPROFILE_WEBSERVER_PORT+i); if(0 == bind(S.ListenerSocket, (sockaddr*)&Addr, sizeof(Addr))) { S.nWebServerPort = MICROPROFILE_WEBSERVER_PORT+i; break; } } listen(S.ListenerSocket, 8); } void MicroProfileWebServerStop() { #ifdef _WIN32 closesocket(S.ListenerSocket); WSACleanup(); #else close(S.ListenerSocket); #endif } int MicroProfileParseGet(const char* pGet) { const char* pStart = pGet; while(*pGet != '\0') { if(*pGet < '0' || *pGet > '9') return 0; pGet++; } int nFrames = atoi(pStart); if(nFrames) { return nFrames; } else { return MICROPROFILE_WEBSERVER_MAXFRAMES; } } bool MicroProfileWebServerUpdate() { MICROPROFILE_SCOPEI("MicroProfile", "Webserver-update", -1); MpSocket Connection = accept(S.ListenerSocket, 0, 0); bool bServed = false; if(!MP_INVALID_SOCKET(Connection)) { std::lock_guard<std::recursive_mutex> Lock(MicroProfileMutex()); char Req[8192]; MicroProfileSetNonBlocking(Connection, 0); int nReceived = recv(Connection, Req, sizeof(Req)-1, 0); if(nReceived > 0) { Req[nReceived] = '\0'; #if MICROPROFILE_MINIZ #define MICROPROFILE_HTML_HEADER "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Encoding: deflate\r\nExpires: Tue, 01 Jan 2199 16:00:00 GMT\r\n\r\n" #else #define MICROPROFILE_HTML_HEADER "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nExpires: Tue, 01 Jan 2199 16:00:00 GMT\r\n\r\n" #endif char* pHttp = strstr(Req, "HTTP/"); char* pGet = strstr(Req, "GET /"); char* pHost = strstr(Req, "Host: "); auto Terminate = [](char* pString) { char* pEnd = pString; while(*pEnd != '\0') { if(*pEnd == '\r' || *pEnd == '\n' || *pEnd == ' ') { *pEnd = '\0'; return; } pEnd++; } }; if(pHost) { pHost += sizeof("Host: ")-1; Terminate(pHost); } if(pHttp && pGet) { *pHttp = '\0'; pGet += sizeof("GET /")-1; Terminate(pGet); int nFrames = MicroProfileParseGet(pGet); if(nFrames) { uint64_t nTickStart = MP_TICK(); send(Connection, MICROPROFILE_HTML_HEADER, sizeof(MICROPROFILE_HTML_HEADER)-1, 0); uint64_t nDataStart = S.nWebServerDataSent; S.WebServerPut = 0; #if 0 == MICROPROFILE_MINIZ MicroProfileDumpHtml(MicroProfileWriteSocket, &Connection, nFrames, pHost); uint64_t nDataEnd = S.nWebServerDataSent; uint64_t nTickEnd = MP_TICK(); uint64_t nDiff = (nTickEnd - nTickStart); float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff; int nKb = ((nDataEnd-nDataStart)>>10) + 1; int nCompressedKb = nKb; MicroProfilePrintf(MicroProfileWriteSocket, &Connection, "\n<!-- Sent %dkb in %.2fms-->\n\n",nKb, fMs); MicroProfileFlushSocket(Connection); #else MicroProfileCompressedSocketState CompressState; MicroProfileCompressedSocketStart(&CompressState, Connection); MicroProfileDumpHtml(MicroProfileCompressedWriteSocket, &CompressState, nFrames, pHost); S.nWebServerDataSent += CompressState.nSize; uint64_t nDataEnd = S.nWebServerDataSent; uint64_t nTickEnd = MP_TICK(); uint64_t nDiff = (nTickEnd - nTickStart); float fMs = MicroProfileTickToMsMultiplier(MicroProfileTicksPerSecondCpu()) * nDiff; int nKb = ((nDataEnd-nDataStart)>>10) + 1; int nCompressedKb = ((CompressState.nCompressedSize)>>10) + 1; MicroProfilePrintf(MicroProfileCompressedWriteSocket, &CompressState, "\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs); MicroProfileCompressedSocketFinish(&CompressState); MicroProfileFlushSocket(Connection); #endif #if MICROPROFILE_DEBUG printf("\n<!-- Sent %dkb(compressed %dkb) in %.2fms-->\n\n", nKb, nCompressedKb, fMs); #endif } } } #ifdef _WIN32 closesocket(Connection); #else close(Connection); #endif } return bServed; } #endif #if MICROPROFILE_CONTEXT_SWITCH_TRACE //functions that need to be implemented per platform. void* MicroProfileTraceThread(void* unused); bool MicroProfileIsLocalThread(uint32_t nThreadId); void MicroProfileStartContextSwitchTrace() { if(!S.bContextSwitchRunning) { S.bContextSwitchRunning = true; S.bContextSwitchStop = false; MicroProfileThreadStart(&S.ContextSwitchThread, MicroProfileTraceThread); } } void MicroProfileStopContextSwitchTrace() { if(S.bContextSwitchRunning) { S.bContextSwitchStop = true; MicroProfileThreadJoin(&S.ContextSwitchThread); } } #ifdef _WIN32 #define INITGUID #include <evntrace.h> #include <evntcons.h> #include <strsafe.h> static GUID g_MicroProfileThreadClassGuid = { 0x3d6fa8d1, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c }; struct MicroProfileSCSwitch { uint32_t NewThreadId; uint32_t OldThreadId; int8_t NewThreadPriority; int8_t OldThreadPriority; uint8_t PreviousCState; int8_t SpareByte; int8_t OldThreadWaitReason; int8_t OldThreadWaitMode; int8_t OldThreadState; int8_t OldThreadWaitIdealProcessor; uint32_t NewThreadWaitTime; uint32_t Reserved; }; VOID WINAPI MicroProfileContextSwitchCallback(PEVENT_TRACE pEvent) { if (pEvent->Header.Guid == g_MicroProfileThreadClassGuid) { if (pEvent->Header.Class.Type == 36) { MicroProfileSCSwitch* pCSwitch = (MicroProfileSCSwitch*) pEvent->MofData; if ((pCSwitch->NewThreadId != 0) || (pCSwitch->OldThreadId != 0)) { MicroProfileContextSwitch Switch; Switch.nThreadOut = pCSwitch->OldThreadId; Switch.nThreadIn = pCSwitch->NewThreadId; Switch.nCpu = pEvent->BufferContext.ProcessorNumber; Switch.nTicks = pEvent->Header.TimeStamp.QuadPart; MicroProfileContextSwitchPut(&Switch); } } } } ULONG WINAPI MicroProfileBufferCallback(PEVENT_TRACE_LOGFILE Buffer) { return (S.bContextSwitchStop || !S.bContextSwitchRunning) ? FALSE : TRUE; } struct MicroProfileKernelTraceProperties : public EVENT_TRACE_PROPERTIES { char dummy[sizeof(KERNEL_LOGGER_NAME)]; }; void MicroProfileContextSwitchShutdownTrace() { TRACEHANDLE SessionHandle = 0; MicroProfileKernelTraceProperties sessionProperties; ZeroMemory(&sessionProperties, sizeof(sessionProperties)); sessionProperties.Wnode.BufferSize = sizeof(sessionProperties); sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID; sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution sessionProperties.Wnode.Guid = SystemTraceControlGuid; sessionProperties.BufferSize = 1; sessionProperties.NumberOfBuffers = 128; sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH; sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE; sessionProperties.MaximumFileSize = 0; sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); sessionProperties.LogFileNameOffset = 0; EVENT_TRACE_LOGFILE log; ZeroMemory(&log, sizeof(log)); log.LoggerName = KERNEL_LOGGER_NAME; log.ProcessTraceMode = 0; TRACEHANDLE hLog = OpenTrace(&log); if (hLog) { ControlTrace(SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties, EVENT_TRACE_CONTROL_STOP); } CloseTrace(hLog); } void* MicroProfileTraceThread(void* unused) { MicroProfileContextSwitchShutdownTrace(); ULONG status = ERROR_SUCCESS; TRACEHANDLE SessionHandle = 0; MicroProfileKernelTraceProperties sessionProperties; ZeroMemory(&sessionProperties, sizeof(sessionProperties)); sessionProperties.Wnode.BufferSize = sizeof(sessionProperties); sessionProperties.Wnode.Flags = WNODE_FLAG_TRACED_GUID; sessionProperties.Wnode.ClientContext = 1; //QPC clock resolution sessionProperties.Wnode.Guid = SystemTraceControlGuid; sessionProperties.BufferSize = 1; sessionProperties.NumberOfBuffers = 128; sessionProperties.EnableFlags = EVENT_TRACE_FLAG_CSWITCH|EVENT_TRACE_FLAG_PROCESS; sessionProperties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE; sessionProperties.MaximumFileSize = 0; sessionProperties.LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); sessionProperties.LogFileNameOffset = 0; status = StartTrace((PTRACEHANDLE) &SessionHandle, KERNEL_LOGGER_NAME, &sessionProperties); if (ERROR_SUCCESS != status) { S.bContextSwitchRunning = false; return 0; } EVENT_TRACE_LOGFILE log; ZeroMemory(&log, sizeof(log)); log.LoggerName = KERNEL_LOGGER_NAME; log.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_RAW_TIMESTAMP; log.EventCallback = MicroProfileContextSwitchCallback; log.BufferCallback = MicroProfileBufferCallback; TRACEHANDLE hLog = OpenTrace(&log); ProcessTrace(&hLog, 1, 0, 0); CloseTrace(hLog); MicroProfileContextSwitchShutdownTrace(); S.bContextSwitchRunning = false; return 0; } bool MicroProfileIsLocalThread(uint32_t nThreadId) { HANDLE h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, nThreadId); if(h == NULL) return false; DWORD hProcess = GetProcessIdOfThread(h); CloseHandle(h); return GetCurrentProcessId() == hProcess; } #elif defined(__APPLE__) #include <sys/time.h> void* MicroProfileTraceThread(void* unused) { FILE* pFile = fopen("mypipe", "r"); if(!pFile) { printf("CONTEXT SWITCH FAILED TO OPEN FILE: make sure to run dtrace script\n"); S.bContextSwitchRunning = false; return 0; } printf("STARTING TRACE THREAD\n"); char* pLine = 0; size_t cap = 0; size_t len = 0; struct timeval tv; gettimeofday(&tv, NULL); uint64_t nsSinceEpoch = ((uint64_t)(tv.tv_sec) * 1000000 + (uint64_t)(tv.tv_usec)) * 1000; uint64_t nTickEpoch = MP_TICK(); uint32_t nLastThread[MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS] = {0}; mach_timebase_info_data_t sTimebaseInfo; mach_timebase_info(&sTimebaseInfo); S.bContextSwitchRunning = true; uint64_t nProcessed = 0; uint64_t nProcessedLast = 0; while((len = getline(&pLine, &cap, pFile))>0 && !S.bContextSwitchStop) { nProcessed += len; if(nProcessed - nProcessedLast > 10<<10) { nProcessedLast = nProcessed; printf("processed %llukb %llukb\n", (nProcessed-nProcessedLast)>>10,nProcessed >>10); } char* pX = strchr(pLine, 'X'); if(pX) { int cpu = atoi(pX+1); char* pX2 = strchr(pX + 1, 'X'); char* pX3 = strchr(pX2 + 1, 'X'); int thread = atoi(pX2+1); char* lala; int64_t timestamp = strtoll(pX3 + 1, &lala, 10); MicroProfileContextSwitch Switch; //convert to ticks. uint64_t nDeltaNsSinceEpoch = timestamp - nsSinceEpoch; uint64_t nDeltaTickSinceEpoch = sTimebaseInfo.numer * nDeltaNsSinceEpoch / sTimebaseInfo.denom; uint64_t nTicks = nDeltaTickSinceEpoch + nTickEpoch; if(cpu < MICROPROFILE_MAX_CONTEXT_SWITCH_THREADS) { Switch.nThreadOut = nLastThread[cpu]; Switch.nThreadIn = thread; nLastThread[cpu] = thread; Switch.nCpu = cpu; Switch.nTicks = nTicks; MicroProfileContextSwitchPut(&Switch); } } } printf("EXITING TRACE THREAD\n"); S.bContextSwitchRunning = false; return 0; } bool MicroProfileIsLocalThread(uint32_t nThreadId) { return false; } #endif #else bool MicroProfileIsLocalThread(uint32_t nThreadId){return false;} void MicroProfileStopContextSwitchTrace(){} void MicroProfileStartContextSwitchTrace(){} #endif #if MICROPROFILE_GPU_TIMERS_D3D11 uint32_t MicroProfileGpuInsertTimeStamp() { MicroProfileD3D11Frame& Frame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame]; if(Frame.m_nRateQueryStarted) { uint32_t nCurrent = (Frame.m_nQueryStart + Frame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES; uint32_t nNext = (nCurrent + 1) % MICROPROFILE_D3D_MAX_QUERIES; if(nNext != S.GPU.m_nQueryGet) { Frame.m_nQueryCount++; ID3D11Query* pQuery = (ID3D11Query*)S.GPU.m_pQueries[nCurrent]; ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext; pContext->End(pQuery); S.GPU.m_nQueryPut = nNext; return nCurrent; } } return (uint32_t)-1; } uint64_t MicroProfileGpuGetTimeStamp(uint32_t nIndex) { if(nIndex == (uint32_t)-1) { return (uint64_t)-1; } int64_t nResult = S.GPU.m_nQueryResults[nIndex]; MP_ASSERT(nResult != -1); return nResult; } bool MicroProfileGpuGetData(void* pQuery, void* pData, uint32_t nDataSize) { HRESULT hr; do { hr = ((ID3D11DeviceContext*)S.GPU.m_pDeviceContext)->GetData((ID3D11Query*)pQuery, pData, nDataSize, 0); }while(hr == S_FALSE); switch(hr) { case DXGI_ERROR_DEVICE_REMOVED: case DXGI_ERROR_INVALID_CALL: case E_INVALIDARG: MP_BREAK(); return false; } return true; } uint64_t MicroProfileTicksPerSecondGpu() { return S.GPU.m_nQueryFrequency; } void MicroProfileGpuFlip() { MicroProfileD3D11Frame& CurrentFrame = S.GPU.m_QueryFrames[S.GPU.m_nQueryFrame]; ID3D11DeviceContext* pContext = (ID3D11DeviceContext*)S.GPU.m_pDeviceContext; if(CurrentFrame.m_nRateQueryStarted) { pContext->End((ID3D11Query*)CurrentFrame.m_pRateQuery); } uint32_t nNextFrame = (S.GPU.m_nQueryFrame + 1) % MICROPROFILE_GPU_FRAME_DELAY; MicroProfileD3D11Frame& OldFrame = S.GPU.m_QueryFrames[nNextFrame]; if(OldFrame.m_nRateQueryStarted) { struct RateQueryResult { uint64_t nFrequency; BOOL bDisjoint; }; RateQueryResult Result; if(MicroProfileGpuGetData(OldFrame.m_pRateQuery, &Result, sizeof(Result))) { if(S.GPU.m_nQueryFrequency != (int64_t)Result.nFrequency) { if(S.GPU.m_nQueryFrequency) { OutputDebugString("Query freq changing"); } S.GPU.m_nQueryFrequency = Result.nFrequency; } uint32_t nStart = OldFrame.m_nQueryStart; uint32_t nCount = OldFrame.m_nQueryCount; for(uint32_t i = 0; i < nCount; ++i) { uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES; if(!MicroProfileGpuGetData(S.GPU.m_pQueries[nIndex], &S.GPU.m_nQueryResults[nIndex], sizeof(uint64_t))) { S.GPU.m_nQueryResults[nIndex] = -1; } } } else { uint32_t nStart = OldFrame.m_nQueryStart; uint32_t nCount = OldFrame.m_nQueryCount; for(uint32_t i = 0; i < nCount; ++i) { uint32_t nIndex = (i + nStart) % MICROPROFILE_D3D_MAX_QUERIES; S.GPU.m_nQueryResults[nIndex] = -1; } } S.GPU.m_nQueryGet = (OldFrame.m_nQueryStart + OldFrame.m_nQueryCount) % MICROPROFILE_D3D_MAX_QUERIES; } S.GPU.m_nQueryFrame = nNextFrame; MicroProfileD3D11Frame& NextFrame = S.GPU.m_QueryFrames[nNextFrame]; pContext->Begin((ID3D11Query*)NextFrame.m_pRateQuery); NextFrame.m_nQueryStart = S.GPU.m_nQueryPut; NextFrame.m_nQueryCount = 0; NextFrame.m_nRateQueryStarted = 1; } void MicroProfileGpuInitD3D11(void* pDevice_, void* pDeviceContext_) { ID3D11Device* pDevice = (ID3D11Device*)pDevice_; ID3D11DeviceContext* pDeviceContext = (ID3D11DeviceContext*)pDeviceContext_; S.GPU.m_pDeviceContext = pDeviceContext_; D3D11_QUERY_DESC Desc; Desc.MiscFlags = 0; Desc.Query = D3D11_QUERY_TIMESTAMP; for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i) { HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_pQueries[i]); MP_ASSERT(hr == S_OK); S.GPU.m_nQueryResults[i] = -1; } S.GPU.m_nQueryPut = 0; S.GPU.m_nQueryGet = 0; S.GPU.m_nQueryFrame = 0; S.GPU.m_nQueryFrequency = 0; Desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT; for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i) { S.GPU.m_QueryFrames[i].m_nQueryStart = 0; S.GPU.m_QueryFrames[i].m_nQueryCount = 0; S.GPU.m_QueryFrames[i].m_nRateQueryStarted = 0; HRESULT hr = pDevice->CreateQuery(&Desc, (ID3D11Query**)&S.GPU.m_QueryFrames[i].m_pRateQuery); MP_ASSERT(hr == S_OK); } } void MicroProfileGpuShutdown() { for(uint32_t i = 0; i < MICROPROFILE_D3D_MAX_QUERIES; ++i) { ((ID3D11Query*)&S.GPU.m_pQueries[i])->Release(); S.GPU.m_pQueries[i] = 0; } for(uint32_t i = 0; i < MICROPROFILE_GPU_FRAME_DELAY; ++i) { ((ID3D11Query*)S.GPU.m_QueryFrames[i].m_pRateQuery)->Release(); S.GPU.m_QueryFrames[i].m_pRateQuery = 0; } } #elif MICROPROFILE_GPU_TIMERS_GL void MicroProfileGpuInitGL() { S.GPU.GLTimerPos = 0; glGenQueries(MICROPROFILE_GL_MAX_QUERIES, &S.GPU.GLTimers[0]); } uint32_t MicroProfileGpuInsertTimeStamp() { uint32_t nIndex = (S.GPU.GLTimerPos+1)%MICROPROFILE_GL_MAX_QUERIES; glQueryCounter(S.GPU.GLTimers[nIndex], GL_TIMESTAMP); S.GPU.GLTimerPos = nIndex; return nIndex; } uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey) { uint64_t result; glGetQueryObjectui64v(S.GPU.GLTimers[nKey], GL_QUERY_RESULT, &result); return result; } uint64_t MicroProfileTicksPerSecondGpu() { return 1000000000ll; } #endif #undef S #ifdef _WIN32 #pragma warning(pop) #endif #endif #endif <file_sep>/Editor/Source/Editor/MaterialShaderEditor/EditorMaterialShaderEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MaterialShaderEditor/EditorMaterialShaderEditor.h" #include "Editor/Editor.h" #include "Engine/Material.h" #include "Engine/Entity.h" #include "ResourceCompiler/ShaderGraph.h" Log_SetChannel(EditorMaterialShaderEditor); EditorMaterialShaderEditor::EditorMaterialShaderEditor(EditorMaterialShaderEditorCallbacks *pCallbacks) { m_pCallbacks = pCallbacks; m_pShaderGenerator = NULL; m_pPreviewMaterialShader = NULL; m_pPreviewMaterial = NULL; m_bRegeneratePreviewMaterial = true; } EditorMaterialShaderEditor::~EditorMaterialShaderEditor() { //if (m_pPreviewMaterialShader != NULL) //m_pPreviewMaterialShader->SetSource(NULL); SAFE_RELEASE(m_pPreviewMaterialShader); SAFE_RELEASE(m_pPreviewMaterial); delete m_pShaderGenerator; } bool EditorMaterialShaderEditor::LoadShader(const char *fileName, ByteStream *pStream) { Assert(m_pShaderGenerator == NULL); MaterialShaderGenerator *pSource = new MaterialShaderGenerator(); if (!pSource->LoadFromXML(nullptr, fileName, pStream)) { delete pSource; return false; } m_pShaderGenerator = pSource; RegeneratePreviewMaterials(); return true; } void EditorMaterialShaderEditor::CreateShader() { Assert(m_pShaderGenerator == NULL); m_pShaderGenerator = new MaterialShaderGenerator(); m_pShaderGenerator->Create(nullptr); } bool EditorMaterialShaderEditor::SaveShader(ByteStream *pStream) { return m_pShaderGenerator->SaveToXML(pStream); } void EditorMaterialShaderEditor::SetBlendingMode(MATERIAL_BLENDING_MODE BlendingMode, bool SupressCallbacks /*= false*/) { m_pShaderGenerator->SetBlendMode(BlendingMode); if (!SupressCallbacks) m_pCallbacks->OnMaterialPropertiesChanged(); } void EditorMaterialShaderEditor::SetLightingMode(MATERIAL_LIGHTING_MODEL LightingMode, bool SupressCallbacks /*= false*/) { m_pShaderGenerator->SetLightingModel(LightingMode); if (!SupressCallbacks) m_pCallbacks->OnMaterialPropertiesChanged(); } void EditorMaterialShaderEditor::SetDoubleSidedLighting(bool Enabled, bool SupressCallbacks /*= false*/) { m_pShaderGenerator->SetTwoSided(Enabled); if (!SupressCallbacks) m_pCallbacks->OnMaterialPropertiesChanged(); } bool EditorMaterialShaderEditor::AddUniformParameter(const char *ParameterName, const char *ParameterDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RenameUniformParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::ChangeUniformParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RemoveUniformParameter(const char *ParameterName, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::AddTextureParameter(const char *ParameterName, TEXTURE_TYPE textureType, const char *ParameterDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RenameTextureParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::ChangeTextureParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RemoveTextureParameter(const char *ParameterName, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::AddStaticSwitchParameter(const char *ParameterName, const char *ParameterDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RenameStaticSwitchParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::ChangeStaticSwitchParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks /*= false*/) { return false; } bool EditorMaterialShaderEditor::RemoveStaticSwitchParameter(const char *ParameterName, bool SupressCallbacks /*= false*/) { return false; } const MaterialShader *EditorMaterialShaderEditor::GetPreviewMaterialShader() const { if (m_bRegeneratePreviewMaterial && !RegeneratePreviewMaterials()) return NULL; return m_pPreviewMaterialShader; } const Material *EditorMaterialShaderEditor::GetPreviewMaterial() const { if (m_bRegeneratePreviewMaterial && !RegeneratePreviewMaterials()) return NULL; return m_pPreviewMaterial; } bool EditorMaterialShaderEditor::RegeneratePreviewMaterials() const { // if (m_pPreviewMaterialShader != NULL) // m_pPreviewMaterialShader->SetSource(NULL); // // SAFE_RELEASE(m_pPreviewMaterialShader); // SAFE_RELEASE(m_pPreviewMaterial); // m_bRegeneratePreviewMaterial = true; // // MaterialShader *pMaterialShader = new MaterialShader(); // if (!pMaterialShader->Create("MATERIAL_SHADER_EDITOR_PREVIEW", m_pShaderGenerator)) // { // pMaterialShader->Release(); // return false; // } // // pMaterialShader->SetSource(m_pShaderGenerator); // // Material *pMaterial = new Material(); // pMaterial->Create("MATERIAL_SHADER_EDITOR_PREVIEW", pMaterialShader); // // m_pPreviewMaterialShader = pMaterialShader; // m_pPreviewMaterial = pMaterial; // m_bRegeneratePreviewMaterial = false; // return true; return false; } <file_sep>/Engine/Source/GameFramework/PointLightEntity.h #include "Engine/Entity.h" class PointLightRenderProxy; class PointLightEntity : public Entity { DECLARE_ENTITY_TYPEINFO(PointLightEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(PointLightEntity); public: PointLightEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~PointLightEntity(); // property accessors const bool GetEnabled() const { return m_bEnabled; } const float &GetRange() const { return m_fRange; } const float3 &GetColor() const { return m_Color; } const float &GetBrightness() const { return m_fBrightness; } const uint32 GetLightShadowFlags() const { return m_iLightShadowFlags; } const float GetFalloffExponent() const { return m_fFalloffExponent; } // property setters void SetEnabled(bool enabled); void SetRange(float range); void SetColor(const float3 &color); void SetBrightness(float brightness); void SetLightShadowFlags(uint32 lightShadowFlags); void SetFalloffExponent(float falloffExponent); // inherited methods virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; private: // helper functions float3 CalculateLightColor(); void UpdateBounds(); // property callbacks static void OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnRangePropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnFalloffExponentChange(ThisClass *pEntity, const void *pUserData = NULL); // local copy of properties bool m_bEnabled; float m_fRange; float3 m_Color; float m_fBrightness; uint32 m_iLightShadowFlags; float m_fFalloffExponent; // instance of render proxy PointLightRenderProxy *m_pRenderProxy; }; <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphBuiltinNodes.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphBuiltinNodes.h" #include "ResourceCompiler/ShaderGraphCompiler.h" #include "Engine/Texture.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(ShaderGraphNode); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Global, ShaderGraphNode, "Global", "Global"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Global); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Global) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Global) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Global) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Global::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; const char *nameString = xmlReader.FetchAttribute("global"); if (nameString == NULL) { xmlReader.PrintError("Could not read name attribute."); return false; } // look up global in schema const ShaderGraphSchema::GlobalDeclaration *pGlobalDefinition = nullptr; for (uint32 i = 0; i < pShaderGraph->GetSchema()->GetGlobalDeclarationCount(); i++) { const ShaderGraphSchema::GlobalDeclaration *pCurrent = pShaderGraph->GetSchema()->GetGlobalDeclaration(i); if (pCurrent->Name.Compare(nameString)) { pGlobalDefinition = pCurrent; break; } } if (pGlobalDefinition == nullptr) { xmlReader.PrintError("Unknown global '%s' not found in schema.", nameString); return false; } // update name and output m_globalName = pGlobalDefinition->Name; m_pOutputs[0].SetValueType(pGlobalDefinition->Type); return true; } void ShaderGraphNode_Global::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); xmlWriter.WriteAttribute("global", m_globalName); } bool ShaderGraphNode_Global::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex < m_nOutputs); return pCompiler->EmitAccessShaderGlobal(m_globalName); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_ShaderInputs, ShaderGraphNode, "ShaderInputs", "ShaderInputs"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_ShaderInputs) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_ShaderInputs) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_ShaderInputs) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_ShaderInputs::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex < m_nOutputs); return pCompiler->EmitAccessShaderInput(m_pOutputs[OutputIndex].GetOutputDesc()->Name); } ShaderGraphNode_ShaderInputs::ShaderGraphNode_ShaderInputs(const ShaderGraphSchema::InputDeclaration *const *ppInputDeclarations, uint32 nInputDeclarations, const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo) { uint32 i; // we shouldn't have any inputs or outputs. this is ok, it is what we want. DebugAssert(m_nInputs == 0 && m_nOutputs == 0); // create outputs based on the shader input declarations m_nOutputs = nInputDeclarations; if (m_nOutputs > 0) { m_pOutputs = new ShaderGraphNodeOutput[m_nOutputs]; for (i = 0; i < m_nOutputs; i++) m_pOutputs[i].Init(this, i, &ppInputDeclarations[i]->OutputDesc); } } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_ShaderOutputs, ShaderGraphNode, "ShaderOutputs", "ShaderOutputs"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_ShaderOutputs) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_ShaderOutputs) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_ShaderOutputs) END_SHADER_GRAPH_NODE_OUTPUTS() ShaderGraphNode_ShaderOutputs::ShaderGraphNode_ShaderOutputs(const ShaderGraphSchema::OutputDeclaration *const *ppOutputDeclarations, uint32 nOutputDeclarations, const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo) { uint32 i; // we shouldn't have any inputs or outputs. this is ok, it is what we want. DebugAssert(m_nInputs == 0 && m_nOutputs == 0); // create inputs based on the shader output declarations m_nInputs = nOutputDeclarations; if (m_nInputs > 0) { m_pInputs = new ShaderGraphNodeInput[m_nInputs]; for (i = 0; i < m_nInputs; i++) m_pInputs[i].Init(this, i, &ppOutputDeclarations[i]->InputDesc); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Parameter, ShaderGraphNode, "Parameter", "Parameter"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Parameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Parameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Parameter) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Parameter::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; const char *parameterNameStr = xmlReader.FetchAttribute("parametername"); if (parameterNameStr == NULL) { xmlReader.PrintError("Could not read parameter name attribute."); return false; } m_strParameterName = parameterNameStr; return true; } void ShaderGraphNode_Parameter::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); xmlWriter.WriteAttribute("parametername", m_strParameterName); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_UniformParameter, ShaderGraphNode_Parameter, "UniformParameter", "UniformParameter"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_UniformParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_UniformParameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_UniformParameter) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_UniformParameter::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; // const char *valueString = xmlReader.FetchAttribute("value"); // if (valueString == NULL) // { // xmlReader.PrintError("Could not read value attribute."); // return false; // } // // if (!SetValueString(valueString)) // { // xmlReader.PrintError("Could not set value to '%s'", valueString); // return false; // } return true; } void ShaderGraphNode_UniformParameter::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); // SmallString valueString; // GetValueString(valueString); // // xmlWriter.WriteAttribute("value", valueString); } bool ShaderGraphNode_UniformParameter::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); const ShaderGraphCompiler::ExternalParameter *pExternalParameter = pCompiler->GetExternalUniformParameter(m_strParameterName); if (pExternalParameter == NULL) { Log_ErrorPrintf("Shader graph node '%s' referencing nonexistant uniform parameter '%s'", m_strName.GetCharArray(), m_strParameterName.GetCharArray()); return false; } if (pExternalParameter->Type != m_pOutputs[0].GetOutputDesc()->Type) { Log_ErrorPrintf("Shader graph node '%s' referencing uniform parameter '%s' has a type mismatch (%s vs %s)", m_strName.GetCharArray(), m_strParameterName.GetCharArray(), NameTable_GetNameString(NameTables::ShaderParameterType, pExternalParameter->Type), NameTable_GetNameString(NameTables::ShaderParameterType, m_pOutputs[0].GetOutputDesc()->Type)); return false; } return pCompiler->EmitAccessExternalParameter(pExternalParameter); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_TextureParameter, ShaderGraphNode_Parameter, "TextureParameter", "TextureParameter"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_TextureParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_TextureParameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_TextureParameter) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_TextureParameter::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; // const char *textureName = xmlReader.FetchAttribute("texture"); // if (textureName == NULL) // { // xmlReader.PrintError("Could not read texture attribute."); // return false; // } // // m_strTextureName = textureName; return true; } void ShaderGraphNode_TextureParameter::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); } bool ShaderGraphNode_TextureParameter::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); const ShaderGraphCompiler::ExternalParameter *pExternalParameter = pCompiler->GetExternalTextureParameter(m_strParameterName); if (pExternalParameter == NULL) { Log_ErrorPrintf("Shader graph node '%s' referencing nonexistant texture parameter '%s'", m_strName.GetCharArray(), m_strParameterName.GetCharArray()); return false; } if (pExternalParameter->Type != m_pOutputs[0].GetOutputDesc()->Type) { Log_ErrorPrintf("Shader graph node '%s' referencing texture parameter '%s' has a type mismatch (%s vs %s)", m_strName.GetCharArray(), m_strParameterName.GetCharArray(), NameTable_GetNameString(NameTables::ShaderParameterType, pExternalParameter->Type), NameTable_GetNameString(NameTables::ShaderParameterType, m_pOutputs[0].GetOutputDesc()->Type)); return false; } return pCompiler->EmitAccessExternalParameter(pExternalParameter); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_StaticSwitchParameter, ShaderGraphNode, "StaticSwitchParameter", "StaticSwitchParameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_StaticSwitchParameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_StaticSwitchParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_StaticSwitchParameter) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("IfEnabled", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("IfDisabled", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_StaticSwitchParameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_StaticSwitchParameter::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; // set combined type if (m_pInputs[0].IsLinked() && m_pInputs[1].IsLinked()) { DebugAssert(m_pInputs[0].GetValueType() == m_pInputs[1].GetValueType()); m_pOutputs[0].SetValueType(m_pInputs[0].GetValueType()); } else { m_pOutputs[0].SetValueType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_StaticSwitchParameter::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); DebugAssert(m_pInputs[0].IsLinked()); DebugAssert(m_pInputs[1].IsLinked()); if (pCompiler->GetExternalStaticSwitchParameter(m_strParameterName)) return pCompiler->EvaluateNode(&m_pInputs[0]); else return pCompiler->EvaluateNode(&m_pInputs[1]); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FloatParameter, ShaderGraphNode_UniformParameter, "FloatParameter", "FloatParameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FloatParameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_FloatParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_FloatParameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_FloatParameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_GRAPH_NODE_OUTPUTS() DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Parameter, ShaderGraphNode_UniformParameter, "Float2Parameter", "Float2Parameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Parameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float2Parameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float2Parameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float2Parameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT2) END_SHADER_GRAPH_NODE_OUTPUTS() DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Parameter, ShaderGraphNode_UniformParameter, "Float3Parameter", "Float3Parameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Parameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float3Parameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float3Parameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float3Parameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT3) END_SHADER_GRAPH_NODE_OUTPUTS() DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Parameter, ShaderGraphNode_UniformParameter, "Float4Parameter", "Float4Parameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Parameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float4Parameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float4Parameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float4Parameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT4) END_SHADER_GRAPH_NODE_OUTPUTS() ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Texture2DParameter, ShaderGraphNode_TextureParameter, "Texture2DParameter", "Texture2DParameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Texture2DParameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Texture2DParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Texture2DParameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Texture2DParameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Texture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_GRAPH_NODE_OUTPUTS() const ResourceTypeInfo *ShaderGraphNode_Texture2DParameter::GetTextureTypeInfo() const { return Texture2D::StaticTypeInfo(); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Texture2DArrayParameter, ShaderGraphNode_TextureParameter, "Texture2DArrayParameter", "Texture2DArrayParameter"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Texture2DArrayParameter); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Texture2DArrayParameter) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Texture2DArrayParameter) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Texture2DArrayParameter) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Texture", SHADER_PARAMETER_TYPE_TEXTURE2DARRAY) END_SHADER_GRAPH_NODE_OUTPUTS() const ResourceTypeInfo *ShaderGraphNode_Texture2DArrayParameter::GetTextureTypeInfo() const { return Texture2DArray::StaticTypeInfo(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Constant, ShaderGraphNode, "Constant", "Constant"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Constant) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Constant) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Constant) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Constant::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; const char *valueString = xmlReader.FetchAttribute("value"); if (valueString == NULL) { xmlReader.PrintError("Could not read value attribute."); return false; } if (!SetValueString(valueString)) { xmlReader.PrintError("Could not set value to '%s'", valueString); return false; } return true; } void ShaderGraphNode_Constant::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); SmallString valueString; GetValueString(valueString); xmlWriter.WriteAttribute("value", valueString); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FloatConstant, ShaderGraphNode_Constant, "FloatConstant", "FloatConstant"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FloatConstant); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_FloatConstant) PROPERTY_TABLE_MEMBER_FLOAT("Value", 0, offsetof(ShaderGraphNode_FloatConstant, m_Value), NULL, NULL) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_FloatConstant) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_FloatConstant) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_GRAPH_NODE_OUTPUTS() ShaderGraphNode_FloatConstant::ShaderGraphNode_FloatConstant(const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo), m_Value(0) { } bool ShaderGraphNode_FloatConstant::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); pCompiler->EmitConstantFloat(m_Value); return true; } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Constant, ShaderGraphNode_Constant, "Float2Constant", "Float2Constant"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Constant); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float2Constant) PROPERTY_TABLE_MEMBER_FLOAT2("Value", 0, offsetof(ShaderGraphNode_Float2Constant, m_Value), NULL, NULL) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float2Constant) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float2Constant) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT2) END_SHADER_GRAPH_NODE_OUTPUTS() ShaderGraphNode_Float2Constant::ShaderGraphNode_Float2Constant(const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo), m_Value(float2::Zero) { } bool ShaderGraphNode_Float2Constant::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); pCompiler->EmitConstantFloat2(m_Value); return true; } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Constant, ShaderGraphNode_Constant, "Float3Constant", "Float3Constant"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Constant); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float3Constant) PROPERTY_TABLE_MEMBER_FLOAT3("Value", 0, offsetof(ShaderGraphNode_Float3Constant, m_Value), NULL, NULL) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float3Constant) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float3Constant) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT3) END_SHADER_GRAPH_NODE_OUTPUTS() ShaderGraphNode_Float3Constant::ShaderGraphNode_Float3Constant(const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo), m_Value(float3::Zero) { } bool ShaderGraphNode_Float3Constant::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); pCompiler->EmitConstantFloat3(m_Value); return true; } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Constant, ShaderGraphNode_Constant, "Float4Constant", "Float4Constant"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Constant); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float4Constant) PROPERTY_TABLE_MEMBER_FLOAT4("Value", 0, offsetof(ShaderGraphNode_Float4Constant, m_Value), NULL, NULL) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float4Constant) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float4Constant) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT4) END_SHADER_GRAPH_NODE_OUTPUTS() ShaderGraphNode_Float4Constant::ShaderGraphNode_Float4Constant(const ShaderGraphNodeTypeInfo *pTypeInfo /*= &s_TypeInfo*/) : BaseClass(pTypeInfo), m_Value(float4::Zero) { } bool ShaderGraphNode_Float4Constant::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); pCompiler->EmitConstantFloat4(m_Value); return true; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_TextureSample, ShaderGraphNode, "TextureSample", "TextureSample"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_TextureSample); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_TextureSample) //PROPERTY_TABLE_MEMBER_ENUM("UnpackOperation", NameTables::ShaderGraphTextureSampleUnpackOperation, 0, offsetof(ShaderGraphNode_TextureSample, m_eUnpackOperation), NULL, NULL) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_TextureSample) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Texture", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("TexCoord", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_TextureSample) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_FLOAT4) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_TextureSample::OnInputConnectionChange(uint32 InputIndex) { SHADER_PARAMETER_TYPE expectedValueType; // determine expected texcoords type if (m_pInputs[0].IsLinked()) { switch (m_pInputs[0].GetValueType()) { case SHADER_PARAMETER_TYPE_TEXTURE1D: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT; break; case SHADER_PARAMETER_TYPE_TEXTURE1DARRAY: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT2; break; case SHADER_PARAMETER_TYPE_TEXTURE2D: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT2; break; case SHADER_PARAMETER_TYPE_TEXTURE2DARRAY: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT3; break; case SHADER_PARAMETER_TYPE_TEXTURE3D: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT3; break; case SHADER_PARAMETER_TYPE_TEXTURECUBE: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT3; break; case SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY: expectedValueType = SHADER_PARAMETER_TYPE_FLOAT4; break; default: return false; } // check texcoords are valid if (m_pInputs[1].IsLinked()) { // try a fixup swizzle (truncate) if (m_pInputs[1].GetValueType() != expectedValueType && !m_pInputs[1].SetFixupSwizzle(expectedValueType)) return false; } else { // update the expected type m_pInputs[1].SetExpectedType(expectedValueType); } } else { // clear the fixup swizzle on the input node if present if (m_pInputs[1].IsLinked()) m_pInputs[1].ClearFixupSwizzle(); else m_pInputs[1].SetExpectedType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_TextureSample::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitTextureSample(&m_pInputs[0], &m_pInputs[1], (SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION)m_eUnpackOperation); } bool ShaderGraphNode_TextureSample::LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) { if (!BaseClass::LoadFromXML(pShaderGraph, xmlReader)) return false; const char *unpackOperation = xmlReader.FetchAttribute("unpack-operation"); if (unpackOperation == NULL || !NameTable_TranslateType(NameTables::ShaderGraphTextureSampleUnpackOperation, unpackOperation, &m_eUnpackOperation, true)) { xmlReader.PrintError("could not read unpack operation attribute ('%s')", (unpackOperation != NULL) ? unpackOperation : "NULL"); return false; } return true; } void ShaderGraphNode_TextureSample::SaveToXML(XMLWriter &xmlWriter) const { BaseClass::SaveToXML(xmlWriter); xmlWriter.WriteAttribute("unpackoperation", NameTable_GetNameString(NameTables::ShaderGraphTextureSampleUnpackOperation, m_eUnpackOperation)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Variable, ShaderGraphNode, "Variable", "Variable"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Variable) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Variable) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Variable) END_SHADER_GRAPH_NODE_OUTPUTS() DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Variable, ShaderGraphNode, "Float2Variable", "Float2Variable"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Variable); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float2Variable) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float2Variable) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("X", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Y", SHADER_PARAMETER_TYPE_FLOAT, "0", true) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float2Variable) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT2) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Float2Variable::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); const ShaderGraphNodeInput *pComponentNodes[2] = { &m_pInputs[0], &m_pInputs[1] }; return pCompiler->EmitConstructPrimitive(SHADER_PARAMETER_TYPE_FLOAT2, pComponentNodes, countof(pComponentNodes)); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Variable, ShaderGraphNode, "Float3Variable", "Float3Variable"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Variable); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float3Variable) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float3Variable) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("X", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Y", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Z", SHADER_PARAMETER_TYPE_FLOAT, "0", true) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float3Variable) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT3) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Float3Variable::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); const ShaderGraphNodeInput *pComponentNodes[3] = { &m_pInputs[0], &m_pInputs[1], &m_pInputs[2] }; return pCompiler->EmitConstructPrimitive(SHADER_PARAMETER_TYPE_FLOAT3, pComponentNodes, countof(pComponentNodes)); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Variable, ShaderGraphNode, "Float4Variable", "Float4Variable"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Variable); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Float4Variable) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Float4Variable) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("X", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Y", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Z", SHADER_PARAMETER_TYPE_FLOAT, "0", true) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("W", SHADER_PARAMETER_TYPE_FLOAT, "0", true) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Float4Variable) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_FLOAT4) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Float4Variable::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); const ShaderGraphNodeInput *pComponentNodes[4] = { &m_pInputs[0], &m_pInputs[1], &m_pInputs[2], &m_pInputs[3] }; return pCompiler->EmitConstructPrimitive(SHADER_PARAMETER_TYPE_FLOAT4, pComponentNodes, countof(pComponentNodes)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Operator, ShaderGraphNode, "Operator", "Operator"); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Operator) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Operator) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Operator) END_SHADER_GRAPH_NODE_OUTPUTS() DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Add, ShaderGraphNode, "Add", "Add"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Add); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Add) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Add) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("A", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("B", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Add) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Add::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; // set combined type if (m_pInputs[0].IsLinked() && m_pInputs[1].IsLinked()) { DebugAssert(m_pInputs[0].GetValueType() == m_pInputs[1].GetValueType()); m_pOutputs[0].SetValueType(m_pInputs[0].GetValueType()); } else { m_pOutputs[0].SetValueType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_Add::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitAdd(&m_pInputs[0], &m_pInputs[1]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Subtract, ShaderGraphNode, "Subtract", "Subtract"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Subtract); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Subtract) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Subtract) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("A", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("B", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Subtract) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Subtract::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; // set combined type if (m_pInputs[0].IsLinked() && m_pInputs[1].IsLinked()) { DebugAssert(m_pInputs[0].GetValueType() == m_pInputs[1].GetValueType()); m_pOutputs[0].SetValueType(m_pInputs[0].GetValueType()); } else { m_pOutputs[0].SetValueType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_Subtract::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitSubtract(&m_pInputs[0], &m_pInputs[1]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Multiply, ShaderGraphNode, "Multiply", "Multiply"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Multiply); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Multiply) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Multiply) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("A", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("B", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Multiply) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Multiply::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; // set combined type if (m_pInputs[0].IsLinked() && m_pInputs[1].IsLinked()) { DebugAssert(m_pInputs[0].GetValueType() == m_pInputs[1].GetValueType()); m_pOutputs[0].SetValueType(m_pInputs[0].GetValueType()); } else { m_pOutputs[0].SetValueType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_Multiply::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitMultiply(&m_pInputs[0], &m_pInputs[1]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Divide, ShaderGraphNode, "Divide", "Divide"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Divide); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Divide) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Divide) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("A", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("B", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Divide) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Divide::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; // set combined type if (m_pInputs[0].IsLinked() && m_pInputs[1].IsLinked()) { DebugAssert(m_pInputs[0].GetValueType() == m_pInputs[1].GetValueType()); m_pOutputs[0].SetValueType(m_pInputs[0].GetValueType()); } else { m_pOutputs[0].SetValueType(SHADER_PARAMETER_TYPE_COUNT); } return true; } bool ShaderGraphNode_Divide::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitDivide(&m_pInputs[0], &m_pInputs[1]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Dot, ShaderGraphNode, "Dot", "Dot"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Dot); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Dot) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Dot) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("A", SHADER_PARAMETER_TYPE_COUNT, "", false) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("B", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Dot) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Result", SHADER_PARAMETER_TYPE_FLOAT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Dot::OnInputConnectionChange(uint32 InputIndex) { // check it matches the other type uint32 otherInput = (InputIndex == 0) ? 1 : 0; if (m_pInputs[otherInput].IsLinked() && m_pInputs[InputIndex].GetValueType() != m_pInputs[otherInput].GetValueType()) return false; // prevent unlinking if linked if (m_pOutputs[0].GetLinkCount() > 0 && !m_pInputs[InputIndex].IsLinked()) return false; return true; } bool ShaderGraphNode_Dot::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitDot(&m_pInputs[0], &m_pInputs[1]); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Normalize, ShaderGraphNode, "Normalize", "Normalize"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Normalize); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Normalize) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Normalize) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Normalize) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Normalize::OnInputConnectionChange(uint32 InputIndex) { SHADER_PARAMETER_TYPE inputValueType = m_pInputs[InputIndex].GetValueType(); if (inputValueType != SHADER_PARAMETER_TYPE_FLOAT && inputValueType != SHADER_PARAMETER_TYPE_FLOAT2 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT3 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT4) { return false; } m_pOutputs[0].SetValueType(inputValueType); return true; } bool ShaderGraphNode_Normalize::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitNormalize(&m_pInputs[OutputIndex]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Negate, ShaderGraphNode, "Negate", "Negate"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Negate); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_Negate) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_Negate) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_Negate) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_Negate::OnInputConnectionChange(uint32 InputIndex) { SHADER_PARAMETER_TYPE inputValueType = m_pInputs[InputIndex].GetValueType(); if (inputValueType != SHADER_PARAMETER_TYPE_FLOAT && inputValueType != SHADER_PARAMETER_TYPE_FLOAT2 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT3 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT4 && inputValueType != SHADER_PARAMETER_TYPE_INT && inputValueType != SHADER_PARAMETER_TYPE_INT2 && inputValueType != SHADER_PARAMETER_TYPE_INT3 && inputValueType != SHADER_PARAMETER_TYPE_INT4) { return false; } m_pOutputs[0].SetValueType(inputValueType); return true; } bool ShaderGraphNode_Negate::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitNegate(&m_pInputs[OutputIndex]); } DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FractionalPart, ShaderGraphNode, "FractionalPart", "Fractional part"); DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FractionalPart); BEGIN_SHADER_GRAPH_NODE_PROPERTIES(ShaderGraphNode_FractionalPart) END_SHADER_GRAPH_NODE_PROPERTIES() DEFINE_SHADER_GRAPH_NODE_INPUTS(ShaderGraphNode_FractionalPart) DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT, "", false) END_SHADER_GRAPH_NODE_INPUTS() DEFINE_SHADER_GRAPH_NODE_OUTPUTS(ShaderGraphNode_FractionalPart) DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY("Value", SHADER_PARAMETER_TYPE_COUNT) END_SHADER_GRAPH_NODE_OUTPUTS() bool ShaderGraphNode_FractionalPart::OnInputConnectionChange(uint32 InputIndex) { SHADER_PARAMETER_TYPE inputValueType = m_pInputs[InputIndex].GetValueType(); if (inputValueType != SHADER_PARAMETER_TYPE_FLOAT && inputValueType != SHADER_PARAMETER_TYPE_FLOAT2 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT3 && inputValueType != SHADER_PARAMETER_TYPE_FLOAT4) { return false; } m_pOutputs[0].SetValueType(inputValueType); return true; } bool ShaderGraphNode_FractionalPart::EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const { DebugAssert(OutputIndex == 0); return pCompiler->EmitFractionalPart(&m_pInputs[OutputIndex]); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ShaderGraph::RegisterBuiltinTypes() { #define REGISTER_TYPE(Type) Type::StaticMutableTypeInfo()->RegisterType() REGISTER_TYPE(ShaderGraphNode); REGISTER_TYPE(ShaderGraphNode_Global); REGISTER_TYPE(ShaderGraphNode_ShaderInputs); REGISTER_TYPE(ShaderGraphNode_ShaderOutputs); REGISTER_TYPE(ShaderGraphNode_Parameter); REGISTER_TYPE(ShaderGraphNode_UniformParameter); REGISTER_TYPE(ShaderGraphNode_TextureParameter); REGISTER_TYPE(ShaderGraphNode_StaticSwitchParameter); REGISTER_TYPE(ShaderGraphNode_FloatParameter); REGISTER_TYPE(ShaderGraphNode_Float2Parameter); REGISTER_TYPE(ShaderGraphNode_Float3Parameter); REGISTER_TYPE(ShaderGraphNode_Float4Parameter); REGISTER_TYPE(ShaderGraphNode_Texture2DParameter); REGISTER_TYPE(ShaderGraphNode_Texture2DArrayParameter); REGISTER_TYPE(ShaderGraphNode_Constant); REGISTER_TYPE(ShaderGraphNode_FloatConstant); REGISTER_TYPE(ShaderGraphNode_Float2Constant); REGISTER_TYPE(ShaderGraphNode_Float3Constant); REGISTER_TYPE(ShaderGraphNode_Float4Constant); REGISTER_TYPE(ShaderGraphNode_Variable); REGISTER_TYPE(ShaderGraphNode_Float2Variable); REGISTER_TYPE(ShaderGraphNode_Float3Variable); REGISTER_TYPE(ShaderGraphNode_Float4Variable); REGISTER_TYPE(ShaderGraphNode_TextureSample); REGISTER_TYPE(ShaderGraphNode_Add); REGISTER_TYPE(ShaderGraphNode_Subtract); REGISTER_TYPE(ShaderGraphNode_Multiply); REGISTER_TYPE(ShaderGraphNode_Divide); REGISTER_TYPE(ShaderGraphNode_Dot); REGISTER_TYPE(ShaderGraphNode_Normalize); REGISTER_TYPE(ShaderGraphNode_Negate); REGISTER_TYPE(ShaderGraphNode_FractionalPart); #undef REGISTER_TYPE } <file_sep>/Engine/Source/Engine/EngineCVars.h #pragma once #include "Engine/Common.h" namespace CVars { // Engine cvars extern CVar e_worker_threads; // Resource manager cvars extern CVar rm_enable_resource_compilation; extern CVar rm_maintenance_interval; extern CVar rm_remote_resource_compiler_close_delay; // Physics cvars extern CVar physics_fps; // Renderer cvars extern CVar r_platform; extern CVar r_use_render_thread; extern CVar r_multithreaded_rendering; extern CVar r_gpu_latency; extern CVar r_fullscreen; extern CVar r_fullscreen_exclusive; extern CVar r_fullscreen_width; extern CVar r_fullscreen_height; extern CVar r_windowed_width; extern CVar r_windowed_height; extern CVar r_vsync; extern CVar r_triple_buffering; extern CVar r_show_fps; extern CVar r_show_debug_info; extern CVar r_show_frame_times; extern CVar r_texture_filtering; extern CVar r_max_anisotropy; extern CVar r_material_debug_mode; extern CVar r_wireframe; extern CVar r_fullbright; extern CVar r_debug_normals; extern CVar r_deferred_shading; extern CVar r_depth_prepass; extern CVar r_show_skeletons; extern CVar r_gpu_skinning; extern CVar r_show_buffers; extern CVar r_use_light_scissor_rect; extern CVar r_occlusion_culling; extern CVar r_occlusion_culling_objects_per_buffer; extern CVar r_occlusion_culling_wait_for_results; extern CVar r_occlusion_prediction; extern CVar r_shadows; extern CVar r_shadow_map_bits; extern CVar r_directional_shadow_map_resolution; extern CVar r_point_shadow_map_resolution; extern CVar r_spot_shadow_map_resolution; extern CVar r_shadow_use_hardware_pcf; extern CVar r_shadow_filtering; extern CVar r_post_processing; extern CVar r_ssao; extern CVar r_use_shader_cache; extern CVar r_allow_shader_cache_writes; extern CVar r_use_debug_device; extern CVar r_use_debug_shaders; extern CVar r_dump_shaders; extern CVar r_enable_multithreaded_resource_creation; extern CVar r_sprite_draw_instanced_quads; extern CVar r_emulate_mobile; // Renderer debug cvars extern CVar r_show_cascades; // Terrain renderer cvars extern CVar r_terrain_renderer; extern CVar r_terrain_render_resolution_multiplier; extern CVar r_terrain_lod_distance_ratio; extern CVar r_terrain_view_distance; extern CVar r_terrain_show_nodes; } <file_sep>/Engine/Source/Renderer/Shaders/ShadowMapShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/ShadowMapShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(ShadowMapShader); BEGIN_SHADER_COMPONENT_PARAMETERS(ShadowMapShader) END_SHADER_COMPONENT_PARAMETERS() bool ShadowMapShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == NULL) return false; return true; } bool ShadowMapShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ShadowMapShader.hlsl", "VSMain"); // Disable pixel shader on materials that don't contain any clipping. if (!pParameters->MaterialShaderName.IsEmpty()) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/ShadowMapShader.hlsl", "PSMain"); pParameters->AddPreprocessorMacro("WITH_MATERIAL", "1"); } // ES2/3 require a fragment shader else if (pParameters->FeatureLevel <= RENDERER_FEATURE_LEVEL_ES3) pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/ShadowMapShader.hlsl", "PSMain"); return true; } <file_sep>/Engine/Source/Engine/BlockMeshUtilities.h #pragma once #include "Engine/Common.h" #include "Engine/BlockPalette.h" #include "Engine/BlockMeshVolume.h" namespace BlockMeshUtilities { float RayMeshIntersection(int3 *pHitPosition, uint8 *pHitFace, const BlockPalette *pBlockList, const int3 &meshMinCoordinates, const int3 &meshMaxCoordinates, const BlockVolumeBlockType *pBlockData, const Ray &ray); float RayMeshIntersection(int32 *pHitX, int32 *pHitY, int32 *pHitZ, uint8 *pHitFace, const BlockPalette *pBlockList, int32 meshMinX, int32 meshMinY, int32 meshMinZ, int32 meshMaxX, int32 meshMaxY, int32 meshMaxZ, const BlockVolumeBlockType *pBlockData, const Ray &ray); void CreateMeshLOD(uint8 *pOutBlockData, uint32 lodLevel, const BlockPalette *pBlockList, const uint8 *pBlockData, uint32 meshSize); }; // namespace BlockMeshUtilities<file_sep>/Engine/Source/Renderer/RenderQueue.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderQueue.h" #include "Engine/Material.h" //Log_SetChannel(Renderer); static uint32 GetTransparencyKey(const RENDER_QUEUE_RENDERABLE_ENTRY *pEntry) { switch (pEntry->pMaterial->GetShader()->GetBlendMode()) { case MATERIAL_BLENDING_MODE_MASKED: return 1; case MATERIAL_BLENDING_MODE_STRAIGHT: case MATERIAL_BLENDING_MODE_PREMULTIPLIED: case MATERIAL_BLENDING_MODE_SOFTMASKED: return 2; //case MATERIAL_BLENDING_MODE_NONE: //case MATERIAL_BLENDING_MODE_ADDITIVE: //default: } if ((pEntry->RenderPassMask & RENDER_PASS_TINT) && (pEntry->TintColor >> 24) != 0xFF) return 2; else return 0; } static uint64 MakeSortKey(const RENDER_QUEUE_RENDERABLE_ENTRY *pEntry, uint32 transparencyKey) { uint32 transparencyPart, layerPart, materialPart, depthPart; static const uint32 transparencyPartFilter = 0x00000003; // 2 bits //static const uint64 transparencyPartMask = 0xC000000000000000ULL; // 2 bits static const uint32 layerPartFilter = 0x00000007; // 3 bits //static const uint64 layerPartMask = 0x3800000000000000ULL; // 3 bits static const uint32 materialPartFilter = 0x07FFFFFF; // 27 bits //static const uint64 materialPartMask = 0x07FFFFFF00000000ULL; // 27 bits static const uint32 depthPartFilter = 0xFFFFFFFF; // 32 bits //static const uint64 depthPartMask = 0x00000000FFFFFFFFULL; // 32 bits transparencyPart = transparencyKey & 0xFF; layerPart = pEntry->Layer & layerPartFilter; // generate material id, fixme later materialPart = HashTrait<String>::GetHash(pEntry->pMaterial->GetName()); // split the number float realPart, fractionalPart; Y_splitf(&realPart, &fractionalPart, Y_fabs(pEntry->ViewDistance)); // use the first 24 bits for the real part depthPart = (Min((uint32)0xFFFFFF, (uint32)Y_truncf(realPart))) << 8; // use the last 8 bits for the fractional part depthPart |= (uint32)Y_truncf(fractionalPart * 255.0f); // sort front-to-back for opaque, back-to-front for transparent // also flip the depth and material bits around so depth gets first priority if (transparencyPart == 2) { depthPart = 0xFFFFFFFF - depthPart; return (uint64(transparencyPart & transparencyPartFilter) << 62) | (uint64(layerPart & layerPartFilter) << 60) | (uint64(depthPart & materialPartFilter) << 27) | (uint64(materialPart & depthPartFilter)); } else { return (uint64(transparencyPart & transparencyPartFilter) << 62) | (uint64(layerPart & layerPartFilter) << 60) | (uint64(materialPart & materialPartFilter) << 32) | (uint64(depthPart & depthPartFilter)); } } RenderQueue::RenderQueue() : m_acceptingLights(false), m_acceptingRenderPassMask(0), m_acceptingOccluders(false), m_acceptingDebugObjects(false), m_queueSize(0), m_numObjectsInvalidatedByOcclusion(0), m_directionalLightArray(1), m_pointLightArray(16), m_spotLightArray(8), m_opaqueRenderables(2048), m_translucentRenderables(1024), m_occluders(512), m_debugDrawObjects(128) { } RenderQueue::~RenderQueue() { } void RenderQueue::AddLight(const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLightEntry) { if (!m_acceptingLights) return; DebugAssert(pLightEntry->ShadowMapIndex == -1); m_directionalLightArray.Add(*pLightEntry); m_queueSize++; } void RenderQueue::AddLight(const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLightEntry) { if (!m_acceptingLights) return; DebugAssert(pLightEntry->ShadowMapIndex == -1); m_pointLightArray.Add(*pLightEntry); m_queueSize++; } void RenderQueue::AddLight(const RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLightEntry) { if (!m_acceptingLights) return; DebugAssert(pLightEntry->ShadowMapIndex == -1); m_spotLightArray.Add(*pLightEntry); m_queueSize++; } void RenderQueue::AddLight(const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLightEntry) { if (!m_acceptingLights) return; m_volumetricLightArray.Add(*pLightEntry); m_queueSize++; } void RenderQueue::AddRenderable(const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { uint32 newMask = pQueueEntry->RenderPassMask & m_acceptingRenderPassMask; if (newMask == 0) return; // throw out tinted objects with an opacity of zero if ((newMask & RENDER_PASS_TINT) && (pQueueEntry->TintColor >> 24) == 0) return; // calc transparency key uint32 transparencyKey = GetTransparencyKey(pQueueEntry); RENDER_QUEUE_RENDERABLE_ENTRY *pAddedEntry; if (pQueueEntry->pMaterial->GetShader()->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) { m_postProcessRenderables.Add(*pQueueEntry); pAddedEntry = m_postProcessRenderables.GetBasePointer() + (m_postProcessRenderables.GetSize() - 1); } else { if (transparencyKey != 2) { m_opaqueRenderables.Add(*pQueueEntry); pAddedEntry = m_opaqueRenderables.GetBasePointer() + (m_opaqueRenderables.GetSize() - 1); } else { m_translucentRenderables.Add(*pQueueEntry); pAddedEntry = m_translucentRenderables.GetBasePointer() + (m_translucentRenderables.GetSize() - 1); } } pAddedEntry->SortKey = MakeSortKey(pAddedEntry, transparencyKey); pAddedEntry->RenderPassMask = newMask; m_queueSize++; } void RenderQueue::AddOccluder(const RENDER_QUEUE_OCCLUDER_ENTRY *pOccluderEntry) { if (!m_acceptingOccluders) return; m_occluders.Add(*pOccluderEntry); m_queueSize++; } void RenderQueue::AddOccluder(const RenderProxy *pRenderProxy, const AABox &boundingBox) { if (!m_acceptingOccluders) return; RENDER_QUEUE_OCCLUDER_ENTRY occluderEntry; occluderEntry.pRenderProxy = pRenderProxy; occluderEntry.MatchUserData = false; occluderEntry.BoundingBox = boundingBox; m_occluders.Add(occluderEntry); } void RenderQueue::AddOccluder(const RenderProxy *pRenderProxy, const AABox &boundingBox, const uint32 userData[], const void *const userDataPointer[]) { if (!m_acceptingOccluders) return; RENDER_QUEUE_OCCLUDER_ENTRY occluderEntry; occluderEntry.pRenderProxy = pRenderProxy; Y_memcpy(occluderEntry.UserData, userData, sizeof(occluderEntry.UserData)); Y_memcpy(occluderEntry.UserDataPointer, userDataPointer, sizeof(occluderEntry.UserDataPointer)); occluderEntry.MatchUserData = true; occluderEntry.BoundingBox = boundingBox; m_occluders.Add(occluderEntry); } void RenderQueue::AddDebugInfoObject(const RenderProxy *pRenderProxy) { if (!m_acceptingDebugObjects) return; m_debugDrawObjects.Add(pRenderProxy); m_queueSize++; } void RenderQueue::InvalidateOpaqueRenderProxy(const RenderProxy *pRenderProxy) { if (m_opaqueRenderables.GetSize() == 0) return; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_opaqueRenderables.GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_opaqueRenderables.GetBasePointer() + m_opaqueRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy) { pQueueEntry->RenderPassMask = 0; m_numObjectsInvalidatedByOcclusion++; } } pQueueEntry = m_translucentRenderables.GetBasePointer(); pQueueEntryEnd = m_translucentRenderables.GetBasePointer() + m_translucentRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy) { pQueueEntry->RenderPassMask = 0; m_numObjectsInvalidatedByOcclusion++; } } } void RenderQueue::InvalidateOpaqueRenderProxy(const RenderProxy *pRenderProxy, const uint32 userData[], const void *const userDataPointer[]) { if (m_opaqueRenderables.GetSize() == 0) return; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_opaqueRenderables.GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_opaqueRenderables.GetBasePointer() + m_opaqueRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy && Y_memcmp(pQueueEntry->UserData, userData, sizeof(pQueueEntry->UserData)) == 0 && Y_memcmp(pQueueEntry->UserDataPointer, userDataPointer, sizeof(pQueueEntry->UserDataPointer)) == 0) { pQueueEntry->RenderPassMask = 0; m_numObjectsInvalidatedByOcclusion++; } } pQueueEntry = m_translucentRenderables.GetBasePointer(); pQueueEntryEnd = m_translucentRenderables.GetBasePointer() + m_translucentRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy && Y_memcmp(pQueueEntry->UserData, userData, sizeof(pQueueEntry->UserData)) == 0 && Y_memcmp(pQueueEntry->UserDataPointer, userDataPointer, sizeof(pQueueEntry->UserDataPointer)) == 0) { pQueueEntry->RenderPassMask = 0; m_numObjectsInvalidatedByOcclusion++; } } } void RenderQueue::MarkRenderProxyWithPredicate(const RenderProxy *pRenderProxy, GPUQuery *pPredicate) { if (m_opaqueRenderables.GetSize() == 0) return; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_opaqueRenderables.GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_opaqueRenderables.GetBasePointer() + m_opaqueRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy) { DebugAssert(pQueueEntry->pPredicate == nullptr); pQueueEntry->pPredicate = pPredicate; m_numObjectsInvalidatedByOcclusion++; } } pQueueEntry = m_translucentRenderables.GetBasePointer(); pQueueEntryEnd = m_translucentRenderables.GetBasePointer() + m_translucentRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy) { DebugAssert(pQueueEntry->pPredicate == nullptr); pQueueEntry->pPredicate = pPredicate; m_numObjectsInvalidatedByOcclusion++; } } } void RenderQueue::MarkRenderProxyWithPredicate(const RenderProxy *pRenderProxy, const uint32 userData[], const void *const userDataPointer[], GPUQuery *pPredicate) { if (m_opaqueRenderables.GetSize() == 0) return; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_opaqueRenderables.GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_opaqueRenderables.GetBasePointer() + m_opaqueRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy && Y_memcmp(pQueueEntry->UserData, userData, sizeof(pQueueEntry->UserData)) == 0 && Y_memcmp(pQueueEntry->UserDataPointer, userDataPointer, sizeof(pQueueEntry->UserDataPointer)) == 0) { DebugAssert(pQueueEntry->pPredicate == nullptr); pQueueEntry->pPredicate = pPredicate; m_numObjectsInvalidatedByOcclusion++; } } pQueueEntry = m_translucentRenderables.GetBasePointer(); pQueueEntryEnd = m_translucentRenderables.GetBasePointer() + m_translucentRenderables.GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->pRenderProxy == pRenderProxy && Y_memcmp(pQueueEntry->UserData, userData, sizeof(pQueueEntry->UserData)) == 0 && Y_memcmp(pQueueEntry->UserDataPointer, userDataPointer, sizeof(pQueueEntry->UserDataPointer)) == 0) { DebugAssert(pQueueEntry->pPredicate == nullptr); pQueueEntry->pPredicate = pPredicate; m_numObjectsInvalidatedByOcclusion++; } } } /* static int CompFunc(const RENDER_QUEUE_RENDERABLE_ENTRY *pLHS, const RENDER_QUEUE_RENDERABLE_ENTRY *pRHS) { // bleh, unsigned ints make life harder if (pLHS->SortKey > pRHS->SortKey) return 1; else if (pLHS->SortKey < pRHS->SortKey) return -1; else return 0; }*/ static bool CompFuncSTL(const RENDER_QUEUE_RENDERABLE_ENTRY &lhs, const RENDER_QUEUE_RENDERABLE_ENTRY &rhs) { return (lhs.SortKey < rhs.SortKey); } void RenderQueue::Sort() { if (m_opaqueRenderables.GetSize() > 0) { //Y_qsortT<RENDER_QUEUE_RENDERABLE_ENTRY>(m_opaqueRenderables.GetBasePointer(), m_opaqueRenderables.GetSize(), CompFunc); std::sort(m_opaqueRenderables.GetBasePointer(), m_opaqueRenderables.GetBasePointer() + m_opaqueRenderables.GetSize(), CompFuncSTL); } if (m_translucentRenderables.GetSize() > 0) { //Y_qsortT<RENDER_QUEUE_RENDERABLE_ENTRY>(m_translucentRenderables.GetBasePointer(), m_translucentRenderables.GetSize(), CompFunc); std::sort(m_translucentRenderables.GetBasePointer(), m_translucentRenderables.GetBasePointer() + m_translucentRenderables.GetSize(), CompFuncSTL); } } void RenderQueue::Clear() { m_directionalLightArray.Clear(); m_pointLightArray.Clear(); m_spotLightArray.Clear(); m_volumetricLightArray.Clear(); m_opaqueRenderables.Clear(); m_translucentRenderables.Clear(); m_postProcessRenderables.Clear(); m_occluders.Clear(); m_debugDrawObjects.Clear(); m_queueSize = 0; m_numObjectsInvalidatedByOcclusion = 0; } <file_sep>/Engine/Source/Engine/TerrainRenderer.h #pragma once #include "Engine/Common.h" #include "Engine/TerrainSection.h" #include "Renderer/RenderProxy.h" class TerrainSectionRendererData; class TerrainSectionRenderProxy; class TerrainRenderer { friend class TerrainManager; public: TerrainRenderer(TERRAIN_RENDERER_TYPE type, const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); virtual ~TerrainRenderer(); // accessors const TERRAIN_RENDERER_TYPE GetType() const { return m_type; } const TerrainParameters *GetTerrainParameters() const { return &m_parameters; } const TerrainLayerList *GetLayerList() const { return m_pLayerList; } // create a render proxy for a section virtual TerrainSectionRenderProxy *CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) = 0; // gpu resources virtual bool CreateGPUResources() = 0; virtual void ReleaseGPUResources() = 0; ////////////////////////////////////////////////////////////////////////// // create renderer static TerrainRenderer *CreateTerrainRenderer(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); protected: // vars TERRAIN_RENDERER_TYPE m_type; TerrainParameters m_parameters; const TerrainLayerList *m_pLayerList; }; class TerrainSectionRenderProxy : public RenderProxy { public: TerrainSectionRenderProxy(uint32 entityId, const TerrainSection *pSection); virtual ~TerrainSectionRenderProxy(); // section access const TerrainSection *GetSection() const { return m_pSection; } const int32 GetSectionX() const { return m_sectionX; } const int32 GetSectionY() const { return m_sectionY; } // when a layer is added to a section virtual void OnLayersModified() = 0; // when a height value is modified virtual void OnPointHeightModified(uint32 x, uint32 y) = 0; // when a layer weight is modified virtual void OnPointLayersModified(uint32 x, uint32 y) = 0; // we implement the raycasting and intersections in the base class, they are common between all renderer types virtual bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const override; virtual uint32 GetIntersectingTriangles(const AABox &searchBox, IntersectingTriangleArray &intersectingTriangles) const override; protected: const TerrainSection *m_pSection; int32 m_sectionX, m_sectionY; }; // keep section in memory //bool IsSectionInVisibleRange(int32 sectionX, int32 sectionY) const; <file_sep>/Engine/Source/GameFramework/InterpolatorComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/InterpolatorComponent.h" #include "Engine/Entity.h" Log_SetChannel(InterpolatorComponent); DEFINE_COMPONENT_TYPEINFO(InterpolatorComponent); DEFINE_COMPONENT_GENERIC_FACTORY(InterpolatorComponent); BEGIN_COMPONENT_PROPERTIES(InterpolatorComponent) PROPERTY_TABLE_MEMBER_FLOAT("MoveDuration", 0, offsetof(InterpolatorComponent, m_moveDuration), PropertyCallbackOnMoveDurationChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("PauseDuration", 0, offsetof(InterpolatorComponent, m_pauseDuration), PropertyCallbackOnMoveDurationChange, nullptr) PROPERTY_TABLE_MEMBER_BOOL("ReverseCycle", 0, offsetof(InterpolatorComponent, m_reverseCycle), PropertyCallbackOnReverseCycleChange, nullptr) PROPERTY_TABLE_MEMBER_UINT("RepeatCount", 0, offsetof(InterpolatorComponent, m_repeatCount), PropertyCallbackOnRepeatCountChange, nullptr) PROPERTY_TABLE_MEMBER_UINT("EasingFunction", 0, offsetof(InterpolatorComponent, m_easingFunction), PropertyCallbackOnEasingFunctionChange, nullptr) PROPERTY_TABLE_MEMBER_BOOL("AutoActivate", 0, offsetof(InterpolatorComponent, m_autoActivate), PropertyCallbackOnAutoActivateChange, nullptr) END_COMPONENT_PROPERTIES() InterpolatorComponent::InterpolatorComponent(const ComponentTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_moveDuration(1.0f), m_pauseDuration(0.0f), m_reverseCycle(true), m_repeatCount(0), m_easingFunction(EasingFunction::Linear), m_autoActivate(true), m_active(false), m_positionInterpolator(float3::Zero, float3::Zero, m_moveDuration, m_pauseDuration, m_reverseCycle, m_repeatCount, (EasingFunction::Type)m_easingFunction), m_rotationInterpolator(Quaternion::Identity, Quaternion::Identity, m_moveDuration, m_pauseDuration, m_reverseCycle, m_repeatCount, (EasingFunction::Type)m_easingFunction), m_scaleInterpolator(float3::One, float3::One, m_moveDuration, m_pauseDuration, m_reverseCycle, m_repeatCount, (EasingFunction::Type)m_easingFunction), m_activeInterpolatorMask(0) { } InterpolatorComponent::~InterpolatorComponent() { } void InterpolatorComponent::SetMoveDuration(float moveDuration) { if (m_moveDuration == moveDuration) return; m_moveDuration = moveDuration; PropertyCallbackOnMoveDurationChange(this); } void InterpolatorComponent::SetPauseDuration(float pauseDuration) { if (m_pauseDuration == pauseDuration) return; m_pauseDuration = pauseDuration; PropertyCallbackOnPauseDurationChange(this); } void InterpolatorComponent::SetReverseCycle(bool autoReverse) { if (m_reverseCycle == autoReverse) return; m_reverseCycle = autoReverse; PropertyCallbackOnReverseCycleChange(this); } void InterpolatorComponent::SetRepeatCount(uint32 repeatCount) { if (m_repeatCount == repeatCount) return; m_repeatCount = repeatCount; PropertyCallbackOnRepeatCountChange(this); } void InterpolatorComponent::SetEasingFunction(EasingFunction::Type easingFunction) { if (m_easingFunction == (uint32)easingFunction) return; m_easingFunction = (uint32)easingFunction; PropertyCallbackOnEasingFunctionChange(this); } void InterpolatorComponent::SetAutoActivate(bool autoActivate) { if (m_autoActivate == autoActivate) return; m_autoActivate = autoActivate; PropertyCallbackOnAutoActivateChange(this); } void InterpolatorComponent::Create(const float3 &moveAmount /* = float3::Zero */, const Quaternion &rotationAmount /* = Quaternion::Identity */, const float3 &scaleAmount /* = float3::One */, float moveDuration /* = 1.0f */, float pauseDuration /* = 0.0f */, bool reverseCycle /* = true */, uint32 repeatCount /* = 0 */, EasingFunction::Type easingFunction /* = EasingFunction::Linear */, bool autoActivate /* = true */) { DebugAssert(moveDuration > 0.0f); m_localPosition = (!moveAmount.NearEqual(float3::Zero, Y_FLT_EPSILON)) ? moveAmount : float3::Zero; m_localRotation = (rotationAmount != Quaternion::Identity) ? rotationAmount : Quaternion::Identity; m_localScale = (!scaleAmount.NearEqual(float3::One, Y_FLT_EPSILON)) ? scaleAmount : float3::One; m_moveDuration = moveDuration; m_pauseDuration = pauseDuration; m_reverseCycle = reverseCycle; m_repeatCount = repeatCount; m_easingFunction = (uint32)easingFunction; m_autoActivate = autoActivate; Initialize(); } void InterpolatorComponent::UpdateActiveInterpolators() { m_activeInterpolatorMask = 0; if (!m_localPosition.NearEqual(float3::Zero, Y_FLT_EPSILON)) { m_activeInterpolatorMask |= ActiveInterpolator_Position; m_positionInterpolator.SetEndValue(m_positionInterpolator.GetStartValue() + m_localPosition); m_positionInterpolator.Reset(); } if (m_localRotation != Quaternion::Identity) { m_activeInterpolatorMask |= ActiveInterpolator_Rotation; m_rotationInterpolator.SetEndValue(m_rotationInterpolator.GetStartValue() * m_localRotation); m_rotationInterpolator.Reset(); } if (!m_localScale.NearEqual(float3::One, Y_FLT_EPSILON)) { m_activeInterpolatorMask |= ActiveInterpolator_Scale; m_scaleInterpolator.SetEndValue(m_scaleInterpolator.GetStartValue() * m_localScale); m_scaleInterpolator.Reset(); } } void InterpolatorComponent::Reset() { if (m_activeInterpolatorMask & ActiveInterpolator_Position) m_positionInterpolator.Reset(); if (m_activeInterpolatorMask & ActiveInterpolator_Rotation) m_rotationInterpolator.Reset(); if (m_activeInterpolatorMask & ActiveInterpolator_Scale) m_scaleInterpolator.Reset(); if (m_pEntity != nullptr) { if (m_activeInterpolatorMask & ActiveInterpolator_Position) m_pEntity->SetPosition(m_positionInterpolator.GetCurrentValue()); if (m_activeInterpolatorMask & ActiveInterpolator_Rotation) m_pEntity->SetRotation(m_rotationInterpolator.GetCurrentValue()); if (m_activeInterpolatorMask & ActiveInterpolator_Scale) m_pEntity->SetScale(m_scaleInterpolator.GetCurrentValue()); } } void InterpolatorComponent::Activate() { if (!m_active) { m_active = true; if (IsAttachedToEntity()) m_pEntity->RegisterForUpdates(0.0f); } } void InterpolatorComponent::Deactivate() { m_active = false; } bool InterpolatorComponent::Initialize() { if (!BaseClass::Initialize()) return false; // initialize the interpolators DebugAssert(m_easingFunction < EasingFunction::TypeCount); m_positionInterpolator.SetMoveDuration(m_moveDuration); m_positionInterpolator.SetPauseDuration(m_pauseDuration); m_positionInterpolator.SetReverseCycle(m_reverseCycle); m_positionInterpolator.SetRepeatCount(m_repeatCount); m_positionInterpolator.SetFunction((EasingFunction::Type)m_easingFunction); m_rotationInterpolator.SetMoveDuration(m_moveDuration); m_rotationInterpolator.SetPauseDuration(m_pauseDuration); m_rotationInterpolator.SetReverseCycle(m_reverseCycle); m_rotationInterpolator.SetRepeatCount(m_repeatCount); m_rotationInterpolator.SetFunction((EasingFunction::Type)m_easingFunction); m_scaleInterpolator.SetMoveDuration(m_moveDuration); m_scaleInterpolator.SetPauseDuration(m_pauseDuration); m_scaleInterpolator.SetReverseCycle(m_reverseCycle); m_scaleInterpolator.SetRepeatCount(m_repeatCount); m_scaleInterpolator.SetFunction((EasingFunction::Type)m_easingFunction); // update which ones are active and set values UpdateActiveInterpolators(); return true; } void InterpolatorComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // extract the starting position from the entity's current position m_positionInterpolator.SetValues(m_pEntity->GetPosition(), m_pEntity->GetPosition() + m_localPosition); m_rotationInterpolator.SetValues(m_pEntity->GetRotation(), m_pEntity->GetRotation() * m_localRotation); m_scaleInterpolator.SetValues(m_pEntity->GetScale(), m_pEntity->GetScale() * m_localScale); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate && pEntity->IsInWorld()) pEntity->RegisterForUpdates(0.0f); } void InterpolatorComponent::OnRemoveFromEntity(Entity *pEntity) { // ensure we're deactivated m_active = false; BaseClass::OnRemoveFromEntity(pEntity); } void InterpolatorComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate || m_active) m_pEntity->RegisterForUpdates(0.0f); } void InterpolatorComponent::OnRemoveFromWorld(World *pWorld) { BaseClass::OnRemoveFromWorld(pWorld); } void InterpolatorComponent::OnLocalTransformChange() { BaseClass::OnLocalTransformChange(); // update the ending position only, the starting position will still be valid UpdateActiveInterpolators(); } void InterpolatorComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // update the starting position of the interpolators if the value differs from the current value if (m_activeInterpolatorMask & ActiveInterpolator_Position && m_pEntity->GetPosition() != m_positionInterpolator.GetCurrentValue()) m_positionInterpolator.SetValues(m_pEntity->GetPosition(), m_pEntity->GetPosition() + m_localPosition); if (m_activeInterpolatorMask & ActiveInterpolator_Rotation && m_pEntity->GetRotation() != m_rotationInterpolator.GetCurrentValue()) m_rotationInterpolator.SetValues(m_pEntity->GetRotation(), m_pEntity->GetRotation() * m_localRotation); if (m_activeInterpolatorMask & ActiveInterpolator_Scale && m_pEntity->GetScale() != m_scaleInterpolator.GetCurrentValue()) m_scaleInterpolator.SetValues(m_pEntity->GetScale(), m_pEntity->GetScale() * m_localScale); } void InterpolatorComponent::Update(float timeSinceLastUpdate) { // this is where the magic happens if (!m_active && m_autoActivate) Activate(); // active? if (m_active) { // update interpolator, and value if it has changed if (m_activeInterpolatorMask & ActiveInterpolator_Position) { m_positionInterpolator.Update(timeSinceLastUpdate); if (m_pEntity->GetPosition() != m_positionInterpolator.GetCurrentValue()) m_pEntity->SetPosition(m_positionInterpolator.GetCurrentValue()); } if (m_activeInterpolatorMask & ActiveInterpolator_Rotation) { m_rotationInterpolator.Update(timeSinceLastUpdate); if (m_pEntity->GetRotation() != m_rotationInterpolator.GetCurrentValue()) m_pEntity->SetRotation(m_rotationInterpolator.GetCurrentValue()); } if (m_activeInterpolatorMask & ActiveInterpolator_Scale) { m_scaleInterpolator.Update(timeSinceLastUpdate); if (m_pEntity->GetScale() != m_scaleInterpolator.GetCurrentValue()) m_pEntity->SetScale(m_scaleInterpolator.GetCurrentValue()); } // if all cycles are complete, deactivate ourselves if ((m_positionInterpolator.IsActive() | m_rotationInterpolator.IsActive() | m_scaleInterpolator.IsActive())) m_active = false; } } void InterpolatorComponent::PropertyCallbackOnMoveDurationChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_positionInterpolator.SetMoveDuration(pComponent->m_moveDuration); pComponent->m_rotationInterpolator.SetMoveDuration(pComponent->m_moveDuration); pComponent->m_scaleInterpolator.SetMoveDuration(pComponent->m_moveDuration); pComponent->Reset(); } void InterpolatorComponent::PropertyCallbackOnPauseDurationChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_positionInterpolator.SetPauseDuration(pComponent->m_pauseDuration); pComponent->m_rotationInterpolator.SetPauseDuration(pComponent->m_pauseDuration); pComponent->m_scaleInterpolator.SetPauseDuration(pComponent->m_pauseDuration); pComponent->Reset(); } void InterpolatorComponent::PropertyCallbackOnReverseCycleChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_positionInterpolator.SetReverseCycle(pComponent->m_reverseCycle); pComponent->m_rotationInterpolator.SetReverseCycle(pComponent->m_reverseCycle); pComponent->m_scaleInterpolator.SetReverseCycle(pComponent->m_reverseCycle); pComponent->Reset(); } void InterpolatorComponent::PropertyCallbackOnRepeatCountChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_positionInterpolator.SetRepeatCount(pComponent->m_repeatCount); pComponent->m_rotationInterpolator.SetRepeatCount(pComponent->m_repeatCount); pComponent->m_scaleInterpolator.SetRepeatCount(pComponent->m_repeatCount); pComponent->Reset(); } void InterpolatorComponent::PropertyCallbackOnEasingFunctionChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { DebugAssert(pComponent->m_easingFunction < EasingFunction::TypeCount); pComponent->m_positionInterpolator.SetFunction((EasingFunction::Type)pComponent->m_easingFunction); pComponent->m_rotationInterpolator.SetFunction((EasingFunction::Type)pComponent->m_easingFunction); pComponent->m_scaleInterpolator.SetFunction((EasingFunction::Type)pComponent->m_easingFunction); pComponent->Reset(); } void InterpolatorComponent::PropertyCallbackOnAutoActivateChange(InterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_autoActivate && !pComponent->m_active && pComponent->IsAttachedToEntity()) pComponent->m_pEntity->RegisterForUpdates(0.0f); } <file_sep>/Engine/Source/MathLib/Angle.h #pragma once #include "MathLib/Common.h" class Angle { public: // Constructs an angle from a degree value Angle(float degrees); // Copies another angle Angle(const Angle &angle); // Converts the angle to a degrees value. float Degrees() const; // Converts the angle to a radians value. float Radians() const; // Setters void SetDegrees(float degrees); void SetRadians(float radians); // Normalize the angle between [0, 360 or PI*2] void Normalize(); Angle Normalized() const; // Constructs a new angle from a radian value. static Angle Radians(float radians); // Constructs a new angle from a degrees value. static Angle Degrees(float degrees); // Overloaded operators bool operator==(const Angle &other) const; bool operator!=(const Angle &other) const; bool operator>=(const Angle &other) const; bool operator<=(const Angle &other) const; bool operator<(const Angle &other) const; bool operator>(const Angle &other) const; // Modification operators Angle &operator=(const Angle &other); Angle &operator+=(const Angle &other); Angle &operator-=(const Angle &other); // Builder operators Angle operator+(const Angle &other) const; Angle operator-(const Angle &other) const; private: // Empty constructor, sets uninitialized. Angle() {} // stored internally as radians for fast access float m_radians; }; <file_sep>/Engine/Source/Engine/ScriptPrimitiveTypes.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptManager.h" #include "Engine/ScriptProxyFunctions.h" #include "lua.hpp" // Primitive types builtin to lua language template<> bool ScriptArg<bool>::Get(lua_State *L, int arg) { return (luaL_checkinteger(L, arg) != 0); } template<> void ScriptArg<bool>::Push(lua_State *L, const bool &arg) { lua_pushboolean(L, (int)arg); } template<> int8 ScriptArg<int8>::Get(lua_State *L, int arg) { return (int8)luaL_checkinteger(L, arg); } template<> void ScriptArg<int8>::Push(lua_State *L, const int8 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> uint8 ScriptArg<uint8>::Get(lua_State *L, int arg) { return (uint8)luaL_checkinteger(L, arg); } template<> void ScriptArg<uint8>::Push(lua_State *L, const uint8 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> int16 ScriptArg<int16>::Get(lua_State *L, int arg) { return (int16)luaL_checkinteger(L, arg); } template<> void ScriptArg<int16>::Push(lua_State *L, const int16 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> uint16 ScriptArg<uint16>::Get(lua_State *L, int arg) { return (uint16)luaL_checkinteger(L, arg); } template<> void ScriptArg<uint16>::Push(lua_State *L, const uint16 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> int32 ScriptArg<int32>::Get(lua_State *L, int arg) { return (int32)luaL_checkinteger(L, arg); } template<> void ScriptArg<int32>::Push(lua_State *L, const int32 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> uint32 ScriptArg<uint32>::Get(lua_State *L, int arg) { return (uint32)luaL_checkinteger(L, arg); } template<> void ScriptArg<uint32>::Push(lua_State *L, const uint32 &arg) { lua_pushinteger(L, (lua_Integer)arg); } template<> float ScriptArg<float>::Get(lua_State *L, int arg) { return (float)luaL_checknumber(L, arg); } template<> void ScriptArg<float>::Push(lua_State *L, const float &arg) { lua_pushnumber(L, (lua_Number)arg); } template<> double ScriptArg<double>::Get(lua_State *L, int arg) { return (double)luaL_checknumber(L, arg); } template<> void ScriptArg<double>::Push(lua_State *L, const double &arg) { lua_pushnumber(L, (lua_Number)arg); } template<> const char *ScriptArg<const char *>::Get(lua_State *L, int arg) { return luaL_checkstring(L, arg); } template<> void ScriptArg<const char *>::Push(lua_State *L, const char *const &arg) { lua_pushstring(L, arg); } template<> String ScriptArg<String>::Get(lua_State *L, int arg) { return String(luaL_checkstring(L, arg)); } template<> void ScriptArg<String>::Push(lua_State *L, const String &arg) { lua_pushstring(L, arg); } // Complex type template<class T> struct ScriptComplexType { }; // So messy... fix this. template<> struct ScriptComplexType<bool> { static bool Get(lua_State *L, int arg) { return (luaL_checkinteger(L, arg) != 0); } static void Push(lua_State *L, const bool &arg) { lua_pushboolean(L, (int)arg); } }; template<> struct ScriptComplexType<float> { static float Get(lua_State *L, int arg) { return (float)luaL_checknumber(L, arg); } static void Push(lua_State *L, const float &arg) { lua_pushnumber(L, (lua_Number)arg); } }; // float2 template<> struct ScriptComplexType<float2> { static inline ScriptReferenceType &MetaTableReference() { static ScriptReferenceType ref = INVALID_SCRIPT_REFERENCE; return ref; } static inline const char *Name() { return "float2"; } // get/push methods static float2 Get(lua_State *L, int arg) { return float2(*reinterpret_cast<const float2 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg))); } static void Push(lua_State *L, const float2 &arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float2), &arg); } // get/push ptr methods static float2 *GetPtr(lua_State *L, int arg) { return reinterpret_cast<float2 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg)); } static void PushPtr(lua_State *L, const float2 *arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float2), arg); } // Metamethods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__add, float2, float2, operator+, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__sub, float2, float2, operator-, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mul, float2, float2, operator*, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__div, float2, float2, operator*, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mod, float2, float2, operator%, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__unm, float2, float2, operator-, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__eq, bool, float2, operator==, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__lt, bool, float2, operator<, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__le, bool, float2, operator<=, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__gt, bool, float2, operator>, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__ge, bool, float2, operator>=, float2); // Methods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P2(Set, float2, Set, float, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SetZero, float2, SetZero); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyLess, bool, float2, AnyLess, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyGreater, bool, float2, AnyGreater, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(NearEqual, bool, float2, NearEqual, float2, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(IsFinite, bool, float2, IsFinite); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Min, float2, float2, Min, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Max, float2, float2, Max, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Clamp, float2, float2, Clamp, float2, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Abs, float2, float2, Abs); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Saturate, float2, float2, Saturate); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Snap, float2, float2, Snap, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Floor, float2, float2, Floor); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Ceil, float2, float2, Ceil); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Round, float2, float2, Round); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Dot, float, float2, Dot, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Lerp, float2, float2, Lerp, float2, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SquaredLength, float, float2, SquaredLength); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Length, float, float2, Length); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(SquaredDistance, float, float2, SquaredDistance, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Distance, float, float2, Distance, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Normalize, float2, float2, Normalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(NormalizeEst, float2, float2, NormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeInPlace, float2, NormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeEstInPlace, float2, NormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalize, float2, float2, SafeNormalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalizeEst, float2, float2, SafeNormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeInPlace, float2, SafeNormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeEstInPlace, float2, SafeNormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Reciprocal, float2, float2, Reciprocal); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Cross, float2, float2, Cross, float2); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MinOfComponents, float, float2, MinOfComponents); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MaxOfComponents, float, float2, MaxOfComponents); // Custom-wrapped metamethods static int Constructor(lua_State *L) { // construct val float2 val; // by args... int nargs = lua_gettop(L); if (nargs == 0) { // set to zero val.SetZero(); } else if (nargs == 1) { // splat across all components float cval = (float)luaL_checknumber(L, 1); val.Set(cval, cval); } else if (nargs == 2) { // all components defined float x = (float)luaL_checknumber(L, 1); float y = (float)luaL_checknumber(L, 2); val.Set(x, y); } else { luaL_error(L, "invalid constructor parameters"); return 0; } g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float2), &val); return 1; } static int __index(lua_State *L) { // should have an argument, always const float2 *self = GetPtr(L, 1); // check the methods table first lua_pushvalue(L, 2); lua_gettable(L, lua_upvalueindex(1)); if (lua_isfunction(L, -1)) return 1; else lua_pop(L, 1); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': lua_pushnumber(L, (lua_Number)self->x); return 1; case 'y': lua_pushnumber(L, (lua_Number)self->y); return 1; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "invalid swizzle: %s", compStr); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 1) { luaL_error(L, "invalid component index: %d", component); return 0; } lua_pushnumber(L, self->ele[component]); return 1; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static int __newindex(lua_State *L) { // should have an argument, always float2 *self = GetPtr(L, 1); float val = (float)luaL_checknumber(L, 3); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': self->x = val; return 0; case 'y': self->y = val; return 0; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "vector sets can only be done with a single component"); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 1) { luaL_error(L, "invalid component index: %d", component); return 0; } self->ele[component] = val; return 0; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MetaMethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "__add", __add }, { "__sub", __sub }, { "__mul", __mul }, { "__div", __div }, { "__mod", __mod }, { "__unm", __unm }, { "__eq", __eq }, { "__lt", __lt }, { "__le", __le }, { "__gt", __gt }, { "__ge", __ge }, { "__index", __index }, { "__newindex", __newindex }, { nullptr, nullptr } }; return reg; } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "Set", Set }, { "SetZero", SetZero }, { "AnyLess", AnyLess }, { "AnyGreater", AnyGreater }, { "IsFinite", IsFinite }, { "Min", Min }, { "Max", Max }, { "Clamp", Clamp }, { "Abs", Abs }, { "Saturate", Saturate }, { "Snap", Snap }, { "Floor", Floor }, { "Ceil", Ceil }, { "Round", Round }, { "Dot", Dot }, { "Lerp", Lerp }, { "SquaredLength", SquaredLength }, { "Length", Length }, { "SquaredDistance", SquaredDistance }, { "Distance", Distance }, { "Normalize", Normalize }, { "NormalizeEst", NormalizeEst }, { "NormalizeInPlace", NormalizeInPlace }, { "NormalizeEstInPlace", NormalizeEstInPlace }, { "SafeNormalize", SafeNormalize }, { "SafeNormalizeEst", SafeNormalizeEst }, { "SafeNormalizeInPlace", SafeNormalizeInPlace }, { "SafeNormalizeEstInPlace", SafeNormalizeEstInPlace }, { "Reciprocal", Reciprocal }, { "Cross", Cross }, { "MinOfComponents", MinOfComponents }, { "MaxOfComponents", MaxOfComponents }, { nullptr, nullptr } }; return reg; } }; template<> struct ScriptComplexType<float3> { static inline ScriptReferenceType &MetaTableReference() { static ScriptReferenceType ref = INVALID_SCRIPT_REFERENCE; return ref; } static inline const char *Name() { return "float3"; } // get/push methods static float3 Get(lua_State *L, int arg) { return float3(*reinterpret_cast<const float3 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg))); } static void Push(lua_State *L, const float3 &arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float3), &arg); } // get/push ptr methods static float3 *GetPtr(lua_State *L, int arg) { return reinterpret_cast<float3 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg)); } static void PushPtr(lua_State *L, const float3 *arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float3), arg); } // Metamethods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__add, float3, float3, operator+, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__sub, float3, float3, operator-, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mul, float3, float3, operator*, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__div, float3, float3, operator*, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mod, float3, float3, operator%, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__unm, float3, float3, operator-, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__eq, bool, float3, operator==, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__lt, bool, float3, operator<, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__le, bool, float3, operator<=, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__gt, bool, float3, operator>, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__ge, bool, float3, operator>=, float3); // Methods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P3(Set, float3, Set, float, float, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SetZero, float3, SetZero); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyLess, bool, float3, AnyLess, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyGreater, bool, float3, AnyGreater, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(NearEqual, bool, float3, NearEqual, float3, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(IsFinite, bool, float3, IsFinite); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Min, float3, float3, Min, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Max, float3, float3, Max, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Clamp, float3, float3, Clamp, float3, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Abs, float3, float3, Abs); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Saturate, float3, float3, Saturate); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Snap, float3, float3, Snap, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Floor, float3, float3, Floor); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Ceil, float3, float3, Ceil); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Round, float3, float3, Round); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Dot, float, float3, Dot, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Lerp, float3, float3, Lerp, float3, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SquaredLength, float, float3, SquaredLength); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Length, float, float3, Length); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(SquaredDistance, float, float3, SquaredDistance, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Distance, float, float3, Distance, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Normalize, float3, float3, Normalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(NormalizeEst, float3, float3, NormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeInPlace, float3, NormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeEstInPlace, float3, NormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalize, float3, float3, SafeNormalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalizeEst, float3, float3, SafeNormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeInPlace, float3, SafeNormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeEstInPlace, float3, SafeNormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Reciprocal, float3, float3, Reciprocal); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Cross, float3, float3, Cross, float3); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MinOfComponents, float, float3, MinOfComponents); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MaxOfComponents, float, float3, MaxOfComponents); // Custom-wrapped metamethods static int Constructor(lua_State *L) { // construct val float3 val; // by args... int nargs = lua_gettop(L); if (nargs == 0) { // set to zero val.SetZero(); } else if (nargs == 1) { // splat across all components float cval = (float)luaL_checknumber(L, 1); val.Set(cval, cval, cval); } else if (nargs == 3) { // all components defined float x = (float)luaL_checknumber(L, 1); float y = (float)luaL_checknumber(L, 2); float z = (float)luaL_checknumber(L, 3); val.Set(x, y, z); } else { luaL_error(L, "invalid constructor parameters"); return 0; } g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float3), &val); return 1; } static int __index(lua_State *L) { // should have an argument, always const float3 *self = GetPtr(L, 1); // check the methods table first lua_pushvalue(L, 2); lua_gettable(L, lua_upvalueindex(1)); if (lua_isfunction(L, -1)) return 1; else lua_pop(L, 1); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': lua_pushnumber(L, (lua_Number)self->x); return 1; case 'y': lua_pushnumber(L, (lua_Number)self->y); return 1; case 'z': lua_pushnumber(L, (lua_Number)self->z); return 1; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "invalid swizzle: %s", compStr); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 2) { luaL_error(L, "invalid component index: %d", component); return 0; } lua_pushnumber(L, self->ele[component]); return 1; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static int __newindex(lua_State *L) { // should have an argument, always float3 *self = GetPtr(L, 1); float val = (float)luaL_checknumber(L, 3); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': self->x = val; return 0; case 'y': self->y = val; return 0; case 'z': self->z = val; return 0; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "vector sets can only be done with a single component"); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 2) { luaL_error(L, "invalid component index: %d", component); return 0; } self->ele[component] = val; return 0; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MetaMethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "__add", __add }, { "__sub", __sub }, { "__mul", __mul }, { "__div", __div }, { "__mod", __mod }, { "__unm", __unm }, { "__eq", __eq }, { "__lt", __lt }, { "__le", __le }, { "__gt", __gt }, { "__ge", __ge }, { "__index", __index }, { "__newindex", __newindex }, { nullptr, nullptr } }; return reg; } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "Set", Set }, { "SetZero", SetZero }, { "AnyLess", AnyLess }, { "AnyGreater", AnyGreater }, { "IsFinite", IsFinite }, { "Min", Min }, { "Max", Max }, { "Clamp", Clamp }, { "Abs", Abs }, { "Saturate", Saturate }, { "Snap", Snap }, { "Floor", Floor }, { "Ceil", Ceil }, { "Round", Round }, { "Dot", Dot }, { "Lerp", Lerp }, { "SquaredLength", SquaredLength }, { "Length", Length }, { "SquaredDistance", SquaredDistance }, { "Distance", Distance }, { "Normalize", Normalize }, { "NormalizeEst", NormalizeEst }, { "NormalizeInPlace", NormalizeInPlace }, { "NormalizeEstInPlace", NormalizeEstInPlace }, { "SafeNormalize", SafeNormalize }, { "SafeNormalizeEst", SafeNormalizeEst }, { "SafeNormalizeInPlace", SafeNormalizeInPlace }, { "SafeNormalizeEstInPlace", SafeNormalizeEstInPlace }, { "Reciprocal", Reciprocal }, { "Cross", Cross }, { "MinOfComponents", MinOfComponents }, { "MaxOfComponents", MaxOfComponents }, { nullptr, nullptr } }; return reg; } }; template<> struct ScriptComplexType<float4> { static inline ScriptReferenceType &MetaTableReference() { static ScriptReferenceType ref = INVALID_SCRIPT_REFERENCE; return ref; } static inline const char *Name() { return "float4"; } // get/push methods static float4 Get(lua_State *L, int arg) { return float4(*reinterpret_cast<const float4 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg))); } static void Push(lua_State *L, const float4 &arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float4), &arg); } // get/push ptr methods static float4 *GetPtr(lua_State *L, int arg) { return reinterpret_cast<float4 *>(g_pScriptManager->CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg)); } static void PushPtr(lua_State *L, const float4 *arg) { g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float4), arg); } // Metamethods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__add, float4, float4, operator+, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__sub, float4, float4, operator-, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mul, float4, float4, operator*, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__div, float4, float4, operator*, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mod, float4, float4, operator%, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__unm, float4, float4, operator-, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__eq, bool, float4, operator==, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__lt, bool, float4, operator<, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__le, bool, float4, operator<=, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__gt, bool, float4, operator>, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__ge, bool, float4, operator>=, float4); // Methods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P4(Set, float4, Set, float, float, float, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SetZero, float4, SetZero); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyLess, bool, float4, AnyLess, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(AnyGreater, bool, float4, AnyGreater, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(NearEqual, bool, float4, NearEqual, float4, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(IsFinite, bool, float4, IsFinite); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Min, float4, float4, Min, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Max, float4, float4, Max, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Clamp, float4, float4, Clamp, float4, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Abs, float4, float4, Abs); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Saturate, float4, float4, Saturate); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Snap, float4, float4, Snap, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Floor, float4, float4, Floor); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Ceil, float4, float4, Ceil); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Round, float4, float4, Round); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Dot, float, float4, Dot, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Lerp, float4, float4, Lerp, float4, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SquaredLength, float, float4, SquaredLength); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Length, float, float4, Length); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(SquaredDistance, float, float4, SquaredDistance, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Distance, float, float4, Distance, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Normalize, float4, float4, Normalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(NormalizeEst, float4, float4, NormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeInPlace, float4, NormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeEstInPlace, float4, NormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalize, float4, float4, SafeNormalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(SafeNormalizeEst, float4, float4, SafeNormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeInPlace, float4, SafeNormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SafeNormalizeEstInPlace, float4, SafeNormalizeEstInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Reciprocal, float4, float4, Reciprocal); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P2(Cross, float4, float4, Cross, float4, float4); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MinOfComponents, float, float4, MinOfComponents); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(MaxOfComponents, float, float4, MaxOfComponents); // Custom-wrapped metamethods static int Constructor(lua_State *L) { // construct val float4 val; // by args... int nargs = lua_gettop(L); if (nargs == 0) { // set to zero val.SetZero(); } else if (nargs == 1) { // splat across all components float cval = (float)luaL_checknumber(L, 1); val.Set(cval, cval, cval, cval); } else if (nargs == 4) { // all components defined float x = (float)luaL_checknumber(L, 1); float y = (float)luaL_checknumber(L, 2); float z = (float)luaL_checknumber(L, 3); float w = (float)luaL_checknumber(L, 4); val.Set(x, y, z, w); } else { luaL_error(L, "invalid constructor parameters"); return 0; } g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float4), &val); return 1; } static int __index(lua_State *L) { // should have an argument, always const float4 *self = GetPtr(L, 1); // check the methods table first lua_pushvalue(L, 2); lua_gettable(L, lua_upvalueindex(1)); if (lua_isfunction(L, -1)) return 1; else lua_pop(L, 1); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': lua_pushnumber(L, (lua_Number)self->x); return 1; case 'y': lua_pushnumber(L, (lua_Number)self->y); return 1; case 'z': lua_pushnumber(L, (lua_Number)self->z); return 1; case 'w': lua_pushnumber(L, (lua_Number)self->w); return 1; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "invalid swizzle: %s", compStr); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 3) { luaL_error(L, "invalid component index: %d", component); return 0; } lua_pushnumber(L, self->ele[component]); return 1; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static int __newindex(lua_State *L) { // should have an argument, always float4 *self = GetPtr(L, 1); float val = (float)luaL_checknumber(L, 3); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': self->x = val; return 0; case 'y': self->y = val; return 0; case 'z': self->z = val; return 0; case 'w': self->w = val; return 0; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "vector sets can only be done with a single component"); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 3) { luaL_error(L, "invalid component index: %d", component); return 0; } self->ele[component] = val; return 0; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MetaMethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "__add", __add }, { "__sub", __sub }, { "__mul", __mul }, { "__div", __div }, { "__mod", __mod }, { "__unm", __unm }, { "__eq", __eq }, { "__lt", __lt }, { "__le", __le }, { "__gt", __gt }, { "__ge", __ge }, { "__index", __index }, { "__newindex", __newindex }, { nullptr, nullptr } }; return reg; } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "Set", Set }, { "SetZero", SetZero }, { "AnyLess", AnyLess }, { "AnyGreater", AnyGreater }, { "IsFinite", IsFinite }, { "Min", Min }, { "Max", Max }, { "Clamp", Clamp }, { "Abs", Abs }, { "Saturate", Saturate }, { "Snap", Snap }, { "Floor", Floor }, { "Ceil", Ceil }, { "Round", Round }, { "Dot", Dot }, { "Lerp", Lerp }, { "SquaredLength", SquaredLength }, { "Length", Length }, { "SquaredDistance", SquaredDistance }, { "Distance", Distance }, { "Normalize", Normalize }, { "NormalizeEst", NormalizeEst }, { "NormalizeInPlace", NormalizeInPlace }, { "NormalizeEstInPlace", NormalizeEstInPlace }, { "SafeNormalize", SafeNormalize }, { "SafeNormalizeEst", SafeNormalizeEst }, { "SafeNormalizeInPlace", SafeNormalizeInPlace }, { "SafeNormalizeEstInPlace", SafeNormalizeEstInPlace }, { "Reciprocal", Reciprocal }, { "Cross", Cross }, { "MinOfComponents", MinOfComponents }, { "MaxOfComponents", MaxOfComponents }, { nullptr, nullptr } }; return reg; } }; template<> struct ScriptComplexType<Quaternion> { static inline ScriptReferenceType &MetaTableReference() { static ScriptReferenceType ref = INVALID_SCRIPT_REFERENCE; return ref; } static inline const char *Name() { return "Quaternion"; } // get/push methods static Quaternion Get(lua_State *L, int arg) { return Quaternion(*reinterpret_cast<const Quaternion *>(ScriptManager::CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg))); } static void Push(lua_State *L, const Quaternion &arg) { ScriptManager::PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(Quaternion), &arg); } // get/push ptr methods static Quaternion *GetPtr(lua_State *L, int arg) { return reinterpret_cast<Quaternion *>(ScriptManager::CheckUserDataTypeByMetaTable(L, MetaTableReference(), arg)); } static void PushPtr(lua_State *L, const Quaternion *arg) { ScriptManager::PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(Quaternion), arg); } // Metamethods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__eq, bool, Quaternion, operator==, Quaternion); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(__mul, Quaternion, Quaternion, operator*, Quaternion); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(__unm, Quaternion, Quaternion, Inverse); // Methods MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_P4(Set, Quaternion, Set, float, float, float, float); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(SetIdentity, Quaternion, SetIdentity); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Length, float, Quaternion, Length); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET_P1(Dot, float, Quaternion, Dot, Quaternion); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(Normalize, Quaternion, Quaternion, Normalize); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL_RET(NormalizeEst, Quaternion, Quaternion, NormalizeEst); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeInPlace, Quaternion, NormalizeInPlace); MAKE_COMPLEX_SCRIPT_PROXY_FUNCTION_THISVAL(NormalizeEstInPlace, Quaternion, NormalizeEstInPlace); // Custom-wrapped metamethods static int Constructor(lua_State *L) { // construct val Quaternion val; // by args... int nargs = lua_gettop(L); if (nargs == 0) { // set to zero val.SetIdentity(); } else if (nargs == 4) { // all components defined float x = (float)luaL_checknumber(L, 1); float y = (float)luaL_checknumber(L, 2); float z = (float)luaL_checknumber(L, 3); float w = (float)luaL_checknumber(L, 4); val.Set(x, y, z, w); } else { luaL_error(L, "invalid constructor parameters"); return 0; } g_pScriptManager->PushNewUserData(L, MetaTableReference(), ScriptUserDataTag_None, sizeof(float4), &val); return 1; } static int __index(lua_State *L) { // should have an argument, always const Quaternion *self = GetPtr(L, 1); // check the methods table first lua_pushvalue(L, 2); lua_gettable(L, lua_upvalueindex(1)); if (lua_isfunction(L, -1)) return 1; else lua_pop(L, 1); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': lua_pushnumber(L, (lua_Number)self->x); return 1; case 'y': lua_pushnumber(L, (lua_Number)self->y); return 1; case 'z': lua_pushnumber(L, (lua_Number)self->z); return 1; case 'w': lua_pushnumber(L, (lua_Number)self->w); return 1; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "invalid swizzle: %s", compStr); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 3) { luaL_error(L, "invalid component index: %d", component); return 0; } lua_pushnumber(L, (&self->x)[component]); return 1; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static int __newindex(lua_State *L) { // should have an argument, always Quaternion *self = GetPtr(L, 1); float val = (float)luaL_checknumber(L, 3); // getting by-string? if (lua_isstring(L, 2)) { // number of components? const char *compStr = lua_tostring(L, 2); size_t compLen = Y_strlen(compStr); if (compLen == 1) { // access single component switch (compStr[0]) { case 'x': self->x = val; return 0; case 'y': self->y = val; return 0; case 'z': self->z = val; return 0; case 'w': self->w = val; return 0; } luaL_error(L, "invalid component: %s", compStr); return 0; } else { // construct new vector using swizzle luaL_error(L, "vector sets can only be done with a single component"); return 0; } } else if (lua_isinteger(L, 2)) { // access component int component = (int)lua_tointeger(L, 2); if (component < 0 || component > 3) { luaL_error(L, "invalid component index: %d", component); return 0; } (&self->x)[component] = val; return 0; } else { ScriptManager::GenerateTypeError(L, 2, "string or integer"); return 0; } } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MetaMethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "__eq", __eq }, { "__mul", __mul }, { "__unm", __unm }, { "__index", __index }, { "__newindex", __newindex }, { nullptr, nullptr } }; return reg; } static inline const SCRIPT_FUNCTION_TABLE_ENTRY *MethodFunctions() { static const SCRIPT_FUNCTION_TABLE_ENTRY reg[] = { { "Set", Set }, { "SetIdentity", SetIdentity }, { "Length", Length }, { "Dot", Dot }, { "Normalize", Normalize }, { "NormalizeEst", NormalizeEst }, { "NormalizeInPlace", NormalizeInPlace }, { "NormalizeEstInPlace", NormalizeEstInPlace }, { nullptr, nullptr } }; return reg; } }; template<typename T> static void RegisterPrimitiveType(lua_State *L) { // use script manager function ScriptReferenceType metaTableReference = g_pScriptManager->DefineUserDataType(ScriptComplexType<T>::Name(), ScriptComplexType<T>::MethodFunctions(), ScriptComplexType<T>::MetaMethodFunctions(), ScriptComplexType<T>::Constructor, nullptr); DebugAssert(metaTableReference != INVALID_SCRIPT_REFERENCE); // set in primitive type ScriptComplexType<T>::MetaTableReference() = metaTableReference; } template<typename T> static void RegisterIndexAccessorsForPrimitiveType(lua_State *L) { luaBackupStack(L); // get the metatable for T lua_rawgeti(L, LUA_REGISTRYINDEX, ScriptComplexType<T>::MetaTableReference()); // set __newindex to the appropriate value lua_pushcclosure(L, ScriptComplexType<T>::__newindex, 0); lua_setfield(L, -2, "__newindex"); // get method table, set it as an upvalue to the __index function lua_getfield(L, -1, "__index"); lua_pushcclosure(L, ScriptComplexType<T>::__index, 1); lua_setfield(L, -2, "__index"); // drop the metatable lua_pop(L, 1); luaVerifyStack(L, 0); } template<typename T> static void UnregisterPrimitiveType(lua_State *L) { int &metaTableReference = ScriptComplexType<T>::MetaTableReference(); if (metaTableReference == INVALID_SCRIPT_REFERENCE) return; luaL_unref(L, LUA_REGISTRYINDEX, metaTableReference); metaTableReference = INVALID_SCRIPT_REFERENCE; } void ScriptManager::RegisterPrimitiveTypes() { RegisterPrimitiveType<float2>(m_state); RegisterIndexAccessorsForPrimitiveType<float2>(m_state); RegisterPrimitiveType<float3>(m_state); RegisterIndexAccessorsForPrimitiveType<float3>(m_state); RegisterPrimitiveType<float4>(m_state); RegisterIndexAccessorsForPrimitiveType<float4>(m_state); RegisterPrimitiveType<Quaternion>(m_state); } void ScriptManager::UnregisterPrimitiveTypes() { UnregisterPrimitiveType<float2>(m_state); UnregisterPrimitiveType<float3>(m_state); UnregisterPrimitiveType<float4>(m_state); UnregisterPrimitiveType<Quaternion>(m_state); } // Redirecting ScriptArg to ScriptComplexType template<> float2 ScriptArg<float2>::Get(lua_State *L, int arg) { return ScriptComplexType<float2>::Get(L, arg); } template<> void ScriptArg<float2>::Push(lua_State *L, const float2 &arg) { ScriptComplexType<float2>::Push(L, arg); } template<> float3 ScriptArg<float3>::Get(lua_State *L, int arg) { return ScriptComplexType<float3>::Get(L, arg); } template<> void ScriptArg<float3>::Push(lua_State *L, const float3 &arg) { ScriptComplexType<float3>::Push(L, arg); } template<> float4 ScriptArg<float4>::Get(lua_State *L, int arg) { return ScriptComplexType<float4>::Get(L, arg); } template<> void ScriptArg<float4>::Push(lua_State *L, const float4 &arg) { ScriptComplexType<float4>::Push(L, arg); } template<> Quaternion ScriptArg<Quaternion>::Get(lua_State *L, int arg) { return ScriptComplexType<Quaternion>::Get(L, arg); } template<> void ScriptArg<Quaternion>::Push(lua_State *L, const Quaternion &arg) { ScriptComplexType<Quaternion>::Push(L, arg); } <file_sep>/Editor/Source/Editor/MapEditor/EditorTerrainEditMode.h #pragma once #include "Editor/MapEditor/EditorEditMode.h" #include "MapCompiler/MapSourceTerrainData.h" #include "Renderer/VertexFactories/PlainVertexFactory.h" class Image; class CompositeRenderProxy; class TerrainLayerListGenerator; class TerrainRenderer; class TerrainSection; class TerrainSectionRenderProxy; class StaticMesh; class Material; struct ui_EditorTerrainEditMode; class EditorTerrainEditMode : public EditorEditMode, private MapSourceTerrainData::EditCallbacks { Q_OBJECT public: // helper function to create the default layer list static TerrainLayerListGenerator *CreateEmptyLayerList(); public: EditorTerrainEditMode(EditorMap *pMap); ~EditorTerrainEditMode(); // widget const EDITOR_TERRAIN_EDIT_MODE_WIDGET GetActiveWidget() const { return m_eActiveWidget; } void SetActiveWidget(EDITOR_TERRAIN_EDIT_MODE_WIDGET widget); // brush settings const float3 &GetBrushColor() const { return m_brushColor; } const float GetBrushRadius() const { return m_brushRadius; } const float GetBrushFalloff() const { return m_brushFalloff; } const float GetBrushHeightStep() const { return m_brushTerrainStep; } const float GetBrushLayerStep() const { return m_brushLayerStep; } const int32 GetBrushLayerSelectedLayer() const { return m_brushLayerSelectedBaseLayer; } void SetBrushColor(const float3 &color); void SetBrushRadius(float radius); void SetBrushFalloff(float falloff); void SetBrushHeightStep(float heightStep) { m_brushTerrainStep = heightStep; } void SetBrushLayerStep(float layerStep) { m_brushLayerStep = layerStep; } void SetBrushLayerSelectedLayer(int32 selectedLayer); // implemented base methods virtual bool Initialize(ProgressCallbacks *pProgressCallbacks) override; virtual QWidget *CreateUI(QWidget *parentWidget) override; virtual void Activate() override; virtual void Deactivate() override; virtual void Update(const float timeSinceLastUpdate) override; virtual void OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) override; virtual void OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterPost(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) override; virtual bool HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) override; virtual bool HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) override; virtual bool HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) override; // import a heightmap bool ImportHeightmap(const Image *pHeightmap, int32 startSectionX, int32 startSectionY, float minHeight, float maxHeight, MapSourceTerrainData::HeightmapImportScaleType scaleType, uint32 scaleAmount, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // rebuild the entire terrain's quadtree bool RebuildQuadTree(uint32 newLodCount, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // edit methods float GetPointHeight(int32 pointX, int32 pointY) { return m_pTerrainData->GetPointHeight(pointX, pointY); } float GetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer) { return m_pTerrainData->GetPointLayerWeight(pointX, pointY, layer); } bool SetPointHeight(int32 pointX, int32 pointY, float height) { return m_pTerrainData->SetPointHeight(pointX, pointY, height); } bool AddPointHeight(int32 pointX, int32 pointY, float mod) { return m_pTerrainData->AddPointHeight(pointX, pointY, mod); } bool SetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float weight) { return m_pTerrainData->SetPointLayerWeight(pointX, pointY, layer, weight); } bool AddPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float amount) { return m_pTerrainData->AddPointLayerWeight(pointX, pointY, layer, amount); } // create a section bool CreateSection(int32 sectionX, int32 sectionY, float createHeight, uint8 createLayer); // delete a section bool DeleteSection(int32 sectionX, int32 sectionY); private: // MapSourceTerrainData::EditCallbacks interface virtual void OnSectionCreated(int32 sectionX, int32 sectionY); virtual void OnSectionDeleted(int32 sectionX, int32 sectionY); virtual void OnSectionLoaded(const TerrainSection *pSection); virtual void OnSectionUnloaded(const TerrainSection *pSection); virtual void OnSectionLayersModified(const TerrainSection *pSection); virtual void OnSectionPointHeightModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY); virtual void OnSectionPointLayersModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY); private: void ClearState(); void UpdateTerrainCoordinates(EditorMapViewport *pViewport, const int2 &mousePosition, bool sectionOnly); void UpdateBrushVisual(); // update the layer list for edit details void UpdateDetailLayerList(); // painting float GetBrushPaintAmount(int32 pointX, int32 pointY) const; bool BeginPaint(); void UpdatePaint(); void EndPaint(); // update ui with selected section void UpdateUIForSelectedSection(); void DrawPostWorldOverlaysTerrainWidget(EditorMapViewport *pViewport); void DrawPostWorldOverlaysSectionWidget(EditorMapViewport *pViewport); enum STATE { STATE_NONE, STATE_PAINT_TERRAIN_HEIGHT, STATE_PAINT_TERRAIN_LAYER, STATE_CAMERA_ROTATION, }; // ui ui_EditorTerrainEditMode *m_ui; // terrain handles MapSourceTerrainData *m_pTerrainData; TerrainRenderer *m_pTerrainRenderer; // helper objects MemArray<PlainVertexFactory::Vertex> m_brushVertices; Material *m_pBrushOverlayMaterial; // active widget EDITOR_TERRAIN_EDIT_MODE_WIDGET m_eActiveWidget; // brush settings //BRUSH_TYPE m_brushType; float3 m_brushColor; float m_brushRadius; float m_brushFalloff; //float m_brushSpeed; float m_brushTerrainStep; float m_brushTerrainMinHeight; float m_brushTerrainMaxHeight; float m_brushLayerStep; int32 m_brushLayerSelectedBaseLayer; // state STATE m_eCurrentState; // any mode that requires a brush float3 m_mouseRayHitLocation; int2 m_mouseOverClosestPoint; float3 m_mouseOverClosestPointPosition; bool m_validMouseOverPosition; // section edit mode -- the section the mouse is under int2 m_mouseOverSection; bool m_validMouseOverSection; int2 m_selectedSection; bool m_validSelectedSection; ////////////////////////////////////////////////////////////////////////// // Section Render Proxy Management ////////////////////////////////////////////////////////////////////////// TerrainSectionRenderProxy *GetSectionRenderProxy(const TerrainSection *pSection); TerrainSectionRenderProxy *GetSectionRenderProxy(int32 sectionX, int32 sectionY); bool CreateSectionRenderProxy(int32 sectionX, int32 sectionY); void DeleteSectionRenderProxy(int32 sectionX, int32 sectionY); bool CreateSectionRenderProxies(); void DeleteSectionRenderProxies(); PODArray<TerrainSectionRenderProxy *> m_sectionRenderProxies; private Q_SLOTS: // ui events void OnUIWidgetEditTerrainClicked(bool checked); void OnUIWidgetEditDetailsClicked(bool checked); void OnUIWidgetEditHolesClicked(bool checked); void OnUIWidgetEditSectionsClicked(bool checked); void OnUIWidgetEditLayersClicked(bool checked); void OnUIWidgetImportHeightmapClicked(bool checked); void OnUIWidgetSettingsClicked(bool checked); void OnUIBrushRadiusChanged(double value); void OnUIBrushFalloffChanged(double value); void OnUIBrushInvertChanged(bool checked); void OnUITerrainStepHeightChanged(double value); void OnUILayersStepWeightChanged(double value); void OnUILayersLayerListItemClicked(QListWidgetItem *pListItem); void OnUILayersEditLayerListClicked(); void OnUISectionsActiveSectionDeleteLayersClicked(); void OnUISectionsActiveSectionDeleteSectionClicked(); void OnUISectionsInactiveSectionCreateSectionClicked(); void OnUIHeightmapImportPanelSourceTypeClicked(bool checked); void OnUIHeightmapImportPanelSelectSourceImageClicked(); void OnUIHeightmapImportPanelScaleAmountChanged(int value); void OnUIHeightmapImportPanelScaleTypeClicked(bool checked); void OnUIHeightmapImportPanelImportClicked(); void OnUISettingsPanelViewDistanceValueChanged(int value); void OnUISettingsPanelRenderResolutionMultiplierChanged(int value); void OnUISettingsPanelLODDistanceRatioChanged(double value); void OnUISettingsPanelRebuildQuadtreeClicked(); }; <file_sep>/Engine/Source/MathLib/StreamOperators.h #pragma once class BinaryReader; class BinaryWriter; struct Vector2f; struct Vector3f; struct Vector4f; struct Vector2i; struct Vector3i; struct Vector4i; struct Vector2u; struct Vector3u; struct Vector4u; struct Quaternion; class AABox; class Sphere; BinaryReader &operator>>(BinaryReader &binaryReader, Vector2f &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector3f &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector4f &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector2i &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector3i &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector4i &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector2u &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector3u &value); BinaryReader &operator>>(BinaryReader &binaryReader, Vector4u &value); BinaryReader &operator>>(BinaryReader &binaryReader, Quaternion &value); BinaryReader &operator>>(BinaryReader &binaryReader, AABox &value); BinaryReader &operator>>(BinaryReader &binaryReader, Sphere &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2f &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3f &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4f &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2i &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3i &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4i &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector2u &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector3u &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Vector4u &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Quaternion &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const AABox &value); BinaryWriter &operator<<(BinaryWriter &binaryWriter, const Sphere &value);<file_sep>/Engine/Source/GameFramework/DirectionalLightEntity.h #pragma once #include "Engine/Entity.h" class DirectionalLightRenderProxy; class DirectionalLightEntity : public Entity { DECLARE_ENTITY_TYPEINFO(DirectionalLightEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(DirectionalLightEntity); public: DirectionalLightEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~DirectionalLightEntity(); // property accessors const bool GetEnabled() const { return m_bEnabled; } const float3 &GetColor() const { return m_Color; } const float GetBrightness() const { return m_fBrightness; } const uint32 GetLightShadowFlags() const { return m_iLightShadowFlags; } const float GetAmbientFactor() const { return m_fAmbientFactor; } // property setters void SetEnabled(bool enabled); void SetColor(const float3 &color); void SetBrightness(float brightness); void SetLightShadowFlags(uint32 lightShadowFlags); void SetAmbientFactor(float ambientContribution); // creation method void Create(uint32 entityID, ENTITY_MOBILITY mobility = ENTITY_MOBILITY_MOVABLE, const Quaternion &rotation = Quaternion::Identity, const bool enabled = true, const float3 &color = float3::One, float brightness = 1.0f, uint32 shadowFlags = LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS, float ambientFactor = 0.2f); // inherited methods virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; private: // updates light properties void UpdateColors(); // determine light direction float3 CalculateLightDirection(); // property callbacks static void OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); // local copy of properties bool m_bEnabled; float3 m_Color; float m_fBrightness; float m_fAmbientFactor; uint32 m_iLightShadowFlags; // instance of render proxy DirectionalLightRenderProxy *m_pRenderProxy; }; <file_sep>/Engine/Source/Renderer/VertexFactories/BlockMeshVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" #include "Engine/BlockMeshBuilder.h" enum BLOCK_MESH_VERTEX_FACTORY_FLAGS { BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXCOORD = (1 << 0), BLOCK_MESH_VERTEX_FACTORY_FLAG_TEXTURE_ARRAY = (1 << 1), BLOCK_MESH_VERTEX_FACTORY_FLAG_ATLAS_TEXCOORDS = (1 << 2), BLOCK_MESH_VERTEX_FACTORY_FLAG_TANGENT_VECTORS = (1 << 3), BLOCK_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS = (1 << 4), BLOCK_MESH_VERTEX_FACTORY_FLAG_FACE_INDEX = (1 << 5), }; class BlockMeshVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(BlockMeshVertexFactory, VertexFactory); public: static uint32 GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static void FillVertices(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const BlockMeshBuilder::Vertex *pVertices, uint32 nVertices, void *pOutputVertices, uint32 cbOutputVertices); static bool CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const BlockMeshBuilder::Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray); static void ShareVerticesBuffer(VertexBufferBindingArray *pDestinationVertexArray, VertexBufferBindingArray *pSourceVertexArray) { ShareBuffers(pDestinationVertexArray, pSourceVertexArray, 0); } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); // determine flags for current renderer static uint32 GetVertexFlagsForCurrentRenderer(); }; <file_sep>/Engine/Source/GameFramework/BlockMeshBrush.h #pragma once #include "Engine/Brush.h" class BlockMesh; namespace Physics { class StaticObject; } class BlockMeshRenderProxy; class BlockMeshBrush : public Brush { DECLARE_OBJECT_TYPE_INFO(BlockMeshBrush, Brush); DECLARE_OBJECT_PROPERTY_MAP(BlockMeshBrush); DECLARE_OBJECT_GENERIC_FACTORY(BlockMeshBrush); public: BlockMeshBrush(const ObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~BlockMeshBrush(); // External creation method bool Create(const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const BlockMesh *pBlockMesh = nullptr, bool visible = true, bool collidable = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // Virtual creation method virtual bool Initialize() override; // Events virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; // property accessors const BlockMesh *GetBlockMesh() const { return m_pBlockMesh; } const bool IsVisible() const { return m_visible; } const uint32 GetShadowFlags() const { return m_shadowFlags; } const bool IsCollidable() const { return m_collidable; } private: // property callbacks static bool PropertyCallbackGetBlockMeshName(ThisClass *pEntity, const void *pUserData, String *pValue); static bool PropertyCallbackSetBlockMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue); // vars const BlockMesh *m_pBlockMesh; bool m_visible; uint32 m_shadowFlags; bool m_collidable; // render proxy BlockMeshRenderProxy *m_pRenderProxy; // physics proxy Physics::StaticObject *m_pCollisionObject; }; <file_sep>/Engine/Source/GameFramework/StaticMeshRigidBodyEntity.h #pragma once #include "Engine/Entity.h" class StaticMesh; namespace Physics { class RigidBody; } class StaticMeshRenderProxy; class StaticMeshRigidBodyEntity : public Entity { DECLARE_ENTITY_TYPEINFO(StaticMeshRigidBodyEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(StaticMeshRigidBodyEntity); public: StaticMeshRigidBodyEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~StaticMeshRigidBodyEntity(); // property accessors const bool IsVisible() const { return m_visible; } const StaticMesh *GetStaticMesh() const { return m_pStaticMesh; } const uint32 GetShadowFlags() const { return m_shadowFlags; } // property setters void SetVisibility(bool visible); void SetStaticMesh(const StaticMesh *pStaticMesh); void SetShadowFlags(uint32 shadowFlags); // physics void SetMass(float mass); void SetFriction(float friction); void SetRollingFriction(float rollingFriction); void ApplyCentralImpulse(const float3 &direction); void ResetForces(); void ResetVelocity(); void ResetForcesAndVelocity(); // External create interface void Create(uint32 entityID, const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One, const StaticMesh *pStaticMesh = nullptr, bool visible = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS, float mass = 1.0f, float friction = 0.5f, float rollingFriction = 1.0f); // Events virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; virtual void OnComponentBoundsChange() override; private: // updates the collision object void UpdateCollisionObject(); void UpdateRenderProxy(); // property callbacks static bool PropertyCallbackGetStaticMesh(ThisClass *pEntity, const void *pUserData, String *pValue); static bool PropertyCallbackSetStaticMesh(ThisClass *pEntity, const void *pUserData, const String *pValue); static void PropertyCallbackStaticMeshChanged(ThisClass *pEntity, const void *pUserData); static void PropertyCallbackEnableCollisionChanged(ThisClass *pEntity, const void *pUserData); static void PropertyCallbackMassChanged(ThisClass *pEntity, const void *pUserData); static void PropertyCallbackFrictionChanged(ThisClass *pEntity, const void *pUserData); static void PropertyCallbackRollingFrictionChanged(ThisClass *pEntity, const void *pUserData); // physics callbacks static void PhysicsCallbackTransformChanged(ThisClass *pEntity, const Transform &physicsTransform); // vars bool m_visible; const StaticMesh *m_pStaticMesh; uint32 m_shadowFlags; float m_mass; float m_friction; float m_rollingFriction; // physics proxy Physics::RigidBody *m_pRigidBody; // render proxy StaticMeshRenderProxy *m_pRenderProxy; }; <file_sep>/Editor/Source/Editor/SkeletalMeshEditor/EditorSkeletalMeshEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/SkeletalMeshEditor/EditorSkeletalMeshEditor.h" #include "Editor/SkeletalMeshEditor/ui_EditorSkeletalMeshEditor.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderProxies/CompositeRenderProxy.h" #include "Renderer/Renderer.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "Engine/ResourceManager.h" #include "Engine/Engine.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "Editor/EditorLightSimulator.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorProgressDialog.h" #include "Editor/EditorResourceSaveDialog.h" #include "Editor/Editor.h" Log_SetChannel(EditorSkeletalMeshEditor); EditorSkeletalMeshEditor::EditorSkeletalMeshEditor() : m_ui(new Ui_EditorSkeletalMeshEditor()), m_renderMode(EDITOR_RENDER_MODE_FULLBRIGHT), m_viewportFlags(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS), m_pGenerator(nullptr), m_pRenderWorld(new RenderWorld()), m_pLightSimulator(new EditorLightSimulator(0, m_pRenderWorld)), m_pMeshPreviewRenderProxy(new CompositeRenderProxy(0, Transform::Identity)), m_pCollisionShapePreviewRenderProxy(new CompositeRenderProxy(0, Transform::Identity)), m_pSwapChain(nullptr), m_pWorldRenderer(nullptr), m_bHardwareResourcesCreated(false), m_bRedrawPending(true), m_lastMousePosition(int2::Zero), m_currentTool(Tool_Information), m_currentState(State_None) { // create ui m_ui->CreateUI(this); m_ui->UpdateUIForCameraMode(m_viewController.GetCameraMode()); m_ui->UpdateUIForRenderMode(m_renderMode); m_ui->UpdateUIForViewportFlags(m_viewportFlags); m_ui->UpdateUIForTool(m_currentTool); // connect events ConnectUIEvents(); // fixup dimensions m_viewController.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); m_guiContext.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); // setup world m_pCollisionShapePreviewRenderProxy->SetVisibility(false); m_pRenderWorld->AddRenderable(m_pMeshPreviewRenderProxy); m_pRenderWorld->AddRenderable(m_pCollisionShapePreviewRenderProxy); } EditorSkeletalMeshEditor::~EditorSkeletalMeshEditor() { } void EditorSkeletalMeshEditor::SetCameraMode(EDITOR_CAMERA_MODE cameraMode) { DebugAssert(cameraMode < EDITOR_CAMERA_MODE_COUNT); m_viewController.SetCameraMode(cameraMode); m_ui->UpdateUIForCameraMode(cameraMode); } void EditorSkeletalMeshEditor::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } // update state m_renderMode = renderMode; m_ui->UpdateUIForRenderMode(renderMode); delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); FlagForRedraw(); // update ui } void EditorSkeletalMeshEditor::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorSkeletalMeshEditor::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorSkeletalMeshEditor::SetCurrentTool(Tool tool) { m_ui->UpdateUIForTool(tool); if (m_currentTool == tool) return; m_currentTool = tool; // adjust collision mesh visibility m_pCollisionShapePreviewRenderProxy->SetVisibility((tool == Tool_Collision)); // redraw FlagForRedraw(); } void EditorSkeletalMeshEditor::Create(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { m_meshName = meshName; m_meshFileName.Format("%s.skm.xml", meshName); // allocate a new generator m_pGenerator = new StaticMeshGenerator(); m_pGenerator->Create(false, false); // update everything OnFileNameChanged(); UpdateInformationTab(); } bool EditorSkeletalMeshEditor::Load(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { // find the filename, and open it PathString fileName; fileName.Format("%s.staticmesh.xml", meshName); AutoReleasePtr<ByteStream> pMeshStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pMeshStream == nullptr) { Log_ErrorPrintf("Could not open file '%s'", fileName.GetCharArray()); return false; } StaticMeshGenerator *pGenerator = new StaticMeshGenerator(); if (!pGenerator->LoadFromXML(fileName, pMeshStream)) { Log_ErrorPrintf("Could not parse file '%s'", fileName.GetCharArray()); delete pGenerator; return false; } // close anything Close(); // store names m_meshName = meshName; m_meshFileName = fileName; // swap the pointers, and do allocations m_pGenerator = pGenerator; if (!LoadMaterials()) { Close(); return false; } // create the preview mesh RefreshPreviewMesh(); RefreshCollisionShapePreview(); // update everything OnFileNameChanged(); UpdateInformationTab(); return true; } bool EditorSkeletalMeshEditor::Save(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (!m_pGenerator->IsCompleteMesh()) { pProgressCallbacks->DisplayError("The mesh is not valid (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(m_meshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } return true; } bool EditorSkeletalMeshEditor::SaveAs(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (!m_pGenerator->IsCompleteMesh()) { pProgressCallbacks->DisplayError("The mesh is not valid (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } PathString newMeshFileName; newMeshFileName.Format("%s.staticmesh.xml", meshName); // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(newMeshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } // update names m_meshName = meshName; m_meshFileName = newMeshFileName; OnFileNameChanged(); return true; } void EditorSkeletalMeshEditor::Close() { if (m_pGenerator == nullptr) return; delete m_pGenerator; m_pGenerator = nullptr; m_pMeshPreviewRenderProxy->DeleteAllObjects(); } bool EditorSkeletalMeshEditor::CreateHardwareResources() { Log_DevPrintf("Creating hardware resources for EditorSkeletalMeshEditor (%u x %u)", (uint32)m_ui->swapChainWidget->size().width(), (uint32)m_ui->swapChainWidget->size().height()); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == NULL) return false; m_pSwapChain->AddRef(); } // get dimensions uint32 swapChainWidth = m_pSwapChain->GetWidth(); uint32 swapChainHeight = m_pSwapChain->GetHeight(); // update gui context, camera m_viewController.SetViewportDimensions(swapChainWidth, swapChainHeight); m_guiContext.SetViewportDimensions(swapChainWidth, swapChainHeight); // create render context if (m_pWorldRenderer == NULL) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); // cancel any pending draws until the windows are arranged and a paint is requested. m_bHardwareResourcesCreated = true; return true; } void EditorSkeletalMeshEditor::ReleaseHardwareResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; m_pWorldRenderer = NULL; SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_bHardwareResourcesCreated = false; } void EditorSkeletalMeshEditor::OnFileNameChanged() { // set the material directory to the same directory as the mesh PathString importDirectory; FileSystem::BuildPathRelativeToFile(importDirectory, m_meshFileName, "", false, true); m_ui->toolImportMaterialDirectory->setText(ConvertStringToQString(importDirectory)); // update the window title setWindowTitle(ConvertStringToQString(String::FromFormat("Static Mesh Editor - %s", m_meshName.GetCharArray()))); } bool EditorSkeletalMeshEditor::LoadMaterials() { #if 0 // allocate a new array PODArray<const Material *> materials; for (uint32 i = 0; i < m_pGenerator->GetMaterialCount(); i++) { const Material *pMaterial = g_pResourceManager->GetMaterial(m_pGenerator->GetMaterialName(i)); if (pMaterial == nullptr) pMaterial = g_pResourceManager->GetDefaultMaterial(); materials.Add(pMaterial); } // swap with the current array m_meshMaterials.Swap(materials); // release the old materials for (uint32 i = 0; i < materials.GetSize(); i++) materials[i]->Release(); #endif return true; } void EditorSkeletalMeshEditor::RefreshPreviewMesh() { #if 0 DebugAssert(m_pGenerator != nullptr && m_pGenerator->GetVertexCount() > 0 && m_pGenerator->GetBatchCount() > 0); // find vertex factory flags uint32 vertexFactoryFlags = 0; if (m_pGenerator->GetVertexTextureCoordinatesEnabled()) vertexFactoryFlags |= LOCAL_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS; if (m_pGenerator->GetVertexColorsEnabled()) vertexFactoryFlags |= LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS; // allocate vertices LocalVertexFactory::Vertex *pVertices = new LocalVertexFactory::Vertex[m_pGenerator->GetVertexCount()]; for (uint32 i = 0; i < m_pGenerator->GetVertexCount(); i++) { const StaticMeshGenerator::Vertex *pSourceVertex = m_pGenerator->GetVertex(i); LocalVertexFactory::Vertex *pDestinationVertex = &pVertices[i]; pDestinationVertex->Position = pSourceVertex->Position; pDestinationVertex->TangentX = pSourceVertex->Tangent; pDestinationVertex->TangentY = pSourceVertex->Binormal; pDestinationVertex->TangentZ = pSourceVertex->Normal; pDestinationVertex->TexCoord = pSourceVertex->TexCoord; pDestinationVertex->Color = pSourceVertex->Color; } // convert vertices to render format uint32 vertexSize = LocalVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), vertexFactoryFlags); byte *pGPUVertices = new byte[vertexSize * m_pGenerator->GetVertexCount()]; LocalVertexFactory::FillVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), vertexFactoryFlags, pVertices, m_pGenerator->GetVertexCount(), pGPUVertices, vertexSize * m_pGenerator->GetVertexCount()); // allocate indices uint32 *pIndices = new uint32[m_pGenerator->GetTriangleCount() * 3]; for (uint32 i = 0; i < m_pGenerator->GetTriangleCount(); i++) Y_memcpy(&pIndices[i * 3], m_pGenerator->GetTriangle(i)->Indices, sizeof(uint32) * 3); // allocate batches CompositeRenderProxy::Batch *pBatches = new CompositeRenderProxy::Batch[m_pGenerator->GetBatchCount()]; for (uint32 i = 0; i < m_pGenerator->GetBatchCount(); i++) { const StaticMeshGenerator::Batch *pSourceBatch = m_pGenerator->GetBatch(i); CompositeRenderProxy::Batch *pDestinationBatch = &pBatches[i]; pDestinationBatch->FirstIndex = pSourceBatch->StartIndex; pDestinationBatch->IndexCount = pSourceBatch->NumIndices; pDestinationBatch->MaterialIndex = pSourceBatch->MaterialIndex; } // delete all preview objects m_pMeshPreviewRenderProxy->DeleteAllObjects(); // allocate a new one uint32 objectID = m_pMeshPreviewRenderProxy->AddObject(); m_pMeshPreviewRenderProxy->UpdateObject(objectID, VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory), vertexFactoryFlags, pGPUVertices, vertexSize, m_pGenerator->GetVertexCount(), pIndices, GPU_INDEX_FORMAT_UINT32, m_pGenerator->GetTriangleCount() * 3, m_meshMaterials.GetBasePointer(), m_meshMaterials.GetSize(), pBatches, m_pGenerator->GetBatchCount(), m_pGenerator->GetBoundingBox(), m_pGenerator->GetBoundingSphere()); // free up memory delete[] pBatches; delete[] pIndices; delete[] pGPUVertices; delete[] pVertices; #endif } void EditorSkeletalMeshEditor::RefreshCollisionShapePreview() { // delete all preview objects m_pCollisionShapePreviewRenderProxy->DeleteAllObjects(); // // depending on the type // const Physics::CollisionShapeGenerator *pCollisionShapeGenerator = m_pGenerator->GetCollisionShape(); // if (pCollisionShapeGenerator != nullptr) // { // switch (pCollisionShapeGenerator->GetType()) // { // case Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH: // { // // } // break; // } // } } void EditorSkeletalMeshEditor::UpdateInformationTab() { #if 0 m_ui->toolInformationMinBounds->setText(ConvertStringToQString(StringConverter::Float3ToString(m_pGenerator->GetBoundingBox().GetMinBounds()))); m_ui->toolInformationMaxBounds->setText(ConvertStringToQString(StringConverter::Float3ToString(m_pGenerator->GetBoundingBox().GetMaxBounds()))); m_ui->toolInformationVertexCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pGenerator->GetVertexCount()))); m_ui->toolInformationTriangleCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pGenerator->GetTriangleCount()))); m_ui->toolInformationMaterialCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pGenerator->GetMaterialCount()))); m_ui->toolInformationBatchCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pGenerator->GetBatchCount()))); m_ui->toolInformationEnableTextureCoordinates->setChecked(m_pGenerator->GetVertexTextureCoordinatesEnabled()); m_ui->toolInformationEnableVertexColors->setChecked(m_pGenerator->GetVertexColorsEnabled()); // collision shape information SmallString collisionShapeInformation; collisionShapeInformation.AppendString("Collision shape: "); if (m_pGenerator->GetCollisionShape() == nullptr) { // no shape collisionShapeInformation.AppendString("None"); m_ui->toolCollisionGenerateTriangleMesh->setChecked(true); } else { const Physics::CollisionShapeGenerator *pCollisionShapeGenerator = m_pGenerator->GetCollisionShape(); switch (pCollisionShapeGenerator->GetType()) { case Physics::COLLISION_SHAPE_TYPE_BOX: collisionShapeInformation.AppendFormattedString("Box, Extents: %s", StringConverter::Float3ToString(pCollisionShapeGenerator->GetBoxExtents()).GetCharArray()); m_ui->toolCollisionGenerateBox->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_SPHERE: collisionShapeInformation.AppendFormattedString("Sphere, radius: %s", StringConverter::FloatToString(pCollisionShapeGenerator->GetSphereRadius()).GetCharArray()); m_ui->toolCollisionGenerateSphere->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH: collisionShapeInformation.AppendFormattedString("Triangle Mesh, %u triangles", pCollisionShapeGenerator->GetTriangleCount()); m_ui->toolCollisionGenerateTriangleMesh->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_CONVEX_HULL: collisionShapeInformation.AppendFormattedString("Convex hull, %u vertices", pCollisionShapeGenerator->GetConvexHullVertexCount()); m_ui->toolCollisionGenerateConvexHull->setChecked(true); break; } } m_ui->toolCollisionInformation->setText(ConvertStringToQString(collisionShapeInformation)); #endif } void EditorSkeletalMeshEditor::Draw() { // create hardware resources if (!m_bHardwareResourcesCreated && !CreateHardwareResources()) return; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // clear it pGPUContext->SetOutputBuffer(m_pSwapChain); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetViewport(m_viewController.GetViewport()); pGPUContext->ClearTargets(true, true, true); // setup 3d state pGPUContext->GetConstants()->SetFromCamera(m_viewController.GetCamera(), true); // invoke draws DrawGrid(); DrawView(); // bias the projection matrix slightly FIXME pGPUContext->GetConstants()->SetCameraProjectionMatrix(m_viewController.GetCamera().GetBiasedProjectionMatrix(0.01f), true); DrawOverlays(pGPUContext); // clear state pGPUContext->ClearState(true, true, true, true); // present pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // clear pending flag m_bRedrawPending = false; } void EditorSkeletalMeshEditor::DrawGrid() { // draw a grid of 2*the mesh size float gridSizeX = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().x), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().x)) * 2.0f); float gridSizeY = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().y), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().y)) * 2.0f); m_guiContext.Draw3DGrid(float3(-gridSizeX, -gridSizeY, 0.0f), float3(gridSizeX, gridSizeY, 0.0f), float3(1.0f, 1.0f, 1.0f), MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255)); } void EditorSkeletalMeshEditor::DrawView() { m_pWorldRenderer->DrawWorld(m_pRenderWorld, m_viewController.GetViewParameters(), NULL, NULL); } void EditorSkeletalMeshEditor::DrawOverlays(GPUContext *pGPUContext) { //m_guiContext.DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), 16, 0, 0, "Hi"); // draw the collision mesh if (m_currentTool == Tool_Collision) { const Physics::CollisionShapeGenerator *pCollisionShape = m_pGenerator->GetCollisionShape(); if (pCollisionShape != nullptr) { switch (pCollisionShape->GetType()) { case Physics::COLLISION_SHAPE_TYPE_BOX: m_guiContext.Draw3DWireBox(AABox(-pCollisionShape->GetBoxExtents(), pCollisionShape->GetBoxExtents()), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255)); break; } } } } void EditorSkeletalMeshEditor::OnFrameExecutionTriggered(float timeSinceLastFrame) { // don't do anything if we haven't loaded if (m_pGenerator == nullptr) return; // update camera m_viewController.Update(timeSinceLastFrame); // force draw if requested by camera if (m_viewController.IsChanged()) FlagForRedraw(); // redraw if required if (m_bRedrawPending) Draw(); } void EditorSkeletalMeshEditor::ConnectUIEvents() { // actions connect(m_ui->actionOpenMesh, SIGNAL(triggered()), this, SLOT(OnActionOpenMeshClicked())); connect(m_ui->actionSaveMesh, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshClicked())); connect(m_ui->actionSaveMeshAs, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshAsClicked())); connect(m_ui->actionClose, SIGNAL(triggered()), this, SLOT(OnActionCloseClicked())); connect(m_ui->actionCameraPerspective, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraPerspectiveTriggered(bool))); connect(m_ui->actionCameraArcball, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraArcballTriggered(bool))); connect(m_ui->actionCameraIsometric, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraIsometricTriggered(bool))); connect(m_ui->actionViewWireframe, SIGNAL(triggered(bool)), this, SLOT(OnActionViewWireframeTriggered(bool))); connect(m_ui->actionViewUnlit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewUnlitTriggered(bool))); connect(m_ui->actionViewLit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewLitTriggered(bool))); connect(m_ui->actionViewFlagShadows, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagShadowsTriggered(bool))); connect(m_ui->actionViewFlagWireframeOverlay, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagWireframeOverlayTriggered(bool))); connect(m_ui->actionToolInformation, SIGNAL(triggered(bool)), this, SLOT(OnActionToolInformationTriggered(bool))); connect(m_ui->actionToolOperations, SIGNAL(triggered(bool)), this, SLOT(OnActionToolOperationsTriggered(bool))); connect(m_ui->actionToolMaterials, SIGNAL(triggered(bool)), this, SLOT(OnActionToolMaterialsTriggered(bool))); connect(m_ui->actionToolLOD, SIGNAL(triggered(bool)), this, SLOT(OnActionToolLODTriggered(bool))); connect(m_ui->actionToolCollision, SIGNAL(triggered(bool)), this, SLOT(OnActionToolCollisionTriggered(bool))); connect(m_ui->actionToolImport, SIGNAL(triggered(bool)), this, SLOT(OnActionToolImportTriggered(bool))); connect(m_ui->actionToolLightManipulator, SIGNAL(triggered(bool)), this, SLOT(OnActionToolLightManipulatorTriggered(bool))); // swapchain connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); connect(m_ui->swapChainWidget, SIGNAL(DropEvent(QDropEvent *)), this, SLOT(OnSwapChainWidgetDropEvent(QDropEvent *))); // frame event connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); // operations connect(m_ui->toolOperationsGenerateTangents, SIGNAL(clicked()), this, SLOT(OnOperationsGenerateTangentsClicked())); connect(m_ui->toolOperationsCenterMesh, SIGNAL(clicked()), this, SLOT(OnOperationsCenterMeshClicked())); connect(m_ui->toolOperationsRemoveUnusedVertices, SIGNAL(clicked()), this, SLOT(OnOperationsRemoveUnusedVerticesClicked())); connect(m_ui->toolOperationsRemoveUnusedTriangles, SIGNAL(clicked()), this, SLOT(OnOperationsRemoveUnusedTrianglesClicked())); // importer connect(m_ui->toolImportSelectFileName, SIGNAL(clicked()), this, SLOT(OnToolImportSelectFileNameClicked())); connect(m_ui->toolImportImport, SIGNAL(clicked()), this, SLOT(OnToolImportImportClicked())); } void EditorSkeletalMeshEditor::closeEvent(QCloseEvent *pCloseEvent) { } void EditorSkeletalMeshEditor::OnActionOpenMeshClicked() { } void EditorSkeletalMeshEditor::OnActionSaveMeshClicked() { EditorProgressDialog progressDialog(this); progressDialog.show(); Save(&progressDialog); } void EditorSkeletalMeshEditor::OnActionSaveMeshAsClicked() { EditorResourceSaveDialog saveDialog(this, OBJECT_TYPEINFO(StaticMesh)); if (saveDialog.exec()) { String newMeshName(saveDialog.GetReturnValueResourceName()); // attempt save EditorProgressDialog progressDialog(this); progressDialog.show(); SaveAs(newMeshName, &progressDialog); } } void EditorSkeletalMeshEditor::OnActionCloseClicked() { } void EditorSkeletalMeshEditor::OnSwapChainWidgetResized() { uint32 newWidth = (uint32)m_ui->swapChainWidget->size().width(); uint32 newHeight = (uint32)m_ui->swapChainWidget->size().height(); // kill old swapchain refs if (m_pSwapChain != nullptr) { m_pSwapChain->Release(); m_pSwapChain = NULL; } // skip full recreation if we can just do the resize if (m_bHardwareResourcesCreated && (m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) != nullptr) m_pSwapChain->AddRef(); else m_bHardwareResourcesCreated = false; m_viewController.SetViewportDimensions(newWidth, newHeight); m_guiContext.SetViewportDimensions(newWidth, newHeight); // flag for redraw FlagForRedraw(); } void EditorSkeletalMeshEditor::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorSkeletalMeshEditor::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // pass to camera m_viewController.HandleKeyboardEvent(pKeyboardEvent); } void EditorSkeletalMeshEditor::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { if (m_currentState == State_None) { } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { //switch (m_currentState) //{ //} } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_currentState == State_None) { // right mouse button enters camera rotation state m_currentState = State_RotateCamera; return; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_currentState == State_RotateCamera) { m_currentState = State_None; return; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pMouseEvent->x(), pMouseEvent->y()); int2 lastMousePosition(m_lastMousePosition); int2 mousePositionDiff(currentMousePosition - lastMousePosition); m_lastMousePosition = currentMousePosition; switch (m_currentState) { case State_RotateCamera: m_viewController.RotateFromMousePosition(mousePositionDiff); FlagForRedraw(); break; } } } void EditorSkeletalMeshEditor::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { } void EditorSkeletalMeshEditor::OnSwapChainWidgetGainedFocusEvent() { } void EditorSkeletalMeshEditor::OnOperationsGenerateTangentsClicked() { for (uint32 i = 0; i < m_pGenerator->GetLODCount(); i++) m_pGenerator->GenerateTangents(i); } void EditorSkeletalMeshEditor::OnOperationsCenterMeshClicked() { QMenu popupMenu; popupMenu.addAction(tr("Origin: Center")); popupMenu.addAction(tr("Origin: Bottom-middle-center")); QAction *action = popupMenu.exec(QCursor::pos()); if (action != nullptr) { if (action->text() == tr("Origin: Center")) m_pGenerator->CenterMesh(StaticMeshGenerator::CenterOrigin_Center); else if (action->text() == tr("Origin: Bottom-middle-center")) m_pGenerator->CenterMesh(StaticMeshGenerator::CenterOrigin_CenterBottom); else return; UpdateInformationTab(); RefreshPreviewMesh(); FlagForRedraw(); } } void EditorSkeletalMeshEditor::OnOperationsRemoveUnusedVerticesClicked() { } void EditorSkeletalMeshEditor::OnOperationsRemoveUnusedTrianglesClicked() { } void EditorSkeletalMeshEditor::OnToolImportSelectFileNameClicked() { QString filename = QFileDialog::getOpenFileName(this, tr("Select Mesh File..."), QStringLiteral(""), tr("Static Mesh Formats (*.obj *.fbx *.ase *.3ds *.bsp *.md3 *.dae *.blend)"), NULL, 0); if (filename.isEmpty()) return; // create a progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // attempt to find the mesh names Array<String> meshNames; if (!AssimpStaticMeshImporter::GetFileSubMeshNames(ConvertQStringToString(filename), meshNames, &progressDialog)) return; // update the combo box m_ui->toolImportSubMeshName->clear(); for (uint32 i = 0; i < meshNames.GetSize(); i++) m_ui->toolImportSubMeshName->addItem(ConvertStringToQString(meshNames[i])); m_ui->toolImportSubMeshName->addItem(tr("* All Meshes"), QVariant(1u)); // enable the import button m_ui->toolImportSelectFileName->setText(filename); m_ui->toolImportImport->setEnabled(true); } void EditorSkeletalMeshEditor::OnToolImportImportClicked() { AssimpStaticMeshImporter::Options options; AssimpStaticMeshImporter::SetDefaultOptions(&options); options.SourcePath = ConvertQStringToString(m_ui->toolImportSelectFileName->text()); options.ImportMaterials = m_ui->toolImportMaterials->isChecked(); options.MaterialDirectory = ConvertQStringToString(m_ui->toolImportMaterialDirectory->text()); options.MaterialPrefix = ConvertQStringToString(m_ui->toolImportMaterialPrefix->text()); options.DefaultMaterialName = g_pEngine->GetDefaultMaterialName(); options.TransformMatrix = float4x4::MakeScaleMatrix(m_ui->toolImportScale->GetValueFloat3()); // create a progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // create and run importer AssimpStaticMeshImporter *pImporter = new AssimpStaticMeshImporter(&options, &progressDialog); if (!pImporter->Execute()) { progressDialog.DisplayError("Import failed. The error log may contain more information."); delete pImporter; return; } // valid? if (!m_pGenerator->IsCompleteMesh()) { progressDialog.DisplayError("Import did not produce any usable meshes."); delete pImporter; return; } // clone the mesh m_pGenerator->Copy(pImporter->GetOutputGenerator()); // and cleanup delete pImporter; // refresh the stuff LoadMaterials(); UpdateInformationTab(); RefreshPreviewMesh(); RefreshCollisionShapePreview(); } <file_sep>/Engine/Source/ContentConverter/AssimpSkeletonImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpSkeletonImporter.h" #include "ContentConverter/AssimpCommon.h" #include "ResourceCompiler/SkeletonGenerator.h" AssimpSkeletonImporter::AssimpSkeletonImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(NULL), m_pLogStream(NULL), m_pScene(NULL), m_pOutputGenerator(NULL) { } AssimpSkeletonImporter::~AssimpSkeletonImporter() { delete m_pOutputGenerator; delete m_pLogStream; delete m_pImporter; } void AssimpSkeletonImporter::SetDefaultOptions(Options *pOptions) { pOptions->CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; pOptions->TransformMatrix.SetIdentity(); } bool AssimpSkeletonImporter::Execute() { Timer timer; if (m_pOptions->SourcePath.IsEmpty() || m_pOptions->OutputResourceName.IsEmpty()) { m_pProgressCallbacks->ModalError("Missing parameters"); return false; } // ensure assimp is initialized if (!AssimpHelpers::InitializeAssimp()) { m_pProgressCallbacks->ModalError("assimp initialization failed"); return false; } timer.Reset(); if (!LoadScene()) { m_pProgressCallbacks->ModalError("LoadScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("LoadScene(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateBones()) { m_pProgressCallbacks->ModalError("CreateBones() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateBones(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!WriteOutput()) { m_pProgressCallbacks->ModalError("WriteOutput() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("WriteOutput(): %.4f ms", timer.GetTimeMilliseconds()); return true; } bool AssimpSkeletonImporter::LoadScene() { // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // get post process flags uint32 postProcessFlags = AssimpHelpers::GetAssimpSkeletonImportPostProcessingFlags(); // get coordinate system transform float4x4 coordinateSystemTransform(float4x4::MakeCoordinateSystemConversionMatrix(m_pOptions->CoordinateSystem, COORDINATE_SYSTEM_Z_UP_RH, nullptr)); // create global transform m_globalTransform = m_pOptions->TransformMatrix * coordinateSystemTransform; m_inverseGlobalTransform = m_globalTransform.Inverse(); // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(postProcessFlags); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } bool AssimpSkeletonImporter::CreateBones() { // create generator m_pOutputGenerator = new SkeletonGenerator(); // read the root bone if (m_pScene->mRootNode == NULL || !ReadBoneInfoFromNode(m_pScene->mRootNode, -1)) return false; m_pProgressCallbacks->DisplayFormattedInformation("Created %u bones", m_pOutputGenerator->GetBoneCount()); return true; } bool AssimpSkeletonImporter::ReadBoneInfoFromNode(const aiNode *pNode, int32 parentBoneIndex) { // // fix coordinate system // aiMatrix4x4 CSTransform(AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4()); // // // decompose the matrix to get the base frame transform from this node // aiVector3D baseFrameScaling; // aiQuaternion baseFrameRotation; // aiVector3D baseFramePosition; // (CSTransform * pNode->mTransformation).Decompose(baseFrameScaling, baseFrameRotation, baseFramePosition); // // for first bone, transform to our coordinate system // if (parentBoneIndex < 0) // { // aiMatrix4x4 tempMatrix(AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4() * pNode->mTransformation); // tempMatrix.Decompose(baseFrameScaling, baseFrameRotation, baseFramePosition); // } // decompose the matrix to get the base frame transform from this node aiVector3D baseFrameScaling; aiQuaternion baseFrameRotation; aiVector3D baseFramePosition; if (parentBoneIndex < 0) { //aiMatrix4x4 tempMatrix(AssimpHelpers::GetAssimpToWorldCoordinateSystemAIMatrix4x4() * pNode->mTransformation); aiMatrix4x4 tempMatrix(AssimpHelpers::Float4x4ToAssimpMatrix4x4(m_globalTransform) * pNode->mTransformation); tempMatrix.Decompose(baseFrameScaling, baseFrameRotation, baseFramePosition); } else { pNode->mTransformation.Decompose(baseFrameScaling, baseFrameRotation, baseFramePosition); } // get bone name SmallString boneName; if (pNode->mName.length == 0) boneName.Format("__bone_%u__", m_pOutputGenerator->GetBoneCount()); else boneName = pNode->mName.C_Str(); // handle duplicate bone names if (m_pOutputGenerator->GetBoneByName(boneName) != nullptr) { boneName.Format("__bone_%u__", m_pOutputGenerator->GetBoneCount()); m_pProgressCallbacks->DisplayFormattedWarning("duplicate bone name: '%s', changing to '%s'", pNode->mName.C_Str(), boneName.GetCharArray()); } // create base frame transform Transform baseFrameTransform(AssimpHelpers::AssimpVector3ToFloat3(baseFramePosition), AssimpHelpers::AssimpQuaternionToQuaternion(baseFrameRotation), AssimpHelpers::AssimpVector3ToFloat3(baseFrameScaling)); // find parent bone in output hierarchy SkeletonGenerator::Bone *pParentBone = (parentBoneIndex >= 0) ? m_pOutputGenerator->GetBoneByIndex((uint32)parentBoneIndex) : NULL; // create bone SkeletonGenerator::Bone *pBone = m_pOutputGenerator->CreateBone(boneName, pParentBone, baseFrameTransform); if (pBone == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not create bone '%s'", boneName.GetCharArray()); return false; } // dump node m_pProgressCallbacks->DisplayFormattedDebugMessage("new bone '%s' (parent '%s') at %s", pBone->GetName().GetCharArray(), (pBone->GetParent() != NULL) ? pBone->GetParent()->GetName().GetCharArray() : "NULL", StringConverter::Float3ToString(pBone->GetBaseFrameTransform().GetPosition()).GetCharArray()); // read children for (uint32 i = 0; i < pNode->mNumChildren; i++) { if (!ReadBoneInfoFromNode(pNode->mChildren[i], (int32)pBone->GetIndex())) return false; } // ok return true; } bool AssimpSkeletonImporter::WriteOutput() { PathString outputResourceFileName; outputResourceFileName.Format("%s.skl.xml", m_pOptions->OutputResourceName.GetCharArray()); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputResourceFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not open file '%s'", outputResourceFileName.GetCharArray()); return false; } if (!m_pOutputGenerator->SaveToXML(pStream)) { m_pProgressCallbacks->DisplayError("failed to save xml file"); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); return true; } <file_sep>/Engine/Source/MathLib/Frustum.cpp #include "MathLib/Frustum.h" #include "MathLib/SIMDVectorf.h" Frustum::Frustum(const Frustum &frCopy) { uint32 i; for (i = 0; i < FRUSTUM_PLANE_COUNT; i++) m_planes[i] = frCopy.m_planes[i]; } void Frustum::SetFromMatrix(const Matrix4x4f &matViewProj) { m_planes[FRUSTUM_PLANE_LEFT].a = matViewProj[3][0] + matViewProj[0][0]; m_planes[FRUSTUM_PLANE_LEFT].b = matViewProj[3][1] + matViewProj[0][1]; m_planes[FRUSTUM_PLANE_LEFT].c = matViewProj[3][2] + matViewProj[0][2]; m_planes[FRUSTUM_PLANE_LEFT].d = matViewProj[3][3] + matViewProj[0][3]; m_planes[FRUSTUM_PLANE_LEFT].NormalizeInPlace(); m_planes[FRUSTUM_PLANE_RIGHT].a = matViewProj[3][0] - matViewProj[0][0]; m_planes[FRUSTUM_PLANE_RIGHT].b = matViewProj[3][1] - matViewProj[0][1]; m_planes[FRUSTUM_PLANE_RIGHT].c = matViewProj[3][2] - matViewProj[0][2]; m_planes[FRUSTUM_PLANE_RIGHT].d = matViewProj[3][3] - matViewProj[0][3]; m_planes[FRUSTUM_PLANE_RIGHT].NormalizeInPlace(); m_planes[FRUSTUM_PLANE_TOP].a = matViewProj[3][0] - matViewProj[1][0]; m_planes[FRUSTUM_PLANE_TOP].b = matViewProj[3][1] - matViewProj[1][1]; m_planes[FRUSTUM_PLANE_TOP].c = matViewProj[3][2] - matViewProj[1][2]; m_planes[FRUSTUM_PLANE_TOP].d = matViewProj[3][3] - matViewProj[1][3]; m_planes[FRUSTUM_PLANE_TOP].NormalizeInPlace(); m_planes[FRUSTUM_PLANE_BOTTOM].a = matViewProj[3][0] + matViewProj[1][0]; m_planes[FRUSTUM_PLANE_BOTTOM].b = matViewProj[3][1] + matViewProj[1][1]; m_planes[FRUSTUM_PLANE_BOTTOM].c = matViewProj[3][2] + matViewProj[1][2]; m_planes[FRUSTUM_PLANE_BOTTOM].d = matViewProj[3][3] + matViewProj[1][3]; m_planes[FRUSTUM_PLANE_BOTTOM].NormalizeInPlace(); m_planes[FRUSTUM_PLANE_NEAR].a = matViewProj[3][0] + matViewProj[2][0]; m_planes[FRUSTUM_PLANE_NEAR].b = matViewProj[3][1] + matViewProj[2][1]; m_planes[FRUSTUM_PLANE_NEAR].c = matViewProj[3][2] + matViewProj[2][2]; m_planes[FRUSTUM_PLANE_NEAR].d = matViewProj[3][3] + matViewProj[2][3]; m_planes[FRUSTUM_PLANE_NEAR].NormalizeInPlace(); m_planes[FRUSTUM_PLANE_FAR].a = matViewProj[3][0] - matViewProj[2][0]; m_planes[FRUSTUM_PLANE_FAR].b = matViewProj[3][1] - matViewProj[2][1]; m_planes[FRUSTUM_PLANE_FAR].c = matViewProj[3][2] - matViewProj[2][2]; m_planes[FRUSTUM_PLANE_FAR].d = matViewProj[3][3] - matViewProj[2][3]; m_planes[FRUSTUM_PLANE_FAR].NormalizeInPlace(); } void Frustum::SetFromAABox(const AABox &aabBox) { const Vector3f &Low = aabBox.GetMinBounds(); const Vector3f &High = aabBox.GetMaxBounds(); m_planes[FRUSTUM_PLANE_LEFT].a = -1.0f; m_planes[FRUSTUM_PLANE_LEFT].b = 0.0f; m_planes[FRUSTUM_PLANE_LEFT].c = 0.0f; m_planes[FRUSTUM_PLANE_LEFT].d = -Low.x; m_planes[FRUSTUM_PLANE_RIGHT].a = 1.0f; m_planes[FRUSTUM_PLANE_RIGHT].b = 0.0f; m_planes[FRUSTUM_PLANE_RIGHT].c = 0.0f; m_planes[FRUSTUM_PLANE_RIGHT].d = High.x; m_planes[FRUSTUM_PLANE_BOTTOM].a = 0.0f; m_planes[FRUSTUM_PLANE_BOTTOM].b = -1.0f; m_planes[FRUSTUM_PLANE_BOTTOM].c = 0.0f; m_planes[FRUSTUM_PLANE_BOTTOM].d = -Low.y; m_planes[FRUSTUM_PLANE_TOP].a = 0.0f; m_planes[FRUSTUM_PLANE_TOP].b = 1.0f; m_planes[FRUSTUM_PLANE_TOP].c = 0.0f; m_planes[FRUSTUM_PLANE_TOP].d = High.y; m_planes[FRUSTUM_PLANE_FAR].a = 0.0f; m_planes[FRUSTUM_PLANE_FAR].b = 0.0f; m_planes[FRUSTUM_PLANE_FAR].c = -1.0f; m_planes[FRUSTUM_PLANE_FAR].d = -Low.z; m_planes[FRUSTUM_PLANE_NEAR].a = 0.0f; m_planes[FRUSTUM_PLANE_NEAR].b = 0.0f; m_planes[FRUSTUM_PLANE_NEAR].c = 1.0f; m_planes[FRUSTUM_PLANE_NEAR].d = High.z; } bool Frustum::AABoxIntersection(const AABox &aabBounds) const { SIMDVector3f cornerVertices[8]; aabBounds.GetCornerPoints(cornerVertices); // check if the points fit in the frustum. if no points fit, toss it out uint32 i, j; for (i = 0; i < FRUSTUM_PLANE_COUNT; i++) { SIMDVector3f planeNormal(m_planes[i].GetNormal()); float planeDistance = m_planes[i].GetDistance(); uint32 pointsIn = 8; for (j = 0; j < 8; j++) { float hitDistance = planeNormal.Dot(cornerVertices[j]) + planeDistance; if (hitDistance < 0) pointsIn--; } if (pointsIn == 0) return false; } return true; } bool Frustum::SphereIntersection(const Sphere &sphere) const { SIMDVector3f sphereCenter(sphere.GetCenter()); float sphereRadius = sphere.GetRadius(); float negSphereRadius = -sphere.GetRadius(); for (uint32 i = 0; i < FRUSTUM_PLANE_COUNT; i++) { float hitDistance = SIMDVector3f(m_planes[i].GetNormal()).Dot(sphereCenter) + m_planes[i].GetDistance(); // Outside if (hitDistance < negSphereRadius) return false; // Intersection if (Math::Abs(hitDistance) < sphereRadius) return true; } return true; } Frustum::IntersectionType Frustum::AABoxIntersectionType(const AABox &box) const { SIMDVector3f cornerVertices[8]; box.GetCornerPoints(cornerVertices); // check if the points fit in the frustum. if no points fit, toss it out IntersectionType intersectionType = INTERSECTION_TYPE_INSIDE; for (uint32 i = 0; i < FRUSTUM_PLANE_COUNT; i++) { SIMDVector3f planeNormal(m_planes[i].GetNormal()); float planeDistance = m_planes[i].GetDistance(); uint32 pointsIn = 8; for (uint32 j = 0; j < 8; j++) { float hitDistance = planeNormal.Dot(cornerVertices[j]) + planeDistance; if (hitDistance < 0) pointsIn--; } if (pointsIn == 0) return INTERSECTION_TYPE_OUTSIDE; else if (pointsIn != 8) intersectionType = INTERSECTION_TYPE_INTERSECTS; } return intersectionType; } Frustum::IntersectionType Frustum::SphereIntersectionType(const Sphere &sphere) const { SIMDVector3f sphereCenter(sphere.GetCenter()); float sphereRadius = sphere.GetRadius(); float negSphereRadius = -sphereRadius; for (uint32 i = 0; i < FRUSTUM_PLANE_COUNT; i++) { float hitDistance = SIMDVector3f(m_planes[i].GetNormal()).Dot(sphereCenter) + m_planes[i].GetDistance(); // if distance < -sphereRadius, outside if (hitDistance < negSphereRadius) return INTERSECTION_TYPE_OUTSIDE; // if abs(distance) < sphereRadius, intersect if (Math::Abs(hitDistance) < sphereRadius) return INTERSECTION_TYPE_INTERSECTS; } return INTERSECTION_TYPE_INSIDE; } bool Frustum::operator==(const Frustum &Comp) const { return m_planes[FRUSTUM_PLANE_LEFT] == Comp.m_planes[FRUSTUM_PLANE_LEFT] && m_planes[FRUSTUM_PLANE_RIGHT] == Comp.m_planes[FRUSTUM_PLANE_RIGHT] && m_planes[FRUSTUM_PLANE_NEAR] == Comp.m_planes[FRUSTUM_PLANE_NEAR] && m_planes[FRUSTUM_PLANE_FAR] == Comp.m_planes[FRUSTUM_PLANE_FAR] && m_planes[FRUSTUM_PLANE_TOP] == Comp.m_planes[FRUSTUM_PLANE_TOP] && m_planes[FRUSTUM_PLANE_BOTTOM] == Comp.m_planes[FRUSTUM_PLANE_BOTTOM]; } bool Frustum::operator!=(const Frustum &Comp) const { return m_planes[FRUSTUM_PLANE_LEFT] != Comp.m_planes[FRUSTUM_PLANE_LEFT] || m_planes[FRUSTUM_PLANE_RIGHT] != Comp.m_planes[FRUSTUM_PLANE_RIGHT] || m_planes[FRUSTUM_PLANE_NEAR] != Comp.m_planes[FRUSTUM_PLANE_NEAR] || m_planes[FRUSTUM_PLANE_FAR] != Comp.m_planes[FRUSTUM_PLANE_FAR] || m_planes[FRUSTUM_PLANE_TOP] != Comp.m_planes[FRUSTUM_PLANE_TOP] || m_planes[FRUSTUM_PLANE_BOTTOM] != Comp.m_planes[FRUSTUM_PLANE_BOTTOM]; } Frustum &Frustum::operator=(const Frustum &Copy) { uint32 i; for (i = 0; i < FRUSTUM_PLANE_COUNT; i++) m_planes[i] = Copy.m_planes[i]; return *this; } void Frustum::GetCornerVertices(Vector3f pVertices[8]) const { SIMDVector3f out[8]; GetCornerVertices(out); for (uint32 i = 0; i < 8; i++) pVertices[i] = out[i]; } void Frustum::GetCornerVertices(SIMDVector3f pVertices[8]) const { #if 0 Matrix4 inverseViewProjectionMatrix(m_ViewProjectionMatrix); inverseViewProjectionMatrix.InvertInPlace(); static const float unitCubeVertices[8][4] = { { -1.0f, -1.0f, 0.0f, 1.0f }, { 1.0f, -1.0f, 0.0f, 1.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 0.0f, 1.0f }, { -1.0f, -1.0f, 1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, }; for (uint32 i = 0; i < 8; i++) { Vector4 transformed = (inverseViewProjectionMatrix * Vector4(unitCubeVertices[i])); pVertices[i] = transformed.xyz() / transformed.w; } #else pVertices[0] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_NEAR], m_planes[FRUSTUM_PLANE_BOTTOM], m_planes[FRUSTUM_PLANE_RIGHT]); pVertices[1] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_NEAR], m_planes[FRUSTUM_PLANE_TOP], m_planes[FRUSTUM_PLANE_RIGHT]); pVertices[2] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_NEAR], m_planes[FRUSTUM_PLANE_TOP], m_planes[FRUSTUM_PLANE_LEFT]); pVertices[3] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_NEAR], m_planes[FRUSTUM_PLANE_BOTTOM], m_planes[FRUSTUM_PLANE_LEFT]); pVertices[4] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_FAR], m_planes[FRUSTUM_PLANE_BOTTOM], m_planes[FRUSTUM_PLANE_RIGHT]); pVertices[5] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_FAR], m_planes[FRUSTUM_PLANE_TOP], m_planes[FRUSTUM_PLANE_RIGHT]); pVertices[6] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_FAR], m_planes[FRUSTUM_PLANE_TOP], m_planes[FRUSTUM_PLANE_LEFT]); pVertices[7] = Plane::CalculateThreePlaneIntersectionPoint(m_planes[FRUSTUM_PLANE_FAR], m_planes[FRUSTUM_PLANE_BOTTOM], m_planes[FRUSTUM_PLANE_LEFT]); #endif } AABox Frustum::GetBoundingAABox() const { SIMDVector3f cornerVertices[8]; GetCornerVertices(cornerVertices); return AABox::FromPoints(cornerVertices, countof(cornerVertices)); } Sphere Frustum::GetBoundingSphere() const { SIMDVector3f cornerVertices[8]; GetCornerVertices(cornerVertices); return Sphere::FromPoints(cornerVertices, countof(cornerVertices)); } <file_sep>/Engine/Source/ContentConverterStandalone/Main.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" #include "Engine/Common.h" #include "Engine/Engine.h" Log_SetChannel(ContentConverter); int ModuleRedirector(int argc, char **argv) { if (argc < 1) { Log_ErrorPrintf("Expected at least a module name."); return 2; } // restore log level g_pLog->SetConsoleOutputParams(true, NULL, LOGLEVEL_PROFILE); // parse first arg char *moduleName = argv[0]; argv = ((--argc) > 0) ? argv + 1 : NULL; if (!Y_stricmp(moduleName, "OBJImporter")) { Log_InfoPrintf("Using OBJImporter module."); return RunOBJImporter(argc, argv); } else if (!Y_stricmp(moduleName, "TextureImporter")) { Log_InfoPrintf("Using TextureImporter module."); return RunTextureImporter(argc, argv); } else if (!Y_stricmp(moduleName, "FontImporter")) { Log_InfoPrintf("Using FontImporter module."); return RunFontImporter(argc, argv); } else if (!Y_stricmp(moduleName, "AssimpSkeletonImporter")) { Log_InfoPrintf("Using AssimpSkeletonImporter module."); return RunAssimpSkeletonImporter(argc, argv); } else if (!Y_stricmp(moduleName, "AssimpSkeletalMeshImporter")) { Log_InfoPrintf("Using AssimpSkeletalMeshImporter module."); return RunAssimpSkeletalMeshImporter(argc, argv); } else if (!Y_stricmp(moduleName, "AssimpSkeletalAnimationImporter")) { Log_InfoPrintf("Using AssimpSkeletalAnimationImporter module."); return RunAssimpSkeletalAnimationImporter(argc, argv); } else if (!Y_stricmp(moduleName, "AssimpStaticMeshImporter")) { Log_InfoPrintf("Using AssimpStaticMeshImporter module."); return RunAssimpStaticMeshImporter(argc, argv); } else if (!Y_stricmp(moduleName, "AssimpSceneImporter")) { Log_InfoPrintf("Using AssimpSceneImporter module."); return RunAssimpSceneImporter(argc, argv); } else { Log_ErrorPrintf("Invalid module name specified."); return 2; } } int main(int argc, char *argv[]) { // set log flags g_pLog->SetConsoleOutputParams(true); g_pLog->SetDebugOutputParams(true); // parse command line uint32 argsStart = g_pConsole->ParseCommandLine(argc, (const char **)argv); // adjust pointers int newArgc = argc - argsStart; char **newArgv = argv + argsStart; // initialize VFS if (!g_pVirtualFileSystem->Initialize()) { Log_ErrorPrintf("VFS startup failed. Cannot continue."); return false; } // initialize engine if (!g_pEngine->Startup()) { Log_ErrorPrintf("Engine startup failed. Cannot continue."); g_pVirtualFileSystem->Shutdown(); return false; } // register types g_pEngine->RegisterEngineTypes(); // run modules int returnCode = ModuleRedirector(newArgc, newArgv); // shutdown everything g_pEngine->Shutdown(); g_pEngine->UnregisterTypes(); g_pVirtualFileSystem->Shutdown(); return returnCode; } <file_sep>/Engine/Source/ResourceCompiler/ObjectTemplateManager.h #pragma once #include "ResourceCompiler/Common.h" #include "ResourceCompiler/ObjectTemplate.h" struct ResourceCompilerCallbacks; class ObjectTemplateManager : public Singleton<ObjectTemplateManager> { public: ObjectTemplateManager(); ~ObjectTemplateManager(); // attempts to load the template if it isn't loaded const ObjectTemplate *GetObjectTemplate(const char *typeName); // loads an object template using a callback for file i/o const ObjectTemplate *GetObjectTemplate(ResourceCompilerCallbacks *pCallbacks, const char *typeName); // accessors const uint32 GetObjectTemplateCount() const { return m_templates.GetMemberCount(); } // load all templates bool LoadAllTemplates(); template<class T> void EnumerateObjectTemplates(T callback) const { for (StorageMap::ConstIterator itr = m_templates.Begin(); !itr.AtEnd(); itr.Forward()) callback(itr->Value); } private: // try loading from disk static ObjectTemplate *LoadObjectTemplate(const char *typeName); static ObjectTemplate *LoadObjectTemplate(ResourceCompilerCallbacks *pCallbacks, const char *typeName); // storage typedef CIStringHashTable<ObjectTemplate *> StorageMap; StorageMap m_templates; bool m_allTemplatesLoaded; }; <file_sep>/Engine/Dependancies/bullet/Demos/VehicleDemo/Makefile.am noinst_PROGRAMS=VehicleDemo VehicleDemo_SOURCES=VehicleDemo.cpp VehicleDemo.h heightfield128x128.cpp main.cpp VehicleDemo_CXXFLAGS=-I@top_builddir@/src -I@top_builddir@/Demos/OpenGL $(CXXFLAGS) VehicleDemo_LDADD=-L../OpenGL -lbulletopenglsupport -L../../src -lBulletDynamics -lBulletCollision -lLinearMath @opengl_LIBS@ <file_sep>/Engine/Source/BaseGame/CMakeLists.txt set(HEADER_FILES BaseGame.h Common.h GameEntity.h GameState.h InteractiveEntity.h LivingEntity.h LoadingScreenProgressCallbacks.h ) set(SOURCE_FILES BaseGame.cpp GameEntity.cpp InteractiveEntity.cpp LivingEntity.cpp LoadingScreenProgressCallbacks.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/../Dependancies/microprofile ${SDL2_INCLUDE_DIR}) add_library(EngineBaseGame STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineBaseGame EngineGameFramework EngineMain EngineCore) <file_sep>/Engine/Source/OpenGLRenderer/OpenGLDefines.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLCommon.h" #include "OpenGLRenderer/OpenGLGPUTexture.h" Log_SetChannel(OpenGLRenderBackend); #define GL_ERROR_NAME(s) Y_NameTable_Entry(#s, s) Y_Define_NameTable(NameTables::GLErrors) GL_ERROR_NAME(GL_NO_ERROR) GL_ERROR_NAME(GL_INVALID_ENUM) GL_ERROR_NAME(GL_INVALID_VALUE) GL_ERROR_NAME(GL_INVALID_OPERATION) GL_ERROR_NAME(GL_STACK_OVERFLOW) GL_ERROR_NAME(GL_STACK_UNDERFLOW) GL_ERROR_NAME(GL_OUT_OF_MEMORY) Y_NameTable_End() void OpenGLTypeConversion::GetOpenGLVersionForRendererFeatureLevel(RENDERER_FEATURE_LEVEL featureLevel, uint32 *pMajorVersion, uint32 *pMinorVersion) { switch (featureLevel) { // case RENDERER_FEATURE_LEVEL_OPENGL_2_1: // *pMajorVersion = 2; *pMinorVersion = 0; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_3_0: // *pMajorVersion = 3; *pMinorVersion = 0; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_3_1: // *pMajorVersion = 3; *pMinorVersion = 1; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_3_2: // *pMajorVersion = 3; *pMinorVersion = 2; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_3_3: // *pMajorVersion = 3; *pMinorVersion = 3; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_4_0: // *pMajorVersion = 4; *pMinorVersion = 0; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_4_1: // *pMajorVersion = 4; *pMinorVersion = 1; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_4_2: // *pMajorVersion = 4; *pMinorVersion = 2; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_4_3: // *pMajorVersion = 4; *pMinorVersion = 3; // break; // // case RENDERER_FEATURE_LEVEL_OPENGL_4_4: // *pMajorVersion = 4; *pMinorVersion = 4; // break; case RENDERER_FEATURE_LEVEL_SM4: *pMajorVersion = 3; *pMinorVersion = 3; break; case RENDERER_FEATURE_LEVEL_SM5: *pMajorVersion = 4; *pMinorVersion = 1; break; default: UnreachableCode(); break; } } RENDERER_FEATURE_LEVEL OpenGLTypeConversion::GetRendererFeatureLevelForOpenGLVersion(uint32 majorVersion, uint32 minorVersion) { if (majorVersion >= 4) { if (minorVersion >= 4) return RENDERER_FEATURE_LEVEL_SM5; else if (minorVersion == 3) return RENDERER_FEATURE_LEVEL_SM5; else if (minorVersion == 2) return RENDERER_FEATURE_LEVEL_SM5; else if (minorVersion == 1) return RENDERER_FEATURE_LEVEL_SM4; else return RENDERER_FEATURE_LEVEL_SM4; } else if (majorVersion == 3) { if (minorVersion >= 3) return RENDERER_FEATURE_LEVEL_SM4; else if (minorVersion == 2) return RENDERER_FEATURE_LEVEL_SM4; else if (minorVersion == 1) return RENDERER_FEATURE_LEVEL_ES3; else return RENDERER_FEATURE_LEVEL_ES2; } else if (majorVersion == 2) { if (minorVersion >= 1) return RENDERER_FEATURE_LEVEL_ES2; } return RENDERER_FEATURE_LEVEL_COUNT; } struct OpenGLTextureFormatMapping { GLint GLInternalFormat; GLenum GLFormat; GLenum GLType; bool IsCompressed; }; /* // PixelFormat // GLInternalFormat // GLFormat // GLType // IsCompressed { PIXEL_FORMAT_R8G8B8A8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R16G16_FLOAT, GL_RG16F, GL_RG, GL_HALF_FLOAT, false }, { PIXEL_FORMAT_R16G16B16A16_FLOAT, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, false }, { PIXEL_FORMAT_R32G32_FLOAT, GL_RG32F, GL_RG, GL_FLOAT, false }, { PIXEL_FORMAT_R32G32B32A32_FLOAT, GL_RGBA32F, GL_RGBA, GL_FLOAT, false }, { PIXEL_FORMAT_B8G8R8X8_UNORM, GL_RGB8, GL_BGRA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_B8G8R8A8_UNORM, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R8G8B8A8_SNORM, GL_RGBA8_SNORM, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R16G16B16A16_SNORM, GL_RGBA16_SNORM, GL_RGBA, GL_UNSIGNED_SHORT, false }, { PIXEL_FORMAT_BC1_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, { PIXEL_FORMAT_BC2_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, { PIXEL_FORMAT_BC3_UNORM, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, { PIXEL_FORMAT_R8_SINT, GL_R8I, GL_RED, GL_BYTE, false }, { PIXEL_FORMAT_R8_UINT, GL_R8UI, GL_RED, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R8_SNORM, GL_R8, GL_RED, GL_BYTE, false }, { PIXEL_FORMAT_R8_UNORM, GL_R8, GL_RED, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R16_SINT, GL_R16I, GL_RED, GL_SHORT, false }, { PIXEL_FORMAT_R16_UINT, GL_R16UI, GL_RED, GL_UNSIGNED_SHORT, false }, { PIXEL_FORMAT_R16_SNORM, GL_R16, GL_RED, GL_SHORT, false }, { PIXEL_FORMAT_R16_UNORM, GL_R16, GL_RED, GL_UNSIGNED_SHORT, false }, { PIXEL_FORMAT_R16_FLOAT, GL_R16F, GL_RED, GL_HALF_FLOAT, false }, { PIXEL_FORMAT_R32_SINT, GL_R32I, GL_RED, GL_INT, false }, { PIXEL_FORMAT_R32_UINT, GL_R32UI, GL_RED, GL_UNSIGNED_INT, false }, { PIXEL_FORMAT_R32_FLOAT, GL_R32F, GL_RED, GL_FLOAT, false }, { PIXEL_FORMAT_D16_UNORM, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, { PIXEL_FORMAT_D24_UNORM_S8_UINT, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, { PIXEL_FORMAT_D32_FLOAT, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false }, { PIXEL_FORMAT_D32_FLOAT_S8X24_UINT, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, false }, { PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB, GL_SRGB8, GL_BGRA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_BC1_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_BC2_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_BC3_UNORM_SRGB, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, false }, { PIXEL_FORMAT_R8G8B8_UNORM, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, */ // todo: 'cannot upload' format, for those with bad format/type static const OpenGLTextureFormatMapping s_OpenGLTextureFormatMapping[PIXEL_FORMAT_COUNT] = { // GLInternalFormat // GLFormat // GLType // IsCompressed { GL_R8UI, GL_RED, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8_UINT { GL_R8I, GL_RED, GL_BYTE, false }, // PIXEL_FORMAT_R8_SINT { GL_R8, GL_RED, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8_UNORM { GL_R8_SNORM, GL_RED, GL_BYTE, false }, // PIXEL_FORMAT_R8_SNORM { GL_RG8UI, GL_RG, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8_UINT { GL_RG8I, GL_RG, GL_BYTE, false }, // PIXEL_FORMAT_R8G8_SINT { GL_RG8, GL_RG, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8_UNORM { GL_RG8_SNORM, GL_RG, GL_BYTE, false }, // PIXEL_FORMAT_R8G8_SNORM { GL_RGBA8UI, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_UINT { GL_RGBA8I, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_SINT { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_UNORM { GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB { GL_RGBA8_SNORM, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_SNORM { GL_RGB9_E5, GL_RGB, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R9G9B9E5_SHAREDEXP { GL_RGB10_A2UI, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R10G10B10A2_UINT { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R10G10B10A2_UNORM { GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R11G11B10_FLOAT { GL_R16UI, GL_RED, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_R16_UINT { GL_R16I, GL_RED, GL_SHORT, false }, // PIXEL_FORMAT_R16_SINT { GL_R16, GL_RED, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_R16_UNORM { GL_R16_SNORM, GL_RED, GL_SHORT, false }, // PIXEL_FORMAT_R16_SNORM { GL_R16F, GL_RED, GL_HALF_FLOAT, false }, // PIXEL_FORMAT_R16_FLOAT { GL_RG16UI, GL_RG, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_R16G16_UINT { GL_RG16I, GL_RG, GL_SHORT, false }, // PIXEL_FORMAT_R16G16_SINT { GL_RG16, GL_RG, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_R16G16_UNORM { GL_RG16_SNORM, GL_RG, GL_SHORT, false }, // PIXEL_FORMAT_R16G16_SNORM { GL_RG16F, GL_RG, GL_HALF_FLOAT, false }, // PIXEL_FORMAT_R16G16_FLOAT { GL_RGBA16UI, GL_RGBA, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_R16G16B16A16_UINT { GL_RGBA16I, GL_RGBA, GL_SHORT, false }, // PIXEL_FORMAT_R16G16B16A16_SINT { GL_RGBA16, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R16G16B16A16_UNORM { GL_RGBA16_SNORM, GL_RGBA, GL_SHORT, false }, // PIXEL_FORMAT_R16G16B16A16_SNORM { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, false }, // PIXEL_FORMAT_R16G16B16A16_FLOAT { GL_R32UI, GL_RED, GL_UNSIGNED_INT, false }, // PIXEL_FORMAT_R32_UINT { GL_R32I, GL_RED, GL_INT, false }, // PIXEL_FORMAT_R32_SINT { GL_R32F, GL_RED, GL_FLOAT, false }, // PIXEL_FORMAT_R32_FLOAT { GL_RG32UI, GL_RG, GL_UNSIGNED_INT, false }, // PIXEL_FORMAT_R32G32_UINT { GL_RG32I, GL_RG, GL_INT, false }, // PIXEL_FORMAT_R32G32_SINT { GL_RG32F, GL_RG, GL_FLOAT, false }, // PIXEL_FORMAT_R32G32_FLOAT { GL_RGB32UI, GL_RGB, GL_UNSIGNED_INT, false }, // PIXEL_FORMAT_R32G32B32_UINT { GL_RGB32I, GL_RGB, GL_INT, false }, // PIXEL_FORMAT_R32G32B32_SINT { GL_RGB32F, GL_RGB, GL_FLOAT, false }, // PIXEL_FORMAT_R32G32B32_FLOAT { GL_RGBA32UI, GL_RGB, GL_UNSIGNED_INT, false }, // PIXEL_FORMAT_R32G32B32A32_UINT { GL_RGBA32I, GL_RGB, GL_INT, false }, // PIXEL_FORMAT_R32G32B32A32_SINT { GL_RGBA32F, GL_RGB, GL_FLOAT, false }, // PIXEL_FORMAT_R32G32B32A32_FLOAT { GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B8G8R8A8_UNORM { GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB { GL_RGB8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B8G8R8X8_UNORM { GL_SRGB8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB { GL_RGB565, GL_BGR, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B5G6R5_UNORM { GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B5G5R5A1_UNORM { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC1_UNORM { GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC1_UNORM_SRGB { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC2_UNORM { GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC2_UNORM_SRGB { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC3_UNORM { GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC3_UNORM_SRGB { GL_COMPRESSED_RED_RGTC1, GL_RED, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC4_UNORM { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC4_SNORM { GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC5_UNORM { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RG, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC5_SNORM { GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RG, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC6H_UF16 { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RG, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC6H_SF16 { GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC7_UNORM { GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC7_UNORM_SRGB { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_D16_UNORM { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // PIXEL_FORMAT_D24_UNORM_S8_UINT { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // PIXEL_FORMAT_D32_FLOAT { GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, false }, // PIXEL_FORMAT_D32_FLOAT_S8X24_UINT { GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8_UNORM { GL_RGB8, GL_BGR, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_B8G8R8_UNORM }; bool OpenGLTypeConversion::GetOpenGLTextureFormat(PIXEL_FORMAT PixelFormat, GLint *pGLInternalFormat, GLenum *pGLFormat, GLenum *pGLType) { DebugAssert(PixelFormat < PIXEL_FORMAT_COUNT); const OpenGLTextureFormatMapping *pMapping = &s_OpenGLTextureFormatMapping[PixelFormat]; if (pMapping->GLFormat == 0) return false; if (pGLInternalFormat != nullptr) *pGLInternalFormat = pMapping->GLInternalFormat; if (pGLFormat != nullptr) *pGLFormat = pMapping->GLFormat; if (pGLType != nullptr) *pGLType = pMapping->GLType; return true; } struct OpenGLUniformShaderVertexElementTypeVAOMapping { GPU_VERTEX_ELEMENT_TYPE VertexElementType; bool IntegerType; GLenum GLType; GLint GLSize; GLboolean GLNormalized; }; static const OpenGLUniformShaderVertexElementTypeVAOMapping s_OpenGLUniformShaderVertexElementTypeVAOMapping[] = { // VertexElementType IntegerType GLType GLSize GLNormalized { GPU_VERTEX_ELEMENT_TYPE_BYTE, true, GL_BYTE, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_BYTE2, true, GL_BYTE, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_BYTE4, true, GL_BYTE, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE, true, GL_UNSIGNED_BYTE, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE2, true, GL_UNSIGNED_BYTE, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE4, true, GL_UNSIGNED_BYTE, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF, false, GL_FLOAT16_NV, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF2, false, GL_FLOAT16_NV, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF4, false, GL_FLOAT16_NV, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT, false, GL_FLOAT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT2, false, GL_FLOAT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT3, false, GL_FLOAT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT4, false, GL_FLOAT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT, true, GL_INT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT2, true, GL_INT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT3, true, GL_INT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT4, true, GL_INT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT, true, GL_UNSIGNED_INT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT2, true, GL_UNSIGNED_INT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT3, true, GL_UNSIGNED_INT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT4, true, GL_UNSIGNED_INT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_SNORM4, false, GL_BYTE, 4, GL_TRUE }, { GPU_VERTEX_ELEMENT_TYPE_UNORM4, false, GL_UNSIGNED_BYTE, 4, GL_TRUE }, }; void OpenGLTypeConversion::GetOpenGLVAOTypeAndSizeForVertexElementType(GPU_VERTEX_ELEMENT_TYPE elementType, bool *pIntegerType, GLenum *pGLType, GLint *pGLSize, GLboolean *pGLNormalized) { uint32 i; for (i = 0; i < countof(s_OpenGLUniformShaderVertexElementTypeVAOMapping); i++) { const OpenGLUniformShaderVertexElementTypeVAOMapping *pTypeMapping = &s_OpenGLUniformShaderVertexElementTypeVAOMapping[i]; if (pTypeMapping->VertexElementType == elementType) { *pIntegerType = pTypeMapping->IntegerType; *pGLType = pTypeMapping->GLType; *pGLSize = pTypeMapping->GLSize; *pGLNormalized = pTypeMapping->GLNormalized; return; } } Panic("Unhandled case!"); } GLenum OpenGLTypeConversion::GetOpenGLComparisonFunc(GPU_COMPARISON_FUNC ComparisonFunc) { static const GLenum OpenGLComparisonFuncs[GPU_COMPARISON_FUNC_COUNT] = { GL_NEVER, // RENDERER_COMPARISON_FUNC_NEVER GL_LESS, // RENDERER_COMPARISON_FUNC_LESS GL_EQUAL, // RENDERER_COMPARISON_FUNC_EQUAL GL_LEQUAL, // RENDERER_COMPARISON_FUNC_LESS_EQUAL GL_GREATER, // RENDERER_COMPARISON_FUNC_GREATER GL_NOTEQUAL, // RENDERER_COMPARISON_FUNC_NOT_EQUAL GL_GEQUAL, // RENDERER_COMPARISON_FUNC_GREATER_EQUAL GL_ALWAYS, // RENDERER_COMPARISON_FUNC_ALWAYS }; DebugAssert(ComparisonFunc < GPU_COMPARISON_FUNC_COUNT); return OpenGLComparisonFuncs[ComparisonFunc]; } GLenum OpenGLTypeConversion::GetOpenGLComparisonMode(TEXTURE_FILTER Filter) { DebugAssert(Filter < TEXTURE_FILTER_COUNT); if (Filter >= TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT && Filter <= TEXTURE_FILTER_COMPARISON_ANISOTROPIC) return GL_COMPARE_REF_TO_TEXTURE; else return GL_NONE; } GLenum OpenGLTypeConversion::GetOpenGLTextureMinFilter(TEXTURE_FILTER Filter) { static const GLenum OpenGLMinFilters[TEXTURE_FILTER_COUNT] = { GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_MAG_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_ANISOTROPIC GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_ANISOTROPIC }; DebugAssert(Filter < TEXTURE_FILTER_COUNT); return OpenGLMinFilters[Filter]; } GLenum OpenGLTypeConversion::GetOpenGLTextureMagFilter(TEXTURE_FILTER Filter) { static const GLenum GLOpenMagFilters[TEXTURE_FILTER_COUNT] = { GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_ANISOTROPIC GL_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT GL_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR GL_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT GL_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR GL_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT GL_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR GL_LINEAR, // TEXTURE_FILTER_COMPARISON_ANISOTROPIC }; DebugAssert(Filter < TEXTURE_FILTER_COUNT); return GLOpenMagFilters[Filter]; } GLenum OpenGLTypeConversion::GetOpenGLTextureWrap(TEXTURE_ADDRESS_MODE AddressMode) { static const GLenum OpenGLTextureAddresses[TEXTURE_ADDRESS_MODE_COUNT] = { GL_REPEAT, // RENDERER_TEXTURE_ADDRESS_WRAP GL_MIRRORED_REPEAT, // RENDERER_TEXTURE_ADDRESS_MIRROR GL_CLAMP_TO_EDGE, // RENDERER_TEXTURE_ADDRESS_CLAMP GL_CLAMP_TO_BORDER, // RENDERER_TEXTURE_ADDRESS_BORDER GL_MIRRORED_REPEAT, // RENDERER_TEXTURE_ADDRESS_MIRROR_ONCE // FIXME }; DebugAssert(AddressMode < TEXTURE_ADDRESS_MODE_COUNT); return OpenGLTextureAddresses[AddressMode]; } GLenum OpenGLTypeConversion::GetOpenGLPolygonMode(RENDERER_FILL_MODE FillMode) { static const GLenum OpenGLPolygonModes[RENDERER_FILL_MODE_COUNT] = { GL_LINE, // RENDERER_FILL_WIREFRAME GL_FILL, // RENDERER_FILL_SOLID }; DebugAssert(FillMode < RENDERER_FILL_MODE_COUNT); return OpenGLPolygonModes[FillMode]; } GLenum OpenGLTypeConversion::GetOpenGLCullFace(RENDERER_CULL_MODE CullMode) { static const GLenum OpenGLCullModes[RENDERER_CULL_MODE_COUNT] = { GL_BACK, // RENDERER_CULL_NONE GL_FRONT, // RENDERER_CULL_FRONT GL_BACK, // RENDERER_CULL_BACK }; DebugAssert(CullMode < RENDERER_CULL_MODE_COUNT); return OpenGLCullModes[CullMode]; } GLenum OpenGLTypeConversion::GetOpenGLStencilOp(RENDERER_STENCIL_OP StencilOp) { static const GLenum OpenGLStencilOps[RENDERER_STENCIL_OP_COUNT] = { GL_KEEP, // RENDERER_STENCIL_OP_KEEP GL_ZERO, // RENDERER_STENCIL_OP_ZERO GL_REPLACE, // RENDERER_STENCIL_OP_REPLACE GL_INCR_WRAP, // RENDERER_STENCIL_OP_INCREMENT_CLAMPED GL_DECR_WRAP, // RENDERER_STENCIL_OP_DECREMENT_CLAMPED GL_INVERT, // RENDERER_STENCIL_OP_INVERT GL_INCR, // RENDERER_STENCIL_OP_INCREMENT GL_DECR, // RENDERER_STENCIL_OP_DECREMENT }; DebugAssert(StencilOp < RENDERER_STENCIL_OP_COUNT); return OpenGLStencilOps[StencilOp]; } GLenum OpenGLTypeConversion::GetOpenGLBlendEquation(RENDERER_BLEND_OP BlendOp) { static const GLenum OpenGLBlendEquations[RENDERER_BLEND_OP_COUNT] = { GL_FUNC_ADD, // RENDERER_BLEND_OP_ADD GL_FUNC_SUBTRACT, // RENDERER_BLEND_OP_SUBTRACT GL_FUNC_REVERSE_SUBTRACT, // RENDERER_BLEND_OP_REV_SUBTRACT GL_MIN, // RENDERER_BLEND_OP_MIN GL_MAX, // RENDERER_BLEND_OP_MAX }; DebugAssert(BlendOp < RENDERER_BLEND_OP_COUNT); return OpenGLBlendEquations[BlendOp]; } GLenum OpenGLTypeConversion::GetOpenGLBlendFunc(RENDERER_BLEND_OPTION BlendFactor) { static const GLenum OpenGLBlendFuncs[RENDERER_BLEND_OPTION_COUNT] = { GL_ZERO, // RENDERER_BLEND_ZERO GL_ONE, // RENDERER_BLEND_ONE GL_SRC_COLOR, // RENDERER_BLEND_SRC_COLOR GL_ONE_MINUS_SRC_COLOR, // RENDERER_BLEND_INV_SRC_COLOR GL_SRC_ALPHA, // RENDERER_BLEND_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA, // RENDERER_BLEND_INV_SRC_ALPHA GL_DST_ALPHA, // RENDERER_BLEND_DEST_ALPHA GL_ONE_MINUS_DST_ALPHA, // RENDERER_BLEND_INV_DEST_ALPHA GL_DST_COLOR, // RENDERER_BLEND_DEST_COLOR GL_ONE_MINUS_DST_COLOR, // RENDERER_BLEND_INV_DEST_COLOR GL_SRC_ALPHA_SATURATE, // RENDERER_BLEND_SRC_ALPHA_SAT GL_CONSTANT_COLOR, // RENDERER_BLEND_BLEND_FACTOR GL_ONE_MINUS_CONSTANT_COLOR, // RENDERER_BLEND_INV_BLEND_FACTOR GL_SRC1_COLOR, // RENDERER_BLEND_SRC1_COLOR GL_ONE_MINUS_SRC1_COLOR, // RENDERER_BLEND_INV_SRC1_COLOR GL_SRC1_ALPHA, // RENDERER_BLEND_SRC1_ALPHA GL_ONE_MINUS_SRC1_ALPHA, // RENDERER_BLEND_INV_SRC1_ALPHA }; DebugAssert(BlendFactor < RENDERER_BLEND_OPTION_COUNT); return OpenGLBlendFuncs[BlendFactor]; } GLenum OpenGLTypeConversion::GetOpenGLTextureTarget(TEXTURE_TYPE textureType) { switch (textureType) { case TEXTURE_TYPE_1D: return GL_TEXTURE_1D; case TEXTURE_TYPE_1D_ARRAY: return GL_TEXTURE_1D_ARRAY; case TEXTURE_TYPE_2D: return GL_TEXTURE_2D; case TEXTURE_TYPE_2D_ARRAY: return GL_TEXTURE_2D_ARRAY; case TEXTURE_TYPE_3D: return GL_TEXTURE_3D; case TEXTURE_TYPE_CUBE: return GL_TEXTURE_CUBE_MAP; case TEXTURE_TYPE_CUBE_ARRAY: return GL_TEXTURE_CUBE_MAP_ARRAY; } Panic("Unhandled type"); return GL_TEXTURE_2D; } GLenum OpenGLHelpers::GetOpenGLTextureTarget(GPUTexture *pGPUTexture) { if (pGPUTexture == NULL) return 0; switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: return GL_TEXTURE_1D; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: return GL_TEXTURE_1D_ARRAY; case GPU_RESOURCE_TYPE_TEXTURE2D: return GL_TEXTURE_2D; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return GL_TEXTURE_2D_ARRAY; case GPU_RESOURCE_TYPE_TEXTURE3D: return GL_TEXTURE_3D; case GPU_RESOURCE_TYPE_TEXTURECUBE: return GL_TEXTURE_CUBE_MAP; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: return GL_TEXTURE_CUBE_MAP_ARRAY; } return 0; } GLuint OpenGLHelpers::GetOpenGLTextureId(GPUTexture *pGPUTexture) { if (pGPUTexture == NULL) return 0; switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: return static_cast<OpenGLGPUTexture1D *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: return static_cast<OpenGLGPUTexture1DArray *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<OpenGLGPUTexture2D *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<OpenGLGPUTexture2DArray *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURE3D: return static_cast<OpenGLGPUTexture3D *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURECUBE: return static_cast<OpenGLGPUTextureCube *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: return static_cast<OpenGLGPUTextureCubeArray *>(pGPUTexture)->GetGLTextureId(); } return 0; } void OpenGLHelpers::BindOpenGLTexture(GPUTexture *pGPUTexture) { if (pGPUTexture == nullptr) { glBindTexture(GL_TEXTURE_2D, 0); return; } switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: glBindTexture(GL_TEXTURE_1D, static_cast<OpenGLGPUTexture1D *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: glBindTexture(GL_TEXTURE_1D_ARRAY, static_cast<OpenGLGPUTexture1DArray *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURE2D: glBindTexture(GL_TEXTURE_2D, static_cast<OpenGLGPUTexture2D *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: glBindTexture(GL_TEXTURE_2D_ARRAY, static_cast<OpenGLGPUTexture2DArray *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURE3D: glBindTexture(GL_TEXTURE_3D, static_cast<OpenGLGPUTexture3D *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: glBindTexture(GL_TEXTURE_CUBE_MAP, static_cast<OpenGLGPUTextureCube *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, static_cast<OpenGLGPUTextureCubeArray *>(pGPUTexture)->GetGLTextureId()); break; } } #if 0 void OpenGLHelpers::OpenGLSetUniform(GLint Location, GLsizei ArraySize, SHADER_UNIFORM_TYPE UniformType, const void *pData) { static bool useNvidiaHack = false; /*#if Y_PLATFORM_LINUX static bool nvidiaHackInitialized = false; if (!nvidiaHackInitialized) { // I'm nvidia and my drivers are behaving weird, they seem to obey the row major layout for uniform buffers, // but also reverses the ordering of program uniforms. This only happens on linux, but not windows... // WTF?! Fix me properly at some point... if (Y_strcmp(reinterpret_cast<const char *>(glGetString(GL_VENDOR)), "NVIDIA Corporation") == 0) useNvidiaHack = true; nvidiaHackInitialized = true; } #endif*/ switch (UniformType) { case SHADER_UNIFORM_TYPE_BOOL: glUniform1iv(Location, ArraySize, reinterpret_cast<const GLint *>(pData)); break; case SHADER_UNIFORM_TYPE_INT: glUniform1iv(Location, ArraySize, reinterpret_cast<const GLint *>(pData)); break; case SHADER_UNIFORM_TYPE_INT2: glUniform2iv(Location, ArraySize, reinterpret_cast<const GLint *>(pData)); break; case SHADER_UNIFORM_TYPE_INT3: glUniform3iv(Location, ArraySize, reinterpret_cast<const GLint *>(pData)); break; case SHADER_UNIFORM_TYPE_INT4: glUniform4iv(Location, ArraySize, reinterpret_cast<const GLint *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT: glUniform1fv(Location, ArraySize, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT2: glUniform2fv(Location, ArraySize, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT3: glUniform3fv(Location, ArraySize, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT4: glUniform4fv(Location, ArraySize, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT2X2: glUniformMatrix2fv(Location, ArraySize, (useNvidiaHack) ? GL_FALSE : GL_TRUE, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT3X3: glUniformMatrix3fv(Location, ArraySize, (useNvidiaHack) ? GL_FALSE : GL_TRUE, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT3X4: glUniformMatrix4x3fv(Location, ArraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pData)); break; case SHADER_UNIFORM_TYPE_FLOAT4X4: glUniformMatrix4fv(Location, ArraySize, (useNvidiaHack) ? GL_FALSE : GL_TRUE, reinterpret_cast<const GLfloat *>(pData)); break; default: UnreachableCode(); break; } } #endif void OpenGLHelpers::ApplySamplerStateToTexture(GLenum target, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, pSamplerStateDesc->BorderColor); glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_ALWAYS); glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE); glTexParameterf(target, GL_TEXTURE_LOD_BIAS, pSamplerStateDesc->LODBias); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, OpenGLTypeConversion::GetOpenGLTextureMinFilter(pSamplerStateDesc->Filter)); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, OpenGLTypeConversion::GetOpenGLTextureMagFilter(pSamplerStateDesc->Filter)); glTexParameterf(target, GL_TEXTURE_MIN_LOD, (float)pSamplerStateDesc->MinLOD); glTexParameterf(target, GL_TEXTURE_MAX_LOD, (float)pSamplerStateDesc->MaxLOD); glTexParameteri(target, GL_TEXTURE_WRAP_S, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressU)); glTexParameteri(target, GL_TEXTURE_WRAP_T, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressV)); glTexParameteri(target, GL_TEXTURE_WRAP_R, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressW)); } void OpenGLHelpers::SetObjectDebugName(GLenum type, GLuint id, const char *debugName) { #ifdef Y_BUILD_CONFIG_DEBUG if (GLAD_GL_KHR_debug) { uint32 length = Y_strlen(debugName); if (length > 0) glObjectLabel(type, id, length, debugName); } #endif } // Since we have multiple threads, the last GL error has to be thread-local Y_DECLARE_THREAD_LOCAL(GLenum) s_lastGLError = GL_NO_ERROR; void OpenGLHelpers::ClearLastGLError() { s_lastGLError = GL_NO_ERROR; while (glGetError() != GL_NO_ERROR) ; } GLenum OpenGLHelpers::CheckForGLError() { GLenum error = glGetError(); s_lastGLError = error; return (error != GL_NO_ERROR); } GLenum OpenGLHelpers::GetLastGLError() { return s_lastGLError; } void OpenGLHelpers::PrintLastGLError(const char *format, ...) { char buffer[128]; va_list ap; va_start(ap, format); Y_vsnprintf(buffer, countof(buffer), format, ap); va_end(ap); GLenum error = s_lastGLError; if (error != GL_NO_ERROR) Log_ErrorPrintf("%s%s (0x%X)", buffer, NameTable_GetNameString(NameTables::GLErrors, error), error); else Log_ErrorPrintf("%sno error", buffer); } <file_sep>/Engine/Source/BlockEngine/BlockWorldMesher.h #pragma once #include "BlockEngine/BlockWorldTypes.h" #include "BlockEngine/BlockWorldVertexFactory.h" #include "Engine/BlockPalette.h" #include "Renderer/RenderQueue.h" class VertexBufferBindingArray; class GPUBuffer; class BlockWorldMesher { public: typedef BlockWorldVertexFactory::Vertex Vertex; struct FullVertex { float3 Position; float3 TexCoord; uint32 Color; float3 Tangent; float3 Binormal; float3 Normal; FullVertex() {} FullVertex(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal) : Position(position), TexCoord(texcoord), Color(color), Tangent(tangent), Binormal(binormal), Normal(normal) {} FullVertex(const FullVertex &v) { Y_memcpy(this, &v, sizeof(*this)); } void Set(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal) { Position = position; TexCoord = texcoord; Color = color; Tangent = tangent; Binormal = binormal; Normal = normal; } }; struct Triangle { uint32 MaterialIndex; uint32 Indices[3]; Triangle() { } Triangle(uint32 materialIndex, uint32 i0, uint32 i1, uint32 i2) { MaterialIndex = materialIndex; Indices[0] = i0; Indices[1] = i1; Indices[2] = i2; } void Set(uint32 materialIndex, uint32 i0, uint32 i1, uint32 i2) { MaterialIndex = materialIndex; Indices[0] = i0; Indices[1] = i1; Indices[2] = i2; } }; struct Batch { uint32 MaterialIndex; uint32 StartIndex; uint32 NumIndices; }; struct MeshInstances { uint32 MeshIndex; MemArray<float3x4> Transforms; uint32 BufferOffset; }; typedef MemArray<BlockWorldVertexFactory::Vertex> VertexArray; typedef MemArray<Triangle> TriangleArray; typedef MemArray<Batch> BatchArray; typedef PODArray<MeshInstances *> MeshInstancesArray; typedef MemArray<RENDER_QUEUE_POINT_LIGHT_ENTRY> LightArray; struct Output { AABox BoundingBox; Sphere BoundingSphere; VertexArray Vertices; TriangleArray Triangles; BatchArray Batches; MeshInstancesArray Instances; LightArray Lights; }; public: BlockWorldMesher(const BlockPalette *pPalette, uint32 chunkSize, uint32 lodLevel, const float3 &basePosition, bool generateLightMaps); ~BlockWorldMesher(); // input data accessors const BlockPalette *GetPalette() const { return m_pPalette; } const int32 GetChunkSize() const { return m_chunkSize; } const int32 GetLODLevel() const { return m_lodLevel; } const float3 &GetBasePosition() const { return m_basePosition; } // input data mutators BlockWorldBlockType *GetBlockValues() { return m_pBlockValues; } BlockWorldBlockDataType *GetBlockData() { return m_pBlockData; } // output data const AABox &GetOutputBoundingBox() const { return m_output.BoundingBox; } const Sphere &GetOutputBoundingSphere() const { return m_output.BoundingSphere; } const VertexArray &GetOutputVertices() const { return m_output.Vertices; } const uint32 GetOutputVertexCount() const { return m_output.Vertices.GetSize(); } const TriangleArray &GetOutputTriangles() const { return m_output.Triangles; } const uint32 GetOutputTriangleCount() const { return m_output.Triangles.GetSize(); } const BatchArray &GetOutputBatches() const { return m_output.Batches; } const uint32 GetOutputBatchCount() const { return m_output.Batches.GetSize(); } const LightArray &GetOutputLights() const { return m_output.Lights; } const uint32 GetOutputLightCount() const { return m_output.Lights.GetSize(); } const MeshInstancesArray &GetOutputMeshInstances() const { return m_output.Instances; } const uint32 GetOutputMeshInstancesCount() const { return m_output.Instances.GetSize(); } // generate a render view of the chunk void GenerateMesh(); // create gpu buffers for the generated data bool CreateGPUBuffers(VertexBufferBindingArray *pVertexBuffers, GPUBuffer **ppIndexBuffer, GPU_INDEX_FORMAT *pIndexFormat, GPUBuffer **ppInstanceTransformBuffer) { return CreateGPUBuffers(m_output, pVertexBuffers, ppIndexBuffer, pIndexFormat, ppInstanceTransformBuffer); } // create gpu buffers for the generated data static bool CreateGPUBuffers(const Output &output, VertexBufferBindingArray *pVertexBuffers, GPUBuffer **ppIndexBuffer, GPU_INDEX_FORMAT *pIndexFormat, GPUBuffer **ppInstanceTransformBuffer); // mesh a single block static bool MeshSingleBlock(const BlockPalette *pPalette, BlockWorldBlockType blockValue, Output &output); private: const BlockWorldBlockType GetBlockValueAt(uint32 x, uint32 y, uint32 z) const; const bool IsVisibleBlockAt(uint32 x, uint32 y, uint32 z) const; const bool IsVisibleNonTransparentBlockAt(uint32 x, uint32 y, uint32 z) const; const bool HasCubeLightBlockingBlockAt(uint32 x, uint32 y, uint32 z) const; const bool CalculateBlockFaceVisibility(uint32 x, uint32 y, uint32 z, BlockWorldBlockType blockValue, CUBE_FACE face) const; static const uint32 CalculateCubeVertexColor(const BlockPalette::BlockType *pBlockType, CUBE_FACE faceIndex, const uint32 blockValue, const uint32 blockLighting); static const uint32 CalculatePlaneVertexColor(const BlockPalette::BlockType *pBlockType, const uint32 blockValue, const uint32 blockLighting); const uint32 CalculateCubeFaceLighting(uint32 x, uint32 y, uint32 z, CUBE_FACE faceIndex); static void AddCubeBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, Output &output); static void AddSlabBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, bool isTopSlab, Output &output); static void AddStairBlockFace(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 startX, uint32 startY, uint32 startZ, uint32 endX, uint32 endY, uint32 endZ, CUBE_FACE face, Output &output); static void AddPlaneBlock(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output); static void AddMeshBlock(const BlockPalette::BlockType *pBlockType, BlockWorldBlockType blockValue, uint32 blockLighting, uint8 blockRotation, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output); static void AddLightBlock(const BlockPalette::BlockType *pBlockType, const float3 &basePosition, uint32 lodLevel, uint32 x, uint32 y, uint32 z, Output &output); static void OptimizeTriangleOrder(Output &output); static void GenerateBatches(Output &output); void GenerateBlocks(uint3 &minBlockCoordinates, uint3 &maxBlockCoordinates); // input data const BlockPalette *m_pPalette; uint32 m_chunkSize; uint32 m_lodLevel; float3 m_basePosition; BlockWorldBlockType *m_pBlockValues; BlockWorldBlockDataType *m_pBlockData; uint8 *m_pBlockFaceMasks; bool m_generateLightMaps; // output data Output m_output; }; <file_sep>/Engine/Source/Renderer/Shaders/SSAOShader.h #pragma once #include "Renderer/ShaderComponent.h" class ShaderProgram; class SSAOShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(SSAOShader, ShaderComponent); public: SSAOShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pNormalsTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; class SSAOApplyShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(SSAOApplyShader, ShaderComponent); public: SSAOApplyShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pAOTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUContext.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" #include "OpenGLRenderer/OpenGLGPUOutputBuffer.h" class OpenGLGPUDevice; class OpenGLGPURenderTargetView; class OpenGLGPUDepthStencilBufferView; class OpenGLGPUComputeView; class OpenGLGPURasterizerState; class OpenGLGPUDepthStencilState; class OpenGLGPUBlendState; class OpenGLGPUSamplerState; class OpenGLGPUBuffer; class OpenGLGPUInputLayout; class OpenGLGPUShaderProgram; class OpenGLGPUContext : public GPUContext { public: struct VertexBufferBinding { OpenGLGPUBuffer *pVertexBuffer; uint32 Offset; uint32 Stride; bool Dirty; }; struct VertexAttributeBinding { uint32 VertexBufferIndex; uint32 Offset; GLenum Type; GLint Size; GLboolean Normalized; GLuint Divisor; bool IntegerFormat; bool Initialized; bool Enabled; bool Dirty; }; struct TextureUnitBinding { GPUTexture *pTexture; OpenGLGPUSamplerState *pSampler; }; public: OpenGLGPUContext(OpenGLGPUDevice *pDevice, SDL_GLContext pSDLGLContext, OpenGLGPUOutputBuffer *pOutputBuffer); ~OpenGLGPUContext(); // Start of frame virtual void BeginFrame() override final; // Ensure all queued commands are sent to the GPU. virtual void Flush() override final; // Ensure all commands have been completed by the GPU. virtual void Finish() override final; // State clearing virtual void ClearState(bool clearShaders = true, bool clearBuffers = true, bool clearStates = true, bool clearRenderTargets = true) override final; // Retrieve RendererVariables interface. virtual GPUContextConstants *GetConstants() override { return m_pConstants; } // State Management (D3D11RenderSystem.cpp) virtual GPURasterizerState *GetRasterizerState() override final; virtual void SetRasterizerState(GPURasterizerState *pRasterizerState) override final; virtual GPUDepthStencilState *GetDepthStencilState() override final; virtual uint8 GetDepthStencilStateStencilRef() override final; virtual void SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 stencilRef) override final; virtual GPUBlendState *GetBlendState() override final; virtual const float4 &GetBlendStateBlendFactor() override final; virtual void SetBlendState(GPUBlendState *pBlendState, const float4 &blendFactor = float4::One) override final; // Viewport Management (D3D11RenderSystem.cpp) virtual const RENDERER_VIEWPORT *GetViewport() override final; virtual void SetViewport(const RENDERER_VIEWPORT *pNewViewport) override final; virtual void SetFullViewport(GPUTexture *pForRenderTarget = NULL) override final; // Scissor Rect Management (D3D11RenderSystem.cpp) virtual const RENDERER_SCISSOR_RECT *GetScissorRect() override final; virtual void SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) override final; // Buffer mapping/reading/writing virtual bool ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) override final; virtual bool WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) override final; virtual bool MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) override final; virtual void Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) override final; // Texture reading/writing virtual bool ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) override final; virtual bool ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) override final; virtual bool WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) override final; virtual bool WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; virtual bool WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) override final; // Texture copying virtual bool CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) override final; virtual bool CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) override final; // Blit (copy) a texture to the currently bound framebuffer. If this texture is a different size, it'll be resized virtual void BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter = RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST) override final; // Generate mips virtual void GenerateMips(GPUTexture *pTexture) override final; // Query accessing virtual bool BeginQuery(GPUQuery *pQuery) override final; virtual bool EndQuery(GPUQuery *pQuery) override final; virtual GPU_QUERY_GETDATA_RESULT GetQueryData(GPUQuery *pQuery, void *pData, uint32 cbData, uint32 flags) override final; // Predicated drawing virtual void SetPredication(GPUQuery *pQuery) override final; // RT Clearing virtual void ClearTargets(bool clearColor = true, bool clearDepth = true, bool clearStencil = true, const float4 &clearColorValue = float4::Zero, float clearDepthValue = 1.0f, uint8 clearStencilValue = 0) override final; virtual void DiscardTargets(bool discardColor = true, bool discardDepth = true, bool discardStencil = true) override final; // Swap chain virtual GPUOutputBuffer *GetOutputBuffer() override final { return m_pCurrentOutputBuffer; } virtual bool GetExclusiveFullScreen() override final; virtual bool SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) override final; virtual void SetOutputBuffer(GPUOutputBuffer *pSwapChain) override final; virtual bool ResizeOutputBuffer(uint32 width = 0, uint32 height = 0) override final; virtual void PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) override final; // RT Changing virtual uint32 GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) override final; virtual void SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) override final; // Drawing Setup virtual DRAW_TOPOLOGY GetDrawTopology() override final; virtual void SetDrawTopology(DRAW_TOPOLOGY topology) override final; // Vertex Buffer Setup virtual uint32 GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) override final; virtual void SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) override final; virtual void SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) override final; virtual void GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) override final; virtual void SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) override final; // Shader Setup virtual void SetShaderProgram(GPUShaderProgram *pShaderProgram) override final; virtual void SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) override final; virtual void SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) override final; virtual void SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) override final; virtual void SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) override final; virtual void SetShaderParameterResource(uint32 index, GPUResource *pResource) override final; virtual void SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) override final; // constant buffer management virtual void WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit = false) override final; virtual void WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit = false) override final; virtual void CommitConstantBuffer(uint32 bufferIndex) override final; // Draw calls virtual void Draw(uint32 firstVertex, uint32 nVertices) override final; virtual void DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) override final; virtual void DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) override final; virtual void DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) override final; // Draw calls with user-space buffer virtual void DrawUserPointer(const void *pVertices, uint32 vertexSize, uint32 nVertices) override final; // Compute shaders virtual void Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) override final; // Command list execution virtual GPUCommandList *CreateCommandList() override final; virtual bool OpenCommandList(GPUCommandList *pCommandList) override final; virtual bool CloseCommandList(GPUCommandList *pCommandList) override final; virtual void ExecuteCommandList(GPUCommandList *pCommandList) override final; // --- gl methods --- bool Create(); OpenGLGPUShaderProgram *GetOpenGLCurrentShaderProgram() { return m_pCurrentShaderProgram; } // constant resource management OpenGLGPUBuffer *GetConstantBuffer(uint32 index); // commit vertex buffer resources void CommitVertexAttributes(); // access to shader states for the shader mutators to modify void SetShaderVertexAttributes(const GPU_VERTEX_ELEMENT_DESC *pAttributeDescriptors, uint32 nAttributes); void SetShaderUniformBlock(uint32 index, OpenGLGPUBuffer *pBuffer); void SetShaderTextureUnit(uint32 index, GPUTexture *pTexture, OpenGLGPUSamplerState *pSamplerState); void SetShaderImageUnit(uint32 index, GPUTexture *pTexture); void SetShaderStorageBuffer(uint32 index, GPUResource *pResource); // commit shader resources (uniform blocks, texture units, image units, storage buffers) void CommitShaderResources(); // sets the active texture unit to the unit that can be most easily used for mutation (ie less likely to be bound) void BindMutatorTextureUnit(); // when using texture creation/modification functions, restores the texture if there was one bound to this texture unit void RestoreMutatorTextureUnit(); // update vsync settings in opengl void UpdateVSyncState(RENDERER_VSYNC_TYPE vsyncType); private: // preallocate constant buffers bool CreateConstantBuffers(); OpenGLGPUDevice *m_pDevice; SDL_GLContext m_pSDLGLContext; OpenGLGPUOutputBuffer *m_pCurrentOutputBuffer; GPUContextConstants *m_pConstants; RENDERER_VIEWPORT m_currentViewport; RENDERER_SCISSOR_RECT m_scissorRect; DRAW_TOPOLOGY m_drawTopology; GLenum m_glDrawTopology; // vertex buffer state GLuint m_vertexArrayObjectId; MemArray<VertexBufferBinding> m_currentVertexBuffers; uint32 m_activeVertexBuffers; bool m_dirtyVertexBuffers; MemArray<VertexAttributeBinding> m_currentVertexAttributes; uint32 m_activeVertexAttributes; bool m_dirtyVertexAttributes; // index buffer state OpenGLGPUBuffer *m_pCurrentIndexBuffer; GPU_INDEX_FORMAT m_currentIndexFormat; uint32 m_currentIndexBufferOffset; // shader state OpenGLGPUShaderProgram *m_pCurrentShaderProgram; // constant buffers struct ConstantBuffer { OpenGLGPUBuffer *pGPUBuffer; uint32 Size; byte *pLocalMemory; int32 DirtyLowerBounds; int32 DirtyUpperBounds; }; MemArray<ConstantBuffer> m_constantBuffers; // shader states PODArray<OpenGLGPUBuffer *> m_currentUniformBlockBindings; uint32 m_activeUniformBlockBindings; int32 m_dirtyUniformBlockBindingsLowerBounds; int32 m_dirtyUniformBlockBindingsUpperBounds; MemArray<TextureUnitBinding> m_currentTextureUnitBindings; uint32 m_activeTextureUnitBindings; uint32 m_mutatorTextureUnit; int32 m_dirtyTextureUnitsLowerBounds; int32 m_dirtyTextureUnitsUpperBounds; PODArray<GPUTexture *> m_currentImageUnitBindings; uint32 m_activeImageUnitBindings; int32 m_dirtyImageUnitsLowerBounds; int32 m_dirtyImageUnitsUpperBounds; PODArray<GPUResource *> m_currentShaderStorageBufferBindings; uint32 m_activeShaderStorageBufferBindings; int32 m_dirtyShaderStorageBuffersLowerBounds; int32 m_dirtyShaderStorageBuffersUpperBounds; // states OpenGLGPURasterizerState *m_pCurrentRasterizerState; OpenGLGPUDepthStencilState *m_pCurrentDepthStencilState; uint8 m_currentDepthStencilStateStencilRef; OpenGLGPUBlendState *m_pCurrentBlendState; float4 m_currentBlendStateBlendFactors; GLuint m_drawFrameBufferObjectId; GLuint m_readFrameBufferObjectId; OpenGLGPURenderTargetView *m_pCurrentRenderTargets[GPU_MAX_SIMULTANEOUS_RENDER_TARGETS]; OpenGLGPUDepthStencilBufferView *m_pCurrentDepthStencilBuffer; uint32 m_nCurrentRenderTargets; OpenGLGPUBuffer *m_pUserVertexBuffer; uint32 m_userVertexBufferSize; uint32 m_userVertexBufferPosition; }; <file_sep>/Engine/Source/Engine/TerrainLayerList.h #pragma once #include "Engine/Common.h" #include "Engine/Texture.h" #include "Engine/Material.h" #define TERRAIN_MAX_LAYERS (64) #define TERRAIN_MAX_STORAGE_LODS (4) #define TERRAIN_MAX_RENDER_LODS (10) struct TerrainLayerListBaseLayer { uint32 Index; bool Allocated; String Name; uint32 TextureRepeatInterval; int32 BaseTextureIndex; int32 BaseTextureArrayIndex; int32 NormalTextureIndex; int32 NormalTextureArrayIndex; }; class TerrainLayerList : public Resource { DECLARE_RESOURCE_TYPE_INFO(TerrainLayerList, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(TerrainLayerList); public: TerrainLayerList(const ResourceTypeInfo *pTypeInfo = &s_TypeInfo); ~TerrainLayerList(); const TerrainLayerListBaseLayer *GetBaseLayer(uint32 index) const { DebugAssert(index < m_baseLayerArraySize); return (m_pBaseLayers[index].Allocated) ? &m_pBaseLayers[index] : nullptr; } const TerrainLayerListBaseLayer *GetBaseLayerByName(const char *name) const; const uint32 GetBaseLayerArraySize() const { return m_baseLayerArraySize; } const Texture *GetTexture(uint32 index) const { DebugAssert(index < m_textureCount); return m_ppTextures[index]; } const uint32 GetTextureCount() const { return m_textureCount; } // create a material that can be used to render these layers, specify -1 to not render a layer const Material *CreateBaseLayerRenderMaterial(const int32 *pLayerIndices, uint32 nLayerIndices, GPUTexture2D *pNormalMapTexture, GPUTexture **pWeightTextures, uint32 nWeightTextures) const; // find the first available layer uint32 GetFirstLayerIndex() const; // serialization bool Load(const char *FileName, ByteStream *pStream); // gpu resources bool CreateGPUResources(); void ReleaseGPUResources(); private: TerrainLayerListBaseLayer *m_pBaseLayers; uint32 m_baseLayerArraySize; const Texture **m_ppTextures; uint32 m_textureCount; int32 m_combinedBaseLayerBaseTextureIndex; int32 m_combinedBaseLayerNormalTextureIndex; }; <file_sep>/Engine/Source/Renderer/RenderProxies/StaticMeshRenderProxy.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexBufferBindingArray.h" #include "Engine/StaticMesh.h" class Material; class StaticMeshRenderProxy : public RenderProxy { public: StaticMeshRenderProxy(uint32 entityId, const StaticMesh *pStaticMesh, const Transform &transform, uint32 shadowFlags); ~StaticMeshRenderProxy(); // update functions void SetStaticMesh(const StaticMesh *pStaticMesh); void SetMaterial(uint32 i, const Material *pMaterialOverride); void SetTransform(const Transform &transform); void SetTintColor(bool enabled, uint32 color = 0); void SetShadowFlags(uint32 shadowFlags); void SetVisibility(bool visible); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual bool CreateDeviceResources() const override; virtual void ReleaseDeviceResources() const override; private: // real methods void RealSetStaticMesh(const StaticMesh *pStaticMesh); void RealSetMaterial(uint32 i, const Material *pMaterialOverride); void RealSetTransform(const Transform &transform); void RealSetTintColor(bool enabled, uint32 color = 0); void RealSetShadowFlags(uint32 shadowFlags); void RealSetVisibility(bool visible); // read from render thread at async time, write from game thread at sync time bool m_visibility; const StaticMesh *m_pStaticMesh; PODArray<const Material *> m_materials; Transform m_transform; float4x4 m_localToWorldMatrix; uint32 m_shadowFlags; bool m_tintEnabled; uint32 m_tintColor; // gpu resources, also owned by render thread. mutable bool m_bGPUResourcesCreated; //mutable VertexBufferBindingArray m_VertexBuffers; }; <file_sep>/Editor/Source/Editor/ui_EditorResourcePreviewWidget.h #pragma once class Ui_EditorResourcePreviewWidget { public: QGridLayout *gridLayout; // toolbar QToolButton *toolbarViewWireframe; QToolButton *toolbarViewUnlit; QToolButton *toolbarViewLit; QToolButton *toolbarViewLightingOnly; QToolButton *toolbarFlagShadows; QToolButton *toolbarFlagWireframeOverlay; // swap chain EditorRendererSwapChainWidget *swapChainWidget; void CreateUI(QWidget *pWidget) { //static const char *TRANSLATION_CONTEXT = "EditorResourcePreviewWidget"; QHBoxLayout *horizontalLayout; QSpacerItem *horizontalSpacer; gridLayout = new QGridLayout(pWidget); gridLayout->setSpacing(0); gridLayout->setContentsMargins(0, 0, 0, 0); gridLayout->setMargin(0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(0); toolbarViewWireframe = new QToolButton(pWidget); toolbarViewWireframe->setMinimumSize(QSize(24, 24)); toolbarViewWireframe->setMaximumSize(QSize(24, 24)); toolbarViewWireframe->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Wireframe.png"))); toolbarViewWireframe->setCheckable(true); toolbarViewWireframe->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewWireframe); toolbarViewUnlit = new QToolButton(pWidget); toolbarViewUnlit->setMinimumSize(QSize(24, 24)); toolbarViewUnlit->setMaximumSize(QSize(24, 24)); toolbarViewUnlit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Unlit.png"))); toolbarViewUnlit->setCheckable(true); toolbarViewUnlit->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewUnlit); toolbarViewLit = new QToolButton(pWidget); toolbarViewLit->setMinimumSize(QSize(24, 24)); toolbarViewLit->setMaximumSize(QSize(24, 24)); toolbarViewLit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Lit.png"))); toolbarViewLit->setCheckable(true); toolbarViewLit->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewLit); toolbarViewLightingOnly = new QToolButton(pWidget); toolbarViewLightingOnly->setMinimumSize(QSize(24, 24)); toolbarViewLightingOnly->setMaximumSize(QSize(24, 24)); toolbarViewLightingOnly->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_LightingOnly.png"))); toolbarViewLightingOnly->setCheckable(true); toolbarViewLightingOnly->setAutoRaise(true); horizontalLayout->addWidget(toolbarViewLightingOnly); horizontalSpacer = new QSpacerItem(4, 24, QSizePolicy::Fixed, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); toolbarFlagShadows = new QToolButton(pWidget); toolbarFlagShadows->setMinimumSize(QSize(24, 24)); toolbarFlagShadows->setMaximumSize(QSize(24, 24)); toolbarFlagShadows->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_Shadows.png"))); toolbarFlagShadows->setCheckable(true); toolbarFlagShadows->setAutoRaise(true); horizontalLayout->addWidget(toolbarFlagShadows); toolbarFlagWireframeOverlay = new QToolButton(pWidget); toolbarFlagWireframeOverlay->setMinimumSize(QSize(24, 24)); toolbarFlagWireframeOverlay->setMaximumSize(QSize(24, 24)); toolbarFlagWireframeOverlay->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_WireframeOverlay.png"))); toolbarFlagWireframeOverlay->setCheckable(true); toolbarFlagWireframeOverlay->setAutoRaise(true); horizontalLayout->addWidget(toolbarFlagWireframeOverlay); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); gridLayout->addLayout(horizontalLayout, 0, 0, 1, 1); swapChainWidget = new EditorRendererSwapChainWidget(pWidget); swapChainWidget->setObjectName(QStringLiteral("swapChainWidget")); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(swapChainWidget->sizePolicy().hasHeightForWidth()); swapChainWidget->setSizePolicy(sizePolicy); swapChainWidget->setMaximumSize(QSize(16777215, 16777215)); swapChainWidget->setMouseTracking(true); swapChainWidget->setFocusPolicy(Qt::FocusPolicy(Qt::TabFocus | Qt::ClickFocus)); gridLayout->addWidget(swapChainWidget, 1, 0, 1, 1); } void UpdateUIForRenderMode(EDITOR_RENDER_MODE renderMode) { toolbarViewWireframe->setChecked((renderMode == EDITOR_RENDER_MODE_WIREFRAME)); toolbarViewUnlit->setChecked((renderMode == EDITOR_RENDER_MODE_FULLBRIGHT)); toolbarViewLit->setChecked((renderMode == EDITOR_RENDER_MODE_LIT)); toolbarViewLightingOnly->setChecked((renderMode == EDITOR_RENDER_MODE_LIGHTING_ONLY)); } void UpdateUIForViewportFlags(uint32 viewportFlags) { toolbarFlagShadows->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) != 0); toolbarFlagWireframeOverlay->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) != 0); } }; <file_sep>/Engine/Source/MathLib/SIMDMatrixf_scalar.cpp #include "MathLib/SIMDMatrixf_scalar.h" const SIMDMatrix3x3f &SIMDMatrix3x3f::Zero = reinterpret_cast<const SIMDMatrix3x3f &>(Matrix3x3f::Zero); const SIMDMatrix3x3f &SIMDMatrix3x3f::Identity = reinterpret_cast<const SIMDMatrix3x3f &>(Matrix3x3f::Identity); const SIMDMatrix4x4f &SIMDMatrix4x4f::Zero = reinterpret_cast<const SIMDMatrix4x4f &>(Matrix4x4f::Zero); const SIMDMatrix4x4f &SIMDMatrix4x4f::Identity = reinterpret_cast<const SIMDMatrix4x4f &>(Matrix4x4f::Identity); <file_sep>/Engine/Source/GameFramework/CMakeLists.txt set(HEADER_FILES BlockMeshBrush.h BlockMeshComponent.h BlockMeshEntity.h Common.h DirectionalLightEntity.h InterpolatorComponent.h ParticleEmitterComponent.h ParticleEmitterEntity.h PointLightComponent.h PointLightEntity.h PositionInterpolatorComponent.h PrecompiledHeader.h RotationInterpolatorComponent.h SpriteComponent.h SpriteEntity.h StaticMeshBrush.h StaticMeshComponent.h StaticMeshEntity.h StaticMeshRigidBodyEntity.h SunLightEntity.h ) set(SOURCE_FILES BlockMeshBrush.cpp BlockMeshComponent.cpp BlockMeshEntity.cpp DirectionalLightEntity.cpp InterpolatorComponent.cpp ParticleEmitterComponent.cpp ParticleEmitterEntity.cpp PointLightComponent.cpp PointLightEntity.cpp PositionInterpolatorComponent.cpp PrecompiledHeader.cpp RotationInterpolatorComponent.cpp SpriteComponent.cpp SpriteEntity.cpp StaticMeshBrush.cpp StaticMeshComponent.cpp StaticMeshEntity.cpp StaticMeshRigidBodyEntity.cpp SunLightEntity.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/../Dependancies/microprofile ${SDL2_INCLUDE_DIR}) add_library(EngineGameFramework STATIC ${HEADER_FILES} ${SOURCE_FILES}) set(EXTRA_LIBRARIES "") LIST(APPEND EXTRA_LIBRARIES EngineRenderer) if(WITH_RESOURCECOMPILER_EMBEDDED) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface EngineResourceCompiler") elseif(WITH_RESOURCECOMPILER_SUBPROCESS) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface") endif() target_link_libraries(EngineGameFramework EngineMain) <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphBuiltinNodes.h #pragma once #include "ResourceCompiler/ShaderGraphNode.h" #include "ResourceCompiler/ShaderGraphSchema.h" class ResourceTypeInfo; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Global : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Global, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Global); public: ShaderGraphNode_Global(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual ~ShaderGraphNode_Global() {} const String &GetGlobalName() const { return m_globalName; } void SetGlobalName(const char *globalName); virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override; virtual void SaveToXML(XMLWriter &xmlWriter) const override; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override; protected: String m_globalName; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_ShaderInputs : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_ShaderInputs, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_ShaderInputs); public: ShaderGraphNode_ShaderInputs(const ShaderGraphSchema::InputDeclaration *const *ppInputDeclarations, uint32 nInputDeclarations, const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override; }; class ShaderGraphNode_ShaderOutputs : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_ShaderOutputs, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_ShaderOutputs); public: ShaderGraphNode_ShaderOutputs(const ShaderGraphSchema::OutputDeclaration *const *ppOutputDeclarations, uint32 nOutputDeclarations, const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Parameter : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Parameter, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_Parameter); public: ShaderGraphNode_Parameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} const String &GetParameterName() const { return m_strParameterName; } void SetParameterName(const char *ParameterName); virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader); virtual void SaveToXML(XMLWriter &xmlWriter) const; protected: String m_strParameterName; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_UniformParameter : public ShaderGraphNode_Parameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_UniformParameter, ShaderGraphNode_Parameter); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_UniformParameter); public: ShaderGraphNode_UniformParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override final; virtual void SaveToXML(XMLWriter &xmlWriter) const override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_TextureParameter : public ShaderGraphNode_Parameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_TextureParameter, ShaderGraphNode_Parameter); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_TextureParameter); public: ShaderGraphNode_TextureParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual const ResourceTypeInfo *GetTextureTypeInfo() const = 0; virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override final; virtual void SaveToXML(XMLWriter &xmlWriter) const override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_StaticSwitchParameter : public ShaderGraphNode_Parameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_StaticSwitchParameter, ShaderGraphNode_Parameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_StaticSwitchParameter); public: ShaderGraphNode_StaticSwitchParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} //virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override; //virtual void SaveToXML(XMLWriter &xmlWriter) const; virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_FloatParameter : public ShaderGraphNode_UniformParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FloatParameter, ShaderGraphNode_UniformParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FloatParameter); public: ShaderGraphNode_FloatParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; class ShaderGraphNode_Float2Parameter : public ShaderGraphNode_UniformParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Parameter, ShaderGraphNode_UniformParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Parameter); public: ShaderGraphNode_Float2Parameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; class ShaderGraphNode_Float3Parameter : public ShaderGraphNode_UniformParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Parameter, ShaderGraphNode_UniformParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Parameter); public: ShaderGraphNode_Float3Parameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; class ShaderGraphNode_Float4Parameter : public ShaderGraphNode_UniformParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Parameter, ShaderGraphNode_UniformParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Parameter); public: ShaderGraphNode_Float4Parameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Texture2DParameter : public ShaderGraphNode_TextureParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Texture2DParameter, ShaderGraphNode_TextureParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Texture2DParameter); public: ShaderGraphNode_Texture2DParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} const ResourceTypeInfo *GetTextureTypeInfo() const; }; class ShaderGraphNode_Texture2DArrayParameter : public ShaderGraphNode_TextureParameter { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Texture2DArrayParameter, ShaderGraphNode_TextureParameter); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Texture2DArrayParameter); public: ShaderGraphNode_Texture2DArrayParameter(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} const ResourceTypeInfo *GetTextureTypeInfo() const; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Constant : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Constant, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_Constant); public: ShaderGraphNode_Constant(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual void GetValueString(String &Destination) const = 0; virtual bool SetValueString(const char *NewValue) = 0; virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override final; virtual void SaveToXML(XMLWriter &xmlWriter) const override final; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_FloatConstant : public ShaderGraphNode_Constant { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FloatConstant, ShaderGraphNode_Constant); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FloatConstant); public: ShaderGraphNode_FloatConstant(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); const float &GetValue() const { return m_Value; } void SetValue(const float &v) { m_Value = v; } virtual void GetValueString(String &Destination) const override final { StringConverter::FloatToString(Destination, m_Value); } virtual bool SetValueString(const char *NewValue) override final { m_Value = StringConverter::StringToFloat(NewValue); return true; } virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; protected: float m_Value; }; class ShaderGraphNode_Float2Constant : public ShaderGraphNode_Constant { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Constant, ShaderGraphNode_Constant); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Constant); public: ShaderGraphNode_Float2Constant(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); const float2 &GetValue() const { return m_Value; } void SetValue(const float2 &v) { m_Value = v; } virtual void GetValueString(String &Destination) const override final { StringConverter::Float2ToString(Destination, m_Value); } virtual bool SetValueString(const char *NewValue) override final { m_Value = StringConverter::StringToFloat2(NewValue); return true; } virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; protected: float2 m_Value; }; class ShaderGraphNode_Float3Constant : public ShaderGraphNode_Constant { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Constant, ShaderGraphNode_Constant); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Constant); public: ShaderGraphNode_Float3Constant(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); const float3 &GetValue() const { return m_Value; } void SetValue(const float3 &v) { m_Value = v; } virtual void GetValueString(String &Destination) const override final { StringConverter::Float3ToString(Destination, m_Value); } virtual bool SetValueString(const char *NewValue) override final { m_Value = StringConverter::StringToFloat3(NewValue); return true; } virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; protected: float3 m_Value; }; class ShaderGraphNode_Float4Constant : public ShaderGraphNode_Constant { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Constant, ShaderGraphNode_Constant); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Constant); public: ShaderGraphNode_Float4Constant(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo); const float4 &GetValue() const { return m_Value; } void SetValue(const float4 &v) { m_Value = v; } virtual void GetValueString(String &Destination) const override final { StringConverter::Float4ToString(Destination, m_Value); } virtual bool SetValueString(const char *NewValue) override final { m_Value = StringConverter::StringToFloat4(NewValue); return true; } virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; protected: float4 m_Value; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Variable : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Variable, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_Variable); public: ShaderGraphNode_Variable(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; class ShaderGraphNode_Float2Variable : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float2Variable, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float2Variable); public: ShaderGraphNode_Float2Variable(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Float3Variable : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float3Variable, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float3Variable); public: ShaderGraphNode_Float3Variable(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Float4Variable : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Float4Variable, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Float4Variable); public: ShaderGraphNode_Float4Variable(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Operator : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Operator, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(ShaderGraphNode_Operator); public: ShaderGraphNode_Operator(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} }; class ShaderGraphNode_Add : public ShaderGraphNode_Operator { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Add, ShaderGraphNode_Operator); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Add); public: ShaderGraphNode_Add(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Subtract : public ShaderGraphNode_Operator { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Subtract, ShaderGraphNode_Operator); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Subtract); public: ShaderGraphNode_Subtract(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Multiply : public ShaderGraphNode_Operator { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Multiply, ShaderGraphNode_Operator); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Multiply); public: ShaderGraphNode_Multiply(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Divide : public ShaderGraphNode_Operator { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Divide, ShaderGraphNode_Operator); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Divide); public: ShaderGraphNode_Divide(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Dot : public ShaderGraphNode_Operator { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Dot, ShaderGraphNode_Operator); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Dot); public: ShaderGraphNode_Dot(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_Normalize : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Normalize, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Normalize); public: ShaderGraphNode_Normalize(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_Negate : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_Negate, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_Negate); public: ShaderGraphNode_Negate(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; class ShaderGraphNode_FractionalPart : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_FractionalPart, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_FractionalPart); public: ShaderGraphNode_FractionalPart(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo) {} virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ShaderGraphNode_TextureSample : public ShaderGraphNode { DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(ShaderGraphNode_TextureSample, ShaderGraphNode); DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(ShaderGraphNode_TextureSample); public: ShaderGraphNode_TextureSample(const ShaderGraphNodeTypeInfo *pTypeInfo = &s_typeInfo) : BaseClass(pTypeInfo), m_eUnpackOperation(SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NONE) {} const SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION GetUnpackOperation() const { return (SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION)m_eUnpackOperation; } virtual bool OnInputConnectionChange(uint32 InputIndex) override final; virtual bool EmitOutput(ShaderGraphCompiler *pCompiler, uint32 OutputIndex) const override final; virtual bool LoadFromXML(const ShaderGraph *pShaderGraph, XMLReader &xmlReader) override final; virtual void SaveToXML(XMLWriter &xmlWriter) const override final; private: uint32 m_eUnpackOperation; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Editor/Source/Editor/EditorProgressCallbacks.h #pragma once #include "Editor/Common.h" class EditorProgressCallbacks : public BaseProgressCallbacks { public: EditorProgressCallbacks(QWidget *parentWidgetForPopups); virtual ~EditorProgressCallbacks(); virtual void ModalError(const char *message) override; virtual bool ModalConfirmation(const char *message) override; virtual uint32 ModalPrompt(const char *message, uint32 nOptions, ...) override; private: QWidget *m_pParentWidgetForPopups; }; <file_sep>/Engine/Source/Engine/Component.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Component.h" #include "Engine/Entity.h" #include "Core/PropertyTable.h" Log_SetChannel(Component); DEFINE_COMPONENT_TYPEINFO(Component); BEGIN_COMPONENT_PROPERTIES(Component) PROPERTY_TABLE_MEMBER_FLOAT3("LocalPosition", 0, offsetof(Component, m_localPosition), ProperyCallbackOnLocalTransformChange, nullptr) PROPERTY_TABLE_MEMBER_QUATERNION("LocalRotation", 0, offsetof(Component, m_localRotation), ProperyCallbackOnLocalTransformChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT3("LocalScale", 0, offsetof(Component, m_localScale), ProperyCallbackOnLocalTransformChange, nullptr) END_COMPONENT_PROPERTIES() Component::Component(const ComponentTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pEntity(nullptr), m_localPosition(float3::Zero), m_localRotation(Quaternion::Identity), m_localScale(float3::Zero), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero) { } Component::~Component() { DebugAssert(m_pEntity == NULL); } bool Component::Initialize() { return true; } void Component::OnLocalTransformChange() { } void Component::OnAddToEntity(Entity *pEntity) { m_pEntity = pEntity; } void Component::OnRemoveFromEntity(Entity *pEntity) { m_pEntity = nullptr; } void Component::OnEntityTransformChange() { } void Component::OnAddToWorld(World *pWorld) { } void Component::OnRemoveFromWorld(World *pWorld) { } void Component::Update(float timeSinceLastUpdate) { } void Component::UpdateAsync(float timeSinceLastUpdate) { } void Component::SetLocalPosition(const float3 &localPosition) { m_localPosition = localPosition; OnLocalTransformChange(); } void Component::SetLocalRotation(const Quaternion &localRotation) { m_localRotation = localRotation; OnLocalTransformChange(); } void Component::SetLocalScale(const float3 &localScale) { m_localScale = localScale; OnLocalTransformChange(); } Transform Component::CalculateWorldTransform() const { if (m_pEntity != nullptr) { // transform local space first, then into world space return Transform::ConcatenateTransforms(Transform(m_localPosition, m_localRotation, m_localScale), Transform(m_pEntity->GetPosition(), Quaternion::Identity, m_pEntity->GetScale())); } else { // just use local return Transform(m_localPosition, m_localRotation, m_localScale); } } void Component::SetBounds(const AABox &boundingBox, const Sphere &boundingSphere, bool notifyEntity /* = true */) { if (boundingBox != m_boundingBox || boundingSphere != m_boundingSphere) { m_boundingBox = boundingBox; m_boundingSphere = boundingSphere; if (notifyEntity && m_pEntity != nullptr) m_pEntity->OnComponentBoundsChange(); } } bool Component::InitializePropertiesFromTable(Component *pComponent, const PropertyTable *pPropertyTable) { // for each property in our type const ComponentTypeInfo *pComponentTypeInfo = pComponent->GetComponentTypeInfo(); for (uint32 propertyIndex = 0; propertyIndex < pComponentTypeInfo->GetPropertyCount(); propertyIndex++) { const PROPERTY_DECLARATION *pPropertyDeclaration = pComponentTypeInfo->GetPropertyDeclarationByIndex(propertyIndex); // attempt to find a value in the property table const String *propertyValue = pPropertyTable->GetPropertyValuePointer(pPropertyDeclaration->Name); if (propertyValue == nullptr) continue; // set the value if (!SetPropertyValueFromString(pComponent, pPropertyDeclaration, *propertyValue)) { Log_WarningPrintf("Failed to initialize component '%s' property '%s' to value '%s'", pComponentTypeInfo->GetTypeName(), pPropertyDeclaration->Name, propertyValue); continue; } } return true; } void Component::ProperyCallbackOnLocalTransformChange(Component *pComponent, void *pUserData /*= nullptr*/) { pComponent->OnLocalTransformChange(); } <file_sep>/Engine/Source/D3D12Renderer/D3D12Common.h #pragma once #include "Renderer/Common.h" #include "Renderer/Renderer.h" #define INITGUID 1 #include <d3d12.h> #include <dxgi1_4.h> #include <D3Dcompiler.h> #include <dxgidebug.h> #include <Uxtheme.h> #include <VersionHelpers.h> // Forward declare all our types class D3D12GPUBuffer; class D3D12GPUDevice; class D3D12GPUContext; class D3D12GPUCommandList; class D3D12GPUQuery; class D3D12GPUShaderProgram; class D3D12GPUOutputBuffer; class D3D12GPUTexture1D; class D3D12GPUTexture1DArray; class D3D12GPUTexture2D; class D3D12GPUTexture2DArray; class D3D12GPUTexture3D; class D3D12GPUTextureCube; class D3D12GPUTextureCubeArray; class D3D12GPUDepthTexture; class D3D12GPUDepthTextureArray; class D3D12GPURasterizerState; class D3D12GPUDepthStencilState; class D3D12GPUBlendState; class D3D12GPUSamplerState; class D3D12GPURenderTargetView; class D3D12GPUDepthStencilBufferView; class D3D12GPUComputeView; class D3D12DescriptorHeap; struct D3D12DescriptorHandle; // Defines #include "D3D12Renderer/D3D12Defines.h" <file_sep>/Engine/Source/Engine/ParticleSystemBuiltinModules.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemBuiltinModules.h" #include "Core/RandomNumberGenerator.h" Log_SetChannel(ParticleSystemBuiltinModules); DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_TimeBased); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_TimeBased) PROPERTY_TABLE_MEMBER_FLOAT("TimeFraction", 0, offsetof(ParticleSystemModule_TimeBased, m_timeFraction), nullptr, nullptr) PROPERTY_TABLE_MEMBER_UINT("EasingFunction", 0, offsetof(ParticleSystemModule_TimeBased, m_easingFunction), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_TimeBased::ParticleSystemModule_TimeBased() : m_timeFraction(1.0f), m_easingFunction(EasingFunction::Linear) { } ParticleSystemModule_TimeBased::~ParticleSystemModule_TimeBased() { } float ParticleSystemModule_TimeBased::GetCoefficient(const ParticleData *pParticle) const { float coefficient = Min(pParticle->LifeRemaining / (pParticle->LifeSpan * m_timeFraction), 1.0f); return EasingFunction::GetCoefficient((EasingFunction::Type)m_easingFunction, coefficient); } float ParticleSystemModule_TimeBased::GetInverseCoefficient(const ParticleData *pParticle) const { float coefficient = Min(pParticle->LifeRemaining / (pParticle->LifeSpan * m_timeFraction), 1.0f); return 1.0f - EasingFunction::GetCoefficient((EasingFunction::Type)m_easingFunction, coefficient); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnLifetime); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnLifetime); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnLifetime) PROPERTY_TABLE_MEMBER_FLOAT("MinTime", 0, offsetof(ParticleSystemModule_SpawnLifetime, m_minTime), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("MaxTime", 0, offsetof(ParticleSystemModule_SpawnLifetime, m_maxTime), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SpawnLifetime::ParticleSystemModule_SpawnLifetime() : ParticleSystemModule(), m_minTime(1.0f), m_maxTime(1.0f) { } ParticleSystemModule_SpawnLifetime::~ParticleSystemModule_SpawnLifetime() { } bool ParticleSystemModule_SpawnLifetime::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { // update the time to live of the particle float timeToLive = (m_minTime == m_maxTime) ? m_minTime : pRNG->NextRangeFloat(m_minTime, m_maxTime); pParticle->LifeSpan = timeToLive; pParticle->LifeRemaining = timeToLive; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnLocation); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnLocation); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnLocation) PROPERTY_TABLE_MEMBER_UINT("LocationType", 0, offsetof(ParticleSystemModule_SpawnLocation, m_spawnLocationType), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT3("PointPosition", 0, offsetof(ParticleSystemModule_SpawnLocation, m_spawnLocationProperties.Fixed.Position), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SpawnLocation::ParticleSystemModule_SpawnLocation() : ParticleSystemModule(), m_spawnLocationType(LocationType_Point) { Y_memzero(&m_spawnLocationProperties, sizeof(m_spawnLocationProperties)); } ParticleSystemModule_SpawnLocation::~ParticleSystemModule_SpawnLocation() { } void ParticleSystemModule_SpawnLocation::SetSpawnLocationPoint(const float3 &point) { m_spawnLocationType = LocationType_Point; point.Store(m_spawnLocationProperties.Fixed.Position); } void ParticleSystemModule_SpawnLocation::SetSpawnLocationBox(const float3 &boxMinBounds, const float3 &boxMaxBounds) { m_spawnLocationType = LocationType_Box; boxMinBounds.Store(m_spawnLocationProperties.Box.MinBounds); boxMaxBounds.Store(m_spawnLocationProperties.Box.MaxBounds); } void ParticleSystemModule_SpawnLocation::SetSpawnLocationSphere(const float3 &sphereCenter, float sphereRadius) { m_spawnLocationType = LocationType_Sphere; sphereCenter.Store(m_spawnLocationProperties.Sphere.Center); m_spawnLocationProperties.Sphere.Radius = sphereRadius; } void ParticleSystemModule_SpawnLocation::SetSpawnLocationCylinder(const float3 &cylinderBase, float width, float height, uint32 heightAxis) { m_spawnLocationType = LocationType_Cylinder; cylinderBase.Store(m_spawnLocationProperties.Cylinder.Center); m_spawnLocationProperties.Cylinder.Width = width; m_spawnLocationProperties.Cylinder.Height = height; m_spawnLocationProperties.Cylinder.HeightAxis = heightAxis; } void ParticleSystemModule_SpawnLocation::SetSpawnLocationTriangle(const float3 &triangleBaseCenter, float height, float depth) { m_spawnLocationType = LocationType_Triangle; triangleBaseCenter.Store(m_spawnLocationProperties.Triangle.BaseCenter); m_spawnLocationProperties.Triangle.Height = height; m_spawnLocationProperties.Triangle.Depth = depth; } bool ParticleSystemModule_SpawnLocation::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { switch (m_spawnLocationType) { case LocationType_Point: pParticle->Position = pBaseTransform->TransformPoint(float3(m_spawnLocationProperties.Fixed.Position)); break; case LocationType_Box: { SIMDVector3f minBounds(m_spawnLocationProperties.Box.MinBounds); SIMDVector3f maxBounds(m_spawnLocationProperties.Box.MaxBounds); SIMDVector3f rng(pRNG->NextUniformFloat(), pRNG->NextUniformFloat(), pRNG->NextUniformFloat()); pParticle->Position = pBaseTransform->TransformPoint(minBounds + ((maxBounds - minBounds) * rng)); } break; case LocationType_Sphere: { float radius = m_spawnLocationProperties.Sphere.Radius; float radiusSq = radius * radius; float3 location; do { location.Set(pRNG->NextRangeFloat(-radius, radius), pRNG->NextRangeFloat(-radius, radius), pRNG->NextRangeFloat(-radius, radius)); } while (location.SquaredLength() > radiusSq); pParticle->Position = location; } break; case LocationType_Cylinder: break; case LocationType_Triangle: break; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnSize); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnSize); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnSize) PROPERTY_TABLE_MEMBER_FLOAT("MinWidth", 0, offsetof(ParticleSystemModule_SpawnSize, m_minWidth), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("MaxWidth", 0, offsetof(ParticleSystemModule_SpawnSize, m_maxWidth), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("MinHeight", 0, offsetof(ParticleSystemModule_SpawnSize, m_minHeight), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("MaxHeight", 0, offsetof(ParticleSystemModule_SpawnSize, m_maxHeight), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SpawnSize::ParticleSystemModule_SpawnSize() : m_minWidth(1.0f), m_maxWidth(1.0f), m_minHeight(1.0f), m_maxHeight(1.0f) { } ParticleSystemModule_SpawnSize::~ParticleSystemModule_SpawnSize() { } bool ParticleSystemModule_SpawnSize::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { pParticle->Width = (m_minWidth == m_maxWidth) ? m_minWidth : pRNG->NextRangeFloat(m_minWidth, m_maxWidth); pParticle->Height = (m_minHeight == m_maxHeight) ? m_minHeight : pRNG->NextRangeFloat(m_minHeight, m_maxHeight); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnVelocity); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnVelocity); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnVelocity) PROPERTY_TABLE_MEMBER_UINT("Type", 0, offsetof(ParticleSystemModule_SpawnVelocity, m_spawnVelocityType), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT3("FixedVelocity", 0, offsetof(ParticleSystemModule_SpawnVelocity, m_spawnVelocityProperties.Fixed.Velocity), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SpawnVelocity::ParticleSystemModule_SpawnVelocity() : ParticleSystemModule(), m_spawnVelocityType(SpawnVelocityType_Fixed) { Y_memzero(&m_spawnVelocityProperties, sizeof(m_spawnVelocityProperties)); } ParticleSystemModule_SpawnVelocity::~ParticleSystemModule_SpawnVelocity() { } void ParticleSystemModule_SpawnVelocity::SetSpawnVelocityFixed(const float3 &fixedVelocity) { m_spawnVelocityType = SpawnVelocityType_Fixed; fixedVelocity.Store(m_spawnVelocityProperties.Fixed.Velocity); } void ParticleSystemModule_SpawnVelocity::SetSpawnVelocityArc(float minAngle, float maxAngle, float distance, uint32 axis) { } void ParticleSystemModule_SpawnVelocity::SetSpawnVelocityRandom(float minSpeed, float maxSpeed) { m_spawnVelocityType = SpawnVelocityType_Random; m_spawnVelocityProperties.Random.MinSpeed = minSpeed; m_spawnVelocityProperties.Random.MaxSpeed = maxSpeed; } void ParticleSystemModule_SpawnVelocity::SetSpawnVelocityRandomFixedAxis(float minSpeed, float maxSpeed, uint32 axis) { m_spawnVelocityType = SpawnVelocityType_RandomFixedAxis; m_spawnVelocityProperties.RandomFixedAxis.MinSpeed = minSpeed; m_spawnVelocityProperties.RandomFixedAxis.MaxSpeed = maxSpeed; m_spawnVelocityProperties.RandomFixedAxis.Axis = axis; } bool ParticleSystemModule_SpawnVelocity::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { switch (m_spawnVelocityType) { case SpawnVelocityType_Fixed: pParticle->Velocity = float3(m_spawnVelocityProperties.Fixed.Velocity); break; case SpawnVelocityType_Arc: break; case SpawnVelocityType_Random: { // get the vector first SIMDVector3f spawnVector(pRNG->NextGaussianFloat(), pRNG->NextGaussianFloat(), pRNG->NextGaussianFloat()); // normalize it, and set result pParticle->Velocity = spawnVector.Normalize() * pRNG->NextRangeFloat(m_spawnVelocityProperties.Random.MinSpeed, m_spawnVelocityProperties.Random.MaxSpeed); } break; case SpawnVelocityType_RandomFixedAxis: { // get the vector first, set the axis static const float3 *lookupVectors[3] = { &float3::UnitX, &float3::UnitX, &float3::UnitZ }; DebugAssert(m_spawnVelocityProperties.RandomFixedAxis.Axis < 3); pParticle->Velocity = *lookupVectors[m_spawnVelocityProperties.RandomFixedAxis.Axis] * pRNG->NextRangeFloat(m_spawnVelocityProperties.RandomFixedAxis.MinSpeed, m_spawnVelocityProperties.RandomFixedAxis.MaxSpeed); } break; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SpawnRotation); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SpawnRotation); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SpawnRotation) PROPERTY_TABLE_MEMBER_FLOAT("MinRotation", 0, offsetof(ParticleSystemModule_SpawnRotation, m_minRotation), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("MaxRotation", 0, offsetof(ParticleSystemModule_SpawnRotation, m_maxRotation), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SpawnRotation::ParticleSystemModule_SpawnRotation() : m_minRotation(0.0f), m_maxRotation(0.0f) { } ParticleSystemModule_SpawnRotation::~ParticleSystemModule_SpawnRotation() { } bool ParticleSystemModule_SpawnRotation::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { pParticle->Rotation = (m_minRotation == m_maxRotation) ? m_minRotation : pRNG->NextRangeFloat(m_minRotation, m_maxRotation); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_LockToEmitter); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_LockToEmitter); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_LockToEmitter) PROPERTY_TABLE_MEMBER_FLOAT3("OffsetPosition", 0, offsetof(ParticleSystemModule_LockToEmitter, m_offsetPosition), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_LockToEmitter::ParticleSystemModule_LockToEmitter() : m_offsetPosition(float3::Zero) { } ParticleSystemModule_LockToEmitter::~ParticleSystemModule_LockToEmitter() { } bool ParticleSystemModule_LockToEmitter::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { // initialize position pParticle->Position = pBaseTransform->TransformPoint(m_offsetPosition); return true; } void ParticleSystemModule_LockToEmitter::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; pParticle->Position = pBaseTransform->TransformPoint(m_offsetPosition); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_FadeOut); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_FadeOut); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_FadeOut) PROPERTY_TABLE_MEMBER_FLOAT("StartFadeTime", 0, offsetof(ParticleSystemModule_FadeOut, m_startFadeTime), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_FadeOut::ParticleSystemModule_FadeOut() : m_startFadeTime(0.0f) { } ParticleSystemModule_FadeOut::~ParticleSystemModule_FadeOut() { } bool ParticleSystemModule_FadeOut::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { // set alpha field to full pParticle->Color |= MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 255); return true; } void ParticleSystemModule_FadeOut::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; // handle start fade-out time float elapsed = pParticle->LifeSpan - pParticle->LifeRemaining; if (elapsed < m_startFadeTime) { pParticle->Color |= 0xFF000000; continue; } float fraction = 1.0f - (pParticle->LifeRemaining / (pParticle->LifeSpan - m_startFadeTime)); pParticle->Color = (pParticle->Color & 0x00FFFFFF) | ((uint32)Math::Truncate(fraction * 255.0f) << 24); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_Flipbook); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_Flipbook); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_Flipbook) PROPERTY_TABLE_MEMBER_UINT("Columns", 0, offsetof(ParticleSystemModule_Flipbook, m_columns), nullptr, nullptr) PROPERTY_TABLE_MEMBER_UINT("Rows", 0, offsetof(ParticleSystemModule_Flipbook, m_rows), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("FlipInterval", 0, offsetof(ParticleSystemModule_Flipbook, m_flipInterval), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_Flipbook::ParticleSystemModule_Flipbook() : m_columns(1), m_rows(1), m_flipInterval(1.0f) { } ParticleSystemModule_Flipbook::~ParticleSystemModule_Flipbook() { } float2 ParticleSystemModule_Flipbook::GetTextureCoordinateRange() const { DebugAssert(m_columns > 0 && m_rows > 0); return float2(1.0f / (float)m_columns, 1.0f / (float)m_rows); } float2 ParticleSystemModule_Flipbook::GetMinTextureCoordinates(uint32 frameNumber) const { DebugAssert(m_columns > 0); uint32 imageX = frameNumber % m_columns; uint32 imageY = frameNumber / m_columns; float2 textureCoordinateRange(GetTextureCoordinateRange()); return float2(textureCoordinateRange.x * (float)imageX, textureCoordinateRange.y * (float)imageY); } float2 ParticleSystemModule_Flipbook::GetMaxTextureCoordinates(uint32 frameNumber) const { DebugAssert(m_columns > 0); uint32 imageX = frameNumber % m_columns; uint32 imageY = frameNumber / m_columns; float2 textureCoordinateRange(GetTextureCoordinateRange()); return float2(textureCoordinateRange.x * (float)imageX + textureCoordinateRange.x, textureCoordinateRange.y * (float)imageY + textureCoordinateRange.y); } bool ParticleSystemModule_Flipbook::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { // Start at the first frame pParticle->MinTextureCoordinates = GetMinTextureCoordinates(0); pParticle->MaxTextureCoordinates = GetMaxTextureCoordinates(0); return true; } void ParticleSystemModule_Flipbook::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { // Precalculate texture coord range, and the number of frames float2 textureCoordinateRange(GetTextureCoordinateRange()); uint32 frameCount = m_columns * m_rows; float inverseFlipInterval = 1.0f / m_flipInterval; // For each particle, calculate the frame number for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; // calculate fraction of time complete float timeElapsed = pParticle->LifeSpan - pParticle->LifeRemaining; float frameNumberF = timeElapsed * inverseFlipInterval; uint32 frameNumber = Math::Truncate(Math::Floor(frameNumberF)) % frameCount; DebugAssert(frameNumber < frameCount); // update the uv range for the particle uint32 imageX = frameNumber % m_columns; uint32 imageY = frameNumber / m_columns; pParticle->MinTextureCoordinates.Set(textureCoordinateRange.x * (float)imageX, textureCoordinateRange.y * (float)imageY); pParticle->MaxTextureCoordinates.Set(pParticle->MinTextureCoordinates + textureCoordinateRange); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_ColorOverTime); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_ColorOverTime); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_ColorOverTime) PROPERTY_TABLE_MEMBER_COLOR("StartColor", 0, offsetof(ParticleSystemModule_ColorOverTime, m_startColor), nullptr, nullptr) PROPERTY_TABLE_MEMBER_COLOR("EndColor", 0, offsetof(ParticleSystemModule_ColorOverTime, m_endColor), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_ColorOverTime::ParticleSystemModule_ColorOverTime() : m_startColor(MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)), m_endColor(MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)) { } ParticleSystemModule_ColorOverTime::~ParticleSystemModule_ColorOverTime() { } bool ParticleSystemModule_ColorOverTime::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { pParticle->Color = m_startColor; return true; } void ParticleSystemModule_ColorOverTime::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { // fixme: lerp on int float3 startColorFloat(PixelFormatHelpers::ConvertRGBAToFloat4(m_startColor).xyz()); float3 endColorFloat(PixelFormatHelpers::ConvertRGBAToFloat4(m_endColor).xyz()); float3 colorRange(endColorFloat - startColorFloat); for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; float timeFraction = GetInverseCoefficient(pParticle); pParticle->Color = (pParticle->Color & 0xFF000000) | PixelFormatHelpers::ConvertFloat4ToRGBA(float4(startColorFloat + colorRange * timeFraction, 0.0f)); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_OpacityOverTime); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_OpacityOverTime); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_OpacityOverTime) PROPERTY_TABLE_MEMBER_FLOAT("StartOpacity", 0, offsetof(ParticleSystemModule_OpacityOverTime, m_startOpacity), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("EndOpacity", 0, offsetof(ParticleSystemModule_OpacityOverTime, m_endOpacity), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_OpacityOverTime::ParticleSystemModule_OpacityOverTime() : m_startOpacity(1.0f), m_endOpacity(1.0f) { } ParticleSystemModule_OpacityOverTime::~ParticleSystemModule_OpacityOverTime() { } bool ParticleSystemModule_OpacityOverTime::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { pParticle->Color = (pParticle->Color & 0x00FFFFFF) | ((uint32)Math::Clamp(Math::Truncate(m_startOpacity * 255.0f), 0, 255) << 24); return true; } void ParticleSystemModule_OpacityOverTime::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { float opacityRange = m_endOpacity - m_startOpacity; for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; float particleOpacity = GetInverseCoefficient(pParticle) * opacityRange + m_startOpacity; pParticle->Color = (pParticle->Color & 0x00FFFFFF) | ((uint32)Math::Clamp(Math::Truncate(particleOpacity * 255.0f), 0, 255) << 24); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_SizeOverTime); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_SizeOverTime); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_SizeOverTime) PROPERTY_TABLE_MEMBER_FLOAT("StartWidth", 0, offsetof(ParticleSystemModule_SizeOverTime, m_startWidth), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("EndWidth", 0, offsetof(ParticleSystemModule_SizeOverTime, m_endWidth), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("StartHeight", 0, offsetof(ParticleSystemModule_SizeOverTime, m_startHeight), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("EndHeight", 0, offsetof(ParticleSystemModule_SizeOverTime, m_endHeight), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_SizeOverTime::ParticleSystemModule_SizeOverTime() : m_startWidth(1.0f), m_endWidth(1.0f), m_startHeight(1.0f), m_endHeight(1.0f) { } ParticleSystemModule_SizeOverTime::~ParticleSystemModule_SizeOverTime() { } void ParticleSystemModule_SizeOverTime::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { float widthRange = m_endWidth - m_startWidth; float heightRange = m_endHeight - m_startHeight; for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; float fraction = GetInverseCoefficient(pParticle); pParticle->Width = m_startWidth + widthRange * fraction; pParticle->Height = m_startHeight + heightRange * fraction; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_RotationSpeed); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_RotationSpeed); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_RotationSpeed) PROPERTY_TABLE_MEMBER_FLOAT("RotationSpeed", 0, offsetof(ParticleSystemModule_RotationSpeed, m_rotationSpeed), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_RotationSpeed::ParticleSystemModule_RotationSpeed() : m_rotationSpeed(0.0f) { } ParticleSystemModule_RotationSpeed::~ParticleSystemModule_RotationSpeed() { } void ParticleSystemModule_RotationSpeed::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { float rotationDelta = m_rotationSpeed * deltaTime; for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; pParticle->Rotation += rotationDelta; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule_RotationOverTime); DEFINE_OBJECT_GENERIC_FACTORY(ParticleSystemModule_RotationOverTime); BEGIN_OBJECT_PROPERTY_MAP(ParticleSystemModule_RotationOverTime) PROPERTY_TABLE_MEMBER_FLOAT("StartRotation", 0, offsetof(ParticleSystemModule_RotationOverTime, m_startRotation), nullptr, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("EndRotation", 0, offsetof(ParticleSystemModule_RotationOverTime, m_endRotation), nullptr, nullptr) END_OBJECT_PROPERTY_MAP() ParticleSystemModule_RotationOverTime::ParticleSystemModule_RotationOverTime() : ParticleSystemModule_TimeBased(), m_startRotation(0.0f), m_endRotation(0.0f) { } ParticleSystemModule_RotationOverTime::~ParticleSystemModule_RotationOverTime() { } bool ParticleSystemModule_RotationOverTime::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { pParticle->Rotation = m_startRotation; return true; } void ParticleSystemModule_RotationOverTime::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { float rotationRange = m_endRotation - m_startRotation; for (uint32 particleIndex = 0; particleIndex < nParticles; particleIndex++) { ParticleData *pParticle = &pParticles[particleIndex]; float particleRotation = GetInverseCoefficient(pParticle) * rotationRange + m_startRotation; pParticle->Rotation = particleRotation; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ParticleSystemModule::RegisterBuiltinModules() { static bool called = false; DebugAssert(!called); called = true; #define REGISTER_TYPE(Type) Type::StaticMutableTypeInfo()->RegisterType() REGISTER_TYPE(ParticleSystemModule_TimeBased); REGISTER_TYPE(ParticleSystemModule_SpawnLifetime); REGISTER_TYPE(ParticleSystemModule_SpawnLocation); REGISTER_TYPE(ParticleSystemModule_SpawnSize); REGISTER_TYPE(ParticleSystemModule_SpawnVelocity); REGISTER_TYPE(ParticleSystemModule_SpawnRotation); REGISTER_TYPE(ParticleSystemModule_LockToEmitter); REGISTER_TYPE(ParticleSystemModule_FadeOut); REGISTER_TYPE(ParticleSystemModule_Flipbook); REGISTER_TYPE(ParticleSystemModule_ColorOverTime); REGISTER_TYPE(ParticleSystemModule_OpacityOverTime); REGISTER_TYPE(ParticleSystemModule_SizeOverTime); REGISTER_TYPE(ParticleSystemModule_RotationSpeed); REGISTER_TYPE(ParticleSystemModule_RotationOverTime); #undef REGISTER_TYPE } <file_sep>/Editor/Source/Editor/MapEditor/EditorEntityEditMode.h #include "Editor/MapEditor/EditorEditMode.h" class Texture2D; class EditorMapViewport; class EditorMapEntity; struct ui_EditorEntityEditMode; class EditorEntityEditMode : public EditorEditMode { Q_OBJECT public: EditorEntityEditMode(EditorMap *pMap); ~EditorEntityEditMode(); // widget const EDITOR_ENTITY_EDIT_MODE_WIDGET GetActiveWidget() const { return m_activeWidget; } void SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET widget); // selection reading const AABox &GetSelectionBounds() const { return m_selectionBounds; } const uint32 GetSelectionCount() const { return m_selectedEntities.GetSize(); } const EditorMapEntity *GetSelection(uint32 i) const { DebugAssert(i < m_selectedEntities.GetSize()); return m_selectedEntities[i]; } EditorMapEntity *GetSelection(uint32 i) { DebugAssert(i < m_selectedEntities.GetSize()); return m_selectedEntities[i]; } // selection enumeration template<typename T> void EnumerateSelection(T callback) const { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) callback(m_selectedEntities[i]); } // any modifications should be done through here to preserve the UI void OnEntityPropertyChanged(const EditorMapEntity *pEntity, const char *propertyName, const char *propertyValue); // set property on selection void SetPropertyOnSelection(const char *propertyName, const char *propertyValue); // add/remove selection void AddSelection(EditorMapEntity *pEntity); void RemoveSelection(EditorMapEntity *pEntity); void ClearSelection(); // select a component void SetSelectedComponentIndex(int32 componentIndex); // selection queries bool IsSelected(const EditorMapEntity *pEntity) const; // selection operations void MoveSelection(const float3 &moveDelta); void RotateSelection(const float3 &rotateDelta); void ScaleSelection(const float3 &scaleDelta); void PushSelection(const float3 &pushDirection, float maxDistance = 100.0f); void SnapSelectionToGrid(); void DeleteSelection(); // create a copy of the selection, and optionally change the active selection, and deselect the old selection void CloneSelection(bool addToSelection, bool clearOldSelection); // helper method for creating a entity in a viewport EditorMapEntity *CreateEntityUsingViewport(EditorMapViewport *pViewport, const char *typeName); // helper method to move a viewport camera in range of an entity void MoveViewportCameraToEntity(EditorMapViewport *pViewport, const EditorMapEntity *pEntity, const Quaternion cameraRotation = Quaternion::FromEulerAngles(-45.0f, 0.0f, 0.0f)); // update selection axis position/rotation void UpdateSelectionAxis(); // implemented base methods virtual bool Initialize(ProgressCallbacks *pProgressCallbacks) override; virtual QWidget *CreateUI(QWidget *pParentWidget) override; virtual void Activate() override; virtual void Deactivate() override; virtual void Update(const float timeSinceLastUpdate) override; virtual void OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) override; virtual void OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) override; virtual void OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterWorld(EditorMapViewport *pViewport) override; virtual void OnViewportDrawAfterPost(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) override; virtual void OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) override; virtual bool HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) override; virtual bool HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) override; virtual bool HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) override; virtual bool HandleResourceViewResourceActivatedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName) override; virtual bool HandleResourceViewResourceDroppedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName, const EditorMapViewport *pViewport, int32 x, int32 y) override; private: enum STATE { STATE_NONE, STATE_CAMERA_ROTATION, STATE_SELECTION_RECT, STATE_WIDGET, }; // draw move gismo void DrawMoveGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, const uint32 anyAxisColor, const uint32 XPlaneFillColor, const uint32 YPlaneFillColor, const uint32 ZPlaneFillColor, int32 onlyAxis = -1); // draw rotate gismo void DrawRotationGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, bool transparent = true, int32 onlyAxis = -1); // draw scale gismo void DrawScaleGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, const uint32 anyAxisColor, int32 onlyAxis = -1); // update the selections void UpdateSelection(EditorMapViewport *pViewport); // update the axis position void UpdateSelectionBounds(); // update the property editor for the current selection void UpdatePropertyEditor(); void UpdatePropertyEditorForComponent(); // ui ui_EditorEntityEditMode *m_ui; // resources const Texture2D *m_pRotationGismoTexture; const Texture2D *m_pRotationGismoTransparentTexture; // widget EDITOR_ENTITY_EDIT_MODE_WIDGET m_activeWidget; // state uint32 m_lastMousePositionEntityId; int2 m_mouseSelectionRegion[2]; STATE m_currentState; uint32 m_currentStateData[2]; float3 m_currentStateDataVector; // selection AABox m_selectionBounds; PODArray<EditorMapEntity *> m_selectedEntities; int32 m_selectedComponentIndex; float3 m_selectionAxisPosition; Quaternion m_selectionAxisRotation; private Q_SLOTS: // ui events void OnUIOptionsFilterSelectionClicked(); void OnUIWidgetSelectClicked(bool checked); void OnUIWidgetMoveClicked(bool checked); void OnUIWidgetRotateClicked(bool checked); void OnUIWidgetScaleClicked(bool checked); void OnUIPushLeftClicked(); void OnUIPushRightClicked(); void OnUIPushForwardClicked(); void OnUIPushBackClicked(); void OnUIPushUpClicked(); void OnUIPushDownClicked(); void OnUIActionCreateEntityTriggered(); void OnUIActionDeleteEntityTriggered(); void OnUIActionEntityLayersTriggered(); void OnUIActionSnapSelectionToGridTriggered(); void OnUIActionCreateComponentTriggered(); void OnUIActionRemoveComponentTriggered(); void OnUIActionSelectionLayersTriggered(); void OnUISelectionComponentListCurrentRowChanged(int currentRow); }; <file_sep>/Tests/CMakeLists.txt set(HEADER_FILES ) set(SOURCE_FILES Source/TestMath.cpp Source/TestRenderer.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/Tests ${SDL2_INCLUDE_DIR}) if(ANDROID) add_library(EngineTestRunner SHARED ${HEADER_FILES} ${SOURCE_FILES}) else() add_executable(EngineTestRunner ${HEADER_FILES} ${SOURCE_FILES}) endif() target_link_libraries(EngineTestRunner ${SDL2MAIN_LIBRARY} EngineMain EngineCore) <file_sep>/Engine/Source/MathLib/Transform.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/SIMDVectorf.h" #include "MathLib/Quaternion.h" #include "MathLib/AABox.h" #include "MathLib/Sphere.h" #include "MathLib/Ray.h" class Transform { public: Transform() {} Transform(const Transform &transform); Transform(const Vector3f &translation, const Quaternion &rotation, const Vector3f &scale); Transform(const Matrix4x4f &transformMatrix); const Vector3f &GetPosition() const { return m_position; } const Quaternion &GetRotation() const { return m_rotation; } const Vector3f &GetScale() const { return m_scale; } void Set(const Vector3f &position, const Quaternion &rotation, const Vector3f &scale) { m_position = position; m_rotation = rotation; m_scale = scale; } void SetPosition(const Vector3f &position) { m_position = position; } void SetRotation(const Quaternion &rotation) { m_rotation = rotation; } void SetScale(const Vector3f &scale) { m_scale = scale; } void SetIdentity(); Vector3f TransformPoint(const Vector3f &v) const; SIMDVector3f TransformPoint(const SIMDVector3f &v) const; Vector3f TransformNormal(const Vector3f &v) const; SIMDVector3f TransformNormal(const SIMDVector3f &v) const; Ray TransformRay(const Ray &v) const; Vector3f UntransformPoint(const Vector3f &v) const; SIMDVector3f UntransformPoint(const SIMDVector3f &v) const; Vector3f UntransformNormal(const Vector3f &v) const; SIMDVector3f UntransformNormal(const SIMDVector3f &v) const; Ray UntransformRay(const Ray &v) const; AABox TransformBoundingBox(const AABox &boundingBox) const; Sphere TransformBoundingSphere(const Sphere &boundingSphere) const; // inverse transform Transform Inverse() const; void InvertInPlace(); Matrix3x4f GetTransformMatrix3x4() const; Matrix4x4f GetTransformMatrix4x4() const; Matrix3x4f GetInverseTransformMatrix3x4() const; Matrix4x4f GetInverseTransformMatrix4x4() const; bool operator==(const Transform &transform) const; bool operator!=(const Transform &transform) const; Transform operator*(const Transform &rightSide) const; Transform &operator=(const Transform &transform); Transform &operator*=(const Transform &rightSide); // transform * vector Vector3f operator*(const Vector3f &rhs) const; SIMDVector3f operator*(const SIMDVector3f &rhs) const; Transform LinearInterpolate(const Transform &end, const float factor); // linear interpolation of transforms static Transform LinearInterpolate(const Transform &start, const Transform &end, const float factor); // transform concatenation. left side will happen before the right side. (reverse of matrix multiplication) static Transform ConcatenateTransforms(const Transform &leftSide, const Transform &rightSide); static const Transform &Identity; private: Vector3f m_position; Quaternion m_rotation; Vector3f m_scale; }; <file_sep>/Editor/Source/Editor/EditorPropertyEditorDialog.h #pragma once #include "Editor/Common.h" #include "Editor/EditorPropertyEditorWidget.h" class EditorMap; class EditorMapEntity; class PropertyTemplate; class EditorPropertyEditorDialog : public QDialog { Q_OBJECT public: EditorPropertyEditorDialog(QWidget *pParent); virtual ~EditorPropertyEditorDialog(); const EditorPropertyEditorWidget *GetPropertyEditor() const { return m_pPropertyEditor; } EditorPropertyEditorWidget *GetPropertyEditor() { return m_pPropertyEditor; } const EditorMap *GetAttachedMap() const { return m_pAttachedMap; } const EditorMapEntity *GetAttachedEntity() const { return m_pAttachedEntity; } void PopulateForEntity(EditorMap *pMap, EditorMapEntity *pEntity); void PopulateForTemplate(const PropertyTemplate *pTemplate); void PopulateForTable(const PropertyTemplate *pTemplate, PropertyTable *pTable); Q_SIGNALS: void OnPropertyChanged(const char *propertyName, const char *propertyValue); private: EditorPropertyEditorWidget *m_pPropertyEditor; EditorMap *m_pAttachedMap; EditorMapEntity *m_pAttachedEntity; const PropertyTemplate *m_pAttachedTemplate; PropertyTable *m_pAttachedTable; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUShaderProgram.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUShaderProgram.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(OpenGLRenderBackend); #define LAZY_RESOURCE_CLEANUP_AFTER_SWITCH OpenGLGPUShaderProgram::OpenGLGPUShaderProgram() : m_pBoundContext(nullptr) { Y_memzero(m_iGLShaderId, sizeof(m_iGLShaderId)); m_iGLProgramId = 0; } OpenGLGPUShaderProgram::~OpenGLGPUShaderProgram() { DebugAssert(m_pBoundContext == NULL); if (m_iGLProgramId > 0) glDeleteProgram(m_iGLProgramId); for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] > 0) glDeleteShader(m_iGLShaderId[i]); } for (uint32 i = 0; i < m_uniformBuffers.GetSize(); i++) { ShaderUniformBuffer &constantBuffer = m_uniformBuffers[i]; if (constantBuffer.pLocalGPUBuffer != nullptr) constantBuffer.pLocalGPUBuffer->Release(); } } void OpenGLGPUShaderProgram::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { // fixme if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void OpenGLGPUShaderProgram::SetDebugName(const char *name) { // set shaders for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] != 0) OpenGLHelpers::SetObjectDebugName(GL_SHADER, m_iGLShaderId[i], name); } // set program OpenGLHelpers::SetObjectDebugName(GL_PROGRAM, m_iGLProgramId, name); } bool OpenGLGPUShaderProgram::LoadBlob(OpenGLGPUDevice *pRenderer, const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { // binary reader BinaryReader binaryReader(pByteCodeStream); // read/validate header OpenGLShaderCacheEntryHeader header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Signature != OPENGL_SHADER_CACHE_ENTRY_HEADER || header.Platform != RENDERER_PLATFORM_OPENGL) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: Shader cache entry header corrupted."); return false; } // begin checked section GL_CHECKED_SECTION_BEGIN(); // time stuff Timer operationTimer; // generate shader ids for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (header.StageSize[i] == 0) continue; // read into memory GLint stageSourceLength = (GLint)header.StageSize[i]; GLchar *pStageSource = new GLchar[stageSourceLength]; if (!binaryReader.SafeReadBytes(pStageSource, stageSourceLength)) { delete[] pStageSource; return false; } // lookup table of i -> GL shader stage static const GLenum glShaderStageMapping[SHADER_PROGRAM_STAGE_COUNT] = { GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER }; // create the shader object if ((m_iGLShaderId[i] = glCreateShader(glShaderStageMapping[i])) == 0) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: glCreateShader failed: "); return false; } // pass it the shader source, and compile it glShaderSource(m_iGLShaderId[i], 1, (const GLchar **)&pStageSource, &stageSourceLength); glCompileShader(m_iGLShaderId[i]); delete[] pStageSource; GLint shaderStatus = GL_FALSE; GLint shaderInfoLogLength = 0; glGetShaderiv(m_iGLShaderId[i], GL_COMPILE_STATUS, &shaderStatus); glGetShaderiv(m_iGLShaderId[i], GL_INFO_LOG_LENGTH, &shaderInfoLogLength); if (shaderStatus == GL_FALSE) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: %s failed compilation:\n", NameTable_GetNameString(NameTables::ShaderProgramStage, i)); if (shaderInfoLogLength > 1) { GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetShaderInfoLog(m_iGLShaderId[i], shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_ErrorPrint(shaderInfoLog); delete[] shaderInfoLog; } return false; } if (shaderInfoLogLength > 1) { Log_WarningPrintf("OpenGLGPUShaderProgram::Create: %s compiled, with warnings:\n", NameTable_GetNameString(NameTables::ShaderProgramStage, i)); GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetShaderInfoLog(m_iGLShaderId[i], shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_WarningPrint(shaderInfoLog); delete[] shaderInfoLog; } Log_PerfPrintf("OpenGLGPUShaderProgram::Create: %s took %.4f msec to compile.", NameTable_GetNameString(NameTables::ShaderProgramStage, i), operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); } // generate program id if ((m_iGLProgramId = glCreateProgram()) == 0) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: glCreateProgram failed: "); return false; } // attach shaders to program for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_iGLShaderId[i] != 0) glAttachShader(m_iGLProgramId, m_iGLShaderId[i]); } // check for any errors if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: One or more glAttachShader calls failed: "); return false; } // log Log_PerfPrintf("OpenGLGPUShaderProgram::Create: Took %.4f msec to attach.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); // bind attributes if (header.VertexAttributeCount > 0) { for (uint32 attributeIndex = 0; attributeIndex < header.VertexAttributeCount; attributeIndex++) { OpenGLShaderCacheEntryVertexAttribute attribute; SmallString attributeVariableName; if (!binaryReader.SafeReadBytes(&attribute, sizeof(attribute)) || !binaryReader.SafeReadFixedString(attribute.NameLength, &attributeVariableName)) return false; // find the corresponding vertex element in spec uint32 ilIndex; for (ilIndex = 0; ilIndex < nVertexElements; ilIndex++) { if (pVertexElements[ilIndex].Semantic == (GPU_VERTEX_ELEMENT_SEMANTIC)attribute.SemanticName && pVertexElements[ilIndex].SemanticIndex == attribute.SemanticIndex) { // bind to the corresponding attribute location glBindAttribLocation(m_iGLProgramId, ilIndex, attributeVariableName); break; } } // found? if (ilIndex == nVertexElements) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: Failed to find binding for required shader input attribute '%s'", attributeVariableName.GetCharArray()); return false; } } // check for errors if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: One or more glBindAttribLocation calls failed: "); return false; } // to avoid bouncing around vertex formats too often we're going to just store the whole thing, this could be moved to a cache m_vertexAttributes.AddRange(pVertexElements, nVertexElements); } // pull in constant buffers if (header.UniformBlockCount > 0) { m_uniformBuffers.Resize(header.UniformBlockCount); for (uint32 uniformBlockIndex = 0; uniformBlockIndex < m_uniformBuffers.GetSize(); uniformBlockIndex++) { OpenGLShaderCacheEntryUniformBlock inUniformBlock; SmallString uniformBlockName; if (!binaryReader.SafeReadBytes(&inUniformBlock, sizeof(inUniformBlock)) || !binaryReader.SafeReadFixedString(inUniformBlock.NameLength, &uniformBlockName)) return false; ShaderUniformBuffer *uniformBuffer = &m_uniformBuffers[uniformBlockIndex]; uniformBuffer->Name = uniformBlockName; uniformBuffer->ParameterIndex = inUniformBlock.ParameterIndex; uniformBuffer->Size = inUniformBlock.Size; uniformBuffer->EngineConstantBufferIndex = 0; uniformBuffer->BlockIndex = -1; uniformBuffer->BindSlot = -1; uniformBuffer->pLocalGPUBuffer = nullptr; uniformBuffer->pLocalBuffer = nullptr; uniformBuffer->LocalBufferDirtyLowerBounds = uniformBuffer->LocalBufferDirtyUpperBounds = -1; if (inUniformBlock.IsLocal) { // create local buffer uniformBuffer->pLocalBuffer = new byte[uniformBuffer->Size]; Y_memzero(uniformBuffer->pLocalBuffer, uniformBuffer->Size); // create gpu buffer GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_WRITABLE | GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER, uniformBuffer->Size); uniformBuffer->pLocalGPUBuffer = static_cast<OpenGLGPUBuffer *>(pRenderer->CreateBuffer(&bufferDesc, uniformBuffer->pLocalBuffer)); if (uniformBuffer->pLocalGPUBuffer == nullptr) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: Failed to create local uniform buffer in GPU memory: %s (size: %u)", uniformBuffer->Name.GetCharArray(), uniformBuffer->Size); return false; } } else { // lookup in engine constant buffer list const ShaderConstantBuffer *pEngineConstantBuffer = ShaderConstantBuffer::GetShaderConstantBufferByName(uniformBuffer->Name, RENDERER_PLATFORM_OPENGL, pRenderer->GetFeatureLevel()); if (pEngineConstantBuffer == nullptr) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: Shader is requesting unknown non-local constant buffer named '%s'.", uniformBuffer->Name.GetCharArray()); return false; } // store index uniformBuffer->EngineConstantBufferIndex = pEngineConstantBuffer->GetIndex(); } } } // pull in parameters if (header.ParameterCount > 0) { m_parameters.Resize(header.ParameterCount); for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { OpenGLShaderCacheEntryParameter inParameter; SmallString parameterName; if (!binaryReader.SafeReadBytes(&inParameter, sizeof(inParameter)) || !binaryReader.SafeReadFixedString(inParameter.NameLength, &parameterName)) return false; // create parameter information ShaderParameter *outParameter = &m_parameters[parameterIndex]; outParameter->Name = parameterName; outParameter->Type = (SHADER_PARAMETER_TYPE)inParameter.Type; outParameter->UniformBlockIndex = inParameter.UniformBlockIndex; outParameter->UniformBlockOffset = inParameter.UniformBlockOffset; outParameter->ArraySize = inParameter.ArraySize; outParameter->ArrayStride = inParameter.ArrayStride; outParameter->BindTarget = (OPENGL_SHADER_BIND_TARGET)inParameter.BindTarget; outParameter->BindLocation = -1; outParameter->BindSlot = -1; } } // bind outputs if (header.FragmentDataCount > 0) { for (uint32 fragDataIndex = 0; fragDataIndex < header.FragmentDataCount; fragDataIndex++) { OpenGLShaderCacheEntryFragmentData fragData; SmallString variableName; if (!binaryReader.SafeReadBytes(&fragData, sizeof(fragData)) || !binaryReader.SafeReadFixedString(fragData.NameLength, &variableName)) return false; // bind to the corresponding attribute location glBindFragDataLocation(m_iGLProgramId, fragData.RenderTargetIndex, variableName); } // check for errors if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: One or more glBindAttribLocation calls failed: "); return false; } } // log Log_PerfPrintf("OpenGLGPUShaderProgram::Create: Took %.4f msec to bind.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); // link program { glLinkProgram(m_iGLProgramId); if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUShaderProgram::Create: glLinkProgram failed: "); return false; } // check link status GLint shaderStatus = GL_FALSE; GLint shaderInfoLogLength = 0; glGetProgramiv(m_iGLProgramId, GL_LINK_STATUS, &shaderStatus); glGetProgramiv(m_iGLProgramId, GL_INFO_LOG_LENGTH, &shaderInfoLogLength); if (shaderStatus == GL_FALSE) { Log_ErrorPrintf("OpenGLGPUShaderProgram::Create: Program failed to link:\n"); if (shaderInfoLogLength > 1) { GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetProgramInfoLog(m_iGLProgramId, shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_ErrorPrint(shaderInfoLog); delete[] shaderInfoLog; } return false; } if (shaderInfoLogLength > 1) { Log_WarningPrintf("OpenGLGPUShaderProgram::Create: Program linked, with warnings:\n"); GLchar *shaderInfoLog = new GLchar[shaderInfoLogLength]; GLint shaderInfoLogLengthWritten; glGetProgramInfoLog(m_iGLProgramId, shaderInfoLogLength, &shaderInfoLogLengthWritten, shaderInfoLog); shaderInfoLog[shaderInfoLogLength - 1] = 0; Log_WarningPrint(shaderInfoLog); delete[] shaderInfoLog; } // logging Log_PerfPrintf("OpenGLGPUShaderProgram::Create: Took %.4f msec to link.", operationTimer.GetTimeMilliseconds()); operationTimer.Reset(); } #ifdef Y_BUILD_CONFIG_DEBUG if (header.DebugNameLength > 0) { SmallString debugName; if (binaryReader.SafeReadFixedString(header.DebugNameLength, &debugName)) SetDebugName(debugName); } #endif #if 1 // todo: lazy bind // store the current program for this thread's context GLint currentProgramId = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &currentProgramId); // bind this program glUseProgram(m_iGLProgramId); // slot allocators uint32 textureSlotAllocator = 0; uint32 uniformBufferSlotAllocator = 0; uint32 imageSlotAllocator = 0; // get uniform block locations for (uint32 i = 0; i < m_uniformBuffers.GetSize(); i++) { ShaderUniformBuffer *uniformBuffer = &m_uniformBuffers[i]; // find in the linked program GLuint blockIndex = glGetUniformBlockIndex(m_iGLProgramId, uniformBuffer->Name); if (blockIndex == GL_INVALID_INDEX) { // optimized out continue; } // store the location, and allocate a slot uniformBuffer->BlockIndex = blockIndex; uniformBuffer->BindSlot = uniformBufferSlotAllocator++; // and update the linked parameter ShaderParameter *parameter = &m_parameters[uniformBuffer->ParameterIndex]; DebugAssert(parameter->BindTarget == OPENGL_SHADER_BIND_TARGET_UNIFORM_BUFFER); parameter->BindLocation = uniformBuffer->BlockIndex; parameter->BindSlot = uniformBuffer->BlockIndex; // bind the actual parameter glUniformBlockBinding(m_iGLProgramId, uniformBuffer->BlockIndex, uniformBuffer->BindSlot); } // get parameter locations for (uint32 i = 0; i < m_parameters.GetSize(); i++) { ShaderParameter *parameter = &m_parameters[i]; switch (parameter->BindTarget) { case OPENGL_SHADER_BIND_TARGET_UNIFORM: { // Find the uniform location for this parameter GLint uniformLocation = glGetUniformLocation(m_iGLProgramId, parameter->Name); if (uniformLocation < 0) { // optimized out continue; } // Store the location parameter->BindLocation = uniformLocation; } break; case OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT: { // Find the uniform location for this parameter GLint uniformLocation = glGetUniformLocation(m_iGLProgramId, parameter->Name); if (uniformLocation < 0) { // optimized out continue; } // Store the location, and allocate a slot parameter->BindLocation = uniformLocation; parameter->BindSlot = textureSlotAllocator++; // and pass this to the shader glUniform1i(parameter->BindLocation, parameter->BindSlot); } break; case OPENGL_SHADER_BIND_TARGET_IMAGE_UNIT: { // Find the uniform location for this parameter GLint uniformLocation = glGetUniformLocation(m_iGLProgramId, parameter->Name); if (uniformLocation < 0) { // optimized out continue; } // Store the location, and allocate a slot parameter->BindLocation = uniformLocation; parameter->BindSlot = imageSlotAllocator++; // and pass this to the shader glUniform1i(parameter->BindLocation, parameter->BindSlot); } break; } } // rebind old program glUseProgram(currentProgramId); Log_PerfPrintf("OpenGLGPUShaderProgram::Create: Took %.4f msec to do parameter linking.", operationTimer.GetTimeMilliseconds()); #endif // all ok return true; } void OpenGLGPUShaderProgram::Bind(OpenGLGPUContext *pContext) { DebugAssert(m_pBoundContext == NULL); // bind program glUseProgram(m_iGLProgramId); m_pBoundContext = pContext; // bind attributes pContext->SetShaderVertexAttributes(m_vertexAttributes.GetBasePointer(), m_vertexAttributes.GetSize()); // bind params InternalBindAutomaticParameters(pContext); } void OpenGLGPUShaderProgram::InternalBindAutomaticParameters(OpenGLGPUContext *pContext) { // bind local and global constant buffers for (uint32 constantBufferIndex = 0; constantBufferIndex < m_uniformBuffers.GetSize(); constantBufferIndex++) { const ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[constantBufferIndex]; if (constantBuffer->BlockIndex < 0) continue; // local? OpenGLGPUBuffer *pUniformBuffer = (constantBuffer->pLocalGPUBuffer != nullptr) ? constantBuffer->pLocalGPUBuffer : m_pBoundContext->GetConstantBuffer(constantBuffer->EngineConstantBufferIndex); pContext->SetShaderUniformBlock(constantBuffer->BindSlot, pUniformBuffer); } } void OpenGLGPUShaderProgram::Switch(OpenGLGPUContext *pContext, OpenGLGPUShaderProgram *pCurrentProgram) { #ifdef LAZY_RESOURCE_CLEANUP_AFTER_SWITCH // bind program glUseProgram(m_iGLProgramId); // swap pointers pCurrentProgram->m_pBoundContext = nullptr; m_pBoundContext = pContext; // bind attributes pContext->SetShaderVertexAttributes(m_vertexAttributes.GetBasePointer(), m_vertexAttributes.GetSize()); // bind params InternalBindAutomaticParameters(pContext); #else pCurrentProgram->Unbind(pContext); Bind(pContext); #endif } void OpenGLGPUShaderProgram::CommitLocalConstantBuffers(OpenGLGPUContext *pContext) { // commit constant buffers for (uint32 i = 0; i < m_uniformBuffers.GetSize(); i++) { ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[i]; if (constantBuffer->LocalBufferDirtyLowerBounds >= 0) { pContext->WriteBuffer(constantBuffer->pLocalGPUBuffer, reinterpret_cast<const byte *>(constantBuffer->pLocalBuffer) + constantBuffer->LocalBufferDirtyLowerBounds, constantBuffer->LocalBufferDirtyLowerBounds, constantBuffer->LocalBufferDirtyUpperBounds - constantBuffer->LocalBufferDirtyLowerBounds); constantBuffer->LocalBufferDirtyLowerBounds = constantBuffer->LocalBufferDirtyUpperBounds = -1; } } } void OpenGLGPUShaderProgram::Unbind(OpenGLGPUContext *pContext) { DebugAssert(m_pBoundContext == pContext); #ifndef LAZY_RESOURCE_CLEANUP_AFTER_SWITCH // unset parameters that we match against for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { const ShaderParameter *parameter = &m_parameters[parameterIndex]; if (parameter->BindSlot < 0) continue; switch (parameter->BindTarget) { case OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT: pContext->SetShaderTextureUnit(parameter->BindSlot, nullptr, nullptr); break; case OPENGL_SHADER_BIND_TARGET_UNIFORM_BUFFER: pContext->SetShaderUniformBlock(parameter->BindSlot, nullptr); break; case OPENGL_SHADER_BIND_TARGET_IMAGE_UNIT: pContext->SetShaderImageUnit(parameter->BindSlot, nullptr); break; case OPENGL_SHADER_BIND_TARGET_SHADER_STORAGE_BUFFER: pContext->SetShaderStorageBuffer(parameter->BindSlot, nullptr); break; } } #endif // unbind program glUseProgram(0); m_pBoundContext = nullptr; } static void GLUniformWrapper(SHADER_PARAMETER_TYPE type, GLuint location, GLuint arraySize, const void *pValue) { // Invoke the appropriate glUniform() command switch (type) { case SHADER_PARAMETER_TYPE_BOOL: glUniform1iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL2: glUniform2iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL3: glUniform3iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL4: glUniform4iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT: glUniform1iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT2: glUniform2iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT3: glUniform3iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT4: glUniform4iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_UINT: glUniform1uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); break; case SHADER_PARAMETER_TYPE_UINT2: glUniform2uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); break; case SHADER_PARAMETER_TYPE_UINT3: glUniform3uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); break; case SHADER_PARAMETER_TYPE_UINT4: glUniform4uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT: glUniform1fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT2: glUniform2fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3: glUniform3fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT4: glUniform4fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT2X2: glUniformMatrix2fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3X3: glUniformMatrix3fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3X4: glUniformMatrix4x3fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT4X4: glUniformMatrix4fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; } } void OpenGLGPUShaderProgram::InternalSetParameterValue(OpenGLGPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == valueType); DebugAssert(pContext == m_pBoundContext); // Local constant buffer? if (parameterInfo->UniformBlockIndex >= 0) { // get the constant buffer ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[parameterInfo->UniformBlockIndex]; DebugAssert(constantBuffer->pLocalBuffer != nullptr); // get size to copy uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(valueSize > 0); // compare memory first byte *pBufferPtr = constantBuffer->pLocalBuffer + parameterInfo->UniformBlockOffset; if (Y_memcmp(pBufferPtr, pValue, valueSize) != 0) { // write to the local constant buffer Y_memcpy(pBufferPtr, pValue, valueSize); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)parameterInfo->UniformBlockOffset; constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)valueSize; } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)parameterInfo->UniformBlockOffset); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)valueSize); } } } // GL uniform? else if (parameterInfo->BindLocation >= 0) { // Send to GL GLUniformWrapper(parameterInfo->Type, parameterInfo->BindLocation, 1, pValue); } } void OpenGLGPUShaderProgram::InternalSetParameterValueArray(OpenGLGPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == valueType); DebugAssert(pContext == m_pBoundContext); // Local constant buffer? if (parameterInfo->UniformBlockIndex >= 0) { // get the constant buffer ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[parameterInfo->UniformBlockIndex]; DebugAssert(constantBuffer->pLocalBuffer != nullptr); // get size to copy uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(valueSize > 0); // if there is no padding, this can be done in a single operation byte *pBufferPtr = constantBuffer->pLocalBuffer + parameterInfo->UniformBlockOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) { uint32 copySize = valueSize * numElements; if (Y_memcmp(pBufferPtr, pValue, copySize) != 0) { // write to the local constant buffer Y_memcpy(pBufferPtr, pValue, copySize); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride); constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride); } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride)); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride)); } } } else { if (Y_memcmp_stride(pBufferPtr, parameterInfo->ArrayStride, pValue, valueSize, valueSize, numElements) != 0) { // write to the local constant buffer Y_memcpy_stride(pBufferPtr, parameterInfo->ArrayStride, pValue, valueSize, valueSize, numElements); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride); constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride); } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride)); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride)); } } } } // GL uniform? else if (parameterInfo->BindLocation >= 0) { // Send to GL GLUniformWrapper(parameterInfo->Type, parameterInfo->BindLocation + firstElement, numElements, pValue); } } void OpenGLGPUShaderProgram::InternalSetParameterStruct(OpenGLGPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT); DebugAssert(pContext == m_pBoundContext && valueSize < parameterInfo->ArrayStride); // Local constant buffer? if (parameterInfo->UniformBlockIndex >= 0) { // get the constant buffer ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[parameterInfo->UniformBlockIndex]; DebugAssert(constantBuffer->pLocalBuffer != nullptr); // compare memory first byte *pBufferPtr = constantBuffer->pLocalBuffer + parameterInfo->UniformBlockOffset; if (Y_memcmp(pBufferPtr, pValue, valueSize) != 0) { // write to the local constant buffer Y_memcpy(pBufferPtr, pValue, valueSize); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)parameterInfo->UniformBlockOffset; constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)valueSize; } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)parameterInfo->UniformBlockOffset); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)valueSize); } } } } void OpenGLGPUShaderProgram::InternalSetParameterStructArray(OpenGLGPUContext *pContext, uint32 parameterIndex, const void *pValues, uint32 valueSize, uint32 firstElement, uint32 numElements) { const ShaderParameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); DebugAssert(pContext == m_pBoundContext); // Local constant buffer? if (parameterInfo->UniformBlockIndex >= 0) { // get the constant buffer ShaderUniformBuffer *constantBuffer = &m_uniformBuffers[parameterInfo->UniformBlockIndex]; DebugAssert(constantBuffer->pLocalBuffer != nullptr); // if there is no padding, this can be done in a single operation byte *pBufferPtr = constantBuffer->pLocalBuffer + parameterInfo->UniformBlockOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) { uint32 copySize = valueSize * numElements; if (Y_memcmp(pBufferPtr, pValues, copySize) != 0) { // write to the local constant buffer Y_memcpy(pBufferPtr, pValues, copySize); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride); constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride); } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride)); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride)); } } } else { if (Y_memcmp_stride(pBufferPtr, parameterInfo->ArrayStride, pValues, valueSize, valueSize, numElements) != 0) { // write to the local constant buffer Y_memcpy_stride(pBufferPtr, parameterInfo->ArrayStride, pValues, valueSize, valueSize, numElements); if (constantBuffer->LocalBufferDirtyLowerBounds < 0) { constantBuffer->LocalBufferDirtyLowerBounds = (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride); constantBuffer->LocalBufferDirtyUpperBounds = constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride); } else { constantBuffer->LocalBufferDirtyLowerBounds = Min(constantBuffer->LocalBufferDirtyLowerBounds, (int32)(parameterInfo->UniformBlockOffset + firstElement * parameterInfo->ArrayStride)); constantBuffer->LocalBufferDirtyUpperBounds = Max(constantBuffer->LocalBufferDirtyUpperBounds, constantBuffer->LocalBufferDirtyLowerBounds + (int32)(valueSize * parameterInfo->ArrayStride)); } } } } } void OpenGLGPUShaderProgram::InternalSetParameterResource(OpenGLGPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, OpenGLGPUSamplerState *pLinkedSamplerState) { const ShaderParameter *parameter = &m_parameters[parameterIndex]; if (parameter->BindSlot < 0) return; switch (parameter->BindTarget) { case OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT: pContext->SetShaderTextureUnit(parameter->BindSlot, static_cast<GPUTexture *>(pResource), pLinkedSamplerState); break; case OPENGL_SHADER_BIND_TARGET_UNIFORM_BUFFER: DebugAssert(pResource->GetResourceType() == GPU_RESOURCE_TYPE_BUFFER); pContext->SetShaderUniformBlock(parameter->BindSlot, static_cast<OpenGLGPUBuffer *>(pResource)); break; case OPENGL_SHADER_BIND_TARGET_IMAGE_UNIT: pContext->SetShaderImageUnit(parameter->BindSlot, static_cast<GPUTexture *>(pResource)); break; case OPENGL_SHADER_BIND_TARGET_SHADER_STORAGE_BUFFER: pContext->SetShaderStorageBuffer(parameter->BindSlot, pResource); break; } } uint32 OpenGLGPUShaderProgram::GetParameterCount() const { return m_parameters.GetSize(); } void OpenGLGPUShaderProgram::GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) { const ShaderParameter *parameter = &m_parameters[index]; *name = parameter->Name; *type = parameter->Type; *arraySize = parameter->ArraySize; } GPUShaderProgram *OpenGLGPUDevice::CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; OpenGLGPUShaderProgram *pProgram = new OpenGLGPUShaderProgram(); if (!pProgram->LoadBlob(this, pVertexElements, nVertexElements, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } GPUShaderProgram *OpenGLGPUDevice::CreateComputeProgram(ByteStream *pByteCodeStream) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; OpenGLGPUShaderProgram *pProgram = new OpenGLGPUShaderProgram(); if (!pProgram->LoadBlob(this, nullptr, 0, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } <file_sep>/Engine/Source/Core/PropertyTable.h #pragma once #include "Core/Common.h" #include "YBaseLib/String.h" #include "YBaseLib/CIStringHashTable.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #include "MathLib/Quaternion.h" class PropertyTemplate; class XMLReader; class XMLWriter; class PropertyTable { public: typedef CIStringHashTable<String> PropertyHashTable; public: PropertyTable(); PropertyTable(const PropertyTable &copy); ~PropertyTable(); const PropertyHashTable &GetPropertyHashTable() const { return m_properties; } bool GetPropertyValue(const char *propertyName, String *pValue) const; const String *GetPropertyValuePointer(const char *propertyName) const; const char *GetPropertyValueDefault(const char *propertyName, const char *defaultValue = "") const; const String &GetPropertyValueDefaultString(const char *propertyName, const String &defaultValue = EmptyString) const; void SetPropertyValue(const char *PropertyName, const char *Value); void SetPropertyValueString(const char *PropertyName, const String &Value); void Create(); void CreateFromTemplate(const PropertyTemplate *pTemplate); void CopyProperties(const PropertyTable *pTable); void Clear(); #ifdef HAVE_LIBXML2 bool LoadFromXML(XMLReader &xmlReader); void SaveToXML(XMLWriter &xmlWriter) const; #endif // typed property readers bool GetPropertyValueBool(const char *propertyName, bool *pValue) const; bool GetPropertyValueInt8(const char *propertyName, int8 *pValue) const; bool GetPropertyValueInt16(const char *propertyName, int16 *pValue) const; bool GetPropertyValueInt32(const char *propertyName, int32 *pValue) const; bool GetPropertyValueInt64(const char *propertyName, int64 *pValue) const; bool GetPropertyValueUInt8(const char *propertyName, uint8 *pValue) const; bool GetPropertyValueUInt16(const char *propertyName, uint16 *pValue) const; bool GetPropertyValueUInt32(const char *propertyName, uint32 *pValue) const; bool GetPropertyValueUInt64(const char *propertyName, uint64 *pValue) const; bool GetPropertyValueFloat(const char *propertyName, float *pValue) const; bool GetPropertyValueDouble(const char *propertyName, double *pValue) const; bool GetPropertyValueColor(const char *propertyName, uint32 *pValue) const; bool GetPropertyValueInt2(const char *propertyName, Vector2i *pValue) const; bool GetPropertyValueInt3(const char *propertyName, Vector3i *pValue) const; bool GetPropertyValueInt4(const char *propertyName, Vector4i *pValue) const; bool GetPropertyValueUInt2(const char *propertyName, Vector2u *pValue) const; bool GetPropertyValueUInt3(const char *propertyName, Vector3u *pValue) const; bool GetPropertyValueUInt4(const char *propertyName, Vector4u *pValue) const; bool GetPropertyValueFloat2(const char *propertyName, Vector2f *pValue) const; bool GetPropertyValueFloat3(const char *propertyName, Vector3f *pValue) const; bool GetPropertyValueFloat4(const char *propertyName, Vector4f *pValue) const; bool GetPropertyValueQuaternion(const char *propertyName, Quaternion *pValue) const; // typed property readers with fallback values bool GetPropertyValueDefaultBool(const char *propertyName, bool defaultValue = false) const; int8 GetPropertyValueDefaultInt8(const char *propertyName, int8 defaultValue = 0) const; int16 GetPropertyValueDefaultInt16(const char *propertyName, int16 defaultValue = 0) const; int32 GetPropertyValueDefaultInt32(const char *propertyName, int32 defaultValue = 0) const; int64 GetPropertyValueDefaultInt64(const char *propertyName, int64 defaultValue = 0) const; uint8 GetPropertyValueDefaultUInt8(const char *propertyName, uint8 defaultValue = 0) const; uint16 GetPropertyValueDefaultUInt16(const char *propertyName, uint16 defaultValue = 0) const; uint32 GetPropertyValueDefaultUInt32(const char *propertyName, uint32 defaultValue = 0) const; uint64 GetPropertyValueDefaultUInt64(const char *propertyName, uint64 defaultValue = 0) const; float GetPropertyValueDefaultFloat(const char *propertyName, float defaultValue = 0) const; double GetPropertyValueDefaultDouble(const char *propertyName, double defaultValue = 0) const; uint32 GetPropertyValueDefaultColor(const char *propertyName, uint32 defaultValue = 0) const; Vector2i GetPropertyValueDefaultInt2(const char *propertyName, const Vector2i &defaultValue = Vector2i::Zero) const; Vector3i GetPropertyValueDefaultInt3(const char *propertyName, const Vector3i &defaultValue = Vector3i::Zero) const; Vector4i GetPropertyValueDefaultInt4(const char *propertyName, const Vector4i &defaultValue = Vector4i::Zero) const; Vector2u GetPropertyValueDefaultUInt2(const char *propertyName, const Vector2u &defaultValue = Vector2u::Zero) const; Vector3u GetPropertyValueDefaultUInt3(const char *propertyName, const Vector3u &defaultValue = Vector3u::Zero) const; Vector4u GetPropertyValueDefaultUInt4(const char *propertyName, const Vector4u &defaultValue = Vector4u::Zero) const; Vector2f GetPropertyValueDefaultFloat2(const char *propertyName, const Vector2f &defaultValue = Vector2f::Zero) const; Vector3f GetPropertyValueDefaultFloat3(const char *propertyName, const Vector3f &defaultValue = Vector3f::Zero) const; Vector4f GetPropertyValueDefaultFloat4(const char *propertyName, const Vector4f &defaultValue = Vector4f::Zero) const; Quaternion GetPropertyValueDefaultQuaternion(const char *propertyName, const Quaternion &defaultValue = Quaternion::Identity) const; // typed property writers void SetPropertyValueBool(const char *propertyName, bool propertyValue); void SetPropertyValueInt8(const char *propertyName, int8 propertyValue); void SetPropertyValueInt16(const char *propertyName, int16 propertyValue); void SetPropertyValueInt32(const char *propertyName, int32 propertyValue); void SetPropertyValueInt64(const char *propertyName, int64 propertyValue); void SetPropertyValueUInt8(const char *propertyName, uint8 propertyValue); void SetPropertyValueUInt16(const char *propertyName, uint16 propertyValue); void SetPropertyValueUInt32(const char *propertyName, uint32 propertyValue); void SetPropertyValueUInt64(const char *propertyName, uint64 propertyValue); void SetPropertyValueFloat(const char *propertyName, float propertyValue); void SetPropertyValueDouble(const char *propertyName, double propertyValue); void SetPropertyValueColor(const char *propertyName, uint32 propertyValue); void SetPropertyValueInt2(const char *propertyName, const Vector2i &propertyValue); void SetPropertyValueInt3(const char *propertyName, const Vector3i &propertyValue); void SetPropertyValueInt4(const char *propertyName, const Vector4i &propertyValue); void SetPropertyValueUInt2(const char *propertyName, const Vector2u &propertyValue); void SetPropertyValueUInt3(const char *propertyName, const Vector3u &propertyValue); void SetPropertyValueUInt4(const char *propertyName, const Vector4u &propertyValue); void SetPropertyValueFloat2(const char *propertyName, const Vector2f &propertyValue); void SetPropertyValueFloat3(const char *propertyName, const Vector3f &propertyValue); void SetPropertyValueFloat4(const char *propertyName, const Vector4f &propertyValue); void SetPropertyValueQuaternion(const char *propertyName, const Quaternion &propertyValue); // property enumerator, callback in form of func(const String &, const String &), or func(const char *, const char *) template<class T> void EnumerateProperties(T callback) const { for (PropertyHashTable::ConstIterator itr = m_properties.Begin(); !itr.AtEnd(); itr.Forward()) callback(itr->Key, itr->Value); } // assignment operator PropertyTable &operator=(const PropertyTable &copy); public: static const PropertyTable &EmptyPropertyList; private: const char *InternalGetPropertyValue(const char *PropertyName) const; String InternalGetPropertyValueString(const char *PropertyName) const; PropertyHashTable m_properties; }; <file_sep>/Engine/Source/GameFramework/StaticMeshEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/StaticMeshEntity.h" #include "Engine/StaticMesh.h" #include "Engine/World.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/KinematicObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/ResourceManager.h" #include "Engine/Physics/BulletHeaders.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderWorld.h" Log_SetChannel(StaticMeshEntity); DEFINE_ENTITY_TYPEINFO(StaticMeshEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(StaticMeshEntity); BEGIN_ENTITY_PROPERTIES(StaticMeshEntity) PROPERTY_TABLE_MEMBER("StaticMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetStaticMeshName, NULL, PropertyCallbackSetStaticMeshName, NULL, PropertyCallbackStaticMeshChanged, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(StaticMeshEntity, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(StaticMeshEntity, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(StaticMeshEntity, m_shadowFlags), NULL, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(StaticMeshEntity) END_ENTITY_SCRIPT_FUNCTIONS() StaticMeshEntity::StaticMeshEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pStaticMesh(nullptr), m_visible(true), m_collidable(false), m_shadowFlags(0), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } StaticMeshEntity::~StaticMeshEntity() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pCollisionObject != nullptr) m_pCollisionObject->Release(); if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); } void StaticMeshEntity::SetStaticMesh(const StaticMesh *pStaticMesh) { DebugAssert(pStaticMesh != nullptr); if (m_pStaticMesh == pStaticMesh) return; if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); PropertyCallbackStaticMeshChanged(this); } void StaticMeshEntity::SetVisible(bool visible) { if (m_visible == visible) return; m_visible = visible; PropertyCallbackVisibleChanged(this); } void StaticMeshEntity::SetShadowFlags(uint32 shadowFlags) { if (m_shadowFlags == shadowFlags) return; m_shadowFlags = shadowFlags; if (m_pRenderProxy != nullptr) m_pRenderProxy->SetShadowFlags(shadowFlags); } void StaticMeshEntity::SetCollidable(bool collidable) { if (m_collidable == collidable) return; m_collidable = collidable; PropertyCallbackCollidableChanged(this); } void StaticMeshEntity::Create(uint32 entityID, ENTITY_MOBILITY mobility /* = ENTITY_MOBILITY_MOVABLE */, const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const StaticMesh *pStaticMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_mobility = mobility; m_transform.Set(position, rotation, scale); if (pStaticMesh != nullptr) { m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); } else { m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; Initialize(entityID, EmptyString); } bool StaticMeshEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; //DebugAssert(m_pStaticMesh != nullptr); if (m_pStaticMesh == nullptr) { Log_ErrorPrintf("StaticMeshEntity::OnCreate: Entity %u missing static mesh", m_entityID); return false; } UpdateRenderProxy(); UpdateCollisionObject(); // determine bounds m_boundingBox = m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()); m_boundingSphere = m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()); return true; } void StaticMeshEntity::UpdateRenderProxy() { if (m_visible) { if (m_pRenderProxy == nullptr) { m_pRenderProxy = new StaticMeshRenderProxy(m_entityID, m_pStaticMesh, m_transform, m_shadowFlags); if (IsInWorld()) m_pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } else { m_pRenderProxy->SetStaticMesh(m_pStaticMesh); } } else { if (m_pRenderProxy != nullptr) { if (IsInWorld()) m_pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); m_pRenderProxy->Release(); m_pRenderProxy = nullptr; } } } void StaticMeshEntity::UpdateCollisionObject() { if (m_collidable && m_pStaticMesh->GetCollisionShape() != nullptr) { if (m_pCollisionObject == nullptr) { // create collision object based on mobility if (m_mobility == ENTITY_MOBILITY_STATIC) m_pCollisionObject = new Physics::StaticObject(m_entityID, m_pStaticMesh->GetCollisionShape(), m_transform); else m_pCollisionObject = new Physics::KinematicObject(m_entityID, m_pStaticMesh->GetCollisionShape(), m_transform); if (IsInWorld()) m_pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); } else { m_pCollisionObject->SetCollisionShape(m_pStaticMesh->GetCollisionShape()); } } else { if (m_pCollisionObject != nullptr) { if (IsInWorld()) m_pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); m_pCollisionObject->Release(); m_pCollisionObject = nullptr; } } } void StaticMeshEntity::UpdateBounds() { // call entity set bounds with the transformed bounds, this will merge with components (if any) Entity::SetBounds(m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void StaticMeshEntity::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } void StaticMeshEntity::OnTransformChange() { BaseClass::OnTransformChange(); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(m_transform); if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(m_transform); UpdateBounds(); } void StaticMeshEntity::OnComponentBoundsChange() { UpdateBounds(); } bool StaticMeshEntity::PropertyCallbackGetStaticMeshName(ThisClass *pEntity, const void *pUserData, String *pValue) { pValue->Assign(pEntity->m_pStaticMesh->GetName()); return true; } bool StaticMeshEntity::PropertyCallbackSetStaticMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue) { const StaticMesh *pStaticMesh = g_pResourceManager->GetStaticMesh(*pValue); if (pStaticMesh == NULL) return false; if (pEntity->m_pStaticMesh != NULL) pEntity->m_pStaticMesh->Release(); pEntity->m_pStaticMesh = pStaticMesh; return true; } void StaticMeshEntity::PropertyCallbackStaticMeshChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateRenderProxy(); pEntity->UpdateCollisionObject(); pEntity->UpdateBounds(); } void StaticMeshEntity::PropertyCallbackVisibleChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateRenderProxy(); } void StaticMeshEntity::PropertyCallbackCollidableChanged(ThisClass *pEntity, const void *pUserData /*= nullptr*/) { pEntity->UpdateCollisionObject(); } <file_sep>/Engine/Source/Engine/MaterialShader.h #pragma once #include "Engine/Common.h" #include "Core/Resource.h" #include "Renderer/ShaderMap.h" #include "Renderer/RendererTypes.h" class Material; class Texture; class GPUTexture; class GPUBlendState; class GPUShaderProgram; class MaterialShader : public Resource { DECLARE_RESOURCE_TYPE_INFO(MaterialShader, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(MaterialShader); public: MaterialShader(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~MaterialShader(); public: struct UniformParameter { struct Value { union { bool asBool; int32 asInt; float asFloat; float asFloat2[2]; float asFloat3[3]; float asFloat4[4]; }; }; uint32 Index; String Name; SHADER_PARAMETER_TYPE Type; Value DefaultValue; }; struct TextureParameter { struct Value { const Texture *pTexture; GPUTexture *pGPUTexture; }; uint32 Index; String Name; TEXTURE_TYPE Type; String DefaultValue; }; struct StaticSwitchParameter { uint32 Index; uint32 Mask; String Name; bool DefaultValue; }; // settings MATERIAL_BLENDING_MODE GetBlendMode() const { return m_blendingMode; } MATERIAL_LIGHTING_TYPE GetLightingType() const { return m_lightingType; } MATERIAL_LIGHTING_MODEL GetLightingModel() const { return m_lightingModel; } MATERIAL_LIGHTING_NORMAL_SPACE GetLightingNormalSpace() const { return m_lightingNormalSpace; } MATERIAL_RENDER_MODE GetRenderMode() const { return m_renderMode; } MATERIAL_RENDER_LAYER GetRenderLayer() const { return m_renderLayer; } bool IsTwoSided() const { return m_twoSided; } bool GetDepthClamping() const { return m_depthClamping; } bool GetBlockDepthTests() const { return m_depthTests; } bool GetDepthWrites() const { return m_depthWrites; } bool CanCastShadows() const { return m_castShadows; } bool CanReceiveShadows() const { return m_receiveShadows; } uint32 GetSourceCRC() const { return m_sourceCRC; } // loading/saving bool Load(const char *resourceName, ByteStream *pStream); // params const UniformParameter *GetUniformParameter(uint32 Index) const { return &m_UniformParameters.GetElement(Index); } const TextureParameter *GetTextureParameter(uint32 Index) const { return &m_TextureParameters.GetElement(Index); } const StaticSwitchParameter *GetStaticSwitchParameter(uint32 Index) const { return &m_StaticSwitchParameters.GetElement(Index); } uint32 GetUniformParameterCount() const { return m_UniformParameters.GetSize(); } uint32 GetTextureParameterCount() const { return m_TextureParameters.GetSize(); } uint32 GetStaticSwitchParameterCount() const { return m_StaticSwitchParameters.GetSize(); } int32 FindUniformParameter(const char *Name) const; int32 FindTextureParameter(const char *Name) const; int32 FindStaticSwitchParameter(const char *Name) const; // device resources bool CreateDeviceResources() const; void ReleaseDeviceResources() const; // shader instances ShaderMap &GetShaderMap() const { return m_ShaderMap; } // helper for determining render passes to use uint32 SelectRenderPassMask(uint32 wantedPassMask) const; uint8 SelectRenderQueueLayer() const; GPURasterizerState *SelectRasterizerState(RENDERER_FILL_MODE fillMode = RENDERER_FILL_SOLID, RENDERER_CULL_MODE cullMode = RENDERER_CULL_BACK, bool depthBias = false, bool scissorTest = false) const; GPUDepthStencilState *SelectDepthStencilState(bool depthTests = true, bool depthWrites = true, GPU_COMPARISON_FUNC comparisonFunc = GPU_COMPARISON_FUNC_LESS) const; GPUBlendState *SelectBlendState() const; private: // settings MATERIAL_BLENDING_MODE m_blendingMode; MATERIAL_LIGHTING_TYPE m_lightingType; MATERIAL_LIGHTING_MODEL m_lightingModel; MATERIAL_LIGHTING_NORMAL_SPACE m_lightingNormalSpace; MATERIAL_RENDER_MODE m_renderMode; MATERIAL_RENDER_LAYER m_renderLayer; bool m_twoSided; bool m_depthClamping; bool m_depthTests; bool m_depthWrites; bool m_castShadows; bool m_receiveShadows; uint32 m_sourceCRC; // parameters Array<UniformParameter> m_UniformParameters; Array<TextureParameter> m_TextureParameters; Array<StaticSwitchParameter> m_StaticSwitchParameters; // shader instances mutable ShaderMap m_ShaderMap; }; <file_sep>/Editor/Source/Editor/EditorSettings.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorSettings.h" #include "Editor/Editor.h" static EditorSettings s_EditorSettings; EditorSettings *g_pEditorSettings = &s_EditorSettings; EditorSettings::EditorSettings() { m_strBuilderBrushWireframeMaterialName = "materials/editor/builder_brush_wireframe"; m_strBrushWireframeMaterialName = "materials/editor/brush_wireframe"; m_strVolumeWireframeMaterialName = "materials/editor/volume_wireframe"; m_strAxisMeshName = "models/editor/axis"; m_eViewportLayout = EDITOR_VIEWPORT_LAYOUT_1X1; } EditorSettings::~EditorSettings() { } <file_sep>/Engine/Source/ResourceCompiler/BlockPaletteGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/BlockPalette.h" #include "Core/Image.h" #include "YBaseLib/ProgressCallbacks.h" class ZipArchive; class XMLReader; class XMLWriter; class BlockPaletteGenerator { public: struct BlockType { uint32 BlockTypeIndex; String Name; uint32 Flags; BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE ShapeType; struct VisualParameters { BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE Type; uint32 Color; uint32 TextureIndex; String MaterialName; }; struct CubeShapeFace { VisualParameters Visual; }; struct SlabShape { float Height; }; struct PlaneShape { VisualParameters Visual; float OffsetX; float OffsetY; float Width; float Height; float BaseRotation; uint32 RepeatCount; float RepeatRotation; }; struct MeshShape { String MeshName; float Scale; }; struct BlockLightEmitter { bool Enabled; uint32 Radius; }; struct PointLightEmitter { bool Enabled; float3 Offset; uint32 Color; float Brightness; float Range; float Falloff; }; CubeShapeFace CubeShapeFaces[CUBE_FACE_COUNT]; SlabShape SlabShapeSettings; PlaneShape PlaneShapeSettings; MeshShape MeshShapeSettings; BlockLightEmitter BlockLightEmitterSettings; PointLightEmitter PointLightEmitterSettings; }; struct Texture { uint32 Index; String Name; BLOCK_MESH_TEXTURE_BLENDING Blending; BLOCK_MESH_TEXTURE_EFFECT Effect; bool AllowTextureFiltering; float2 ScrollDirection; float ScrollSpeed; uint32 AnimationFrameCount; float AnimationSpeed; Image *pDiffuseMap; Image *pSpecularMap; Image *pNormalMap; //uint32 TextureCount; }; public: BlockPaletteGenerator(); ~BlockPaletteGenerator(); // creation void Create(uint32 diffuseMapSize, uint32 specularMapSize, uint32 normalMapSize); bool Load(const char *FileName, ByteStream *pStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // output bool Save(ByteStream *pStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback) const; // map resolutions const uint32 GetDiffuseMapSize() const { return m_diffuseMapSize; } const uint32 GetSpecularMapSize() const { return m_specularMapSize; } const uint32 GetNormalMapSize() const { return m_normalMapSize; } void SetDiffuseMapSize(uint32 size) { DebugAssert(size > 0); m_diffuseMapSize = size; } void SetSpecularMapSize(uint32 size) { DebugAssert(size > 0); m_specularMapSize = size; } void SetNormalMapSize(uint32 size) { DebugAssert(size > 0); m_normalMapSize = size; } // block type accessing const BlockType *GetBlockType(uint32 i) const { DebugAssert(i < BLOCK_MESH_MAX_BLOCK_TYPES); return (m_allocatedBlockTypes[i]) ? &m_blockTypes[i] : NULL; } BlockType *GetBlockType(uint32 i) { DebugAssert(i < BLOCK_MESH_MAX_BLOCK_TYPES); return (m_allocatedBlockTypes[i]) ? &m_blockTypes[i] : NULL; } // find by name const BlockType *GetBlockTypeByName(const char *name) const; BlockType *GetBlockTypeByName(const char *name); int32 FindBlockTypeByName(const char *name) const; // block management BlockType *CreateBlockType(const char *blockName, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType, uint32 flags); BlockType *CreateBlockType(uint32 blockTypeIndex, const char *blockName, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType, uint32 flags); void RemoveBlockType(uint32 blockTypeIndex); // texture lookup const Texture *GetTexture(uint32 i) const { DebugAssert(i < m_textures.GetSize()); return m_textures[i]; } const Texture *GetTextureByName(const char *name) const; const uint32 GetTextureCount() const { return m_textures.GetSize(); } // texture management const Texture *CreateTexture(const char *textureName, BLOCK_MESH_TEXTURE_BLENDING blending, bool allowTextureFiltering); bool SetTextureDiffuseMap(uint32 textureIndex, const Image *pImage); bool SetTextureSpecularMap(uint32 textureIndex, const Image *pImage); bool SetTextureNormalMap(uint32 textureIndex, const Image *pImage); void SetTextureBlending(uint32 textureIndex, BLOCK_MESH_TEXTURE_BLENDING blending); void SetTextureEffectNone(uint32 textureIndex); void SetTextureEffectScrolled(uint32 textureIndex, const float2 &scrollDirection, float scrollSpeed); void SetTextureEffectAnimation(uint32 textureIndex, uint32 animationFrameCount, float animationSpeed); // texture atlas importing bool ImportTextureAtlas(const char *namePrefix, const char *diffuseMapFileName, const char *specularMapFileName, const char *normalMapFileName, uint32 tilesWide, uint32 tilesHigh, const bool *pImportTileIndices, uint32 maxImportTileIndices, String *pOutTextureNames, uint32 maxOutTextureNames); // compiler bool Compile(TEXTURE_PLATFORM texturePlatform, ByteStream *pOutputStream) const; // assignment operator BlockPaletteGenerator &operator=(const BlockPaletteGenerator &copyFrom); private: bool LoadXML(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks); bool LoadTextures(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks); bool SaveXML(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const; bool SaveTextures(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const; bool SaveTexture(ZipArchive *pArchive, const Image *pImage, const char *filename) const; static Image *LoadTextureImage(ByteStream *pStream, const char *filename); bool m_allocatedBlockTypes[BLOCK_MESH_MAX_BLOCK_TYPES]; BlockType m_blockTypes[BLOCK_MESH_MAX_BLOCK_TYPES]; uint32 m_diffuseMapSize; uint32 m_specularMapSize; uint32 m_normalMapSize; PODArray<Texture *> m_textures; }; <file_sep>/Engine/Source/Renderer/RendererTypes.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RendererTypes.h" #include "Renderer/Renderer.h" int32 DrawTopology_CalculateNumVertices(DRAW_TOPOLOGY Topology, int32 nPrimitives) { switch (Topology) { case DRAW_TOPOLOGY_POINTS: return nPrimitives; case DRAW_TOPOLOGY_LINE_LIST: return nPrimitives * 2; case DRAW_TOPOLOGY_LINE_STRIP: return nPrimitives + 1; case DRAW_TOPOLOGY_TRIANGLE_LIST: return nPrimitives * 3; case DRAW_TOPOLOGY_TRIANGLE_STRIP: return nPrimitives + 2; } UnreachableCode(); return 0; } int32 DrawTopology_CalculateNumPrimitives(DRAW_TOPOLOGY Topology, int32 nVertices) { switch (Topology) { case DRAW_TOPOLOGY_POINTS: return nVertices; case DRAW_TOPOLOGY_LINE_LIST: return nVertices / 2; case DRAW_TOPOLOGY_LINE_STRIP: return nVertices - 1; case DRAW_TOPOLOGY_TRIANGLE_LIST: return nVertices / 3; case DRAW_TOPOLOGY_TRIANGLE_STRIP: return nVertices - 2; } UnreachableCode(); return 0; } Y_Define_NameTable(NameTables::GPUResourceType) Y_NameTable_Entry("RasterizerState", GPU_RESOURCE_TYPE_RASTERIZER_STATE) Y_NameTable_Entry("DepthStencilState", GPU_RESOURCE_TYPE_DEPTH_STENCIL_STATE) Y_NameTable_Entry("BlendState", GPU_RESOURCE_TYPE_BLEND_STATE) Y_NameTable_Entry("SamplerState", GPU_RESOURCE_TYPE_SAMPLER_STATE) Y_NameTable_Entry("Buffer", GPU_RESOURCE_TYPE_BUFFER) Y_NameTable_Entry("Texture1D", GPU_RESOURCE_TYPE_TEXTURE1D) Y_NameTable_Entry("Texture1DArray", GPU_RESOURCE_TYPE_TEXTURE1DARRAY) Y_NameTable_Entry("Texture2D", GPU_RESOURCE_TYPE_TEXTURE2D) Y_NameTable_Entry("Texture2DArray", GPU_RESOURCE_TYPE_TEXTURE2DARRAY) Y_NameTable_Entry("Texture3D", GPU_RESOURCE_TYPE_TEXTURE3D) Y_NameTable_Entry("TextureCube", GPU_RESOURCE_TYPE_TEXTURECUBE) Y_NameTable_Entry("TextureCubeArray", GPU_RESOURCE_TYPE_TEXTURECUBEARRAY) Y_NameTable_Entry("TextureBuffer", GPU_RESOURCE_TYPE_TEXTUREBUFFER) Y_NameTable_Entry("DepthTexture", GPU_RESOURCE_TYPE_DEPTH_TEXTURE) Y_NameTable_Entry("Query", GPU_RESOURCE_TYPE_QUERY) Y_NameTable_Entry("ShaderProgram", GPU_RESOURCE_TYPE_SHADER_PROGRAM) Y_NameTable_End() Y_Define_NameTable(NameTables::ShaderParameterType) Y_NameTable_Entry("bool", SHADER_PARAMETER_TYPE_BOOL) Y_NameTable_Entry("bool2", SHADER_PARAMETER_TYPE_BOOL2) Y_NameTable_Entry("bool3", SHADER_PARAMETER_TYPE_BOOL3) Y_NameTable_Entry("bool4", SHADER_PARAMETER_TYPE_BOOL4) Y_NameTable_Entry("half", SHADER_PARAMETER_TYPE_HALF) Y_NameTable_Entry("half2", SHADER_PARAMETER_TYPE_HALF2) Y_NameTable_Entry("half3", SHADER_PARAMETER_TYPE_HALF3) Y_NameTable_Entry("half4", SHADER_PARAMETER_TYPE_HALF4) Y_NameTable_Entry("int", SHADER_PARAMETER_TYPE_INT) Y_NameTable_Entry("int2", SHADER_PARAMETER_TYPE_INT2) Y_NameTable_Entry("int3", SHADER_PARAMETER_TYPE_INT3) Y_NameTable_Entry("int4", SHADER_PARAMETER_TYPE_INT4) Y_NameTable_Entry("uint", SHADER_PARAMETER_TYPE_UINT) Y_NameTable_Entry("uint2", SHADER_PARAMETER_TYPE_UINT2) Y_NameTable_Entry("uint3", SHADER_PARAMETER_TYPE_UINT3) Y_NameTable_Entry("uint4", SHADER_PARAMETER_TYPE_UINT4) Y_NameTable_Entry("float", SHADER_PARAMETER_TYPE_FLOAT) Y_NameTable_Entry("float2", SHADER_PARAMETER_TYPE_FLOAT2) Y_NameTable_Entry("float3", SHADER_PARAMETER_TYPE_FLOAT3) Y_NameTable_Entry("float4", SHADER_PARAMETER_TYPE_FLOAT4) Y_NameTable_Entry("float2x2", SHADER_PARAMETER_TYPE_FLOAT2X2) Y_NameTable_Entry("float3x3", SHADER_PARAMETER_TYPE_FLOAT3X3) Y_NameTable_Entry("float3x4", SHADER_PARAMETER_TYPE_FLOAT3X4) Y_NameTable_Entry("float4x4", SHADER_PARAMETER_TYPE_FLOAT4X4) Y_NameTable_Entry("Texture1D", SHADER_PARAMETER_TYPE_TEXTURE1D) Y_NameTable_Entry("Texture1DArray", SHADER_PARAMETER_TYPE_TEXTURE1DARRAY) Y_NameTable_Entry("Texture2D", SHADER_PARAMETER_TYPE_TEXTURE2D) Y_NameTable_Entry("Texture2DArray", SHADER_PARAMETER_TYPE_TEXTURE2DARRAY) Y_NameTable_Entry("Texture2DMS", SHADER_PARAMETER_TYPE_TEXTURE2DMS) Y_NameTable_Entry("Texture2DMSArray", SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY) Y_NameTable_Entry("Texture3D", SHADER_PARAMETER_TYPE_TEXTURE3D) Y_NameTable_Entry("TextureCube", SHADER_PARAMETER_TYPE_TEXTURECUBE) Y_NameTable_Entry("TextureCubeArray", SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY) Y_NameTable_Entry("TextureBuffer", SHADER_PARAMETER_TYPE_TEXTUREBUFFER) Y_NameTable_Entry("ConstantBuffer", SHADER_PARAMETER_TYPE_CONSTANT_BUFFER) Y_NameTable_Entry("SamplerState", SHADER_PARAMETER_TYPE_SAMPLER_STATE) Y_NameTable_Entry("Buffer", SHADER_PARAMETER_TYPE_BUFFER) Y_NameTable_Entry("Struct", SHADER_PARAMETER_TYPE_STRUCT) Y_NameTable_End() uint32 ShaderParameterValueTypeSize(SHADER_PARAMETER_TYPE Type) { static const uint32 Sizes[SHADER_PARAMETER_TYPE_COUNT] = { 4, // SHADER_PARAMETER_TYPE_BOOL 8, // SHADER_PARAMETER_TYPE_BOOL2 12, // SHADER_PARAMETER_TYPE_BOOL3 16, // SHADER_PARAMETER_TYPE_BOOL4 2, // SHADER_PARAMETER_TYPE_HALF 4, // SHADER_PARAMETER_TYPE_HALF2 6, // SHADER_PARAMETER_TYPE_HALF3 8, // SHADER_PARAMETER_TYPE_HALF4 4, // SHADER_PARAMETER_TYPE_INT 8, // SHADER_PARAMETER_TYPE_INT2 12, // SHADER_PARAMETER_TYPE_INT3 16, // SHADER_PARAMETER_TYPE_INT4 4, // SHADER_PARAMETER_TYPE_UINT 8, // SHADER_PARAMETER_TYPE_UINT2 12, // SHADER_PARAMETER_TYPE_UINT3 16, // SHADER_PARAMETER_TYPE_UINT4 4, // SHADER_PARAMETER_TYPE_FLOAT 8, // SHADER_PARAMETER_TYPE_FLOAT2 12, // SHADER_PARAMETER_TYPE_FLOAT3 16, // SHADER_PARAMETER_TYPE_FLOAT4 16, // SHADER_PARAMETER_TYPE_FLOAT2X2 36, // SHADER_PARAMETER_TYPE_FLOAT3X3 48, // SHADER_PARAMETER_TYPE_FLOAT3X4 64, // SHADER_PARAMETER_TYPE_FLOAT4X4 0, // SHADER_PARAMETER_TYPE_TEXTURE1D 0, // SHADER_PARAMETER_TYPE_TEXTURE1DARRAY 0, // SHADER_PARAMETER_TYPE_TEXTURE2D 0, // SHADER_PARAMETER_TYPE_TEXTURE2DARRAY 0, // SHADER_PARAMETER_TYPE_TEXTURE2DMS 0, // SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY 0, // SHADER_PARAMETER_TYPE_TEXTURE3D 0, // SHADER_PARAMETER_TYPE_TEXTURECUBE 0, // SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY 0, // SHADER_PARAMETER_TYPE_TEXTUREBUFFER 0, // SHADER_PARAMETER_TYPE_CONSTANT_BUFFER 0, // SHADER_PARAMETER_TYPE_SAMPLER_STATE 0, // SHADER_PARAMETER_TYPE_BUFFER 0 // SHADER_PARAMETER_TYPE_STRUCT }; DebugAssert(Type < SHADER_PARAMETER_TYPE_COUNT); return Sizes[Type]; } GPU_RESOURCE_TYPE ShaderParameterResourceType(SHADER_PARAMETER_TYPE Type) { static const GPU_RESOURCE_TYPE resourceTypes[SHADER_PARAMETER_TYPE_COUNT] = { GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_BOOL GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_BOOL2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_BOOL3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_BOOL4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_HALF GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_HALF2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_HALF3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_HALF4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_INT GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_INT2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_INT3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_INT4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_UINT GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_UINT2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_UINT3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_UINT4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT2X2 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT3X3 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT3X4 GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_FLOAT4X4 GPU_RESOURCE_TYPE_TEXTURE1D, // SHADER_PARAMETER_TYPE_TEXTURE1D GPU_RESOURCE_TYPE_TEXTURE1DARRAY, // SHADER_PARAMETER_TYPE_TEXTURE1DARRAY GPU_RESOURCE_TYPE_TEXTURE2D, // SHADER_PARAMETER_TYPE_TEXTURE2D GPU_RESOURCE_TYPE_TEXTURE2DARRAY, // SHADER_PARAMETER_TYPE_TEXTURE2DARRAY GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_TEXTURE2DMS GPU_RESOURCE_TYPE_COUNT, // SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY GPU_RESOURCE_TYPE_TEXTURE3D, // SHADER_PARAMETER_TYPE_TEXTURE3D GPU_RESOURCE_TYPE_TEXTURECUBE, // SHADER_PARAMETER_TYPE_TEXTURECUBE GPU_RESOURCE_TYPE_TEXTURECUBEARRAY, // SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY GPU_RESOURCE_TYPE_TEXTUREBUFFER, // SHADER_PARAMETER_TYPE_TEXTUREBUFFER GPU_RESOURCE_TYPE_BUFFER, // SHADER_PARAMETER_TYPE_CONSTANT_BUFFER GPU_RESOURCE_TYPE_SAMPLER_STATE, // SHADER_PARAMETER_TYPE_SAMPLER_STATE GPU_RESOURCE_TYPE_BUFFER, // SHADER_PARAMETER_TYPE_BUFFER GPU_RESOURCE_TYPE_COUNT // SHADER_PARAMETER_TYPE_STRUCT }; DebugAssert(Type < SHADER_PARAMETER_TYPE_COUNT); return resourceTypes[Type]; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<bool>() { return SHADER_PARAMETER_TYPE_BOOL; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<int32>() { return SHADER_PARAMETER_TYPE_INT; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<float>() { return SHADER_PARAMETER_TYPE_FLOAT; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<float2>() { return SHADER_PARAMETER_TYPE_FLOAT2; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<float3>() { return SHADER_PARAMETER_TYPE_FLOAT3; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<float4>() { return SHADER_PARAMETER_TYPE_FLOAT4; } template<> SHADER_PARAMETER_TYPE ShaderParameterTypeFor<float4x4>() { return SHADER_PARAMETER_TYPE_FLOAT4X4; } template<> bool ShaderParameterTypeFromString<bool>(const char *StringValue) { return StringConverter::StringToBool(StringValue); } template<> int32 ShaderParameterTypeFromString<int32>(const char *StringValue) { return StringConverter::StringToInt32(StringValue); } template<> float ShaderParameterTypeFromString<float>(const char *StringValue) { return StringConverter::StringToFloat(StringValue); } template<> float2 ShaderParameterTypeFromString<float2>(const char *StringValue) { return StringConverter::StringToVector2f(StringValue); } template<> float3 ShaderParameterTypeFromString<float3>(const char *StringValue) { return StringConverter::StringToVector3f(StringValue); } template<> float4 ShaderParameterTypeFromString<float4>(const char *StringValue) { return StringConverter::StringToVector4f(StringValue); } void ShaderParameterTypeFromString(SHADER_PARAMETER_TYPE Type, void *pDestination, const char *StringValue) { switch (Type) { case SHADER_PARAMETER_TYPE_BOOL: *reinterpret_cast<bool *>(pDestination) = StringConverter::StringToBool(StringValue); break; case SHADER_PARAMETER_TYPE_INT: *reinterpret_cast<int32 *>(pDestination) = StringConverter::StringToInt32(StringValue); break; case SHADER_PARAMETER_TYPE_FLOAT: *reinterpret_cast<float *>(pDestination) = StringConverter::StringToFloat(StringValue); break; case SHADER_PARAMETER_TYPE_FLOAT2: *reinterpret_cast<float2 *>(pDestination) = StringConverter::StringToVector2f(StringValue); break; case SHADER_PARAMETER_TYPE_FLOAT3: *reinterpret_cast<float3 *>(pDestination) = StringConverter::StringToVector3f(StringValue); break; case SHADER_PARAMETER_TYPE_FLOAT4: *reinterpret_cast<float4 *>(pDestination) = StringConverter::StringToVector4f(StringValue); break; default: UnreachableCode(); break; } } template<> void ShaderParameterTypeToString<bool>(String &Destination, const bool &Value) { return StringConverter::BoolToString(Destination, Value); } template<> void ShaderParameterTypeToString<int32>(String &Destination, const int32 &Value) { return StringConverter::Int32ToString(Destination, Value); } template<> void ShaderParameterTypeToString<float>(String &Destination, const float &Value) { return StringConverter::FloatToString(Destination, Value); } template<> void ShaderParameterTypeToString<float2>(String &Destination, const float2 &Value) { return StringConverter::Vector2fToString(Destination, Value); } template<> void ShaderParameterTypeToString<float3>(String &Destination, const float3 &Value) { return StringConverter::Vector3fToString(Destination, Value); } template<> void ShaderParameterTypeToString<float4>(String &Destination, const float4 &Value) { return StringConverter::Vector4fToString(Destination, Value); } void ShaderParameterTypeToString(String &Destination, SHADER_PARAMETER_TYPE Type, const void *pValue) { switch (Type) { case SHADER_PARAMETER_TYPE_BOOL: StringConverter::BoolToString(Destination, *reinterpret_cast<const bool *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT: StringConverter::Int32ToString(Destination, *reinterpret_cast<const int32 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT: StringConverter::FloatToString(Destination, *reinterpret_cast<const float *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT2: StringConverter::Vector2fToString(Destination, *reinterpret_cast<const float2 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3: StringConverter::Vector3fToString(Destination, *reinterpret_cast<const float3 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT4: StringConverter::Vector4fToString(Destination, *reinterpret_cast<const float4 *>(pValue)); break; default: UnreachableCode(); break; } } Y_Define_NameTable(NameTables::GPUVertexElementType) Y_NameTable_Entry("byte", GPU_VERTEX_ELEMENT_TYPE_BYTE) Y_NameTable_Entry("byte2", GPU_VERTEX_ELEMENT_TYPE_BYTE2) Y_NameTable_Entry("byte4", GPU_VERTEX_ELEMENT_TYPE_BYTE4) Y_NameTable_Entry("ubyte", GPU_VERTEX_ELEMENT_TYPE_UBYTE) Y_NameTable_Entry("ubyte2", GPU_VERTEX_ELEMENT_TYPE_UBYTE2) Y_NameTable_Entry("ubyte4", GPU_VERTEX_ELEMENT_TYPE_UBYTE4) Y_NameTable_Entry("half", GPU_VERTEX_ELEMENT_TYPE_HALF) Y_NameTable_Entry("half2", GPU_VERTEX_ELEMENT_TYPE_HALF2) Y_NameTable_Entry("half4", GPU_VERTEX_ELEMENT_TYPE_HALF4) Y_NameTable_Entry("float", GPU_VERTEX_ELEMENT_TYPE_FLOAT) Y_NameTable_Entry("float2", GPU_VERTEX_ELEMENT_TYPE_FLOAT2) Y_NameTable_Entry("float3", GPU_VERTEX_ELEMENT_TYPE_FLOAT3) Y_NameTable_Entry("float4", GPU_VERTEX_ELEMENT_TYPE_FLOAT4) Y_NameTable_Entry("int", GPU_VERTEX_ELEMENT_TYPE_INT) Y_NameTable_Entry("int2", GPU_VERTEX_ELEMENT_TYPE_INT2) Y_NameTable_Entry("int3", GPU_VERTEX_ELEMENT_TYPE_INT3) Y_NameTable_Entry("int4", GPU_VERTEX_ELEMENT_TYPE_INT4) Y_NameTable_Entry("uint", GPU_VERTEX_ELEMENT_TYPE_UINT) Y_NameTable_Entry("uint2", GPU_VERTEX_ELEMENT_TYPE_UINT2) Y_NameTable_Entry("uint3", GPU_VERTEX_ELEMENT_TYPE_UINT3) Y_NameTable_Entry("uint4", GPU_VERTEX_ELEMENT_TYPE_UINT4) Y_NameTable_Entry("color", GPU_VERTEX_ELEMENT_TYPE_UNORM4) Y_NameTable_End() Y_Define_NameTable(NameTables::GPUVertexElementSemantic) Y_NameTable_Entry("POSITION", GPU_VERTEX_ELEMENT_SEMANTIC_POSITION) Y_NameTable_Entry("TEXCOORD", GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD) Y_NameTable_Entry("COLOR", GPU_VERTEX_ELEMENT_SEMANTIC_COLOR) Y_NameTable_Entry("TANGENT", GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT) Y_NameTable_Entry("BINORMAL", GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL) Y_NameTable_Entry("NORMAL", GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL) Y_NameTable_Entry("POINTSIZE", GPU_VERTEX_ELEMENT_SEMANTIC_POINTSIZE) Y_NameTable_Entry("BLENDINDICES", GPU_VERTEX_ELEMENT_SEMANTIC_BLENDINDICES) Y_NameTable_Entry("BLENDWEIGHTS", GPU_VERTEX_ELEMENT_SEMANTIC_BLENDWEIGHTS) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererFogMode) Y_NameTable_Entry("NONE", RENDERER_FOG_MODE_NONE) Y_NameTable_Entry("LINEAR", RENDERER_FOG_MODE_LINEAR) Y_NameTable_Entry("EXP", RENDERER_FOG_MODE_EXP) Y_NameTable_Entry("EXP2", RENDERER_FOG_MODE_EXP2) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererPlatform) Y_NameTable_Entry("D3D11", RENDERER_PLATFORM_D3D11) Y_NameTable_Entry("D3D12", RENDERER_PLATFORM_D3D12) Y_NameTable_Entry("OPENGL", RENDERER_PLATFORM_OPENGL) Y_NameTable_Entry("OPENGLES2", RENDERER_PLATFORM_OPENGLES2) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererPlatformFullName) Y_NameTable_Entry("Direct3D 11", RENDERER_PLATFORM_D3D11) Y_NameTable_Entry("Direct3D 12", RENDERER_PLATFORM_D3D12) Y_NameTable_Entry("OpenGL", RENDERER_PLATFORM_OPENGL) Y_NameTable_Entry("OpenGL ES 2", RENDERER_PLATFORM_OPENGLES2) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererFeatureLevel) Y_NameTable_Entry("ES2", RENDERER_FEATURE_LEVEL_ES2) Y_NameTable_Entry("ES3", RENDERER_FEATURE_LEVEL_ES3) Y_NameTable_Entry("SM4", RENDERER_FEATURE_LEVEL_SM4) Y_NameTable_Entry("SM5", RENDERER_FEATURE_LEVEL_SM5) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererFeatureLevelFullName) Y_NameTable_Entry("OpenGL ES 2.0", RENDERER_FEATURE_LEVEL_ES2) Y_NameTable_Entry("OpenGL ES 3.0", RENDERER_FEATURE_LEVEL_ES3) Y_NameTable_Entry("Shader Model 4", RENDERER_FEATURE_LEVEL_SM4) Y_NameTable_Entry("Shader Model 5", RENDERER_FEATURE_LEVEL_SM5) Y_NameTable_End() Y_Define_NameTable(NameTables::ShaderProgramStage) Y_NameTable_Entry("VertexShader", SHADER_PROGRAM_STAGE_VERTEX_SHADER) Y_NameTable_Entry("DomainShader", SHADER_PROGRAM_STAGE_DOMAIN_SHADER) Y_NameTable_Entry("HullShader", SHADER_PROGRAM_STAGE_HULL_SHADER) Y_NameTable_Entry("GeometryShader", SHADER_PROGRAM_STAGE_GEOMETRY_SHADER) Y_NameTable_Entry("PixelShader", SHADER_PROGRAM_STAGE_PIXEL_SHADER) Y_NameTable_Entry("ComputeShader", SHADER_PROGRAM_STAGE_COMPUTE_SHADER) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererFillModes) Y_NameTable_Entry("Wireframe", RENDERER_FILL_WIREFRAME) Y_NameTable_Entry("Solid", RENDERER_FILL_SOLID) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererCullModes) Y_NameTable_Entry("None", RENDERER_CULL_NONE) Y_NameTable_Entry("Front", RENDERER_CULL_FRONT) Y_NameTable_Entry("Back", RENDERER_CULL_BACK) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererComparisonFunc) Y_NameTable_Entry("Never", GPU_COMPARISON_FUNC_NEVER) Y_NameTable_Entry("Less", GPU_COMPARISON_FUNC_LESS) Y_NameTable_Entry("Equal", GPU_COMPARISON_FUNC_EQUAL) Y_NameTable_Entry("LessEqual", GPU_COMPARISON_FUNC_LESS_EQUAL) Y_NameTable_Entry("Greater", GPU_COMPARISON_FUNC_GREATER) Y_NameTable_Entry("NotEqual", GPU_COMPARISON_FUNC_NOT_EQUAL) Y_NameTable_Entry("GreaterEqual", GPU_COMPARISON_FUNC_GREATER_EQUAL) Y_NameTable_Entry("Always", GPU_COMPARISON_FUNC_ALWAYS) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererBlendOptions) Y_NameTable_Entry("Zero", RENDERER_BLEND_ZERO) Y_NameTable_Entry("One", RENDERER_BLEND_ONE) Y_NameTable_Entry("SrcColor", RENDERER_BLEND_SRC_COLOR) Y_NameTable_Entry("InvSrcColor", RENDERER_BLEND_INV_SRC_COLOR) Y_NameTable_Entry("SrcAlpha", RENDERER_BLEND_SRC_ALPHA) Y_NameTable_Entry("InvSrcAlpha", RENDERER_BLEND_INV_SRC_ALPHA) Y_NameTable_Entry("DestAlpha", RENDERER_BLEND_DEST_ALPHA) Y_NameTable_Entry("InvDestAlpha", RENDERER_BLEND_INV_DEST_ALPHA) Y_NameTable_Entry("DestColor", RENDERER_BLEND_DEST_COLOR) Y_NameTable_Entry("InvDestColor", RENDERER_BLEND_INV_DEST_COLOR) Y_NameTable_Entry("SrcAlphaSat", RENDERER_BLEND_SRC_ALPHA_SAT) Y_NameTable_Entry("BlendFactor", RENDERER_BLEND_BLEND_FACTOR) Y_NameTable_Entry("InvBlendFactor", RENDERER_BLEND_INV_BLEND_FACTOR) Y_NameTable_Entry("Src1Color", RENDERER_BLEND_SRC1_COLOR) Y_NameTable_Entry("InvSrc1Color", RENDERER_BLEND_INV_SRC1_COLOR) Y_NameTable_Entry("Src1Alpha", RENDERER_BLEND_SRC1_ALPHA) Y_NameTable_Entry("InvSrc1Alpha", RENDERER_BLEND_INV_SRC1_ALPHA) Y_NameTable_End() Y_Define_NameTable(NameTables::RendererBlendOps) Y_NameTable_Entry("Add", RENDERER_BLEND_OP_ADD) Y_NameTable_Entry("Subtract", RENDERER_BLEND_OP_SUBTRACT) Y_NameTable_Entry("RevSubtract", RENDERER_BLEND_OP_REV_SUBTRACT) Y_NameTable_Entry("Min", RENDERER_BLEND_OP_MIN) Y_NameTable_Entry("Max", RENDERER_BLEND_OP_MAX) Y_NameTable_End() GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1D *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1DArray *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(pTexture->GetDesc()->ArraySize), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1DArray *pTexture, uint32 mipLevel, uint32 arrayIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2D *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(pTexture->GetDesc()->ArraySize), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel, uint32 arrayIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTexture3D *pTexture, uint32 mipLevel, uint32 slideIndex) : MipLevel(mipLevel), FirstLayerIndex(slideIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(CUBE_FACE_COUNT), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel, CUBE_FACE faceIndex) : MipLevel(mipLevel), FirstLayerIndex(faceIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex * CUBE_FACE_COUNT), NumLayers(CUBE_FACE_COUNT), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex, CUBE_FACE faceIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex * CUBE_FACE_COUNT + faceIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_RENDER_TARGET_VIEW_DESC::GPU_RENDER_TARGET_VIEW_DESC(GPUDepthTexture *pTexture) : MipLevel(0), FirstLayerIndex(0), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2D *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(pTexture->GetDesc()->ArraySize), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel, uint32 arrayIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel /*= 0*/) : MipLevel(mipLevel), FirstLayerIndex(0), NumLayers(CUBE_FACE_COUNT), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel, CUBE_FACE faceIndex) : MipLevel(mipLevel), FirstLayerIndex(faceIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex * CUBE_FACE_COUNT), NumLayers(CUBE_FACE_COUNT), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex, CUBE_FACE faceIndex) : MipLevel(mipLevel), FirstLayerIndex(arrayIndex * CUBE_FACE_COUNT + faceIndex), NumLayers(1), Format(pTexture->GetDesc()->Format) { } GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC::GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUDepthTexture *pTexture) : MipLevel(0), FirstLayerIndex(0), NumLayers(1), Format(pTexture->GetDesc()->Format) { } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUShaderProgram.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUShaderProgram.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUBuffer.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(Renderer); #define LAZY_RESOURCE_CLEANUP_AFTER_SWITCH 1 D3D11GPUShaderProgram::D3D11GPUShaderProgram() : m_pD3DInputLayout(nullptr), m_pD3DVertexShader(nullptr), m_pD3DHullShader(nullptr), m_pD3DDomainShader(nullptr), m_pD3DGeometryShader(nullptr), m_pD3DPixelShader(nullptr), m_pD3DComputeShader(nullptr), m_pBoundContext(nullptr) { } D3D11GPUShaderProgram::~D3D11GPUShaderProgram() { DebugAssert(m_pBoundContext == NULL); SAFE_RELEASE(m_pD3DComputeShader); SAFE_RELEASE(m_pD3DPixelShader); SAFE_RELEASE(m_pD3DGeometryShader); SAFE_RELEASE(m_pD3DDomainShader); SAFE_RELEASE(m_pD3DHullShader); SAFE_RELEASE(m_pD3DVertexShader); SAFE_RELEASE(m_pD3DInputLayout); } void D3D11GPUShaderProgram::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { // dummy values for now if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 128; } void D3D11GPUShaderProgram::SetDebugName(const char *name) { if (m_pD3DVertexShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DVertexShader, name); if (m_pD3DHullShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DHullShader, name); if (m_pD3DDomainShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DDomainShader, name); if (m_pD3DGeometryShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DGeometryShader, name); if (m_pD3DPixelShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DPixelShader, name); if (m_pD3DComputeShader != nullptr) D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DComputeShader, name); } bool D3D11GPUShaderProgram::Create(D3D11GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexAttributes, uint32 nVertexAttributes, ByteStream *pByteCodeStream) { HRESULT hResult; ID3D11Device *pD3DDevice = pDevice->GetD3DDevice(); BinaryReader binaryReader(pByteCodeStream); // get the header of the shader cache entry D3DShaderCacheEntryHeader header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Signature != D3D_SHADER_CACHE_ENTRY_HEADER) { Log_ErrorPrintf("D3D11GPUShaderProgram::Create: Shader cache entry header corrupted."); return false; } // save a copy of the vertex shader code, we need it to validate the input layout byte *pVertexShaderByteCode = nullptr; uint32 vertexShaderByteCodeSize = 0; // create d3d shader objects, and arrays for them for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (header.StageSize[stageIndex] == 0) continue; // read in stage bytecode uint32 stageByteCodeSize = header.StageSize[stageIndex]; byte *pStageByteCode = new byte[stageByteCodeSize]; if (!binaryReader.SafeReadBytes(pStageByteCode, stageByteCodeSize)) { delete[] pVertexShaderByteCode; return false; } // create d3d objects switch (stageIndex) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: { if ((hResult = pD3DDevice->CreateVertexShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DVertexShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateVertexShader failed with hResult %08X.", hResult); delete[] pStageByteCode; return false; } // save VS bytecode pVertexShaderByteCode = pStageByteCode; vertexShaderByteCodeSize = stageByteCodeSize; } break; case SHADER_PROGRAM_STAGE_HULL_SHADER: { if ((hResult = pD3DDevice->CreateHullShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DHullShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateHullShader failed with hResult %08X.", hResult); delete[] pStageByteCode; delete[] pVertexShaderByteCode; return false; } delete[] pStageByteCode; } break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: { if ((hResult = pD3DDevice->CreateDomainShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DDomainShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateDomainShader failed with hResult %08X.", hResult); delete[] pStageByteCode; delete[] pVertexShaderByteCode; return false; } delete[] pStageByteCode; } break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: { if ((hResult = pD3DDevice->CreateGeometryShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DGeometryShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateGeometryShader failed with hResult %08X.", hResult); delete[] pStageByteCode; delete[] pVertexShaderByteCode; return false; } delete[] pStageByteCode; } break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: { if ((hResult = pD3DDevice->CreatePixelShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DPixelShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreatePixelShader failed with hResult %08X.", hResult); delete[] pStageByteCode; delete[] pVertexShaderByteCode; return false; } delete[] pStageByteCode; } break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: { if ((hResult = pD3DDevice->CreateComputeShader(pStageByteCode, stageByteCodeSize, nullptr, &m_pD3DComputeShader)) != S_OK) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateComputeShader failed with hResult %08X.", hResult); delete[] pStageByteCode; delete[] pVertexShaderByteCode; return false; } delete[] pStageByteCode; } break; default: UnreachableCode(); break; } } #ifdef Y_BUILD_CONFIG_DEBUG // // set debug name // { // SmallString debugName; // debugName.Format("%s:%u:%s:%u:%s:%u", pCacheEntryHeader->BaseShaderName, pCacheEntryHeader->BaseShaderFlags, pCacheEntryHeader->VertexFactoryName, pCacheEntryHeader->VertexFactoryFlags, pCacheEntryHeader->MaterialShaderName, pCacheEntryHeader->MaterialShaderFlags); // if (m_pD3DVertexShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DVertexShader, debugName); // if (m_pD3DHullShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DHullShader, debugName); // if (m_pD3DDomainShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DDomainShader, debugName); // if (m_pD3DGeometryShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DGeometryShader, debugName); // if (m_pD3DPixelShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DPixelShader, debugName); // if (m_pD3DComputeShader != nullptr) // D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DComputeShader, debugName); // } #endif // load up vertex attributes if (header.VertexAttributeCount > 0 && vertexShaderByteCodeSize > 0) { // create a filtered list of vertex attributes provided and those used by the shader D3D11_INPUT_ELEMENT_DESC usedVertexAttributes[GPU_INPUT_LAYOUT_MAX_ELEMENTS]; uint32 nUsedVertexAttributes = 0; for (uint32 i = 0; i < header.VertexAttributeCount; i++) { D3DShaderCacheEntryVertexAttribute attribute; if (!binaryReader.SafeReadBytes(&attribute, sizeof(attribute))) { delete[] pVertexShaderByteCode; return false; } // search in the list provided uint32 listIndex; for (listIndex = 0; listIndex < nVertexAttributes; listIndex++) { if (pVertexAttributes[listIndex].Semantic == (GPU_VERTEX_ELEMENT_SEMANTIC)attribute.SemanticName && pVertexAttributes[listIndex].SemanticIndex == attribute.SemanticIndex) { break; } } // make sure it exists if (listIndex == nVertexAttributes) { Log_ErrorPrintf("D3D11ShaderProgram::Create: failed to match shader attribute with provided attributes"); delete[] pVertexShaderByteCode; return false; } // copy info in usedVertexAttributes[nUsedVertexAttributes].SemanticName = NameTable_GetNameString(NameTables::GPUVertexElementSemantic, pVertexAttributes[listIndex].Semantic); usedVertexAttributes[nUsedVertexAttributes].SemanticIndex = pVertexAttributes[listIndex].SemanticIndex; usedVertexAttributes[nUsedVertexAttributes].Format = D3D11TypeConversion::VertexElementTypeToDXGIFormat(pVertexAttributes[listIndex].Type); usedVertexAttributes[nUsedVertexAttributes].InputSlot = pVertexAttributes[listIndex].StreamIndex; usedVertexAttributes[nUsedVertexAttributes].AlignedByteOffset = pVertexAttributes[listIndex].StreamOffset; usedVertexAttributes[nUsedVertexAttributes].InputSlotClass = (pVertexAttributes[listIndex].InstanceStepRate != 0) ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA; usedVertexAttributes[nUsedVertexAttributes].InstanceDataStepRate = pVertexAttributes[listIndex].InstanceStepRate; nUsedVertexAttributes++; } // create input layout // TODO: Cache these if (FAILED(hResult = pD3DDevice->CreateInputLayout(usedVertexAttributes, nUsedVertexAttributes, pVertexShaderByteCode, vertexShaderByteCodeSize, &m_pD3DInputLayout))) { Log_ErrorPrintf("D3D11ShaderProgram::Create: CreateInputLayout failed with hResult %08X", hResult); delete[] pVertexShaderByteCode; return false; } } // can finally free this now delete[] pVertexShaderByteCode; // load up constant buffers if (header.ConstantBufferCount > 0) { m_constantBuffers.Resize(header.ConstantBufferCount); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { D3DShaderCacheEntryConstantBuffer srcConstantBufferInfo; ConstantBuffer *pDstConstantBuffer = &m_constantBuffers[i]; if (!binaryReader.SafeReadBytes(&srcConstantBufferInfo, sizeof(srcConstantBufferInfo))) return false; // read name if (!binaryReader.SafeReadFixedString(srcConstantBufferInfo.NameLength, &pDstConstantBuffer->Name)) return false; // constant buffer struct pDstConstantBuffer->MinimumSize = srcConstantBufferInfo.MinimumSize; pDstConstantBuffer->ParameterIndex = srcConstantBufferInfo.ParameterIndex; pDstConstantBuffer->EngineConstantBufferIndex = 0; // lookup engine constant buffer const ShaderConstantBuffer *pEngineConstantBuffer = ShaderConstantBuffer::GetShaderConstantBufferByName(pDstConstantBuffer->Name, RENDERER_PLATFORM_D3D11, pDevice->GetFeatureLevel()); if (pEngineConstantBuffer == nullptr) { Log_ErrorPrintf("D3D11ShaderProgram::Create: Shader is requesting unknown constant buffer named '%s'.", pDstConstantBuffer->Name); return false; } // store index pDstConstantBuffer->EngineConstantBufferIndex = pEngineConstantBuffer->GetIndex(); } } // load parameters if (header.ParameterCount > 0) { m_parameters.Resize(header.ParameterCount); for (uint32 i = 0; i < m_parameters.GetSize(); i++) { D3DShaderCacheEntryParameter srcParameter; Parameter *pDstParameterInfo = &m_parameters[i]; if (!binaryReader.SafeReadBytes(&srcParameter, sizeof(srcParameter))) return false; // read name if (!binaryReader.SafeReadFixedString(srcParameter.NameLength, &pDstParameterInfo->Name)) return false; pDstParameterInfo->Type = srcParameter.Type; pDstParameterInfo->ConstantBufferIndex = srcParameter.ConstantBufferIndex; pDstParameterInfo->ConstantBufferOffset = srcParameter.ConstantBufferOffset; pDstParameterInfo->ArraySize = srcParameter.ArraySize; pDstParameterInfo->ArrayStride = srcParameter.ArrayStride; pDstParameterInfo->BindTarget = (D3D_SHADER_BIND_TARGET)srcParameter.BindTarget; Y_memcpy(pDstParameterInfo->BindPoint, srcParameter.BindPoint, sizeof(pDstParameterInfo->BindPoint)); pDstParameterInfo->LinkedSamplerIndex = srcParameter.LinkedSamplerIndex; } } // all ok return true; } void D3D11GPUShaderProgram::Bind(D3D11GPUContext *pContext) { DebugAssert(m_pBoundContext == nullptr); ID3D11DeviceContext *pD3DDeviceContext = pContext->GetD3DContext(); // ------------------ IA ------------------ if (m_pD3DInputLayout != nullptr) pD3DDeviceContext->IASetInputLayout(m_pD3DInputLayout); // ------------------ VS ------------------ if (m_pD3DVertexShader != nullptr) pD3DDeviceContext->VSSetShader(m_pD3DVertexShader, nullptr, 0); // ------------------ HS ------------------ if (m_pD3DHullShader != nullptr) pD3DDeviceContext->HSSetShader(m_pD3DHullShader, nullptr, 0); // ------------------ DS ------------------ if (m_pD3DDomainShader != nullptr) pD3DDeviceContext->DSSetShader(m_pD3DDomainShader, nullptr, 0); // ------------------ GS ------------------ if (m_pD3DGeometryShader != nullptr) pD3DDeviceContext->GSSetShader(m_pD3DGeometryShader, nullptr, 0); // ------------------ PS ------------------ if (m_pD3DPixelShader != nullptr) pD3DDeviceContext->PSSetShader(m_pD3DPixelShader, nullptr, 0); // ------------------ CS ------------------ if (m_pD3DComputeShader != nullptr) pD3DDeviceContext->CSSetShader(m_pD3DComputeShader, nullptr, 0); // bound m_pBoundContext = pContext; // bind params InternalBindAutomaticParameters(pContext); } void D3D11GPUShaderProgram::InternalBindAutomaticParameters(D3D11GPUContext *pContext) { // bind constant buffers for (uint32 constantBufferIndex = 0; constantBufferIndex < m_constantBuffers.GetSize(); constantBufferIndex++) { ConstantBuffer *pConstantBufferDef = &m_constantBuffers[constantBufferIndex]; // local? D3D11GPUBuffer *pConstantBuffer = pContext->GetConstantBuffer(pConstantBufferDef->EngineConstantBufferIndex); InternalSetParameterResource(pContext, pConstantBufferDef->ParameterIndex, pConstantBuffer, nullptr); } } void D3D11GPUShaderProgram::Switch(D3D11GPUContext *pContext, D3D11GPUShaderProgram *pCurrentProgram) { #ifdef LAZY_RESOURCE_CLEANUP_AFTER_SWITCH ID3D11DeviceContext *pD3DDeviceContext = pContext->GetD3DContext(); DebugAssert(m_pBoundContext == nullptr && pCurrentProgram->m_pBoundContext == pContext); // ------------------ IA ------------------ if (m_pD3DInputLayout != nullptr) pD3DDeviceContext->IASetInputLayout(m_pD3DInputLayout); else if (pCurrentProgram->m_pD3DInputLayout != nullptr) pD3DDeviceContext->IASetInputLayout(nullptr); // ------------------ VS ------------------ if (m_pD3DVertexShader != nullptr) pD3DDeviceContext->VSSetShader(m_pD3DVertexShader, nullptr, 0); else if (pCurrentProgram->m_pD3DVertexShader != nullptr) pD3DDeviceContext->VSSetShader(nullptr, nullptr, 0); // ------------------ HS ------------------ if (m_pD3DHullShader != nullptr) pD3DDeviceContext->HSSetShader(m_pD3DHullShader, nullptr, 0); else if (pCurrentProgram->m_pD3DHullShader != nullptr) pD3DDeviceContext->HSSetShader(nullptr, nullptr, 0); // ------------------ DS ------------------ if (m_pD3DDomainShader != nullptr) pD3DDeviceContext->DSSetShader(m_pD3DDomainShader, nullptr, 0); else if (pCurrentProgram->m_pD3DDomainShader != nullptr) pD3DDeviceContext->DSSetShader(nullptr, nullptr, 0); // ------------------ GS ------------------ if (m_pD3DGeometryShader != nullptr) pD3DDeviceContext->GSSetShader(m_pD3DGeometryShader, nullptr, 0); else if (pCurrentProgram->m_pD3DGeometryShader != nullptr) pD3DDeviceContext->GSSetShader(nullptr, nullptr, 0); // ------------------ PS ------------------ if (m_pD3DPixelShader != nullptr) pD3DDeviceContext->PSSetShader(m_pD3DPixelShader, nullptr, 0); else if (pCurrentProgram->m_pD3DPixelShader != nullptr) pD3DDeviceContext->PSSetShader(nullptr, nullptr, 0); // ------------------ CS ------------------ if (m_pD3DComputeShader != nullptr) pD3DDeviceContext->CSSetShader(m_pD3DComputeShader, nullptr, 0); else if (pCurrentProgram->m_pD3DComputeShader != nullptr) pD3DDeviceContext->CSSetShader(nullptr, nullptr, 0); // swap pointers pCurrentProgram->m_pBoundContext = nullptr; m_pBoundContext = pContext; // bind params InternalBindAutomaticParameters(pContext); #else pCurrentProgram->Unbind(pContext); Bind(pContext); #endif } void D3D11GPUShaderProgram::Unbind(D3D11GPUContext *pContext) { ID3D11DeviceContext *pD3DDeviceContext = m_pBoundContext->GetD3DContext(); DebugAssert(m_pBoundContext == pContext); #ifndef LAZY_RESOURCE_CLEANUP_AFTER_SWITCH // unset parameters that we match against for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { const Parameter *parameter = &m_parameters[parameterIndex]; for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (parameter->BindPoint[i] == -1) continue; switch (parameter->BindTarget) { case D3D_SHADER_BIND_TARGET_CONSTANT_BUFFER: pContext->SetShaderConstantBuffers((SHADER_PROGRAM_STAGE)i, parameter->BindPoint[i], nullptr); break; case D3D_SHADER_BIND_TARGET_RESOURCE: pContext->SetShaderResources((SHADER_PROGRAM_STAGE)i, parameter->BindPoint[i], nullptr); break; case D3D_SHADER_BIND_TARGET_SAMPLER: pContext->SetShaderSamplers((SHADER_PROGRAM_STAGE)i, parameter->BindPoint[i], nullptr); break; } } } #endif // ------------------ IA ------------------ if (m_pD3DInputLayout != nullptr) pD3DDeviceContext->IASetInputLayout(nullptr); // ------------------ VS ------------------ if (m_pD3DVertexShader != nullptr) pD3DDeviceContext->VSSetShader(nullptr, nullptr, 0); // ------------------ HS ------------------ if (m_pD3DHullShader != nullptr) pD3DDeviceContext->HSSetShader(nullptr, nullptr, 0); // ------------------ DS ------------------ if (m_pD3DDomainShader != nullptr) pD3DDeviceContext->DSSetShader(nullptr, nullptr, 0); // ------------------ GS ------------------ if (m_pD3DGeometryShader != nullptr) pD3DDeviceContext->GSSetShader(nullptr, nullptr, 0); // ------------------ PS ------------------ if (m_pD3DPixelShader != nullptr) pD3DDeviceContext->PSSetShader(nullptr, nullptr, 0); // ------------------ CSS ------------------ if (m_pD3DComputeShader != nullptr) pD3DDeviceContext->CSSetShader(nullptr, nullptr, 0); m_pBoundContext = nullptr; } void D3D11GPUShaderProgram::InternalSetParameterValue(D3D11GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue) { const Parameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(pContext == m_pBoundContext); uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); // should be attached to a local constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); // get the constant buffer ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D11GPUShaderProgram::InternalSetParameterValueArray(D3D11GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { const Parameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(pContext == m_pBoundContext); uint32 valueSize = ShaderParameterValueTypeSize(parameterInfo->Type); DebugAssert(parameterInfo->Type == valueType && valueSize > 0); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // should be attached to a local constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); // get the constant buffer ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pContext->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D11GPUShaderProgram::InternalSetParameterStruct(D3D11GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize) { const Parameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(pContext == m_pBoundContext); DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); // should be attached to a local constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); // get the constant buffer ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // write to the constant buffer pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, parameterInfo->ConstantBufferOffset, valueSize, pValue, false); } void D3D11GPUShaderProgram::InternalSetParameterStructArray(D3D11GPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { const Parameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(pContext == m_pBoundContext); DebugAssert(parameterInfo->Type == SHADER_PARAMETER_TYPE_STRUCT && valueSize <= parameterInfo->ArrayStride); DebugAssert(numElements > 0 && (firstElement + numElements) <= parameterInfo->ArraySize); // should be attached to a local constant buffer DebugAssert(parameterInfo->ConstantBufferIndex >= 0); // get the constant buffer ConstantBuffer *constantBuffer = &m_constantBuffers[parameterInfo->ConstantBufferIndex]; // if there is no padding, this can be done in a single operation uint32 bufferOffset = parameterInfo->ConstantBufferOffset + (firstElement * parameterInfo->ArrayStride); if (valueSize == parameterInfo->ArrayStride) pContext->WriteConstantBuffer(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, valueSize * numElements, pValue); else pContext->WriteConstantBufferStrided(constantBuffer->EngineConstantBufferIndex, parameterIndex, bufferOffset, parameterInfo->ArrayStride, valueSize, numElements, pValue); } void D3D11GPUShaderProgram::InternalSetParameterResource(D3D11GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, GPUSamplerState *pLinkedSamplerState) { const Parameter *parameterInfo = &m_parameters[parameterIndex]; DebugAssert(pContext == m_pBoundContext); // // handle type mismatches // if (pResource != nullptr) // { // GPU_RESOURCE_TYPE expectedResourceType = ShaderParameterResourceType(parameterInfo->Type); // if (pResource->GetResourceType() != expectedResourceType) // { // Log_WarningPrintf("D3D11GPUShaderProgram::InternalSetParameterResource: Parameter %u type mismatch (expecting %s, got %s for ptype %s), setting to null", parameterIndex, NameTable_GetNameString(NameTables::GPUResourceType, expectedResourceType), NameTable_GetNameString(NameTables::GPUResourceType, pResource->GetResourceType()), NameTable_GetNameString(NameTables::ShaderParameterType, parameterInfo->Type)); // return; // } // } // branch out according to target switch (parameterInfo->BindTarget) { case D3D_SHADER_BIND_TARGET_CONSTANT_BUFFER: { ID3D11Buffer *pD3DBuffer = (pResource != nullptr) ? static_cast<D3D11GPUBuffer *>(pResource)->GetD3DBuffer() : nullptr; for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderConstantBuffers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DBuffer); } } break; case D3D_SHADER_BIND_TARGET_RESOURCE: { ID3D11ShaderResourceView *pD3DSRV = (pResource != nullptr) ? D3D11Helpers::GetResourceShaderResourceView(pResource) : nullptr; for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderResources((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DSRV); } } break; case D3D_SHADER_BIND_TARGET_SAMPLER: { ID3D11SamplerState *pD3DSamplerState = (pResource != nullptr) ? D3D11Helpers::GetResourceSamplerState(pResource) : nullptr; for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DSamplerState); } } break; case D3D_SHADER_BIND_TARGET_UNORDERED_ACCESS_VIEW: { ID3D11UnorderedAccessView *pD3DUAV = (pResource != nullptr && pResource->GetResourceType() == GPU_RESOURCE_TYPE_COMPUTE_VIEW) ? static_cast<D3D11GPUComputeView *>(pResource)->GetD3DUAV() : nullptr; for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = parameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderUAVs((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DUAV); } } break; } // for texture types with a linked sampler state, update it if (parameterInfo->LinkedSamplerIndex >= 0) { const Parameter *samplerParameterInfo = &m_parameters[parameterInfo->LinkedSamplerIndex]; DebugAssert(samplerParameterInfo->Type == SHADER_PARAMETER_TYPE_SAMPLER_STATE && samplerParameterInfo->BindTarget == D3D_SHADER_BIND_TARGET_SAMPLER); // write to stages ID3D11SamplerState *pD3DSamplerState = (pResource != nullptr) ? D3D11Helpers::GetResourceSamplerState((pLinkedSamplerState != nullptr) ? pLinkedSamplerState : pResource) : nullptr; for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { int32 bindPoint = samplerParameterInfo->BindPoint[stageIndex]; if (bindPoint >= 0) pContext->SetShaderSamplers((SHADER_PROGRAM_STAGE)stageIndex, bindPoint, pD3DSamplerState); } } } uint32 D3D11GPUShaderProgram::GetParameterCount() const { return m_parameters.GetSize(); } void D3D11GPUShaderProgram::GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) { const Parameter *parameter = &m_parameters[index]; *name = parameter->Name; *type = parameter->Type; *arraySize = parameter->ArraySize; } GPUShaderProgram *D3D11GPUDevice::CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) { D3D11GPUShaderProgram *pProgram = new D3D11GPUShaderProgram(); if (!pProgram->Create(this, pVertexElements, nVertexElements, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } GPUShaderProgram *D3D11GPUDevice::CreateComputeProgram(ByteStream *pByteCodeStream) { D3D11GPUShaderProgram *pProgram = new D3D11GPUShaderProgram(); if (!pProgram->Create(this, nullptr, 0, pByteCodeStream)) { pProgram->Release(); return nullptr; } return pProgram; } <file_sep>/Engine/Source/Engine/ParticleSystem.h #pragma once #include "Engine/Common.h" #include "Engine/ParticleSystemCommon.h" #include "Engine/ParticleSystemEmitter.h" #include "Engine/ParticleSystemModule.h" class ParticleSystemGenerator; class ParticleSystem : public Resource { DECLARE_RESOURCE_TYPE_INFO(ParticleSystem, Resource); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystem); // public: // struct InstanceData // { // ParticleSystemEmitter::InstanceData *pEmitterData; // ParticleSystemEmitter::InstanceRenderData *pEmitterRenderData; // uint32 EmitterCount; // }; public: ParticleSystem(const ResourceTypeInfo *pTypeInfo = &s_TypeInfo); virtual ~ParticleSystem(); // Emitter management const ParticleSystemEmitter *GetEmitter(uint32 emitterIndex) const { return m_emitters[emitterIndex]; } const uint32 GetEmitterCount() const { return m_emitters.GetSize(); } void AddEmitter(const ParticleSystemEmitter *pEmitter); void RemoveEmitter(const ParticleSystemEmitter *pEmitter); // Update interval const float GetUpdateInterval() const { return m_updateInterval; } // // Instance initialization // bool InitializeInstance(InstanceData *pInstanceData) const; // // // Instance cleanup // void CleanupInstance(InstanceData *pInstanceData) const; // // // Instance update // void UpdateInstance(InstanceData *pInstanceData, const Transform *pBaseTransform, float deltaTime) const; // // // Render-thread instance update // void UpdateInstanceRenderData(InstanceData *pInstanceData) const; // load from serialized bool LoadFromStream(const char *name, ByteStream *pStream); private: PODArray<const ParticleSystemEmitter *> m_emitters; float m_updateInterval; }; <file_sep>/Tests/Source/TestMath.cpp #include "MathLib/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/Matrixf.h" #include "YBaseLib/String.h" #include "YBaseLib/Timer.h" #include "MathLib/Frustum.h" #include "YBaseLib/Log.h" #include "YBaseLib/StringConverter.h" #include "MathLib/StringConverters.h" #include <cstdio> #include <cstdlib> #include <functional> #include <algorithm> Log_SetChannel(TestMath); #include "YBaseLib/Functor.h" #include "MathLib/Quaternion.h" #include "YBaseLib/MemArray.h" #include "YBaseLib/AutoReleasePtr.h" #include "YBaseLib/ByteStream.h" #include "Core/RandomNumberGenerator.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/FileSystem.h" #include "Core/MeshUtilties.h" float randfloat(float fMax = 9999.0f) { float fv = rand() / (float)RAND_MAX; return fv * fMax; } #if Y_COMPILER_MSVC __declspec(noinline) #endif void printvec(const char *name, const Vector4f &v) { printf("%s %f %f %f %f\n", name, v.x, v.y, v.z, v.w); } #if Y_COMPILER_MSVC __declspec(noinline) #endif void printmat(const char *name, const Matrix4x4f &m) { printvec(name, m[0]); printvec(name, m[1]); printvec(name, m[2]); printvec(name, m[3]); } class test { public: void method() { printf("blah\n"); } void method1(uint32 n) { printf("blah %u\n", n); } }; //__declspec(align(16)) struct aligned16 //{ // float x[4]; //}; //int main(int argc, char *argv[]) //{ // { // Vector4 v1 = Vector4(5, 6, 7, 8); // Vector4 v2 = Vector4(5, 6, 7, 8); // // Vector4 acc1 = Vector4::Zero; // Vector4 acc2 = Vector4(0, 0, 0, 0); // // Timer t; // uint32 i; // // t.Reset(); // for (i = 0; i < 50000000; i++) // acc1 += v1.Normalize(); // printf("%.4f %f %f %f %f\n", t.GetTimeMilliseconds(), acc1.x, acc1.y, acc1.z, acc1.w); // // t.Reset(); // for (i = 0; i < 50000000; i++) // acc2 += v2.Normalize(); // printf("%.4f %f %f %f %f\n", t.GetTimeMilliseconds(), acc2.x, acc2.y, acc2.z, acc2.w); // } // Vector4 test(1, 2, 3, 4); // Vector2 test3 = test.xy(); // Vector3 test2 = test.xyz(); // test *ptest = new test(); // Functor *pf = MakeFunctor(ptest, &test::method); // Functor *pf1 = MakeFunctor(ptest, &test::method1, (uint32)1); // // pf->Invoke(); // pf1->Invoke(); // // pf1->Release(); // pf->Release(); // delete ptest; //Matrix4 m1 = Make4x4VerticalFoVPerspectiveProjectionMatrix(Math::DegreesToRadians(60.0f), 640, 480, 1.0f, 100.0f); //Matrix4 m2 = Make4x4VerticalFoVPerspectiveProjectionMatrix(Math::DegreesToRadians(60.0f), 640, 480, 1.0f + 0.001f, 100.0f + 0.001f); //Matrix4 m3 = Make4x4VerticalFoVPerspectiveProjectionMatrix(Math::DegreesToRadians(60.0f), 640, 480, 1.0f + 0.5f, 100.0f + 0.5f); //float t1 = m1.m22 + 0.001f * m1.m22; //float t2 = 0.001f * m1.m23; // float f1_12 = m2.m22 / m1.m22; // float f2_12 = m2.m23 / m1.m23; // float f1_13 = m3.m22 / m1.m22; // float f2_13 = m3.m23 / m1.m23; // // float np2 = -m2.m23 / m2.m22; // float fp2 = m2.m23 / (1.0f - m2.m22); // // Frustum f; // f.SetFromMatrix(m3); //Quaternion q = Quaternion::FromRotationYXZ(Math::DegreesToRadians(-90.0f), 0.0f, 0.0f); // Timer t; // // Vector3 temp(StringConverter::StringToVector3("1.0 2.0 3.0")); // Vector3 tempa(temp * temp); // Vector3 tempb((tempa * tempa).Normalize()); // // for (uint32 i = 0; i < 100000000; i++) // { // tempb *= tempa; // tempa /= tempb; // tempb += tempa; // } // // float3 temp_f(tempb.GetFloat3()); // printf("%f %f %f\n", temp_f.x, temp_f.y, temp_f.z); // printf("%.4fmsec\n", t.GetTimeMilliseconds()); // float3 v(Math::DegreesToRadians(50),Math::DegreesToRadians(100), Math::DegreesToRadians(270)); // // //Quaternion q(Quaternion::FromEulerAngles(v).Normalize()); // //Quaternion q(-0.683013, -0.298836, 0.640856, -0.183013); // Quaternion q(-0.707106829, 0.0f, 0.0f, 0.707106829f); // q.NormalizeInPlace(); // //float4x4 m1(float4x4::MakeRotationFromEulerAnglesMatrix(v)); // float4x4 mq(q.GetFloat4x4()); // //printmat("m1", m1); // printmat("mq", mq); // Quaternion mq_q(Quaternion::FromFloat4x4(mq)); // // float3 src(1, 2, 3); // float3 r1(q * src); // float3 r1q(mq.TransformPoint(src)); // float3 r2(mq_q * src); //Quaternion quat(Quaternion::FromEulerAngles(50.0f, 0.0f, 0.0f)); //float3 euler(quat.GetEulerAngles()); // euler.x = Math::RadiansToDegrees(euler.x); // euler.y = Math::RadiansToDegrees(euler.y); // euler.z = Math::RadiansToDegrees(euler.z); // int x = 5; // Quaternion temp(Quaternion::Identity); // aligned16 a16; // // auto func = [x, temp, a16]() // { // printf("%i", x); // }; // // func(); // int y = sizeof(func); // //void(*fptr)() = func; // std::function<void()> fptr = func; // int z = sizeof(fptr); // fptr(); // // return 0; // } // class cb_base // { // public: // virtual ~cb_base() {} // virtual void execute() = 0; // }; // // template<class T> // class cb_impl : public cb_base // { // T val; // // public: // cb_impl(const T & val_) : val(val_) {} // // virtual void execute() // { // val(); // } // }; // // struct q_entry // { // cb_base *ptr; // int size; // }; // // MemArray<cb_base *> q_entries; // // template<class T> // void add_to_q(const T &val) // { // //cb_impl<T> *vp = new cb_impl<T>(val); // cb_impl<T> *vp = (cb_impl<T> *)malloc(sizeof(cb_impl<T>)); // new (vp)cb_impl<T>(val); // q_entries.Add(vp); // } // // void drain_q() // { // printf("drain_q()\n"); // while (q_entries.GetSize() > 0) // { // cb_base *vp; // q_entries.PopFront(&vp); // vp->execute(); // //delete vp; // vp->~cb_base(); // free(vp); // } // } // // void inner() // { // Quaternion q(Quaternion::Identity); // float3 v(float3::One); // AutoReleasePtr<ByteStream> s = ByteStream_CreateGrowableMemoryStream(); // // add_to_q([q, v, s]() { // printf("inside lambda, %f %f %f\n", v.x, v.y, v.z); // //bool b = s.IsNull(); // }); // } // // static std::initializer_list<int> i_x = { 5, 10, 15, 20 }; // // int main(int argc, char *argv[]) // { // //inner(); // //drain_q(); // // int c = 0; // for (size_t i = 0; i < i_x.size(); i++) // c += *(i_x.begin() + i); // // printf("%d", c); // return 0; // } // int main(int argc, char *argv[]) // { // RandomNumberGenerator rng; // /*for (uint32 i = 0; i < 32; i++) // { // float x = rng.NextRangeFloat(-1.0f, 1.0f); // float y = rng.NextRangeFloat(-1.0f, 1.0f); // float z = rng.NextRangeFloat(0.0f, 1.0f); // float3 val(x, y, z); // val.NormalizeInPlace(); // printf("float3(%f, %f, %f),\n", val.x, val.y, val.z); // }*/ // // Image img; // uint32 sz = 64; // img.Create(PIXEL_FORMAT_R8G8B8A8_UNORM, sz, sz, 1); // for (uint32 y = 0; y < sz; y++) // { // byte *pData = img.GetData() + (y * img.GetDataRowPitch()); // for (uint32 x = 0; x < sz; x++) // { // float nx = rng.NextRangeFloat(-1.0f, 1.0f); // float ny = rng.NextRangeFloat(-1.0f, 1.0f); // float3 nrm(nx, ny, 0.0f); // nrm.NormalizeInPlace(); // // nrm *= 0.5f; // nrm += 0.5f; // *pData++ = (byte)Math::Truncate(Math::Clamp(nrm.x * 255.0f, 0.0f, 255.0f)); // *pData++ = (byte)Math::Truncate(Math::Clamp(nrm.y * 255.0f, 0.0f, 255.0f)); // *pData++ = (byte)Math::Truncate(Math::Clamp(nrm.z * 255.0f, 0.0f, 255.0f)); // *pData++ = 255; // } // } // // const char *filename = "D:\\random.png"; // ImageCodec *codec = ImageCodec::GetImageCodecForFileName(filename); // ByteStream *pStream = FileSystem::OpenFile(filename, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); // codec->EncodeImage(filename, pStream, &img); // pStream->Release(); // // return 0; // } int main__(int argc, char *argv[]) { Log::GetInstance().SetConsoleOutputParams(true); Log::GetInstance().SetDebugOutputParams(true); /*{ float4x4 rotMat(float4x4::MakeRotationMatrixZ(90.0f)); float4x4 preTransMat(float4x4::MakeTranslationMatrix(-0.5f, -0.5f, -0.5f)); float4x4 postTransMat(float4x4::MakeTranslationMatrix(0.5f, 0.5f, 0.5f)); float4x4 resMat(postTransMat * rotMat * preTransMat); Log_DevPrintf("{ { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff } }", resMat.m00, resMat.m01, resMat.m02, resMat.m03, resMat.m10, resMat.m11, resMat.m12, resMat.m13, resMat.m20, resMat.m21, resMat.m22, resMat.m23); } { float4x4 rotMat(float4x4::MakeRotationMatrixZ(180.0f)); float4x4 preTransMat(float4x4::MakeTranslationMatrix(-0.5f, -0.5f, -0.5f)); float4x4 postTransMat(float4x4::MakeTranslationMatrix(0.5f, 0.5f, 0.5f)); float4x4 resMat(postTransMat * rotMat * preTransMat); Log_DevPrintf("{ { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff } }", resMat.m00, resMat.m01, resMat.m02, resMat.m03, resMat.m10, resMat.m11, resMat.m12, resMat.m13, resMat.m20, resMat.m21, resMat.m22, resMat.m23); } { float4x4 rotMat(float4x4::MakeRotationMatrixZ(270.0f)); float4x4 preTransMat(float4x4::MakeTranslationMatrix(-0.5f, -0.5f, -0.5f)); float4x4 postTransMat(float4x4::MakeTranslationMatrix(0.5f, 0.5f, 0.5f)); float4x4 resMat(postTransMat * rotMat * preTransMat); Log_DevPrintf("{ { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff }, { %.6ff, %.6ff, %.6ff, %.6ff } }", resMat.m00, resMat.m01, resMat.m02, resMat.m03, resMat.m10, resMat.m11, resMat.m12, resMat.m13, resMat.m20, resMat.m21, resMat.m22, resMat.m23); }*/ static const float CUBE_FACE_TANGENTS[CUBE_FACE_COUNT][3] = { { 0, -1, 0 }, // RIGHT { 0, -1, 0 }, // LEFT { 1, 0, 0 }, // BACK { 1, 0, 0 }, // FRONT { 1, 0, 0 }, // TOP { 1, 0, 0 }, // BOTTOM }; static const float CUBE_FACE_BINORMALS[CUBE_FACE_COUNT][3] = { { 0, 0, -1 }, // RIGHT { 0, 0, -1 }, // LEFT { 0, 0, -1 }, // BACK { 0, 0, -1 }, // FRONT { 0, -1, 0 }, // TOP { 0, -1, 0 }, // BOTTOM }; static const float CUBE_FACE_NORMALS[CUBE_FACE_COUNT][3] = { { 1, 0, 0 }, // RIGHT { -1, 0, 0 }, // LEFT { 0, 1, 0 }, // BACK { 0, -1, 0 }, // FRONT { 0, 0, 1 }, // TOP { 0, 0, -1 }, // BOTTOM }; for (uint32 i = 0; i < 6; i++) { Vector3f outTangent; float outBinormalSign; MeshUtilites::OrthogonalizeTangent(CUBE_FACE_TANGENTS[i], CUBE_FACE_BINORMALS[i], CUBE_FACE_NORMALS[i], outTangent, outBinormalSign); uint32 packedTangentAndSign, packedNormal; union { uint32 asUInt32; int8 asInt8[4]; } converter; converter.asInt8[0] = (int8)Math::Clamp(outTangent.x * 127.0f, -127.0f, 127.0f); converter.asInt8[1] = (int8)Math::Clamp(outTangent.y * 127.0f, -127.0f, 127.0f); converter.asInt8[2] = (int8)Math::Clamp(outTangent.z * 127.0f, -127.0f, 127.0f); converter.asInt8[3] = (int8)Math::Clamp(outBinormalSign * 127.0f, -127.0f, 127.0f); packedTangentAndSign = converter.asUInt32; converter.asInt8[0] = (int8)Math::Clamp(CUBE_FACE_NORMALS[i][0] * 127.0f, -127.0f, 127.0f); converter.asInt8[1] = (int8)Math::Clamp(CUBE_FACE_NORMALS[i][1] * 127.0f, -127.0f, 127.0f); converter.asInt8[2] = (int8)Math::Clamp(CUBE_FACE_NORMALS[i][2] * 127.0f, -127.0f, 127.0f); converter.asInt8[3] = (int8)0; packedNormal = converter.asUInt32; Log_DevPrintf("{ 0x%08X, 0x%08X },", packedTangentAndSign, packedNormal); } return 0; } <file_sep>/Editor/Source/Editor/MapEditor/EditorWorldOutlinerWidget.h #pragma once #include "Editor/Common.h" #include "Editor/SimpleTreeModel.h" class EditorMap; class EditorMapEntity; class EditorWorldOutlinerModel; class EditorWorldOutlinerWidget : public QWidget { Q_OBJECT public: EditorWorldOutlinerWidget(QWidget *pParent); virtual ~EditorWorldOutlinerWidget(); // called when map is removed void Clear(); // entity interface void AddEntity(const EditorMapEntity *pEntity); void OnEntityPositionChanged(const EditorMapEntity *pEntity); void RemoveEntity(const EditorMapEntity *pEntity); Q_SIGNALS: void OnEntitySelected(const EditorMapEntity *pEntity); void OnEntityActivated(const EditorMapEntity *pEntity); private Q_SLOTS: void OnTreeViewItemClicked(const QModelIndex &index); void OnTreeViewItemActivated(const QModelIndex &index); private: // ui elements QLineEdit *m_pSearchBox; QTreeView *m_pTreeView; // lazy, so we copy to this model SimpleTreeModel m_model; // various headers SimpleTreeModel::Container *m_pEntityContainer; SimpleTreeModel::Container *m_pVolumesContainer; }; <file_sep>/Engine/Source/Engine/Font.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Font.h" #include "Engine/Texture.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" #include "Renderer/Renderer.h" Log_SetChannel(Font); namespace NameTables { Y_Define_NameTable(FontType) Y_NameTable_VEntry(FONT_TYPE_BITMAP, "Bitmap") Y_NameTable_VEntry(FONT_TYPE_SIGNED_DISTANCE_FIELD, "SignedDistanceField") Y_NameTable_End() } DEFINE_RESOURCE_TYPE_INFO(Font); DEFINE_RESOURCE_GENERIC_FACTORY(Font); Font::Font(const ResourceTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_bestRenderingSize(0) { } Font::~Font() { for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (m_textures[i] != nullptr) m_textures[i]->Release(); } } bool Font::LoadFromStream(const char *fontName, ByteStream *pStream) { uint64 headerOffset = pStream->GetPosition(); // read header DF_FONT_HEADER header; if (!pStream->Read2(&header, sizeof(header)) || header.Magic != DF_FONT_HEADER_MAGIC || header.Size < sizeof(header) || header.CharacterDataCount == 0) { Log_ErrorPrintf("Font file '%s' is invalid or corrupted.", fontName); return false; } // alloc characters and textures m_strName = fontName; m_bestRenderingSize = header.BestRenderingSize; // allocate characters m_characterData.Resize(header.CharacterDataCount); // read characters { // seek to characters DF_FONT_CHARACTER *pFileCharacters = new DF_FONT_CHARACTER[m_characterData.GetSize()]; if (!pStream->SeekAbsolute(headerOffset + (uint64)header.CharacterDataOffset) || !pStream->Read2(pFileCharacters, sizeof(DF_FONT_CHARACTER) * m_characterData.GetSize())) { Log_ErrorPrintf("Font file '%s' is invalid or corrupted.", fontName); delete[] pFileCharacters; return false; } // parse them for (uint32 characterIndex = 0; characterIndex < m_characterData.GetSize(); characterIndex++) { const DF_FONT_CHARACTER *pSourceCharacter = &pFileCharacters[characterIndex]; CharacterData *pDestCharacter = &m_characterData[characterIndex]; pDestCharacter->CodePoint = pSourceCharacter->CodePoint; pDestCharacter->StartU = pSourceCharacter->StartU; pDestCharacter->EndU = pSourceCharacter->EndU; pDestCharacter->StartV = pSourceCharacter->StartV; pDestCharacter->EndV = pSourceCharacter->EndV; pDestCharacter->DrawOffsetX = pSourceCharacter->DrawOffsetX; pDestCharacter->DrawOffsetY = pSourceCharacter->DrawOffsetY; pDestCharacter->DrawWidth = pSourceCharacter->DrawWidth; pDestCharacter->DrawHeight = pSourceCharacter->DrawHeight; pDestCharacter->Advance = pSourceCharacter->Advance; pDestCharacter->TextureIndex = pSourceCharacter->TextureIndex; pDestCharacter->IsWhiteSpace = pSourceCharacter->IsWhiteSpace; } // cleanup delete[] pFileCharacters; } // allocate textures if (header.TextureCount > 0) { SmallString textureName; m_textures.Resize(header.TextureCount); m_textures.ZeroContents(); uint64 nextTextureOffset = headerOffset + (uint64)header.TextureOffset; for (uint32 textureIndex = 0; textureIndex < m_textures.GetSize(); textureIndex++) { if (!pStream->SeekAbsolute(nextTextureOffset)) return false; DF_FONT_TEXTURE fontTexture; if (!pStream->Read2(&fontTexture, sizeof(fontTexture)) || fontTexture.TextureType != TEXTURE_TYPE_2D) return false; // calc next texture offset nextTextureOffset += sizeof(fontTexture) + (uint64)fontTexture.TextureSize; // read texture Texture2D *pTexture = new Texture2D(); textureName.Format("%s_tex%u", fontName, textureIndex); if (!pTexture->Load(textureName, pStream)) { Log_ErrorPrintf("Failed to load font texture %u", textureIndex); pTexture->Release(); return false; } m_textures[textureIndex] = pTexture; } } return true; } const Font::CharacterData *Font::GetCharacterDataForCodePoint(uint32 codePoint) const { // binary search the character array const CharacterData *pFoundData = m_characterData.BinarySearchKey<uint32>(codePoint, [](const uint32 *pCodePoint, const CharacterData *pCharacterData) { return (int32)*pCodePoint - (int32)pCharacterData->CodePoint; }); DebugAssert(pFoundData == nullptr || pFoundData->CodePoint == codePoint); return pFoundData; } uint32 Font::GetTextWidth(const char *Text, uint32 nCharacters, float Scale) const { // uint32 i; // const CharacterData *pCharacterData; // float Width = 0.0f; // // for (i = 0; i < nCharacters; i++) // { // pCharacterData = GetCharacterData(Text[i]); // if (pCharacterData != NULL) // { // float f = Y_ceilf((float)pCharacterData->x1 - (float)pCharacterData->x0); // if (f > Y_ceilf(pCharacterData->xAdvance)) // Width += Y_ceilf(f * Scale); // else // Width += Y_ceilf(pCharacterData->xAdvance * Scale); // } // } // // return (uint32)Y_ceilf(Width); if (nCharacters == 0) return 0; uint32 i; const CharacterData *pCharacterData; uint32 Width = 0; for (i = 0; i < nCharacters; i++) { pCharacterData = GetCharacterDataForCodePoint(Text[i]); if (pCharacterData != nullptr) { // use max of scaled glyph width and xadvance for last character if (i == (nCharacters - 1) && !pCharacterData->IsWhiteSpace) { float scaledWidth = (pCharacterData->DrawOffsetX + pCharacterData->DrawWidth) * Scale; Width += (uint32)Y_roundf(Max(scaledWidth, pCharacterData->Advance * Scale)); } else { // as normal Width += (uint32)Y_roundf(pCharacterData->Advance * Scale); } } } return Width; } bool Font::CreateDeviceResources() const { for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (!m_textures[i]->CreateDeviceResources()) return false; } return true; } void Font::ReleaseDeviceResources() const { for (uint32 i = 0; i < m_textures.GetSize(); i++) m_textures[i]->ReleaseDeviceResources(); } <file_sep>/Engine/Source/Core/ObjectTypeInfo.cpp #include "Core/PrecompiledHeader.h" #include "Core/ObjectTypeInfo.h" ObjectTypeInfo::RegistryType &ObjectTypeInfo::GetRegistry() { static RegistryType s_Registry; return s_Registry; } ObjectTypeInfo::ObjectTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory) : m_iTypeIndex(INVALID_OBJECT_TYPE_INDEX), m_iInheritanceDepth(0), m_strTypeName(TypeName), m_pParentType(pParentTypeInfo), m_pFactory(pFactory), m_pSourcePropertyDeclarations(pPropertyDeclarations), m_ppPropertyDeclarations(NULL), m_nPropertyDeclarations(0) { } ObjectTypeInfo::~ObjectTypeInfo() { //DebugAssert(m_iTypeIndex == INVALID_TYPE_INDEX); } bool ObjectTypeInfo::IsDerived(const ObjectTypeInfo *pTypeInfo) const { const ObjectTypeInfo *pCur = this; do { if (pCur == pTypeInfo) return true; pCur = pCur->m_pParentType; } while (pCur != NULL); return false; } const PROPERTY_DECLARATION *ObjectTypeInfo::GetPropertyDeclarationByName(const char *PropertyName) const { for (uint32 i = 0; i < m_nPropertyDeclarations; i++) { if (!Y_stricmp(m_ppPropertyDeclarations[i]->Name, PropertyName)) return m_ppPropertyDeclarations[i]; } return nullptr; } void ObjectTypeInfo::RegisterType() { if (m_iTypeIndex != INVALID_OBJECT_TYPE_INDEX) return; // our stuff const ObjectTypeInfo *pCurrentTypeInfo; const PROPERTY_DECLARATION *pPropertyDeclaration; uint32 i; // get property count pCurrentTypeInfo = this; m_nPropertyDeclarations = 0; m_iInheritanceDepth = 0; while (pCurrentTypeInfo != nullptr) { if (pCurrentTypeInfo->m_pSourcePropertyDeclarations != nullptr) { pPropertyDeclaration = pCurrentTypeInfo->m_pSourcePropertyDeclarations; while (pPropertyDeclaration->Name != nullptr) { m_nPropertyDeclarations++; pPropertyDeclaration++; } } pCurrentTypeInfo = pCurrentTypeInfo->GetParentType(); m_iInheritanceDepth++; } if (m_nPropertyDeclarations > 0) { m_ppPropertyDeclarations = new const PROPERTY_DECLARATION *[m_nPropertyDeclarations]; pCurrentTypeInfo = this; i = 0; while (pCurrentTypeInfo != nullptr) { if (pCurrentTypeInfo->m_pSourcePropertyDeclarations != nullptr) { pPropertyDeclaration = pCurrentTypeInfo->m_pSourcePropertyDeclarations; while (pPropertyDeclaration->Name != nullptr) { DebugAssert(i < m_nPropertyDeclarations); m_ppPropertyDeclarations[i++] = pPropertyDeclaration++; } } pCurrentTypeInfo = pCurrentTypeInfo->GetParentType(); } } m_iTypeIndex = GetRegistry().RegisterTypeInfo(this, m_strTypeName, m_iInheritanceDepth); } void ObjectTypeInfo::UnregisterType() { if (m_iTypeIndex == INVALID_OBJECT_TYPE_INDEX) return; delete[] m_ppPropertyDeclarations; m_ppPropertyDeclarations = nullptr; m_nPropertyDeclarations = 0; m_iTypeIndex = INVALID_OBJECT_TYPE_INDEX; GetRegistry().UnregisterTypeInfo(this); } <file_sep>/Editor/Source/Editor/ResourceBrowser/EditorResourceBrowserWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/ToolMenuWidget.h" #include "Editor/ResourceBrowser/EditorResourceBrowserWidget.h" #include "Editor/ResourceBrowser/EditorStaticMeshImportDialog.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorEditMode.h" #include "Editor/EditorResourceSelectionDialogModel.h" #include "Editor/EditorProgressDialog.h" #include "Editor/Editor.h" #include "Engine/BlockMesh.h" #include "Editor/BlockMeshEditor/EditorBlockMeshEditor.h" #include "Engine/SkeletalAnimation.h" #include "Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.h" #include "Engine/SkeletalMesh.h" #include "Editor/SkeletalMeshEditor/EditorSkeletalMeshEditor.h" #include "Engine/StaticMesh.h" #include "Editor/StaticMeshEditor/EditorStaticMeshEditor.h" static const uint32 PREVIEW_ICON_SIZE = 96; struct Ui_EditorResourceBrowserWidget { ToolMenuWidget *toolbar; QAction *actionDirectoryBack; QAction *actionDirectoryUp; QAction *actionNewDirectory; QAction *actionDeleteResource; QAction *actionImportStaticMesh; QAction *actionInsertResource; QAction *actionEditBlockMesh; QAction *actionEditSkeletalAnimation; QAction *actionEditSkeletalMesh; QAction *actionEditStaticMesh; EditorResourceSelectionDialogModel *directoryTreeModel; EditorResourceSelectionDialogModel *resourceListModel; QTreeView *directoryTree; QListView *resourceList; void CreateUI(QWidget *root) { QVBoxLayout *rootLayout = new QVBoxLayout(); root->setMinimumSize(300, 200); root->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); // actions { actionDirectoryBack = new QAction(root->tr("Back"), root); actionDirectoryBack->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionDirectoryUp = new QAction(root->tr("Up"), root); actionDirectoryUp->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionNewDirectory = new QAction(root->tr("New Directory"), root); actionNewDirectory->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionDeleteResource = new QAction(root->tr("Delete Resource"), root); actionDeleteResource->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionImportStaticMesh = new QAction(root->tr("Import Static Mesh..."), root); actionImportStaticMesh->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionInsertResource = new QAction(root->tr("Insert Resource"), root); actionEditBlockMesh = new QAction(root->tr("Edit Block Mesh..."), root); actionEditSkeletalAnimation = new QAction(root->tr("Edit Skeletal Animation..."), root); actionEditSkeletalMesh = new QAction(root->tr("Edit Skeletal Mesh..."), root); actionEditStaticMesh = new QAction(root->tr("Edit Static Mesh..."), root); } // toolbar { toolbar = new ToolMenuWidget(root, Qt::Horizontal, false); toolbar->addAction(actionDirectoryBack); toolbar->addAction(actionDirectoryUp); toolbar->addSeperator(); toolbar->addAction(actionNewDirectory); toolbar->addAction(actionDeleteResource); toolbar->addSeperator(); toolbar->addAction(actionImportStaticMesh); rootLayout->addWidget(toolbar); } // models { directoryTreeModel = new EditorResourceSelectionDialogModel(EmptyString, true, false, PREVIEW_ICON_SIZE, root); resourceListModel = new EditorResourceSelectionDialogModel(EmptyString, false, true, PREVIEW_ICON_SIZE, root); } // bottom half - splitter { QSplitter *bottomSplitter = new QSplitter(root); directoryTree = new QTreeView(bottomSplitter); directoryTree->setMaximumWidth(150); directoryTree->setModel(directoryTreeModel); directoryTree->hideColumn(1); directoryTree->hideColumn(2); directoryTree->setHeaderHidden(true); bottomSplitter->addWidget(directoryTree); resourceList = new QListView(bottomSplitter); resourceList->setModel(resourceListModel); resourceList->setViewMode(QListView::ListMode); resourceList->setIconSize(QSize(PREVIEW_ICON_SIZE, PREVIEW_ICON_SIZE)); resourceList->setContextMenuPolicy(Qt::ActionsContextMenu); bottomSplitter->addWidget(resourceList); rootLayout->addWidget(bottomSplitter, 1); } root->setLayout(rootLayout); } void SetResourceListActionsForResourceType(const ResourceTypeInfo *pTypeInfo) { // clear everything out while (resourceList->actions().size() > 0) resourceList->removeAction(resourceList->actions().at(0)); // don't bother checking if nothing is specified if (pTypeInfo == nullptr) return; // type specific if (pTypeInfo == OBJECT_TYPEINFO(BlockMesh)) { resourceList->addAction(actionInsertResource); resourceList->addAction(actionEditBlockMesh); } else if (pTypeInfo == OBJECT_TYPEINFO(SkeletalAnimation)) { resourceList->addAction(actionEditSkeletalAnimation); } else if (pTypeInfo == OBJECT_TYPEINFO(SkeletalMesh)) { resourceList->addAction(actionInsertResource); resourceList->addAction(actionEditSkeletalMesh); } else if (pTypeInfo == OBJECT_TYPEINFO(StaticMesh)) { resourceList->addAction(actionInsertResource); resourceList->addAction(actionEditStaticMesh); } } }; void EditorResourceBrowserWidget::ConnectUIEvents() { connect(m_ui->actionDirectoryBack, SIGNAL(triggered()), this, SLOT(OnActionDirectoryBackTriggered())); connect(m_ui->actionDirectoryUp, SIGNAL(triggered()), this, SLOT(OnActionDirectoryUpTriggered())); connect(m_ui->actionNewDirectory, SIGNAL(triggered()), this, SLOT(OnActionNewDirectoryTriggered())); connect(m_ui->actionDeleteResource, SIGNAL(triggered()), this, SLOT(OnActionDeleteResourceTriggered())); connect(m_ui->actionImportStaticMesh, SIGNAL(triggered()), this, SLOT(OnActionImportStaticMeshTriggered())); connect(m_ui->actionInsertResource, SIGNAL(triggered()), this, SLOT(OnActionInsertResourceTriggered())); connect(m_ui->actionEditBlockMesh, SIGNAL(triggered()), this, SLOT(OnActionEditBlockMeshTriggered())); connect(m_ui->actionEditSkeletalAnimation, SIGNAL(triggered()), this, SLOT(OnActionEditSkeletalAnimationTriggered())); connect(m_ui->actionEditSkeletalMesh, SIGNAL(triggered()), this, SLOT(OnActionEditSkeletalMeshTriggered())); connect(m_ui->actionEditStaticMesh, SIGNAL(triggered()), this, SLOT(OnActionEditStaticMeshTriggered())); connect(m_ui->directoryTree, SIGNAL(clicked(const QModelIndex &)), this, SLOT(OnDirectoryTreeItemClickedOrActivated(const QModelIndex &))); connect(m_ui->directoryTree, SIGNAL(activated(const QModelIndex &)), this, SLOT(OnDirectoryTreeItemClickedOrActivated(const QModelIndex &))); connect(m_ui->resourceList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(OnResourceListItemClicked(const QModelIndex &))); connect(m_ui->resourceList, SIGNAL(activated(const QModelIndex &)), this, SLOT(OnResourceListItemActivated(const QModelIndex &))); } EditorResourceBrowserWidget::EditorResourceBrowserWidget(EditorMapWindow *pMapWindow, QWidget *parent) : QWidget(parent), m_pMapWindow(pMapWindow), m_ui(new Ui_EditorResourceBrowserWidget()) { m_ui->CreateUI(this); ConnectUIEvents(); } EditorResourceBrowserWidget::~EditorResourceBrowserWidget() { delete m_ui; } void EditorResourceBrowserWidget::NavigateToDirectory(const char *path) { if (path == nullptr) { NavigateToDirectory(""); return; } if (m_currentDirectory == path) return; // set us to disabled, this will grey everything out temporarily setEnabled(false); g_pEditor->ProcessBackgroundEvents(); // actually change the path m_currentDirectory = path; m_ui->resourceList->setModel(nullptr); delete m_ui->resourceListModel; m_ui->resourceListModel = new EditorResourceSelectionDialogModel(m_currentDirectory, false, true, PREVIEW_ICON_SIZE, this); m_ui->resourceList->setModel(m_ui->resourceListModel); m_selectedResourceName.Clear(); m_pSelectedResourceType = nullptr; // re-enable everything setEnabled(true); } void EditorResourceBrowserWidget::OnActionDirectoryBackTriggered() { } void EditorResourceBrowserWidget::OnActionDirectoryUpTriggered() { } void EditorResourceBrowserWidget::OnActionNewDirectoryTriggered() { } void EditorResourceBrowserWidget::OnActionDeleteResourceTriggered() { } void EditorResourceBrowserWidget::OnActionImportStaticMeshTriggered() { // create a static mesh import dialog EditorStaticMeshImportDialog *staticMeshImportDialog = new EditorStaticMeshImportDialog(nullptr); staticMeshImportDialog->show(); } void EditorResourceBrowserWidget::OnActionInsertResourceTriggered() { if (m_pSelectedResourceType == nullptr) return; // pass to active edit mode if (m_pMapWindow->IsMapOpen()) m_pMapWindow->GetActiveEditModePointer()->HandleResourceViewResourceActivatedEvent(m_pSelectedResourceType, m_selectedResourceName); } void EditorResourceBrowserWidget::OnActionEditBlockMeshTriggered() { if (m_pSelectedResourceType != OBJECT_TYPEINFO(BlockMesh)) return; // open progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // open a static mesh editor dialog EditorBlockMeshEditor *editor = new EditorBlockMeshEditor(); if (!editor->Load(m_selectedResourceName, &progressDialog)) { progressDialog.ModalError("Failed to open block mesh editor."); delete editor; return; } progressDialog.close(); editor->show(); } void EditorResourceBrowserWidget::OnActionEditSkeletalMeshTriggered() { if (m_pSelectedResourceType != OBJECT_TYPEINFO(SkeletalMesh)) return; // open progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // open a static mesh editor dialog EditorSkeletalMeshEditor *editor = new EditorSkeletalMeshEditor(); if (!editor->Load(m_selectedResourceName, &progressDialog)) { progressDialog.ModalError("Failed to open skeletal mesh editor."); delete editor; return; } progressDialog.close(); editor->show(); } void EditorResourceBrowserWidget::OnActionEditSkeletalAnimationTriggered() { if (m_pSelectedResourceType != OBJECT_TYPEINFO(SkeletalAnimation)) return; // open progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // open a static mesh editor dialog EditorSkeletalAnimationEditor *editor = new EditorSkeletalAnimationEditor(); if (!editor->Load(m_selectedResourceName, &progressDialog)) { progressDialog.ModalError("Failed to open skeletal animation editor."); delete editor; return; } progressDialog.close(); editor->show(); } void EditorResourceBrowserWidget::OnActionEditStaticMeshTriggered() { if (m_pSelectedResourceType != OBJECT_TYPEINFO(StaticMesh)) return; // open progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); // open a static mesh editor dialog EditorStaticMeshEditor *editor = new EditorStaticMeshEditor(); if (!editor->Load(m_selectedResourceName, &progressDialog)) { progressDialog.ModalError("Failed to open static mesh editor."); delete editor; return; } progressDialog.close(); editor->show(); } void EditorResourceBrowserWidget::OnDirectoryTreeItemClickedOrActivated(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_ui->directoryTreeModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == nullptr) return; if (pDirectoryNode->IsDirectory()) { // enter this directory, have to temporarily copy the string though, as navigating will destroy the node String directoryPathCopy(pDirectoryNode->GetFullName()); NavigateToDirectory(directoryPathCopy); } } void EditorResourceBrowserWidget::OnResourceListItemClicked(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_ui->directoryTreeModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == nullptr || pDirectoryNode->IsDirectory() || pDirectoryNode->GetResourceTypeInfo() == nullptr) { m_selectedResourceName.Clear(); m_pSelectedResourceType = nullptr; m_ui->SetResourceListActionsForResourceType(nullptr); return; } m_selectedResourceName = pDirectoryNode->GetFullName(); m_pSelectedResourceType = pDirectoryNode->GetResourceTypeInfo(); m_ui->SetResourceListActionsForResourceType(m_pSelectedResourceType); } void EditorResourceBrowserWidget::OnResourceListItemActivated(const QModelIndex &index) { const EditorResourceSelectionDialogModel::DirectoryNode *pDirectoryNode = m_ui->directoryTreeModel->GetDirectoryNodeForIndex(index); if (pDirectoryNode == nullptr || pDirectoryNode->IsDirectory() || pDirectoryNode->GetResourceTypeInfo() == nullptr) return; // pass to active edit mode if (m_pMapWindow->IsMapOpen()) m_pMapWindow->GetActiveEditModePointer()->HandleResourceViewResourceActivatedEvent(pDirectoryNode->GetResourceTypeInfo(), pDirectoryNode->GetFullName()); } <file_sep>/Engine/Source/Core/ResourceTypeInfo.cpp #include "Core/PrecompiledHeader.h" #include "Core/ResourceTypeInfo.h" ResourceTypeInfo::ResourceTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory) : ObjectTypeInfo(TypeName, pParentTypeInfo, pPropertyDeclarations, pFactory) { } ResourceTypeInfo::~ResourceTypeInfo() { } <file_sep>/Engine/Source/ResourceCompiler/FontGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/FontGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/DataFormats.h" #include "YBaseLib/ZipArchive.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "Core/DDSReader.h" #include "Core/DDSWriter.h" #include "Core/ImageCodec.h" #include "Core/TexturePacker.h" Log_SetChannel(FontGenerator); static const char *STORAGE_FONT_XML_FILENAME = "font.xml"; static const char *STORAGE_FONT_DATA_PREFIX = "codepoint_"; static const uint32 MAXIMUM_CHARACTERS_PER_TEXTURE = 256; PIXEL_FORMAT FontGenerator::GetFontStoragePixelFormat(FONT_TYPE type) { if (type == FONT_TYPE_BITMAP) return PIXEL_FORMAT_R8G8B8A8_UNORM; else if (type == FONT_TYPE_SIGNED_DISTANCE_FIELD) return PIXEL_FORMAT_R32_FLOAT; UnreachableCode(); return PIXEL_FORMAT_COUNT; } PIXEL_FORMAT FontGenerator::GetCompiledPixelFormat(FONT_TYPE type) { if (type == FONT_TYPE_BITMAP) return PIXEL_FORMAT_R8G8B8A8_UNORM; else if (type == FONT_TYPE_SIGNED_DISTANCE_FIELD) return PIXEL_FORMAT_R32_FLOAT; UnreachableCode(); return PIXEL_FORMAT_COUNT; } uint32 FontGenerator::GetMaximumTextureDimension() { return 16384; } FontGenerator::FontGenerator() : m_type(FONT_TYPE_COUNT), m_characterHeight(0), m_useTextureFiltering(false), m_generateMipmaps(false) { } FontGenerator::~FontGenerator() { for (uint32 i = 0; i < m_characters.GetSize(); i++) delete m_characters[i].pContents; } const FontGenerator::Character *FontGenerator::GetCharacterByCodePoint(uint32 codePoint) const { for (uint32 i = 0; i < m_characters.GetSize(); i++) { if (m_characters[i].CodePoint == codePoint) return &m_characters[i]; } return nullptr; } FontGenerator::Character *FontGenerator::GetCharacterByCodePoint(uint32 codePoint) { for (uint32 i = 0; i < m_characters.GetSize(); i++) { if (m_characters[i].CodePoint == codePoint) return &m_characters[i]; } return nullptr; } bool FontGenerator::AddCharacter(uint32 codePoint, uint32 paddingX, uint32 paddingY, int32 drawOffsetX, int32 drawOffsetY, float advance, const Image *pContents) { if (GetCharacterByCodePoint(codePoint) != nullptr) return false; // ensure correct format if (!pContents->IsValidImage() || pContents->GetPixelFormat() != GetFontStoragePixelFormat(m_type)) return false; Character character; character.CodePoint = codePoint; character.PaddingX = paddingX; character.PaddingY = paddingY; character.DrawOffsetX = drawOffsetX; character.DrawOffsetY = drawOffsetY; character.Advance = advance; character.pContents = new Image(*pContents); character.IsWhitespace = false; m_characters.Add(character); return true; } bool FontGenerator::AddWhitespaceCharacter(uint32 codePoint, float advance) { if (GetCharacterByCodePoint(codePoint) != nullptr) return false; Character character; character.CodePoint = codePoint; character.PaddingX = 0; character.PaddingY = 0; character.DrawOffsetX = 0; character.DrawOffsetY = 0; character.Advance = advance; character.pContents = nullptr; character.IsWhitespace = true; m_characters.Add(character); return true; } bool FontGenerator::RemoveCharacter(uint32 codePoint) { for (uint32 i = 0; i < m_characters.GetSize(); i++) { if (m_characters[i].CodePoint == codePoint) { delete m_characters[i].pContents; m_characters.OrderedRemove(i); return true; } } return false; } void FontGenerator::Create(FONT_TYPE type, uint32 characterHeight) { DebugAssert(type < FONT_TYPE_COUNT); m_type = type; m_characterHeight = characterHeight; } bool FontGenerator::Load(const char *fileName, ByteStream *pStream) { ZipArchive *pArchive = ZipArchive::OpenArchiveReadOnly(pStream); if (pArchive == nullptr) { Log_ErrorPrintf("FontGenerator::Load: Could not open '%s' as archive.", fileName); return false; } // load xml if (!LoadXML(pArchive)) { delete pArchive; return false; } // load character data if (!LoadCharacters(pArchive)) { delete pArchive; return false; } // done return true; } bool FontGenerator::LoadXML(ZipArchive *pArchive) { AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile("font.xml", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_ErrorPrintf("FontGenerator::Load: Could not open font.xml in archive"); return false; } XMLReader xmlReader; if (!xmlReader.Create(pStream, "font.xml") || !xmlReader.SkipToElement("font")) return false; // read attributes const char *fontTypeStr = xmlReader.FetchAttribute("type"); const char *fontCharacterHeightStr = xmlReader.FetchAttribute("character-height"); const char *fontUseTextureFilteringStr = xmlReader.FetchAttribute("use-texture-filtering"); const char *fontGenerateMipmapsStr = xmlReader.FetchAttribute("generate-mipmaps"); if (fontTypeStr == nullptr || fontCharacterHeightStr == nullptr || fontUseTextureFilteringStr == nullptr || fontGenerateMipmapsStr == nullptr || !NameTable_TranslateType(NameTables::FontType, fontTypeStr, &m_type, true) || (m_characterHeight = StringConverter::StringToUInt32(fontCharacterHeightStr)) == 0) { xmlReader.PrintError("missing or invalid attributes"); return false; } // parse remaining attributes m_useTextureFiltering = StringConverter::StringToBool(fontUseTextureFilteringStr); m_generateMipmaps = StringConverter::StringToBool(fontGenerateMipmapsStr); // parse the xml for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 fontSelection = xmlReader.Select("characters"); if (fontSelection < 0) return false; switch (fontSelection) { // characters case 0: { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 charactersSelection = xmlReader.Select("character"); if (charactersSelection < 0) return false; switch (charactersSelection) { // character case 0: { const char *codePointStr = xmlReader.FetchAttribute("codepoint"); const char *paddingXStr = xmlReader.FetchAttribute("padding-x"); const char *paddingYStr = xmlReader.FetchAttribute("padding-y"); const char *drawOffsetXStr = xmlReader.FetchAttribute("draw-offset-x"); const char *drawOffsetYStr = xmlReader.FetchAttribute("draw-offset-y"); const char *advanceStr = xmlReader.FetchAttribute("advance"); const char *whitespaceStr = xmlReader.FetchAttribute("whitespace"); if (codePointStr == nullptr || paddingXStr == nullptr || paddingYStr == nullptr || drawOffsetXStr == nullptr || drawOffsetYStr == nullptr || advanceStr == nullptr || whitespaceStr == nullptr) { xmlReader.PrintError("missing attributes"); return false; } // create character struct Character character; character.CodePoint = StringConverter::StringToUInt32(codePointStr); character.PaddingX = StringConverter::StringToUInt32(paddingXStr); character.PaddingY = StringConverter::StringToUInt32(paddingYStr); character.DrawOffsetX = StringConverter::StringToInt32(drawOffsetXStr); character.DrawOffsetY = StringConverter::StringToInt32(drawOffsetYStr); character.Advance = StringConverter::StringToFloat(advanceStr); character.IsWhitespace = StringConverter::StringToBool(whitespaceStr); character.pContents = nullptr; // ensure it doesn't exist for (uint32 i = 0; i < m_characters.GetSize(); i++) { if (m_characters[i].CodePoint == character.CodePoint) { xmlReader.PrintError("duplicate code point definition: %u", character.CodePoint); return false; } } // add to list m_characters.Add(character); // skip element if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "characters") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "font") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } // ok return true; } bool FontGenerator::LoadCharacters(ZipArchive *pArchive) { const char *imageExtension = (m_type == FONT_TYPE_SIGNED_DISTANCE_FIELD) ? ".dds" : ".png"; PIXEL_FORMAT expectedPixelFormat = GetFontStoragePixelFormat(m_type); PathString fileName; // loop over characters for (uint32 characterIndex = 0; characterIndex < m_characters.GetSize(); characterIndex++) { Character &character = m_characters[characterIndex]; if (character.IsWhitespace) continue; // construct filename fileName.Format("%s%u%s", STORAGE_FONT_DATA_PREFIX, character.CodePoint, imageExtension); // open it AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) { Log_ErrorPrintf("FontGenerator::LoadCharacters: Can't open file '%s' in archive.", fileName.GetCharArray()); return false; } // use dds for distance fields, otherwise png if (m_type == FONT_TYPE_SIGNED_DISTANCE_FIELD) { DDSReader ddsReader; if (!ddsReader.Open(fileName, pStream) || !ddsReader.LoadMipLevel(0)) { Log_ErrorPrintf("FontGenerator::LoadCharacters: Failed to parse DDS file '%s' in archive.", fileName.GetCharArray()); return false; } // should be the correct pixel format if (expectedPixelFormat != ddsReader.GetPixelFormat()) { Log_ErrorPrintf("FontGenerator::LoadCharacters: DDS file '%s' has incorrect pixel format (%s vs %s)", fileName.GetCharArray(), NameTable_GetNameString(NameTables::PixelFormat, ddsReader.GetPixelFormat()), NameTable_GetNameString(NameTables::PixelFormat, expectedPixelFormat)); return false; } // load it up character.pContents = new Image(); character.pContents->Create(expectedPixelFormat, ddsReader.GetWidth(), ddsReader.GetHeight(), 1); Y_memcpy_stride(character.pContents->GetData(), character.pContents->GetDataRowPitch(), ddsReader.GetMipLevelData(0, 0), ddsReader.GetMipPitch(0, 0), Min(character.pContents->GetDataRowPitch(), ddsReader.GetMipPitch(0, 0)), ddsReader.GetHeight()); } else { // allocate image character.pContents = new Image(); // decode the image ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(fileName, pStream); if (pCodec == nullptr || !pCodec->DecodeImage(character.pContents, fileName, pStream)) { Log_ErrorPrintf("FontGenerator::LoadCharacters: Failed to parse image file '%s' in archive.", fileName.GetCharArray()); return false; } // ensure pixel format matches, it's okay if it doesn't // freeimage likes to strip away alpha channels when all pixels are opaque.. if (character.pContents->GetPixelFormat() != expectedPixelFormat && !character.pContents->ConvertPixelFormat(expectedPixelFormat)) { Log_ErrorPrintf("FontGenerator::LoadCharacters: Image file '%s' has incorrect pixel format (%s vs %s) and could not be converted.", fileName.GetCharArray(), NameTable_GetNameString(NameTables::PixelFormat, character.pContents->GetPixelFormat()), NameTable_GetNameString(NameTables::PixelFormat, expectedPixelFormat)); return false; } } } // done return true; } bool FontGenerator::Save(ByteStream *pOutputStream) const { ZipArchive *pArchive = ZipArchive::CreateArchive(pOutputStream); if (pArchive == nullptr) { Log_ErrorPrintf("TextureGenerator::Save: Could not create archive."); return false; } if (!SaveXML(pArchive)) { pArchive->DiscardChanges(); delete pArchive; return false; } if (!SaveCharacters(pArchive)) { pArchive->DiscardChanges(); delete pArchive; return false; } if (!pArchive->CommitChanges()) return false; delete pArchive; return true; } bool FontGenerator::SaveXML(ZipArchive *pArchive) const { AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile("font.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_ErrorPrintf("FontGenerator::SaveXML: Could not open font.xml in archive"); return false; } XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("font"); xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::FontType, m_type)); xmlWriter.WriteAttribute("character-height", StringConverter::UInt32ToString(m_characterHeight)); xmlWriter.WriteAttribute("use-texture-filtering", StringConverter::BoolToString(m_useTextureFiltering)); xmlWriter.WriteAttribute("generate-mipmaps", StringConverter::BoolToString(m_generateMipmaps)); { xmlWriter.StartElement("characters"); { for (uint32 characterIndex = 0; characterIndex < m_characters.GetSize(); characterIndex++) { const Character &character = m_characters[characterIndex]; xmlWriter.StartElement("character"); xmlWriter.WriteAttribute("codepoint", StringConverter::UInt32ToString(character.CodePoint)); xmlWriter.WriteAttribute("padding-x", StringConverter::UInt32ToString(character.PaddingX)); xmlWriter.WriteAttribute("padding-y", StringConverter::UInt32ToString(character.PaddingY)); xmlWriter.WriteAttribute("draw-offset-x", StringConverter::Int32ToString(character.DrawOffsetX)); xmlWriter.WriteAttribute("draw-offset-y", StringConverter::Int32ToString(character.DrawOffsetY)); xmlWriter.WriteAttribute("advance", StringConverter::FloatToString(character.Advance)); xmlWriter.WriteAttribute("whitespace", StringConverter::BoolToString(character.IsWhitespace)); xmlWriter.EndElement(); // </character> } } xmlWriter.EndElement(); // </characters> } xmlWriter.EndElement(); // </font> xmlWriter.Close(); return (!pStream->InErrorState()); } bool FontGenerator::SaveCharacters(ZipArchive *pArchive) const { const char *imageExtension = (m_type == FONT_TYPE_SIGNED_DISTANCE_FIELD) ? ".dds" : ".png"; PathString fileName; // loop over characters for (uint32 characterIndex = 0; characterIndex < m_characters.GetSize(); characterIndex++) { const Character &character = m_characters[characterIndex]; if (character.IsWhitespace) continue; // construct filename const Image *pImage = character.pContents; fileName.Format("%s%u%s", STORAGE_FONT_DATA_PREFIX, character.CodePoint, imageExtension); // open it AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) { Log_ErrorPrintf("FontGenerator::SaveCharacters: Can't open file '%s' in archive.", fileName.GetCharArray()); return false; } // use dds for distance fields, otherwise png if (m_type == FONT_TYPE_SIGNED_DISTANCE_FIELD) { DDSWriter ddsWriter; ddsWriter.Initialize(pStream); if (!ddsWriter.WriteHeader(DDS_TEXTURE_TYPE_2D, pImage->GetPixelFormat(), pImage->GetWidth(), pImage->GetHeight(), 1, 1) || !ddsWriter.WriteMipLevel(0, pImage->GetData(), pImage->GetDataSize()) || !ddsWriter.Finalize()) { Log_ErrorPrintf("FontGenerator::SaveCharacters: Failed to write DDS file '%s' in archive.", fileName.GetCharArray()); return false; } } else { // encode the image ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(fileName, pStream); if (pCodec == nullptr || !pCodec->EncodeImage(fileName, pStream, pImage)) { Log_ErrorPrintf("FontGenerator::SaveCharacters: Failed to write image file '%s' in archive.", fileName.GetCharArray()); return false; } } } return true; } class FontCompiler { public: struct CharacterData { uint32 CodePoint; int32 DrawOffsetX, DrawOffsetY; float Advance; bool IsWhitespace; Image *pContents; int32 TextureIndex; uint32 AtlasStartX, AtlasEndX; uint32 AtlasStartY, AtlasEndY; }; private: const FontGenerator *m_pGenerator; TEXTURE_PLATFORM m_texturePlatform; typedef MemArray<CharacterData> CharacterDataArray; CharacterDataArray m_characters; typedef PODArray<Image *> AtlasImageArray; AtlasImageArray m_atlasImages; typedef PODArray<TextureGenerator *> TextureGeneratorArray; TextureGeneratorArray m_textures; public: FontCompiler(const FontGenerator *pGenerator, TEXTURE_PLATFORM platform) : m_pGenerator(pGenerator), m_texturePlatform(platform) { } ~FontCompiler() { } bool Compile(ByteStream *pStream) { if (m_pGenerator->GetCharacterCount() == 0) return false; BuildCharacters(); if (!BuildTextures()) return false; if (!GenerateTextures()) return false; if (!WriteCompiledStream(pStream)) return false; return true; } private: void BuildCharacters() { // add references to all images for (uint32 i = 0; i < m_pGenerator->GetCharacterCount(); i++) { const FontGenerator::Character *pCharacter = m_pGenerator->GetCharacterByIndex(i); CharacterData data; data.CodePoint = pCharacter->CodePoint; data.DrawOffsetX = pCharacter->DrawOffsetX; data.DrawOffsetY = pCharacter->DrawOffsetY; data.Advance = pCharacter->Advance; data.IsWhitespace = pCharacter->IsWhitespace; data.pContents = pCharacter->pContents; data.TextureIndex = -1; data.AtlasStartX = data.AtlasEndX = 0; data.AtlasStartY = data.AtlasEndY = 0; m_characters.Add(data); } // // re-align so that the origin is top-left instead of bottom-left // int32 lowestY = m_characters[0].DrawOffsetY; // for (uint32 i = 1; i < m_characters.GetSize(); i++) // lowestY = Max(lowestY, m_characters[i].DrawOffsetY); // for (uint32 i = 0; i < m_characters.GetSize(); i++) // m_characters[i].DrawOffsetY -= lowestY; // Log_DevPrintf("Moved characters up %d pixels", lowestY); // compute the largest overhang, and move everything up // this is a giant hack.. but ehh int32 largestOverhang = 0; for (uint32 i = 0; i < m_characters.GetSize(); i++) { const FontGenerator::Character *pCharacter = m_pGenerator->GetCharacterByIndex(i); if (pCharacter->pContents != nullptr) largestOverhang = Max(largestOverhang, m_characters[i].DrawOffsetY + (int32)pCharacter->pContents->GetHeight()); } if (largestOverhang > (int32)m_pGenerator->GetCharacterHeight()) { largestOverhang -= (int32)m_pGenerator->GetCharacterHeight(); for (uint32 i = 0; i < m_characters.GetSize(); i++) m_characters[i].DrawOffsetY -= largestOverhang; //Log_DevPrintf("Moved characters up %d pixels", largestOverhang); } // sort the character list in ascending order m_characters.Sort([](const CharacterData *pLeft, const CharacterData *pRight) { return ((int32)pLeft->CodePoint) - ((int32)pRight->CodePoint); }); } bool BuildTextures() { const uint32 maximumDimensions = FontGenerator::GetMaximumTextureDimension(); const PIXEL_FORMAT pixelFormat = FontGenerator::GetFontStoragePixelFormat(m_pGenerator->GetType()); const uint32 paddingAmount = 2; // start by trying to pack everything into a single texture uint32 charactersToPack = 0; uint32 remainingCharacters = 0; uint32 currentTextureWidth = 0; uint32 currentTextureHeight = 0; // count non-whitespace characters for (uint32 characterIndex = 0; characterIndex < m_characters.GetSize(); characterIndex++) { if (!m_characters[characterIndex].IsWhitespace) { charactersToPack++; remainingCharacters++; } } // keep going until we succeed while (remainingCharacters > 0) { // add images TexturePacker packer(pixelFormat); uint32 packCount = 0; for (uint32 i = 0; i < m_characters.GetSize() && packCount < charactersToPack; i++) { if (m_characters[i].TextureIndex < 0 && !m_characters[i].IsWhitespace) { packer.AddImage(m_characters[i].pContents, paddingAmount, &m_characters[i]); packCount++; } } // try packing this number of characters into a single texture for (;;) { // if cursize == 0, guess the dimensions if (currentTextureWidth == 0) { packer.GuessPackedImageDimensions(&currentTextureWidth, &currentTextureHeight); currentTextureWidth = Min(currentTextureWidth, maximumDimensions); currentTextureHeight = Min(currentTextureHeight, maximumDimensions); } // attempt to pack them Log_DevPrintf("FontCompiler::BuildTextures: Trying to pack %u characters into a %u x %u texture", packCount, currentTextureWidth, currentTextureHeight); if (packer.Pack(currentTextureWidth, currentTextureHeight, 0.0f, 0.0f, 0.0f, 0.0f)) { // pack successful remainingCharacters -= packCount; // update data for (uint32 i = 0; i < m_characters.GetSize(); i++) { CharacterData &data = m_characters[i]; if (data.TextureIndex < 0 && !data.IsWhitespace && packer.GetImageLocation(&data, &data.AtlasStartX, &data.AtlasEndX, &data.AtlasStartY, &data.AtlasEndY)) data.TextureIndex = (uint32)m_atlasImages.GetSize(); } // add the image m_atlasImages.Add(new Image(*packer.GetPackedImage())); break; } else { // pack failed, are we at the maximum texture dimensions? if (currentTextureWidth == maximumDimensions && currentTextureHeight == maximumDimensions) { // try packing less characters, let's try half charactersToPack /= 2; if (charactersToPack == 0) { // we're never gonna be able to do this... return false; } // break back to the outer loop break; } else { // first expand horizontally, then vertically if (currentTextureWidth == currentTextureHeight) currentTextureWidth *= 2; else currentTextureHeight *= 2; // try the pack operation again DebugAssert(currentTextureWidth <= maximumDimensions && currentTextureHeight <= maximumDimensions); continue; } } } } // if we got here, everything was packed return true; } bool GenerateTextures() { const PIXEL_FORMAT finalPixelFormat = FontGenerator::GetCompiledPixelFormat(m_pGenerator->GetType()); for (uint32 textureIndex = 0; textureIndex < m_atlasImages.GetSize(); textureIndex++) { // initialize it const Image *pSourceImage = m_atlasImages[textureIndex]; TextureGenerator *pGenerator = new TextureGenerator(); if (!pGenerator->Create(TEXTURE_TYPE_2D, pSourceImage->GetPixelFormat(), pSourceImage->GetWidth(), pSourceImage->GetHeight(), 1, 1, TEXTURE_USAGE_UI_ASSET)) { Log_ErrorPrintf("FontCompiler::GenerateTextures: Failed to create texture %u", textureIndex); delete pGenerator; return false; } // set parameters pGenerator->SetTextureFilter((m_pGenerator->GetUseTextureFiltering()) == FONT_TYPE_BITMAP ? TEXTURE_FILTER_ANISOTROPIC : TEXTURE_FILTER_MIN_MAG_MIP_POINT); pGenerator->SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_CLAMP); pGenerator->SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_CLAMP); pGenerator->SetTextureAddressModeW(TEXTURE_ADDRESS_MODE_CLAMP); pGenerator->SetGenerateMipmaps(m_pGenerator->GetGenerateMipmaps()); pGenerator->SetEnablePremultipliedAlpha((m_pGenerator->GetType()) == FONT_TYPE_BITMAP); pGenerator->SetSourcePremultipliedAlpha(false); pGenerator->SetTextureUsage(TEXTURE_USAGE_UI_ASSET); pGenerator->SetEnableTextureCompression(true); pGenerator->SetSourceSRGB(false); pGenerator->SetEnableSRGB(false); // add the image if (!pGenerator->SetImage(0, pSourceImage)) { Log_ErrorPrintf("FontCompiler::GenerateTextures: Failed to set texture %u", textureIndex); delete pGenerator; return false; } // convert pixel formats if (pGenerator->GetPixelFormat() != finalPixelFormat && !pGenerator->ConvertToPixelFormat(finalPixelFormat)) { Log_ErrorPrintf("FontCompiler::GenerateTextures: Failed to convert to final pixel format %s", NameTable_GetNameString(NameTables::PixelFormat, finalPixelFormat)); delete pGenerator; return false; } // add generator m_textures.Add(pGenerator); } return true; } bool WriteCompiledStream(ByteStream *pStream) { // write the header uint64 headerOffset = pStream->GetPosition(); DF_FONT_HEADER header; header.Magic = DF_FONT_HEADER_MAGIC; header.Size = sizeof(header); header.Type = m_pGenerator->GetType(); header.BestRenderingSize = m_pGenerator->GetCharacterHeight(); header.CharacterDataCount = 0; header.CharacterDataOffset = 0; header.TextureCount = 0; header.TextureOffset = 0; if (!pStream->Write(&header, sizeof(header))) return false; // write character info if (m_characters.GetSize() > 0) { header.CharacterDataCount = m_characters.GetSize(); header.CharacterDataOffset = (uint32)(pStream->GetPosition() - headerOffset); if (!WriteCompiledCharacterInfo(pStream)) return false; } // write textures if (m_textures.GetSize() > 0) { header.TextureCount = m_textures.GetSize(); header.TextureOffset = (uint32)(pStream->GetPosition() - headerOffset); if (!WriteCompiledTextures(pStream)) return false; } // rewrite header uint64 endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(headerOffset) || !pStream->Write2(&header, sizeof(header)) || !pStream->SeekAbsolute(endOffset)) return false; return true; } bool WriteCompiledCharacterInfo(ByteStream *pStream) { for (uint32 characterIndex = 0; characterIndex < m_characters.GetSize(); characterIndex++) { const CharacterData &cdata = m_characters[characterIndex]; DF_FONT_CHARACTER odata; odata.CodePoint = cdata.CodePoint; odata.DrawOffsetX = cdata.DrawOffsetX; odata.DrawOffsetY = cdata.DrawOffsetY; odata.Advance = cdata.Advance; odata.IsWhiteSpace = cdata.IsWhitespace; if (!cdata.IsWhitespace) { DebugAssert(cdata.TextureIndex >= 0); const TextureGenerator *pTextureForCharacter = m_textures[cdata.TextureIndex]; odata.DrawWidth = cdata.pContents->GetWidth(); odata.DrawHeight = cdata.pContents->GetHeight(); odata.StartU = (float)cdata.AtlasStartX / (float)pTextureForCharacter->GetWidth(); odata.EndU = (float)cdata.AtlasEndX / (float)pTextureForCharacter->GetWidth(); odata.StartV = (float)cdata.AtlasStartY / (float)pTextureForCharacter->GetHeight(); odata.EndV = (float)cdata.AtlasEndY / (float)pTextureForCharacter->GetHeight(); odata.TextureIndex = (uint32)cdata.TextureIndex; } else { odata.DrawWidth = (uint32)Math::Truncate(Math::Round(cdata.Advance)); odata.DrawHeight = m_pGenerator->GetCharacterHeight(); odata.StartU = odata.EndU = 0.0f; odata.StartV = odata.EndV = 0.0f; odata.TextureIndex = 0xFFFFFFFF; } if (!pStream->Write(&odata, sizeof(odata))) return false; } return true; } bool WriteCompiledTextures(ByteStream *pStream) { // compile each texture and write it to the stream for (uint32 textureIndex = 0; textureIndex < m_textures.GetSize(); textureIndex++) { // SmallString foo; // foo.Format("dbg%u.tex.zip", textureIndex); // ByteStream *str = g_pVirtualFileSystem->OpenFile(foo, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_WRITE); // m_textures[textureIndex]->Save(str); // str->Release(); AutoReleasePtr<ByteStream> pMemoryStream = ByteStream_CreateGrowableMemoryStream(); if (!m_textures[textureIndex]->Compile(pMemoryStream, m_texturePlatform)) { Log_ErrorPrintf("FontCompiler::WriteCompiledTextures: Failed to compile texture %u", textureIndex); return false; } DF_FONT_TEXTURE fontTex; fontTex.TextureType = TEXTURE_TYPE_2D; fontTex.TextureSize = (uint32)pMemoryStream->GetSize(); if (!pStream->Write2(&fontTex, sizeof(fontTex)) || !ByteStream_AppendStream(pMemoryStream, pStream)) return false; } return true; } }; bool FontGenerator::Compile(ByteStream *pOutputStream, TEXTURE_PLATFORM platform) const { // invoke compiler FontCompiler compiler(this, platform); return compiler.Compile(pOutputStream); } // Interface BinaryBlob *ResourceCompiler::CompileFont(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.font.zip", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileFont: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); FontGenerator *pGenerator = new FontGenerator(); if (!pGenerator->Load(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream, platform)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2Common.h #pragma once #include "Renderer/Common.h" #include "Renderer/Renderer.h" // include sdl before GLEW #include "Engine/SDLHeaders.h" // use sdl's opengles2 header #if 1 #include <glad/glad.h> #else #include <SDL_opengles2.h> // to get around SDL's lack of DXTC types #ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 #endif #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 #endif #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 #endif #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 #endif #endif // Forward declare all our types class OpenGLES2GPUBuffer; class OpenGLES2GPUContext; class OpenGLES2GPUShaderProgram; class OpenGLES2GPUTexture2D; class OpenGLES2GPUTextureCube; class OpenGLES2GPUDepthTexture; class OpenGLES2GPUDevice; class OpenGLES2GPURasterizerState; class OpenGLES2GPUDepthStencilState; class OpenGLES2GPUBlendState; class OpenGLES2GPUOutputBuffer; class OpenGLES2GPURenderTargetView; class OpenGLES2GPUDepthStencilBufferView; class OpenGLES2ConstantLibrary; #include "OpenGLES2Renderer/OpenGLES2Defines.h" #include "OpenGLES2Renderer/OpenGLES2CVars.h" <file_sep>/Engine/Source/Engine/Texture.h #pragma once #include "Core/Resource.h" #include "Renderer/RendererTypes.h" class Image; class GPUTexture; class GPUSamplerState; class Texture : public Resource { DECLARE_RESOURCE_TYPE_INFO(Texture, Resource); DECLARE_RESOURCE_NO_FACTORY(Texture); struct ImageData { uint32 Size; uint32 RowPitch; uint32 SlicePitch; uint32 FileOffset; byte *pPixels; }; public: Texture(TEXTURE_TYPE TextureType, const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); virtual ~Texture(); static TEXTURE_TYPE GetTextureTypeForStream(const char *FileName, ByteStream *pStream); static Texture *CreateTextureObjectForType(TEXTURE_TYPE textureType); static const ResourceTypeInfo *GetResourceTypeInfoForTextureType(TEXTURE_TYPE textureType); static uint3 GetTextureDimensions(const Texture *pTexture); const TEXTURE_TYPE GetTextureType() const { return m_eTextureType; } const TEXTURE_PLATFORM GetTexturePlatform() const { return m_eTexturePlatform; } const TEXTURE_FILTER GetTextureFilter() const { return m_eTextureFilter; } const PIXEL_FORMAT GetPixelFormat() const { return m_ePixelFormat; } const MATERIAL_BLENDING_MODE GetBlendingMode() const { return m_eBlendingMode; } uint32 GetNumMipLevels() const { return m_nMipLevels; } virtual bool Load(const char *FileName, ByteStream *pInputStream) = 0; GPUTexture *GetGPUTexture() const; virtual bool CreateDeviceResources() const; virtual void ReleaseDeviceResources() const; protected: TEXTURE_TYPE m_eTextureType; TEXTURE_PLATFORM m_eTexturePlatform; PIXEL_FORMAT m_ePixelFormat; TEXTURE_USAGE m_eTextureUsage; TEXTURE_FILTER m_eTextureFilter; MATERIAL_BLENDING_MODE m_eBlendingMode; int32 m_iMinLOD; int32 m_iMaxLOD; uint32 m_nMipLevels; uint32 m_nImages; ImageData *m_pImages; mutable GPUTexture *m_pDeviceTexture; mutable bool m_bDeviceResourcesCreated; }; class Texture2D : public Texture { DECLARE_RESOURCE_TYPE_INFO(Texture2D, Texture); DECLARE_RESOURCE_GENERIC_FACTORY(Texture2D); public: Texture2D(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~Texture2D(); const TEXTURE_ADDRESS_MODE GetAddressModeU() const { return m_eAddressModeU; } const TEXTURE_ADDRESS_MODE GetAddressModeV() const { return m_eAddressModeV; } const uint32 GetWidth() const { return m_iWidth; } const uint32 GetHeight() const { return m_iHeight; } // manually create a texture resource. the image data will only contain junk until it is properly filled. bool Create(const char *Name, TEXTURE_PLATFORM texturePlatform, TEXTURE_USAGE textureUsage, TEXTURE_FILTER textureFilter, MATERIAL_BLENDING_MODE blendingMode, TEXTURE_ADDRESS_MODE addressModeU, TEXTURE_ADDRESS_MODE addressModeV, int32 minLOD, int32 maxLOD, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 mipLevels); bool Load(const char *name, ByteStream *pStream); // mip level accessor const ImageData *GetMipLevelData(uint32 mipIndex) const { DebugAssert(mipIndex < m_nMipLevels); return &m_pImages[mipIndex]; } ImageData *GetMipLevelData(uint32 mipIndex) { DebugAssert(mipIndex < m_nMipLevels); return &m_pImages[mipIndex]; } // device resources virtual bool CreateDeviceResources() const; virtual void ReleaseDeviceResources() const; // texture sampling/loading bool GetTexelLevel(uint32 x, uint32 y, uint32 mipLevel, SHADER_PARAMETER_TYPE outType, void *pOutValue); bool SampleTexelLevel(float u, float v, uint32 mipLevel, SHADER_PARAMETER_TYPE outType, void *pOutValue, TEXTURE_FILTER overrideFilter = TEXTURE_FILTER_COUNT); // calculate the U coordinate from this texture float GetUCoordinate(int32 pos) const { return (float)pos / (float)m_iWidth; } float GetVCoordinate(int32 pos) const { return (float)pos / (float)m_iHeight; } // exporting to an image bool ExportToImage(uint32 mipIndex, Image *pOutputImage) const; protected: TEXTURE_ADDRESS_MODE m_eAddressModeU, m_eAddressModeV; uint32 m_iWidth, m_iHeight; }; class Texture2DArray : public Texture { DECLARE_RESOURCE_TYPE_INFO(Texture2DArray, Texture); DECLARE_RESOURCE_GENERIC_FACTORY(Texture2DArray); public: Texture2DArray(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~Texture2DArray(); const TEXTURE_ADDRESS_MODE GetAddressModeU() const { return m_eAddressModeU; } const TEXTURE_ADDRESS_MODE GetAddressModeV() const { return m_eAddressModeV; } const uint32 GetWidth() const { return m_iWidth; } const uint32 GetHeight() const { return m_iHeight; } const uint32 GetArraySize() const { return m_iArraySize; } // manually create a texture resource. the image data will only contain junk until it is properly filled. bool Create(const char *Name, TEXTURE_PLATFORM texturePlatform, TEXTURE_USAGE textureUsage, TEXTURE_FILTER textureFilter, MATERIAL_BLENDING_MODE blendingMode, TEXTURE_ADDRESS_MODE addressModeU, TEXTURE_ADDRESS_MODE addressModeV, int32 minLOD, int32 maxLOD, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 arraySize, uint32 mipLevels); bool Load(const char *name, ByteStream *pStream); // mip level accessor const ImageData *GetMipLevelData(uint32 mipIndex, uint32 arrayIndex) const { DebugAssert(arrayIndex < m_iArraySize && mipIndex < m_nMipLevels); return &m_pImages[mipIndex * m_iArraySize + arrayIndex]; } ImageData *GetMipLevelData(uint32 mipIndex, uint32 arrayIndex) { DebugAssert(arrayIndex < m_iArraySize && mipIndex < m_nMipLevels); return &m_pImages[mipIndex * m_iArraySize + arrayIndex]; } // device resources virtual bool CreateDeviceResources() const; virtual void ReleaseDeviceResources() const; // calculate the U coordinate from this texture float GetUCoordinate(int32 pos) const { return (float)pos / (float)m_iWidth; } float GetVCoordinate(int32 pos) const { return (float)pos / (float)m_iHeight; } // exporting to an image bool ExportToImage(uint32 mipIndex, uint32 arrayIndex, Image *pOutputImage) const; protected: TEXTURE_ADDRESS_MODE m_eAddressModeU, m_eAddressModeV; uint32 m_iWidth, m_iHeight; uint32 m_iArraySize; }; class TextureCube : public Texture { DECLARE_RESOURCE_TYPE_INFO(TextureCube, Texture); DECLARE_RESOURCE_GENERIC_FACTORY(TextureCube); public: TextureCube(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~TextureCube(); const TEXTURE_ADDRESS_MODE GetAddressModeU() const { return m_eAddressModeU; } const TEXTURE_ADDRESS_MODE GetAddressModeV() const { return m_eAddressModeV; } const uint32 GetWidth() const { return m_iWidth; } const uint32 GetHeight() const { return m_iHeight; } bool Load(const char *name, ByteStream *pStream); // mip level accessor const ImageData *GetMipLevelData(uint32 cubeFace, uint32 mipIndex) const { DebugAssert(cubeFace < CUBEMAP_FACE_COUNT && mipIndex < m_nMipLevels); return &m_pImages[(uint32)cubeFace * m_nMipLevels + mipIndex]; } ImageData *GetMipLevelData(uint32 cubeFace, uint32 mipIndex) { DebugAssert(cubeFace < CUBEMAP_FACE_COUNT && mipIndex < m_nMipLevels); return &m_pImages[(uint32)cubeFace * m_nMipLevels + mipIndex]; } // device resources virtual bool CreateDeviceResources() const; virtual void ReleaseDeviceResources() const; // calculate the U coordinate from this texture float GetUCoordinate(int32 pos) const { return (float)pos / (float)m_iWidth; } float GetVCoordinate(int32 pos) const { return (float)pos / (float)m_iHeight; } // exporting to an image bool ExportToImage(uint32 cubeFace, uint32 mipIndex, Image *pOutputImage) const; protected: TEXTURE_ADDRESS_MODE m_eAddressModeU, m_eAddressModeV; uint32 m_iWidth, m_iHeight; }; /* // mip level accessor const ImageData *GetMipLevelData(uint32 ArrayIndex, uint32 MipIndex) const { DebugAssert(ArrayIndex < m_iArraySize && MipIndex < m_nMipLevels); return &m_pImages[ArrayIndex * m_nMipLevels + MipIndex]; } ImageData *GetMipLevelData(uint32 ArrayIndex, uint32 MipIndex) { DebugAssert(ArrayIndex < m_iArraySize && MipIndex < m_nMipLevels); return &m_pImages[ArrayIndex * m_nMipLevels + MipIndex]; } */ <file_sep>/Engine/Source/OpenGLRenderer/OpenGLRenderBackend.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUBuffer.h" #include "OpenGLRenderer/OpenGLGPUOutputBuffer.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" #include "Engine/EngineCVars.h" #include "Engine/SDLHeaders.h" Log_SetChannel(OpenGLRenderBackend); // our gl debug callback static void APIENTRY GLDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { struct IgnoredWarning { GLenum type; GLuint id; GLenum severity; }; static const IgnoredWarning ignoredWarnings[] = { //type id severity //{ GL_DEBUG_TYPE_PERFORMANCE, 131154, GL_DEBUG_SEVERITY_MEDIUM }, // 131154 Pixel-path performance warning: Pixel transfer is synchronized with 3D rendering. { GL_DEBUG_TYPE_OTHER, 131185, GL_DEBUG_SEVERITY_NOTIFICATION }, // Buffer detailed info: Buffer object 5 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations. }; for (uint32 i = 0; i < countof(ignoredWarnings); i++) { if (type == ignoredWarnings[i].type && id == ignoredWarnings[i].id && severity == ignoredWarnings[i].severity) { return; } } const char *sourceStr = "UNKNOWN"; switch (source) { case GL_DEBUG_SOURCE_API: sourceStr = "GL_DEBUG_SOURCE_API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: sourceStr = "GL_DEBUG_SOURCE_WINDOW_SYSTEM"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: sourceStr = "GL_DEBUG_SOURCE_SHADER_COMPILER"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: sourceStr = "GL_DEBUG_SOURCE_THIRD_PARTY"; break; case GL_DEBUG_SOURCE_APPLICATION: sourceStr = "GL_DEBUG_SOURCE_APPLICATION"; break; case GL_DEBUG_SOURCE_OTHER: sourceStr = "GL_DEBUG_SOURCE_OTHER"; break; } const char *typeStr = "UNKNOWN"; switch (type) { case GL_DEBUG_TYPE_ERROR: typeStr = "GL_DEBUG_TYPE_ERROR"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: typeStr = "GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: typeStr = "GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR"; break; case GL_DEBUG_TYPE_PORTABILITY: typeStr = "GL_DEBUG_TYPE_PORTABILITY"; break; case GL_DEBUG_TYPE_PERFORMANCE: typeStr = "GL_DEBUG_TYPE_PERFORMANCE"; break; case GL_DEBUG_TYPE_OTHER: typeStr = "GL_DEBUG_TYPE_OTHER"; break; } LOGLEVEL outputLogLevel = LOGLEVEL_DEV; switch (severity) { case GL_DEBUG_SEVERITY_HIGH: outputLogLevel = LOGLEVEL_ERROR; break; case GL_DEBUG_SEVERITY_MEDIUM: outputLogLevel = LOGLEVEL_WARNING; break; case GL_DEBUG_SEVERITY_LOW: outputLogLevel = LOGLEVEL_INFO; break; case GL_DEBUG_SEVERITY_NOTIFICATION: outputLogLevel = LOGLEVEL_DEV; break; } char tempStr[1024]; uint32 copyLength = (length >= countof(tempStr)) ? countof(tempStr) - 1 : length; Y_memcpy(tempStr, message, copyLength); tempStr[copyLength] = 0; Log::GetInstance().Writef(___LogChannel___, LOG_MESSAGE_FUNCTION_NAME, outputLogLevel, "*** OpenGL Debug: src: %s, type: %s, id: %u, msg: %s ***", sourceStr, typeStr, id, tempStr); } static bool SetSDLGLColorAttributes(PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilBufferFormat) { // set colour buffer attributes uint32 redBits = 0; uint32 greenBits = 0; uint32 blueBits = 0; uint32 alphaBits = 0; bool srgbEnabled = false; switch (backBufferFormat) { case PIXEL_FORMAT_R8G8B8A8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 8; srgbEnabled = false; break; case PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 8; srgbEnabled = true; break; case PIXEL_FORMAT_B8G8R8A8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 0; srgbEnabled = true; break; case PIXEL_FORMAT_B8G8R8X8_UNORM: redBits = 8; greenBits = 8; blueBits = 8; alphaBits = 0; srgbEnabled = false; break; default: Log_ErrorPrintf("SetSDLGLColorAttributes: Unhandled backbuffer format '%s'.", PixelFormat_GetPixelFormatInfo(backBufferFormat)->Name); return false; } // set depth buffer attributes uint32 depthBits = 0; uint32 stencilBits = 0; switch (depthStencilBufferFormat) { case PIXEL_FORMAT_D16_UNORM: depthBits = 16; stencilBits = 0; break; case PIXEL_FORMAT_D24_UNORM_S8_UINT: depthBits = 24; stencilBits = 8; break; case PIXEL_FORMAT_D32_FLOAT: depthBits = 32; stencilBits = 0; break; case PIXEL_FORMAT_D32_FLOAT_S8X24_UINT: depthBits = 32; stencilBits = 8; break; case PIXEL_FORMAT_UNKNOWN: depthBits = 0; stencilBits = 0; break; default: Log_ErrorPrintf("SetSDLGLColorAttributes: Unhandled depthstencil format '%s'.", PixelFormat_GetPixelFormatInfo(depthStencilBufferFormat)->Name); return false; } // pass them to sdl SDL_GL_SetAttribute(SDL_GL_RED_SIZE, redBits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, greenBits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, blueBits); // GLX doesn't seem to like the alpha bits... :S #if !Y_PLATFORM_LINUX SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, alphaBits); #endif SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilBits); SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, (srgbEnabled) ? 1 : 0); return true; } static bool SetSDLGLVersionAttributes(RENDERER_FEATURE_LEVEL featureLevel) { // we always want h/w acceleration SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // determine context flags uint32 contextFlags = 0; // forward compatibilty preferred contextFlags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG; #if Y_BUILD_CONFIG_DEBUG // use debug context in debug builds if (CVars::r_use_debug_device.GetBool()) contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG; #endif // we need the major version, minor version, and profile mask uint32 majorVersion, minorVersion, profileMask; // branch out depending on version switch (featureLevel) { case RENDERER_FEATURE_LEVEL_SM5: majorVersion = 4; minorVersion = 4; profileMask = SDL_GL_CONTEXT_PROFILE_CORE; break; case RENDERER_FEATURE_LEVEL_SM4: majorVersion = 3; minorVersion = 3; profileMask = SDL_GL_CONTEXT_PROFILE_CORE; break; default: Log_ErrorPrintf("SetSDLGLVersionAttributes: Unhandled renderer feature level: %s", NameTable_GetNameString(NameTables::RendererFeatureLevel, featureLevel)); return false; } // set attributes SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majorVersion); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minorVersion); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profileMask); return true; } static bool InitializeGLAD() { // use the sdl loader if (gladLoadGLLoader(SDL_GL_GetProcAddress) != GL_TRUE) { Log_ErrorPrint("Failed to initialize GLAD"); return false; } return true; } // set common stuff for this new gl context static void InitializeCurrentGLContext() { // set debug callbacks if (GLAD_GL_ARB_debug_output && CVars::r_use_debug_device.GetBool()) { Log_DevPrintf("Using GL_ARB_debug_output."); glDebugMessageCallbackARB(GLDebugCallback, NULL); glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } } bool OpenGLRenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer) { // select formats PIXEL_FORMAT outputBackBufferFormat = pCreateParameters->BackBufferFormat; PIXEL_FORMAT outputDepthStencilFormat = pCreateParameters->DepthStencilBufferFormat; // if the backbuffer format is unspecified, use the best for the platform if (outputBackBufferFormat == PIXEL_FORMAT_UNKNOWN) { // by default this is rgba8 outputBackBufferFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; } // initialize colour attributes if (!SetSDLGLColorAttributes(outputBackBufferFormat, outputDepthStencilFormat)) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Failed to set opengl window system parameters."); return false; } // no sharing possible as there is no current context SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0); // define an order of versions to attempt to create RENDERER_FEATURE_LEVEL featureLevelCreationOrder[] = { RENDERER_FEATURE_LEVEL_SM5, RENDERER_FEATURE_LEVEL_SM4 }; // try creating each one until we get one SDL_GLContext pMainSDLGLContext = nullptr; RENDERER_FEATURE_LEVEL featureLevel; TEXTURE_PLATFORM texturePlatform; for (uint32 i = 0; i < countof(featureLevelCreationOrder); i++) { // set the attributes if (!SetSDLGLVersionAttributes(featureLevelCreationOrder[i])) continue; // try creation Log_DevPrintf("OpenGLRenderBackend::Create: Trying to create a %s context", NameTable_GetNameString(NameTables::RendererFeatureLevel, featureLevelCreationOrder[i])); pMainSDLGLContext = SDL_GL_CreateContext(pSDLWindow); if (pMainSDLGLContext == nullptr) continue; // log+return Log_InfoPrintf("OpenGLRenderBackend::Create: Got a %s context (%s)", NameTable_GetNameString(NameTables::RendererFeatureLevel, featureLevelCreationOrder[i]), NameTable_GetNameString(NameTables::RendererFeatureLevelFullName, featureLevelCreationOrder[i])); // initialize glew if (!InitializeGLAD()) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Failed to initialize GLEW"); SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(pMainSDLGLContext); continue; } // set context settings featureLevel = featureLevelCreationOrder[i]; texturePlatform = (featureLevelCreationOrder[i] == RENDERER_FEATURE_LEVEL_SM4) ? TEXTURE_PLATFORM_DXTC : TEXTURE_PLATFORM_DXTC; InitializeCurrentGLContext(); break; } // failed? if (pMainSDLGLContext == nullptr) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Failed to create an acceptable GL context"); return nullptr; } // create the off-thread context SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); SDL_GLContext pOffThreadGLContext = SDL_GL_CreateContext(pSDLWindow); if (pOffThreadGLContext == nullptr) { SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(pMainSDLGLContext); Log_ErrorPrintf("OpenGLRenderBackend::Create: Failed to create off-thread GL context"); return nullptr; } // initialize off-thread context, and restore main context InitializeCurrentGLContext(); SDL_GL_MakeCurrent(pSDLWindow, pMainSDLGLContext); // log some info { Log_InfoPrintf("OpenGL Renderer Feature Level: %s", NameTable_GetNameString(NameTables::RendererFeatureLevelFullName, featureLevel)); Log_InfoPrintf("Texture Platform: %s", NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); // log vendor info Log_InfoPrintf("GL_VENDOR: %s", (glGetString(GL_VENDOR) != NULL) ? glGetString(GL_VENDOR) : (const GLubyte *)"NULL"); Log_InfoPrintf("GL_RENDERER: %s", (glGetString(GL_RENDERER) != NULL) ? glGetString(GL_RENDERER) : (const GLubyte *)"NULL"); GLint majorVersion, minorVersion; glGetIntegerv(GL_MAJOR_VERSION, &majorVersion); glGetIntegerv(GL_MINOR_VERSION, &minorVersion); Log_InfoPrintf("GL_VERSION: %s (%i.%i)", (glGetString(GL_VERSION) != NULL) ? glGetString(GL_VERSION) : (const GLubyte *)"NULL", majorVersion, minorVersion); // log extensions #if 0 GLint numExtensions; String extensionsString; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); extensionsString.Format("GL_NUM_EXTENSIONS: %i [", numExtensions); for (GLint i = 0; i < numExtensions; i++) { if (i != 0) extensionsString.AppendCharacter(' '); extensionsString.AppendString((const char *)glGetStringi(GL_EXTENSIONS, i)); } extensionsString.AppendCharacter(']'); Log_InfoPrint(extensionsString); #endif } // run glget calls uint32 maxTextureAnisotropy = 0; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, reinterpret_cast<GLint *>(&maxTextureAnisotropy)); Log_DevPrintf("glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT): %u", maxTextureAnisotropy); // query max attributes and max render targets uint32 maxVertexAttributes = 0; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); Log_DevPrintf("glGetIntegerv(GL_MAX_VERTEX_ATTRIBS): %u", maxVertexAttributes); uint32 maxColorAttachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, reinterpret_cast<GLint *>(&maxColorAttachments)); Log_DevPrintf("glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS): %u", maxColorAttachments); // max uniform buffers uint32 maxUniformBufferBindings = 0; glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, reinterpret_cast<GLint *>(&maxUniformBufferBindings)); Log_DevPrintf("glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS): %u", maxUniformBufferBindings); // check minspec if (maxVertexAttributes < GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS || maxColorAttachments < GPU_MAX_SIMULTANEOUS_RENDER_TARGETS) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Requires support for at least %u vertex attributes and %u render targets. (%u/%u)", (uint32)GPU_INPUT_LAYOUT_MAX_ELEMENTS, (uint32)GPU_MAX_SIMULTANEOUS_RENDER_TARGETS, maxVertexAttributes, maxColorAttachments); SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(pMainSDLGLContext); return false; } // for debugging only if (CVars::r_opengl_disable_vertex_attrib_binding.GetBool()) *const_cast<int *>(&GLAD_GL_ARB_vertex_attrib_binding) = GL_FALSE; if (CVars::r_opengl_disable_direct_state_access.GetBool()) *const_cast<int *>(&GLAD_GL_EXT_direct_state_access) = GL_FALSE; if (CVars::r_opengl_disable_multi_bind.GetBool()) *const_cast<int *>(&GLAD_GL_ARB_multi_bind) = GL_FALSE; // log warnings about missing but not required extensions if (!GLAD_GL_ARB_vertex_attrib_binding) Log_WarningPrint("Missing GL_ARB_vertex_attrib_binding, performance will suffer as a result. Please update your drivers."); else Log_InfoPrint("Using GL_ARB_vertex_attrib_binding."); // multi bind if (!GLAD_GL_ARB_multi_bind) Log_WarningPrint("Missing GL_ARB_multi_bind, performance will suffer as a result. Please update your drivers."); else Log_InfoPrint("Using GL_ARB_multi_bind."); // direct state access if (!GLAD_GL_EXT_direct_state_access) Log_WarningPrint("Missing GL_EXT_direct_state_access, performance will suffer as a result. Please update your drivers."); else Log_InfoPrint("Using GL_EXT_direct_state_access."); // direct state access if (GLAD_GL_ARB_copy_image) Log_InfoPrint("Using GL_ARB_copy_image."); else if (GLAD_GL_NV_copy_image) Log_InfoPrint("Using GL_NV_copy_image."); else Log_WarningPrint("Missing GL_ARB_copy_image and GL_NV_copy_image, performance will suffer as a result. Please update your drivers."); // create output buffer OpenGLGPUOutputBuffer *pImplicitOutputBuffer = new OpenGLGPUOutputBuffer(pSDLWindow, outputBackBufferFormat, outputDepthStencilFormat, pCreateParameters->ImplicitSwapChainVSyncType, false); // create device and context OpenGLGPUDevice *pDevice = new OpenGLGPUDevice(pMainSDLGLContext, pOffThreadGLContext, pImplicitOutputBuffer, featureLevel, texturePlatform, outputBackBufferFormat, outputDepthStencilFormat); OpenGLGPUContext *pContext = new OpenGLGPUContext(pDevice, pMainSDLGLContext, pImplicitOutputBuffer); if (!pContext->Create()) { Log_ErrorPrintf("OpenGLRenderBackend::Create: Could not create device context."); pImplicitOutputBuffer->Release(); pContext->Release(); pDevice->Release(); return false; } // set pointers *ppDevice = pDevice; *ppImmediateContext = pContext; *ppOutputBuffer = pImplicitOutputBuffer; Log_InfoPrint("OpenGL render backend creation successful."); return true; } <file_sep>/Editor/Source/Editor/MaterialShaderEditor/EditorMaterialShaderEditor.h #pragma once #include "Editor/Common.h" #include "Engine/MaterialShader.h" #include "ResourceCompiler/MaterialShaderGenerator.h" class Material; struct INPUT_EVENT_KEYBOARD; struct INPUT_EVENT_MOUSE; class EditorMaterialShaderEditorCallbacks { public: virtual void OnMaterialPropertiesChanged() = 0; virtual void OnMaterialParametersChanged() = 0; }; class EditorMaterialShaderEditor { public: EditorMaterialShaderEditor(EditorMaterialShaderEditorCallbacks *pCallbacks); ~EditorMaterialShaderEditor(); // accessors const bool GetShaderCodeAvailability(RENDERER_FEATURE_LEVEL featureLevel) const { return m_pShaderGenerator->GetShaderCodeAvailability(featureLevel); } String *CreateShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->CreateShaderCode(featureLevel); } const String *GetShaderCode(RENDERER_FEATURE_LEVEL featureLevel) const { return m_pShaderGenerator->GetShaderCode(featureLevel); } String *GetShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->GetShaderCode(featureLevel); } void DeleteShaderCode(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->DeleteShaderCode(featureLevel); } const bool GetShaderGraphAvailability(RENDERER_FEATURE_LEVEL featureLevel) const { return m_pShaderGenerator->GetShaderGraphAvailability(featureLevel); } ShaderGraph *CreateShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->CreateShaderGraph(nullptr, featureLevel); } const ShaderGraph *GetShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) const { return m_pShaderGenerator->GetShaderGraph(featureLevel); } ShaderGraph *GetShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->GetShaderGraph(featureLevel); } void DeleteShaderGraph(RENDERER_FEATURE_LEVEL featureLevel) { return m_pShaderGenerator->DeleteShaderGraph(featureLevel); } // previews const MaterialShader *GetPreviewMaterialShader() const; const Material *GetPreviewMaterial() const; bool RegeneratePreviewMaterials() const; // shader loaders void CreateShader(); bool LoadShader(const char *fileName, ByteStream *pStream); bool SaveShader(ByteStream *pStream); // material property getters const MATERIAL_BLENDING_MODE GetBlendingMode() const { return m_pShaderGenerator->GetBlendMode(); } const MATERIAL_LIGHTING_MODEL GetLightingModel() const { return m_pShaderGenerator->GetLightingModel(); } const bool GetDoubleSidedLighting() const { return m_pShaderGenerator->GetTwoSided(); } // material parameter getters const uint32 GetUniformParameterCount() const { return m_pShaderGenerator->GetUniformParameterCount(); } const MaterialShaderGenerator::UniformParameter *GetUniformParameter(uint32 i) const { return m_pShaderGenerator->GetUniformParameter(i); } const uint32 GetTextureParameterCount() const { return m_pShaderGenerator->GetTextureParameterCount(); } const MaterialShaderGenerator::TextureParameter *GetTextureParameter(uint32 i) const { return m_pShaderGenerator->GetTextureParameter(i); } const uint32 GetStaticSwitchParameterCount() const { return m_pShaderGenerator->GetStaticSwitchParameterCount(); } const MaterialShaderGenerator::StaticSwitchParameter *GetStaticSwitchParameter(uint32 i) const { return m_pShaderGenerator->GetStaticSwitchParameter(i); } // material property setters void SetBlendingMode(MATERIAL_BLENDING_MODE BlendingMode, bool SupressCallbacks = false); void SetLightingMode(MATERIAL_LIGHTING_MODEL LightingMode, bool SupressCallbacks = false); void SetDoubleSidedLighting(bool Enabled, bool SupressCallbacks = false); // material parameter manipulators // uniform bool AddUniformParameter(const char *ParameterName, const char *ParameterDefaultValue, bool SupressCallbacks = false); bool RenameUniformParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks = false); bool ChangeUniformParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks = false); bool RemoveUniformParameter(const char *ParameterName, bool SupressCallbacks = false); // texture bool AddTextureParameter(const char *ParameterName, TEXTURE_TYPE textureType, const char *ParameterDefaultValue, bool SupressCallbacks = false); bool RenameTextureParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks = false); bool ChangeTextureParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks = false); bool RemoveTextureParameter(const char *ParameterName, bool SupressCallbacks = false); // static switch bool AddStaticSwitchParameter(const char *ParameterName, const char *ParameterDefaultValue, bool SupressCallbacks = false); bool RenameStaticSwitchParameter(const char *ParameterName, const char *NewParameterName, bool SupressCallbacks = false); bool ChangeStaticSwitchParameterDefaultValue(const char *ParameterName, const char *NewDefaultValue, bool SupressCallbacks = false); bool RemoveStaticSwitchParameter(const char *ParameterName, bool SupressCallbacks = false); private: // callback interface EditorMaterialShaderEditorCallbacks *m_pCallbacks; // shader generator, and generated shader MaterialShaderGenerator *m_pShaderGenerator; // we can't render a shader directly, it needs an actual material attached to it. so, we generate one on the fly. mutable MaterialShader *m_pPreviewMaterialShader; mutable Material *m_pPreviewMaterial; mutable bool m_bRegeneratePreviewMaterial; }; <file_sep>/Engine/Source/Engine/ScriptObjectTypeInfo.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptObjectTypeInfo.h" #include "Engine/ScriptObject.h" #include "Engine/ScriptManager.h" ScriptObjectTypeInfo::ScriptObjectTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory, uint32 scriptFlags, const SCRIPT_FUNCTION_TABLE_ENTRY *pScriptFunctions) : ObjectTypeInfo(TypeName, pParentTypeInfo, pPropertyDeclarations, pFactory), m_pScriptFunctions(pScriptFunctions), m_scriptFlags(scriptFlags), m_nScriptFunctions(0), m_metaTableReference(INVALID_SCRIPT_REFERENCE) { if (pScriptFunctions != nullptr) { // count functions for (m_nScriptFunctions = 0; m_pScriptFunctions[m_nScriptFunctions].FunctionPointer != nullptr; m_nScriptFunctions++) { } } } ScriptObjectTypeInfo::~ScriptObjectTypeInfo() { } bool ScriptObjectTypeInfo::RegisterScriptType() { DebugAssert(m_metaTableReference == INVALID_SCRIPT_REFERENCE); // find script flags, and the number of functions uint32 scriptFlags = m_scriptFlags; uint32 functionCount = 0; for (const ScriptObjectTypeInfo *pTypeInfo = this;;) { // add flags if (pTypeInfo->m_scriptFlags & SCRIPT_OBJECT_FLAG_TABLED) scriptFlags |= SCRIPT_OBJECT_FLAG_TABLED; // add functions functionCount += pTypeInfo->m_nScriptFunctions; // move to parent if (pTypeInfo->m_pParentType != nullptr && pTypeInfo->m_pParentType->IsDerived(OBJECT_TYPEINFO(ScriptObject))) pTypeInfo = static_cast<const ScriptObjectTypeInfo *>(pTypeInfo->m_pParentType); else break; } // add functions once again SCRIPT_FUNCTION_TABLE_ENTRY *pFunctions = (functionCount > 0) ? (SCRIPT_FUNCTION_TABLE_ENTRY *)alloca(sizeof(SCRIPT_FUNCTION_TABLE_ENTRY) * (functionCount + 1)) : nullptr; uint32 nFunctions = 0; for (const ScriptObjectTypeInfo *pTypeInfo = this;;) { for (uint32 i = 0; i < pTypeInfo->m_nScriptFunctions; i++) { DebugAssert(nFunctions < functionCount); pFunctions[nFunctions].FunctionName = pTypeInfo->m_pScriptFunctions[i].FunctionName; pFunctions[nFunctions].FunctionPointer = pTypeInfo->m_pScriptFunctions[i].FunctionPointer; nFunctions++; } // move to parent if (pTypeInfo->m_pParentType != nullptr && pTypeInfo->m_pParentType->IsDerived(OBJECT_TYPEINFO(ScriptObject))) pTypeInfo = static_cast<const ScriptObjectTypeInfo *>(pTypeInfo->m_pParentType); else break; } // add null entry if (nFunctions > 0) { pFunctions[nFunctions].FunctionName = nullptr; pFunctions[nFunctions].FunctionPointer = nullptr; } // create the userdata type if (scriptFlags & SCRIPT_OBJECT_FLAG_TABLED) m_metaTableReference = g_pScriptManager->DefineTabledUserDataType(GetTypeName(), pFunctions, nullptr, nullptr, nullptr); else m_metaTableReference = g_pScriptManager->DefineTabledUserDataType(GetTypeName(), pFunctions, nullptr, nullptr, nullptr); return (m_metaTableReference != INVALID_SCRIPT_REFERENCE); } void ScriptObjectTypeInfo::UnregisterScriptType() { if (m_metaTableReference == INVALID_SCRIPT_REFERENCE) return; // drop the reference to the metatable g_pScriptManager->ReleaseReference(m_metaTableReference); m_metaTableReference = INVALID_SCRIPT_REFERENCE; } void ScriptObjectTypeInfo::RegisterType() { // register object stuff ObjectTypeInfo::RegisterType(); } void ScriptObjectTypeInfo::UnregisterType() { } void ScriptObjectTypeInfo::RegisterAllScriptTypes() { // iterate types, looking for those that inherit ScriptObject const RegistryType &registry = GetRegistry(); for (uint32 typeIndex = 0; typeIndex < registry.GetNumTypes(); typeIndex++) { const ObjectTypeInfo *pObjectTypeInfo = registry.GetTypeInfoByIndex(typeIndex); if (pObjectTypeInfo == nullptr || !pObjectTypeInfo->IsDerived(OBJECT_TYPEINFO(ScriptObject))) continue; // ugh, hack ScriptObjectTypeInfo *pScriptObjectTypeInfo = const_cast<ScriptObjectTypeInfo *>(static_cast<const ScriptObjectTypeInfo *>(pObjectTypeInfo)); pScriptObjectTypeInfo->RegisterScriptType(); } } void ScriptObjectTypeInfo::UnregisterAllScriptTypes() { // iterate types, looking for those that inherit ScriptObject const RegistryType &registry = GetRegistry(); for (uint32 typeIndex = 0; typeIndex < registry.GetNumTypes(); typeIndex++) { const ObjectTypeInfo *pObjectTypeInfo = registry.GetTypeInfoByIndex(typeIndex); if (pObjectTypeInfo == nullptr || !pObjectTypeInfo->IsDerived(OBJECT_TYPEINFO(ScriptObject))) continue; // ugh, hack ScriptObjectTypeInfo *pScriptObjectTypeInfo = const_cast<ScriptObjectTypeInfo *>(static_cast<const ScriptObjectTypeInfo *>(pObjectTypeInfo)); pScriptObjectTypeInfo->UnregisterScriptType(); } } // void ScriptObjectTypeInfo::PushObject(lua_State *L, const ScriptObject *pObject) // { // ScriptReferenceType argRef = pObject->GetPersistentScriptObjectReference(); // if (argRef == INVALID_SCRIPT_REFERENCE) // lua_rawgeti(L, LUA_REGISTRYINDEX, argRef); // else // lua_pushnil(L); // } // // ScriptObject *ScriptObjectTypeInfo::CheckObject(lua_State *L, const ScriptObjectTypeInfo *pTypeInfo, int arg) // { // luaBackupStack(L); // // // should be a userdata // void *pUserData; // if (lua_type(L, arg) != LUA_TUSERDATA || (pUserData = lua_touserdata(L, arg)) == nullptr) // { // ScriptManager::GenerateTypeError(L, arg, pTypeInfo->GetMetaTableReference()); // return nullptr; // } // // // skip through each class, checking if any of the metatables match // const ScriptObjectTypeInfo *pCurrentTypeInfo = pTypeInfo; // while (pCurrentTypeInfo) // // // resolve metatable reference // lua_rawgeti(L, LUA_REGISTRYINDEX, metaTableReference); // DebugAssert(lua_istable(L, -1)); // // // get the parameter's metatable // lua_getmetatable(L, arg); // // // check they match // if (!lua_rawequal(L, -1, -2)) // { // lua_pop(L, 2); // GenerateTypeError(L, arg, metaTableReference); // return nullptr; // } // // // type is ok, pop metatable + table // lua_pop(L, 2); // luaVerifyStack(L, 0); // return pUserData; // } <file_sep>/Engine/Source/Engine/Physics/KinematicObject.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/KinematicObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/BulletHeaders.h" //Log_SetChannel(KinematicObject); namespace Physics { class KinematicObject::MotionState : public btMotionState { public: BT_DECLARE_ALIGNED_ALLOCATOR(); MotionState(const btTransform &transform) : m_transform(transform) {} virtual void getWorldTransform(btTransform& worldTrans) const override { worldTrans = m_transform; } virtual void setWorldTransform(const btTransform& worldTrans) override { m_transform = worldTrans; } private: btTransform m_transform; }; KinematicObject::KinematicObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform) : CollisionObject(entityID, pCollisionShape, transform), m_pBulletRigidBody(nullptr) { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // create motion state m_pMotionState = new MotionState(bulletTransform); // and RB construction info btRigidBody::btRigidBodyConstructionInfo rbConstructionInfo(0.0f, m_pMotionState, m_pCollisionShape->GetBulletShape()); // create bullet object m_pBulletRigidBody = new btRigidBody(rbConstructionInfo); m_pBulletRigidBody->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); m_pBulletRigidBody->forceActivationState(DISABLE_SIMULATION); m_pBulletRigidBody->setUserPointer(reinterpret_cast<void *>(this)); // update our aabb from bullet UpdateBoundingBox(); } KinematicObject::~KinematicObject() { delete m_pBulletRigidBody; delete m_pMotionState; } btCollisionObject *Physics::KinematicObject::GetBulletCollisionObject() const { return static_cast<btCollisionObject *>(m_pBulletRigidBody); } void Physics::KinematicObject::OnCollisionShapeChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet m_pBulletRigidBody->setCollisionShape(m_pCollisionShape->GetBulletShape()); m_pBulletRigidBody->setWorldTransform(bulletTransform); m_pMotionState->setWorldTransform(bulletTransform); // update aabb UpdateBoundingBox(); } void Physics::KinematicObject::OnTransformChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet, motion state only, since it will get pulled back next iteration m_pMotionState->setWorldTransform(bulletTransform); // fix up our copy of the aabb manually, since the collision object still contains the old transform btVector3 aabbMin, aabbMax; m_pCollisionShape->GetBulletShape()->getAabb(bulletTransform, aabbMin, aabbMax); m_boundingBox.SetBounds(BulletVector3ToFloat3(aabbMin), BulletVector3ToFloat3(aabbMax)); } void KinematicObject::OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) { PhysicsProxy::OnAddedToPhysicsWorld(pPhysicsWorld); pPhysicsWorld->GetBulletWorld()->addRigidBody(m_pBulletRigidBody); } void KinematicObject::OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) { pPhysicsWorld->GetBulletWorld()->removeRigidBody(m_pBulletRigidBody); PhysicsProxy::OnRemovedFromPhysicsWorld(pPhysicsWorld); } } // namespace Physics <file_sep>/Engine/Source/Renderer/RendererTypes.h #pragma once #include "Renderer/Common.h" // Forward declarations for all GPU objects class GPUResource; class GPUSamplerState; class GPURasterizerState; class GPUDepthStencilState; class GPUBlendState; class GPUBuffer; class GPUTexture; class GPUTexture1D; class GPUTexture1DArray; class GPUTexture2D; class GPUTexture2DArray; class GPUTexture3D; class GPUTextureCube; class GPUTextureCubeArray; class GPUDepthTexture; class GPUQuery; class GPUShaderProgram; class GPUShaderPipeline; class GPURenderTargetView; class GPUDepthStencilBufferView; class GPUComputeView; class GPUOutputBuffer; class RendererOutputWindow; class GPUContextConstants; class GPUContext; class GPUDevice; class GPUCommandList; class Renderer; // Platform i.e. API enum RENDERER_PLATFORM { RENDERER_PLATFORM_D3D11, RENDERER_PLATFORM_D3D12, RENDERER_PLATFORM_OPENGL, RENDERER_PLATFORM_OPENGLES2, RENDERER_PLATFORM_COUNT, }; // Each feature level is considered to be a superset of the previous level. enum RENDERER_FEATURE_LEVEL { RENDERER_FEATURE_LEVEL_ES2, RENDERER_FEATURE_LEVEL_ES3, RENDERER_FEATURE_LEVEL_SM4, RENDERER_FEATURE_LEVEL_SM5, RENDERER_FEATURE_LEVEL_COUNT, }; enum RENDERER_FULLSCREEN_STATE { RENDERER_FULLSCREEN_STATE_WINDOWED, RENDERER_FULLSCREEN_STATE_WINDOWED_FULLSCREEN, RENDERER_FULLSCREEN_STATE_FULLSCREEN, RENDERER_FULLSCREEN_STATE_COUNT, }; enum RENDERER_VSYNC_TYPE { RENDERER_VSYNC_TYPE_NONE, RENDERER_VSYNC_TYPE_VSYNC, RENDERER_VSYNC_TYPE_ADAPTIVE_VSYNC, RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING, RENDERER_VSYNC_TYPE_COUNT, }; enum GPU_PRESENT_BEHAVIOUR { GPU_PRESENT_BEHAVIOUR_IMMEDIATE, GPU_PRESENT_BEHAVIOUR_WAIT_FOR_VBLANK, GPU_PRESENT_BEHAVIOUR_COUNT }; enum GPU_INDEX_FORMAT { GPU_INDEX_FORMAT_UINT16, GPU_INDEX_FORMAT_UINT32, GPU_INDEX_FORMAT_COUNT, }; enum GPU_COMPARISON_FUNC { GPU_COMPARISON_FUNC_NEVER, GPU_COMPARISON_FUNC_LESS, GPU_COMPARISON_FUNC_EQUAL, GPU_COMPARISON_FUNC_LESS_EQUAL, GPU_COMPARISON_FUNC_GREATER, GPU_COMPARISON_FUNC_NOT_EQUAL, GPU_COMPARISON_FUNC_GREATER_EQUAL, GPU_COMPARISON_FUNC_ALWAYS, GPU_COMPARISON_FUNC_COUNT, }; enum DRAW_TOPOLOGY { DRAW_TOPOLOGY_UNDEFINED, DRAW_TOPOLOGY_POINTS, DRAW_TOPOLOGY_LINE_LIST, DRAW_TOPOLOGY_LINE_STRIP, DRAW_TOPOLOGY_TRIANGLE_LIST, DRAW_TOPOLOGY_TRIANGLE_STRIP, DRAW_TOPOLOGY_COUNT, }; int32 DrawTopology_CalculateNumVertices(DRAW_TOPOLOGY Topology, int32 nPrimitives); int32 DrawTopology_CalculateNumPrimitives(DRAW_TOPOLOGY Topology, int32 nVertices); enum GPU_MAP_TYPE { GPU_MAP_TYPE_READ, GPU_MAP_TYPE_READ_WRITE, GPU_MAP_TYPE_WRITE, GPU_MAP_TYPE_WRITE_DISCARD, GPU_MAP_TYPE_WRITE_NO_OVERWRITE, GPU_MAP_TYPE_COUNT, }; struct RENDERER_SCISSOR_RECT { uint32 Left; uint32 Top; uint32 Right; uint32 Bottom; RENDERER_SCISSOR_RECT() {} RENDERER_SCISSOR_RECT(uint32 left, uint32 top, uint32 right, uint32 bottom) : Left(left), Top(top), Right(right), Bottom(bottom) {} void Set(uint32 left, uint32 top, uint32 right, uint32 bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } }; struct RENDERER_VIEWPORT { uint32 TopLeftX; uint32 TopLeftY; uint32 Width; uint32 Height; float MinDepth; float MaxDepth; RENDERER_VIEWPORT() {} RENDERER_VIEWPORT(uint32 topLeftX, uint32 topLeftY, uint32 width, uint32 height, float minDepth, float maxDepth) : TopLeftX(topLeftX), TopLeftY(topLeftY), Width(width), Height(height), MinDepth(minDepth), MaxDepth(maxDepth) {} void Set(uint32 topLeftX, uint32 topLeftY, uint32 width, uint32 height, float minDepth, float maxDepth) { TopLeftX = topLeftX; TopLeftY = topLeftY; Width = width; Height = height; MinDepth = minDepth; MaxDepth = maxDepth; } }; enum GPU_RESOURCE_TYPE { GPU_RESOURCE_TYPE_RASTERIZER_STATE, GPU_RESOURCE_TYPE_DEPTH_STENCIL_STATE, GPU_RESOURCE_TYPE_BLEND_STATE, GPU_RESOURCE_TYPE_SAMPLER_STATE, GPU_RESOURCE_TYPE_BUFFER, GPU_RESOURCE_TYPE_TEXTURE1D, GPU_RESOURCE_TYPE_TEXTURE1DARRAY, GPU_RESOURCE_TYPE_TEXTURE2D, GPU_RESOURCE_TYPE_TEXTURE2DARRAY, GPU_RESOURCE_TYPE_TEXTURE3D, GPU_RESOURCE_TYPE_TEXTURECUBE, GPU_RESOURCE_TYPE_TEXTURECUBEARRAY, GPU_RESOURCE_TYPE_TEXTUREBUFFER, GPU_RESOURCE_TYPE_DEPTH_TEXTURE, GPU_RESOURCE_TYPE_RENDER_TARGET_VIEW, GPU_RESOURCE_TYPE_DEPTH_BUFFER_VIEW, GPU_RESOURCE_TYPE_COMPUTE_VIEW, GPU_RESOURCE_TYPE_QUERY, GPU_RESOURCE_TYPE_SHADER_PROGRAM, GPU_RESOURCE_TYPE_SHADER_PIPELINE, GPU_RESOURCE_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(GPUResourceType); } #define GPU_MAX_SIMULTANEOUS_RENDER_TARGETS (8) #define GPU_MAX_SIMULTANEOUS_VERTEX_BUFFERS (8) #define GPU_INPUT_LAYOUT_MAX_ELEMENTS (16) enum GPU_VERTEX_ELEMENT_TYPE { GPU_VERTEX_ELEMENT_TYPE_BYTE, GPU_VERTEX_ELEMENT_TYPE_BYTE2, GPU_VERTEX_ELEMENT_TYPE_BYTE4, GPU_VERTEX_ELEMENT_TYPE_UBYTE, GPU_VERTEX_ELEMENT_TYPE_UBYTE2, GPU_VERTEX_ELEMENT_TYPE_UBYTE4, GPU_VERTEX_ELEMENT_TYPE_HALF, GPU_VERTEX_ELEMENT_TYPE_HALF2, GPU_VERTEX_ELEMENT_TYPE_HALF4, GPU_VERTEX_ELEMENT_TYPE_FLOAT, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, GPU_VERTEX_ELEMENT_TYPE_FLOAT3, GPU_VERTEX_ELEMENT_TYPE_FLOAT4, GPU_VERTEX_ELEMENT_TYPE_INT, GPU_VERTEX_ELEMENT_TYPE_INT2, GPU_VERTEX_ELEMENT_TYPE_INT3, GPU_VERTEX_ELEMENT_TYPE_INT4, GPU_VERTEX_ELEMENT_TYPE_UINT, GPU_VERTEX_ELEMENT_TYPE_UINT2, GPU_VERTEX_ELEMENT_TYPE_UINT3, GPU_VERTEX_ELEMENT_TYPE_UINT4, GPU_VERTEX_ELEMENT_TYPE_SNORM4, GPU_VERTEX_ELEMENT_TYPE_UNORM4, GPU_VERTEX_ELEMENT_TYPE_COUNT, }; enum GPU_VERTEX_ELEMENT_SEMANTIC { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD, GPU_VERTEX_ELEMENT_SEMANTIC_COLOR, GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT, GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL, GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL, GPU_VERTEX_ELEMENT_SEMANTIC_POINTSIZE, GPU_VERTEX_ELEMENT_SEMANTIC_BLENDINDICES, GPU_VERTEX_ELEMENT_SEMANTIC_BLENDWEIGHTS, GPU_VERTEX_ELEMENT_SEMANTIC_COUNT, }; struct GPU_VERTEX_ELEMENT_DESC { GPU_VERTEX_ELEMENT_SEMANTIC Semantic; uint32 SemanticIndex; GPU_VERTEX_ELEMENT_TYPE Type; uint32 StreamIndex; uint32 StreamOffset; uint32 InstanceStepRate; GPU_VERTEX_ELEMENT_DESC() {} GPU_VERTEX_ELEMENT_DESC(GPU_VERTEX_ELEMENT_SEMANTIC semantic, uint32 semanticIndex, GPU_VERTEX_ELEMENT_TYPE type, uint32 streamIndex, uint32 streamOffset, uint32 instanceStepRate) : Semantic(semantic), SemanticIndex(semanticIndex), Type(type), StreamIndex(streamIndex), StreamOffset(streamOffset), InstanceStepRate(instanceStepRate) {} void Set(GPU_VERTEX_ELEMENT_SEMANTIC semantic, uint32 semanticIndex, GPU_VERTEX_ELEMENT_TYPE type, uint32 streamIndex, uint32 streamOffset, uint32 instanceStepRate) { Semantic = semantic; SemanticIndex = semanticIndex; Type = type; StreamIndex = streamIndex; StreamOffset = streamOffset; InstanceStepRate = instanceStepRate; } }; enum GPU_QUERY_TYPE { GPU_QUERY_TYPE_SAMPLES_PASSED, // uint64 GPU_QUERY_TYPE_OCCLUSION, // bool GPU_QUERY_TYPE_PRIMITIVES_GENERATED, // uint64 GPU_QUERY_TYPE_TIMESTAMP, // api-specific key GPU_QUERY_TYPE_FREQUENCY, // frequency to divide timestamp by to get seconds, 0 if unstable GPU_QUERY_TYPE_COUNT, }; enum GPU_QUERY_GETDATA_FLAGS { GPU_QUERY_GETDATA_FLAG_NOFLUSH = (1 << 0), }; enum GPU_QUERY_GETDATA_RESULT { GPU_QUERY_GETDATA_RESULT_OK, GPU_QUERY_GETDATA_RESULT_NOT_READY, GPU_QUERY_GETDATA_RESULT_ERROR, }; enum SHADER_PROGRAM_STAGE { SHADER_PROGRAM_STAGE_VERTEX_SHADER, SHADER_PROGRAM_STAGE_HULL_SHADER, SHADER_PROGRAM_STAGE_DOMAIN_SHADER, SHADER_PROGRAM_STAGE_GEOMETRY_SHADER, SHADER_PROGRAM_STAGE_PIXEL_SHADER, SHADER_PROGRAM_STAGE_COMPUTE_SHADER, SHADER_PROGRAM_STAGE_COUNT, }; enum SHADER_PROGRAM_STAGE_MASK { SHADER_PROGRAM_STAGE_MASK_VERTEX_SHADER = (1 << SHADER_PROGRAM_STAGE_VERTEX_SHADER), SHADER_PROGRAM_STAGE_MASK_HULL_SHADER = (1 << SHADER_PROGRAM_STAGE_HULL_SHADER), SHADER_PROGRAM_STAGE_MASK_DOMAIN_SHADER = (1 << SHADER_PROGRAM_STAGE_DOMAIN_SHADER), SHADER_PROGRAM_STAGE_MASK_GEOMETRY_SHADER = (1 << SHADER_PROGRAM_STAGE_GEOMETRY_SHADER), SHADER_PROGRAM_STAGE_MASK_PIXEL_SHADER = (1 << SHADER_PROGRAM_STAGE_PIXEL_SHADER), SHADER_PROGRAM_STAGE_MASK_COMPUTE_SHADER = (1 << SHADER_PROGRAM_STAGE_COMPUTE_SHADER), }; enum SHADER_GLOBAL_FLAG { SHADER_GLOBAL_FLAG_MATERIAL_TINT = (1 << 0), SHADER_GLOBAL_FLAG_SHADER_QUALITY_LOW = (1 << 1), SHADER_GLOBAL_FLAG_SHADER_QUALITY_MEDIUM = (1 << 2), SHADER_GLOBAL_FLAG_SHADER_QUALITY_HIGH = (1 << 3), SHADER_GLOBAL_FLAG_USE_VERTEX_ID_QUADS = (1 << 4) }; enum SHADER_PARAMETER_TYPE { // Value Types SHADER_PARAMETER_TYPE_BOOL, SHADER_PARAMETER_TYPE_BOOL2, SHADER_PARAMETER_TYPE_BOOL3, SHADER_PARAMETER_TYPE_BOOL4, SHADER_PARAMETER_TYPE_HALF, SHADER_PARAMETER_TYPE_HALF2, SHADER_PARAMETER_TYPE_HALF3, SHADER_PARAMETER_TYPE_HALF4, SHADER_PARAMETER_TYPE_INT, SHADER_PARAMETER_TYPE_INT2, SHADER_PARAMETER_TYPE_INT3, SHADER_PARAMETER_TYPE_INT4, SHADER_PARAMETER_TYPE_UINT, SHADER_PARAMETER_TYPE_UINT2, SHADER_PARAMETER_TYPE_UINT3, SHADER_PARAMETER_TYPE_UINT4, SHADER_PARAMETER_TYPE_FLOAT, SHADER_PARAMETER_TYPE_FLOAT2, SHADER_PARAMETER_TYPE_FLOAT3, SHADER_PARAMETER_TYPE_FLOAT4, SHADER_PARAMETER_TYPE_FLOAT2X2, SHADER_PARAMETER_TYPE_FLOAT3X3, SHADER_PARAMETER_TYPE_FLOAT3X4, SHADER_PARAMETER_TYPE_FLOAT4X4, // Texture Types SHADER_PARAMETER_TYPE_TEXTURE1D, SHADER_PARAMETER_TYPE_TEXTURE1DARRAY, SHADER_PARAMETER_TYPE_TEXTURE2D, SHADER_PARAMETER_TYPE_TEXTURE2DARRAY, SHADER_PARAMETER_TYPE_TEXTURE2DMS, SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY, SHADER_PARAMETER_TYPE_TEXTURE3D, SHADER_PARAMETER_TYPE_TEXTURECUBE, SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY, SHADER_PARAMETER_TYPE_TEXTUREBUFFER, // Resource Types SHADER_PARAMETER_TYPE_CONSTANT_BUFFER, SHADER_PARAMETER_TYPE_SAMPLER_STATE, SHADER_PARAMETER_TYPE_BUFFER, SHADER_PARAMETER_TYPE_STRUCT, // Count SHADER_PARAMETER_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(ShaderParameterType); } uint32 ShaderParameterValueTypeSize(SHADER_PARAMETER_TYPE Type); GPU_RESOURCE_TYPE ShaderParameterResourceType(SHADER_PARAMETER_TYPE Type); template<typename T> SHADER_PARAMETER_TYPE ShaderParameterTypeFor(); template<typename T> T ShaderParameterTypeFromString(const char *StringValue); void ShaderParameterTypeFromString(SHADER_PARAMETER_TYPE Type, void *pDestination, const char *StringValue); template<typename T> void ShaderParameterTypeToString(String &Destination, const T &Value); void ShaderParameterTypeToString(String &Destination, SHADER_PARAMETER_TYPE Type, const void *pValue); //-------------------------------- SamplerState ------------------------------- struct GPU_SAMPLER_STATE_DESC { TEXTURE_FILTER Filter; TEXTURE_ADDRESS_MODE AddressU; TEXTURE_ADDRESS_MODE AddressV; TEXTURE_ADDRESS_MODE AddressW; float4 BorderColor; float LODBias; int32 MinLOD; int32 MaxLOD; uint32 MaxAnisotropy; GPU_COMPARISON_FUNC ComparisonFunc; GPU_SAMPLER_STATE_DESC() {} GPU_SAMPLER_STATE_DESC(TEXTURE_FILTER filter, TEXTURE_ADDRESS_MODE addressU, TEXTURE_ADDRESS_MODE addressV, TEXTURE_ADDRESS_MODE addressW, const float4 &borderColor, float lodBias, int32 minLOD, int32 maxLOD, uint32 maxAnisotropy, GPU_COMPARISON_FUNC comparisonFunc) : Filter(filter), AddressU(addressU), AddressV(addressV), AddressW(addressW), BorderColor(borderColor), LODBias(lodBias), MinLOD(minLOD), MaxLOD(maxLOD), MaxAnisotropy(maxAnisotropy), ComparisonFunc(comparisonFunc) {} void Set(TEXTURE_FILTER filter, TEXTURE_ADDRESS_MODE addressU, TEXTURE_ADDRESS_MODE addressV, TEXTURE_ADDRESS_MODE addressW, const float4 &borderColor, float lodBias, int32 minLOD, int32 maxLOD, uint32 maxAnisotropy, GPU_COMPARISON_FUNC comparisonFunc) { Filter = filter; AddressU = addressU; AddressV = addressV; AddressW = addressW; BorderColor = borderColor; LODBias = lodBias; MinLOD = minLOD; MaxLOD = maxLOD; MaxAnisotropy = maxAnisotropy; ComparisonFunc = comparisonFunc; } }; //-------------------------------- RasterizerState ------------------------------- enum RENDERER_FILL_MODE { RENDERER_FILL_WIREFRAME, RENDERER_FILL_SOLID, RENDERER_FILL_MODE_COUNT, }; enum RENDERER_CULL_MODE { RENDERER_CULL_NONE, RENDERER_CULL_FRONT, RENDERER_CULL_BACK, RENDERER_CULL_MODE_COUNT, }; struct RENDERER_RASTERIZER_STATE_DESC { RENDERER_FILL_MODE FillMode; RENDERER_CULL_MODE CullMode; bool FrontCounterClockwise; bool ScissorEnable; int32 DepthBias; float SlopeScaledDepthBias; bool DepthClipEnable; }; //-------------------------------- DepthStencilState ------------------------------- enum RENDERER_STENCIL_OP { RENDERER_STENCIL_OP_KEEP, RENDERER_STENCIL_OP_ZERO, RENDERER_STENCIL_OP_REPLACE, RENDERER_STENCIL_OP_INCREMENT_CLAMPED, RENDERER_STENCIL_OP_DECREMENT_CLAMPED, RENDERER_STENCIL_OP_INVERT, RENDERER_STENCIL_OP_INCREMENT, RENDERER_STENCIL_OP_DECREMENT, RENDERER_STENCIL_OP_COUNT, }; struct RENDERER_FACE_STENCIL_OP { RENDERER_STENCIL_OP FailOp; RENDERER_STENCIL_OP DepthFailOp; RENDERER_STENCIL_OP PassOp; GPU_COMPARISON_FUNC CompareFunc; }; struct RENDERER_DEPTHSTENCIL_STATE_DESC { bool DepthTestEnable; bool DepthWriteEnable; GPU_COMPARISON_FUNC DepthFunc; bool StencilTestEnable; uint8 StencilReadMask; uint8 StencilWriteMask; RENDERER_FACE_STENCIL_OP StencilFrontFace; RENDERER_FACE_STENCIL_OP StencilBackFace; }; //-------------------------------- BlendState ------------------------------- enum RENDERER_BLEND_OPTION { RENDERER_BLEND_ZERO, RENDERER_BLEND_ONE, RENDERER_BLEND_SRC_COLOR, RENDERER_BLEND_INV_SRC_COLOR, RENDERER_BLEND_SRC_ALPHA, RENDERER_BLEND_INV_SRC_ALPHA, RENDERER_BLEND_DEST_ALPHA, RENDERER_BLEND_INV_DEST_ALPHA, RENDERER_BLEND_DEST_COLOR, RENDERER_BLEND_INV_DEST_COLOR, RENDERER_BLEND_SRC_ALPHA_SAT, RENDERER_BLEND_BLEND_FACTOR, RENDERER_BLEND_INV_BLEND_FACTOR, RENDERER_BLEND_SRC1_COLOR, RENDERER_BLEND_INV_SRC1_COLOR, RENDERER_BLEND_SRC1_ALPHA, RENDERER_BLEND_INV_SRC1_ALPHA, RENDERER_BLEND_OPTION_COUNT, }; enum RENDERER_BLEND_OP { RENDERER_BLEND_OP_ADD, RENDERER_BLEND_OP_SUBTRACT, RENDERER_BLEND_OP_REV_SUBTRACT, RENDERER_BLEND_OP_MIN, RENDERER_BLEND_OP_MAX, RENDERER_BLEND_OP_COUNT, }; struct RENDERER_BLEND_STATE_DESC { bool BlendEnable; RENDERER_BLEND_OPTION SrcBlend; RENDERER_BLEND_OP BlendOp; RENDERER_BLEND_OPTION DestBlend; RENDERER_BLEND_OPTION SrcBlendAlpha; RENDERER_BLEND_OP BlendOpAlpha; RENDERER_BLEND_OPTION DestBlendAlpha; bool ColorWriteEnable; }; enum GPU_TEXTURE_FLAGS { GPU_TEXTURE_FLAG_READABLE = (1 << 0), // Able to be read from user code. Usually via staging buffer. GPU_TEXTURE_FLAG_WRITABLE = (1 << 1), // Able to be written to from user code. Usually via staging buffer. GPU_TEXTURE_FLAG_SHADER_BINDABLE = (1 << 2), // Bindable to shader samplers/resources. GPU_TEXTURE_FLAG_BIND_RENDER_TARGET = (1 << 3), // Bindable as a render target. GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER = (1 << 4), // Bindable as depth stencil buffer. GPU_TEXTURE_FLAG_BIND_COMPUTE_WRITABLE = (1 << 5), // Binds to image units in OpenGL, or unordered access views in Direct3D GPU_TEXTURE_FLAG_GENERATE_MIPS = (1 << 6) // Supports real time mip generation }; struct GPU_TEXTURE1D_DESC { uint32 Width; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; GPU_TEXTURE1D_DESC() {} GPU_TEXTURE1D_DESC(uint32 width, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) : Width(width), Format(format), Flags(flags), MipLevels(mipLevels) {} void Set(uint32 width, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) { Width = width; Format = format; Flags = flags; MipLevels = mipLevels; } }; struct GPU_TEXTURE1DARRAY_DESC { uint32 Width; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; uint32 ArraySize; GPU_TEXTURE1DARRAY_DESC() {} GPU_TEXTURE1DARRAY_DESC(uint32 width, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) : Width(width), Format(format), Flags(flags), MipLevels(mipLevels), ArraySize(arraySize) {} void Set(uint32 width, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) { Width = width; Format = format; Flags = flags; MipLevels = mipLevels; ArraySize = arraySize; } }; struct GPU_TEXTURE2D_DESC { uint32 Width; uint32 Height; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; GPU_TEXTURE2D_DESC() {} GPU_TEXTURE2D_DESC(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) : Width(width), Height(height), Format(format), Flags(flags), MipLevels(mipLevels) {} void Set(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) { Width = width; Height = height; Format = format; Flags = flags; MipLevels = mipLevels; } }; struct GPU_TEXTURE2DARRAY_DESC { uint32 Width; uint32 Height; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; uint32 ArraySize; GPU_TEXTURE2DARRAY_DESC() {} GPU_TEXTURE2DARRAY_DESC(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) : Width(width), Height(height), Format(format), Flags(flags), MipLevels(mipLevels), ArraySize(arraySize) {} void Set(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) { Width = width; Height = height; Format = format; Flags = flags; MipLevels = mipLevels; ArraySize = arraySize; } }; struct GPU_TEXTURE3D_DESC { uint32 Width; uint32 Height; uint32 Depth; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; GPU_TEXTURE3D_DESC() {} GPU_TEXTURE3D_DESC(uint32 width, uint32 height, uint32 depth, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) : Width(width), Height(height), Depth(depth), Format(format), Flags(flags), MipLevels(mipLevels) {} void Set(uint32 width, uint32 height, uint32 depth, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) { Width = width; Height = height; Depth = depth; Format = format; Flags = flags; MipLevels = mipLevels; } }; struct GPU_TEXTURECUBE_DESC { uint32 Width; uint32 Height; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; GPU_TEXTURECUBE_DESC() {} GPU_TEXTURECUBE_DESC(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) : Width(width), Height(height), Format(format), Flags(flags), MipLevels(mipLevels) {} void Set(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels) { Width = width; Height = height; Format = format; Flags = flags; MipLevels = mipLevels; } }; struct GPU_TEXTURECUBEARRAY_DESC { uint32 Width; uint32 Height; PIXEL_FORMAT Format; uint32 Flags; uint32 MipLevels; uint32 ArraySize; GPU_TEXTURECUBEARRAY_DESC() {} GPU_TEXTURECUBEARRAY_DESC(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) : Width(width), Height(height), Format(format), Flags(flags), MipLevels(mipLevels), ArraySize(arraySize) {} void Set(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags, uint32 mipLevels, uint32 arraySize) { Width = width; Height = height; Format = format; Flags = flags; MipLevels = mipLevels; ArraySize = arraySize; } }; struct GPU_DEPTH_TEXTURE_DESC { uint32 Width; uint32 Height; PIXEL_FORMAT Format; uint32 Flags; GPU_DEPTH_TEXTURE_DESC() {} GPU_DEPTH_TEXTURE_DESC(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags) : Width(width), Height(height), Format(format), Flags(flags) {} void Set(uint32 width, uint32 height, PIXEL_FORMAT format, uint32 flags) { Width = width; Height = height; Format = format; Flags = flags; } }; enum GPU_BUFFER_FLAGS { GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER = (1 << 0), GPU_BUFFER_FLAG_BIND_INDEX_BUFFER = (1 << 1), GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER = (1 << 2), GPU_BUFFER_FLAG_READABLE = (1 << 4), GPU_BUFFER_FLAG_WRITABLE = (1 << 5), GPU_BUFFER_FLAG_MAPPABLE = (1 << 6), }; struct GPU_BUFFER_DESC { uint32 Flags; uint32 Size; GPU_BUFFER_DESC() {} GPU_BUFFER_DESC(uint32 flags, uint32 size) : Flags(flags), Size(size) {} }; struct GPU_RENDER_TARGET_VIEW_DESC { GPU_RENDER_TARGET_VIEW_DESC() {} GPU_RENDER_TARGET_VIEW_DESC(uint32 mipLevel, uint32 firstLayerIndex, uint32 numLayers, PIXEL_FORMAT format) : MipLevel(mipLevel), FirstLayerIndex(firstLayerIndex), NumLayers(numLayers), Format(format) {} GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1D *pTexture, uint32 mipLevel = 0); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1DArray *pTexture, uint32 mipLevel = 0); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture1DArray *pTexture, uint32 mipLevel, uint32 arrayIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2D *pTexture, uint32 mipLevel = 0); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel = 0); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel, uint32 arrayIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUTexture3D *pTexture, uint32 mipLevel, uint32 slideIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel = 0); GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel, CUBE_FACE faceIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex, CUBE_FACE faceIndex); GPU_RENDER_TARGET_VIEW_DESC(GPUDepthTexture *pTexture); void Set(uint32 mipLevel, uint32 firstLayerIndex, uint32 numLayers, PIXEL_FORMAT format) { MipLevel = mipLevel; FirstLayerIndex = firstLayerIndex; NumLayers = numLayers; Format = format; } uint32 MipLevel; uint32 FirstLayerIndex; uint32 NumLayers; PIXEL_FORMAT Format; }; struct GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC { GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC() {} GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(uint32 mipLevel, uint32 firstLayerIndex, uint32 numLayers, PIXEL_FORMAT format) : MipLevel(mipLevel), FirstLayerIndex(firstLayerIndex), NumLayers(numLayers), Format(format) {} GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2D *pTexture, uint32 mipLevel = 0); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel = 0); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTexture2DArray *pTexture, uint32 mipLevel, uint32 arrayIndex); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel = 0); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCube *pTexture, uint32 mipLevel, CUBE_FACE faceIndex); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUTextureCubeArray *pTexture, uint32 mipLevel, uint32 arrayIndex, CUBE_FACE faceIndex); GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC(GPUDepthTexture *pTexture); void Set(uint32 mipLevel, uint32 firstLayerIndex, uint32 numLayers, PIXEL_FORMAT format) { MipLevel = mipLevel; FirstLayerIndex = firstLayerIndex; NumLayers = numLayers; Format = format; } uint32 MipLevel; uint32 FirstLayerIndex; uint32 NumLayers; PIXEL_FORMAT Format; }; struct GPU_COMPUTE_VIEW_DESC { GPU_COMPUTE_VIEW_DESC() {} union { struct { uint32 StartOffset; uint32 Stride; } Buffer; struct { uint32 MipLevel; uint32 FirstLayerIndex; uint32 NumLayers; } Texture; }; }; enum RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER { RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_LINEAR, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_COUNT, }; enum RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE { RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_NONE, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_ADDITIVE, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_ALPHA_BLENDING, NUM_RENDERER_FRAMEBUFFER_BLIT_BLEND_MODES }; // World renderer stuff enum RENDERER_FOG_MODE { RENDERER_FOG_MODE_NONE, RENDERER_FOG_MODE_LINEAR, RENDERER_FOG_MODE_EXP, RENDERER_FOG_MODE_EXP2, RENDERER_FOG_MODE_COUNT, }; enum RENDERER_SHADOW_FILTER { RENDERER_SHADOW_FILTER_1X1, RENDERER_SHADOW_FILTER_3X3, RENDERER_SHADOW_FILTER_5X5, NUM_RENDERER_SHADOW_FILTERS }; namespace NameTables { Y_Declare_NameTable(RendererFogMode); } // Nametables namespace NameTables { Y_Declare_NameTable(RendererPlatform); Y_Declare_NameTable(RendererPlatformFullName); Y_Declare_NameTable(RendererFeatureLevel); Y_Declare_NameTable(RendererFeatureLevelFullName); Y_Declare_NameTable(RendererComparisonFunc); Y_Declare_NameTable(GPUVertexElementType); Y_Declare_NameTable(GPUVertexElementSemantic); Y_Declare_NameTable(ShaderProgramStage); Y_Declare_NameTable(RendererFillModes); Y_Declare_NameTable(RendererCullModes); Y_Declare_NameTable(RendererBlendOptions); Y_Declare_NameTable(RendererBlendOps); } <file_sep>/Engine/Source/Engine/Material.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Material.h" #include "Engine/Texture.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" Log_SetChannel(Material); DEFINE_RESOURCE_TYPE_INFO(Material); DEFINE_RESOURCE_GENERIC_FACTORY(Material); Material::Material(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(pResourceTypeInfo) { m_pShader = NULL; m_iShaderStaticSwitchMask = 0; m_bDeviceResourcesCreated = false; } Material::~Material() { uint32 i; for (i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[i]; if (value.pTexture != NULL) value.pTexture->Release(); else if (value.pGPUTexture != NULL) value.pGPUTexture->Release(); } SAFE_RELEASE(m_pShader); } void Material::Create(const char *resourceName, const MaterialShader *pShader) { // set name m_strName = resourceName; // set shader m_pShader = pShader; m_pShader->AddRef(); // create parameter arrays if (m_pShader->GetUniformParameterCount() > 0) m_ShaderUniformParameters.Resize(m_pShader->GetUniformParameterCount()); if (m_pShader->GetTextureParameterCount() > 0) m_ShaderTextureParameters.Resize(m_pShader->GetTextureParameterCount()); // set default uniforms for (uint32 i = 0; i < m_pShader->GetUniformParameterCount(); i++) Y_memcpy(&m_ShaderUniformParameters[i], &m_pShader->GetUniformParameter(i)->DefaultValue, sizeof(MaterialShader::UniformParameter::Value)); // set default textures for (uint32 i = 0; i < m_pShader->GetTextureParameterCount(); i++) { const MaterialShader::TextureParameter *pTextureParameter = m_pShader->GetTextureParameter(i); const Texture *pTexture = NULL; if (pTextureParameter->DefaultValue.GetLength() > 0) { pTexture = g_pResourceManager->GetTexture(pTextureParameter->DefaultValue); if (pTexture != NULL && pTexture->GetTextureType() != pTextureParameter->Type) { pTexture->Release(); pTexture = NULL; } } if (pTexture != NULL) m_ShaderTextureParameters[i].pTexture = pTexture; else m_ShaderTextureParameters[i].pTexture = g_pResourceManager->GetDefaultTexture(pTextureParameter->Type); m_ShaderTextureParameters[i].pGPUTexture = NULL; } // set default staticswitch mask for (uint32 i = 0; i < m_pShader->GetStaticSwitchParameterCount(); i++) { const MaterialShader::StaticSwitchParameter *pStaticSwitchParameter = m_pShader->GetStaticSwitchParameter(i); if (pStaticSwitchParameter->DefaultValue) m_iShaderStaticSwitchMask |= pStaticSwitchParameter->Mask; } } bool Material::Load(const char *resourceName, ByteStream *pStream) { BinaryReader binaryReader(pStream); // set name m_strName = resourceName; // read header DF_MATERIAL_HEADER header; if (!binaryReader.SafeReadBytes(&header, sizeof(header)) || header.Magic != DF_MATERIAL_HEADER_MAGIC || header.HeaderSize != sizeof(header)) return false; // read shader name SmallString materialShaderName; if (!binaryReader.SafeReadFixedString(header.ShaderNameLength, &materialShaderName)) return false; // get shader if ((m_pShader = g_pResourceManager->GetMaterialShader(materialShaderName)) == nullptr) { Log_ErrorPrintf("Could not load material '%s': shader '%s' not found", resourceName, materialShaderName.GetCharArray()); return false; } // compare our sizes against the shader, it should match, if not, we're outdated if (header.UniformParameterCount != m_pShader->GetUniformParameterCount() || header.TextureParameterCount != m_pShader->GetTextureParameterCount()) { Log_ErrorPrintf("Could not load material '%s': parameter mismatch with shader '%s'", resourceName, materialShaderName.GetCharArray()); return false; } // load uniform parameters m_ShaderUniformParameters.Resize(header.UniformParameterCount); m_ShaderUniformParameters.ZeroContents(); for (uint32 i = 0; i < m_ShaderUniformParameters.GetSize(); i++) { DF_MATERIAL_UNIFORM_PARAMETER uniformParameter; if (!binaryReader.SafeReadBytes(&uniformParameter, sizeof(uniformParameter))) return false; // validate against shader if (uniformParameter.UniformType != (uint32)m_pShader->GetUniformParameter(i)->Type) { Log_ErrorPrintf("Could not load material '%s': uniform parameter %u type mismatch with shader '%s'", resourceName, i, materialShaderName.GetCharArray()); return false; } // store value Y_memcpy(&m_ShaderUniformParameters[i], uniformParameter.UniformValue, sizeof(MaterialShader::UniformParameter::Value)); } // load texture parameters m_ShaderTextureParameters.Resize(header.TextureParameterCount); m_ShaderTextureParameters.ZeroContents(); for (uint32 i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { DF_MATERIAL_TEXTURE_PARAMETER textureParameter; if (!binaryReader.SafeReadBytes(&textureParameter, sizeof(textureParameter))) return false; // validate against shader if (textureParameter.TextureType != (uint32)m_pShader->GetTextureParameter(i)->Type) { Log_ErrorPrintf("Could not load material '%s': texture parameter %u type mismatch with shader '%s'", resourceName, i, materialShaderName.GetCharArray()); return false; } // read texture name SmallString textureName; if (!binaryReader.SafeReadFixedString(textureParameter.TextureNameLength, &textureName)) return false; // load texture const Texture *pTexture = g_pResourceManager->GetTexture(textureName); if (pTexture == nullptr) { Log_WarningPrintf("In material '%s': texture parameter %u could not be loaded '%s'", resourceName, i, textureName.GetCharArray()); pTexture = g_pResourceManager->GetDefaultTexture((TEXTURE_TYPE)textureParameter.TextureType); } else if (pTexture->GetTextureType() != (TEXTURE_TYPE)textureParameter.TextureType) { Log_WarningPrintf("In material '%s': texture parameter %u is bad type '%s'", resourceName, i, textureName.GetCharArray()); pTexture->Release(); pTexture = g_pResourceManager->GetDefaultTexture((TEXTURE_TYPE)textureParameter.TextureType); } // set pointer m_ShaderTextureParameters[i].pTexture = pTexture; m_ShaderTextureParameters[i].pGPUTexture = nullptr; } // store static switch mask m_iShaderStaticSwitchMask = header.StaticSwitchMask; // create on gpu if (g_pRenderer != nullptr && !CreateDeviceResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool Material::CreateDeviceResources() const { uint32 i; if (m_bDeviceResourcesCreated) return true; for (i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { const MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[i]; if (value.pTexture != NULL && !value.pTexture->CreateDeviceResources()) return false; } m_bDeviceResourcesCreated = true; return true; } bool Material::BindDeviceResources(GPUCommandList *pCommandList, ShaderProgram *pProgram) const { uint32 i; if (!m_bDeviceResourcesCreated && !CreateDeviceResources()) return false; for (i = 0; i < m_ShaderUniformParameters.GetSize(); i++) pProgram->SetMaterialParameterValue(pCommandList, i, m_pShader->GetUniformParameter(i)->Type, &m_ShaderUniformParameters[i]); for (i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { const MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[i]; pProgram->SetMaterialParameterResource(pCommandList, i, (value.pGPUTexture != NULL) ? value.pGPUTexture : value.pTexture->GetGPUTexture()); } return true; } void Material::ReleaseDeviceResources() const { m_bDeviceResourcesCreated = false; // kill any references to direct gpu textures for (uint32 i = 0; i < m_ShaderTextureParameters.GetSize(); i++) { MaterialShader::TextureParameter::Value *pValue = const_cast<MaterialShader::TextureParameter::Value *>(&m_ShaderTextureParameters[i]); SAFE_RELEASE(pValue->pGPUTexture); } } void Material::SetShaderUniformParameterString(uint32 Index, const char *NewValue) { const MaterialShader::UniformParameter *pUniformParameter = m_pShader->GetUniformParameter(Index); ShaderParameterTypeFromString(pUniformParameter->Type, &m_ShaderUniformParameters[Index], NewValue); } bool Material::SetShaderTextureParameterString(uint32 Index, const char *NewValue) { const MaterialShader::TextureParameter *pTextureParameter = m_pShader->GetTextureParameter(Index); const Texture *pTexture = g_pResourceManager->GetTexture(NewValue); if (pTexture != NULL && pTexture->GetTextureType() == pTextureParameter->Type) { pTexture->AddRef(); MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[Index]; if (value.pGPUTexture != NULL) { DebugAssert(value.pTexture == NULL); value.pGPUTexture->Release(); value.pGPUTexture = NULL; value.pTexture = pTexture; } else if (value.pTexture != NULL) { DebugAssert(value.pGPUTexture == NULL); value.pTexture->Release(); value.pTexture = pTexture; } if (m_bDeviceResourcesCreated) { // todo: log warning if fail pTexture->CreateDeviceResources(); } return true; } else if (pTexture != NULL) { pTexture->Release(); } return false; } void Material::SetShaderUniformParameter(uint32 Index, SHADER_PARAMETER_TYPE Type, const void *pNewValue) { const MaterialShader::UniformParameter *pUniformParameter = m_pShader->GetUniformParameter(Index); uint32 typeSize = ShaderParameterValueTypeSize(pUniformParameter->Type); if (typeSize > 0) Y_memcpy(&m_ShaderUniformParameters[Index], pNewValue, typeSize); } bool Material::SetShaderTextureParameter(uint32 Index, const Texture *pNewTexture) { const MaterialShader::TextureParameter *pTextureParameter = m_pShader->GetTextureParameter(Index); if (pNewTexture == NULL || pNewTexture->GetTextureType() != pTextureParameter->Type) return false; pNewTexture->AddRef(); MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[Index]; if (value.pGPUTexture != NULL) { DebugAssert(value.pTexture == NULL); value.pGPUTexture->Release(); value.pGPUTexture = NULL; value.pTexture = pNewTexture; } else if (value.pTexture != NULL) { DebugAssert(value.pGPUTexture == NULL); value.pTexture->Release(); value.pTexture = pNewTexture; } if (m_bDeviceResourcesCreated) pNewTexture->CreateDeviceResources(); return true; } bool Material::SetShaderTextureParameter(uint32 Index, GPUTexture *pNewTexture) { const MaterialShader::TextureParameter *pTextureParameter = m_pShader->GetTextureParameter(Index); MaterialShader::TextureParameter::Value &value = m_ShaderTextureParameters[Index]; if (pNewTexture == NULL) { // reset back to the default value if a gpu texture is currently bound if (value.pGPUTexture == NULL) return false; // find default value const Texture *pTexture = NULL; if (pTextureParameter->DefaultValue.GetLength() > 0) { pTexture = g_pResourceManager->GetTexture(pTextureParameter->DefaultValue); if (pTexture != NULL && pTexture->GetTextureType() != pTextureParameter->Type) { pTexture->Release(); pTexture = NULL; } } // kill old value DebugAssert(value.pTexture == NULL); value.pGPUTexture->Release(); value.pGPUTexture = NULL; // set if (pTexture != NULL) m_ShaderTextureParameters[Index].pTexture = pTexture; else m_ShaderTextureParameters[Index].pTexture = g_pResourceManager->GetDefaultTexture(pTextureParameter->Type); // ok return true; } if (pNewTexture->GetTextureType() != pTextureParameter->Type) return false; pNewTexture->AddRef(); if (value.pGPUTexture != NULL) { DebugAssert(value.pTexture == NULL); value.pGPUTexture->Release(); value.pGPUTexture = pNewTexture; } else if (value.pTexture != NULL) { DebugAssert(value.pGPUTexture == NULL); value.pTexture->Release(); value.pTexture = NULL; value.pGPUTexture = pNewTexture; } return true; } void Material::SetShaderStaticSwitchParameter(uint32 Index, bool On) { DebugAssert(Index < m_pShader->GetStaticSwitchParameterCount()); const MaterialShader::StaticSwitchParameter *pParameter = m_pShader->GetStaticSwitchParameter(Index); if (On) m_iShaderStaticSwitchMask |= pParameter->Mask; else m_iShaderStaticSwitchMask &= ~pParameter->Mask; } bool Material::SetShaderUniformParameterStringByName(const char *Name, const char *NewValue) { int32 Index = m_pShader->FindUniformParameter(Name); if (Index < 0) return false; SetShaderUniformParameterString(Index, NewValue); return true; } bool Material::SetShaderTextureParameterStringByName(const char *Name, const char *NewValue) { int32 Index = m_pShader->FindTextureParameter(Name); return (Index >= 0) ? SetShaderTextureParameterString(Index, NewValue) : false; } bool Material::SetShaderUniformParameterByName(const char *Name, SHADER_PARAMETER_TYPE Type, const void *pNewValue) { int32 Index = m_pShader->FindUniformParameter(Name); if (Index < 0) return false; SetShaderUniformParameter(Index, Type, pNewValue); return true; } bool Material::SetShaderTextureParameterByName(const char *Name, const Texture *pNewTexture) { int32 Index = m_pShader->FindTextureParameter(Name); if (Index < 0) return false; return SetShaderTextureParameter(Index, pNewTexture); } bool Material::SetShaderTextureParameterByName(const char *Name, GPUTexture *pNewTexture) { int32 Index = m_pShader->FindTextureParameter(Name); if (Index < 0) return false; return SetShaderTextureParameter(Index, pNewTexture); } bool Material::SetShaderStaticSwitchParameterByName(const char *Name, bool On) { int32 Index = m_pShader->FindStaticSwitchParameter(Name); if (Index < 0) return false; SetShaderStaticSwitchParameter(Index, On); return true; } ////////////////////////////////////////////////////////////////////////// <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphCompilerHLSL.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphCompilerHLSL.h" #include "ResourceCompiler/ShaderGraphBuiltinNodes.h" Log_SetChannel(ShaderGraphCompilerHLSL); ShaderGraphCompilerHLSL::ShaderGraphCompilerHLSL(const ShaderGraph *pShaderGraph) : ShaderGraphCompiler(pShaderGraph), m_currentStage(SHADER_PROGRAM_STAGE_COUNT) { } ShaderGraphCompilerHLSL::~ShaderGraphCompilerHLSL() { } bool ShaderGraphCompilerHLSL::Compile(ByteStream *pStream) { if (!InternalCompile()) return false; // output to sink static const char header[] = "// Begin generated shader graph code.\n\n"; static const char footer[] = "// End generated shader graph code.\n\n"; bool writeResult = true; SmallString tempStr; writeResult &= pStream->Write2(header, sizeof(header) - 1); for (CompileDefineMap::Iterator itr = m_defines.Begin(); !itr.AtEnd(); itr.Forward()) { tempStr.Format("#define %s %s\n", itr->Key.GetCharArray(), itr->Value.GetCharArray()); writeResult &= pStream->Write2(tempStr.GetCharArray(), tempStr.GetLength()); } if (m_externsCode.GetLength() > 0) writeResult &= pStream->Write2(m_externsCode.GetCharArray(), m_externsCode.GetLength()); if (m_globalsCode.GetLength() > 0) writeResult &= pStream->Write2(m_globalsCode.GetCharArray(), m_globalsCode.GetLength()); if (m_methodsCode.GetLength() > 0) writeResult &= pStream->Write2(m_methodsCode.GetCharArray(), m_methodsCode.GetLength()); writeResult &= pStream->Write2(footer, sizeof(footer) - 1); return writeResult; } void ShaderGraphCompilerHLSL::CleanString(String &str) { uint32 i; for (i = 0; i < str.GetLength(); i++) { char ch = str[i]; if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_') { continue; } str[i] = '_'; } } const char *ShaderGraphCompilerHLSL::GetTypeNameString(SHADER_PARAMETER_TYPE ValueType) { switch (ValueType) { case SHADER_PARAMETER_TYPE_BOOL: return "bool"; case SHADER_PARAMETER_TYPE_INT: return "int"; case SHADER_PARAMETER_TYPE_INT2: return "int2"; case SHADER_PARAMETER_TYPE_INT3: return "int3"; case SHADER_PARAMETER_TYPE_INT4: return "int4"; case SHADER_PARAMETER_TYPE_FLOAT: return "float"; case SHADER_PARAMETER_TYPE_FLOAT2: return "float2"; case SHADER_PARAMETER_TYPE_FLOAT3: return "float3"; case SHADER_PARAMETER_TYPE_FLOAT4: return "float4"; case SHADER_PARAMETER_TYPE_FLOAT2X2: return "float2x2"; case SHADER_PARAMETER_TYPE_FLOAT3X3: return "float3x3"; case SHADER_PARAMETER_TYPE_FLOAT3X4: return "float3x4"; case SHADER_PARAMETER_TYPE_FLOAT4X4: return "float4x4"; case SHADER_PARAMETER_TYPE_TEXTURE1D: return "Texture1D"; case SHADER_PARAMETER_TYPE_TEXTURE2D: return "Texture2D"; case SHADER_PARAMETER_TYPE_TEXTURE3D: return "Texture3D"; case SHADER_PARAMETER_TYPE_TEXTURECUBE: return "TextureCube"; case SHADER_PARAMETER_TYPE_TEXTURE1DARRAY: return "Texture1DArray"; case SHADER_PARAMETER_TYPE_TEXTURE2DARRAY: return "Texture2DArray"; case SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY: return "TextureCubeArray"; } UnreachableCode(); return NULL; } bool ShaderGraphCompilerHLSL::AddCompileDefine(const char *Name, const char *Value) { for (CompileDefineMap::Iterator itr = m_defines.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Key == Name) return (itr->Value == Value); } DefinePair definePair(Name, Value); m_defines.PushBack(definePair); return true; } bool ShaderGraphCompilerHLSL::AddBufferedCompileDefine(const char *Name, const char *Value) { for (CompileDefineMap::Iterator itr = m_bufferedDefines.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->Key == Name) return (itr->Value == Value); } DefinePair definePair(Name, Value); m_bufferedDefines.PushBack(definePair); return true; } bool ShaderGraphCompilerHLSL::EvaluateNode(const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle, SHADER_GRAPH_VALUE_SWIZZLE FixupSwizzle) { DebugAssert(pSourceNode != NULL && OutputIndex < pSourceNode->GetOutputCount()); if (!pSourceNode->EmitOutput(this, OutputIndex)) return false; if (Swizzle != SHADER_GRAPH_VALUE_SWIZZLE_NONE) EmitSwizzle(Swizzle); if (FixupSwizzle != SHADER_GRAPH_VALUE_SWIZZLE_NONE) EmitSwizzle(FixupSwizzle); return true; } bool ShaderGraphCompilerHLSL::EvaluateNode(const ShaderGraphNodeInput *pNodeLink) { if (pNodeLink->IsLinked()) return EvaluateNode(pNodeLink->GetSourceNode(), pNodeLink->GetSourceOutputIndex(), pNodeLink->GetSwizzle(), pNodeLink->GetFixupSwizzle()); // if it's not linked, use the default value if (!InternalCompileDefaultValue(pNodeLink->GetInputDesc()->Type, pNodeLink->GetInputDesc()->DefaultValue)) return false; // handle swizzles if (pNodeLink->GetSwizzle() != SHADER_GRAPH_VALUE_SWIZZLE_NONE) EmitSwizzle(pNodeLink->GetSwizzle()); if (pNodeLink->GetFixupSwizzle() != SHADER_GRAPH_VALUE_SWIZZLE_NONE) EmitSwizzle(pNodeLink->GetFixupSwizzle()); return true; } #define EVALUATE_NODE(pNode) { if (!EvaluateNode(pNode)) { return false; } } #define APPEND_STR(str) { m_buffer.AppendString(str); } bool ShaderGraphCompilerHLSL::EmitAdd(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) { APPEND_STR("("); EVALUATE_NODE(pA); APPEND_STR(" + "); EVALUATE_NODE(pB); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitSubtract(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) { APPEND_STR("("); EVALUATE_NODE(pA); APPEND_STR(" - "); EVALUATE_NODE(pB); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitMultiply(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) { APPEND_STR("("); EVALUATE_NODE(pA); APPEND_STR(" * "); EVALUATE_NODE(pB); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitDivide(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) { APPEND_STR("("); EVALUATE_NODE(pA); APPEND_STR(" / "); EVALUATE_NODE(pB); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitDot(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) { APPEND_STR("dot("); EVALUATE_NODE(pA); APPEND_STR(", "); EVALUATE_NODE(pB); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitNormalize(const ShaderGraphNodeInput *pNode) { APPEND_STR("normalize("); EVALUATE_NODE(pNode); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitNegate(const ShaderGraphNodeInput *pNode) { APPEND_STR("-("); EVALUATE_NODE(pNode); APPEND_STR(")"); return true; } bool ShaderGraphCompilerHLSL::EmitFractionalPart(const ShaderGraphNodeInput *pNode) { APPEND_STR("frac("); EVALUATE_NODE(pNode); APPEND_STR(")"); return true; } void ShaderGraphCompilerHLSL::EmitConstant(SHADER_PARAMETER_TYPE ValueType, const void *pValue) { switch (ValueType) { case SHADER_PARAMETER_TYPE_BOOL: EmitConstantBool(*reinterpret_cast<const bool *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT: EmitConstantInt(*reinterpret_cast<const int32 *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT2: EmitConstantInt2(*reinterpret_cast<const int2 *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT3: EmitConstantInt3(*reinterpret_cast<const int3 *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT4: EmitConstantInt4(*reinterpret_cast<const int4 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT: EmitConstantFloat(*reinterpret_cast<const float *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT2: EmitConstantFloat2(*reinterpret_cast<const float2 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3: EmitConstantFloat3(*reinterpret_cast<const float3 *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT4: EmitConstantFloat4(*reinterpret_cast<const float4 *>(pValue)); break; default: UnreachableCode(); break; } } void ShaderGraphCompilerHLSL::EmitConstantBool(bool Value) { m_buffer.AppendString(Value ? "true" : "false"); } void ShaderGraphCompilerHLSL::EmitConstantInt(int32 Value) { m_buffer.AppendFormattedString("int(%d)", Value); } void ShaderGraphCompilerHLSL::EmitConstantInt2(const int2 &Value) { m_buffer.AppendFormattedString("int2(%d, %d)", Value.x, Value.y); } void ShaderGraphCompilerHLSL::EmitConstantInt3(const int3 &Value) { m_buffer.AppendFormattedString("int3(%d, %d, %d)", Value.x, Value.y, Value.z); } void ShaderGraphCompilerHLSL::EmitConstantInt4(const int4 &Value) { m_buffer.AppendFormattedString("int4(%d, %d, %d, %d)", Value.x, Value.y, Value.z, Value.w); } void ShaderGraphCompilerHLSL::EmitConstantFloat(const float &Value) { m_buffer.AppendFormattedString("float(%.6f)", Value); } void ShaderGraphCompilerHLSL::EmitConstantFloat2(const float2 &Value) { m_buffer.AppendFormattedString("float2(%.6f, %.6f)", Value.x, Value.y); } void ShaderGraphCompilerHLSL::EmitConstantFloat3(const float3 &Value) { m_buffer.AppendFormattedString("float3(%.6f, %.6f, %.6f)", Value.x, Value.y, Value.z); } void ShaderGraphCompilerHLSL::EmitConstantFloat4(const float4 &Value) { m_buffer.AppendFormattedString("float4(%.6f, %.6f, %.6f, %.6f)", Value.x, Value.y, Value.z, Value.w); } bool ShaderGraphCompilerHLSL::EmitAccessShaderGlobal(const char *GlobalName) { const ShaderGraphSchema *pSchema = m_pShaderGraph->GetSchema(); uint32 i; for (i = 0; i < pSchema->GetGlobalDeclarationCount(); i++) { if (pSchema->GetGlobalDeclaration(i)->Name.Compare(GlobalName)) break; } if (i == pSchema->GetInputDeclarationCount()) { Log_ErrorPrintf("Attempting to access unknown shader global '%s'.", GlobalName); return false; } // get input decl, write the variable name const ShaderGraphSchema::GlobalDeclaration *pGlobalDeclaration = pSchema->GetGlobalDeclaration(i); m_buffer.AppendString(pGlobalDeclaration->VariableName.GetCharArray()); return true; } bool ShaderGraphCompilerHLSL::EmitAccessShaderInput(const char *InputName) { const ShaderGraphSchema *pSchema = m_pShaderGraph->GetSchema(); uint32 i; for (i = 0; i < pSchema->GetInputDeclarationCount(); i++) { if (pSchema->GetInputDeclaration(i)->Name.Compare(InputName)) break; } if (i == pSchema->GetInputDeclarationCount()) { Log_ErrorPrintf("Attempting to access unknown shader input '%s'.", InputName); return false; } // get input decl const ShaderGraphSchema::InputDeclaration *pInputDeclaration = pSchema->GetInputDeclaration(i); DebugAssert(m_currentStage < SHADER_PROGRAM_STAGE_COUNT); // check the input is accessible from this stage if (pInputDeclaration->Access[m_currentStage].VariableName.IsEmpty()) { Log_ErrorPrintf("attempting to access input '%s' that is not accessible from this stage (%s)", pInputDeclaration->Name.GetCharArray(), NameTable_GetNameString(NameTables::ShaderProgramStage, m_currentStage)); return false; } // add defines if (pInputDeclaration->Access[m_currentStage].DefineName.GetLength() > 0) AddBufferedCompileDefine(pInputDeclaration->Access[m_currentStage].DefineName, "1"); // write the string out m_buffer.AppendString(pInputDeclaration->Access[m_currentStage].VariableName.GetCharArray()); return true; } bool ShaderGraphCompilerHLSL::EmitAccessExternalParameter(const ExternalParameter *pExternalParameter) { m_buffer.AppendString(pExternalParameter->BindingName); return true; } bool ShaderGraphCompilerHLSL::EmitTextureSample(const ShaderGraphNodeInput *pTextureNodeLink, const ShaderGraphNodeInput *pTexCoordNodeLink, SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION unpackOperation) { switch (unpackOperation) { case SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NORMAL_MAP: APPEND_STR("(("); break; } EVALUATE_NODE(pTextureNodeLink); APPEND_STR(".Sample("); { EVALUATE_NODE(pTextureNodeLink); APPEND_STR("_SamplerState"); APPEND_STR(", "); EVALUATE_NODE(pTexCoordNodeLink); } APPEND_STR(")"); switch (unpackOperation) { case SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION_NORMAL_MAP: APPEND_STR(" - 0.5) * 2.0)"); break; } return true; } bool ShaderGraphCompilerHLSL::EmitConstructPrimitive(SHADER_PARAMETER_TYPE primitiveType, const ShaderGraphNodeInput **ppInputNodes, uint32 nInputNodes) { switch (primitiveType) { case SHADER_PARAMETER_TYPE_FLOAT2: { if (nInputNodes != 2) return false; APPEND_STR("float2("); EVALUATE_NODE(ppInputNodes[0]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[1]); APPEND_STR(")"); return true; } case SHADER_PARAMETER_TYPE_FLOAT3: { if (nInputNodes != 3) return false; APPEND_STR("float3("); EVALUATE_NODE(ppInputNodes[0]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[1]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[2]); APPEND_STR(")"); return true; } case SHADER_PARAMETER_TYPE_FLOAT4: { if (nInputNodes != 4) return false; APPEND_STR("float4("); EVALUATE_NODE(ppInputNodes[0]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[1]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[2]); APPEND_STR(", "); EVALUATE_NODE(ppInputNodes[3]); APPEND_STR(")"); return true; } } return false; } void ShaderGraphCompilerHLSL::EmitSwizzle(SHADER_GRAPH_VALUE_SWIZZLE Swizzle) { if (Swizzle == SHADER_GRAPH_VALUE_SWIZZLE_NONE) return; char swizzleStr[5]; if (!ShaderGraph::GetStringForValueSwizzle(swizzleStr, Swizzle)) Panic("Invalid swizzle value encountered"); m_buffer.AppendCharacter('.'); m_buffer.AppendString(swizzleStr); } bool ShaderGraphCompilerHLSL::InternalCompile() { uint32 i; // write external parameters for (ExternalParameterList::ConstIterator itr = m_ExternalUniforms.Begin(); !itr.AtEnd(); itr.Forward()) { // get type name const char *uniformTypeName = GetTypeNameString(itr->Type); m_externsCode.AppendFormattedString("%s %s;\n", uniformTypeName, itr->BindingName.GetCharArray()); } for (ExternalParameterList::ConstIterator itr = m_ExternalTextures.Begin(); !itr.AtEnd(); itr.Forward()) { // get type name const char *textureTypeName = GetTypeNameString(itr->Type); m_externsCode.AppendFormattedString("%s %s;\n", textureTypeName, itr->BindingName.GetCharArray()); m_externsCode.AppendFormattedString("SamplerState %s_SamplerState;\n", itr->BindingName.GetCharArray()); } // compile outputs dependant on output profile const ShaderGraphSchema *pSchema = m_pShaderGraph->GetSchema(); for (i = 0; i < pSchema->GetOutputDeclarationCount(); i++) { if (!InternalCompileOutput(i)) return false; } return true; } bool ShaderGraphCompilerHLSL::InternalCompileDefaultValue(SHADER_PARAMETER_TYPE Type, const char *DefaultValue) { if (Y_strnicmp(DefaultValue, "input:", 6) == 0) { // find the input node.. this cast should not fail const ShaderGraphNode_ShaderInputs *pInputsNode = m_pShaderGraph->GetShaderInputsNode()->Cast<ShaderGraphNode_ShaderInputs>(); if (pInputsNode == NULL) return false; // find the output in the list uint32 outputIndex; for (outputIndex = 0; outputIndex < pInputsNode->GetOutputCount(); outputIndex++) { if (Y_strcmp(DefaultValue + 6, pInputsNode->GetOutput(outputIndex)->GetOutputDesc()->Name) == 0) break; } if (outputIndex == pInputsNode->GetOutputCount()) { Log_ErrorPrintf("could not compile default value '%s': output not found.", DefaultValue); return false; } // check type if (Type != pInputsNode->GetOutput(outputIndex)->GetValueType()) { Log_ErrorPrintf("could not compile default value '%s': value types mismatch (%s, %s).", DefaultValue, NameTable_GetNameString(NameTables::ShaderParameterType, Type), NameTable_GetNameString(NameTables::ShaderParameterType, pInputsNode->GetOutput(outputIndex)->GetValueType())); return false; } // evaluate the output return EvaluateNode(pInputsNode, outputIndex, SHADER_GRAPH_VALUE_SWIZZLE_NONE, SHADER_GRAPH_VALUE_SWIZZLE_NONE); } else if (Y_strnicmp(DefaultValue, "link:", 5) == 0) { const ShaderGraphNode *pLinkNode = m_pShaderGraph->GetNodeByName(DefaultValue + 5); if (pLinkNode == NULL || pLinkNode->GetOutputCount() < 1) return false; // evaluate the default node return EvaluateNode(pLinkNode, 0, SHADER_GRAPH_VALUE_SWIZZLE_NONE, SHADER_GRAPH_VALUE_SWIZZLE_NONE); } else { // parse the default node, it should be a primitive type. switch (Type) { case SHADER_PARAMETER_TYPE_BOOL: EmitConstantBool(StringConverter::StringToBool(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_INT: EmitConstantInt(StringConverter::StringToInt32(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_INT2: EmitConstantInt2(StringConverter::StringToInt2(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_INT3: EmitConstantInt3(StringConverter::StringToInt3(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_INT4: EmitConstantInt4(StringConverter::StringToInt4(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_FLOAT: EmitConstantFloat(StringConverter::StringToFloat(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_FLOAT2: EmitConstantFloat2(StringConverter::StringToFloat2(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_FLOAT3: EmitConstantFloat3(StringConverter::StringToFloat3(DefaultValue)); return true; case SHADER_PARAMETER_TYPE_FLOAT4: EmitConstantFloat4(StringConverter::StringToFloat4(DefaultValue)); return true; } return false; } } bool ShaderGraphCompilerHLSL::InternalCompileOutput(uint32 outputIndex) { // find and cast the outputs node const ShaderGraphNode_ShaderOutputs *pShaderOutputsNode = m_pShaderGraph->GetShaderOutputsNode()->SafeCast<ShaderGraphNode_ShaderOutputs>(); if (pShaderOutputsNode == nullptr) return false; // clear everything out m_currentScope.Clear(); m_buffer.Clear(); m_bufferedDefines.Clear(); // sanity check: this should always match. otherwise something really bad has happened at some point const ShaderGraphSchema *pSchema = m_pShaderGraph->GetSchema(); const ShaderGraphSchema::OutputDeclaration *pOutputDeclaration = pSchema->GetOutputDeclaration(outputIndex); const ShaderGraphNodeInput *pInput = pShaderOutputsNode->GetInput(outputIndex); DebugAssert(pInput->GetInputDesc() == &pOutputDeclaration->InputDesc); // update current stage //static const char *stageDefines[SHADER_PROGRAM_STAGE_COUNT] = { "VERTEX_SHADER", "HULL_SHADER", "DOMAIN_SHADER", "GEOMETRY_SHADER", "PIXEL_SHADER", "COMPUTE_SHADER" }; m_currentStage = pOutputDeclaration->Stage; // check if it is bound if (!pInput->IsLinked()) { // use default value if (!InternalCompileDefaultValue(pOutputDeclaration->Type, pOutputDeclaration->DefaultValue)) return false; } else { // compile the value if (!EvaluateNode(pInput)) return false; } // check for define if (pOutputDeclaration->DefineName.GetLength() > 0) m_methodsCode.AppendFormattedString("#if %s\n\n", pOutputDeclaration->DefineName.GetCharArray()); // add any buffered defines for (CompileDefineMap::ConstIterator itr = m_bufferedDefines.Begin(); !itr.AtEnd(); itr.Forward()) { const DefinePair &definePair = *itr; m_methodsCode.AppendFormattedString("#if !%s\n", definePair.Key.GetCharArray()); m_methodsCode.AppendFormattedString(" #define %s %s\n", definePair.Key.GetCharArray(), definePair.Value.GetCharArray()); m_methodsCode.AppendFormattedString("#endif\n"); } // get input type string const char *inputTypeString = GetTypeNameString(pInput->GetValueType()); // add code //m_methodsCode.AppendFormattedString("#if %s\n\n", stageDefines[m_currentStage]); m_methodsCode.AppendFormattedString("%s %s\n", inputTypeString, pOutputDeclaration->FunctionSignature.GetCharArray()); m_methodsCode.AppendString("{\n"); m_methodsCode.AppendString(m_currentScope); m_methodsCode.AppendString(" return "); m_methodsCode.AppendString(m_buffer); m_methodsCode.AppendString(";\n"); m_methodsCode.AppendString("}\n\n"); //m_methodsCode.AppendFormattedString("#endif // %s\n\n", stageDefines[m_currentStage]); // end define if (pOutputDeclaration->DefineName.GetLength() > 0) m_methodsCode.AppendFormattedString("#endif // %s\n\n", pOutputDeclaration->DefineName.GetCharArray()); // done return true; } <file_sep>/Editor/Source/Editor/SimpleTreeModel.h #pragma once #include <QtCore/QAbstractItemModel> class SimpleTreeModel : public QAbstractItemModel { Q_OBJECT public: class Container; class Item; class Item { friend class SimpleTreeModel; Item(SimpleTreeModel *pModel, const Container *pParent, int parentIndex); virtual ~Item(); virtual const bool IsContainer() const { return false; } public: const Container *GetParent() const { return m_pParent; } int GetParentIndex() const { return m_parentIndex; } const QString GetText(int column) const; void *GetUserData() const { return m_pUserData; } void SetText(int column, const QString text); void SetUserData(void *pUserData); QModelIndex CreateIndexRelativeToParent(int column = 0) const; QModelIndex CreateIndex(int column = 0) const; protected: SimpleTreeModel *m_pModel; const Container *m_pParent; int m_parentIndex; QString *m_pFields; int m_nColumns; void *m_pUserData; }; class Container : public Item { friend class SimpleTreeModel; Container(SimpleTreeModel *pModel, Container *pParent, int parentIndex); virtual ~Container(); virtual const bool IsContainer() const { return true; } public: // title const QString GetTitle() const { return GetText(0); } void SetTitle(const QString title) { SetText(0, title); } // create new item Item *CreateItem(); Container *CreateContainer(const QString titleText); // item access const Item *GetItem(int index) const; Item *GetItem(int index); // get an item by userdata int FindItemIndexByPointer(const Item *pItem) const; int FindItemIndexByUserData(void *pUserData) const; // remove item void RemoveItem(Item *pItem); void RemoveItem(int index); // remove all items void RemoveAllItems(); private: QList<Item *> m_items; }; public: SimpleTreeModel(int nColumns, QObject *pParent = nullptr); virtual ~SimpleTreeModel(); // access int GetColumnCount() const { return m_nColumns; } QString GetColumnTitle(int i) const { Q_ASSERT(i >= 0 && i < m_nColumns); return m_pColumnNames[i]; } void SetColumnTitle(int i, const QString name); // item creation Container *CreateContainer(const QString titleText, Container *pContainer = nullptr); Item *CreateItem(Container *pContainer = nullptr); // root item access const Item *GetRootItem() const { return &m_rootItem; } Item *GetRootItem() { return &m_rootItem; } // pushes through to root item const Item *GetItem(int index) const { return m_rootItem.GetItem(index); } Item *GetItem(int index) { return m_rootItem.GetItem(index); } int FindItemIndexByPointer(const Item *pItem) const { return m_rootItem.FindItemIndexByPointer(pItem); } int FindItemIndexByUserData(void *pUserData) const { return m_rootItem.FindItemIndexByUserData(pUserData); } void RemoveItem(Item *pItem) { m_rootItem.RemoveItem(pItem); } void RemoveItem(int index) { m_rootItem.RemoveItem(index); } // virtual interface methods virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; virtual QModelIndex parent(const QModelIndex &child) const; virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; private: int m_nColumns; QString *m_pColumnNames; Container m_rootItem; }; <file_sep>/Editor/Source/Editor/Main.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" Log_SetChannel(EditorMain); #if defined(Y_PLATFORM_LINUX) && 0 #include <qpa/qplatformnativeinterface.h> #include "Core/XDisplay.h" static bool UpdateXDisplayPointer(QApplication *pApplication) { QPlatformNativeInterface *pNativeInterface = pApplication->platformNativeInterface(); if (pNativeInterface == NULL) { Log_ErrorPrintf("UpdateXDisplayPointer(): Could not get platform native interface."); return false; } Display *pX11Display = reinterpret_cast<Display *>(pNativeInterface->nativeResourceForScreen(QByteArray("display"), QGuiApplication::primaryScreen())); if (pX11Display == NULL) { Log_ErrorPrintf("UpdateXDisplayPointer(): Could not get X11 connection from Qt."); return false; } Y_SetXDisplayPointer(pX11Display); return true; } #endif int main(int argc, char *argv[]) { // set log flags g_pLog->SetConsoleOutputParams(true); g_pLog->SetDebugOutputParams(true); // create application Editor editor(argc, argv); // platform-specific initializtion #if defined(Y_PLATFORM_LINUX) && 0 UpdateXDisplayPointer(&editor); #endif // pass control over return editor.Execute(); } <file_sep>/cmake_android.sh #!/bin/bash BASEPATH="${BASH_SOURCE[0]}" BASEPATH=$(dirname $BASEPATH) echo BASEPATH=$BASEPATH cmake -G"Unix Makefiles" \ -DCMAKE_TOOLCHAIN_FILE=$BASEPATH/CMakeModules/android.toolchain.cmake \ -DANDROID_ABI=armeabi-v7a \ -DANDROID_NATIVE_API_LEVEL=android-19 \ -DANDROID_STL=gnustl_shared \ $BASEPATH <file_sep>/Engine/Source/Renderer/VertexFactories/LocalVertexFactory.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/VertexBufferBindingArray.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(LocalVertexFactory) END_SHADER_COMPONENT_PARAMETERS() uint32 LocalVertexFactory::GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags) { // calculate vertices buffer size // base vertex size - position + normal uint32 vertexSize = sizeof(float3) + sizeof(float3); // add tangent space if (flags & LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) vertexSize += sizeof(float3) + sizeof(float3); // add texcoords if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS) vertexSize += sizeof(float2); else if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS) vertexSize += sizeof(float3); // add colors if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS) vertexSize += sizeof(uint32); // set it return vertexSize; } bool LocalVertexFactory::CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); uint32 bufferSize = vertexSize * nVertices; byte *pBuffer = new byte[bufferSize]; FillVerticesBuffer(platform, featureLevel, flags, pVertices, nVertices, pBuffer, bufferSize); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, bufferSize); GPUBuffer *pVertexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, pBuffer); delete[] pBuffer; if (pVertexBuffer == NULL) return false; pVertexBufferBindingArray->SetBuffer(0, pVertexBuffer, 0, vertexSize); pVertexBuffer->Release(); return true; } bool LocalVertexFactory::FillVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer) { uint32 vertexSize = GetVertexSize(platform, featureLevel, flags); if (cbBuffer < (vertexSize * nVertices)) return false; uint32 i; byte *pOutVertexPtr = reinterpret_cast<byte *>(pBuffer); for (i = 0; i < nVertices; i++) { const Vertex *pVertex = &pVertices[i]; // position Y_memcpy(pOutVertexPtr, &pVertex->Position, sizeof(float3)); pOutVertexPtr += sizeof(float3); // normal Y_memcpy(pOutVertexPtr, &pVertex->Normal, sizeof(float3)); pOutVertexPtr += sizeof(float3); if (flags & LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) { // tangent Y_memcpy(pOutVertexPtr, &pVertex->Tangent, sizeof(float3)); pOutVertexPtr += sizeof(float3); // binormal Y_memcpy(pOutVertexPtr, &pVertex->Binormal, sizeof(float3)); pOutVertexPtr += sizeof(float3); } // texcoord if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS) { Y_memcpy(pOutVertexPtr, &pVertex->TexCoord, sizeof(float3)); pOutVertexPtr += sizeof(float3); } else if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS) { Y_memcpy(pOutVertexPtr, &pVertex->TexCoord, sizeof(float2)); pOutVertexPtr += sizeof(float2); } // color if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { Y_memcpy(pOutVertexPtr, &pVertex->Color, sizeof(uint32)); pOutVertexPtr += sizeof(uint32); } } return true; } bool LocalVertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool LocalVertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/LocalVertexFactory.hlsl"); if (vertexFactoryFlags & LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) pParameters->AddPreprocessorMacro("LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS", "1"); if (vertexFactoryFlags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS) pParameters->AddPreprocessorMacro("LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS", "1"); if (vertexFactoryFlags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS) pParameters->AddPreprocessorMacro("LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS", "1"); if (vertexFactoryFlags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS) pParameters->AddPreprocessorMacro("LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS", "1"); if (vertexFactoryFlags & LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX) pParameters->AddPreprocessorMacro("LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX", "1"); return true; } uint32 LocalVertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { // create format declaration GPU_VERTEX_ELEMENT_DESC *pElementDesc = pElementsDesc; uint32 streamOffset; uint32 nElements = 0; uint32 nStreams = 0; // build stream 0 { streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // normal pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // tangent space if (flags & LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS) { // tangent pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // binormal pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; } // texcoord if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT3; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; } else if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; } // color if (flags & LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS) { pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_COLOR; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_UNORM4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(uint32); pElementDesc++; nElements++; } // end of stream nStreams++; } // build stream 1 // lightmap coords if (flags & LOCAL_VERTEX_FACTORY_FLAG_LIGHTMAP_TEXCOORD_STREAM) { streamOffset = 0; pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD; pElementDesc->SemanticIndex = 1; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float2); pElementDesc++; nElements++; nStreams++; } // build stream 2 // instance transforms if (flags & LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX) { streamOffset = 0; // row 1 of transform pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 1; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float4); pElementDesc++; nElements++; // row 2 of transform pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 2; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float4); pElementDesc++; nElements++; // row 3 of transform pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 3; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT4; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 1; streamOffset += sizeof(float4); pElementDesc++; nElements++; nStreams++; } // done return nElements; } <file_sep>/Engine/Source/Engine/Physics/StaticObject.h #pragma once #include "Engine/Physics/CollisionObject.h" namespace Physics { class StaticObject : public CollisionObject { public: StaticObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform); virtual ~StaticObject(); // overrides virtual void OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; virtual void OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) override; protected: // overrides virtual btCollisionObject *GetBulletCollisionObject() const override; virtual void OnCollisionShapeChanged() override; virtual void OnTransformChanged() override; btCollisionObject *m_pBulletCollisionObject; }; } // namespace Physics <file_sep>/Engine/Source/BaseGame/LoadingScreenProgressCallbacks.h #pragma once #include "BaseGame/Common.h" #include "YBaseLib/ProgressCallbacks.h" class GPUContext; class MiniGUIContext; class LoadingScreenProgressCallbacks : public BaseProgressCallbacks { public: LoadingScreenProgressCallbacks(uint32 offsetX = 0, uint32 offsetY = 0, uint32 fontHeight = 16, uint32 barWidth = 300, uint32 barHeight = 20); ~LoadingScreenProgressCallbacks(); virtual void PushState(); virtual void PopState(); virtual void SetCancellable(bool cancellable); virtual void SetStatusText(const char *statusText); virtual void SetProgressRange(uint32 range); virtual void SetProgressValue(uint32 value); virtual void DisplayError(const char *message); virtual void DisplayWarning(const char *message); virtual void DisplayInformation(const char *message); virtual void DisplayDebugMessage(const char *message); virtual void ModalError(const char *message); virtual bool ModalConfirmation(const char *message); virtual uint32 ModalPrompt(const char *message, uint32 nOptions, ...); private: void Redraw(); virtual void RedrawRenderThread(); uint32 m_offsetX; uint32 m_offsetY; uint32 m_fontHeight; uint32 m_barWidth; uint32 m_barHeight; float m_lastPercentComplete; uint32 m_lastBarLength; Timer m_timeSinceLastDraw; }; <file_sep>/Engine/Source/ContentConverter/AssimpMaterialImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpMaterialImporter.h" #include "ContentConverter/AssimpCommon.h" #include "ContentConverter/TextureImporter.h" #include "ResourceCompiler/MaterialGenerator.h" AssimpMaterialImporter::AssimpMaterialImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(NULL), m_pLogStream(NULL), m_pScene(NULL) { } AssimpMaterialImporter::~AssimpMaterialImporter() { delete m_pLogStream; delete m_pImporter; } void AssimpMaterialImporter::SetDefaultOptions(Options *pOptions) { pOptions->ListOnly = false; pOptions->AllMaterials = false; } bool AssimpMaterialImporter::Execute() { if (m_pOptions->SourcePath.GetLength() == 0 || m_pOptions->OutputName.GetLength() == 0 || m_pOptions->OutputDirectory.GetLength() == 0) { } return false; } bool AssimpMaterialImporter::LoadScene() { // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(AssimpHelpers::GetAssimpSkeletalMeshImportPostProcessingFlags()); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } void AssimpMaterialImporter::ListMaterials() { m_pProgressCallbacks->DisplayFormattedInformation("%u materials in scene: ", m_pScene->mNumMaterials); for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { aiString aiMaterialName; if (!aiGetMaterialString(m_pScene->mMaterials[i], AI_MATKEY_NAME, &aiMaterialName)) aiMaterialName.Set(String::FromFormat("material%u", i)); m_pProgressCallbacks->DisplayFormattedInformation(" %s", aiMaterialName.C_Str()); } } bool AssimpMaterialImporter::ImportMaterials() { return false; } static bool GetTextureFileName(String &fileName, const char *sourceFileName, const char *textureFileName, ProgressCallbacks *pProgressCallbacks) { FileSystem::BuildPathRelativeToFile(fileName, sourceFileName, textureFileName, true, true); if (FileSystem::FileExists(fileName)) return true; // try to correct it by stripping all the crud off and making it relative to the source const char *lastSlashPos = Max(Y_strrchr(textureFileName, '/'), Y_strrchr(textureFileName, '\\')); if (lastSlashPos == nullptr) return false; // construct relative filename FileSystem::BuildPathRelativeToFile(fileName, sourceFileName, lastSlashPos + 1, true, true); if (FileSystem::FileExists(fileName)) { pProgressCallbacks->DisplayFormattedWarning("Successfully corrected filename '%s' to '%s'", textureFileName, fileName.GetCharArray()); return true; } pProgressCallbacks->DisplayFormattedError("Failed to locate texture at '%s' relative to '%s'", textureFileName, sourceFileName); return false; } static bool ImportTexture(const char *sourceFileName, const char *textureFileName, const char *maskFileName, const char *outputName, aiTextureMapMode *textureMapModes, TEXTURE_USAGE usage, ProgressCallbacks *pProgressCallbacks) { // get full texture file name PathString fileName; // check if the name already exists fileName.Format("%s.tex.zip", outputName); if (g_pVirtualFileSystem->FileExists(fileName)) { pProgressCallbacks->DisplayFormattedInformation("Skipping import of texture '%s', it already exists ('%s')", textureFileName, outputName); return true; } // get filename pProgressCallbacks->DisplayFormattedInformation("Trying to import texture at '%s'...", textureFileName); // exists? if (!GetTextureFileName(fileName, sourceFileName, textureFileName, pProgressCallbacks)) return false; // create texture importer TextureImporterOptions options; TextureImporter::SetDefaultOptions(&options); options.InputFileNames.Add(fileName); options.OutputName = outputName; options.Usage = usage; options.Compile = false; options.Optimize = false; options.SourcePremultipliedAlpha = false; // handle masks if (maskFileName != nullptr) { pProgressCallbacks->DisplayFormattedInformation("With mask texture at '%s'...", maskFileName); // exists? if (!GetTextureFileName(fileName, sourceFileName, maskFileName, pProgressCallbacks)) return false; options.InputMaskFileNames.Add(fileName); } // u mode if (textureMapModes[0] == aiTextureMapMode_Wrap) options.AddressU = TEXTURE_ADDRESS_MODE_WRAP; else if (textureMapModes[0] == aiTextureMapMode_Mirror) options.AddressU = TEXTURE_ADDRESS_MODE_MIRROR; else if (textureMapModes[0] == aiTextureMapMode_Clamp) options.AddressU = TEXTURE_ADDRESS_MODE_CLAMP; else options.AddressU = TEXTURE_ADDRESS_MODE_WRAP; // v mode if (textureMapModes[1] == aiTextureMapMode_Wrap) options.AddressV = TEXTURE_ADDRESS_MODE_WRAP; else if (textureMapModes[1] == aiTextureMapMode_Mirror) options.AddressV = TEXTURE_ADDRESS_MODE_MIRROR; else if (textureMapModes[1] == aiTextureMapMode_Clamp) options.AddressV = TEXTURE_ADDRESS_MODE_CLAMP; else options.AddressV = TEXTURE_ADDRESS_MODE_WRAP; // run the importer TextureImporter importer(pProgressCallbacks); if (!importer.Execute(&options)) { pProgressCallbacks->DisplayFormattedError("Failed to import texture '%s'...", fileName.GetCharArray()); return false; } // done return true; } bool AssimpMaterialImporter::ImportMaterial(const aiMaterial *pAIMaterial, const char *sourceFileName, const char *outputDirectory, const char *outputPrefix, const char *outputName, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { aiColor4D propColor; aiString propString; aiString maskString; int propInt; aiTextureMapMode textureMapMode[2]; PathString fileName; SmallString resourceName; unsigned int textureFlags; // pull some initial properties bool isTransparent = (aiGetMaterialInteger(pAIMaterial, AI_MATKEY_BLEND_FUNC, &propInt) == aiReturn_SUCCESS); bool hasNormalMap = (aiGetMaterialTextureCount(pAIMaterial, aiTextureType_NORMALS) > 0); bool hasBumpMap = (aiGetMaterialTextureCount(pAIMaterial, aiTextureType_HEIGHT) > 0); if (!isTransparent) { // try searching for an opacity map if not transparent textureFlags = 0; if ((aiGetMaterialTexture(pAIMaterial, aiTextureType_DIFFUSE, 0, &propString, nullptr, nullptr, nullptr, nullptr, nullptr, &textureFlags) == aiReturn_SUCCESS && textureFlags & aiTextureFlags_UseAlpha) || aiGetMaterialTexture(pAIMaterial, aiTextureType_OPACITY, 0, &propString, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == aiReturn_SUCCESS) { // no blending is defined, but the material is transparent. assume default of straight blending isTransparent = true; } } // determine material to use MaterialGenerator materialGenerator; if (isTransparent) materialGenerator.Create((hasNormalMap || hasBumpMap) ? "shaders/engine/phong_lit_normalmap_transparent" : "shaders/engine/phong_lit_transparent"); else materialGenerator.Create((hasNormalMap || hasBumpMap) ? "shaders/engine/phong_lit_normalmap" : "shaders/engine/phong_lit"); // base color { if (aiGetMaterialColor(pAIMaterial, AI_MATKEY_COLOR_DIFFUSE, &propColor) != aiReturn_SUCCESS) { propColor.r = 1.0f; propColor.g = 1.0f; propColor.b = 1.0f; propColor.a = 1.0f; } float3 diffuseColor(propColor.r, propColor.g, propColor.b); materialGenerator.SetShaderUniformParameterByName("BaseColor", SHADER_PARAMETER_TYPE_FLOAT3, &diffuseColor); } // default texture map mode textureMapMode[0] = aiTextureMapMode_Wrap; textureMapMode[1] = aiTextureMapMode_Wrap; // base texture if (aiGetMaterialTexture(pAIMaterial, aiTextureType_DIFFUSE, 0, &propString, nullptr, nullptr, nullptr, nullptr, textureMapMode, &textureFlags) == aiReturn_SUCCESS) { // remove the extension resourceName = propString.C_Str(); int32 extensionPos = resourceName.RFind('.'); if (extensionPos > 0) resourceName.Erase(extensionPos); // sanitize the texture name FileSystem::SanitizeFileName(resourceName); fileName.Format("%s/%s%s", outputDirectory, outputPrefix, resourceName.GetCharArray()); // has an alpha mask? add it at the same time if (isTransparent) { // if use alpha flag is set, use that as the alpha channel. otherwise, try for the opacity texture if (textureFlags & aiTextureFlags_UseAlpha) maskString = propString; else aiGetMaterialTexture(pAIMaterial, aiTextureType_OPACITY, 0, &maskString, nullptr, nullptr, nullptr, nullptr, nullptr, &textureFlags); } // try importing it if (ImportTexture(sourceFileName, propString.C_Str(), (maskString.length != 0) ? maskString.C_Str() : nullptr, fileName, textureMapMode, TEXTURE_USAGE_COLOR_MAP, pProgressCallbacks)) { materialGenerator.SetShaderStaticSwitchParameterByName("UseBaseTexture", true); materialGenerator.SetShaderTextureParameterStringByName("BaseTexture", fileName); } } if (hasNormalMap && aiGetMaterialTexture(pAIMaterial, aiTextureType_NORMALS, 0, &propString, nullptr, nullptr, nullptr, nullptr, textureMapMode, &textureFlags) == aiReturn_SUCCESS) { // remove the extension resourceName = propString.C_Str(); int32 extensionPos = resourceName.RFind('.'); if (extensionPos > 0) resourceName.Erase(extensionPos); // sanitize the texture name FileSystem::SanitizeFileName(resourceName); fileName.Format("%s/%s%s", outputDirectory, outputPrefix, resourceName.GetCharArray()); // try importing it if (ImportTexture(sourceFileName, propString.C_Str(), nullptr, fileName, textureMapMode, TEXTURE_USAGE_NORMAL_MAP, pProgressCallbacks)) materialGenerator.SetShaderTextureParameterStringByName("NormalMap", fileName); } else if (hasBumpMap && aiGetMaterialTexture(pAIMaterial, aiTextureType_HEIGHT, 0, &propString, nullptr, nullptr, nullptr, nullptr, textureMapMode, &textureFlags) == aiReturn_SUCCESS) { // remove the extension resourceName = propString.C_Str(); int32 extensionPos = resourceName.RFind('.'); if (extensionPos > 0) resourceName.Erase(extensionPos); // sanitize the texture name FileSystem::SanitizeFileName(resourceName); fileName.Format("%s/%s%s", outputDirectory, outputPrefix, resourceName.GetCharArray()); // try importing it // for now, treat bump map == height map if (ImportTexture(sourceFileName, propString.C_Str(), nullptr, fileName, textureMapMode, TEXTURE_USAGE_NORMAL_MAP, pProgressCallbacks)) materialGenerator.SetShaderTextureParameterStringByName("NormalMap", fileName); } // construct output filename fileName.Format("%s.mtl.xml", outputName); AutoReleasePtr<ByteStream> pOutputStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pOutputStream == nullptr || !materialGenerator.SaveToXML(pOutputStream)) { pProgressCallbacks->DisplayFormattedError("Failed to write material file '%s'", fileName.GetCharArray()); if (pOutputStream != nullptr) pOutputStream->Discard(); return false; } pOutputStream->Commit(); return true; } <file_sep>/Engine/Source/ContentConverter/BaseImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/BaseImporter.h" BaseImporter::BaseImporter(ProgressCallbacks *pProgressCallbacks) : m_pProgressCallbacks(pProgressCallbacks) { } BaseImporter::~BaseImporter() { } <file_sep>/Engine/Source/MapCompilerStandalone/CMakeLists.txt set(HEADER_FILES Common.h ) set(SOURCE_FILES MapCompiler.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/MapCompilerStandalone) add_executable(MapCompiler ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(MapCompiler EngineMapCompiler EngineResourceCompiler EngineMain EngineCore) install(TARGETS MapCompiler DESTINATION ${INSTALL_BINARIES_DIRECTORY}) <file_sep>/DemoGame/Source/DemoGame/PrecompiledHeader.h #include "Engine/Common.h" <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2CVars.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2CVars.h" namespace CVars { // OpenGL CVars //CVar r_opengl_disable_vertex_attrib_binding("r_opengl_disable_vertex_attrib_binding", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "Disable ARB_vertex_attrib_binding even if detected", "bool"); //CVar r_opengl_disable_direct_state_access("r_opengl_disable_direct_state_access", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "Disable EXT_direct_state_access even if detected", "bool"); //CVar r_opengl_disable_multi_bind("r_opengl_disable_multi_bind", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "Disable ARB_multi_bind even if detected", "bool"); } <file_sep>/DemoGame/Source/DemoGame/PrecompiledHeader.cpp #include "DemoGame/PrecompiledHeader.h" <file_sep>/Engine/Source/Core/Resource.cpp #include "Core/PrecompiledHeader.h" #include "Core/Resource.h" DEFINE_RESOURCE_TYPE_INFO(Resource); Resource::Resource(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(pResourceTypeInfo) { } Resource::~Resource() { } static inline bool ResourceNameCharacterIsSane(char c, bool stripSlashes) { if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && c != '_' && c != '-') { if (!stripSlashes && c == '/') return true; return false; } return true; } void Resource::SanitizeResourceName(String &resourceName, bool stripSlashes /* = true */) { for (uint32 i = 0; i < resourceName.GetLength(); i++) { if (!ResourceNameCharacterIsSane(resourceName[i], stripSlashes)) resourceName[i] = '_'; } } <file_sep>/Engine/Source/ContentConverter/AssimpStaticMeshImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/AssimpCommon.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "ContentConverter/AssimpMaterialImporter.h" #include "ResourceCompiler/StaticMeshGenerator.h" AssimpStaticMeshImporter::AssimpStaticMeshImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks), m_pOptions(pOptions), m_pImporter(NULL), m_pLogStream(NULL), m_pScene(NULL), m_globalTransform(float4x4::Identity), m_pOutputGenerator(NULL) { } AssimpStaticMeshImporter::~AssimpStaticMeshImporter() { delete m_pOutputGenerator; delete m_pLogStream; delete m_pImporter; } void AssimpStaticMeshImporter::SetDefaultOptions(Options *pOptions) { pOptions->ImportMaterials = false; pOptions->DefaultMaterialName = "materials/engine/default"; pOptions->BuildCollisionShapeType = StaticMeshGenerator::CollisionShapeType_TriangleMesh; pOptions->CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; pOptions->FlipFaceOrder = false; pOptions->TransformMatrix.SetIdentity(); } bool AssimpStaticMeshImporter::GetFileSubMeshNames(const char *filename, Array<String> &meshNames, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // create temporary log callback AssimpHelpers::ProgressCallbacksLogStream logCallback(pProgressCallbacks); // import the file Assimp::Importer importer; const aiScene *pScene = importer.ReadFile(filename, 0); if (pScene == nullptr) { pProgressCallbacks->DisplayFormattedError("Failed to parse file '%s'", filename); return false; } // post process the scene, but only to reduce the amount of meshes if (!importer.ApplyPostProcessing(aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph)) { pProgressCallbacks->DisplayFormattedError("Failed to postprocess file '%s'", filename); return false; } // get the mesh names for (unsigned int i = 0; i < pScene->mNumMeshes; i++) { const aiMesh *pMesh = pScene->mMeshes[i]; if (pMesh->mName.length == 0) meshNames.Add(String::FromFormat("* Unnamed Mesh %u", i)); else meshNames.Add(pMesh->mName.C_Str()); } return true; } bool AssimpStaticMeshImporter::Execute() { Timer timer; if (m_pOptions->SourcePath.IsEmpty() || m_pOptions->DefaultMaterialName.IsEmpty() || (m_pOptions->ImportMaterials && m_pOptions->MaterialDirectory.IsEmpty())) { m_pProgressCallbacks->ModalError("Missing parameters"); return false; } // ensure assimp is initialized if (!AssimpHelpers::InitializeAssimp()) { m_pProgressCallbacks->ModalError("assimp initialization failed"); return false; } // determine base output path { int32 lastSlashPosition = m_pOptions->OutputResourceName.RFind('/'); if (lastSlashPosition >= 0) m_baseOutputPath = m_pOptions->OutputResourceName.SubString(0, lastSlashPosition); } timer.Reset(); if (!LoadScene()) { m_pProgressCallbacks->ModalError("LoadScene() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("LoadScene(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateGenerator()) { m_pProgressCallbacks->ModalError("CreateGenerator() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateGenerator(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateMaterials()) { m_pProgressCallbacks->ModalError("CreateMaterials() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateMaterials(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!CreateMesh()) { m_pProgressCallbacks->ModalError("CreateMesh() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("CreateMesh(): %.4f ms", timer.GetTimeMilliseconds()); timer.Reset(); if (!PostProcess()) { m_pProgressCallbacks->ModalError("PostProcess() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("PostProcess(): %.4f ms", timer.GetTimeMilliseconds()); if (m_pOptions->OutputResourceName.GetLength() > 0) { timer.Reset(); if (!WriteOutput()) { m_pProgressCallbacks->ModalError("WriteOutput() failed. The log may contain more information as to why."); return false; } m_pProgressCallbacks->DisplayFormattedInformation("WriteOutput(): %.4f ms", timer.GetTimeMilliseconds()); } return true; } bool AssimpStaticMeshImporter::LoadScene() { // create importer m_pImporter = new Assimp::Importer(); // hook up log interface m_pLogStream = new AssimpHelpers::ProgressCallbacksLogStream(m_pProgressCallbacks); // pass filename to assimp m_pScene = m_pImporter->ReadFile(m_pOptions->SourcePath, 0); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ReadFile failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // get post process flags uint32 postProcessFlags = AssimpHelpers::GetAssimpStaticMeshImportPostProcessingFlags(); // get coordinate system transform bool reverseWinding; float4x4 coordinateSystemTransform(float4x4::MakeCoordinateSystemConversionMatrix(m_pOptions->CoordinateSystem, COORDINATE_SYSTEM_Z_UP_RH, &reverseWinding)); if (m_pOptions->FlipFaceOrder) reverseWinding = !reverseWinding; if (reverseWinding) postProcessFlags |= aiProcess_FlipWindingOrder; // create global transform m_globalTransform = m_pOptions->TransformMatrix * coordinateSystemTransform; // apply postprocessing m_pScene = m_pImporter->ApplyPostProcessing(postProcessFlags); if (m_pScene == NULL) { const char *errorMessage = m_pImporter->GetErrorString(); m_pProgressCallbacks->DisplayFormattedError("Importer::ApplyPostProcessing failed. Error: %s", (errorMessage != NULL) ? errorMessage : "none"); return false; } // display info m_pProgressCallbacks->DisplayFormattedInformation("Scene info: %u animations, %u camera, %u lights, %u materials, %u meshes, %u textures", m_pScene->mNumAnimations, m_pScene->mNumCameras, m_pScene->mNumLights, m_pScene->mNumMaterials, m_pScene->mNumMeshes, m_pScene->mNumTextures); // ok return true; } bool AssimpStaticMeshImporter::CreateGenerator() { bool hasTextureCoordinates = false; bool hasVertexColors = false; // determine whether there are any texture coordinates, vertex colors for (uint32 i = 0; i < m_pScene->mNumMeshes; i++) { if (m_pScene->mMeshes[i]->GetNumUVChannels() > 0) hasTextureCoordinates = true; if (m_pScene->mMeshes[i]->GetNumColorChannels() > 0) hasVertexColors = true; } // create generator m_pOutputGenerator = new StaticMeshGenerator(); m_pOutputGenerator->Create(hasTextureCoordinates, hasVertexColors); // add level zero lod m_pOutputGenerator->AddLOD(); return true; } bool AssimpStaticMeshImporter::CreateMaterials() { if (!m_pOptions->ImportMaterials) { for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { m_materialMapping.Add(m_pOptions->DefaultMaterialName); } return true; } for (uint32 i = 0; i < m_pScene->mNumMaterials; i++) { const aiMaterial *pAIMaterial = m_pScene->mMaterials[i]; aiString aiMaterialName; if (!aiGetMaterialString(pAIMaterial, AI_MATKEY_NAME, &aiMaterialName) || aiMaterialName.length == 0) aiMaterialName.Set(String::FromFormat("material%u", i)); SmallString sanitizedMaterialName; FileSystem::SanitizeFileName(sanitizedMaterialName, aiMaterialName.C_Str()); PathString materialResourceName; PathString fileName; materialResourceName.Format("%s/%s%s", m_pOptions->MaterialDirectory.GetCharArray(), m_pOptions->MaterialPrefix.GetCharArray(), sanitizedMaterialName.GetCharArray()); m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' -> '%s'", aiMaterialName.C_Str(), materialResourceName.GetCharArray()); // does this material exist? fileName.Format("%s.mtl.xml", materialResourceName.GetCharArray()); if (g_pVirtualFileSystem->FileExists(fileName)) { m_pProgressCallbacks->DisplayFormattedInformation("Material '%s' already exists, skipping import...", materialResourceName.GetCharArray()); m_materialMapping.Add(materialResourceName); continue; } // import the material if (!AssimpMaterialImporter::ImportMaterial(pAIMaterial, m_pOptions->SourcePath, m_pOptions->MaterialDirectory, m_pOptions->MaterialPrefix, materialResourceName, m_pProgressCallbacks)) { m_pProgressCallbacks->DisplayFormattedWarning("Material '%s' failed import, using default material.", materialResourceName.GetCharArray()); m_materialMapping.Add(m_pOptions->DefaultMaterialName); continue; } // add it m_materialMapping.Add(materialResourceName); } return true; } bool AssimpStaticMeshImporter::CreateMesh() { // todo: global transform //const aiNode *pRootNode = m_pScene->mRootNode; // parse all meshes for (uint32 i = 0; i < m_pScene->mNumMeshes; i++) { const aiMesh *pMesh = m_pScene->mMeshes[i]; if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) { m_pProgressCallbacks->DisplayFormattedWarning("Skipping non-triangle mesh %u", i); continue; } if (pMesh->mNumVertices == 0 || pMesh->mNumFaces == 0) { m_pProgressCallbacks->DisplayFormattedWarning("Skipping empty mesh %u", i); continue; } if (!ParseMesh(pMesh, m_pOutputGenerator, 0, pMesh->mName.C_Str())) return false; } // ok return true; } bool AssimpStaticMeshImporter::ParseMesh(const aiMesh *pMesh, StaticMeshGenerator *pOutputGenerator, uint32 lodIndex, const char *meshName) { // for each mesh... //uint64 smoothingGroupMask = (1 << 0); // create output mesh, using max nweights for now m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] using material %s", meshName, m_materialMapping[pMesh->mMaterialIndex].GetCharArray()); // for this mesh MemArray<uint32> meshVertexIndices; // create batch uint32 batchIndex = pOutputGenerator->AddBatch(lodIndex, m_materialMapping[pMesh->mMaterialIndex]); // create vertices without any weights in them for (uint32 vertexIndex = 0; vertexIndex < pMesh->mNumVertices; vertexIndex++) { float3 vertexPosition = m_globalTransform.TransformPoint(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mVertices[vertexIndex])); float2 vertexTextureCoordinates = ((pMesh->GetNumUVChannels() > 0) ? AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTextureCoords[0][vertexIndex]).xy() : float2::Zero); uint32 vertexColor = ((pMesh->GetNumColorChannels() > 0) ? AssimpHelpers::AssimpColor4ToColor(pMesh->mColors[0][vertexIndex]) : MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); float3 vertexTangent; float3 vertexBinormal; float3 vertexNormal; if (pMesh->HasTangentsAndBitangents()) { vertexTangent = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mTangents[vertexIndex])); vertexBinormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mBitangents[vertexIndex])); vertexNormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else if (pMesh->HasNormals()) { vertexTangent = float3::UnitX; vertexBinormal = float3::UnitY; vertexNormal = m_globalTransform.TransformNormal(AssimpHelpers::AssimpVector3ToFloat3(pMesh->mNormals[vertexIndex])); } else { vertexTangent = float3::UnitX; vertexBinormal = float3::UnitY; vertexNormal = float3::UnitZ; } // add to list uint32 outVertexIndex = pOutputGenerator->AddVertex(lodIndex, vertexPosition, vertexTangent, vertexBinormal, vertexNormal, vertexTextureCoordinates, vertexColor); meshVertexIndices.Add(outVertexIndex); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u vertices", meshName, pMesh->mNumVertices); // read triangles for (uint32 faceIndex = 0; faceIndex < pMesh->mNumFaces; faceIndex++) { const aiFace *pFace = &pMesh->mFaces[faceIndex]; if (pFace->mNumIndices != 3) { m_pProgressCallbacks->DisplayFormattedError("in mesh %s: face %u does not have 3 indices", meshName, faceIndex); return false; } DebugAssert(pFace->mIndices[0] < meshVertexIndices.GetSize() && pFace->mIndices[1] < meshVertexIndices.GetSize() && pFace->mIndices[2] < meshVertexIndices.GetSize()); m_pOutputGenerator->AddTriangle(lodIndex, batchIndex, meshVertexIndices[pFace->mIndices[0]], meshVertexIndices[pFace->mIndices[1]], meshVertexIndices[pFace->mIndices[2]]); } m_pProgressCallbacks->DisplayFormattedInformation("[mesh %s] added %u faces/triangles", meshName, pMesh->mNumFaces); return true; } bool AssimpStaticMeshImporter::PostProcess() { m_pOutputGenerator->GenerateTangents(0); m_pOutputGenerator->CalculateBounds(); // build collision shape if (m_pOptions->BuildCollisionShapeType != StaticMeshGenerator::CollisionShapeType_Count) { // build box m_pProgressCallbacks->DisplayFormattedInformation("Generating collision shape..."); if (!m_pOutputGenerator->BuildCollisionShape((StaticMeshGenerator::CollisionShapeType)m_pOptions->BuildCollisionShapeType)) { m_pProgressCallbacks->DisplayError("Failed to generate collision shape."); return false; } } return true; } bool AssimpStaticMeshImporter::WriteOutput() { PathString outputResourceFileName; outputResourceFileName.Format("%s.staticmesh.xml", m_pOptions->OutputResourceName.GetCharArray()); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputResourceFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("could not open file '%s'", outputResourceFileName.GetCharArray()); return false; } if (!m_pOutputGenerator->SaveToXML(pStream)) { m_pProgressCallbacks->DisplayError("failed to save xml file"); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); return true; } StaticMeshGenerator *AssimpStaticMeshImporter::DetachOutputGenerator() { StaticMeshGenerator *pGenerator = m_pOutputGenerator; m_pOutputGenerator = nullptr; return pGenerator; } <file_sep>/Engine/Source/Engine/Physics/CollisionShape.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/CollisionShape.h" #include "Engine/Physics/BoxCollisionShape.h" #include "Engine/Physics/ConvexHullCollisionShape.h" #include "Engine/Physics/SphereCollisionShape.h" #include "Engine/Physics/TriangleMeshCollisionShape.h" namespace Physics { Y_Define_NameTable(NameTables::CollisionShapeType) Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_NONE, "None") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_BOX, "Box") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_SPHERE, "Sphere") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_TRIANGLE_MESH, "TriangleMesh") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_SCALED_TRIANGLE_MESH, "ScaledTriangleMesh") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_CONVEX_HULL, "ConvexHull") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_TERRAIN, "Terrain") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_BLOCK_MESH, "BlockMesh") Y_NameTable_VEntry(COLLISION_SHAPE_TYPE_BLOCK_TERRAIN, "BlockTerrain") Y_NameTable_End() static CollisionShape *CreateCollisionShape(uint8 shapeType) { switch (shapeType) { case COLLISION_SHAPE_TYPE_BOX: return new BoxCollisionShape(); case COLLISION_SHAPE_TYPE_SPHERE: return new SphereCollisionShape(); case COLLISION_SHAPE_TYPE_CONVEX_HULL: return nullptr; case COLLISION_SHAPE_TYPE_TRIANGLE_MESH: return new TriangleMeshCollisionShape(); } return nullptr; } CollisionShape *CollisionShape::CreateFromData(const void *pData, uint32 dataSize) { if (dataSize < sizeof(uint8)) return nullptr; const uint8 shapeType = *(const uint8 *)pData; const byte *pShapeData = reinterpret_cast<const byte *>(pData) + sizeof(uint8); uint32 shapeDataSize = dataSize - sizeof(uint8); CollisionShape *pReturnShape = CreateCollisionShape(shapeType); if (pReturnShape == nullptr || !pReturnShape->LoadFromData(pShapeData, shapeDataSize)) { pReturnShape->Release(); return nullptr; } return pReturnShape; } CollisionShape *CollisionShape::CreateFromStream(ByteStream *pStream, uint32 dataSize) { if (dataSize < sizeof(uint8)) return nullptr; uint8 shapeType; uint32 shapeDataSize = dataSize - sizeof(uint8); if (!pStream->ReadByte(&shapeType)) return nullptr; CollisionShape *pReturnShape = CreateCollisionShape(shapeType); if (pReturnShape == nullptr || !pReturnShape->LoadFromStream(pStream, shapeDataSize)) { pReturnShape->Release(); return nullptr; } return pReturnShape; } } // namespace Physics <file_sep>/Engine/Source/BlockEngine/BlockWorld.h #pragma once #include "Engine/World.h" #include "Engine/BlockPalette.h" #include "BlockEngine/BlockWorldTypes.h" #include "BlockEngine/BlockDrawTemplate.h" class BlockWorldSection; class BlockWorldChunk; class BlockWorldGenerator; class BlockDrawTemplate; class FIFVolume; namespace Physics { class RigidBody; } class BlockWorld : public World { public: BlockWorld(); virtual ~BlockWorld(); // world entity methods virtual void AddBrush(Brush *pObject) override; virtual void RemoveBrush(Brush *pObject) override; virtual const Entity *GetEntityByID(uint32 EntityId) const override; virtual Entity *GetEntityByID(uint32 EntityId) override; virtual void AddEntity(Entity *pEntity) override; virtual void MoveEntity(Entity *pEntity) override; virtual void RemoveEntity(Entity *pEntity) override; virtual void UpdateEntity(Entity *pEntity) override; // world update methods virtual void BeginFrame(float deltaTime) override; virtual void UpdateAsync(float deltaTime) override; virtual void Update(float deltaTime) override; virtual void EndFrame() override; // world creation/loading method bool Create(const char *basePath, const BlockPalette *pPalette, int32 chunkSize, int32 sectionSize, int32 lodLevels); bool Load(const char *basePath); // accessors const BlockPalette *GetPalette() const { return m_pPalette; } const BlockDrawTemplate *GetBlockDrawTemplate() const { return m_pBlockDrawTemplate; } const int32 GetChunkSize() const { return m_chunkSize; } const int32 GetSectionSize() const { return m_sectionSize; } const int32 GetLODLevels() const { return m_lodLevels; } const int32 GetRenderGroupsPerSectionXY() const { return m_renderGroupsPerSectionXY; } // size queries int32 GetMinSectionX() const { return m_minSectionX; } int32 GetMinSectionY() const { return m_minSectionY; } int32 GetMaxSectionX() const { return m_maxSectionX; } int32 GetMaxSectionY() const { return m_maxSectionY; } int32 GetSectionCount() const { return m_sectionCount; } int32 GetSectionCountX() const { return m_sectionCountX; } int32 GetSectionCountY() const { return m_sectionCountY; } // helper functions for determining block visibility bool IsVisibilityBlockingBlockValue(BlockWorldBlockType blockValue, CUBE_FACE checkFace = CUBE_FACE_COUNT) const; bool IsLightBlockingBlockValue(BlockWorldBlockType blockValue, CUBE_FACE checkFace = CUBE_FACE_COUNT) const; // helper function to calculate tile bounds static AABox CalculateSectionBoundingBox(int32 sectionSize, int32 chunkSize, int32 sectionX, int32 sectionY); static AABox CalculateSectionBoundingBox(int32 sectionSize, int32 chunkSize, int32 sectionX, int32 sectionY, int32 minChunkZ, int32 maxChunkZ); // helper function to calculate chunk bounds static AABox CalculateChunkBoundingBox(int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ); static AABox CalculateChunkBoundingBox(int32 chunkSize, int32 sectionSize, int32 sectionX, int32 sectionY, int32 lodLevel, int32 relativeChunkX, int32 relativeChunkY, int32 relativeChunkZ); // helper converters static void SplitCoordinates(int32 *sectionX, int32 *sectionY, int32 *localChunkX, int32 *localChunkY, int32 *localChunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 chunkSize, int32 sectionSize, int32 bx, int32 by, int32 bz); static void SplitCoordinates(int32 *chunkX, int32 *chunkY, int32 *chunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 chunkSize, int32 bx, int32 by, int32 bz); // convert local chunk block coordinates to global coordinates static void ConvertChunkBlockCoordinatesToGlobalCoordinates(int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ, int32 blockX, int32 blockY, int32 blockZ, int32 *pGlobalBlockX, int32 *pGlobalBlockY, int32 *pGlobalBlockZ); // global chunk coordinates to section + local chunk coordinates static void CalculateRelativeChunkCoordinates(int32 *sectionX, int32 *sectionY, int32 *relativeChunkX, int32 *relativeChunkY, int32 *relativeChunkZ, int32 sectionSize, int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ); // coordinate splitter void SplitCoordinates(int32 *sectionX, int32 *sectionY, int32 *localChunkX, int32 *localChunkY, int32 *localChunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 bx, int32 by, int32 bz) const; void SplitCoordinates(int32 *chunkX, int32 *chunkY, int32 *chunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 bx, int32 by, int32 bz) const; // global chunk coordinates to section + local chunk coordinates void CalculateRelativeChunkCoordinates(int32 *sectionX, int32 *sectionY, int32 *relativeChunkX, int32 *relativeChunkY, int32 *relativeChunkZ, int32 chunkX, int32 chunkY, int32 chunkZ) const; // helper function to calculate the section of a specified position void CalculateSectionForPosition(int32 *sx, int32 *sy, const float3 &position) const; // helper function to find the global chunk coordinates for a position void CalculateChunkForPosition(int32 *cx, int32 *cy, int32 *cz, const float3 &position) const; // helper function to calculate a global point from a position int3 CalculatePointForPosition(const float3 &position) const; // tile availability void GetSectionStatus(bool *available, bool *loaded, int32 sectionX, int32 sectionY, int32 requiredLODLevel = Y_INT32_MAX) const; bool IsSectionAvailable(int32 sectionX, int32 sectionY) const; bool IsSectionLoaded(int32 sectionX, int32 sectionY, int32 requiredLODLevel = Y_INT32_MAX) const; // chunk availablity void GetChunkStatus(bool *available, bool *loaded, int32 chunkX, int32 chunkY, int32 chunkZ, int32 requiredLODLevel) const; bool IsChunkAvailable(int32 chunkX, int32 chunkY, int32 chunkZ) const; bool IsChunkLoaded(int32 chunkX, int32 chunkY, int32 chunkZ, int32 requiredLODLevel = Y_INT32_MAX) const; // pending chunk count accessor (really block groups when transitioning) uint32 GetPendingChunkCount() const { return m_pendingChunks.GetSize(); } uint32 GetChunksMeshingInProgress() const { return m_chunksMeshingInProgress; } uint32 GetLoadedSectionCount() const { return m_loadedSections.GetSize(); } // tile accessors const BlockWorldSection *GetSection(int32 sectionX, int32 sectionY) const; BlockWorldSection *GetSection(int32 sectionX, int32 sectionY); // chunk accessors const BlockWorldChunk *GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const; BlockWorldChunk *GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ); // generator const BlockWorldGenerator *GetGenerator() const { return m_pGenerator; } BlockWorldGenerator *GetGenerator() { return m_pGenerator; } void SetGenerator(BlockWorldGenerator *pGenerator) { m_pGenerator = pGenerator; } // ensures that all sections are loaded (loads all lods) bool LoadAllSections(int32 maxLODLevel = 0, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // unloads all sections void UnloadAllSections(); // save changes to any sections bool SaveChangedSections(); // can this chunk be modified? (ie checks if we are the boundary chunk on a section and checks for neighbour sections) bool IsChunkNeighboursLoaded(const BlockWorldChunk *pChunk, int32 lodLevel) const; bool EnsureChunkNeighboursLoaded(const BlockWorldChunk *pChunk, int32 lodLevel); // create a new section where it doesn't exist BlockWorldSection *CreateSection(int32 sectionX, int32 sectionY, int32 minChunkZ, int32 maxChunkZ); void DeleteSection(int32 sectionX, int32 sectionY); void DeleteAllSections(); // expanded version const BlockWorldBlockType GetBlockValue(int32 bx, int32 by, int32 bz) const; bool ClearBlock(int32 bx, int32 by, int32 bz); bool SetBlockType(int32 bx, int32 by, int32 bz, BlockWorldBlockType blockType, BLOCK_WORLD_BLOCK_ROTATION blockRotation = BLOCK_WORLD_BLOCK_ROTATION_NORTH, bool createNonExistantChunks = false); bool SetBlockColor(int32 bx, int32 by, int32 bz, uint32 blockColor, bool createNonExistantChunks = false); // block-only raycast, this will hit blocks that aren't cubes as well bool RayCastBlock(const Ray &ray, int32 *pBlockX, int32 *pBlockY, int32 *pBlockZ, CUBE_FACE *pBlockFace, BlockWorldBlockType *pBlockValue, float *pDistance) const; bool RayCastBlock(const float3 &origin, const float3 &direction, float maxDistance, int32 *pBlockX, int32 *pBlockY, int32 *pBlockZ, CUBE_FACE *pBlockFace, BlockWorldBlockType *pBlockValue, float *pDistance) const { return RayCastBlock(Ray(origin, direction, maxDistance), pBlockX, pBlockY, pBlockZ, pBlockFace, pBlockValue, pDistance); } // helpers static bool IsValidChunkSize(uint32 chunkSize, uint32 sectionSize, uint32 lodCount); static int32 GetSectionArrayIndex(int32 sectionX, int32 sectionY, int32 minSectionX, int32 minSectionY, int32 maxSectionX, int32 maxSectionY); int32 GetSectionArrayIndex(int32 sectionX, int32 sectionY) const; // Create an animated block 'explosion'-type effect. bool CreateAnimatedPhysicsBlock(const float3 &basePosition, const Quaternion &rotation, BlockWorldBlockType blockValue, const float3 &forceVector, float despawnTime = 5.0f); bool CreateAnimatedPhysicsBlock(int32 x, int32 y, int32 z, const float3 &forceVector, bool removeBlock = true, float despawnTime = 5.0f); // create a block animation bool CreateBlockAnimation(BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation, const Transform &startTransform, const Transform &endTransform, float spawnTime = 1.0f, EasingFunction::Type easingFunction = EasingFunction::Linear, bool setAfterSpawn = false, int32 setBlockX = 0, int32 setBlockY = 0, int32 setBlockZ = 0); // Create an animated block spawn event void SetBlockWithAnimation(int32 blockX, int32 blockY, int32 blockZ, BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation, const Transform &startTransform, float spawnTime = 1.0f, EasingFunction::Type easingFunction = EasingFunction::Linear, bool setAfterSpawn = true); void SetBlockWithAnimation(int32 blockX, int32 blockY, int32 blockZ, BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation); private: // helper function to determine world bounds AABox CalculateBlockWorldBoundingBox() const; // file access ByteStream *OpenWorldFile(const char *fileName, uint32 access); // index initialization bool AllocateIndex(); bool LoadIndex(); bool SaveIndex(); // global entity load/save bool LoadGlobalEntities(); bool SaveGlobalEntities(); // rebuild section array void ResizeIndex(int32 newMinSectionX, int32 newMinSectionY, int32 newMaxSectionX, int32 newMaxSectionY); // section loading/unloading bool LoadSection(int32 sectionX, int32 sectionY, int32 lodLevel, bool unloadHigherLODs); void UnloadSection(int32 sectionX, int32 sectionY); bool SaveSection(int32 sectionX, int32 sectionY); bool SaveSection(BlockWorldSection *pSection); // call when a section/chunk is created or loaded void OnChunkLoaded(BlockWorldSection *pSection, BlockWorldChunk *pChunk); void OnChunkUnloaded(BlockWorldSection *pSection, BlockWorldChunk *pChunk); // helper for calculating lod of section int32 CalculateSectionLODForViewer(int32 sectionX, int32 sectionY, const float3 &viewerPosition); // load any sections that are now in-range void LoadNewInRangeSections(); // unload any sections that are out-of-range void UnloadOutOfRangeSections(float timeSinceLastUpdate); // stream in/out any needed sections void StreamSections(float timeSinceLastUpdate); // update the lod level of currently-loaded chunks void TransitionLoadedChunkRenderLODs(); // remove chunks from the specified lod level/render group from the world void RemoveChunkMesh(BlockWorldChunk *pChunk); // remove all meshes from the specified section at the specified lod void RemoveSectionMeshes(BlockWorldSection *pSection); // queue a chunk for meshing void QueueSingleChunkForMeshing(BlockWorldChunk *pChunk, int32 lodLevel); // call once per frame, sorts queued chunks according to distance from viewers void SortPendingMeshChunks(); // mesh a single chunk, returns true if any triangles are to be rendered void MeshSingleChunk(BlockWorldSection *pSection, BlockWorldChunk *pChunk, int32 lodLevel); // call once per frame, meshes queued chunks void ProcessPendingMeshChunks(); // chunk creator BlockWorldChunk *CreateChunk(int32 chunkX, int32 chunkY, int32 chunkZ); BlockWorldChunk *GetWritableChunk(int32 chunkX, int32 chunkY, int32 chunkZ, bool allowCreate = true); // helper functions for block setting void OnBlockChanged(BlockWorldChunk *pChunk, int32 lx, int32 ly, int32 lz); void OnEdgeBlockChanged(BlockWorldChunk *pChunk, int32 lx, int32 ly, int32 lz); bool ClearBlockBit(int32 x, int32 y, int32 z, BlockWorldBlockType bit); bool SetBlockBit(int32 x, int32 y, int32 z, BlockWorldBlockType bit); // block lighting update helper friend struct BlockLightingUpdateNode; void SpreadBlockLighting(BlockWorldChunk *pChunk, int32 x, int32 y, int32 z, uint8 lightLevel); void UnspreadBlockLighting(BlockWorldChunk *pChunk, int32 x, int32 y, int32 z); // so it can access the entity lookup hash table friend BlockWorldSection; void OnLoadEntity(Entity *pEntity); void OnUnloadEntity(Entity *pEntity); // all entities hash table typedef HashTable<uint32, Entity *> EntityHashTable; EntityHashTable m_entityHashTable; // global entities, ie entities that are global, or a section does not exist for them typedef MemArray<BlockWorldEntityReference> GlobalEntityReferenceArray; GlobalEntityReferenceArray m_globalEntityReferences; // settings String m_basePath; FIFVolume *m_pFIFVolume; const BlockPalette *m_pPalette; BlockDrawTemplate *m_pBlockDrawTemplate; int32 m_chunkSize; int32 m_sectionSize; int32 m_lodLevels; int32 m_sectionSizeInBlocks; int32 m_renderGroupsPerSectionXY; // section storage int32 m_minSectionX; int32 m_minSectionY; int32 m_maxSectionX; int32 m_maxSectionY; int32 m_sectionCountX; int32 m_sectionCountY; int32 m_sectionCount; BlockWorldSection **m_ppSections; BitSet32 m_availableSectionMask; // for faster iteration when unloading/streaming, we store loaded sections here, todo store x/y for cache efficiency PODArray<BlockWorldSection *> m_loadedSections; // sections queued to load struct QueuedSectionLoad { int32 SectionX, SectionY; int32 LODLevel; int32 ViewRange; }; MemArray<QueuedSectionLoad> m_queuedLoadSections; // chunk or chunk render group that is pending meshing struct PendingMeshingChunk { BlockWorldSection *pSection; BlockWorldChunk *pChunk; float3 ViewCenter; float MinimumViewDistance; int32 OldLODLevel; int32 NewLODLevel; }; MemArray<PendingMeshingChunk> m_pendingChunks; uint32 m_chunksMeshingInProgress; // generator BlockWorldGenerator *m_pGenerator; // block animation struct BlockAnimation { // Common.. make this use less memory perhaps? not like there will be a lot of them... BlockWorldBlockType BlockType; int32 LocationX, LocationY, LocationZ; BLOCK_WORLD_BLOCK_ROTATION Rotation; BlockDrawTemplate::BlockRenderProxy *pRenderProxy; Transform LastTransform; float LifeTime; float TimeRemaining; // Physics-only Physics::RigidBody *pRigidBody; // Spawn-only EasingFunction::Type AnimationFunction; Transform AnimationStartTransform; Transform AnimationEndTransform; bool SetAfterCompletion; }; MemArray<BlockAnimation> m_blockAnimations; BlockWorldBlockType m_animationInProgressBlockType; void UpdateBlockAnimations(float deltaTime); }; <file_sep>/Engine/Source/ContentConverter/BaseImporter.h #pragma once #include "ContentConverter/Common.h" #include "YBaseLib/ProgressCallbacks.h" class BaseImporter { public: BaseImporter(ProgressCallbacks *pProgressCallbacks); virtual ~BaseImporter(); ProgressCallbacks *GetProgressCallbacks() const { return m_pProgressCallbacks; } void SetProgressCallbacks(ProgressCallbacks *pProgressCallbacks) { m_pProgressCallbacks = pProgressCallbacks; } protected: ProgressCallbacks *m_pProgressCallbacks; };<file_sep>/Engine/Source/D3D12Renderer/D3D12CommandQueue.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" #include "D3D12Renderer/D3D12LinearHeaps.h" class D3D12CommandQueue { public: D3D12CommandQueue(D3D12GPUDevice *pGPUDevice, ID3D12Device *pD3DDevice, D3D12_COMMAND_LIST_TYPE type, uint32 linearBufferHeapSize, uint32 linearViewHeapSize, uint32 linearSamplerHeapSize); ~D3D12CommandQueue(); // accessors const D3D12_COMMAND_LIST_TYPE GetType() const { return m_type; } const uint32 GetLinearBufferHeapSize() const { return m_linearBufferHeapSize; } const uint32 GetLinearViewHeapSize() const { return m_linearViewHeapSize; } const uint32 GetLinearSamplerHeapSize() const { return m_linearSamplerHeapSize; } const uint64 GetNextFenceValue() const { return m_nextFenceValue; } const uint64 GetLastCompletedFenceValue() const { return m_lastCompletedFenceValue; } ID3D12CommandQueue *GetD3DCommandQueue() const { return m_pD3DCommandQueue; } // initialization bool Initialize(); // increment the fence value without executing anything uint64 CreateSynchronizationPoint(); // execute a command list. void ExecuteCommandList(ID3D12CommandList *pCommandList); // command list request, release ID3D12GraphicsCommandList *RequestCommandList(); ID3D12GraphicsCommandList *RequestAndOpenCommandList(ID3D12CommandAllocator *pCommandAllocator); void ReleaseCommandList(ID3D12GraphicsCommandList *pCommandList); void ReleaseFailedCommandList(ID3D12GraphicsCommandList *pCommandList); // command allocator request, release ID3D12CommandAllocator *RequestCommandAllocator(); void ReleaseCommandAllocator(ID3D12CommandAllocator *pAllocator, uint64 availableFenceValue); void ReleaseCommandAllocator(ID3D12CommandAllocator *pAllocator) { ReleaseCommandAllocator(pAllocator, GetNextFenceValue()); } // linear buffer request, release D3D12LinearBufferHeap *RequestLinearBufferHeap(); void ReleaseLinearBufferHeap(D3D12LinearBufferHeap *pHeap, uint64 availableFenceValue); void ReleaseLinearBufferHeap(D3D12LinearBufferHeap *pHeap) { ReleaseLinearBufferHeap(pHeap, GetNextFenceValue()); } // linear resource descriptor heap request, release D3D12LinearDescriptorHeap *RequestLinearViewHeap(); void ReleaseLinearViewHeap(D3D12LinearDescriptorHeap *pHeap, uint64 availableFenceValue); void ReleaseLinearViewHeap(D3D12LinearDescriptorHeap *pHeap) { ReleaseLinearViewHeap(pHeap, GetNextFenceValue()); } // linear sampler descriptor heap request, release D3D12LinearDescriptorHeap *RequestLinearSamplerHeap(); void ReleaseLinearSamplerHeap(D3D12LinearDescriptorHeap *pHeap, uint64 availableFenceValue); void ReleaseLinearSamplerHeap(D3D12LinearDescriptorHeap *pHeap) { ReleaseLinearSamplerHeap(pHeap, GetNextFenceValue()); } // waits until the specified fence value is completed void WaitForFence(uint64 fence); // resource cleanup void ScheduleResourceForDeletion(ID3D12Pageable *pResource); void ScheduleResourceForDeletion(ID3D12Pageable *pResource, uint64 fenceValue); void ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle); void ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle, uint64 fenceValue); // cleanup any resources that have had the fence passed void ReleaseStaleResources(); private: void UpdateLastCompletedFenceValue(); template<class T> T *SearchPool(MemArray<KeyValuePair<T *, uint64>> &pool); template<class T> T *SearchPoolAndWait(MemArray<KeyValuePair<T *, uint64>> &pool); template<class T> void InsertIntoPool(MemArray<KeyValuePair<T *, uint64>> &pool, T *pItem, uint64 fenceValue); void DeletePendingResources(uint64 fenceValue); // parents D3D12GPUDevice *m_pGPUDevice; ID3D12Device *m_pD3DDevice; D3D12_COMMAND_LIST_TYPE m_type; uint32 m_linearBufferHeapSize; uint32 m_linearViewHeapSize; uint32 m_linearSamplerHeapSize; uint32 m_maxCommandAllocatorPoolSize; uint32 m_maxLinearBufferHeapPoolSize; uint32 m_maxLinearViewHeapPoolSize; uint32 m_maxLinearSamplerHeapPoolSize; // actual command queue ID3D12CommandQueue *m_pD3DCommandQueue; ID3D12Fence *m_pD3DFence; HANDLE m_fenceEvent; uint64 m_nextFenceValue; uint64 m_lastCompletedFenceValue; // command list pool PODArray<ID3D12GraphicsCommandList *> m_commandListPool; uint32 m_outstandingCommandLists; // command allocator pool typedef KeyValuePair<ID3D12CommandAllocator *, uint64> CommandAllocatorEntry; MemArray<CommandAllocatorEntry> m_commandAllocatorPool; uint32 m_outstandingCommandAllocators; // linear buffer pool typedef KeyValuePair<D3D12LinearBufferHeap *, uint64> LinearBufferHeapEntry; MemArray<LinearBufferHeapEntry> m_linearBufferHeapPool; uint32 m_outstandingLinearBufferHeaps; // resource descriptor pool typedef KeyValuePair<D3D12LinearDescriptorHeap *, uint64> LinearResourceDescriptorHeapEntry; MemArray<LinearResourceDescriptorHeapEntry> m_linearViewHeapPool; uint32 m_outstandingLinearViewHeaps; // sampler descriptor pool typedef KeyValuePair<D3D12LinearDescriptorHeap *, uint64> LinearSamplerDescriptorHeapEntry; MemArray<LinearSamplerDescriptorHeapEntry> m_linearSamplerHeapPool; uint32 m_outstandingLinearSamplerHeaps; // allocator lock RecursiveMutex m_allocatorLock; // object scheduled for deletion // this has a lock mainly for the main graphics queue, since it can be called from any thread struct PendingDeletionResource { ID3D12Pageable *pResource; uint64 FenceValue; }; struct PendingDeletionDescriptor { D3D12DescriptorHandle Handle; uint64 FenceValue; }; MemArray<PendingDeletionResource> m_pendingDeletionResources; MemArray<PendingDeletionDescriptor> m_pendingDeletionDescriptors; Mutex m_pendingResourceLock; }; <file_sep>/Engine/Source/MapCompiler/MapSource.h #pragma once #include "MapCompiler/MapCompiler.h" #include "MapCompiler/MapSourceGeometryData.h" #include "Engine/Common.h" #include "Engine/TerrainRenderer.h" #include "Core/PropertyTable.h" #include "YBaseLib/ProgressCallbacks.h" class XMLReader; class XMLWriter; class EntityTypeInfo; class ObjectTemplate; class TerrainLayerListGenerator; class MapSourceRegion; class MapSourceEntityData; class MapSourceTerrainData; class MapSource { friend class MapCompiler; friend class MapSourceRegion; public: MapSource(); ~MapSource(); ZipArchive *GetMapArchive() const { return m_pMapArchive; } // object template, may or may not be present const ObjectTemplate *GetObjectTemplate() const { return m_pObjectTemplate; } bool IsChanged() const; void FlagAsChanged(); // helper methods const int2 GetRegionForPosition(const float3 &position) const; const int2 GetRegionForTerrainSection(int32 sectionX, int32 sectionY) const; // Serialization. void Create(uint32 regionSize = 1024); bool Load(const char *fileName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool Save(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool SaveAs(const char *newFileName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // Loading from stream. Save() will not be possible, SaveAs() will be possible, however. bool LoadFromStream(ByteStream *pArchiveStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // Properties const uint32 GetVersion() const { return m_version; } const uint32 GetRegionSize() const { return m_regionSize; } const uint32 GetRegionLODLevels() const { return m_regionLODLevels; } const PropertyTable *GetProperties() const { return &m_properties; } PropertyTable *GetProperties() { return &m_properties; } // Terrain Data bool HasTerrain() const { return (m_pTerrainData != NULL); } const MapSourceTerrainData *GetTerrainData() const { return m_pTerrainData; } MapSourceTerrainData *GetTerrainData() { return m_pTerrainData; } MapSourceTerrainData *CreateTerrainData(const TerrainLayerListGenerator *pLayerList, TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat, uint32 scale, uint32 sectionSize, uint32 renderLODCount, int32 minHeight, int32 maxHeight, int32 baseHeight, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void DeleteTerrainData(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // Geometry Data //const MapSourceGeometryData *GetEntityData() const { return &m_GeometryData; } //MapSourceGeometryData *GetEntityData() { return &m_GeometryData; } // Entity id allocation String GenerateEntityName(const char *typeName); // Entity adding/removal. Removing an entity from here by pointer leaves the cleanup to the caller. MapSourceEntityData *CreateEntity(const char *typeName, const char *entityName = nullptr); MapSourceEntityData *CreateEntityFromTemplate(const ObjectTemplate *pTemplate, const char *entityName = nullptr); MapSourceEntityData *CopyEntity(const MapSourceEntityData *pEntity, const char *entityName = nullptr); bool AddEntity(MapSourceEntityData *pEntityData); void RemoveEntity(MapSourceEntityData *pEntityData); bool RemoveEntity(const char *entityName); // Entity readback. uint32 GetEntityCount() const { return m_entities.GetMemberCount(); } const MapSourceEntityData *GetEntityData(const char *entityName) const; MapSourceEntityData *GetEntityData(const char *entityName); // iteration functions template<typename T> void EnumerateEntities(T callback) { for (EntityTable::Iterator itr = m_entities.Begin(); !itr.AtEnd(); itr.Forward()) callback(itr->Value); } template<typename T> void EnumerateEntities(T callback) const { for (EntityTable::ConstIterator itr = m_entities.Begin(); !itr.AtEnd(); itr.Forward()) callback(itr->Value); } private: void SetDefaults(); bool IsEntitiesChanged() const; // entities loading/saving bool LoadEntities(ProgressCallbacks *pProgressCallbacks); bool SaveEntities(ProgressCallbacks *pProgressCallbacks) const; // terrain loading/saving bool LoadTerrain(ProgressCallbacks *pProgressCallbacks); bool SaveTerrain(ProgressCallbacks *pProgressCallbacks) const; String m_filename; ZipArchive *m_pMapArchive; bool m_isChanged; // properties uint32 m_version; uint32 m_regionSize; uint32 m_regionLODLevels; const ObjectTemplate *m_pObjectTemplate; PropertyTable m_properties; // entities uint32 m_nextEntitySuffix; typedef CIStringHashTable<MapSourceEntityData *> EntityTable; EntityTable m_entities; mutable bool m_entityListChanged; // terrain MapSourceTerrainData *m_pTerrainData; // geometry //MapSourceGeometryData m_GeometryData; }; class MapSourceEntityComponent { friend MapSource; friend MapSourceEntityData; MapSourceEntityComponent(); public: ~MapSourceEntityComponent(); const String &GetComponentName() const { return m_componentName; } const String &GetTypeName() const { return m_typeName; } const bool IsChanged() const { return m_changed; } void Create(const String &componentName, const String &typeName); void CreateFromTemplate(const String &componentName, const ObjectTemplate *pTemplate); bool LoadFromXML(XMLReader &xmlReader); void SaveToXML(XMLWriter &xmlWriter) const; const PropertyTable *GetPropertyTable() const { return &m_properties; } const String *GetPropertyValuePointer(const char *propertyName) const; String GetPropertyValueString(const char *propertyName) const; void SetPropertyValue(const char *propertyName, const char *propertyValue); void SetPropertyValue(const char *propertyName, const String &propertyValue); void SetChangedFlag() { m_changed = true; } void ClearChangedFlag() { m_changed = false; } private: String m_componentName; String m_typeName; mutable bool m_changed; PropertyTable m_properties; }; class MapSourceEntityData { friend MapSource; MapSourceEntityData(); public: ~MapSourceEntityData(); const String &GetEntityName() const { return m_entityName; } const String &GetTypeName() const { return m_typeName; } const bool IsChanged() const; void SetChangedFlag(); void ClearChangedFlag(); const PropertyTable *GetPropertyTable() const { return &m_properties; } const String *GetPropertyValuePointer(const char *propertyName) const; String GetPropertyValueString(const char *propertyName) const; void SetPropertyValue(const char *propertyName, const char *propertyValue); void SetPropertyValue(const char *propertyName, const String &propertyValue); const String &GetScript() const { return m_script; } void SetScript(const char *script) { m_script = script; m_changed = true; } void SetScript(const String &script) { m_script = script; m_changed = true; } const MapSourceEntityComponent *GetComponentByIndex(uint32 index) const { return m_components[index]; } const MapSourceEntityComponent *GetComponentByName(const char *name) const; const uint32 GetComponentCount() const { return m_components.GetSize(); } MapSourceEntityComponent *GetComponentByIndex(uint32 index) { return m_components[index]; } MapSourceEntityComponent *GetComponentByName(const char *name); MapSourceEntityComponent *CreateComponent(const char *typeName, const char *componentName = nullptr); MapSourceEntityComponent *CreateComponent(const ObjectTemplate *pTemplate, const char *componentName = nullptr); void AddComponent(MapSourceEntityComponent *pComponent); void RemoveComponent(MapSourceEntityComponent *pComponent); void Create(const String &entityName, const String &typeName); void CreateFromTemplate(const String &entityName, const ObjectTemplate *pTemplate); bool LoadFromXML(XMLReader &xmlReader); void SaveToXML(XMLWriter &xmlWriter) const; // typed property readers bool GetPropertyValueBool(const char *propertyName, bool *pValue) const; bool GetPropertyValueInt8(const char *propertyName, int8 *pValue) const; bool GetPropertyValueInt16(const char *propertyName, int16 *pValue) const; bool GetPropertyValueInt32(const char *propertyName, int32 *pValue) const; bool GetPropertyValueInt64(const char *propertyName, int64 *pValue) const; bool GetPropertyValueUInt8(const char *propertyName, uint8 *pValue) const; bool GetPropertyValueUInt16(const char *propertyName, uint16 *pValue) const; bool GetPropertyValueUInt32(const char *propertyName, uint32 *pValue) const; bool GetPropertyValueUInt64(const char *propertyName, uint64 *pValue) const; bool GetPropertyValueFloat(const char *propertyName, float *pValue) const; bool GetPropertyValueDouble(const char *propertyName, double *pValue) const; bool GetPropertyValueColor(const char *propertyName, uint32 *pValue) const; bool GetPropertyValueInt2(const char *propertyName, int2 *pValue) const; bool GetPropertyValueInt3(const char *propertyName, int3 *pValue) const; bool GetPropertyValueInt4(const char *propertyName, int4 *pValue) const; bool GetPropertyValueUInt2(const char *propertyName, uint2 *pValue) const; bool GetPropertyValueUInt3(const char *propertyName, uint3 *pValue) const; bool GetPropertyValueUInt4(const char *propertyName, uint4 *pValue) const; bool GetPropertyValueFloat2(const char *propertyName, float2 *pValue) const; bool GetPropertyValueFloat3(const char *propertyName, float3 *pValue) const; bool GetPropertyValueFloat4(const char *propertyName, float4 *pValue) const; bool GetPropertyValueQuaternion(const char *propertyName, Quaternion *pValue) const; // typed property readers with fallback values bool GetPropertyValueDefaultBool(const char *propertyName, bool defaultValue = false) const; int8 GetPropertyValueDefaultInt8(const char *propertyName, int8 defaultValue = 0) const; int16 GetPropertyValueDefaultInt16(const char *propertyName, int16 defaultValue = 0) const; int32 GetPropertyValueDefaultInt32(const char *propertyName, int32 defaultValue = 0) const; int64 GetPropertyValueDefaultInt64(const char *propertyName, int64 defaultValue = 0) const; uint8 GetPropertyValueDefaultUInt8(const char *propertyName, uint8 defaultValue = 0) const; uint16 GetPropertyValueDefaultUInt16(const char *propertyName, uint16 defaultValue = 0) const; uint32 GetPropertyValueDefaultUInt32(const char *propertyName, uint32 defaultValue = 0) const; uint64 GetPropertyValueDefaultUInt64(const char *propertyName, uint64 defaultValue = 0) const; float GetPropertyValueDefaultFloat(const char *propertyName, float defaultValue = 0) const; double GetPropertyValueDefaultDouble(const char *propertyName, double defaultValue = 0) const; uint32 GetPropertyValueDefaultColor(const char *propertyName, uint32 defaultValue = 0) const; int2 GetPropertyValueDefaultInt2(const char *propertyName, const int2 &defaultValue = int2::Zero) const; int3 GetPropertyValueDefaultInt3(const char *propertyName, const int3 &defaultValue = int3::Zero) const; int4 GetPropertyValueDefaultInt4(const char *propertyName, const int4 &defaultValue = int4::Zero) const; uint2 GetPropertyValueDefaultUInt2(const char *propertyName, const uint2 &defaultValue = uint2::Zero) const; uint3 GetPropertyValueDefaultUInt3(const char *propertyName, const uint3 &defaultValue = uint3::Zero) const; uint4 GetPropertyValueDefaultUInt4(const char *propertyName, const uint4 &defaultValue = uint4::Zero) const; float2 GetPropertyValueDefaultFloat2(const char *propertyName, const float2 &defaultValue = float2::Zero) const; float3 GetPropertyValueDefaultFloat3(const char *propertyName, const float3 &defaultValue = float3::Zero) const; float4 GetPropertyValueDefaultFloat4(const char *propertyName, const float4 &defaultValue = float4::Zero) const; Quaternion GetPropertyValueDefaultQuaternion(const char *propertyName, const Quaternion &defaultValue = Quaternion::Identity) const; // typed property writers void SetPropertyValueBool(const char *propertyName, bool propertyValue); void SetPropertyValueInt8(const char *propertyName, int8 propertyValue); void SetPropertyValueInt16(const char *propertyName, int16 propertyValue); void SetPropertyValueInt32(const char *propertyName, int32 propertyValue); void SetPropertyValueInt64(const char *propertyName, int64 propertyValue); void SetPropertyValueUInt8(const char *propertyName, uint8 propertyValue); void SetPropertyValueUInt16(const char *propertyName, uint16 propertyValue); void SetPropertyValueUInt32(const char *propertyName, uint32 propertyValue); void SetPropertyValueUInt64(const char *propertyName, uint64 propertyValue); void SetPropertyValueFloat(const char *propertyName, float propertyValue); void SetPropertyValueDouble(const char *propertyName, double propertyValue); void SetPropertyValueColor(const char *propertyName, uint32 propertyValue); void SetPropertyValueInt2(const char *propertyName, const int2 &propertyValue); void SetPropertyValueInt3(const char *propertyName, const int3 &propertyValue); void SetPropertyValueInt4(const char *propertyName, const int4 &propertyValue); void SetPropertyValueUInt2(const char *propertyName, const uint2 &propertyValue); void SetPropertyValueUInt3(const char *propertyName, const uint3 &propertyValue); void SetPropertyValueUInt4(const char *propertyName, const uint4 &propertyValue); void SetPropertyValueFloat2(const char *propertyName, const float2 &propertyValue); void SetPropertyValueFloat3(const char *propertyName, const float3 &propertyValue); void SetPropertyValueFloat4(const char *propertyName, const float4 &propertyValue); void SetPropertyValueQuaternion(const char *propertyName, const Quaternion &propertyValue); private: String m_entityName; String m_typeName; PropertyTable m_properties; String m_script; mutable bool m_changed; typedef PODArray<MapSourceEntityComponent *> ComponentArray; ComponentArray m_components; }; <file_sep>/Engine/Source/Renderer/ShaderComponentTypeInfo.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderComponentTypeInfo.h" ShaderComponentTypeInfo::ShaderComponentTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, IsValidPermutationFunction fpIsValidPermutation, FillShaderCompilerParametersFunction fpFillShaderCompilerParameters, const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBindings) : ObjectTypeInfo(TypeName, pParentTypeInfo, nullptr, nullptr), m_pParameterBindings(pParameterBindings), m_nParameterBindings(0), m_parameterCRC(0), m_fpIsValidPermutation(fpIsValidPermutation), m_fpFillShaderCompilerParameters(fpFillShaderCompilerParameters) { for (; m_pParameterBindings[m_nParameterBindings].ParameterName != nullptr; m_nParameterBindings++); } ShaderComponentTypeInfo::~ShaderComponentTypeInfo() { } bool ShaderComponentTypeInfo::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) const { return m_fpIsValidPermutation(globalShaderFlags, pBaseShaderTypeInfo, baseShaderFlags, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags); } bool ShaderComponentTypeInfo::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) const { return m_fpFillShaderCompilerParameters(globalShaderFlags, baseShaderFlags, vertexFactoryFlags, pParameters); } void ShaderComponentTypeInfo::SetParameterCRC(uint32 parameterCRC) { m_parameterCRC = parameterCRC; } <file_sep>/Editor/Source/Editor/MapEditor/moc_EditorMapViewport.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorMapViewport.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorMapViewport.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorMapViewport.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorMapViewport_t { QByteArrayData data[32]; char stringdata[743]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorMapViewport_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorMapViewport_t qt_meta_stringdata_EditorMapViewport = { { QT_MOC_LITERAL(0, 0, 17), // "EditorMapViewport" QT_MOC_LITERAL(1, 18, 27), // "OnToolbarMoreOptionsClicked" QT_MOC_LITERAL(2, 46, 0), // "" QT_MOC_LITERAL(3, 47, 24), // "OnToolbarRealtimeClicked" QT_MOC_LITERAL(4, 72, 7), // "checked" QT_MOC_LITERAL(5, 80, 24), // "OnToolbarGameViewClicked" QT_MOC_LITERAL(6, 105, 27), // "OnToolbarCameraFrontClicked" QT_MOC_LITERAL(7, 133, 26), // "OnToolbarCameraSideClicked" QT_MOC_LITERAL(8, 160, 25), // "OnToolbarCameraTopClicked" QT_MOC_LITERAL(9, 186, 31), // "OnToolbarCameraIsometricClicked" QT_MOC_LITERAL(10, 218, 33), // "OnToolbarCameraPerspectiveCli..." QT_MOC_LITERAL(11, 252, 29), // "OnToolbarViewWireframeClicked" QT_MOC_LITERAL(12, 282, 25), // "OnToolbarViewUnlitClicked" QT_MOC_LITERAL(13, 308, 23), // "OnToolbarViewLitClicked" QT_MOC_LITERAL(14, 332, 32), // "OnToolbarViewLightingOnlyClicked" QT_MOC_LITERAL(15, 365, 27), // "OnToolbarFlagShadowsClicked" QT_MOC_LITERAL(16, 393, 36), // "OnToolbarFlagWireframeOverlay..." QT_MOC_LITERAL(17, 430, 24), // "OnSwapChainWidgetResized" QT_MOC_LITERAL(18, 455, 22), // "OnSwapChainWidgetPaint" QT_MOC_LITERAL(19, 478, 30), // "OnSwapChainWidgetKeyboardEvent" QT_MOC_LITERAL(20, 509, 16), // "const QKeyEvent*" QT_MOC_LITERAL(21, 526, 14), // "pKeyboardEvent" QT_MOC_LITERAL(22, 541, 27), // "OnSwapChainWidgetMouseEvent" QT_MOC_LITERAL(23, 569, 18), // "const QMouseEvent*" QT_MOC_LITERAL(24, 588, 11), // "pMouseEvent" QT_MOC_LITERAL(25, 600, 27), // "OnSwapChainWidgetWheelEvent" QT_MOC_LITERAL(26, 628, 18), // "const QWheelEvent*" QT_MOC_LITERAL(27, 647, 11), // "pWheelEvent" QT_MOC_LITERAL(28, 659, 26), // "OnSwapChainWidgetDropEvent" QT_MOC_LITERAL(29, 686, 11), // "QDropEvent*" QT_MOC_LITERAL(30, 698, 10), // "pDropEvent" QT_MOC_LITERAL(31, 709, 33) // "OnSwapChainWidgetGainedFocusE..." }, "EditorMapViewport\0OnToolbarMoreOptionsClicked\0" "\0OnToolbarRealtimeClicked\0checked\0" "OnToolbarGameViewClicked\0" "OnToolbarCameraFrontClicked\0" "OnToolbarCameraSideClicked\0" "OnToolbarCameraTopClicked\0" "OnToolbarCameraIsometricClicked\0" "OnToolbarCameraPerspectiveClicked\0" "OnToolbarViewWireframeClicked\0" "OnToolbarViewUnlitClicked\0" "OnToolbarViewLitClicked\0" "OnToolbarViewLightingOnlyClicked\0" "OnToolbarFlagShadowsClicked\0" "OnToolbarFlagWireframeOverlayClicked\0" "OnSwapChainWidgetResized\0" "OnSwapChainWidgetPaint\0" "OnSwapChainWidgetKeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "OnSwapChainWidgetMouseEvent\0" "const QMouseEvent*\0pMouseEvent\0" "OnSwapChainWidgetWheelEvent\0" "const QWheelEvent*\0pWheelEvent\0" "OnSwapChainWidgetDropEvent\0QDropEvent*\0" "pDropEvent\0OnSwapChainWidgetGainedFocusEvent" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorMapViewport[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 21, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 119, 2, 0x08 /* Private */, 3, 1, 120, 2, 0x08 /* Private */, 5, 1, 123, 2, 0x08 /* Private */, 6, 1, 126, 2, 0x08 /* Private */, 7, 1, 129, 2, 0x08 /* Private */, 8, 1, 132, 2, 0x08 /* Private */, 9, 1, 135, 2, 0x08 /* Private */, 10, 1, 138, 2, 0x08 /* Private */, 11, 1, 141, 2, 0x08 /* Private */, 12, 1, 144, 2, 0x08 /* Private */, 13, 1, 147, 2, 0x08 /* Private */, 14, 1, 150, 2, 0x08 /* Private */, 15, 1, 153, 2, 0x08 /* Private */, 16, 1, 156, 2, 0x08 /* Private */, 17, 0, 159, 2, 0x08 /* Private */, 18, 0, 160, 2, 0x08 /* Private */, 19, 1, 161, 2, 0x08 /* Private */, 22, 1, 164, 2, 0x08 /* Private */, 25, 1, 167, 2, 0x08 /* Private */, 28, 1, 170, 2, 0x08 /* Private */, 31, 0, 173, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 20, 21, QMetaType::Void, 0x80000000 | 23, 24, QMetaType::Void, 0x80000000 | 26, 27, QMetaType::Void, 0x80000000 | 29, 30, QMetaType::Void, 0 // eod }; void EditorMapViewport::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorMapViewport *_t = static_cast<EditorMapViewport *>(_o); switch (_id) { case 0: _t->OnToolbarMoreOptionsClicked(); break; case 1: _t->OnToolbarRealtimeClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: _t->OnToolbarGameViewClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 3: _t->OnToolbarCameraFrontClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 4: _t->OnToolbarCameraSideClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnToolbarCameraTopClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnToolbarCameraIsometricClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnToolbarCameraPerspectiveClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnToolbarViewWireframeClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->OnToolbarViewUnlitClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnToolbarViewLitClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 11: _t->OnToolbarViewLightingOnlyClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->OnToolbarFlagShadowsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 13: _t->OnToolbarFlagWireframeOverlayClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 14: _t->OnSwapChainWidgetResized(); break; case 15: _t->OnSwapChainWidgetPaint(); break; case 16: _t->OnSwapChainWidgetKeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 17: _t->OnSwapChainWidgetMouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 18: _t->OnSwapChainWidgetWheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 19: _t->OnSwapChainWidgetDropEvent((*reinterpret_cast< QDropEvent*(*)>(_a[1]))); break; case 20: _t->OnSwapChainWidgetGainedFocusEvent(); break; default: ; } } } const QMetaObject EditorMapViewport::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_EditorMapViewport.data, qt_meta_data_EditorMapViewport, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorMapViewport::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorMapViewport::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorMapViewport.stringdata)) return static_cast<void*>(const_cast< EditorMapViewport*>(this)); return QWidget::qt_metacast(_clname); } int EditorMapViewport::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 21) qt_static_metacall(this, _c, _id, _a); _id -= 21; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 21) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 21; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphCompiler.h #pragma once #include "ResourceCompiler/ShaderGraph.h" #include "Renderer/RendererTypes.h" class ShaderGraphNode_MaterialInput; class ShaderGraphNode_UniformParameter; class ShaderGraphNode_TextureParameter; class ShaderGraphCompiler { public: struct ExternalParameter { String Name; SHADER_PARAMETER_TYPE Type; String BindingName; }; public: ShaderGraphCompiler(const ShaderGraph *pShaderGraph); virtual ~ShaderGraphCompiler(); const ShaderGraph *GetShaderGraph() const { return m_pShaderGraph; } const ExternalParameter *GetExternalUniformParameter(const char *uniformName) const; const ExternalParameter *GetExternalTextureParameter(const char *textureName) const; const bool GetExternalStaticSwitchParameter(const char *staticSwitchName) const; void AddExternalUniformParameter(const char *uniformName, SHADER_PARAMETER_TYPE uniformType, const char *bindingName); void AddExternalTextureParameter(const char *textureName, TEXTURE_TYPE textureType, const char *bindingName); void AddExternalStaticSwitchParameter(const char *staticSwitchName, bool enabled); virtual bool Compile(ByteStream *pOutputStream) = 0; // emitters virtual bool EmitAdd(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) = 0; virtual bool EmitSubtract(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) = 0; virtual bool EmitMultiply(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) = 0; virtual bool EmitDivide(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) = 0; virtual bool EmitDot(const ShaderGraphNodeInput *pA, const ShaderGraphNodeInput *pB) = 0; virtual bool EmitNormalize(const ShaderGraphNodeInput *pNode) = 0; virtual bool EmitNegate(const ShaderGraphNodeInput *pNode) = 0; virtual bool EmitFractionalPart(const ShaderGraphNodeInput *pNode) = 0; virtual void EmitConstant(SHADER_PARAMETER_TYPE ValueType, const void *pValue) = 0; virtual void EmitConstantBool(bool Value) = 0; virtual void EmitConstantInt(int32 Value) = 0; virtual void EmitConstantInt2(const int2 &Value) = 0; virtual void EmitConstantInt3(const int3 &Value) = 0; virtual void EmitConstantInt4(const int4 &Value) = 0; virtual void EmitConstantFloat(const float &Value) = 0; virtual void EmitConstantFloat2(const float2 &Value) = 0; virtual void EmitConstantFloat3(const float3 &Value) = 0; virtual void EmitConstantFloat4(const float4 &Value) = 0; virtual bool EmitAccessShaderGlobal(const char *GlobalName) = 0; virtual bool EmitAccessShaderInput(const char *InputName) = 0; virtual bool EmitAccessExternalParameter(const ExternalParameter *pExternalParameter) = 0; virtual bool EmitTextureSample(const ShaderGraphNodeInput *pTextureNodeLink, const ShaderGraphNodeInput *pTexCoordNodeLink, SHADER_GRAPH_TEXTURE_SAMPLE_UNPACK_OPERATION unpackOperation) = 0; virtual bool EmitConstructPrimitive(SHADER_PARAMETER_TYPE primitiveType, const ShaderGraphNodeInput **ppInputNodes, uint32 nInputNodes) = 0; virtual void EmitSwizzle(SHADER_GRAPH_VALUE_SWIZZLE Swizzle) = 0; virtual bool EvaluateNode(const ShaderGraphNode *pSourceNode, uint32 OutputIndex, SHADER_GRAPH_VALUE_SWIZZLE Swizzle, SHADER_GRAPH_VALUE_SWIZZLE FixupSwizzle) = 0; virtual bool EvaluateNode(const ShaderGraphNodeInput *pNodeLink) = 0; protected: const ShaderGraph *m_pShaderGraph; typedef LinkedList<ExternalParameter> ExternalParameterList; ExternalParameterList m_ExternalUniforms; ExternalParameterList m_ExternalTextures; typedef LinkedList< Pair<String, bool> > StaticSwitchList; StaticSwitchList m_ExternalStaticSwitches; }; <file_sep>/Engine/Source/Renderer/WorldRenderers/ForwardShadingWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/ForwardShadingWorldRenderer.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" #include "Renderer/Renderer.h" #include "Renderer/RenderWorld.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderProgramSelector.h" #include "Renderer/Shaders/DepthOnlyShader.h" #include "Renderer/Shaders/ForwardShadingShaders.h" #include "Engine/Material.h" #include "Engine/EngineCVars.h" #include "Engine/ResourceManager.h" #include "Engine/Profiling.h" #include "MathLib/CollisionDetection.h" Log_SetChannel(ForwardShadingWorldRenderer); ForwardShadingWorldRenderer::ForwardShadingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : CompositingWorldRenderer(pGPUContext, pOptions), m_pSceneColorBuffer(nullptr), m_pSceneColorBufferCopy(nullptr), m_pSceneDepthBuffer(nullptr), m_pSceneDepthBufferCopy(nullptr), m_pDirectionalShadowMapRenderer(nullptr), m_pPointShadowMapRenderer(nullptr), m_pSpotShadowMapRenderer(nullptr), m_lastDirectionalLightIndex(0xFFFFFFFF), m_lastPointLightIndex(0xFFFFFFFF), m_lastSpotLightIndex(0xFFFFFFFF), m_lastVolumetricLightIndex(0xFFFFFFFF), m_directionalLightShaderFlags(DirectionalLightShader::CalculateFlags(pOptions->EnableShadows, pOptions->EnableHardwareShadowFiltering, pOptions->ShadowMapFiltering, pOptions->ShowShadowMapCascades)), m_pointLightShaderFlags(PointLightShader::CalculateFlags(pOptions->EnableShadows, pOptions->EnableHardwareShadowFiltering)), m_spotLightShaderFlags(0) { // render passes that we can draw static const uint32 availableRenderPassMask = RENDER_PASS_LIGHTMAP | RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING | RENDER_PASS_OCCLUSION_CULLING_PROXY | RENDER_PASS_TINT; // set up render queue m_renderQueue.SetAcceptingLights(true); m_renderQueue.SetAcceptingRenderPassMask(availableRenderPassMask); m_renderQueue.SetAcceptingOccluders((pOptions->EnableOcclusionCulling | pOptions->EnableOcclusionPredication) != 0); m_renderQueue.SetAcceptingDebugObjects(pOptions->ShowDebugInfo); } ForwardShadingWorldRenderer::~ForwardShadingWorldRenderer() { // release postprocess buffers DebugAssert(m_pSceneColorBufferCopy == nullptr && m_pSceneDepthBufferCopy == nullptr); ReleaseIntermediateBuffer(m_pSceneDepthBuffer); ReleaseIntermediateBuffer(m_pSceneColorBuffer); // delete cached shadow maps for (uint32 i = 0; i < m_directionalShadowMaps.GetSize(); i++) m_pDirectionalShadowMapRenderer->FreeShadowMap(&m_directionalShadowMaps[i]); m_directionalShadowMaps.Clear(); for (uint32 i = 0; i < m_pointShadowMaps.GetSize(); i++) m_pPointShadowMapRenderer->FreeShadowMap(&m_pointShadowMaps[i]); m_pointShadowMaps.Clear(); for (uint32 i = 0; i < m_spotShadowMaps.GetSize(); i++) m_pSpotShadowMapRenderer->FreeShadowMap(&m_spotShadowMaps[i]); m_spotShadowMaps.Clear(); // delete shadow map renderers delete m_pDirectionalShadowMapRenderer; delete m_pPointShadowMapRenderer; delete m_pSpotShadowMapRenderer; } bool ForwardShadingWorldRenderer::Initialize() { if (!CompositingWorldRenderer::Initialize()) return false; // create buffers m_pSceneColorBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, SCENE_COLOR_PIXEL_FORMAT, 1); m_pSceneDepthBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, SCENE_DEPTH_PIXEL_FORMAT, 1); if (m_pSceneColorBuffer == nullptr || m_pSceneDepthBuffer == nullptr) return false; // create shadow map renderers if (m_options.EnableShadows) { m_pDirectionalShadowMapRenderer = new DirectionalShadowMapRenderer(m_options.DirectionalShadowMapResolution, m_options.ShadowMapPixelFormat, m_options.ShadowMapCascadeCount, 0.95f); m_pPointShadowMapRenderer = new PointShadowMapRenderer(m_options.PointShadowMapResolution, m_options.ShadowMapPixelFormat); m_pSpotShadowMapRenderer = new SpotShadowMapRenderer(m_options.SpotShadowMapResolution, m_options.ShadowMapPixelFormat); } // all done return true; } void ForwardShadingWorldRenderer::DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) { // add the main camera //RENDER_PROFILER_ADD_CAMERA(pRenderProfiler, &pViewParameters->ViewCamera, "World View Camera"); // culling FillRenderQueue(&pViewParameters->ViewCamera, pRenderWorld); // draw shadow maps DrawShadowMaps(pRenderWorld, pViewParameters); // // handle override cameras // if (pRenderProfiler != nullptr && pRenderProfiler->HasCameraOverride()) // { // // clone view parameters // ViewParameters *viewParametersCopy = (ViewParameters *)alloca(sizeof(ViewParameters)); // Y_memcpy(viewParametersCopy, pViewParameters, sizeof(ViewParameters)); // viewParametersCopy->ViewCamera = *pRenderProfiler->GetCameraOverrideCamera(); // pViewParameters = viewParametersCopy; // // // reissue renderable query with new camera // FillRenderQueue(&viewParametersCopy->ViewCamera, pRenderWorld); // } // clear render targets { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "Prepare", MICROPROFILE_COLOR(127, 72, 98)); // need a seperate viewport RENDERER_VIEWPORT bufferViewport(0, 0, m_options.RenderWidth, m_options.RenderHeight, 0.0f, 1.0f); m_pGPUContext->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, m_pSceneDepthBuffer->pDSV); m_pGPUContext->SetViewport(&bufferViewport); m_pGPUContext->ClearTargets(true, true, true, pViewParameters->FogColor); // set up view-dependent constants GPUContextConstants *pConstants = m_pGPUContext->GetConstants(); pConstants->SetFromCamera(pViewParameters->ViewCamera, false); pConstants->SetWorldTime(pViewParameters->WorldTime, false); pConstants->CommitChanges(); } // pull occlusion results back from gpu if (m_options.EnableOcclusionCulling) CollectOcclusionCullingResults(); else if (m_options.EnableOcclusionPredication) BindOcclusionQueriesToQueueEntries(); // depth prepass if (m_options.EnableDepthPrepass) DrawDepthPrepass(pViewParameters); // opaque objects DrawOpaqueObjects(pViewParameters); // if occlusion culling is enabled, draw proxies if ((m_options.EnableOcclusionCulling | m_options.EnableOcclusionPredication) != 0) DrawOcclusionCullingProxies(m_pGPUContext, &pViewParameters->ViewCamera); // transparent objects DrawTranslucentObjects(pViewParameters); // post process objects DrawPostProcessObjects(pViewParameters); // tonemap to present buffer ApplyFinalCompositePostProcess(pViewParameters, m_pSceneColorBuffer->pTexture, pRenderTargetView); // debug info - draw to backbuffer if (m_pGUIContext != nullptr) { if (m_options.ShowDebugInfo) DrawDebugInfo(&pViewParameters->ViewCamera); if (m_options.ShowIntermediateBuffers) DrawIntermediateBuffers(); } // frame complete m_pGPUContext->ClearState(true, true, true, true); OnFrameComplete(); } void ForwardShadingWorldRenderer::OnFrameComplete() { CompositingWorldRenderer::OnFrameComplete(); // release all shadow maps for (uint32 i = 0; i < m_directionalShadowMaps.GetSize(); i++) m_directionalShadowMaps[i].IsActive = false; for (uint32 i = 0; i < m_pointShadowMaps.GetSize(); i++) m_pointShadowMaps[i].IsActive = false; for (uint32 i = 0; i < m_spotShadowMaps.GetSize(); i++) m_spotShadowMaps[i].IsActive = false; // clear last indices m_lastDirectionalLightIndex = 0xFFFFFFFF; m_lastPointLightIndex = 0xFFFFFFFF; m_lastSpotLightIndex = 0xFFFFFFFF; m_lastVolumetricLightIndex = 0xFFFFFFFF; } void ForwardShadingWorldRenderer::DrawShadowMaps(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "DrawShadowMaps", MICROPROFILE_COLOR(127, 98, 42)); // directional lights { RenderQueue::DirectionalLightArray &directionalLights = m_renderQueue.GetDirectionalLightArray(); for (uint32 i = 0; i < directionalLights.GetSize(); i++) { RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight = &directionalLights[i]; if (pLight->ShadowFlags & LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) DrawDirectionalShadowMap(pRenderWorld, pViewParameters, pLight); } } // point lights { RenderQueue::PointLightArray &pointLights = m_renderQueue.GetPointLightArray(); for (uint32 i = 0; i < pointLights.GetSize(); i++) { RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight = &pointLights[i]; if (pLight->ShadowFlags & LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) DrawPointShadowMap(pRenderWorld, pViewParameters, pLight); } } // clear shaders/targets since the targets will be bound to inputs m_pGPUContext->ClearState(true, false, false, true); } bool ForwardShadingWorldRenderer::DrawDirectionalShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { if (m_pDirectionalShadowMapRenderer == nullptr) return false; // find a free directional shadow map uint32 shadowMapIndex = 0; for (; shadowMapIndex < m_directionalShadowMaps.GetSize(); shadowMapIndex++) { if (!m_directionalShadowMaps[shadowMapIndex].IsActive) break; } // none found? if (shadowMapIndex == m_directionalShadowMaps.GetSize()) { // allocate it DirectionalShadowMapRenderer::ShadowMapData shadowMapData; if (!m_pDirectionalShadowMapRenderer->AllocateShadowMap(&shadowMapData)) return false; m_directionalShadowMaps.Add(shadowMapData); } // get shadow map data pointer DirectionalShadowMapRenderer::ShadowMapData *pShadowMapData = &m_directionalShadowMaps[shadowMapIndex]; pShadowMapData->IsActive = true; // bind the shadow map to the light pLight->ShadowMapIndex = shadowMapIndex; // invoke draw m_pDirectionalShadowMapRenderer->DrawShadowMap(m_pGPUContext, pShadowMapData, &pViewParameters->ViewCamera, pViewParameters->MaximumShadowViewDistance, pRenderWorld, pLight); // add debug view AddDebugBufferView(pShadowMapData->pShadowMapTexture, "DirectionalShadowMap"); // ok return true; } bool ForwardShadingWorldRenderer::DrawPointShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { if (m_pPointShadowMapRenderer == nullptr) return false; // find a free directional shadow map uint32 shadowMapIndex = 0; for (; shadowMapIndex < m_pointShadowMaps.GetSize(); shadowMapIndex++) { if (!m_pointShadowMaps[shadowMapIndex].IsActive) break; } // none found? if (shadowMapIndex == m_pointShadowMaps.GetSize()) { // allocate it PointShadowMapRenderer::ShadowMapData shadowMapData; if (!m_pPointShadowMapRenderer->AllocateShadowMap(&shadowMapData)) return false; m_pointShadowMaps.Add(shadowMapData); } // get shadow map data pointer PointShadowMapRenderer::ShadowMapData *pShadowMapData = &m_pointShadowMaps[shadowMapIndex]; pShadowMapData->IsActive = true; // bind the shadow map to the light pLight->ShadowMapIndex = shadowMapIndex; // invoke draw m_pPointShadowMapRenderer->DrawShadowMap(m_pGPUContext, pShadowMapData, &pViewParameters->ViewCamera, pViewParameters->MaximumShadowViewDistance, pRenderWorld, pLight); // ok return true; } bool ForwardShadingWorldRenderer::DrawSpotShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight) { return false; } void ForwardShadingWorldRenderer::SetCommonShaderProgramParameters(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram) { pQueueEntry->pMaterial->BindDeviceResources(m_pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext, pShaderProgram); // post process material? const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); if (pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) { DebugAssert(m_pSceneColorBufferCopy != nullptr && m_pSceneDepthBufferCopy != nullptr); // set post process textures const uint32 BASE_INDEX = pMaterialShader->GetTextureParameterCount(); pShaderProgram->SetMaterialParameterTexture(m_pGPUContext, BASE_INDEX + 0, m_pSceneColorBufferCopy->pTexture, nullptr); pShaderProgram->SetMaterialParameterTexture(m_pGPUContext, BASE_INDEX + 1, m_pSceneDepthBufferCopy->pTexture, nullptr); } } uint32 ForwardShadingWorldRenderer::DrawBasePassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool depthWrites, GPU_COMPARISON_FUNC depthFunc) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); uint32 renderPassMask = pQueueEntry->RenderPassMask; // base pass flags uint32 basePassFlags = 0; // emissive if (renderPassMask & RENDER_PASS_EMISSIVE) basePassFlags |= BasePassShader::WITH_EMISSIVE; // lightmap else if (renderPassMask & RENDER_PASS_LIGHTMAP) basePassFlags |= BasePassShader::WITH_LIGHTMAP; // nothing for base pass else return 0; // should have flags DebugAssert(basePassFlags != 0); // draw base pass ShaderProgram *pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(BasePassShader), basePassFlags, pQueueEntry); if (pShaderProgram != nullptr) { // set states m_pGPUContext->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, depthWrites, depthFunc), 0); // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); // draw away pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } // done return 1; } void ForwardShadingWorldRenderer::DrawEmptyPassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // get shader ShaderProgram *pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(BasePassShader), 0, pQueueEntry); if (pShaderProgram != nullptr) { // set initial states m_pGPUContext->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); // draw it pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } } uint32 ForwardShadingWorldRenderer::DrawForwardLightPassesForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool useAdditiveBlending, bool depthWrites, GPU_COMPARISON_FUNC depthFunc) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); const bool staticLightMask = ((pQueueEntry->RenderPassMask & RENDER_PASS_STATIC_LIGHTING) != 0); const uint32 renderPassMask = pQueueEntry->RenderPassMask; ShaderProgram *pShaderProgram; uint32 drawnLights = 0; // draw lights macro #define DRAW_LIGHT() MULTI_STATEMENT_MACRO_BEGIN \ if (drawnLights == 0) \ { \ m_pGPUContext->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); \ m_pGPUContext->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, depthWrites, depthFunc), 0); \ if (useAdditiveBlending) \ SetAdditiveBlendingModeForMaterial(m_pGPUContext, pQueueEntry); \ else \ SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); \ } \ else if (drawnLights == 1) \ { \ if (!useAdditiveBlending) \ SetAdditiveBlendingModeForMaterial(m_pGPUContext, pQueueEntry); \ if (depthWrites) \ m_pGPUContext->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, false, GPU_COMPARISON_FUNC_EQUAL), 0); \ } \ SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); \ pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); \ drawnLights++; \ MULTI_STATEMENT_MACRO_END // draw directional lights RenderQueue::DirectionalLightArray &directionalLights = m_renderQueue.GetDirectionalLightArray(); for (uint32 lightIndex = 0; lightIndex < directionalLights.GetSize(); lightIndex++) { const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight = &directionalLights[lightIndex]; const bool usingShadowMap = (pLight->ShadowMapIndex >= 0 && (renderPassMask & RENDER_PASS_SHADOWED_LIGHTING)); // mask static lights on static objects away if ((pLight->Static & staticLightMask) != pLight->Static) continue; // get shader flags uint32 directionalLightShaderFlags = m_directionalLightShaderFlags; if (!usingShadowMap) directionalLightShaderFlags &= ~DirectionalLightShader::SHADOW_BITS_MASK; // get shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(DirectionalLightShader), directionalLightShaderFlags, pQueueEntry)) == nullptr) continue; // bind shader and set parameters m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); // using shadow map? note: we need the shadow map data to set the constant buffer up, even if this object does not use it const DirectionalShadowMapRenderer::ShadowMapData *pShadowMapData = (pLight->ShadowMapIndex >= 0) ? &m_directionalShadowMaps[pLight->ShadowMapIndex] : nullptr; // set constant buffer parameters if (m_lastDirectionalLightIndex != lightIndex) { DirectionalLightShader::SetLightParameters(m_pGPUContext, pLight, pShadowMapData); m_lastDirectionalLightIndex = lightIndex; } // and the shadow map textures if (pShadowMapData) DirectionalLightShader::SetProgramParameters(m_pGPUContext, pShaderProgram, pLight, pShadowMapData); // draw light DRAW_LIGHT(); } // draw point lights RenderQueue::PointLightArray &pointLights = m_renderQueue.GetPointLightArray(); const RENDER_QUEUE_POINT_LIGHT_ENTRY *queuedLights[PointLightListShader::MAX_LIGHTS]; uint32 queuedLightCount = 0; for (uint32 lightIndex = 0; lightIndex < pointLights.GetSize(); lightIndex++) { const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight = &pointLights[lightIndex]; const bool usingShadowMap = (pLight->ShadowMapIndex >= 0 && (renderPassMask & RENDER_PASS_SHADOWED_LIGHTING)); // mask static lights on static objects away if ((pLight->Static & staticLightMask) != pLight->Static) continue; // test if it intersects the renderable if (!CollisionDetection::AABoxIntersectsSphere(pQueueEntry->BoundingBox.GetMinBounds(), pQueueEntry->BoundingBox.GetMaxBounds(), pLight->Position, pLight->Range)) { continue; } // we only draw shadowed lights immediately, otherwise queue if (!usingShadowMap) { if (queuedLightCount == PointLightListShader::MAX_LIGHTS) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightListShader), 0, pQueueEntry)) != nullptr) { // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); // initialize light pointers for (uint32 queuedLightIndex = 0; queuedLightIndex < queuedLightCount; queuedLightIndex++) PointLightListShader::SetLightParameters(m_pGPUContext, queuedLightIndex, queuedLights[queuedLightIndex]); // commit parameters, and draw PointLightListShader::SetActiveLightCount(m_pGPUContext, queuedLightCount); PointLightListShader::CommitParameters(m_pGPUContext); DRAW_LIGHT(); } queuedLightCount = 0; } // add to queued light list queuedLights[queuedLightCount++] = pLight; continue; } // get shader flags uint32 pointLightShaderFlags = m_pointLightShaderFlags; if (!usingShadowMap) pointLightShaderFlags &= ~PointLightShader::SHADOW_BITS_MASK; // get shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightShader), pointLightShaderFlags, pQueueEntry)) == nullptr) continue; // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); // using shadow map? note: we need the shadow map data to set the constant buffer up, even if this object does not use it const PointShadowMapRenderer::ShadowMapData *pShadowMapData = (pLight->ShadowMapIndex >= 0) ? &m_pointShadowMaps[pLight->ShadowMapIndex] : nullptr; // set constant buffer parameters if (m_lastPointLightIndex != lightIndex) { PointLightShader::SetLightParameters(m_pGPUContext, pLight, pShadowMapData); m_lastPointLightIndex = lightIndex; } // set program parameters PointLightShader::SetProgramParameters(m_pGPUContext, pShaderProgram, pLight, pShadowMapData); // draw light DRAW_LIGHT(); } // if there's only one remaining light, we can use the fast shader, otherwise use the multi-light shader if (queuedLightCount == 1) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightShader), 0, pQueueEntry)) != nullptr) { m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); PointLightShader::SetLightParameters(m_pGPUContext, queuedLights[0], nullptr); DRAW_LIGHT(); } } else if (queuedLightCount > 0) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightListShader), 0, pQueueEntry)) != nullptr) { // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); // initialize light pointers for (uint32 queuedLightIndex = 0; queuedLightIndex < queuedLightCount; queuedLightIndex++) PointLightListShader::SetLightParameters(m_pGPUContext, queuedLightIndex, queuedLights[queuedLightIndex]); // commit parameters, and draw PointLightListShader::SetActiveLightCount(m_pGPUContext, queuedLightCount); PointLightListShader::CommitParameters(m_pGPUContext); DRAW_LIGHT(); } } // draw volumetric lights RenderQueue::VolumetricLightArray &volumetricLights = m_renderQueue.GetVolumetricLightArray(); for (uint32 lightIndex = 0; lightIndex < volumetricLights.GetSize(); lightIndex++) { const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight = &volumetricLights[lightIndex]; // test with bounding box, meh. if (!CollisionDetection::AABoxIntersectsSphere(pQueueEntry->BoundingBox.GetMinBounds(), pQueueEntry->BoundingBox.GetMaxBounds(), pLight->Position, pLight->Range)) { continue; } // get shader flags uint32 volumetricShaderFlags = VolumetricLightShader::GetTypeFlagsForPrimitive(pLight->Primitive); // find shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(VolumetricLightShader), volumetricShaderFlags, pQueueEntry)) == NULL) continue; // bind shader m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); // and parameters if (m_lastVolumetricLightIndex != lightIndex) { VolumetricLightShader::SetLightParameters(m_pGPUContext, pLight); m_lastVolumetricLightIndex = lightIndex; } // set program parameters VolumetricLightShader::SetProgramParameters(m_pGPUContext, pShaderProgram, pLight); // draw light DRAW_LIGHT(); } #undef DRAW_LIGHT return drawnLights; } void ForwardShadingWorldRenderer::DrawDepthPrepass(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "DrawDepthPrepass", MICROPROFILE_COLOR(255, 100, 255)); ShaderProgramSelector shaderSelector(m_globalShaderFlags); shaderSelector.SetBaseShader(OBJECT_TYPEINFO(DepthOnlyShader), 0); // Everything here uses the normal rasterizer state, so set that up here. m_pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoColorWrites()); // Iterate over renderables RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask == 0) continue; // get material const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // ignore materials that don't write depth values for the prepass if (!pMaterialShader->GetDepthWrites()) continue; // set states m_pGPUContext->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // For now, only masked materials are drawn with clipping shaderSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); shaderSelector.SetMaterial((pQueueEntry->pMaterial->GetShader()->GetBlendMode() == MATERIAL_BLENDING_MODE_MASKED) ? pQueueEntry->pMaterial : nullptr); // only continue with shader ShaderProgram *pShaderProgram = shaderSelector.MakeActive(m_pGPUContext); if (pShaderProgram != nullptr) { m_pGPUContext->SetPredication(pQueueEntry->pPredicate); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } } // clear predication m_pGPUContext->SetPredication(nullptr); } void ForwardShadingWorldRenderer::DrawOpaqueObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(90, 127, 42)); // Iterate over renderables. RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask == 0) continue; // determine whether to write depth values bool writeDepthValues = !(CVars::r_depth_prepass.GetBool() && pQueueEntry->pMaterial->GetShader()->GetDepthWrites()); // draw base pass uint32 drawCount = DrawBasePassForObject(pViewParameters, pQueueEntry, writeDepthValues, GPU_COMPARISON_FUNC_LESS); // draw lighting passes if (pQueueEntry->RenderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pViewParameters, pQueueEntry, (drawCount > 0), (drawCount > 0) ? false : writeDepthValues, (drawCount > 0) ? GPU_COMPARISON_FUNC_EQUAL : GPU_COMPARISON_FUNC_LESS); // if nothing has been drawn for this object [and no depth prepass], draw a blank pass (for depth) if (drawCount == 0 && !CVars::r_depth_prepass.GetBool()) DrawEmptyPassForObject(pViewParameters, pQueueEntry); } // wireframe overlay if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetOpaqueRenderables()); } void ForwardShadingWorldRenderer::DrawTranslucentObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "DrawTranslucentObjects", MICROPROFILE_COLOR(20, 50, 42)); // Iterate over renderables. RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { uint32 renderPassMask = pQueueEntry->RenderPassMask; uint32 drawCount = 0; // skip anything without any passes if (renderPassMask == 0) continue; // draw base pass? if (renderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount = DrawBasePassForObject(pViewParameters, pQueueEntry, false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw light passes? if (renderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pViewParameters, pQueueEntry, (drawCount != 0), false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw blank pass if there is no draw calls for this object if (drawCount == 0) DrawEmptyPassForObject(pViewParameters, pQueueEntry); } // wireframe overlay if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetTranslucentRenderables()); } void ForwardShadingWorldRenderer::DrawPostProcessObjects(const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("ForwardShadingWorldRenderer", "DrawPostProcessObjects", MICROPROFILE_COLOR(50, 20, 42)); // if we don't have any objects, exit early if (m_renderQueue.GetPostProcessRenderables().GetSize() == 0) return; // acquire copy of scene colour + depth m_pSceneColorBufferCopy = RequestIntermediateBufferMatching(m_pSceneColorBuffer); m_pSceneDepthBufferCopy = RequestIntermediateBufferMatching(m_pSceneDepthBuffer); m_pGPUContext->CopyTexture(m_pSceneColorBuffer->pTexture, m_pSceneColorBufferCopy->pTexture); m_pGPUContext->CopyTexture(m_pSceneDepthBuffer->pTexture, m_pSceneDepthBufferCopy->pTexture); // common rasterizer state m_pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState()); // draw the objects RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetPostProcessRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetPostProcessRenderables().GetBasePointer() + m_renderQueue.GetPostProcessRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); MATERIAL_BLENDING_MODE blendingMode = pMaterialShader->GetBlendMode(); uint32 renderPassMask = pQueueEntry->RenderPassMask; uint32 drawCount = 0; // skip anything without any passes if (renderPassMask == 0) continue; // draw appropriately switch (blendingMode) { case MATERIAL_BLENDING_MODE_STRAIGHT: case MATERIAL_BLENDING_MODE_PREMULTIPLIED: { // draw base pass? if (renderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount = DrawBasePassForObject(pViewParameters, pQueueEntry, false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw light passes? if (renderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pViewParameters, pQueueEntry, (drawCount != 0), false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw blank pass if there is no draw calls for this object if (drawCount == 0) DrawEmptyPassForObject(pViewParameters, pQueueEntry); } break; default: { // draw base pass drawCount = DrawBasePassForObject(pViewParameters, pQueueEntry, false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw lighting passes if (pQueueEntry->RenderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pViewParameters, pQueueEntry, (drawCount > 0), false, GPU_COMPARISON_FUNC_LESS_EQUAL); // if nothing has been drawn for this object [and no depth prepass], draw a blank pass (for depth) if (drawCount == 0) DrawEmptyPassForObject(pViewParameters, pQueueEntry); } break; } } // release intermediate buffers ReleaseIntermediateBuffer(m_pSceneDepthBufferCopy); ReleaseIntermediateBuffer(m_pSceneColorBufferCopy); m_pSceneDepthBufferCopy = nullptr; m_pSceneColorBufferCopy = nullptr; // wireframe overlay if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(m_pGPUContext, &pViewParameters->ViewCamera, &m_renderQueue.GetPostProcessRenderables()); } <file_sep>/Engine/Source/Engine/FPSCounter.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/FPSCounter.h" #include "Engine/ScriptManager.h" #include "Renderer/MiniGUIContext.h" #include "Renderer/Renderer.h" FPSCounter::FPSCounter() : m_pGPUContext(nullptr), m_accumulatedTime(0.0), m_framesRendered(0), m_fps(0), m_lastFrameTime(0), m_lastGameFrameTime(0), m_lastRenderFrameTime(0), m_lastFrameTimesIndex(0), m_lastDrawCallCount(0), m_lastMemoryUsage(0), m_lastScriptMemoryUsage(0) { Y_memzero(m_lastFrameTimes, sizeof(m_lastFrameTimes)); } FPSCounter::~FPSCounter() { ReleaseGPUResources(); } bool FPSCounter::CreateGPUResources() { return true; } void FPSCounter::ReleaseGPUResources() { } void FPSCounter::GetFrameTimeHistory(float *pFrameTimes, uint32 frameCount) const { uint32 currentIndex = (m_lastFrameTimesIndex == 0) ? KEEP_FRAME_TIME_COUNT - 1 : m_lastFrameTimesIndex - 1; for (uint32 i = 0; i < frameCount; i++) { pFrameTimes[i] = m_lastFrameTimes[currentIndex]; if (currentIndex == 0) currentIndex = KEEP_FRAME_TIME_COUNT - 1; else currentIndex--; } } void FPSCounter::BeginFrame() { m_lastFrameTime = (float)m_lastFrameStartTimer.GetTimeSeconds(); m_lastFrameStartTimer.Reset(); m_gameThreadTimer.Reset(); m_renderThreadTimer.Reset(); //m_pGPUContext->ResetDrawCallCounter(); // add to history m_lastFrameTimesIndex %= KEEP_FRAME_TIME_COUNT; m_lastFrameTimes[m_lastFrameTimesIndex++] = m_lastFrameTime; // update fps // todo: seperate timer for this, between invocations? m_accumulatedTime += m_lastFrameTime; m_framesRendered++; if (m_accumulatedTime > 0.1) { m_fps = (((float)m_framesRendered) / m_accumulatedTime); m_accumulatedTime = 0.0; m_framesRendered = 0; } // update last memory usage m_lastMemoryUsage = Platform::GetProgramMemoryUsage(); m_lastScriptMemoryUsage = g_pScriptManager->GetMemoryUsage(); } void FPSCounter::EndGameThreadFrame() { m_lastGameFrameTime = (float)m_gameThreadTimer.GetTimeSeconds(); } void FPSCounter::EndRenderThreadFrame() { m_lastRenderFrameTime = (float)m_renderThreadTimer.GetTimeSeconds(); m_lastDrawCallCount = g_pRenderer->GetCounters()->GetDrawCallCounter(); } void FPSCounter::DrawDetails(const Font *pFont, MiniGUIContext *pGUIContext, int32 startX /* = -100 */, int32 startY /* = 0 */, uint32 fontSize /* = 16 */) const { double minFrameTime = m_lastFrameTimes[0]; double maxFrameTime = m_lastFrameTimes[0]; double avgFrameTime = m_lastFrameTimes[0]; for (uint32 i = 1; i < KEEP_FRAME_TIME_COUNT; i++) { double frameTime = m_lastFrameTimes[i]; minFrameTime = Min(minFrameTime, frameTime); maxFrameTime = Max(maxFrameTime, frameTime); avgFrameTime += frameTime; } avgFrameTime /= (double)KEEP_FRAME_TIME_COUNT; SmallString message; message.Format("%.2f fps (%.2f ms) [%.2f-%.2f, avg %.2f]", m_fps, m_lastFrameTime * 1000.0, minFrameTime * 1000.0, maxFrameTime * 1000.0, avgFrameTime * 1000.0); // determine color uint32 color; if (avgFrameTime >= 16.0) color = MAKE_COLOR_R8G8B8A8_UNORM(255, 0, 0, 255); else if (avgFrameTime >= 8.0) color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); else color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); pGUIContext->DrawText(pFont, fontSize, startX, startY, message, color, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); // second line message.Format("game: %.2f ms render: %.2f ms draws: %u", m_lastGameFrameTime * 1000.0, m_lastRenderFrameTime * 1000.0, m_lastDrawCallCount); pGUIContext->DrawText(pFont, fontSize, startX, startY + fontSize, message, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); message.Format("script: %s mem: %s", StringConverter::SizeToHumanReadableString((uint64)m_lastScriptMemoryUsage).GetCharArray(), StringConverter::SizeToHumanReadableString((uint64)m_lastMemoryUsage).GetCharArray()); pGUIContext->DrawText(pFont, fontSize, startX, startY + fontSize * 2, message, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); } <file_sep>/Editor/Source/Editor/Editor.h #pragma once #include "Editor/Common.h" #include "Editor/EditorIconLibrary.h" class Image; class Font; class ObjectTemplate; class EditorVisualDefinition; class EditorMapWindow; class Editor : public QApplication { Q_OBJECT public: Editor(int &argc, char **argv); ~Editor(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // State Management /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // initialization/exit int Execute(); void Exit(); // frame execution blocking void BlockFrameExecution() { m_blockFrameExecution++; } void UnblockFrameExecution() { DebugAssert(m_blockFrameExecution > 0); m_blockFrameExecution--; } // trigger a frame execution event, to avoid waiting for the timer void QueueFrameExecution(); // repaint ui without running any frames void ProcessBackgroundEvents(); // framerate, assuming we don't sleep float GetEditorFPS() const { return m_editorFPS; } // change theme const EDITOR_THEME GetEditorTheme() const { return m_editorTheme; } void SetEditorTheme(EDITOR_THEME theme); // new map/open map EditorMapWindow *CreateMap(); EditorMapWindow *OpenMap(const char *mapFileName); // managed map windows const EditorMapWindow *GetMapWindow(uint32 index) const { return m_mapWindows[index]; } EditorMapWindow *GetMapWindow(uint32 index) { return m_mapWindows[index]; } uint32 GetMapWindowCount() const { return m_mapWindows.GetSize(); } void AddMapWindow(EditorMapWindow *pMapWindow); void RemoveMapWindow(EditorMapWindow *pMapWindow); void CloseAllMapWindows(); // other managed windows const QMainWindow *GetMainWindow(uint32 index) const { return m_mainWindows[index]; } QMainWindow *GetMainWindow(uint32 index) { return m_mainWindows[index]; } uint32 GetMainWindowCount() const { return m_mainWindows.GetSize(); } void AddMainWindow(QMainWindow *pMainWindow); void RemoveMainWindow(QMainWindow *pMainWindow); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Resource Management /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // icon library const EditorIconLibrary *GetIconLibrary() const { return &m_iconLibrary; } // viewport overlay font const Font *GetViewportOverlayFont() const { return m_pViewportOverlayFont; } // visual definitions const EditorVisualDefinition *GetVisualDefinitionByName(const char *typeName) const; const EditorVisualDefinition *GetVisualDefinitionForObjectTemplate(const ObjectTemplate *pTemplate) const; const uint32 GetVisualDefinitionCount() const { return m_visualDefinitions.GetMemberCount(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Signals /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Q_SIGNALS: // frame event void OnFrameExecution(float timeSinceLastFrame); private: void RegisterEditorTypes(); bool LoadObjectTemplates(); bool LoadVisualDefinitions(); bool Initialize(); bool Startup(); void Shutdown(); // app arguments const char **m_pCommandLineArguments; uint32 m_nCommandLineArguments; // state bool m_running; QTimer *m_pFrameExecuteTimer; uint32 m_blockFrameExecution; bool m_frameExecutionQueued; Timer m_lastFrameTime; uint32 m_editorFPSAccumulator; float m_editorFPSTimeAccumulator; float m_editorFPS; // theme EDITOR_THEME m_editorTheme; // resources EditorIconLibrary m_iconLibrary; typedef CIStringHashTable<EditorVisualDefinition *> VisualDefinitionHashTable; VisualDefinitionHashTable m_visualDefinitions; const Font *m_pViewportOverlayFont; PODArray<EditorMapWindow *> m_mapWindows; PODArray<QMainWindow *> m_mainWindows; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Slots /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private Q_SLOTS: void OnPendingCloseTriggered(); void OnFrameExecuteTimerTriggered(); }; extern Editor *g_pEditor; <file_sep>/Engine/Source/Renderer/MiniGUIContext.h #pragma once #include "Renderer/Common.h" #include "Renderer/Shaders/OverlayShader.h" enum MINIGUI_HORIZONTAL_ALIGNMENT { MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_HORIZONTAL_ALIGNMENT_CENTER, MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT, }; enum MINIGUI_VERTICAL_ALIGNMENT { MINIGUI_VERTICAL_ALIGNMENT_TOP, MINIGUI_VERTICAL_ALIGNMENT_CENTER, MINIGUI_VERTICAL_ALIGNMENT_BOTTOM, }; struct MINIGUI_RECT { int32 left, right; int32 top, bottom; MINIGUI_RECT() {} MINIGUI_RECT(int32 left_, int32 right_, int32 top_, int32 bottom_) : left(left_) , right(right_), top(top_), bottom(bottom_) { } void Set(int32 left_, int32 right_, int32 top_, int32 bottom_) { left = left_; right = right_; top = top_; bottom = bottom_; } int32 GetHeight() const { return (bottom - top); } int32 GetWidth() const { return (right - left); } }; #define SET_MINIGUI_RECT(rectPtr, leftVal, rightVal, topVal, bottomVal) { (rectPtr)->left = (leftVal); (rectPtr)->right = (rightVal); (rectPtr)->top = (topVal); (rectPtr)->bottom = (bottomVal); } struct MINIGUI_UV_RECT { float left, right; // u direction float top, bottom; // v direction MINIGUI_UV_RECT() {} MINIGUI_UV_RECT(float left_, float right_, float top_, float bottom_) : left(left_), right(right_), top(top_), bottom(bottom_) { } void Set(float left_, float right_, float top_, float bottom_) { left = left_; right = right_; top = top_; bottom = bottom_; } static const MINIGUI_UV_RECT FULL_RECT; }; class Camera; class Font; class Material; class Texture2D; class GPUTexture; class GPUDepthTexture; class MiniGUIContext { public: enum BATCH_TYPE { BATCH_TYPE_NONE, BATCH_TYPE_2D_COLORED_LINES, BATCH_TYPE_2D_COLORED_TRIANGLES, BATCH_TYPE_2D_TEXTURED_TRIANGLES, BATCH_TYPE_2D_TEXT, BATCH_TYPE_3D_COLORED_LINES, BATCH_TYPE_3D_COLORED_TRIANGLES, BATCH_TYPE_3D_TEXTURED_TRIANGLES, BATCH_TYPE_3D_TEXT, }; enum ALPHABLENDING_MODE { ALPHABLENDING_MODE_NONE, ALPHABLENDING_MODE_STRAIGHT, ALPHABLENDING_MODE_PREMULTIPLIED, ALPHABLENDING_MODE_COUNT, }; enum IMMEDIATE_PRIMITIVE { //IMMEDIATE_PRIMITIVE_POINTS, IMMEDIATE_PRIMITIVE_LINES, IMMEDIATE_PRIMITIVE_LINE_STRIP, IMMEDIATE_PRIMITIVE_LINE_LOOP, IMMEDIATE_PRIMITIVE_TRIANGLES, IMMEDIATE_PRIMITIVE_TRIANGLE_STRIP, IMMEDIATE_PRIMITIVE_TRIANGLE_FAN, IMMEDIATE_PRIMITIVE_QUADS, IMMEDIATE_PRIMITIVE_QUAD_STRIP, IMMEDIATE_PRIMITIVE_COUNT, }; public: MiniGUIContext(GPUContext *pGPUContext = nullptr, uint32 viewportWidth = 1, uint32 viewportHeight = 1); ~MiniGUIContext(); // context GPUContext *GetGPUContext() const { return m_pGPUContext; } void SetGPUContext(GPUContext *pGPUContext) { m_pGPUContext = pGPUContext; } // state const uint32 GetViewportWidth() const { return m_viewportWidth; } const uint32 GetViewportHeight() const { return m_viewportHeight; } const bool GetDepthTestingEnabled() const { return m_depthTestingEnabled; } const bool GetAlphaBlendingEnabled() const { return (m_alphaBlendingMode != ALPHABLENDING_MODE_NONE); } const ALPHABLENDING_MODE GetAlphaBlendingMode() const { return m_alphaBlendingMode; } const bool GetManualFlushEnabled() const { return (m_manualFlushCount > 0); } void SetViewportDimensions(uint32 width, uint32 height); void SetViewportDimensions(const RENDERER_VIEWPORT *pViewport); void SetDepthTestingEnabled(bool enabled); void SetAlphaBlendingEnabled(bool enabled); void SetAlphaBlendingMode(ALPHABLENDING_MODE mode); void PushManualFlush(); void PopManualFlush(); void ClearState(); // rect manipulation const MINIGUI_RECT GetTopRect() const { return m_topRect; } void PushRect(const MINIGUI_RECT *pRect); void PopRect(); // immediate mode drawing void BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive); void BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive, const Texture2D *pTexture); void BeginImmediate2D(IMMEDIATE_PRIMITIVE primitive, GPUTexture *pGPUTexture); void BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive); void BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive, const Texture2D *pTexture); void BeginImmediate3D(IMMEDIATE_PRIMITIVE primitive, GPUTexture *pGPUTexture); void ImmediateVertex(const float2 &position); void ImmediateVertex(const float2 &position, const float2 &texCoord); void ImmediateVertex(const float2 &position, const uint32 color); void ImmediateVertex(const float3 &position); void ImmediateVertex(const float3 &position, const float2 &texCoord); void ImmediateVertex(const float3 &position, const uint32 color); void ImmediateVertex(float x, float y); void ImmediateVertex(float x, float y, float u, float v); void ImmediateVertex(float x, float y, uint32 color); void ImmediateVertex(float x, float y, float z); void ImmediateVertex(float x, float y, float z, float u, float v); void ImmediateVertex(float x, float y, float z, uint32 color); void EndImmediate(); // 2D drawing void DrawLine(const int2 &LineVertex1, const int2 &LineVertex2, const uint32 Color); void DrawLine(const int2 &LineVertex1, const uint32 Color1, const int2 &LineVertex2, const uint32 Color2); void DrawRect(const MINIGUI_RECT *pRect, const uint32 Color); void DrawFilledRect(const MINIGUI_RECT *pRect, const uint32 Color); void DrawFilledRect(const MINIGUI_RECT *pRect, const uint32 Color1, const uint32 Color2, const uint32 Color3, const uint32 Color4); void DrawGradientRect(const MINIGUI_RECT *pRect, const uint32 Color1, const uint32 Color2, bool Horizontal = false); void DrawTexturedRect(const MINIGUI_RECT *pRect, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture); void DrawTexturedRect(const MINIGUI_RECT *pRect, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture); void DrawEmissiveRect(const MINIGUI_RECT *pRect, const Material *pMaterial); void DrawText(const Font *pFontData, int32 Size, const MINIGUI_RECT *pRect, const char *Text, const uint32 Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), bool AllowFormatting = false, MINIGUI_HORIZONTAL_ALIGNMENT hAlign = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT vAlign = MINIGUI_VERTICAL_ALIGNMENT_TOP); void DrawText(const Font *pFontData, int32 Size, const int2 &Position, const char *Text, const uint32 Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), bool AllowFormatting = false, MINIGUI_HORIZONTAL_ALIGNMENT hAlign = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT vAlign = MINIGUI_VERTICAL_ALIGNMENT_TOP); void DrawText(const Font *pFontData, int32 Size, int32 x, int32 y, const char *Text, const uint32 Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), bool AllowFormatting = false, MINIGUI_HORIZONTAL_ALIGNMENT hAlign = MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT vAlign = MINIGUI_VERTICAL_ALIGNMENT_TOP); // 3D drawing void Draw3DLine(const float3 &p0, const float3 &p1, const uint32 color); void Draw3DLine(const float3 &p0, const uint32 color1, const float3 &p1, const uint32 color2); void Draw3DLineWidth(const float3 &p0, const float3 &p1, const uint32 color, float lineWidth, bool widthScale = true); void Draw3DLineWidth(const float3 &p0, const uint32 color1, const float3 &p1, const uint32 color2, float lineWidth, bool widthScale = true); void Draw3DRect(const float3 &p0, const float3 &p1, const uint32 color); void Draw3DRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color); void Draw3DRectWidth(const float3 &p0, const float3 &p1, const uint32 color, float lineWidth, bool widthScale = true); void Draw3DRectWidth(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color, float lineWidth, bool widthScale = true); void Draw3DFilledRect(const float3 &p0, const float3 &p1, const uint32 color); void Draw3DFilledRect(const float3 &p0, const uint32 color0, const float3 &p1, const uint32 color1); void Draw3DFilledRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const uint32 color); void Draw3DFilledRect(const float3 &p0, const uint32 color0, const float3 &p1, const uint32 color1, const float3 &p2, const uint32 color2, const float3 &p3, const uint32 color3); void Draw3DGradientRect(const float3 &p0, const float3 &p1, const uint32 fromColor, const uint32 toColor, bool horizontal = false); void Draw3DTexturedRect(const float3 &p0, const float3 &p1, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture); void Draw3DTexturedRect(const float3 &p0, const float3 &p1, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture); void Draw3DTexturedRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const MINIGUI_UV_RECT *pUVRect, const Texture2D *pTexture); void Draw3DTexturedRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const MINIGUI_UV_RECT *pUVRect, GPUTexture *pDeviceTexture); void Draw3DEmissiveRect(const float3 &p0, const float3 &p1, const float3 &p2, const float3 &p3, const Material *pMaterial); void Draw3DGrid(const Plane &groundPlane, const float3 &origin, const float gridWidth, const float gridHeight, const float lineStep = 0.0f, const uint32 lineColor = 0); void Draw3DGrid(const float3 &minCoordinates, const float3 &maxCoordinates, const float3 &gridStep, const uint32 lineColor); void Draw3DWireBox(const float3 &minBounds, const float3 &maxBounds, const uint32 color); void Draw3DWireBox(const AABox &box, const uint32 color) { Draw3DWireBox(box.GetMinBounds(), box.GetMaxBounds(), color); } void Draw3DWireSphere(const float3 &sphereCenter, float radius, uint32 color, uint32 slices = 16, uint32 stacks = 16); void Draw3DBox(const float3 &minBounds, const float3 &maxBounds, const uint32 color); void Draw3DBox(const AABox &box, const uint32 color) { Draw3DBox(box.GetMinBounds(), box.GetMaxBounds(), color); } void Draw3DSphere(const float3 &sphereCenter, float radius, uint32 color, uint32 slices = 16, uint32 stacks = 16); void Draw3DArrow(const float3 &arrowStart, const float3 &arrowDirection, float lineLength, float lineThickness, float tipLength, float tipRadius, uint32 color, uint32 tipVertexCount = 24); // text drawing interface // caret position const int32 GetTextCaretPositionX() const { return m_textCaretPositionX; } const int32 GetTextCaretPositionY() const { return m_textCaretPositionY; } void SetTextCaretPosition(int32 x, int32 y) { m_textCaretPositionX = x; m_textCaretPositionY = y; } // word wrap const bool GetTextWordWrap() const { return m_textWordWrap; } void SetTextWordWrap(bool wordWrap) { m_textWordWrap = wordWrap; } // text alignment const MINIGUI_HORIZONTAL_ALIGNMENT GetTextHorizontalAlign() const { return m_textHorizontalAlign;} const MINIGUI_VERTICAL_ALIGNMENT GetTextVerticalAlign() const { return m_textVerticalAlign; } void SetTextHorizontalAlign(MINIGUI_HORIZONTAL_ALIGNMENT horizontalAlign) { m_textHorizontalAlign = horizontalAlign; } void SetTextVerticalAlign(MINIGUI_VERTICAL_ALIGNMENT verticalAlign) { m_textVerticalAlign = verticalAlign; } // draw text using current state void DrawText(const Font *pFont, int32 size, uint32 color, const char *text); void DrawFormattedText(const Font *pFont, int32 size, uint32 color, const char *format, ...); // draw text directly to point void DrawTextAt(int32 x, int32 y, const Font *pFont, int32 size, uint32 color, const char *text); void DrawFormattedTextAt(int32 x, int32 y, const Font *pFont, int32 size, uint32 color, const char *format, ...); // void Flush(); private: typedef MemArray<MINIGUI_RECT> RectStack; typedef MemArray<OverlayShader::Vertex2D> Vertex2DArray; typedef MemArray<OverlayShader::Vertex3D> Vertex3DArray; // target GPUContext *m_pGPUContext; uint32 m_viewportWidth, m_viewportHeight; // state bool m_depthTestingEnabled; ALPHABLENDING_MODE m_alphaBlendingMode; uint32 m_manualFlushCount; // rect stack RectStack m_rectStack; MINIGUI_RECT m_topRect; // immediate mode properties IMMEDIATE_PRIMITIVE m_immediatePrimitive; uint32 m_immediateStartVertex; // text int32 m_textCaretPositionX; int32 m_textCaretPositionY; MINIGUI_HORIZONTAL_ALIGNMENT m_textHorizontalAlign; MINIGUI_VERTICAL_ALIGNMENT m_textVerticalAlign; bool m_textWordWrap; // batch BATCH_TYPE m_batchType; GPUTexture *m_pBatchTexture; Vertex2DArray m_batchVertices2D; Vertex3DArray m_batchVertices3D; // shaders // rect functions bool ValidateRect(const MINIGUI_RECT *pRect); void TranslateRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect); void UntranslateRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect); void ClipRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect); void TranslateAndClipRect(MINIGUI_RECT *pDestinationRect, const MINIGUI_RECT *pSourceRect); void ClipUVRect(MINIGUI_UV_RECT *pDestinationUVRect, const MINIGUI_UV_RECT *pSourceUVRect, const MINIGUI_RECT *pClippedRect, const MINIGUI_RECT *pOriginalRect); // point functions int2 TranslateAndClipPoint(const int2 &Point); void InternalDrawText(const Font *pFontData, float scale, uint32 color, const MINIGUI_RECT *pRect, const char *text, uint32 nCharacters, bool skipFlushCheck); void SetBatchType(BATCH_TYPE type); void AddVertices(const OverlayShader::Vertex2D *pVertices, uint32 nVertices); void AddVertices(const OverlayShader::Vertex3D *pVertices, uint32 nVertices); void ImmediateVertex(const OverlayShader::Vertex2D &vertex); void ImmediateVertex(const OverlayShader::Vertex3D &vertex); }; <file_sep>/Editor/Source/Editor/EditorViewController.h #pragma once #include "Editor/Common.h" #include "Engine/Camera.h" #include "Renderer/WorldRenderer.h" class EditorViewController { public: EditorViewController(); ~EditorViewController(); // Camera mode const EDITOR_CAMERA_MODE GetCameraMode() const { return m_mode; } void SetCameraMode(EDITOR_CAMERA_MODE mode); void Reset(); // actual camera const WorldRenderer::ViewParameters *GetViewParameters() const { return &m_viewParameters; } const Camera &GetCamera() const { return m_viewParameters.ViewCamera; } // Common properties const float GetDrawDistance() const { return m_viewParameters.ViewCamera.GetObjectCullDistance(); } const float GetShadowDistance() const { return m_viewParameters.MaximumShadowViewDistance; } const float GetNearPlaneDistance() const { return m_viewParameters.ViewCamera.GetNearPlaneDistance(); } const float GetPerspectiveFieldOfView() const { return m_viewParameters.ViewCamera.GetPerspectiveFieldOfView(); } const float GetPerspectiveAcceleration() const { return m_perspectiveAcceleration; } const float GetPerspectiveMaxSpeed() const { return m_perspectiveMaxSpeed; } const float GetOrthographicScale() const { return m_orthographicScale; } const bool IsOrthoView() const { return (m_mode >= EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT && m_mode <= EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP); } const bool IsTurboEnabled() const { return m_turboEnabled; } const bool IsChanged() const { return m_changed; } // Camera properties const float3 &GetCameraPosition() const { return m_viewParameters.ViewCamera.GetPosition(); } const Quaternion &GetCameraRotation() const { return m_viewParameters.ViewCamera.GetRotation(); } const float3 GetCameraRightDirection() const { return (m_viewParameters.ViewCamera.GetRotation() * float3::UnitX).Normalize(); } const float3 GetCameraForwardDirection() const { return (m_viewParameters.ViewCamera.GetRotation() * float3::UnitY).Normalize(); } const float3 GetCameraUpDirection() const { return (m_viewParameters.ViewCamera.GetRotation() * float3::UnitZ).Normalize(); } // Common properties void SetDrawDistance(float v); void SetShadowDistance(float v); void SetNearPlaneDistance(float v); void SetPerspectiveFieldOfView(float fov); void SetPerspectiveAcceleration(float v); void SetPerspectiveMaxSpeed(float v); void SetOrthographicScale(float v); void SetTurboEnabled(bool enabled); // Camera properties void SetCameraPosition(const float3 &position); void SetCameraRotation(const Quaternion &rotation); // viewport const RENDERER_VIEWPORT *GetViewport() const { return &m_viewParameters.Viewport; } void SetViewportDimensions(uint32 width, uint32 height); // Move the camera in the specified direction. void Move(const float3 &direction, float distance); // Pitch/yaw/roll the camera. void ModPitch(float amount); void ModYaw(float amount); void ModRoll(float amount); // Using the current position, change the orientation of the camera to look at the specified coordinates. void LookAt(const float3 &lookAtPosition); // Rotate the camera around a specified axis and angle. void Rotate(const float3 &axis, float angle); // Rotate using the specified quaternion. void Rotate(const Quaternion &rotation); // Handle a keyboard event, returns true if the event was consumed bool HandleKeyboardEvent(const QKeyEvent *pKeyboardEvent); // Move from mouse position (mostly left-button held down in camera mode) void MoveFromMousePosition(const int2 &mousePositionDiff); // Move from mouse position (mostly right-button held down in any mode) void RotateFromMousePosition(const int2 &mousePositionDiff); // time update void Update(float dt); // get a pick ray Ray GetPickRay(int32 x, int32 y) const; // project a world coordinate to window coordinates float3 Project(const float3 &worldCoordindates) const; // unproject window coordinates to world coordinates float3 Unproject(const float3 &windowCoordinates) const; protected: // update camera rotation void UpdateCameraRotation(); // update camera settings from our settings void UpdateViewportDependancies(); // current mode EDITOR_CAMERA_MODE m_mode; // mode properties float m_perspectiveAcceleration; float m_perspectiveMaxSpeed; float m_orthographicScale; // state float m_yaw; float m_pitch; float m_roll; float3 m_currentPerspectiveMoveVector; bool m_leftKeyState; bool m_rightKeyState; bool m_forwardKeyState; bool m_backKeyState; bool m_upKeyState; bool m_downKeyState; bool m_turboEnabled; bool m_internalChanged; bool m_changed; // renderer stuff WorldRenderer::ViewParameters m_viewParameters; }; <file_sep>/DemoGame/Source/DemoGame/DemoGame.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/DemoGame.h" #include "Engine/InputManager.h" Log_SetChannel(BlockGame); DemoGame::DemoGame() : BaseGame(), m_pLaunchpadGameState(nullptr) { } DemoGame::~DemoGame() { } void DemoGame::OnRegisterTypes() { BaseGame::OnRegisterTypes(); } bool DemoGame::OnStart() { if (!BaseGame::OnStart()) return false; m_pLaunchpadGameState = new LaunchpadGameState(this); SetNextGameState(m_pLaunchpadGameState); return true; } void DemoGame::OnExit() { BaseGame::OnExit(); //delete m_pLaunchpadGameState; m_pLaunchpadGameState = nullptr; } <file_sep>/Editor/Source/Editor/EditorScriptEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorScriptEditor.h" EditorScriptEditor::EditorScriptEditor(QWidget *parent) { } EditorScriptEditor::~EditorScriptEditor() { } <file_sep>/Engine/Source/Renderer/RenderProxies/SpriteRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/SpriteRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/Material.h" #include "Engine/Texture.h" #include "Engine/Camera.h" #include "Engine/ResourceManager.h" #include "Engine/Engine.h" static const char *SPRITE_MATERIAL_TEXTURE_PARAMETER_NAME = "SpriteTexture"; SpriteRenderProxy::SpriteRenderProxy(uint32 entityId, const Texture2D *pTexture /* = nullptr */, const float3 &position /* = float3::Zero */) : RenderProxy(entityId), m_pMaterial(nullptr), m_visibility(true), m_pTexture(nullptr), m_position(position), m_width(0.0f), m_height(0.0f), m_shadowFlags(0), m_tintEnabled(false), m_tintColor(0xFFFFFFFF), m_bGPUResourcesCreated(false) //m_pVertexArray(NULL) { // set texture pointer m_pTexture = pTexture; if (m_pTexture != nullptr) m_pTexture->AddRef(); else m_pTexture = g_pResourceManager->GetDefaultTexture2D(); // get sprite dimensions m_width = (float)m_pTexture->GetWidth(); m_height = (float)m_pTexture->GetHeight(); // setup material const MaterialShader *pSpriteShader = g_pResourceManager->GetMaterialShader(g_pEngine->GetSpriteMaterialShaderName()); DebugAssert(pSpriteShader != NULL); m_pMaterial = new Material(); m_pMaterial->Create("", pSpriteShader); m_pMaterial->SetShaderTextureParameterByName(SPRITE_MATERIAL_TEXTURE_PARAMETER_NAME, pTexture); pSpriteShader->Release(); // update bounds UpdateBounds(); } SpriteRenderProxy::~SpriteRenderProxy() { ReleaseDeviceResources(); m_pTexture->Release(); } void SpriteRenderProxy::SetTexture(const Texture2D *pTexture) { } void SpriteRenderProxy::RealSetTexture(const Texture2D *pTexture) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pTexture != NULL); if (m_pTexture == pTexture) return; ReleaseDeviceResources(); // release mesh m_pTexture->Release(); // set new mesh m_pTexture = pTexture; m_pTexture->AddRef(); // update material m_pMaterial->SetShaderTextureParameterByName(SPRITE_MATERIAL_TEXTURE_PARAMETER_NAME, pTexture); // fix up bounds UpdateBounds(); } void SpriteRenderProxy::SetPosition(const float3 &position) { if (!IsInWorld()) { RealSetPosition(position); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, position]() { pThis->RealSetPosition(position); }); } } void SpriteRenderProxy::RealSetPosition(const float3 &position) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_position = position; UpdateBounds(); } void SpriteRenderProxy::SetSizeByTextureScale(float textureScale) { if (!IsInWorld()) { RealSetSizeByTextureScale(textureScale); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, textureScale]() { pThis->RealSetSizeByTextureScale(textureScale); }); } } void SpriteRenderProxy::RealSetSizeByTextureScale(float textureScale) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); float newWidth = (float)m_pTexture->GetWidth() * textureScale; float newHeight = (float)m_pTexture->GetHeight() * textureScale; m_width = newWidth; m_height = newHeight; UpdateBounds(); } void SpriteRenderProxy::SetSizeByDimensions(float width, float height) { if (!IsInWorld()) { RealSetSizeByDimensions(width, height); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, width, height]() { pThis->RealSetSizeByDimensions(width, height); }); } } void SpriteRenderProxy::RealSetSizeByDimensions(float width, float height) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_width = width; m_height = height; UpdateBounds(); } void SpriteRenderProxy::SetShadowFlags(uint32 shadowFlags) { if (!IsInWorld()) { RealSetShadowFlags(shadowFlags); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, shadowFlags]() { pThis->RealSetShadowFlags(shadowFlags); }); } } void SpriteRenderProxy::RealSetShadowFlags(uint32 shadowFlags) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_shadowFlags = shadowFlags; UpdateBounds(); } void SpriteRenderProxy::SetTintColor(bool enabled, uint32 color /* = 0 */) { if (!IsInWorld()) { RealSetTintColor(enabled, color); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, enabled, color]() { pThis->RealSetTintColor(enabled, color); }); } } void SpriteRenderProxy::RealSetTintColor(bool enabled, uint32 color /*= 0*/) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_tintEnabled = enabled; m_tintColor = (enabled) ? color : 0xFFFFFFFF; UpdateBounds(); } void SpriteRenderProxy::SetVisibility(bool visible) { if (!IsInWorld()) { RealSetVisibility(visible); } else { ReferenceCountedHolder<SpriteRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, visible]() { pThis->RealSetVisibility(visible); }); } } void SpriteRenderProxy::RealSetVisibility(bool visible) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_visibility = visible; } void SpriteRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_visibility) return; // Store the requested render passes. uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOW_MAP; if (m_tintEnabled) wantedRenderPasses |= RENDER_PASS_TINT; // skip for no passes if ((pRenderQueue->GetAcceptingRenderPassMask() & wantedRenderPasses) == 0) return; // Determine render passes. uint32 renderPassMask = m_pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { // Calculate view distance float viewDistance = pCamera->CalculateDepthToPoint(m_position); // Create queue entry RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.pVertexFactoryTypeInfo = OBJECT_TYPEINFO(PlainVertexFactory); queueEntry.VertexFactoryFlags = PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD; queueEntry.pMaterial = m_pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = m_tintColor; queueEntry.Layer = m_pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } void SpriteRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; uint32 i; PlainVertexFactory::Vertex vertices[4]; float hw = m_width * 0.5f; float hh = m_height * 0.5f; // these coordinates have to be in y-up coordinate system, as we are working with the view matrix vertices[0].SetUV(-hw, hh, 0.0f, 0.0f, 0.0f); vertices[1].SetUV(-hw, -hh, 0.0f, 0.0f, 1.0f); vertices[2].SetUV(hw, hh, 0.0f, 1.0f, 0.0f); vertices[3].SetUV(hw, -hh, 0.0f, 1.0f, 1.0f); // extracting the rotation component will make it an orthogonal matrix, so we can gain some perf by transposing instead of inverting float4x4 tempMatrix(pCamera->GetViewMatrix()); tempMatrix.SetColumn(3, float4::UnitW); tempMatrix.TransposeInPlace(); // translate matrix tempMatrix.SetColumn(3, float4(m_position, 1.0f)); // pretransform the vertices on the cpu, avoiding a gpu stall for (i = 0; i < 4; i++) vertices[i].Position = tempMatrix.TransformPoint(vertices[i].Position); pCommandList->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); //const float4x4 &viewMatrix = pGPUDevice->GetGPUConstants()->GetCameraViewMatrix(); //Vector3 cameraUp(viewMatrix.GetColumn(1)); //Vector3 camUp(pContext->GetCamera()->GetUpDirection()); /*Vector3 camUp(Vector3::UnitZ); Vector3 yAxis((Vector3(pContext->GetCamera()->GetEyePosition() - Vector3(m_Position))).Normalize()); Vector3 xAxis(camUp.Cross(yAxis)); Vector3 zAxis(yAxis.Cross(xAxis)); Matrix4 billboardMatrix; billboardMatrix.SetRow(0, Vector4(xAxis, m_Position.x)); billboardMatrix.SetRow(1, Vector4(yAxis, m_Position.y)); billboardMatrix.SetRow(2, Vector4(zAxis, m_Position.z)); billboardMatrix.SetRow(3, Vector4::UnitW); //pGPUDevice->GetGPUConstants()->SetLocalToWorldMatrix(billboardMatrix, true); for (i = 0; i < 4; i++) vertices[i].Position = billboardMatrix.TransformPoint(vertices[i].Position); pGPUDevice->GetGPUConstants()->SetLocalToWorldMatrix(Matrix4::Identity, true); */ pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_STRIP); pCommandList->DrawUserPointer(vertices, sizeof(vertices[0]), countof(vertices)); } bool SpriteRenderProxy::CreateDeviceResources() const { if (m_bGPUResourcesCreated) return true; // material will automatically create texture resources if (!m_pMaterial->CreateDeviceResources()) return false; m_bGPUResourcesCreated = true; return true; } void SpriteRenderProxy::ReleaseDeviceResources() const { //SAFE_RELEASE(m_pVertexArray); m_bGPUResourcesCreated = false; } void SpriteRenderProxy::UpdateBounds() { // depending on the camera angle, the z could stretch up to the width of the sprite. SIMDVector3f halfWorldSize(SIMDVector3f(m_width, m_height, m_width) * 0.5f); SIMDVector3f position(m_position); AABox newBounds(position - halfWorldSize, position + halfWorldSize); SetBounds(newBounds, Sphere::FromAABox(newBounds)); } <file_sep>/Editor/Source/Editor/StaticMeshEditor/EditorStaticMeshEditor.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/StaticMeshEditor/EditorStaticMeshEditor.h" #include "Editor/StaticMeshEditor/ui_EditorStaticMeshEditor.h" #include "Engine/ResourceManager.h" #include "Engine/Engine.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderProxies/CompositeRenderProxy.h" #include "Renderer/Renderer.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "Editor/EditorLightSimulator.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorProgressDialog.h" #include "Editor/EditorResourceSaveDialog.h" #include "Editor/Editor.h" Log_SetChannel(EditorStaticMeshEditor); EditorStaticMeshEditor::EditorStaticMeshEditor() : m_ui(new Ui_EditorStaticMeshEditor()), m_renderMode(EDITOR_RENDER_MODE_FULLBRIGHT), m_viewportFlags(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS), m_pGenerator(nullptr), m_pCompiledMesh(nullptr), m_pRenderWorld(new RenderWorld()), m_pLightSimulator(new EditorLightSimulator(0, m_pRenderWorld)), m_pMeshPreviewRenderProxy(nullptr), m_pCollisionShapePreviewRenderProxy(nullptr), m_pSwapChain(nullptr), m_pWorldRenderer(nullptr), m_bHardwareResourcesCreated(false), m_bRedrawPending(true), m_lastMousePosition(int2::Zero), m_currentTool(Tool_Information), m_currentState(State_None) { // create ui m_ui->CreateUI(this); m_ui->UpdateUIForCameraMode(m_viewController.GetCameraMode()); m_ui->UpdateUIForRenderMode(m_renderMode); m_ui->UpdateUIForViewportFlags(m_viewportFlags); m_ui->UpdateUIForTool(m_currentTool); // connect events ConnectUIEvents(); // fixup dimensions m_viewController.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); m_guiContext.SetViewportDimensions(m_ui->swapChainWidget->size().width(), m_ui->swapChainWidget->size().height()); } EditorStaticMeshEditor::~EditorStaticMeshEditor() { ReleaseHardwareResources(); delete m_pLightSimulator; SAFE_RELEASE(m_pCollisionShapePreviewRenderProxy); SAFE_RELEASE(m_pMeshPreviewRenderProxy); SAFE_RELEASE(m_pCompiledMesh); m_pRenderWorld->Release(); delete m_pGenerator; } void EditorStaticMeshEditor::SetCameraMode(EDITOR_CAMERA_MODE cameraMode) { DebugAssert(cameraMode < EDITOR_CAMERA_MODE_COUNT); m_viewController.SetCameraMode(cameraMode); m_ui->UpdateUIForCameraMode(cameraMode); } void EditorStaticMeshEditor::SetRenderMode(EDITOR_RENDER_MODE renderMode) { DebugAssert(renderMode < EDITOR_RENDER_MODE_COUNT); if (m_renderMode == renderMode) { // update ui anyway m_ui->UpdateUIForRenderMode(renderMode); return; } // update state m_renderMode = renderMode; m_ui->UpdateUIForRenderMode(renderMode); delete m_pWorldRenderer; m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); FlagForRedraw(); // update ui } void EditorStaticMeshEditor::SetViewportFlag(uint32 flag) { flag &= ~m_viewportFlags; if (flag == 0) return; m_viewportFlags |= flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorStaticMeshEditor::ClearViewportFlag(uint32 flag) { flag &= m_viewportFlags; if (flag == 0) return; m_viewportFlags &= ~flag; m_ui->UpdateUIForViewportFlags(m_viewportFlags); FlagForRedraw(); } void EditorStaticMeshEditor::SetCurrentTool(Tool tool) { m_ui->UpdateUIForTool(tool); if (m_currentTool == tool) return; m_currentTool = tool; // adjust collision mesh visibility m_pCollisionShapePreviewRenderProxy->SetVisibility((tool == Tool_Collision)); // redraw FlagForRedraw(); } bool EditorStaticMeshEditor::Create(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { DebugAssert(m_pGenerator == nullptr); m_meshName = meshName; m_meshFileName.Format("%s.staticmesh.xml", meshName); // allocate a new generator m_pGenerator = new StaticMeshGenerator(); m_pGenerator->Create(false, false); // load materials if (!RecompileMesh()) return false; // update everything OnFileNameChanged(); UpdateMaterials(); UpdateInformationTab(); RefreshCollisionShapePreview(); return true; } bool EditorStaticMeshEditor::Create(const StaticMeshGenerator *pGenerator, const char *meshName /* = nullptr */, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { DebugAssert(m_pGenerator == nullptr); // clone generator m_pGenerator = new StaticMeshGenerator(); m_pGenerator->Copy(pGenerator); // load materials if (!RecompileMesh()) return false; // update everything OnFileNameChanged(); UpdateMaterials(); UpdateInformationTab(); RefreshCollisionShapePreview(); return true; } bool EditorStaticMeshEditor::Load(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { DebugAssert(m_pGenerator == nullptr); // find the filename, and open it PathString fileName; fileName.Format("%s.staticmesh.xml", meshName); AutoReleasePtr<ByteStream> pMeshStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pMeshStream == nullptr) { Log_ErrorPrintf("Could not open file '%s'", fileName.GetCharArray()); return false; } StaticMeshGenerator *pGenerator = new StaticMeshGenerator(); if (!pGenerator->LoadFromXML(fileName, pMeshStream)) { Log_ErrorPrintf("Could not parse file '%s'", fileName.GetCharArray()); delete pGenerator; return false; } // close anything Close(); // store names m_meshName = meshName; m_meshFileName = fileName; // swap the pointers, and do allocations m_pGenerator = pGenerator; if (!RecompileMesh()) { Close(); return false; } // update everything OnFileNameChanged(); UpdateMaterials(); UpdateInformationTab(); RefreshCollisionShapePreview(); return true; } bool EditorStaticMeshEditor::Save(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { // if we have no name, use save as instead if (m_meshName.IsEmpty()) { m_ui->actionSaveMeshAs->trigger(); return !(m_meshName.IsEmpty()); } if (!m_pGenerator->IsCompleteMesh()) { pProgressCallbacks->DisplayError("The mesh is incomplete (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(m_meshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } return true; } bool EditorStaticMeshEditor::SaveAs(const char *meshName, ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { if (!m_pGenerator->IsCompleteMesh()) { pProgressCallbacks->DisplayError("The mesh is incomplete (does not contain either vertices, triangles, materials, batches). It cannot be saved."); return false; } PathString newMeshFileName; newMeshFileName.Format("%s.staticmesh.xml", meshName); // open stream AutoReleasePtr<ByteStream> pStream = g_pVirtualFileSystem->OpenFile(newMeshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == NULL) return false; if (!m_pGenerator->SaveToXML(pStream)) { pStream->Discard(); return false; } // update names m_meshName = meshName; m_meshFileName = newMeshFileName; OnFileNameChanged(); return true; } void EditorStaticMeshEditor::Close() { if (m_pGenerator == nullptr) return; if (m_pMeshPreviewRenderProxy != nullptr) { m_pRenderWorld->RemoveRenderable(m_pMeshPreviewRenderProxy); m_pMeshPreviewRenderProxy->Release(); m_pMeshPreviewRenderProxy = nullptr; } if (m_pCollisionShapePreviewRenderProxy != nullptr) { m_pRenderWorld->RemoveRenderable(m_pCollisionShapePreviewRenderProxy); m_pCollisionShapePreviewRenderProxy->Release(); m_pCollisionShapePreviewRenderProxy = nullptr; } SAFE_RELEASE(m_pCompiledMesh); delete m_pGenerator; m_pGenerator = nullptr; } bool EditorStaticMeshEditor::CreateHardwareResources() { Log_DevPrintf("Creating hardware resources for EditorStaticMeshEditor (%u x %u)", (uint32)m_ui->swapChainWidget->size().width(), (uint32)m_ui->swapChainWidget->size().height()); // create swap chain if (m_pSwapChain == NULL) { if ((m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) == NULL) return false; m_pSwapChain->AddRef(); } // get dimensions uint32 swapChainWidth = m_pSwapChain->GetWidth(); uint32 swapChainHeight = m_pSwapChain->GetHeight(); // update gui context, camera m_viewController.SetViewportDimensions(swapChainWidth, swapChainHeight); m_guiContext.SetViewportDimensions(swapChainWidth, swapChainHeight); // create render context if (m_pWorldRenderer == NULL) m_pWorldRenderer = EditorHelpers::CreateWorldRendererForRenderMode(m_renderMode, g_pRenderer->GetGPUContext(), m_viewportFlags, m_pSwapChain->GetWidth(), m_pSwapChain->GetHeight()); // cancel any pending draws until the windows are arranged and a paint is requested. m_bHardwareResourcesCreated = true; return true; } void EditorStaticMeshEditor::ReleaseHardwareResources() { m_guiContext.ClearState(); delete m_pWorldRenderer; m_pWorldRenderer = NULL; SAFE_RELEASE(m_pSwapChain); m_ui->swapChainWidget->DestroySwapChain(); m_bHardwareResourcesCreated = false; } void EditorStaticMeshEditor::OnFileNameChanged() { // update the window title setWindowTitle(ConvertStringToQString(String::FromFormat("Static Mesh Editor - %s", (m_meshName.IsEmpty()) ? "<unsaved mesh>" : m_meshName.GetCharArray()))); } void EditorStaticMeshEditor::UpdateMaterials() { m_meshMaterialNames.Clear(); for (uint32 lodIndex = 0; lodIndex < m_pGenerator->GetLODCount(); lodIndex++) { const StaticMeshGenerator::LOD *lod = m_pGenerator->GetLOD(lodIndex); for (uint32 batchIndex = 0; batchIndex < lod->Batches.GetSize(); batchIndex++) { const StaticMeshGenerator::Batch *batch = lod->Batches[batchIndex]; uint32 materialIndex = 0; for (; materialIndex < m_meshMaterialNames.GetSize(); materialIndex++) { if (m_meshMaterialNames[materialIndex] == batch->MaterialName) break; } if (materialIndex == m_meshMaterialNames.GetSize()) m_meshMaterialNames.Add(batch->MaterialName); } } } bool EditorStaticMeshEditor::RecompileMesh() { // update status bar m_ui->statusBarStatusLabel->setText(tr("Compiling mesh...")); g_pEditor->ProcessBackgroundEvents(); // don't update anything until the compile is complete.. StaticMesh *pStaticMesh = new StaticMesh(); //if (!pStaticMesh->Create("__StaticMeshEditor_PreviewMesh__", m_pGenerator)) { pStaticMesh->Release(); m_ui->statusBarStatusLabel->setText(tr("Failed to compile mesh.")); return false; } // update the render proxy if (m_pMeshPreviewRenderProxy == nullptr) { m_pMeshPreviewRenderProxy = new StaticMeshRenderProxy(0, pStaticMesh, Transform::Identity, 0); m_pRenderWorld->AddRenderable(m_pMeshPreviewRenderProxy); } else { m_pMeshPreviewRenderProxy->SetStaticMesh(pStaticMesh); } // clear out the old mesh if (m_pCompiledMesh != nullptr) m_pCompiledMesh->Release(); m_pCompiledMesh = pStaticMesh; FlagForRedraw(); m_ui->statusBarStatusLabel->setText(tr("Ready")); return true; } void EditorStaticMeshEditor::RefreshCollisionShapePreview() { // delete all preview objects if (m_pCollisionShapePreviewRenderProxy == nullptr) { m_pCollisionShapePreviewRenderProxy = new CompositeRenderProxy(0, Transform::Identity); m_pRenderWorld->AddRenderable(m_pCollisionShapePreviewRenderProxy); } else { m_pCollisionShapePreviewRenderProxy->DeleteAllObjects(); } // // depending on the type // const Physics::CollisionShapeGenerator *pCollisionShapeGenerator = m_pGenerator->GetCollisionShape(); // if (pCollisionShapeGenerator != nullptr) // { // switch (pCollisionShapeGenerator->GetType()) // { // case Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH: // { // // } // break; // } // } } void EditorStaticMeshEditor::UpdateInformationTab() { m_ui->toolInformationMinBounds->setText(ConvertStringToQString(StringConverter::Float3ToString(m_pCompiledMesh->GetBoundingBox().GetMinBounds()))); m_ui->toolInformationMaxBounds->setText(ConvertStringToQString(StringConverter::Float3ToString(m_pCompiledMesh->GetBoundingBox().GetMaxBounds()))); m_ui->toolInformationVertexCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pCompiledMesh->GetLOD(0)->GetVertexCount()))); m_ui->toolInformationTriangleCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pCompiledMesh->GetLOD(0)->GetIndexCount() / 3))); m_ui->toolInformationMaterialCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pCompiledMesh->GetMaterialCount()))); m_ui->toolInformationBatchCount->setText(ConvertStringToQString(StringConverter::UInt32ToString(m_pCompiledMesh->GetLOD(0)->GetBatchCount()))); m_ui->toolInformationEnableTextureCoordinates->setChecked(m_pGenerator->GetVertexTextureCoordinatesEnabled()); m_ui->toolInformationEnableVertexColors->setChecked(m_pGenerator->GetVertexColorsEnabled()); // collision shape information SmallString collisionShapeInformation; collisionShapeInformation.AppendString("Collision shape: "); if (m_pGenerator->GetCollisionShape() == nullptr) { // no shape collisionShapeInformation.AppendString("None"); m_ui->toolCollisionGenerateTriangleMesh->setChecked(true); } else { const Physics::CollisionShapeGenerator *pCollisionShapeGenerator = m_pGenerator->GetCollisionShape(); switch (pCollisionShapeGenerator->GetType()) { case Physics::COLLISION_SHAPE_TYPE_BOX: collisionShapeInformation.AppendFormattedString("Box, Extents: %s", StringConverter::Float3ToString(pCollisionShapeGenerator->GetBoxExtents()).GetCharArray()); m_ui->toolCollisionGenerateBox->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_SPHERE: collisionShapeInformation.AppendFormattedString("Sphere, radius: %s", StringConverter::FloatToString(pCollisionShapeGenerator->GetSphereRadius()).GetCharArray()); m_ui->toolCollisionGenerateSphere->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH: collisionShapeInformation.AppendFormattedString("Triangle Mesh, %u triangles", pCollisionShapeGenerator->GetTriangleCount()); m_ui->toolCollisionGenerateTriangleMesh->setChecked(true); break; case Physics::COLLISION_SHAPE_TYPE_CONVEX_HULL: collisionShapeInformation.AppendFormattedString("Convex hull, %u vertices", pCollisionShapeGenerator->GetConvexHullVertexCount()); m_ui->toolCollisionGenerateConvexHull->setChecked(true); break; } } m_ui->toolCollisionInformation->setText(ConvertStringToQString(collisionShapeInformation)); } void EditorStaticMeshEditor::Draw() { // create hardware resources if (!m_bHardwareResourcesCreated && !CreateHardwareResources()) return; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); // clear it pGPUContext->SetOutputBuffer(m_pSwapChain); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetViewport(m_viewController.GetViewport()); pGPUContext->ClearTargets(true, true, true); // setup 3d state pGPUContext->GetConstants()->SetFromCamera(m_viewController.GetCamera(), true); // invoke draws DrawGrid(); DrawView(); // bias the projection matrix slightly FIXME pGPUContext->GetConstants()->SetCameraProjectionMatrix(m_viewController.GetCamera().GetBiasedProjectionMatrix(0.01f), true); DrawOverlays(pGPUContext); // clear state pGPUContext->ClearState(true, true, true, true); // present pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); // clear pending flag m_bRedrawPending = false; } void EditorStaticMeshEditor::DrawGrid() { // draw a grid of 2*the mesh size float gridSizeX = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().x), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().x)) * 2.0f); float gridSizeY = Max(16.0f, Max(Math::Abs(m_pGenerator->GetBoundingBox().GetMinBounds().y), Math::Abs(m_pGenerator->GetBoundingBox().GetMaxBounds().y)) * 2.0f); m_guiContext.Draw3DGrid(float3(-gridSizeX, -gridSizeY, 0.0f), float3(gridSizeX, gridSizeY, 0.0f), float3(1.0f, 1.0f, 1.0f), MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255)); } void EditorStaticMeshEditor::DrawView() { m_pWorldRenderer->DrawWorld(m_pRenderWorld, m_viewController.GetViewParameters(), NULL, NULL); } void EditorStaticMeshEditor::DrawOverlays(GPUContext *pGPUContext) { m_guiContext.SetDepthTestingEnabled(false); m_guiContext.SetAlphaBlendingEnabled(false); // draw the collision mesh if (m_currentTool == Tool_Collision) { const Physics::CollisionShapeGenerator *pCollisionShape = m_pGenerator->GetCollisionShape(); if (pCollisionShape != nullptr) { switch (pCollisionShape->GetType()) { case Physics::COLLISION_SHAPE_TYPE_BOX: m_guiContext.Draw3DWireBox(AABox(-pCollisionShape->GetBoxExtents(), pCollisionShape->GetBoxExtents()), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255)); break; } } } } void EditorStaticMeshEditor::OnFrameExecutionTriggered(float timeSinceLastFrame) { // don't do anything if we haven't loaded if (m_pGenerator == nullptr) return; // update camera m_viewController.Update(timeSinceLastFrame); // force draw if requested by camera if (m_viewController.IsChanged()) FlagForRedraw(); // redraw if required if (m_bRedrawPending) Draw(); } void EditorStaticMeshEditor::ConnectUIEvents() { // actions connect(m_ui->actionOpenMesh, SIGNAL(triggered()), this, SLOT(OnActionOpenMeshClicked())); connect(m_ui->actionSaveMesh, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshClicked())); connect(m_ui->actionSaveMeshAs, SIGNAL(triggered()), this, SLOT(OnActionSaveMeshAsClicked())); connect(m_ui->actionClose, SIGNAL(triggered()), this, SLOT(OnActionCloseClicked())); connect(m_ui->actionCameraPerspective, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraPerspectiveTriggered(bool))); connect(m_ui->actionCameraArcball, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraArcballTriggered(bool))); connect(m_ui->actionCameraIsometric, SIGNAL(triggered(bool)), this, SLOT(OnActionCameraIsometricTriggered(bool))); connect(m_ui->actionViewWireframe, SIGNAL(triggered(bool)), this, SLOT(OnActionViewWireframeTriggered(bool))); connect(m_ui->actionViewUnlit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewUnlitTriggered(bool))); connect(m_ui->actionViewLit, SIGNAL(triggered(bool)), this, SLOT(OnActionViewLitTriggered(bool))); connect(m_ui->actionViewFlagShadows, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagShadowsTriggered(bool))); connect(m_ui->actionViewFlagWireframeOverlay, SIGNAL(triggered(bool)), this, SLOT(OnActionViewFlagWireframeOverlayTriggered(bool))); connect(m_ui->actionToolInformation, SIGNAL(triggered(bool)), this, SLOT(OnActionToolInformationTriggered(bool))); connect(m_ui->actionToolOperations, SIGNAL(triggered(bool)), this, SLOT(OnActionToolOperationsTriggered(bool))); connect(m_ui->actionToolMaterials, SIGNAL(triggered(bool)), this, SLOT(OnActionToolMaterialsTriggered(bool))); connect(m_ui->actionToolLOD, SIGNAL(triggered(bool)), this, SLOT(OnActionToolLODTriggered(bool))); connect(m_ui->actionToolCollision, SIGNAL(triggered(bool)), this, SLOT(OnActionToolCollisionTriggered(bool))); connect(m_ui->actionToolLightManipulator, SIGNAL(triggered(bool)), this, SLOT(OnActionToolLightManipulatorTriggered(bool))); // swapchain connect(m_ui->swapChainWidget, SIGNAL(ResizedEvent()), this, SLOT(OnSwapChainWidgetResized())); connect(m_ui->swapChainWidget, SIGNAL(PaintEvent()), this, SLOT(OnSwapChainWidgetPaint())); connect(m_ui->swapChainWidget, SIGNAL(KeyboardEvent(const QKeyEvent *)), this, SLOT(OnSwapChainWidgetKeyboardEvent(const QKeyEvent *))); connect(m_ui->swapChainWidget, SIGNAL(MouseEvent(const QMouseEvent *)), this, SLOT(OnSwapChainWidgetMouseEvent(const QMouseEvent *))); connect(m_ui->swapChainWidget, SIGNAL(WheelEvent(const QWheelEvent *)), this, SLOT(OnSwapChainWidgetWheelEvent(const QWheelEvent *))); connect(m_ui->swapChainWidget, SIGNAL(DropEvent(QDropEvent *)), this, SLOT(OnSwapChainWidgetDropEvent(QDropEvent *))); // frame event connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); // operations connect(m_ui->toolOperationsGenerateTangents, SIGNAL(clicked()), this, SLOT(OnOperationsGenerateTangentsClicked())); connect(m_ui->toolOperationsCenterMesh, SIGNAL(clicked()), this, SLOT(OnOperationsCenterMeshClicked())); connect(m_ui->toolOperationsRemoveUnusedVertices, SIGNAL(clicked()), this, SLOT(OnOperationsRemoveUnusedVerticesClicked())); connect(m_ui->toolOperationsRemoveUnusedTriangles, SIGNAL(clicked()), this, SLOT(OnOperationsRemoveUnusedTrianglesClicked())); } void EditorStaticMeshEditor::closeEvent(QCloseEvent *pCloseEvent) { deleteLater(); } void EditorStaticMeshEditor::OnActionOpenMeshClicked() { } void EditorStaticMeshEditor::OnActionSaveMeshClicked() { EditorProgressDialog progressDialog(this); progressDialog.show(); Save(&progressDialog); } void EditorStaticMeshEditor::OnActionSaveMeshAsClicked() { EditorResourceSaveDialog saveDialog(this, OBJECT_TYPEINFO(StaticMesh)); if (saveDialog.exec()) { String newMeshName(saveDialog.GetReturnValueResourceName()); // attempt save EditorProgressDialog progressDialog(this); progressDialog.show(); SaveAs(newMeshName, &progressDialog); } } void EditorStaticMeshEditor::OnActionCloseClicked() { } void EditorStaticMeshEditor::OnSwapChainWidgetResized() { uint32 newWidth = (uint32)m_ui->swapChainWidget->size().width(); uint32 newHeight = (uint32)m_ui->swapChainWidget->size().height(); // kill old swapchain refs if (m_pSwapChain != nullptr) { m_pSwapChain->Release(); m_pSwapChain = NULL; } // skip full recreation if we can just do the resize if (m_bHardwareResourcesCreated && (m_pSwapChain = m_ui->swapChainWidget->GetSwapChain()) != nullptr) m_pSwapChain->AddRef(); else m_bHardwareResourcesCreated = false; m_viewController.SetViewportDimensions(newWidth, newHeight); m_guiContext.SetViewportDimensions(newWidth, newHeight); // flag for redraw FlagForRedraw(); } void EditorStaticMeshEditor::OnSwapChainWidgetPaint() { FlagForRedraw(); } void EditorStaticMeshEditor::OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent) { // pass to camera m_viewController.HandleKeyboardEvent(pKeyboardEvent); } void EditorStaticMeshEditor::OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { if (m_currentState == State_None) { } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { //switch (m_currentState) //{ //} } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_currentState == State_None) { // right mouse button enters camera rotation state m_currentState = State_RotateCamera; return; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_currentState == State_RotateCamera) { m_currentState = State_None; return; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pMouseEvent->x(), pMouseEvent->y()); int2 lastMousePosition(m_lastMousePosition); int2 mousePositionDiff(currentMousePosition - lastMousePosition); m_lastMousePosition = currentMousePosition; switch (m_currentState) { case State_RotateCamera: m_viewController.RotateFromMousePosition(mousePositionDiff); FlagForRedraw(); break; } } } void EditorStaticMeshEditor::OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent) { } void EditorStaticMeshEditor::OnSwapChainWidgetGainedFocusEvent() { } void EditorStaticMeshEditor::OnOperationsGenerateTangentsClicked() { for (uint32 i = 0; i < m_pGenerator->GetLODCount(); i++) m_pGenerator->GenerateTangents(i); } void EditorStaticMeshEditor::OnOperationsCenterMeshClicked() { QMenu popupMenu; popupMenu.addAction(tr("Origin: Center")); popupMenu.addAction(tr("Origin: Bottom-middle-center")); QAction *action = popupMenu.exec(QCursor::pos()); if (action != nullptr) { if (action->text() == tr("Origin: Center")) m_pGenerator->CenterMesh(StaticMeshGenerator::CenterOrigin_Center); else if (action->text() == tr("Origin: Bottom-middle-center")) m_pGenerator->CenterMesh(StaticMeshGenerator::CenterOrigin_CenterBottom); else return; RecompileMesh(); UpdateInformationTab(); FlagForRedraw(); } } void EditorStaticMeshEditor::OnOperationsRemoveUnusedVerticesClicked() { } void EditorStaticMeshEditor::OnOperationsRemoveUnusedTrianglesClicked() { } <file_sep>/Engine/Source/ContentConverterStandalone/AssimpSceneImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" #include "ResourceCompiler/StaticMeshGenerator.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintAssimpSceneImporterSyntax() { Log_InfoPrint("Assimp Scene Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -meshdir <path>: Output mesh directory."); Log_InfoPrint(" -meshprefix <name>: Output mesh prefix."); Log_InfoPrint(" -genmap <path>: Absolute map output directory."); Log_InfoPrint(" -[no]materials: Enable/disable material importing"); Log_InfoPrint(" -materialdir: Directory for writing materials to"); Log_InfoPrint(" -materialprefix: Prefix for material names"); Log_InfoPrint(" -defaultmaterialname: Default material name"); Log_InfoPrint(" -rotate(X|Y|Z) <amount>: Rotate around the axis as a post-transform."); Log_InfoPrint(" -translate(X|Y|Z) <degrees>: Translate along the axis as a post-transform."); Log_InfoPrint(" -scale[X|Y|Z] <amount>: Uniform or nonuniform scale on axis as a post-transform."); Log_InfoPrint(" -flipwinding: Flip the triangle winding order"); Log_InfoPrint(" -cs <(yup|zup)_(lh|rh)>: File uses specified coordinate system, convert if necessary."); Log_InfoPrint(" -center: Center mesh in the center."); Log_InfoPrint(" -centerbase: Center mesh in the bottom-center-middle."); Log_InfoPrint(" -collision: Defines collision shape type, defaults to none. (trianglemesh, convexhull)"); Log_InfoPrint(""); } static uint32 GetCollisionShapeTypeIndex(const char *name) { if (Y_stricmp(name, "none") == 0) return StaticMeshGenerator::CollisionShapeType_None; else if (Y_stricmp(name, "box") == 0) return StaticMeshGenerator::CollisionShapeType_Box; else if (Y_stricmp(name, "sphere") == 0) return StaticMeshGenerator::CollisionShapeType_Sphere; else if (Y_stricmp(name, "trianglemesh") == 0) return StaticMeshGenerator::CollisionShapeType_TriangleMesh; else if (Y_stricmp(name, "convexhull") == 0) return StaticMeshGenerator::CollisionShapeType_ConvexHull; else return StaticMeshGenerator::CollisionShapeType_None; } bool ParseAssimpSceneImporterOption(AssimpSceneImporter::Options &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.SourcePath = argv[++i]; else if (CHECK_ARG_PARAM("-meshdir")) Options.MeshDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-meshprefix")) Options.MeshPrefix = argv[++i]; else if (CHECK_ARG_PARAM("-genmap")) Options.OutputMapName = argv[++i]; else if (CHECK_ARG("-nomaterials")) Options.ImportMaterials = false; else if (CHECK_ARG("-materials")) Options.ImportMaterials = true; else if (CHECK_ARG_PARAM("-materialdir")) Options.MaterialDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-materialprefix")) Options.MaterialPrefix = argv[++i]; else if (CHECK_ARG_PARAM("-defaultmaterialname")) Options.DefaultMaterialName = argv[++i]; else if (CHECK_ARG_PARAM("-collision")) Options.BuildCollisionShapeType = GetCollisionShapeTypeIndex(argv[++i]); else if (CHECK_ARG_PARAM("-rotateX")) Options.TransformMatrix = float4x4::MakeRotationMatrixX(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateY")) Options.TransformMatrix = float4x4::MakeRotationMatrixY(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateZ")) Options.TransformMatrix = float4x4::MakeRotationMatrixZ(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateX")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateY")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateZ")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleX")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleY")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleZ")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scale")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG("-center")) Options.CenterMeshes = StaticMeshGenerator::CenterOrigin_Center; else if (CHECK_ARG("-centerbase")) Options.CenterMeshes = StaticMeshGenerator::CenterOrigin_CenterBottom; else if (CHECK_ARG_PARAM("-cs")) { ++i; if (!Y_stricmp(argv[i], "yup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_LH; else if (!Y_stricmp(argv[i], "yup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; else if (!Y_stricmp(argv[i], "zup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_LH; else if (!Y_stricmp(argv[i], "zup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_RH; else { Log_ErrorPrintf("Invalid coordinate system specified."); return false; } } else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintAssimpSceneImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunAssimpSceneImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintAssimpSceneImporterSyntax(); return 0; } AssimpSceneImporter::Options options; AssimpSceneImporter::SetDefaultOptions(&options); for (i = 0; i < argc; i++) { if (!ParseAssimpSceneImporterOption(options, i, argc, argv)) return 1; } if (options.SourcePath.IsEmpty() || options.MeshDirectory.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; AssimpSceneImporter importer(&options, &progressCallbacks); if (!importer.Execute()) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Source/Engine/CMakeLists.txt include(${CMAKE_MODULE_PATH}/PrecompiledHeader.cmake) set(HEADER_FILES ArcBallCamera.h BlockMeshBuilder.h BlockMeshCollisionShape.h BlockMesh.h BlockMeshUtilities.h BlockMeshVolume.h BlockPalette.h Brush.h BulletDebugDraw.h Camera.h CommandQueue.h Common.h Component.h ComponentTypeInfo.h DataFormats.h Defines.h DynamicWorld.h EngineCVars.h Engine.h Entity.h EntityTypeInfo.h Font.h FPSCounter.h InputManager.h Map.h Material.h MaterialShader.h OverlayConsole.h ParticleSystemBuiltinEmitters.h ParticleSystemBuiltinModules.h ParticleSystemCommon.h ParticleSystemEmitter.h ParticleSystem.h ParticleSystemModule.h ParticleSystemRenderProxy.h ParticleSystemVertexFactory.h Physics/BoxCollisionShape.h Physics/BulletHeaders.h Physics/CollisionObject.h Physics/CollisionShape.h Physics/ConvexHullCollisionShape.h Physics/GhostObject.h Physics/KinematicObject.h Physics/PhysicsProxy.h Physics/PhysicsWorld.h Physics/RigidBody.h Physics/ScaledTriangleMeshCollisionShape.h Physics/SphereCollisionShape.h Physics/StaticObject.h Physics/TriangleMeshCollisionShape.h PrecompiledHeader.h Profiling.h ResourceManager.h ScriptManager.h ScriptObject.h ScriptObjectTypeInfo.h ScriptProxyFunctions.h ScriptTypes.h SDLHeaders.h SkeletalAnimation.h SkeletalAnimationPlayer.h SkeletalMesh.h Skeleton.h StaticMesh.h TerrainLayerList.h TerrainQuadTree.h TerrainRendererCDLOD.h TerrainRenderer.h TerrainRendererNull.h TerrainSectionCollisionShape.h TerrainSection.h TerrainTypes.h Texture.h World.h ) set(SOURCE_FILES ArcBallCamera.cpp BlockMeshBuilder.cpp BlockMeshCollisionShape.cpp BlockMesh.cpp BlockMeshUtilities.cpp BlockMeshVolume.cpp BlockPalette.cpp Brush.cpp BulletDebugDraw.cpp Camera.cpp CommandQueue.cpp Component.cpp ComponentTypeInfo.cpp Defines.cpp DynamicWorld.cpp Engine.cpp EngineCVars.cpp EngineTypes.cpp Entity.cpp EntityTypeInfo.cpp Font.cpp FPSCounter.cpp InputManager.cpp Map.cpp Material.cpp MaterialShader.cpp OverlayConsole.cpp ParticleSystemBuiltinEmitters.cpp ParticleSystemBuiltinModules.cpp ParticleSystem.cpp ParticleSystemEmitter.cpp ParticleSystemModule.cpp ParticleSystemRenderProxy.cpp ParticleSystemVertexFactory.cpp Physics/BoxCollisionShape.cpp Physics/CollisionObject.cpp Physics/CollisionShape.cpp Physics/ConvexHullCollisionShape.cpp Physics/GhostObject.cpp Physics/KinematicObject.cpp Physics/PhysicsProxy.cpp Physics/PhysicsWorld.cpp Physics/RigidBody.cpp Physics/ScaledTriangleMeshCollisionShape.cpp Physics/SphereCollisionShape.cpp Physics/StaticObject.cpp Physics/TriangleMeshCollisionShape.cpp PrecompiledHeader.cpp Profiling.cpp ResourceManager.cpp ScriptBuiltinFunctions.cpp ScriptManager.cpp ScriptObject.cpp ScriptObjectTypeInfo.cpp ScriptPrimitiveTypes.cpp ScriptTypes.cpp SkeletalAnimation.cpp SkeletalAnimationPlayer.cpp SkeletalMesh.cpp Skeleton.cpp StaticMesh.cpp TerrainLayerList.cpp TerrainQuadTree.cpp TerrainRendererCDLOD.cpp TerrainRenderer.cpp TerrainRendererNull.cpp TerrainSectionCollisionShape.cpp TerrainSection.cpp TerrainTypes.cpp Texture.cpp World.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/../Dependancies/microprofile ${SDL2_INCLUDE_DIR}) add_library(EngineMain STATIC ${HEADER_FILES} ${SOURCE_FILES}) set(EXTRA_LIBRARIES "") LIST(APPEND EXTRA_LIBRARIES "EngineRenderer") # remove once EngineTypes.cpp mess is fixed LIST(APPEND EXTRA_LIBRARIES "EngineGameFramework") if(WITH_RESOURCECOMPILER_EMBEDDED) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface EngineResourceCompiler") elseif(WITH_RESOURCECOMPILER_SUBPROCESS) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface") endif() #add_precompiled_header(EngineMain PrecompiledHeader.h SOURCE_CXX PrecompiledHeader.cpp) target_link_libraries(EngineMain EngineCore ${EXTRA_LIBRARIES} bullet lua ${SDL2_LIBRARY}) <file_sep>/Engine/Source/ResourceCompiler/MaterialGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/Material.h" struct ResourceCompilerCallbacks; class MaterialGenerator { public: typedef KeyValuePair<String, String> ShaderUniformParameter; typedef KeyValuePair<String, String> ShaderTextureParameter; typedef KeyValuePair<String, bool> ShaderStaticSwitchParameter; public: MaterialGenerator(); ~MaterialGenerator(); void Create(const char *ShaderName); void CreateFromMaterial(const Material *pMaterial); bool LoadFromXML(const char *FileName, ByteStream *pStream); bool SaveToXML(ByteStream *pStream); bool Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pOutputStream); const String &GetShaderName() const { return m_strShaderName; } void SetShaderName(const String &ShaderName) { m_strShaderName = ShaderName; } void SetShaderName(const char *ShaderName) { m_strShaderName = ShaderName; } const uint32 GetShaderUniformParameterCount() const { return m_ShaderUniformParameters.GetSize(); } const uint32 GetShaderTextureParameterCount() const { return m_ShaderTextureParameters.GetSize(); } const uint32 GetShaderStaticSwitchParameterCount() const { return m_ShaderStaticSwitchParameters.GetSize(); } const ShaderUniformParameter *GetShaderUniformParameter(uint32 Index) const { DebugAssert(Index < m_ShaderUniformParameters.GetSize()); return &m_ShaderUniformParameters[Index]; } const ShaderTextureParameter *GetShaderTextureParameter(uint32 Index) const { DebugAssert(Index < m_ShaderTextureParameters.GetSize()); return &m_ShaderTextureParameters[Index]; } const ShaderStaticSwitchParameter *GetShaderStaticSwitchParameter(uint32 Index) const { DebugAssert(Index < m_ShaderStaticSwitchParameters.GetSize()); return &m_ShaderStaticSwitchParameters[Index]; } // find parameters int32 FindShaderUniformParameter(const char *Name); int32 FindShaderTextureParameter(const char *Name); int32 FindShaderStaticSwitchParameter(const char *Name); // remove parameters (i.e. use default value) void RemoveShaderUniformParameter(uint32 Index); void RemoveShaderTextureParameter(uint32 Index); void RemoveShaderStaticSwitchParameter(uint32 Index); bool RemoveShaderUniformParameterByName(const char *Name); bool RemoveShaderTextureParameterByName(const char *Name); bool RemoveShaderStaticSwitchParameterByName(const char *Name); // shader parameters void SetShaderUniformParameter(uint32 Index, SHADER_PARAMETER_TYPE Type, const void *pNewValue); void SetShaderUniformParameterString(uint32 Index, const char *NewValue); void SetShaderTextureParameter(uint32 Index, const Texture *pTexture); void SetShaderTextureParameterString(uint32 Index, const char *NewTextureName); void SetShaderStaticSwitchParameter(uint32 Index, bool On); // shader parameters by string void SetShaderUniformParameterByName(const char *Name, SHADER_PARAMETER_TYPE Type, const void *pNewValue); void SetShaderUniformParameterStringByName(const char *Name, const char *NewValue); void SetShaderTextureParameterByName(const char *Name, const Texture *pNewTexture); void SetShaderTextureParameterStringByName(const char *Name, const char *NewTextureName); void SetShaderStaticSwitchParameterByName(const char *Name, bool On); // assignment operator MaterialGenerator &operator=(const MaterialGenerator &copyFrom); private: String m_strShaderName; Array<ShaderUniformParameter> m_ShaderUniformParameters; Array<ShaderTextureParameter> m_ShaderTextureParameters; Array<ShaderStaticSwitchParameter> m_ShaderStaticSwitchParameters; }; <file_sep>/Engine/Source/ContentConverter/TextureImporter.h #pragma once #include "ContentConverter/BaseImporter.h" #include "Engine/Common.h" #include "Core/Image.h" class ByteStream; class TextureGenerator; struct TextureImporterOptions { Array<String> InputFileNames; Array<String> InputMaskFileNames; String OutputName; bool AppendTexture; bool RebuildTexture; TEXTURE_TYPE Type; TEXTURE_USAGE Usage; TEXTURE_FILTER Filter; TEXTURE_ADDRESS_MODE AddressU; TEXTURE_ADDRESS_MODE AddressV; TEXTURE_ADDRESS_MODE AddressW; uint32 ResizeWidth; uint32 ResizeHeight; IMAGE_RESIZE_FILTER ResizeFilter; bool GenerateMipMaps; bool SourcePremultipliedAlpha; bool EnablePremultipliedAlpha; bool EnableTextureCompression; PIXEL_FORMAT OutputFormat; bool Optimize; bool Compile; }; class TextureImporter : public BaseImporter { public: TextureImporter(ProgressCallbacks *pProgressCallbacks); ~TextureImporter(); static void SetDefaultOptions(TextureImporterOptions *pOptions); static bool HasTextureFileExtension(const char *fileName); bool Execute(const TextureImporterOptions *pOptions); private: const TextureImporterOptions *m_pOptions; PODArray<Image *> m_sourceImages; TextureGenerator *m_pGenerator; // bool LoadSources(); bool LoadGenerator(); // bool CreateGenerator(); bool AppendImages(); bool ResizeAndSetProperties(); // bool WriteOutput(); bool WriteCompiledOutput(); }; <file_sep>/Engine/Source/Renderer/CMakeLists.txt set(HEADER_FILES Common.h DecalManager.h ImGuiBridge.h MiniGUIContext.h PrecompiledHeader.h Renderer.h RendererStateBlock.h RendererTypes.h RenderProfiler.h RenderProxies/BlockMeshRenderProxy.h RenderProxies/CompositeRenderProxy.h RenderProxies/DirectionalLightRenderProxy.h RenderProxies/PointLightRenderProxy.h RenderProxies/SkeletalMeshRenderProxy.h RenderProxies/SpriteRenderProxy.h RenderProxies/StaticMeshRenderProxy.h RenderProxies/VolumetricLightRenderProxy.h RenderProxy.h RenderQueue.h RenderWorld.h ShaderCompilerFrontend.h ShaderComponent.h ShaderComponentTypeInfo.h ShaderConstantBuffer.h ShaderMap.h ShaderProgram.h ShaderProgramSelector.h Shaders/DeferredShadingShaders.h Shaders/DepthOnlyShader.h Shaders/DownsampleShader.h Shaders/ForwardShadingShaders.h Shaders/FullBrightShader.h Shaders/MobileShaders.h Shaders/OneColorShader.h Shaders/OverlayShader.h Shaders/PlainShader.h Shaders/ShadowMapShader.h Shaders/SSAOShader.h Shaders/TextureBlitShader.h VertexBufferBindingArray.h VertexFactories/BlockMeshVertexFactory.h VertexFactories/LocalVertexFactory.h VertexFactories/PlainVertexFactory.h VertexFactories/SkeletalMeshVertexFactory.h VertexFactory.h VertexFactoryTypeInfo.h WorldRenderer.h WorldRenderers/CompositingWorldRenderer.h WorldRenderers/CSMShadowMapRenderer.h WorldRenderers/CubeMapShadowMapRenderer.h WorldRenderers/DebugNormalsWorldRenderer.h WorldRenderers/DeferredShadingWorldRenderer.h WorldRenderers/ForwardShadingWorldRenderer.h WorldRenderers/FullBrightWorldRenderer.h WorldRenderers/MobileWorldRenderer.h WorldRenderers/SingleShaderWorldRenderer.h WorldRenderers/SSMShadowMapRenderer.h ) set(SOURCE_FILES DecalManager.cpp ImGuiBridge.cpp MiniGUIContext.cpp PrecompiledHeader.cpp Renderer.cpp RendererStateBlock.cpp RendererTypes.cpp RenderProfiler.cpp RenderProxies/BlockMeshRenderProxy.cpp RenderProxies/CompositeRenderProxy.cpp RenderProxies/DirectionalLightRenderProxy.cpp RenderProxies/PointLightRenderProxy.cpp RenderProxies/SkeletalMeshRenderProxy.cpp RenderProxies/SpriteRenderProxy.cpp RenderProxies/StaticMeshRenderProxy.cpp RenderProxies/VolumetricLightRenderProxy.cpp RenderProxy.cpp RenderQueue.cpp RenderWorld.cpp ShaderCompilerFrontend.cpp ShaderComponent.cpp ShaderComponentTypeInfo.cpp ShaderConstantBuffer.cpp ShaderMap.cpp ShaderProgram.cpp ShaderProgramSelector.cpp Shaders/DeferredShadingShaders.cpp Shaders/DepthOnlyShader.cpp Shaders/DownsampleShader.cpp Shaders/ForwardShadingShaders.cpp Shaders/FullBrightShader.cpp Shaders/MobileShaders.cpp Shaders/OneColorShader.cpp Shaders/OverlayShader.cpp Shaders/PlainShader.cpp Shaders/ShadowMapShader.cpp Shaders/SSAOShader.cpp Shaders/TextureBlitShader.cpp VertexBufferBindingArray.cpp VertexFactories/BlockMeshVertexFactory.cpp VertexFactories/LocalVertexFactory.cpp VertexFactories/PlainVertexFactory.cpp VertexFactories/SkeletalMeshVertexFactory.cpp VertexFactory.cpp VertexFactoryTypeInfo.cpp WorldRenderer.cpp WorldRenderers/CompositingWorldRenderer.cpp WorldRenderers/CSMShadowMapRenderer.cpp WorldRenderers/CubeMapShadowMapRenderer.cpp WorldRenderers/DebugNormalsWorldRenderer.cpp WorldRenderers/DeferredShadingWorldRenderer.cpp WorldRenderers/ForwardShadingWorldRenderer.cpp WorldRenderers/FullBrightWorldRenderer.cpp WorldRenderers/MobileWorldRenderer.cpp WorldRenderers/SingleShaderWorldRenderer.cpp WorldRenderers/SSMShadowMapRenderer.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${ENGINE_BASE_DIRECTORY}/../Dependancies/microprofile ${SDL2_INCLUDE_DIR}) add_library(EngineRenderer STATIC ${HEADER_FILES} ${SOURCE_FILES}) set(EXTRA_LIBRARIES "") if(WITH_IMGUI) LIST(APPEND EXTRA_LIBRARIES imgui) endif() if(WITH_RENDERER_D3D11) LIST(APPEND EXTRA_LIBRARIES "EngineD3D11Renderer") endif() if(WITH_RENDERER_OPENGL) LIST(APPEND EXTRA_LIBRARIES "EngineOpenGLRenderer") endif() if(WITH_RENDERER_OPENGLES2) LIST(APPEND EXTRA_LIBRARIES "EngineOpenGLES2Renderer") endif() if(WITH_RESOURCECOMPILER_EMBEDDED) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface EngineResourceCompiler") elseif(WITH_RESOURCECOMPILER_SUBPROCESS) LIST(APPEND EXTRA_LIBRARIES "EngineResourceCompilerInterface") endif() target_link_libraries(EngineRenderer EngineMain ${EXTRA_LIBRARIES} ${SDL2_LIBRARY}) <file_sep>/Engine/Source/MathLib/Vectori.cpp #include "MathLib/Vectori.h" #include "MathLib/SIMDVectori.h" Vector2i::Vector2i(const SIMDVector2i &v) { Set(v.x, v.y); } Vector3i::Vector3i(const SIMDVector3i &v) { Set(v.x, v.y, v.z); } Vector4i::Vector4i(const SIMDVector4i &v) { Set(v.x, v.y, v.z, v.w); } void Vector2i::Set(const SIMDVector2i &v) { Set(v.x, v.y); } void Vector3i::Set(const SIMDVector3i &v) { Set(v.x, v.y, v.z); } void Vector4i::Set(const SIMDVector4i &v) { Set(v.x, v.y, v.z, v.w); } Vector2i &Vector2i::operator=(const SIMDVector2i &v) { Set(v.x, v.y); return *this; } Vector3i &Vector3i::operator=(const SIMDVector3i &v) { Set(v.x, v.y, v.z); return *this; } Vector4i &Vector4i::operator=(const SIMDVector4i &v) { Set(v.x, v.y, v.z, v.w); return *this; } static const int32 __int2Zero[2] = { 0, 0 }; static const int32 __int2One[2] = { 1, 1 }; static const int32 __int2NegativeOne[2] = { -1, -1 }; const Vector2i &Vector2i::Zero = reinterpret_cast<const Vector2i &>(__int2Zero); const Vector2i &Vector2i::One = reinterpret_cast<const Vector2i &>(__int2One); const Vector2i &Vector2i::NegativeOne = reinterpret_cast<const Vector2i &>(__int2NegativeOne); static const int32 __int3Zero[3] = { 0, 0, 0 }; static const int32 __int3One[3] = { 1, 1, 1 }; static const int32 __int3NegativeOne[3] = { -1, -1, -1 }; const Vector3i &Vector3i::Zero = reinterpret_cast<const Vector3i &>(__int3Zero); const Vector3i &Vector3i::One = reinterpret_cast<const Vector3i &>(__int3One); const Vector3i &Vector3i::NegativeOne = reinterpret_cast<const Vector3i &>(__int3NegativeOne); static const int32 __int4Zero[4] = { 0, 0, 0, 0 }; static const int32 __int4One[4] = { 1, 1, 1, 1 }; static const int32 __int4NegativeOne[4] = { -1, -1, -1, -1 }; const Vector4i &Vector4i::Zero = reinterpret_cast<const Vector4i &>(__int4Zero); const Vector4i &Vector4i::One = reinterpret_cast<const Vector4i &>(__int4One); const Vector4i &Vector4i::NegativeOne = reinterpret_cast<const Vector4i &>(__int4NegativeOne); <file_sep>/Engine/Source/Renderer/VertexFactories/PlainVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" enum PLAIN_VERTEX_FACTORY_FLAGS { PLAIN_VERTEX_FACTORY_FLAG_TEXCOORD = (1 << 0), PLAIN_VERTEX_FACTORY_FLAG_COLOR = (1 << 1), }; class PlainVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(PlainVertexFactory, VertexFactory); public: struct Vertex { float3 Position; float2 TexCoord; uint32 Color; void SetUV(float x_, float y_, float z_, float u_, float v_); void SetUVColor(float x_, float y_, float z_, float u_, float v_, uint32 color); void SetUVColorFloat(float x_, float y_, float z_, float u_, float v_, float r_, float g_, float b_, float a_); void SetUVColorByte(float x_, float y_, float z_, float u_, float v_, uint8 r_, uint8 g_, uint8 b_, uint8 a_); void SetColor(float x_, float y_, float z_, uint32 color); void SetColorFloat(float x_, float y_, float z_, float r_, float g_, float b_, float a_); void SetColorByte(float x_, float y_, float z_, uint8 r_, uint8 g_, uint8 b_, uint8 a_); void Set(const float3 &Position_, const float2 &TexCoord_, const float4 &Color_); void Set(const float3 &Position_, const float2 &TexCoord_, const uint32 Color_); }; public: static uint32 GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static bool FillBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); }; // operators for vertex array building bool operator==(const PlainVertexFactory::Vertex &v1, const PlainVertexFactory::Vertex &v2); bool operator!=(const PlainVertexFactory::Vertex &v1, const PlainVertexFactory::Vertex &v2); <file_sep>/Editor/Source/Editor/EditorVisual.h #pragma once #include "Editor/Common.h" #include "Core/PropertyTable.h" #include "Core/PropertyTemplate.h" class RenderWorld; class ObjectTemplate; class EditorVisualComponentDefinition; class EditorVisualComponentInstance; class ByteStream; class EditorVisualDefinition { public: EditorVisualDefinition(); ~EditorVisualDefinition(); const String &GetName() const { return m_strName; } bool CreateFromName(const char *name); bool CreateFromTemplate(const ObjectTemplate *pTemplate); const EditorVisualComponentDefinition *GetVisualDefinition(uint32 i) const { DebugAssert(i < m_visualComponentDefinitions.GetSize()); return m_visualComponentDefinitions[i]; } const uint32 GetVisualDefinitionCount() const { return m_visualComponentDefinitions.GetSize(); } private: bool LoadComponentsFromStream(const char *FileName, ByteStream *pStream); String m_strName; typedef PODArray<EditorVisualComponentDefinition *> VisualDefinitionArray; VisualDefinitionArray m_visualComponentDefinitions; }; class EditorVisualInstance { public: ~EditorVisualInstance(); static EditorVisualInstance *Create(uint32 pickingID, const EditorVisualDefinition *pDefinition, const PropertyTable *pInitialProperties = &PropertyTable::EmptyPropertyList); // accessors const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } RenderWorld *GetRenderWorld() const { return m_pRenderWorld; } // world manipulation void AddToRenderWorld(RenderWorld *pWorld); void RemoveFromRenderWorld(RenderWorld *pWorld); // events void OnPropertyModified(const char *propertyName, const char *propertyValue); void OnSelectedStateChanged(bool selected); private: EditorVisualInstance(const EditorVisualDefinition *pDefinition); void UpdateBounds(); const EditorVisualDefinition *m_pDefinition; RenderWorld *m_pRenderWorld; typedef PODArray<EditorVisualComponentInstance *> VisualComponentInstanceArray; VisualComponentInstanceArray m_visualInstances; // bounding box of all components AABox m_boundingBox; Sphere m_boundingSphere; }; <file_sep>/Engine/Source/MapCompilerStandalone/Common.h #pragma once #include "MapCompiler/Common.h" #include "MapCompiler/MapSource.h" <file_sep>/Engine/Source/Renderer/VertexFactoryTypeInfo.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactoryTypeInfo.h" VertexFactoryTypeInfo::VertexFactoryTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, IsValidPermutationFunction fpIsValidPermutation, FillShaderCompilerParametersFunction fpFillShaderCompilerParameters, const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBindings, GetVertexElementsDescFunction fpGetVertexElementsDesc) : ShaderComponentTypeInfo(TypeName, pParentTypeInfo, fpIsValidPermutation, fpFillShaderCompilerParameters, pParameterBindings), m_fpGetVertexElementsDesc(fpGetVertexElementsDesc) { } VertexFactoryTypeInfo::~VertexFactoryTypeInfo() { } <file_sep>/Engine/Source/Core/Property.h #pragma once #include "Core/Common.h" #include "YBaseLib/NameTable.h" #include "YBaseLib/String.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #include "MathLib/Quaternion.h" #include "MathLib/Transform.h" class BinaryReader; class BinaryWriter; #define MAX_PROPERTY_TABLE_NAME_LENGTH 128 #define MAX_PROPERTY_NAME_LENGTH 128 enum PROPERTY_TYPE { PROPERTY_TYPE_BOOL, PROPERTY_TYPE_UINT, PROPERTY_TYPE_INT, PROPERTY_TYPE_INT2, PROPERTY_TYPE_INT3, PROPERTY_TYPE_INT4, PROPERTY_TYPE_FLOAT, PROPERTY_TYPE_FLOAT2, PROPERTY_TYPE_FLOAT3, PROPERTY_TYPE_FLOAT4, PROPERTY_TYPE_QUATERNION, PROPERTY_TYPE_TRANSFORM, PROPERTY_TYPE_STRING, PROPERTY_TYPE_COLOR, PROPERTY_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(PropertyType); } enum PROPERTY_FLAG { PROPERTY_FLAG_READ_ONLY = (1 << 0), // Property cannot be modified by user. Engine can still modify it, however. PROPERTY_FLAG_INVOKE_CHANGE_CALLBACK_ON_CREATE = (1 << 1), // Property change callback will be invoked when the object is being created. By default it is not. }; struct PROPERTY_DECLARATION { typedef bool(*GET_PROPERTY_CALLBACK)(const void *pObjectPtr, const void *pUserData, void *pValuePtr); typedef bool(*SET_PROPERTY_CALLBACK)(void *pObjectPtr, const void *pUserData, const void *pValuePtr); typedef void(*PROPERTY_CHANGED_CALLBACK)(void *pObjectPtr, const void *pUserData); const char *Name; PROPERTY_TYPE Type; uint32 Flags; GET_PROPERTY_CALLBACK GetPropertyCallback; const void *pGetPropertyCallbackUserData; SET_PROPERTY_CALLBACK SetPropertyCallback; const void *pSetPropertyCallbackUserData; PROPERTY_CHANGED_CALLBACK PropertyChangedCallback; const void *pPropertyChangedCallbackUserData; }; bool GetPropertyValueAsString(const void *pObject, const PROPERTY_DECLARATION *pProperty, String &StrValue); bool SetPropertyValueFromString(void *pObject, const PROPERTY_DECLARATION *pProperty, const char *szValue); bool WritePropertyValueToBuffer(const void *pObject, const PROPERTY_DECLARATION *pProperty, BinaryWriter &binaryWriter); bool ReadPropertyValueFromBuffer(void *pObject, const PROPERTY_DECLARATION *pProperty, BinaryReader &binaryReader); bool EncodePropertyTypeToBuffer(PROPERTY_TYPE propertyType, const char *valueString, BinaryWriter &binaryWriter); namespace DefaultPropertyTableCallbacks { // builtin functions bool GetBool(const void *pObjectPtr, const void *pUserData, bool *pValuePtr); bool SetBool(void *pObjectPtr, const void *pUserData, const bool *pValuePtr); bool GetUInt(const void *pObjectPtr, const void *pUserData, uint32 *pValuePtr); bool SetUInt(void *pObjectPtr, const void *pUserData, const uint32 *pValuePtr); bool GetInt(const void *pObjectPtr, const void *pUserData, int32 *pValuePtr); bool SetInt(void *pObjectPtr, const void *pUserData, const int32 *pValuePtr); bool GetInt2(const void *pObjectPtr, const void *pUserData, Vector2i *pValuePtr); bool SetInt2(void *pObjectPtr, const void *pUserData, const Vector2i *pValuePtr); bool GetInt3(const void *pObjectPtr, const void *pUserData, Vector3i *pValuePtr); bool SetInt3(void *pObjectPtr, const void *pUserData, const Vector3i *pValuePtr); bool GetInt4(const void *pObjectPtr, const void *pUserData, Vector4i *pValuePtr); bool SetInt4(void *pObjectPtr, const void *pUserData, const Vector4i *pValuePtr); bool GetFloat(const void *pObjectPtr, const void *pUserData, float *pValuePtr); bool SetFloat(void *pObjectPtr, const void *pUserData, const float *pValuePtr); bool GetFloat2(const void *pObjectPtr, const void *pUserData, Vector2f *pValuePtr); bool SetFloat2(void *pObjectPtr, const void *pUserData, const Vector2f *pValuePtr); bool GetFloat3(const void *pObjectPtr, const void *pUserData, Vector3f *pValuePtr); bool SetFloat3(void *pObjectPtr, const void *pUserData, const Vector3f *pValuePtr); bool GetFloat4(const void *pObjectPtr, const void *pUserData, Vector4f *pValuePtr); bool SetFloat4(void *pObjectPtr, const void *pUserData, const Vector4f *pValuePtr); bool GetQuaternion(const void *pObjectPtr, const void *pUserData, Quaternion *pValuePtr); bool SetQuaternion(void *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr); bool GetTransform(const void *pObjectPtr, const void *pUserData, Transform *pValuePtr); bool SetTransform(void *pObjectPtr, const void *pUserData, const Transform *pValuePtr); bool GetString(const void *pObjectPtr, const void *pUserData, String *pValuePtr); bool SetString(void *pObjectPtr, const void *pUserData, const String *pValuePtr); bool GetColor(const void *pObjectPtr, const void *pUserData, uint32 *pValuePtr); bool SetColor(const void *pObjectPtr, const void *pUserData, const uint32 *pValuePtr); // static bool value bool GetConstBool(const void *pObjectPtr, const void *pUserData, bool *pValuePtr); } #define PROPERTY_TABLE_MEMBER(Name, Type, Flags, \ GetPropertyCallback, GetPropertyCallbackUserData, \ SetPropertyCallback, SetPropertyCallbackUserData, \ PropertyChangedCallback, PropertyChangedCallbackUserData) \ { \ Name, Type, Flags, \ (PROPERTY_DECLARATION::GET_PROPERTY_CALLBACK)(GetPropertyCallback), (const void *)(GetPropertyCallbackUserData), \ (PROPERTY_DECLARATION::SET_PROPERTY_CALLBACK)(SetPropertyCallback), (const void *)(SetPropertyCallbackUserData), \ (PROPERTY_DECLARATION::PROPERTY_CHANGED_CALLBACK)(PropertyChangedCallback), (const void *)(PropertyChangedCallbackUserData) \ }, #define PROPERTY_TABLE_MEMBER_BOOL(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_BOOL, Flags, \ DefaultPropertyTableCallbacks::GetBool, (Offset), \ DefaultPropertyTableCallbacks::SetBool, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_UINT(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_INT, Flags, \ DefaultPropertyTableCallbacks::GetUInt, (Offset), \ DefaultPropertyTableCallbacks::SetUInt, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_INT(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_INT, Flags, \ DefaultPropertyTableCallbacks::GetInt, (Offset), \ DefaultPropertyTableCallbacks::SetInt, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_INT2(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_INT2, Flags, \ DefaultPropertyTableCallbacks::GetInt2, (Offset), \ DefaultPropertyTableCallbacks::SetInt2, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_INT3(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_INT3, Flags, \ DefaultPropertyTableCallbacks::GetInt3, (Offset), \ DefaultPropertyTableCallbacks::SetInt3, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_INT4(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_INT4, Flags, \ DefaultPropertyTableCallbacks::GetInt4, (Offset), \ DefaultPropertyTableCallbacks::SetInt4, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_FLOAT(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_FLOAT, Flags, \ DefaultPropertyTableCallbacks::GetFloat, (Offset), \ DefaultPropertyTableCallbacks::SetFloat, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_FLOAT2(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_FLOAT2, Flags, \ DefaultPropertyTableCallbacks::GetFloat2, (Offset), \ DefaultPropertyTableCallbacks::SetFloat2, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_FLOAT3(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_FLOAT3, Flags, \ DefaultPropertyTableCallbacks::GetFloat3, (Offset), \ DefaultPropertyTableCallbacks::SetFloat3, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_FLOAT4(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_FLOAT4, Flags, \ DefaultPropertyTableCallbacks::GetFloat4, (Offset), \ DefaultPropertyTableCallbacks::SetFloat4, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_QUATERNION(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_QUATERNION, Flags, \ DefaultPropertyTableCallbacks::GetQuaternion, (Offset), \ DefaultPropertyTableCallbacks::SetQuaternion, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_TRANSFORM(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_TRANSFORM, Flags, \ DefaultPropertyTableCallbacks::GetTransform, (Offset), \ DefaultPropertyTableCallbacks::SetTransform, (Offset), \ ChangedFunc, ChangedFuncUserData) #define PROPERTY_TABLE_MEMBER_COLOR(Name, Flags, Offset, ChangedFunc, ChangedFuncUserData) \ PROPERTY_TABLE_MEMBER(Name, PROPERTY_TYPE_COLOR, Flags, \ DefaultPropertyTableCallbacks::GetColor, (Offset), \ DefaultPropertyTableCallbacks::SetColor, (Offset), \ ChangedFunc, ChangedFuncUserData) <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUContext.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" #include "OpenGLRenderer/OpenGLGPUOutputBuffer.h" #include "OpenGLRenderer/OpenGLGPUTexture.h" #include "OpenGLRenderer/OpenGLGPUBuffer.h" #include "OpenGLRenderer/OpenGLGPUShaderProgram.h" #include "Renderer/ShaderConstantBuffer.h" Log_SetChannel(OpenGLRenderBackend); #define DEFER_SHADER_STATE_CHANGES 1 OpenGLGPUContext::OpenGLGPUContext(OpenGLGPUDevice *pDevice, SDL_GLContext pSDLGLContext, OpenGLGPUOutputBuffer *pOutputBuffer) { m_pDevice = pDevice; m_pDevice->SetImmediateContext(this); m_pDevice->AddRef(); m_pSDLGLContext = pSDLGLContext; m_pCurrentOutputBuffer = pOutputBuffer; if (m_pCurrentOutputBuffer != nullptr) m_pCurrentOutputBuffer->AddRef(); m_pConstants = nullptr; Y_memzero(&m_currentViewport, sizeof(m_currentViewport)); Y_memzero(&m_scissorRect, sizeof(m_scissorRect)); m_drawTopology = DRAW_TOPOLOGY_TRIANGLE_LIST; m_glDrawTopology = GL_TRIANGLES; m_vertexArrayObjectId = 0; m_activeVertexBuffers = 0; m_dirtyVertexBuffers = false; m_activeVertexAttributes = 0; m_dirtyVertexAttributes = false; m_pCurrentIndexBuffer = nullptr; m_currentIndexFormat = GPU_INDEX_FORMAT_UINT16; m_currentIndexBufferOffset = 0; m_pCurrentShaderProgram = nullptr; m_activeUniformBlockBindings = 0; m_dirtyUniformBlockBindingsLowerBounds = -1; m_dirtyUniformBlockBindingsUpperBounds = -1; m_activeTextureUnitBindings = 0; m_dirtyTextureUnitsLowerBounds = -1; m_dirtyTextureUnitsUpperBounds = -1; m_activeImageUnitBindings = 0; m_dirtyImageUnitsLowerBounds = -1; m_dirtyImageUnitsUpperBounds = -1; m_activeShaderStorageBufferBindings = 0; m_dirtyShaderStorageBuffersLowerBounds = -1; m_dirtyShaderStorageBuffersUpperBounds = -1; m_mutatorTextureUnit = 0; m_pCurrentRasterizerState = nullptr; m_pCurrentDepthStencilState = nullptr; m_currentDepthStencilStateStencilRef = 0; m_pCurrentBlendState = nullptr; m_currentBlendStateBlendFactors.SetZero(); m_drawFrameBufferObjectId = 0; m_readFrameBufferObjectId = 0; Y_memzero(m_pCurrentRenderTargets, sizeof(m_pCurrentRenderTargets)); m_pCurrentDepthStencilBuffer = nullptr; m_nCurrentRenderTargets = 0; m_pUserVertexBuffer = nullptr; m_userVertexBufferSize = 1024 * 1024; m_userVertexBufferPosition = 0; } OpenGLGPUContext::~OpenGLGPUContext() { // unbind vertex attributes SetShaderVertexAttributes(nullptr, 0); CommitVertexAttributes(); // unbind shader stuff for (uint32 i = 0; i < m_activeShaderStorageBufferBindings; i++) { if (m_currentShaderStorageBufferBindings[i] != nullptr) SetShaderStorageBuffer(i, nullptr); } for (uint32 i = 0; i < m_activeImageUnitBindings; i++) { if (m_currentImageUnitBindings[i] != nullptr) SetShaderImageUnit(i, nullptr); } for (uint32 i = 0; i < m_activeUniformBlockBindings; i++) { if (m_currentUniformBlockBindings[i] != nullptr) SetShaderUniformBlock(i, nullptr); } for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i].pTexture != nullptr || m_currentTextureUnitBindings[i].pSampler != nullptr) SetShaderTextureUnit(i, nullptr, nullptr); } if (m_pCurrentShaderProgram != nullptr) SetShaderProgram(nullptr); CommitShaderResources(); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; if (constantBuffer->pGPUBuffer != nullptr) constantBuffer->pGPUBuffer->Release(); delete[] constantBuffer->pLocalMemory; } if (m_drawFrameBufferObjectId > 0) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &m_drawFrameBufferObjectId); } if (m_readFrameBufferObjectId > 0) glDeleteFramebuffers(1, &m_readFrameBufferObjectId); if (m_vertexArrayObjectId > 0) { glBindVertexArray(0); glDeleteVertexArrays(1, &m_vertexArrayObjectId); } for (uint32 i = 0; i < m_activeVertexBuffers; i++) SAFE_RELEASE(m_currentVertexBuffers[i].pVertexBuffer); SAFE_RELEASE(m_pCurrentIndexBuffer); SAFE_RELEASE(m_pCurrentRasterizerState); SAFE_RELEASE(m_pCurrentDepthStencilState); SAFE_RELEASE(m_pCurrentBlendState); for (uint32 i = 0; i < GPU_MAX_SIMULTANEOUS_RENDER_TARGETS; i++) SAFE_RELEASE(m_pCurrentRenderTargets[i]); SAFE_RELEASE(m_pCurrentDepthStencilBuffer); //SAFE_RELEASE(m_pUserIndexBuffer); SAFE_RELEASE(m_pUserVertexBuffer); delete m_pConstants; // last thing to release is the output window, this is safe because it won't make any gl calls SAFE_RELEASE(m_pCurrentOutputBuffer); // release device m_pDevice->SetImmediateContext(nullptr); m_pDevice->Release(); } void OpenGLGPUContext::UpdateVSyncState(RENDERER_VSYNC_TYPE vsyncType) { int swapInterval = 0; switch (vsyncType) { case RENDERER_VSYNC_TYPE_NONE: swapInterval = 0; break; case RENDERER_VSYNC_TYPE_VSYNC: swapInterval = 1; break; case RENDERER_VSYNC_TYPE_ADAPTIVE_VSYNC: swapInterval = -1; break; case RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING: swapInterval = 1; break; } SDL_GL_SetSwapInterval(swapInterval); } bool OpenGLGPUContext::Create() { glGenFramebuffers(1, &m_drawFrameBufferObjectId); glGenFramebuffers(1, &m_readFrameBufferObjectId); if (m_drawFrameBufferObjectId == 0 || m_readFrameBufferObjectId == 0) { GL_PRINT_ERROR("OpenGLGPUContext::Create: glGenFrameBuffers failed: "); return false; } glGenVertexArrays(1, &m_vertexArrayObjectId); if (m_vertexArrayObjectId == 0) { GL_PRINT_ERROR("OpenGLGPUContext::Create: glGenVertexArrays failed: "); return false; } glBindVertexArray(m_vertexArrayObjectId); // allocate shader state arrays uint32 maxCombinedTextureImageUnits = 0; uint32 maxUniformBufferBindings = 0; uint32 maxCombinedImageUniforms = 0; uint32 maxCombinedShaderStorageBlocks = 0; uint32 maxVertexAttributes = 0; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, reinterpret_cast<GLint *>(&maxCombinedTextureImageUnits)); glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, reinterpret_cast<GLint *>(&maxUniformBufferBindings)); glGetIntegerv(GL_MAX_COMBINED_IMAGE_UNIFORMS, reinterpret_cast<GLint *>(&maxCombinedImageUniforms)); glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, reinterpret_cast<GLint *>(&maxCombinedShaderStorageBlocks)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); // these should be >0 if (maxCombinedTextureImageUnits == 0 || maxUniformBufferBindings == 0 || maxVertexAttributes == 0) { Log_ErrorPrintf("OpenGLGPUContext::Create: GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%u) or GL_MAX_UNIFORM_BUFFER_BINDINGS (%u) is below required amounts.", maxCombinedTextureImageUnits, maxUniformBufferBindings); return false; } // allocate storage m_currentTextureUnitBindings.Resize(maxCombinedTextureImageUnits); m_currentTextureUnitBindings.ZeroContents(); m_currentUniformBlockBindings.Resize(maxUniformBufferBindings); m_currentUniformBlockBindings.ZeroContents(); m_currentImageUnitBindings.Resize(maxCombinedImageUniforms); m_currentImageUnitBindings.ZeroContents(); m_currentShaderStorageBufferBindings.Resize(maxCombinedShaderStorageBlocks); m_currentShaderStorageBufferBindings.ZeroContents(); m_currentVertexAttributes.Resize(maxVertexAttributes); m_currentVertexAttributes.ZeroContents(); m_currentVertexBuffers.Resize(maxVertexAttributes); m_currentVertexBuffers.ZeroContents(); // set deps m_mutatorTextureUnit = m_currentTextureUnitBindings.GetSize() - 1; // create plain vertex buffer { GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_MAPPABLE | GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, m_userVertexBufferSize); if ((m_pUserVertexBuffer = static_cast<OpenGLGPUBuffer *>(m_pDevice->CreateBuffer(&vertexBufferDesc, NULL))) == NULL) { Log_ErrorPrintf("OpenGLGPUContext::Create: Failed to create plain dynamic vertex buffer."); return false; } } // create constants buffers m_pConstants = new GPUContextConstants(m_pDevice, this); // create constant buffers if (!CreateConstantBuffers()) return false; // update swap interval UpdateVSyncState(m_pCurrentOutputBuffer->GetVSyncType()); // enable srgb writes for textures in this format if (PixelFormatHelpers::IsSRGBFormat(m_pCurrentOutputBuffer->GetBackBufferFormat())) glEnable(GL_FRAMEBUFFER_SRGB); // done Log_InfoPrint("OpenGLGPUContext::Create: Context creation complete."); return true; } void OpenGLGPUContext::ClearState(bool clearShaders /* = true */, bool clearBuffers /* = true */, bool clearStates /* = true */, bool clearRenderTargets /* = true */) { if (clearShaders) { SetShaderProgram(NULL); // unbind shader stuff SetShaderVertexAttributes(nullptr, 0); CommitVertexAttributes(); for (uint32 i = 0; i < m_activeShaderStorageBufferBindings; i++) { if (m_currentShaderStorageBufferBindings[i] != nullptr) SetShaderStorageBuffer(i, nullptr); } for (uint32 i = 0; i < m_activeImageUnitBindings; i++) { if (m_currentImageUnitBindings[i] != nullptr) SetShaderImageUnit(i, nullptr); } for (uint32 i = 0; i < m_activeUniformBlockBindings; i++) { if (m_currentUniformBlockBindings[i] != nullptr) SetShaderUniformBlock(i, nullptr); } for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i].pTexture != nullptr || m_currentTextureUnitBindings[i].pSampler != nullptr) SetShaderTextureUnit(i, nullptr, nullptr); } CommitShaderResources(); } if (clearBuffers) { for (uint32 i = 0; i < m_activeVertexBuffers; i++) SetVertexBuffer(i, nullptr, 0, 0); SetIndexBuffer(nullptr, GPU_INDEX_FORMAT_UINT16, 0); CommitVertexAttributes(); } if (clearStates) { SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState()); SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(), 0); SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); SetDrawTopology(DRAW_TOPOLOGY_UNDEFINED); RENDERER_SCISSOR_RECT scissor(0, 0, 0, 0); SetFullViewport(nullptr); SetScissorRect(&scissor); } if (clearRenderTargets) SetRenderTargets(0, nullptr, nullptr); } GPURasterizerState *OpenGLGPUContext::GetRasterizerState() { return m_pCurrentRasterizerState; } void OpenGLGPUContext::SetRasterizerState(GPURasterizerState *pRasterizerState) { if (m_pCurrentRasterizerState == pRasterizerState) return; // if new buffer is null, unbind old if (m_pCurrentRasterizerState != NULL) { if (pRasterizerState == NULL) m_pCurrentRasterizerState->Unapply(); m_pCurrentRasterizerState->Release(); } if ((m_pCurrentRasterizerState = static_cast<OpenGLGPURasterizerState *>(pRasterizerState)) != NULL) { m_pCurrentRasterizerState->AddRef(); m_pCurrentRasterizerState->Apply(); } } GPUDepthStencilState *OpenGLGPUContext::GetDepthStencilState() { return m_pCurrentDepthStencilState; } uint8 OpenGLGPUContext::GetDepthStencilStateStencilRef() { return m_currentDepthStencilStateStencilRef; } void OpenGLGPUContext::SetDepthStencilState(GPUDepthStencilState *pDepthStencilState, uint8 StencilRef) { if (m_pCurrentDepthStencilState == pDepthStencilState && m_currentDepthStencilStateStencilRef == StencilRef) return; m_currentDepthStencilStateStencilRef = StencilRef; // if new buffer is null, unbind old if (m_pCurrentDepthStencilState != NULL) { if (pDepthStencilState == NULL) m_pCurrentDepthStencilState->Unapply(); m_pCurrentDepthStencilState->Release(); } if ((m_pCurrentDepthStencilState = static_cast<OpenGLGPUDepthStencilState *>(pDepthStencilState)) != NULL) { m_pCurrentDepthStencilState->AddRef(); m_pCurrentDepthStencilState->Apply(StencilRef); } } GPUBlendState *OpenGLGPUContext::GetBlendState() { return m_pCurrentBlendState; } const float4 &OpenGLGPUContext::GetBlendStateBlendFactor() { return m_currentBlendStateBlendFactors; } void OpenGLGPUContext::SetBlendState(GPUBlendState *pBlendState, const float4 &BlendFactor /* = float4::One */) { if (m_pCurrentBlendState != pBlendState) { // if new buffer is null, unbind old if (m_pCurrentBlendState != NULL) { if (pBlendState == NULL) m_pCurrentBlendState->Unapply(); m_pCurrentBlendState->Release(); } if ((m_pCurrentBlendState = static_cast<OpenGLGPUBlendState *>(pBlendState)) != NULL) { m_pCurrentBlendState->AddRef(); m_pCurrentBlendState->Apply(); } } if (BlendFactor != m_currentBlendStateBlendFactors) { m_currentBlendStateBlendFactors = BlendFactor; glBlendColor(BlendFactor.r, BlendFactor.g, BlendFactor.b, BlendFactor.a); } } const RENDERER_VIEWPORT *OpenGLGPUContext::GetViewport() { return &m_currentViewport; } void OpenGLGPUContext::SetViewport(const RENDERER_VIEWPORT *pNewViewport) { if (Y_memcmp(&m_currentViewport, pNewViewport, sizeof(RENDERER_VIEWPORT)) == 0) return; Y_memcpy(&m_currentViewport, pNewViewport, sizeof(m_currentViewport)); glViewport(m_currentViewport.TopLeftX, m_currentViewport.TopLeftY, m_currentViewport.Width, m_currentViewport.Height); glDepthRange(m_currentViewport.MinDepth, m_currentViewport.MaxDepth); // update constants m_pConstants->SetViewportOffset((float)m_currentViewport.TopLeftX, (float)m_currentViewport.TopLeftY, false); m_pConstants->SetViewportSize((float)m_currentViewport.Width, (float)m_currentViewport.Height, false); m_pConstants->CommitChanges(); // fix scissor rect if (m_scissorRect.Top != m_scissorRect.Bottom) glScissor(m_scissorRect.Left, m_currentViewport.Height - m_scissorRect.Bottom, m_scissorRect.Right - m_scissorRect.Left, m_scissorRect.Bottom - m_scissorRect.Top); } void OpenGLGPUContext::SetFullViewport(GPUTexture *pForRenderTarget /*= NULL*/) { RENDERER_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; if (pForRenderTarget != nullptr) { uint3 renderTargetDimensions = Renderer::GetTextureDimensions(pForRenderTarget); viewport.Width = renderTargetDimensions.x; viewport.Height = renderTargetDimensions.y; } else if (m_nCurrentRenderTargets > 0 || m_pCurrentDepthStencilBuffer != nullptr) { uint3 renderTargetDimensions = Renderer::GetTextureDimensions((m_nCurrentRenderTargets > 0) ? m_pCurrentRenderTargets[0]->GetTargetTexture() : m_pCurrentDepthStencilBuffer->GetTargetTexture()); viewport.Width = renderTargetDimensions.x; viewport.Height = renderTargetDimensions.y; } else { viewport.Width = m_pCurrentOutputBuffer->GetWidth(); viewport.Height = m_pCurrentOutputBuffer->GetHeight(); } viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; SetViewport(&viewport); } const RENDERER_SCISSOR_RECT *OpenGLGPUContext::GetScissorRect() { return &m_scissorRect; } void OpenGLGPUContext::SetScissorRect(const RENDERER_SCISSOR_RECT *pScissorRect) { if (Y_memcmp(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)) == 0) return; Y_memcpy(&m_scissorRect, pScissorRect, sizeof(m_scissorRect)); glScissor(m_scissorRect.Left, m_currentViewport.Height - m_scissorRect.Bottom, m_scissorRect.Right - m_scissorRect.Left, m_scissorRect.Bottom - m_scissorRect.Top); } void OpenGLGPUContext::ClearTargets(bool clearColor /* = true */, bool clearDepth /* = true */, bool clearStencil /* = true */, const float4 &clearColorValue /* = float4::Zero */, float clearDepthValue /* = 1.0f */, uint8 clearStencilValue /* = 0 */) { bool oldColorWritesEnabled = (m_pCurrentBlendState == NULL) ? true : m_pCurrentBlendState->GetGLColorWritesEnabled(); GLboolean oldDepthMask = (m_pCurrentDepthStencilState == NULL) ? GL_TRUE : m_pCurrentDepthStencilState->GetGLDepthMask(); GLuint oldStencilMask = (m_pCurrentDepthStencilState == NULL) ? 0xFF : m_pCurrentDepthStencilState->GetGLStencilWriteMask(); bool oldScissorTest = (m_pCurrentRasterizerState == NULL) ? false : m_pCurrentRasterizerState->GetGLScissorTestEnable(); // change settings so the whole RT gets cleared if (!oldColorWritesEnabled) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if (oldDepthMask == GL_FALSE) glDepthMask(GL_TRUE); if (oldStencilMask != 0xFF) glStencilMask(0xFF); if (oldScissorTest) glDisable(GL_SCISSOR_TEST); // use new functions if using FBOs if (m_nCurrentRenderTargets != 0 || m_pCurrentDepthStencilBuffer != NULL) { uint32 i; if (clearColor) { for (i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargets[i] != NULL) glClearBufferfv(GL_COLOR, i, clearColorValue); } } if (m_pCurrentDepthStencilBuffer != NULL) { if (clearDepth && clearStencil) glClearBufferfi(GL_DEPTH_STENCIL, 0, clearDepthValue, clearStencilValue); else if (clearDepth) glClearBufferfv(GL_DEPTH, 0, &clearDepthValue); else if (clearStencil) { GLint clearStencilValueInt = (GLint)clearStencilValue; glClearBufferiv(GL_STENCIL, 0, &clearStencilValueInt); } } } else { GLbitfield clearMask = 0; if (clearColor) { glClearColor(clearColorValue.r, clearColorValue.g, clearColorValue.b, clearColorValue.a); clearMask |= GL_COLOR_BUFFER_BIT; } if (clearDepth) { glDepthMask(GL_TRUE); glClearDepth(clearDepthValue); clearMask |= GL_DEPTH_BUFFER_BIT; } if (clearStencil) { glClearStencil(clearStencilValue); clearMask |= GL_STENCIL_BUFFER_BIT; } if (clearMask != 0) glClear(clearMask); } // restore settings if (oldScissorTest) glEnable(GL_SCISSOR_TEST); if (oldStencilMask != 0xFF) glStencilMask(0xFF); if (oldDepthMask == GL_FALSE) glDepthMask(GL_FALSE); if (!oldColorWritesEnabled) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } void OpenGLGPUContext::DiscardTargets(bool discardColor /* = true */, bool discardDepth /* = true */, bool discardStencil /* = true */) { if (GLAD_GL_EXT_discard_framebuffer) { GLenum attachments[3]; uint32 nAttachments = 0; // ugh, multiple paths again??! if (m_nCurrentRenderTargets > 0 || m_pCurrentDepthStencilBuffer != nullptr) { if (discardColor) attachments[nAttachments++] = GL_COLOR_ATTACHMENT0; if (discardDepth) attachments[nAttachments++] = GL_DEPTH_ATTACHMENT; if (discardStencil) attachments[nAttachments++] = GL_STENCIL_ATTACHMENT; } else { if (discardColor) attachments[nAttachments++] = GL_COLOR_EXT; if (discardDepth) attachments[nAttachments++] = GL_DEPTH_EXT; if (discardStencil) attachments[nAttachments++] = GL_STENCIL_EXT; } glDiscardFramebufferEXT(GL_DRAW_FRAMEBUFFER, nAttachments, attachments); } } void OpenGLGPUContext::SetOutputBuffer(GPUOutputBuffer *pSwapChain) { OpenGLGPUOutputBuffer *pOpenGLOutputBuffer = static_cast<OpenGLGPUOutputBuffer *>(pSwapChain); DebugAssert(pOpenGLOutputBuffer != nullptr); // same? if (m_pCurrentOutputBuffer == pOpenGLOutputBuffer) return; // make this the new current context if (SDL_GL_MakeCurrent(pOpenGLOutputBuffer->GetSDLWindow(), m_pSDLGLContext) != 0) { Log_ErrorPrintf("OpenGLGPUContext::SetOutputBuffer: SDL_GL_MakeCurrent failed: %s", SDL_GetError()); Panic("SDL_GL_MakeCurrent failed"); } // update swap interval if (pOpenGLOutputBuffer->GetVSyncType() != m_pCurrentOutputBuffer->GetVSyncType()) UpdateVSyncState(pOpenGLOutputBuffer->GetVSyncType()); // update pointers m_pCurrentOutputBuffer->Release(); m_pCurrentOutputBuffer = pOpenGLOutputBuffer; m_pCurrentOutputBuffer->AddRef(); } bool OpenGLGPUContext::GetExclusiveFullScreen() { if (SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN) return true; else return false; } bool OpenGLGPUContext::SetExclusiveFullScreen(bool enabled, uint32 width, uint32 height, uint32 refreshRate) { if (enabled) { // find the matching sdl pixel format SDL_DisplayMode preferredDisplayMode; preferredDisplayMode.w = (width == 0) ? m_pCurrentOutputBuffer->GetWidth() : width; preferredDisplayMode.h = (height == 0) ? m_pCurrentOutputBuffer->GetHeight() : height; preferredDisplayMode.refresh_rate = refreshRate; preferredDisplayMode.driverdata = nullptr; // we only have a limited number of backbuffer format possibilities switch (m_pCurrentOutputBuffer->GetBackBufferFormat()) { case PIXEL_FORMAT_R8G8B8A8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_RGBA8888; break; case PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_RGBA8888; break; case PIXEL_FORMAT_B8G8R8A8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRA8888; break; case PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRA8888; break; case PIXEL_FORMAT_B8G8R8X8_UNORM: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRX8888; break; case PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB: preferredDisplayMode.format = SDL_PIXELFORMAT_BGRX8888; break; default: Log_ErrorPrintf("OpenGLGPUContext::SetExclusiveFullScreen: Unable to find SDL pixel format for %s", PixelFormat_GetPixelFormatInfo(m_pCurrentOutputBuffer->GetBackBufferFormat())->Name); return false; } // find the closest match SDL_DisplayMode foundDisplayMode; if (SDL_GetClosestDisplayMode(0, &preferredDisplayMode, &foundDisplayMode) == nullptr) { Log_ErrorPrintf("OpenGLGPUContext::SetExclusiveFullScreen: Unable to find matching video mode for: %i x %i (%s)", preferredDisplayMode.w, preferredDisplayMode.h, PixelFormat_GetPixelFormatInfo(m_pCurrentOutputBuffer->GetBackBufferFormat())->Name); return false; } // change to this mode if (SDL_SetWindowDisplayMode(m_pCurrentOutputBuffer->GetSDLWindow(), &foundDisplayMode) != 0) { Log_ErrorPrintf("OpenGLGPUContext::SetExclusiveFullScreen: SDL_SetWindowDisplayMode failed: %s", SDL_GetError()); return false; } // and switch to fullscreen if not already there if (!(SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN)) { if (SDL_SetWindowFullscreen(m_pCurrentOutputBuffer->GetSDLWindow(), SDL_WINDOW_FULLSCREEN) != 0) { Log_ErrorPrintf("OpenGLGPUContext::SetExclusiveFullScreen: SDL_SetWindowFullscreen failed: %s", SDL_GetError()); return false; } } // update the window size m_pCurrentOutputBuffer->Resize(foundDisplayMode.w, foundDisplayMode.h); return true; } else { // leaving fullscreen if (SDL_GetWindowFlags(m_pCurrentOutputBuffer->GetSDLWindow()) & SDL_WINDOW_FULLSCREEN) { if (SDL_SetWindowFullscreen(m_pCurrentOutputBuffer->GetSDLWindow(), 0) != 0) { Log_ErrorPrintf("OpenGLGPUContext::SetExclusiveFullScreen: SDL_SetWindowFullscreen failed: %s", SDL_GetError()); return false; } } // get window size int windowWidth, windowHeight; SDL_GetWindowSize(m_pCurrentOutputBuffer->GetSDLWindow(), &windowWidth, &windowHeight); m_pCurrentOutputBuffer->Resize(windowWidth, windowHeight); return true; } } bool OpenGLGPUContext::ResizeOutputBuffer(uint32 width /* = 0 */, uint32 height /* = 0 */) { // GL buffers are automatically resized m_pCurrentOutputBuffer->Resize(width, height); return true; } void OpenGLGPUContext::PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR presentBehaviour) { // @TODO: Present Behaviour SDL_GL_SwapWindow(m_pCurrentOutputBuffer->GetSDLWindow()); } void OpenGLGPUContext::BeginFrame() { } void OpenGLGPUContext::Flush() { glFlush(); } void OpenGLGPUContext::Finish() { glFinish(); } uint32 OpenGLGPUContext::GetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargetViews, GPUDepthStencilBufferView **ppDepthBufferView) { uint32 i; for (i = 0; i < m_nCurrentRenderTargets && i < nRenderTargets; i++) ppRenderTargetViews[i] = m_pCurrentRenderTargets[i]; if (ppDepthBufferView != nullptr) *ppDepthBufferView = m_pCurrentDepthStencilBuffer; return i; } static void BindRTVToFramebufferColorAttachment(GLenum frameBufferTarget, GLenum frameBufferAttachment, OpenGLGPURenderTargetView *pRTV) { switch (pRTV->GetTextureType()) { case TEXTURE_TYPE_1D: glFramebufferTexture1D(frameBufferTarget, frameBufferAttachment, GL_TEXTURE_1D, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel); break; case TEXTURE_TYPE_1D_ARRAY: (pRTV->IsMultiLayer()) ? glFramebufferTexture1D(frameBufferTarget, frameBufferAttachment, GL_TEXTURE_1D, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel) : glFramebufferTextureLayer(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel, pRTV->GetDesc()->FirstLayerIndex); break; case TEXTURE_TYPE_2D: glFramebufferTexture2D(frameBufferTarget, frameBufferAttachment, GL_TEXTURE_2D, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel); break; case TEXTURE_TYPE_2D_ARRAY: (pRTV->IsMultiLayer()) ? glFramebufferTexture2D(frameBufferTarget, frameBufferAttachment, GL_TEXTURE_2D, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel) : glFramebufferTextureLayer(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel, pRTV->GetDesc()->FirstLayerIndex); break; case TEXTURE_TYPE_3D: glFramebufferTexture3D(frameBufferTarget, frameBufferAttachment, GL_TEXTURE_3D, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel, pRTV->GetDesc()->FirstLayerIndex); break; case TEXTURE_TYPE_CUBE: (pRTV->IsMultiLayer()) ? glFramebufferTexture(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel) : glFramebufferTextureLayer(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel, pRTV->GetDesc()->FirstLayerIndex); break; case TEXTURE_TYPE_CUBE_ARRAY: (pRTV->IsMultiLayer()) ? glFramebufferTexture(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel) : glFramebufferTextureLayer(frameBufferTarget, frameBufferAttachment, pRTV->GetTextureName(), pRTV->GetDesc()->MipLevel, pRTV->GetDesc()->FirstLayerIndex); break; } } static void BindDSVToFramebufferDepthAttachment(GLenum frameBufferTarget, OpenGLGPUDepthStencilBufferView *pDSV) { switch (pDSV->GetTextureType()) { case TEXTURE_TYPE_2D: glFramebufferTexture2D(frameBufferTarget, pDSV->GetAttachmentPoint(), GL_TEXTURE_2D, pDSV->GetTextureName(), pDSV->GetDesc()->MipLevel); break; case TEXTURE_TYPE_2D_ARRAY: (pDSV->IsMultiLayer()) ? glFramebufferTexture2D(frameBufferTarget, pDSV->GetAttachmentPoint(), GL_TEXTURE_2D, pDSV->GetTextureName(), pDSV->GetDesc()->MipLevel) : glFramebufferTextureLayer(frameBufferTarget, pDSV->GetAttachmentPoint(), pDSV->GetTextureName(), pDSV->GetDesc()->MipLevel, pDSV->GetDesc()->FirstLayerIndex); break; case TEXTURE_TYPE_DEPTH: glFramebufferRenderbuffer(frameBufferTarget, pDSV->GetAttachmentPoint(), GL_RENDERBUFFER, pDSV->GetTextureName()); break; } } void OpenGLGPUContext::SetRenderTargets(uint32 nRenderTargets, GPURenderTargetView **ppRenderTargets, GPUDepthStencilBufferView *pDepthBufferView) { DebugAssert(nRenderTargets < GPU_MAX_SIMULTANEOUS_RENDER_TARGETS); // switch to swap chain? if ((nRenderTargets == 0 || (nRenderTargets == 1 && ppRenderTargets[0] == nullptr)) && pDepthBufferView == nullptr) { // currently using FBO? if (m_nCurrentRenderTargets > 0 || m_pCurrentDepthStencilBuffer != nullptr) { for (uint32 i = 0; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargets[i] != nullptr) { glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, 0, 0, 0); m_pCurrentRenderTargets[i]->Release(); m_pCurrentRenderTargets[i] = nullptr; } } m_nCurrentRenderTargets = 0; if (m_pCurrentDepthStencilBuffer != nullptr) { glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); m_pCurrentDepthStencilBuffer->Release(); m_pCurrentDepthStencilBuffer = nullptr; } glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } // disable srgb writes if the framebuffer is not srgb.. seems to be even though we didn't specify it :S if (!PixelFormatHelpers::IsSRGBFormat(m_pCurrentOutputBuffer->GetBackBufferFormat())) glDisable(GL_FRAMEBUFFER_SRGB); // rest of the path is unnecessary return; } // fbo bound? if (m_nCurrentRenderTargets == 0 && m_pCurrentDepthStencilBuffer == nullptr) { // set fbo glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_drawFrameBufferObjectId); // if the system framebuffer was not srgb, enable srgb writes if (!PixelFormatHelpers::IsSRGBFormat(m_pCurrentOutputBuffer->GetBackBufferFormat())) glEnable(GL_FRAMEBUFFER_SRGB); } // bind buffers for (uint32 i = 0; i < nRenderTargets; i++) { if (m_pCurrentRenderTargets[i] != ppRenderTargets[i]) { OpenGLGPURenderTargetView *pOldRenderTarget = m_pCurrentRenderTargets[i]; if ((m_pCurrentRenderTargets[i] = static_cast<OpenGLGPURenderTargetView *>(ppRenderTargets[i])) != nullptr) { m_pCurrentRenderTargets[i]->AddRef(); BindRTVToFramebufferColorAttachment(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, m_pCurrentRenderTargets[i]); if (pOldRenderTarget != nullptr) pOldRenderTarget->Release(); } else if (pOldRenderTarget != nullptr) { glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, 0, 0, 0); pOldRenderTarget->Release(); } } } // unbind remaining buffers for (uint32 i = nRenderTargets; i < m_nCurrentRenderTargets; i++) { if (m_pCurrentRenderTargets[i] != nullptr) { glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, 0, 0, 0); m_pCurrentRenderTargets[i]->Release(); m_pCurrentRenderTargets[i] = nullptr; } } m_nCurrentRenderTargets = nRenderTargets; if (m_pCurrentDepthStencilBuffer != pDepthBufferView) { OpenGLGPUDepthStencilBufferView *pOldDepthStencilBuffer = m_pCurrentDepthStencilBuffer; if ((m_pCurrentDepthStencilBuffer = static_cast<OpenGLGPUDepthStencilBufferView *>(pDepthBufferView)) != nullptr) { m_pCurrentDepthStencilBuffer->AddRef(); BindDSVToFramebufferDepthAttachment(GL_DRAW_FRAMEBUFFER, m_pCurrentDepthStencilBuffer); // unbind before bind if attachment changes? if (pOldDepthStencilBuffer != nullptr) pOldDepthStencilBuffer->Release(); } else if (pOldDepthStencilBuffer != nullptr) { glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, pOldDepthStencilBuffer->GetAttachmentPoint(), GL_RENDERBUFFER, 0); pOldDepthStencilBuffer->Release(); } } // check fbo completeness //GLenum status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); //DebugAssert(status == GL_FRAMEBUFFER_COMPLETE); DebugAssert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // set draw buffers static const GLenum drawBuffers[GPU_MAX_SIMULTANEOUS_RENDER_TARGETS] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7 }; glDrawBuffers(nRenderTargets, (nRenderTargets > 0) ? drawBuffers : NULL); // set state m_nCurrentRenderTargets = nRenderTargets; } DRAW_TOPOLOGY OpenGLGPUContext::GetDrawTopology() { return m_drawTopology; } void OpenGLGPUContext::SetDrawTopology(DRAW_TOPOLOGY topology) { DebugAssert(topology < DRAW_TOPOLOGY_COUNT); if (topology == m_drawTopology) return; m_drawTopology = topology; switch (topology) { case DRAW_TOPOLOGY_POINTS: m_glDrawTopology = GL_POINTS; break; case DRAW_TOPOLOGY_LINE_LIST: m_glDrawTopology = GL_LINES; break; case DRAW_TOPOLOGY_LINE_STRIP: m_glDrawTopology = GL_LINE_STRIP; break; case DRAW_TOPOLOGY_TRIANGLE_LIST: m_glDrawTopology = GL_TRIANGLES; break; case DRAW_TOPOLOGY_TRIANGLE_STRIP: m_glDrawTopology = GL_TRIANGLE_STRIP; break; } } uint32 OpenGLGPUContext::GetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer **ppVertexBuffers, uint32 *pVertexBufferOffsets, uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < m_currentVertexBuffers.GetSize()); uint32 count; for (count = 0; count < nBuffers; count++) { uint32 idx = firstBuffer + count; if (idx >= m_activeVertexBuffers) break; VertexBufferBinding *vb = &m_currentVertexBuffers[idx]; ppVertexBuffers[count] = vb->pVertexBuffer; pVertexBufferOffsets[count] = vb->Offset; pVertexBufferStrides[count] = vb->Stride; } return count; } void OpenGLGPUContext::SetVertexBuffers(uint32 firstBuffer, uint32 nBuffers, GPUBuffer *const *ppVertexBuffers, const uint32 *pVertexBufferOffsets, const uint32 *pVertexBufferStrides) { DebugAssert(firstBuffer + nBuffers < m_currentVertexBuffers.GetSize()); // update each buffer bool updateDirtyFlag = false; for (uint32 i = 0; i < nBuffers; i++) { uint32 bufferIndex = firstBuffer + i; VertexBufferBinding *vbBinding = &m_currentVertexBuffers[bufferIndex]; OpenGLGPUBuffer *pBuffer = static_cast<OpenGLGPUBuffer *>(ppVertexBuffers[i]); uint32 bufferOffset = pVertexBufferOffsets[i]; uint32 bufferStride = pVertexBufferStrides[i]; // any changes? if (vbBinding->pVertexBuffer != pBuffer || vbBinding->Offset != bufferOffset || vbBinding->Stride != bufferStride) { // buffer change? if (vbBinding->pVertexBuffer != pBuffer) { if (vbBinding->pVertexBuffer != nullptr) vbBinding->pVertexBuffer->Release(); if ((vbBinding->pVertexBuffer = pBuffer) != nullptr) { vbBinding->pVertexBuffer->AddRef(); vbBinding->Offset = pVertexBufferOffsets[i]; vbBinding->Stride = pVertexBufferStrides[i]; } else { vbBinding->Offset = 0; vbBinding->Stride = 0; } } // dirty flag vbBinding->Dirty = true; updateDirtyFlag = true; } } // update active range uint32 searchCount = Max(m_activeVertexBuffers, firstBuffer + nBuffers); uint32 activeCount = 0; for (uint32 i = 0; i < searchCount; i++) { const VertexBufferBinding *binding = &m_currentVertexBuffers[i]; if (binding->pVertexBuffer != nullptr || binding->Dirty) activeCount = i + 1; } m_activeVertexBuffers = activeCount; // dirty flag m_dirtyVertexBuffers |= updateDirtyFlag; } void OpenGLGPUContext::SetVertexBuffer(uint32 bufferIndex, GPUBuffer *pVertexBuffer, uint32 offset, uint32 stride) { DebugAssert(bufferIndex < m_currentVertexBuffers.GetSize()); VertexBufferBinding *vbBinding = &m_currentVertexBuffers[bufferIndex]; OpenGLGPUBuffer *pBuffer = static_cast<OpenGLGPUBuffer *>(pVertexBuffer); // any changes? if (vbBinding->pVertexBuffer != pBuffer || vbBinding->Offset != offset || vbBinding->Stride != stride) { // buffer change? if (vbBinding->pVertexBuffer != pBuffer) { if (vbBinding->pVertexBuffer != nullptr) vbBinding->pVertexBuffer->Release(); if ((vbBinding->pVertexBuffer = pBuffer) != nullptr) { vbBinding->pVertexBuffer->AddRef(); vbBinding->Offset = offset; vbBinding->Stride = stride; } else { vbBinding->Offset = 0; vbBinding->Stride = 0; } } // dirty flag vbBinding->Dirty = true; } else { // no changes return; } // update active range if (bufferIndex >= m_activeVertexBuffers) { m_activeVertexBuffers = bufferIndex + 1; } else if ((bufferIndex + 1) == m_activeVertexBuffers) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeVertexBuffers; i++) { const VertexBufferBinding *binding = &m_currentVertexBuffers[i]; if (binding->pVertexBuffer != nullptr || binding->Dirty) lastPos = i + 1; } m_activeVertexBuffers = lastPos; } // dirty flag m_dirtyVertexBuffers = true; } void OpenGLGPUContext::SetShaderVertexAttributes(const GPU_VERTEX_ELEMENT_DESC *pAttributeDescriptors, uint32 nAttributes) { uint32 attributeIndex; for (attributeIndex = 0; attributeIndex < nAttributes; attributeIndex++) { const GPU_VERTEX_ELEMENT_DESC *pAttributeDesc = &pAttributeDescriptors[attributeIndex]; VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; // convert to gl bool integerType; GLenum glType; GLint glSize; GLboolean glNormalized; OpenGLTypeConversion::GetOpenGLVAOTypeAndSizeForVertexElementType(pAttributeDesc->Type, &integerType, &glType, &glSize, &glNormalized); // handle format changes if (!pAttributeBinding->Initialized || pAttributeBinding->VertexBufferIndex != pAttributeDesc->StreamIndex || pAttributeBinding->Offset != pAttributeDesc->StreamOffset || pAttributeBinding->IntegerFormat != integerType || pAttributeBinding->Type != glType || pAttributeBinding->Size != glSize || pAttributeBinding->Normalized != glNormalized) { // initialize struct // todo: different dirty flags for each field (main, dividor, etc), worth it? pAttributeBinding->Initialized = true; pAttributeBinding->VertexBufferIndex = pAttributeDesc->StreamIndex; pAttributeBinding->Offset = pAttributeDesc->StreamOffset; pAttributeBinding->IntegerFormat = integerType; pAttributeBinding->Type = glType; pAttributeBinding->Size = glSize; pAttributeBinding->Normalized = glNormalized; pAttributeBinding->Dirty = true; m_dirtyVertexAttributes = true; } } // disable remaining attributes for (; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (pAttributeBinding->Initialized) { pAttributeBinding->VertexBufferIndex = 0; pAttributeBinding->Offset = 0; pAttributeBinding->Type = 0; pAttributeBinding->Size = 0; pAttributeBinding->Normalized = GL_FALSE; pAttributeBinding->Divisor = 0; pAttributeBinding->IntegerFormat = false; pAttributeBinding->Initialized = false; pAttributeBinding->Dirty = true; m_dirtyVertexAttributes = true; } } // update active count, keep it as low as possible m_activeVertexAttributes = Max(m_activeVertexAttributes, nAttributes); } void OpenGLGPUContext::CommitVertexAttributes() { if (!(m_dirtyVertexAttributes | m_dirtyVertexBuffers)) return; // using vertex formats? if (GLAD_GL_ARB_vertex_attrib_binding) { // fast path, handle vertex buffers and attributes separately if (m_dirtyVertexAttributes) { // fix up changed vertex attributes uint32 nActiveAttributes = 0; for (uint32 attributeIndex = 0; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (!pAttributeBinding->Dirty) { if (pAttributeBinding->Initialized) nActiveAttributes = attributeIndex + 1; continue; } if (pAttributeBinding->Initialized) { if (pAttributeBinding->IntegerFormat) glVertexAttribIFormat(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pAttributeBinding->Offset); else glVertexAttribFormat(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pAttributeBinding->Normalized, pAttributeBinding->Offset); glVertexAttribDivisor(attributeIndex, pAttributeBinding->Divisor); glVertexAttribBinding(attributeIndex, pAttributeBinding->VertexBufferIndex); // determine whether it should be enabled bool enabledState = (m_currentVertexBuffers[pAttributeBinding->VertexBufferIndex].pVertexBuffer != nullptr); if (pAttributeBinding->Enabled != enabledState) { pAttributeBinding->Enabled = enabledState; if (enabledState) { // enable attribute glEnableVertexAttribArray(attributeIndex); } else { // disable it and warn //Log_WarningPrintf("OpenGLGPUContext::CommitVertexAttributes: Attribute %u is referencing vertex buffer %u with no buffer bound. Disabling attribute.", attributeIndex, pAttributeBinding->VertexBufferIndex); glDisableVertexAttribArray(attributeIndex); } } // update max index nActiveAttributes = attributeIndex + 1; } else { // disable now-non-existant vertex attributes if (pAttributeBinding->Enabled) { glDisableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = false; } } // clear dirty flag pAttributeBinding->Dirty = false; } // update stored max index m_activeVertexAttributes = nActiveAttributes; m_dirtyVertexAttributes = false; } // handle buffer changes if (m_dirtyVertexBuffers) { // vertex buffers changed: TODO USE MULTI BIND HERE? // find dirty vertex buffers for (uint32 vertexBufferIndex = 0; vertexBufferIndex < m_activeVertexBuffers; vertexBufferIndex++) { VertexBufferBinding *pVertexBufferBinding = &m_currentVertexBuffers[vertexBufferIndex]; if (!pVertexBufferBinding->Dirty) continue; // have a buffer? if (pVertexBufferBinding->pVertexBuffer != nullptr) { // change the pointer glBindVertexBuffer(vertexBufferIndex, pVertexBufferBinding->pVertexBuffer->GetGLBufferId(), pVertexBufferBinding->Offset, pVertexBufferBinding->Stride); } else { // if enabled, disable it glBindVertexBuffer(vertexBufferIndex, 0, 0, 0); } // remove dirty flag pVertexBufferBinding->Dirty = false; } // disable attributes that match an unbound vertex buffer, the nvidia gl driver at least crashes on draw if an unbound vertex buffer isn't disabled for (uint32 attributeIndex = 0; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (!pAttributeBinding->Initialized) continue; VertexBufferBinding *pVertexBufferBinding = &m_currentVertexBuffers[pAttributeBinding->VertexBufferIndex]; bool enabledState = (pVertexBufferBinding->pVertexBuffer != nullptr); if (pAttributeBinding->Enabled != enabledState) { pAttributeBinding->Enabled = enabledState; if (enabledState) { // enable attribute glEnableVertexAttribArray(attributeIndex); } else { // disable it and warn //Log_WarningPrintf("OpenGLGPUContext::CommitVertexAttributes: Attribute %u is referencing vertex buffer %u with no buffer bound. Disabling attribute.", attributeIndex, pAttributeBinding->VertexBufferIndex); glDisableVertexAttribArray(attributeIndex); } } } // or globally m_dirtyVertexBuffers = false; } } else { // slow path uint32 lastBufferIndex = 0xFFFFFFFF; uint32 nActiveAttributes = 0; for (uint32 attributeIndex = 0; attributeIndex < m_activeVertexAttributes; attributeIndex++) { VertexAttributeBinding *pAttributeBinding = &m_currentVertexAttributes[attributeIndex]; if (!pAttributeBinding->Initialized) { // non-initialized attributes, should be disabled, could also check dirty flag here too if (pAttributeBinding->Enabled) { glDisableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = false; pAttributeBinding->Dirty = false; } // skip continue; } // skip non-dirty attributes+buffers const VertexBufferBinding *pVertexBufferBinding = &m_currentVertexBuffers[pAttributeBinding->VertexBufferIndex]; if (!(pAttributeBinding->Dirty | pVertexBufferBinding->Dirty)) { nActiveAttributes = attributeIndex + 1; continue; } // determine whether it should be enabled if (pVertexBufferBinding->pVertexBuffer != nullptr) { // should it be enabled? if (lastBufferIndex != pAttributeBinding->VertexBufferIndex) { glBindBuffer(GL_ARRAY_BUFFER, pVertexBufferBinding->pVertexBuffer->GetGLBufferId()); lastBufferIndex = pAttributeBinding->VertexBufferIndex; } // set the pointer if (pAttributeBinding->IntegerFormat) glVertexAttribIPointer(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pVertexBufferBinding->Stride, reinterpret_cast<const void *>(pVertexBufferBinding->Offset + pAttributeBinding->Offset)); else glVertexAttribPointer(attributeIndex, pAttributeBinding->Size, pAttributeBinding->Type, pAttributeBinding->Normalized, pVertexBufferBinding->Stride, reinterpret_cast<const void *>(pVertexBufferBinding->Offset + pAttributeBinding->Offset)); // and divisor glVertexAttribDivisor(attributeIndex, pAttributeBinding->Divisor); // enable attribute if (!pAttributeBinding->Enabled) { glEnableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = true; } // update max index nActiveAttributes = attributeIndex + 1; } else { // disable attribute if enabled if (pAttributeBinding->Enabled) { glDisableVertexAttribArray(attributeIndex); pAttributeBinding->Enabled = false; } } // clear dirty flag on attribute pAttributeBinding->Dirty = false; } // clear buffer binding if (lastBufferIndex != 0xFFFFFFFF) glBindBuffer(GL_ARRAY_BUFFER, 0); // flag all vertex buffers as clean for (uint32 vertexBufferIndex = 0; vertexBufferIndex < m_activeVertexBuffers; vertexBufferIndex++) m_currentVertexBuffers[vertexBufferIndex].Dirty = false; } // and the global flags m_dirtyVertexAttributes = false; m_dirtyVertexBuffers = false; } void OpenGLGPUContext::GetIndexBuffer(GPUBuffer **ppBuffer, GPU_INDEX_FORMAT *pFormat, uint32 *pOffset) { *ppBuffer = m_pCurrentIndexBuffer; *pFormat = m_currentIndexFormat; *pOffset = m_currentIndexBufferOffset; } void OpenGLGPUContext::SetIndexBuffer(GPUBuffer *pBuffer, GPU_INDEX_FORMAT format, uint32 offset) { if (m_pCurrentIndexBuffer == pBuffer && m_currentIndexFormat == format && m_currentIndexBufferOffset == offset) return; GPUBuffer *pOldIndexBuffer = m_pCurrentIndexBuffer; if ((m_pCurrentIndexBuffer = static_cast<OpenGLGPUBuffer *>(pBuffer)) != NULL) { m_pCurrentIndexBuffer->AddRef(); m_currentIndexFormat = format; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_pCurrentIndexBuffer->GetGLBufferId()); } else { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_currentIndexFormat = GPU_INDEX_FORMAT_UINT16; } if (pOldIndexBuffer != NULL) pOldIndexBuffer->Release(); } void OpenGLGPUContext::SetShaderProgram(GPUShaderProgram *pShaderProgram) { if (m_pCurrentShaderProgram == pShaderProgram) return; OpenGLGPUShaderProgram *pGLShaderProgram = static_cast<OpenGLGPUShaderProgram *>(pShaderProgram); if (m_pCurrentShaderProgram != nullptr && pGLShaderProgram != nullptr) { pGLShaderProgram->Switch(this, m_pCurrentShaderProgram); m_pCurrentShaderProgram->Release(); m_pCurrentShaderProgram = pGLShaderProgram; m_pCurrentShaderProgram->AddRef(); } else { if (m_pCurrentShaderProgram != nullptr) { m_pCurrentShaderProgram->Unbind(this); m_pCurrentShaderProgram->Release(); } if ((m_pCurrentShaderProgram = pGLShaderProgram) != nullptr) { m_pCurrentShaderProgram->Bind(this); m_pCurrentShaderProgram->AddRef(); } } } void OpenGLGPUContext::SetShaderParameterValue(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValue(this, index, valueType, pValue); } void OpenGLGPUContext::SetShaderParameterValueArray(uint32 index, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterValueArray(this, index, valueType, pValue, firstElement, numElements); } void OpenGLGPUContext::SetShaderParameterStruct(uint32 index, const void *pValue, uint32 valueSize) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStruct(this, index, pValue, valueSize); } void OpenGLGPUContext::SetShaderParameterStructArray(uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterStructArray(this, index, pValue, valueSize, firstElement, numElements); } void OpenGLGPUContext::SetShaderParameterResource(uint32 index, GPUResource *pResource) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pResource, nullptr); } void OpenGLGPUContext::SetShaderParameterTexture(uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->InternalSetParameterResource(this, index, pTexture, static_cast<OpenGLGPUSamplerState *>(pSamplerState)); } OpenGLGPUBuffer *OpenGLGPUContext::GetConstantBuffer(uint32 index) { ConstantBuffer *constantBuffer = &m_constantBuffers[index]; if (constantBuffer->Size == 0) return nullptr; if (constantBuffer->pGPUBuffer == nullptr) { // lazy create? if (constantBuffer->pLocalMemory == nullptr) constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; // create the gpu buffer GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER | GPU_BUFFER_FLAG_WRITABLE, constantBuffer->Size); constantBuffer->pGPUBuffer = static_cast<OpenGLGPUBuffer *>(m_pDevice->CreateBuffer(&bufferDesc, constantBuffer->pLocalMemory)); if (constantBuffer->pGPUBuffer == nullptr) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(index); Log_ErrorPrintf("OpenGLGPUContext::GetConstantBuffer: Failed to lazy-allocate constant buffer %u (%s)", index, declaration->GetBufferName()); return nullptr; } } return constantBuffer->pGPUBuffer; } bool OpenGLGPUContext::CreateConstantBuffers() { uint32 memoryUsage = 0; uint32 activeCount = 0; // allocate constant buffer storage const ShaderConstantBuffer::RegistryType *registry = ShaderConstantBuffer::GetRegistry(); m_constantBuffers.Resize(registry->GetNumTypes()); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; constantBuffer->pGPUBuffer = nullptr; constantBuffer->Size = 0; constantBuffer->pLocalMemory = nullptr; constantBuffer->DirtyLowerBounds = constantBuffer->DirtyUpperBounds = -1; // applicable to us? const ShaderConstantBuffer *declaration = registry->GetTypeInfoByIndex(i); if (declaration == nullptr) continue; if (declaration->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && declaration->GetPlatformRequirement() != RENDERER_PLATFORM_OPENGL) continue; if (declaration->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && declaration->GetMinimumFeatureLevel() > m_pDevice->GetFeatureLevel()) continue; // set size so we know to allocate it later or on demand constantBuffer->Size = declaration->GetBufferSize(); // stats memoryUsage += constantBuffer->Size; activeCount++; } // preallocate constant buffers, todo lazy allocation Log_DevPrintf("Preallocating %u constant buffers, total VRAM usage: %u bytes", activeCount, memoryUsage); for (uint32 i = 0; i < m_constantBuffers.GetSize(); i++) { ConstantBuffer *constantBuffer = &m_constantBuffers[i]; if (constantBuffer->Size == 0) continue; // allocate local memory first (so we can use it as initialization data) constantBuffer->pLocalMemory = new byte[constantBuffer->Size]; Y_memzero(constantBuffer->pLocalMemory, constantBuffer->Size); // create the gpu buffer GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER | GPU_BUFFER_FLAG_WRITABLE, constantBuffer->Size); constantBuffer->pGPUBuffer = static_cast<OpenGLGPUBuffer *>(m_pDevice->CreateBuffer(&bufferDesc, constantBuffer->pLocalMemory)); if (constantBuffer->pGPUBuffer == nullptr) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(i); Log_ErrorPrintf("OpenGLGPUContext::CreateResources: Failed to allocate constant buffer %u (%s)", i, declaration->GetBufferName()); return false; } } return true; } void OpenGLGPUContext::WriteConstantBuffer(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 count, const void *pData, bool commit) { ConstantBuffer *constantBuffer = &m_constantBuffers[bufferIndex]; if (constantBuffer->pGPUBuffer == nullptr) { // buffer non-existant and creation has previously failed? if (constantBuffer->pLocalMemory == nullptr) return; } // changed? DebugAssert(count > 0 && (offset + count) <= constantBuffer->Size); if (Y_memcmp(constantBuffer->pLocalMemory + offset, pData, count) != 0) { // write it Y_memcpy(constantBuffer->pLocalMemory + offset, pData, count); // update dirty pointer if (constantBuffer->DirtyLowerBounds < 0) { constantBuffer->DirtyLowerBounds = (int32)offset; constantBuffer->DirtyUpperBounds = (int32)(offset + count); } else { constantBuffer->DirtyLowerBounds = Min(constantBuffer->DirtyLowerBounds, (int32)offset); constantBuffer->DirtyUpperBounds = Max(constantBuffer->DirtyUpperBounds, (int32)(offset + count - 1)); } // commit buffer? if (commit) OpenGLGPUContext::CommitConstantBuffer(bufferIndex); } } void OpenGLGPUContext::WriteConstantBufferStrided(uint32 bufferIndex, uint32 fieldIndex, uint32 offset, uint32 bufferStride, uint32 copySize, uint32 count, const void *pData, bool commit) { ConstantBuffer *constantBuffer = &m_constantBuffers[bufferIndex]; if (constantBuffer->pGPUBuffer == nullptr) { // buffer non-existant and creation has previously failed? if (constantBuffer->pLocalMemory == nullptr) return; } // changed? DebugAssert(count > 0 && (offset + count) <= constantBuffer->Size); if (Y_memcmp_stride(constantBuffer->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count) != 0) { // write it Y_memcpy_stride(constantBuffer->pLocalMemory + offset, bufferStride, pData, copySize, copySize, count); // update dirty pointer uint32 writtenCount = bufferStride * count; if (constantBuffer->DirtyLowerBounds < 0) { constantBuffer->DirtyLowerBounds = (int32)offset; constantBuffer->DirtyUpperBounds = (int32)(offset + writtenCount); } else { constantBuffer->DirtyLowerBounds = Min(constantBuffer->DirtyLowerBounds, (int32)offset); constantBuffer->DirtyUpperBounds = Max(constantBuffer->DirtyUpperBounds, (int32)(offset + writtenCount - 1)); } // commit buffer? if (commit) OpenGLGPUContext::CommitConstantBuffer(bufferIndex); } } void OpenGLGPUContext::CommitConstantBuffer(uint32 bufferIndex) { ConstantBuffer *constantBuffer = &m_constantBuffers[bufferIndex]; if (constantBuffer->DirtyLowerBounds < 0) return; DebugAssert(constantBuffer->pGPUBuffer != nullptr); WriteBuffer(constantBuffer->pGPUBuffer, constantBuffer->pLocalMemory + constantBuffer->DirtyLowerBounds, constantBuffer->DirtyLowerBounds, constantBuffer->DirtyUpperBounds - constantBuffer->DirtyLowerBounds); constantBuffer->DirtyLowerBounds = constantBuffer->DirtyUpperBounds = -1; } void OpenGLGPUContext::SetShaderUniformBlock(uint32 index, OpenGLGPUBuffer *pBuffer) { if (m_currentUniformBlockBindings[index] == pBuffer) return; #if DEFER_SHADER_STATE_CHANGES // update dirty range if (m_dirtyUniformBlockBindingsLowerBounds < 0) { m_dirtyUniformBlockBindingsLowerBounds = m_dirtyUniformBlockBindingsUpperBounds = (int32)index; } else { m_dirtyUniformBlockBindingsLowerBounds = Min(m_dirtyUniformBlockBindingsLowerBounds, (int32)index); m_dirtyUniformBlockBindingsUpperBounds = Max(m_dirtyUniformBlockBindingsUpperBounds, (int32)index); } #else // bind new buffer if (pBuffer != nullptr) glBindBufferRange(GL_UNIFORM_BUFFER, index, pBuffer->GetGLBufferId(), 0, pBuffer->GetDesc()->Size); else glBindBufferRange(GL_UNIFORM_BUFFER, index, 0, 0, 0); #endif // update references if (m_currentUniformBlockBindings[index] != nullptr) m_currentUniformBlockBindings[index]->Release(); if ((m_currentUniformBlockBindings[index] = pBuffer) != nullptr) pBuffer->AddRef(); // update counters if (pBuffer != nullptr) { if (index >= m_activeUniformBlockBindings) m_activeUniformBlockBindings = index + 1; } else { if ((index + 1) == m_activeUniformBlockBindings) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeUniformBlockBindings; i++) { if (m_currentUniformBlockBindings[i] != nullptr) lastPos = i + 1; } m_activeUniformBlockBindings = lastPos; } } } void OpenGLGPUContext::SetShaderTextureUnit(uint32 index, GPUTexture *pTexture, OpenGLGPUSamplerState *pSamplerState) { TextureUnitBinding *texUnitState = &m_currentTextureUnitBindings[index]; #if DEFER_SHADER_STATE_CHANGES if (texUnitState->pTexture == pTexture && texUnitState->pSampler == pSamplerState) return; if (texUnitState->pTexture != pTexture) { // release the old (if any) texture reference if (texUnitState->pTexture != nullptr) texUnitState->pTexture->Release(); if ((texUnitState->pTexture = pTexture) != nullptr) texUnitState->pTexture->AddRef(); } if (texUnitState->pSampler != pSamplerState) { if (texUnitState->pSampler != nullptr) texUnitState->pSampler->Release(); if ((texUnitState->pSampler = pSamplerState) != nullptr) texUnitState->pSampler->AddRef(); } // update dirty range if (m_dirtyTextureUnitsLowerBounds < 0) { m_dirtyTextureUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = (int32)index; } else { m_dirtyTextureUnitsLowerBounds = Min(m_dirtyTextureUnitsLowerBounds, (int32)index); m_dirtyTextureUnitsUpperBounds = Max(m_dirtyTextureUnitsUpperBounds, (int32)index); } #else // texture changed? if (texUnitState->pTexture != pTexture) { // alter the binding glActiveTexture(GL_TEXTURE0 + index); OpenGLHelpers::BindOpenGLTexture(pTexture); glActiveTexture(GL_TEXTURE0); } // sampler change? if (texUnitState->pSampler != pSamplerState) { // bind the sampler state override if provided if (pSamplerState != nullptr) { glBindSampler(index, pSamplerState->GetGLSamplerID()); if (texUnitState->pSampler != nullptr) texUnitState->pSampler->Release(); texUnitState->pSampler = pSamplerState; texUnitState->pSampler->AddRef(); } else if (texUnitState->pSampler != nullptr) { glBindSampler(index, 0); texUnitState->pSampler->Release(); texUnitState->pSampler = nullptr; } } #endif // update counters if (pTexture != nullptr) { if (index >= m_activeTextureUnitBindings) m_activeTextureUnitBindings = index + 1; } else { if ((index + 1) == m_activeTextureUnitBindings) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeTextureUnitBindings; i++) { if (m_currentTextureUnitBindings[i].pTexture != nullptr) lastPos = i + 1; } m_activeTextureUnitBindings = lastPos; } } } void OpenGLGPUContext::SetShaderImageUnit(uint32 index, GPUTexture *pTexture) { if (m_currentImageUnitBindings[index] == pTexture) return; // update dirty range if (m_dirtyImageUnitsLowerBounds < 0) { m_dirtyImageUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = (int32)index; } else { m_dirtyTextureUnitsLowerBounds = Min(m_dirtyTextureUnitsLowerBounds, (int32)index); m_dirtyTextureUnitsUpperBounds = Max(m_dirtyTextureUnitsUpperBounds, (int32)index); } // update references if (m_currentImageUnitBindings[index] != nullptr) m_currentImageUnitBindings[index]->Release(); if ((m_currentImageUnitBindings[index] = pTexture) != nullptr) pTexture->AddRef(); // update counters if (pTexture != nullptr) { if (index >= m_activeImageUnitBindings) m_activeImageUnitBindings = index + 1; } else { if ((index + 1) == m_activeImageUnitBindings) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeImageUnitBindings; i++) { if (m_currentImageUnitBindings[i] != nullptr) lastPos = i + 1; } m_activeImageUnitBindings = lastPos; } } } void OpenGLGPUContext::SetShaderStorageBuffer(uint32 index, GPUResource *pResource) { if (m_currentShaderStorageBufferBindings[index] == pResource) return; #if DEFER_SHADER_STATE_CHANGES // update dirty range if (m_dirtyShaderStorageBuffersLowerBounds < 0) { m_dirtyShaderStorageBuffersLowerBounds = m_dirtyShaderStorageBuffersUpperBounds = (int32)index; } else { m_dirtyShaderStorageBuffersLowerBounds = Min(m_dirtyShaderStorageBuffersLowerBounds, (int32)index); m_dirtyShaderStorageBuffersUpperBounds = Max(m_dirtyShaderStorageBuffersUpperBounds, (int32)index); } #else // bind new buffer if (pResource != nullptr) { switch (pResource->GetResourceType()) { case GPU_RESOURCE_TYPE_BUFFER: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, static_cast<OpenGLGPUBuffer *>(pResource)->GetGLBufferId(), 0, static_cast<OpenGLGPUBuffer *>(pResource)->GetDesc()->Size); break; default: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, 0, 0, 0); break; } } else { glBindBufferRange(GL_SHADER_STORAGE_BUFFER, index, 0, 0, 0); } #endif // update references if (m_currentShaderStorageBufferBindings[index] != nullptr) m_currentShaderStorageBufferBindings[index]->Release(); if ((m_currentShaderStorageBufferBindings[index] = pResource) != nullptr) pResource->AddRef(); // update counters if (pResource != nullptr) { if (index >= m_activeShaderStorageBufferBindings) m_activeShaderStorageBufferBindings = index + 1; } else { if ((index + 1) == m_activeShaderStorageBufferBindings) { uint32 lastPos = 0; for (uint32 i = 0; i < m_activeShaderStorageBufferBindings; i++) { if (m_currentShaderStorageBufferBindings[i] != nullptr) lastPos = i + 1; } m_activeShaderStorageBufferBindings = lastPos; } } } void OpenGLGPUContext::CommitShaderResources() { if (GLAD_GL_ARB_multi_bind) { // uniform blocks if (m_dirtyUniformBlockBindingsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyUniformBlockBindingsUpperBounds - m_dirtyUniformBlockBindingsLowerBounds + 1); GLuint *pBufferIDs = (GLuint *)alloca(sizeof(GLuint) * countToBind); GLintptr *pBufferOffsets = (GLintptr *)alloca(sizeof(GLintptr) * countToBind); GLsizeiptr *pBufferSizes = (GLsizeiptr *)alloca(sizeof(GLsizeiptr) * countToBind); for (uint32 i = 0; i < countToBind; i++) { OpenGLGPUBuffer *pBuffer = m_currentUniformBlockBindings[m_dirtyUniformBlockBindingsLowerBounds + i]; if (pBuffer != nullptr) { pBufferIDs[i] = pBuffer->GetGLBufferId(); pBufferOffsets[i] = 0; pBufferSizes[i] = pBuffer->GetDesc()->Size; } else { // ugh. this seems to be picky, the size has to be >0, even if the buffer is null... //pBufferIDs[i] = 0; //pBufferOffsets[i] = 0; //pBufferSizes[i] = 0; // for now, stuff it, we'll just do the slow path if we hit a null for (uint32 j = 0; j < countToBind; j++) { OpenGLGPUBuffer *pInnerBuffer = m_currentUniformBlockBindings[m_dirtyUniformBlockBindingsLowerBounds + j]; if (pInnerBuffer != nullptr) glBindBufferRange(GL_UNIFORM_BUFFER, m_dirtyUniformBlockBindingsLowerBounds + j, pInnerBuffer->GetGLBufferId(), 0, pInnerBuffer->GetDesc()->Size); else glBindBufferRange(GL_UNIFORM_BUFFER, m_dirtyUniformBlockBindingsLowerBounds + j, 0, 0, 0); } countToBind = 0; } } // send them across if (countToBind > 0) glBindBuffersRange(GL_UNIFORM_BUFFER, m_dirtyUniformBlockBindingsLowerBounds, countToBind, pBufferIDs, pBufferOffsets, pBufferSizes); m_dirtyUniformBlockBindingsLowerBounds = m_dirtyUniformBlockBindingsUpperBounds = -1; } // texture units if (m_dirtyTextureUnitsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyTextureUnitsUpperBounds - m_dirtyTextureUnitsLowerBounds + 1); GLuint *pTextureIDs = (GLuint *)alloca(sizeof(GLuint) * countToBind); GLuint *pSamplerIDs = (GLuint *)alloca(sizeof(GLuint) * countToBind); for (uint32 i = 0; i < countToBind; i++) { TextureUnitBinding *texUnitBinding = &m_currentTextureUnitBindings[m_dirtyTextureUnitsLowerBounds + i]; pTextureIDs[i] = (texUnitBinding->pTexture != nullptr) ? OpenGLHelpers::GetOpenGLTextureId(texUnitBinding->pTexture) : 0; pSamplerIDs[i] = (texUnitBinding->pSampler != nullptr) ? texUnitBinding->pSampler->GetGLSamplerID() : 0; } // send them across glBindTextures(m_dirtyTextureUnitsLowerBounds, countToBind, pTextureIDs); glBindSamplers(m_dirtyTextureUnitsLowerBounds, countToBind, pSamplerIDs); m_dirtyTextureUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = -1; } // image units if (m_dirtyImageUnitsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyImageUnitsUpperBounds - m_dirtyImageUnitsLowerBounds + 1); GLuint *pTextureIDs = (GLuint *)alloca(sizeof(GLuint) * countToBind); for (uint32 i = 0; i < countToBind; i++) { GPUTexture *pTexture = m_currentImageUnitBindings[i]; if (pTexture != nullptr) pTextureIDs[i] = OpenGLHelpers::GetOpenGLTextureId(pTexture); else pTextureIDs[i] = 0; } // send them across -- fixme on this one... glBindImageTextures(m_dirtyImageUnitsLowerBounds, countToBind, pTextureIDs); m_dirtyImageUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = -1; } // shader storage blocks if (m_dirtyShaderStorageBuffersLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyShaderStorageBuffersUpperBounds - m_dirtyShaderStorageBuffersLowerBounds + 1); GLuint *pBufferIDs = (GLuint *)alloca(sizeof(GLuint) * countToBind); GLintptr *pBufferOffsets = (GLintptr *)alloca(sizeof(GLintptr) * countToBind); GLsizeiptr *pBufferSizes = (GLsizeiptr *)alloca(sizeof(GLsizeiptr) * countToBind); for (uint32 i = 0; i < countToBind; i++) { GPUResource *pResource = m_currentShaderStorageBufferBindings[m_dirtyShaderStorageBuffersLowerBounds + i]; switch ((pResource != nullptr) ? pResource->GetResourceType() : GPU_RESOURCE_TYPE_COUNT) { case GPU_RESOURCE_TYPE_BUFFER: pBufferIDs[i] = static_cast<OpenGLGPUBuffer *>(pResource)->GetGLBufferId(); pBufferOffsets[i] = 0; pBufferSizes[i] = static_cast<OpenGLGPUBuffer *>(pResource)->GetDesc()->Size; break; default: { // ugh. this seems to be picky, the size has to be >0, even if the buffer is null... //pBufferIDs[i] = 0; //pBufferOffsets[i] = 0; //pBufferSizes[i] = 0; // for now, stuff it, we'll just do the slow path if we hit a null for (uint32 j = 0; j < countToBind; j++) { GPUResource *pInnerResource = m_currentShaderStorageBufferBindings[m_dirtyShaderStorageBuffersLowerBounds + j]; switch ((pInnerResource != nullptr) ? pInnerResource->GetResourceType() : GPU_RESOURCE_TYPE_COUNT) { case GPU_RESOURCE_TYPE_BUFFER: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, m_dirtyShaderStorageBuffersLowerBounds + j, static_cast<OpenGLGPUBuffer *>(pInnerResource)->GetGLBufferId(), 0, static_cast<OpenGLGPUBuffer *>(pInnerResource)->GetDesc()->Size); break; default: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, m_dirtyShaderStorageBuffersLowerBounds + j, 0, 0, 0); break; } } countToBind = 0; } break; } } // send them across if (countToBind > 0) glBindBuffersRange(GL_SHADER_STORAGE_BUFFER, m_dirtyShaderStorageBuffersLowerBounds, countToBind, pBufferIDs, pBufferOffsets, pBufferSizes); m_dirtyShaderStorageBuffersLowerBounds = m_dirtyShaderStorageBuffersUpperBounds = -1; } } else { // uniform blocks if (m_dirtyUniformBlockBindingsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyUniformBlockBindingsUpperBounds - m_dirtyUniformBlockBindingsLowerBounds + 1); for (uint32 i = 0; i < countToBind; i++) { OpenGLGPUBuffer *pBuffer = m_currentUniformBlockBindings[m_dirtyUniformBlockBindingsLowerBounds + i]; if (pBuffer != nullptr) glBindBufferRange(GL_UNIFORM_BUFFER, m_dirtyUniformBlockBindingsLowerBounds + i, pBuffer->GetGLBufferId(), 0, pBuffer->GetDesc()->Size); else glBindBufferRange(GL_UNIFORM_BUFFER, m_dirtyUniformBlockBindingsLowerBounds + i, 0, 0, 0); } // reset dirty range m_dirtyUniformBlockBindingsLowerBounds = m_dirtyUniformBlockBindingsUpperBounds = -1; } // texture units if (m_dirtyTextureUnitsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyTextureUnitsUpperBounds - m_dirtyTextureUnitsLowerBounds + 1); for (uint32 i = 0; i < countToBind; i++) { TextureUnitBinding *texUnitBinding = &m_currentTextureUnitBindings[m_dirtyTextureUnitsLowerBounds + i]; glActiveTexture(GL_TEXTURE0 + m_dirtyTextureUnitsLowerBounds + i); OpenGLHelpers::BindOpenGLTexture(texUnitBinding->pTexture); glBindSampler(m_dirtyTextureUnitsLowerBounds + i, (texUnitBinding->pSampler != nullptr) ? texUnitBinding->pSampler->GetGLSamplerID() : 0); } glActiveTexture(GL_TEXTURE0); // reset dirty range m_dirtyTextureUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = -1; } // image units if (m_dirtyImageUnitsLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyImageUnitsUpperBounds - m_dirtyImageUnitsLowerBounds + 1); for (uint32 i = 0; i < countToBind; i++) { //GPUTexture *pTexture = m_currentImageUnitBindings[i]; //glBindImageTexture(i, OpenGLHelpers::GetOpenGLTextureId(pTexture), 0, GL_FALSE, 0, } // reset dirty range m_dirtyImageUnitsLowerBounds = m_dirtyTextureUnitsUpperBounds = -1; } // shader storage blocks if (m_dirtyShaderStorageBuffersLowerBounds >= 0) { uint32 countToBind = (uint32)(m_dirtyShaderStorageBuffersUpperBounds - m_dirtyShaderStorageBuffersLowerBounds + 1); for (uint32 i = 0; i < countToBind; i++) { GPUResource *pResource = m_currentShaderStorageBufferBindings[m_dirtyShaderStorageBuffersLowerBounds + i]; switch ((pResource != nullptr) ? pResource->GetResourceType() : GPU_RESOURCE_TYPE_COUNT) { case GPU_RESOURCE_TYPE_BUFFER: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, m_dirtyShaderStorageBuffersLowerBounds + i, static_cast<OpenGLGPUBuffer *>(pResource)->GetGLBufferId(), 0, static_cast<OpenGLGPUBuffer *>(pResource)->GetDesc()->Size); break; default: glBindBufferRange(GL_SHADER_STORAGE_BUFFER, m_dirtyShaderStorageBuffersLowerBounds + i, 0, 0, 0); break; } } // reset dirty range m_dirtyShaderStorageBuffersLowerBounds = m_dirtyShaderStorageBuffersUpperBounds = -1; } } } void OpenGLGPUContext::BindMutatorTextureUnit() { glActiveTexture(GL_TEXTURE0 + m_mutatorTextureUnit); } void OpenGLGPUContext::RestoreMutatorTextureUnit() { OpenGLHelpers::BindOpenGLTexture(m_currentTextureUnitBindings[m_mutatorTextureUnit].pTexture); glActiveTexture(GL_TEXTURE0); } void OpenGLGPUContext::Draw(uint32 firstVertex, uint32 nVertices) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nVertices == 0) return; CommitVertexAttributes(); m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); glDrawArrays(m_glDrawTopology, firstVertex, nVertices); //m_drawCallCounter++; } void OpenGLGPUContext::DrawInstanced(uint32 firstVertex, uint32 nVertices, uint32 nInstances) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nVertices == 0 || nInstances == 0) return; CommitVertexAttributes(); m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); glDrawArraysInstanced(m_glDrawTopology, firstVertex, nVertices, nInstances); //m_drawCallCounter++; } void OpenGLGPUContext::DrawIndexed(uint32 startIndex, uint32 nIndices, uint32 baseVertex) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nIndices == 0) return; DebugAssert(m_pCurrentIndexBuffer != nullptr); CommitVertexAttributes(); m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); GLenum arrayType; uint32 indexBufferOffset = m_currentIndexBufferOffset; if (m_currentIndexFormat == GPU_INDEX_FORMAT_UINT32) { indexBufferOffset += startIndex * sizeof(uint32); arrayType = GL_UNSIGNED_INT; } else { indexBufferOffset += startIndex * sizeof(uint16); arrayType = GL_UNSIGNED_SHORT; } if (baseVertex == 0) glDrawElements(m_glDrawTopology, nIndices, arrayType, reinterpret_cast<GLvoid *>(indexBufferOffset)); else glDrawElementsBaseVertex(m_glDrawTopology, nIndices, arrayType, reinterpret_cast<GLvoid *>(indexBufferOffset), baseVertex); //m_drawCallCounter++; } void OpenGLGPUContext::DrawIndexedInstanced(uint32 startIndex, uint32 nIndices, uint32 baseVertex, uint32 nInstances) { DebugAssert(m_pCurrentShaderProgram != nullptr); if (nIndices == 0 || nInstances == 0) return; DebugAssert(m_pCurrentIndexBuffer != nullptr); CommitVertexAttributes(); m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); GLenum arrayType; uint32 indexBufferOffset = m_currentIndexBufferOffset; if (m_currentIndexFormat == GPU_INDEX_FORMAT_UINT32) { indexBufferOffset += startIndex * sizeof(uint32); arrayType = GL_UNSIGNED_INT; } else { indexBufferOffset += startIndex * sizeof(uint16); arrayType = GL_UNSIGNED_SHORT; } if (baseVertex == 0) glDrawElementsInstanced(m_glDrawTopology, nIndices, arrayType, reinterpret_cast<GLvoid *>(indexBufferOffset), nInstances); else glDrawElementsInstancedBaseVertex(m_glDrawTopology, nIndices, arrayType, reinterpret_cast<GLvoid *>(indexBufferOffset), nInstances, baseVertex); //m_drawCallCounter++; } void OpenGLGPUContext::Dispatch(uint32 threadGroupCountX, uint32 threadGroupCountY, uint32 threadGroupCountZ) { DebugAssert(m_pCurrentShaderProgram != nullptr); m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); glDispatchCompute(threadGroupCountX, threadGroupCountY, threadGroupCountZ); } void OpenGLGPUContext::DrawUserPointer(const void *pVertices, uint32 VertexSize, uint32 nVertices) { uint32 maxVerticesPerPass = m_userVertexBufferSize / VertexSize; DebugAssert(m_pCurrentShaderProgram != nullptr); // obtain the current vertex buffer in slot zero, since we need to overwrite this OpenGLGPUBuffer *pRestoreVertexBuffer = m_currentVertexBuffers[0].pVertexBuffer; uint32 restoreVertexBufferOffset = m_currentVertexBuffers[0].Offset; uint32 restoreVertexBufferStride = m_currentVertexBuffers[0].Stride; if (pRestoreVertexBuffer != nullptr) pRestoreVertexBuffer->AddRef(); // update uniforms m_pCurrentShaderProgram->CommitLocalConstantBuffers(this); CommitShaderResources(); // draw vertices loop const byte *pCurrentVertexPointer = reinterpret_cast<const byte *>(pVertices); uint32 nRemainingVertices = nVertices; while (nRemainingVertices > 0) { byte *pWritePointer; uint32 nVerticesThisPass = Min(nRemainingVertices, maxVerticesPerPass); uint32 spaceRequired = VertexSize * nVerticesThisPass; if ((m_userVertexBufferPosition + spaceRequired) < m_userVertexBufferSize) { // we can fit into the remaining space if (!MapBuffer(m_pUserVertexBuffer, GPU_MAP_TYPE_WRITE_NO_OVERWRITE, reinterpret_cast<void **>(&pWritePointer))) { Log_ErrorPrintf("Failed to map plain vertex buffer."); return; } } else { // discard buffer m_userVertexBufferPosition = 0; if (!MapBuffer(m_pUserVertexBuffer, GPU_MAP_TYPE_WRITE_DISCARD, reinterpret_cast<void **>(&pWritePointer))) { Log_ErrorPrintf("Failed to map plain vertex buffer."); return; } } // write to it Y_memcpy(pWritePointer + m_userVertexBufferPosition, pCurrentVertexPointer, spaceRequired); // unmap and draw Unmapbuffer(m_pUserVertexBuffer, pWritePointer); // bind the vertex buffer OpenGLGPUContext::SetVertexBuffer(0, m_pUserVertexBuffer, m_userVertexBufferPosition, VertexSize); CommitVertexAttributes(); // invoke draw glDrawArrays(m_glDrawTopology, 0, nVerticesThisPass); //m_drawCallCounter++; // increment pointers m_userVertexBufferPosition += spaceRequired; pCurrentVertexPointer += VertexSize * nVerticesThisPass; nRemainingVertices -= nVerticesThisPass; } // re-bind saved vertex buffer SetVertexBuffer(0, pRestoreVertexBuffer, restoreVertexBufferOffset, restoreVertexBufferStride); if (pRestoreVertexBuffer != nullptr) pRestoreVertexBuffer->Release(); // leave the commit out here, next draw will fix it up anyway //CommitVertexAttributes(); } bool OpenGLGPUContext::CopyTexture(GPUTexture2D *pSourceTexture, GPUTexture2D *pDestinationTexture) { // textures have to be compatible, for now this means same texture format OpenGLGPUTexture2D *pOpenGLSourceTexture = static_cast<OpenGLGPUTexture2D *>(pSourceTexture); OpenGLGPUTexture2D *pOpenGLDestinationTexture = static_cast<OpenGLGPUTexture2D *>(pDestinationTexture); if (pOpenGLSourceTexture->GetDesc()->Width != pOpenGLDestinationTexture->GetDesc()->Width || pOpenGLSourceTexture->GetDesc()->Height != pOpenGLDestinationTexture->GetDesc()->Height || pOpenGLSourceTexture->GetDesc()->Format != pOpenGLDestinationTexture->GetDesc()->Format || pOpenGLSourceTexture->GetDesc()->MipLevels != pOpenGLDestinationTexture->GetDesc()->MipLevels) { return false; } if (GLAD_GL_ARB_copy_image) { // preferred standard method for (uint32 level = 0; level < pOpenGLSourceTexture->GetDesc()->MipLevels; level++) glCopyImageSubData(pOpenGLSourceTexture->GetGLTextureId(), GL_TEXTURE_2D, level, 0, 0, 0, pOpenGLDestinationTexture->GetGLTextureId(), GL_TEXTURE_2D, level, 0, 0, 0, pOpenGLSourceTexture->GetDesc()->Width, pOpenGLSourceTexture->GetDesc()->Height, 1); } else if (GLAD_GL_NV_copy_image) { // fallback nvidia extension for (uint32 level = 0; level < pOpenGLSourceTexture->GetDesc()->MipLevels; level++) glCopyImageSubDataNV(pOpenGLSourceTexture->GetGLTextureId(), GL_TEXTURE_2D, level, 0, 0, 0, pOpenGLDestinationTexture->GetGLTextureId(), GL_TEXTURE_2D, level, 0, 0, 0, pOpenGLSourceTexture->GetDesc()->Width, pOpenGLSourceTexture->GetDesc()->Height, 1); } else { // use fbo BindMutatorTextureUnit(); glBindTexture(GL_TEXTURE_2D, pOpenGLSourceTexture->GetGLTextureId()); glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pOpenGLSourceTexture->GetGLTextureId(), 0); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, pOpenGLSourceTexture->GetDesc()->Width, pOpenGLSourceTexture->GetDesc()->Height); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); RestoreMutatorTextureUnit(); } return true; } bool OpenGLGPUContext::CopyTextureRegion(GPUTexture2D *pSourceTexture, uint32 sourceX, uint32 sourceY, uint32 width, uint32 height, uint32 sourceMipLevel, GPUTexture2D *pDestinationTexture, uint32 destX, uint32 destY, uint32 destMipLevel) { // textures have to be compatible, for now this means same texture format OpenGLGPUTexture2D *pOpenGLSourceTexture = static_cast<OpenGLGPUTexture2D *>(pSourceTexture); OpenGLGPUTexture2D *pOpenGLDestinationTexture = static_cast<OpenGLGPUTexture2D *>(pDestinationTexture); if (pOpenGLSourceTexture->GetDesc()->Format != pOpenGLDestinationTexture->GetDesc()->Format || pOpenGLSourceTexture->GetDesc()->MipLevels != pOpenGLDestinationTexture->GetDesc()->MipLevels) { return false; } if (GLAD_GL_ARB_copy_image) { // preferred standard method glCopyImageSubData(pOpenGLSourceTexture->GetGLTextureId(), GL_TEXTURE_2D, sourceMipLevel, sourceX, sourceY, 0, pOpenGLDestinationTexture->GetGLTextureId(), GL_TEXTURE_2D, destMipLevel, destX, destY, 0, width, height, 1); } else if (GLAD_GL_NV_copy_image) { // fallback nvidia extension glCopyImageSubDataNV(pOpenGLSourceTexture->GetGLTextureId(), GL_TEXTURE_2D, sourceMipLevel, sourceX, sourceY, 0, pOpenGLDestinationTexture->GetGLTextureId(), GL_TEXTURE_2D, destMipLevel, destX, destY, 0, width, height, 1); } else { // use fbo BindMutatorTextureUnit(); glBindTexture(GL_TEXTURE_2D, pOpenGLSourceTexture->GetGLTextureId()); glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pOpenGLSourceTexture->GetGLTextureId(), sourceMipLevel); glCopyTexSubImage2D(GL_TEXTURE_2D, destMipLevel, destX, destY, sourceX, sourceY, width, height); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); RestoreMutatorTextureUnit(); } return true; } void OpenGLGPUContext::BlitFrameBuffer(GPUTexture2D *pTexture, uint32 sourceX, uint32 sourceY, uint32 sourceWidth, uint32 sourceHeight, uint32 destX, uint32 destY, uint32 destWidth, uint32 destHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER resizeFilter /*= RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST*/) { // bind read framebuffer to source texture glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, static_cast<OpenGLGPUTexture2D *>(pTexture)->GetGLTextureId(), 0); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the blit operation glBlitFramebuffer(sourceX, sourceY, sourceX + sourceWidth, sourceY + sourceHeight, destX, destY, destX + destWidth, destY + destHeight, GL_COLOR_BUFFER_BIT, (resizeFilter == RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST) ? GL_NEAREST : GL_LINEAR); // unbind texture from fbo, and the fbo glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } void OpenGLGPUContext::GenerateMips(GPUTexture *pTexture) { BindMutatorTextureUnit(); switch (pTexture->GetTextureType()) { case TEXTURE_TYPE_1D: glBindTexture(GL_TEXTURE_1D, static_cast<OpenGLGPUTexture1D *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_1D); break; case TEXTURE_TYPE_1D_ARRAY: glBindTexture(GL_TEXTURE_1D_ARRAY, static_cast<OpenGLGPUTexture1DArray *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_1D_ARRAY); break; case TEXTURE_TYPE_2D: glBindTexture(GL_TEXTURE_2D, static_cast<OpenGLGPUTexture2D *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_2D); break; case TEXTURE_TYPE_2D_ARRAY: glBindTexture(TEXTURE_TYPE_2D_ARRAY, static_cast<OpenGLGPUTexture2DArray *>(pTexture)->GetGLTextureId()); glGenerateMipmap(TEXTURE_TYPE_2D_ARRAY); break; case TEXTURE_TYPE_3D: glBindTexture(GL_TEXTURE_3D, static_cast<OpenGLGPUTexture3D *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_3D); break; case TEXTURE_TYPE_CUBE: glBindTexture(GL_TEXTURE_CUBE_MAP, static_cast<OpenGLGPUTextureCube *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_CUBE_MAP); break; case TEXTURE_TYPE_CUBE_ARRAY: glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, static_cast<OpenGLGPUTextureCubeArray *>(pTexture)->GetGLTextureId()); glGenerateMipmap(GL_TEXTURE_CUBE_MAP_ARRAY); break; } RestoreMutatorTextureUnit(); } GPUCommandList *OpenGLGPUContext::CreateCommandList() { return nullptr; } bool OpenGLGPUContext::OpenCommandList(GPUCommandList *pCommandList) { return false; } bool OpenGLGPUContext::CloseCommandList(GPUCommandList *pCommandList) { return false; } void OpenGLGPUContext::ExecuteCommandList(GPUCommandList *pCommandList) { Panic("Not available."); } <file_sep>/Editor/Source/Editor/MapEditor/EditorMapWindow.h #pragma once #include "Editor/Common.h" #include "Editor/Editor.h" #include "Editor/EditorPropertyEditorWidget.h" #include "Editor/MapEditor/EditorMap.h" class EditorEditMode; class EditorMapViewport; class EditorWorldOutlinerWidget; class EditorResourceBrowserWidget; struct Ui_EditorMapWindow; class EditorMapWindow : public QMainWindow { Q_OBJECT friend class EditorMap; public: EditorMapWindow(); ~EditorMapWindow(); // const accessors const bool IsMapOpen() const { return (m_pOpenMap != NULL); } const EditorMap *GetMap() const { return m_pOpenMap; } const EditorEditMode *GetActiveEditModePointer() const { return m_pActiveEditModePointer; } const Ui_EditorMapWindow *GetUI() const { return m_ui; } const EditorWorldOutlinerWidget *GetWorldOutlinerWidget() const; const EditorResourceBrowserWidget *GetResourceBrowserWidget() const; const EditorPropertyEditorWidget *GetPropertyEditorWidget() const; // accessors EditorMap *GetMap() { return m_pOpenMap; } EditorEditMode *GetActiveEditModePointer() { return m_pActiveEditModePointer; } Ui_EditorMapWindow *GetUI() { return m_ui; } EditorWorldOutlinerWidget *GetWorldOutlinerWidget(); EditorResourceBrowserWidget *GetResourceBrowserWidget(); EditorPropertyEditorWidget *GetPropertyEditorWidget(); // map open/close bool NewMap(); bool OpenMap(const char *fileName); bool SaveMap(); bool SaveMapAs(const char *newFileName); void CloseMap(); // reference coordinate system const EDITOR_REFERENCE_COORDINATE_SYSTEM GetReferenceCoordinateSystem() const { return m_referenceCoordinateSystem; } void SetReferenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM referenceCoordinateSystem); // edit mode const EDITOR_EDIT_MODE GetEditMode() const { return m_editMode; } void SetEditMode(EDITOR_EDIT_MODE mode); // property editor management // todo: virtual property editor //void ClearPropertyEditor(); //void BuildPropertyEditorForEntities(const uint32 *pEntities, uint32 nEntities); //void UpdatePropertyEditorEntity(uint32 entityId, const char *propertyName, const char *oldPropertyValue, const char *newPropertyValue); // viewport management const EditorMapViewport *GetActiveViewport() const { return m_pActiveViewport; } const EditorMapViewport *GetViewport(uint32 i) const { DebugAssert(i < m_viewports.GetSize()); return m_viewports[i]; } EditorMapViewport *GetViewport(uint32 i) { DebugAssert(i < m_viewports.GetSize()); return m_viewports[i]; } EditorMapViewport *GetActiveViewport() { return m_pActiveViewport; } uint32 GetViewportCount() const { return m_viewports.GetSize(); } void SetActiveViewport(EditorMapViewport *pViewport); void SetViewportLayout(EDITOR_VIEWPORT_LAYOUT layout); void RedrawAllViewports(); // when viewport camera changes void OnViewportCameraChange(EditorMapViewport *pViewport); private: // map bool OnMapOpened(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // viewports EditorMapViewport *CreateViewport(EDITOR_CAMERA_MODE cameraMode, EDITOR_RENDER_MODE renderMode, uint32 flags); void DeleteAllViewports(); // ui pointers Ui_EditorMapWindow *m_ui; // open map EditorMap *m_pOpenMap; // reference coordinate system EDITOR_REFERENCE_COORDINATE_SYSTEM m_referenceCoordinateSystem; // edit mode EDITOR_EDIT_MODE m_editMode; EditorEditMode *m_pActiveEditModePointer; // viewports EDITOR_VIEWPORT_LAYOUT m_viewportLayout; typedef PODArray<EditorMapViewport *> ViewportWidgetArray; ViewportWidgetArray m_viewports; EditorMapViewport *m_pActiveViewport; //=================================================================================================================================================================== // logging callback //=================================================================================================================================================================== static void LogCallback(void *pUserParam, const char *channelName, const char *functionName, LOGLEVEL level, const char *message); //=================================================================================================================================================================== // implemented qt methods //=================================================================================================================================================================== virtual void closeEvent(QCloseEvent *pCloseEvent); //=================================================================================================================================================================== // gui event callbacks //=================================================================================================================================================================== void ConnectUIEvents(); void UpdateStatusBarCameraFields(); void UpdateStatusBarFPSField(); private Q_SLOTS: void OnActionFileNewMapTriggered(); void OnActionFileOpenMapTriggered(); void OnActionFileSaveMapTriggered(); void OnActionFileSaveMapAsTriggered(); void OnActionFileCloseMapTriggered(); void OnActionFileExitTriggered(); void OnActionEditReferenceCoordinateSystemLocalTriggered(bool checked) { SetReferenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM_LOCAL); } void OnActionEditReferenceCoordinateSystemWorldTriggered(bool checked) { SetReferenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM_WORLD); } void OnActionViewWorldOutlinerTriggered(bool checked); void OnActionViewResourceBrowserTriggered(bool checked); void OnActionViewToolboxTriggered(bool checked); void OnActionViewPropertyEditorTriggered(bool checked); void OnActionViewThemeNone() { g_pEditor->SetEditorTheme(EDITOR_THEME_NONE); } void OnActionViewThemeDark() { g_pEditor->SetEditorTheme(EDITOR_THEME_DARK); } void OnActionViewThemeDarkOther() { g_pEditor->SetEditorTheme(EDITOR_THEME_DARK_OTHER); } void OnActionToolsMapEditModeTriggered(bool checked) { SetEditMode(EDITOR_EDIT_MODE_MAP); } void OnActionToolsEntityEditModeTriggered(bool checked) { SetEditMode((checked) ? EDITOR_EDIT_MODE_ENTITY : EDITOR_EDIT_MODE_MAP); } void OnActionToolsGeometryEditModeTriggered(bool checked) { SetEditMode((checked) ? EDITOR_EDIT_MODE_GEOMETRY : EDITOR_EDIT_MODE_MAP); } void OnActionToolsHeightfieldTerrainEditModeTriggered(bool checked) { SetEditMode((checked) ? EDITOR_EDIT_MODE_TERRAIN : EDITOR_EDIT_MODE_MAP); } void OnActionToolsCreateTerrainTriggered(); void OnActionToolsDeleteTerrainTriggered(); void OnActionToolsCreateBlockTerrainTriggered(); void OnActionToolsDeleteBlockTerrainTriggered(); void OnStatusBarGridSnapEnabledToggled(bool checked); void OnStatusBarGridSnapIntervalChanged(double value); void OnStatusBarGridLinesVisibleToggled(bool checked); void OnStatusBarGridLinesIntervalChanged(double value); void OnWorldOutlinerEntitySelected(const EditorMapEntity *pEntity); void OnWorldOutlinerEntityActivated(const EditorMapEntity *pEntity); void OnToolboxTabWidgetCurrentChanged(int index); void OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue); void OnFrameExecutionTriggered(float timeSinceLastFrame); }; <file_sep>/Engine/Source/ContentConverterStandalone/AssimpSkeletonImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintAssimpSkeletonImporterSyntax() { Log_InfoPrint("Assimp Skeleton Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -o <path>: Output resource name."); Log_InfoPrint(" -rotate(X|Y|Z) <amount>: Rotate around the axis as a post-transform."); Log_InfoPrint(" -translate(X|Y|Z) <degrees>: Translate along the axis as a post-transform."); Log_InfoPrint(" -scale[X|Y|Z] <amount>: Uniform or nonuniform scale on axis as a post-transform."); Log_InfoPrint(" -cs <(yup|zup)_(lh|rh)>: File uses specified coordinate system, convert if necessary."); Log_InfoPrint(""); } bool ParseAssimpSkeletonImporterOption(AssimpSkeletonImporter::Options &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.SourcePath = argv[++i]; else if (CHECK_ARG_PARAM("-o")) Options.OutputResourceName = argv[++i]; else if (CHECK_ARG_PARAM("-rotateX")) Options.TransformMatrix = float4x4::MakeRotationMatrixX(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateY")) Options.TransformMatrix = float4x4::MakeRotationMatrixY(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateZ")) Options.TransformMatrix = float4x4::MakeRotationMatrixZ(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateX")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateY")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateZ")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleX")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleY")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleZ")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scale")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-cs")) { ++i; if (!Y_stricmp(argv[i], "yup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_LH; else if (!Y_stricmp(argv[i], "yup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; else if (!Y_stricmp(argv[i], "zup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_LH; else if (!Y_stricmp(argv[i], "zup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_RH; else { Log_ErrorPrintf("Invalid coordinate system specified."); return false; } } else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintAssimpSkeletonImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunAssimpSkeletonImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintAssimpSkeletonImporterSyntax(); return 0; } AssimpSkeletonImporter::Options options; AssimpSkeletonImporter::SetDefaultOptions(&options); for (i = 0; i < argc; i++) { if (!ParseAssimpSkeletonImporterOption(options, i, argc, argv)) return 1; } if (options.SourcePath.IsEmpty() || options.OutputResourceName.IsEmpty()) { Log_ErrorPrintf("Missing input file name or output name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; AssimpSkeletonImporter importer(&options, &progressCallbacks); if (!importer.Execute()) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/DemoGame/Source/DemoGame/ImGuiDemo.h #pragma once #include "DemoGame/BaseDemoGameState.h" class ImGuiDemo : public BaseDemoGameState { public: ImGuiDemo(DemoGame *pDemoGame); virtual ~ImGuiDemo(); virtual void OnSwitchedIn() override; virtual bool OnWindowEvent(const union SDL_Event *event) override; protected: virtual void OnRenderThreadBeginFrame(float deltaTime) override; virtual void DrawUI(float deltaTime) override; }; <file_sep>/Engine/Source/MathLib/HashTraits.cpp #include "MathLib/HashTraits.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" HashType HashTrait<Vector2f>::GetHash(const Vector2f &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; return (xhash + yhash * 37); } HashType HashTrait<Vector3f>::GetHash(const Vector3f &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; uint32 zhash = *(uint32 *)&Value.z; return (xhash + yhash * 37 + zhash * 101); } HashType HashTrait<Vector4f>::GetHash(const Vector4f &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; uint32 zhash = *(uint32 *)&Value.z; uint32 whash = *(uint32 *)&Value.w; return (xhash + yhash * 37 + zhash * 101 + whash * 241); } HashType HashTrait<Vector2i>::GetHash(const Vector2i &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; return (xhash + yhash * 37); } HashType HashTrait<Vector3i>::GetHash(const Vector3i &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; uint32 zhash = *(uint32 *)&Value.z; return (xhash + yhash * 37 + zhash * 101); } HashType HashTrait<Vector4i>::GetHash(const Vector4i &Value) { uint32 xhash = *(uint32 *)&Value.x; uint32 yhash = *(uint32 *)&Value.y; uint32 zhash = *(uint32 *)&Value.z; uint32 whash = *(uint32 *)&Value.w; return (xhash + yhash * 37 + zhash * 101 + whash * 241); } HashType HashTrait<Vector2u>::GetHash(const Vector2u &Value) { uint32 xhash = Value.x; uint32 yhash = Value.y; return (xhash + yhash * 37); } HashType HashTrait<Vector3u>::GetHash(const Vector3u &Value) { uint32 xhash = Value.x; uint32 yhash = Value.y; uint32 zhash = Value.z; return (xhash + yhash * 37 + zhash * 101); } HashType HashTrait<Vector4u>::GetHash(const Vector4u &Value) { uint32 xhash = Value.x; uint32 yhash = Value.y; uint32 zhash = Value.z; uint32 whash = Value.w; return (xhash + yhash * 37 + zhash * 101 + whash * 241); } <file_sep>/Editor/Source/Editor/MapEditor/EditorEditMode.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorEditMode.h" #include "Editor/MapEditor/EditorMapViewport.h" EditorEditMode::EditorEditMode(EditorMap *pMap) : m_pMap(pMap), m_bActive(false), m_cameraLeftMouseButtonDown(false), m_cameraRightMouseButtonDown(false) { } EditorEditMode::~EditorEditMode() { } bool EditorEditMode::Initialize(ProgressCallbacks *pProgressCallbacks) { return true; } QWidget *EditorEditMode::CreateUI(QWidget *parentWidget) { QWidget *rootWidget = new QWidget(parentWidget); return rootWidget; } void EditorEditMode::Activate() { DebugAssert(!m_bActive); m_bActive = true; } void EditorEditMode::Deactivate() { DebugAssert(m_bActive); m_bActive = false; m_cameraLeftMouseButtonDown = false; m_cameraRightMouseButtonDown = false; } void EditorEditMode::Update(const float timeSinceLastUpdate) { } void EditorEditMode::OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) { } void EditorEditMode::OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) { m_cameraLeftMouseButtonDown = false; m_cameraRightMouseButtonDown = false; } bool EditorEditMode::HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) { // pass through to camera if (pViewport->GetViewController().HandleKeyboardEvent(pKeyboardEvent)) return true; return false; } bool EditorEditMode::HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { if ((m_cameraLeftMouseButtonDown | m_cameraRightMouseButtonDown) == 0) { pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_CROSS); pViewport->LockMouseCursor(); } m_cameraLeftMouseButtonDown = true; return true; } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { m_cameraLeftMouseButtonDown = false; if ((m_cameraLeftMouseButtonDown | m_cameraRightMouseButtonDown) == 0) { pViewport->UnlockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); } return true; } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { if ((m_cameraLeftMouseButtonDown | m_cameraRightMouseButtonDown) == 0) { pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_CROSS); pViewport->LockMouseCursor(); } m_cameraRightMouseButtonDown = true; return true; } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { m_cameraRightMouseButtonDown = false; if ((m_cameraLeftMouseButtonDown | m_cameraRightMouseButtonDown) == 0) { pViewport->UnlockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); } return true; } else if (pMouseEvent->type() == QEvent::MouseMove) { // pass to camera if (m_cameraLeftMouseButtonDown) { pViewport->GetViewController().MoveFromMousePosition(pViewport->GetMouseDelta()); return true; } if (m_cameraRightMouseButtonDown) { pViewport->GetViewController().RotateFromMousePosition(pViewport->GetMouseDelta()); return true; } } return false; } bool EditorEditMode::HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) { return false; } void EditorEditMode::OnViewportDrawAfterWorld(EditorMapViewport *pViewport) { } void EditorEditMode::OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) { } void EditorEditMode::OnViewportDrawAfterPost(EditorMapViewport *pViewport) { } void EditorEditMode::OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) { } void EditorEditMode::OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) { } bool EditorEditMode::HandleResourceViewResourceActivatedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName) { return false; } bool EditorEditMode::HandleResourceViewResourceDroppedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName, const EditorMapViewport *pViewport, int32 x, int32 y) { return false; } <file_sep>/Engine/Source/GameFramework/PointLightEntity.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/PointLightEntity.h" #include "Renderer/RenderProxies/PointLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Engine/World.h" DEFINE_ENTITY_TYPEINFO(PointLightEntity, 0); DEFINE_ENTITY_GENERIC_FACTORY(PointLightEntity); BEGIN_ENTITY_PROPERTIES(PointLightEntity) PROPERTY_TABLE_MEMBER_BOOL("Enabled", 0, offsetof(PointLightEntity, m_bEnabled), OnEnabledPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT("Range", 0, offsetof(PointLightEntity, m_fRange), OnRangePropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT3("Color", 0, offsetof(PointLightEntity, m_Color), OnColorOrBrightnessPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT("Brightness", 0, offsetof(PointLightEntity, m_fBrightness), OnColorOrBrightnessPropertyChange, NULL) PROPERTY_TABLE_MEMBER_UINT("LightShadowFlags", 0, offsetof(PointLightEntity, m_iLightShadowFlags), OnShadowPropertyChange, NULL) PROPERTY_TABLE_MEMBER_FLOAT("FalloffExponent", 0, offsetof(PointLightEntity, m_fFalloffExponent), OnFalloffExponentChange, NULL) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(PointLightEntity) END_ENTITY_SCRIPT_FUNCTIONS() PointLightEntity::PointLightEntity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_bEnabled(true), m_fRange(8.0f), m_Color(float3::One), m_fBrightness(1.0f), m_iLightShadowFlags(0), m_fFalloffExponent(1.0f), m_pRenderProxy(NULL) { } PointLightEntity::~PointLightEntity() { m_pRenderProxy->Release(); } void PointLightEntity::SetEnabled(bool enabled) { m_bEnabled = enabled; OnEnabledPropertyChange(this); } void PointLightEntity::SetRange(float range) { m_fRange = range; OnRangePropertyChange(this); } void PointLightEntity::SetColor(const float3 &color) { m_Color = color; OnColorOrBrightnessPropertyChange(this); } void PointLightEntity::SetBrightness(float brightness) { m_fBrightness = brightness; OnColorOrBrightnessPropertyChange(this); } void PointLightEntity::SetLightShadowFlags(uint32 lightShadowFlags) { m_iLightShadowFlags = lightShadowFlags; OnShadowPropertyChange(this); } void PointLightEntity::SetFalloffExponent(float falloffExponent) { m_fFalloffExponent = falloffExponent; OnFalloffExponentChange(this); } bool PointLightEntity::Initialize(uint32 entityID, const String &entityName) { if (!BaseClass::Initialize(entityID, entityName)) return false; // create the render proxy m_pRenderProxy = new PointLightRenderProxy(GetEntityID(), GetPosition(), GetRange(), CalculateLightColor(), m_iLightShadowFlags, GetFalloffExponent()); UpdateBounds(); return true; } void PointLightEntity::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void PointLightEntity::OnRemoveFromWorld(World *pWorld) { pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); BaseClass::OnRemoveFromWorld(pWorld); } void PointLightEntity::OnTransformChange() { BaseClass::OnTransformChange(); m_pRenderProxy->SetPosition(m_transform.GetPosition()); UpdateBounds(); } void PointLightEntity::OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetEnabled(pEntity->m_bEnabled); } void PointLightEntity::OnRangePropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetRange(pEntity->GetRange()); pEntity->UpdateBounds(); } void PointLightEntity::OnColorOrBrightnessPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetColor(pEntity->CalculateLightColor()); } void PointLightEntity::OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetShadowFlags(pEntity->m_iLightShadowFlags); } void PointLightEntity::OnFalloffExponentChange(ThisClass *pEntity, const void *pUserData) { pEntity->m_pRenderProxy->SetFalloffExponent(pEntity->GetFalloffExponent()); } float3 PointLightEntity::CalculateLightColor() { float3 lightColor(m_Color * m_fBrightness); return lightColor; } void PointLightEntity::UpdateBounds() { SIMDVector3f lightPosition(GetPosition()); SIMDVector3f minBounds(lightPosition - m_fRange); SIMDVector3f maxBounds(lightPosition + m_fRange); SetBounds(AABox(minBounds, maxBounds), Sphere(lightPosition, m_fRange)); } <file_sep>/Engine/Source/Engine/ScriptManager.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptManager.h" #include "Engine/ScriptObjectTypeInfo.h" #include "Engine/Entity.h" Log_SetChannel(ScriptManager); // Stack dump function int ScriptManager::DumpScriptStack(lua_State *L) { Log_InfoPrint("Script stack dump: (top-down)"); int idx = lua_gettop(L); for (; idx > 0; idx--) { int t = lua_type(L, idx); if (t == LUA_TSTRING) Log_InfoPrintf(" string(%s)", lua_tostring(L, idx)); else if (t == LUA_TNUMBER) Log_InfoPrintf(" number(%f)", lua_tonumber(L, idx)); else if (t == LUA_TFUNCTION && lua_iscfunction(L, idx)) Log_InfoPrintf(" cfunction(%p)", lua_tocfunction(L, idx)); else if (t == LUA_TFUNCTION) Log_InfoPrintf(" function"); else { if (!luaL_callmeta(L, idx, "__type")) lua_pushstring(L, luaL_typename(L, idx)); Log_InfoPrintf(" %s", lua_tostring(L, -1)); lua_pop(L, 1); } } return 0; } // Traceback function int ScriptManager::DumpScriptTraceback(lua_State *L) { luaBackupStack(L); Log_ErrorPrint("Traceback: (most recent call first)"); int level = 0; // we don't want to include this error function lua_Debug dbg; while (lua_getstack(L, level++, &dbg) == 1) { // get function info lua_getinfo(L, "Snl", &dbg); // build stack trace line char line[512]; line[0] = 0; if (*dbg.source == '=') { Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), "<native code>:"); } else { Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), "%s:", dbg.short_src); if (dbg.currentline > 0) Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), "%d:", dbg.currentline); } if (level == 1) Y_strncat(line, sizeof(line), " <error handler called>"); else if (*dbg.namewhat != '\0') Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), " in '%s' function '%s'", dbg.namewhat, dbg.name); else { if (*dbg.what == 'm') Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), " in main chunk"); else Y_snprintf(&line[Y_strlen(line)], countof(line) - Y_strlen(line), " unknown"); } // output line Log_ErrorPrint(line); } luaVerifyStack(L, 0); return 0; } // Error handler function static int ErrorHandler(lua_State *L) { const char *msg = (lua_isstring(L, 1)) ? lua_tostring(L, 1) : nullptr; Log_ErrorPrintf("Script error: %s", (msg != nullptr) ? msg : "(null)"); ScriptManager::DumpScriptTraceback(L); return 0; } // Panic handler function static int PanicHandler(lua_State *L) { const char *str = (lua_isstring(L, -1)) ? lua_tostring(L, -1) : nullptr; char msg[200]; Y_snprintf(msg, countof(msg), "Script engine panic: %s", str); Y_OnPanicReached(msg, __FUNCTION__, __FILE__, __LINE__); return 0; } // Redirector method for our userdata type to handle getting members. static int UserDataAttribute_Index(lua_State *L) { luaBackupStack(L); // check if the userdata has a uservalue (data table) lua_getuservalue(L, 1); if (lua_istable(L, -1)) { // search the uservalue table for the key, raw method will work fine here since there shouldn't be any metamethods on this table lua_pushvalue(L, 2); lua_rawget(L, -2); if (!lua_isnil(L, -1)) { // value found, so drop out and clean up the stack (replace the uservalue table with the value itself lua_replace(L, -2); luaVerifyStack(L, 1); return 1; } // drop the nil, usertable off the stack lua_pop(L, 2); } else { // drop the usertable off the stack lua_pop(L, 1); } // search the table as normal, this is the methods table, so there won't be any metamethods here either lua_pushvalue(L, 2); lua_rawget(L, lua_upvalueindex(1)); luaVerifyStack(L, 1); return 1; } // Redirector method for our userdata type to handle setting members. static int UserDataAttribute_NewIndex(lua_State *L) { luaBackupStack(L); // does this userdata currently have a uservalue? lua_getuservalue(L, 1); if (lua_isnil(L, -1)) { // nil, so create the table, and bind it to the userdata lua_pop(L, 1); lua_newtable(L); lua_pushvalue(L, -1); lua_setuservalue(L, 1); } // assign it to the table, use raw set here though lua_pushvalue(L, 2); lua_pushvalue(L, 3); lua_rawset(L, -3); lua_pop(L, 1); luaVerifyStack(L, 0); return 0; } // Static error method when trying to allocate a non-script-allocatable user type, expects the type name in upvalue#1 static int UserData_AllocateUnallocatableTypeError(lua_State *L) { const char *typeName = lua_tostring(L, lua_upvalueindex(1)); luaL_error(L, "attempt to allocate unallocatable type %s", typeName); return 0; } static ScriptManager s_scriptManager; ScriptManager *g_pScriptManager = &s_scriptManager; ScriptManager::ScriptManager() : m_state(nullptr) { } ScriptManager::~ScriptManager() { DebugAssert(m_state == nullptr); } static int UserData_GetMetaTableName(lua_State *L, int idx) { luaBackupStack(L); lua_getfield(L, idx, "__name"); if (lua_isstring(L, -1)) { // remove the metatable luaVerifyStack(L, 1); return 1; } lua_pop(L, 1); lua_pushstring(L, "<<unknown>>"); luaVerifyStack(L, 1); return 1; } static int UserData_GetTypeName(lua_State *L, int idx) { luaBackupStack(L); if (lua_isuserdata(L, idx)) { if (!luaL_callmeta(L, idx, "__type")) { // get __name from metatable lua_getmetatable(L, idx); if (lua_istable(L, -1)) { lua_getfield(L, -1, "__name"); if (lua_isstring(L, -1)) { // remove the metatable lua_remove(L, -2); luaVerifyStack(L, 1); return 1; } lua_pop(L, 1); } lua_pop(L, 1); } } lua_pushstring(L, luaL_typename(L, idx)); luaVerifyStack(L, 1); return 1; } int ScriptManager::GenerateTypeError(lua_State *L, int narg, const char *type) { UserData_GetTypeName(L, narg); const char *msg = lua_pushfstring(L, "%s expected, got %s", type, lua_tostring(L, -1)); return luaL_argerror(L, narg, msg); } int ScriptManager::GenerateTypeError(lua_State *L, int narg, ScriptReferenceType metaTableReference) { UserData_GetTypeName(L, narg); // resolve metatable lua_rawgeti(L, LUA_REGISTRYINDEX, metaTableReference); UserData_GetMetaTableName(L, -1); const char *msg = lua_pushfstring(L, "%s expected, got %s", lua_tostring(L, -1), lua_tostring(L, -3)); return luaL_argerror(L, narg, msg); } ScriptReferenceType ScriptManager::CreateReference(lua_State *L) { return luaL_ref(L, LUA_REGISTRYINDEX); } void ScriptManager::ReleaseReference(ScriptReferenceType objectReference) { luaL_unref(m_state, LUA_REGISTRYINDEX, objectReference); } size_t ScriptManager::GetMemoryUsage() const { return (size_t)lua_gc(m_state, LUA_GCCOUNT, 0) << 10 | (size_t)lua_gc(m_state, LUA_GCCOUNTB, 0); } void ScriptManager::RunGCStep() { lua_gc(m_state, LUA_GCSTEP, 0); } void ScriptManager::RunGCFull() { lua_gc(m_state, LUA_GCCOLLECT, 0); } bool ScriptManager::Startup() { Log_InfoPrint("ScriptManager::Startup()"); Timer tmr; Timer ttmr; // allocate state m_state = luaL_newstate(); Log_PerfPrintf("newstate took %.4f msec", tmr.GetTimeMilliseconds()); tmr.Reset(); lua_atpanic(m_state, PanicHandler); // load libs luaopen_base(m_state); luaopen_table(m_state); luaopen_string(m_state); luaopen_utf8(m_state); luaopen_math(m_state); luaopen_debug(m_state); lua_pop(m_state, 6); Log_PerfPrintf("lib funcs took %.4f msec", tmr.GetTimeMilliseconds()); tmr.Reset(); // create types RegisterBuiltinFunctions(); Log_PerfPrintf("builtin funcs took %.4f msec", tmr.GetTimeMilliseconds()); tmr.Reset(); RegisterPrimitiveTypes(); Log_PerfPrintf("primitive funcs took %.4f msec", tmr.GetTimeMilliseconds()); tmr.Reset(); ScriptObjectTypeInfo::RegisterAllScriptTypes(); Log_PerfPrintf("object funcs took %.4f msec", tmr.GetTimeMilliseconds()); tmr.Reset(); Log_PerfPrintf("total took %.4f msec", ttmr.GetTimeMilliseconds()); // done return true; } void ScriptManager::Shutdown() { Log_InfoPrint("ScriptManager::Shutdown()"); // unregister object types ScriptObjectTypeInfo::UnregisterAllScriptTypes(); // unregister all primitive types UnregisterPrimitiveTypes(); // finally delete state lua_close(m_state); m_state = nullptr; } ScriptReferenceType ScriptManager::DefineTabledUserDataType(const char *typeName, const SCRIPT_FUNCTION_TABLE_ENTRY *pMethods /* = nullptr */, const SCRIPT_FUNCTION_TABLE_ENTRY *pMetaMethods /* = nullptr */, ScriptNativeFunctionType constructor /* = nullptr */, ScriptNativeFunctionType destructor /* = nullptr */) { luaBackupStack(m_state); // allocate metatable if (!luaL_newmetatable(m_state, typeName)) { lua_pop(m_state, 1); luaVerifyStack(m_state, 0); return INVALID_SCRIPT_REFERENCE; } // fill method table lua_newtable(m_state); if (pMethods != nullptr) { for (const SCRIPT_FUNCTION_TABLE_ENTRY *pMethod = pMethods; pMethod->FunctionPointer != nullptr; pMethod++) { lua_pushcclosure(m_state, pMethod->FunctionPointer, 0); lua_setfield(m_state, -2, pMethod->FunctionName); } } // set __index of the metatable to our redirector function, using the method table as an upvalue lua_pushcclosure(m_state, UserDataAttribute_Index, 1); lua_setfield(m_state, -2, "__index"); // set __newindex of the metatable to our redirector function lua_pushcclosure(m_state, UserDataAttribute_NewIndex, 0); lua_setfield(m_state, -2, "__newindex"); // create constructor if provided (TypeName() method) if (constructor != nullptr) { lua_pushcclosure(m_state, constructor, 0); lua_setglobal(m_state, typeName); } else { // create a stub method that errors out when trying to allocate the type, that way the name is reserved lua_pushstring(m_state, typeName); lua_pushcclosure(m_state, UserData_AllocateUnallocatableTypeError, 1); lua_setglobal(m_state, typeName); } // create destructor if provided if (destructor != nullptr) { lua_pushcclosure(m_state, destructor, 0); lua_setfield(m_state, -2, "__gc"); } // add any metamethods if (pMetaMethods != nullptr) { for (const SCRIPT_FUNCTION_TABLE_ENTRY *pMethod = pMethods; pMethod->FunctionPointer != nullptr; pMethod++) { lua_pushcclosure(m_state, pMethod->FunctionPointer, 0); lua_setfield(m_state, -2, pMethod->FunctionName); } } // reference the metatable type ScriptReferenceType ref = luaL_ref(m_state, LUA_REGISTRYINDEX); // verify stack and return luaVerifyStack(m_state, 0); return ref; } ScriptReferenceType ScriptManager::DefineUserDataType(const char *typeName, const SCRIPT_FUNCTION_TABLE_ENTRY *pMethods /* = nullptr */, const SCRIPT_FUNCTION_TABLE_ENTRY *pMetaMethods /* = nullptr */, ScriptNativeFunctionType constructor /* = nullptr */, ScriptNativeFunctionType destructor /* = nullptr */) { luaBackupStack(m_state); // allocate metatable if (!luaL_newmetatable(m_state, typeName)) { luaVerifyStack(m_state, 0); return INVALID_SCRIPT_REFERENCE; } // if methods are provided, allocate and fill the method table if (pMethods != nullptr) { // todo: create sized table lua_createtable lua_newtable(m_state); for (const SCRIPT_FUNCTION_TABLE_ENTRY *pMethod = pMethods; pMethod->FunctionPointer != nullptr; pMethod++) { lua_pushcclosure(m_state, pMethod->FunctionPointer, 0); lua_setfield(m_state, -2, pMethod->FunctionName); } // set __index of the metatable to this table lua_setfield(m_state, -2, "__index"); } // create constructor if provided (TypeName() method) if (constructor != nullptr) { lua_pushcclosure(m_state, constructor, 0); lua_setglobal(m_state, typeName); } else { // create a stub method that errors out when trying to allocate the type, that way the name is reserved lua_pushstring(m_state, typeName); lua_pushcclosure(m_state, UserData_AllocateUnallocatableTypeError, 1); lua_setglobal(m_state, typeName); } // create destructor if provided if (destructor != nullptr) { lua_pushcclosure(m_state, destructor, 0); lua_setfield(m_state, -2, "__gc"); } // add any metamethods if (pMetaMethods != nullptr) { for (const SCRIPT_FUNCTION_TABLE_ENTRY *pMethod = pMethods; pMethod->FunctionPointer != nullptr; pMethod++) { lua_pushcclosure(m_state, pMethod->FunctionPointer, 0); lua_setfield(m_state, -2, pMethod->FunctionName); } } // reference the metatable type ScriptReferenceType ref = luaL_ref(m_state, LUA_REGISTRYINDEX); // verify stack and return luaVerifyStack(m_state, 0); return ref; } void *ScriptManager::CheckUserDataTypeByMetaTable(lua_State *L, ScriptReferenceType metaTableReference, int arg) { void *pUserData; luaBackupStack(L); // should be a userdata if (lua_type(L, arg) != LUA_TUSERDATA || (pUserData = lua_touserdata(L, arg)) == nullptr) { GenerateTypeError(L, arg, metaTableReference); return nullptr; } // resolve metatable reference lua_rawgeti(L, LUA_REGISTRYINDEX, metaTableReference); DebugAssert(lua_istable(L, -1)); // get the parameter's metatable lua_getmetatable(L, arg); // check they match if (!lua_rawequal(L, -1, -2)) { lua_pop(L, 2); GenerateTypeError(L, arg, metaTableReference); return nullptr; } // type is ok, pop metatable + table lua_pop(L, 2); luaVerifyStack(L, 0); return reinterpret_cast<ScriptUserDataTag *>(pUserData) + 1; } void *ScriptManager::CheckUserDataTypeByTag(lua_State *L, ScriptUserDataTag tag, int arg) { void *pUserData; luaBackupStack(L); // should be a userdata if (lua_type(L, arg) != LUA_TUSERDATA || (pUserData = lua_touserdata(L, arg)) == nullptr) { luaL_argerror(L, arg, "expected userdata"); return nullptr; } // read the tag of the userdata ScriptUserDataTag udTag = *reinterpret_cast<ScriptUserDataTag *>(pUserData); if (udTag != tag) { lua_pushfstring(L, "expected userdata tag %u, got %u", tag, udTag); luaL_argerror(L, arg, lua_tostring(L, -1)); return nullptr; } // type is ok, pop metatable + table luaVerifyStack(L, 0); return reinterpret_cast<ScriptUserDataTag *>(pUserData) + 1; } void ScriptManager::PushNewUserData(lua_State *L, ScriptReferenceType metaTableReference, ScriptUserDataTag tag, uint32 size, const void *data) { luaBackupStack(L); // create user data and copy it in void *pUserData = lua_newuserdata(L, size + sizeof(ScriptUserDataTag)); *reinterpret_cast<ScriptUserDataTag *>(pUserData) = tag; Y_memcpy(reinterpret_cast<ScriptUserDataTag *>(pUserData) + 1, data, size); // resolve metatable reference lua_rawgeti(L, LUA_REGISTRYINDEX, metaTableReference); DebugAssert(lua_istable(L, -1)); // set the metatable of the newly generated user data to it lua_setmetatable(L, -2); luaVerifyStack(L, 1); } ScriptReferenceType ScriptManager::AllocateAndReferenceNewUserData(ScriptReferenceType metaTableReference, ScriptUserDataTag tag, uint32 size, const void *data) { luaBackupStack(m_state); PushNewUserData(m_state, metaTableReference, tag, size, data); // reference the object ScriptReferenceType ref = luaL_ref(m_state, LUA_REGISTRYINDEX); luaVerifyStack(m_state, 0); return ref; } void ScriptManager::SetUserDataReferenceTag(ScriptReferenceType reference, ScriptUserDataTag tag) { luaBackupStack(m_state); lua_rawgeti(m_state, LUA_REGISTRYINDEX, reference); DebugAssert(lua_isuserdata(m_state, -1)); ScriptUserDataTag *pUserDataTag = reinterpret_cast<ScriptUserDataTag *>(lua_touserdata(m_state, -1)); *pUserDataTag = tag; lua_pop(m_state, 1); luaVerifyStack(m_state, 0); } ScriptCallResult ScriptManager::RunScript(const byte *script, uint32 scriptLength, const char *source /* = "text chunk" */) { // stack should be empty DebugAssert(lua_gettop(m_state) == 0); luaBackupStack(m_state); // push error handler lua_pushcfunction(m_state, ErrorHandler); // parse string if (luaL_loadbuffer(m_state, (const char *)script, scriptLength, source) != 0) { lua_pop(m_state, 1); luaVerifyStack(m_state, 0); return ScriptCallResult_ParseError; } // run string int r = lua_pcall(m_state, 0, 0, -2); if (r != 0) { const char *errorMessage = lua_tostring(m_state, -1); if (errorMessage != nullptr) Log_ErrorPrintf("Script error: %s", errorMessage); // pop error message and handler lua_pop(m_state, 2); luaVerifyStack(m_state, 0); return ScriptCallResult_RuntimeError; } // pop error handler lua_pop(m_state, 1); luaVerifyStack(m_state, 0); return ScriptCallResult_Success; } void ScriptManager::PushNewObjectReference(lua_State *L, ScriptReferenceType metaTableReference, ScriptUserDataTag tag, const void *pObjectPointer) { DebugAssert(metaTableReference != INVALID_SCRIPT_REFERENCE); luaBackupStack(L); // allocate userdata of pointer-size void *pUserData = lua_newuserdata(L, sizeof(void *) + sizeof(ScriptUserDataTag)); *reinterpret_cast<ScriptUserDataTag *>(pUserData) = tag; *reinterpret_cast<void **>(reinterpret_cast<ScriptUserDataTag *>(pUserData) + 1) = const_cast<void *>(pObjectPointer); // set metatable lua_rawgeti(L, LUA_REGISTRYINDEX, metaTableReference); lua_setmetatable(L, -2); luaVerifyStack(L, 1); } ScriptReferenceType ScriptManager::AllocateAndReferenceObject(ScriptReferenceType metaTableReference, ScriptUserDataTag tag, const void *pObjectPointer) { DebugAssert(metaTableReference != INVALID_SCRIPT_REFERENCE); luaBackupStack(m_state); // push it PushNewObjectReference(m_state, metaTableReference, tag, pObjectPointer); // reference it ScriptReferenceType ref = luaL_ref(m_state, LUA_REGISTRYINDEX); luaVerifyStack(m_state, 0); return ref; } void ScriptManager::SetObjectReferencePointer(ScriptReferenceType objectReference, const void *pObject) { DebugAssert(objectReference != INVALID_SCRIPT_REFERENCE); // push the reference lua_rawgeti(m_state, LUA_REGISTRYINDEX, objectReference); // replace the userdata void **ppUserData = (void **)lua_touserdata(m_state, -1); *ppUserData = const_cast<void *>(pObject); lua_pop(m_state, 1); } void *ScriptManager::CheckObjectTypeByMetaTable(lua_State *L, ScriptReferenceType metaTableReference, int arg) { void **ppUserData = (void **)CheckUserDataTypeByMetaTable(L, metaTableReference, arg); return *ppUserData; } void *ScriptManager::CheckObjectTypeByTag(lua_State *L, ScriptUserDataTag tag, int arg) { void **ppUserData = (void **)CheckUserDataTypeByTag(L, tag, arg); return *ppUserData; } ScriptCallResult ScriptManager::RunObjectScript(ScriptReferenceType objectReference, const byte *script, uint32 scriptLength, const char *source /* = "text chunk" */) { // stack should be empty DebugAssert(lua_gettop(m_state) == 0); luaBackupStack(m_state); // dereference the userdata object lua_rawgeti(m_state, LUA_REGISTRYINDEX, objectReference); // create a new table for the environment of the running script lua_newtable(m_state); // alias self to the entity's table lua_pushvalue(m_state, -2); lua_setfield(m_state, -2, "self"); // create a temporary metatable, redirect __index so that it first checks the local environment before the global lua_newtable(m_state); lua_pushglobaltable(m_state); lua_setfield(m_state, -2, "__index"); lua_setmetatable(m_state, -2); // push error handler lua_pushcfunction(m_state, ErrorHandler); // load the script if (luaL_loadbuffer(m_state, (const char *)script, scriptLength, source) != 0) { // todo: reorder this const char *errorMessage = lua_tostring(m_state, -1); if (errorMessage != nullptr) Log_ErrorPrintf("Script parse error: %s", errorMessage); // failed, pop both error handler, and the table lua_pop(m_state, 4); luaVerifyStack(m_state, 0); return ScriptCallResult_ParseError; } // set environment for execution to the environment for this script lua_pushvalue(m_state, -3); lua_setupvalue(m_state, -2, 1); // run the script int r = lua_pcall(m_state, 0, 0, -2); if (r != 0) { const char *errorMessage = lua_tostring(m_state, -1); if (errorMessage != nullptr) Log_ErrorPrintf("Script error: %s", errorMessage); // execution failed lua_pop(m_state, 4); luaVerifyStack(m_state, 0); return ScriptCallResult_RuntimeError; } // pop the error handler off, this should leave us with the environment table, object reference lua_pop(m_state, 1); // drop self from the environment table lua_pushnil(m_state); lua_setfield(m_state, -2, "self"); // copy everything out of the environment table into the entity's table lua_pushnil(m_state); while (lua_next(m_state, -2) != 0) { const char *key = lua_tostring(m_state, -2); Log_TracePrintf("ScriptManager::RunEntityScript: found %s - %s", key, lua_typename(m_state, lua_type(m_state, -1))); // skip non-functions if (!lua_isfunction(m_state, -1)) { lua_pop(m_state, 1); continue; } // set the key to the value, this will drop the value from the stack too // todo: optimize this to a lua_settable to avoid string allocation lua_setfield(m_state, -4, key); } // drop the environment table, and the dereferenced object lua_pop(m_state, 2); luaVerifyStack(m_state, 0); return ScriptCallResult_Success; } ScriptCallResult ScriptManager::BeginObjectMethodCall(ScriptReferenceType objectReference, const char *methodName) { // stack should be empty DebugAssert(lua_gettop(m_state) == 0); // todo: optimize me luaBackupStack(m_state); // dereference object lua_rawgeti(m_state, LUA_REGISTRYINDEX, objectReference); // do we have a method by this name? lua_getfield(m_state, -1, methodName); if (!lua_isfunction(m_state, -1)) { // nope, bail out lua_pop(m_state, 2); luaVerifyStack(m_state, 0); return ScriptCallResult_MethodNotFound; } // swap the object{self} and function around so that the function comes first lua_insert(m_state, -2); // push the error handler, rotate so that stack = errorhandler, function, self lua_pushcfunction(m_state, ErrorHandler); lua_insert(m_state, -3); luaVerifyStack(m_state, 3); return ScriptCallResult_Success; } ScriptCallResult ScriptManager::InvokeObjectMethodCall(bool saveResults /* = false */) { // error handler, function, self, args... int argCount = lua_gettop(m_state) - 2; DebugAssert(argCount > 0); // invoke pcall, pretty straightforward int r = lua_pcall(m_state, argCount, (saveResults) ? LUA_MULTRET : 0, 1); if (r != 0) { const char *errorMessage = lua_tostring(m_state, -1); if (errorMessage != nullptr) Log_ErrorPrintf("Script error: %s", errorMessage); // pop error message and handler lua_settop(m_state, 0); return ScriptCallResult_RuntimeError; } // saving results? if (!saveResults) { // empty the stack lua_settop(m_state, 0); } else { // remove error handler DebugAssert(lua_gettop(m_state) > 0); lua_remove(m_state, 0); } return ScriptCallResult_Success; } uint32 ScriptManager::GetCallResultCount() { int nResults = lua_gettop(m_state); DebugAssert(nResults >= 0); return (uint32)nResults; } void ScriptManager::EndCall() { // drop results lua_settop(m_state, 0); } ScriptThread::ScriptThread(lua_State *threadState, ScriptReferenceType threadReference) : m_pThreadState(threadState), m_threadReference(threadReference), m_waitChannel(""), m_timeout(DEFAULT_SCRIPT_TIMEOUT), m_timeoutAction(ScriptThreadTimeoutAction_Abort), m_yieldCount(0) { } ScriptThread::~ScriptThread() { g_pScriptManager->ReleaseReference(m_threadReference); } ScriptCallResult ScriptManager::BeginThreadedObjectMethodCall(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName) { // stack should be empty DebugAssert(lua_gettop(m_state) == 0); luaBackupStack(m_state); // dereference the object lua_rawgeti(m_state, LUA_REGISTRYINDEX, objectReference); // do we have a method by this name? //lua_getfield(m_state, -1, methodName); lua_pushstring(m_state, methodName); lua_gettable(m_state, -2); if (!lua_isfunction(m_state, -1)) { // nope, bail out lua_pop(m_state, 2); luaVerifyStack(m_state, 0); return ScriptCallResult_MethodNotFound; } // swap the object{self} and function around so that the function comes first lua_insert(m_state, -2); // allocate thread wrapper, and dereference the thread state. this is necessary to pin it and prevent gc lua_State *pThreadState = lua_newthread(m_state); ScriptReferenceType threadReference = CreateReference(m_state); ScriptThread *pThread = new ScriptThread(pThreadState, threadReference); *ppThread = pThread; // move the 2 stack elements from the global state to the thread state lua_xmove(m_state, pThread->m_pThreadState, 2); DebugAssert(lua_gettop(pThread->m_pThreadState) == 2); luaVerifyStack(m_state, 0); return ScriptCallResult_Success; } ScriptCallResult ScriptManager::ResumeThreadedObjectMethodCall(ScriptThread *pThread, bool saveResults /* = false */) { int argCount = lua_gettop(pThread->m_pThreadState); // if this is the initial call if (pThread->m_yieldCount == 0) { // function and self are provided in the initial call DebugAssert(argCount >= 2); argCount -= 2; } // use lua_resume instead of lua_pcall int r = lua_resume(pThread->m_pThreadState, nullptr, argCount); if (r == LUA_YIELD) { // we should have the three wait setup parameters DebugAssert(lua_gettop(pThread->m_pThreadState) == 3); // extract wait channel const char *waitChannel = lua_tostring(pThread->m_pThreadState, 1); if (waitChannel != nullptr && *waitChannel != '\0') pThread->m_waitChannel = waitChannel; else pThread->m_waitChannel = EmptyString; // extract timeout and action pThread->m_timeout = (float)lua_tonumber(pThread->m_pThreadState, 2); pThread->m_timeoutAction = (ScriptThreadTimeoutAction)lua_tointeger(pThread->m_pThreadState, 3); // pop yield args lua_pop(pThread->m_pThreadState, 3); // if this is the first yield, place the thread into the paused threads list if (pThread->m_yieldCount == 0) m_pausedThreads.Add(pThread); // increment yield count pThread->m_yieldCount++; return ScriptCallResult_Yielded; } // error case else if (r != 0) { const char *errorMessage = lua_tostring(pThread->m_pThreadState, -1); if (errorMessage != nullptr) Log_ErrorPrintf("Threaded script execution exception: %s", errorMessage); // the stack is remaining in its current state, it is not unwound. so we can execute a traceback from here. ScriptManager::DumpScriptTraceback(pThread->m_pThreadState); // remove from paused thread list if (pThread->m_yieldCount != 0) m_pausedThreads.OrderedRemove((uint32)m_pausedThreads.IndexOf(pThread)); // lose everything on the stack, and cleanup the thread lua_pop(pThread->m_pThreadState, lua_gettop(pThread->m_pThreadState)); delete pThread; // error return ScriptCallResult_RuntimeError; } // remove from paused thread list if (pThread->m_yieldCount != 0) m_pausedThreads.OrderedRemove((uint32)m_pausedThreads.IndexOf(pThread)); // if we're not interested in the results, cleanup the thread now if (!saveResults) { //DumpScriptStack(pThread->m_pThreadState); lua_settop(pThread->m_pThreadState, 0); delete pThread; } else { // seems to keep the self pointer on the stack in position 1.. dunno why? lua_remove(m_state, 1); } // execution ok return ScriptCallResult_Success; } int ScriptManager::YieldThreadedCall(lua_State *L, const char *waitChannel /* = "" */, float timeout /* = DEFAULT_SCRIPT_TIMEOUT */, ScriptThreadTimeoutAction timeoutAction /* = ScriptThreadTimeoutAction_Abort */) { lua_pushstring(L, waitChannel); lua_pushnumber(L, (lua_Number)timeout); lua_pushinteger(L, (lua_Integer)timeoutAction); return lua_yieldk(L, 3, 0, nullptr); } uint32 ScriptManager::GetThreadedCallResultCount(ScriptThread *pThread) { int nResults = lua_gettop(pThread->m_pThreadState); DebugAssert(nResults > 0); return (uint32)nResults; } void ScriptManager::AbortThreadedCall(ScriptThread *pThread) { // remove from list int32 index = m_pausedThreads.IndexOf(pThread); DebugAssert(index >= 0); m_pausedThreads.OrderedRemove((uint32)index); // clean up the thread delete pThread; } void ScriptManager::EndThreadedCall(ScriptThread *pThread) { // drop results lua_settop(pThread->m_pThreadState, 0); } void ScriptManager::CheckPausedThreadTimeout(float deltaTime) { for (uint32 i = 0; i < m_pausedThreads.GetSize(); ) { ScriptThread *pThread = m_pausedThreads[i]; if (deltaTime < pThread->m_timeout) { // timeout not elapsed yet pThread->m_timeout -= deltaTime; i++; continue; } // what's the timeout action? switch (pThread->m_timeoutAction) { case ScriptThreadTimeoutAction_ReturnNil: { // first return nil, then fall through and resume lua_pushnil(pThread->m_pThreadState); } case ScriptThreadTimeoutAction_Resume: { // resume thread execution ScriptCallResult executeResult = ResumeThreadedObjectMethodCall(pThread, false); if (executeResult == ScriptCallResult_Yielded) { // thread has yielded, it will still be in the list i++; } // thread has ended or thrown an error continue; } } // kill the thread, and remove it from the list Log_WarningPrintf("ScriptManager::CheckPausedThreadTimeout: Aborting thread %p due to timeout", pThread); m_pausedThreads.OrderedRemove(i); delete pThread; } } <file_sep>/Engine/Source/ResourceCompiler/ClassTableGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ClassTableGenerator.h" #include "Engine/DataFormats.h" #include "Core/PropertyTemplate.h" #include "Core/ClassTableDataFormat.h" ClassTableGenerator::Type::Type(uint32 index, const char *typeName) : m_index(index), m_typeName(typeName) { } ClassTableGenerator::Type::~Type() { for (uint32 i = 0; i < m_properties.GetSize(); i++) delete m_properties[i]; } const ClassTableGenerator::Type::PropertyDeclaration *ClassTableGenerator::Type::GetPropertyDeclarationByName(const char *name) const { for (uint32 i = 0; i < m_properties.GetSize(); i++) { if (m_properties[i]->Name.CompareInsensitive(name)) return m_properties[i]; } return nullptr; } const ClassTableGenerator::Type::PropertyDeclaration *ClassTableGenerator::Type::AddPropertyDeclaration(const char *name, PROPERTY_TYPE type) { for (uint32 i = 0; i < m_properties.GetSize(); i++) { if (m_properties[i]->Name.CompareInsensitive(name)) return nullptr; } PropertyDeclaration *decl = new PropertyDeclaration(); decl->Index = m_properties.GetSize(); decl->Name = name; decl->Type = type; m_properties.Add(decl); return decl; } ClassTableGenerator::ClassTableGenerator() { } ClassTableGenerator::~ClassTableGenerator() { for (uint32 i = 0; i < m_types.GetSize(); i++) delete m_types[i]; } const ClassTableGenerator::Type *ClassTableGenerator::GetTypeByName(const char *name) const { for (uint32 i = 0; i < m_types.GetSize(); i++) { if (m_types[i]->GetTypeName().CompareInsensitive(name)) return m_types[i]; } return nullptr; } const ClassTableGenerator::Type *ClassTableGenerator::CreateType(const char *name) { for (uint32 i = 0; i < m_types.GetSize(); i++) { if (m_types[i]->GetTypeName().CompareInsensitive(name)) return nullptr; } Type *type = new Type(m_types.GetSize(), name); m_types.Add(type); return type; } const ClassTableGenerator::Type *ClassTableGenerator::CreateTypeFromPropertyTemplate(const char *name, const PropertyTemplate *pPropertyTemplate) { for (uint32 i = 0; i < m_types.GetSize(); i++) { if (m_types[i]->GetTypeName().CompareInsensitive(name)) return nullptr; } Type *type = new Type(m_types.GetSize(), name); m_types.Add(type); for (uint32 propIndex = 0; propIndex < pPropertyTemplate->GetPropertyDefinitionCount(); propIndex++) { const PropertyTemplateProperty *pProperty = pPropertyTemplate->GetPropertyDefinition(propIndex); type->AddPropertyDeclaration(pProperty->GetName(), pProperty->GetType()); } return type; } const ClassTableGenerator::Type *ClassTableGenerator::CreateTypeFromPropertyDeclarationList(const char *name, const PROPERTY_DECLARATION **ppProperties, uint32 nProperties) { for (uint32 i = 0; i < m_types.GetSize(); i++) { if (m_types[i]->GetTypeName().CompareInsensitive(name)) return nullptr; } Type *type = new Type(m_types.GetSize(), name); m_types.Add(type); for (uint32 propIndex = 0; propIndex < nProperties; propIndex++) type->AddPropertyDeclaration(ppProperties[propIndex]->Name, ppProperties[propIndex]->Type); return type; } bool ClassTableGenerator::Compile(ByteStream *pStream) { // build the header uint64 headerOffset = pStream->GetPosition(); DF_CLASS_TABLE_HEADER classTableHeader; classTableHeader.Magic = DF_CLASS_TABLE_HEADER_MAGIC; classTableHeader.TotalSize = sizeof(DF_CLASS_TABLE_HEADER); classTableHeader.HeaderSize = sizeof(DF_CLASS_TABLE_HEADER); classTableHeader.TypeCount = m_types.GetSize(); if (!pStream->Write2(&classTableHeader, sizeof(classTableHeader))) return false; // write types for (uint32 typeIndex = 0; typeIndex < m_types.GetSize(); typeIndex++) { const Type *type = m_types[typeIndex]; uint64 typeStartOffset = pStream->GetPosition(); // we write the header bits out manually here byte typeHeaderBuffer[sizeof(DF_CLASS_TABLE_TYPE)]; DF_CLASS_TABLE_TYPE *typeHeader = reinterpret_cast<DF_CLASS_TABLE_TYPE *>(typeHeaderBuffer); typeHeader->TotalSize = sizeof(DF_CLASS_TABLE_TYPE) + type->GetTypeName().GetLength(); typeHeader->PropertyCount = type->GetPropertyDeclarationCount(); typeHeader->TypeNameLength = type->GetTypeName().GetLength(); if (!pStream->Write2(typeHeader, sizeof(*typeHeader)) || !pStream->Write2(type->GetTypeName().GetCharArray(), typeHeader->TypeNameLength)) return false; // write properties for (uint32 propIndex = 0; propIndex < type->GetPropertyDeclarationCount(); propIndex++) { const Type::PropertyDeclaration *propDeclaration = type->GetPropertyDeclarationByIndex(propIndex); byte propHeaderBuffer[sizeof(DF_CLASS_TABLE_TYPE_PROPERTY)]; DF_CLASS_TABLE_TYPE_PROPERTY *propHeader = reinterpret_cast<DF_CLASS_TABLE_TYPE_PROPERTY *>(propHeaderBuffer); propHeader->PropertyType = (uint32)propDeclaration->Type; propHeader->PropertyNameLength = propDeclaration->Name.GetLength(); if (!pStream->Write2(propHeader, sizeof(*propHeader)) || !pStream->Write2(propDeclaration->Name.GetCharArray(), propHeader->PropertyNameLength)) return false; typeHeader->TotalSize += sizeof(*propHeader) + propHeader->PropertyNameLength; } // update type header size uint64 reseekOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(typeStartOffset) || !pStream->Write2(typeHeader, sizeof(*typeHeader)) || !pStream->SeekAbsolute(reseekOffset)) return false; // update overall size classTableHeader.TotalSize += typeHeader->TotalSize; } // update header size uint64 reseekOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(headerOffset) || !pStream->Write2(&classTableHeader, sizeof(classTableHeader)) || !pStream->SeekAbsolute(reseekOffset)) return false; return true; } bool ClassTableGenerator::SerializeObjectBinary(ByteStream *pStream, const char *typeName, const PropertyTemplate *pPropertyTemplate, const PropertyTable *pPropertyTable, uint32 *pTypeIndex, uint32 *pWrittenBytes) const { // get template const Type *typeInfo = GetTypeByName(typeName); if (typeInfo == nullptr) return false; // create temporary stream AutoReleasePtr<ByteStream> pTemporaryStream = ByteStream_CreateGrowableMemoryStream(); // write the object header uint32 writtenBytes = 0; //DF_SERIALIZED_OBJECT_HEADER objectHeader; //objectHeader.TypeIndex = typeInfo->GetIndex(); //objectHeader.TotalSize = sizeof(objectHeader); //pTemporaryStream->Write2(&objectHeader, sizeof(objectHeader)); // write properties for (uint32 propIndex = 0; propIndex < typeInfo->GetPropertyDeclarationCount(); propIndex++) { const Type::PropertyDeclaration *propDeclaration = typeInfo->GetPropertyDeclarationByIndex(propIndex); // does this property even exist? const String *propertyValue = pPropertyTable->GetPropertyValuePointer(propDeclaration->Name); if (propertyValue == nullptr) { // use the default value from the template const PropertyTemplateProperty *pTemplateProperty = pPropertyTemplate->GetPropertyDefinitionByName(propDeclaration->Name); if (pTemplateProperty == nullptr) return false; // store it propertyValue = &pTemplateProperty->GetDefaultValue(); } uint32 propertySize; if (!SerializePropertyValueStringAsNativeType(propDeclaration->Type, *propertyValue, pTemporaryStream, &propertySize)) return false; //objectHeader.TotalSize += propertySize; writtenBytes += propertySize; } // copy back to main stream if (pTypeIndex != nullptr) *pTypeIndex = typeInfo->GetIndex(); if (pWrittenBytes != nullptr) *pWrittenBytes = writtenBytes; return ByteStream_AppendStream(pTemporaryStream, pStream); } bool ClassTableGenerator::SerializePropertyValueStringAsNativeType(PROPERTY_TYPE propertyType, const char *propertyValueString, ByteStream *pOutputStream, uint32 *pWrittenBytes) { if (propertyType == PROPERTY_TYPE_STRING) { // Write out the structure individually uint32 stringLength = Y_strlen(propertyValueString) + 1; if (pWrittenBytes != nullptr) *pWrittenBytes = sizeof(uint32) + stringLength; return (pOutputStream->Write2(&stringLength, sizeof(stringLength)) && pOutputStream->Write2(propertyValueString, stringLength)); } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte tempBuffer[4 + 32]; DF_SERIALIZED_OBJECT_PROPERTY *propData = reinterpret_cast<DF_SERIALIZED_OBJECT_PROPERTY *>(tempBuffer); // Un-stringize based on type. switch (propertyType) { case PROPERTY_TYPE_BOOL: { bool value = StringConverter::StringToBool(propertyValueString); propData->DataSize = 1; propData->Data[0] = (value ? 1 : 0); } break; case PROPERTY_TYPE_UINT: { uint32 value = StringConverter::StringToUInt32(propertyValueString); uint32 *dest = reinterpret_cast<uint32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_INT: { int32 value = StringConverter::StringToInt32(propertyValueString); int32 *dest = reinterpret_cast<int32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_INT2: { int2 value(StringConverter::StringToInt2(propertyValueString)); DF_STRUCT_INT2 *dest = reinterpret_cast<DF_STRUCT_INT2 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; } break; case PROPERTY_TYPE_INT3: { int3 value(StringConverter::StringToInt3(propertyValueString)); DF_STRUCT_INT3 *dest = reinterpret_cast<DF_STRUCT_INT3 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; } break; case PROPERTY_TYPE_INT4: { int4 value(StringConverter::StringToInt4(propertyValueString)); DF_STRUCT_INT4 *dest = reinterpret_cast<DF_STRUCT_INT4 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_FLOAT: { float value = StringConverter::StringToFloat(propertyValueString); float *dest = reinterpret_cast<float *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; case PROPERTY_TYPE_FLOAT2: { float2 value(StringConverter::StringToFloat2(propertyValueString)); DF_STRUCT_FLOAT2 *dest = reinterpret_cast<DF_STRUCT_FLOAT2 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; } break; case PROPERTY_TYPE_FLOAT3: { float3 value(StringConverter::StringToFloat3(propertyValueString)); DF_STRUCT_FLOAT3 *dest = reinterpret_cast<DF_STRUCT_FLOAT3 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; } break; case PROPERTY_TYPE_FLOAT4: { float4 value(StringConverter::StringToFloat4(propertyValueString)); DF_STRUCT_FLOAT4 *dest = reinterpret_cast<DF_STRUCT_FLOAT4 *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_QUATERNION: { Quaternion value(StringConverter::StringToQuaternion(propertyValueString)); DF_STRUCT_QUATERNION *dest = reinterpret_cast<DF_STRUCT_QUATERNION *>(propData->Data); propData->DataSize = sizeof(*dest); dest->x = value.x; dest->y = value.y; dest->z = value.z; dest->w = value.w; } break; case PROPERTY_TYPE_TRANSFORM: { Transform value(StringConverter::StringToTranform(propertyValueString)); DF_STRUCT_TRANSFORM *dest = reinterpret_cast<DF_STRUCT_TRANSFORM *>(propData->Data); propData->DataSize = sizeof(*dest); dest->Position.x = value.GetPosition().x; dest->Position.y = value.GetPosition().y; dest->Position.z = value.GetPosition().z; dest->Rotation.x = value.GetRotation().x; dest->Rotation.y = value.GetRotation().y; dest->Rotation.z = value.GetRotation().z; dest->Rotation.w = value.GetRotation().w; dest->Scale.x = value.GetScale().x; dest->Scale.y = value.GetScale().y; dest->Scale.z = value.GetScale().z; } break; case PROPERTY_TYPE_COLOR: { uint32 value = StringConverter::StringToColor(propertyValueString); uint32 *dest = reinterpret_cast<uint32 *>(propData->Data); propData->DataSize = sizeof(*dest); *dest = value; } break; default: UnreachableCode(); break; } // Write to the stream if (pWrittenBytes != nullptr) *pWrittenBytes = sizeof(DF_SERIALIZED_OBJECT_PROPERTY) + propData->DataSize; DebugAssert(propData->DataSize < (sizeof(tempBuffer) - sizeof(DF_SERIALIZED_OBJECT_PROPERTY))); return pOutputStream->Write2(tempBuffer, sizeof(DF_SERIALIZED_OBJECT_PROPERTY) + propData->DataSize); } } <file_sep>/Engine/Source/ResourceCompiler/SkeletalMeshGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/SkeletalMesh.h" struct ResourceCompilerCallbacks; namespace Physics { class CollisionShapeGenerator; } class SkeletalMeshGenerator { public: struct Bone { uint32 Index; String Name; Transform LocalToBoneTransform; Bone(uint32 index, const char *name, const Transform &localToBoneTransform) : Index(index), Name(name), LocalToBoneTransform(localToBoneTransform) {} }; struct Vertex { float3 Position; float3 Tangent; float3 Binormal; float3 Normal; float2 TextureCoordinates; uint32 Color; int32 BoneIndices[SKELETAL_MESH_MAX_BONES_PER_VERTEX]; float BoneWeights[SKELETAL_MESH_MAX_BONES_PER_VERTEX]; }; struct Triangle { uint32 MaterialIndex; uint64 SmoothingGroups; uint32 VertexIndices[3]; }; // struct Batch // { // uint32 MaterialIndex; // uint32 WeightCount; // uint32 FirstTriangle; // uint32 TriangleCount; // }; public: SkeletalMeshGenerator(); ~SkeletalMeshGenerator(); // skeleton const String &GetSkeletonName() const { return m_skeletonName; } void SetSkeletonName(const char *skeletonName) { m_skeletonName = skeletonName; } // flags bool GetProvideVertexTextureCoordinates() const { return m_provideVertexTextureCoordinates; } void SetProvideVertexTextureCoordinates(bool on) { m_provideVertexTextureCoordinates = on; } bool GetProvideVertexColors() const { return m_provideVertexTextureCoordinates; } void SetProvideVertexColors(bool on) { m_provideVertexTextureCoordinates = on; } // bones const uint32 GetBoneNameCount() const { return m_bones.GetSize(); } const Bone *GetBoneByIndex(uint32 i) const { return &m_bones[i]; } const int32 FindBoneIndexByName(const char *boneName) const; Bone *GetBoneByIndex(uint32 i) { return &m_bones[i]; } Bone *AddBone(const char *boneName, const Transform &localToBoneTransform); // materials const uint32 GetMaterialNameCount() const { return m_materialNames.GetSize(); } const String &GetMaterialNameByIndex(uint32 i) const { return m_materialNames[i]; } const int32 FindMaterialNameIndex(const char *materialName) const; const uint32 AddMaterialName(const char *materialName); // add already-complete vertex uint32 AddVertex(const Vertex &vertex); // add a vertex without any bones yet uint32 AddVertex(const float3 &position, const float2 &textureCoordinates); uint32 AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &normal); uint32 AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &tangent, const float3 &binormal, const float3 &normal); // coordinates are assumed to be in local space uint32 AddVertex(const float3 &position, const float2 &textureCoordinates, const int32 *pBoneIndices, const float *pBoneWeights); uint32 AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &normal, const int32 *pBoneIndices, const float *pBoneWeights); uint32 AddVertex(const float3 &position, const float2 &textureCoordinates, const float3 &tangent, const float3 &binormal, const float3 &normal, const int32 *pBoneIndices, const float *pBoneWeights); // triangles uint32 AddTriangle(uint32 materialNameIndex, uint64 smoothingGroups, uint32 v0, uint32 v1, uint32 v2); uint32 AddTriangle(uint32 materialNameIndex, uint64 smoothingGroups, const uint32 *pIndices); // tangent space building void CalculateTangentVectors(); void CalculateTangentVectorsAndNormals(); // Loading interface (from XML) bool LoadFromXML(const char *FileName, ByteStream *pStream); // Output interface bool SaveToXML(ByteStream *pStream) const; bool Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const; // Collision shapes bool BuildBoxCollisionShape(); bool BuildSphereCollisionShape(); bool BuildTriangleMeshCollisionShape(); bool BuildConvexHullCollisionShape(); void SetCollisionShape(Physics::CollisionShapeGenerator *pGenerator); void RemoveCollisionShape(); private: bool m_provideVertexTextureCoordinates; bool m_provideVertexColors; String m_skeletonName; Array<Bone> m_bones; Array<String> m_materialNames; MemArray<Vertex> m_vertices; MemArray<Triangle> m_triangles; Physics::CollisionShapeGenerator *m_pCollisionShapeGenerator; }; <file_sep>/DemoGame/Source/DemoGame/SkeletalAnimationDemo.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/SkeletalAnimationDemo.h" #include "DemoGame/DemoUtilities.h" #include "Engine/World.h" #include "Renderer/RenderWorld.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(SkeletalAnimationDemo); static const char *MODEL_LIST = "Ninja\0\0"; SkeletalAnimationDemo::SkeletalAnimationDemo(DemoGame *pDemoGame) : BaseDemoWorldGameState(pDemoGame) , m_pSunLightEntity(nullptr) , m_sunLightRotation(float3::Zero) , m_pSkeletalMeshRenderProxy(nullptr) , m_skeletalMeshIndex(0) , m_skeletalAnimationIndex(0) { } SkeletalAnimationDemo::~SkeletalAnimationDemo() { SAFE_RELEASE(m_pSkeletalMeshRenderProxy); SAFE_RELEASE(m_pSunLightEntity); } bool SkeletalAnimationDemo::Initialize() { if (!BaseDemoWorldGameState::Initialize()) return false; if (!CreateDynamicWorld()) return false; // init view m_viewParameters.MaximumShadowViewDistance = 500.0f; m_viewParameters.EnableBloom = false; m_viewParameters.EnableManualExposure = true; m_viewParameters.ManualExposure = 1.0f; return true; } bool SkeletalAnimationDemo::OnWorldCreated(World *pWorld) { if (!BaseDemoWorldGameState::OnWorldCreated(pWorld)) return false; // sun entity //m_pSunLightEntity = DemoUtilities::CreateSunLight(m_pWorld, float3(1.0f, 1.0f, 1.0f), 1.2f, 0.4f); m_pSunLightEntity = DemoUtilities::CreateSunLight(m_pWorld, float3(1.0f, 0.992f, 0.8f), 1.2f, 0.4f); // ground plane AutoReleasePtr<const Material> pGroundPlaneMaterial = g_pResourceManager->GetDefaultMaterial(); AutoReleasePtr<Entity> pGroundPlaneEntity = DemoUtilities::CreatePlaneShape(m_pWorld, float3::UnitZ, float3(0.0f, 0.0f, 0.0f), 100.0f, pGroundPlaneMaterial, 10.0f); // set model, this creates the renderable too if (!SetModelIndex(0)) return false; // done return true; } void SkeletalAnimationDemo::Shutdown() { BaseDemoWorldGameState::Shutdown(); } void SkeletalAnimationDemo::OnWorldDeleted(World *pWorld) { BaseDemoWorldGameState::OnWorldDeleted(pWorld); } void SkeletalAnimationDemo::OnMainThreadTick(float deltaTime) { BaseDemoWorldGameState::OnMainThreadTick(deltaTime); if (m_sunLightRotation.SquaredLength() > 0.0f) m_pSunLightEntity->SetRotation((m_pSunLightEntity->GetRotation() * Quaternion::FromEulerAngles(m_sunLightRotation.x * deltaTime, m_sunLightRotation.y * deltaTime, 0.0f)).Normalize()); // no thread safety here captain :( m_skeletalAnimationPlayer.Update(deltaTime); m_skeletalAnimationPlayer.UpdateMeshState(); m_skeletalAnimationPlayer.UpdateSkeletalMeshRenderProxy(m_pSkeletalMeshRenderProxy); //for (uint32 i = 0; i < m_pSkeletalMeshRenderProxy->GetSkeletalMesh()->GetSkeleton()->GetBoneCount(); i++) //m_pSkeletalMeshRenderProxy->SetBoneTransforms(i, 1, &float3x4::Identity); } void SkeletalAnimationDemo::DrawOverlays(float deltaTime) { BaseDemoWorldGameState::DrawOverlays(deltaTime); } void SkeletalAnimationDemo::DrawUI(float deltaTime) { BaseDemoWorldGameState::DrawUI(deltaTime); ImGui::SetNextWindowPos(ImVec2(10, float(m_viewParameters.Viewport.Height - 250)), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(320, 240), ImGuiSetCond_FirstUseEver); // annoyingly, everything is drawn on the UI thread yet commands have to be invoked on the main thread.. if (ImGui::Begin("Skeletal Animation Demo")) { int intValue; float floatValue; bool boolValue; ImGui::PushItemWidth(-140.0f); intValue = m_skeletalMeshIndex; if (ImGui::Combo("Mesh", &intValue, MODEL_LIST)) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, intValue]() { SetModelIndex(intValue); }); } // eww ugly, @TODO cache this? { char animationNamesList[512]; uint32 animationNamesListPos = 0; for (const char *animationName : m_animationNames) { const char *partAnimationName = Y_strrchr(animationName, '/'); if (partAnimationName != nullptr) partAnimationName++; else partAnimationName = animationName; uint32 len = Y_strlen(partAnimationName); if ((animationNamesListPos + len + 1) < countof(animationNamesList)) { Y_memcpy(animationNamesList + animationNamesListPos, partAnimationName, len + 1); animationNamesListPos += len + 1; } else { break; } } animationNamesListPos = Min(animationNamesListPos, uint32(countof(animationNamesList) - 7)); Y_strncpy(animationNamesList + animationNamesListPos, 5, "None"); animationNamesListPos += 5; animationNamesList[animationNamesListPos++] = '\0'; intValue = m_skeletalAnimationIndex; if (ImGui::Combo("Animation", &intValue, animationNamesList)) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, intValue]() { SetAnimationIndex(intValue); }); } } floatValue = m_skeletalAnimationPlayer.GetChannelPlaybackSpeed(0); if (ImGui::InputFloat("Playback Speed", &floatValue, 0.1f, 0.5f, 2)) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, floatValue]() { m_skeletalAnimationPlayer.SetPlaybackSpeed(floatValue, 0); }); } boolValue = m_skeletalAnimationPlayer.GetChannelPlaying(0); if (ImGui::Button(boolValue ? "Pause" : "Resume")) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, boolValue]() { (m_skeletalAnimationPlayer.GetChannelPlaying(0)) ? m_skeletalAnimationPlayer.PauseAnimation(0) : m_skeletalAnimationPlayer.ResumeAnimation(0); }); } // @TODO model rotation/scale/etc ImGui::PopItemWidth(); } ImGui::End(); } bool SkeletalAnimationDemo::OnWindowEvent(const union SDL_Event *event) { if (event->type == SDL_KEYDOWN) { switch (event->key.keysym.sym) { case SDLK_PAGEUP: { if (m_skeletalAnimationIndex == 0) SetAnimationIndex(m_animationNames.GetSize()); else SetAnimationIndex(m_skeletalAnimationIndex - 1); return true; } break; case SDLK_PAGEDOWN: { if (m_skeletalAnimationIndex == m_animationNames.GetSize()) SetAnimationIndex(0); else SetAnimationIndex(m_skeletalAnimationIndex + 1); return true; } break; case SDLK_1: SetModelIndex(0); break; case SDLK_2: SetModelIndex(1); break; case SDLK_KP_PLUS: { m_skeletalAnimationPlayer.SetPlaybackSpeed(m_skeletalAnimationPlayer.GetChannelPlaybackSpeed(0) + 0.25f, 0); return true; } break; case SDLK_KP_MINUS: { m_skeletalAnimationPlayer.SetPlaybackSpeed(m_skeletalAnimationPlayer.GetChannelPlaybackSpeed(0) - 0.25f, 0); return true; } break; case SDLK_SPACE: { if (m_skeletalAnimationPlayer.GetChannelPlaying(0)) m_skeletalAnimationPlayer.PauseAnimation(); else m_skeletalAnimationPlayer.ResumeAnimation(); return true; } break; } } if (event->type == SDL_KEYDOWN || event->type == SDL_KEYUP) { bool isKeyDownEvent = (event->type == SDL_KEYDOWN); switch (event->key.keysym.sym) { case SDLK_LEFT: m_sunLightRotation.x += (isKeyDownEvent) ? -1.0f : 1.0f; return true; case SDLK_RIGHT: m_sunLightRotation.x += (isKeyDownEvent) ? 1.0f : -1.0f; return true; case SDLK_UP: m_sunLightRotation.y += (isKeyDownEvent) ? 1.0f : -1.0f; return true; case SDLK_DOWN: m_sunLightRotation.y += (isKeyDownEvent) ? -1.0f : 1.0f; return true; } } return BaseDemoWorldGameState::OnWindowEvent(event); } bool SkeletalAnimationDemo::SetModelIndex(uint32 index) { AutoReleasePtr<const SkeletalMesh> pSkeletalMesh; Transform transform(Transform::Identity); if (index == 0) { // ninja if ((pSkeletalMesh = g_pResourceManager->GetSkeletalMesh("models/ninja/ninja")) == nullptr) return false; m_animationNames.Clear(); m_animationNames.Add("models/ninja/ninja_walk"); m_animationNames.Add("models/ninja/ninja_stealth_walk"); m_animationNames.Add("models/ninja/ninja_punch_swipe"); m_animationNames.Add("models/ninja/ninja_swipe_spin"); m_animationNames.Add("models/ninja/ninja_twohand_swipe"); m_animationNames.Add("models/ninja/ninja_block"); m_animationNames.Add("models/ninja/ninja_kick"); m_animationNames.Add("models/ninja/ninja_crouch_start"); m_animationNames.Add("models/ninja/ninja_crouch_end"); m_animationNames.Add("models/ninja/ninja_jump"); m_animationNames.Add("models/ninja/ninja_jump_noheight"); m_animationNames.Add("models/ninja/ninja_jump_attack"); m_animationNames.Add("models/ninja/ninja_sidekick"); m_animationNames.Add("models/ninja/ninja_spin_attack"); m_animationNames.Add("models/ninja/ninja_backflip"); m_animationNames.Add("models/ninja/ninja_climbwall"); m_animationNames.Add("models/ninja/ninja_death_forwards"); m_animationNames.Add("models/ninja/ninja_death_backwards"); m_animationNames.Add("models/ninja/ninja_idle_1"); m_animationNames.Add("models/ninja/ninja_idle_2"); m_animationNames.Add("models/ninja/ninja_idle_3"); transform.Set(float3(0.0f, 0.0f, 1.0f), Quaternion::Identity, float3::One); } else { return false; } // not initializing if (m_pSkeletalMeshRenderProxy == nullptr) { m_pSkeletalMeshRenderProxy = new SkeletalMeshRenderProxy(0, pSkeletalMesh, Transform::Identity, ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); m_pWorld->GetRenderWorld()->AddRenderable(m_pSkeletalMeshRenderProxy); } m_skeletalMeshIndex = index; m_pSkeletalMeshRenderProxy->SetSkeletalMesh(pSkeletalMesh); m_skeletalAnimationPlayer.SetSkeletalMesh(pSkeletalMesh); m_skeletalAnimationPlayer.ClearAllAnimations(); m_skeletalAnimationIndex = m_animationNames.GetSize(); // this needs to be fixed properly, ugh. because we're not being threadsafe main thread changes the animations.. QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([](){}); ResetCamera(); return true; } bool SkeletalAnimationDemo::SetAnimationIndex(uint32 index) { DebugAssert(index <= m_animationNames.GetSize()); m_skeletalAnimationIndex = index; if (m_skeletalAnimationIndex == m_animationNames.GetSize()) { m_skeletalAnimationPlayer.ClearAnimation(); return true; } AutoReleasePtr<const SkeletalAnimation> pSkeletalAnimation = g_pResourceManager->GetSkeletalAnimation(m_animationNames[m_skeletalAnimationIndex]); if (pSkeletalAnimation == nullptr) { Log_ErrorPrintf("Failed to load skeletal animation '%s'", m_animationNames[m_skeletalAnimationIndex]); m_skeletalAnimationPlayer.ClearAnimation(); return false; } m_skeletalAnimationPlayer.PlayAnimation(pSkeletalAnimation, 1.0f, -1, true); return true; } void SkeletalAnimationDemo::ResetCamera() { const float3 moveVec(1.0f, -1.0f, 1.0f); const Sphere &boundingSphere = m_pSkeletalMeshRenderProxy->GetBoundingSphere(); float3 cameraPos(boundingSphere.GetCenter() + moveVec * (boundingSphere.GetRadius() * 2.5f)); m_camera.SetPosition(cameraPos); m_camera.SetRotation(Quaternion::FromEulerAngles(-30.0f, 0.0f, 45.0f)); } bool LaunchpadGameState::InvokeSkeletalAnimationDemo() { return RunDemo(new SkeletalAnimationDemo(m_pDemoGame)); } <file_sep>/Engine/Source/MapCompiler/MapCompiler.h #pragma once #include "MapCompiler/Common.h" #include "YBaseLib/ProgressCallbacks.h" #define BUILDER_BRUSH_ENTITY_ID 0 class MapSource; class MapSourceEntityData; class ObjectTemplate; class ChunkFileWriter; class ZipArchive; class ClassTable; class ClassTableGenerator; class MapCompiler { public: MapCompiler(MapSource *pMapSource); ~MapCompiler(); bool StartFreshCompile(ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool StartReuseCompile(ByteStream *pInputStream, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // overrides void SetOverrideRegionLODLevels(uint32 lodLevels) { DebugAssert(lodLevels >= 1); m_regionLODLevels = lodLevels; } void SetOverrideRegionLoadRadius(uint32 loadRadius) { DebugAssert(loadRadius > 0); m_regionLoadRadius = loadRadius; } void SetOverrideRegionActivationRadius(uint32 activationRadius) { DebugAssert(activationRadius > 0); m_regionActivationRadius = activationRadius; } // build everything for a map, if mapLOD is set to -1, all lods will be built bool BuildAll(int32 mapLOD = -1, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // build the global entities bool BuildGlobalEntities(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // build the entirety of a region bool BuildRegion(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // build the entities component of a region bool BuildRegionEntities(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // build the terrain component of a region bool BuildRegionTerrain(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // finalize the compile bool FinalizeCompile(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // discard the compile results void DiscardCompile(); private: ////////////////////////////////////////////////////////////////////////// // LOD LEVEL GENERATION ////////////////////////////////////////////////////////////////////////// bool BuildRegionLOD(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool BuildRegionLODEntities(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool BuildRegionLODTerrain(int32 regionX, int32 regionY, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); private: ////////////////////////////////////////////////////////////////////////// // HEADER ////////////////////////////////////////////////////////////////////////// // common stuff MapSource *m_pMapSource; ByteStream *m_pInputStream; ByteStream *m_pOutputStream; ZipArchive *m_pOutputArchive; // class table ClassTableGenerator *m_pClassTableGenerator; // lod levels uint32 m_regionSize; uint32 m_regionLODLevels; uint32 m_regionLoadRadius; uint32 m_regionActivationRadius; // world bounding box AABox m_worldBoundingBox; void UpdateWorldBoundingBox(const AABox &boundingBox); void UpdateWorldBoundingBox(const float3 &point); ////////////////////////////////////////////////////////////////////////// // COMPILATION ////////////////////////////////////////////////////////////////////////// // this structure contains a binary block of entity data for a region struct RegionEntityData { RegionEntityData(uint32 entityCount, BinaryBlob *data) : EntityCount(entityCount), pData(data) {} ~RegionEntityData() { pData->Release(); } uint32 EntityCount; BinaryBlob *pData; }; // build region entity data from a list of entities bool CompileEntityDataSingle(const MapSourceEntityData *pEntityData, const ObjectTemplate *pTemplate, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks); bool CompileEntityData(const MapSourceEntityData *const *ppEntities, uint32 entityCount, RegionEntityData **ppOutData, ProgressCallbacks *pProgressCallbacks); // this structure contains a binary block of terrain data for a section inside a region struct RegionTerrainSectionData { RegionTerrainSectionData(int32 sectionX, int32 sectionY, BinaryBlob *data) : SectionX(sectionX), SectionY(sectionY), pData(data) {} ~RegionTerrainSectionData() { pData->Release(); } int32 SectionX; int32 SectionY; BinaryBlob *pData; }; // build terrain data for a terrain section inside a region bool CompileTerrainSection(int32 sectionX, int32 sectionY, RegionTerrainSectionData **ppOutData); // run preparation steps bool PrepareSourceForCompiling(ProgressCallbacks *pProgressCallbacks); ////////////////////////////////////////////////////////////////////////// // REGIONS ////////////////////////////////////////////////////////////////////////// // region information struct Region { Region(MapCompiler *pMapCompiler, int32 regionX, int32 regionY, uint32 lodLevel); ~Region(); MapCompiler *pMapCompiler; int32 RegionX; int32 RegionY; uint32 RegionLODLevel; bool RegionExistsInCurrentStream; bool RegionExistsInNewStream; bool RegionLoaded; bool RegionChanged; // terrain information from the NEW source MemArray<int2> NewTerrainSections; // terrain information for either freshly compiled source, or current compiled data PODArray<RegionTerrainSectionData *> CompiledTerrainData; // block terrain information from the NEW source MemArray<int2> NewBlockTerrainSections; // entity information from the NEW source PODArray<const MapSourceEntityData *> NewEntityRefs; // entity information for either freshly compiled source, or current compiled data RegionEntityData *CompiledEntityData; // build new terrain data for this region bool RecompileTerrainData(ProgressCallbacks *pProgressCallbacks); // build new entity data for this region bool RecompileEntityData(ProgressCallbacks *pProgressCallbacks); // load any missing data bool LoadData(); }; // array of regions PODArray<Region *> m_regions; // helper to obtain a region pointer Region *CreateRegion(int32 regionX, int32 regionY, uint32 lodLevel); Region *GetRegion(int32 regionX, int32 regionY, uint32 lodLevel); // create any regions that exist due to entities, terrain or block terrain void CreateRegions(ProgressCallbacks *pProgressCallbacks); void CreateRegions_Entities(ProgressCallbacks *pProgressCallbacks); void CreateRegions_Terrain(ProgressCallbacks *pProgressCallbacks); // save region to the output archive bool SaveRegion(Region *pRegion); // load regions from current map bool SaveMapHeader(); // other headers bool SaveRegionsHeader(); bool SaveTerrainHeader(); bool SaveClassTable(); // global entities PODArray<const MapSourceEntityData *> m_newGlobalEntityRefs; RegionEntityData *m_pGlobalEntityData; bool LoadGlobalEntityData(); bool CompileGlobalEntityData(ProgressCallbacks *pProgressCallbacks); bool SaveGlobalEntityData(); #if 0 ////////////////////////////////////////////////////////////////////////// // STATIC LIGHTING MESH DATA ////////////////////////////////////////////////////////////////////////// // static mesh information, used mainly for static lighting enum LightingMeshType { LightingMeshType_StaticMesh, LightingMeshType_StaticBlockMesh, LightingMeshType_Count, }; struct LightingMeshData { LightingMeshType MeshType; String MeshResourceName; AABox BoundingBox; Sphere BoundingSphere; struct Triangle { struct Vertex { float3 Position; float3 Normal; bool UseNormalMap; const Texture2D *pNormalMapTexture; float3 NormalMapCoordinates; }; }; MemArray<Triangle> Triangles; }; // get lighting mesh information LightingMeshData *GetLightingMeshData(LightingMeshType type, const String &resourceName); bool GetLightingMeshBounds(LightingMeshType type, const String &resourceName, AABox *pBoundingBox, Sphere *pBoundingSphere); ////////////////////////////////////////////////////////////////////////// // STATIC LIGHTING INSTANCE DATA ////////////////////////////////////////////////////////////////////////// struct LightingMeshInstanceData { LightingMeshType MeshType; String ResourceName; Transform MeshTransform; AABox BoundingBox; Sphere BoundingSphere; }; PODArray<LightingMeshInstanceData *> m_lightingMeshInstanceData; // generate lighting mesh instance data bool GenerateLightingMeshInstanceData(); // get a list of all lighting meshes intersecting the specified bounding box void GetLightingMeshesIntersectingBoundingBox(const AABox &boundingBox, PODArray<LightingMeshInstanceData *> *pInstances); #endif }; <file_sep>/Engine/Source/GameFramework/SunLightEntity.h #pragma once #include "Engine/Entity.h" class DirectionalLightRenderProxy; class SunLightEntity : public Entity { DECLARE_ENTITY_TYPEINFO(SunLightEntity, Entity); DECLARE_ENTITY_GENERIC_FACTORY(SunLightEntity); public: struct Step { float Hours; float Minutes; float3 Direction; uint32 Color; float Brightness; float AmbientTerm; float StartTime; }; public: SunLightEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~SunLightEntity(); // steps void AddStep(float hours, float minutes, const float3 &direction, uint32 color, float brightness, float ambientTerm); void AddDefaultSteps(); // time of day const float GetTimeOfDay() const { return m_timeOfDay; } const float GetTimeOfDayHours() const { return Math::Floor(m_timeOfDay / 3600.0f); } const float GetTimeOfDayMinutes() const { return Math::Floor(Y_fmodf(m_timeOfDay / 60.0f, 60.0f)); } const float GetTimeOfDaySeconds() const { return Y_fmodf(m_timeOfDay, 60.0f); } void SetTimeOfDay(float hours, float minutes, float seconds); void SetTimeOfDay(float secondInDay); // time scale const float GetTimeScale() const { return m_timeScale; } void SetTimeScale(float timeScale) { m_timeScale = timeScale; } // other void SetEnabled(bool enabled); void SetLightShadowFlags(uint32 lightShadowFlags); // creation method void Create(uint32 entityID, const bool enabled = true, uint32 shadowFlags = LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS); // inherited methods virtual bool Initialize(uint32 entityID, const String &entityName) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnTransformChange() override; virtual void Update(float timeSinceLastUpdate) override; private: void SortSteps(); // updates light properties void UpdateLight(); // property callbacks static void OnEnabledPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); static void OnShadowPropertyChange(ThisClass *pEntity, const void *pUserData = NULL); // local copy of properties bool m_bEnabled; uint32 m_iLightShadowFlags; // time of day float m_timeOfDay; float m_timeScale; // steps MemArray<Step> m_steps; // instance of render proxy DirectionalLightRenderProxy *m_pRenderProxy; }; <file_sep>/Engine/Source/Renderer/VertexFactory.h #pragma once #include "Renderer/ShaderComponent.h" #include "Renderer/VertexFactoryTypeInfo.h" class ShaderComponentTypeInfo; class MaterialShader; class VertexBufferBindingArray; class ShaderCompiler; class VertexFactory : public ShaderComponent { DECLARE_VERTEX_FACTORY_TYPE_INFO(VertexFactory, ShaderComponent); public: static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); static void ShareBuffers(VertexBufferBindingArray *pDestinationVertexArray, const VertexBufferBindingArray *pSourceVertexArray, int32 BufferIndex = -1); }; <file_sep>/Engine/Source/Renderer/Shaders/PlainShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/PlainShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/MaterialShader.h" #include "Engine/Texture.h" DEFINE_SHADER_COMPONENT_INFO(PlainShader); BEGIN_SHADER_COMPONENT_PARAMETERS(PlainShader) DEFINE_SHADER_COMPONENT_PARAMETER("PlainTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void PlainShader::SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture *pTexture) { DebugAssert(pShaderProgram->GetBaseShaderFlags() & WITH_TEXTURE); pShaderProgram->SetBaseShaderParameterResource(pContext, 0, pTexture); } void PlainShader::SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, Texture *pTexture) { DebugAssert(pShaderProgram->GetBaseShaderFlags() & WITH_TEXTURE); pShaderProgram->SetBaseShaderParameterResource(pContext, 0, (pTexture != NULL) ? pTexture->GetGPUTexture() : NULL); } bool PlainShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != VERTEX_FACTORY_TYPE_INFO(PlainVertexFactory)) return false; if (((baseShaderFlags & (WITH_TEXTURE | WITH_VERTEX_COLOR)) == (WITH_TEXTURE | WITH_VERTEX_COLOR)) && !(baseShaderFlags & BLEND_TEXTURE_AND_VERTEX_COLOR)) return false; if (baseShaderFlags & WITH_MATERIAL && pMaterialShader == NULL) return false; return true; } bool PlainShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/PlainShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/PlainShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_TEXTURE) pParameters->AddPreprocessorMacro("WITH_TEXTURE", "1"); if (baseShaderFlags & WITH_VERTEX_COLOR) pParameters->AddPreprocessorMacro("WITH_VERTEX_COLOR", "1"); if (baseShaderFlags & WITH_MATERIAL) pParameters->AddPreprocessorMacro("WITH_MATERIAL", "1"); if (baseShaderFlags & BLEND_TEXTURE_AND_VERTEX_COLOR) pParameters->AddPreprocessorMacro("BLEND_TEXTURE_AND_VERTEX_COLOR", "1"); return true; } <file_sep>/Engine/Source/Core/DefinitionFile.h #pragma once #include "Core/Common.h" #include "YBaseLib/String.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/TextReader.h" class DefinitionFileParser { public: DefinitionFileParser(ByteStream *pStream, const char *FileName); ~DefinitionFileParser(); const String &GetToken() const { return m_szToken; } bool IsAtEOF() const { return m_bAtEOF; } bool NextToken(bool AllowEOF = false, const char *TokenSeperatorCharacters = " \t"); bool Expect(const char *ExpectTokens); bool ExpectNot(const char *NotExpectTokens); int32 Select(const char *SelectTokens); void PrintError(const char *Format, ...); void PrintWarning(const char *Format, ...); private: bool NextLine(); int32 InternalSelect(const char *SelectTokens); TextReader m_Reader; String m_szFileName; String m_szLine; String m_szToken; uint32 m_uLine; uint32 m_uCharacter; bool m_bAtEOF; DeclareNonCopyable(DefinitionFileParser); }; <file_sep>/Engine/Source/Renderer/RenderProxies/VolumetricLightRenderProxy.h #pragma once #include "Renderer/RenderProxy.h" class VolumetricLightRenderProxy : public RenderProxy { public: VolumetricLightRenderProxy(uint32 entityId, bool enabled = true, const float3 &color = float3::One, const float3 &position = float3::Zero, float falloffRate = 0.5f); ~VolumetricLightRenderProxy(); // can be called at any time. void SetEnabled(bool newEnabled); void SetColor(const float3 &newColor); void SetPosition(const float3 &position); void SetFalloffRate(float falloffRate); void SetPrimitive(VOLUMETRIC_LIGHT_PRIMITIVE primitive); void SetBoxPrimitiveExtents(float3 boxExtents); void SetSpherePrimitiveRadius(float sphereRadius); // virtual methods virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; protected: void UpdateBounds(); bool m_enabled; float3 m_color; float3 m_position; float m_falloffRate; float m_renderRange; VOLUMETRIC_LIGHT_PRIMITIVE m_primitive; float3 m_boxPrimitiveExtents; float m_spherePrimitiveRadius; }; <file_sep>/Engine/Source/Core/VirtualFileSystem.h #pragma once #include "Core/Common.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/FileSystem.h" #include "YBaseLib/BinaryBlob.h" #include "YBaseLib/LinkedList.h" class VirtualFileSystemArchive { public: virtual ~VirtualFileSystemArchive() {} virtual const char *GetArchiveTypeName() const = 0; virtual bool FindFiles(const char *Path, const char *Pattern, uint32 Flags, FileSystem::FindResultsArray *pResults) = 0; virtual bool StatFile(const char *Path, FILESYSTEM_STAT_DATA *pStatData) = 0; virtual bool GetFileName(String &Destination, const char *FileName) = 0; virtual ByteStream *OpenFile(const char *FileName, uint32 Flags) = 0; virtual bool DeleteFile(const char *FileName) = 0; virtual bool DeleteDirectory(const char *FileName, bool recursive) = 0; virtual FileSystem::ChangeNotifier *CreateChangeNotifier(const String &directoryPath) = 0; }; class VirtualFileSystem { public: VirtualFileSystem(); ~VirtualFileSystem(); // initialization bool Initialize(); void Shutdown(); // search for files bool FindFiles(const char *Path, const char *Pattern, uint32 Flags, FileSystem::FindResultsArray *pResults); // stat file bool StatFile(const char *Path, FILESYSTEM_STAT_DATA *pStatData); // file exists? bool FileExists(const char *Path); // directory exists? bool DirectoryExists(const char *Path); // get filename on disk, fixes case-sensitivity bool GetFileName(String &Destination, const char *FileName); bool GetFileName(String &FileName); // open files ByteStream *OpenFile(const char *FileName, uint32 Flags); // delete files bool DeleteFile(const char *FileName); // delete directory, optionally recursive, if not recursive, will fail if files exist bool DeleteDirectory(const char *FileName, bool recursive); // create change notifier interface virtual FileSystem::ChangeNotifier *CreateChangeNotifier(const char *directoryPath = nullptr); // get file contents helper BinaryBlob *GetFileContents(const char *filename); // put file contents helper bool PutFileContents(const char *filename, const void *pData, uint32 dataSize, bool overwrite = true, bool createPath = true); private: // searches the path for any pack files, and mounts them at the specified priority //void AddPackFiles(const char *Path, int32 Priority); // mounts a local file system at this path bool AddDirectory(const char *Path, int32 Priority, bool ReadOnly, bool AddNonexistantDirectories); // adds a precreated VFS archive at the specified priority. void AddArchive(VirtualFileSystemArchive *pArchiveInterface, const String &SortKey, int32 Priority); struct VirtualFileSystemArchiveEntry { VirtualFileSystemArchive *pArchiveInterface; String SortKey; int32 Priority; }; // TODO: Convert to array typedef LinkedList<VirtualFileSystemArchiveEntry> ArchiveList; ArchiveList m_liArchives; }; extern VirtualFileSystem *g_pVirtualFileSystem; <file_sep>/Editor/Source/Editor/EditorResourcePreviewGenerator.h #pragma once #include "Editor/Common.h" #include "Engine/ArcBallCamera.h" #include "Engine/BlockPalette.h" #include "Renderer/RendererStateBlock.h" #include "Renderer/WorldRenderer.h" class Image; class Resource; class ResourceTypeInfo; class Texture2D; class Material; class MaterialShader; class Texture; class StaticMesh; class Font; class EditorResourcePreviewGenerator { public: EditorResourcePreviewGenerator(); ~EditorResourcePreviewGenerator(); void SetGPUContext(GPUContext *pGPUContext) { m_pGPUContext = pGPUContext; } bool CreateGPUResources(); void ReleaseGPUResources(); bool GenerateResourcePreview(Image *pDestinationImage, const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName); bool GenerateResourcePreview(Image *pDestinationImage, const Resource *pResource); bool GenerateMaterialPreview(Image *pDestinationImage, const Material *pMaterial); bool GenerateMaterialShaderPreview(Image *pDestinationImage, const MaterialShader *pMaterialShader); bool GenerateTexture2DPreview(Image *pDestinationImage, const Texture2D *pTexture); bool GenerateStaticMeshPreview(Image *pDestinationImage, const StaticMesh *pStaticMesh); bool GenerateFontDataPreview(Image *pDestinationImage, const Font *pFontData); bool GenerateBlockMeshBlockListPreview(Image *pDestinationImage, const BlockPalette *pBlockList); bool GenerateBlockMeshBlockListBlockPreview(Image *pDestinationImage, const BlockPalette *pBlockList, uint32 blockType); private: bool SetupRender(Image *pDestinationImage); bool CompleteRender(Image *pDestinationImage); void SetCameraMatricesFor2D(); void SetCameraMatricesForArcBall(); void ResetCamera(); // target info uint32 m_targetWidth; uint32 m_targetHeight; // gpu resources GPUContext *m_pGPUContext; GPUTexture2D *m_pRenderTarget; GPURenderTargetView *m_pRenderTargetView; GPUDepthTexture *m_pDepthStencilBuffer; GPUDepthStencilBufferView *m_pDepthStencilBufferView; WorldRenderer *m_pWorldRenderer; WorldRenderer::ViewParameters m_viewParameters; MiniGUIContext m_GUIContext; bool m_bGPUResourcesCreated; // state block RendererStateBlock m_stateBlock; // fonts Font *m_pOverlayTextFont; // cameras ArcBallCamera m_ArcBallCamera; // world RenderWorld *m_pRenderWorld; }; <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUTexture.h #pragma once #include "OpenGLES2Renderer/OpenGLES2Common.h" class OpenGLES2GPUTexture2D : public GPUTexture2D { public: OpenGLES2GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLES2GPUTexture2D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLES2GPUTextureCube : public GPUTextureCube { public: OpenGLES2GPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLES2GPUTextureCube(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLES2GPUDepthTexture : public GPUDepthTexture { public: OpenGLES2GPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, GLuint glRenderBufferId); virtual ~OpenGLES2GPUDepthTexture(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLRenderBufferId() const { return m_glRenderBufferId; } private: GLuint m_glRenderBufferId; }; class OpenGLES2GPURenderTargetView : public GPURenderTargetView { public: OpenGLES2GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLuint textureName); virtual ~OpenGLES2GPURenderTargetView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; TEXTURE_TYPE GetTextureType() const { return m_textureType; } GLuint GetTextureName() const { return m_textureName; } protected: TEXTURE_TYPE m_textureType; GLuint m_textureName; }; class OpenGLES2GPUDepthStencilBufferView : public GPUDepthStencilBufferView { public: OpenGLES2GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLenum attachmentPoint, GLuint textureName); virtual ~OpenGLES2GPUDepthStencilBufferView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; TEXTURE_TYPE GetTextureType() const { return m_textureType; } GLenum GetAttachmentPoint() const { return m_attachmentPoint; } GLuint GetTextureName() const { return m_textureName; } protected: TEXTURE_TYPE m_textureType; GLenum m_attachmentPoint; GLuint m_textureName; }; <file_sep>/Engine/Source/ResourceCompiler/BlockMeshGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/BlockMeshGenerator.h" #include "ResourceCompiler/BlockPaletteGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "Engine/BlockPalette.h" #include "Engine/BlockMeshBuilder.h" #include "Engine/DataFormats.h" #include "Engine/ResourceManager.h" #include "Engine/BlockMesh.h" #include "Core/ChunkFileWriter.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(BlockMeshGenerator); BlockMeshGenerator::BlockMeshGenerator() : m_changed(false), m_pPalette(NULL), m_scale(1.0f), m_useAmbientOcclusion(false), m_collisionShapeType(Physics::COLLISION_SHAPE_TYPE_NONE), m_pLODLevels(NULL), m_nLODLevels(0) { } BlockMeshGenerator::~BlockMeshGenerator() { delete[] m_pLODLevels; if (m_pPalette != NULL) m_pPalette->Release(); } void BlockMeshGenerator::SetScale(float scale) { float currentScale = scale; for (uint32 i = 0; i < m_nLODLevels; i++) { m_pLODLevels[i].SetScale(currentScale); currentScale *= 2.0f; } } bool BlockMeshGenerator::Create(const BlockPalette *pPalette, float scale /* = 1.0f */, Physics::COLLISION_SHAPE_TYPE collisionShapeType /* = COLLISION_SHAPE_TYPE_TRIANGLE_MESH */) { m_pPalette = pPalette; m_pPalette->AddRef(); m_scale = scale; m_collisionShapeType = collisionShapeType; m_nLODLevels = 1; m_pLODLevels = new BlockMeshVolume[1]; m_pLODLevels[0].SetPalette(pPalette); m_pLODLevels[0].SetScale(scale); m_pLODLevels[0].Resize(int3::Zero, int3::Zero); m_pLODLevels[0].Clear(); m_changed = true; return true; } bool BlockMeshGenerator::LoadFromXML(const char *FileName, ByteStream *pStream) { // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { xmlReader.PrintError("failed to create XML reader"); return false; } // skip to correct node if (!xmlReader.SkipToElement("blockmesh")) { xmlReader.PrintError("failed to skip to blockmesh element"); return false; } // read attributes const char *nameStr = xmlReader.FetchAttribute("palette"); const char *scaleStr = xmlReader.FetchAttribute("scale"); const char *lodCountStr = xmlReader.FetchAttribute("lod-count"); const char *ambientOcclusionEnabledStr = xmlReader.FetchAttribute("ambient-occlusion"); const char *collisionShapeTypeStr = xmlReader.FetchAttribute("collision-shape-type"); // check if (nameStr == NULL || scaleStr == NULL || lodCountStr == NULL || ambientOcclusionEnabledStr == NULL || collisionShapeTypeStr == NULL) { xmlReader.PrintError("incomplete mesh definition"); return false; } // load palette m_pPalette = g_pResourceManager->GetBlockPalette(nameStr); if (m_pPalette == NULL) { xmlReader.PrintError("failed to load palette '%s'", nameStr); return false; } // load settings m_scale = StringConverter::StringToFloat(scaleStr); m_nLODLevels = StringConverter::StringToUInt32(lodCountStr); m_useAmbientOcclusion = StringConverter::StringToBool(ambientOcclusionEnabledStr); if (!NameTable_TranslateType(Physics::NameTables::CollisionShapeType, collisionShapeTypeStr, &m_collisionShapeType, true)) { xmlReader.PrintError("unknown collision shape type '%s'", collisionShapeTypeStr); return false; } // validate if (m_scale <= 0.0f || m_nLODLevels == 0 || m_nLODLevels > BlockMesh::MAX_LOD_LEVELS) { xmlReader.PrintError("invalid scale: %f, or lod level count: %u", m_scale, m_nLODLevels); return false; } // alloc lods m_pLODLevels = new BlockMeshVolume[m_nLODLevels]; for (uint32 i = 0; i < m_nLODLevels; i++) { m_pLODLevels[i].SetPalette(m_pPalette); m_pLODLevels[i].SetScale(m_scale * (float)(1 << i)); } // skip to data if (xmlReader.IsEmptyElement() || !xmlReader.MoveToElement()) { xmlReader.PrintError("blockmesh element should have content"); return false; } // start parsing xml for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("lod") < 0) return false; const char *lodLevelStr = xmlReader.FetchAttribute("level"); uint32 lodLevelIndex; if (lodLevelStr == NULL || (lodLevelIndex = StringConverter::StringToUInt32(lodLevelStr)) >= m_nLODLevels || m_pLODLevels[lodLevelIndex].GetWidth() > 0) { xmlReader.PrintError("invalid lod definition"); return false; } // get range const char *minXStr = xmlReader.FetchAttribute("minx"); const char *minYStr = xmlReader.FetchAttribute("miny"); const char *minZStr = xmlReader.FetchAttribute("minz"); const char *maxXStr = xmlReader.FetchAttribute("maxx"); const char *maxYStr = xmlReader.FetchAttribute("maxy"); const char *maxZStr = xmlReader.FetchAttribute("maxz"); if (minXStr == NULL || minYStr == NULL || minZStr == NULL || maxXStr == NULL || maxYStr == NULL || maxZStr == NULL) { xmlReader.PrintError("incomplete mesh declaration"); return false; } int3 minCoordinates(StringConverter::StringToInt32(minXStr), StringConverter::StringToInt32(minYStr), StringConverter::StringToInt32(minZStr)); int3 maxCoordinates(StringConverter::StringToInt32(maxXStr), StringConverter::StringToInt32(maxYStr), StringConverter::StringToInt32(maxZStr)); if (minCoordinates.AnyGreater(maxCoordinates)) { xmlReader.PrintError("invalid mesh size"); return false; } // init volume BlockMeshVolume &meshVolume = m_pLODLevels[lodLevelIndex]; meshVolume.Resize(minCoordinates, maxCoordinates); meshVolume.Clear(); // read block info if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("block") < 0) return false; const char *xStr = xmlReader.FetchAttribute("x"); const char *yStr = xmlReader.FetchAttribute("y"); const char *zStr = xmlReader.FetchAttribute("z"); const char *typeStr = xmlReader.FetchAttribute("type"); if (xStr == NULL || yStr == NULL || zStr == NULL || typeStr == NULL) { xmlReader.PrintError("incomplete block declaration"); return false; } int3 at(StringConverter::StringToInt32(xStr), StringConverter::StringToInt32(yStr), StringConverter::StringToInt32(zStr)); uint32 t = StringConverter::StringToUInt32(typeStr); if (at.AnyLess(minCoordinates) || at.AnyGreater(maxCoordinates) || t > BLOCK_MESH_MAX_BLOCK_TYPES || !m_pPalette->GetBlockType(t)->IsAllocated) { xmlReader.PrintError("invalid block declaration."); return false; } meshVolume.SetBlock(at, (uint8)t); } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "lod") == 0); break; } else { UnreachableCode(); } } } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "blockmesh") == 0); break; } } for (uint32 i = 0; i < m_nLODLevels; i++) { if (m_pLODLevels[i].GetWidth() == 0) { xmlReader.PrintError("lod level %u not defined", i); return false; } } m_changed = false; return true; } bool BlockMeshGenerator::SaveToXML(ByteStream *pStream) { XMLWriter xmlWriter; if (!xmlWriter.Create(pStream)) return false; xmlWriter.StartElement("blockmesh"); { xmlWriter.WriteAttribute("palette", m_pPalette->GetName()); xmlWriter.WriteAttributef("scale", "%f", m_scale); xmlWriter.WriteAttributef("lod-count", "%u", m_nLODLevels); xmlWriter.WriteAttribute("ambient-occlusion", StringConverter::BoolToString(m_useAmbientOcclusion)); xmlWriter.WriteAttribute("collision-shape-type", NameTable_GetNameString(Physics::NameTables::CollisionShapeType, m_collisionShapeType)); for (uint32 i = 0; i < m_nLODLevels; i++) { const BlockMeshVolume &meshVolume = m_pLODLevels[i]; xmlWriter.StartElement("lod"); { int32 minX = meshVolume.GetMinCoordinates().x; int32 minY = meshVolume.GetMinCoordinates().y; int32 minZ = meshVolume.GetMinCoordinates().z; int32 maxX = meshVolume.GetMaxCoordinates().x; int32 maxY = meshVolume.GetMaxCoordinates().y; int32 maxZ = meshVolume.GetMaxCoordinates().z; xmlWriter.WriteAttributef("level", "%u", i); xmlWriter.WriteAttributef("minx", "%i", minX); xmlWriter.WriteAttributef("miny", "%i", minY); xmlWriter.WriteAttributef("minz", "%i", minZ); xmlWriter.WriteAttributef("maxx", "%i", maxX); xmlWriter.WriteAttributef("maxy", "%i", maxY); xmlWriter.WriteAttributef("maxz", "%i", maxZ); for (int32 z = minZ; z <= maxZ; z++) { for (int32 y = minY; y <= maxY; y++) { for (int32 x = minX; x <= maxX; x++) { uint8 blockValue = GetBlock(i, x, y, z); if (blockValue == 0) continue; xmlWriter.StartElement("block"); { xmlWriter.WriteAttributef("x", "%i", x); xmlWriter.WriteAttributef("y", "%i", y); xmlWriter.WriteAttributef("z", "%i", z); xmlWriter.WriteAttributef("type", "%u", (uint32)blockValue); } xmlWriter.EndElement(); } } } } xmlWriter.EndElement(); } } xmlWriter.EndElement(); m_changed = false; return (!xmlWriter.InErrorState() && !pStream->InErrorState()); } void BlockMeshGenerator::Clear() { for (uint32 i = 0; i < m_nLODLevels; i++) Clear(i); } void BlockMeshGenerator::Clear(uint32 LOD) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.Clear(); m_changed = true; } void BlockMeshGenerator::Resize(uint32 LOD, const int3 &newMinCoordinates, const int3 &newMaxCoordinates) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.Resize(newMinCoordinates, newMaxCoordinates); m_changed = true; } bool BlockMeshGenerator::GetActiveCoordinatesRange(uint32 LOD, int3 *pMinActiveCoordinates, int3 *pMaxActiveCoordinates) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); return meshVolume.GetActiveCoordinatesRange(pMinActiveCoordinates, pMaxActiveCoordinates); } void BlockMeshGenerator::Center() { for (uint32 i = 0; i < m_nLODLevels; i++) Center(i); } void BlockMeshGenerator::Center(uint32 LOD) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.Center(); m_changed = true; } void BlockMeshGenerator::Shrink() { for (uint32 i = 0; i < m_nLODLevels; i++) Shrink(i); } void BlockMeshGenerator::Shrink(uint32 LOD) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.Shrink(); m_changed = true; } void BlockMeshGenerator::MoveBlock(uint32 LOD, const int3 &blockCoordinates, const int3 &moveDelta) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.MoveBlock(blockCoordinates, moveDelta); m_changed = true; } void BlockMeshGenerator::MoveBlocks(uint32 LOD, const int3 &selectionMin, const int3 &selectionMax, const int3 &moveDelta) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); meshVolume.MoveBlocks(selectionMin, selectionMax, moveDelta); m_changed = true; } uint8 BlockMeshGenerator::GetBlock(uint32 LOD, const int3 &coords) const { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); if (coords.AnyLess(meshVolume.GetMinCoordinates()) || coords.AnyGreater(meshVolume.GetMaxCoordinates())) { Log_WarningPrintf("BlockMeshGenerator::GetBlock: Reading out-of-range block (%i,%i,%i)", coords.x, coords.y, coords.z); return 0; } return meshVolume.GetBlock(coords); } void BlockMeshGenerator::SetBlock(uint32 LOD, const int3 &coords, BlockVolumeBlockType v) { BlockMeshVolume &meshVolume = m_pLODLevels[LOD]; DebugAssert(LOD < m_nLODLevels); if (coords.AnyLess(meshVolume.GetMinCoordinates()) || coords.AnyGreater(meshVolume.GetMaxCoordinates())) { Log_WarningPrintf("BlockMeshGenerator::SetBlock: Setting out-of-range block (%i,%i,%i). Resizing mesh.", coords.x, coords.y, coords.z); int3 newMinCoordinates = coords.Min(meshVolume.GetMinCoordinates()); int3 newMaxCoordinates = coords.Max(meshVolume.GetMaxCoordinates()); Resize(LOD, newMinCoordinates, newMaxCoordinates); } meshVolume.SetBlock(coords, v); m_changed = true; } void BlockMeshGenerator::SetPalette(const BlockPalette *pPalette) { if (m_pPalette == pPalette) return; m_pPalette->Release(); m_pPalette = pPalette; m_pPalette->AddRef(); // check blocks for (uint32 i = 0; i < m_nLODLevels; i++) { BlockMeshVolume &meshVolume = m_pLODLevels[i]; meshVolume.SetPalette(pPalette); int32 minX = meshVolume.GetMinCoordinates().x; int32 minY = meshVolume.GetMinCoordinates().y; int32 minZ = meshVolume.GetMinCoordinates().z; int32 maxX = meshVolume.GetMaxCoordinates().x; int32 maxY = meshVolume.GetMaxCoordinates().y; int32 maxZ = meshVolume.GetMaxCoordinates().z; int32 x, y, z; for (z = minZ; z <= maxZ; z++) { for (y = minY; y <= maxY; y++) { for (x = minX; x <= maxX; x++) { BlockVolumeBlockType blockValue = GetBlock(i, x, y, z); if (blockValue != 0 && !pPalette->GetBlockType(blockValue)->IsAllocated) SetBlock(i, x, y, z, 0); } } } } m_changed = true; } bool BlockMeshGenerator::Compile(ByteStream *pOutputStream) const { // calculate bounding box AABox boundingBox; for (uint32 i = 0; i < m_nLODLevels; i++) { // update bounds AABox levelBoundingBox(m_pLODLevels[i].CalculateActiveBoundingBox()); if (i == 0) boundingBox = levelBoundingBox; else boundingBox.Merge(levelBoundingBox); } // from this calculate bounding sphere Sphere boundingSphere(Sphere::FromAABox(boundingBox)); // write to file BinaryWriter binaryWriter(pOutputStream); // magic binaryWriter.WriteUInt32(DF_BLOCK_MESH_HEADER_MAGIC); // blocklist name binaryWriter.WriteSizePrefixedString(m_pPalette->GetName()); // settings binaryWriter.WriteFloat(m_scale); binaryWriter.WriteBool(m_useAmbientOcclusion); binaryWriter.WriteUInt32(m_nLODLevels); // bounding box binaryWriter << (boundingBox.GetMinBounds()); binaryWriter << (boundingBox.GetMaxBounds()); // bounding sphere binaryWriter << (boundingSphere.GetCenter()); binaryWriter << (boundingSphere.GetRadius()); // write lod levels for (uint32 i = 0; i < m_nLODLevels; i++) { const BlockMeshVolume &meshVolume = m_pLODLevels[i]; AABox levelBoundingBox(meshVolume.CalculateActiveBoundingBox()); Sphere levelBoundingSphere(Sphere::FromAABox(levelBoundingBox)); binaryWriter << (meshVolume.GetScale()); binaryWriter << (levelBoundingBox.GetMinBounds()); binaryWriter << (levelBoundingBox.GetMaxBounds()); binaryWriter << (levelBoundingSphere.GetCenter()); binaryWriter << (levelBoundingSphere.GetRadius()); binaryWriter << (meshVolume.GetMinCoordinates()); binaryWriter << (meshVolume.GetMaxCoordinates()); binaryWriter << (meshVolume.GetWidth()); binaryWriter << (meshVolume.GetLength()); binaryWriter << (meshVolume.GetHeight()); uint32 nBlocks = meshVolume.GetWidth() * meshVolume.GetLength() * meshVolume.GetHeight(); binaryWriter.WriteBytes(meshVolume.GetData(), sizeof(BlockVolumeBlockType) * nBlocks); } binaryWriter.WriteUInt32(m_collisionShapeType); if (m_collisionShapeType != Physics::COLLISION_SHAPE_TYPE_NONE && m_collisionShapeType != Physics::COLLISION_SHAPE_TYPE_BLOCK_MESH) { // build triangle mesh BlockMeshBuilder builder; builder.SetFromVolume(&m_pLODLevels[0]); builder.SetAmbientOcclusionEnabled(false); builder.GenerateCollisionMesh(); // get builder verts/tris const BlockMeshBuilder::VertexArray &builderVertices = builder.GetOutputVertices(); const BlockMeshBuilder::TriangleArray &builderTriangles = builder.GetOutputTriangles(); // send to collision shape generator Physics::CollisionShapeGenerator collisionShapeGenerator(Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH); for (uint32 i = 0; i < builderTriangles.GetSize(); i++) { const uint32 *indices = builderTriangles[i].Indices; collisionShapeGenerator.AddTriangle(builderVertices[indices[0]].Position, builderVertices[indices[1]].Position, builderVertices[indices[2]].Position); } // convert to the appropriate type if (m_collisionShapeType == Physics::COLLISION_SHAPE_TYPE_BOX) { collisionShapeGenerator.ConvertToBox(); } else if (m_collisionShapeType == Physics::COLLISION_SHAPE_TYPE_SPHERE) { collisionShapeGenerator.ConvertToSphere(); } else if (m_collisionShapeType == Physics::COLLISION_SHAPE_TYPE_CONVEX_HULL) { collisionShapeGenerator.ConvertToConvexHull(); } else if (m_collisionShapeType != Physics::COLLISION_SHAPE_TYPE_TRIANGLE_MESH) { Log_ErrorPrintf("BlockMeshGenerator::Compile: Unhandled collision shape type '%s'", NameTable_GetNameString(Physics::NameTables::CollisionShapeType, m_collisionShapeType)); return false; } // write it out BinaryBlob *pBlob; if (!collisionShapeGenerator.Compile(&pBlob)) { Log_ErrorPrintf("BlockMeshGenerator::Compile: Collision shape compilation failed."); return false; } // copy to stream binaryWriter.WriteUInt32(pBlob->GetDataSize()); binaryWriter.WriteBytes(pBlob->GetDataPointer(), pBlob->GetDataSize()); pBlob->Release(); } return !binaryWriter.InErrorState(); } // Interface BinaryBlob *ResourceCompiler::CompileBlockMesh(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.blm.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileBlockMesh: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); BlockMeshGenerator *pGenerator = new BlockMeshGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Engine/OverlayConsole.h #pragma once #include "Engine/Common.h" class Font; class MiniGUIContext; union SDL_Event; class OverlayConsole { public: enum ACTIVATION_STATE { ACTIVATION_STATE_NONE, ACTIVATION_STATE_INPUT_ONLY, ACTIVATION_STATE_PARTIAL, ACTIVATION_STATE_FULL, }; // struct ColorConfig // { // uint32 InputBackgroundColor; // uint32 InputBorderColor; // uint32 InputForegroundColor; // // uint32 BufferBackgroundColor; // uint32 BufferBorderColor; // // uint32 LogErrorColor; // uint32 LogWarningColor; // uint32 LogInfoColor; // uint32 LogPerfColor; // uint32 LogDevColor; // uint32 LogProfileColor; // uint32 LogTraceColor; // // void SetDefault(); // }; public: OverlayConsole(); ~OverlayConsole(); // change the activation state ACTIVATION_STATE GetActivationState() const { return m_activationState; } void SetActivationState(ACTIVATION_STATE activationState) { m_activationState = activationState; } // logging level customization void SetBufferLogLevel(LOGLEVEL level); void SetDisplayLogLevel(LOGLEVEL level); // call every frame void Update(float timeDifference); // call from render thread void Draw(MiniGUIContext *pGUIContext) const; // call when an input event occurs. if it is consumed by the console, true will be returned bool OnInputEvent(const SDL_Event *pEvent); private: // append a message to the log buffer contents, wiping out anything that has to be void AppendMessageToBuffer(const char *message, uint32 length, uint32 color); // append a message to the display void AppendMessageToDisplay(const char *message, uint32 length, float time, uint32 color); // update messagecolors array //void UpdateMessageColors(const ColorConfig *pConfig); // draw messages only void DrawQueuedMessages(MiniGUIContext *pGUIContext) const; void DrawInputOnly(MiniGUIContext *pGUIContext) const; void DrawPartial(MiniGUIContext *pGUIContext) const; // log callback static void LogCallbackTrampoline(void *pUserParam, const char *channelName, const char *functionName, LOGLEVEL level, const char *message); void LogCallback(const char *channelName, const char *functionName, LOGLEVEL level, const char *message); // anything is pretty much locked mutable Mutex m_lock; // font info const Font *m_pFont; uint32 m_fontSize; // color config uint32 m_titleBackgroundColor; uint32 m_titleForegroundColor; uint32 m_inputBackgroundColor; uint32 m_inputBorderColor; uint32 m_inputForegroundColor; uint32 m_inputCaretColor; uint32 m_bufferBackgroundColor; uint32 m_bufferBorderColor; uint32 m_messageColors[LOGLEVEL_COUNT]; uint32 m_maxMessageLength; uint32 m_maxCommandHistory; // buffered text LOGLEVEL m_logBufferLevel; uint32 m_logBufferSize; // displayed text LOGLEVEL m_logDisplayLevel; uint32 m_logDisplayLines; float m_logDisplayTime; float m_logFadeOutTime; // state ACTIVATION_STATE m_activationState; uint32 m_logBufferLinesScrolledVertical; uint32 m_logBufferCharactersScrolledHorizontal; String m_inputBuffer; int32 m_inputCaretPosition; Array<String> m_commandHistory; int32 m_currentCommandHistoryIndex; // log buffer String m_logBufferContents; uint32 m_logBufferLines; // display buffer struct LogDisplayEntry { SmallString Message; uint32 Color; float TimeRemaining; }; PODArray<LogDisplayEntry *> m_logDisplayEntries; }; <file_sep>/Engine/Source/D3D12Renderer/PrecompiledHeader.cpp #include "D3D12Renderer/PrecompiledHeader.h" <file_sep>/Engine/Source/Engine/TerrainTypes.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainTypes.h" Y_Define_NameTable(NameTables::TerrainRendererType) Y_NameTable_VEntry(TERRAIN_RENDERER_TYPE_NULL, "null") Y_NameTable_VEntry(TERRAIN_RENDERER_TYPE_CDLOD, "cdlod") Y_NameTable_End() Y_Define_NameTable(NameTables::TerrainHeightStorageFormat) Y_NameTable_VEntry(TERRAIN_HEIGHT_STORAGE_FORMAT_UINT8, "uint8") Y_NameTable_VEntry(TERRAIN_HEIGHT_STORAGE_FORMAT_UINT16, "uint16") Y_NameTable_VEntry(TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, "float32") Y_NameTable_End() bool TerrainUtilities::IsValidParameters(const TerrainParameters *pParameters) { if (pParameters->MinHeight > pParameters->MaxHeight) return false; if (pParameters->BaseHeight > pParameters->MaxHeight) return false; if (pParameters->Scale < 1) return false; if (pParameters->SectionSize == 0 || !Math::IsPowerOfTwo(pParameters->SectionSize)) return false; if (pParameters->LODCount == 0 || ((pParameters->SectionSize >> (pParameters->LODCount - 1)) == 0)) return false; return true; } uint32 TerrainUtilities::GetHeightElementStorageSize(TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat) { static const uint32 s_heightStorageFormatElementSizes[TERRAIN_HEIGHT_STORAGE_FORMAT_COUNT] = { 1, // uint8 2, // uint16 4, // float32 }; DebugAssert(heightStorageFormat < countof(s_heightStorageFormatElementSizes)); return s_heightStorageFormatElementSizes[heightStorageFormat]; } PIXEL_FORMAT TerrainUtilities::GetHeightStoragePixelFormat(TERRAIN_HEIGHT_STORAGE_FORMAT heightStorageFormat) { static const PIXEL_FORMAT s_heightStorageFormatPixelFormats[TERRAIN_HEIGHT_STORAGE_FORMAT_COUNT] = { PIXEL_FORMAT_R8_UNORM, // uint8 PIXEL_FORMAT_R16_SNORM, // uint16 PIXEL_FORMAT_R32_FLOAT, // float32 }; DebugAssert(heightStorageFormat < countof(s_heightStorageFormatPixelFormats)); return s_heightStorageFormatPixelFormats[heightStorageFormat]; } AABox TerrainUtilities::CalculateSectionBoundingBox(const TerrainParameters *pTerrainParameters, int32 sectionX, int32 sectionY) { int32 scale = (int32)pTerrainParameters->Scale; int32 sectionSize = (int32)pTerrainParameters->SectionSize; int32 minX = (sectionX * sectionSize) * scale; int32 maxX = ((sectionX + 1) * sectionSize) * scale; int32 minY = (sectionY * sectionSize) * scale; int32 maxY = ((sectionY + 1) * sectionSize) * scale; return AABox((float)minX, (float)minY, (float)pTerrainParameters->MinHeight, (float)maxX, (float)maxY, (float)pTerrainParameters->MaxHeight); } int2 TerrainUtilities::CalculateSectionForPoint(const TerrainParameters *pTerrainParameters, int32 globalX, int32 globalY) { int32 sectionX = (globalX >= 0) ? (globalX / (int32)pTerrainParameters->SectionSize) : (((globalX + 1) / (int32)pTerrainParameters->SectionSize) - 1); int32 sectionY = (globalY >= 0) ? (globalY / (int32)pTerrainParameters->SectionSize) : (((globalY + 1) / (int32)pTerrainParameters->SectionSize) - 1); return int2(sectionX, sectionY); } int2 TerrainUtilities::CalculateSectionForPosition(const TerrainParameters *pTerrainParameters, const float3 &position) { float px = position.x / (float)pTerrainParameters->Scale; float py = position.y / (float)pTerrainParameters->Scale; int32 gx = Math::Truncate(px); int32 gy = Math::Truncate(py); return CalculateSectionForPoint(pTerrainParameters, gx, gy); } void TerrainUtilities::CalculateSectionAndOffsetForPoint(const TerrainParameters *pTerrainParameters, int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, int32 globalX, int32 globalY) { int32 sectionSize = (int32)pTerrainParameters->SectionSize; if (globalX >= 0) { *pSectionX = globalX / sectionSize; *pIndexX = (uint32)(globalX % sectionSize); } else { *pSectionX = ((globalX + 1) / sectionSize) - 1; *pIndexX = (sectionSize - 1) - (-(globalX + 1) % sectionSize); } if (globalY >= 0) { *pSectionY = globalY / sectionSize; *pIndexY = (uint32)(globalY % sectionSize); } else { *pSectionY = ((globalY + 1) / sectionSize) - 1; *pIndexY = (sectionSize - 1) - (-(globalY + 1) % sectionSize); } } void TerrainUtilities::CalculateSectionAndOffsetForPosition(const TerrainParameters *pTerrainParameters, int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, const float3 &position) { // round instead of truncate here float px = position.x / (float)pTerrainParameters->Scale; float py = position.y / (float)pTerrainParameters->Scale; int32 gx = Math::Truncate(Math::Round(px)); int32 gy = Math::Truncate(Math::Round(py)); CalculateSectionAndOffsetForPoint(pTerrainParameters, pSectionX, pSectionY, pIndexX, pIndexY, gx, gy); } int2 TerrainUtilities::CalculatePointForPosition(const TerrainParameters *pTerrainParameters, const float3 &position) { // round instead of truncate here float px = position.x / (float)pTerrainParameters->Scale; float py = position.y / (float)pTerrainParameters->Scale; int32 gx = Math::Truncate(Math::Round(px)); int32 gy = Math::Truncate(Math::Round(py)); return int2(gx, gy); } float3 TerrainUtilities::CalculatePositionForPoint(const TerrainParameters *pTerrainParameters, int32 globalX, int32 globalY) { int32 sectionX, sectionY; uint32 offsetX, offsetY; CalculateSectionAndOffsetForPoint(pTerrainParameters, &sectionX, &sectionY, &offsetX, &offsetY, globalX, globalY); return float3((float)(globalX * (int32)pTerrainParameters->Scale), (float)(globalY * (int32)pTerrainParameters->Scale), (float)pTerrainParameters->BaseHeight); } void TerrainUtilities::CalculatePointForSectionAndOffset(const TerrainParameters *pTerrainParameters, int32 *pGlobalX, int32 *pGlobalY, int32 sectionX, int32 sectionY, uint32 offsetX, uint32 offsetY) { int32 sectionSize = (int32)pTerrainParameters->SectionSize; if (sectionX >= 0) *pGlobalX = (sectionX * sectionSize) + (int32)offsetX; else *pGlobalX = (sectionX * sectionSize) + (sectionSize - (int32)offsetX); if (sectionY >= 0) *pGlobalY = (sectionY * sectionSize) + (int32)offsetY; else *pGlobalY = (sectionY * sectionSize) + (sectionSize - (int32)offsetY); } <file_sep>/Engine/Source/ContentConverter/AssimpMaterialImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiMaterial; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class MaterialGenerator; class AssimpMaterialImporter : public BaseImporter { public: struct Options { String SourcePath; bool ListOnly; bool AllMaterials; String SingleMaterialName; String OutputName; String OutputDirectory; String OutputPrefix; }; public: AssimpMaterialImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpMaterialImporter(); static void SetDefaultOptions(Options *pOptions); bool Execute(); static bool ImportMaterial(const aiMaterial *pAIMaterial, const char *sourceFileName, const char *outputDirectory, const char *outputPrefix, const char *outputName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); private: bool LoadScene(); void ListMaterials(); bool ImportMaterials(); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; }; <file_sep>/Engine/Source/Renderer/VertexFactory.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/VertexFactory.h" #include "Renderer/VertexBufferBindingArray.h" DEFINE_VERTEX_FACTORY_TYPE_INFO(VertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(VertexFactory) END_SHADER_COMPONENT_PARAMETERS() bool VertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return false; } bool VertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { return false; } uint32 VertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { return 0; } void VertexFactory::ShareBuffers(VertexBufferBindingArray *pDestinationVertexArray, const VertexBufferBindingArray *pSourceVertexArray, int32 BufferIndex /* = -1 */) { if (BufferIndex < 0) { uint32 i; uint32 nBuffersToSet = pSourceVertexArray->GetActiveBufferCount(); for (i = 0; i < nBuffersToSet; i++) pDestinationVertexArray->SetBuffer(i, pSourceVertexArray->GetBuffer(i), pSourceVertexArray->GetBufferOffset(i), pSourceVertexArray->GetBufferStride(i)); } else { DebugAssert(static_cast<uint32>(BufferIndex) < pSourceVertexArray->GetActiveBufferCount()); pDestinationVertexArray->SetBuffer(BufferIndex, pSourceVertexArray->GetBuffer(BufferIndex), pSourceVertexArray->GetBufferOffset(BufferIndex), pSourceVertexArray->GetBufferStride(BufferIndex)); } } <file_sep>/Engine/Source/BlockEngine/BlockDrawTemplate.h #pragma once #include "BlockEngine/BlockWorldTypes.h" #include "Engine/BlockPalette.h" #include "Renderer/RenderProxy.h" #include "Renderer/Renderer.h" class ShaderProgram; class BlockDrawTemplate : public ReferenceCounted { public: class BlockRenderProxy : public RenderProxy { public: BlockRenderProxy(uint32 entityID, const BlockDrawTemplate *pDrawTemplate, uint32 startBatch, uint32 batchCount, const float4x4 &transformMatrix, uint32 tintColor); BlockRenderProxy(uint32 entityID, const BlockDrawTemplate *pDrawTemplate, BlockWorldBlockType blockType, const float4x4 &transformMatrix, uint32 tintColor); virtual ~BlockRenderProxy(); void SetBlockType(BlockWorldBlockType blockType); void SetTransform(const float4x4 &transformMatrix); void SetTintColor(uint32 tintColor); void SetVisible(bool visible); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; private: // recalculate bounding box void UpdateBounds(); // vars const BlockDrawTemplate *m_pDrawTemplate; uint32 m_startBatch; uint32 m_batchCount; float4x4 m_transformMatrix; uint32 m_tintColor; bool m_visible; }; public: BlockDrawTemplate(const BlockPalette *pPalette); ~BlockDrawTemplate(); // Create meshes, buffers, batches. bool Initialize(); // Get the starting batch and batch count for a block type. bool GetBatchRangeForBlock(BlockWorldBlockType blockType, uint32 *startBatch, uint32 *batchCount) const; // Retrieves the material for a specified batch. const Material *GetBatchMaterial(uint32 batchIndex) const; // Retrieves the vertex factory and flags for a specified batch. const VertexFactoryTypeInfo *GetBatchVertexFactoryType(uint32 batchIndex) const; const uint32 GetBatchVertexFactoryFlags(uint32 batchIndex) const; // Draws a batch using the specified shader. void DrawBatch(GPUContext *pContext, ShaderProgram *pShaderProgram, uint32 batchIndex) const; // Create a renderproxy instance to draw a block at the specified position. // The origin is located at the bottom-front-left corner of the box. BlockRenderProxy *CreateBlockRenderProxy(BlockWorldBlockType blockType, uint32 entityID, const float4x4 &transformMatrix, uint32 tintColor = 0) const; private: // properties const BlockPalette *m_pBlockPalette; // gpu buffers GPUBuffer *m_pVertexBuffer; GPUBuffer *m_pIndexBuffer; GPUBuffer *m_pInstanceTransformBuffer; // block information struct BlockDrawInfo { uint32 StartBatch; uint32 BatchCount; }; // batch information struct Batch { Batch() {} Batch(const BlockPalette::BlockType *pBlockType_, const StaticMesh *pMesh_, const Material *pMaterial_, uint32 baseVertex, uint32 baseIndex, uint32 firstIndex, uint32 indexCount) : pBlockType(pBlockType_), pMesh(pMesh_), pMaterial(pMaterial_), BaseVertex(baseVertex), BaseIndex(baseIndex), FirstIndex(firstIndex), IndexCount(indexCount) {} const BlockPalette::BlockType *pBlockType; const StaticMesh *pMesh; const Material *pMaterial; uint32 BaseVertex; uint32 BaseIndex; uint32 FirstIndex; uint32 IndexCount; }; // arrays MemArray<BlockDrawInfo> m_blockDrawInfo; MemArray<Batch> m_batches; }; <file_sep>/Engine/Source/Engine/Brush.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Brush.h" #include "Engine/World.h" #include "Core/PropertyTable.h" //Log_SetChannel(WorldObject); DEFINE_OBJECT_TYPE_INFO(Brush); BEGIN_OBJECT_PROPERTY_MAP(Brush) PROPERTY_TABLE_MEMBER("Position", PROPERTY_TYPE_FLOAT3, PROPERTY_FLAG_READ_ONLY, PropertyCallbackGetPosition, nullptr, PropertyCallbackSetPosition, nullptr, nullptr, nullptr) PROPERTY_TABLE_MEMBER("Rotation", PROPERTY_TYPE_QUATERNION, PROPERTY_FLAG_READ_ONLY, PropertyCallbackGetRotation, nullptr, PropertyCallbackSetRotation, nullptr, nullptr, nullptr) PROPERTY_TABLE_MEMBER("Scale", PROPERTY_TYPE_FLOAT3, PROPERTY_FLAG_READ_ONLY, PropertyCallbackGetScale, nullptr, PropertyCallbackSetScale, nullptr, nullptr, nullptr) END_OBJECT_PROPERTY_MAP() Brush::Brush(const ObjectTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pWorld(nullptr), m_transform(Transform::Identity), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero) { } Brush::~Brush() { DebugAssert(m_pWorld == nullptr); } void Brush::OnAddToWorld(World *pWorld) { DebugAssert(m_pWorld == nullptr); // set world pointer m_pWorld = pWorld; } void Brush::OnRemoveFromWorld(World *pWorld) { DebugAssert(m_pWorld == pWorld); // null world pointer m_pWorld = nullptr; } bool Brush::PropertyCallbackGetPosition(Brush *pObjectPtr, const void *pUserData, float3 *pValuePtr) { *pValuePtr = pObjectPtr->GetPosition(); return true; } bool Brush::PropertyCallbackSetPosition(Brush *pObjectPtr, const void *pUserData, const float3 *pValuePtr) { pObjectPtr->m_transform.SetPosition(*pValuePtr); return true; } bool Brush::PropertyCallbackGetRotation(Brush *pObjectPtr, const void *pUserData, Quaternion *pValuePtr) { *pValuePtr = pObjectPtr->GetRotation(); return true; } bool Brush::PropertyCallbackSetRotation(Brush *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr) { pObjectPtr->m_transform.SetRotation(*pValuePtr); return true; } bool Brush::PropertyCallbackGetScale(Brush *pObjectPtr, const void *pUserData, float3 *pValuePtr) { *pValuePtr = pObjectPtr->GetScale(); return true; } bool Brush::PropertyCallbackSetScale(Brush *pObjectPtr, const void *pUserData, const float3 *pValuePtr) { pObjectPtr->m_transform.SetScale(*pValuePtr); return true; } <file_sep>/Engine/Source/Core/Console.cpp #include "Core/PrecompiledHeader.h" #include "Core/Console.h" #include "YBaseLib/Log.h" #include "YBaseLib/StringConverter.h" Log_SetChannel(Console); Console *g_pConsole = NULL; Console::Console() : m_appStarted(false), m_rendererStarted(false), m_hasPendingRenderCVars(false) { DebugAssert(g_pConsole == NULL); g_pConsole = this; } Console::~Console() { DebugAssert(g_pConsole == this); g_pConsole = NULL; } void Console::RegisterCVar(CVar *pCVar) { // make sure there's no unregistered cvar with this name CVar *pUnregisteredCVar = NULL; CVarHashTable::Member *pMember = m_hmCVars.Find(pCVar->m_strName.GetCharArray()); if (pMember != NULL) { // if it's registered, we have duplicate cvar names somewhere.. this is bad. DebugAssert(!(pMember->Value->m_iFlags & CVAR_FLAG_REGISTERED)); pUnregisteredCVar = pMember->Value; } // set registered flag DebugAssert(!(pCVar->m_iFlags & CVAR_FLAG_REGISTERED)); pCVar->m_iFlags |= CVAR_FLAG_REGISTERED; // store in map if (pMember != NULL) pMember->Value = pCVar; else pMember = m_hmCVars.Insert(pCVar->GetName().GetCharArray(), pCVar); // if unregistered, set value to what the unregistered cvar was set to if (pUnregisteredCVar != NULL) { pCVar->m_iFlags |= CVAR_FLAG_WAS_UNREGISTERED; if (!UpdateCVar(pCVar, pUnregisteredCVar->m_strStrValue.GetCharArray(), false)) Log_WarningPrintf("Could not set unregistered value for CVar '%s' (value: '%s')", pCVar->m_strName.GetCharArray(), pUnregisteredCVar->m_strStrValue.GetCharArray()); // and free the unregistered one (shouldn't have any external references, as we never return unregistered vars) delete pUnregisteredCVar; } else { // set value to default WriteCVar(pCVar, pCVar->m_strDefaultValue.GetCharArray()); } // create a command for it if (m_commands.Find(pCVar->GetName()) == nullptr) { RegisteredCommand command; command.Name = pCVar->GetName(); command.ExecuteMethod = CVarViewEditCommandExecuteHandler; command.HelpMethod = CVarViewEditCommandHelpHandler; command.pUserData = reinterpret_cast<void *>(pCVar); m_commands.Insert(command.Name, command); } } void Console::RemoveCVar(CVar *pCVar) { CVarHashTable::Member *pMember = m_hmCVars.Find(pCVar->m_strName.GetCharArray()); DebugAssert(pMember != NULL && pMember->Value == pCVar); m_hmCVars.Remove(pMember); // remove the command CommandTable::Member *pCommandTableMember = m_commands.Find(pCVar->GetName()); if (pCommandTableMember != nullptr && pCommandTableMember->Value.pUserData == pCVar) m_commands.Remove(pCommandTableMember); } CVar *Console::GetCVar(const char *Name) { CVarHashTable::Member *pMember = m_hmCVars.Find(Name); return (pMember != NULL && pMember->Value->m_iFlags & CVAR_FLAG_REGISTERED) ? pMember->Value : NULL; } bool Console::SetCVarByName(const char *Name, const char *Value, bool Force /* = false */, bool CreateUnregistered /* = true */) { CVarHashTable::Member *pMember = m_hmCVars.Find(Name); if (pMember == NULL) return UpdateCVar(new CVar(Name, 0, NULL, NULL, NULL), Value, Force); else return UpdateCVar(pMember->Value, Value, Force); } bool Console::SetCVar(CVar *pCVar, const char *Value, bool Force /* = false */) { DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, Value, Force); } bool Console::SetCVar(CVar *pCVar, uint32 Value, bool Force /* = false */) { char Str[128]; Y_strfromuint32(Str, countof(Str), Value); DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, Str, Force); } bool Console::SetCVar(CVar *pCVar, int32 Value, bool Force /* = false */) { char Str[128]; Y_strfromint32(Str, countof(Str), Value); DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, Str, Force); } bool Console::SetCVar(CVar *pCVar, float Value, bool Force /* = false */) { char Str[128]; Y_strfromfloat(Str, countof(Str), Value); DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, Str, Force); } bool Console::SetCVar(CVar *pCVar, bool Value, bool Force /* = false */) { char Str[128]; Y_strfrombool(Str, countof(Str), Value); DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, Str, Force); } bool Console::ResetCVar(CVar *pCVar) { DebugAssert(pCVar->m_iFlags & CVAR_FLAG_REGISTERED); return UpdateCVar(pCVar, pCVar->m_strDefaultValue.GetCharArray(), false); } bool Console::UpdateCVar(CVar *pCVar, const char *NewValue, bool Force) { AcquireMutex(); // todo validation // update modified flag if (pCVar->m_strDefaultValue.Compare(NewValue)) pCVar->m_iFlags &= ~CVAR_FLAG_MODIFIED; else pCVar->m_iFlags |= CVAR_FLAG_MODIFIED; // pending set? if (pCVar->m_iFlags & CVAR_FLAG_REQUIRE_APP_RESTART && m_appStarted) { Log_InfoPrintf("\"%s\" will be set upon application restart.", pCVar->m_strName.GetCharArray()); pCVar->m_strPendingValue = NewValue; pCVar->m_bChangePending = true; ReleaseMutex(); return true; } else if (pCVar->m_iFlags & CVAR_FLAG_REQUIRE_RENDER_RESTART && m_rendererStarted) { Log_InfoPrintf("\"%s\" will be set upon render restart.", pCVar->m_strName.GetCharArray()); pCVar->m_strPendingValue = NewValue; pCVar->m_bChangePending = true; m_hasPendingRenderCVars = true; ReleaseMutex(); return true; } // update actual value WriteCVar(pCVar, NewValue); ReleaseMutex(); return true; } void Console::WriteCVar(CVar *pCVar, const char *NewValue) { pCVar->m_strStrValue = NewValue; pCVar->m_iIntValue = Y_strtoint32(pCVar->m_strStrValue.GetCharArray(), NULL); pCVar->m_fFloatValue = Y_strtofloat(pCVar->m_strStrValue.GetCharArray(), NULL); pCVar->m_bBoolValue = Y_strtobool(pCVar->m_strStrValue.GetCharArray(), NULL); for (uint32 i = 0; i < pCVar->m_callbacks.GetSize(); i++) pCVar->m_callbacks[i]->Invoke(); } void Console::ApplyPendingAppCVars() { Log_InfoPrintf("Console::ApplyPendingAppCVars()"); m_appStarted = true; for (CVarHashTable::Iterator itr = m_hmCVars.Begin(); !itr.AtEnd(); itr.Forward()) { CVar *pCVar = itr->Value; if (pCVar->m_iFlags & CVAR_FLAG_REQUIRE_APP_RESTART && pCVar->m_bChangePending) { WriteCVar(pCVar, pCVar->m_strPendingValue.GetCharArray()); pCVar->m_strPendingValue.Obliterate(); pCVar->m_bChangePending = false; } } } void Console::ApplyPendingRenderCVars() { Log_InfoPrintf("Console::ApplyPendingRenderCVars()"); m_rendererStarted = true; for (CVarHashTable::Iterator itr = m_hmCVars.Begin(); !itr.AtEnd(); itr.Forward()) { CVar *pCVar = itr->Value; if (pCVar->m_iFlags & CVAR_FLAG_REQUIRE_RENDER_RESTART && pCVar->m_bChangePending) { Log_DevPrintf(" %s -> '%s'", pCVar->GetName().GetCharArray(), pCVar->m_strPendingValue.GetCharArray()); WriteCVar(pCVar, pCVar->m_strPendingValue.GetCharArray()); pCVar->m_strPendingValue.Obliterate(); pCVar->m_bChangePending = false; } } m_hasPendingRenderCVars = false; } uint32 Console::ParseCommandLine(uint32 argc, const char **argv) { /* #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) // argv[0] always contains the path to the binary, so we ignore it. if (argc < 2) return true; // start reading arguments for (int i = 1; i < argc; ) { if (CHECK_ARG_PARAM("-fs_basepath")) // alter base path g_pVirtualFileSystem->SetBasePath(argv[++i]); else if (CHECK_ARG_PARAM("-fs_userpath")) // alter user path g_pVirtualFileSystem->SetUserPath(argv[++i]); else if (CHECK_ARG_PARAM("-fs_gamedir")) // alter game name g_pVirtualFileSystem->SetGameDirectory(argv[++i]); i++; } return true; #undef*/ // argv[0] always contains the path to the binary, so we ignore it. if (argc < 2) return argc - 1; // start reading arguments for (uint32 i = 1; i < argc; i++) { if (argv[i][0] == '-') { if ((i + 1) < argc) { const char *cvarName = &argv[i][1]; const char *cvarValue = argv[++i]; // possible cvar CVarHashTable::Iterator itr; for (itr = m_hmCVars.Begin(); !itr.AtEnd(); itr.Forward()) { CVar *pCVar = itr->Value; if (pCVar->GetName().CompareInsensitive(cvarName)) { // set to this cvar if (UpdateCVar(pCVar, cvarValue, false)) Log_DevPrintf("Console::ParseCommandLine: Set cvar '%s' to '%s'", cvarName, cvarValue); else Log_WarningPrintf("Console::ParseCommandLine: Setting cvar '%s' to value '%s' failed.", pCVar->GetName().GetCharArray(), cvarValue); break; } } if (itr.AtEnd()) Log_WarningPrintf("Console::ParseCommandLine: Did not find a cvar named '%s' in registry.", cvarName); } } else { return i; } } return argc; } bool Console::ExecuteText(const char *text) { uint32 textLength = Y_strlen(text); if (textLength == 0) return false; // echo it Log_InfoPrintf("> %s", text); // copy the string to local memory char *tempString = (char *)alloca(textLength + 1); Y_memcpy(tempString, text, textLength + 1); // tokenize it char *tokens[32]; uint32 nTokens = Y_strsplit2(tempString, ' ', tokens, countof(tokens)); DebugAssert(nTokens > 0); // lookup registered commands CommandTable::Member *pMember = m_commands.Find(tokens[0]); if (pMember == nullptr) { // log an error Log_ErrorPrintf("No command or variable named '%s' was found.", tokens[0]); return false; } // execute it return pMember->Value.ExecuteMethod(pMember->Value.pUserData, nTokens, tokens); } bool Console::HandlePartialHelp(const char *text) { uint32 textLength = Y_strlen(text); if (textLength == 0) return false; // copy the string to local memory char *tempString = (char *)alloca(textLength + 1); Y_memcpy(tempString, text, textLength + 1); // tokenize it char *tokens[32]; uint32 nTokens = Y_strsplit2(tempString, ' ', tokens, countof(tokens)); DebugAssert(nTokens > 0); // lookup registered commands, is there an exact match? const CommandTable::Member *pMember = m_commands.Find(tokens[0]); if (pMember != nullptr) { // refer to the command's help handler Log_InfoPrintf("> %s", text); return pMember->Value.HelpMethod(pMember->Value.pUserData, nTokens, tokens); } // find the closest match, if there is more than one, dump everything starting with this name const CommandTable::Member *pClosestMatch = nullptr; for (CommandTable::ConstIterator itr = m_commands.Begin(); !itr.AtEnd(); itr.Forward()) { // begins with it? if (itr->Value.Name.StartsWith(tokens[0], false)) { // found one already? if (pClosestMatch == nullptr) { pClosestMatch = &(*itr); continue; } // more than one command starts with this prefix, so find everything starting with it, dump it in a temp array PODArray<const RegisteredCommand *> foundCommands; for (CommandTable::ConstIterator innerItr = m_commands.Begin(); !innerItr.AtEnd(); innerItr.Forward()) { if (innerItr->Value.Name.StartsWith(tokens[0], false)) foundCommands.Add(&innerItr->Value); } // sort them in alphabetical order foundCommands.SortCB([](const RegisteredCommand *pLeft, const RegisteredCommand *pRight) { return pLeft->Name.NumericCompareInsensitive(pRight->Name); }); // display found entries Log_InfoPrintf("> %s [%u matches listed]:", text, foundCommands.GetSize()); for (uint32 i = 0; i < foundCommands.GetSize(); i++) Log_InfoPrintf(" %s", foundCommands[i]->Name.GetCharArray()); // done for now return true; } } // execute the closest match if (pClosestMatch != nullptr) { // refer to the command's help handler Log_InfoPrintf(">%s", text); return pClosestMatch->Value.HelpMethod(pMember->Value.pUserData, nTokens, tokens); } // nope.avi Log_InfoPrintf(">%s", text); Log_ErrorPrintf(" No matches"); return false; } bool Console::HandleAutoCompletion(String &commandString) { // currently unsupported for arguments if (commandString.Find(' ') >= 0) return false; // lookup registered commands, is there an exact match? const CommandTable::Member *pMember = m_commands.Find(commandString); if (pMember != nullptr) { // already done return true; } // find the closest match, if there is more than one, dump everything starting with this name const CommandTable::Member *pClosestMatch = nullptr; for (CommandTable::ConstIterator itr = m_commands.Begin(); !itr.AtEnd(); itr.Forward()) { // begins with it? if (itr->Value.Name.StartsWith(commandString, false)) { // found one already? if (pClosestMatch == nullptr) { pClosestMatch = &(*itr); continue; } // more than one command starts with this prefix, so find everything starting with it, dump it in a temp array PODArray<const RegisteredCommand *> foundCommands; for (CommandTable::ConstIterator innerItr = m_commands.Begin(); !innerItr.AtEnd(); innerItr.Forward()) { if (innerItr->Value.Name.StartsWith(commandString, false)) foundCommands.Add(&innerItr->Value); } // sort them in alphabetical order foundCommands.SortCB([](const RegisteredCommand *pLeft, const RegisteredCommand *pRight) { return pLeft->Name.NumericCompareInsensitive(pRight->Name); }); // find where the similarities end SmallString matchCommandPart; for (uint32 i = 0; i < foundCommands[0]->Name.GetLength(); i++) { char ch = foundCommands[0]->Name[i]; for (uint32 j = 1; j < foundCommands.GetSize(); j++) { if (i >= foundCommands[j]->Name.GetLength() || foundCommands[j]->Name[i] != ch) { ch = 0; break; } } if (ch != 0) matchCommandPart.AppendCharacter(ch); else break; } // change to this command commandString.Clear(); commandString.AppendString(matchCommandPart); // display found entries Log_InfoPrintf("> %s [%u matches listed]:", commandString.GetCharArray(), foundCommands.GetSize()); for (uint32 i = 0; i < foundCommands.GetSize(); i++) Log_InfoPrintf(" %s", foundCommands[i]->Name.GetCharArray()); // done for now return true; } } // replace with closest match if (pClosestMatch != nullptr) { commandString.Format("%s", pClosestMatch->Value.Name.GetCharArray()); return true; } // nope Log_InfoPrintf(">%s", commandString.GetCharArray()); Log_ErrorPrintf(" No matches"); return false; } void Console::DumpCVarHelp(const CVar *pCVar) { SmallString flagsString; if (pCVar->GetFlags() & CVAR_FLAG_REGISTERED) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "Registered"); if (pCVar->GetFlags() & CVAR_FLAG_WAS_UNREGISTERED) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "Unregistered"); if (pCVar->GetFlags() & CVAR_FLAG_READ_ONLY) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "ReadOnly"); if (pCVar->GetFlags() & CVAR_FLAG_MODIFIED) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "Modified"); if (pCVar->GetFlags() & CVAR_FLAG_NO_ARCHIVE) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "NoArchive"); if (pCVar->GetFlags() & CVAR_FLAG_REQUIRE_APP_RESTART) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "RequireAppRestart"); if (pCVar->GetFlags() & CVAR_FLAG_REQUIRE_RENDER_RESTART) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "RequireRenderRestart"); if (pCVar->GetFlags() & CVAR_FLAG_REQUIRE_MAP_RESTART) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "RequireMapRestart"); if (pCVar->GetFlags() & CVAR_FLAG_PAUSE_RENDER_THREAD) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "PauseRenderThread"); if (pCVar->GetFlags() & CVAR_FLAG_CHEAT) flagsString.AppendFormattedString("%s%s", (flagsString.GetLength() > 0) ? ", " : "", "Cheat"); Log_InfoPrintf("CVar information for %s:", pCVar->GetName().GetCharArray()); Log_InfoPrintf(" Description: %s", pCVar->GetHelp().GetCharArray()); Log_InfoPrintf(" Flags: %s", flagsString.GetCharArray()); Log_InfoPrintf(" Domain: %s", pCVar->GetDomain().GetCharArray()); Log_InfoPrintf(" Default Value: %s", pCVar->GetDefaultValue().GetCharArray()); Log_InfoPrintf(" Current Value: %s", pCVar->GetString().GetCharArray()); } void Console::DumpCVarValue(const CVar *pCVar) { SmallString message; // 'cvar_name' is 'value' message.Format("'%s' is '%s'", pCVar->GetName().GetCharArray(), pCVar->GetString().GetCharArray()); // , domain is 'bool' message.AppendFormattedString(", domain is '%s'", pCVar->GetDomain().GetCharArray()); // log it Log_InfoPrint(message); } bool Console::CVarViewEditCommandExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { CVar *pCVar = reinterpret_cast<CVar *>(userData); // if argument count is one, display information about it if (argumentCount == 1) { g_pConsole->DumpCVarHelp(pCVar); return true; } else if (argumentCount == 2) { // change the value if (g_pConsole->SetCVarByName(argumentValues[0], argumentValues[1], false, false)) { Log_InfoPrintf(" CVar '%s' set to '%s'.", pCVar->GetName().GetCharArray(), argumentValues[1]); return true; } else { Log_ErrorPrintf(" Failed to modify cvar '%s'", pCVar->GetName().GetCharArray()); return false; } } else { Log_ErrorPrint(" Invalid arguments, a single argument, the value, is permitted"); return false; } } bool Console::CVarViewEditCommandHelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]) { CVar *pCVar = reinterpret_cast<CVar *>(userData); DebugAssert(argumentCount > 0); if (argumentCount == 1) Log_InfoPrintf(" <%s> or <CR> (current value is %s)", pCVar->GetDomain().GetCharArray(), pCVar->GetString().GetCharArray()); else if (argumentCount == 2) Log_InfoPrint(" <CR>"); else Log_ErrorPrint(" Invalid arguments, a single argument, the value, is permitted"); return true; } bool Console::RegisterCommand(const char *commandName, CommandHandlerMethod executeMethod, CommandHandlerMethod helpMethod, void *userData, const void *ownerPtr /* = nullptr */) { CommandTable::Member *pMember = m_commands.Find(commandName); if (pMember != nullptr) return false; RegisteredCommand command; command.Name = commandName; command.ExecuteMethod = executeMethod; command.HelpMethod = helpMethod; command.pUserData = userData; command.pOwnerPtr = ownerPtr; m_commands.Insert(command.Name, command); return true; } bool Console::UnregisterCommand(const char *commandName) { CommandTable::Member *pMember = m_commands.Find(commandName); if (pMember == nullptr) return false; m_commands.Remove(pMember); return true; } uint32 Console::UnregisterCommandsWithOwner(const void *ownerPtr) { uint32 commandsRemoved = 0; for (CommandTable::Iterator itr = m_commands.Begin(); !itr.AtEnd();) { CommandTable::Member *pMember = &(*itr); itr.Forward(); if (pMember->Value.pOwnerPtr == ownerPtr) { m_commands.Remove(pMember); commandsRemoved++; } } return commandsRemoved; } CVar::CVar(const char *Name, uint32 Flags, const char *DefaultValue /* = NULL */, const char *Help /* = NULL */, const char *Domain /* = NULL */) { // set values DebugAssert(Name != NULL && *Name != '\0'); m_strName = Name; if (DefaultValue != NULL) m_strDefaultValue = DefaultValue; if (Help != NULL) m_strHelp = Help; if (Domain != NULL) m_strDomain = Domain; // clear flags that shouldn't be getting passed m_iFlags = Flags & ~(CVAR_FLAG_MODIFIED | CVAR_FLAG_REGISTERED | CVAR_FLAG_WAS_UNREGISTERED); // have to use the singleton accessor here Console::GetInstance().RegisterCVar(this); } CVar::~CVar() { Console::GetInstance().RemoveCVar(this); for (uint32 i = 0; i < m_callbacks.GetSize(); i++) delete m_callbacks[i]; } void CVar::AddChangeCallback(Functor *pCallback) { Console::GetInstance().AcquireMutex(); m_callbacks.Add(pCallback); Console::GetInstance().ReleaseMutex(); } void CVar::RemoveChangeCallback(Functor *pCallback) { Console::GetInstance().AcquireMutex(); for (uint32 i = 0; i < m_callbacks.GetSize(); i++) { if (m_callbacks[i] == pCallback) { m_callbacks.OrderedRemove(i); break; } } Console::GetInstance().ReleaseMutex(); } const String &CVar::GetPendingString() const { return (m_bChangePending) ? m_strPendingValue : m_strStrValue; } int32 CVar::GetPendingInt() const { return (m_bChangePending) ? StringConverter::StringToInt32(m_strPendingValue) : m_iIntValue; } uint32 CVar::GetPendingUInt() const { return (m_bChangePending) ? (uint32)StringConverter::StringToInt32(m_strPendingValue) : (uint32)m_iIntValue; } float CVar::GetPendingFloat() const { return (m_bChangePending) ? StringConverter::StringToFloat(m_strPendingValue) : m_fFloatValue; } bool CVar::GetPendingBool() const { return (m_bChangePending) ? StringConverter::StringToBool(m_strPendingValue) : m_bBoolValue; } <file_sep>/Engine/Source/ResourceCompiler/PrecompiledHeader.h #pragma once #include "ResourceCompiler/Common.h" <file_sep>/Engine/Source/Renderer/Shaders/DeferredShadingShaders.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/DeferredShadingShaders.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderConstantBuffer.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Renderer.h" #include "Engine/MaterialShader.h" DEFINE_SHADER_COMPONENT_INFO(DeferredGBufferShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredGBufferShader) END_SHADER_COMPONENT_PARAMETERS() bool DeferredGBufferShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo == nullptr || pMaterialShader == nullptr) return false; if (pMaterialShader->GetLightingType() == MATERIAL_LIGHTING_TYPE_REFLECTIVE) return false; return true; } bool DeferredGBufferShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DeferredGBufferShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DeferredGBufferShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_LIGHTMAP) pParameters->AddPreprocessorMacro("WITH_LIGHTMAP", "1"); if (baseShaderFlags & WITH_LIGHTBUFFER) pParameters->AddPreprocessorMacro("WITH_LIGHTBUFFER", "1"); if (baseShaderFlags & NO_ALBEDO) pParameters->AddPreprocessorMacro("NO_ALBEDO", "1"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DeferredDirectionalLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredDirectionalLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer0", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer1", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer2", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("ShadowMapTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbDeferredDirectionalLightParameters, "DeferredDirectionalLightParameters", "cbDeferredDirectionalLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_SM4, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightVector", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("AmbientColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("ShadowMapSize", SHADER_PARAMETER_TYPE_FLOAT4, 1) SHADER_CONSTANT_BUFFER_FIELD("CascadeViewProjectionMatrix", SHADER_PARAMETER_TYPE_FLOAT4X4, CSMShadowMapRenderer::MaxCascadeCount) SHADER_CONSTANT_BUFFER_FIELD("CascadeSplitDepths", SHADER_PARAMETER_TYPE_FLOAT, CSMShadowMapRenderer::MaxCascadeCount) END_SHADER_CONSTANT_BUFFER(cbDeferredDirectionalLightParameters) uint32 DeferredDirectionalLightShader::CalculateShadowFlags(bool enableShadows, bool useHardwareShadowFiltering, RENDERER_SHADOW_FILTER shadowFilter, bool showCascades) { uint32 flags = 0; if (enableShadows) { flags |= WITH_SHADOW_MAP; if (useHardwareShadowFiltering) flags |= USE_HARDWARE_PCF; switch (shadowFilter) { case RENDERER_SHADOW_FILTER_3X3: flags |= SHADOW_FILTER_3X3; break; case RENDERER_SHADOW_FILTER_5X5: flags |= SHADOW_FILTER_5X5; break; //case RENDERER_SHADOW_FILTER_1X1: default: flags |= SHADOW_FILTER_1X1; break; } if (showCascades) flags |= SHOW_CASCADES; } return flags; } void DeferredDirectionalLightShader::SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { // TODO convert direction to viewspace //cbDeferredDirectionalLightParameters.SetFieldFloat3(pCommandList, 0, pLight->Direction, false); cbDeferredDirectionalLightParameters.SetFieldFloat3(pCommandList, 0, pViewParameters->ViewCamera.GetViewMatrix().TransformNormal(pLight->Direction), false); cbDeferredDirectionalLightParameters.SetFieldFloat3(pCommandList, 1, pLight->LightColor, false); cbDeferredDirectionalLightParameters.SetFieldFloat3(pCommandList, 2, pLight->AmbientColor, false); } void DeferredDirectionalLightShader::SetShadowParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const CSMShadowMapRenderer::ShadowMapData *pShadowMapData) { uint32 shadowMapWidth = pShadowMapData->pShadowMapTexture->GetDesc()->Width; uint32 shadowMapHeight = pShadowMapData->pShadowMapTexture->GetDesc()->Height; float4 shadowMapSize((float)shadowMapWidth, 1.0f / (float)pShadowMapData->CascadeCount, 1.0f / (float)shadowMapWidth, 1.0f / (float)shadowMapHeight); cbDeferredDirectionalLightParameters.SetFieldFloat4(pCommandList, 3, shadowMapSize, false); cbDeferredDirectionalLightParameters.SetFieldFloat4x4Array(pCommandList, 4, 0, pShadowMapData->CascadeCount, pShadowMapData->ViewProjectionMatrices, false); cbDeferredDirectionalLightParameters.SetFieldFloatArray(pCommandList, 5, 0, pShadowMapData->CascadeCount, pShadowMapData->CascadeFrustumEyeSpaceDepths, false); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 4, pShadowMapData->pShadowMapTexture, nullptr); } void DeferredDirectionalLightShader::SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pDepthBuffer, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 1, pGBuffer0, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 2, pGBuffer1, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 3, pGBuffer2, nullptr); } void DeferredDirectionalLightShader::CommitParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) { cbDeferredDirectionalLightParameters.CommitChanges(pCommandList); } bool DeferredDirectionalLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DeferredDirectionalLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DeferredDirectionalLightShader.hlsl", "PSMain"); // need view ray from VS /*GPU_VERTEX_ELEMENT_DESC screenQuadVertexElementDesc(GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT3, 0, 0, 0); pParameters->AddVertexAttribute(&screenQuadVertexElementDesc);*/ pParameters->AddPreprocessorMacro("GENERATE_VIEW_RAY", "1"); if (baseShaderFlags & WITH_SHADOW_MAP) { pParameters->AddPreprocessorMacro("WITH_SHADOW_MAP", "1"); if (baseShaderFlags & USE_HARDWARE_PCF) pParameters->AddPreprocessorMacro("USE_HARDWARE_PCF", "1"); // filter if (baseShaderFlags & SHADOW_FILTER_3X3) pParameters->AddPreprocessorMacro("SHADOW_FILTER_3X3", "1"); else if (baseShaderFlags & SHADOW_FILTER_5X5) pParameters->AddPreprocessorMacro("SHADOW_FILTER_5X5", "1"); else //if (baseShaderFlags & SHADOW_FILTER_1X1) pParameters->AddPreprocessorMacro("SHADOW_FILTER_1X1", "1"); if (baseShaderFlags & SHOW_CASCADES) pParameters->AddPreprocessorMacro("SHOW_CASCADES", "1"); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DeferredPointLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredPointLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer0", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer1", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer2", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("ShadowMapTexture", SHADER_PARAMETER_TYPE_TEXTURECUBE) END_SHADER_COMPONENT_PARAMETERS() BEGIN_SHADER_CONSTANT_BUFFER(cbDeferredPointLightParameters, "DeferredPointLightParameters", "cbDeferredPointLightParameters", RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_COUNT, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) SHADER_CONSTANT_BUFFER_FIELD("LightColor", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPosition", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightPositionVS", SHADER_PARAMETER_TYPE_FLOAT3, 1) SHADER_CONSTANT_BUFFER_FIELD("LightRange", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightInverseRange", SHADER_PARAMETER_TYPE_FLOAT, 1) SHADER_CONSTANT_BUFFER_FIELD("LightFalloffExponent", SHADER_PARAMETER_TYPE_FLOAT, 1) END_SHADER_CONSTANT_BUFFER(cbDeferredPointLightParameters) uint32 DeferredPointLightShader::CalculateShadowFlags(bool enableShadows, bool useHardwareShadowFiltering) { uint32 flags = 0; if (enableShadows) { flags |= WITH_SHADOW_MAP; if (useHardwareShadowFiltering) flags |= USE_HARDWARE_PCF; } return flags; } void DeferredPointLightShader::SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { cbDeferredPointLightParameters.SetFieldFloat3(pCommandList, 0, pLight->LightColor, false); cbDeferredPointLightParameters.SetFieldFloat3(pCommandList, 1, pLight->Position, false); cbDeferredPointLightParameters.SetFieldFloat3(pCommandList, 2, pViewParameters->ViewCamera.GetViewMatrix().TransformPoint(pLight->Position), false); cbDeferredPointLightParameters.SetFieldFloat(pCommandList, 3, pLight->Range, false); cbDeferredPointLightParameters.SetFieldFloat(pCommandList, 4, pLight->InverseRange, false); cbDeferredPointLightParameters.SetFieldFloat(pCommandList, 5, pLight->FalloffExponent, false); cbDeferredPointLightParameters.CommitChanges(pCommandList); } void DeferredPointLightShader::SetShadowParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const CubeMapShadowMapRenderer::ShadowMapData *pShadowMapData) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 4, pShadowMapData->pShadowMapTexture, nullptr); } void DeferredPointLightShader::SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pDepthBuffer, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 1, pGBuffer0, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 2, pGBuffer1, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 3, pGBuffer2, nullptr); } bool DeferredPointLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DeferredPointLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DeferredPointLightShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DeferredPointLightShader.hlsl", "PSMain"); if (baseShaderFlags & WITH_SHADOW_MAP) { pParameters->AddPreprocessorMacro("WITH_SHADOW_MAP", "1"); if (baseShaderFlags & USE_HARDWARE_PCF) pParameters->AddPreprocessorMacro("USE_HARDWARE_PCF", "1"); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DeferredPointLightListShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredPointLightListShader) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer0", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer1", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer2", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("LightParameters", SHADER_PARAMETER_TYPE_STRUCT) END_SHADER_COMPONENT_PARAMETERS() struct _ShaderPointLight { _ShaderPointLight(const float3 &position, float range, const float3 &color, float falloffExponent) : Position(position), Range(range), Color(color), FalloffExponent(falloffExponent) {} float3 Position; float Range; float3 Color; float FalloffExponent; }; void DeferredPointLightListShader::SetLightParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, uint32 lightIndex, const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { DebugAssert(lightIndex < MAX_LIGHTS); _ShaderPointLight lightParams(pLight->Position, pLight->Range, pLight->LightColor, pLight->FalloffExponent); pShaderProgram->SetBaseShaderParameterStructArray(pCommandList, 4, &lightParams, sizeof(lightParams), lightIndex, 1); } void DeferredPointLightListShader::SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pDepthBuffer, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 1, pGBuffer0, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 2, pGBuffer1, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 3, pGBuffer2, nullptr); } bool DeferredPointLightListShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DeferredPointLightListShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/DeferredPointLightListShader.hlsl", "VSMain"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DeferredPointLightListShader.hlsl", "PSMain"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DeferredTiledPointLightShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredTiledPointLightShader) DEFINE_SHADER_COMPONENT_PARAMETER("ActiveLightCount", SHADER_PARAMETER_TYPE_UINT) DEFINE_SHADER_COMPONENT_PARAMETER("TileCountX", SHADER_PARAMETER_TYPE_UINT) DEFINE_SHADER_COMPONENT_PARAMETER("TileCountY", SHADER_PARAMETER_TYPE_UINT) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer0", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer1", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("GBuffer2", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("LightBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() DEFINE_RAW_SHADER_CONSTANT_BUFFER(cbDeferredTiledPointLightShaderLightBuffer, "DeferredTiledPointLightShaderLightBuffer", "", sizeof(DeferredTiledPointLightShader::Light) * DeferredTiledPointLightShader::MAX_LIGHTS_PER_DISPATCH, RENDERER_PLATFORM_COUNT, RENDERER_FEATURE_LEVEL_SM5, SHADER_CONSTANT_BUFFER_UPDATE_FREQUENCY_PER_PROGRAM) void DeferredTiledPointLightShader::SetLights(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const Light *pLights, uint32 nLights) { cbDeferredTiledPointLightShaderLightBuffer.SetRawData(pCommandList, 0, sizeof(Light) * nLights, pLights, true); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 0, SHADER_PARAMETER_TYPE_UINT, &nLights); } void DeferredTiledPointLightShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, uint32 tileCountX, uint32 tileCountY) { pShaderProgram->SetBaseShaderParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_UINT, &tileCountX); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 2, SHADER_PARAMETER_TYPE_UINT, &tileCountY); } void DeferredTiledPointLightShader::SetBufferParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pGBuffer0, GPUTexture2D *pGBuffer1, GPUTexture2D *pGBuffer2, GPUTexture2D *pLightBuffer) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 3, pDepthBuffer, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 4, pGBuffer0, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 5, pGBuffer1, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 6, pGBuffer2, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 7, pLightBuffer, nullptr); } void DeferredTiledPointLightShader::CommitParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) { cbDeferredTiledPointLightShaderLightBuffer.CommitChanges(pCommandList); } bool DeferredTiledPointLightShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DeferredTiledPointLightShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM5 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM5) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_COMPUTE_SHADER, "shaders/base/d3d11/DeferredTiledPointLightShader.hlsl", "Main"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_SHADER_COMPONENT_INFO(DeferredFogShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DeferredFogShader) DEFINE_SHADER_COMPONENT_PARAMETER("FogStartDistance", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("FogEndDistance", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("FogDistance", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("FogDensity", SHADER_PARAMETER_TYPE_FLOAT) DEFINE_SHADER_COMPONENT_PARAMETER("FogColor", SHADER_PARAMETER_TYPE_FLOAT3) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() uint32 DeferredFogShader::GetFlagsForMode(RENDERER_FOG_MODE mode) { switch (mode) { case RENDERER_FOG_MODE_LINEAR: return MODE_LINEAR; case RENDERER_FOG_MODE_EXP: return MODE_EXP; case RENDERER_FOG_MODE_EXP2: return MODE_EXP2; } return 0; } void DeferredFogShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const WorldRenderer::ViewParameters *pViewParameters, GPUTexture2D *pDepthBuffer) { float fogDistance = pViewParameters->FogEndDistance - pViewParameters->FogStartDistance; float3 fogColor(PixelFormatHelpers::ConvertSRGBToLinear(pViewParameters->FogColor)); float3 f2(PixelFormatHelpers::ConvertLinearToSRGB(fogColor)); // set parameters pShaderProgram->SetBaseShaderParameterValue(pCommandList, 0, SHADER_PARAMETER_TYPE_FLOAT, &pViewParameters->FogStartDistance); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT, &pViewParameters->FogEndDistance); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 2, SHADER_PARAMETER_TYPE_FLOAT, &fogDistance); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 3, SHADER_PARAMETER_TYPE_FLOAT, &pViewParameters->FogDensity); pShaderProgram->SetBaseShaderParameterValue(pCommandList, 4, SHADER_PARAMETER_TYPE_FLOAT3, &fogColor); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 5, pDepthBuffer, nullptr); } bool DeferredFogShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DeferredFogShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/FogShader.hlsl", "PSMain"); // need view ray from VS pParameters->AddPreprocessorMacro("GENERATE_VIEW_RAY", "1"); // mode flags if (baseShaderFlags & MODE_LINEAR) pParameters->AddPreprocessorMacro("FOG_MODE_LINEAR", "1"); if (baseShaderFlags & MODE_EXP) pParameters->AddPreprocessorMacro("FOG_MODE_EXP", "1"); if (baseShaderFlags & MODE_EXP2) pParameters->AddPreprocessorMacro("FOG_MODE_EXP2", "1"); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Engine/Source/Engine/Profiling.h #pragma once #include "Engine/Common.h" #ifdef WITH_PROFILER #ifdef Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable: 4127) // warning C4127: conditional expression is constant #include "microprofile.h" #pragma warning(pop) #else #include "microprofile.h" #endif #define MICROPROFILE_COLOR(r, g, b) ((uint32)0xFF000000 | ((uint32)(r) << 16) | ((uint32)(g) << 8) | ((uint32)(b)) ) #endif // WITH_PROFILER namespace Profiling { bool GetProfilerEnabled(); void SetProfilerEnabled(bool enabled); bool IsProfilerDisplayEnabled(); bool SetProfilerDisplay(uint32 mode); bool ToggleProfilerDisplay(); void HideProfilerDisplay(); void Initialize(); void StartFrame(); // Returns true if the event was used, false otherwise. bool HandleSDLEvent(const void *pEvent); void DrawDisplay(); void EndFrame(); } <file_sep>/Engine/Source/Engine/TerrainRendererNull.h #pragma once #include "Engine/TerrainRenderer.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/VertexFactory.h" class TerrainRendererNull; class TerrainSectionRenderProxyNull; class TerrainRendererNull : public TerrainRenderer { public: TerrainRendererNull(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); virtual ~TerrainRendererNull(); // create a render proxy for this terrain virtual TerrainSectionRenderProxy *CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) override final; // gpu resources virtual bool CreateGPUResources() override final; virtual void ReleaseGPUResources() override final; }; class TerrainSectionRenderProxyNull : public TerrainSectionRenderProxy { public: TerrainSectionRenderProxyNull(uint32 entityId, const TerrainRendererNull *pRenderer, const TerrainSection *pSection); ~TerrainSectionRenderProxyNull(); virtual void OnLayersModified() override final; virtual void OnPointHeightModified(uint32 x, uint32 y) override final; virtual void OnPointLayersModified(uint32 x, uint32 y) override final; private: const TerrainRendererNull *m_pRenderer; }; <file_sep>/Engine/Source/GameFramework/StaticMeshComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/StaticMeshComponent.h" #include "Engine/ResourceManager.h" #include "Engine/Entity.h" #include "Engine/World.h" #include "Engine/Physics/KinematicObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderWorld.h" DEFINE_COMPONENT_TYPEINFO(StaticMeshComponent); DEFINE_COMPONENT_GENERIC_FACTORY(StaticMeshComponent); BEGIN_COMPONENT_PROPERTIES(StaticMeshComponent) PROPERTY_TABLE_MEMBER("StaticMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetMeshName, NULL, PropertyCallbackSetMeshName, NULL, PropertyCallbackStaticMeshChanged, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(StaticMeshComponent, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(StaticMeshComponent, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(StaticMeshComponent, m_shadowFlags), NULL, NULL) END_COMPONENT_PROPERTIES() StaticMeshComponent::StaticMeshComponent(const ComponentTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pStaticMesh(nullptr), m_visible(true), m_collidable(false), m_shadowFlags(0), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } StaticMeshComponent::~StaticMeshComponent() { if (m_pCollisionObject != nullptr) m_pCollisionObject->Release(); if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); } void StaticMeshComponent::SetStaticMesh(const StaticMesh *pStaticMesh) { DebugAssert(pStaticMesh != nullptr); if (m_pStaticMesh == pStaticMesh) return; if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); PropertyCallbackStaticMeshChanged(this); } void StaticMeshComponent::SetVisible(bool visible) { if (m_visible == visible) return; m_visible = visible; PropertyCallbackVisibleChanged(this); } void StaticMeshComponent::SetShadowFlags(uint32 shadowFlags) { if (m_shadowFlags == shadowFlags) return; m_shadowFlags = shadowFlags; if (m_pRenderProxy != nullptr) m_pRenderProxy->SetShadowFlags(shadowFlags); } void StaticMeshComponent::SetCollidable(bool collidable) { if (m_collidable == collidable) return; m_collidable = collidable; PropertyCallbackCollidableChanged(this); } void StaticMeshComponent::Create(const float3 &localPosition /* = float3::Zero */, const Quaternion &localRotation /* = Quaternion::Identity */, const float3 &localScale /* = float3::One */, const StaticMesh *pStaticMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_localPosition = localPosition; m_localRotation = localRotation; m_localScale = localScale; if (pStaticMesh != nullptr) { m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); } else { m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; Initialize(); } bool StaticMeshComponent::Initialize() { if (!BaseClass::Initialize()) return false; DebugAssert(m_pStaticMesh != nullptr); if (m_visible) m_pRenderProxy = new StaticMeshRenderProxy(0, m_pStaticMesh, Transform::Identity, m_shadowFlags); if (m_collidable && m_pStaticMesh->GetCollisionShape() != nullptr) m_pCollisionObject = new Physics::KinematicObject(0, m_pStaticMesh->GetCollisionShape(), Transform::Identity); return true; } void StaticMeshComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // calculate the transform Transform worldTransform(CalculateWorldTransform()); // update entity ids if (m_pRenderProxy != nullptr) { m_pRenderProxy->SetEntityID(pEntity->GetEntityID()); m_pRenderProxy->SetTransform(worldTransform); } if (m_pCollisionObject != nullptr) { m_pCollisionObject->SetEntityID(pEntity->GetEntityID()); m_pCollisionObject->SetTransform(worldTransform); } // update bounds, no need to notify the entity as it'll be recalculated when the add is complete SetBounds(worldTransform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), false); } void StaticMeshComponent::OnRemoveFromEntity(Entity *pEntity) { if (m_pRenderProxy != nullptr) m_pRenderProxy->SetEntityID(0); if (m_pCollisionObject != nullptr) m_pCollisionObject->SetEntityID(0); BaseClass::OnRemoveFromEntity(pEntity); } void StaticMeshComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void StaticMeshComponent::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } void StaticMeshComponent::OnLocalTransformChange() { BaseClass::OnLocalTransformChange(); // recalculate the world transform Transform worldTransform(CalculateWorldTransform()); // update proxies if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(worldTransform); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(worldTransform); // change bounding box SetBounds(worldTransform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } void StaticMeshComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // recalculate the world transform Transform worldTransform(CalculateWorldTransform()); // update proxies if (m_pCollisionObject != nullptr) m_pCollisionObject->SetTransform(worldTransform); if (m_pRenderProxy != nullptr) m_pRenderProxy->SetTransform(worldTransform); // change bounding box SetBounds(worldTransform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()), worldTransform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()), true); } bool StaticMeshComponent::PropertyCallbackGetMeshName(ThisClass *pComponent, const void *pUserData, String *pValue) { pValue->Assign(pComponent->m_pStaticMesh->GetName()); return true; } bool StaticMeshComponent::PropertyCallbackSetMeshName(ThisClass *pComponent, const void *pUserData, const String *pValue) { const StaticMesh *pStaticMesh = g_pResourceManager->GetStaticMesh(*pValue); if (pStaticMesh == NULL) return false; if (pComponent->m_pStaticMesh != nullptr) pComponent->m_pStaticMesh->Release(); pComponent->m_pStaticMesh = pStaticMesh; return true; } void StaticMeshComponent::PropertyCallbackStaticMeshChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_visible) { DebugAssert(pComponent->m_pRenderProxy != nullptr); pComponent->m_pRenderProxy->SetStaticMesh(pComponent->m_pStaticMesh); } if (pComponent->m_collidable) { if (pComponent->m_pStaticMesh->GetCollisionShape() != nullptr) { if (pComponent->m_pCollisionObject != nullptr) { pComponent->m_pCollisionObject->SetCollisionShape(pComponent->m_pStaticMesh->GetCollisionShape()); } else { pComponent->m_pCollisionObject = new Physics::KinematicObject((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pStaticMesh->GetCollisionShape(), pComponent->CalculateWorldTransform()); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->AddObject(pComponent->m_pCollisionObject); } } else { if (pComponent->m_pCollisionObject != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->RemoveObject(pComponent->m_pCollisionObject); pComponent->m_pCollisionObject->Release(); pComponent->m_pCollisionObject = nullptr; } } } } void StaticMeshComponent::PropertyCallbackVisibleChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_visible) { if (pComponent->m_pRenderProxy == nullptr) { pComponent->m_pRenderProxy = new StaticMeshRenderProxy((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pStaticMesh, pComponent->CalculateWorldTransform(), pComponent->m_shadowFlags); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetRenderWorld()->AddRenderable(pComponent->m_pRenderProxy); } } else { if (pComponent->m_pRenderProxy != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetRenderWorld()->RemoveRenderable(pComponent->m_pRenderProxy); pComponent->m_pRenderProxy->Release(); pComponent->m_pRenderProxy = nullptr; } } } void StaticMeshComponent::PropertyCallbackCollidableChanged(ThisClass *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_collidable) { if (pComponent->m_pCollisionObject == nullptr && pComponent->m_pStaticMesh->GetCollisionShape() != nullptr) { pComponent->m_pCollisionObject = new Physics::KinematicObject((pComponent->IsAttachedToEntity()) ? pComponent->GetEntity()->GetEntityID() : 0, pComponent->m_pStaticMesh->GetCollisionShape(), pComponent->CalculateWorldTransform()); if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->AddObject(pComponent->m_pCollisionObject); } } else { if (pComponent->m_pCollisionObject != nullptr) { if (pComponent->IsAttachedToEntity() && pComponent->GetEntity()->IsInWorld()) pComponent->GetEntity()->GetWorld()->GetPhysicsWorld()->RemoveObject(pComponent->m_pCollisionObject); pComponent->m_pCollisionObject->Release(); pComponent->m_pCollisionObject = nullptr; } } } <file_sep>/Editor/Source/Editor/StaticMeshEditor/moc_EditorStaticMeshEditor.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorStaticMeshEditor.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorStaticMeshEditor.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorStaticMeshEditor.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorStaticMeshEditor_t { QByteArrayData data[39]; char stringdata[1029]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorStaticMeshEditor_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorStaticMeshEditor_t qt_meta_stringdata_EditorStaticMeshEditor = { { QT_MOC_LITERAL(0, 0, 22), // "EditorStaticMeshEditor" QT_MOC_LITERAL(1, 23, 23), // "OnActionOpenMeshClicked" QT_MOC_LITERAL(2, 47, 0), // "" QT_MOC_LITERAL(3, 48, 23), // "OnActionSaveMeshClicked" QT_MOC_LITERAL(4, 72, 25), // "OnActionSaveMeshAsClicked" QT_MOC_LITERAL(5, 98, 20), // "OnActionCloseClicked" QT_MOC_LITERAL(6, 119, 34), // "OnActionCameraPerspectiveTrig..." QT_MOC_LITERAL(7, 154, 7), // "checked" QT_MOC_LITERAL(8, 162, 30), // "OnActionCameraArcballTriggered" QT_MOC_LITERAL(9, 193, 32), // "OnActionCameraIsometricTriggered" QT_MOC_LITERAL(10, 226, 30), // "OnActionViewWireframeTriggered" QT_MOC_LITERAL(11, 257, 26), // "OnActionViewUnlitTriggered" QT_MOC_LITERAL(12, 284, 24), // "OnActionViewLitTriggered" QT_MOC_LITERAL(13, 309, 32), // "OnActionViewFlagShadowsTriggered" QT_MOC_LITERAL(14, 342, 41), // "OnActionViewFlagWireframeOver..." QT_MOC_LITERAL(15, 384, 32), // "OnActionToolInformationTriggered" QT_MOC_LITERAL(16, 417, 31), // "OnActionToolOperationsTriggered" QT_MOC_LITERAL(17, 449, 30), // "OnActionToolMaterialsTriggered" QT_MOC_LITERAL(18, 480, 24), // "OnActionToolLODTriggered" QT_MOC_LITERAL(19, 505, 30), // "OnActionToolCollisionTriggered" QT_MOC_LITERAL(20, 536, 37), // "OnActionToolLightManipulatorT..." QT_MOC_LITERAL(21, 574, 24), // "OnSwapChainWidgetResized" QT_MOC_LITERAL(22, 599, 22), // "OnSwapChainWidgetPaint" QT_MOC_LITERAL(23, 622, 30), // "OnSwapChainWidgetKeyboardEvent" QT_MOC_LITERAL(24, 653, 16), // "const QKeyEvent*" QT_MOC_LITERAL(25, 670, 14), // "pKeyboardEvent" QT_MOC_LITERAL(26, 685, 27), // "OnSwapChainWidgetMouseEvent" QT_MOC_LITERAL(27, 713, 18), // "const QMouseEvent*" QT_MOC_LITERAL(28, 732, 11), // "pMouseEvent" QT_MOC_LITERAL(29, 744, 27), // "OnSwapChainWidgetWheelEvent" QT_MOC_LITERAL(30, 772, 18), // "const QWheelEvent*" QT_MOC_LITERAL(31, 791, 11), // "pWheelEvent" QT_MOC_LITERAL(32, 803, 33), // "OnSwapChainWidgetGainedFocusE..." QT_MOC_LITERAL(33, 837, 25), // "OnFrameExecutionTriggered" QT_MOC_LITERAL(34, 863, 18), // "timeSinceLastFrame" QT_MOC_LITERAL(35, 882, 35), // "OnOperationsGenerateTangentsC..." QT_MOC_LITERAL(36, 918, 29), // "OnOperationsCenterMeshClicked" QT_MOC_LITERAL(37, 948, 39), // "OnOperationsRemoveUnusedVerti..." QT_MOC_LITERAL(38, 988, 40) // "OnOperationsRemoveUnusedTrian..." }, "EditorStaticMeshEditor\0OnActionOpenMeshClicked\0" "\0OnActionSaveMeshClicked\0" "OnActionSaveMeshAsClicked\0" "OnActionCloseClicked\0" "OnActionCameraPerspectiveTriggered\0" "checked\0OnActionCameraArcballTriggered\0" "OnActionCameraIsometricTriggered\0" "OnActionViewWireframeTriggered\0" "OnActionViewUnlitTriggered\0" "OnActionViewLitTriggered\0" "OnActionViewFlagShadowsTriggered\0" "OnActionViewFlagWireframeOverlayTriggered\0" "OnActionToolInformationTriggered\0" "OnActionToolOperationsTriggered\0" "OnActionToolMaterialsTriggered\0" "OnActionToolLODTriggered\0" "OnActionToolCollisionTriggered\0" "OnActionToolLightManipulatorTriggered\0" "OnSwapChainWidgetResized\0" "OnSwapChainWidgetPaint\0" "OnSwapChainWidgetKeyboardEvent\0" "const QKeyEvent*\0pKeyboardEvent\0" "OnSwapChainWidgetMouseEvent\0" "const QMouseEvent*\0pMouseEvent\0" "OnSwapChainWidgetWheelEvent\0" "const QWheelEvent*\0pWheelEvent\0" "OnSwapChainWidgetGainedFocusEvent\0" "OnFrameExecutionTriggered\0timeSinceLastFrame\0" "OnOperationsGenerateTangentsClicked\0" "OnOperationsCenterMeshClicked\0" "OnOperationsRemoveUnusedVerticesClicked\0" "OnOperationsRemoveUnusedTrianglesClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorStaticMeshEditor[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 29, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 159, 2, 0x08 /* Private */, 3, 0, 160, 2, 0x08 /* Private */, 4, 0, 161, 2, 0x08 /* Private */, 5, 0, 162, 2, 0x08 /* Private */, 6, 1, 163, 2, 0x08 /* Private */, 8, 1, 166, 2, 0x08 /* Private */, 9, 1, 169, 2, 0x08 /* Private */, 10, 1, 172, 2, 0x08 /* Private */, 11, 1, 175, 2, 0x08 /* Private */, 12, 1, 178, 2, 0x08 /* Private */, 13, 1, 181, 2, 0x08 /* Private */, 14, 1, 184, 2, 0x08 /* Private */, 15, 1, 187, 2, 0x08 /* Private */, 16, 1, 190, 2, 0x08 /* Private */, 17, 1, 193, 2, 0x08 /* Private */, 18, 1, 196, 2, 0x08 /* Private */, 19, 1, 199, 2, 0x08 /* Private */, 20, 1, 202, 2, 0x08 /* Private */, 21, 0, 205, 2, 0x08 /* Private */, 22, 0, 206, 2, 0x08 /* Private */, 23, 1, 207, 2, 0x08 /* Private */, 26, 1, 210, 2, 0x08 /* Private */, 29, 1, 213, 2, 0x08 /* Private */, 32, 0, 216, 2, 0x08 /* Private */, 33, 1, 217, 2, 0x08 /* Private */, 35, 0, 220, 2, 0x08 /* Private */, 36, 0, 221, 2, 0x08 /* Private */, 37, 0, 222, 2, 0x08 /* Private */, 38, 0, 223, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Bool, 7, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 24, 25, QMetaType::Void, 0x80000000 | 27, 28, QMetaType::Void, 0x80000000 | 30, 31, QMetaType::Void, QMetaType::Void, QMetaType::Float, 34, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void EditorStaticMeshEditor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorStaticMeshEditor *_t = static_cast<EditorStaticMeshEditor *>(_o); switch (_id) { case 0: _t->OnActionOpenMeshClicked(); break; case 1: _t->OnActionSaveMeshClicked(); break; case 2: _t->OnActionSaveMeshAsClicked(); break; case 3: _t->OnActionCloseClicked(); break; case 4: _t->OnActionCameraPerspectiveTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnActionCameraArcballTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnActionCameraIsometricTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnActionViewWireframeTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 8: _t->OnActionViewUnlitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->OnActionViewLitTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnActionViewFlagShadowsTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 11: _t->OnActionViewFlagWireframeOverlayTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->OnActionToolInformationTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 13: _t->OnActionToolOperationsTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 14: _t->OnActionToolMaterialsTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 15: _t->OnActionToolLODTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 16: _t->OnActionToolCollisionTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 17: _t->OnActionToolLightManipulatorTriggered((*reinterpret_cast< bool(*)>(_a[1]))); break; case 18: _t->OnSwapChainWidgetResized(); break; case 19: _t->OnSwapChainWidgetPaint(); break; case 20: _t->OnSwapChainWidgetKeyboardEvent((*reinterpret_cast< const QKeyEvent*(*)>(_a[1]))); break; case 21: _t->OnSwapChainWidgetMouseEvent((*reinterpret_cast< const QMouseEvent*(*)>(_a[1]))); break; case 22: _t->OnSwapChainWidgetWheelEvent((*reinterpret_cast< const QWheelEvent*(*)>(_a[1]))); break; case 23: _t->OnSwapChainWidgetGainedFocusEvent(); break; case 24: _t->OnFrameExecutionTriggered((*reinterpret_cast< float(*)>(_a[1]))); break; case 25: _t->OnOperationsGenerateTangentsClicked(); break; case 26: _t->OnOperationsCenterMeshClicked(); break; case 27: _t->OnOperationsRemoveUnusedVerticesClicked(); break; case 28: _t->OnOperationsRemoveUnusedTrianglesClicked(); break; default: ; } } } const QMetaObject EditorStaticMeshEditor::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_EditorStaticMeshEditor.data, qt_meta_data_EditorStaticMeshEditor, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorStaticMeshEditor::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorStaticMeshEditor::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorStaticMeshEditor.stringdata)) return static_cast<void*>(const_cast< EditorStaticMeshEditor*>(this)); return QMainWindow::qt_metacast(_clname); } int EditorStaticMeshEditor::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 29) qt_static_metacall(this, _c, _id, _a); _id -= 29; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 29) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 29; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/Core/Console.h #pragma once #include "Core/Common.h" #include "YBaseLib/String.h" #include "YBaseLib/Functor.h" #include "YBaseLib/PODArray.h" #include "YBaseLib/Singleton.h" #include "YBaseLib/CIStringHashTable.h" #include "YBaseLib/Mutex.h" // Console.h -> CVar.h ? enum CVAR_FLAG { CVAR_FLAG_REGISTERED = (1 << 0), CVAR_FLAG_WAS_UNREGISTERED = (1 << 1), CVAR_FLAG_READ_ONLY = (1 << 2), CVAR_FLAG_MODIFIED = (1 << 3), CVAR_FLAG_NO_ARCHIVE = (1 << 4), CVAR_FLAG_REQUIRE_APP_RESTART = (1 << 5), CVAR_FLAG_REQUIRE_RENDER_RESTART = (1 << 6), CVAR_FLAG_REQUIRE_MAP_RESTART = (1 << 7), CVAR_FLAG_PAUSE_RENDER_THREAD = (1 << 8), CVAR_FLAG_CHEAT = (1 << 9), }; class CVar { friend class Console; public: CVar(const char *Name, uint32 Flags, const char *DefaultValue = NULL, const char *Help = NULL, const char *Domain = NULL); ~CVar(); inline const String &GetName() const { return m_strName; } inline uint32 GetFlags() const { return m_iFlags; } inline const String &GetDefaultValue() const { return m_strDefaultValue; } inline const String &GetHelp() const { return m_strHelp; } inline const String &GetDomain() const { return m_strDomain; } inline const String &GetString() const { return m_strStrValue; } inline int32 GetInt() const { return m_iIntValue; } inline uint32 GetUInt() const { return (uint32)m_iIntValue; } inline float GetFloat() const { return m_fFloatValue; } inline bool GetBool() const { return m_bBoolValue; } inline bool IsChangePending() const { return m_bChangePending; } void AddChangeCallback(Functor *pCallback); void RemoveChangeCallback(Functor *pCallback); const String &GetPendingString() const; int32 GetPendingInt() const; uint32 GetPendingUInt() const; float GetPendingFloat() const; bool GetPendingBool() const; private: String m_strName; uint32 m_iFlags; String m_strDefaultValue; String m_strHelp; String m_strDomain; String m_strStrValue; int32 m_iIntValue; float m_fFloatValue; bool m_bBoolValue; bool m_bChangePending; String m_strPendingValue; PODArray<Functor *> m_callbacks; }; class Console : public Singleton<Console> { friend class CVar; public: typedef bool(*CommandHandlerMethod)(void *userData, uint32 argumentCount, const char *const argumentValues[]); public: Console(); ~Console(); //////////////////////////////////////////////////////////////////////////////////// // CVar Management //////////////////////////////////////////////////////////////////////////////////// CVar *GetCVar(const char *Name); bool SetCVar(CVar *pCVar, const char *Value, bool Force = false); bool SetCVar(CVar *pCVar, uint32 Value, bool Force = false); bool SetCVar(CVar *pCVar, int32 Value, bool Force = false); bool SetCVar(CVar *pCVar, float Value, bool Force = false); bool SetCVar(CVar *pCVar, bool Value, bool Force = false); bool ResetCVar(CVar *pCVar); // this function will create unregistered cvars if one is not present bool SetCVarByName(const char *Name, const char *Value, bool Force = false, bool CreateUnregistered = true); // Called when app is started void ApplyPendingAppCVars(); // Called when the renderer is restarted. void ApplyPendingRenderCVars(); // command line parser for any fs switches uint32 ParseCommandLine(uint32 argc, const char **argv); /////////////////////////////////////////////////////////////////////////////////// // Command Management /////////////////////////////////////////////////////////////////////////////////// bool RegisterCommand(const char *commandName, CommandHandlerMethod executeMethod, CommandHandlerMethod helpMethod, void *userData, const void *ownerPtr = nullptr); bool UnregisterCommand(const char *commandName); uint32 UnregisterCommandsWithOwner(const void *ownerPtr); // execute text bool ExecuteText(const char *text); // handle autocompletion bool HandleAutoCompletion(String &commandString); // handle help bool HandlePartialHelp(const char *text); private: // Console lock void AcquireMutex() { m_consoleLock.Lock(); } void ReleaseMutex() { m_consoleLock.Unlock(); } // CVar manangement void RegisterCVar(CVar *pCVar); void RemoveCVar(CVar *pCVar); void CreateUnregisteredCVar(const char *Name, const char *Value); bool ValidateCVar(CVar *pCVar, const char *NewValue); bool UpdateCVar(CVar *pCVar, const char *NewValue, bool Force); void WriteCVar(CVar *pCVar, const char *NewValue); // log the cvar information void DumpCVarHelp(const CVar *pCVar); void DumpCVarValue(const CVar *pCVar); // command handler for a cvar, expects the cvar pointer in userData static bool CVarViewEditCommandExecuteHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); static bool CVarViewEditCommandHelpHandler(void *userData, uint32 argumentCount, const char *const argumentValues[]); private: typedef CIStringHashTable<CVar *> CVarHashTable; CVarHashTable m_hmCVars; Mutex m_consoleLock; struct RegisteredCommand { String Name; CommandHandlerMethod ExecuteMethod; CommandHandlerMethod HelpMethod; void *pUserData; const void *pOwnerPtr; }; typedef CIStringHashTable<RegisteredCommand> CommandTable; CommandTable m_commands; bool m_appStarted; bool m_rendererStarted; bool m_hasPendingRenderCVars; }; extern Console *g_pConsole; <file_sep>/Engine/Source/Renderer/RenderProxies/SkeletalMeshRenderProxy.h #pragma once #include "Renderer/RenderProxy.h" #include "Engine/SkeletalMesh.h" class SkeletalMeshRenderProxy : public RenderProxy { public: SkeletalMeshRenderProxy(uint32 entityID, const SkeletalMesh *pSkeletalMesh, const Transform &transform, uint32 shadowFlags); ~SkeletalMeshRenderProxy(); const SkeletalMesh *GetSkeletalMesh() const { return m_pSkeletalMesh; } void SetSkeletalMesh(const SkeletalMesh *pSkeletalMesh); void SetMaterial(uint32 i, const Material *pMaterialOverride); void SetTransform(const Transform &transform); void SetTintColor(bool enabled, uint32 color = 0); void SetShadowFlags(uint32 shadowFlags); void SetVisibility(bool visible); // animation void SetBoneTransforms(uint32 firstTransform, uint32 transformCount, const float3x4 *pTransforms); void SetBoneTransforms(uint32 firstTransform, uint32 transformCount, const Transform *pTransforms); void ResetToBaseFrameTransform(); // render proxy stuff virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual void DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const override; virtual bool CreateDeviceResources() const override; virtual void ReleaseDeviceResources() const override; private: // real methods void RealSetSkeletalMesh(const SkeletalMesh *pSkeletalMesh); void RealSetMaterial(uint32 i, const Material *pMaterialOverride); void RealSetTransform(const Transform &transform); void RealSetTintColor(bool enabled, uint32 color = 0); void RealSetShadowFlags(uint32 shadowFlags); void RealSetVisibility(bool visible); // initialize the bone transform array void InitializeBoneTransformArray(); // cpu skinning void TransformVerticesOnCPU(); bool m_visibility; const SkeletalMesh *m_pSkeletalMesh; PODArray<const Material *> m_materials; Transform m_transform; float4x4 m_localToWorldMatrix; uint32 m_shadowFlags; bool m_tintEnabled; uint32 m_tintColor; // gpu resources, also owned by render thread. mutable bool m_bGPUResourcesCreated; mutable VertexBufferBindingArray m_VertexBuffers; MemArray<float3x4> m_boneTransforms; // cpu skinning mutable MemArray<SkeletalMeshVertexFactory::Vertex> m_cpuSkinnedVertices; mutable GPUBuffer *m_pCPUSkinningVertexBuffer; mutable bool m_useGPUSkinning; }; <file_sep>/Editor/Source/Editor/EditorVisualComponent.h #pragma once #include "Editor/Common.h" class XMLReader; class RenderProxy; class RenderWorld; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Texture2D; class StaticMesh; class BlockMesh; class DirectionalLightRenderProxy; class PointLightRenderProxy; class AmbientLightRenderProxy; class SpriteRenderProxy; class StaticMeshRenderProxy; class BlockMeshRenderProxy; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentInstance; class EditorVisualComponentDefinition { public: EditorVisualComponentDefinition(); virtual ~EditorVisualComponentDefinition(); virtual EditorVisualComponentDefinition *Clone() const = 0; virtual bool ParseXML(XMLReader &xmlReader) = 0; virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const = 0; }; class EditorVisualComponentInstance { public: EditorVisualComponentInstance(uint32 pickingID); virtual ~EditorVisualComponentInstance(); const uint32 GetPickingID() const { return m_pickingID; } const AABox &GetVisualBounds() const { return m_visualBounds; } virtual void OnAddedToRenderWorld(RenderWorld *pRenderWorld) = 0; virtual void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) = 0; virtual void OnPropertyChange(const char *propertyName, const char *propertyValue) = 0; virtual void OnSelectionStateChange(bool selected) = 0; protected: uint32 m_pickingID; AABox m_visualBounds; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentDefinition_DirectionalLight : public EditorVisualComponentDefinition { public: EditorVisualComponentDefinition_DirectionalLight(); virtual ~EditorVisualComponentDefinition_DirectionalLight(); const bool GetEnabled() const { return m_bEnabled; } const String &GetEnabledFromPropertyName() const { return m_strEnabledFromPropertyName; } const Quaternion &GetRotation() const { return m_Rotation; } const String &GetRotationFromPropertyName() const { return m_strRotationFromPropertyName; } const Quaternion &GetRotationOffset() const { return m_RotationOffset; } const float3 &GetColor() const { return m_Color; } const String &GetColorFromPropertyName() const { return m_strColorFromPropertyName; } const float GetBrightness() const { return m_Brightness; } const String &GetBrightnessFromPropertyName() const { return m_strBrightnessFromPropertyName; } const uint32 GetShadowFlags() const { return m_iShadowFlags; } const String &GetShadowFlagsFromPropertyName() const { return m_strShadowFlagsFromPropertyName; } const float GetAmbientFactor() const { return m_fAmbientFactor; } const String &GetAmbientFactorFromPropertyName() const { return m_strAmbientFactorFromPropertyName; } const bool GetOnlyShowWhenSelected() const { return m_bOnlyShowWhenSelected; } virtual EditorVisualComponentDefinition *Clone() const; virtual bool ParseXML(XMLReader &xmlReader); virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const; private: bool m_bEnabled; String m_strEnabledFromPropertyName; Quaternion m_Rotation; String m_strRotationFromPropertyName; Quaternion m_RotationOffset; float3 m_Color; String m_strColorFromPropertyName; float m_Brightness; String m_strBrightnessFromPropertyName; uint32 m_iShadowFlags; String m_strShadowFlagsFromPropertyName; float m_fAmbientFactor; String m_strAmbientFactorFromPropertyName; // tint colour bool m_bOnlyShowWhenSelected; }; class EditorVisualComponentInstance_DirectionalLight : public EditorVisualComponentInstance { public: EditorVisualComponentInstance_DirectionalLight(uint32 pickingID, const EditorVisualComponentDefinition_DirectionalLight *pDefinition); virtual ~EditorVisualComponentInstance_DirectionalLight(); void OnAddedToRenderWorld(RenderWorld *pRenderWorld) override; void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) override; void OnPropertyChange(const char *propertyName, const char *propertyValue) override; void OnSelectionStateChange(bool selected) override; private: // recalculate light colours void UpdateLightColor(); float3 CalculateDirection(); // definition const EditorVisualComponentDefinition_DirectionalLight *m_pDefinition; // cached property values bool m_Enabled; Quaternion m_Rotation; float3 m_Color; float m_Brightness; uint32 m_ShadowFlags; float m_AmbientFactor; // render proxy DirectionalLightRenderProxy *m_pDirectionalLightRenderProxy; AmbientLightRenderProxy *m_pAmbientLightRenderProxy; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentDefinition_PointLight : public EditorVisualComponentDefinition { public: EditorVisualComponentDefinition_PointLight(); virtual ~EditorVisualComponentDefinition_PointLight(); const bool GetEnabled() const { return m_bEnabled; } const String &GetEnabledFromPropertyName() const { return m_strEnabledFromPropertyName; } const float3 &GetPosition() const { return m_Position; } const String &GetPositionFromPropertyName() const { return m_strPositionFromPropertyName; } const float3 &GetPositionOffset() const { return m_PositionOffset; } const float GetRange() const { return m_Range; } const String &GetRangeFromPropertyName() const { return m_strRangeFromPropertyName; } const float3 &GetColor() const { return m_Color; } const String &GetColorFromPropertyName() const { return m_strColorFromPropertyName; } const float GetBrightness() const { return m_Brightness; } const String &GetBrightnessFromPropertyName() const { return m_strBrightnessFromPropertyName; } const float GetFalloffExponent() const { return m_FalloffExponent; } const String &GetFalloffExponentFromPropertyName() const { return m_strFalloffExponentFromPropertyName; } const uint32 GetShadowFlags() const { return m_iShadowFlags; } const String &GetShadowFlagsFromPropertyName() const { return m_strShadowFlagsFromPropertyName; } const bool GetOnlyShowWhenSelected() const { return m_bOnlyShowWhenSelected; } virtual EditorVisualComponentDefinition *Clone() const; virtual bool ParseXML(XMLReader &xmlReader); virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const; private: bool m_bEnabled; String m_strEnabledFromPropertyName; float3 m_Position; String m_strPositionFromPropertyName; float3 m_PositionOffset; float m_Range; String m_strRangeFromPropertyName; float3 m_Color; String m_strColorFromPropertyName; float m_Brightness; String m_strBrightnessFromPropertyName; float m_FalloffExponent; String m_strFalloffExponentFromPropertyName; uint32 m_iShadowFlags; String m_strShadowFlagsFromPropertyName; // tint colour bool m_bOnlyShowWhenSelected; }; class EditorVisualComponentInstance_PointLight : public EditorVisualComponentInstance { public: EditorVisualComponentInstance_PointLight(uint32 pickingID, const EditorVisualComponentDefinition_PointLight *pDefinition); virtual ~EditorVisualComponentInstance_PointLight(); void OnAddedToRenderWorld(RenderWorld *pRenderWorld) override; void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) override; void OnPropertyChange(const char *propertyName, const char *propertyValue) override; void OnSelectionStateChange(bool selected) override; private: // recalculates the transform for an instanced visual void UpdateBounds(); // definition const EditorVisualComponentDefinition_PointLight *m_pDefinition; // cached property values bool m_Enabled; float3 m_Position; float m_Range; float3 m_Color; float m_Brightness; float m_FalloffExponent; uint32 m_ShadowFlags; float3 m_EntityPosition; // render proxy PointLightRenderProxy *m_pRenderProxy; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentDefinition_Sprite : public EditorVisualComponentDefinition { public: EditorVisualComponentDefinition_Sprite(); virtual ~EditorVisualComponentDefinition_Sprite(); const float3 &GetPosition() const { return m_Position; } const String &GetPositionFromPropertyName() const { return m_strPositionFromPropertyName; } const float3 &GetPositionOffset() const { return m_PositionOffset; } const float3 &GetScale() const { return m_Scale; } const String &GetScaleFromPropertyName() const { return m_strScaleFromPropertyName; } const float3 &GetScaleOffset() const { return m_ScaleOffset; } const uint32 GetShadowFlags() const { return m_iShadowFlags; } const String &GetShadowFlagsFromPropertyName() const { return m_strShadowFlagsFromPropertyName; } const bool GetVisible() const { return m_bVisible; } const String &GetVisibleFromPropertyName() const { return m_strVisibleFromPropertyName; } const String &GetTextureName() const { return m_strTextureName; } const String &GetTextureFromPropertyName() const { return m_strTextureFromPropertyName; } const MATERIAL_BLENDING_MODE GetBlendingMode() const { return m_eBlendingMode; } const String &GetBlendingModeFromPropertyName() const { return m_strBlendingModeFromPropertyName; } const float &GetWidth() const { return m_fWidth; } const String &GetWidthFromPropertyName() const { return m_strWidthFromPropertyName; } const float &GetHeight() const { return m_fHeight; } const String &GetHeightFromPropertyName() const { return m_strHeightFromPropertyName; } const uint32 GetTintColor() const { return m_TintColor; } const uint32 GetSelectedTintColor() const { return m_SelectedTintColor; } const bool GetOnlyShowWhenSelected() const { return m_bOnlyShowWhenSelected; } virtual EditorVisualComponentDefinition *Clone() const; virtual bool ParseXML(XMLReader &xmlReader); virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const; private: float3 m_Position; String m_strPositionFromPropertyName; float3 m_PositionOffset; float3 m_Scale; String m_strScaleFromPropertyName; float3 m_ScaleOffset; uint32 m_iShadowFlags; String m_strShadowFlagsFromPropertyName; bool m_bVisible; String m_strVisibleFromPropertyName; // texture String m_strTextureName; String m_strTextureFromPropertyName; // blending MATERIAL_BLENDING_MODE m_eBlendingMode; String m_strBlendingModeFromPropertyName; // width float m_fWidth; String m_strWidthFromPropertyName; // height float m_fHeight; String m_strHeightFromPropertyName; // tint colour uint32 m_TintColor; uint32 m_SelectedTintColor; bool m_bOnlyShowWhenSelected; }; class EditorVisualComponentInstance_Sprite : public EditorVisualComponentInstance { public: EditorVisualComponentInstance_Sprite(uint32 pickingID, const EditorVisualComponentDefinition_Sprite *pDefinition); virtual ~EditorVisualComponentInstance_Sprite(); void OnAddedToRenderWorld(RenderWorld *pRenderWorld) override; void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) override; void OnPropertyChange(const char *propertyName, const char *propertyValue) override; void OnSelectionStateChange(bool selected) override; private: // recalculates the transform for an instanced visual void UpdateBounds(); // definition const EditorVisualComponentDefinition_Sprite *m_pDefinition; // cached property values const Texture2D *m_pTexture; MATERIAL_BLENDING_MODE m_eBlendingMode; float3 m_Position; float3 m_Scale; bool m_Visible; uint32 m_ShadowFlags; float m_fWidth, m_fHeight; // render proxy SpriteRenderProxy *m_pRenderProxy; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentDefinition_StaticMesh : public EditorVisualComponentDefinition { public: EditorVisualComponentDefinition_StaticMesh(); virtual ~EditorVisualComponentDefinition_StaticMesh(); const float3 &GetPosition() const { return m_Position; } const String &GetPositionFromPropertyName() const { return m_strPositionFromPropertyName; } const float3 &GetPositionOffset() const { return m_PositionOffset; } const Quaternion &GetRotation() const { return m_Rotation; } const String &GetRotationFromPropertyName() const { return m_strRotationFromPropertyName; } const Quaternion &GetRotationOffset() const { return m_RotationOffset; } const float3 &GetScale() const { return m_Scale; } const String &GetScaleFromPropertyName() const { return m_strScaleFromPropertyName; } const float3 &GetScaleOffset() const { return m_ScaleOffset; } const uint32 GetShadowFlags() const { return m_iShadowFlags; } const String &GetShadowFlagsFromPropertyName() const { return m_strShadowFlagsFromPropertyName; } const bool GetVisible() const { return m_bVisible; } const String &GetVisibleFromPropertyName() const { return m_strVisibleFromPropertyName; } const String &GetMeshName() const { return m_strMeshName; } const String &GetMeshFromPropertyName() const { return m_strMeshFromPropertyName; } const uint32 GetTintColor() const { return m_TintColor; } const uint32 GetSelectedTintColor() const { return m_SelectedTintColor; } const bool GetOnlyShowWhenSelected() const { return m_bOnlyShowWhenSelected; } virtual EditorVisualComponentDefinition *Clone() const; virtual bool ParseXML(XMLReader &xmlReader); virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const; private: float3 m_Position; String m_strPositionFromPropertyName; float3 m_PositionOffset; Quaternion m_Rotation; String m_strRotationFromPropertyName; Quaternion m_RotationOffset; float3 m_Scale; String m_strScaleFromPropertyName; float3 m_ScaleOffset; uint32 m_iShadowFlags; String m_strShadowFlagsFromPropertyName; bool m_bVisible; String m_strVisibleFromPropertyName; // mesh String m_strMeshName; String m_strMeshFromPropertyName; // tint colour uint32 m_TintColor; uint32 m_SelectedTintColor; bool m_bOnlyShowWhenSelected; }; class EditorVisualComponentInstance_StaticMesh : public EditorVisualComponentInstance { public: EditorVisualComponentInstance_StaticMesh(uint32 pickingID, const EditorVisualComponentDefinition_StaticMesh *pDefinition); virtual ~EditorVisualComponentInstance_StaticMesh(); void OnAddedToRenderWorld(RenderWorld *pRenderWorld) override; void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) override; void OnPropertyChange(const char *propertyName, const char *propertyValue) override; void OnSelectionStateChange(bool selected) override; private: // recalculates the transform for an instanced visual void UpdateTransform(); void UpdateBounds(); // definition const EditorVisualComponentDefinition_StaticMesh *m_pDefinition; // cached property values const StaticMesh *m_pStaticMesh; float3 m_Position; Quaternion m_Rotation; float3 m_Scale; bool m_Visible; uint32 m_ShadowFlags; // cached transform Transform m_CachedTransform; // render proxy instance StaticMeshRenderProxy *m_pRenderProxy; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class EditorVisualComponentDefinition_BlockMesh : public EditorVisualComponentDefinition { public: EditorVisualComponentDefinition_BlockMesh(); virtual ~EditorVisualComponentDefinition_BlockMesh(); const float3 &GetPosition() const { return m_Position; } const String &GetPositionFromPropertyName() const { return m_strPositionFromPropertyName; } const float3 &GetPositionOffset() const { return m_PositionOffset; } const Quaternion &GetRotation() const { return m_Rotation; } const String &GetRotationFromPropertyName() const { return m_strRotationFromPropertyName; } const Quaternion &GetRotationOffset() const { return m_RotationOffset; } const float3 &GetScale() const { return m_Scale; } const String &GetScaleFromPropertyName() const { return m_strScaleFromPropertyName; } const float3 &GetScaleOffset() const { return m_ScaleOffset; } const uint32 GetShadowFlags() const { return m_iShadowFlags; } const String &GetShadowFlagsFromPropertyName() const { return m_strShadowFlagsFromPropertyName; } const bool GetVisible() const { return m_bVisible; } const String &GetVisibleFromPropertyName() const { return m_strVisibleFromPropertyName; } const String &GetMeshName() const { return m_strMeshName; } const String &GetMeshFromPropertyName() const { return m_strMeshFromPropertyName; } const uint32 GetTintColor() const { return m_TintColor; } const uint32 GetSelectedTintColor() const { return m_SelectedTintColor; } const bool GetOnlyShowWhenSelected() const { return m_bOnlyShowWhenSelected; } virtual EditorVisualComponentDefinition *Clone() const; virtual bool ParseXML(XMLReader &xmlReader); virtual EditorVisualComponentInstance *CreateVisual(uint32 pickingID) const; private: float3 m_Position; String m_strPositionFromPropertyName; float3 m_PositionOffset; Quaternion m_Rotation; String m_strRotationFromPropertyName; Quaternion m_RotationOffset; float3 m_Scale; String m_strScaleFromPropertyName; float3 m_ScaleOffset; uint32 m_iShadowFlags; String m_strShadowFlagsFromPropertyName; bool m_bVisible; String m_strVisibleFromPropertyName; // mesh String m_strMeshName; String m_strMeshFromPropertyName; // tint colour uint32 m_TintColor; uint32 m_SelectedTintColor; bool m_bOnlyShowWhenSelected; }; class EditorVisualComponentInstance_BlockMesh : public EditorVisualComponentInstance { public: EditorVisualComponentInstance_BlockMesh(uint32 pickingID, const EditorVisualComponentDefinition_BlockMesh *pDefinition); virtual ~EditorVisualComponentInstance_BlockMesh(); void OnAddedToRenderWorld(RenderWorld *pRenderWorld) override; void OnRemovedFromRenderWorld(RenderWorld *pRenderWorld) override; void OnPropertyChange(const char *propertyName, const char *propertyValue) override; void OnSelectionStateChange(bool selected) override; private: // recalculates the transform for an instanced visual void UpdateTransform(); void UpdateBounds(); // definition const EditorVisualComponentDefinition_BlockMesh *m_pDefinition; // cached property values const BlockMesh *m_pBlockMesh; float3 m_Position; Quaternion m_Rotation; float3 m_Scale; bool m_Visible; uint32 m_ShadowFlags; // cached transform Transform m_CachedTransform; // render proxy instance BlockMeshRenderProxy *m_pRenderProxy; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <file_sep>/Editor/Source/Editor/MapEditor/EditorEntityEditMode.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/MapEditor/EditorEntityEditMode.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "Editor/MapEditor/ui_EditorMapWindow.h" #include "Editor/EditorVisual.h" #include "Editor/EditorPropertyEditorDialog.h" #include "Editor/EditorHelpers.h" #include "Editor/ToolMenuWidget.h" #include "Engine/Entity.h" #include "Engine/ResourceManager.h" #include "Engine/StaticMesh.h" #include "Renderer/Renderer.h" #include "Renderer/VertexFactories/PlainVertexFactory.h" #include "MathLib/CollisionDetection.h" #include "ResourceCompiler/ObjectTemplate.h" #include "MapCompiler/MapSource.h" Log_SetChannel(EditorEntityEditMode); const uint32 EDITOR_ENTITY_ID_WIDGET_AXIS_X = 0xFFFFFFFC; const uint32 EDITOR_ENTITY_ID_WIDGET_AXIS_Y = 0xFFFFFFFD; const uint32 EDITOR_ENTITY_ID_WIDGET_AXIS_Z = 0xFFFFFFFE; const uint32 EDITOR_ENTITY_ID_WIDGET_AXIS_ANY = 0xFFFFFFFF; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ui_EditorEntityEditMode { QWidget *root; QAction *actionWidgetSelect; QAction *actionWidgetMove; QAction *actionWidgetRotate; QAction *actionWidgetScale; QAction *actionCreateEntity; QAction *actionDeleteEntity; QAction *actionFilterSelection; QAction *actionDeselectAll; QAction *actionSelectionLayers; QAction *actionSnapSelectionToGrid; QLabel *selectionTitleText; QListWidget *selectionComponents; QAction *actionAddComponent; QAction *actionRemoveComponent; QAction *actionPushLeft; QAction *actionPushRight; QAction *actionPushForward; QAction *actionPushBack; QAction *actionPushUp; QAction *actionPushDown; QGroupBox *pushContainer; QComboBox *pushShape; QDoubleSpinBox *pushMaxDistance; void CreateUI(QWidget *parentWidget) { QVBoxLayout *rootLayout; root = new QWidget(parentWidget); rootLayout = new QVBoxLayout(root); rootLayout->setSizeConstraint(QLayout::SetMaximumSize); rootLayout->setSpacing(2); rootLayout->setMargin(0); // create all actions first { actionWidgetSelect = new QAction(root); actionWidgetSelect->setText(root->tr("Select Entities")); actionWidgetSelect->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); actionWidgetSelect->setCheckable(true); actionWidgetMove = new QAction(root); actionWidgetMove->setText(root->tr("Move Entities")); actionWidgetMove->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Move.png"))); actionWidgetMove->setCheckable(true); actionWidgetRotate = new QAction(root); actionWidgetRotate->setText(root->tr("Rotate Entities")); actionWidgetRotate->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Rotate.png"))); actionWidgetRotate->setCheckable(true); actionWidgetScale = new QAction(root); actionWidgetScale->setText(root->tr("Scale Entities")); actionWidgetScale->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Scale.png"))); actionWidgetScale->setCheckable(true); actionCreateEntity = new QAction(root); actionCreateEntity->setText(root->tr("Create Entity")); actionCreateEntity->setIcon(QIcon(QStringLiteral(":/editor/icons/NewDocumentHS.png"))); actionDeleteEntity = new QAction(root); actionDeleteEntity->setText(root->tr("Delete Entities")); actionDeleteEntity->setIcon(QIcon(QStringLiteral(":/editor/icons/DeleteHS.png"))); actionFilterSelection = new QAction(root); actionFilterSelection->setText(root->tr("Filter Selection")); actionFilterSelection->setIcon(QIcon(QStringLiteral(":/editor/icons/FullScreenHH.png"))); actionDeselectAll = new QAction(root); actionDeselectAll->setText(root->tr("Deselect All")); actionDeselectAll->setIcon(QIcon(QStringLiteral(":/editor/icons/FullScreenHH.png"))); actionSnapSelectionToGrid = new QAction(root->tr("Snap To Grid"), root); actionSnapSelectionToGrid->setIcon(QIcon(QStringLiteral(":/editor/icons/FullScreenHH.png"))); actionSelectionLayers = new QAction(root->tr("Entity Layers"), root); actionSelectionLayers->setIcon(QIcon(QStringLiteral(":/editor/icons/NewDirectory_16x16.png"))); actionAddComponent = new QAction(root->tr("Add Component"), root); actionAddComponent->setIcon(QIcon(QStringLiteral(":/editor/icons/NewDocumentHS.png"))); actionRemoveComponent = new QAction(root->tr("Remove Component"), root); actionRemoveComponent->setIcon(QIcon(QStringLiteral(":/editor/icons/DeleteHS.png"))); actionPushLeft = new QAction(root); actionPushLeft->setText(root->tr("Push Left")); actionPushLeft->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsLeftHS.png"))); actionPushRight = new QAction(root); actionPushRight->setText(root->tr("Push Right")); actionPushRight->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsRightHS.png"))); actionPushForward = new QAction(root); actionPushForward->setText(root->tr("Push Forward")); actionPushForward->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsCenteredVerticalHS.png"))); actionPushBack = new QAction(root); actionPushBack->setText(root->tr("Push Back")); actionPushBack->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsTopHS.png"))); actionPushUp = new QAction(root); actionPushUp->setText(root->tr("Push Up")); actionPushUp->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsCenteredHorizontalHS.png"))); actionPushDown = new QAction(root); actionPushDown->setText(root->tr("Push Down")); actionPushDown->setIcon(QIcon(QStringLiteral(":/editor/icons/AlignObjectsBottomHS.png"))); } // fixed, ie always present buttons { ToolMenuWidget *fixedToolMenu = new ToolMenuWidget(root); fixedToolMenu->setBackgroundRole(QPalette::Background); fixedToolMenu->addAction(actionWidgetSelect); fixedToolMenu->addAction(actionWidgetMove); fixedToolMenu->addAction(actionWidgetRotate); fixedToolMenu->addAction(actionWidgetScale); fixedToolMenu->addAction(actionSnapSelectionToGrid); fixedToolMenu->addAction(actionCreateEntity); fixedToolMenu->addAction(actionDeleteEntity); fixedToolMenu->addAction(actionFilterSelection); fixedToolMenu->addAction(actionDeselectAll); rootLayout->addWidget(fixedToolMenu); } // operation-specific commands { QScrollArea *scrollArea = new QScrollArea(root); QWidget *scrollAreaWidget = new QWidget(scrollArea); scrollArea->setBackgroundRole(QPalette::Background); scrollArea->setFrameStyle(0); scrollArea->setWidgetResizable(true); scrollArea->setWidget(scrollAreaWidget); QVBoxLayout *scrollAreaLayout = new QVBoxLayout(scrollArea); scrollAreaLayout->setMargin(0); scrollAreaLayout->setSpacing(2); scrollAreaLayout->setContentsMargins(0, 0, 0, 0); // common entity menu { QGroupBox *commonGroupBox = new QGroupBox(root->tr("Selection Info"), scrollAreaWidget); commonGroupBox->setMinimumSize(1, 200); commonGroupBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout *commonLayout = new QVBoxLayout(commonGroupBox); commonLayout->setContentsMargins(0, 0, 0, 0); commonLayout->setMargin(0); // title { QHBoxLayout *titleLayout = new QHBoxLayout(commonGroupBox); titleLayout->setContentsMargins(4, 4, 4, 4); titleLayout->setAlignment(Qt::AlignTop); QLabel *titleIcon = new QLabel(commonGroupBox); titleIcon->setPixmap(QPixmap(QStringLiteral(":/editor/icons/EditCodeHS.png"))); titleIcon->setFixedSize(32, 32); titleIcon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); titleLayout->addWidget(titleIcon); selectionTitleText = new QLabel(commonGroupBox); selectionTitleText->setTextFormat(Qt::RichText); selectionTitleText->setText("<strong>hi</strong><br>Fooooo"); titleLayout->addWidget(selectionTitleText); commonLayout->addLayout(titleLayout); } // components { QLabel *selectionComponentsLabel = new QLabel(root->tr("Components:"), commonGroupBox); commonLayout->addWidget(selectionComponentsLabel); selectionComponents = new QListWidget(commonGroupBox); commonLayout->addWidget(selectionComponents, 1); } // tool menu { ToolMenuWidget *layerToolMenu = new ToolMenuWidget(root); layerToolMenu->addAction(actionAddComponent); layerToolMenu->addAction(actionRemoveComponent); layerToolMenu->addAction(actionSelectionLayers); commonLayout->addWidget(layerToolMenu); } commonGroupBox->setLayout(commonLayout); scrollAreaLayout->addWidget(commonGroupBox); } // push menu { pushContainer = new QGroupBox(root->tr("Push Object"), root); QVBoxLayout *pushContainerLayout = new QVBoxLayout(pushContainer); pushContainerLayout->setMargin(0); pushContainerLayout->setSpacing(0); pushContainerLayout->setContentsMargins(4, 4, 4, 4); // push shape/distance { QFormLayout *formLayout = new QFormLayout(pushContainer); formLayout->setMargin(0); formLayout->setSpacing(0); formLayout->setContentsMargins(0, 0, 0, 0); pushShape = new QComboBox(pushContainer); pushShape->setEditable(false); pushShape->addItem(root->tr("Axis-Aligned Box")); pushShape->addItem(root->tr("Sphere")); formLayout->addRow(root->tr("Shape"), pushShape); pushMaxDistance = new QDoubleSpinBox(pushContainer); pushMaxDistance->setMinimum(0.5); pushMaxDistance->setMaximum(1000.0); pushMaxDistance->setValue(100.0); formLayout->addRow(root->tr("Distance"), pushMaxDistance); pushContainerLayout->addLayout(formLayout); } QHBoxLayout *toolMenuLayout = new QHBoxLayout(pushContainer); toolMenuLayout->setMargin(0); toolMenuLayout->setSpacing(0); toolMenuLayout->setContentsMargins(0, 0, 0, 0); ToolMenuWidget *leftToolMenu = new ToolMenuWidget(pushContainer); ToolMenuWidget *rightToolMenu = new ToolMenuWidget(pushContainer); leftToolMenu->addAction(actionPushLeft); rightToolMenu->addAction(actionPushRight); leftToolMenu->addAction(actionPushForward); rightToolMenu->addAction(actionPushBack); leftToolMenu->addAction(actionPushUp); rightToolMenu->addAction(actionPushDown); toolMenuLayout->addWidget(leftToolMenu); toolMenuLayout->addWidget(rightToolMenu); pushContainerLayout->addLayout(toolMenuLayout); pushContainer->setLayout(pushContainerLayout); scrollAreaLayout->addWidget(pushContainer); pushContainer->hide(); } // use remaining space scrollAreaLayout->addStretch(1); // finalize scroll area scrollAreaWidget->setLayout(scrollAreaLayout); rootLayout->addWidget(scrollArea, 1); } root->setLayout(rootLayout); } void OnEntityEditWidgetChanged(EDITOR_ENTITY_EDIT_MODE_WIDGET currentWidget) { actionWidgetSelect->setChecked((currentWidget == EDITOR_ENTITY_EDIT_MODE_WIDGET_SELECT)); actionWidgetMove->setChecked((currentWidget == EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE)); actionWidgetRotate->setChecked((currentWidget == EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE)); actionWidgetScale->setChecked((currentWidget == EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE)); // only show push box on move (currentWidget == EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE) ? pushContainer->show() : pushContainer->hide(); } }; QWidget *EditorEntityEditMode::CreateUI(QWidget *pParentWidget) { DebugAssert(m_ui == nullptr); m_ui = new ui_EditorEntityEditMode(); m_ui->CreateUI(pParentWidget); // bind events connect(m_ui->actionWidgetSelect, SIGNAL(triggered(bool)), this, SLOT(OnUIWidgetSelectClicked(bool))); connect(m_ui->actionWidgetMove, SIGNAL(triggered(bool)), this, SLOT(OnUIWidgetMoveClicked(bool))); connect(m_ui->actionWidgetRotate, SIGNAL(triggered(bool)), this, SLOT(OnUIWidgetRotateClicked(bool))); connect(m_ui->actionWidgetScale, SIGNAL(triggered(bool)), this, SLOT(OnUIWidgetScaleClicked(bool))); connect(m_ui->actionCreateEntity, SIGNAL(triggered()), this, SLOT(OnUIActionCreateEntityTriggered())); connect(m_ui->actionDeleteEntity, SIGNAL(triggered()), this, SLOT(OnUIActionDeleteEntityTriggered())); connect(m_ui->actionFilterSelection, SIGNAL(triggered()), this, SLOT(OnUIOptionsFilterSelectionClicked())); connect(m_ui->actionSelectionLayers, SIGNAL(triggered()), this, SLOT(OnUIActionEntityLayersTriggered())); connect(m_ui->actionDeselectAll, SIGNAL(triggered()), this, SLOT(OnUIActionDeselectAllTriggered())); connect(m_ui->actionPushLeft, SIGNAL(triggered()), this, SLOT(OnUIPushLeftClicked())); connect(m_ui->actionPushRight, SIGNAL(triggered()), this, SLOT(OnUIPushRightClicked())); connect(m_ui->actionPushForward, SIGNAL(triggered()), this, SLOT(OnUIPushForwardClicked())); connect(m_ui->actionPushBack, SIGNAL(triggered()), this, SLOT(OnUIPushBackClicked())); connect(m_ui->actionPushUp, SIGNAL(triggered()), this, SLOT(OnUIPushUpClicked())); connect(m_ui->actionPushDown, SIGNAL(triggered()), this, SLOT(OnUIPushDownClicked())); connect(m_ui->actionSnapSelectionToGrid, SIGNAL(triggered()), this, SLOT(OnUIActionSnapSelectionToGridTriggered())); connect(m_ui->actionAddComponent, SIGNAL(triggered()), this, SLOT(OnUIActionCreateComponentTriggered())); connect(m_ui->actionRemoveComponent, SIGNAL(triggered()), this, SLOT(OnUIActionRemoveComponentTriggered())); connect(m_ui->actionSelectionLayers, SIGNAL(triggered()), this, SLOT(OnUIActionSelectionLayersTriggered())); connect(m_ui->selectionComponents, SIGNAL(currentRowChanged(int)), this, SLOT(OnUISelectionComponentListCurrentRowChanged(int))); // update state m_ui->OnEntityEditWidgetChanged(m_activeWidget); return m_ui->root; } void EditorEntityEditMode::OnUIOptionsFilterSelectionClicked() { } void EditorEntityEditMode::OnUIWidgetSelectClicked(bool checked) { SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET_SELECT); } void EditorEntityEditMode::OnUIWidgetMoveClicked(bool checked) { SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE); } void EditorEntityEditMode::OnUIWidgetRotateClicked(bool checked) { SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE); } void EditorEntityEditMode::OnUIWidgetScaleClicked(bool checked) { SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE); } void EditorEntityEditMode::OnUIPushLeftClicked() { PushSelection(float3::NegativeUnitX, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIPushRightClicked() { PushSelection(float3::UnitX, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIPushForwardClicked() { PushSelection(float3::UnitY, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIPushBackClicked() { PushSelection(float3::NegativeUnitY, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIPushUpClicked() { PushSelection(float3::UnitZ, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIPushDownClicked() { PushSelection(float3::NegativeUnitZ, (float)m_ui->pushMaxDistance->value()); } void EditorEntityEditMode::OnUIActionCreateEntityTriggered() { QMenu entityTypeMenu; EditorHelpers::CreateEntityTypeMenu(&entityTypeMenu, true); QAction *pChoice = entityTypeMenu.exec(QCursor::pos()); if (pChoice != nullptr) { // get type name QString typeName(pChoice->data().toString()); // create this entity type EditorMapViewport *pViewport = m_pMap->GetMapWindow()->GetActiveViewport(); if (pViewport != nullptr) CreateEntityUsingViewport(pViewport, ConvertQStringToString(typeName)); else m_pMap->CreateEntity(ConvertQStringToString(typeName)); } } void EditorEntityEditMode::OnUIActionDeleteEntityTriggered() { DeleteSelection(); } void EditorEntityEditMode::OnUIActionEntityLayersTriggered() { } void EditorEntityEditMode::OnUIActionSnapSelectionToGridTriggered() { SnapSelectionToGrid(); } void EditorEntityEditMode::OnUIActionCreateComponentTriggered() { // should only have a single selection if (m_selectedEntities.GetSize() != 1) return; // components can only be added to entities, not static objects EditorMapEntity *pSelectedEntity = m_selectedEntities[0]; if (!pSelectedEntity->IsEntity()) return; QMenu componentTypeMenu; EditorHelpers::CreateComponentTypeMenu(&componentTypeMenu, true); QAction *pChoice = componentTypeMenu.exec(QCursor::pos()); if (pChoice != nullptr) { // get type name QString typeName(pChoice->data().toString()); // add it int32 componentIndex = pSelectedEntity->CreateComponent(ConvertQStringToString(typeName)); if (componentIndex >= 0) { // update ui UpdatePropertyEditor(); SetSelectedComponentIndex(componentIndex); } } } void EditorEntityEditMode::OnUIActionRemoveComponentTriggered() { } void EditorEntityEditMode::OnUIActionSelectionLayersTriggered() { } void EditorEntityEditMode::OnUISelectionComponentListCurrentRowChanged(int currentRow) { SetSelectedComponentIndex(currentRow); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorEntityEditMode::EditorEntityEditMode(EditorMap *pMap) : EditorEditMode(pMap), m_ui(nullptr), m_pRotationGismoTexture(nullptr), m_activeWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET_SELECT), m_lastMousePositionEntityId(0), m_currentState(STATE_NONE) { m_mouseSelectionRegion[0].SetZero(); m_mouseSelectionRegion[1].SetZero(); Y_memzero(m_currentStateData, sizeof(m_currentStateData)); m_currentStateDataVector.SetZero(); m_selectionBounds.SetZero(); m_selectedComponentIndex = -1; m_selectionAxisPosition.SetZero(); m_selectionAxisRotation.SetIdentity(); } EditorEntityEditMode::~EditorEntityEditMode() { delete m_ui; } bool EditorEntityEditMode::Initialize(ProgressCallbacks *pProgressCallbacks) { // base class init if (!EditorEditMode::Initialize(pProgressCallbacks)) return false; // load resources if ((m_pRotationGismoTexture = g_pResourceManager->GetTexture2D("resources/editor/textures/rotation_gismo")) == nullptr) m_pRotationGismoTexture = g_pResourceManager->GetDefaultTexture2D(); if ((m_pRotationGismoTransparentTexture = g_pResourceManager->GetTexture2D("resources/editor/textures/rotation_gismo_transparent")) == nullptr) m_pRotationGismoTransparentTexture = g_pResourceManager->GetDefaultTexture2D(); // ok return true; } void EditorEntityEditMode::Activate() { // fall through EditorEditMode::Activate(); // set the initial properties window caption //m_pMap->GetMapWindow()->GetUI()->propertyEditor->SetTitleText("No selection"); } void EditorEntityEditMode::Deactivate() { // clear any selection ClearSelection(); // clear state variables m_lastMousePositionEntityId = 0; m_mouseSelectionRegion[0].SetZero(); m_mouseSelectionRegion[1].SetZero(); m_currentState = STATE_NONE; Y_memzero(m_currentStateData, sizeof(m_currentStateData)); // fall through EditorEditMode::Deactivate(); } void EditorEntityEditMode::SetActiveWidget(EDITOR_ENTITY_EDIT_MODE_WIDGET widget) { DebugAssert(widget < EDITOR_ENTITY_EDIT_MODE_WIDGET_COUNT); if (widget == m_activeWidget) { m_ui->OnEntityEditWidgetChanged(m_activeWidget); return; } m_activeWidget = widget; m_ui->OnEntityEditWidgetChanged(m_activeWidget); m_pMap->GetMapWindow()->RedrawAllViewports(); } void EditorEntityEditMode::AddSelection(EditorMapEntity *pEntity) { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { if (m_selectedEntities[i] == pEntity) return; } // update selected state pEntity->OnSelectedStateChanged(true); // shouldn't have a component selected m_selectedComponentIndex = -1; // add to selection array m_selectedEntities.Add(pEntity); // update property editor UpdatePropertyEditor(); // update bounds UpdateSelectionBounds(); UpdateSelectionAxis(); // redraw m_pMap->GetMapWindow()->RedrawAllViewports(); //EditorPropertyEditorDialog *pd = new EditorPropertyEditorDialog(m_pMap->GetMapWindow()); //pd->PopulateForEntity(m_pMap, pEntity); //pd->show(); } void EditorEntityEditMode::RemoveSelection(EditorMapEntity *pEntity) { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { if (m_selectedEntities[i] == pEntity) { pEntity->OnSelectedStateChanged(false); m_selectedEntities.OrderedRemove(i); break; } } // shouldn't have a component selected m_selectedComponentIndex = -1; // update property editor UpdatePropertyEditor(); // update bounds UpdateSelectionBounds(); UpdateSelectionAxis(); // redraw m_pMap->GetMapWindow()->RedrawAllViewports(); } void EditorEntityEditMode::ClearSelection() { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) m_selectedEntities[i]->OnSelectedStateChanged(false); m_selectedComponentIndex = -1; m_selectedEntities.Clear(); m_selectionAxisPosition.SetZero(); // update property editor UpdatePropertyEditor(); // update bounds UpdateSelectionBounds(); UpdateSelectionAxis(); // redraw m_pMap->GetMapWindow()->RedrawAllViewports(); } void EditorEntityEditMode::SetSelectedComponentIndex(int32 componentIndex) { if (m_selectedEntities.GetSize() != 1) { m_selectedComponentIndex = -1; return; } EditorMapEntity *pEntity = m_selectedEntities[0]; if (!pEntity->IsEntity()) { m_selectedComponentIndex = -1; return; } // deselect current if ((uint32)m_selectedComponentIndex < pEntity->GetComponentCount()) pEntity->OnComponentSelectedStateChanged(m_selectedComponentIndex, false); pEntity->OnSelectedStateChanged(true); // deselecting? if (componentIndex < 0) { m_selectedComponentIndex = -1; m_pMap->RedrawAllViewports(); return; } // selecting? if ((uint32)componentIndex >= pEntity->GetComponentCount()) { m_selectedComponentIndex = -1; return; } // set it pEntity->OnSelectedStateChanged(false); pEntity->OnComponentSelectedStateChanged(componentIndex, true); m_selectedComponentIndex = componentIndex; UpdatePropertyEditorForComponent(); m_pMap->RedrawAllViewports(); } bool EditorEntityEditMode::IsSelected(const EditorMapEntity *pEntity) const { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { if (m_selectedEntities[i] == pEntity) return true; } return false; } void EditorEntityEditMode::MoveSelection(const float3 &moveDelta) { if (m_selectedEntities.GetSize() == 0) return; // handle component case if (m_selectedEntities.GetSize() == 1 && m_selectedComponentIndex >= 0) { EditorMapEntity *pEntity = m_selectedEntities[0]; float3 currentValue(StringConverter::StringToFloat3(pEntity->GetComponentPropertyValue(m_selectedComponentIndex, "LocalPosition"))); pEntity->SetComponentPropertyValue(m_selectedComponentIndex, "LocalPosition", StringConverter::Float3ToString(currentValue + moveDelta)); } else { for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { EditorMapEntity *pEntity = m_selectedEntities[i]; // we'll use the position from the entity visual, since that should be up-to-date anyway. float3 newPosition(pEntity->GetPosition() + moveDelta); // commit it to the source pEntity->SetPosition(newPosition); } } } void EditorEntityEditMode::RotateSelection(const float3 &rotateDelta) { Quaternion rotationMod(Quaternion::FromEulerAngles(rotateDelta)); if (m_selectedEntities.GetSize() == 0) return; for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { EditorMapEntity *pEntity = m_selectedEntities[i]; // we'll use the position from the entity visual, since that should be up-to-date anyway. Quaternion newRotation(pEntity->GetRotation() * rotationMod); // commit it to the source pEntity->SetRotation(newRotation); } } void EditorEntityEditMode::ScaleSelection(const float3 &scaleDelta) { if (m_selectedEntities.GetSize() == 0) return; for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { EditorMapEntity *pEntity = m_selectedEntities[i]; // we'll use the position from the entity visual, since that should be up-to-date anyway. float3 newScale(pEntity->GetScale() + scaleDelta); // commit it to the source pEntity->SetScale(newScale); } } void EditorEntityEditMode::PushSelection(const float3 &pushDirection, float maxDistance /*= 100.0f*/) { if (m_selectedEntities.GetSize() == 0) return; bool useBoundingSpheres = false; uint32 mainAxis = (pushDirection.x != 0.0f) ? 0 : ((pushDirection.y != 0.0f) ? 1 : 2); for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { EditorMapEntity *pEntity = m_selectedEntities[i]; float bestContactDistance = Y_FLT_INFINITE; if (!useBoundingSpheres) { // construct a new box with the extent of the axis extended to the max distance float3 boxCenter(pEntity->GetBoundingBox().GetCenter()); float3 boxHalfExtents(pEntity->GetBoundingBox().GetExtents() * 0.5f); boxHalfExtents[mainAxis] = Max(boxHalfExtents[mainAxis], maxDistance * 0.5f); AABox searchBox(boxCenter - boxHalfExtents, boxCenter + boxHalfExtents); // loop over objects float3 displacement(pushDirection * maxDistance); m_pMap->EnumerateEntitiesInAABox(searchBox, [pEntity, &bestContactDistance, &displacement](const EditorMapEntity *pOtherEntity) { // skip entities without visuals if (pEntity == pOtherEntity || !pOtherEntity->IsVisualCreated()) return; float contactDistance = CollisionDetection::AABoxSweep(pEntity->GetBoundingBox().GetMinBounds(), pEntity->GetBoundingBox().GetMaxBounds(), displacement, pOtherEntity->GetBoundingBox().GetMinBounds(), pOtherEntity->GetBoundingBox().GetMaxBounds()); bestContactDistance = Min(bestContactDistance, contactDistance); }); } else { } // did we hit anything? if (bestContactDistance != Y_FLT_INFINITE) { // move in the push direction, this distance float3 newPosition(pEntity->GetPosition() + pushDirection * bestContactDistance); Log_DevPrintf("push contact distance %f", bestContactDistance); // commit it to the source pEntity->SetPosition(newPosition); } else { Log_DevPrintf("no contacts found"); } } } void EditorEntityEditMode::SnapSelectionToGrid() { if (m_selectedEntities.GetSize() == 0) return; float3 snapInterval(m_pMap->GetGridSnapInterval(), m_pMap->GetGridSnapInterval(), m_pMap->GetGridSnapInterval()); for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { EditorMapEntity *pEntity = m_selectedEntities[i]; pEntity->SetPosition(pEntity->GetPosition().Snap(snapInterval)); } } void EditorEntityEditMode::DeleteSelection() { if (m_selectedEntities.GetSize() == 0) return; while (m_selectedEntities.GetSize() > 0) { EditorMapEntity *pEntity = m_selectedEntities[m_selectedEntities.GetSize() - 1]; m_selectedEntities.PopBack(); pEntity->OnSelectedStateChanged(false); m_pMap->DeleteEntity(pEntity); } m_selectionAxisPosition.SetZero(); // update property editor UpdatePropertyEditor(); // update bounds UpdateSelectionBounds(); UpdateSelectionAxis(); m_pMap->RedrawAllViewports(); } void EditorEntityEditMode::CloneSelection(bool addToSelection, bool clearOldSelection) { if (m_selectedEntities.GetSize() == 0) return; // create new entities EditorMapEntity **ppNewEntities = (EditorMapEntity **)alloca(sizeof(EditorMapEntity *) * m_selectedEntities.GetSize()); uint32 nNewEntities = 0; for (uint32 selectionIndex = 0; selectionIndex < m_selectedEntities.GetSize(); selectionIndex++) { // copy it if ((ppNewEntities[nNewEntities] = m_pMap->CopyEntity(m_selectedEntities[selectionIndex])) != nullptr) nNewEntities++; } // clear old selection first if (clearOldSelection) ClearSelection(); // then add the new if (addToSelection) { for (uint32 i = 0; i < nNewEntities; i++) AddSelection(ppNewEntities[i]); } } void EditorEntityEditMode::Update(const float timeSinceLastUpdate) { EditorEditMode::Update(timeSinceLastUpdate); } void EditorEntityEditMode::OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) { SetPropertyOnSelection(propertyName, propertyValue); } void EditorEntityEditMode::OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) { EditorEditMode::OnActiveViewportChanged(pOldActiveViewport, pNewActiveViewport); // clear state variables m_lastMousePositionEntityId = 0; m_mouseSelectionRegion[0].SetZero(); m_mouseSelectionRegion[1].SetZero(); m_currentState = STATE_NONE; Y_memzero(m_currentStateData, sizeof(m_currentStateData)); // cleanp old viewport, if there is one if (pOldActiveViewport != NULL) { pOldActiveViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); } // setup new viewport, if there is one if (pNewActiveViewport != NULL) { pNewActiveViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); } } bool EditorEntityEditMode::HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) { // our handlers switch (pKeyboardEvent->type()) { case QEvent::KeyPress: { } break; case QEvent::KeyRelease: { switch (pKeyboardEvent->key()) { case Qt::Key_Escape: ClearSelection(); return true; case Qt::Key_Delete: DeleteSelection(); return true; #if 0 // temp testing stuff case Qt::Key_L: { PointLightEntity *pEntity = new PointLightEntity(m_pEditorMap->GetWorld()->AllocateEntityId()); pEntity->SetPosition(m_Camera.GetCameraPosition()); pEntity->SetRange(512.0f); pEntity->SetCastDynamicShadows(true); pEntity->SetCastStaticShadows(true); m_pEditorMap->GetWorld()->AddEntity(pEntity); pEntity->Release(); Log_DevPrintf("spawned test light @ %.3f %.3f %.3f", m_Camera.GetCameraPosition().x, m_Camera.GetCameraPosition().y, m_Camera.GetCameraPosition().z); pViewport->FlagForRedraw(); } break; #endif } } break; } // nothing left return EditorEditMode::HandleViewportKeyboardInputEvent(pViewport, pKeyboardEvent); } bool EditorEntityEditMode::HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { // if not currently in any state, determine which state to transition to if (m_currentState == STATE_NONE) { // what is under the texel that we are currently sitting on? if (m_lastMousePositionEntityId >= EDITOR_ENTITY_ID_WIDGET_AXIS_X && m_lastMousePositionEntityId <= EDITOR_ENTITY_ID_WIDGET_AXIS_ANY) { // under a selection axis. change to move mode, and set the correct movement axis m_currentState = STATE_WIDGET; m_currentStateData[0] = m_lastMousePositionEntityId - EDITOR_ENTITY_ID_WIDGET_AXIS_X; m_mouseSelectionRegion[0] = pViewport->GetMousePosition(); m_currentStateDataVector.SetZero(); // update the cursor switch (m_activeWidget) { case EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_SIZING); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_RIGHT_ARROW); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_MAGNIFIER); break; } // redraw the viewport //pViewport->LockMouseCursor(); pViewport->FlagForRedraw(); return true; } else { // under nothing or an entity, so change to selection rect mode m_currentState = STATE_SELECTION_RECT; m_mouseSelectionRegion[0] = m_mouseSelectionRegion[1] = pViewport->GetMousePosition(); m_currentStateData[0] = 0; UpdateSelection(pViewport); // update cursor + redraw pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); pViewport->FlagForRedraw(); return true; } } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { switch (m_currentState) { case STATE_SELECTION_RECT: case STATE_WIDGET: { m_mouseSelectionRegion[0].SetZero(); m_mouseSelectionRegion[1].SetZero(); m_currentState = STATE_NONE; Y_memzero(m_currentStateData, sizeof(m_currentStateData)); //pViewport->UnlockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); pViewport->FlagForRedraw(); return true; } break; } } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_currentState == STATE_NONE) { // right mouse button enters camera rotation state m_currentState = STATE_CAMERA_ROTATION; // lock cursor, set cursor, and redraw pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_CROSS); pViewport->LockMouseCursor(); pViewport->FlagForRedraw(); return true; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_currentState == STATE_CAMERA_ROTATION) { // exit the state m_currentState = STATE_NONE; Y_memzero(m_currentStateData, sizeof(m_currentStateData)); // reset viewport state pViewport->UnlockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); pViewport->FlagForRedraw(); return true; } } else if (pMouseEvent->type() == QEvent::MouseMove) { int2 currentMousePosition(pViewport->GetMousePosition()); int2 mousePositionDelta(pViewport->GetMouseDelta()); uint32 lastMousePositionEntityId = m_lastMousePositionEntityId; uint32 mousePositionEntityId = pViewport->GetPickingTextureValue(currentMousePosition); // handle mouse movement based on state switch (m_currentState) { case STATE_NONE: { // if not in any state, but the entity id under the mouse changes, or is nonzero, we need to redraw it // so the hover overlay can be shown if (mousePositionEntityId != lastMousePositionEntityId) { if (mousePositionEntityId >= EDITOR_ENTITY_ID_RESERVED_BEGIN) { // handle cursor updates if (mousePositionEntityId >= EDITOR_ENTITY_ID_WIDGET_AXIS_X && mousePositionEntityId <= EDITOR_ENTITY_ID_WIDGET_AXIS_ANY) { switch (m_activeWidget) { case EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_SIZING); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_RIGHT_ARROW); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE: pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_MAGNIFIER); break; } pViewport->FlagForRedraw(); } } else { if (lastMousePositionEntityId >= EDITOR_ENTITY_ID_WIDGET_AXIS_X && lastMousePositionEntityId <= EDITOR_ENTITY_ID_WIDGET_AXIS_ANY) { // reset cursor pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); } pViewport->FlagForRedraw(); } } } break; case STATE_CAMERA_ROTATION: { // pass difference through to camera pViewport->GetViewController().RotateFromMousePosition(mousePositionDelta); pViewport->FlagForRedraw(); } break; case STATE_SELECTION_RECT: { // update selection rect bounds m_mouseSelectionRegion[1] = currentMousePosition; UpdateSelection(pViewport); pViewport->FlagForRedraw(); } break; case STATE_WIDGET: { // get the center of the selection bounds, this is our reference point float3 selectionBoundsCenter(m_selectionBounds.GetCenter()); // project this to the screen float3 projectedSelectionBoundsCenter(pViewport->GetViewController().Project(selectionBoundsCenter)); // get the position with the mouse offset float3 projectedOffsetSelectionBoundsCenter(projectedSelectionBoundsCenter + float3((float)mousePositionDelta.x, (float)mousePositionDelta.y, 0.0f)); // unproject back to world space float3 offsetSelectionBoundsCenter(pViewport->GetViewController().Unproject(projectedOffsetSelectionBoundsCenter)); // axis mask static const float axisMask[4][3] = { { 1.0f, 0.0f, 0.0f }, // move x { 0.0f, 1.0f, 0.0f }, // move y { 0.0f, 0.0f, 1.0f }, // move z { 1.0f, 1.0f, 1.0f }, // move all }; // determine move amount in worldspace on all axises float3 entityMoveAmount(offsetSelectionBoundsCenter - selectionBoundsCenter); // apply axis mask DebugAssert(m_currentStateData[0] < 4); entityMoveAmount = entityMoveAmount * float3(axisMask[m_currentStateData[0]]); // Logging /*Log_DevPrintf("mouseDiff = %d %d, selectionBoundsCenter = %.3f %.3f %.3f, projectedSelectionBoundsCenter = %.3f %.3f %.3f, offsetSelectionBoundsCenter = %.3f %.3f %.3f, entityMoveAmount = %.3f %.3f %.3f", mousePositionDelta.x, mousePositionDelta.y, selectionBoundsCenter.x, selectionBoundsCenter.y, selectionBoundsCenter.z, projectedSelectionBoundsCenter.x, projectedSelectionBoundsCenter.y, projectedSelectionBoundsCenter.z, offsetSelectionBoundsCenter.x, offsetSelectionBoundsCenter.y, offsetSelectionBoundsCenter.z, entityMoveAmount.x, entityMoveAmount.y, entityMoveAmount.z);*/ // if alt modifier is held down, create a copy of the entity unless it's already been done if (pMouseEvent->modifiers() & Qt::AltModifier && m_currentStateData[1] == 0) { // copy selection CloneSelection(true, true); // flag as 'copied' m_currentStateData[1] = 1; } // disable grid snap if shift is held down bool snapToGrid = true; if (pMouseEvent->modifiers() & Qt::ShiftModifier) snapToGrid = false; // snapping to grid? if (snapToGrid) { float3 lastTotalAmountMoved(m_currentStateDataVector); float3 newTotalAmountMoved(lastTotalAmountMoved + entityMoveAmount); // snap the total amount to the grid interval float3 snapInterval(m_pMap->GetGridSnapInterval(), m_pMap->GetGridSnapInterval(), m_pMap->GetGridSnapInterval()); float3 snappedTotalAmountMoved(newTotalAmountMoved.Snap(snapInterval)); float3 snappedLastTotalAmountMoved(lastTotalAmountMoved.Snap(snapInterval)); // apply changes entityMoveAmount = snappedTotalAmountMoved - snappedLastTotalAmountMoved; m_currentStateDataVector = newTotalAmountMoved; } else { m_currentStateDataVector += entityMoveAmount; } // Handle based on active widget switch (m_activeWidget) { case EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE: { // Move the entities // if moving in any direction, don't use the local coordinate system if (m_currentStateData[0] != 3) entityMoveAmount = m_selectionAxisRotation * entityMoveAmount; MoveSelection(entityMoveAmount); } break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE: { // Rotate the entities RotateSelection(entityMoveAmount * 100.0f); } break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE: { // Scale the entities // special case for scaling, keep the values consistent for uniform scaling if (m_currentStateData[0] == 3) { float uniformScaling = Max(entityMoveAmount.x, Max(entityMoveAmount.y, entityMoveAmount.z)); entityMoveAmount.Set(uniformScaling, uniformScaling, uniformScaling); } ScaleSelection(entityMoveAmount); } break; } } break; } // store values m_lastMousePositionEntityId = mousePositionEntityId; } return EditorEditMode::HandleViewportMouseInputEvent(pViewport, pMouseEvent); } bool EditorEntityEditMode::HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) { return EditorEditMode::HandleViewportWheelInputEvent(pViewport, pWheelEvent); } void EditorEntityEditMode::OnViewportDrawAfterWorld(EditorMapViewport *pViewport) { MINIGUI_RECT guiRect; MiniGUIContext &guiContext = pViewport->GetGUIContext(); // fall through EditorEditMode::OnViewportDrawAfterWorld(pViewport); // draw axis on selection if (m_selectedEntities.GetSize() > 0) { // draw bounding box around selection { guiContext.PushManualFlush(); guiContext.SetAlphaBlendingEnabled(false); guiContext.SetDepthTestingEnabled(false); for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) guiContext.Draw3DWireBox(m_selectedEntities[i]->GetBoundingBox(), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); guiContext.PopManualFlush(); guiContext.Flush(); } // determine axis colors uint32 XAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 0, 0, 255); uint32 YAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255); uint32 ZAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 255, 255); uint32 anyAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(45, 188, 236, 255); uint32 XPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 0); uint32 YPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 0); uint32 ZPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 0); int32 onlyAxis = -1; // currently using widget? if (m_currentState == STATE_WIDGET) { // nuke the other axises switch (m_currentStateData[0]) { case 0: XAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); XPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); YAxisColor = 0; YPlaneFillColor = 0; ZAxisColor = 0; ZPlaneFillColor = 0; onlyAxis = 0; break; case 1: XAxisColor = 0; XPlaneFillColor = 0; YAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); YPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); ZAxisColor = 0; ZPlaneFillColor = 0; onlyAxis = 1; break; case 2: XAxisColor = 0; XPlaneFillColor = 0; YAxisColor = 0; YPlaneFillColor = 0; ZAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); ZPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); onlyAxis = 2; break; } } else { // if any are highlighted change the color switch (m_lastMousePositionEntityId) { case EDITOR_ENTITY_ID_WIDGET_AXIS_X: XAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); XPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); break; case EDITOR_ENTITY_ID_WIDGET_AXIS_Y: YAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); YPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); break; case EDITOR_ENTITY_ID_WIDGET_AXIS_Z: ZAxisColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); ZPlaneFillColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 128); break; } } // draw appropriate axis switch (m_activeWidget) { case EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE: //DrawSelectionMoveAxis(pViewport, XAxisColor, YAxisColor, ZAxisColor, XAxisColor, YAxisColor, ZAxisColor, XPlaneFillColor, YPlaneFillColor, ZPlaneFillColor); DrawMoveGismo(pViewport, XAxisColor, YAxisColor, ZAxisColor, anyAxisColor, XPlaneFillColor, YPlaneFillColor, ZPlaneFillColor, onlyAxis); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE: DrawRotationGismo(pViewport, XAxisColor, YAxisColor, ZAxisColor, true, onlyAxis); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE: DrawScaleGismo(pViewport, XAxisColor, YAxisColor, ZAxisColor, anyAxisColor, onlyAxis); break; } } // draw the selection rectangle if (m_currentState == STATE_SELECTION_RECT) { // draw outer rect guiRect.left = Min(m_mouseSelectionRegion[0].x, m_mouseSelectionRegion[1].x); guiRect.right = Max(m_mouseSelectionRegion[0].x, m_mouseSelectionRegion[1].x); guiRect.top = Min(m_mouseSelectionRegion[0].y, m_mouseSelectionRegion[1].y); guiRect.bottom = Max(m_mouseSelectionRegion[0].y, m_mouseSelectionRegion[1].y); guiContext.DrawRect(&guiRect, MAKE_COLOR_R8G8B8A8_UNORM(51, 153, 255, 255)); #if 0 // if >1 pixel, draw alpha blended inside rect if (guiRect.left != guiRect.right && guiRect.top != guiRect.bottom) { guiRect.left++; guiRect.right--; guiRect.top++; guiRect.bottom--; g_pGUISystem->GetRenderer()->DrawFilledRect(&guiRect, Vector4(1.0f, 1.0f, 1.0f, 0.5f), true); } #endif #if 0 // draw the selection RT to a small section in the corner MINIGUI_UV_RECT uvRect = { 0.0f, 1.0f, 0.0f, 1.0f }; guiRect.left = (int32)Y_floorf(0.05f * (float)m_RenderTargetDimensions.x); guiRect.right = (int32)Y_ceilf(0.4f * (float)m_RenderTargetDimensions.x); guiRect.top = (int32)Y_floorf(0.05f * (float)m_RenderTargetDimensions.y); guiRect.bottom = (int32)Y_ceilf(float(guiRect.right - guiRect.left) * ((float)m_RenderTargetDimensions.y / (float)m_RenderTargetDimensions.x)); m_GUIContext.DrawTexturedRect(&guiRect, &uvRect, m_pPickingRenderTarget); #endif } else { // // draw entity tooltip? // if (m_eViewportState == EDITOR_VIEWPORT_STATE_NONE && m_iLastMousePositionEntityId != 0 && m_iLastMousePositionEntityId < EDITOR_ENTITY_ID_RESERVED_BEGIN) // { // // draw text near the entity, indicating its type and id // const Entity *pEntity = g_pEditor->GetWorld()->GetEntityById(m_iLastMousePositionEntityId); // if (pEntity != NULL) // { // // draw tooltip // tempStr.Format("Entity %u (Map ID %u): %s", pEntity->GetEntityId(), g_pEditor->LookupMapEntityId(pEntity->GetEntityId()), pEntity->GetTypeInfo()->GetName()); // m_GUIContext.DrawText(m_pOverlayFont, 16, m_LastMousePosition + 16, tempStr, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); // pEntity->Release(); // } // } } } void EditorEntityEditMode::OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawBeforeWorld(pViewport); } void EditorEntityEditMode::OnViewportDrawAfterPost(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterPost(pViewport); } void EditorEntityEditMode::OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawAfterWorld(pViewport); // drawing picking texture if (m_selectedEntities.GetSize() > 0) { // draw selection axis const uint32 xColor = EDITOR_ENTITY_ID_WIDGET_AXIS_X; const uint32 yColor = EDITOR_ENTITY_ID_WIDGET_AXIS_Y; const uint32 zColor = EDITOR_ENTITY_ID_WIDGET_AXIS_Z; const uint32 anyAxisColor = EDITOR_ENTITY_ID_WIDGET_AXIS_ANY; // draw appropriate axis switch (m_activeWidget) { case EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE: //DrawSelectionMoveAxis(pViewport, xColor, yColor, zColor, xColor, yColor, zColor, xColor, yColor, zColor); DrawMoveGismo(pViewport, xColor, yColor, zColor, anyAxisColor, xColor, yColor, zColor, -1); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE: DrawRotationGismo(pViewport, xColor, yColor, zColor, false, -1); break; case EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE: DrawScaleGismo(pViewport, xColor, yColor, zColor, anyAxisColor, -1); break; } } } void EditorEntityEditMode::OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawBeforeWorld(pViewport); } void EditorEntityEditMode::DrawMoveGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, const uint32 anyAxisColor, const uint32 XPlaneFillColor, const uint32 YPlaneFillColor, const uint32 ZPlaneFillColor, int32 onlyAxis /* = -1 */) { float lineLength = 2.0f; float lineThickness = 2.0f; float halfLineLength = lineLength * 0.5f; float tipLength = 1.0f; float tipRadius = 0.1875f; float totalLength = lineLength + tipLength + tipRadius; uint32 tipVertexCount = 24; float anyAxisBoxExtents = 0.2f; // cache device pointers GPUContext *pGPUDevice = g_pRenderer->GetGPUContext(); // Build transforms. { const AABox &entitySelectionBounds = m_selectionBounds; float3 boundsDimensions = entitySelectionBounds.GetMaxBounds() - entitySelectionBounds.GetMinBounds(); // Determine the scale to draw the axis at. float largestDimension = Max(boundsDimensions.x, Max(boundsDimensions.y, boundsDimensions.z)); float desiredSize = largestDimension / 6.0f; float scale = Max(0.25f, desiredSize / totalLength); //float4x4 scaleMatrix(float4x4::MakeScaleMatrix(scale, scale, scale)); // scale everything up lineLength *= scale; halfLineLength *= scale; tipLength *= scale; tipRadius *= scale; totalLength = lineLength + tipLength + tipRadius; anyAxisBoxExtents *= scale; // Get rotation matrix. //float4x4 rotationMatrix(m_selectionAxisRotation.GetFloat4x4()); // Get translation matrix. //float4x4 translationMatrix(float4x4::MakeTranslationMatrix(m_selectionAxisPosition)); // Generate and set world matrix. //float4x4 localToWorldMatrix(translationMatrix * scaleMatrix * rotationMatrix); //pGPUDevice->GetGPUConstants()->SetLocalToWorldMatrix(localToWorldMatrix, true); pGPUDevice->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); } // arrow base position float3 arrowBasePosition(m_selectionAxisPosition); // setup pdi MiniGUIContext &guiContext = pViewport->GetGUIContext(); guiContext.SetAlphaBlendingEnabled(false); guiContext.SetDepthTestingEnabled(false); // Draw any axis box if (onlyAxis < 0) guiContext.Draw3DBox(float3(arrowBasePosition) - float3(anyAxisBoxExtents, anyAxisBoxExtents, anyAxisBoxExtents), float3(arrowBasePosition) + float3(anyAxisBoxExtents, anyAxisBoxExtents, anyAxisBoxExtents), anyAxisColor); // X axis arrow if (onlyAxis < 0 || onlyAxis == 0) guiContext.Draw3DArrow(arrowBasePosition, m_selectionAxisRotation * float3::UnitX, lineLength, lineThickness, tipLength, tipRadius, XAxisColor, tipVertexCount); // Y axis arrow if (onlyAxis < 0 || onlyAxis == 1) guiContext.Draw3DArrow(arrowBasePosition, m_selectionAxisRotation * float3::UnitY, lineLength, lineThickness, tipLength, tipRadius, YAxisColor, tipVertexCount); // Z axis arrow if (onlyAxis < 0 || onlyAxis == 2) guiContext.Draw3DArrow(arrowBasePosition, m_selectionAxisRotation * float3::UnitZ, lineLength, lineThickness, tipLength, tipRadius, ZAxisColor, tipVertexCount); // Draw plane borders guiContext.BeginImmediate3D(MiniGUIContext::IMMEDIATE_PRIMITIVE_LINES); // X axis plane border if (onlyAxis < 0 || onlyAxis == 0) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), XAxisColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), XAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), XAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), XAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), XAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, halfLineLength), XAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, halfLineLength), XAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), XAxisColor); // top-left } // Y axis plane if (onlyAxis < 0 || onlyAxis == 1) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), YAxisColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), YAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), YAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), YAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), YAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, halfLineLength), YAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, halfLineLength), YAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), YAxisColor); // top-left } // Z axis plane if (onlyAxis < 0 || onlyAxis == 2) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), ZAxisColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), ZAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), ZAxisColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), ZAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), ZAxisColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, halfLineLength, 0.0f), ZAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, halfLineLength, 0.0f), ZAxisColor); // top-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), ZAxisColor); // top-left } // End plane borders guiContext.EndImmediate(); // Draw plane guiContext.SetAlphaBlendingEnabled(true); guiContext.SetAlphaBlendingMode(MiniGUIContext::ALPHABLENDING_MODE_STRAIGHT); guiContext.BeginImmediate3D(MiniGUIContext::IMMEDIATE_PRIMITIVE_QUADS); // X axis plane if (XPlaneFillColor != 0 && (onlyAxis < 0 || onlyAxis == 0)) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), XPlaneFillColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), XPlaneFillColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), XPlaneFillColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, halfLineLength), XPlaneFillColor); // top-right } // Y axis plane if (YPlaneFillColor != 0 && (onlyAxis < 0 || onlyAxis == 1)) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, halfLineLength), YPlaneFillColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), YPlaneFillColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), YPlaneFillColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, halfLineLength), YPlaneFillColor); // top-right } // Z axis plane if (ZPlaneFillColor != 0 && (onlyAxis < 0 || onlyAxis == 2)) { guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, halfLineLength, 0.0f), ZPlaneFillColor); // top-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(0.0f, 0.0f, 0.0f), ZPlaneFillColor); // bottom-left guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, 0.0f, 0.0f), ZPlaneFillColor); // bottom-right guiContext.ImmediateVertex(arrowBasePosition + m_selectionAxisRotation * float3(halfLineLength, halfLineLength, 0.0f), ZPlaneFillColor); // top-right } // end planes guiContext.EndImmediate(); } void EditorEntityEditMode::DrawRotationGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, bool transparent /* = true */, int32 onlyAxis /* = -1 */) { // roughly the size of the rotator gismo float gismoRadius = 0.5f; // cache device pointers GPUContext *pGPUDevice = g_pRenderer->GetGPUContext(); // Setup renderer. pGPUDevice->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE)); //pGPUDevice->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerStateWireframeNoCull()); pGPUDevice->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pGPUDevice->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending()); // Build transforms. { const AABox &entitySelectionBounds = m_selectionBounds; float3 boundsDimensions = entitySelectionBounds.GetMaxBounds() - entitySelectionBounds.GetMinBounds(); // Determine the scale to draw the axis at. float largestDimension = Max(boundsDimensions.x, Max(boundsDimensions.y, boundsDimensions.z)); float desiredSize = largestDimension / 6.0f; float scale = Max(0.25f, desiredSize / gismoRadius); float4x4 scaleMatrix(float4x4::MakeScaleMatrix(scale, scale, scale)); // if drawing a single axis, scale it by 2 if (onlyAxis >= 0) scale *= 0.5f; // Get rotation matrix. float4x4 rotationMatrix(m_selectionAxisRotation.GetMatrix4x4()); // Get translation matrix. float4x4 translationMatrix(float4x4::MakeTranslationMatrix(m_selectionAxisPosition)); // Generate and set world matrix. float4x4 localToWorldMatrix(translationMatrix * scaleMatrix * rotationMatrix); pGPUDevice->GetConstants()->SetLocalToWorldMatrix(localToWorldMatrix, true); } PlainVertexFactory::Vertex gismoVertices[3 * 2 * 3]; uint32 nVertices = 0; // find the selection center float3 selectionCenter(m_selectionBounds.GetCenter()); // draw single axis? if (onlyAxis >= 0) { switch (onlyAxis) { // x axis case 0: gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, -1.0f, 0.0f, 1.0f, XAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 1.0f, 0.0f, 0.0f, XAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(0.0f, 1.0f, -1.0f, 1.0f, 1.0f, XAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, 1.0f, -1.0f, 1.0f, 1.0f, XAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 1.0f, 0.0f, 0.0f, XAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, XAxisColor); // top-right break; // y axis case 1: gismoVertices[nVertices++].SetUVColor(-1.0f, 0.0f, -1.0f, 0.0f, 1.0f, YAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, YAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, -1.0f, 1.0f, 1.0f, YAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, -1.0f, 1.0f, 1.0f, YAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, YAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, 1.0f, 1.0f, 0.0f, YAxisColor); // top-right break; // z axis case 2: gismoVertices[nVertices++].SetUVColor(-1.0f, -1.0f, 0.0f, 0.0f, 1.0f, ZAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(-1.0f, 1.0f, 0.0f, 0.0f, 0.0f, ZAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, -1.0f, 0.0f, 1.0f, 1.0f, ZAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(1.0f, -1.0f, 0.0f, 1.0f, 1.0f, ZAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(-1.0f, 1.0f, 0.0f, 0.0f, 0.0f, ZAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, ZAxisColor); // top-right break; } } // draw all axises else { // x axis - points backwards down y axis gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 0.0f, 0.0f, 0.5f, XAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 1.0f, 0.0f, 0.0f, XAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 0.0f, 0.5f, 0.5f, XAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 0.0f, 0.5f, 0.5f, XAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 1.0f, 0.0f, 0.0f, XAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 1.0f, 0.0f, 0.5f, XAxisColor); // top-right // y axis - points forwards down x axis gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 0.0f, 0.5f, 0.5f, YAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 1.0f, 0.5f, 0.0f, YAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, 0.0f, 1.0f, 0.5f, YAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, 0.0f, 1.0f, 0.5f, YAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 1.0f, 0.5f, 0.0f, YAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, 1.0f, 1.0f, 0.0f, YAxisColor); // top-right // z axis - points forwards down x axis gismoVertices[nVertices++].SetUVColor(0.0f, -1.0f, 0.0f, 0.5f, 1.0f, ZAxisColor); // bottom-left gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 0.0f, 0.5f, 0.5f, ZAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, -1.0f, 0.0f, 1.0f, 1.0f, ZAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(1.0f, -1.0f, 0.0f, 1.0f, 1.0f, ZAxisColor); // bottom-right gismoVertices[nVertices++].SetUVColor(0.0f, 0.0f, 0.0f, 0.5f, 0.5f, ZAxisColor); // top-left gismoVertices[nVertices++].SetUVColor(1.0f, 0.0f, 0.0f, 1.0f, 0.5f, ZAxisColor); // top-right } // draw the gismo pGPUDevice->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); //g_pRenderer->DrawPlainBlended(pGPUDevice, gismoVertices, nVertices, (transparent) ? m_pRotationGismoTransparentTexture->GetGPUTexture() : m_pRotationGismoTexture->GetGPUTexture()); //g_pRenderer->DrawPlainColored(pGPUDevice, gismoVertices, nVertices); } void EditorEntityEditMode::DrawScaleGismo(EditorMapViewport *pViewport, const uint32 XAxisColor, const uint32 YAxisColor, const uint32 ZAxisColor, const uint32 anyAxisColor, int32 onlyAxis /* = -1 */) { static const float lineLength = 2.0f; static const float boxSize = 0.5f; static const float boxExtents = boxSize * 0.5f; static const float totalLength = lineLength + boxExtents; // cache device pointers GPUContext *pGPUDevice = g_pRenderer->GetGPUContext(); // Setup renderer. pGPUDevice->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_NONE)); pGPUDevice->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pGPUDevice->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending()); // Build transforms. { const AABox &entitySelectionBounds = m_selectionBounds; float3 boundsDimensions = entitySelectionBounds.GetMaxBounds() - entitySelectionBounds.GetMinBounds(); // Determine the scale to draw the axis at. float largestDimension = Max(boundsDimensions.x, Max(boundsDimensions.y, boundsDimensions.z)); float desiredSize = largestDimension / 6.0f; float scale = Max(0.25f, desiredSize / totalLength); float4x4 scaleMatrix(float4x4::MakeScaleMatrix(scale, scale, scale)); // Get rotation matrix. float4x4 rotationMatrix(m_selectionAxisRotation.GetMatrix4x4()); // Get translation matrix. float4x4 translationMatrix(float4x4::MakeTranslationMatrix(m_selectionAxisPosition)); // Generate and set world matrix. float4x4 localToWorldMatrix(translationMatrix * scaleMatrix * rotationMatrix); pGPUDevice->GetConstants()->SetLocalToWorldMatrix(localToWorldMatrix, true); } // Determine the position at which to draw the axis. float3 axisBasePosition = float3::Zero; // setup pdi MiniGUIContext &guiContext = pViewport->GetGUIContext(); guiContext.SetAlphaBlendingEnabled(false); guiContext.SetDepthTestingEnabled(false); // X axis line if (onlyAxis < 0 || onlyAxis == 0) { guiContext.Draw3DLine(float3::Zero, float2::Zero, XAxisColor); guiContext.Draw3DLine(float3(lineLength, 0.0f, 0.0f), float2::Zero, XAxisColor); } // Y axis line if (onlyAxis < 0 || onlyAxis == 1) { guiContext.Draw3DLine(float3::Zero, float2::Zero, YAxisColor); guiContext.Draw3DLine(float3(0.0f, lineLength, 0.0f), float2::Zero, YAxisColor); } // Z axis line if (onlyAxis < 0 || onlyAxis == 2) { guiContext.Draw3DLine(float3::Zero, float2::Zero, ZAxisColor); guiContext.Draw3DLine(float3(0.0f, 0.0f, lineLength), float2::Zero, ZAxisColor); } // Draw "all axises" box if (onlyAxis < 0) guiContext.Draw3DBox(float3(-boxExtents, -boxExtents, -boxExtents), float3(boxExtents, boxExtents, boxExtents), anyAxisColor); // Draw x axis box if (onlyAxis < 0 || onlyAxis == 0) guiContext.Draw3DBox(float3(lineLength + -boxExtents, -boxExtents, -boxExtents), float3(lineLength + boxExtents, boxExtents, boxExtents), XAxisColor); // Draw y axis box if (onlyAxis < 0 || onlyAxis == 1) guiContext.Draw3DBox(float3(-boxExtents, lineLength + -boxExtents, -boxExtents), float3(boxExtents, lineLength + boxExtents, boxExtents), YAxisColor); // Draw y axis box if (onlyAxis < 0 || onlyAxis == 2) guiContext.Draw3DBox(float3(-boxExtents, -boxExtents, lineLength + -boxExtents), float3(boxExtents, boxExtents, lineLength + boxExtents), ZAxisColor); } void EditorEntityEditMode::UpdateSelection(EditorMapViewport *pViewport) { // determine min/max coordinates Vector2i minCoordinates = m_mouseSelectionRegion[0].Min(m_mouseSelectionRegion[1]); Vector2i maxCoordinates = m_mouseSelectionRegion[0].Max(m_mouseSelectionRegion[1]); Log_DevPrintf("New selection: [%d-%d] [%d-%d]", m_mouseSelectionRegion[0].x, m_mouseSelectionRegion[1].x, m_mouseSelectionRegion[0].y, m_mouseSelectionRegion[1].y); // allocate memory for receiving entity ids Vector2i coordinateRange = maxCoordinates - minCoordinates + 1; uint32 *pTexelValues = new uint32[coordinateRange.x * coordinateRange.y]; uint32 *pCurrentTexelValue = pTexelValues; // read texel values if (pViewport->GetPickingTextureValues(minCoordinates, maxCoordinates, pTexelValues)) { // clear current selection ClearSelection(); // iterate each pixel that is selected, determining which render target was hit on the screen Vector2i currentPosition = minCoordinates; for (; currentPosition.y <= maxCoordinates.y; currentPosition.y++) { for (currentPosition.x = minCoordinates.x; currentPosition.x <= maxCoordinates.x; currentPosition.x++) { uint32 texelValue = *pCurrentTexelValue++; if (texelValue == 0 || texelValue >= EDITOR_ENTITY_ID_RESERVED_BEGIN) continue; // look up the visual that this texel has EditorMapEntity *pEntity = m_pMap->GetEntityByArrayIndex(texelValue - 1); if (pEntity == nullptr) continue; //Log_DevPrintf(" hit queue id %u : %s", texelValue, (pEntity != NULL) ? pEntity->GetTypeInfo()->GetName() : "NULL"); // is it a visual entity? AddSelection(pEntity); } } } } void EditorEntityEditMode::UpdateSelectionBounds() { m_selectionBounds = AABox::Zero; for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { if (i == 0) m_selectionBounds = m_selectedEntities[i]->GetBoundingBox(); else m_selectionBounds.Merge(m_selectedEntities[i]->GetBoundingBox()); } } void EditorEntityEditMode::UpdateSelectionAxis() { // if we have one selection, we set the axis position to be the position of the entity. // if we have more than one, then we use the centre of the merged bounds of the selection. if (m_selectedEntities.GetSize() == 1) { m_selectionAxisPosition = m_selectedEntities[0]->GetPosition(); if (m_pMap->GetMapWindow()->GetReferenceCoordinateSystem() == EDITOR_REFERENCE_COORDINATE_SYSTEM_LOCAL) m_selectionAxisRotation = m_selectedEntities[0]->GetRotation(); else m_selectionAxisRotation.SetIdentity(); } else if (m_selectedEntities.GetSize() > 1) { m_selectionAxisPosition = m_selectionBounds.GetCenter(); m_selectionAxisRotation.SetIdentity(); } else { m_selectionAxisPosition.SetZero(); m_selectionAxisRotation.SetIdentity(); } // force redraw m_pMap->GetMapWindow()->RedrawAllViewports(); } void EditorEntityEditMode::OnEntityPropertyChanged(const EditorMapEntity *pEntity, const char *propertyName, const char *propertyValue) { EditorMapWindow *pMapWindow = m_pMap->GetMapWindow(); EditorPropertyEditorWidget *propertyEditor = pMapWindow->GetUI()->propertyEditor; // check for entity edit mode if (pMapWindow->GetEditMode() == EDITOR_EDIT_MODE_ENTITY && IsSelected(pEntity)) { // we're selected, so update the property manager if it's tracked // first check if the value matches the other entities const char *propertyEditorValue = propertyValue; for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) { if (m_selectedEntities[i] == pEntity) continue; const String *otherValue = m_selectedEntities[i]->GetEntityData()->GetPropertyValuePointer(propertyName); if (otherValue == nullptr || otherValue->Compare(propertyValue) != 0) { propertyEditorValue = "<different values>"; break; } } // and update the property editor propertyEditor->UpdatePropertyValue(propertyName, propertyEditorValue); // this may be a position-related property, so update the selection bounds/axis UpdateSelectionBounds(); UpdateSelectionAxis(); } } void EditorEntityEditMode::SetPropertyOnSelection(const char *propertyName, const char *propertyValue) { EditorMapWindow *pMapWindow = m_pMap->GetMapWindow(); EditorPropertyEditorWidget *propertyEditor = pMapWindow->GetUI()->propertyEditor; if (m_selectedEntities.GetSize() == 0) return; // handle case of components if (m_selectedEntities.GetSize() == 1 && m_selectedComponentIndex >= 0) { m_selectedEntities[0]->SetComponentPropertyValue(m_selectedComponentIndex, propertyName, propertyValue); } else { // this makes it easier, applying it to all. for (uint32 i = 0; i < m_selectedEntities.GetSize(); i++) m_selectedEntities[i]->SetEntityPropertyValue(propertyName, propertyValue); } // in edit mode? update property editor if (pMapWindow->GetEditMode() == EDITOR_EDIT_MODE_ENTITY) propertyEditor->UpdatePropertyValue(propertyName, propertyValue); // fix up selection bounds and redraw UpdateSelectionBounds(); UpdateSelectionAxis(); pMapWindow->RedrawAllViewports(); } EditorMapEntity *EditorEntityEditMode::CreateEntityUsingViewport(EditorMapViewport *pViewport, const char *typeName) { // create the entity EditorMapEntity *pEntity = m_pMap->CreateEntity(typeName); if (pEntity == nullptr) return nullptr; // determine position // fixme: use proper position float3 entityPosition = pViewport->GetViewController().GetCameraPosition() + (pViewport->GetViewController().GetCameraForwardDirection() * 3.0f); // set position property SmallString positionString; StringConverter::Float3ToString(positionString, entityPosition); pEntity->SetEntityPropertyValue("Position", positionString); // clear & set the selection to this new entity ClearSelection(); AddSelection(pEntity); // set focus to that viewport pViewport->SetFocus(); // done m_pMap->RedrawAllViewports(); return pEntity; } void EditorEntityEditMode::MoveViewportCameraToEntity(EditorMapViewport *pViewport, const EditorMapEntity *pEntity, const Quaternion cameraRotation /* = Quaternion::FromEulerAngles(Math::DegreesToRadians(-45.0f) , 0.0f, 0.0f)*/) { DebugAssert(pEntity != nullptr); // find the maximum dimension from the bounding box float3 boxExtents(pEntity->GetBoundingBox().GetExtents()); float viewDistance = Max(1.0f, Max(boxExtents.x, Max(boxExtents.y, boxExtents.z))) * 2.0f; // calculate eye position float3 moveVector(cameraRotation * float3::UnitY); float3 eyePosition(pEntity->GetBoundingBox().GetCenter() - moveVector * viewDistance); // set camera position pViewport->GetViewController().SetCameraPosition(eyePosition); // if perspective, set the rotation if (pViewport->GetViewController().GetCameraMode() == EDITOR_CAMERA_MODE_PERSPECTIVE) pViewport->GetViewController().SetCameraRotation(cameraRotation); } void EditorEntityEditMode::UpdatePropertyEditor() { EditorPropertyEditorWidget *propertyEditor = m_pMap->GetMapWindow()->GetUI()->propertyEditor; // clear the property editor propertyEditor->ClearProperties(); // got any selection? if (m_selectedEntities.GetSize() == 0) { m_ui->selectionTitleText->setText(QStringLiteral("No selection")); m_ui->selectionComponents->clear(); m_ui->selectionComponents->setEnabled(false); m_ui->actionAddComponent->setEnabled(false); m_ui->actionRemoveComponent->setEnabled(false); m_ui->actionSelectionLayers->setEnabled(false); return; } // single selection? if (m_selectedEntities.GetSize() == 1) { // just add all properties from this const EditorMapEntity *pEntity = m_selectedEntities[0]; const MapSourceEntityData *pEntityData = pEntity->GetEntityData(); const ObjectTemplate *pTemplate = pEntity->GetTemplate(); // and set all the values for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pProperty = pTemplate->GetPropertyDefinition(i); const String *propertyValue = pEntity->GetEntityData()->GetPropertyValuePointer(pProperty->GetName()); if (propertyValue == nullptr) propertyValue = &pProperty->GetDefaultValue(); propertyEditor->AddProperty(pProperty, *propertyValue); } // build title text LargeString titleText; titleText.AppendFormattedString("<strong>%s</strong>&nbsp;(%s)<br>", pEntity->GetEntityData()->GetEntityName().GetCharArray(), pEntity->GetTemplate()->GetTypeName().GetCharArray()); titleText.AppendString(pEntity->GetTemplate()->GetDescription()); // update ui m_ui->selectionTitleText->setText(ConvertStringToQString(titleText)); m_ui->selectionComponents->setEnabled(true); m_ui->actionAddComponent->setEnabled(true); m_ui->actionRemoveComponent->setEnabled(true); m_ui->actionSelectionLayers->setEnabled(true); // update component list m_selectedComponentIndex = -1; m_ui->selectionComponents->clear(); for (uint32 componentIndex = 0; componentIndex < pEntityData->GetComponentCount(); componentIndex++) { const MapSourceEntityComponent *pComponent = pEntityData->GetComponentByIndex(componentIndex); SmallString componentListItemName; componentListItemName.Format("%s (%s)", pComponent->GetComponentName().GetCharArray(), pComponent->GetTypeName().GetCharArray()); /*m_ui->selectionComponents->addItem(*/new QListWidgetItem(ConvertStringToQString(componentListItemName), m_ui->selectionComponents); } } else { // add all properties from the first entity to a temporary list PODArray<const PropertyTemplateProperty *> propertyList; { const EditorMapEntity *pEntity = m_selectedEntities[0]; const ObjectTemplate *pTemplate = pEntity->GetTemplate(); for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) propertyList.Add(pTemplate->GetPropertyDefinition(i)); } // now remove any properties not present across the entire selection for (uint32 propertyIndex = 0; propertyIndex < propertyList.GetSize(); ) { const PropertyTemplateProperty *pProperty = propertyList[propertyIndex]; uint32 selectionIndex; for (selectionIndex = 0; selectionIndex < m_selectedEntities.GetSize(); selectionIndex++) { if (m_selectedEntities[selectionIndex]->GetTemplate()->GetPropertyDefinitionByName(pProperty->GetName()) == nullptr) break; } if (selectionIndex != m_selectedEntities.GetSize()) { // this property wasn't found, remove it propertyList.OrderedRemove(propertyIndex); continue; } else { // go to next propertyIndex++; continue; } } // add found properties to the editor, and update their values for (uint32 i = 0; i < propertyList.GetSize(); i++) { const PropertyTemplateProperty *pProperty = propertyList[i]; // get the value for the first selected entity String propertyValue = m_selectedEntities[0]->GetEntityData()->GetPropertyTable()->GetPropertyValueDefaultString(pProperty->GetName(), pProperty->GetDefaultValue()); // confirm that it matches the others for (uint32 j = 1; j < m_selectedEntities.GetSize(); j++) { String otherPropertyValue = m_selectedEntities[j]->GetEntityData()->GetPropertyTable()->GetPropertyValueDefaultString(pProperty->GetName(), pProperty->GetDefaultValue()); // check match if (propertyValue.Compare(otherPropertyValue) != 0) { // mismatch propertyValue = "<different values>"; break; } } // add it propertyEditor->AddProperty(pProperty, propertyValue); } // build title text m_ui->selectionTitleText->setText(ConvertStringToQString(SmallString::FromFormat("<strong>Multiple selection</strong>&nbsp;(%u objects)<br>", m_selectedEntities.GetSize()))); m_ui->selectionComponents->clear(); m_ui->selectionComponents->setEnabled(false); m_ui->actionAddComponent->setEnabled(false); m_ui->actionRemoveComponent->setEnabled(false); m_ui->actionSelectionLayers->setEnabled(false); } } void EditorEntityEditMode::UpdatePropertyEditorForComponent() { if (m_selectedEntities.GetSize() != 1 || m_selectedComponentIndex < 0) { UpdatePropertyEditor(); return; } EditorMapEntity *pEntity = m_selectedEntities[0]; if ((uint32)m_selectedComponentIndex >= pEntity->GetComponentCount()) { UpdatePropertyEditor(); return; } // get stuff const ObjectTemplate *pTemplate = pEntity->GetComponentTemplate(m_selectedComponentIndex); const MapSourceEntityComponent *pData = pEntity->GetComponentData(m_selectedComponentIndex); EditorPropertyEditorWidget *pPropertyEditor = m_pMap->GetMapWindow()->GetUI()->propertyEditor; // build title text LargeString titleText; titleText.AppendFormattedString("<strong>%s</strong>&nbsp;(%s)<br>", pData->GetComponentName().GetCharArray(), pTemplate->GetTypeName().GetCharArray()); titleText.AppendString(pTemplate->GetDescription()); m_ui->selectionTitleText->setText(ConvertStringToQString(titleText)); // add properties pPropertyEditor->ClearProperties(); for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pProperty = pTemplate->GetPropertyDefinition(i); const String *propertyValue = pData->GetPropertyValuePointer(pProperty->GetName()); if (propertyValue == nullptr) propertyValue = &pProperty->GetDefaultValue(); pPropertyEditor->AddProperty(pProperty, *propertyValue); } } bool EditorEntityEditMode::HandleResourceViewResourceActivatedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName) { // if we are dropping a static mesh, create an entity if (pResourceTypeInfo == OBJECT_TYPEINFO(StaticMesh)) { EditorMapEntity *pEntity = CreateEntityUsingViewport(m_pMap->GetMapWindow()->GetActiveViewport(), "StaticMeshBrush"); if (pEntity != nullptr) pEntity->SetEntityPropertyValue("StaticMeshName", resourceName); } return EditorEditMode::HandleResourceViewResourceActivatedEvent(pResourceTypeInfo, resourceName); } bool EditorEntityEditMode::HandleResourceViewResourceDroppedEvent(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName, const EditorMapViewport *pViewport, int32 x, int32 y) { return EditorEditMode::HandleResourceViewResourceDroppedEvent(pResourceTypeInfo, resourceName, pViewport, x, y); } <file_sep>/Engine/Source/Renderer/WorldRenderers/CSMShadowMapRenderer.h #pragma once #include "Renderer/Renderer.h" #include "Renderer/RenderQueue.h" class Camera; class RenderWorld; class CSMShadowMapRenderer { public: // maximum number of splits per shadow map enum { MaxCascadeCount = 3 }; // shadow map data structure struct ShadowMapData { bool IsActive; GPUTexture2D *pShadowMapTexture; GPUDepthStencilBufferView *pShadowMapDSV; uint32 CascadeCount; float4x4 ViewProjectionMatrices[MaxCascadeCount]; float CascadeFrustumEyeSpaceDepths[MaxCascadeCount]; }; public: CSMShadowMapRenderer(uint32 shadowMapResolution = 256, PIXEL_FORMAT shadowMapFormat = PIXEL_FORMAT_D16_UNORM, uint32 cascadeCount = 3, float splitLambda = 0.95f); virtual ~CSMShadowMapRenderer(); // getters const uint32 GetShadowMapResolution() const { return m_shadowMapResolution; } const PIXEL_FORMAT GetShadowMapFormat() const { return m_shadowMapFormat; } const uint32 GetCascadeCount() const { return m_cascadeCount; } float GetSplitLambda() const { return m_splitLambda; } // allocator bool AllocateShadowMap(ShadowMapData *pShadowMapData); void FreeShadowMap(ShadowMapData *pShadowMapData); // drawer void DrawShadowMap(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); private: // calculate split depths, store in m_splitDepths void CalculateSplitDepths(const Camera *pViewCamera, float shadowDistance); // fill temporary variables void CalculateViewDependantVariables(const Camera *pViewCamera); // build the camera for this split void BuildCascadeCamera(Camera *pOutCascadeCamera, const Camera *pViewCamera, const float3 &lightDirection, uint32 splitIndex, uint32 splitCount, float lambda, float shadowDrawDistance, const RenderWorld *pRenderWorld); // draw using multipass technique void DrawMultiPass(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); // in vars uint32 m_shadowMapResolution; PIXEL_FORMAT m_shadowMapFormat; uint32 m_cascadeCount; float m_splitLambda; // temp vars float m_splitDepths[MaxCascadeCount + 1]; float3 m_frustumCornersVS[8]; // render queue RenderQueue m_renderQueue; }; <file_sep>/Engine/Source/ContentConverter/PrecompiledHeader.cpp #include "ContentConverter/PrecompiledHeader.h" <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphNodeType.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphNodeType.h" ShaderGraphNodeTypeInfo::ShaderGraphNodeTypeInfo(const char *Name, const ObjectTypeInfo *pParentType, const PROPERTY_DECLARATION *pPropertyDeclarations, const SHADER_GRAPH_NODE_INPUT *pInputs, const SHADER_GRAPH_NODE_OUTPUT *pOutputs, const char *ShortName, const char *Description, ObjectFactory *pFactory) : ObjectTypeInfo(Name, pParentType, pPropertyDeclarations, pFactory), m_szShortName(ShortName), m_szDescription(Description), m_nInputs(0), m_pInputs(pInputs), m_nOutputs(0), m_pOutputs(pOutputs) { if (m_pInputs != NULL) { for (; m_pInputs[m_nInputs].Name != NULL; m_nInputs++); } if (m_pOutputs != NULL) { for (; m_pOutputs[m_nOutputs].Name != NULL; m_nOutputs++); } } ShaderGraphNodeTypeInfo::~ShaderGraphNodeTypeInfo() { //DebugAssert(m_iTypeIndex == INVALID_TYPE_INDEX); } <file_sep>/Engine/Source/Engine/Map.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Map.h" #include "Engine/EngineCVars.h" #include "Engine/DataFormats.h" #include "Engine/ResourceManager.h" #include "Engine/Camera.h" #include "Engine/TerrainSection.h" #include "Engine/TerrainSectionCollisionShape.h" #include "Engine/TerrainRenderer.h" #include "Engine/World.h" #include "Engine/Entity.h" #include "Engine/Brush.h" #include "Engine/Component.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/StaticMesh.h" #include "Renderer/Renderer.h" #include "Renderer/RenderWorld.h" #include "Core/ClassTable.h" #include "YBaseLib/ZipArchive.h" Log_SetChannel(Map); Map::Map() : m_pMapArchive(nullptr), m_pClassTable(nullptr), m_pWorld(nullptr), m_pTerrainLayerList(nullptr), m_pTerrainRenderer(nullptr) { } Map::~Map() { UnloadAllRegions(); // we don't call the remove method for terrain entities since they'll be dropped in the remove queue // anyway, but they'll be cleaned up when the world is deleted delete m_pWorld; if (m_pTerrainRenderer != nullptr) delete m_pTerrainRenderer; if (m_pTerrainLayerList != nullptr) m_pTerrainLayerList->Release(); delete m_pClassTable; delete m_pMapArchive; } const int2 Map::GetRegionForPosition(const float3 &position) const { return int2((Math::Truncate(position.x) / (int32)m_regionSize) - ((position.x < 0.0f) ? 1 : 0), (Math::Truncate(position.y) / (int32)m_regionSize) - ((position.y < 0.0f) ? 1 : 0)); } const uint32 Map::GetWorldEntityIdForMapEntityName(const char *mapEntityName) { CIStringHashTable<uint32>::Member *pMember = m_mapEntityNameMapping.Find(mapEntityName); return (pMember != nullptr) ? pMember->Value : 0; } bool Map::LoadMap(const char *mapName, const float3 *pInitialPositionOverride, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { PathString fileName; PathString resourceName; AutoReleasePtr<ByteStream> pArchiveStream; Timer loadTimer; pProgressCallbacks->SetCancellable(false); pProgressCallbacks->SetStatusText("Loading map..."); pProgressCallbacks->SetProgressRange(1); pProgressCallbacks->SetProgressValue(0); fileName.Format("%s.cmap", mapName); if (!g_pVirtualFileSystem->GetFileName(fileName) || (pArchiveStream = g_pVirtualFileSystem->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE)) == NULL || (m_pMapArchive = ZipArchive::OpenArchiveReadOnly(pArchiveStream)) == NULL) { Log_ErrorPrintf("Map::LoadMap: Could not open file '%s'", fileName.GetCharArray()); return false; } // get map name m_mapName = fileName.SubString(0, -5); // map header DF_MAP_HEADER mapHeader; { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(DF_MAP_HEADER_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_ErrorPrintf("Map::LoadMap: Could not open " DF_MAP_HEADER_FILENAME " in zipfile '%s'", fileName.GetCharArray()); return false; } // parse the map header if (!pStream->Read2(&mapHeader, sizeof(mapHeader)) || mapHeader.Version != DF_MAP_HEADER_VERSION || mapHeader.HeaderSize != sizeof(mapHeader)) { Log_ErrorPrintf("Map::LoadMap: Invalid header"); return false; } } // load the class table { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(DF_MAP_CLASS_TABLE_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { Log_ErrorPrintf("Map::LoadMap: Could not open " DF_MAP_CLASS_TABLE_FILENAME " in zipfile '%s'", fileName.GetCharArray()); return false; } m_pClassTable = new ClassTable(); if (!m_pClassTable->LoadFromStream(pStream, false)) { Log_ErrorPrintf("Map::LoadMap: Failed to load class table in map '%s'.", fileName.GetCharArray()); return false; } } // create world m_pWorld = new DynamicWorld(); // initialize fields m_regionSize = mapHeader.RegionSize; m_regionLODLevels = mapHeader.RegionLODLevels; m_regionLoadRadius = mapHeader.RegionLoadRadius; m_regionActivationRadius = mapHeader.RegionActivationRadius; m_mapBounds.SetBounds(float3(mapHeader.WorldBoundingBoxMin), float3(mapHeader.WorldBoundingBoxMax)); // log messages Log_InfoPrintf("Map::LoadMap: Map '%s' starting creation, bounds are (%f, %f, %f - %f %f %f)", mapName, m_mapBounds.GetMinBounds().x, m_mapBounds.GetMinBounds().y, m_mapBounds.GetMinBounds().z, m_mapBounds.GetMaxBounds().x, m_mapBounds.GetMaxBounds().y, m_mapBounds.GetMaxBounds().z); Log_DevPrintf("Region size is %u units", m_regionSize); Log_DevPrintf("Map has %u levels of detail per region", m_regionLODLevels); Log_DevPrintf("Loading radius is %u regions", m_regionLoadRadius); Log_DevPrintf("Activation radius is %u regions", m_regionActivationRadius); // has regions? if (mapHeader.HasRegions) { pProgressCallbacks->SetStatusText("Loading regions..."); if (!LoadRegionsHeader(pProgressCallbacks)) return false; } // has terrain? if (mapHeader.HasTerrain) { pProgressCallbacks->SetStatusText("Loading terrain..."); if (!LoadTerrainHeader(pProgressCallbacks)) return false; } pProgressCallbacks->SetProgressValue(3); // has global entities? if (mapHeader.HasGlobalEntities) { pProgressCallbacks->SetStatusText("Loading global entities..."); if (!LoadGlobalEntities(pProgressCallbacks)) return false; } // starting position: todo move to map header float3 initialStreamingPosition((pInitialPositionOverride != nullptr) ? *pInitialPositionOverride : float3::Zero); pProgressCallbacks->SetStatusText("Loading starting regions..."); pProgressCallbacks->PushState(); m_pWorld->AddObserver(this, initialStreamingPosition); HandleStreaming(pProgressCallbacks); m_pWorld->RemoveObserver(this); pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(1); // done Log_InfoPrintf("Map '%s' loaded in %.4f seconds", mapName, loadTimer.GetTimeSeconds()); return true; } void Map::LoadAllRegions(ProgressCallbacks *pProgressCallbacks /*= ProgressCallbacks::NullProgressCallback*/) { pProgressCallbacks->SetProgressRange(m_regions.GetMemberCount()); pProgressCallbacks->SetProgressValue(0); uint32 progressValue = 0; for (MapRegionTable::Iterator itr = m_regions.Begin(); !itr.AtEnd(); itr.Forward()) { Vector2i regionPosition(itr->Key); MapRegion *pRegion = itr->Value; if (!pRegion->IsLoaded()) { pProgressCallbacks->SetFormattedStatusText("Loading region (%i, %i)", pRegion->GetRegionX(), pRegion->GetRegionY()); pProgressCallbacks->PushState(); if (!LoadRegion(regionPosition.x, regionPosition.y, pProgressCallbacks)) { Log_WarningPrintf("Map::LoadAllRegions: Failed to load region (%i, %i)", regionPosition.x, regionPosition.y); pProgressCallbacks->PopState(); continue; } pProgressCallbacks->PopState(); } pProgressCallbacks->SetProgressValue(++progressValue); } } void Map::UnloadAllRegions() { for (MapRegionTable::Iterator itr = m_regions.Begin(); !itr.AtEnd(); itr.Forward()) { Vector2i regionPosition(itr->Key); MapRegion *pRegion = itr->Value; if (pRegion->IsLoaded()) UnloadRegion(regionPosition.x, regionPosition.y); } } void Map::HandleStreaming(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { const uint32 observerCount = m_pWorld->GetObserverCount(); if (observerCount == 0) return; const int32 loadRadius = (int32)m_regionLoadRadius; pProgressCallbacks->SetProgressRange(m_regions.GetMemberCount()); pProgressCallbacks->SetProgressValue(0); // get region for camera position int2 *pObserverRegions = (int2 *)alloca(sizeof(int2) * observerCount); for (uint32 i = 0; i < observerCount; i++) pObserverRegions[i] = GetRegionForPosition(m_pWorld->GetObserverLocation(i)); // load any regions that are within distance of the camera, unload anything that's not for (MapRegionTable::Iterator itr = m_regions.Begin(); !itr.AtEnd(); itr.Forward()) { const int2 &regionPosition = itr->Key; int32 regionsFromCamera = Y_INT32_MAX; for (uint32 i = 0; i < observerCount; i++) regionsFromCamera = Min(regionsFromCamera, Max(Math::Abs(pObserverRegions[i].x - regionPosition.x), Math::Abs(pObserverRegions[i].y - regionPosition.y))); // determine the lod level applicable for this region int32 lodLevelForRegion; int32 maxLoadDistance = loadRadius; for (lodLevelForRegion = 0; lodLevelForRegion < (int32)m_regionLODLevels; lodLevelForRegion++) { if (regionsFromCamera <= maxLoadDistance) break; if (maxLoadDistance == 1) maxLoadDistance++; else maxLoadDistance *= maxLoadDistance; } // out of range? if (lodLevelForRegion == (int32)m_regionLODLevels) lodLevelForRegion = -1; const MapRegion *pRegion = itr->Value; DebugAssert(pRegion != NULL); // matches? if (pRegion->GetLoadedLODLevel() == lodLevelForRegion) continue; // switch the lod level Log_PerfPrintf("Map::HandleStreaming: Region (%i, %i) transitioning from LOD %i to %i...", regionPosition.x, regionPosition.y, pRegion->GetLoadedLODLevel(), lodLevelForRegion); if (!ChangeRegionLOD(regionPosition.x, regionPosition.y, lodLevelForRegion)) { Log_WarningPrintf("Map::HandleStreaming: Failed to transition region (%i, %i) from LOD %i to %i", regionPosition.x, regionPosition.y, pRegion->GetLoadedLODLevel(), lodLevelForRegion); continue; } pProgressCallbacks->IncrementProgressValue(); } } bool Map::LoadRegionsHeader(ProgressCallbacks *pProgressCallbacks) { // read header AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(DF_MAP_REGIONS_HEADER_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; DF_MAP_REGIONS_HEADER regionsHeader; if (!pStream->Read2(&regionsHeader, sizeof(regionsHeader)) || regionsHeader.HeaderSize != sizeof(regionsHeader)) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadMap: Invalid regions header"); return false; } for (uint32 i = 0; i < regionsHeader.RegionCount; i++) { int2 regionCoordinates; if (!pStream->Read2(&regionCoordinates, sizeof(int2))) return false; DebugAssert(m_regions.Find(regionCoordinates) == nullptr); MapRegion *pRegion = new MapRegion(this, regionCoordinates.x, regionCoordinates.y); m_regions.Insert(regionCoordinates, pRegion); } return true; } bool Map::LoadTerrainHeader(ProgressCallbacks *pProgressCallbacks) { PathString fileName; // read header { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(DF_MAP_TERRAIN_HEADER_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; DF_MAP_TERRAIN_HEADER terrainHeader; if (!pStream->Read2(&terrainHeader, sizeof(terrainHeader)) || terrainHeader.HeaderSize != sizeof(terrainHeader)) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadTerrainHeader: Invalid terrain header"); return false; } // fill in terrain parameters m_terrainParameters.HeightStorageFormat = (TERRAIN_HEIGHT_STORAGE_FORMAT)terrainHeader.HeightStorageFormat; m_terrainParameters.MinHeight = terrainHeader.MinHeight; m_terrainParameters.MaxHeight = terrainHeader.MaxHeight; m_terrainParameters.BaseHeight = terrainHeader.BaseHeight; m_terrainParameters.Scale = terrainHeader.Scale; m_terrainParameters.SectionSize = terrainHeader.SectionSize; m_terrainParameters.LODCount = terrainHeader.LODCount; if (!TerrainUtilities::IsValidParameters(&m_terrainParameters)) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadTerrainHeader: Invalid terrain parameters"); return false; } } // load layer list { fileName.Format("%s", DF_MAP_TERRAIN_LAYERS_FILENAME_PREFIX); // since this layer list is a chunked file, it needs to be seekable AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; // load it TerrainLayerList *pTerrainLayerList = new TerrainLayerList(); if (!pTerrainLayerList->Load(fileName, pStream)) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadTerrainHeader: Could not load terrain layers"); pTerrainLayerList->Release(); return false; } m_pTerrainLayerList = pTerrainLayerList; } // create terrain renderer if (g_pRenderer != nullptr) { m_pTerrainRenderer = TerrainRenderer::CreateTerrainRenderer(&m_terrainParameters, m_pTerrainLayerList); if (m_pTerrainRenderer == nullptr) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadTerrainHeader: Failed to create terrain renderer"); return false; } } // ok return true; } bool Map::LoadGlobalEntities(ProgressCallbacks *pProgressCallbacks) { AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(DF_MAP_GLOBAL_ENTITIES_FILENAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; DF_MAP_GLOBAL_ENTITIES_HEADER globalEntitiesHeader; if (!pStream->Read2(&globalEntitiesHeader, sizeof(globalEntitiesHeader)) || globalEntitiesHeader.HeaderSize != sizeof(globalEntitiesHeader)) { pProgressCallbacks->DisplayFormattedModalError("Map::LoadMap: Invalid regions header"); return false; } // create the entities, no need to track the ids CreateEntitiesFromStream(pStream, globalEntitiesHeader.EntityCount, globalEntitiesHeader.EntityDataSize, nullptr, nullptr, ProgressCallbacks::NullProgressCallback); // all good return true; } uint32 Map::CreateEntitiesFromStream(ByteStream *pStream, uint32 entityCount, uint32 entityDataSize, PODArray<uint32> *pOutDynamicEntityIDArray, PODArray<Brush *> *pOutStaticObjectsArray, ProgressCallbacks *pProgressCallbacks) { SmallString objectName; SmallString componentName; // create reader BinaryReader binaryReader(pStream); // initalize progress pProgressCallbacks->SetProgressRange(entityCount); pProgressCallbacks->SetProgressValue(0); // iterate over entities uint32 createdEntityCount = 0; for (uint32 i = 0; i < entityCount; i++) { DF_MAP_ENTITY_HEADER entityHeader; if (!binaryReader.SafeReadType(&entityHeader) || entityHeader.HeaderSize != sizeof(entityHeader)) return createdEntityCount; // calculate offset to next entity uint64 nextEntityOffset = binaryReader.GetStreamPosition() + entityHeader.EntitySize + entityHeader.ComponentsSize; // read the entity name if (!binaryReader.SafeReadFixedString(entityHeader.EntityNameLength, &objectName)) return createdEntityCount; // deserialize the entity object Object *pObject = m_pClassTable->UnserializeObject(pStream, entityHeader.EntityTypeIndex); if (pObject == nullptr) { // creation failed.. or corruption.. could be either. pProgressCallbacks->DisplayFormattedWarning("Failed to deserialize object '%s' (type index %u)", objectName.GetCharArray(), entityHeader.EntityTypeIndex); if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; else continue; } // should be the correct type if (pObject->IsDerived(OBJECT_TYPEINFO(Brush))) { Brush *pBrush = pObject->Cast<Brush>(); // shouldn't have any components if (entityHeader.ComponentCount > 0) { pProgressCallbacks->DisplayFormattedWarning("Brush '%s' has components on a brush type.", objectName.GetCharArray()); pBrush->Release(); if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; else continue; } // finalize it if (!pBrush->Initialize()) { pProgressCallbacks->DisplayFormattedWarning("Failed to initialize Brush '%s'.", objectName.GetCharArray()); pBrush->Release(); if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; else continue; } // store it if (pOutStaticObjectsArray != nullptr) { pBrush->AddRef(); pOutStaticObjectsArray->Add(pBrush); } // and add it to the world m_pWorld->AddBrush(pBrush); pBrush->Release(); createdEntityCount++; } else if (pObject->IsDerived(OBJECT_TYPEINFO(Entity))) { Entity *pEntity = pObject->Cast<Entity>(); uint32 entityID = m_pWorld->AllocateEntityID(); // construct the entity if (!pEntity->Initialize(entityID, objectName)) { pProgressCallbacks->DisplayFormattedWarning("Failed to initialize Entity '%s'.", objectName.GetCharArray()); pEntity->Release(); if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; else continue; } // deserialize any components for (uint32 componentIndex = 0; componentIndex < entityHeader.ComponentCount; componentIndex++) { DF_MAP_ENTITY_COMPONENT_HEADER componentHeader; if (!binaryReader.SafeReadType(&componentHeader)) { pEntity->Release(); return createdEntityCount; } // calc offset to next component uint64 nextComponentOffset = binaryReader.GetStreamPosition() + componentHeader.ComponentSize; // read component name if (!binaryReader.SafeReadFixedString(componentHeader.ComponentNameLength, &componentName)) { pEntity->Release(); return createdEntityCount; } // deserialize the component object Object *pComponentObject = m_pClassTable->UnserializeObject(pStream, componentHeader.ComponentTypeIndex); if (pComponentObject == nullptr) { pProgressCallbacks->DisplayFormattedWarning("Failed to deserialize component '%s' of entity '%s'.", componentName.GetCharArray(), objectName.GetCharArray()); if (!binaryReader.SafeSeekAbsolute(nextComponentOffset)) { pEntity->Release(); return createdEntityCount; } else { continue; } } // if not a component, skip it if (!pComponentObject->IsDerived(OBJECT_TYPEINFO(Component))) { pProgressCallbacks->DisplayFormattedWarning("Failed to deserialize component '%s' of entity '%s' is an invalid type '%s'.", componentName.GetCharArray(), objectName.GetCharArray(), pComponentObject->GetObjectTypeInfo()->GetTypeName()); pComponentObject->GetObjectTypeInfo()->GetFactory()->DeleteObject(pComponentObject); if (!binaryReader.SafeSeekAbsolute(nextComponentOffset)) { pEntity->Release(); return createdEntityCount; } else { continue; } } // initialize the component Component *pComponent = pComponentObject->Cast<Component>(); if (!pComponent->Initialize()) { pProgressCallbacks->DisplayFormattedWarning("Failed to initialize Component '%s' of entity '%s'.", componentName.GetCharArray(), objectName.GetCharArray()); pComponent->Release(); if (!binaryReader.SafeSeekAbsolute(nextComponentOffset)) { pEntity->Release(); return createdEntityCount; } else { continue; } } // add it to the entity pEntity->AddComponent(pComponent); pComponent->Release(); // seek to next if (!binaryReader.SafeSeekAbsolute(nextComponentOffset)) { pEntity->Release(); return createdEntityCount; } } if (pOutDynamicEntityIDArray != nullptr) pOutDynamicEntityIDArray->Add(pEntity->GetEntityID()); m_pWorld->AddEntity(pEntity); createdEntityCount++; pEntity->Release(); } else { pProgressCallbacks->DisplayFormattedWarning("Object '%s' is an invalid type '%s'.", objectName.GetCharArray(), pObject->GetObjectTypeInfo()->GetTypeName()); pObject->GetObjectTypeInfo()->GetFactory()->DeleteObject(pObject); if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; else continue; } // seek to the next object if (!binaryReader.SafeSeekAbsolute(nextEntityOffset)) return createdEntityCount; } // ok return createdEntityCount; } bool Map::LoadRegion(int32 regionX, int32 regionY, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { int2 regionPosition(regionX, regionY); MapRegionTable::Member *pMember = m_regions.Find(regionPosition); if (pMember == NULL) { Log_WarningPrintf("Map::LoadRegion: Attempting to load unknown region (%i, %i)", regionX, regionY); return false; } MapRegion *pRegion = pMember->Value; if (!pRegion->IsLoaded()) { PathString fileName; fileName.Format("region_%i_%i.0", regionX, regionY); AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == NULL) { Log_WarningPrintf("Map::LoadRegion: Could not open region file for (%i, %i) '%s'", regionX, regionY, fileName.GetCharArray()); return false; } if (!pRegion->LoadRegion(pStream, 0, pProgressCallbacks)) { Log_WarningPrintf("Map::LoadRegion: Could not load region (%i, %i)", regionX, regionY); //pRegion->UnloadRegion(); return false; } } return true; } bool Map::ChangeRegionLOD(int32 regionX, int32 regionY, int32 newLOD, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { int2 regionPosition(regionX, regionY); MapRegionTable::Member *pMember = m_regions.Find(regionPosition); if (pMember == NULL) { Log_WarningPrintf("Map::ChangeRegionLOD: Attempting to load unknown region (%i, %i)", regionX, regionY); return false; } MapRegion *pRegion = pMember->Value; if (pRegion->GetLoadedLODLevel() == newLOD) return true; // changed Log_DevPrintf("Map::ChangeRegionLOD: Region (%i, %i) LOD %i -> %i", regionX, regionY, pRegion->GetLoadedLODLevel(), newLOD); // unload old data if (pRegion->IsLoaded()) pRegion->UnloadRegion(); // handle new data if (newLOD >= 0) { PathString fileName; fileName.Format("region_%i_%i.%u", regionX, regionY, newLOD); AutoReleasePtr<ByteStream> pStream = m_pMapArchive->OpenFile(fileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == NULL) { Log_WarningPrintf("Map::LoadRegion: Could not open region file for (%i, %i, LOD %i), '%s'", regionX, regionY, newLOD, fileName.GetCharArray()); return false; } if (!pRegion->LoadRegion(pStream, (uint32)newLOD, pProgressCallbacks)) { Log_WarningPrintf("Map::LoadRegion: Could not load region (%i, %i, LOD %i)", regionX, regionY, newLOD); //pRegion->UnloadRegion(); return false; } } return true; } void Map::UnloadRegion(int32 regionX, int32 regionY) { int2 regionPosition(regionX, regionY); MapRegionTable::Member *pMember = m_regions.Find(regionPosition); if (pMember == NULL) { Log_WarningPrintf("Map::UnloadRegion: Attempting to unload unknown region (%i, %i)", regionX, regionY); return; } MapRegion *pRegion = pMember->Value; if (pRegion->IsLoaded()) pRegion->UnloadRegion(); } MapRegion::MapRegion(Map *pMap, int32 regionX, int32 regionY) : m_pMap(pMap), m_regionX(regionX), m_regionY(regionY), m_loadedLODLevel(-1) { } MapRegion::~MapRegion() { } bool MapRegion::LoadRegion(ByteStream *pStream, uint32 lodLevel, ProgressCallbacks *pProgressCallbacks) { uint64 nextChunkPosition; DebugAssert(m_loadedLODLevel < 0); // prevent any double loading m_loadedLODLevel = (int32)lodLevel; // load header DF_MAP_REGION_HEADER regionHeader; if (!pStream->Read2(&regionHeader, sizeof(regionHeader)) || regionHeader.HeaderSize != sizeof(regionHeader)) { Log_ErrorPrintf("MapRegion::LoadRegion: Invalid region header"); return false; } // bit of validation if (regionHeader.RegionX != m_regionX || regionHeader.RegionY != m_regionY || regionHeader.LODLevel != lodLevel) { Log_ErrorPrintf("MapRegion::LoadRegion: Invalid region header"); return false; } // read terrain sections nextChunkPosition = pStream->GetPosition() + (uint64)regionHeader.TerrainDataSize; if (regionHeader.TerrainSectionCount > 0) { for (uint32 i = 0; i < regionHeader.TerrainSectionCount; i++) { DF_MAP_REGION_TERRAIN_SECTION_HEADER terrainSectionHeader; if (!pStream->Read2(&terrainSectionHeader, sizeof(terrainSectionHeader))) { Log_ErrorPrintf("MapRegion::LoadRegion: Failed to read terrain section header."); return false; } TerrainSection *pTerrainSection = new TerrainSection(&m_pMap->m_terrainParameters, terrainSectionHeader.SectionX, terrainSectionHeader.SectionY, terrainSectionHeader.LODLevel); if (!pTerrainSection->LoadFromStream(pStream)) { Log_ErrorPrintf("MapRegion::LoadRegion: Failed to load terrain section."); delete pTerrainSection; return false; } // remove me if (terrainSectionHeader.SectionX == 0 && terrainSectionHeader.SectionY == 0) { AutoReleasePtr<const StaticMesh> pStaticMesh = g_pResourceManager->GetStaticMesh("models/terrain/grass_blades"); int32 idx = pTerrainSection->AddDetailMesh(pStaticMesh, 30.0f); const uint32 XN = 200; const uint32 YN = 300; for (uint32 x = 0; x < XN; x++) { for (uint32 y = 0; y < YN; y++) { pTerrainSection->AddDetailMeshInstance(idx, x / (float)XN, y / (float)YN, 1.0f, (float)((x * y) % 360)); } } } // create data struct RegionTerrainSection sectionData; sectionData.pData = pTerrainSection; // create collision shape and insert the object, the translation is the base position of the section with no height modification sectionData.pCollisionShape = new TerrainSectionCollisionShape(&m_pMap->m_terrainParameters, pTerrainSection); sectionData.pCollisionObject = new Physics::StaticObject(0, sectionData.pCollisionShape, TerrainSectionCollisionShape::GetSectionTransform(&m_pMap->m_terrainParameters, pTerrainSection)); m_pMap->m_pWorld->GetPhysicsWorld()->AddObject(sectionData.pCollisionObject); // create renderer if (m_pMap->m_pTerrainRenderer != nullptr) { sectionData.pRenderProxy = m_pMap->m_pTerrainRenderer->CreateSectionRenderProxy(0, pTerrainSection); if (sectionData.pRenderProxy == nullptr) Log_WarningPrintf("MapRegion::LoadRegion: Failed to create terrain section render proxy [%i, %i: %i, %i]", m_regionX, m_regionY, pTerrainSection->GetSectionX(), pTerrainSection->GetSectionY()); else m_pMap->m_pWorld->GetRenderWorld()->AddRenderable(sectionData.pRenderProxy); } else { sectionData.pRenderProxy = nullptr; } // store it m_terrainSections.Add(sectionData); } } // check position if (pStream->GetPosition() != nextChunkPosition && !pStream->SeekAbsolute(nextChunkPosition)) { Log_ErrorPrintf("MapRegion::LoadRegion: Stream not in correct position after terrain load, and seek failed."); return false; } // read entities nextChunkPosition = pStream->GetPosition() + (uint64)regionHeader.EntityDataSize; if (regionHeader.EntityCount > 0) { pProgressCallbacks->PushState(); m_pMap->CreateEntitiesFromStream(pStream, regionHeader.EntityCount, regionHeader.EntityDataSize, &m_loadedEntityIDs, &m_loadedStaticObjects, pProgressCallbacks); pProgressCallbacks->PopState(); } // check position if (pStream->GetPosition() != nextChunkPosition && !pStream->SeekAbsolute(nextChunkPosition)) { Log_ErrorPrintf("MapRegion::LoadRegion: Stream not in correct position after entity load, and seek failed."); return false; } // done return true; } void MapRegion::UnloadRegion() { // remove all static entities for (uint32 i = 0; i < m_loadedStaticObjects.GetSize(); i++) { Brush *pObject = m_loadedStaticObjects[i]; if (pObject->IsInWorld()) m_pMap->m_pWorld->RemoveBrush(pObject); else Log_WarningPrintf("MapRegion::UnloadRegion: StaticObject %p from region (%i, %i) was not in world at region unload time.", pObject, m_regionX, m_regionY); pObject->Release(); } m_loadedStaticObjects.Obliterate(); // remove dynamic entities // // unload all static entities // { // for (i = 0; i < m_loadedStaticEntities.GetSize(); i++) // { // uint32 mapStaticEntityId = m_loadedStaticEntities[i]; // uint32 worldStaticEntityId = m_pMap->GetWorldEntityIdForMapEntityId(mapStaticEntityId); // DebugAssert(worldStaticEntityId != 0); // // m_pMap->m_mapEntityIdMapping.Remove(mapStaticEntityId); // // Entity *pEntity = m_pMap->GetWorld()->GetEntityById(worldStaticEntityId); // DebugAssert(pEntity != NULL); // // m_pMap->GetWorld()->QueueRemoveEntity(pEntity); // } // } // remove terrain sections for (uint32 i = 0; i < m_terrainSections.GetSize(); i++) { RegionTerrainSection *pSection = &m_terrainSections[i]; if (pSection->pRenderProxy != nullptr) { m_pMap->m_pWorld->GetRenderWorld()->RemoveRenderable(pSection->pRenderProxy); pSection->pRenderProxy->Release(); } m_pMap->m_pWorld->GetPhysicsWorld()->RemoveObject(pSection->pCollisionObject); pSection->pCollisionObject->Release(); pSection->pCollisionShape->Release(); pSection->pData->Release(); } m_terrainSections.Obliterate(); m_loadedLODLevel = -1; } <file_sep>/Engine/Source/Core/RandomNumberGenerator.h #pragma once #include "Core/Common.h" #ifdef HAVE_SFMT // uses mersenne twister class RandomNumberGenerator { public: // constructor RandomNumberGenerator(); RandomNumberGenerator(uint32 seed); RandomNumberGenerator(const byte *pKey, uint32 keyLength); RandomNumberGenerator(const RandomNumberGenerator &copy); ~RandomNumberGenerator(); // reinitialize state void Reseed(); void Reseed(uint32 seed); void Reseed(const byte *pKey, uint32 keyLength); // copier RandomNumberGenerator &operator=(const RandomNumberGenerator &copy); // uniform-based generators uint32 NextUInt(); float NextUniformFloat(); double NextUniformDouble(); // gaussian i.e. -1 >= result <= 1 float NextGaussianFloat(); double NextGaussianDouble(); // range-based generators int32 NextRangeInt(int32 min, int32 max); uint32 NextRangeUInt(uint32 min, uint32 max); float NextRangeFloat(float min, float max); double NextRangeDouble(double min, double max); // test a chance-based number, chance is expected to be 0 >= chance <= 100 bool NextBoolean(float chance); private: void AllocateState(); void FreeState(); struct SFMT_T *m_state; }; #endif // HAVE_SFMT <file_sep>/Engine/Source/Renderer/VertexFactories/SkeletalMeshVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" class ShaderProgram; enum SKELETAL_MESH_VERTEX_FACTORY_FLAGS { SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS = (1 << 0), SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS = (1 << 1), SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING = (1 << 2), SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_0_ENABLED = (1 << 3), SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_1_ENABLED = (1 << 4), SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_2_ENABLED = (1 << 5), SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_3_ENABLED = (1 << 6) }; class SkeletalMeshVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(SkeletalMeshVertexFactory, VertexFactory); public: struct Vertex { float3 Position; float3 TangentX; float3 TangentY; float3 TangentZ; float2 TexCoord; uint32 Color; uint8 BoneIndices[4]; float BoneWeights[4]; }; public: static void SetBoneMatrices(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, uint32 firstBoneIndex, uint32 boneCount, const float3x4 *pBoneMatrices); static uint32 GetVertexSize(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags); static bool CreateVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, VertexBufferBindingArray *pVertexBufferBindingArray); static bool FillVerticesBuffer(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, const Vertex *pVertices, uint32 nVertices, void *pBuffer, uint32 cbBuffer); static void ShareVerticesBuffer(VertexBufferBindingArray *pDestinationVertexArray, const VertexBufferBindingArray *pSourceVertexArray) { ShareBuffers(pDestinationVertexArray, pSourceVertexArray, 0); } static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); }; <file_sep>/Engine/Source/Core/FIFVolume.cpp #include "Core/PrecompiledHeader.h" #include "Core/FIFVolume.h" #include "YBaseLib/BinaryReader.h" #include "YBaseLib/BinaryWriter.h" #include "YBaseLib/Timestamp.h" #include "YBaseLib/Log.h" #include "libfif/fif.h" Log_SetChannel(FIFVolume); // FIF IO functions mapped to ByteStream static int ByteStream_fif_io_read(fif_io_userdata userdata, void *buffer, unsigned int count) { ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); return (int)pStream->Read(buffer, count); } static int ByteStream_fif_io_write(fif_io_userdata userdata, const void *buffer, unsigned int count) { ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); return (int)pStream->Write(buffer, count); } static int64_t ByteStream_fif_io_seek(fif_io_userdata userdata, fif_offset_t offset, enum FIF_SEEK_MODE mode) { ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); bool res; if (mode == FIF_SEEK_MODE_CUR) res = pStream->SeekRelative(offset); else if (mode == FIF_SEEK_MODE_END) res = pStream->SeekToEnd(); else res = pStream->SeekAbsolute(offset); return (res) ? (fif_offset_t)pStream->GetPosition() : (fif_offset_t)FIF_ERROR_IO_ERROR; } static int ByteStream_fif_io_zero(fif_io_userdata userdata, fif_offset_t offset, unsigned int count) { ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); if (pStream->InErrorState()) return FIF_ERROR_IO_ERROR; uint64 oldOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(offset)) return FIF_ERROR_BAD_OFFSET; int written = 0; while (count > 0) { static const byte zeroes[128] = { 0 }; unsigned int writeCount = Min(count, (unsigned int)sizeof(zeroes)); uint32 writtenBlock = pStream->Write(zeroes, writeCount); if (writtenBlock != writeCount) break; written += writeCount; count -= writeCount; } pStream->SeekAbsolute(oldOffset); return written; } static int ByteStream_fif_io_ftruncate(fif_io_userdata userdata, fif_offset_t newsize) { // truncate right now will only increase the size ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); if (pStream->InErrorState()) return FIF_ERROR_IO_ERROR; if (newsize <= (int64_t)pStream->GetSize()) return FIF_ERROR_SUCCESS; fif_offset_t zeroCount = newsize - (fif_offset_t)pStream->GetSize(); return ((int64_t)ByteStream_fif_io_zero(userdata, (fif_offset_t)pStream->GetSize(), (unsigned int)zeroCount) == zeroCount) ? FIF_ERROR_SUCCESS : FIF_ERROR_IO_ERROR; } static int64_t ByteStream_fif_io_filesize(fif_io_userdata userdata) { ByteStream *pStream = reinterpret_cast<ByteStream *>(userdata); return (int64_t)pStream->GetSize(); } static void ByteStream_fif_io(ByteStream *pStream, fif_io *pIO) { pIO->io_read = ByteStream_fif_io_read; pIO->io_write = ByteStream_fif_io_write; pIO->io_seek = ByteStream_fif_io_seek; pIO->io_zero = ByteStream_fif_io_zero; pIO->io_ftruncate = ByteStream_fif_io_ftruncate; pIO->io_filesize = ByteStream_fif_io_filesize; pIO->userdata = reinterpret_cast<fif_io_userdata>(pStream); } class FIFFileStream : public ByteStream { public: FIFFileStream(FIFVolume *pFIFVolume, fif_mount_handle mountHandle, fif_file_handle fileHandle) : m_pFIFVolume(pFIFVolume), m_mountHandle(mountHandle), m_fileHandle(fileHandle) { } ~FIFFileStream() { fif_close(m_mountHandle, m_fileHandle); } virtual uint32 Read(void *pDestination, uint32 ByteCount) override { if (m_errorState) return 0; int readResult = fif_read(m_mountHandle, m_fileHandle, pDestination, ByteCount); if (readResult < 0) { m_errorState = true; return 0; } return (uint32)readResult; } virtual bool ReadByte(byte *pDestByte) override { return (Read(reinterpret_cast<void *>(pDestByte), sizeof(byte)) == sizeof(byte)); } virtual bool Read2(void *pDestination, uint32 ByteCount, uint32 *pNumberOfBytesRead = nullptr) override { uint32 nBytes = Read(pDestination, ByteCount); if (pNumberOfBytesRead != nullptr) *pNumberOfBytesRead = nBytes; return (nBytes == ByteCount); } virtual uint32 Write(const void *pSource, uint32 ByteCount) override { if (m_errorState) return false; int writeResult = fif_write(m_mountHandle, m_fileHandle, pSource, ByteCount); if (writeResult < 0) { Log_ErrorPrintf("fif_write error state: %i", writeResult); m_errorState = true; return 0; } return (uint32)writeResult; } virtual bool WriteByte(byte SourceByte) override { return (Write(&SourceByte, sizeof(SourceByte)) == sizeof(SourceByte)); } virtual bool Write2(const void *pSource, uint32 ByteCount, uint32 *pNumberOfBytesWritten = nullptr) override { uint32 nBytes = Write(pSource, ByteCount); if (pNumberOfBytesWritten != nullptr) *pNumberOfBytesWritten = nBytes; return (nBytes == ByteCount); } virtual bool SeekAbsolute(uint64 Offset) override { if (m_errorState) return false; fif_offset_t seekResult = fif_seek(m_mountHandle, m_fileHandle, (fif_offset_t)Offset, FIF_SEEK_MODE_SET); if (seekResult != (fif_offset_t)Offset) { m_errorState = true; return false; } return true; } virtual bool SeekRelative(int64 Offset) override { if (m_errorState) return false; fif_offset_t seekResult = fif_seek(m_mountHandle, m_fileHandle, (fif_offset_t)Offset, FIF_SEEK_MODE_CUR); if (seekResult < 0) { m_errorState = true; return false; } return true; } virtual bool SeekToEnd() override { if (m_errorState) return false; fif_offset_t seekResult = fif_seek(m_mountHandle, m_fileHandle, 0, FIF_SEEK_MODE_END); if (seekResult < 0) { m_errorState = true; return false; } return true; } virtual uint64 GetPosition() const override { return (uint32)fif_tell(m_mountHandle, m_fileHandle); } virtual uint64 GetSize() const override { fif_fileinfo fileInfo; return (fif_fstat(m_mountHandle, m_fileHandle, &fileInfo) != FIF_ERROR_SUCCESS) ? 0 : (uint64)fileInfo.size; } virtual bool Flush() override { return true; } virtual bool Discard() override { return false; } virtual bool Commit() override { return true; } private: FIFVolume *m_pFIFVolume; fif_mount_handle m_mountHandle; fif_file_handle m_fileHandle; }; FIFVolume::FIFVolume(ByteStream *pStream, ByteStream *pTraceStream, fif_mount_handle mountHandle) : m_pStream(pStream), m_pTraceStream(pTraceStream), m_mountHandle(mountHandle) { if (pStream != nullptr) pStream->AddRef(); if (pTraceStream != nullptr) pTraceStream->AddRef(); } FIFVolume::~FIFVolume() { int unmountResult = fif_unmount_volume(m_mountHandle); if (unmountResult != FIF_ERROR_SUCCESS) Panic("Failed to unmount volume"); if (m_pTraceStream != nullptr) m_pTraceStream->Release(); m_pStream->Release(); } bool FIFVolume::StatFile(const char *filename, FILESYSTEM_STAT_DATA *pStatData) const { // get fileinfo fif_fileinfo fileInfo; int result = fif_stat(m_mountHandle, filename, &fileInfo); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::StatFile: fif_stat() failed: %i", result); return false; } // convert attributes pStatData->Attributes = 0; if (fileInfo.attributes & FIF_FILE_ATTRIBUTE_DIRECTORY) pStatData->Attributes |= FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY; if (fileInfo.attributes & FIF_FILE_ATTRIBUTE_COMPRESSED) pStatData->Attributes |= FILESYSTEM_FILE_ATTRIBUTE_COMPRESSED; // remaining information pStatData->ModificationTime.SetUnixTimestamp(fileInfo.modify_timestamp); pStatData->Size = fileInfo.size; return true; } ByteStream *FIFVolume::OpenFile(const char *filename, uint32 openMode, uint32 compressionLevel /* = 6 */) { // translate open flags unsigned int fifOpenMode = 0; if (openMode & BYTESTREAM_OPEN_READ) fifOpenMode |= FIF_OPEN_MODE_READ; if (openMode & BYTESTREAM_OPEN_WRITE) fifOpenMode |= FIF_OPEN_MODE_WRITE; if (openMode & BYTESTREAM_OPEN_APPEND) fifOpenMode |= FIF_OPEN_MODE_APPEND; if (openMode & BYTESTREAM_OPEN_TRUNCATE) fifOpenMode |= FIF_OPEN_MODE_TRUNCATE; if (openMode & BYTESTREAM_OPEN_CREATE) fifOpenMode |= FIF_OPEN_MODE_CREATE; if (openMode & BYTESTREAM_OPEN_STREAMED) fifOpenMode |= FIF_OPEN_MODE_STREAMED; // todo: // - BYTESTREAM_OPEN_ATOMIC_UPDATE // - BYTESTREAM_OPEN_SEEKABLE // open file fif_file_handle fileHandle; int result = fif_open(m_mountHandle, filename, fifOpenMode, &fileHandle); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::OpenFile: fif_open() failed: %i", result); return nullptr; } // create stream return new FIFFileStream(this, m_mountHandle, fileHandle); } bool FIFVolume::DeleteFile(const char *filename) { // forward through int result = fif_unlink(m_mountHandle, filename); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::DeleteFile: fif_unlink() failed: %i", result); return false; } return true; } FIFVolume *FIFVolume::CreateVolume(ByteStream *pStream, ByteStream *pTraceStream /* = nullptr */) { // initialize io fif_io io; ByteStream_fif_io(pStream, &io); // fill default settings fif_volume_options volumeOptions; fif_mount_options mountOptions; fif_set_default_volume_options(&volumeOptions); fif_set_default_mount_options(&mountOptions); //volumeOptions.block_size = 16384 * 1024; mountOptions.new_file_compression_algorithm = FIF_COMPRESSION_ALGORITHM_ZLIB; mountOptions.new_file_compression_level = 6; // tracing? fif_mount_handle mountHandle; if (pTraceStream != nullptr) { // create trace io fif_io trace_io; ByteStream_fif_io(pTraceStream, &trace_io); // create the archive int result = fif_trace_create_volume(&mountHandle, &io, NULL, &volumeOptions, &mountOptions, &trace_io); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::CreateVolume: fif_trace_create_volume() failed: %i", result); return nullptr; } } else { // create the archive int result = fif_create_volume(&mountHandle, &io, NULL, &volumeOptions, &mountOptions); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::CreateVolume: fif_create_volume() failed: %i", result); return nullptr; } } // create volume return new FIFVolume(pStream, pTraceStream, mountHandle); } FIFVolume *FIFVolume::OpenVolume(ByteStream *pStream, ByteStream *pTraceStream /* = nullptr */) { // initialize io fif_io io; ByteStream_fif_io(pStream, &io); // fill default settings fif_mount_options mountOptions; fif_set_default_mount_options(&mountOptions); // tracing? fif_mount_handle mountHandle; if (pTraceStream != nullptr) { // create trace io fif_io trace_io; ByteStream_fif_io(pTraceStream, &trace_io); // create the archive int result = fif_trace_mount_volume(&mountHandle, &io, NULL, &mountOptions, &trace_io); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::OpenVolume: fif_trace_mount_volume() failed: %i", result); return nullptr; } } else { // mount volume int result = fif_mount_volume(&mountHandle, &io, NULL, &mountOptions); if (result != FIF_ERROR_SUCCESS) { Log_ErrorPrintf("FIFVolume::OpenVolume: fif_mount_volume() failed: %i", result); return nullptr; } } // create volume return new FIFVolume(pStream, pTraceStream, mountHandle); } bool FIFVolume::FindFiles(const char *path, const char *pattern, uint32 flags, FileSystem::FindResultsArray *pResults) const { // has a path if (path[0] == '\0') return false; // clear result array if (!(flags & FILESYSTEM_FIND_KEEP_ARRAY)) pResults->Clear(); //fif_enumdir() return false; } <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUTexture.cpp #include "OpenGLRenderer/PrecompiledHeader.h" #include "OpenGLRenderer/OpenGLGPUTexture.h" #include "OpenGLRenderer/OpenGLGPUContext.h" #include "OpenGLRenderer/OpenGLGPUDevice.h" Log_SetChannel(OpenGLRenderBackend); //#undef GLEW_ARB_texture_storage //#define GLEW_ARB_texture_storage 0 static const GLenum s_GLCubeMapFaceEnums[CUBEMAP_FACE_COUNT] = { GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; static void SetOpenGLTextureState(GLenum textureTarget, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { glTexParameterfv(textureTarget, GL_TEXTURE_BORDER_COLOR, pSamplerStateDesc->BorderColor); glTexParameteri(textureTarget, GL_TEXTURE_COMPARE_FUNC, OpenGLTypeConversion::GetOpenGLComparisonFunc(pSamplerStateDesc->ComparisonFunc)); glTexParameteri(textureTarget, GL_TEXTURE_COMPARE_MODE, OpenGLTypeConversion::GetOpenGLComparisonMode(pSamplerStateDesc->Filter)); glTexParameterf(textureTarget, GL_TEXTURE_LOD_BIAS, pSamplerStateDesc->LODBias); glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, OpenGLTypeConversion::GetOpenGLTextureMinFilter(pSamplerStateDesc->Filter)); glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, OpenGLTypeConversion::GetOpenGLTextureMagFilter(pSamplerStateDesc->Filter)); glTexParameterf(textureTarget, GL_TEXTURE_MIN_LOD, (float)pSamplerStateDesc->MinLOD); glTexParameterf(textureTarget, GL_TEXTURE_MAX_LOD, (float)pSamplerStateDesc->MaxLOD); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressU)); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressV)); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_R, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressW)); if (pSamplerStateDesc->Filter == TEXTURE_FILTER_ANISOTROPIC || pSamplerStateDesc->Filter == TEXTURE_FILTER_COMPARISON_ANISOTROPIC) glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)pSamplerStateDesc->MaxAnisotropy); else glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } static void SetOpenGLTextureStateDSA(GLuint textureID, GLenum textureTarget, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { glTextureParameterfvEXT(textureID, textureTarget, GL_TEXTURE_BORDER_COLOR, pSamplerStateDesc->BorderColor); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_COMPARE_FUNC, OpenGLTypeConversion::GetOpenGLComparisonFunc(pSamplerStateDesc->ComparisonFunc)); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_COMPARE_MODE, OpenGLTypeConversion::GetOpenGLComparisonMode(pSamplerStateDesc->Filter)); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_LOD_BIAS, pSamplerStateDesc->LODBias); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_MIN_FILTER, OpenGLTypeConversion::GetOpenGLTextureMinFilter(pSamplerStateDesc->Filter)); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_MAG_FILTER, OpenGLTypeConversion::GetOpenGLTextureMagFilter(pSamplerStateDesc->Filter)); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MIN_LOD, (float)pSamplerStateDesc->MinLOD); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MAX_LOD, (float)pSamplerStateDesc->MaxLOD); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_S, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressU)); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_T, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressV)); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_R, OpenGLTypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressW)); if (pSamplerStateDesc->Filter == TEXTURE_FILTER_ANISOTROPIC || pSamplerStateDesc->Filter == TEXTURE_FILTER_COMPARISON_ANISOTROPIC) glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)pSamplerStateDesc->MaxAnisotropy); else glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } static void SetDefaultOpenGLTextureState(GLenum textureTarget) { glTexParameterfv(textureTarget, GL_TEXTURE_BORDER_COLOR, float4::Zero); glTexParameteri(textureTarget, GL_TEXTURE_COMPARE_FUNC, GL_ALWAYS); glTexParameteri(textureTarget, GL_TEXTURE_COMPARE_MODE, GL_NONE); glTexParameterf(textureTarget, GL_TEXTURE_LOD_BIAS, 0.0f); glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(textureTarget, GL_TEXTURE_MIN_LOD, -1000.0f); glTexParameterf(textureTarget, GL_TEXTURE_MAX_LOD, 1000.0f); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_R, GL_CLAMP); glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } static void SetDefaultOpenGLTextureStateDSA(GLuint textureID, GLenum textureTarget) { glTextureParameterfvEXT(textureID, textureTarget, GL_TEXTURE_BORDER_COLOR, float4::Zero); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_COMPARE_FUNC, GL_ALWAYS); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_COMPARE_MODE, GL_NONE); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_LOD_BIAS, 0.0f); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MIN_LOD, -1000.0f); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MAX_LOD, 1000.0f); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP); glTextureParameteriEXT(textureID, textureTarget, GL_TEXTURE_WRAP_R, GL_CLAMP); glTextureParameterfEXT(textureID, textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTexture1D::OpenGLGPUTexture1D(const GPU_TEXTURE1D_DESC *pDesc, GLuint glTextureId) : GPUTexture1D(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTexture1D::~OpenGLGPUTexture1D() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTexture1D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage; } } void OpenGLGPUTexture1D::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture1D *OpenGLGPUDevice::CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && !pPixelFormatInfo->IsBlockCompressed); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTexture1D: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture1D: glGenTextures failed: "); return nullptr; } // have data for us? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage1DEXT(glTextureId, GL_TEXTURE_1D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width); // upload mip levels if (hasInitialData) { for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) glTextureSubImage1DEXT(glTextureId, GL_TEXTURE_1D, i, 0, Max((uint32)1, pTextureDesc->Width >> i), glFormat, glType, ppInitialData[i]); } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_1D, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_1D); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_1D, glTextureId); // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage1D(GL_TEXTURE_1D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); glTexSubImage1D(GL_TEXTURE_1D, i, 0, mipWidth, glFormat, glType, ppInitialData[i]); } } } else { // flip and upload mip levels for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); glTexImage1D(GL_TEXTURE_1D, i, glInternalFormat, mipWidth, 0, glFormat, glType, hasInitialData ? ppInitialData[i] : nullptr); } } // set texture parameters glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_1D, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_1D); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture1D: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTexture1D(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTexture1D *pTexture, void *pDestination, uint32 cbDestination, uint32 mipIndex, uint32 start, uint32 count) { OpenGLGPUTexture1D *pOpenGLTexture = static_cast<OpenGLGPUTexture1D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(count > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth) return false; // check destination size if (PixelFormat_CalculateRowPitch(pOpenGLTexture->GetDesc()->Format, mipWidth) > cbDestination) return false; // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // complete read? if (start == 0 && count == mipWidth) { BindMutatorTextureUnit(); glGetTexImage(GL_TEXTURE_1D, mipIndex, glFormat, glType, pDestination); RestoreMutatorTextureUnit(); } else { // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTexture1D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_1D, pOpenGLTexture->GetGLTextureId(), mipIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(start, 0, count, 1, glFormat, glType, pDestination); // unbind texture glFramebufferTexture1D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } return true; } bool OpenGLGPUContext::WriteTexture(GPUTexture1D *pTexture, const void *pSource, uint32 cbSource, uint32 mipIndex, uint32 start, uint32 count) { OpenGLGPUTexture1D *pOpenGLTexture = static_cast<OpenGLGPUTexture1D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(count > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth) return false; // check destination size if (PixelFormat_CalculateRowPitch(pOpenGLTexture->GetDesc()->Format, mipWidth) > cbSource) return false; // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage1DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_1D, mipIndex, start, count, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_1D, pOpenGLTexture->GetGLTextureId()); glTexSubImage1D(GL_TEXTURE_1D, mipIndex, start, count, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTexture1DArray::OpenGLGPUTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pDesc, GLuint glTextureId) : GPUTexture1DArray(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTexture1DArray::~OpenGLGPUTexture1DArray() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTexture1DArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), 1, 1); *gpuMemoryUsage = memoryUsage * m_desc.ArraySize; } } void OpenGLGPUTexture1DArray::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture1DArray *OpenGLGPUDevice::CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr && !pPixelFormatInfo->IsBlockCompressed); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTexture1DArray: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture1DArray: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage2DEXT(glTextureId, GL_TEXTURE_1D_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->ArraySize); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_1D_ARRAY, mipIndex, 0, arrayIndex, mipWidth, 1, glFormat, glType, ppInitialData[dataIndex]); } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_1D_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_1D_ARRAY); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_1D_ARRAY, glTextureId); // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage2D(GL_TEXTURE_1D_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->ArraySize); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage2D(GL_TEXTURE_1D_ARRAY, mipIndex, 0, arrayIndex, mipWidth, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } else { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); // allocate the mip level glTexImage2D(GL_TEXTURE_1D_ARRAY, mipIndex, glInternalFormat, mipWidth, pTextureDesc->ArraySize, 0, glFormat, glType, nullptr); // upload array if (hasInitialData) { for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage2D(GL_TEXTURE_1D_ARRAY, mipIndex, 0, arrayIndex, mipWidth, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } // set texture parameters glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_1D_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_1D_ARRAY); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture1DArray: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTexture1DArray(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTexture1DArray *pTexture, void *pDestination, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { OpenGLGPUTexture1DArray *pOpenGLTexture = static_cast<OpenGLGPUTexture1DArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(count > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if (PixelFormat_CalculateRowPitch(pOpenGLTexture->GetDesc()->Format, count) > cbDestination) return false; // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, pOpenGLTexture->GetGLTextureId(), mipIndex, arrayIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(start, 0, count, 0, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); return true; } bool OpenGLGPUContext::WriteTexture(GPUTexture1DArray *pTexture, const void *pSource, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 start, uint32 count) { OpenGLGPUTexture1DArray *pOpenGLTexture = static_cast<OpenGLGPUTexture1DArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(count > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); if ((start + count) > mipWidth || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if (PixelFormat_CalculateRowPitch(pOpenGLTexture->GetDesc()->Format, count) > cbSource) return false; // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage2DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_1D_ARRAY, mipIndex, start, arrayIndex, count, 1, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_1D_ARRAY, pOpenGLTexture->GetGLTextureId()); glTexSubImage2D(GL_TEXTURE_1D_ARRAY, mipIndex, start, arrayIndex, count, 1, glFormat, glType, pSource); glBindTexture(GL_TEXTURE_1D_ARRAY, 0); } RestoreMutatorTextureUnit(); } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTexture2D::OpenGLGPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, GLuint glTextureId) : GPUTexture2D(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTexture2D::~OpenGLGPUTexture2D() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTexture2D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage; } } void OpenGLGPUTexture2D::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture2D *OpenGLGPUDevice::CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTexture2D: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture2D: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage2DEXT(glTextureId, GL_TEXTURE_2D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // upload mip levels if (hasInitialData) { // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_2D, i, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[i] * blocksHigh, ppInitialData[i]); } } else { for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_2D, i, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[i]); } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_2D, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_2D); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_2D, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage glTexStorage2D(GL_TEXTURE_2D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // fill mip levels if provided if (hasInitialData) { for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); glCompressedTexSubImage2D(GL_TEXTURE_2D, i, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[i] * blocksHigh, ppInitialData[i]); } } } else { // use traditional method for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); uint32 imageSize = (hasInitialData) ? pInitialDataPitch[i] * blocksHigh : 0; const void *pInitialData = (hasInitialData) ? ppInitialData[i] : nullptr; glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, imageSize, pInitialData); } } } else { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage2D(GL_TEXTURE_2D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); glTexSubImage2D(GL_TEXTURE_2D, i, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[i]); } } } else { // flip and upload mip levels for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, (hasInitialData) ? ppInitialData[i] : nullptr); } } } // set texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_2D, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_2D); } // restore mutator texture unit RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture2D: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTexture2D(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTexture2D *pOpenGLTexture = static_cast<OpenGLGPUTexture2D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // complete read? if (startX == 0 && startY == 0 && countX == mipWidth && countY == mipHeight) { BindMutatorTextureUnit(); glGetTexImage(GL_TEXTURE_2D, mipIndex, glFormat, glType, pDestination); RestoreMutatorTextureUnit(); } else { // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pOpenGLTexture->GetGLTextureId(), mipIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLGPUContext::WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTexture2D *pOpenGLTexture = static_cast<OpenGLGPUTexture2D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage2DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_2D, mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_2D, pOpenGLTexture->GetGLTextureId()); glTexSubImage2D(GL_TEXTURE_2D, mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTexture2DArray::OpenGLGPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, GLuint glTextureId) : GPUTexture2DArray(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTexture2DArray::~OpenGLGPUTexture2DArray() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTexture2DArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage * m_desc.ArraySize; } } void OpenGLGPUTexture2DArray::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture2DArray *OpenGLGPUDevice::CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTexture2DArray: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture2DArray: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // use texture storage glTextureStorage3DEXT(glTextureId, GL_TEXTURE_2D_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->ArraySize); // texture is compressed? if (hasInitialData) { if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTextureSubImage3DEXT(glTextureId, GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } else { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTextureSubImage3DEXT(glTextureId, GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_2D_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_2D_ARRAY); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_2D_ARRAY, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage glTexStorage3D(GL_TEXTURE_2D_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->ArraySize); // fill mip levels if provided if (hasInitialData) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } } else { // use traditional method for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // allocate mip level glTexImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, glInternalFormat, mipWidth, mipHeight, pTextureDesc->ArraySize, 0, glFormat, glType, nullptr); // upload each array texture if (hasInitialData) { for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } } } else { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage3D(GL_TEXTURE_2D_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->ArraySize); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } else { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // allocate the mip level glTexImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, glInternalFormat, mipWidth, mipHeight, pTextureDesc->ArraySize, 0, glFormat, glType, nullptr); // upload array if (hasInitialData) { for (uint32 arrayIndex = 0; arrayIndex < pTextureDesc->ArraySize; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } } // set texture parameters glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_2D_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_2D_ARRAY); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture2DArray: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTexture2DArray(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTexture2DArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTexture2DArray *pOpenGLTexture = static_cast<OpenGLGPUTexture2DArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, pOpenGLTexture->GetGLTextureId(), mipIndex, arrayIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLGPUContext::WriteTexture(GPUTexture2DArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTexture2DArray *pOpenGLTexture = static_cast<OpenGLGPUTexture2DArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage3DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_2D_ARRAY, mipIndex, startX, startY, arrayIndex, countX, countY, 1, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_2D_ARRAY, pOpenGLTexture->GetGLTextureId()); glTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, startX, startY, arrayIndex, countX, countY, 1, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTexture3D::OpenGLGPUTexture3D(const GPU_TEXTURE3D_DESC *pDesc, GLuint glTextureId) : GPUTexture3D(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTexture3D::~OpenGLGPUTexture3D() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTexture3D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), Max(m_desc.Depth >> j, (uint32)1)); *gpuMemoryUsage = memoryUsage; } } void OpenGLGPUTexture3D::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture3D *OpenGLGPUDevice::CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */, const uint32 *pInitialDataSlicePitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->Depth > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTexture3D: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture3D: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage3DEXT(glTextureId, GL_TEXTURE_3D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->Depth); // upload mip levels if (hasInitialData) { // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); uint32 blocksDeep = Max((uint32)1, mipDepth / pPixelFormatInfo->BlockSize); glCompressedTextureSubImage3DEXT(glTextureId, GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glInternalFormat, pInitialDataSlicePitch[mipIndex] * blocksDeep, ppInitialData[mipIndex]); } } else { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); // upload image glTextureSubImage3DEXT(glTextureId, GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glFormat, glType, ppInitialData[mipIndex]); } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_3D, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_3D); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_3D, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage glTexStorage3D(GL_TEXTURE_3D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->Depth); // fill mip levels if provided if (hasInitialData) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); uint32 blocksDeep = Max((uint32)1, mipDepth / pPixelFormatInfo->BlockSize); glCompressedTexSubImage3D(GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glInternalFormat, pInitialDataSlicePitch[mipIndex] * blocksDeep, ppInitialData[mipIndex]); } } } else { // use traditional method for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); uint32 blocksDeep = Max((uint32)1, mipDepth / pPixelFormatInfo->BlockSize); // allocate mip level if (hasInitialData) glCompressedTexImage3D(GL_TEXTURE_3D, mipIndex, glInternalFormat, mipWidth, mipHeight, mipDepth, 0, pInitialDataSlicePitch[mipIndex] * blocksDeep, ppInitialData[mipIndex]); else glCompressedTexImage3D(GL_TEXTURE_3D, mipIndex, glInternalFormat, mipWidth, mipHeight, mipDepth, 0, 0, nullptr); } } } else { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage3D(GL_TEXTURE_3D, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, pTextureDesc->Depth); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); // upload image glTexSubImage3D(GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glFormat, glType, ppInitialData[mipIndex]); } } } else { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 mipDepth = Max((uint32)1, pTextureDesc->Depth >> mipIndex); if (hasInitialData) glTexSubImage3D(GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glFormat, glType, ppInitialData[mipIndex]); else glTexSubImage3D(GL_TEXTURE_3D, mipIndex, 0, 0, 0, mipWidth, mipHeight, mipDepth, glFormat, glType, nullptr); } } } // set texture parameters glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_3D, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_3D); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTexture3D: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTexture3D(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTexture3D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 destinationSlicePitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { OpenGLGPUTexture3D *pOpenGLTexture = static_cast<OpenGLGPUTexture3D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0 && countZ > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); uint32 mipDepth = Max(pOpenGLTexture->GetDesc()->Depth >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || (startZ + countZ) > mipDepth) return false; // check destination size if ((countZ * destinationSlicePitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // read each slice byte *pWritePointer = reinterpret_cast<byte *>(pDestination); for (uint32 i = 0; i < countZ; i++) { glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, pOpenGLTexture->GetGLTextureId(), mipIndex, startZ + i); DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); glReadPixels(startX, startY, countX, countY, glFormat, glType, pWritePointer); pWritePointer += destinationSlicePitch; } // unbind texture glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { pWritePointer = reinterpret_cast<byte *>(pDestination); for (uint32 i = 0; i < countZ; i++) { PixelFormat_FlipImageInPlace(pWritePointer, destinationRowPitch, countY); pWritePointer += destinationSlicePitch; } } return true; } bool OpenGLGPUContext::WriteTexture(GPUTexture3D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 sourceSlicePitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 startZ, uint32 countX, uint32 countY, uint32 countZ) { OpenGLGPUTexture3D *pOpenGLTexture = static_cast<OpenGLGPUTexture3D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0 && countZ > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); uint32 mipDepth = Max(pOpenGLTexture->GetDesc()->Depth >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || (startZ + countZ) > mipDepth) return false; // check destination size if ((countZ * sourceSlicePitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; const byte *pReadPointer = reinterpret_cast<const byte *>(pSource); byte *pWritePointer = reinterpret_cast<byte *>(pFlippedPixels); for (uint32 i = 0; i < countZ; i++) { PixelFormat_FlipImage(pWritePointer, pReadPointer, sourceRowPitch, countY); pReadPointer += sourceSlicePitch; pWritePointer += sourceSlicePitch; } pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage3DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_3D, mipIndex, startX, startY, startZ, countX, countY, countZ, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_3D, pOpenGLTexture->GetGLTextureId()); glTexSubImage3D(GL_TEXTURE_3D, mipIndex, startX, startY, startZ, countX, countY, countZ, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTextureCube::OpenGLGPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, GLuint glTextureId) : GPUTextureCube(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTextureCube::~OpenGLGPUTextureCube() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTextureCube::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage * CUBEMAP_FACE_COUNT; } } void OpenGLGPUTextureCube::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTextureCube *OpenGLGPUDevice::CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTextureCube: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTextureCube: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // upload mip levels if (hasInitialData) { if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // upload each face glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glCompressedTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } else { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // upload data glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glTextureSubImage2DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_CUBE_MAP, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_CUBE_MAP); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_CUBE_MAP, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage glTexStorage2D(GL_TEXTURE_CUBE_MAP, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // fill mip levels if provided if (hasInitialData) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // upload each face glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glInternalFormat, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } } else { // use traditional method for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // upload each array texture if (hasInitialData) { // upload each face glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } } } else { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage2D(GL_TEXTURE_CUBE_MAP, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); // has data? if (hasInitialData) { // upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // upload data glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, 0, 0, mipWidth, mipHeight, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } } else { // upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // upload array if (hasInitialData) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } else { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); } } } } // set texture parameters glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_CUBE_MAP, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_CUBE_MAP); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTextureCube: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTextureCube(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTextureCube *pOpenGLTexture = static_cast<OpenGLGPUTextureCube *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, s_GLCubeMapFaceEnums[face], pOpenGLTexture->GetGLTextureId(), mipIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLGPUContext::WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTextureCube *pOpenGLTexture = static_cast<OpenGLGPUTextureCube *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET ) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage2DEXT(pOpenGLTexture->GetGLTextureId(), s_GLCubeMapFaceEnums[face], mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_CUBE_MAP, pOpenGLTexture->GetGLTextureId()); glTexSubImage2D(s_GLCubeMapFaceEnums[face], mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUTextureCubeArray::OpenGLGPUTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pDesc, GLuint glTextureId) : GPUTextureCubeArray(pDesc), m_glTextureId(glTextureId) { } OpenGLGPUTextureCubeArray::~OpenGLGPUTextureCubeArray() { glDeleteTextures(1, &m_glTextureId); } void OpenGLGPUTextureCubeArray::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage * m_desc.ArraySize * CUBEMAP_FACE_COUNT; } } void OpenGLGPUTextureCubeArray::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTextureCubeArray *OpenGLGPUDevice::CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT && pTextureDesc->ArraySize > 0); uint32 faceLayerCount = pTextureDesc->ArraySize * CUBEMAP_FACE_COUNT; // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateTextureCubeArray: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTextureCubeArray: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // using DSA? we'll also require texture storage since if we have DSA we'll likely have texture storage if (GLAD_GL_EXT_direct_state_access && GLAD_GL_ARB_texture_storage) { // allocate storage glTextureStorage3DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, faceLayerCount); // upload mip levels if (hasInitialData) { if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTextureSubImage3DEXT(glTextureId, GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } else { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTextureSubImage3DEXT(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } // set texture parameters glTextureParameteriEXT(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureStateDSA(glTextureId, GL_TEXTURE_CUBE_MAP_ARRAY); } } else { // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage glTexStorage3D(GL_TEXTURE_CUBE_MAP_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, faceLayerCount); // fill mip levels if provided if (hasInitialData) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTexSubImage3D(GL_TEXTURE_2D_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } } else { // use traditional method for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // allocate mip level glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, glInternalFormat, mipWidth, mipHeight, faceLayerCount, 0, glFormat, glType, nullptr); // upload each array texture if (hasInitialData) { for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glCompressedTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glInternalFormat, pInitialDataPitch[dataIndex] * blocksHigh, ppInitialData[dataIndex]); } } } } } else { // has storage extension? if (GLAD_GL_ARB_texture_storage) { // use texture storage to allocate glTexStorage3D(GL_TEXTURE_CUBE_MAP_ARRAY, pTextureDesc->MipLevels, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height, faceLayerCount); // has data? if (hasInitialData) { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } else { // flip and upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // allocate the mip level glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, glInternalFormat, mipWidth, mipHeight, faceLayerCount, 0, glFormat, glType, nullptr); // upload array if (hasInitialData) { for (uint32 arrayIndex = 0; arrayIndex < faceLayerCount; arrayIndex++) { uint32 dataIndex = pTextureDesc->MipLevels * arrayIndex + mipIndex; glTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, 0, 0, arrayIndex, mipWidth, mipHeight, 1, glFormat, glType, ppInitialData[dataIndex]); } } } } } // set texture parameters glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAX_LEVEL, pTextureDesc->MipLevels - 1); // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_CUBE_MAP_ARRAY, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_CUBE_MAP_ARRAY); } // restore currently-bound texture RestoreMutatorTextureUnit(); } // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateTextureCubeArray: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLGPUTextureCubeArray(pTextureDesc, glTextureId); } bool OpenGLGPUContext::ReadTexture(GPUTextureCubeArray *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTextureCubeArray *pOpenGLTexture = static_cast<OpenGLGPUTextureCubeArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, pOpenGLTexture->GetGLTextureId(), mipIndex, (arrayIndex * CUBEMAP_FACE_COUNT) + (uint32)face); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLGPUContext::WriteTexture(GPUTextureCubeArray *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 arrayIndex, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUTextureCubeArray *pOpenGLTexture = static_cast<OpenGLGPUTextureCubeArray *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight || arrayIndex >= pOpenGLTexture->GetDesc()->ArraySize) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_BIND_RENDER_TARGET) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture if (GLAD_GL_EXT_direct_state_access) { glTextureSubImage3DEXT(pOpenGLTexture->GetGLTextureId(), GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, startX, startY, (arrayIndex * CUBEMAP_FACE_COUNT) + (uint32)face, countX, countY, 1, glFormat, glType, pSource); } else { BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, pOpenGLTexture->GetGLTextureId()); glTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, mipIndex, startX, startY, (arrayIndex * CUBEMAP_FACE_COUNT) + (uint32)face, countX, countY, 1, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); } // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLGPUDepthTexture::OpenGLGPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, GLuint glRenderBufferId) : GPUDepthTexture(pDesc), m_glRenderBufferId(glRenderBufferId) { } OpenGLGPUDepthTexture::~OpenGLGPUDepthTexture() { glDeleteRenderbuffers(1, &m_glRenderBufferId); } void OpenGLGPUDepthTexture::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { *gpuMemoryUsage = PixelFormat_CalculateImageSize(m_desc.Format, m_desc.Width, m_desc.Height, 1); } } void OpenGLGPUDepthTexture::SetDebugName(const char *name) { OpenGLHelpers::SetObjectDebugName(GL_RENDERBUFFER, m_glRenderBufferId, name); } GPUDepthTexture *OpenGLGPUDevice::CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) { UploadContextReference ctxRef(this); if (!ctxRef.HasContext()) return nullptr; // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0); // convert to opengl types GLint glInternalFormat; if (!OpenGLTypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, nullptr, nullptr)) { Log_ErrorPrintf("OpenGLGPUDevice::CreateDepthTexture: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glRenderBufferId; glGenRenderbuffers(1, &glRenderBufferId); if (glRenderBufferId == 0) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateDepthTexture: glGenTextures failed: "); return nullptr; } // bind texture, and allocate storage glBindRenderbuffer(GL_RENDERBUFFER, glRenderBufferId); glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); glBindRenderbuffer(GL_RENDERBUFFER, 0); // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLGPUDevice::CreateDepthTexture: One or more GL errors occured: "); glDeleteTextures(1, &glRenderBufferId); return nullptr; } // create texture class return new OpenGLGPUDepthTexture(pTextureDesc, glRenderBufferId); } bool OpenGLGPUContext::ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLGPUDepthTexture *pOpenGLTexture = static_cast<OpenGLGPUDepthTexture *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level if ((startX + countX) > pOpenGLTexture->GetDesc()->Width || (startY + countY) > pOpenGLTexture->GetDesc()->Height) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. startY = pOpenGLTexture->GetDesc()->Height - startY - countY; DebugAssert(startY < pOpenGLTexture->GetDesc()->Height); // get gl formats GLenum glFormat; GLenum glType; OpenGLTypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO if (glFormat == GL_DEPTH_COMPONENT) glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, pOpenGLTexture->GetGLRenderBufferId()); else if (glFormat == GL_DEPTH_STENCIL) glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, pOpenGLTexture->GetGLRenderBufferId()); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture if (glFormat == GL_DEPTH_COMPONENT) glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); else if (glFormat == GL_DEPTH_STENCIL) glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); // restore fbo state glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLGPUContext::WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { // can't write to renderbuffers return false; } static GLenum GetDepthStencilFramebufferAttachmentPoint(PIXEL_FORMAT pixelFormat) { switch (pixelFormat) { case PIXEL_FORMAT_D16_UNORM: case PIXEL_FORMAT_D32_FLOAT: return GL_DEPTH_ATTACHMENT; case PIXEL_FORMAT_D24_UNORM_S8_UINT: case PIXEL_FORMAT_D32_FLOAT_S8X24_UINT: return GL_DEPTH_STENCIL_ATTACHMENT; } UnreachableCode(); return 0; } OpenGLGPURenderTargetView::OpenGLGPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLuint textureName, bool multiLayer) : GPURenderTargetView(pTexture, pDesc), m_textureType(textureType), m_textureName(textureName), m_multiLayer(multiLayer) { } OpenGLGPURenderTargetView::~OpenGLGPURenderTargetView() { } void OpenGLGPURenderTargetView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void OpenGLGPURenderTargetView::SetDebugName(const char *name) { } GPURenderTargetView *OpenGLGPUDevice::CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // fill in DSV structure TEXTURE_TYPE textureType; GLuint textureName; bool multiLayer; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: textureType = TEXTURE_TYPE_1D; textureName = static_cast<OpenGLGPUTexture1D *>(pTexture)->GetGLTextureId(); multiLayer = false; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: textureType = TEXTURE_TYPE_1D_ARRAY; textureName = static_cast<OpenGLGPUTexture1DArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURE2D: textureType = TEXTURE_TYPE_2D; textureName = static_cast<OpenGLGPUTexture2D *>(pTexture)->GetGLTextureId(); multiLayer = false; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: textureType = TEXTURE_TYPE_2D_ARRAY; textureName = static_cast<OpenGLGPUTexture2DArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: textureType = TEXTURE_TYPE_CUBE; textureName = static_cast<OpenGLGPUTextureCube *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: textureType = TEXTURE_TYPE_CUBE_ARRAY; textureName = static_cast<OpenGLGPUTextureCubeArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: textureType = TEXTURE_TYPE_DEPTH; textureName = static_cast<OpenGLGPUDepthTexture *>(pTexture)->GetGLRenderBufferId(); multiLayer = false; break; default: Log_ErrorPrintf("OpenGLGPUDevice::CreateRenderTargetView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } // @TODO views return new OpenGLGPURenderTargetView(pTexture, pDesc, textureType, textureName, multiLayer); } OpenGLGPUDepthStencilBufferView::OpenGLGPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLenum attachmentPoint, GLuint textureName, bool multiLayer) : GPUDepthStencilBufferView(pTexture, pDesc), m_textureType(textureType), m_attachmentPoint(attachmentPoint), m_textureName(textureName), m_multiLayer(multiLayer) { } OpenGLGPUDepthStencilBufferView::~OpenGLGPUDepthStencilBufferView() { } void OpenGLGPUDepthStencilBufferView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void OpenGLGPUDepthStencilBufferView::SetDebugName(const char *name) { } GPUDepthStencilBufferView *OpenGLGPUDevice::CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // fill in DSV structure TEXTURE_TYPE textureType; GLenum attachmentPoint; GLuint textureName; bool multiLayer; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: textureType = TEXTURE_TYPE_1D; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTexture1D *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTexture1D *>(pTexture)->GetGLTextureId(); multiLayer = false; break; case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: textureType = TEXTURE_TYPE_1D_ARRAY; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTexture1DArray *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTexture1DArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURE2D: textureType = TEXTURE_TYPE_2D; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTexture2D *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTexture2D *>(pTexture)->GetGLTextureId(); multiLayer = false; break; case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: textureType = TEXTURE_TYPE_2D_ARRAY; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTexture2DArray *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTexture2DArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: textureType = TEXTURE_TYPE_CUBE; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTextureCube *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTextureCube *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: textureType = TEXTURE_TYPE_CUBE_ARRAY; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUTextureCubeArray *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUTextureCubeArray *>(pTexture)->GetGLTextureId(); multiLayer = (pDesc->NumLayers > 1); break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: textureType = TEXTURE_TYPE_DEPTH; attachmentPoint = GetDepthStencilFramebufferAttachmentPoint(static_cast<OpenGLGPUDepthTexture *>(pTexture)->GetDesc()->Format); textureName = static_cast<OpenGLGPUDepthTexture *>(pTexture)->GetGLRenderBufferId(); multiLayer = false; break; default: Log_ErrorPrintf("OpenGLGPUDevice::CreateDepthBufferView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } // @TODO views return new OpenGLGPUDepthStencilBufferView(pTexture, pDesc, textureType, attachmentPoint, textureName, multiLayer); } OpenGLGPUComputeView::OpenGLGPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) : GPUComputeView(pResource, pDesc) { } OpenGLGPUComputeView::~OpenGLGPUComputeView() { } void OpenGLGPUComputeView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void OpenGLGPUComputeView::SetDebugName(const char *name) { } GPUComputeView *OpenGLGPUDevice::CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { Panic("Unimplemented"); return nullptr; } <file_sep>/Engine/Source/GameFramework/ParticleEmitterComponent.h #pragma once #include "Engine/Component.h" #include "Engine/ParticleSystem.h" class ParticleSystemRenderProxy; class ParticleEmitterComponent : public Component { DECLARE_COMPONENT_TYPEINFO(ParticleEmitterComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(ParticleEmitterComponent); public: ParticleEmitterComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~ParticleEmitterComponent(); // particle system const ParticleSystem *GetParticleSystem() const { return m_pParticleSystem; } void SetParticleSystem(const ParticleSystem *pParticleSystem); // create new instance bool Create(const ParticleSystem *pParticleSystem, const float3 &offsetPosition = float3::Zero, const Quaternion &offsetRotation = Quaternion::Identity); // reset to initial state void Reset(); // activate/deactivate void Activate(); void Deactivate(); // Events virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; virtual void Update(float timeSinceLastUpdate) override; private: const ParticleSystem *m_pParticleSystem; bool m_autoStart; ParticleSystemRenderProxy *m_pRenderProxy; Transform m_cachedTransform; bool m_active; }; <file_sep>/Editor/Source/Editor/EditorVirtualFileSystemModel.h #pragma once #include "Editor/Common.h" class EditorVirtualFileSystemModel : public QAbstractItemModel { Q_OBJECT public: EditorVirtualFileSystemModel(QWidget *pParent = NULL); ~EditorVirtualFileSystemModel(); virtual QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex( ) ) const; virtual QModelIndex parent( const QModelIndex &child ) const; virtual int rowCount( const QModelIndex &parent = QModelIndex( ) ) const; virtual int columnCount( const QModelIndex &parent = QModelIndex( ) ) const; virtual bool hasChildren( const QModelIndex &parent = QModelIndex( ) ) const; virtual QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const; virtual QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; }; <file_sep>/Engine/Source/Core/XDisplay.cpp #include "Core/PrecompiledHeader.h" #include "Core/XDisplay.h" #if defined(Y_PLATFORM_LINUX) #include "YBaseLib/Assert.h" #include "YBaseLib/Log.h" #include <cstdlib> Log_SetChannel(XDisplay); static Display *g_pXDisplay = NULL; void Y_AtExitCloseXDisplay() { if (g_pXDisplay != NULL) { XCloseDisplay(g_pXDisplay); g_pXDisplay = NULL; } } void Y_SetXDisplayPointer(Display *pXDisplay) { DebugAssert((g_pXDisplay == NULL && pXDisplay != NULL) || (g_pXDisplay != NULL && pXDisplay == NULL)); g_pXDisplay = pXDisplay; } bool Y_CheckXDisplayPointer() { if (g_pXDisplay == NULL) { g_pXDisplay = XOpenDisplay(NULL); if (g_pXDisplay == NULL) { Log_ErrorPrintf("Could not connect to X server."); return false; } atexit(Y_AtExitCloseXDisplay); } return true; } Display *Y_GetXDisplayPointer() { return g_pXDisplay; } #endif // Y_PLATFORM_LINUX <file_sep>/Engine/Source/BlockEngine/BlockWorldSection.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldSection.h" #include "BlockEngine/BlockWorldChunk.h" #include "BlockEngine/BlockWorld.h" #include "Engine/Entity.h" #include "Core/ClassTable.h" Log_SetChannel(BlockWorldSection); BlockWorldSection::BlockWorldSection(BlockWorld *pWorld, int32 sectionX, int32 sectionY) : m_pWorld(pWorld), m_sectionSize(pWorld->GetSectionSize()), m_chunkSize(pWorld->GetChunkSize()), m_sectionX(sectionX), m_sectionY(sectionY), m_lodLevels(pWorld->GetLODLevels()), m_baseChunkX(sectionX * m_sectionSize), m_baseChunkY(sectionY * m_sectionSize), m_boundingBox(BlockWorld::CalculateSectionBoundingBox(m_sectionSize, m_chunkSize, sectionX, sectionY)), m_loadedLODLevel(m_lodLevels), m_chunksPendingMeshing(0), m_minChunkZ(0), m_maxChunkZ(0), m_chunkCountZ(0), m_chunkCount(0), m_ppChunks(nullptr), m_loadState(LoadState_Loaded) { } BlockWorldSection::~BlockWorldSection() { while (m_entities.GetSize() > 0) { Entity *pEntity = m_entities[m_entities.GetSize() - 1].pEntity; m_entities.RemoveBack(); // unload entity pEntity->OnRemoveFromWorld(m_pWorld); m_pWorld->OnUnloadEntity(pEntity); pEntity->Release(); } for (int32 i = 0; i < m_chunkCount; i++) { BlockWorldChunk *pChunk = m_ppChunks[i]; if (pChunk != nullptr) { m_pWorld->OnChunkUnloaded(this, pChunk); delete pChunk; } } delete[] m_ppChunks; } int32 BlockWorldSection::GetChunkArrayIndex(int32 chunkX, int32 chunkY, int32 chunkZ) const { DebugAssert(chunkX >= 0 && chunkX < m_sectionSize); DebugAssert(chunkY >= 0 && chunkY < m_sectionSize); DebugAssert(chunkZ >= m_minChunkZ && chunkZ <= m_maxChunkZ); const int32 yStride = m_sectionSize; const int32 zStride = m_sectionSize * yStride; return (chunkZ - m_minChunkZ) * zStride + (chunkY * yStride) + chunkX; } void BlockWorldSection::InitializeChunkArray(int32 minChunkZ, int32 maxChunkZ) { DebugAssert(minChunkZ <= maxChunkZ); m_minChunkZ = minChunkZ; m_maxChunkZ = maxChunkZ; m_chunkCountZ = (m_maxChunkZ - m_minChunkZ) + 1; m_chunkCount = m_sectionSize * m_sectionSize * m_chunkCountZ; m_ppChunks = new BlockWorldChunk *[m_chunkCount]; Y_memzero(m_ppChunks, sizeof(BlockWorldChunk *) * m_chunkCount); m_chunkAvailability.Resize(m_chunkCount); m_chunkAvailability.Clear(); } void BlockWorldSection::ResizeChunkArray(int32 minChunkZ, int32 maxChunkZ) { DebugAssert(minChunkZ <= maxChunkZ); int32 newChunkCountZ = (maxChunkZ - minChunkZ) + 1; int32 newChunkCount = m_sectionSize * m_sectionSize * newChunkCountZ; int32 newZStride = m_sectionSize * m_sectionSize; DebugAssert(newChunkCount > 0); BitSet32 newChunkAvailability; newChunkAvailability.Resize(newChunkCount); newChunkAvailability.Clear(); BlockWorldChunk **ppChunks = new BlockWorldChunk *[newChunkCount]; Y_memzero(ppChunks, sizeof(BlockWorldChunk *) * newChunkCount); uint32 chunkIndex = 0; for (int32 z = m_minChunkZ; z <= m_maxChunkZ; z++) { for (int32 y = 0; y < m_sectionSize; y++) { for (int32 x = 0; x < m_sectionSize; x++) { if (!m_chunkAvailability.TestBit(chunkIndex)) { chunkIndex++; continue; } if (z >= minChunkZ && z <= maxChunkZ) { // determine new chunk index uint32 newChunkIndex = newZStride * (z - minChunkZ) + (y * m_sectionSize) + x; ppChunks[newChunkIndex] = m_ppChunks[chunkIndex]; newChunkAvailability.SetBit(newChunkIndex); } chunkIndex++; } } } // swap everything over delete[] m_ppChunks; m_minChunkZ = minChunkZ; m_maxChunkZ = maxChunkZ; m_chunkCountZ = newChunkCountZ; m_chunkCount = newChunkCount; m_chunkAvailability.Swap(newChunkAvailability); m_ppChunks = ppChunks; } bool BlockWorldSection::GetChunkAvailability(int32 chunkX, int32 chunkY, int32 chunkZ) const { if (chunkZ < m_minChunkZ || chunkZ > m_maxChunkZ) return false; int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); return m_chunkAvailability.TestBit((uint32)arrayIndex); } void BlockWorldSection::SetChunkAvailability(int32 chunkX, int32 chunkY, int32 chunkZ, bool availability) { int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); if (availability) m_chunkAvailability.SetBit((uint32)arrayIndex); else m_chunkAvailability.UnsetBit((uint32)arrayIndex); } const BlockWorldChunk *BlockWorldSection::GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const { int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); return m_ppChunks[arrayIndex]; } BlockWorldChunk *BlockWorldSection::GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); return m_ppChunks[arrayIndex]; } const BlockWorldChunk *BlockWorldSection::SafeGetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const { if (chunkZ < m_minChunkZ || chunkZ > m_maxChunkZ) return nullptr; int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); return m_ppChunks[arrayIndex]; } BlockWorldChunk *BlockWorldSection::SafeGetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { if (chunkZ < m_minChunkZ || chunkZ > m_maxChunkZ) return nullptr; int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); return m_ppChunks[arrayIndex]; } BlockWorldChunk *BlockWorldSection::CreateChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { // we should be at lod 0 DebugAssert(m_loadedLODLevel == 0); // ensure the chunk array can fit if (chunkZ < m_minChunkZ || chunkZ > m_maxChunkZ) ResizeChunkArray(Min(chunkZ, m_minChunkZ), Max(chunkZ, m_maxChunkZ)); // shouldn't be allocated DebugAssert(!GetChunkAvailability(chunkX, chunkY, chunkZ)); // allocate chunk BlockWorldChunk *pChunk = new BlockWorldChunk(this, chunkX, chunkY, chunkZ); pChunk->Create(); // store chunk int32 arrayIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); DebugAssert(arrayIndex >= 0 && arrayIndex < m_chunkCount); m_ppChunks[arrayIndex] = pChunk; m_chunkAvailability.SetBit(arrayIndex); // flag as changed if (m_loadState == LoadState_Loaded) m_loadState = LoadState_Changed; return pChunk; } void BlockWorldSection::DeleteChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { DebugAssert(m_loadedLODLevel == 0); if (chunkZ < m_minChunkZ || chunkZ > m_maxChunkZ) return; uint32 chunkIndex = GetChunkArrayIndex(chunkX, chunkY, chunkZ); if (!m_chunkAvailability.TestBit(chunkIndex)) return; delete m_ppChunks[chunkIndex]; m_ppChunks[chunkIndex] = nullptr; m_chunkAvailability.UnsetBit(chunkIndex); if (m_loadState == LoadState_Loaded) m_loadState = LoadState_Changed; } void BlockWorldSection::Create(int32 minChunkZ /* = 0 */, int32 maxChunkZ /* = 0 */) { InitializeChunkArray(minChunkZ, maxChunkZ); m_loadedLODLevel = 0; m_loadState = LoadState_Changed; } bool BlockWorldSection::LoadFromStream(ByteStream *pStream, int32 maxLODLevel) { BinaryReader binaryReader(pStream); uint32 signature; if (!binaryReader.SafeReadUInt32(&signature) || signature != 0xCCBBAA03) return false; int32 chunkSize; int32 sectionSize; int32 lodLevels; if (!binaryReader.SafeReadInt32(&chunkSize) || chunkSize != m_chunkSize || !binaryReader.SafeReadInt32(&sectionSize) || sectionSize != m_sectionSize || !binaryReader.SafeReadInt32(&lodLevels) || lodLevels != m_lodLevels) { return false; } // read min, max int32 minChunkZ, maxChunkZ; if (!binaryReader.SafeReadInt32(&minChunkZ) || !binaryReader.SafeReadInt32(&maxChunkZ)) { return false; } // allocate array InitializeChunkArray(minChunkZ, maxChunkZ); // read mask size uint32 maskDwordCount; if (!binaryReader.SafeReadUInt32(&maskDwordCount) || maskDwordCount != m_chunkAvailability.GetValueCount()) return false; // read mask bits if (!pStream->Read2(m_chunkAvailability.GetValuesPointer(), sizeof(uint32) * maskDwordCount)) return false; // load the actual data return InternalLoadLODs(pStream, maxLODLevel); } bool BlockWorldSection::LoadLODs(ByteStream *pStream, int32 maxLODLevel) { BinaryReader binaryReader(pStream); uint32 signature; if (!binaryReader.SafeReadUInt32(&signature) || signature != 0xCCBBAA03) return false; int32 chunkSize; int32 sectionSize; int32 lodLevels; if (!binaryReader.SafeReadInt32(&chunkSize) || chunkSize != m_chunkSize || !binaryReader.SafeReadInt32(&sectionSize) || sectionSize != m_sectionSize || !binaryReader.SafeReadInt32(&lodLevels) || lodLevels != m_lodLevels) { return false; } // read min, max int32 minChunkZ, maxChunkZ; if (!binaryReader.SafeReadInt32(&minChunkZ) || m_minChunkZ != minChunkZ || !binaryReader.SafeReadInt32(&maxChunkZ) || m_maxChunkZ != maxChunkZ) { return false; } // read mask size uint32 maskDwordCount; if (!binaryReader.SafeReadUInt32(&maskDwordCount) || maskDwordCount != m_chunkAvailability.GetValueCount()) return false; // skip mask bits if (!pStream->SeekRelative(sizeof(uint32) * maskDwordCount)) return false; // load the actual data return InternalLoadLODs(pStream, maxLODLevel); } bool BlockWorldSection::InternalLoadLODs(ByteStream *pStream, int32 maxLODLevel) { BinaryReader binaryReader(pStream); // read in the offsets to each lod uint32 *lodOffsets = (uint32 *)alloca(sizeof(uint32) * m_lodLevels); if (!binaryReader.SafeReadBytes(lodOffsets, sizeof(uint32) * m_lodLevels)) return false; // read in the offset to the entities uint32 entitiesOffset, entityCount; if (!binaryReader.SafeReadUInt32(&entitiesOffset) || !binaryReader.SafeReadUInt32(&entityCount)) return false; // start at the bottom level (first in file), and stop when we reach the requested level for (int32 lodLevel = (m_lodLevels - 1); lodLevel >= maxLODLevel; lodLevel--) { // if it's already loaded, skip it if (lodLevel > m_loadedLODLevel) continue; // seek to offset if (!binaryReader.SafeSeekAbsolute((uint64)lodOffsets[lodLevel])) return false; // read chunks int32 chunkIndex = 0; for (int32 z = m_minChunkZ; z <= m_maxChunkZ; z++) { for (int32 y = 0; y < m_sectionSize; y++) { for (int32 x = 0; x < m_sectionSize; x++) { int32 thisChunkIndex = chunkIndex++; if (!m_chunkAvailability[thisChunkIndex]) continue; BlockWorldChunk *pChunk = m_ppChunks[thisChunkIndex]; if (pChunk == nullptr) { pChunk = new BlockWorldChunk(this, x, y, z); if (!pChunk->LoadFromStream(lodLevel, pStream)) { delete pChunk; return false; } m_ppChunks[thisChunkIndex] = pChunk; m_pWorld->OnChunkLoaded(this, pChunk); } else { if (!pChunk->LoadFromStream(lodLevel, pStream)) return false; } } } } } // update loaded level uint32 oldLODLevel = m_loadedLODLevel; m_loadedLODLevel = maxLODLevel; // if we loaded lod level 0, load entities if (oldLODLevel > 0 && maxLODLevel == 0 && entityCount > 0) { DebugAssert(m_entities.GetSize() == 0); // move to the position of the class table and entities if (!pStream->SeekAbsolute(entitiesOffset)) return false; // read in class table ClassTable *pClassTable = new ClassTable; if (!pClassTable->LoadFromStream(pStream)) { Log_ErrorPrintf("BlockWorldSection::LoadLODs: Failed to load class table."); return false; } // read entities for (uint32 i = 0; i < entityCount; i++) { uint32 typeIndex, entitySize; if (!binaryReader.SafeReadUInt32(&typeIndex) || !binaryReader.SafeReadUInt32(&entitySize)) { delete pClassTable; return false; } // calculate offset to next entity uint32 nextEntityOffset = (uint32)pStream->GetPosition() + entitySize; // load the object Object *pObject = pClassTable->UnserializeObject(pStream, typeIndex); if (pObject != nullptr) { // should be an entity if (pObject->IsDerived(OBJECT_TYPEINFO(Entity))) { // add it to the world, the reference will be moved across Entity *pEntity = pObject->Cast<Entity>(); pEntity->OnAddToWorld(m_pWorld); m_pWorld->OnLoadEntity(pEntity); AddEntity(pEntity); } else { Log_ErrorPrintf("BlockWorldSection::LoadLODs: Loaded bad entity object that is not derived from Entity."); pObject->Release(); } } // seek to next entity if (!pStream->SeekAbsolute(nextEntityOffset)) { delete pClassTable; return false; } } // drop the class table delete pClassTable; } return true; } void BlockWorldSection::UnloadLODs(int32 lodLevel) { // sanity checks here DebugAssert(lodLevel >= m_loadedLODLevel); // if the render lod is currently higher than the new lod level, we need to move all the chunks down to the new level, // or the easiest fix is to just nuke them if they're too high lod. this should only occur if we're lagging. { bool logged = false; // unload lod from all chunks for (int32 i = 0; i < m_chunkCount; i++) { BlockWorldChunk *pChunk = m_ppChunks[i]; if (pChunk != nullptr && pChunk->GetRenderLODLevel() < lodLevel) { if (!logged) { Log_WarningPrintf("BlockWorldSection::UnloadLODs: Unloading section [%i, %i] with render LODs at higher level of detail. This will be visually jarring until the chunks are re-meshed.", m_sectionX, m_sectionY); logged = true; } m_pWorld->RemoveChunkMesh(pChunk); } } } // unload all levels below lodLevel for (int32 currentLODLevel = (lodLevel - 1); currentLODLevel >= m_loadedLODLevel; currentLODLevel--) { // unload entities if unloading lod0 if (currentLODLevel == 0) { while (m_entities.GetSize() > 0) { Entity *pEntity = m_entities[m_entities.GetSize() - 1].pEntity; m_entities.RemoveBack(); // unload entity pEntity->OnRemoveFromWorld(m_pWorld); m_pWorld->OnUnloadEntity(pEntity); pEntity->Release(); } } // unload lod from all chunks for (int32 i = 0; i < m_chunkCount; i++) { if (m_ppChunks[i] != nullptr) m_ppChunks[i]->UnloadLODLevel(currentLODLevel); } } // and update the loaded lod level m_loadedLODLevel = lodLevel; } bool BlockWorldSection::SaveToStream(ByteStream *pStream) const { // we should be at lod0 if we're saving DebugAssert(m_loadedLODLevel == 0); // create writer BinaryWriter binaryWriter(pStream); bool writeResult = true; // write header writeResult &= binaryWriter.SafeWriteUInt32(0xCCBBAA03); writeResult &= binaryWriter.SafeWriteInt32(m_chunkSize); writeResult &= binaryWriter.SafeWriteInt32(m_sectionSize); writeResult &= binaryWriter.SafeWriteInt32(m_lodLevels); writeResult &= binaryWriter.SafeWriteInt32(m_minChunkZ); writeResult &= binaryWriter.SafeWriteInt32(m_maxChunkZ); // write bitmask writeResult &= binaryWriter.SafeWriteUInt32(m_chunkAvailability.GetValueCount()); writeResult &= binaryWriter.SafeWriteBytes(m_chunkAvailability.GetValuesPointer(), sizeof(uint32) * m_chunkAvailability.GetValueCount()); // count available chunks int32 availableChunkCount = 0; for (int32 i = 0; i < m_chunkCount; i++) { if (m_chunkAvailability.TestBit(i)) availableChunkCount++; } // calculate the offset to each lod level, and save it for checking later uint32 *lodLevelOffsets = (uint32 *)alloca(sizeof(uint32) * m_lodLevels); uint32 currentOffset = (uint32)binaryWriter.GetStreamPosition() + (sizeof(uint32) * m_lodLevels) + sizeof(uint32) + sizeof(uint32); for (int32 lodLevel = (m_lodLevels - 1); lodLevel >= 0; lodLevel--) { // save offset lodLevelOffsets[lodLevel] = currentOffset; // calculate size of this lod int32 chunkSizeInBlocks = m_chunkSize >> lodLevel; int32 chunkSizeInBytes = (chunkSizeInBlocks * chunkSizeInBlocks * chunkSizeInBlocks) * (sizeof(BlockWorldBlockType) + sizeof(BlockWorldBlockDataType)); currentOffset += chunkSizeInBytes * availableChunkCount; } // write the offsets writeResult &= binaryWriter.SafeWriteBytes(lodLevelOffsets, sizeof(uint32) * m_lodLevels); // write entity offsets and counts writeResult &= binaryWriter.SafeWriteUInt32(currentOffset); writeResult &= binaryWriter.SafeWriteUInt32(m_entities.GetSize()); // now save each lod level's data for (int32 lodLevel = (m_lodLevels - 1); lodLevel >= 0; lodLevel--) { DebugAssert(binaryWriter.GetStreamPosition() == lodLevelOffsets[lodLevel]); int32 chunkIndex = 0; for (int32 z = m_minChunkZ; z <= m_maxChunkZ; z++) { for (int32 y = 0; y < m_sectionSize; y++) { for (int32 x = 0; x < m_sectionSize; x++) { int32 thisChunkIndex = chunkIndex++; if (!m_chunkAvailability[thisChunkIndex]) continue; BlockWorldChunk *pChunk = m_ppChunks[thisChunkIndex]; DebugAssert(pChunk != nullptr); if (!pChunk->SaveToStream(lodLevel, pStream)) { Log_ErrorPrintf("Failed to write section %i,%i chunk %i,%i,%i", m_sectionX, m_sectionY, x, y, z); return false; } } } } } // should be equal DebugAssert(pStream->GetPosition() == currentOffset); // write entities if (m_entities.GetSize() > 0) { // allocate class table ClassTable *pClassTable = new ClassTable(); // create a growable stream for temporary use, because unfortunately we have to write the class table first, // which we don't know about until we actually write entities, and then the entity size is unknown until written ByteStream *pMemoryStream = ByteStream_CreateGrowableMemoryStream(); // write entities for (const BlockWorldEntityReference &entityRef : m_entities) { uint32 entityHeaderOffset = (uint32)pMemoryStream->GetPosition(); const Entity *pEntity = entityRef.pEntity; // entity in type list? if not, add it int32 typeIndex = pClassTable->GetTypeMappingForType(pEntity->GetObjectTypeInfo()); if (typeIndex < 0) typeIndex = pClassTable->AddType(pEntity->GetObjectTypeInfo()); // start with a size of zero if (!binaryWriter.SafeWriteInt32(typeIndex) || !binaryWriter.SafeWriteUInt32(0)) { pMemoryStream->Release(); delete pClassTable; return false; } // write the actual entity uint32 entityStartOffset = (uint32)pMemoryStream->GetPosition(); if (!pClassTable->SerializeObject(entityRef.pEntity, pStream)) { Log_ErrorPrintf("Failed to write section %i,%i entity %u", m_sectionX, m_sectionY, entityRef.EntityID); pMemoryStream->Release(); delete pClassTable; return false; } // now fix-up the size uint32 entityEndOffset = (uint32)pMemoryStream->GetPosition(); if (!pMemoryStream->SeekAbsolute(entityHeaderOffset + sizeof(int32)) || !binaryWriter.SafeWriteUInt32(entityEndOffset - entityStartOffset) || !pMemoryStream->SeekAbsolute(entityEndOffset)) { pMemoryStream->Release(); delete pClassTable; return false; } } // write class table if (!pClassTable->SaveToStream(pStream)) { pMemoryStream->Release(); delete pClassTable; return false; } // write entities if (!ByteStream_AppendStream(pMemoryStream, pStream)) { pMemoryStream->Release(); delete pClassTable; return false; } // clean up pMemoryStream->Release(); delete pClassTable; } return writeResult; } void BlockWorldSection::RemoveEmptyChunks() { /* for (int32 i = 0; i < m_chunkCount; i++) { BlockWorldChunk *pChunk = m_ppChunks[i]; if (pChunk != nullptr && pChunk->IsAirChunk()) { Log_DevPrintf("Dropping air chunk %i, %i, %i (section %i, %i)", pChunk->GetRelativeChunkX(), pChunk->GetRelativeChunkY(), pChunk->GetRelativeChunkZ(), m_sectionX, m_sectionY); DeleteChunk(pChunk->GetRelativeChunkX(), pChunk->GetRelativeChunkY(), pChunk->GetRelativeChunkZ()); } } */ } void BlockWorldSection::UpdateChunkLODLevels(BlockWorldChunk *pChunk, int32 lodLevel, int32 blockX, int32 blockY, int32 blockZ) { pChunk->UpdateLODs(lodLevel, blockX, blockY, blockZ); } void BlockWorldSection::RebuildLODsForChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { BlockWorldChunk *pChunk = GetChunk(chunkX, chunkY, chunkZ); DebugAssert(pChunk != nullptr); // update every 'block quad' for the chunk for (int32 blockZ = 0; blockZ < m_chunkSize; blockZ += 2) { for (int32 blockY = 0; blockY < m_chunkSize; blockY += 2) { for (int32 blockX = 0; blockX < m_chunkSize; blockX += 2) UpdateChunkLODLevels(pChunk, 0, blockX, blockY, blockZ); } } } void BlockWorldSection::RebuildLODs(int32 lodCount) { // lod change? handle this DebugAssert(lodCount == m_lodLevels); DebugAssert(m_loadedLODLevel == 0); // for each chunk, rebuild the lod for (int32 i = 0; i < m_chunkCount; i++) { BlockWorldChunk *pChunk = m_ppChunks[i]; if (pChunk == nullptr) continue; // update every 'block quad' for the chunk for (int32 blockZ = 0; blockZ < m_chunkSize; blockZ += 2) { for (int32 blockY = 0; blockY < m_chunkSize; blockY += 2) { for (int32 blockX = 0; blockX < m_chunkSize; blockX += 2) UpdateChunkLODLevels(pChunk, 0, blockX, blockY, blockZ); } } } } void BlockWorldSection::AddEntity(Entity *pEntity) { // should only happen at lod0 DebugAssert(m_loadedLODLevel == 0); // add ref BlockWorldEntityReference entityRef; entityRef.pEntity = pEntity; entityRef.EntityID = pEntity->GetEntityID(); entityRef.BoundingBox = pEntity->GetBoundingBox(); entityRef.BoundingSphere = pEntity->GetBoundingSphere(); m_entities.Add(entityRef); } void BlockWorldSection::MoveEntity(Entity *pEntity) { // should only happen at lod0 DebugAssert(m_loadedLODLevel == 0); // search and remove for (uint32 idx = 0; idx < m_entities.GetSize(); idx++) { if (m_entities[idx].pEntity == pEntity) { m_entities[idx].BoundingBox = pEntity->GetBoundingBox(); m_entities[idx].BoundingSphere = pEntity->GetBoundingSphere(); return; } } Panic("entity not found in list"); } void BlockWorldSection::RemoveEntity(Entity *pEntity) { // should only happen at lod0 DebugAssert(m_loadedLODLevel == 0); // search and remove for (uint32 idx = 0; idx < m_entities.GetSize(); idx++) { if (m_entities[idx].pEntity == pEntity) { m_entities.FastRemove(idx); return; } } Panic("entity not found in list"); } <file_sep>/Engine/Source/Renderer/WorldRenderers/FullBrightWorldRenderer.h #pragma once #include "Renderer/WorldRenderers/SingleShaderWorldRenderer.h" #include "Renderer/RenderQueue.h" #include "Renderer/MiniGUIContext.h" class FullBrightWorldRenderer : public SingleShaderWorldRenderer { public: FullBrightWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~FullBrightWorldRenderer(); protected: virtual void DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) override; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUShaderProgram.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" #include "OpenGLRenderer/OpenGLShaderCacheEntry.h" class OpenGLGPUShaderProgram : public GPUShaderProgram { public: struct ShaderUniformBuffer { String Name; uint32 ParameterIndex; uint32 Size; uint32 EngineConstantBufferIndex; int32 BlockIndex; int32 BindSlot; OpenGLGPUBuffer *pLocalGPUBuffer; byte *pLocalBuffer; int32 LocalBufferDirtyLowerBounds; int32 LocalBufferDirtyUpperBounds; }; struct ShaderParameter { String Name; SHADER_PARAMETER_TYPE Type; int32 UniformBlockIndex; uint32 UniformBlockOffset; uint32 ArraySize; uint32 ArrayStride; OPENGL_SHADER_BIND_TARGET BindTarget; int32 BindLocation; int32 BindSlot; }; public: OpenGLGPUShaderProgram(); virtual ~OpenGLGPUShaderProgram(); // resource virtuals virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; // creation bool LoadBlob(OpenGLGPUDevice *pRenderer, const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream); // bind to a context that has no current shader void Bind(OpenGLGPUContext *pContext); // switch context to a new shader void Switch(OpenGLGPUContext *pContext, OpenGLGPUShaderProgram *pCurrentProgram); // update the local constant buffers for this shader with pending values void CommitLocalConstantBuffers(OpenGLGPUContext *pContext); // unbind from a context, resetting all shader states void Unbind(OpenGLGPUContext *pContext); // --- internal query api --- uint32 InternalGetConstantBufferCount() const { return m_uniformBuffers.GetSize(); } uint32 InternalGetParameterCount() const { return m_parameters.GetSize(); } const ShaderUniformBuffer *GetConstantBuffer(uint32 Index) const { DebugAssert(Index < m_uniformBuffers.GetSize()); return &m_uniformBuffers[Index]; } const ShaderParameter *GetParameter(uint32 Index) const { DebugAssert(Index < m_parameters.GetSize()); return &m_parameters[Index]; } // --- internal parameter api --- void InternalSetParameterValue(OpenGLGPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue); void InternalSetParameterValueArray(OpenGLGPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements); void InternalSetParameterStruct(OpenGLGPUContext *pContext, uint32 parameterIndex, const void *pValue, uint32 valueSize); void InternalSetParameterStructArray(OpenGLGPUContext *pContext, uint32 parameterIndex, const void *pValues, uint32 valueSize, uint32 firstElement, uint32 numElements); void InternalSetParameterResource(OpenGLGPUContext *pContext, uint32 parameterIndex, GPUResource *pResource, OpenGLGPUSamplerState *pLinkedSamplerState); void InternalBindAutomaticParameters(OpenGLGPUContext *pContext); // --- public parameter api --- virtual uint32 GetParameterCount() const override; virtual void GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) override; protected: // arrays typedef MemArray<GPU_VERTEX_ELEMENT_DESC> VertexAttributeArray; typedef MemArray<ShaderUniformBuffer> ConstantBufferArray; typedef MemArray<ShaderParameter> ParameterArray; // shader objects GLuint m_iGLShaderId[SHADER_PROGRAM_STAGE_COUNT]; GLuint m_iGLProgramId; // arrays of above VertexAttributeArray m_vertexAttributes; ConstantBufferArray m_uniformBuffers; ParameterArray m_parameters; // context we are bound to OpenGLGPUContext *m_pBoundContext; }; <file_sep>/Engine/Source/Engine/BlockMesh.h #pragma once #include "Engine/Common.h" #include "Engine/BlockPalette.h" #include "Engine/BlockMeshVolume.h" #include "Renderer/VertexFactories/BlockMeshVertexFactory.h" #include "Renderer/VertexBufferBindingArray.h" namespace Physics { class CollisionShape; } class BlockMesh : public Resource { DECLARE_RESOURCE_TYPE_INFO(BlockMesh, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(BlockMesh); public: static const uint32 MAX_LOD_LEVELS = 10; public: struct Batch { uint32 MaterialIndex; uint32 StartIndex; uint32 IndexCount; }; public: BlockMesh(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~BlockMesh(); const BlockPalette *GetBlockList() const { return m_pPalette; } const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } const uint32 GetLODCount() const { return m_nLODLevels; } const BlockMeshVolume &GetMeshVolume(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume; } const int3 &GetMeshMinCoordinates(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetMinCoordinates(); } const int3 &GetMeshMaxCoordinates(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetMaxCoordinates(); } const uint32 GetMeshWidth(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetWidth(); } const uint32 GetMeshLength(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetLength(); } const uint32 GetMeshHeight(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetHeight(); } const uint8 *GetMeshData(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pLODLevels[LOD].Volume.GetData(); } const Physics::CollisionShape *GetCollisionShape() const { return m_pCollisionShape; } const Batch *GetBatch(uint32 LOD, uint32 i) const { DebugAssert(LOD < m_nLODLevels && i < m_pRenderData[LOD].BatchCount); return &m_pRenderData[LOD].pBatches[i]; } uint32 GetBatchCount(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pRenderData[LOD].BatchCount; } // binary serialization bool Load(const char *resourceName, ByteStream *pStream); // resource binding & device resource management const uint32 GetVertexFactoryFlags() const { return m_vertexFactoryFlags; } VertexBufferBindingArray *GetVertexBuffers(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return &m_pRenderData[LOD].VertexBuffers; } GPUBuffer *GetIndexBuffer(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pRenderData[LOD].pIndexBuffer; } GPU_INDEX_FORMAT GetIndexFormat(uint32 LOD) const { DebugAssert(LOD < m_nLODLevels); return m_pRenderData[LOD].IndexFormat; } bool CreateGPUResources() const; void ReleaseGPUResources() const; bool CheckGPUResources() const; private: bool CreateRenderData(); struct LODLevel { AABox BoundingBox; Sphere BoundingSphere; BlockMeshVolume Volume; }; struct RenderData { const BlockMeshBuilder::Vertex *pVertices; uint32 VertexCount; union { const void *pIndices; const uint16 *pIndices16; const uint32 *pIndices32; }; GPU_INDEX_FORMAT IndexFormat; uint32 IndexCount; const Batch *pBatches; uint32 BatchCount; VertexBufferBindingArray VertexBuffers; GPUBuffer *pIndexBuffer; }; const BlockPalette *m_pPalette; float m_scale; bool m_useAmbientOcclusion; uint32 m_nLODLevels; AABox m_boundingBox; Sphere m_boundingSphere; LODLevel *m_pLODLevels; Physics::CollisionShape *m_pCollisionShape; mutable RenderData *m_pRenderData; mutable uint32 m_vertexFactoryFlags; mutable bool m_bGPUResourcesCreated; }; <file_sep>/Engine/Source/Renderer/RenderProxies/PointLightRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/PointLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" PointLightRenderProxy::PointLightRenderProxy(uint32 entityId, const float3 &position /* = float3::Zero */, const float range /* = 64.0f */, const float3 &color /* = float3::One */, uint32 shadowFlags /* = 0 */, const float falloffExponent /* = 2.0f */) : RenderProxy(entityId), m_enabled(true), m_position(position), m_range(range), m_color(color), m_shadowFlags(shadowFlags), m_falloffExponent(falloffExponent) { UpdateBounds(); } PointLightRenderProxy::~PointLightRenderProxy() { } void PointLightRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_enabled || !pRenderQueue->IsAcceptingLights()) return; RENDER_QUEUE_POINT_LIGHT_ENTRY rcLight; rcLight.Position = m_position; rcLight.Range = m_range; rcLight.InverseRange = 1.0f / m_range; rcLight.LightColor = PixelFormatHelpers::ConvertSRGBToLinear(m_color); rcLight.FalloffExponent = m_falloffExponent; rcLight.ShadowFlags = m_shadowFlags; rcLight.ShadowMapIndex = -1; rcLight.Static = false; pRenderQueue->AddLight(&rcLight); } void PointLightRenderProxy::UpdateBounds() { SetBounds(CalculatePointLightBoundingBox(m_position, m_range), CalculatePointLightBoundingSphere(m_position, m_range)); } void PointLightRenderProxy::SetEnabled(bool newEnabled) { if (!IsInWorld()) { m_enabled = newEnabled; } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newEnabled]() { pThis->m_enabled = newEnabled; }); } } void PointLightRenderProxy::SetPosition(const float3 &newPosition) { if (!IsInWorld()) { m_position = newPosition; UpdateBounds(); } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newPosition]() { pThis->m_position = newPosition; pThis->UpdateBounds(); }); } } void PointLightRenderProxy::SetRange(const float newRange) { if (!IsInWorld()) { m_range = newRange; UpdateBounds(); } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newRange]() { pThis->m_range = newRange; pThis->UpdateBounds(); }); } } void PointLightRenderProxy::SetShadowFlags(uint32 newShadowFlags) { if (!IsInWorld()) { m_shadowFlags = newShadowFlags; } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newShadowFlags]() { pThis->m_shadowFlags = newShadowFlags; }); } } void PointLightRenderProxy::SetColor(const float3 &newColor) { if (!IsInWorld()) { m_color = newColor; } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newColor]() { pThis->m_color = newColor; }); } } void PointLightRenderProxy::SetFalloffExponent(const float newFalloffExponent) { if (!IsInWorld()) { m_falloffExponent = newFalloffExponent; } else { ReferenceCountedHolder<PointLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newFalloffExponent]() { pThis->m_falloffExponent = newFalloffExponent; }); } } AABox PointLightRenderProxy::CalculatePointLightBoundingBox(const float3 &position, float range) { SIMDVector3f lightPosition(position); SIMDVector3f lightRange(range, range, range); SIMDVector3f minBounds(lightPosition - lightRange); SIMDVector3f maxBounds(lightPosition + lightRange); return AABox(minBounds, maxBounds); } Sphere PointLightRenderProxy::CalculatePointLightBoundingSphere(const float3 &position, float range) { return Sphere(position, range); } <file_sep>/Editor/Source/Editor/MapEditor/EditorCreateTerrainDialog.h #pragma once #include "Editor/Common.h" #include "Editor/MapEditor/ui_EditorCreateTerrainDialog.h" #include "Engine/TerrainTypes.h" #include "Engine/TerrainLayerList.h" class EditorCreateTerrainDialog : public QDialog { Q_OBJECT public: EditorCreateTerrainDialog(QWidget *pParent, Qt::WindowFlags windowFlags = 0); ~EditorCreateTerrainDialog(); const TerrainLayerList *GetLayerList() const { return m_pLayerList; } const uint32 GetSectionSize() const { return m_sectionSize; } const uint32 GetUnitsPerPoint() const { return m_unitsPerPoint; } const uint32 GetQuadTreeNodeSize() const { return m_quadTreeNodeSize; } const uint32 GetTextureRepeatInterval() const { return m_textureRepeatInterval; } const TERRAIN_HEIGHT_STORAGE_FORMAT GetStorageFormat() const { return m_storageFormat; } const int32 GetMinHeight() const { return m_minHeight; } const int32 GetMaxHeight() const { return m_maxHeight; } const int32 GetBaseHeight() const { return m_baseHeight; } const bool GetCreateCenterSection() const { return m_createCenterSection; } public Q_SLOTS: private Q_SLOTS: bool Validate(); void OnLayerListChanged(const QString &value); void OnHeightFormatChanged(int currentIndex); void OnCreateButtonTriggered(); void OnCancelButtonTriggered(); private: Ui_EditorCreateTerrainDialog *m_ui; const TerrainLayerList *m_pLayerList; uint32 m_sectionSize; uint32 m_unitsPerPoint; uint32 m_quadTreeNodeSize; uint32 m_textureRepeatInterval; TERRAIN_HEIGHT_STORAGE_FORMAT m_storageFormat; int32 m_minHeight; int32 m_maxHeight; int32 m_baseHeight; bool m_createCenterSection; }; <file_sep>/Editor/Source/Editor/EditorPropertyEditorWidget.h #pragma once #include "Editor/Common.h" #include "Core/PropertyTable.h" #include "Core/PropertyTemplate.h" class ResourceTypeInfo; class EditorEntityPropertyDefinition; class EditorMapWindow; class EditorMap; class EditorResourceSelectionWidget; class EditorPropertyEditorResourcePropertyManager; class EditorPropertyEditorResourceEditorFactory; class EditorVectorEditWidget; class EditorPropertyEditorVectorPropertyManager; class EditorPropertyEditorVectorEditFactory; class EditorPropertyEditorWidget : public QWidget { Q_OBJECT public: EditorPropertyEditorWidget(QWidget *pParent); ~EditorPropertyEditorWidget(); const PropertyTable *GetDestinationPropertyTable() const { return m_pDestinationPropertyTable; } PropertyTable *GetDestinationPropertyTable() { return m_pDestinationPropertyTable; } public Q_SLOTS: // set the title text //void SetTitleText(const char *titleText); // adds a property to the editor bool AddProperty(const PropertyTemplateProperty *pPropertyDefinition, const char *currentValue); // initialize the editor for the specified property template void AddPropertiesFromTemplate(const PropertyTemplate *pTemplate); // clear everything from the property editor void ClearProperties(); // set the property list this editor is connected to void SetDestinationPropertyTable(PropertyTable *pPropertyTable); // update property value from an external source (only updates UI, not table) void UpdatePropertyValue(const char *propertyName, const char *propertyValue); // update property value from bound table (only updates UI) void UpdatePropertyValueFromTable(const char *propertyName); Q_SIGNALS: void OnPropertyValueChange(const char *propertyName, const char *propertyValue); private Q_SLOTS: void OnTreeBrowserCurrentItemChanged(QtBrowserItem *pBrowserItem); void OnPropertyManagerPropertyChanged(QtProperty *pProperty); private: void CreateUI(); void ConnectEvents(); bool GetFinalPropertyValue(const QtProperty *pProperty, String *pPropertyName, String *pPropertyValue); // property managers QtGroupPropertyManager *m_pGroupPropertyManager; QtBoolPropertyManager *m_pBoolPropertyManager; QtStringPropertyManager *m_pStringPropertyManager; QtIntPropertyManager *m_pIntSpinBoxPropertyManager; QtIntPropertyManager *m_pIntSliderPropertyManager; QtDoublePropertyManager *m_pDoubleSpinBoxPropertyManager; QtEnumPropertyManager *m_pEnumPropertyManager; QtFlagPropertyManager *m_pFlagPropertyManager; EditorPropertyEditorResourcePropertyManager *m_pResourcePropertyManager; EditorPropertyEditorVectorPropertyManager *m_pVectorPropertyManager; bool m_supressPropertyUpdates; // ui elements QtTreePropertyBrowser *m_pTreePropertyBrowser; //QLabel *m_pTitleText; QTextEdit *m_pHelpText; // for entities struct PropertyEntry { String PropertyName; const PropertyTemplateProperty *pPropertyDefinition; QtProperty *pProperty; QtAbstractPropertyManager *pPropertyManager; bool OwnsPropertyManager; }; MemArray<PropertyEntry> m_properties; PODArray<QtProperty *> m_categories; PropertyTable *m_pDestinationPropertyTable; }; class EditorPropertyEditorResourcePropertyManager : public QtAbstractPropertyManager { Q_OBJECT public: EditorPropertyEditorResourcePropertyManager(QObject *pParent = NULL); ~EditorPropertyEditorResourcePropertyManager(); QString value(const QtProperty *pProperty) const; const ResourceTypeInfo *resourceType(const QtProperty *pProperty) const; public Q_SLOTS: void setValue(QtProperty *pProperty, const QString &value); void setResourceType(QtProperty *pProperty, const ResourceTypeInfo *pResourceTypeInfo); Q_SIGNALS: void valueChanged(QtProperty *pProperty, const QString &value); protected: virtual QString valueText(const QtProperty *pProperty) const; virtual void initializeProperty(QtProperty *pProperty); virtual void uninitializeProperty(QtProperty *pProperty); private: struct Data { Data() : pResourceTypeInfo(NULL) {} QString val; const ResourceTypeInfo *pResourceTypeInfo; }; typedef QMap<const QtProperty *, Data> PropertyValueMap; PropertyValueMap m_values; }; class EditorPropertyEditorResourceEditorFactory : public QtAbstractEditorFactory<EditorPropertyEditorResourcePropertyManager> { Q_OBJECT public: EditorPropertyEditorResourceEditorFactory(QObject *pParent = NULL); ~EditorPropertyEditorResourceEditorFactory(); protected: virtual void connectPropertyManager(EditorPropertyEditorResourcePropertyManager *pManager); virtual QWidget *createEditor(EditorPropertyEditorResourcePropertyManager *pManager, QtProperty *pProperty, QWidget *pParent); virtual void disconnectPropertyManager(EditorPropertyEditorResourcePropertyManager *pManager); private Q_SLOTS: void slotManagerValueChanged(QtProperty *pProperty, const QString &value); void slotEditorValueChanged(const QString &value); void slotEditorDestroyed(QObject *pEditor); private: typedef QList<EditorResourceSelectionWidget *> EditorList; typedef QMap<QtProperty *, EditorList> PropertyToEditorListMap; typedef QMap<EditorResourceSelectionWidget *, QtProperty *> EditorToPropertyMap; PropertyToEditorListMap m_createdEditors; EditorToPropertyMap m_editorToProperty; }; class EditorPropertyEditorVectorPropertyManager : public QtAbstractPropertyManager { Q_OBJECT public: EditorPropertyEditorVectorPropertyManager(QObject *pParent = NULL); ~EditorPropertyEditorVectorPropertyManager(); uint32 numComponents(const QtProperty *pProperty) const; QString valueString(const QtProperty *pProperty) const; float4 valueVector(const QtProperty *pProperty) const; public Q_SLOTS: void setNumComponents(QtProperty *pProperty, uint32 nComponents); void setValueString(QtProperty *pProperty, const char *value); void setValueVector(QtProperty *pProperty, const float4 &value); Q_SIGNALS: void valueChanged(QtProperty *pProperty, const float4 &value); protected: virtual QString valueText(const QtProperty *pProperty) const; virtual void initializeProperty(QtProperty *pProperty); virtual void uninitializeProperty(QtProperty *pProperty); private: struct Data { Data() : numComponents(4), valueVector(float4::Zero) {} uint32 numComponents; float4 valueVector; }; typedef QMap<const QtProperty *, Data> PropertyValueMap; PropertyValueMap m_values; }; class EditorPropertyEditorVectorEditFactory : public QtAbstractEditorFactory<EditorPropertyEditorVectorPropertyManager> { Q_OBJECT public: EditorPropertyEditorVectorEditFactory(QObject *pParent = NULL); ~EditorPropertyEditorVectorEditFactory(); protected: virtual void connectPropertyManager(EditorPropertyEditorVectorPropertyManager *pManager); virtual QWidget *createEditor(EditorPropertyEditorVectorPropertyManager *pManager, QtProperty *pProperty, QWidget *pParent); virtual void disconnectPropertyManager(EditorPropertyEditorVectorPropertyManager *pManager); private Q_SLOTS: void slotManagerValueChanged(QtProperty *pProperty, const float4 &value); void slotEditorValueChanged(const float4 &value); void slotEditorDestroyed(QObject *pEditor); private: typedef QList<EditorVectorEditWidget *> EditorList; typedef QMap<QtProperty *, EditorList> PropertyToEditorListMap; typedef QMap<EditorVectorEditWidget *, QtProperty *> EditorToPropertyMap; PropertyToEditorListMap m_createdEditors; EditorToPropertyMap m_editorToProperty; }; <file_sep>/DemoGame/Source/DemoGame/Main.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/DemoGame.h" Log_SetChannel(Main); // Pretty much copied from the SDL header #if defined(__WIN32__) || defined(__WINRT__) || defined(__IPHONEOS__) || defined(__ANDROID__) #define main SDL_main #endif // SDL requires the entry point declared without c++ decoration extern "C" int main(int argc, char *argv[]) { // change gamename g_pConsole->SetCVarByName("vfs_gamedir", "DemoGame", true); g_pConsole->ApplyPendingAppCVars(); // set log flags g_pLog->SetConsoleOutputParams(true); g_pLog->SetDebugOutputParams(true); #if defined(__WIN32__) // fix up stdout/stderr on win32 freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); #endif // parse command line g_pConsole->ParseCommandLine(argc, (const char **)argv); g_pConsole->ApplyPendingAppCVars(); // create game instance, and run it DemoGame *pDemoGame = new DemoGame(); int32 result = pDemoGame->MainEntryPoint(); // game has ended, so cleanup delete pDemoGame; return result; } <file_sep>/Engine/Source/Renderer/PrecompiledHeader.cpp #include "Renderer/PrecompiledHeader.h" <file_sep>/Engine/Source/Core/ImageCodecDDS.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "Core/DDSFormat.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Log.h" Log_SetChannel(ImageCodecDDS); class ImageCodecDDS : public ImageCodec { public: const char *GetCodecName() const { return "DDS"; } bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyTable &decoderOptions = PropertyTable::EmptyPropertyList) { uint32 DDSMagic; DDS_HEADER DDSHeader; if (pInputStream->Read(&DDSMagic, sizeof(uint32)) != sizeof(uint32) || DDSMagic != DDS_MAGIC || pInputStream->Read(&DDSHeader, sizeof(DDS_HEADER)) != sizeof(DDS_HEADER)) { Log_ErrorPrintf("ImageCodecDDS::DecodeImage: Reading header failed."); return false; } // determine pixel format PIXEL_FORMAT Format = PIXEL_FORMAT_UNKNOWN; if (DDSHeader.ddspf.dwFlags & DDS_RGB) { Log_ErrorPrintf("ImageCodecDDS::DecodeImage: RGB currently unsupported."); return false; } else if (DDSHeader.ddspf.dwFlags & DDS_FOURCC) { if (DDSHeader.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '1')) Format = PIXEL_FORMAT_BC1_UNORM; else if (DDSHeader.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '3')) Format = PIXEL_FORMAT_BC2_UNORM; else if (DDSHeader.ddspf.dwFourCC == DDS_MAKEFOURCC('D', 'X', 'T', '5')) Format = PIXEL_FORMAT_BC3_UNORM; else { Log_ErrorPrintf("ImageCodecDDS::DecodeImage: Unknown FOURCC %08X", DDSHeader.ddspf.dwFourCC); return false; } } if (Format == PIXEL_FORMAT_UNKNOWN) { Log_ErrorPrintf("ImageCodecDDS::DecodeImage: Could not determine pixel format of image."); return false; } // TODO fix up mipmapping uint32 CurWidth = DDSHeader.dwWidth; uint32 CurHeight = DDSHeader.dwHeight; DebugAssert(DDSHeader.dwDepth == 0); // create image pOutputImage->Create(Format, CurWidth, CurHeight, 1); if (pInputStream->Read(pOutputImage->GetData(), pOutputImage->GetDataSize()) != pOutputImage->GetDataSize()) { Log_ErrorPrintf("ImageCodecDDS::DecodeImage: Failed to read %u bytes of image data."); return false; } return true; } bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyTable &encoderOptions = PropertyTable::EmptyPropertyList) { return false; } }; static ImageCodecDDS g_ImageCodecDDS; ImageCodec *__GetImageCodecDDS() { return &g_ImageCodecDDS; } <file_sep>/Engine/Source/Engine/Font.h #pragma once #include "Core/Resource.h" class Texture2D; enum FONT_TYPE { FONT_TYPE_BITMAP, FONT_TYPE_SIGNED_DISTANCE_FIELD, FONT_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(FontType); } class Font : public Resource { DECLARE_RESOURCE_TYPE_INFO(Font, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(Font); public: struct CharacterData { uint32 CodePoint; float StartU; float EndU; float StartV; float EndV; int32 DrawOffsetX; int32 DrawOffsetY; uint32 DrawWidth; uint32 DrawHeight; float Advance; uint32 TextureIndex; bool IsWhiteSpace; }; public: Font(const ResourceTypeInfo *pTypeInfo = &s_TypeInfo); ~Font(); bool LoadFromStream(const char *fontName, ByteStream *pStream); uint32 GetHeight() const { return m_bestRenderingSize; } const CharacterData *GetCharacterDataForCodePoint(uint32 codePoint) const; const CharacterData *GetCharacterDataByIndex(uint32 index) const { return &m_characterData[index]; } const uint32 GetCharacterDataCount() const { return m_characterData.GetSize(); } const Texture2D *GetTexture(uint32 i) const { return m_textures[i]; } uint32 GetTextureCount() const { return m_textures.GetSize(); } bool CreateDeviceResources() const; void ReleaseDeviceResources() const; template<typename T> bool GetVertex(const CharacterData *pCharacterData, int32 &x, int32 &y, const float &scale, int32 maxX, int32 maxY, T vertices[6]) const { int32 x0, x1; int32 y0, y1; float fx, fy; // check it is valid if (pCharacterData->IsWhiteSpace) { int32 newX = Math::Truncate(Math::Round((float)x + pCharacterData->Advance * scale)); if (newX > maxX) return false; x = newX; return false; } // get quad // the font expects the y coordinate to reference the base line, not the top, so adjust for this // x0 = (int32)Y_ceilf((float)x + pCharacterData->xOffset * scale); // y0 = (int32)Y_ceilf((float)y + pCharacterData->yOffset * scale); // x1 = (int32)Y_ceilf((float)x0 + (float)((pCharacterData->x1 - pCharacterData->x0) * scale)); // y1 = (int32)Y_ceilf((float)y0 + (float)((pCharacterData->y1 - pCharacterData->y0) * scale)); // x0 = (int32)Y_roundf((float)x + pCharacterData->xOffset * scale); // y0 = (int32)Y_roundf((float)y + pCharacterData->yOffset * scale); // x1 = x0 + (int32)Y_roundf((float)(pCharacterData->x1 - pCharacterData->x0) * scale); // y1 = y0 + (int32)Y_roundf((float)(pCharacterData->y1 - pCharacterData->y0) * scale); fx = (float)x + (float)pCharacterData->DrawOffsetX * scale; fy = (float)y + (float)pCharacterData->DrawOffsetY * scale; x0 = (int32)Y_roundf(fx); y0 = (int32)Y_roundf(fy); x1 = (int32)Y_roundf(fx + (float)pCharacterData->DrawWidth * scale); y1 = (int32)Y_roundf(fy + (float)pCharacterData->DrawHeight * scale); // if in range if (x0 > maxX || x1 > maxX || y0 > maxY || y1 > maxY) return false; //x += (int32)Y_ceilf(pCharacterData->Advance * scale); x += (int32)Y_roundf(pCharacterData->Advance * scale); if (pCharacterData->IsWhiteSpace) return false; #define SET_VERTEX(i, px, py, u, v) vertices[i].Position.x = (float)(px); vertices[i].Position.y = (float)(py); \ vertices[i].TexCoord.x = (u); vertices[i].TexCoord.y = (v); // t1 SET_VERTEX(0, x0, y0, pCharacterData->StartU, pCharacterData->StartV); SET_VERTEX(1, x0, y1, pCharacterData->StartU, pCharacterData->EndV); SET_VERTEX(2, x1, y0, pCharacterData->EndU, pCharacterData->StartV); // t2 SET_VERTEX(3, x0, y1, pCharacterData->StartU, pCharacterData->EndV); SET_VERTEX(4, x1, y1, pCharacterData->EndU, pCharacterData->EndV); SET_VERTEX(5, x1, y0, pCharacterData->EndU, pCharacterData->StartV); #undef SET_VERTEX return true; } uint32 GetTextWidth(const char *Text, uint32 nCharacters, float Scale) const; private: uint32 m_bestRenderingSize; MemArray<CharacterData> m_characterData; PODArray<const Texture2D *> m_textures; }; <file_sep>/Engine/Source/MathLib/StringConverters.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/Vectori.h" #include "MathLib/Vectoru.h" #include "MathLib/Quaternion.h" #include "MathLib/Transform.h" #include "MathLib/SIMDVectorf.h" #include "MathLib/SIMDVectori.h" #include "YBaseLib/String.h" namespace StringConverter { Vector2f StringToVector2f(const char *Source); Vector3f StringToVector3f(const char *Source); Vector4f StringToVector4f(const char *Source); void Vector2fToString(String &Destination, const Vector2f &Source); void Vector3fToString(String &Destination, const Vector3f &Source); void Vector4fToString(String &Destination, const Vector4f &Source); Vector2i StringToVector2i(const char *Source); Vector3i StringToVector3i(const char *Source); Vector4i StringToVector4i(const char *Source); Vector2u StringToVector2u(const char *Source); Vector3u StringToVector3u(const char *Source); Vector4u StringToVector4u(const char *Source); void Vector2iToString(String &Destination, const Vector2i &Source); void Vector3iToString(String &Destination, const Vector3i &Source); void Vector4iToString(String &Destination, const Vector4i &Source); void Vector2uToString(String &Destination, const Vector2u &Source); void Vector3uToString(String &Destination, const Vector3u &Source); void Vector4uToString(String &Destination, const Vector4u &Source); SIMDVector2f StringToSIMDVector2f(const char *Source); SIMDVector3f StringToSIMDVector3f(const char *Source); SIMDVector4f StringToSIMDVector4f(const char *Source); void SIMDVector2fToString(String &Destination, const SIMDVector2f &Source); void SIMDVector3fToString(String &Destination, const SIMDVector3f &Source); void SIMDVector4fToString(String &Destination, const SIMDVector4f &Source); SIMDVector2i StringToSIMDVector2i(const char *Source); SIMDVector3i StringToSIMDVector3i(const char *Source); SIMDVector4i StringToSIMDVector4i(const char *Source); void SIMDVector2iToString(String &Destination, const SIMDVector2i &Source); void SIMDVector3iToString(String &Destination, const SIMDVector3i &Source); void SIMDVector4iToString(String &Destination, const SIMDVector4i &Source); Quaternion StringToQuaternion(const char *Source); void QuaternionToString(String &Destination, const Quaternion &Source); void TransformToString(String &dest, const Transform &transform); Transform StringToTranform(const String &str); TinyString Vector2fToString(const Vector2f &Source); TinyString Vector3fToString(const Vector3f &Source); TinyString Vector4fToString(const Vector4f &Source); TinyString Vector2iToString(const Vector2i &Source); TinyString Vector3iToString(const Vector3i &Source); TinyString Vector4iToString(const Vector4i &Source); TinyString Vector2uToString(const Vector2u &Source); TinyString Vector3uToString(const Vector3u &Source); TinyString Vector4uToString(const Vector4u &Source); TinyString SIMDVector2fToString(const SIMDVector2f &Source); TinyString SIMDVector3fToString(const SIMDVector3f &Source); TinyString SIMDVector4fToString(const SIMDVector4f &Source); TinyString SIMDVector2iToString(const SIMDVector2i &Source); TinyString SIMDVector3iToString(const SIMDVector3i &Source); TinyString SIMDVector4iToString(const SIMDVector4i &Source); TinyString QuaternionToString(const Quaternion &Source); SmallString TransformToString(const Transform &Source); } <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphSchema.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderGraphSchema.h" #include "ResourceCompiler/ResourceCompiler.h" #include "YBaseLib/XMLReader.h" Log_SetChannel(ShaderGraphSchema); ShaderGraphSchema *ShaderGraphSchema::GetSchemaForFeatureLevel(ResourceCompilerCallbacks *pCallbacks, RENDERER_FEATURE_LEVEL featureLevel) { static const char *schemaFileNames[RENDERER_FEATURE_LEVEL_COUNT] = { "resources/engine/shadergraph/material_schema_es2.xml", "resources/engine/shadergraph/material_schema_es3.xml", "resources/engine/shadergraph/material_schema_sm4.xml", "resources/engine/shadergraph/material_schema_sm5.xml" }; DebugAssert(featureLevel < RENDERER_FEATURE_LEVEL_COUNT); BinaryBlob *pBlob = pCallbacks->GetFileContents(schemaFileNames[featureLevel]); if (pBlob == nullptr) { Log_ErrorPrintf("ShaderGraphSchema::GetSchemaForFeatureLevel: Failed to get file '%s'", schemaFileNames[featureLevel]); return nullptr; } ByteStream *pStream = pBlob->CreateReadOnlyStream(); ShaderGraphSchema *pSchema = new ShaderGraphSchema(); if (!pSchema->LoadFromXML(schemaFileNames[featureLevel], pStream)) { Log_ErrorPrintf("ShaderGraphSchema::GetSchemaForFeatureLevel: Failed to load file '%s'", schemaFileNames[featureLevel]); pSchema->Release(); pStream->Release(); pBlob->Release(); return nullptr; } pStream->Release(); pBlob->Release(); return pSchema; } ShaderGraphSchema::ShaderGraphSchema() { } ShaderGraphSchema::~ShaderGraphSchema() { for (GlobalDeclaration *pDeclaration : m_globalDeclarations) delete pDeclaration; for (InputDeclaration *pDeclaration : m_inputDeclarations) delete pDeclaration; for (OutputDeclaration *pDeclaration : m_outputDeclarations) delete pDeclaration; } bool ShaderGraphSchema::LoadFromXML(const char *FileName, ByteStream *pStream) { uint32 i; // set name //m_strName = FileName; //m_strName.Erase(m_strName.RFind('.')); // parse the xml XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName) || !xmlReader.SkipToElement("schema")) { Log_ErrorPrintf("ShaderGraphSchemaManager::GetSchema: Could not initialize XML reader for schema file '%s'.", FileName); return false; } // get version attribute uint32 version = StringConverter::StringToUInt32(xmlReader.FetchAttributeString("version")); if (version < 3 || version > 3) { xmlReader.PrintError("invalid schema version: %u", version); return false; } // iterate nodes for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT && !xmlReader.IsEmptyElement()) { int32 schemaSelection = xmlReader.Select("globals|inputs|outputs"); if (schemaSelection < 0) return false; switch (schemaSelection) { // globals case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 inputsSelection = xmlReader.Select("global"); if (inputsSelection < 0) return false; const char *nameStr = xmlReader.FetchAttribute("name"); const char *displayNameStr = xmlReader.FetchAttribute("displayname"); const char *typeStr = xmlReader.FetchAttribute("type"); const char *variableStr = xmlReader.FetchAttribute("variable"); if (nameStr == nullptr || typeStr == nullptr || variableStr == nullptr) { xmlReader.PrintError("Incomplete input declaration."); return false; } SHADER_PARAMETER_TYPE valueType; if (!NameTable_TranslateType(NameTables::ShaderParameterType, typeStr, &valueType, true)) { xmlReader.PrintError("Unknown value type '%s'", typeStr); return false; } // make sure it doesn't already exist for (i = 0; i < m_inputDeclarations.GetSize(); i++) { if (Y_stricmp(m_inputDeclarations[i]->Name, nameStr) == 0) { xmlReader.PrintError("duplicate input declared: '%s'", nameStr); return false; } } // allocate+fill it GlobalDeclaration *pGlobalDeclaration = new GlobalDeclaration(); pGlobalDeclaration->Name = nameStr; if (displayNameStr != nullptr) pGlobalDeclaration->DisplayName = displayNameStr; pGlobalDeclaration->Type = valueType; pGlobalDeclaration->VariableName = variableStr; pGlobalDeclaration->OutputDesc.Name = pGlobalDeclaration->Name; pGlobalDeclaration->OutputDesc.Type = pGlobalDeclaration->Type; // add to list m_globalDeclarations.Add(pGlobalDeclaration); // skip element if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { if (!xmlReader.ExpectEndOfElementName("globals")) return false; break; } else { UnreachableCode(); } } } } break; // inputs case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 inputsSelection = xmlReader.Select("input"); if (inputsSelection < 0) return false; const char *nameStr = xmlReader.FetchAttribute("name"); const char *typeStr = xmlReader.FetchAttribute("type"); if (nameStr == nullptr || typeStr == nullptr) { xmlReader.PrintError("Incomplete input declaration."); return false; } SHADER_PARAMETER_TYPE valueType; if (!NameTable_TranslateType(NameTables::ShaderParameterType, typeStr, &valueType, true)) { xmlReader.PrintError("Unknown value type '%s'", typeStr); return false; } // make sure it doesn't already exist for (i = 0; i < m_inputDeclarations.GetSize(); i++) { if (Y_stricmp(m_inputDeclarations[i]->Name, nameStr) == 0) { xmlReader.PrintError("duplicate input declared: '%s'", nameStr); return false; } } // allocate+fill it InputDeclaration *pInputDeclaration = new InputDeclaration(); pInputDeclaration->Name = nameStr; pInputDeclaration->Type = valueType; pInputDeclaration->OutputDesc.Name = pInputDeclaration->Name; pInputDeclaration->OutputDesc.Type = pInputDeclaration->Type; // add to list m_inputDeclarations.Add(pInputDeclaration); // handle access if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { if (xmlReader.Select("access") < 0) break; const char *stageStr = xmlReader.FetchAttribute("stage"); const char *defineStr = xmlReader.FetchAttribute("define"); const char *variableStr = xmlReader.FetchAttribute("variable"); if (stageStr == nullptr || variableStr == nullptr) { xmlReader.PrintError("Incomplete access declaration."); return false; } SHADER_PROGRAM_STAGE stageIndex; if (!NameTable_TranslateType(NameTables::ShaderProgramStage, stageStr, &stageIndex, true)) { xmlReader.PrintError("Unknown stage: '%s'", stageStr); return false; } if (defineStr != nullptr) pInputDeclaration->Access[stageIndex].DefineName = defineStr; pInputDeclaration->Access[stageIndex].VariableName = variableStr; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { if (!xmlReader.ExpectEndOfElementName("input")) return false; break; } else { UnreachableCode(); } } } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { if (!xmlReader.ExpectEndOfElementName("inputs")) return false; break; } else { UnreachableCode(); } } } } break; // outputs case 2: { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 outputsSelection = xmlReader.Select("output"); if (outputsSelection < 0) return false; const char *stageStr = xmlReader.FetchAttribute("stage"); const char *nameStr = xmlReader.FetchAttribute("name"); const char *displayNameStr = xmlReader.FetchAttribute("displayname"); const char *defineStr = xmlReader.FetchAttribute("define"); const char *typeStr = xmlReader.FetchAttribute("type"); const char *signatureStr = xmlReader.FetchAttribute("signature"); const char *defaultStr = xmlReader.FetchAttribute("default"); if (stageStr == nullptr || nameStr == nullptr || typeStr == nullptr || signatureStr == nullptr || defaultStr == nullptr) { xmlReader.PrintError("Incomplete output declaration."); return false; } SHADER_PARAMETER_TYPE valueType; if (!NameTable_TranslateType(NameTables::ShaderParameterType, typeStr, &valueType, true)) { xmlReader.PrintError("Unknown value type '%s'", typeStr); return false; } SHADER_PROGRAM_STAGE stageIndex; if (!NameTable_TranslateType(NameTables::ShaderProgramStage, stageStr, &stageIndex, true)) { xmlReader.PrintError("Unknown stage: '%s'", stageStr); return false; } // make sure it doesn't already exist for (i = 0; i < m_outputDeclarations.GetSize(); i++) { if (Y_stricmp(m_outputDeclarations[i]->Name, nameStr) == 0) { xmlReader.PrintError("duplicate output declared: '%s'", nameStr); return false; } } // allocate+fill it OutputDeclaration *pOutputDeclaration = new OutputDeclaration(); pOutputDeclaration->Name = nameStr; pOutputDeclaration->DisplayName = displayNameStr; if (defineStr != nullptr) pOutputDeclaration->DefineName = defineStr; pOutputDeclaration->Stage = stageIndex; pOutputDeclaration->Type = valueType; pOutputDeclaration->FunctionSignature = signatureStr; pOutputDeclaration->DefaultValue = defaultStr; pOutputDeclaration->InputDesc.Name = pOutputDeclaration->Name; pOutputDeclaration->InputDesc.Type = pOutputDeclaration->Type; pOutputDeclaration->InputDesc.DefaultValue = pOutputDeclaration->DefaultValue; pOutputDeclaration->InputDesc.Optional = false; // add to list m_outputDeclarations.Add(pOutputDeclaration); // skip element if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { if (!xmlReader.ExpectEndOfElementName("outputs")) return false; break; } else { UnreachableCode(); } } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { if (!xmlReader.ExpectEndOfElementName("schema")) return false; break; } else { UnreachableCode(); } } return true; } <file_sep>/Engine/Source/Engine/Camera.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Camera.h" #include "Renderer/RendererTypes.h" // takes from z-up to y-up DEFINE_CONST_MATRIX4X4F(s_ZUpToYUpMatrix, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); DEFINE_CONST_MATRIX4X4F(s_YUpToZUpMatrix, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); const float4x4 &Camera::GetWorldToCameraCoordinateSystemTransform() { return s_ZUpToYUpMatrix; } const float4x4 &Camera::GetCameraToWorldCoordinateSystemTransform() { return s_YUpToZUpMatrix; } float3 Camera::TransformFromWorldToCameraCoordinateSystem(const float3 &v) { return float3(v.x, v.z, -v.y); } float3 Camera::TransformFromCameraToWorldCoordinateSystem(const float3 &v) { return float3(v.x, -v.z, v.y); } Camera::Camera() : m_position(float3::Zero), m_rotation(Quaternion::Identity), m_projectionType(CAMERA_PROJECTION_TYPE_PERSPECTIVE), m_nearPlaneDistance(1.0f), m_farPlaneDistance(1000.0f), m_objectCullDistance(1000.0f), m_orthoWindowLeft(-100.0f), m_orthoWindowRight(100.0f), m_orthoWindowTop(100.0f), m_orthoWindowBottom(-100.0f), m_perspectiveFieldOfView(45.0f), m_perspectiveAspect(640.0f / 480.0f) { UpdateViewMatrix(); UpdateProjectionMatrix(); } Camera::Camera(const Camera &camera) : m_position(camera.m_position), m_rotation(camera.m_rotation), m_objectCullDistance(camera.m_objectCullDistance), m_projectionType(camera.m_projectionType), m_nearPlaneDistance(camera.m_nearPlaneDistance), m_farPlaneDistance(camera.m_farPlaneDistance), m_orthoWindowLeft(camera.m_orthoWindowLeft), m_orthoWindowRight(camera.m_orthoWindowRight), m_orthoWindowTop(camera.m_orthoWindowTop), m_orthoWindowBottom(camera.m_orthoWindowBottom), m_perspectiveFieldOfView(camera.m_perspectiveFieldOfView), m_perspectiveAspect(camera.m_perspectiveAspect), m_frustum(camera.m_frustum), m_viewMatrix(camera.m_viewMatrix), m_projectionMatrix(camera.m_projectionMatrix), m_inverseViewMatrix(camera.m_inverseViewMatrix), m_inverseProjectionMatrix(camera.m_inverseProjectionMatrix), m_viewProjectionMatrix(camera.m_viewProjectionMatrix), m_inverseViewProjectionMatrix(camera.m_inverseViewProjectionMatrix) { } Camera::Camera(const float4x4 &viewMatrix) : Camera() { SetViewMatrix(viewMatrix); } float3 Camera::CalculateViewDirection() const { return (m_rotation * float3::UnitY); } float3 Camera::CalculateUpDirection() const { return (m_rotation * float3::UnitZ); } float Camera::CalculateDepthToPoint(const float3 &point) const { return Math::Abs(m_viewMatrix.GetRow(1).xyz().Dot(point) + m_viewMatrix(1, 3)); } float Camera::CalculateDepthToBox(const AABox &box) const { // // optimize me! // float minDistance = Y_FLT_INFINITE; // float3 boxCorners[8]; // box.GetCornerPoints(boxCorners); // for (uint32 i = 0; i < 8; i++) // minDistance = Min(minDistance, Math::Abs(m_viewMatrix.GetRow(1).xyz().Dot(boxCorners[i]) + m_viewMatrix(1, 3))); // return minDistance; // transform box to view space AABox transformedBox(box.GetTransformed(m_viewMatrix)); return Math::Abs(transformedBox.GetMinBounds().z); } void Camera::SetPosition(const float3 &position) { m_position = position; UpdateViewMatrix(); UpdateFrustum(); } void Camera::SetRotation(const Quaternion &rotation) { m_rotation = rotation; UpdateViewMatrix(); UpdateFrustum(); } void Camera::SetViewMatrix(const float4x4 &viewMatrix) { m_position = -viewMatrix.GetColumn(3).xyz(); m_rotation = Quaternion::FromFloat4x4(viewMatrix); // switch to z-up m_viewMatrix = s_ZUpToYUpMatrix * viewMatrix; m_inverseViewMatrix = m_viewMatrix.Inverse(); UpdateFrustum(); } void Camera::LookAt(const float3 &eye, const float3 &target, const float3 &upVector) { // transform to camera space float3 cameraSpaceEye(TransformFromWorldToCameraCoordinateSystem(eye)); float3 cameraSpaceTarget(TransformFromWorldToCameraCoordinateSystem(target)); float3 cameraSpaceUp(TransformFromWorldToCameraCoordinateSystem(upVector)); // add some distance to target if (cameraSpaceEye == cameraSpaceTarget) cameraSpaceTarget.z -= 1.0f; // get matrix float4x4 lookAtMatrix = float4x4::MakeLookAtViewMatrix(cameraSpaceEye, cameraSpaceTarget, cameraSpaceUp); // go back to world space //lookAtMatrix = GetCameraToWorldCoordinateSystemTransform() * lookAtMatrix; // update rotation m_position = eye; m_rotation = Quaternion::FromFloat4x4(lookAtMatrix).Inverse(); UpdateViewMatrix(); UpdateFrustum(); } void Camera::LookDirection(const float3 &direction, const float3 &upVector) { // transform to camera space float3 cameraSpaceDirection(TransformFromWorldToCameraCoordinateSystem(direction).Normalize()); float3 cameraSpaceUp(TransformFromWorldToCameraCoordinateSystem(upVector)); // get matrix float4x4 lookAtMatrix = float4x4::MakeLookAtViewMatrix(float3::Zero, cameraSpaceDirection, cameraSpaceUp); // go back to world space //lookAtMatrix = GetCameraToWorldCoordinateSystemTransform() * lookAtMatrix; // update rotation m_rotation = Quaternion::FromFloat4x4(lookAtMatrix).Inverse(); UpdateViewMatrix(); UpdateFrustum(); } void Camera::SetProjectionType(CAMERA_PROJECTION_TYPE type) { DebugAssert(type < CAMERA_PROJECTION_TYPE_COUNT); m_projectionType = type; UpdateProjectionMatrix(); UpdateFrustum(); } void Camera::SetNearFarPlaneDistances(float nearDistance, float farDistance) { m_nearPlaneDistance = nearDistance; m_farPlaneDistance = farDistance; UpdateProjectionMatrix(); UpdateFrustum(); } void Camera::SetNearPlaneDistance(float distance) { m_nearPlaneDistance = distance; UpdateProjectionMatrix(); UpdateFrustum(); } void Camera::SetFarPlaneDistance(float distance) { m_farPlaneDistance = distance; UpdateProjectionMatrix(); UpdateFrustum(); } void Camera::SetProjectionMatrix(const float4x4 &projectionMatrix) { m_projectionMatrix = projectionMatrix; m_inverseProjectionMatrix = projectionMatrix.Inverse(); UpdateFrustum(); } float4x4 Camera::GetBiasedProjectionMatrix(float amount) const { if (m_projectionType == CAMERA_PROJECTION_TYPE_PERSPECTIVE) return float4x4::MakePerspectiveProjectionMatrix(Math::DegreesToRadians(m_perspectiveFieldOfView), m_perspectiveAspect, m_nearPlaneDistance + amount, m_farPlaneDistance + amount); else return float4x4::MakeOrthographicOffCenterProjectionMatrix(m_orthoWindowLeft, m_orthoWindowRight, m_orthoWindowBottom, m_orthoWindowTop, m_nearPlaneDistance + amount, m_farPlaneDistance + amount); } void Camera::SetPerspectiveFieldOfView(float fieldOfView) { m_perspectiveFieldOfView = fieldOfView; if (m_projectionType == CAMERA_PROJECTION_TYPE_PERSPECTIVE) { UpdateProjectionMatrix(); UpdateFrustum(); } } void Camera::SetPerspectiveAspect(float aspect) { m_perspectiveAspect = aspect; if (m_projectionType == CAMERA_PROJECTION_TYPE_PERSPECTIVE) { UpdateProjectionMatrix(); UpdateFrustum(); } } void Camera::SetPerspectiveAspect(float width, float height) { DebugAssert(height != 0.0f); SetPerspectiveAspect(width / height); } void Camera::SetOrthographicWindow(float left, float right, float bottom, float top) { m_orthoWindowLeft = left; m_orthoWindowRight = right; m_orthoWindowBottom = bottom; m_orthoWindowTop = top; if (m_projectionType == CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC) { UpdateProjectionMatrix(); UpdateFrustum(); } } void Camera::SetOrthographicWindow(float width, float height) { // create width/height around the center float halfWidth = width / 2.0f; float halfHeight = height / 2.0f; SetOrthographicWindow(-halfWidth, halfWidth, -halfHeight, halfHeight); } Ray Camera::GetPickRay(float x, float y, const RENDERER_VIEWPORT *pViewport) const { #if 0 // calculate projection space coordinates float tx = (float)(x - (int32)pViewport->TopLeftX) / (float)pViewport->Width; float ty = (float)(y - (int32)pViewport->TopLeftY) / (float)pViewport->Height; float px = (2.0f * tx) - 1.0f; float py = -((2.0f * ty) - 1.0f); // and vectors float4 projSpaceOrigin(px, py, 0.0f, 1.0f); float4 projSpaceTarget(px, py, 1.0f, 1.0f); // transform to world space Vector4 worldSpaceOrigin(m_inverseViewProjectionMatrix * projSpaceOrigin); Vector4 worldSpaceTarget(m_inverseViewProjectionMatrix * projSpaceTarget); worldSpaceOrigin /= worldSpaceOrigin.w; worldSpaceTarget /= worldSpaceTarget.w; //Log_DevPrintf("WS Origin = %s, Target = %s", StringConverter::Float3ToString(worldSpaceOrigin.xyz()).GetCharArray(), StringConverter::Float3ToString(worldSpaceTarget.xyz()).GetCharArray()); return Ray(worldSpaceOrigin.xyz(), worldSpaceTarget.xyz()); #else float3 worldSpaceOrigin(Unproject(float3(x, y, 0.0f), pViewport)); float3 worldSpaceTarget(Unproject(float3(x, y, 1.0f), pViewport)); //Log_DevPrintf("WS Origin = %s, Target = %s", StringConverter::Float3ToString(worldSpaceOrigin.xyz()).GetCharArray(), StringConverter::Float3ToString(worldSpaceTarget.xyz()).GetCharArray()); return Ray(worldSpaceOrigin, worldSpaceTarget); #endif } Camera &Camera::operator=(const Camera &camera) { m_position = camera.m_position; m_rotation = camera.m_rotation; m_objectCullDistance = camera.m_objectCullDistance; m_projectionType = camera.m_projectionType; m_nearPlaneDistance = camera.m_nearPlaneDistance; m_farPlaneDistance = camera.m_farPlaneDistance; m_orthoWindowLeft = camera.m_orthoWindowLeft; m_orthoWindowRight = camera.m_orthoWindowRight; m_orthoWindowBottom = camera.m_orthoWindowBottom; m_orthoWindowTop = camera.m_orthoWindowTop; m_perspectiveFieldOfView = camera.m_perspectiveFieldOfView; m_perspectiveAspect = camera.m_perspectiveAspect; m_frustum = camera.m_frustum; m_viewMatrix = camera.m_viewMatrix; m_projectionMatrix = camera.m_projectionMatrix; m_inverseViewMatrix = camera.m_inverseViewMatrix; m_inverseProjectionMatrix = camera.m_inverseProjectionMatrix; m_viewProjectionMatrix = camera.m_viewProjectionMatrix; m_inverseViewProjectionMatrix = camera.m_inverseViewProjectionMatrix; return *this; } void Camera::UpdateViewMatrix() { float4x4 rotationMatrix(m_rotation.Inverse().GetMatrix4x4()); float4x4 translationMatrix(float4x4::MakeTranslationMatrix(-m_position)); // transform to y-up last // note: unlike object transforms, we first translate then rotate, since we are // moving our view around a point, rather than moving a rotated object to a point m_viewMatrix = s_ZUpToYUpMatrix * rotationMatrix * translationMatrix; m_inverseViewMatrix = m_viewMatrix.Inverse(); } void Camera::UpdateProjectionMatrix() { if (m_projectionType == CAMERA_PROJECTION_TYPE_PERSPECTIVE) m_projectionMatrix = float4x4::MakePerspectiveProjectionMatrix(Math::DegreesToRadians(m_perspectiveFieldOfView), m_perspectiveAspect, m_nearPlaneDistance, m_farPlaneDistance); else m_projectionMatrix = float4x4::MakeOrthographicOffCenterProjectionMatrix(m_orthoWindowLeft, m_orthoWindowRight, m_orthoWindowBottom, m_orthoWindowTop, m_nearPlaneDistance, m_farPlaneDistance); m_inverseProjectionMatrix = m_projectionMatrix.Inverse(); } void Camera::UpdateFrustum() { // update view+projection matrices m_viewProjectionMatrix = m_projectionMatrix * m_viewMatrix; //m_inverseViewProjectionMatrix = m_inverseViewMatrix * m_inverseProjectionMatrix; m_inverseViewProjectionMatrix = m_viewProjectionMatrix.Inverse(); // update frustum m_frustum.SetFromMatrix(m_viewProjectionMatrix); } float3 Camera::Project(const float3 &worldCoordindates, const RENDERER_VIEWPORT *pViewport) const { // assume w=1 float4 projectedPosition(m_viewProjectionMatrix * float4(worldCoordindates, 1.0f)); // project back to w==1 projectedPosition /= projectedPosition.w; // transform from ndc to viewport coordinates float x = (float)pViewport->TopLeftX + (1.0f + projectedPosition.x) * (float)pViewport->Width / 2.0f; float y = (float)pViewport->TopLeftY + (1.0f - projectedPosition.y) * (float)pViewport->Height / 2.0f; float z = pViewport->MinDepth + projectedPosition.z * (pViewport->MaxDepth - pViewport->MinDepth); // make vector return float3(x, y, z); } float3 Camera::Unproject(const float3 &windowCoordinates, const RENDERER_VIEWPORT *pViewport) const { float x = 2.0f * (windowCoordinates.x - (float)pViewport->TopLeftX) / (float)pViewport->Width - 1.0f; float y = 1.0f - 2.0f * (windowCoordinates.y - (float)pViewport->TopLeftY) / (float)pViewport->Height; float z = (windowCoordinates.z - pViewport->MinDepth) / (pViewport->MaxDepth - pViewport->MinDepth); // transform back to world space float4 worldSpace(m_inverseViewProjectionMatrix * float4(x, y, z, 1.0f)); return worldSpace.xyz() / worldSpace.w; } <file_sep>/Engine/Source/Engine/OverlayConsole.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/OverlayConsole.h" #include "Engine/Font.h" #include "Engine/SDLHeaders.h" #include "Renderer/Renderer.h" #include "Renderer/MiniGUIContext.h" Log_SetChannel(OverlayConsole); OverlayConsole::OverlayConsole() { // default settings m_pFont = g_pRenderer->GetFixedResources()->GetDebugFont(); m_pFont->AddRef(); m_fontSize = 16; // colors m_titleBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(120, 30, 50, 220); m_titleForegroundColor = MAKE_COLOR_R8G8B8A8_UNORM(220, 220, 220, 255); m_inputBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 150); m_inputBorderColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); m_inputForegroundColor = MAKE_COLOR_R8G8B8A8_UNORM(220, 220, 220, 255); m_inputCaretColor = MAKE_COLOR_R8G8B8A8_UNORM(220, 220, 220, 220); m_bufferBackgroundColor = MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 0, 180); m_bufferBorderColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); // message colors Y_memset(m_messageColors, 255, sizeof(m_messageColors)); m_messageColors[LOGLEVEL_ERROR] = MAKE_COLOR_R8G8B8A8_UNORM(255, 0, 0, 255); // error m_messageColors[LOGLEVEL_WARNING] = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255); // warning m_messageColors[LOGLEVEL_SUCCESS] = MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255); // success m_messageColors[LOGLEVEL_INFO] = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); // info m_messageColors[LOGLEVEL_PERF] = MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 255, 255); // perf m_messageColors[LOGLEVEL_DEV] = MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255); // dev m_messageColors[LOGLEVEL_PROFILE] = MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 255, 255); // profile m_messageColors[LOGLEVEL_TRACE] = MAKE_COLOR_R8G8B8A8_UNORM(200, 200, 200, 255); // trace // maximum message length m_maxMessageLength = 160; m_maxCommandHistory = 32; // buffered level m_logBufferLevel = LOGLEVEL_TRACE; m_logBufferSize = 1048576 - 1; m_logBufferContents.Reserve(m_logBufferSize); // display level m_logDisplayLevel = LOGLEVEL_DEV; m_logDisplayLines = 10; m_logDisplayTime = 5.0f; m_logFadeOutTime = 2.0f; // state m_activationState = ACTIVATION_STATE_NONE; m_logBufferLinesScrolledVertical = 0; m_logBufferCharactersScrolledHorizontal = 0; m_logBufferLines = 0; m_inputCaretPosition = 0; m_currentCommandHistoryIndex = 0; // hook into log system Log::GetInstance().RegisterCallback(LogCallbackTrampoline, reinterpret_cast<void *>(this)); } OverlayConsole::~OverlayConsole() { // unhook from log system Log::GetInstance().UnregisterCallback(LogCallbackTrampoline, reinterpret_cast<void *>(this)); // delete display entries for (uint32 i = 0; i < m_logDisplayEntries.GetSize(); i++) delete m_logDisplayEntries[i]; // release vars SAFE_RELEASE(m_pFont); } void OverlayConsole::SetBufferLogLevel(LOGLEVEL level) { } void OverlayConsole::SetDisplayLogLevel(LOGLEVEL level) { } void OverlayConsole::LogCallbackTrampoline(void *pUserParam, const char *channelName, const char *functionName, LOGLEVEL level, const char *message) { OverlayConsole *pThis = reinterpret_cast<OverlayConsole *>(pUserParam); pThis->LogCallback(channelName, functionName, level, message); } void OverlayConsole::LogCallback(const char *channelName, const char *functionName, LOGLEVEL level, const char *message) { SmallString formattedMessage; Log::FormatLogMessageForDisplay(channelName, functionName, level, message, [](const char *text, void *str) { ((String *)str)->AppendString(text); }, (void *)&formattedMessage); uint32 messageLength = Min(formattedMessage.GetLength(), m_maxMessageLength); MutexLock lock(m_lock); // protect this since it is converted to a char if (level >= LOGLEVEL_COUNT) level = (LOGLEVEL)(LOGLEVEL_COUNT - 1); // append to display buffer if (level <= m_logDisplayLevel) { if (m_logDisplayEntries.GetSize() >= m_logDisplayLines) { delete m_logDisplayEntries[0]; m_logDisplayEntries.PopFront(); } LogDisplayEntry *pEntry = new LogDisplayEntry; pEntry->Message = formattedMessage; pEntry->Color = (level < countof(m_messageColors)) ? m_messageColors[level] : m_messageColors[0]; pEntry->TimeRemaining = m_logDisplayTime; m_logDisplayEntries.Add(pEntry); } // append to store buffer? if (level <= m_logBufferLevel) { // clear out the earliest lines to make room for this line while ((messageLength + m_logBufferContents.GetLength() + 1) >= m_logBufferSize) { // find the first line terminator uint32 linePosition = 0; for (; linePosition < m_logBufferContents.GetLength(); linePosition++) { if (m_logBufferContents[linePosition] < 0) break; } // nuke everything up to and including this point m_logBufferContents.Erase(0, linePosition + 1); if (m_logBufferLines > 0) m_logBufferLines--; } // append it to the buffer uint32 charactersWritten = 0; for (uint32 i = 0; i < messageLength; i++) { // character range 240-255 are reserved for internal use, so replace these characters with a . char ch = formattedMessage[i]; if (ch <= 0 || ch == '\n') continue; // append it m_logBufferContents.AppendCharacter(ch); charactersWritten++; } // written? if (charactersWritten > 0) { m_logBufferContents.AppendCharacter(-((char)level + 1)); m_logBufferLines++; } } } void OverlayConsole::Update(float timeDifference) { MutexLock lock(m_lock); // fade out/delete display entries for (uint32 i = 0; i < m_logDisplayEntries.GetSize(); ) { LogDisplayEntry *pEntry = m_logDisplayEntries[i]; // update the time pEntry->TimeRemaining -= timeDifference; if (pEntry->TimeRemaining <= 0.0f) { delete pEntry; m_logDisplayEntries.PopFront(); continue; } // update the color if (pEntry->TimeRemaining <= m_logFadeOutTime) { float fractionRemaining = pEntry->TimeRemaining / m_logFadeOutTime; uint32 alpha = (uint32)Math::Truncate(fractionRemaining * 255.0f); // change alpha value pEntry->Color = (pEntry->Color & 0x00FFFFFF) | (alpha << 24); } // move to next entry i++; } } void OverlayConsole::Draw(MiniGUIContext *pGUIContext) const { // uses manual lock/unlock to allow the flush to occur after the lock is released pGUIContext->PushManualFlush(); m_lock.Lock(); switch (m_activationState) { case ACTIVATION_STATE_NONE: DrawQueuedMessages(pGUIContext); break; case ACTIVATION_STATE_INPUT_ONLY: DrawQueuedMessages(pGUIContext); DrawInputOnly(pGUIContext); break; case ACTIVATION_STATE_PARTIAL: DrawPartial(pGUIContext); break; } m_lock.Unlock(); pGUIContext->PopManualFlush(); } void OverlayConsole::DrawQueuedMessages(MiniGUIContext *pGUIContext) const { // draw display entries const uint32 X_INDENT = 16; const uint32 Y_INDENT = 16; const uint32 Y_SPACING = 2; uint32 currentY = Y_INDENT; for (uint32 i = 0; i < m_logDisplayEntries.GetSize(); i++) { const LogDisplayEntry *pEntry = m_logDisplayEntries[i]; DebugAssert(pEntry->TimeRemaining >= 0.0f); pGUIContext->DrawText(m_pFont, m_fontSize, X_INDENT, currentY, pEntry->Message, pEntry->Color, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); currentY += m_fontSize + Y_SPACING; } } void OverlayConsole::DrawInputOnly(MiniGUIContext *pGUIContext) const { const int32 INPUTFIELD_HEIGHT = 24; const int32 VERTICAL_PADDING = 4; String displayLine; MINIGUI_RECT regionRect = pGUIContext->GetTopRect(); MINIGUI_RECT rect; // push some space around SET_MINIGUI_RECT(&rect, regionRect.left, regionRect.right, regionRect.bottom - INPUTFIELD_HEIGHT, regionRect.bottom); pGUIContext->PushRect(&rect); // draw the input box background SET_MINIGUI_RECT(&rect, 0, regionRect.right, 0, INPUTFIELD_HEIGHT); pGUIContext->DrawFilledRect(&rect, m_inputBackgroundColor); // draw the input box contents SET_MINIGUI_RECT(&rect, 0, regionRect.right, VERTICAL_PADDING, VERTICAL_PADDING + m_fontSize); displayLine.Format("> %s", m_inputBuffer.GetCharArray()); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, displayLine, m_inputForegroundColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); // calculate the text width with the current caret position uint32 caretOffset = m_pFont->GetTextWidth("> ", 2, (float)m_fontSize / (float)m_pFont->GetHeight()); uint32 caretSize = m_pFont->GetTextWidth(" ", 1, (float)m_fontSize / (float)m_pFont->GetHeight()); if (m_inputBuffer.GetLength() > 0) { uint32 textWidth = m_pFont->GetTextWidth(m_inputBuffer, Min((int32)m_inputBuffer.GetLength(), m_inputCaretPosition), (float)m_fontSize / (float)m_pFont->GetHeight()); caretOffset += textWidth; } // draw the caret SET_MINIGUI_RECT(&rect, caretOffset, caretOffset + caretSize, VERTICAL_PADDING, VERTICAL_PADDING + m_fontSize); pGUIContext->DrawFilledRect(&rect, m_inputCaretColor); // pop rect stack pGUIContext->PopRect(); } void OverlayConsole::DrawPartial(MiniGUIContext *pGUIContext) const { // config const int32 HORIZONTAL_MARGIN = 0; const int32 VERTICAL_MARGIN = 0; const int32 HORIZONTAL_PADDING = 4; const int32 VERTICAL_PADDING = 4; const int32 BOX_PADDING = 2; const int32 TITLE_START_OFFSET = 0; const int32 TITLE_END_OFFSET = 16 + VERTICAL_PADDING; const int32 LINE_START_OFFSET = TITLE_END_OFFSET; const int32 LINE_END_OFFSET = LINE_START_OFFSET + 320 + BOX_PADDING; const int32 INPUT_START_OFFSET = LINE_END_OFFSET + 1; const int32 INPUT_END_OFFSET = INPUT_START_OFFSET + 16 + BOX_PADDING; // rects SmallString displayLine; MINIGUI_RECT regionRect = pGUIContext->GetTopRect(); MINIGUI_RECT rect; // adjust region rect for margins regionRect.left += HORIZONTAL_MARGIN; regionRect.right -= HORIZONTAL_MARGIN; regionRect.top += VERTICAL_MARGIN; regionRect.bottom -= VERTICAL_MARGIN; // draw the title background SET_MINIGUI_RECT(&rect, regionRect.left, regionRect.right, regionRect.top + TITLE_START_OFFSET, regionRect.top + TITLE_END_OFFSET); pGUIContext->DrawFilledRect(&rect, m_titleBackgroundColor); // draw the title text SET_MINIGUI_RECT(&rect, regionRect.left + HORIZONTAL_PADDING, regionRect.right - HORIZONTAL_PADDING, regionRect.top + TITLE_START_OFFSET, regionRect.top + TITLE_END_OFFSET); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, "Console", m_titleForegroundColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, "press ` to close", m_titleForegroundColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT, MINIGUI_VERTICAL_ALIGNMENT_TOP); // draw the box background SET_MINIGUI_RECT(&rect, regionRect.left, regionRect.right, regionRect.top + LINE_START_OFFSET, regionRect.top + LINE_END_OFFSET); pGUIContext->DrawFilledRect(&rect, m_bufferBackgroundColor); // and the border //SET_MINIGUI_RECT(&rect, regionRect.left + 1, regionRect.right, regionRect.top, regionRect.top + LINE_END_OFFSET); //pGUIContext->DrawRect(&rect, m_bufferBorderColor); // anything in the buffer? if (m_logBufferContents.GetLength() > 1) { // find the starting point of the buffer int32 displayStartPosition = m_logBufferContents.GetLength() - 1; // move up to the scroll point if (m_logBufferLinesScrolledVertical > 0) { int32 caretIndicatorPosition = regionRect.top + LINE_END_OFFSET - m_fontSize - BOX_PADDING; SET_MINIGUI_RECT(&rect, regionRect.left + HORIZONTAL_PADDING, regionRect.right - HORIZONTAL_PADDING, caretIndicatorPosition, caretIndicatorPosition + m_fontSize + 1); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, "^^^^ ", MAKE_COLOR_R8G8B8A8_UNORM(230, 230, 230, 255), false, MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT, MINIGUI_VERTICAL_ALIGNMENT_TOP); for (uint32 i = 0; i < m_logBufferLinesScrolledVertical; i++) { if (displayStartPosition == 0) break; // remove the log level displayStartPosition--; // and each character while (displayStartPosition > 0 && m_logBufferContents[displayStartPosition] > 0) displayStartPosition--; } } // display these strings int32 currentStartOffset = regionRect.top + LINE_END_OFFSET - m_fontSize - BOX_PADDING; while (displayStartPosition > 0 && currentStartOffset >= LINE_START_OFFSET) { // wipe the last line displayLine.Clear(); // extract the log level unsigned char messageLevel = static_cast<unsigned char>(-(m_logBufferContents[displayStartPosition]) - 1); DebugAssert(messageLevel < countof(m_messageColors)); displayStartPosition--; // add each character in while (displayStartPosition >= 0 && m_logBufferContents[displayStartPosition] > 0) { displayLine.PrependCharacter(m_logBufferContents[displayStartPosition]); displayStartPosition--; } // draw the line if (displayLine.GetLength() > 0) { // if horizontal scroll is enabled, remove characters for (uint32 i = 0; i < m_logBufferCharactersScrolledHorizontal && displayLine.GetLength() > 0; i++) displayLine.Erase(0, 1); // set rect and draw SET_MINIGUI_RECT(&rect, regionRect.left + HORIZONTAL_PADDING, regionRect.right - HORIZONTAL_PADDING, currentStartOffset, currentStartOffset + m_fontSize + 1); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, displayLine, m_messageColors[messageLevel], false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); } // move the cursor currentStartOffset -= m_fontSize; if (currentStartOffset < 0 || displayStartPosition <= 0) break; } } // draw the input box background SET_MINIGUI_RECT(&rect, regionRect.left, regionRect.right, regionRect.top + INPUT_START_OFFSET, regionRect.top + INPUT_END_OFFSET); pGUIContext->DrawFilledRect(&rect, m_inputBackgroundColor); // draw the seperator line pGUIContext->DrawLine(int2(regionRect.left, regionRect.top + INPUT_START_OFFSET), int2(regionRect.right, regionRect.top + INPUT_START_OFFSET), m_inputBorderColor); // draw the input box contents SET_MINIGUI_RECT(&rect, regionRect.left + HORIZONTAL_PADDING, regionRect.right - HORIZONTAL_PADDING, regionRect.top + INPUT_START_OFFSET, regionRect.top + INPUT_END_OFFSET); displayLine.Format("> %s", m_inputBuffer.GetCharArray()); pGUIContext->DrawText(m_pFont, m_fontSize, &rect, displayLine, m_inputForegroundColor, false, MINIGUI_HORIZONTAL_ALIGNMENT_LEFT, MINIGUI_VERTICAL_ALIGNMENT_TOP); // calculate the text width with the current caret position uint32 caretOffset = regionRect.left + HORIZONTAL_PADDING + m_pFont->GetTextWidth("> ", 2, (float)m_fontSize / (float)m_pFont->GetHeight()); uint32 caretSize = m_pFont->GetTextWidth(" ", 1, (float)m_fontSize / (float)m_pFont->GetHeight()); if (m_inputBuffer.GetLength() > 0) { uint32 textWidth = m_pFont->GetTextWidth(m_inputBuffer, Min((int32)m_inputBuffer.GetLength(), m_inputCaretPosition), (float)m_fontSize / (float)m_pFont->GetHeight()); caretOffset += textWidth; } // draw the caret SET_MINIGUI_RECT(&rect, caretOffset, caretOffset + caretSize, regionRect.top + INPUT_START_OFFSET, regionRect.top + INPUT_END_OFFSET); pGUIContext->DrawFilledRect(&rect, m_inputCaretColor); } bool OverlayConsole::OnInputEvent(const SDL_Event *pEvent) { MutexLock lock(m_lock); // handle the case that we're not active first if (m_activationState == ACTIVATION_STATE_NONE) { if (pEvent->type == SDL_KEYDOWN && pEvent->key.keysym.sym == SDLK_BACKQUOTE) { // change activation state if (m_activationState == ACTIVATION_STATE_NONE) m_activationState = ACTIVATION_STATE_INPUT_ONLY; else if (m_activationState == ACTIVATION_STATE_INPUT_ONLY) m_activationState = ACTIVATION_STATE_PARTIAL; else if (m_activationState == ACTIVATION_STATE_PARTIAL) //m_activationState = ACTIVATION_STATE_FULL; //else m_activationState = ACTIVATION_STATE_NONE; // consume it return true; } // not using the event return false; } // // we are active! // // hitting the ` key? if (pEvent->type == SDL_KEYDOWN) { if (pEvent->key.keysym.sym == SDLK_BACKQUOTE) { // change activation state if (m_activationState == ACTIVATION_STATE_NONE) m_activationState = ACTIVATION_STATE_INPUT_ONLY; else if (m_activationState == ACTIVATION_STATE_INPUT_ONLY) m_activationState = ACTIVATION_STATE_PARTIAL; //else if (m_activationState == ACTIVATION_STATE_PARTIAL) //m_activationState = ACTIVATION_STATE_FULL; else m_activationState = ACTIVATION_STATE_NONE; // consume it return true; } // scroll up? if (pEvent->key.keysym.sym == SDLK_PAGEUP) { if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { if (m_logBufferCharactersScrolledHorizontal > 0) m_logBufferCharactersScrolledHorizontal--; } else { m_logBufferLinesScrolledVertical++; } return true; } // scroll down? if (pEvent->key.keysym.sym == SDLK_PAGEDOWN) { if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { m_logBufferCharactersScrolledHorizontal++; } else { if (m_logBufferLinesScrolledVertical > 0) m_logBufferLinesScrolledVertical--; } return true; } if (pEvent->key.keysym.sym == SDLK_HOME) { // scroll to start of display? if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) m_logBufferLinesScrolledVertical = (m_logBufferLines > 0) ? (m_logBufferLines - 1) : 0; else m_inputCaretPosition = 0; } // scroll to end? if (pEvent->key.keysym.sym == SDLK_END) { if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) m_logBufferLinesScrolledVertical = 0; else m_inputCaretPosition = m_inputBuffer.GetLength(); return true; } // left arrow key? if (pEvent->key.keysym.sym == SDLK_LEFT) { // ctrl+left? if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { // find the previous space, if not, the start of the input if (m_inputBuffer.GetLength() > 0 && m_inputCaretPosition > 0) { m_inputCaretPosition--; // currently on a whitespace? if (m_inputBuffer[m_inputCaretPosition] == ' ') { // back up until we find something not whitespace while (m_inputCaretPosition > 0) { m_inputCaretPosition--; if (m_inputBuffer[m_inputCaretPosition] != ' ') break; } } // find the next whitespace while (m_inputCaretPosition > 0) { if (m_inputBuffer[m_inputCaretPosition - 1] == ' ') break; m_inputCaretPosition--; } } } else { // normal left if (m_inputCaretPosition > 0) m_inputCaretPosition--; } return true; } // right arrow key? if (pEvent->key.keysym.sym == SDLK_RIGHT) { // ctrl+right? if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { // find the previous space, if not, the start of the input if ((uint32)m_inputCaretPosition < m_inputBuffer.GetLength()) { m_inputCaretPosition++; while ((uint32)m_inputCaretPosition < m_inputBuffer.GetLength()) { if (m_inputBuffer[m_inputCaretPosition] == ' ') { m_inputCaretPosition = Min((int32)m_inputBuffer.GetLength(), m_inputCaretPosition + 1); break; } m_inputCaretPosition++; } // skip over any consecutive whitespace while ((uint32)m_inputCaretPosition < m_inputBuffer.GetLength()) { if (m_inputBuffer[m_inputCaretPosition] != ' ') break; m_inputCaretPosition++; } } } else { // normal if (m_inputCaretPosition < (int32)m_inputBuffer.GetLength()) m_inputCaretPosition++; } return true; } // hitting the enter key? submit the command if (pEvent->key.keysym.sym == SDLK_RETURN) { if (m_inputBuffer.GetLength() > 0) { // release the lock to execute the command lock.Unlock(); // actually execute it bool executeResult = g_pConsole->ExecuteText(m_inputBuffer.GetCharArray()); // re-lock after execution lock.Lock(); // clear history position m_currentCommandHistoryIndex = -1; // add to history if (m_commandHistory.GetSize() == m_maxCommandHistory) m_commandHistory.OrderedRemove(0); m_commandHistory.Add(m_inputBuffer); // succeeded? if (executeResult) { // if execution succeeded and we are in input only mode, immediately hide the console if (m_activationState == ACTIVATION_STATE_INPUT_ONLY) SetActivationState(ACTIVATION_STATE_NONE); } // wipe out buffer m_inputBuffer.Clear(); m_inputCaretPosition = 0; } return true; } // hitting the backspace key? if (pEvent->key.keysym.sym == SDLK_BACKSPACE) { if (m_inputBuffer.GetLength() > 0) { m_inputBuffer.Erase(-1); m_inputCaretPosition = Max(m_inputCaretPosition - 1, (int32)0); } return true; } // hitting the autocomplete key? if (pEvent->key.keysym.sym == SDLK_TAB) { // unlock before doing auto-completion lock.Unlock(); g_pConsole->HandleAutoCompletion(m_inputBuffer); // re-lock to modify variables lock.Lock(); m_inputCaretPosition = m_inputBuffer.GetLength(); return true; } // hitting the up arrow? if (pEvent->key.keysym.sym == SDLK_UP) { if (m_currentCommandHistoryIndex == -1) { if (m_commandHistory.GetSize() > 0) { m_currentCommandHistoryIndex = m_commandHistory.GetSize() - 1; m_inputBuffer = m_commandHistory[m_currentCommandHistoryIndex]; m_inputCaretPosition = m_inputBuffer.GetLength(); } } else if (m_currentCommandHistoryIndex > 0) { m_currentCommandHistoryIndex--; m_inputBuffer = m_commandHistory[m_currentCommandHistoryIndex]; m_inputCaretPosition = m_inputBuffer.GetLength(); } } // hitting the down arrow? if (pEvent->key.keysym.sym == SDLK_DOWN) { if (m_currentCommandHistoryIndex >= 0) { if ((m_currentCommandHistoryIndex + 1) < (int32)m_commandHistory.GetSize()) { m_currentCommandHistoryIndex++; m_inputBuffer = m_commandHistory[m_currentCommandHistoryIndex]; m_inputCaretPosition = m_inputBuffer.GetLength(); } else { // clear it m_currentCommandHistoryIndex = -1; m_inputBuffer.Clear(); m_inputCaretPosition = 0; } } } // ctrl+v paste if (pEvent->key.keysym.sym == SDLK_v && SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { // get clipboard text char *clipboardText = SDL_GetClipboardText(); if (clipboardText != nullptr) { uint32 textLength = Y_strlen(clipboardText); m_inputBuffer.InsertString(m_inputCaretPosition, clipboardText, textLength); m_inputCaretPosition += textLength; SDL_free(clipboardText); } return true; } // ctrl+w remove everything, but not including the last space if (pEvent->key.keysym.sym == SDLK_w && SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) { int32 lastPos = m_inputBuffer.RFind(' '); if (lastPos >= 0) m_inputBuffer.Erase((lastPos != ((int32)m_inputBuffer.GetLength() - 1)) ? (lastPos + 1) : (lastPos)); else m_inputBuffer.Clear(); return true; } } // handle text being entered if (pEvent->type == SDL_TEXTINPUT) { // hack: remove the ` keystrokes if (pEvent->text.text[0] == '`') return true; // ignore anything pressed with ctrl if (SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) return true; // hitting the help key? if (pEvent->text.text[0] == '?') { lock.Unlock(); g_pConsole->HandlePartialHelp(m_inputBuffer); return true; } // clear current history position m_currentCommandHistoryIndex = -1; // append the text uint32 insertStringLength = Y_strlen(pEvent->text.text); m_inputBuffer.InsertString(m_inputCaretPosition, pEvent->text.text, insertStringLength); m_inputCaretPosition += insertStringLength; return true; } // handle mouse wheel scrolling if (pEvent->type == SDL_MOUSEWHEEL) { m_logBufferCharactersScrolledHorizontal = Max((int32)m_logBufferCharactersScrolledHorizontal + pEvent->wheel.x, 0); m_logBufferLinesScrolledVertical = Max((int32)m_logBufferLinesScrolledVertical + pEvent->wheel.y, 0); return true; } // block all other keyboard events while we're active if (pEvent->type == SDL_KEYDOWN || pEvent->type == SDL_KEYUP) return true; else return false; } <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUOutputBuffer.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" #include "OpenGLRenderer/OpenGLGPUTexture.h" class OpenGLGPUOutputBuffer : public GPUOutputBuffer { public: OpenGLGPUOutputBuffer(SDL_Window *pSDLWindow, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType, bool externalWindow); virtual ~OpenGLGPUOutputBuffer(); // virtual methods virtual uint32 GetWidth() const override { return m_width; } virtual uint32 GetHeight() const override { return m_height; } virtual void SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) override; // views SDL_Window *GetSDLWindow() const { return m_pSDLWindow; } PIXEL_FORMAT GetBackBufferFormat() const { return m_backBufferFormat; } PIXEL_FORMAT GetDepthStencilBufferFormat() const { return m_depthStencilBufferFormat; } void Resize(uint32 width, uint32 height); private: SDL_Window *m_pSDLWindow; uint32 m_width; uint32 m_height; PIXEL_FORMAT m_backBufferFormat; PIXEL_FORMAT m_depthStencilBufferFormat; RENDERER_VSYNC_TYPE m_vsyncType; bool m_externalWindow; }; <file_sep>/Engine/Source/MapCompiler/MapSourceTerrainData.h #pragma once #include "MapCompiler/MapSource.h" #include "Engine/TerrainTypes.h" #include "Engine/TerrainLayerList.h" #include "Engine/TerrainSection.h" #include "Engine/TerrainQuadTree.h" #include "YBaseLib/ProgressCallbacks.h" class Camera; class TerrainSection; class TerrainRenderer; class TerrainStreamingCallbacks; // todo: shrink method class MapSourceTerrainData { friend class MapSource; public: class EditCallbacks { public: virtual void OnSectionCreated(int32 sectionX, int32 sectionY) {} virtual void OnSectionDeleted(int32 sectionX, int32 sectionY) {} virtual void OnSectionLoaded(const TerrainSection *pSection) {} virtual void OnSectionUnloaded(const TerrainSection *pSection) {} virtual void OnSectionLayersModified(const TerrainSection *pSection) {} virtual void OnSectionPointHeightModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY) {} virtual void OnSectionPointLayersModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY) {} }; enum HeightmapImportScaleType { HeightmapImportScaleType_None, HeightmapImportScaleType_Downscale, HeightmapImportScaleType_Upscale, HeightmapImportScaleType_Count, }; public: MapSourceTerrainData(MapSource *pMapSource); ~MapSourceTerrainData(); public: // accessors const TerrainParameters *GetParameters() const { return &m_parameters; } const TerrainLayerListGenerator *GetLayerListGenerator() const { return m_pLayerListGenerator; } const TerrainLayerList *GetLayerList() const { return m_pLayerList; } // callbacks interface EditCallbacks *GetEditCallbacks() { return m_pEditCallbacks; } void SetEditCallbacks(EditCallbacks *pEditCallbacks) { m_pEditCallbacks = pEditCallbacks; } // test if changed bool IsChanged() const; // lod queries int32 GetMinSectionX() const { return m_minSectionX; } int32 GetMinSectionY() const { return m_minSectionY; } int32 GetMaxSectionX() const { return m_maxSectionX; } int32 GetMaxSectionY() const { return m_maxSectionY; } int32 GetSectionCount() const { return m_sectionCount; } int32 GetSectionCountX() const { return m_sectionCountX; } int32 GetSectionCountY() const { return m_sectionCountY; } // helper function to calculate tile bounds AABox CalculateSectionBoundingBox(int32 sectionX, int32 sectionY) const; // helper function to determine world bounds AABox CalculateTerrainBoundingBox() const; // helper function to calculate the section of the specified global indices int2 CalculateSectionForPoint(int32 globalX, int32 globalY) const; // helper function to calculate the section of a specified position int2 CalculateSectionForPosition(const float3 &position) const; // helper function to calculate the section and indexed position of the specified global indices void CalculateSectionAndOffsetForPoint(int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, int32 globalX, int32 globalY) const; // helper function to calculate the section and index position closest to the specified position void CalculateSectionAndOffsetForPosition(int32 *pSectionX, int32 *pSectionY, uint32 *pIndexX, uint32 *pIndexY, const float3 &position) const; // helper function to calculate a global point from a position int2 CalculatePointForPosition(const float3 &position) const; // helper function for going from point to position float3 CalculatePositionForPoint(int32 globalX, int32 globalY) const; // helper function to calculate global coordinates from the specified section and offsets void CalculatePointForSectionAndOffset(int32 *pGlobalX, int32 *pGlobalY, int32 sectionX, int32 sectionY, uint32 offsetX, uint32 offsetY) const; // tile availability bool IsSectionAvailable(int32 sectionX, int32 sectionY) const; bool IsSectionLoaded(int32 sectionX, int32 sectionY) const; // tile accessors const TerrainSection *GetSection(int32 sectionX, int32 sectionY) const; TerrainSection *GetSection(int32 sectionX, int32 sectionY); // creates a blank terrain void Create(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // enumerates available sections, format is Callback(int32 sectionX, int32 sectionY) template<class T> void EnumerateAvailableSections(T callback) const; // enumerates loaded sections, format is Callback(const TerrainSection *pSection) template<class T> void EnumerateLoadedSections(T callback) const; template<class T> void EnumerateLoadedSections(T callback); // ensures that all sections are loaded (loads all lods) bool LoadAllSections(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // unloads all sections void UnloadAllSections(bool discardChanges = false); // coarse then fine iteration of sections to render in a frustum // callback is in format of callback(const TerrainSection *pSection) template<typename CALLBACK_TYPE> void EnumerateSectionsInFrustum(const Frustum &frustum, CALLBACK_TYPE callback) const; // callback is in format of callback(const TerrainSection *pSection) template<typename CALLBACK_TYPE> void EnumerateSectionsOverlappingBox(const AABox &box, CALLBACK_TYPE callback); // callback is in format of callback(const TerrainSection *pSection) template<typename CALLBACK_TYPE> void EnumerateSectionsIntersectingRay(const Ray &ray, CALLBACK_TYPE callback); // callback is in format of callback(const float3 vertices[4]) template<typename CALLBACK_TYPE> void EnumerateQuadsIntersectingBox(const AABox &box, CALLBACK_TYPE callback); // ray casting bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint); ////////////////////////////////////////////////////////////////////////// // Editor Methods ////////////////////////////////////////////////////////////////////////// // section loading/unloading bool LoadSection(int32 sectionX, int32 sectionY); void UnloadSection(int32 sectionX, int32 sectionY); // ensure the adjacent sections (+/- x/y) are loaded bool EnsureAdjacentSectionsLoaded(int32 sectionX, int32 sectionY); // section create/delete // if the index is negative on either axis, the terrain will be moved to fit in the new section uint32 CreateSections(const int2 *pNewSectionIndices, uint32 newSectionCount, float createHeight, uint8 createLayer, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void DeleteSections(const int2 *pSectionIndices, uint32 sectionCount, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // single versions of above bool CreateSection(int32 sectionX, int32 sectionY, float createHeight, uint8 createLayer, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void DeleteSection(int32 sectionX, int32 sectionY, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); void DeleteAllSections(); // changing heights/weights float GetPointHeight(int32 pointX, int32 pointY); float GetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer); bool SetPointHeight(int32 pointX, int32 pointY, float height); bool AddPointHeight(int32 pointX, int32 pointY, float mod); bool SetPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float weight, bool renormalize = true); bool AddPointLayerWeight(int32 pointX, int32 pointY, uint8 layer, float amount, bool renormalize = true); // import a heightmap bool ImportHeightmap(const Image *pHeightmap, int32 startSectionX, int32 startSectionY, float minHeight, float maxHeight, HeightmapImportScaleType scaleType, uint32 scaleAmount, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // rebuilds quadtree on all section bool RebuildQuadTree(uint32 newLODCount, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // helpers static void MakeTerrainStorageFileName(String &str, int32 sectionX, int32 sectionY); static int32 GetSectionArrayIndex(int32 sectionX, int32 sectionY, int32 minSectionX, int32 minSectionY, int32 maxSectionX, int32 maxSectionY); int32 GetSectionArrayIndex(int32 sectionX, int32 sectionY) const; private: // compile the layer list TerrainLayerList *CompileLayerList(const TerrainLayerListGenerator *pGenerator, BinaryBlob **ppStoreBlob); // create a new terrain bool Create(const TerrainParameters *pParameters, const TerrainLayerListGenerator *pLayerListGenerator, ProgressCallbacks *pProgressCallbacks); // load an existing terrain bool Load(ProgressCallbacks *pProgressCallbacks); // save it bool Save(ProgressCallbacks *pProgressCallbacks); // delete it void Delete(); private: // rebuild section array void ResizeSectionArray(int32 newMinSectionX, int32 newMinSectionY, int32 newMaxSectionX, int32 newMaxSectionY); // find the default layer index uint8 GetDefaultLayer() const; // copy weights from one section's point to another void CopySectionPointWeights(const TerrainSection *pSourceSection, uint32 sourceOffsetX, uint32 sourceOffsetY, TerrainSection *pDestinationSection, uint32 destinationOffsetX, uint32 destinationOffsetY); // handle edge point updates void HandleEdgePointsHeightUpdate(TerrainSection *pSection, uint32 offsetX, uint32 offsetY); void HandleEdgePointsWeightUpdate(TerrainSection *pSection, uint32 offsetX, uint32 offsetY); // normalize a single point's layer weights bool NormalizePointLayerWeights(TerrainSection *pSection, uint32 offsetX, uint32 offsetY); // normalize a section's layer weights bool NormalizeSectionLayerWeights(TerrainSection *pSection); // remove low weighted points from a single point bool RemovePointLayerWeights(TerrainSection *pSection, uint32 offsetX, uint32 offsetY, float threshold = 0.1f, bool normalizeAfterRemove = true); // remove low weighted points from a section bool RemoveSectionLayerWeights(TerrainSection *pSection, float threshold = 0.1f, bool normalizeAfterRemove = true); // map we are associated with MapSource *m_pMapSource; // parameters TerrainParameters m_parameters; // layer list const TerrainLayerListGenerator *m_pLayerListGenerator; const TerrainLayerList *m_pLayerList; bool m_layerListChanged; // section storage int32 m_minSectionX; int32 m_minSectionY; int32 m_maxSectionX; int32 m_maxSectionY; int32 m_sectionCountX; int32 m_sectionCountY; int32 m_sectionCount; TerrainSection **m_ppSections; BitSet32 m_availableSectionMask; bool m_availableSectionsChanged; // for faster iteration when unloading/streaming, we store loaded sections here PODArray<TerrainSection *> m_loadedSections; // track deleted sections, that way upon save the storage can be nuked for them typedef MemArray<int2> DeletedSectionArray; DeletedSectionArray m_deletedSections; // edit callbacks EditCallbacks *m_pEditCallbacks; }; // enumeration template<class T> void MapSourceTerrainData::EnumerateAvailableSections(T callback) const { uint32 sectionIndex = 0; for (int32 y = m_minSectionY; y <= m_maxSectionY; y++) { for (int32 x = m_minSectionX; x <= m_maxSectionX; x++) { if (m_availableSectionMask[sectionIndex++]) callback(x, y); } } } template<class T> void MapSourceTerrainData::EnumerateLoadedSections(T callback) const { for (int32 i = 0; i < m_sectionCount; i++) { const TerrainSection *pSection = m_ppSections[i]; if (pSection != NULL) callback(pSection); } } template<class T> void MapSourceTerrainData::EnumerateLoadedSections(T callback) { for (int32 i = 0; i < m_sectionCount; i++) { TerrainSection *pSection = m_ppSections[i]; if (pSection != NULL) callback(pSection); } } template<typename CALLBACK_TYPE> void MapSourceTerrainData::EnumerateSectionsInFrustum(const Frustum &frustum, CALLBACK_TYPE callback) const { // get a box containing the frustum // this will be much wider than necessary at the camera origin, but provides an estimation for a starting point AABox frustumBoundingBox(frustum.GetBoundingAABox()); // find the sections this box encompasses int2 startSection(CalculateSectionForPosition(frustumBoundingBox.GetMinBounds())); int2 endSection(CalculateSectionForPosition(frustumBoundingBox.GetMaxBounds())); // clamp to terrain bounds int32 startSectionX = Math::Clamp(startSection.x, m_minSectionX, m_maxSectionX); int32 startSectionY = Math::Clamp(startSection.y, m_minSectionY, m_maxSectionY); int32 endSectionX = Math::Clamp(endSection.x, m_minSectionX, m_maxSectionX); int32 endSectionY = Math::Clamp(endSection.y, m_minSectionY, m_maxSectionY); // iterate over these sections for (int32 sectionY = startSectionY; sectionY <= endSectionY; sectionY++) { for (int32 sectionX = startSectionX; sectionX <= endSectionX; sectionX++) { // loaded? const TerrainSection *pSection = GetSection(sectionX, sectionY); if (pSection != NULL) { // do finer bounds test if (frustum.AABoxIntersection(pSection->GetBoundingBox())) callback(pSection); } } } } template<typename CALLBACK_TYPE> void MapSourceTerrainData::EnumerateSectionsOverlappingBox(const AABox &box, CALLBACK_TYPE callback) { // get the min/max regions int2 searchSectionMin(CalculateSectionForPosition(box.GetMinBounds())); int2 searchSectionMax(CalculateSectionForPosition(box.GetMaxBounds())); // clamp to terrain bounds int32 startSectionX = Math::Clamp(searchSectionMin.x, m_minSectionX, m_maxSectionX); int32 startSectionY = Math::Clamp(searchSectionMin.y, m_minSectionY, m_maxSectionY); int32 endSectionX = Math::Clamp(searchSectionMax.x, m_minSectionX, m_maxSectionX); int32 endSectionY = Math::Clamp(searchSectionMax.y, m_minSectionY, m_maxSectionY); // iterate over these sections for (int32 sectionY = startSectionY; sectionY <= endSectionY; sectionY++) { for (int32 sectionX = startSectionX; sectionX <= endSectionX; sectionX++) { const TerrainSection *pSection = GetSection(sectionX, sectionY); if (pSection == NULL) continue; callback(pSection); } } } template<typename CALLBACK_TYPE> void MapSourceTerrainData::EnumerateSectionsIntersectingRay(const Ray &ray, CALLBACK_TYPE callback) { // get ray bounding box AABox rayBoundingBox(ray.GetAABox()); // get the min/max regions int2 searchSectionMin(CalculateSectionForPosition(rayBoundingBox.GetMinBounds())); int2 searchSectionMax(CalculateSectionForPosition(rayBoundingBox.GetMaxBounds())); // clamp to terrain bounds int32 startSectionX = Math::Clamp(searchSectionMin.x, m_minSectionX, m_maxSectionX); int32 startSectionY = Math::Clamp(searchSectionMin.y, m_minSectionY, m_maxSectionY); int32 endSectionX = Math::Clamp(searchSectionMax.x, m_minSectionX, m_maxSectionX); int32 endSectionY = Math::Clamp(searchSectionMax.y, m_minSectionY, m_maxSectionY); // iterate over these sections for (int32 sectionY = startSectionY; sectionY <= endSectionY; sectionY++) { for (int32 sectionX = startSectionX; sectionX <= endSectionX; sectionX++) { const TerrainSection *pSection = GetSection(sectionX, sectionY); if (pSection == NULL) continue; // test if it intersects the top level node of the quadtree, since this has the correct heights if (!ray.AABoxIntersection(pSection->GetQuadTree()->GetTopLevelNode()->GetBoundingBox())) continue; callback(pSection); } } } template<typename CALLBACK_TYPE> void MapSourceTerrainData::EnumerateQuadsIntersectingBox(const AABox &box, CALLBACK_TYPE callback) { // find the sections this overlaps EnumerateSectionsOverlappingBox(box, [this, box, callback](const TerrainSection *pSection) { uint32 unitsPerPoint = m_parameters.Scale; float fUnitsPerPoint = (float)unitsPerPoint; int32 sectionSizeMinusOne = (int32)m_parameters.SectionSize - 1; // get region min bounds float3 sectionMinBounds(pSection->GetBoundingBox().GetMinBounds()); // find the overlapping points float3 regionMinPoints((box.GetMinBounds() - sectionMinBounds) / fUnitsPerPoint); float3 regionMaxPoints((box.GetMaxBounds() - sectionMinBounds) / fUnitsPerPoint); // quantize them int32 startXi = Math::Truncate(Math::Floor(regionMinPoints.x)); int32 startYi = Math::Truncate(Math::Floor(regionMinPoints.y)); int32 endXi = Math::Truncate(Math::Ceil(regionMaxPoints.x)); int32 endYi = Math::Truncate(Math::Ceil(regionMaxPoints.y)); // fix up range uint32 startX = (uint32)Min(Max(startXi, (int32)0), sectionSizeMinusOne); uint32 startY = (uint32)Min(Max(startYi, (int32)0), sectionSizeMinusOne); uint32 endX = (uint32)Min(Max(endXi, (int32)0), sectionSizeMinusOne); uint32 endY = (uint32)Min(Max(endYi, (int32)0), sectionSizeMinusOne); // iterate over points float3 triangleVertices[4]; for (uint32 ly = startY; ly <= endY; ly++) { for (uint32 lx = startX; lx <= endX; lx++) { // first triangle triangleVertices[0].Set(sectionMinBounds.x + (float)((lx) * unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), pSection->GetHeightMapValue(lx, ly + 1)); triangleVertices[1].Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly + 1) * unitsPerPoint), pSection->GetHeightMapValue(lx + 1, ly + 1)); triangleVertices[2].Set(sectionMinBounds.x + (float)((lx) * unitsPerPoint), sectionMinBounds.y + (float)((ly) * unitsPerPoint), pSection->GetHeightMapValue(lx, ly)); triangleVertices[3].Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly) * unitsPerPoint), pSection->GetHeightMapValue(lx + 1, ly)); callback(triangleVertices); /* // second triangle triangleVertices[1][0] = triangleVertices[0][2]; triangleVertices[1][1] = triangleVertices[0][1]; triangleVertices[1][2].Set(sectionMinBounds.x + (float)((lx + 1) * unitsPerPoint), sectionMinBounds.y + (float)((ly) * unitsPerPoint), pSection->GetHeightMapValue(lx + 1, ly)); // invoke callback callback(triangleVertices[0]); callback(triangleVertices[1]); */ } } }); } <file_sep>/Engine/Source/ResourceCompiler/SkeletalAnimationGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Engine/SkeletalAnimation.h" #include "Core/PropertyTable.h" struct ResourceCompilerCallbacks; class SkeletalAnimationGenerator { public: class TransformTrack { friend class SkeletalAnimationGenerator; public: struct KeyFrame { KeyFrame() {} KeyFrame(const float time, const float3 &position, const Quaternion &rotation, const float3 &scale) : m_time(time), m_position(position), m_rotation(rotation), m_scale(scale) {} const float &GetTime() const { return m_time; } const float3 &GetPosition() const { return m_position; } const Quaternion &GetRotation() const { return m_rotation; } const float3 &GetScale() const { return m_scale; } void SetTime(float time) { m_time = time; } void SetPosition(const float3 &position) { m_position = position; } void SetRotation(const Quaternion &rotation) { m_rotation = rotation; } void SetScale(const float3 &scale) { m_scale = scale; } private: float m_time; float3 m_position; Quaternion m_rotation; float3 m_scale; }; public: TransformTrack(); ~TransformTrack(); // keyframes const uint32 GetKeyFrameCount() const { return m_keyFrames.GetSize(); } const KeyFrame *GetKeyFrame(uint32 index) const; KeyFrame *GetKeyFrame(uint32 index); KeyFrame *AddKeyFrame(float time, const float3 &position = float3::Zero, const Quaternion &rotation = Quaternion::Identity, const float3 &scale = float3::One); void DeleteKeyFrame(uint32 index); void SortKeyFrames(); // duration const float GetDuration() const { return m_duration; } void UpdateDuration(); // get keyframe for a time, may fail const KeyFrame *GetKeyFrameForTime(float time) const; // interpolate and calculate keyframe for the specified time void InterpolateKeyFrameAtTime(float time, KeyFrame *pOutKeyFrame) const; // clip keyframes void ClipKeyFrames(float startTime, float endTime); // optimize the animation sequence void Optimize(); private: MemArray<KeyFrame> m_keyFrames; float m_duration; }; class BoneTrack : public TransformTrack { public: BoneTrack(const char *boneName); ~BoneTrack(); // referenced bone const String &GetBoneName() const { return m_boneName; } void SetBoneName(const char *boneName) { m_boneName = boneName; } private: String m_boneName; }; class RootMotionTrack : public TransformTrack { public: RootMotionTrack(); ~RootMotionTrack(); private: }; public: SkeletalAnimationGenerator(); ~SkeletalAnimationGenerator(); // properties const PropertyTable *GetPropertyTable() const { return &m_properties; } // skeleton const String &GetSkeletonName() const { return m_skeletonName; } void SetSkeletonName(const char *skeletonName) { m_skeletonName = skeletonName; } // preview mesh const String &GetPreviewMeshName() const; void SetPreviewMeshName(const char *previewMeshName); // duration const float GetDuration() const { return m_duration; } void UpdateDuration(); // bone tracks const BoneTrack *GetBoneTrackByIndex(uint32 index) const { return m_boneTracks[index]; } const BoneTrack *GetBoneTrackByName(const char *boneName) const; void AddBoneTrack(BoneTrack *boneTrack); BoneTrack *CreateBoneTrack(const char *boneName); BoneTrack *GetBoneTrackByIndex(uint32 index) { return m_boneTracks[index]; } BoneTrack *GetBoneTrackByName(const char *boneName); uint32 GetBoneTrackCount() const { return m_boneTracks.GetSize(); } void RemoveBoneTrack(BoneTrack *boneTrack); // root motion track const RootMotionTrack *GetRootMotionTrack() const { return m_pRootMotionTrack; } RootMotionTrack *GetRootMotionTrack() { return m_pRootMotionTrack; } void SetRootMotionTrack(RootMotionTrack *rootMotionTrack) { delete m_pRootMotionTrack; m_pRootMotionTrack = rootMotionTrack; } RootMotionTrack *AddRootMotionTrack(); void DeleteRootMotionTrack(); // clip the animation to the specified time range, performs interpolation if necessary void ClipAnimation(float startTime, float endTime); // optimize animations void Optimize(bool removeEmptyTracks = true, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // Loading interface (from XML) bool LoadFromXML(const char *FileName, ByteStream *pStream); // Output interface bool SaveToXML(ByteStream *pStream) const; bool Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream, bool optimize = true) const; // Copy existing animation void Copy(const SkeletalAnimationGenerator *pCopy); // generate a list of times for keyframes, this is not stored with the animation but can be generated on demand void GenerateKeyFrameTimeList(PODArray<float> *pKeyFrameTimeArray) const; private: bool InternalCompile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const; static bool InternalWriteTransformKeyFrame(ByteStream *pStream, const TransformTrack::KeyFrame *pKeyFrame); String m_skeletonName; PropertyTable m_properties; float m_duration; PODArray<BoneTrack *> m_boneTracks; RootMotionTrack *m_pRootMotionTrack; }; <file_sep>/Engine/Source/Renderer/RenderWorld.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderProxy.h" //#define RENDER_WORLD_USE_LINKED_LIST 1 class RenderWorld : public ReferenceCounted { public: RenderWorld(); ~RenderWorld(); // Can be called from game thread. void AddRenderable(RenderProxy *pRenderProxy); void RemoveRenderable(RenderProxy *pRenderProxy); // Can be called from render thread. void MoveRenderable(RenderProxy *pRenderProxy); #if RENDER_WORLD_USE_LINKED_LIST // enumerators template<typename T> void EnumerateRenderables(T &Callback) { NodeList::Iterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) Callback(itr->pRenderProxy); } template<typename T> void EnumerateRenderables(T &Callback) const { NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) Callback(itr->pRenderProxy); } template<typename T> void EnumerateRenderablesInAABox(const AABox &aaBox, T Callback) { NodeList::Iterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { if (aaBox.AABoxIntersection(itr->BoundingBox)) Callback(itr->pRenderProxy); } } template<typename T> void EnumerateRenderablesForEntity(uint32 entityId, T Callback) { NodeList::Iterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { Node &node = *itr; if (node.pRenderProxy->GetEntityId() == entityId) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesInAABox(const AABox &aaBox, T Callback) const { NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { if (aaBox.AABoxIntersection(itr->BoundingBox)) Callback(itr->pRenderProxy); } } template<typename T> void EnumerateRenderablesInFrustum(const Frustum &rFrustum, T Callback) { NodeList::Iterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { //if (rFrustum.SphereIntersection(itr->BoundingSphere) && rFrustum.AABoxIntersection(itr->BoundingBox)) if (rFrustum.AABoxIntersection(itr->BoundingBox)) Callback(itr->pRenderProxy); } } template<typename T> void EnumerateRenderablesInFrustum(const Frustum &rFrustum, T Callback) const { NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { //if (rFrustum.SphereIntersection(itr->BoundingSphere) && rFrustum.AABoxIntersection(itr->BoundingBox)) if (rFrustum.AABoxIntersection(itr->BoundingBox)) Callback(itr->pRenderProxy); } } template<typename T> void EnumerateRenderablesForEntity(uint32 entityId, T Callback) const { NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { const Node &node = *itr; if (node.pRenderProxy->GetEntityId() == entityId) Callback(node.pRenderProxy); } } bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const { float closestDistance = Y_FLT_INFINITE; float3 closestNormal, closestPoint; NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { const Node &node = *itr; float3 nodeContactNormal, nodeContactPoint; if (node.pRenderProxy->RayCast(ray, nodeContactNormal, nodeContactPoint, exitAtFirstIntersection)) { if (exitAtFirstIntersection) { contactNormal = nodeContactNormal; contactPoint = nodeContactPoint; return true; } float nodeDistance = (nodeContactPoint - ray.GetOrigin()).SquaredLength(); if (nodeDistance < closestDistance) { closestDistance = nodeDistance; closestNormal = nodeContactNormal; closestPoint = nodeContactPoint; } } } if (closestDistance == Y_FLT_INFINITE) return false; contactNormal = closestNormal; contactPoint = closestPoint; return true; } void GetIntersectingTrianglesInAABox(const AABox &aaBox, RenderProxy::IntersectingTriangleArray &intersectingTriangles) const { NodeList::ConstIterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { const Node &node = *itr; if (node.pRenderProxy->GetBoundingBox().AABoxIntersection(aaBox)) node.pRenderProxy->GetIntersectingTriangles(aaBox, intersectingTriangles); } } #else // enumerators template<typename T> void EnumerateRenderables(T &Callback) { for (uint32 i = 0; i < m_nodes.GetSize(); i++) Callback(m_nodes[i].pRenderProxy); } template<typename T> void EnumerateRenderables(T &Callback) const { for (uint32 i = 0; i < m_nodes.GetSize(); i++) Callback(m_nodes[i].pRenderProxy); } template<typename T> void EnumerateRenderablesInAABox(const AABox &aaBox, T Callback) { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { Node &node = m_nodes[i]; if (aaBox.AABoxIntersection(node.BoundingBox)) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesForEntity(uint32 entityId, T Callback) { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { Node &node = m_nodes[i]; if (node.pRenderProxy->GetEntityId() == entityId) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesInAABox(const AABox &aaBox, T Callback) const { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; if (aaBox.AABoxIntersection(node.BoundingBox)) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesInFrustum(const Frustum &rFrustum, T Callback) { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { Node &node = m_nodes[i]; if (rFrustum.SphereIntersection(node.BoundingSphere) && rFrustum.AABoxIntersection(node.BoundingBox)) //if (rFrustum.AABoxIntersection(node.BoundingBox)) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesInFrustum(const Frustum &rFrustum, T Callback) const { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; if (rFrustum.SphereIntersection(node.BoundingSphere) && rFrustum.AABoxIntersection(node.BoundingBox)) //if (rFrustum.AABoxIntersection(node.BoundingBox)) Callback(node.pRenderProxy); } } template<typename T> void EnumerateRenderablesForEntity(uint32 entityId, T Callback) const { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; if (node.pRenderProxy->GetEntityId() == entityId) Callback(node.pRenderProxy); } } bool RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const { float closestDistance = Y_FLT_INFINITE; float3 closestNormal, closestPoint; for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; float3 nodeContactNormal, nodeContactPoint; if (node.pRenderProxy->RayCast(ray, nodeContactNormal, nodeContactPoint, exitAtFirstIntersection)) { if (exitAtFirstIntersection) { contactNormal = nodeContactNormal; contactPoint = nodeContactPoint; return true; } float nodeDistance = (nodeContactPoint - ray.GetOrigin()).SquaredLength(); if (nodeDistance < closestDistance) { closestDistance = nodeDistance; closestNormal = nodeContactNormal; closestPoint = nodeContactPoint; } } } if (closestDistance == Y_FLT_INFINITE) return false; contactNormal = closestNormal; contactPoint = closestPoint; return true; } void GetIntersectingTrianglesInAABox(const AABox &aaBox, RenderProxy::IntersectingTriangleArray &intersectingTriangles) const { for (uint32 i = 0; i < m_nodes.GetSize(); i++) { const Node &node = m_nodes[i]; if (node.pRenderProxy->GetBoundingBox().AABoxIntersection(aaBox)) node.pRenderProxy->GetIntersectingTriangles(aaBox, intersectingTriangles); } } #endif private: struct Node { // TODO: Look at storing entity here, using it for grouping? AABox BoundingBox; Sphere BoundingSphere; RenderProxy *pRenderProxy; }; #if RENDER_WORLD_USE_LINKED_LIST typedef List<Node> NodeList; #else typedef MemArray<Node> NodeList; #endif typedef PODArray<RenderProxy *> RenderProxyQueue; // Owned by render thread at async run time. // Owned by game thread at synchronization time. NodeList m_nodes; }; <file_sep>/Engine/Source/Core/Property.cpp #include "Core/PrecompiledHeader.h" #include "Core/Property.h" #include "YBaseLib/BinaryReader.h" #include "YBaseLib/BinaryWriter.h" #include "YBaseLib/StringConverter.h" #include "MathLib/StringConverters.h" #include "MathLib/StreamOperators.h" Y_Define_NameTable(NameTables::PropertyType) Y_NameTable_Entry("bool", PROPERTY_TYPE_BOOL) Y_NameTable_Entry("uint", PROPERTY_TYPE_UINT) Y_NameTable_Entry("int", PROPERTY_TYPE_INT) Y_NameTable_Entry("int2", PROPERTY_TYPE_INT2) Y_NameTable_Entry("int3", PROPERTY_TYPE_INT3) Y_NameTable_Entry("int4", PROPERTY_TYPE_INT4) Y_NameTable_Entry("float", PROPERTY_TYPE_FLOAT) Y_NameTable_Entry("float2", PROPERTY_TYPE_FLOAT2) Y_NameTable_Entry("float3", PROPERTY_TYPE_FLOAT3) Y_NameTable_Entry("float4", PROPERTY_TYPE_FLOAT4) Y_NameTable_Entry("Color", PROPERTY_TYPE_COLOR) Y_NameTable_Entry("Quaternion", PROPERTY_TYPE_QUATERNION) Y_NameTable_Entry("Transform", PROPERTY_TYPE_TRANSFORM) Y_NameTable_Entry("String", PROPERTY_TYPE_STRING) Y_NameTable_End() bool GetPropertyValueAsString(const void *pObject, const PROPERTY_DECLARATION *pProperty, String &StrValue) { if (pProperty->GetPropertyCallback == NULL) return false; // Strings handled seperately. if (pProperty->Type == PROPERTY_TYPE_STRING) { // We can pass StrValue directly across. return pProperty->GetPropertyCallback(pObject, pProperty->pGetPropertyCallbackUserData, &StrValue); } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte TempValue[32]; // Call the function. if (!pProperty->GetPropertyCallback(pObject, pProperty->pGetPropertyCallbackUserData, &TempValue)) return false; // Now stringize it based on type. switch (pProperty->Type) { case PROPERTY_TYPE_BOOL: StringConverter::BoolToString(StrValue, reinterpret_cast<const bool &>(TempValue)); break; case PROPERTY_TYPE_UINT: StringConverter::UInt32ToString(StrValue, reinterpret_cast<const uint32 &>(TempValue)); break; case PROPERTY_TYPE_INT: StringConverter::Int32ToString(StrValue, reinterpret_cast<const int32 &>(TempValue)); break; case PROPERTY_TYPE_INT2: StringConverter::Vector2iToString(StrValue, reinterpret_cast<const Vector2i &>(TempValue)); break; case PROPERTY_TYPE_INT3: StringConverter::Vector3iToString(StrValue, reinterpret_cast<const Vector3i &>(TempValue)); break; case PROPERTY_TYPE_INT4: StringConverter::Vector4iToString(StrValue, reinterpret_cast<const Vector4i &>(TempValue)); break; case PROPERTY_TYPE_FLOAT: StringConverter::FloatToString(StrValue, reinterpret_cast<const float &>(TempValue)); break; case PROPERTY_TYPE_FLOAT2: StringConverter::Vector2fToString(StrValue, reinterpret_cast<const Vector2f &>(TempValue)); break; case PROPERTY_TYPE_FLOAT3: StringConverter::Vector3fToString(StrValue, reinterpret_cast<const Vector3f &>(TempValue)); break; case PROPERTY_TYPE_FLOAT4: StringConverter::Vector4fToString(StrValue, reinterpret_cast<const Vector4f &>(TempValue)); break; case PROPERTY_TYPE_QUATERNION: StringConverter::QuaternionToString(StrValue, reinterpret_cast<const Quaternion &>(TempValue)); break; case PROPERTY_TYPE_TRANSFORM: StringConverter::TransformToString(StrValue, reinterpret_cast<const Transform &>(TempValue)); break; case PROPERTY_TYPE_COLOR: StringConverter::ColorToString(StrValue, reinterpret_cast<const uint32 &>(TempValue)); break; default: UnreachableCode(); break; } return true; } } bool SetPropertyValueFromString(void *pObject, const PROPERTY_DECLARATION *pProperty, const char *szValue) { if (pProperty->SetPropertyCallback == NULL) return false; // Strings handled seperately. if (pProperty->Type == PROPERTY_TYPE_STRING) { // Create a constant string. StaticString StringRef(szValue); if (!pProperty->SetPropertyCallback(pObject, pProperty->pSetPropertyCallbackUserData, &StringRef)) return false; } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte TempValue[32]; // Un-stringize based on type. switch (pProperty->Type) { case PROPERTY_TYPE_BOOL: reinterpret_cast<bool &>(TempValue) = StringConverter::StringToBool(szValue); break; case PROPERTY_TYPE_UINT: reinterpret_cast<uint32 &>(TempValue) = StringConverter::StringToUInt32(szValue); break; case PROPERTY_TYPE_INT: reinterpret_cast<int32 &>(TempValue) = StringConverter::StringToInt32(szValue); break; case PROPERTY_TYPE_INT2: reinterpret_cast<Vector2i &>(TempValue) = StringConverter::StringToVector2i(szValue); break; case PROPERTY_TYPE_INT3: reinterpret_cast<Vector3i &>(TempValue) = StringConverter::StringToVector3i(szValue); break; case PROPERTY_TYPE_INT4: reinterpret_cast<Vector4i &>(TempValue) = StringConverter::StringToVector4i(szValue); break; case PROPERTY_TYPE_FLOAT: reinterpret_cast<float &>(TempValue) = StringConverter::StringToFloat(szValue); break; case PROPERTY_TYPE_FLOAT2: reinterpret_cast<Vector2f &>(TempValue) = StringConverter::StringToVector2f(szValue); break; case PROPERTY_TYPE_FLOAT3: reinterpret_cast<Vector3f &>(TempValue) = StringConverter::StringToVector3f(szValue); break; case PROPERTY_TYPE_FLOAT4: reinterpret_cast<Vector4f &>(TempValue) = StringConverter::StringToVector4f(szValue); break; case PROPERTY_TYPE_QUATERNION: reinterpret_cast<Quaternion &>(TempValue) = StringConverter::StringToQuaternion(szValue); break; case PROPERTY_TYPE_TRANSFORM: reinterpret_cast<Transform &>(TempValue) = StringConverter::StringToTranform(szValue); break; case PROPERTY_TYPE_COLOR: reinterpret_cast<uint32 &>(TempValue) = StringConverter::StringToColor(szValue); break; default: UnreachableCode(); break; } // Call the function. if (!pProperty->SetPropertyCallback(pObject, pProperty->pSetPropertyCallbackUserData, TempValue)) return false; } // Notify updater if needed. //if (pProperty->PropertyChangedCallback != NULL) //pProperty->PropertyChangedCallback(pObject, pProperty->pPropertyChangedCallbackUserData); return true; } bool WritePropertyValueToBuffer(const void *pObject, const PROPERTY_DECLARATION *pProperty, BinaryWriter &binaryWriter) { if (pProperty->GetPropertyCallback == NULL) return false; // Strings handled seperately. if (pProperty->Type == PROPERTY_TYPE_STRING) { // We can pass StrValue directly across. SmallString stringValue; if (!pProperty->GetPropertyCallback(pObject, pProperty->pGetPropertyCallbackUserData, &stringValue)) return false; binaryWriter.WriteUInt32(stringValue.GetLength() + 1); binaryWriter.WriteCString(stringValue); return true; } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte TempValue[32]; // Call the function. if (!pProperty->GetPropertyCallback(pObject, pProperty->pGetPropertyCallbackUserData, &TempValue)) return false; // Now stringize it based on type. switch (pProperty->Type) { case PROPERTY_TYPE_BOOL: binaryWriter.WriteUInt32(1); binaryWriter.WriteBool(reinterpret_cast<const bool &>(TempValue)); break; case PROPERTY_TYPE_UINT: binaryWriter.WriteUInt32(4); binaryWriter.WriteUInt32(reinterpret_cast<const uint32 &>(TempValue)); break; case PROPERTY_TYPE_INT: binaryWriter.WriteUInt32(4); binaryWriter.WriteInt32(reinterpret_cast<const int32 &>(TempValue)); break; case PROPERTY_TYPE_INT2: binaryWriter.WriteUInt32(8); binaryWriter << (reinterpret_cast<const Vector2i &>(TempValue)); break; case PROPERTY_TYPE_INT3: binaryWriter.WriteUInt32(12); binaryWriter << (reinterpret_cast<const Vector3i &>(TempValue)); break; case PROPERTY_TYPE_INT4: binaryWriter.WriteUInt32(16); binaryWriter << (reinterpret_cast<const Vector4i &>(TempValue)); break; case PROPERTY_TYPE_FLOAT: binaryWriter.WriteUInt32(4); binaryWriter.WriteFloat(reinterpret_cast<const float &>(TempValue)); break; case PROPERTY_TYPE_FLOAT2: binaryWriter.WriteUInt32(8); binaryWriter << (reinterpret_cast<const Vector2f &>(TempValue)); break; case PROPERTY_TYPE_FLOAT3: binaryWriter.WriteUInt32(12); binaryWriter << (reinterpret_cast<const Vector3f &>(TempValue)); break; case PROPERTY_TYPE_FLOAT4: binaryWriter.WriteUInt32(16); binaryWriter << (reinterpret_cast<const Vector4f &>(TempValue)); break; case PROPERTY_TYPE_QUATERNION: binaryWriter.WriteUInt32(16); binaryWriter << (reinterpret_cast<const Quaternion &>(TempValue).GetVectorRepresentation()); break; case PROPERTY_TYPE_TRANSFORM: binaryWriter.WriteUInt32(12 + 16 + 4); binaryWriter << (reinterpret_cast<const Transform &>(TempValue).GetPosition()); binaryWriter << (reinterpret_cast<const Transform &>(TempValue).GetRotation().GetVectorRepresentation()); binaryWriter << (reinterpret_cast<const Transform &>(TempValue).GetScale()); break; case PROPERTY_TYPE_COLOR: binaryWriter.WriteUInt32(4); binaryWriter.WriteUInt32(reinterpret_cast<const uint32 &>(TempValue)); break; default: UnreachableCode(); break; } return true; } } bool ReadPropertyValueFromBuffer(void *pObject, const PROPERTY_DECLARATION *pProperty, BinaryReader &binaryReader) { if (pProperty->SetPropertyCallback == NULL) return false; // Strings handled seperately. if (pProperty->Type == PROPERTY_TYPE_STRING) { uint32 stringLength = binaryReader.ReadUInt32(); SmallString stringValue; binaryReader.ReadCString(stringValue); if (stringValue.GetLength() != (stringLength - 1) || !pProperty->SetPropertyCallback(pObject, pProperty->pSetPropertyCallbackUserData, &stringValue)) return false; } else { // 32 bytes should be enough for the actual value. (largest is currently transform, which is float3 + quat + float) byte TempValue[32]; // Un-stringize based on type. switch (pProperty->Type) { case PROPERTY_TYPE_BOOL: if (binaryReader.ReadUInt32() != 1) { return false; } reinterpret_cast<bool &>(TempValue) = binaryReader.ReadBool(); break; case PROPERTY_TYPE_UINT: if (binaryReader.ReadUInt32() != 4) { return false; } reinterpret_cast<uint32 &>(TempValue) = binaryReader.ReadUInt32(); break; case PROPERTY_TYPE_INT: if (binaryReader.ReadUInt32() != 4) { return false; } reinterpret_cast<int32 &>(TempValue) = binaryReader.ReadInt32(); break; case PROPERTY_TYPE_INT2: if (binaryReader.ReadUInt32() != 8) { return false; } binaryReader >> reinterpret_cast<Vector2i &>(TempValue); break; case PROPERTY_TYPE_INT3: if (binaryReader.ReadUInt32() != 12) { return false; } binaryReader >> reinterpret_cast<Vector3i &>(TempValue); break; case PROPERTY_TYPE_INT4: if (binaryReader.ReadUInt32() != 16) { return false; } binaryReader >> reinterpret_cast<Vector4i &>(TempValue); break; case PROPERTY_TYPE_FLOAT: if (binaryReader.ReadUInt32() != 4) { return false; } reinterpret_cast<float &>(TempValue) = binaryReader.ReadFloat(); break; case PROPERTY_TYPE_FLOAT2: if (binaryReader.ReadUInt32() != 8) { return false; } binaryReader >> reinterpret_cast<Vector2f &>(TempValue); break; case PROPERTY_TYPE_FLOAT3: if (binaryReader.ReadUInt32() != 12) { return false; } binaryReader >> reinterpret_cast<Vector3f &>(TempValue); break; case PROPERTY_TYPE_FLOAT4: if (binaryReader.ReadUInt32() != 16) { return false; } binaryReader >> reinterpret_cast<Vector4f &>(TempValue); break; case PROPERTY_TYPE_QUATERNION: if (binaryReader.ReadUInt32() != 16) { return false; } binaryReader >> reinterpret_cast<Quaternion &>(TempValue); break; case PROPERTY_TYPE_TRANSFORM: { if (binaryReader.ReadUInt32() != (12 + 16 + 4)) { return false; } Vector3f position; Quaternion rotation; Vector3f scale; binaryReader >> position >> rotation >> scale; reinterpret_cast<Transform &>(TempValue).SetPosition(position); reinterpret_cast<Transform &>(TempValue).SetRotation(rotation); reinterpret_cast<Transform &>(TempValue).SetScale(scale); } break; case PROPERTY_TYPE_COLOR: if (binaryReader.ReadUInt32() != 4) { return false; } reinterpret_cast<uint32 &>(TempValue) = binaryReader.ReadUInt32(); break; default: UnreachableCode(); break; } // Call the function. if (!pProperty->SetPropertyCallback(pObject, pProperty->pSetPropertyCallbackUserData, TempValue)) return false; } // Notify updater if needed. //if (pProperty->PropertyChangedCallback != NULL) //pProperty->PropertyChangedCallback(pObject, pProperty->pPropertyChangedCallbackUserData); return true; } bool EncodePropertyTypeToBuffer(PROPERTY_TYPE propertyType, const char *valueString, BinaryWriter &binaryWriter) { // Strings handled seperately. if (propertyType == PROPERTY_TYPE_STRING) { // We can pass StrValue directly across. binaryWriter.WriteUInt32(Y_strlen(valueString) + 1); binaryWriter.WriteCString(valueString); return true; } else { // Now stringize it based on type. switch (propertyType) { case PROPERTY_TYPE_BOOL: binaryWriter.WriteUInt32(1); binaryWriter.WriteBool(StringConverter::StringToBool(valueString)); break; case PROPERTY_TYPE_UINT: binaryWriter.WriteUInt32(4); binaryWriter.WriteUInt32(StringConverter::StringToUInt32(valueString)); break; case PROPERTY_TYPE_INT: binaryWriter.WriteUInt32(4); binaryWriter.WriteInt32(StringConverter::StringToInt32(valueString)); break; case PROPERTY_TYPE_INT2: binaryWriter.WriteUInt32(8); binaryWriter << (StringConverter::StringToVector2i(valueString)); break; case PROPERTY_TYPE_INT3: binaryWriter.WriteUInt32(12); binaryWriter << (StringConverter::StringToVector3i(valueString)); break; case PROPERTY_TYPE_INT4: binaryWriter.WriteUInt32(16); binaryWriter << (StringConverter::StringToVector4i(valueString)); break; case PROPERTY_TYPE_FLOAT: binaryWriter.WriteUInt32(4); binaryWriter.WriteFloat(StringConverter::StringToFloat(valueString)); break; case PROPERTY_TYPE_FLOAT2: binaryWriter.WriteUInt32(8); binaryWriter << (StringConverter::StringToVector2f(valueString)); break; case PROPERTY_TYPE_FLOAT3: binaryWriter.WriteUInt32(12); binaryWriter << (StringConverter::StringToVector3f(valueString)); break; case PROPERTY_TYPE_FLOAT4: binaryWriter.WriteUInt32(16); binaryWriter << (StringConverter::StringToVector4f(valueString)); break; case PROPERTY_TYPE_QUATERNION: binaryWriter.WriteUInt32(16); binaryWriter << (StringConverter::StringToQuaternion(valueString)); break; case PROPERTY_TYPE_TRANSFORM: { Transform transform(StringConverter::StringToTranform(valueString)); binaryWriter.WriteUInt32(12 + 16 + 4); binaryWriter << (transform.GetPosition()); binaryWriter << (transform.GetRotation()); binaryWriter << (transform.GetScale()); } break; case PROPERTY_TYPE_COLOR: binaryWriter.WriteUInt32(4); binaryWriter.WriteUInt32(StringConverter::StringToColor(valueString));; break; default: UnreachableCode(); break; } return true; } } // default property callbacks bool DefaultPropertyTableCallbacks::GetBool(const void *pObjectPtr, const void *pUserData, bool *pValuePtr) { *pValuePtr = *((const bool *)((((const byte *)pObjectPtr) + (*(int *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetBool(void *pObjectPtr, const void *pUserData, const bool *pValuePtr) { *((bool *)((((byte *)pObjectPtr) + (*(int *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetUInt(const void *pObjectPtr, const void *pUserData, uint32 *pValuePtr) { *pValuePtr = *((const uint32 *)((((const byte *)pObjectPtr) + (*(uint32 *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetUInt(void *pObjectPtr, const void *pUserData, const uint32 *pValuePtr) { *((uint32 *)((((byte *)pObjectPtr) + (*(uint32 *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetInt(const void *pObjectPtr, const void *pUserData, int32 *pValuePtr) { *pValuePtr = *((const int32 *)((((const byte *)pObjectPtr) + (*(int32 *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetInt(void *pObjectPtr, const void *pUserData, const int32 *pValuePtr) { *((int32 *)((((byte *)pObjectPtr) + (*(int32 *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetInt2(const void *pObjectPtr, const void *pUserData, Vector2i *pValuePtr) { *pValuePtr = *((const Vector2i *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetInt2(void *pObjectPtr, const void *pUserData, const Vector2i *pValuePtr) { *((Vector2i *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetInt3(const void *pObjectPtr, const void *pUserData, Vector3i *pValuePtr) { *pValuePtr = *((const Vector3i *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetInt3(void *pObjectPtr, const void *pUserData, const Vector3i *pValuePtr) { *((Vector3i *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetInt4(const void *pObjectPtr, const void *pUserData, Vector4i *pValuePtr) { *pValuePtr = *((const Vector4i *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetInt4(void *pObjectPtr, const void *pUserData, const Vector4i *pValuePtr) { *((Vector4i *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetFloat(const void *pObjectPtr, const void *pUserData, float *pValuePtr) { *pValuePtr = *((const float *)((((const byte *)pObjectPtr) + (*(int *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetFloat(void *pObjectPtr, const void *pUserData, const float *pValuePtr) { *((float *)((((byte *)pObjectPtr) + (*(int *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetFloat2(const void *pObjectPtr, const void *pUserData, Vector2f *pValuePtr) { *pValuePtr = *((const Vector2f *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetFloat2(void *pObjectPtr, const void *pUserData, const Vector2f *pValuePtr) { *((Vector2f *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetFloat3(const void *pObjectPtr, const void *pUserData, Vector3f *pValuePtr) { *pValuePtr = *((const Vector3f *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetFloat3(void *pObjectPtr, const void *pUserData, const Vector3f *pValuePtr) { *((Vector3f *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetFloat4(const void *pObjectPtr, const void *pUserData, Vector4f *pValuePtr) { *pValuePtr = *((const Vector4f *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetFloat4(void *pObjectPtr, const void *pUserData, const Vector4f *pValuePtr) { *((Vector4f *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::SetString(void *pObjectPtr, const void *pUserData, const String *pValuePtr) { ((String *)((((byte *)pObjectPtr) + (*(int *)&pUserData))))->Assign(*pValuePtr); return true; } bool DefaultPropertyTableCallbacks::GetQuaternion(const void *pObjectPtr, const void *pUserData, Quaternion *pValuePtr) { *pValuePtr = *((const Quaternion *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetQuaternion(void *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr) { *((Quaternion *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetTransform(const void *pObjectPtr, const void *pUserData, Transform *pValuePtr) { *pValuePtr = *((const Transform *)((((const byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetTransform(void *pObjectPtr, const void *pUserData, const Transform *pValuePtr) { *((Transform *)((((byte *)pObjectPtr) + (*(ptrdiff_t *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetString(const void *pObjectPtr, const void *pUserData, String *pValuePtr) { pValuePtr->Assign(*((const String *)((((const byte *)pObjectPtr) + (*(int *)&pUserData))))); return true; } bool DefaultPropertyTableCallbacks::GetColor(const void *pObjectPtr, const void *pUserData, uint32 *pValuePtr) { *pValuePtr = *((const uint32 *)((((const byte *)pObjectPtr) + (*(uint32 *)&pUserData)))); return true; } bool DefaultPropertyTableCallbacks::SetColor(const void *pObjectPtr, const void *pUserData, const uint32 *pValuePtr) { *((uint32 *)((((byte *)pObjectPtr) + (*(uint32 *)&pUserData)))) = *pValuePtr; return true; } bool DefaultPropertyTableCallbacks::GetConstBool(const void *pObjectPtr, const void *pUserData, bool *pValuePtr) { bool Value = (pUserData != 0) ? true : false; *pValuePtr = Value; return true; } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUShaderProgram.h #pragma once #include "OpenGLES2Renderer/OpenGLES2Common.h" #include "OpenGLES2Renderer/OpenGLES2ConstantLibrary.h" class OpenGLES2GPUShaderProgram : public GPUShaderProgram { public: struct ShaderParameter { String Name; SHADER_PARAMETER_TYPE Type; uint32 ArraySize; uint32 ArrayStride; uint32 BindTarget; int32 BindLocation; int32 BindSlot; OpenGLES2ConstantLibrary::ConstantID LibraryID; bool LibraryValueChanged; }; public: OpenGLES2GPUShaderProgram(); virtual ~OpenGLES2GPUShaderProgram(); // resource virtuals virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; // creation bool LoadProgram(OpenGLES2GPUDevice *pDevice, const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream); // bind to a context that has no current shader void Bind(OpenGLES2GPUContext *pContext); // switch context to a new shader void Switch(OpenGLES2GPUContext *pContext, OpenGLES2GPUShaderProgram *pCurrentProgram); // when a constant parameter changes void OnLibraryConstantChanged(OpenGLES2ConstantLibrary::ConstantID constantID); // update the program copy of parameters before draw void CommitLibraryConstants(OpenGLES2GPUContext *pContext); // unbind from a context, resetting all shader states void Unbind(OpenGLES2GPUContext *pContext); // --- internal query api --- uint32 InternalGetParameterCount() const { return m_parameters.GetSize(); } const ShaderParameter *GetParameter(uint32 Index) const { DebugAssert(Index < m_parameters.GetSize()); return &m_parameters[Index]; } // --- internal parameter api --- void InternalSetParameterValue(OpenGLES2GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue); void InternalSetParameterValueArray(OpenGLES2GPUContext *pContext, uint32 parameterIndex, SHADER_PARAMETER_TYPE valueType, const void *pValue, uint32 firstElement, uint32 numElements); void InternalSetParameterTexture(OpenGLES2GPUContext *pContext, uint32 parameterIndex, GPUResource *pResource); // --- public parameter api --- virtual uint32 GetParameterCount() const override; virtual void GetParameterInformation(uint32 index, const char **name, SHADER_PARAMETER_TYPE *type, uint32 *arraySize) override; protected: // shader objects GLuint m_iGLShaderId[SHADER_PROGRAM_STAGE_COUNT]; GLuint m_iGLProgramId; // parameters typedef MemArray<GPU_VERTEX_ELEMENT_DESC> VertexAttributeArray; typedef Array<ShaderParameter> ParameterArray; VertexAttributeArray m_vertexAttributes; ParameterArray m_parameters; // context we are bound to OpenGLES2GPUContext *m_pBoundContext; }; <file_sep>/Engine/Source/Renderer/Shaders/OneColorShader.h #pragma once #include "Renderer/ShaderComponent.h" class ShaderProgram; class OneColorShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(OneColorShader, ShaderComponent); public: OneColorShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) { } static void SetColor(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, const float4 &col); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Editor/Source/Editor/Defines.h #pragma once class Entity; enum EDITOR_THEME { EDITOR_THEME_NONE, EDITOR_THEME_DARK, EDITOR_THEME_DARK_OTHER, EDITOR_THEME_COUNT, }; enum EDITOR_CURSOR_TYPE { EDITOR_CURSOR_TYPE_ARROW, EDITOR_CURSOR_TYPE_RIGHT_ARROW, EDITOR_CURSOR_TYPE_CROSS, EDITOR_CURSOR_TYPE_BULLSEYE, EDITOR_CURSOR_TYPE_HAND, EDITOR_CURSOR_TYPE_IBEAM, EDITOR_CURSOR_TYPE_SIZE_NS, EDITOR_CURSOR_TYPE_SIZE_WE, EDITOR_CURSOR_TYPE_SIZE_NESW, EDITOR_CURSOR_TYPE_SIZE_NWSE, EDITOR_CURSOR_TYPE_SIZING, EDITOR_CURSOR_TYPE_MAGNIFIER, EDITOR_CURSOR_TYPE_COUNT, }; enum EDITOR_VIEWPORT_LAYOUT { EDITOR_VIEWPORT_LAYOUT_1X1, // 1 viewport, perspective by default EDITOR_VIEWPORT_LAYOUT_2X2, // 4 viewports, from top-left to bottom-right, top, front, side, perspective EDITOR_VIEWPORT_LAYOUT_COUNT, }; enum EDITOR_EDIT_MODE { EDITOR_EDIT_MODE_NONE, EDITOR_EDIT_MODE_MAP, EDITOR_EDIT_MODE_ENTITY, EDITOR_EDIT_MODE_GEOMETRY, EDITOR_EDIT_MODE_TERRAIN, EDITOR_EDIT_MODE_COUNT, }; enum EDITOR_ENTITY_EDIT_MODE_WIDGET { EDITOR_ENTITY_EDIT_MODE_WIDGET_SELECT, EDITOR_ENTITY_EDIT_MODE_WIDGET_MOVE, EDITOR_ENTITY_EDIT_MODE_WIDGET_ROTATE, EDITOR_ENTITY_EDIT_MODE_WIDGET_SCALE, EDITOR_ENTITY_EDIT_MODE_WIDGET_COUNT, }; enum EDITOR_BLOCK_TERRAIN_EDIT_MODE_WIDGET { EDITOR_BLOCK_TERRAIN_EDIT_MODE_WIDGET_SELECT, EDITOR_BLOCK_TERRAIN_EDIT_MODE_WIDGET_PLACE, EDITOR_BLOCK_TERRAIN_EDIT_MODE_WIDGET_DELETE, EDITOR_BLOCK_TERRAIN_EDIT_MODE_WIDGET_COUNT, }; enum EDITOR_TERRAIN_EDIT_MODE_WIDGET { EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_IMPORT_HEIGHTMAP, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_SETTINGS, EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_COUNT, }; enum EDITOR_REFERENCE_COORDINATE_SYSTEM { EDITOR_REFERENCE_COORDINATE_SYSTEM_LOCAL, EDITOR_REFERENCE_COORDINATE_SYSTEM_WORLD, EDITOR_REFERENCE_COORDINATE_SYSTEM_COUNT, }; enum EDITOR_CAMERA_MODE { EDITOR_CAMERA_MODE_ORTHOGRAPHIC_FRONT, EDITOR_CAMERA_MODE_ORTHOGRAPHIC_SIDE, EDITOR_CAMERA_MODE_ORTHOGRAPHIC_TOP, EDITOR_CAMERA_MODE_ISOMETRIC, EDITOR_CAMERA_MODE_PERSPECTIVE, EDITOR_CAMERA_MODE_ARCBALL, EDITOR_CAMERA_MODE_COUNT, }; enum EDITOR_RENDER_MODE { EDITOR_RENDER_MODE_WIREFRAME, EDITOR_RENDER_MODE_LIT, EDITOR_RENDER_MODE_FULLBRIGHT, EDITOR_RENDER_MODE_LIGHTING_ONLY, EDITOR_RENDER_MODE_COUNT, }; enum EDITOR_VIEWPORT_FLAGS { EDITOR_VIEWPORT_FLAG_REALTIME = (1 << 0), EDITOR_VIEWPORT_FLAG_GAME_VIEW = (1 << 1), EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS = (1 << 2), EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY = (1 << 3), EDITOR_VIEWPORT_FLAG_ENABLE_DEBUG_INFO = (1 << 4), }; const uint32 EDITOR_ENTITY_ID_RESERVED_BEGIN = 0xFFFFFFF7; <file_sep>/Engine/Source/Core/ImageCodecFreeImage.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/Log.h" #include "YBaseLib/Math.h" #include <cstdio> Log_SetChannel(ImageCodecFreeImage); #ifdef HAVE_FREEIMAGE #include <FreeImage.h> // Include the .lib #if Y_PLATFORM_WINDOWS #if Y_BUILD_CONFIG_DEBUG #pragma comment(lib, "FreeImaged.lib") #else #pragma comment(lib, "FreeImage.lib") #endif #endif // Y_PLATFORM_WINDOWS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ByteStream IO Functions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static unsigned DLL_CALLCONV __FreeImageByteStreamIO_ReadProc(void *buffer, unsigned size, unsigned count, fi_handle handle) { byte *pWritePointer = reinterpret_cast<byte *>(buffer); unsigned read = 0; for (unsigned i = 0; i < count; i++) { if (!reinterpret_cast<ByteStream *>(handle)->Read2(pWritePointer, size)) break; pWritePointer += size; read++; } return read; } static unsigned DLL_CALLCONV __FreeImageByteStreamIO_WriteProc(void *buffer, unsigned size, unsigned count, fi_handle handle) { const byte *pReadPointer = reinterpret_cast<byte *>(buffer); unsigned written = 0; for (unsigned i = 0; i < count; i++) { if (!reinterpret_cast<ByteStream *>(handle)->Write2(pReadPointer, size)) break; pReadPointer += size; written++; } return written; } static int DLL_CALLCONV __FreeImageByteStreamIO_SeekProc(fi_handle handle, long offset, int origin) { ByteStream *pStream = reinterpret_cast<ByteStream *>(handle); bool res; if (origin == SEEK_SET) res = pStream->SeekAbsolute((uint64)offset); else if (origin == SEEK_CUR) res = pStream->SeekRelative((int64)offset); else if (origin == SEEK_END) res = pStream->SeekToEnd(); else res = false; return (res) ? 0 : -1; } static long DLL_CALLCONV __FreeImageByteStreamIO_TellProc(fi_handle handle) { return (long)reinterpret_cast<ByteStream *>(handle)->GetPosition(); } static FreeImageIO s_freeImageByteStreamIO = { __FreeImageByteStreamIO_ReadProc, __FreeImageByteStreamIO_WriteProc, __FreeImageByteStreamIO_SeekProc, __FreeImageByteStreamIO_TellProc }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FreeImage <-> Pixel Format Conversion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template<PIXEL_FORMAT PIXELFORMAT, int RED_INDEX, int GREEN_INDEX, int BLUE_INDEX> bool __FreeImagePC_ReadBitmapRGB(Image *pOutputImage, FIBITMAP *pInputBitmap) { uint32 width = FreeImage_GetWidth(pInputBitmap); uint32 height = FreeImage_GetHeight(pInputBitmap); pOutputImage->Create(PIXELFORMAT, width, height, 1); const BYTE *pInputBits = FreeImage_GetBits(pInputBitmap); uint32 inputPitch = FreeImage_GetPitch(pInputBitmap); byte *pOutputBits = pOutputImage->GetData(); uint32 outputPitch = pOutputImage->GetDataRowPitch(); // freeimage coordinate system is upside down DebugAssert(height > 0); pInputBits += (height - 1) * inputPitch; for (uint32 y = 0; y < height; y++) { const BYTE *pInputPixels = reinterpret_cast<const byte *>(pInputBits); byte *pOutputPixels = pOutputBits; for (uint32 x = 0; x < width; x++) { pOutputPixels[BLUE_INDEX] = pInputPixels[FI_RGBA_BLUE]; pOutputPixels[GREEN_INDEX] = pInputPixels[FI_RGBA_GREEN]; pOutputPixels[RED_INDEX] = pInputPixels[FI_RGBA_RED]; pInputPixels += 3; pOutputPixels += 3; } pInputBits -= inputPitch; pOutputBits += outputPitch; } return true; } template<PIXEL_FORMAT PIXELFORMAT, int RED_INDEX, int GREEN_INDEX, int BLUE_INDEX, int ALPHA_INDEX> bool __FreeImagePC_ReadBitmapRGBA(Image *pOutputImage, FIBITMAP *pInputBitmap) { uint32 width = FreeImage_GetWidth(pInputBitmap); uint32 height = FreeImage_GetHeight(pInputBitmap); pOutputImage->Create(PIXELFORMAT, width, height, 1); const BYTE *pInputBits = FreeImage_GetBits(pInputBitmap); uint32 inputPitch = FreeImage_GetPitch(pInputBitmap); byte *pOutputBits = pOutputImage->GetData(); uint32 outputPitch = pOutputImage->GetDataRowPitch(); // freeimage coordinate system is upside down DebugAssert(height > 0); pInputBits += (height - 1) * inputPitch; for (uint32 y = 0; y < height; y++) { const BYTE *pInputPixels = reinterpret_cast<const byte *>(pInputBits); byte *pOutputPixels = pOutputBits; for (uint32 x = 0; x < width; x++) { pOutputPixels[BLUE_INDEX] = pInputPixels[FI_RGBA_BLUE]; pOutputPixels[GREEN_INDEX] = pInputPixels[FI_RGBA_GREEN]; pOutputPixels[RED_INDEX] = pInputPixels[FI_RGBA_RED]; pOutputPixels[ALPHA_INDEX] = pInputPixels[FI_RGBA_ALPHA]; pInputPixels += 4; pOutputPixels += 4; } pInputBits -= inputPitch; pOutputBits += outputPitch; } return true; } bool __FreeImagePC_ReadBitmap(Image *pOutputImage, FIBITMAP *pInputBitmap) { // get image format, color format and bpp FREE_IMAGE_TYPE imageType = FreeImage_GetImageType(pInputBitmap); FREE_IMAGE_COLOR_TYPE imageColorType = FreeImage_GetColorType(pInputBitmap); uint32 imageBPP = FreeImage_GetBPP(pInputBitmap); // handle known types bool result = false; if (imageType == FIT_BITMAP && imageColorType == FIC_RGB && imageBPP == 24) result = __FreeImagePC_ReadBitmapRGB<PIXEL_FORMAT_R8G8B8_UNORM, 0, 1, 2>(pOutputImage, pInputBitmap); else if (imageType == FIT_BITMAP && (imageColorType == FIC_RGB || imageColorType == FIC_RGBALPHA) && imageBPP == 32) // freeimage returns FIC_RGB for RGBA images that are opaque result = __FreeImagePC_ReadBitmapRGBA<PIXEL_FORMAT_R8G8B8A8_UNORM, 0, 1, 2, 3>(pOutputImage, pInputBitmap); else if (imageType == FIT_BITMAP && imageColorType == FIC_PALETTE) { // transparent? if (FreeImage_IsTransparent(pInputBitmap)) { // convert to 32bpp FIBITMAP *pConvertedBitmap = FreeImage_ConvertTo32Bits(pInputBitmap); if (pConvertedBitmap != nullptr) { result = __FreeImagePC_ReadBitmap(pOutputImage, pConvertedBitmap); FreeImage_Unload(pConvertedBitmap); } } else { // convert to 24bpp FIBITMAP *pConvertedBitmap = FreeImage_ConvertTo24Bits(pInputBitmap); if (pConvertedBitmap != nullptr) { result = __FreeImagePC_ReadBitmap(pOutputImage, pConvertedBitmap); FreeImage_Unload(pConvertedBitmap); } } } // error? if (!result) Log_ErrorPrintf("__FreeImagePC_ReadBitmap: Reading image failed (type %u, color type %u, bpp %u)", (uint32)imageType, (uint32)imageColorType, imageBPP); return result; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FreeImage <-> Pixel Format Conversion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template<int RED_INDEX, int GREEN_INDEX, int BLUE_INDEX> bool __FreeImagePC_WriteBitmapRGB(FIBITMAP **ppOutputBitmap, const Image *pInputImage) { uint32 width = pInputImage->GetWidth(); uint32 height = pInputImage->GetHeight(); // allocate bitmap FIBITMAP *pOutputBitmap = FreeImage_AllocateT(FIT_BITMAP, width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); if (pOutputBitmap == NULL) return false; // get pointers BYTE *pOutputBits = FreeImage_GetBits(pOutputBitmap); uint32 outputPitch = FreeImage_GetPitch(pOutputBitmap); const byte *pInputBits = pInputImage->GetData(); uint32 inputPitch = pInputImage->GetDataRowPitch(); // freeimage coordinate system is upside down DebugAssert(height > 0); pOutputBits = pOutputBits + (height - 1) * outputPitch; // write lines for (uint32 y = 0; y < height; y++) { const BYTE *pInputPixels = reinterpret_cast<const byte *>(pInputBits); byte *pOutputPixels = pOutputBits; for (uint32 x = 0; x < width; x++) { pOutputPixels[FI_RGBA_BLUE] = pInputPixels[BLUE_INDEX]; pOutputPixels[FI_RGBA_GREEN] = pInputPixels[GREEN_INDEX]; pOutputPixels[FI_RGBA_RED] = pInputPixels[RED_INDEX]; pInputPixels += 3; pOutputPixels += 3; } pOutputBits -= outputPitch; pInputBits += inputPitch; } *ppOutputBitmap = pOutputBitmap; return true; } template<int RED_INDEX, int GREEN_INDEX, int BLUE_INDEX> bool __FreeImagePC_WriteBitmapRGBX(FIBITMAP **ppOutputBitmap, const Image *pInputImage) { uint32 width = pInputImage->GetWidth(); uint32 height = pInputImage->GetHeight(); // allocate bitmap FIBITMAP *pOutputBitmap = FreeImage_AllocateT(FIT_BITMAP, width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); if (pOutputBitmap == NULL) return false; // get pointers BYTE *pOutputBits = FreeImage_GetBits(pOutputBitmap); uint32 outputPitch = FreeImage_GetPitch(pOutputBitmap); const byte *pInputBits = pInputImage->GetData(); uint32 inputPitch = pInputImage->GetDataRowPitch(); // freeimage coordinate system is upside down DebugAssert(height > 0); pOutputBits = pOutputBits + (height - 1) * outputPitch; // write lines for (uint32 y = 0; y < height; y++) { const BYTE *pInputPixels = reinterpret_cast<const byte *>(pInputBits); byte *pOutputPixels = pOutputBits; for (uint32 x = 0; x < width; x++) { pOutputPixels[FI_RGBA_BLUE] = pInputPixels[BLUE_INDEX]; pOutputPixels[FI_RGBA_GREEN] = pInputPixels[GREEN_INDEX]; pOutputPixels[FI_RGBA_RED] = pInputPixels[RED_INDEX]; pInputPixels += 4; pOutputPixels += 3; } pOutputBits -= outputPitch; pInputBits += inputPitch; } *ppOutputBitmap = pOutputBitmap; return true; } template<int RED_INDEX, int GREEN_INDEX, int BLUE_INDEX, int ALPHA_INDEX> bool __FreeImagePC_WriteBitmapRGBA(FIBITMAP **ppOutputBitmap, const Image *pInputImage) { uint32 width = pInputImage->GetWidth(); uint32 height = pInputImage->GetHeight(); // allocate bitmap FIBITMAP *pOutputBitmap = FreeImage_AllocateT(FIT_BITMAP, width, height, 32, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); if (pOutputBitmap == NULL) return false; // get pointers BYTE *pOutputBits = FreeImage_GetBits(pOutputBitmap); uint32 outputPitch = FreeImage_GetPitch(pOutputBitmap); const byte *pInputBits = pInputImage->GetData(); uint32 inputPitch = pInputImage->GetDataRowPitch(); // freeimage coordinate system is upside down DebugAssert(height > 0); pOutputBits = pOutputBits + (height - 1) * outputPitch; // write lines for (uint32 y = 0; y < height; y++) { const BYTE *pInputPixels = reinterpret_cast<const byte *>(pInputBits); byte *pOutputPixels = pOutputBits; for (uint32 x = 0; x < width; x++) { pOutputPixels[FI_RGBA_BLUE] = pInputPixels[BLUE_INDEX]; pOutputPixels[FI_RGBA_GREEN] = pInputPixels[GREEN_INDEX]; pOutputPixels[FI_RGBA_RED] = pInputPixels[RED_INDEX]; pOutputPixels[FI_RGBA_ALPHA] = pInputPixels[ALPHA_INDEX]; pInputPixels += 4; pOutputPixels += 4; } pOutputBits -= outputPitch; pInputBits += inputPitch; } *ppOutputBitmap = pOutputBitmap; return true; } bool __FreeImagePC_WriteBitmap(FIBITMAP **ppOutputBitmap, const Image *pInputImage) { PIXEL_FORMAT pixelFormat = pInputImage->GetPixelFormat(); // handle known types bool result = false; switch (pixelFormat) { case PIXEL_FORMAT_R8G8B8A8_UNORM: result = __FreeImagePC_WriteBitmapRGBA<0, 1, 2, 3>(ppOutputBitmap, pInputImage); break; case PIXEL_FORMAT_B8G8R8X8_UNORM: result = __FreeImagePC_WriteBitmapRGBX<2, 1, 0>(ppOutputBitmap, pInputImage); break; case PIXEL_FORMAT_B8G8R8A8_UNORM: result = __FreeImagePC_WriteBitmapRGBA<2, 1, 0, 3>(ppOutputBitmap, pInputImage); break; case PIXEL_FORMAT_R8G8B8_UNORM: result = __FreeImagePC_WriteBitmapRGB<0, 1, 2>(ppOutputBitmap, pInputImage); break; } // error? if (!result) Log_ErrorPrintf("__FreeImagePC_WriteBitmap: Writing image failed (PF %s)", PixelFormat_GetPixelFormatInfo(pixelFormat)->Name); return result; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Resize wrapper /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool __ImageCodecFreeImage_ResizeImage(IMAGE_RESIZE_FILTER resizeFilter, PIXEL_FORMAT pixelFormat, uint32 width, uint32 height, uint32 newWidth, uint32 newHeight, const byte *pInImageData, byte *pOutImageData) { static const FREE_IMAGE_FILTER imageResizeFilterToFIFilter[IMAGE_RESIZE_FILTER_COUNT] = { FILTER_BOX, // IMAGE_RESIZE_FILTER_BOX FILTER_BILINEAR, // IMAGE_RESIZE_FILTER_BILINEAR FILTER_BICUBIC, // IMAGE_RESIZE_FILTER_BICUBIC FILTER_BSPLINE, // IMAGE_RESIZE_FILTER_BSPLINE FILTER_CATMULLROM, // IMAGE_RESIZE_FILTER_CATMULLROM FILTER_LANCZOS3, // IMAGE_RESIZE_FILTER_LANCZOS3 }; // ugh, extra copies.. optimize me at some point? Image temporaryImage; temporaryImage.Create(pixelFormat, width, height, 1); Y_memcpy(temporaryImage.GetData(), pInImageData, temporaryImage.GetDataSize()); // copy into a freeimage bitmap FIBITMAP *pInputBitmap; if (!__FreeImagePC_WriteBitmap(&pInputBitmap, &temporaryImage)) return false; // invoke the resize DebugAssert(resizeFilter < IMAGE_RESIZE_FILTER_COUNT); FIBITMAP *pRescaledBitmap = FreeImage_Rescale(pInputBitmap, newWidth, newHeight, imageResizeFilterToFIFilter[resizeFilter]); // success? bool result = false; if (pRescaledBitmap != NULL) { temporaryImage.Delete(); result = __FreeImagePC_ReadBitmap(&temporaryImage, pRescaledBitmap); if (result) { if (temporaryImage.GetPixelFormat() == pixelFormat) Y_memcpy(pOutImageData, temporaryImage.GetData(), temporaryImage.GetDataSize()); else result = false; temporaryImage.Delete(); } FreeImage_Unload(pRescaledBitmap); } // kill original bitmap FreeImage_Unload(pInputBitmap); // done return result; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Codec Class /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class ImageCodecFreeImage : public ImageCodec { public: virtual const char *GetCodecName() const; virtual bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyTable &decoderOptions = PropertyTable::EmptyPropertyList); virtual bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyTable &encoderOptions = PropertyTable::EmptyPropertyList); }; const char *ImageCodecFreeImage::GetCodecName() const { return "FreeImage"; } bool ImageCodecFreeImage::DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyTable &decoderOptions /* = PropertyList::EmptyPropertyList */) { // detect format FREE_IMAGE_FORMAT fiFormat = FreeImage_GetFileTypeFromHandle(&s_freeImageByteStreamIO, reinterpret_cast<fi_handle>(pInputStream), 0); if (fiFormat == FIF_UNKNOWN) { // try by filename const char *extension = Y_strrchr(FileName, '.'); if (extension == nullptr) extension = FileName; else extension++; fiFormat = FreeImage_GetFIFFromFormat(extension); if (fiFormat == FIF_UNKNOWN) { Log_ErrorPrintf("ImageCodecFreeImage::DecodeImage: Could not determine FIF for filename '%s'", FileName); return false; } } // seek back to start if (!pInputStream->SeekAbsolute(0)) return false; // open the file FIBITMAP *pFIBitmap = FreeImage_LoadFromHandle(fiFormat, &s_freeImageByteStreamIO, reinterpret_cast<fi_handle>(pInputStream), 0); if (pFIBitmap == NULL) { Log_ErrorPrintf("ImageCodecFreeImage::DecodeImage: FreeImage_LoadFromHandle failed for filename '%s'", FileName); return false; } // dump error bool result = __FreeImagePC_ReadBitmap(pOutputImage, pFIBitmap); if (!result) Log_ErrorPrintf("ImageCodecFreeImage::DecodeImage: __FreeImagePC_ReadBitmap failed for filename '%s'", FileName); // free image resources FreeImage_Unload(pFIBitmap); return result; } bool ImageCodecFreeImage::EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyTable &encoderOptions /* = PropertyList::EmptyPropertyList */) { FREE_IMAGE_FORMAT fiFormat = FreeImage_GetFIFFromFilename(FileName); if (fiFormat == FIF_UNKNOWN) { Log_ErrorPrintf("ImageCodecFreeImage::EncodeImage: Could not determine image format for filename '%s'", FileName); return false; } FIBITMAP *pFIBitmap; if (!__FreeImagePC_WriteBitmap(&pFIBitmap, pInputImage)) { Log_ErrorPrintf("ImageCodecFreeImage::EncodeImage: Failed to write bitmap.", FileName); return false; } // handle options uint32 flags = 0; switch (fiFormat) { case FIF_JPEG: { flags = JPEG_DEFAULT | Math::Clamp<uint32>(encoderOptions.GetPropertyValueDefaultUInt32(ImageCodecEncoderOptions::JPEG_QUALITY_LEVEL, 75), 10, 100); // jpeg quality } break; case FIF_PNG: { flags = PNG_DEFAULT | Math::Clamp<uint32>(encoderOptions.GetPropertyValueDefaultUInt32(ImageCodecEncoderOptions::PNG_COMPRESSION_LEVEL), 1, 9); // png compression speed } break; } // do the save BOOL result = FreeImage_SaveToHandle(fiFormat, pFIBitmap, &s_freeImageByteStreamIO, reinterpret_cast<fi_handle>(pOutputStream), flags); if (!result) Log_ErrorPrintf("ImageCodecFreeImage::DecodeImage: FreeImage_SaveToHandle failed for filename '%s'", FileName); // free bitmap FreeImage_Unload(pFIBitmap); return (result == TRUE); } static ImageCodecFreeImage s_freeImageCodec; ImageCodec *__GetImageCodecFreeImage() { return &s_freeImageCodec; } #else // HAVE_FREEIMAGE ImageCodec *__GetImageCodecFreeImage() { return nullptr; } #endif // HAVE_FREEIMAGE <file_sep>/Engine/Source/MathLib/Vectorh.h #pragma once #include "MathLib/Common.h" // interoperability between float/vector types struct Vector2f; struct Vector3f; struct Vector4f; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #pragma pack(push, 2) struct half { half() {} half(const half &v) : value(v.value) {} half(uint16 v) : value(v) {} half(const float f) : value(Math::FloatToHalf(f)) {} operator uint16() const { return value; } operator float() const { return Math::HalfToFloat(value); } half &operator=(const half &h) { value = h.value; return *this; } private: uint16 value; }; struct Vector2h { Vector2h() {} Vector2h(const Vector2h &v) : x(v.x) , y(v.y) {} Vector2h(const float x_, const float y_) : x((x_)), y((y_)) {} Vector2h(const Vector2f &v); operator Vector2f() const; private: half x, y; }; struct Vector3h { Vector3h() {} Vector3h(const Vector3h &v) : x(v.x) , y(v.y), z(v.z) {} Vector3h(const float x_, const float y_, const float z_) : x((x_)), y((y_)), z((z_)) {} Vector3h(const Vector3f &v); operator Vector3f() const; private: half x, y, z; }; struct Vector4h { Vector4h() {} Vector4h(const Vector4h &v) : x(v.x) , y(v.y), z(v.z), w(v.w) {} Vector4h(const float x_, const float y_, const float z_, const float w_) : x((x_)), y((y_)), z((z_)), w((w_)) {} Vector4h(const Vector4f &v); operator Vector4f() const; private: half x, y, z, w; }; #pragma pack(pop) //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- <file_sep>/Editor/Source/Editor/EditorTypes.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #define REGISTER_VERTEXFACTORY(Type) VERTEX_FACTORY_MUTABLE_TYPE_INFO(Type)->RegisterType() #define REGISTER_ENTITY(Type) ENTITY_MUTABLE_TYPEINFO(Type)->RegisterType() void Editor::RegisterEditorTypes() { } #undef REGISTER_VERTEXFACTORY #undef REGISTER_ENTITY <file_sep>/Editor/Source/Editor/rcc_Editor.cpp /**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.4.0 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/Vsepartoolbar.png 0x0,0x0,0x0,0xbb, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x3f,0x0,0x0,0x0,0x7,0x8,0x6,0x0,0x0,0x0,0xbf,0x76,0x95,0x1f, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0x9,0x35,0x2b,0x55,0xca,0x52,0x6a,0x0,0x0,0x0,0x3b,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0x60,0x18,0x5,0x23,0x13,0x30,0x12,0xa3,0xa8,0xbe,0x7d,0x2a,0x25,0x76, 0xfc,0xa7,0x97,0x3b,0xd1,0xc1,0xaa,0xa5,0x73,0x18,0xae,0x5f,0x39,0x8f,0x53,0x9e, 0x69,0x34,0xe6,0x9,0x0,0x4d,0x1d,0xc3,0x21,0x19,0xf3,0xc,0xc,0xc,0x78,0x63, 0x7e,0x14,0x8c,0x54,0x0,0x0,0x69,0x64,0xb,0x5,0xfd,0x6b,0x58,0xca,0x0,0x0, 0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/up_arrow_disabled.png 0x0,0x0,0x0,0x9f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x8,0x14,0x1f,0xf9, 0x23,0xd9,0xb,0x0,0x0,0x0,0x23,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0xd,0xe6,0x7c,0x80,0xb1,0x18,0x91,0x5,0x52,0x4,0xe0,0x42,0x8,0x15,0x29,0x2, 0xc,0xc,0x8c,0xc8,0x2,0x8,0x95,0x68,0x0,0x0,0xac,0xac,0x7,0x90,0x4e,0x65, 0x34,0xac,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/close.png 0x0,0x0,0x2,0x71, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1, 0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0xb,0x1,0x28,0x74,0x6d,0x24,0x49,0x0,0x0,0x1,0xf1,0x49,0x44,0x41,0x54,0x58, 0xc3,0xcd,0x57,0x41,0x4e,0x2,0x31,0x14,0xfd,0xfd,0xb5,0x6e,0x70,0x21,0x89,0xb8, 0x11,0x8d,0x89,0x5b,0xef,0x80,0x3b,0xb7,0xde,0x80,0x36,0x70,0x2c,0xa0,0xbd,0x86, 0x3b,0xc2,0x19,0xd8,0xb9,0x21,0x11,0x13,0x23,0xb,0x4d,0x94,0x49,0xb4,0x69,0xeb, 0xc6,0xea,0xa4,0x61,0x86,0xb6,0x40,0xf0,0xef,0xc8,0xd0,0x79,0x7d,0xef,0xbf,0x79, 0xed,0x7,0xd8,0x73,0x91,0xaa,0x7,0x4a,0xa9,0x57,0x0,0x0,0xe7,0xdc,0x52,0x8, 0xd1,0xce,0x79,0xb9,0x94,0x72,0x4e,0x8,0x69,0x0,0x0,0x70,0xce,0x9b,0x51,0x1b, 0x18,0xc,0x6,0x53,0xc6,0xd8,0xa5,0x5f,0x8,0x0,0x60,0xad,0x5d,0x70,0xce,0x4f, 0x53,0xc0,0x95,0x52,0x2f,0x88,0xd8,0xf2,0xbf,0x9d,0x73,0x4b,0xad,0xf5,0xac,0xdf, 0xef,0x5f,0x97,0xff,0x87,0xe1,0xc2,0x10,0x1c,0x0,0x0,0x11,0x5b,0x52,0xca,0x79, 0xa,0xf3,0x32,0x38,0x0,0x0,0x21,0xa4,0xc1,0x18,0xbb,0xac,0x54,0x60,0x15,0xf3, 0xb0,0xb4,0xd6,0xf3,0x5e,0xaf,0x77,0x5e,0x7,0x3e,0x1c,0xe,0x1f,0x19,0x63,0x95, 0x2d,0xb,0x95,0xc0,0x3a,0xe6,0x61,0x51,0x4a,0x6b,0x95,0x90,0x52,0xce,0x29,0xa5, 0xad,0x5a,0xd3,0x5,0x4a,0x10,0x6f,0x38,0x44,0x3c,0x8e,0x95,0x78,0x95,0x27,0xc2, 0x9e,0x47,0xbc,0xe3,0x8d,0x73,0xde,0xc4,0x1c,0x77,0x87,0x9e,0x58,0xd5,0xf3,0xd8, 0x3a,0xf0,0x7d,0x1,0x80,0xe3,0x94,0x85,0x94,0xd2,0x33,0xa5,0xd4,0x8b,0xdf,0x50, 0x2a,0xf0,0xf,0xe6,0x9f,0x9,0x53,0x25,0xdc,0xa4,0xca,0x2d,0xfc,0x6d,0x1,0xe7, 0xfc,0xd4,0x18,0xf3,0xb4,0x6b,0x70,0x63,0xcc,0x53,0xd9,0x3f,0x64,0x5d,0x80,0xec, 0x8a,0x79,0x65,0x10,0xed,0x4a,0x89,0x90,0x79,0xcc,0x59,0xb0,0x35,0x25,0xea,0xa2, 0xbc,0xf2,0x33,0xdc,0x96,0x12,0x55,0xcc,0xd7,0x2a,0xb0,0xd,0x25,0x62,0xe,0x31, 0x84,0x3d,0x17,0xa6,0x9e,0x6a,0x9b,0x24,0x66,0xea,0x85,0x64,0x7f,0x26,0xdc,0x94, 0x79,0x8a,0x12,0xff,0x2b,0x88,0xb6,0xcd,0x3c,0x46,0x89,0xff,0x71,0x18,0xe5,0x32, 0xb7,0xd6,0x2e,0xac,0xb5,0x8b,0x4d,0x94,0x40,0x7f,0x4d,0xca,0x4d,0xb8,0xdc,0xc4, 0xf4,0x98,0x98,0x2b,0x61,0x79,0x56,0x10,0x42,0xb4,0x73,0x94,0xf8,0xdd,0x0,0xe7, 0xbc,0xe9,0x6f,0x28,0xb9,0xd9,0x9e,0xa2,0x84,0x73,0x6e,0xe9,0x7,0x15,0x2c,0x5d, 0xb9,0x67,0xeb,0x36,0x11,0x32,0xf,0x4b,0x8,0xd1,0x36,0xc6,0x3c,0x3,0x80,0xad, 0x21,0xf0,0xa1,0xb5,0x9e,0x55,0xe6,0x80,0x94,0xf2,0x1d,0x11,0x1b,0x84,0x10,0x52, 0x2,0xfe,0x72,0xce,0xdd,0xa,0x21,0xc6,0x91,0x83,0xc9,0xd,0x21,0xe4,0x1e,0x11, 0xf,0x43,0xe6,0xdd,0x6e,0xf7,0xa8,0x36,0x9,0xa7,0xd3,0xe9,0x95,0xb5,0x76,0x59, 0x2,0xff,0x2c,0x8a,0xe2,0x2e,0x16,0xfc,0x47,0x89,0x71,0x51,0x14,0x77,0xd6,0xda, 0xcf,0x70,0x20,0x49,0x1e,0x4e,0x27,0x93,0xc9,0xc5,0x68,0x34,0x7a,0xcf,0x31,0x58, 0xa7,0xd3,0x39,0x11,0x42,0x3c,0xd4,0xd,0xa7,0x7b,0xaf,0x6f,0x1a,0x2b,0x5a,0x88, 0xa9,0x6c,0x88,0x2e,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/down_arrow.png 0x0,0x0,0x0,0xa5, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0x9c,0x53,0x34,0xfc,0x5d,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0xb,0x2,0x4,0x6d, 0x98,0x1b,0x69,0x0,0x0,0x0,0x29,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0x0,0x8c,0xc,0xc,0xff,0xcf,0xa3,0x8,0x18,0x32,0x32,0x30,0x20,0xb,0x32,0x1a, 0x32,0x30,0x30,0x42,0x98,0x10,0x41,0x46,0x43,0x14,0x13,0x50,0xb5,0xa3,0x1,0x0, 0xd6,0x10,0x7,0xd2,0x2f,0x48,0xdf,0x4a,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/transparent.png 0x0,0x0,0x0,0xc3, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x40,0x0,0x0,0x0,0x40,0x8,0x6,0x0,0x0,0x0,0xaa,0x69,0x71,0xde, 0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd, 0xa7,0x93,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0, 0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7, 0xdc,0xb,0x7,0x9,0x2e,0x37,0xff,0x44,0xe8,0xf0,0x0,0x0,0x0,0x1d,0x69,0x54, 0x58,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x0,0x0,0x0,0x0,0x43,0x72, 0x65,0x61,0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x64, 0x2e,0x65,0x7,0x0,0x0,0x0,0x27,0x49,0x44,0x41,0x54,0x78,0xda,0xed,0xc1,0x1, 0xd,0x0,0x0,0x0,0xc2,0xa0,0xf7,0x4f,0x6d,0xe,0x37,0xa0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x77,0x3,0x40,0x40, 0x0,0x1,0xaf,0x7a,0xe,0xe8,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/branch_closed-on.png 0x0,0x0,0x0,0x93, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x2,0x62,0x4b,0x47,0x44,0x0,0xd3,0xb5,0x57,0xa0,0x5c,0x0,0x0, 0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0, 0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0xb,0x7,0xc, 0xc,0x2b,0x4a,0x3c,0x30,0x74,0x0,0x0,0x0,0x24,0x49,0x44,0x41,0x54,0x8,0xd7, 0x63,0x60,0x40,0x5,0xff,0xff,0xc3,0x58,0x4c,0xc8,0x5c,0x26,0x64,0x59,0x26,0x64, 0xc5,0x70,0xe,0x23,0x23,0x9c,0xc3,0xc8,0x88,0x61,0x1a,0xa,0x0,0x0,0x9e,0x14, 0xa,0x5,0x2b,0xca,0xe5,0x75,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/Hsepartoolbar.png 0x0,0x0,0x0,0xce, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x7,0x0,0x0,0x0,0x3f,0x8,0x6,0x0,0x0,0x0,0x2c,0x7b,0xd2,0x13, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0x9,0x2f,0x7,0xd7,0x3f,0xc4,0x52,0x0,0x0,0x0,0x4e,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0x60,0x18,0x36,0x80,0x19,0xc6,0xa8,0x6f,0x9f,0xca,0xe0,0xe0,0xe2,0xcd, 0xf0,0xea,0xe5,0x73,0x86,0x37,0xaf,0x5e,0x30,0x30,0x30,0x30,0x30,0x30,0xe1,0xd3, 0x39,0x2a,0x49,0x48,0x92,0x5,0x89,0xfd,0x1f,0x89,0xcd,0x38,0x1a,0x42,0xa3,0x92, 0x83,0x27,0x69,0x32,0x8e,0x86,0x10,0xa9,0x92,0xf0,0x20,0xd3,0xd4,0x31,0x84,0xb, 0x5e,0xbf,0x72,0x9e,0x61,0x14,0x40,0x1,0x0,0x13,0x4d,0xc,0x46,0x89,0x2a,0xa, 0x20,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/branch_open-on.png 0x0,0x0,0x0,0x96, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x2,0x62,0x4b,0x47,0x44,0x0,0xd3,0xb5,0x57,0xa0,0x5c,0x0,0x0, 0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0, 0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0xb,0x7,0xc, 0xd,0x1b,0x75,0xfe,0x31,0x99,0x0,0x0,0x0,0x27,0x49,0x44,0x41,0x54,0x8,0xd7, 0x65,0x8c,0xb1,0xd,0x0,0x0,0x8,0x83,0xe0,0xff,0xa3,0x75,0x70,0xb1,0xca,0xd4, 0x90,0x50,0x78,0x8,0x55,0x21,0x14,0xb6,0x54,0x70,0xe6,0x48,0x8d,0x87,0xcc,0xf, 0xd,0xe0,0xf0,0x8,0x2,0x34,0xe2,0x2b,0xa7,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/right_arrow_disabled.png 0x0,0x0,0x0,0xa0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x14,0x1f,0xd,0xfc, 0x52,0x2b,0x9c,0x0,0x0,0x0,0x24,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0x40, 0x5,0x73,0x3e,0xc0,0x58,0x4c,0xc8,0x5c,0x26,0x64,0x59,0x26,0x64,0xc5,0x70,0x4e, 0x8a,0x0,0x9c,0x93,0x22,0x80,0x61,0x1a,0xa,0x0,0x0,0x29,0x95,0x8,0xaf,0x88, 0xac,0xba,0x34,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/undock.png 0x0,0x0,0x1,0xc8, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1, 0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0xb,0x3,0x24,0x4f,0xed,0xa,0xe0,0x0,0x0,0x1,0x48,0x49,0x44,0x41,0x54,0x58, 0xc3,0xed,0x57,0x41,0x8e,0x83,0x30,0xc,0xb4,0x21,0xd0,0x3e,0x10,0x3f,0x8e,0x23, 0xe7,0x20,0xbe,0xb3,0x3f,0xd9,0x55,0x3,0x9b,0xd9,0x4b,0x2a,0x45,0x10,0x96,0x24, 0x4,0xf5,0x82,0xcf,0x2e,0x63,0x4f,0xc6,0x63,0x97,0xe8,0xc3,0xc1,0x57,0x7c,0x54, 0x6b,0x6d,0x98,0xb9,0x3a,0xca,0x3,0xb0,0xa8,0xb,0x9b,0xab,0x23,0x72,0x7e,0xab, 0x2b,0x90,0x45,0xa4,0x5,0xb0,0xc4,0xe4,0x56,0x57,0xb5,0x2f,0x22,0xd,0x80,0xf9, 0x28,0x6f,0xf3,0x4,0xe3,0x38,0x2e,0x39,0x80,0x0,0xac,0x88,0xb4,0xa9,0xbf,0x53, 0x9e,0x70,0x7e,0x98,0xb9,0xcd,0x64,0x65,0x3,0xae,0xb5,0x9e,0x99,0x59,0x45,0x3f, 0xc1,0x19,0x70,0x0,0x26,0x30,0x5,0x2a,0x9a,0x1,0x47,0x7b,0x16,0x78,0xd7,0x75, 0x75,0x42,0xe7,0x76,0x8d,0x73,0x46,0x84,0xa9,0x9d,0x5b,0x0,0x66,0x3d,0x1d,0xca, 0x5a,0x4b,0xd3,0x34,0xad,0x5,0x35,0xa7,0xa,0xea,0xa8,0x73,0x9f,0x29,0x57,0x68, 0x43,0x44,0x54,0xd,0xc3,0xf0,0x5,0x60,0x23,0xea,0xc,0xe7,0x53,0xb1,0x4c,0x39, 0x9f,0x30,0x44,0x64,0xd9,0xd3,0x40,0xed,0x31,0x60,0x44,0xe4,0x51,0xba,0xf3,0xe2, 0x46,0x94,0xda,0x79,0x94,0x11,0x15,0x8a,0xe0,0x74,0x38,0xbf,0x78,0x14,0x63,0x60, 0xc7,0xf3,0x93,0xa6,0xe3,0x34,0x3,0x22,0xd2,0x78,0xaa,0x4e,0xf5,0x85,0x32,0xcb, 0xe8,0xad,0xea,0x1c,0x47,0x2c,0xa6,0x81,0xd0,0xd4,0xc4,0x1c,0x25,0x97,0xad,0xe3, 0xd8,0xb8,0xb,0xb8,0xb,0xb8,0xb,0xa8,0x4a,0xff,0x61,0xe9,0xfb,0xbe,0x71,0x26, 0xf4,0x1d,0x58,0xf3,0x71,0x46,0xc4,0xcc,0x2a,0xf7,0x3a,0x76,0xeb,0x9d,0x0,0x44, 0x19,0x91,0x7a,0x9f,0xd4,0xcc,0x5c,0xaf,0x18,0xa8,0xcf,0x50,0xcb,0xcc,0xa1,0x23, 0x7,0xbb,0x54,0xc7,0x9e,0xd1,0xb9,0x1,0xe0,0x25,0x22,0xcf,0x7f,0xdf,0xda,0xbf, 0xd5,0xca,0x62,0xc3,0x84,0xc0,0x83,0x62,0xd3,0x5a,0xbf,0x4a,0x17,0xb0,0x7,0x4e, 0x44,0xf4,0x7,0xae,0xf5,0xd5,0xa6,0x1d,0xd1,0x22,0x8,0x0,0x0,0x0,0x0,0x49, 0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/Hmovetoolbar.png 0x0,0x0,0x0,0xe1, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0xa,0x0,0x0,0x0,0x36,0x8,0x6,0x0,0x0,0x0,0xfe,0x8a,0x8,0x6b, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0x9,0x33,0x22,0x7a,0x4c,0x4d,0x48,0x0,0x0,0x0,0x61,0x49,0x44,0x41,0x54,0x48, 0xc7,0x63,0xfc,0xcf,0x40,0x1c,0x60,0x62,0xa0,0x99,0x42,0x63,0x23,0x23,0x6,0x63, 0x23,0x23,0xc,0x36,0x1d,0xac,0x1e,0x55,0x38,0xc8,0x14,0x32,0xfe,0x67,0x60,0x60, 0x68,0x68,0x9f,0x8a,0x33,0x59,0xae,0x5a,0x3a,0x87,0xe1,0xda,0x95,0xf3,0x8c,0x34, 0xb2,0x5a,0x4b,0xc7,0x10,0x6f,0x8e,0xb8,0x76,0xe5,0x3c,0x23,0xe3,0x7f,0xa4,0x84, 0xcb,0xc0,0xc0,0xc0,0x70,0xf6,0xdc,0x39,0x14,0xf6,0x68,0x80,0x8f,0x6,0xf8,0x68, 0x80,0x8f,0x96,0x66,0x43,0x27,0x3d,0xe,0x72,0x37,0x2,0x0,0x10,0x30,0x40,0xb3, 0x35,0xa0,0x7c,0x49,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/up_arrow.png 0x0,0x0,0x0,0x9e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x8,0x15,0xf,0xfd, 0x8f,0xf8,0x2e,0x0,0x0,0x0,0x22,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0xd,0xfe,0x9f,0x87,0xb1,0x18,0x91,0x5,0x18,0xd,0xe1,0x42,0x48,0x2a,0xc,0x19, 0x18,0x18,0x91,0x5,0x10,0x2a,0xd1,0x0,0x0,0xca,0xb5,0x7,0xd2,0x76,0xbb,0xb2, 0xc5,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/branch_open.png 0x0,0x0,0x0,0xa6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0x9c,0x53,0x34,0xfc,0x5d,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0xb,0x1b,0xe,0x16, 0x4d,0x5b,0x6f,0x0,0x0,0x0,0x2a,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0x0,0x8c,0xc,0xc,0x73,0x3e,0x20,0xb,0xa4,0x8,0x30,0x32,0x30,0x20,0xb,0xa6, 0x8,0x30,0x30,0x30,0x42,0x98,0x10,0xc1,0x14,0x1,0x14,0x13,0x50,0xb5,0xa3,0x1, 0x0,0xc6,0xb9,0x7,0x90,0x5d,0x66,0x1f,0x83,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/left_arrow_disabled.png 0x0,0x0,0x0,0xa6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x14,0x1f,0x20,0xb9, 0x8d,0x77,0xe9,0x0,0x0,0x0,0x2a,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0x6,0xe6,0x7c,0x60,0x60,0x60,0x42,0x30,0xa1,0x1c,0x8,0x93,0x81,0x81,0x9,0xc1, 0x64,0x60,0x60,0x62,0x60,0x48,0x11,0x40,0xe2,0x20,0x73,0x19,0x90,0x8d,0x40,0x2, 0x0,0x23,0xed,0x8,0xaf,0x64,0x9f,0xf,0x15,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/stylesheet-vline.png 0x0,0x0,0x0,0xef, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x51,0x0,0x0,0x0,0x3a,0x8,0x6,0x0,0x0,0x0,0xc8,0xbc,0xb5,0xaf, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0xb,0x2a,0x32,0xff,0x7f,0x20,0x5a,0x0,0x0,0x0,0x6f,0x49,0x44,0x41,0x54,0x78, 0xda,0xed,0xd0,0xb1,0xd,0x0,0x30,0x8,0x3,0x41,0xc8,0xa0,0xc,0xc7,0xa2,0x49, 0xcf,0x4,0x28,0xba,0x2f,0x5d,0x59,0x97,0xb1,0xb4,0xee,0xbe,0x73,0xab,0xaa,0xdc, 0xf8,0xf5,0x84,0x20,0x42,0x84,0x28,0x88,0x10,0x21,0x42,0x14,0x44,0x88,0x10,0x21, 0xa,0x22,0x44,0x88,0x10,0x5,0x11,0x22,0x44,0x88,0x82,0x8,0x11,0x22,0x44,0x41, 0x84,0x8,0x51,0x10,0x21,0x42,0x84,0x28,0x88,0x10,0x21,0x42,0x14,0x44,0x88,0x10, 0x21,0xa,0x22,0x44,0x88,0x10,0x5,0x11,0x22,0x44,0x88,0x82,0x8,0x11,0x22,0x44, 0x41,0x84,0x8,0x51,0x10,0x21,0x42,0xfc,0xaa,0x7,0x12,0x55,0x4,0x74,0x56,0x9e, 0x9e,0x54,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/branch_closed.png 0x0,0x0,0x0,0xa0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0x9c,0x53,0x34,0xfc,0x5d,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0xb,0x1b,0x29,0xb3, 0x47,0xee,0x4,0x0,0x0,0x0,0x24,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0x40, 0x5,0x73,0x3e,0xc0,0x58,0x4c,0xc8,0x5c,0x26,0x64,0x59,0x26,0x64,0xc5,0x70,0x4e, 0x8a,0x0,0x9c,0x93,0x22,0x80,0x61,0x1a,0xa,0x0,0x0,0x29,0x95,0x8,0xaf,0x88, 0xac,0xba,0x34,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/left_arrow.png 0x0,0x0,0x0,0xa6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x14,0x1d,0x0,0xb0, 0xd5,0x35,0xa3,0x0,0x0,0x0,0x2a,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0x6,0xfe,0x9f,0x67,0x60,0x60,0x42,0x30,0xa1,0x1c,0x8,0x93,0x81,0x81,0x9,0xc1, 0x64,0x60,0x60,0x62,0x60,0x60,0x34,0x44,0xe2,0x20,0x73,0x19,0x90,0x8d,0x40,0x2, 0x0,0x64,0x40,0x9,0x75,0x86,0xb3,0xad,0x9c,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/right_arrow.png 0x0,0x0,0x0,0xa0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x6,0x0,0x0,0x0,0x9,0x8,0x4,0x0,0x0,0x0,0xbb,0x93,0x95,0x16, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x14,0x1c,0x1f,0x24, 0xc6,0x9,0x17,0x0,0x0,0x0,0x24,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0x40, 0x5,0xff,0xcf,0xc3,0x58,0x4c,0xc8,0x5c,0x26,0x64,0x59,0x26,0x64,0xc5,0x70,0xe, 0xa3,0x21,0x9c,0xc3,0x68,0x88,0x61,0x1a,0xa,0x0,0x0,0x6d,0x84,0x9,0x75,0x37, 0x9e,0xd9,0x23,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/checkbox.png 0x0,0x0,0x1,0x57, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x9,0x8,0x6,0x0,0x0,0x0,0xe0,0x91,0x6,0x10, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4, 0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a, 0x25,0x0,0x0,0x80,0x83,0x0,0x0,0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75, 0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5, 0x46,0x0,0x0,0x0,0xdd,0x49,0x44,0x41,0x54,0x78,0xda,0x5c,0x8e,0xb1,0x4e,0x84, 0x40,0x18,0x84,0x67,0xef,0x4c,0x2c,0xc8,0xd9,0x2c,0xd,0x58,0x50,0x1b,0xb,0xc3, 0xfa,0x24,0x77,0xbd,0xd,0x85,0x4f,0x40,0xb,0xbb,0xcb,0x3b,0xd0,0x68,0x41,0x72, 0xc5,0xd2,0x28,0x4f,0x2,0xcf,0xb1,0x97,0x40,0x61,0xd4,0xc2,0xc4,0x62,0x2c,0xbc, 0x4d,0xd0,0x49,0xfe,0xbf,0xf8,0x32,0xff,0x3f,0x23,0x48,0xc2,0x5a,0x3b,0x0,0x80, 0xd6,0xfa,0x80,0xb3,0xac,0xb5,0x3,0x49,0x18,0x63,0xe,0x5b,0x21,0xc4,0x90,0xe7, 0xf9,0x3e,0x49,0x92,0x9b,0xbe,0xef,0xef,0xca,0xb2,0x7c,0xf5,0xde,0xbf,0x4,0xe6, 0x9c,0xbb,0xbd,0x20,0xf9,0x19,0xae,0x95,0x52,0xfb,0x2c,0xcb,0xbe,0xa5,0x94,0x1, 0x81,0xe4,0x9b,0x38,0xbf,0x3c,0x2a,0xa5,0x1e,0xf0,0x4f,0xe3,0x38,0x3e,0x37,0x4d, 0xf3,0x28,0x48,0x2,0x0,0xba,0xae,0x7b,0x97,0x52,0xee,0x82,0x61,0x59,0x96,0x8f, 0xa2,0x28,0xae,0x0,0x60,0x3,0x0,0xc6,0x98,0xe3,0xda,0x0,0x0,0x71,0x1c,0xef, 0xb4,0xd6,0x4f,0x0,0xb0,0x5,0xf0,0x27,0x6a,0x9e,0x67,0x44,0x51,0x4,0x0,0x48, 0xd3,0xf4,0xde,0x39,0x77,0xbd,0x21,0xf9,0xb5,0xea,0x70,0x6a,0xdb,0xf6,0x72,0x9a, 0xa6,0xd3,0xaa,0xf8,0xef,0xaa,0xeb,0xda,0x57,0x55,0xe5,0x49,0x22,0xcc,0x9a,0xfd, 0xc,0x0,0x24,0xab,0x6e,0xfa,0x96,0x21,0xfc,0xb8,0x0,0x0,0x0,0x0,0x49,0x45, 0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/stylesheet-branch-end.png 0x0,0x0,0x0,0xe0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x51,0x0,0x0,0x0,0x3a,0x8,0x6,0x0,0x0,0x0,0xc8,0xbc,0xb5,0xaf, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0xb,0x29,0x1c,0x8,0x84,0x7e,0x56,0x0,0x0,0x0,0x60,0x49,0x44,0x41,0x54,0x78, 0xda,0xed,0xd9,0xb1,0xd,0x0,0x20,0x8,0x0,0x41,0x71,0x50,0x86,0x63,0x51,0xed, 0x8d,0x85,0x25,0x89,0x77,0xa5,0x15,0xf9,0x48,0x45,0x8c,0xa6,0xaa,0x6a,0x9d,0x6f, 0x99,0x19,0x1d,0x67,0x9d,0x3,0x11,0x45,0x14,0x11,0x11,0x45,0x14,0x51,0x44,0x44, 0x14,0x51,0x44,0x11,0x11,0x51,0x44,0x11,0x45,0x44,0x44,0x11,0x45,0x14,0x11,0x11, 0x45,0x14,0xf1,0x5b,0xd1,0x75,0xb0,0xdb,0xdd,0xd9,0x4f,0xb4,0xce,0x88,0x28,0x22, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xcf,0x36,0xce,0x69,0x7,0x1e,0xe9, 0x39,0x55,0x40,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/stylesheet-branch-more.png 0x0,0x0,0x0,0xb6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x18,0x0,0x0,0x0,0x11,0x8,0x6,0x0,0x0,0x0,0xc7,0x78,0x6c,0x30, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0xb,0x2c,0xd,0x1f,0x43,0xaa,0xe1,0x0,0x0,0x0,0x36,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0x60,0x20,0x1,0x2c,0x5a,0xb4,0xe8,0xff,0xa2,0x45,0x8b,0xfe,0x93,0xa2, 0x87,0x89,0x81,0xc6,0x60,0xd4,0x82,0x11,0x60,0x1,0x23,0xa9,0xc9,0x74,0xd0,0xf9, 0x80,0x85,0x1c,0x4d,0x71,0x71,0x71,0x8c,0xa3,0xa9,0x68,0xd4,0x82,0x61,0x64,0x1, 0x0,0x31,0xb5,0x9,0xec,0x1f,0x4b,0xb4,0x15,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/Vmovetoolbar.png 0x0,0x0,0x0,0xe4, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x36,0x0,0x0,0x0,0xa,0x8,0x6,0x0,0x0,0x0,0xff,0xfd,0xad,0xb, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0x7f,0x0,0x87,0x0,0x95,0xe6,0xde,0xa6,0xaf,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1, 0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17, 0x9,0x2a,0x2b,0x98,0x90,0x5c,0xf4,0x0,0x0,0x0,0x64,0x49,0x44,0x41,0x54,0x48, 0xc7,0x63,0xfc,0xcf,0x30,0x3c,0x1,0xb,0xa5,0x6,0x34,0xb4,0x4f,0x85,0x87,0xcd, 0xaa,0xa5,0x73,0x18,0xae,0x5d,0x39,0xcf,0x48,0x2b,0x35,0x14,0x79,0xcc,0xd8,0xc8, 0x88,0x24,0x3,0x7c,0x89,0xd0,0x4f,0x2d,0x35,0x84,0xc0,0xd9,0x73,0xe7,0xe0,0x6c, 0x26,0x86,0x91,0x92,0x14,0x91,0x7d,0x4d,0x54,0x52,0xc,0x4d,0x26,0xa8,0x9f,0x5a, 0x6a,0x46,0x93,0xe2,0x68,0x52,0x1c,0x82,0x49,0x91,0x91,0xd2,0x7a,0x4c,0x4b,0xc7, 0x10,0xc5,0x8,0x6c,0xc5,0x34,0xb5,0xd4,0xd0,0xd5,0x63,0x83,0x15,0x0,0x0,0x7a, 0x30,0x4a,0x9,0x71,0xea,0x2d,0x6e,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae, 0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/down_arrow_disabled.png 0x0,0x0,0x0,0xa6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x9,0x0,0x0,0x0,0x6,0x8,0x4,0x0,0x0,0x0,0xbb,0xce,0x7c,0x4e, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x2,0x62,0x4b,0x47,0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18, 0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x8,0x17,0x8,0x15,0x3b,0xdc, 0x3b,0xc,0x9b,0x0,0x0,0x0,0x2a,0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0xc0, 0x0,0x8c,0xc,0xc,0x73,0x3e,0x20,0xb,0xa4,0x8,0x30,0x32,0x30,0x20,0xb,0xa6, 0x8,0x30,0x30,0x30,0x42,0x98,0x10,0xc1,0x14,0x1,0x14,0x13,0x50,0xb5,0xa3,0x1, 0x0,0xc6,0xb9,0x7,0x90,0x5d,0x66,0x1f,0x83,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/rc/sizegrip.png 0x0,0x0,0x0,0x81, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x1,0x3,0x0,0x0,0x0,0x25,0x3d,0x6d,0x22, 0x0,0x0,0x0,0x6,0x50,0x4c,0x54,0x45,0x0,0x0,0x0,0xae,0xae,0xae,0x77,0x6b, 0xd6,0x2d,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0, 0x0,0x0,0x29,0x49,0x44,0x41,0x54,0x78,0x5e,0x5,0xc0,0xb1,0xd,0x0,0x20,0x8, 0x4,0xc0,0xc3,0x58,0xd8,0xfe,0xa,0xcc,0xc2,0x70,0x8c,0x6d,0x28,0xe,0x97,0x47, 0x68,0x86,0x55,0x71,0xda,0x1d,0x6f,0x25,0xba,0xcd,0xd8,0xfd,0x35,0xa,0x4,0x1b, 0xd6,0xd9,0x1a,0x92,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/scrollbar.png 0x0,0x0,0x0,0xea, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0xd,0x0,0x0,0x0,0xd,0x8,0x6,0x0,0x0,0x0,0x72,0xeb,0xe4,0x7c, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc3,0x0,0x0,0xe,0xc3,0x1, 0xc7,0x6f,0xa8,0x64,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x5,0x1b, 0x14,0x18,0x1a,0x82,0x86,0x43,0x95,0x0,0x0,0x0,0x1d,0x69,0x54,0x58,0x74,0x43, 0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x0,0x0,0x0,0x0,0x43,0x72,0x65,0x61,0x74, 0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x64,0x2e,0x65,0x7, 0x0,0x0,0x0,0x41,0x49,0x44,0x41,0x54,0x28,0xcf,0xed,0xd2,0xa1,0x11,0x0,0x20, 0xc,0x4,0xc1,0x83,0x61,0x22,0x53,0x57,0x4a,0x4e,0x5d,0x69,0x0,0x4,0xe,0x3, 0x44,0xa0,0x38,0xbf,0xea,0xbf,0x88,0x48,0xe7,0xb2,0x6,0x60,0x66,0xc7,0xc0,0xdd, 0x27,0x2,0x88,0x88,0x2d,0x50,0x55,0x0,0x2a,0x89,0x3e,0x7a,0x8e,0xda,0x3a,0xdc, 0x49,0x25,0xf3,0xbd,0x1,0x3,0xd0,0x8,0x6b,0x25,0x92,0x78,0x1c,0x0,0x0,0x0, 0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/border3.png 0x0,0x0,0x1,0x5e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x13,0x0,0x0,0x0,0x14,0x8,0x6,0x0,0x0,0x0,0x6f,0x55,0x6,0x74, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0x3b,0x0,0x3b,0x0,0x3b,0xb6,0x87,0xd1,0xbd,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc3,0x0,0x0,0xe,0xc3,0x1, 0xc7,0x6f,0xa8,0x64,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x5,0x1b, 0x14,0x2e,0x3,0x6f,0xf1,0x7a,0x20,0x0,0x0,0x0,0x1d,0x69,0x54,0x58,0x74,0x43, 0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x0,0x0,0x0,0x0,0x43,0x72,0x65,0x61,0x74, 0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x64,0x2e,0x65,0x7, 0x0,0x0,0x0,0xb5,0x49,0x44,0x41,0x54,0x38,0xcb,0xc5,0x54,0x39,0xa,0x4,0x21, 0x10,0x2c,0x87,0x49,0xd5,0x57,0x98,0xfb,0x3e,0x73,0x7d,0x9f,0xa9,0xf8,0xa,0x5, 0xe3,0xde,0x60,0x10,0x56,0x98,0x9e,0x71,0x45,0xd8,0x82,0xa6,0xc0,0xa3,0xfa,0xc0, 0x52,0x48,0x29,0x9,0x9b,0x70,0x2,0x80,0x31,0x6,0x4a,0xa9,0x65,0x91,0x5a,0x2b, 0x72,0xce,0x97,0x98,0x52,0xa,0xad,0xb5,0x65,0xb1,0x5e,0xc8,0x81,0x8d,0x38,0x1, 0x80,0x88,0x40,0xb4,0x3e,0xba,0x7e,0xf7,0xf8,0x5e,0xb8,0x8b,0x94,0xd2,0xc0,0x77, 0xd1,0xf1,0xda,0x66,0x8,0x61,0xe0,0x27,0xbc,0x8a,0x39,0xe7,0x6,0x9e,0x12,0xe3, 0x5a,0xf0,0xde,0xf,0x3c,0xd5,0x26,0x77,0xd0,0x39,0x37,0xf0,0x7f,0x67,0xf6,0x56, 0xd9,0xa3,0x18,0x57,0xfe,0xec,0xcc,0xa6,0xdf,0xd9,0xcf,0x33,0xe3,0x36,0x1,0xc0, 0x7b,0x3f,0x30,0x97,0x18,0x0,0x84,0x94,0x92,0xac,0xb5,0x28,0xa5,0x2c,0xdb,0x49, 0x6b,0x8d,0x18,0xe3,0xe5,0x4d,0xce,0x6b,0x1c,0x84,0x10,0xbc,0xd1,0x67,0x4,0x66, 0x92,0x6d,0xfd,0x35,0xc4,0xce,0x6f,0xfb,0x3,0x59,0x9b,0x43,0x0,0xaf,0x6f,0xc6, 0x10,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/style_debug.css 0x0,0x0,0x4,0x96, 0x0, 0x0,0x19,0x61,0x78,0x9c,0xd5,0x58,0x4b,0x6f,0xe3,0x36,0x10,0x3e,0x2b,0x40,0xfe, 0x3,0x81,0x5c,0xda,0x5,0x5c,0xcb,0x76,0x76,0xd7,0xa5,0x4f,0x9b,0xf4,0x75,0xd8, 0x2,0x5d,0x6c,0xd0,0x3d,0x16,0x94,0xc4,0x58,0xac,0x65,0x52,0xa0,0xa8,0x3a,0x41, 0xb0,0xff,0xbd,0x43,0x8a,0x92,0x45,0x3d,0x6c,0x39,0x72,0xb2,0xad,0x79,0x49,0x28, 0x72,0x1e,0xdf,0x7c,0x9c,0x19,0xf2,0xd3,0x17,0x16,0xad,0xa9,0x42,0xe8,0xc9,0xf3, 0xbc,0xcb,0xb,0x2f,0x20,0xe1,0x66,0x2d,0x45,0xce,0x23,0x8c,0xae,0xae,0x7d,0x3d, 0x56,0x7a,0x3e,0x14,0x89,0x90,0x18,0xed,0x62,0xa6,0xe8,0xea,0xf2,0xe2,0xeb,0xe5, 0xc5,0xe5,0xc5,0xa7,0x9f,0x44,0xb8,0xb1,0xfb,0x9f,0x7a,0xf6,0xb6,0x97,0x62,0xac, 0x98,0x4a,0x68,0xb1,0x43,0xc8,0x88,0xca,0x9,0xdb,0x92,0x35,0xc5,0x28,0x97,0xc9, 0x77,0x78,0x4a,0x23,0xa6,0x84,0x9c,0x66,0xea,0x31,0xa1,0x7f,0x45,0x44,0x6e,0xa6, 0xc5,0xaa,0xc5,0xf,0x29,0x5f,0x7f,0xbf,0xda,0xef,0xda,0xb1,0x48,0xc5,0x18,0xcd, 0xd3,0x87,0xda,0x64,0x42,0xef,0x15,0x46,0x33,0x77,0xd2,0xc8,0xc2,0x28,0x13,0x9, 0x8b,0xf4,0x74,0x4a,0xa2,0x88,0xf1,0x35,0x46,0xd7,0x66,0x59,0x61,0xe1,0x2f,0x92, 0x6c,0xe9,0x51,0x3f,0x3e,0x87,0x52,0x24,0xc9,0x7,0x49,0xc9,0xd1,0xa5,0x77,0x42, 0x24,0x1,0x91,0x47,0xd7,0x7d,0x24,0x1,0x4d,0x5a,0xab,0x94,0x24,0x3c,0x4b,0x89, 0xa4,0x5c,0x55,0x2b,0x3f,0x4,0x19,0x4c,0x87,0x6a,0x80,0x11,0xde,0x89,0xe8,0xce, 0x7b,0xd0,0x5d,0x38,0x40,0x5a,0x16,0x5c,0xf9,0xe6,0x77,0x0,0xe1,0x6,0x5d,0xbc, 0x7b,0xc1,0x75,0x58,0xfc,0x1a,0xde,0xbf,0x4a,0x92,0xc6,0x2c,0xcc,0xfe,0x64,0x74, 0xd7,0x70,0xa3,0xd2,0x53,0x21,0xe5,0x65,0x34,0xa1,0xa1,0x62,0x82,0x57,0xdf,0xee, 0xcd,0xcf,0xfd,0xd6,0x21,0x62,0xee,0xeb,0xd1,0xc5,0xe1,0x6e,0xa3,0x44,0x9e,0xde, 0x88,0x7,0x7d,0x1c,0x4e,0x44,0x70,0x10,0x80,0x83,0x98,0x78,0x1b,0xd3,0x70,0x63, 0x8c,0x18,0xc0,0x89,0x72,0x31,0xc6,0x8c,0x47,0x2c,0x24,0x60,0x9b,0x39,0xcb,0x9e, 0x87,0x46,0x3a,0xd0,0xb4,0x75,0x8,0x31,0x0,0xeb,0xe5,0xc2,0x3f,0x64,0x1c,0xce, 0x79,0xa8,0x67,0x69,0x84,0x63,0xf1,0xf,0xed,0x37,0x96,0xb,0x4e,0xdb,0x6a,0x67, 0x46,0x2d,0xea,0x17,0x6f,0x85,0x5b,0xb1,0xcf,0x92,0xb,0x92,0xff,0xc8,0xb3,0xf8, 0x26,0x57,0x4a,0xf0,0x7e,0x41,0xaf,0x88,0xa6,0xe6,0xe2,0x96,0xf1,0x72,0xf5,0x75, 0x41,0xd9,0xa3,0x9c,0x6e,0xd2,0xcb,0xdb,0x12,0xb9,0x66,0xbc,0xf4,0xf6,0x6b,0xc3, 0x55,0x27,0x20,0x27,0x22,0xd7,0x92,0x95,0x4a,0x9a,0x65,0xcf,0x8d,0x43,0x4b,0x9a, 0x1b,0xd5,0x91,0xc2,0x22,0x96,0x91,0x20,0xd1,0xd2,0xf6,0x0,0x5e,0x2d,0x7d,0x3d, 0x56,0xcf,0x90,0x7c,0xa7,0x85,0x95,0xb5,0xd,0xc2,0xb0,0xc5,0x8e,0x6,0x4,0x3f, 0xab,0x64,0x2d,0xc9,0xa3,0x53,0x1e,0x1c,0x8a,0xbd,0x2c,0xc3,0xe6,0x87,0x19,0x36, 0x9c,0x4a,0xbe,0x4b,0xa5,0x7a,0xf6,0xdc,0xbb,0x34,0x9e,0x4a,0x35,0x59,0xe3,0x83, 0xbf,0x2f,0xb1,0x9d,0x7d,0xcc,0xad,0xd8,0x6,0xa2,0x4a,0xb8,0x43,0xd0,0x9c,0x1d, 0x39,0xaf,0x3,0xb1,0x9c,0xd7,0xb1,0xb4,0xbd,0x8b,0x3b,0xa7,0x44,0x5a,0x4e,0xb9, 0xb6,0x2,0xc9,0xa4,0x48,0x27,0x91,0xd8,0x71,0x63,0x76,0x96,0x7,0x21,0x28,0x81, 0xc6,0x60,0x22,0x24,0x33,0xa1,0xb1,0x6a,0x56,0xee,0xd7,0x54,0x64,0x4c,0x17,0x4b, 0x28,0x27,0x22,0x45,0xb0,0x34,0xd6,0xc5,0xc4,0x2b,0x1d,0x7b,0x6b,0x74,0xb9,0xd, 0x55,0xb7,0xd7,0xe6,0x8b,0x75,0x54,0xd3,0xd2,0xb2,0xdb,0xf9,0xec,0xa0,0x88,0xa6, 0x6f,0xd0,0xdf,0x79,0xa6,0x10,0x41,0x19,0xd8,0x5,0x3d,0x60,0xc2,0x38,0x45,0x6f, 0xa6,0x55,0x93,0xc8,0x48,0xb3,0x11,0x6a,0x97,0xfb,0xb2,0x9f,0xcc,0xe1,0x80,0x7d, 0x4e,0x19,0xb7,0xd5,0xba,0x41,0x8d,0xe7,0x84,0x8f,0xcc,0x97,0xe4,0x6d,0x99,0x6e, 0x4f,0x8a,0x60,0x87,0x4d,0x18,0xe7,0xe9,0x24,0xb0,0xe7,0xbb,0x3b,0x3e,0x85,0xfa, 0x1,0xe1,0xd1,0xc0,0x95,0xf3,0x88,0x28,0xa4,0x62,0xba,0xff,0xa,0xc9,0x45,0x72, 0x38,0x6b,0x1a,0xc6,0x9e,0x3e,0xf3,0x5c,0xac,0x2e,0x97,0xbd,0x83,0x75,0xe8,0x98, 0xd7,0x65,0xa,0x68,0x59,0xb5,0xd4,0xa3,0xf,0x34,0xcd,0xe7,0x71,0xb0,0x5,0x2, 0x36,0x6f,0xff,0x87,0xc8,0xd5,0x5c,0x1f,0x88,0x9d,0x4b,0xff,0x63,0x79,0xf1,0x5b, 0x1c,0x89,0x6f,0x7b,0x18,0x5e,0x2c,0x72,0xff,0x1,0xba,0xbe,0x98,0x6f,0x1f,0x21, 0x27,0xff,0xc,0x2d,0x47,0xf5,0x22,0x70,0x40,0x64,0x8f,0xfa,0x11,0xdd,0x45,0x9d, 0x3c,0x77,0xf4,0x41,0x15,0x96,0x9c,0x54,0xf2,0xcf,0x67,0xdc,0xec,0x90,0x71,0x24, 0x28,0x7b,0xbe,0x94,0x40,0x15,0x7b,0xd2,0xb1,0xbb,0xd3,0xf1,0x22,0x1,0xda,0x15, 0x8f,0x22,0xf7,0xe6,0x49,0x41,0xc7,0x4b,0x37,0x81,0x56,0x7f,0x59,0xd1,0xb,0xc3, 0xd0,0x55,0xe8,0xeb,0x51,0x97,0x7b,0x43,0x24,0xc6,0x5a,0x4c,0xdb,0xef,0x57,0xbe, 0x73,0x34,0xef,0xf,0x1d,0x37,0xe6,0x9a,0xbd,0x23,0x2e,0x74,0x6d,0x59,0xc5,0xa5, 0x7e,0xdc,0x5,0xc2,0x74,0xe6,0xc5,0xfb,0x42,0x25,0xa2,0x9e,0x4e,0x17,0xef,0xf5, 0xd0,0x32,0xd6,0x92,0x45,0xba,0x19,0xd9,0xbf,0x3c,0x14,0x99,0xf6,0xb4,0xb6,0x62, 0xd0,0x9d,0xf8,0x37,0x4a,0xe0,0xab,0xb6,0xa,0x83,0x93,0xe6,0xdd,0xe2,0xc0,0x13, 0xd1,0x79,0xe,0x7a,0xe7,0x33,0xc3,0xde,0x90,0xc1,0x7,0xcc,0xef,0x4,0xb7,0xf8, 0xf3,0xd6,0x64,0x27,0xdb,0xb2,0xbb,0x9e,0x9d,0xc1,0x5,0x7b,0xe3,0xff,0x9d,0xf2, 0xdc,0x50,0x44,0xdf,0xb3,0x8a,0x8c,0x9b,0x92,0xd0,0xb8,0x66,0x92,0x18,0x9c,0x41, 0x3b,0x81,0x2,0xaa,0x76,0x94,0x72,0xb4,0x85,0x2d,0x48,0xbf,0xc3,0xe9,0x2d,0x59, 0x91,0x3d,0x2b,0x3c,0x60,0x93,0xd9,0xd8,0xc0,0xbf,0xeb,0xa1,0xc5,0x51,0x5d,0xa3, 0xa7,0xd6,0xb9,0x8b,0x41,0x51,0x35,0x95,0xeb,0xee,0x16,0x6d,0x45,0x9e,0x51,0x24, 0x24,0xda,0xd0,0xc7,0x40,0x10,0x19,0x75,0xf4,0x19,0x64,0xa9,0x47,0x8f,0x8a,0xea, 0x6,0xdd,0xdc,0xb5,0x34,0xbf,0x7d,0x8d,0x35,0xaf,0x81,0x66,0x1f,0x54,0x98,0x49, 0xa,0xf1,0x6b,0xef,0x59,0x2c,0xf5,0x18,0x49,0xa8,0x66,0xfb,0xb1,0x57,0xc,0x78, 0xbe,0x96,0x62,0xe4,0x6a,0x8e,0x9,0x8f,0x92,0xe,0xbd,0xcb,0x77,0x7a,0xac,0x5a, 0xc4,0xee,0xcb,0xa0,0x99,0x11,0x9,0x3c,0x39,0xeb,0xb5,0xba,0xcf,0xde,0xa3,0xd, 0xde,0xf9,0x5b,0x39,0xfb,0x10,0x5a,0x5,0xf,0xb6,0x52,0xb0,0x7,0x54,0x83,0x29, 0x18,0xac,0x51,0x2c,0x6c,0x5d,0xbf,0xa0,0x3f,0x49,0xe0,0x1f,0x93,0x43,0xaa,0x96, 0x85,0x4,0xa0,0x38,0x87,0x4a,0xa9,0x13,0x63,0x71,0x69,0xfd,0x51,0x1f,0x3e,0xd3, 0xa5,0x14,0x7f,0x8f,0x33,0x75,0xe1,0xeb,0xd1,0x32,0xd5,0x42,0xe7,0x98,0x1a,0xd3, 0x42,0xe9,0xac,0xf9,0x2c,0x81,0x26,0x73,0x9b,0x10,0xe8,0x3,0x14,0xe8,0x8,0x89, 0x5c,0x65,0x20,0xc7,0xf4,0x54,0x85,0xd3,0xc5,0x81,0x7c,0xa9,0xd4,0x6b,0xc1,0xfe, 0x17,0xe,0x73,0xb6,0xd0, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/border2.png 0x0,0x0,0x1,0xf, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x27,0x0,0x0,0x0,0x16,0x8,0x6,0x0,0x0,0x0,0x43,0x85,0x85,0x3d, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc3,0x0,0x0,0xe,0xc3,0x1, 0xc7,0x6f,0xa8,0x64,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x5,0x1b, 0x13,0x2f,0x37,0x52,0x11,0xa9,0x51,0x0,0x0,0x0,0x1d,0x69,0x54,0x58,0x74,0x43, 0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x0,0x0,0x0,0x0,0x43,0x72,0x65,0x61,0x74, 0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x64,0x2e,0x65,0x7, 0x0,0x0,0x0,0x66,0x49,0x44,0x41,0x54,0x48,0xc7,0xed,0xd7,0x21,0xe,0xc0,0x30, 0xc,0x3,0xc0,0x74,0x9a,0x4a,0xc,0xfb,0x82,0xbc,0xa3,0xff,0x47,0x7d,0x44,0x5f, 0x11,0x12,0xb2,0xa1,0x4e,0xea,0x3e,0x50,0x3,0x1b,0x19,0x9e,0x14,0xe2,0x94,0xd6, 0xda,0x63,0xa4,0xb9,0x57,0xc9,0x4c,0x1a,0x54,0xad,0x75,0xc7,0xf5,0xde,0xd,0xc0, 0x71,0x58,0x44,0xd8,0x18,0x63,0xc7,0x1,0xb0,0x39,0xe7,0x71,0x9c,0xbb,0x7f,0xfd, 0x32,0xe2,0x8,0x27,0x9c,0x70,0xc2,0x9,0x27,0x9c,0x70,0xc2,0x91,0x2d,0xe1,0xff, 0x96,0x62,0x48,0x61,0xfe,0x21,0xa8,0xcf,0xfa,0x2,0x1a,0x9c,0xf,0x39,0xbd,0x81, 0xd0,0xc9,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/border.png 0x0,0x0,0x1,0x71, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x2c,0x0,0x0,0x0,0x19,0x8,0x6,0x0,0x0,0x0,0x4a,0x33,0xcc,0x1f, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc3,0x0,0x0,0xe,0xc3,0x1, 0xc7,0x6f,0xa8,0x64,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdc,0x5,0x1b, 0x13,0x9,0x1a,0xd4,0x10,0x76,0x0,0x0,0x0,0x0,0x1d,0x69,0x54,0x58,0x74,0x43, 0x6f,0x6d,0x6d,0x65,0x6e,0x74,0x0,0x0,0x0,0x0,0x0,0x43,0x72,0x65,0x61,0x74, 0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x47,0x49,0x4d,0x50,0x64,0x2e,0x65,0x7, 0x0,0x0,0x0,0xc8,0x49,0x44,0x41,0x54,0x58,0xc3,0xed,0x98,0xb1,0xd,0xc3,0x20, 0x14,0x44,0xef,0xac,0x5f,0xd0,0x31,0x85,0x67,0x70,0xeb,0xd,0x3c,0xab,0x37,0xa1, 0xf7,0x14,0xee,0x68,0x80,0x14,0x91,0x63,0x22,0x48,0x97,0xe2,0x90,0x4c,0x9,0xcd, 0xe9,0xe9,0x71,0x5f,0xc0,0x75,0x5d,0xb,0x6,0x5a,0x6,0x0,0xc7,0x71,0x20,0xc6, 0x28,0x1d,0xd4,0x39,0x87,0x79,0x9e,0x61,0x24,0x11,0x63,0xc4,0xb6,0x6d,0xd2,0x81, 0xf7,0x7d,0x7,0xc9,0x37,0x61,0x0,0x28,0xa5,0xe0,0x3c,0x4f,0xc9,0xb0,0xde,0xfb, 0x6f,0x25,0xae,0xc0,0x39,0x67,0xc9,0xc0,0xa5,0xdc,0xd7,0xcc,0x48,0x7e,0x36,0xeb, 0x3,0xc5,0xc0,0x24,0x31,0x5d,0x81,0x55,0xe9,0xd6,0xd9,0x1a,0x87,0xd5,0x9,0x37, 0x4a,0xa8,0x3b,0x3c,0x24,0xe1,0xa9,0xb7,0xf9,0xb4,0xc4,0x3f,0x95,0xa8,0x5b,0x42, 0xd5,0xe1,0x6e,0x4b,0xe4,0x9c,0x65,0x9,0xd7,0x20,0x1f,0x25,0x9e,0xc1,0xf1,0xab, 0x25,0x86,0x21,0x7c,0x5,0x4e,0x29,0xc9,0x12,0x4e,0x29,0xf5,0x5b,0x42,0x9d,0x70, 0xa3,0x84,0x7a,0xad,0x8d,0x3f,0x38,0x9c,0x73,0x63,0x28,0x61,0x66,0x8,0x21,0x68, 0x3f,0xef,0xcd,0x6e,0x25,0x96,0x65,0x19,0xe6,0x5f,0xe2,0x5,0x54,0xb0,0xb8,0x9f, 0xe4,0x5e,0x22,0xb2,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/style_dark/style.css 0x0,0x0,0x4,0xfc, 0x0, 0x0,0x23,0x27,0x78,0x9c,0xdd,0x59,0x4b,0x6f,0xdb,0x38,0x10,0x3e,0xdb,0x40,0xfe, 0x3,0x1,0x5f,0xda,0x22,0x5e,0xcb,0x72,0xe2,0xaa,0xcc,0x29,0xc9,0xbe,0xe,0x5d, 0xa0,0x8b,0x16,0xed,0x71,0x41,0x89,0xb4,0x45,0x44,0x16,0x55,0x8a,0xda,0x38,0x58, 0xec,0x7f,0x5f,0x3e,0x24,0x59,0x2f,0x5b,0x6a,0x4c,0x67,0xdd,0x6a,0x0,0xc3,0xa2, 0xf8,0x98,0xf9,0x66,0x86,0x9c,0x19,0x92,0xf,0x48,0x84,0x9f,0x29,0x79,0x4,0xff, 0x5c,0x8c,0x1,0x0,0x5f,0x13,0xce,0x12,0xc2,0xc5,0xd3,0x34,0x60,0xd1,0x3d,0x63, 0x1c,0xdf,0x6e,0x49,0xa,0xc1,0x63,0x48,0x5,0xb9,0xb9,0x18,0xff,0x7b,0x31,0xbe, 0x18,0xff,0xf9,0x85,0xe2,0x35,0x11,0x6a,0xc8,0xc8,0x47,0xc1,0xc3,0x9a,0xb3,0x2c, 0xc6,0x10,0x4c,0xae,0x1c,0x45,0x37,0x23,0xd9,0x2e,0x87,0x33,0xde,0x1c,0xf7,0x33, 0xb,0x1e,0x7a,0xc6,0xb6,0xbb,0x42,0x28,0xa8,0x88,0x48,0x6b,0xc4,0xd7,0x88,0xc6, 0x4,0xf1,0x35,0x47,0x98,0x92,0x58,0xbc,0x4a,0x13,0x4e,0x10,0x86,0x9,0xc2,0x97, 0x60,0x3b,0x87,0xce,0x25,0x78,0xd2,0xbf,0x5b,0x57,0xff,0x77,0xe1,0xfc,0x12,0xa4, 0x82,0x25,0xd0,0x1,0x93,0xc5,0xb5,0xa2,0xfc,0x7d,0xe,0x26,0x6e,0xa0,0xe8,0xf5, 0x8d,0x5a,0x42,0xca,0x4c,0xf8,0x94,0x6e,0xd0,0x9a,0x40,0x90,0xf1,0xe8,0x15,0x9c, 0x11,0x4c,0x5,0xe3,0xb3,0x54,0x3c,0x45,0xe4,0x2f,0x8c,0xf8,0xc3,0xcc,0xf4,0x5a, 0xfc,0x94,0xc4,0xeb,0xea,0xa8,0x47,0x8a,0x45,0x8,0x81,0x9b,0x6c,0x2b,0x8d,0x11, 0x59,0x9,0x8,0xe6,0xf5,0x46,0x3d,0x17,0x4,0x29,0x8b,0x28,0x56,0xcd,0x92,0x6d, 0x4c,0xe3,0x35,0x4,0x57,0xba,0x9b,0x1,0xe1,0x57,0x8e,0x36,0x6d,0xc1,0x9b,0x50, 0x7d,0xc,0x38,0x8b,0xa2,0x5b,0x29,0x7d,0x6f,0xd7,0x4f,0x8c,0x45,0x3e,0xe2,0xbd, 0xfd,0xde,0x23,0x9f,0x44,0xad,0x5e,0x82,0xa3,0x38,0x4d,0x10,0x97,0x68,0x97,0x3d, 0x6f,0xfd,0x54,0x36,0x7,0x62,0x0,0x13,0xa3,0x6f,0x44,0xd7,0xdd,0x83,0xee,0xa2, 0x6,0x64,0x6e,0x68,0x13,0x47,0x3f,0x7,0x10,0x5e,0xb1,0x58,0xa9,0xc1,0xa9,0xe0, 0xfb,0x1b,0x47,0x49,0x48,0x83,0xb4,0x70,0x80,0xa,0xdb,0xe5,0xbc,0x25,0x32,0xa3, 0x94,0x44,0x24,0x10,0x94,0xc5,0xe5,0xb7,0x95,0x7e,0xea,0xdf,0x3a,0xa6,0x70,0x1d, 0x45,0x5a,0xfe,0x4e,0x26,0x58,0x96,0xdc,0xb1,0xed,0x39,0x1a,0xf8,0x20,0xd,0xc, 0x32,0xe5,0xfb,0x90,0x4,0xf,0x5d,0x52,0x76,0x19,0x55,0xd1,0x19,0x42,0x1a,0x63, 0x1a,0x20,0xc9,0x9b,0x55,0x74,0xae,0x56,0x8a,0x76,0xe8,0x2c,0x2,0x45,0x47,0xa3, 0xd3,0x4,0x62,0x88,0xd9,0x4a,0xcb,0xf0,0x16,0xce,0x21,0xc9,0x61,0x16,0x7,0xaa, 0x95,0x60,0x18,0xb2,0xbf,0x9,0xcf,0x77,0x6a,0x60,0xd,0xc,0x4f,0xd1,0xe,0xc, 0xf3,0xde,0x1,0x46,0xcc,0x62,0xd2,0x16,0x6b,0xae,0xc5,0x2,0xfb,0xd9,0xcf,0x99, 0xb7,0xcd,0xb6,0xeb,0x29,0xaa,0xe8,0xd0,0x53,0xf4,0x3c,0xb6,0x3f,0x64,0x69,0x78, 0x97,0x9,0xc1,0xe2,0x1f,0xde,0xcc,0x46,0x1b,0x1a,0x17,0x5d,0xaf,0xcc,0x36,0x54, 0xdf,0x94,0x9a,0xee,0x3b,0xda,0x48,0xe9,0x69,0x5c,0x20,0xd6,0x4,0x6c,0x67,0x93, 0xf6,0x60,0xb3,0x61,0x90,0x2d,0x3e,0x25,0x3,0x69,0x6a,0xcc,0xd0,0x1a,0xa7,0x56, 0x6c,0xb0,0xc5,0x69,0xc5,0x61,0xce,0x9c,0x53,0x4c,0x53,0xe4,0x47,0x39,0xab,0x85, 0xa9,0x79,0x8e,0xa2,0xe7,0xcc,0xfc,0x49,0x4d,0x56,0x4,0x7d,0x32,0x6e,0xdc,0xc0, 0xda,0xa,0x6a,0xf7,0xc8,0x17,0x91,0x18,0x3c,0xd5,0x82,0x9a,0x1f,0xc5,0x7b,0xdd, 0x1e,0xef,0xdd,0xe3,0xaa,0x4e,0xdd,0x55,0xab,0xe1,0xc5,0xe,0x9d,0xf3,0x76,0xd5, 0xa,0x9f,0x67,0xee,0x0,0x65,0x70,0x5c,0x1e,0xda,0x6c,0xe3,0x33,0xdb,0x11,0x5c, 0xbf,0xf9,0x1d,0xb6,0xa4,0xf9,0xf3,0x2c,0xc9,0xad,0x5a,0x52,0x9e,0xba,0xd4,0xdb, 0x14,0x3f,0x79,0x53,0x5d,0xfc,0x13,0xd8,0xd7,0xf5,0x4a,0x51,0xc5,0xbe,0x2,0x45, 0xaf,0xdb,0x4b,0x43,0x2c,0xf3,0xd6,0x29,0x66,0x8f,0x66,0xf,0x48,0x33,0x3f,0x90, 0xf2,0xc9,0x94,0x64,0xca,0x38,0xd5,0x3e,0x91,0x4b,0x78,0x53,0xff,0x9a,0xb0,0x94, 0xaa,0xb0,0x5d,0xc6,0xa1,0x2c,0x1,0xb2,0x6b,0xa8,0xa2,0xd0,0x51,0x81,0xe1,0x75, 0x2b,0x91,0xeb,0x86,0x57,0x7f,0xc9,0x31,0x56,0xbe,0x9f,0xef,0x4f,0xb5,0xcf,0xd, 0x75,0xe5,0x69,0x2e,0x45,0xcd,0x3c,0xab,0x9d,0x5d,0x14,0x19,0x71,0x26,0x77,0xc2, 0x8f,0x9,0x8d,0xad,0x9b,0x9a,0x4e,0x71,0x2a,0xa6,0xe6,0x28,0x3a,0xd6,0xd4,0x90, 0xeb,0xa1,0xeb,0x7e,0x53,0xeb,0x10,0xe,0xc2,0x2c,0x99,0xfa,0xbb,0x1d,0xbd,0x43, 0x9b,0x66,0xad,0x61,0xca,0xec,0x4e,0x74,0x6d,0xf9,0x51,0xd1,0x6d,0x29,0xfb,0x81, 0x3e,0x71,0xf6,0xb8,0x48,0xbe,0x6f,0xee,0x43,0x43,0x99,0xf5,0x71,0x78,0xf8,0x4c, 0xe,0xde,0xf4,0x41,0xf2,0x72,0x80,0x54,0x24,0x1a,0x8,0xc9,0xff,0x63,0xf7,0xdd, 0x67,0xc2,0xc9,0xbd,0xe1,0xf4,0x7e,0x60,0xf5,0xd0,0xd7,0x30,0xda,0x3b,0x99,0x3a, 0xd,0x68,0xb0,0x2f,0x1d,0x75,0xdc,0x38,0x8a,0xba,0xc2,0x99,0x6,0x13,0xa7,0xf5, 0xc8,0xef,0x57,0x39,0xfd,0x7e,0x7d,0x4a,0xf5,0xbc,0x97,0x53,0xff,0x22,0xc3,0xf0, 0x17,0x8e,0xc3,0x3a,0x91,0xdb,0x83,0xf2,0x37,0xc6,0x61,0x79,0x68,0x4c,0xb6,0xc2, 0xbe,0x5c,0x43,0x37,0xbf,0x13,0x14,0x27,0x72,0x99,0x1b,0xb9,0x5f,0x91,0xf9,0x25, 0x28,0x26,0x65,0xb5,0xc8,0xc,0x2f,0x62,0x4e,0x33,0x2f,0x98,0x4,0x8e,0xa2,0xea, 0xe0,0x3b,0xc4,0x21,0x14,0xc8,0xff,0xfe,0x53,0xc0,0xbe,0x2,0x4e,0xb3,0x3e,0xd3, 0x51,0x52,0xae,0xe0,0x71,0xe6,0x49,0x5f,0x85,0x51,0x53,0x42,0x27,0xf8,0x62,0x7c, 0xa6,0x79,0x9f,0x2e,0x4f,0x94,0x57,0x5,0x87,0x2a,0xfe,0x56,0x37,0xb9,0xca,0x6, 0x5e,0x8d,0x8f,0x16,0x6f,0x15,0xa9,0xe6,0x35,0xa7,0x58,0x2d,0xb8,0xbb,0xb2,0x30, 0xa1,0xd3,0x48,0x3d,0xc0,0x92,0xd9,0x19,0x8,0x7e,0x97,0x62,0x10,0xae,0x30,0x80, 0x52,0x5f,0x5a,0xfc,0x3,0x77,0x49,0x76,0x4e,0x9c,0xce,0xeb,0x84,0x1d,0x23,0x66, 0xfd,0x1,0xaa,0x74,0x3a,0x55,0x69,0xfe,0xde,0x33,0x1e,0x13,0x9e,0x97,0x1f,0xaa, 0x92,0xd9,0xac,0x58,0x2f,0x9d,0xa5,0xf7,0xb6,0xa2,0x59,0x23,0xa2,0xb5,0xa3,0x39, 0xaf,0x65,0xff,0x41,0xe2,0xec,0xe,0x95,0xb7,0x4,0xa0,0xdf,0x3a,0x7b,0xef,0x92, 0xf4,0xc9,0xd0,0x65,0x91,0xf5,0x25,0x4d,0xcd,0xce,0x38,0x47,0x82,0x2,0xad,0xb3, 0x65,0xe3,0x58,0x93,0xef,0x45,0x5b,0xdf,0x25,0x50,0x6d,0xd6,0x72,0x77,0x68,0x9b, 0x1b,0xf2,0x14,0xed,0x19,0xb6,0xaf,0xea,0x3b,0xf1,0xf4,0x53,0x1b,0xd5,0x5a,0x9, 0xd8,0xd5,0xff,0x3b,0x47,0xd1,0xe,0x47,0xe3,0xe9,0x95,0xe8,0x52,0x5f,0xa1,0x6a, 0xde,0x65,0xc8,0x38,0x4d,0xa4,0x2d,0xb7,0xf9,0x36,0xfb,0xd7,0x91,0x36,0xd3,0xcc, 0xad,0x76,0xb,0x4b,0x3d,0xbd,0xd4,0xc2,0xa0,0xbe,0x72,0x88,0x62,0xdc,0x71,0xcb, 0x3f,0xf1,0x96,0x8a,0x86,0x1f,0xb9,0xa9,0x9e,0xd2,0x47,0x76,0xb,0xaf,0xfb,0xf8, 0xed,0xcd,0x5e,0xed,0x67,0x92,0xf9,0x6d,0x72,0xa9,0x3c,0x39,0x94,0x48,0x7e,0xe4, 0xd2,0x92,0x15,0x28,0xb9,0x11,0x34,0x68,0x15,0x95,0x64,0xc2,0x11,0xc9,0x17,0xed, 0x8b,0x65,0xe,0x82,0x7c,0xb9,0x70,0x26,0x88,0xa,0xe4,0x47,0xa6,0xd4,0xf7,0x4e, 0x85,0xf5,0x3a,0x29,0x31,0xff,0x8f,0x63,0xd5,0xec,0x1c,0x2d,0x56,0x73,0xe8,0x6a, 0xac,0x86,0xc4,0x2c,0x3a,0x6f,0x96,0xb2,0xc1,0x54,0xa9,0x6,0xcc,0xde,0x0,0xb2, 0x95,0x91,0x21,0x6,0x2c,0x13,0xa9,0x9c,0x7,0x88,0x90,0x0,0x23,0x34,0x78,0x33, 0x3b,0xd5,0x19,0x94,0x23,0xfd,0x1f,0xd2,0x0,0xac,0x48, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_CreateSubtractiveBrush.png 0x0,0x0,0x6,0xb3, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x5,0xa8,0x49,0x44,0x41,0x54,0x58,0xc3,0xe5,0x97,0xcf,0x8f,0x1c,0x57, 0x11,0xc7,0x3f,0x55,0xaf,0x7b,0x7a,0x7e,0xec,0xec,0x86,0x38,0x59,0xd9,0x71,0x12, 0x90,0x3,0x9c,0x12,0x38,0x4,0x4,0x52,0x88,0x2c,0x38,0xe4,0x84,0x38,0x20,0xfe, 0x4c,0x24,0x2e,0x39,0x45,0x1c,0xc8,0x21,0x88,0x3,0x87,0x60,0xe,0x86,0xc4,0x26, 0xb6,0x6c,0xd6,0xc6,0xeb,0x78,0x7f,0xcc,0xcc,0xce,0xf4,0xf4,0x7b,0x55,0x1c,0xde, 0x9b,0xd9,0x1d,0x7b,0x2c,0x2d,0x17,0x72,0xc8,0x93,0x5a,0xdd,0xad,0x99,0xae,0xfa, 0xd6,0xb7,0xbe,0xf5,0x7d,0xdd,0xe2,0xee,0xce,0x37,0xb8,0xf4,0x9b,0x4c,0xe,0x50, 0x5d,0xbc,0xf9,0xf8,0xfe,0x27,0xff,0xb7,0xc4,0xbf,0xfe,0xee,0x47,0x2f,0x2,0xb8, 0xcc,0x7a,0x7b,0xf8,0x16,0x1e,0x5,0xc7,0x71,0x2f,0x7,0xe0,0xe6,0x3c,0xb6,0x83, 0x4b,0xc7,0xf9,0xf4,0xee,0x5f,0xb9,0xf9,0xce,0x4f,0x90,0xcb,0x68,0xe0,0xd6,0xe1, 0x6d,0x30,0x85,0x92,0x6c,0xee,0x33,0xda,0xde,0x94,0xd1,0x48,0x99,0xcf,0x13,0xbe, 0xa8,0x69,0x6c,0x44,0x4d,0x8d,0x88,0x20,0x28,0x2a,0xca,0x8f,0xae,0xfd,0x70,0x6b, 0xbc,0x8f,0xef,0x7f,0xc2,0x5e,0xba,0xc2,0x87,0x37,0xde,0x7f,0x39,0x3,0xb7,0xe, 0x6f,0x63,0xe6,0xb8,0xe5,0xfb,0xe4,0x2d,0x67,0xf5,0x9,0x83,0x1d,0xd8,0xe9,0xd7, 0xec,0xd0,0x90,0x92,0x51,0xed,0x28,0x3e,0x82,0x65,0x3c,0x65,0xd2,0x26,0x68,0x2b, 0x7a,0x69,0xc8,0x40,0x86,0xfc,0xfd,0xf1,0x17,0x8,0x2,0xc0,0xbb,0x57,0x7f,0xb0, 0x11,0x5f,0x44,0xb6,0xb7,0xe0,0xd6,0xe1,0x6d,0xba,0x2e,0x61,0xe6,0x98,0x1b,0x6d, 0x35,0xa3,0xde,0x89,0xec,0x8d,0x1b,0x86,0xf4,0x0,0xca,0x6f,0x99,0x38,0x77,0x30, 0x77,0x54,0x84,0x41,0x13,0x48,0xb5,0x61,0x36,0xe1,0x24,0x9d,0x60,0xcb,0x8a,0x26, 0xd,0xe8,0xcb,0x90,0xbf,0x1d,0xfc,0x13,0x73,0xc7,0x2c,0x65,0x0,0x6c,0x1,0xf0, 0xe7,0x7b,0x9f,0x23,0x2,0x5d,0x58,0x20,0xa3,0x96,0xdd,0x71,0xcd,0xb8,0xa,0x40, 0x40,0x51,0x82,0xd7,0x4,0x2a,0x54,0x2,0x4a,0x0,0x84,0x14,0x12,0xc9,0x12,0x91, 0x48,0x67,0x89,0xa5,0x2c,0xe9,0xa4,0xc3,0x3,0x84,0x41,0x22,0xf9,0x94,0x89,0x9d, 0x12,0x3b,0xf0,0x56,0xb1,0x25,0xbc,0x5e,0x5d,0x25,0x92,0x5e,0x4,0x60,0x18,0xe3, 0xeb,0xb,0x7a,0x55,0x85,0xd3,0x7,0xa0,0xa6,0x61,0x87,0x57,0x8,0x4,0x90,0x5c, 0xb9,0x63,0x98,0x38,0x86,0xa1,0xae,0x20,0x82,0x68,0xa0,0xc2,0x69,0xa4,0x4f,0xd2, 0x44,0xb4,0xc8,0xc2,0x16,0xb4,0xb6,0xa0,0xd2,0xc0,0x68,0xd0,0xd0,0xd5,0x91,0xa3, 0xd9,0x14,0x8b,0xc6,0x4a,0x78,0x9b,0x0,0xcc,0x98,0xce,0x97,0x7c,0x6f,0xf0,0x6, 0x75,0x8,0x44,0xe9,0x10,0x24,0x27,0xcf,0xba,0x7,0x71,0xf2,0xd3,0x17,0xb5,0xeb, 0xf9,0x90,0x7c,0x56,0x57,0x6a,0xc9,0x82,0x1c,0x84,0x3e,0x5d,0x34,0x8e,0xa6,0xa7, 0xcc,0xda,0x5,0x86,0x93,0xc4,0x58,0x69,0x7f,0x3,0x80,0xbb,0xd3,0x2e,0x23,0xff, 0x68,0xef,0xb0,0x57,0xbf,0xc2,0xd5,0xc1,0xeb,0x8c,0xab,0x31,0x51,0x96,0x44,0x69, 0x33,0x80,0xd,0x21,0x81,0x94,0x7e,0x4a,0x79,0x1e,0x77,0x44,0x84,0xc6,0xfb,0x44, 0x33,0x9e,0xcc,0x9e,0xf1,0x74,0xf6,0x8c,0x44,0x42,0x54,0x10,0x11,0xa2,0xa5,0x35, 0xfe,0x4d,0x6,0xdc,0x8,0xaa,0x24,0x77,0x4e,0xba,0x63,0x8e,0x96,0x47,0xf4,0x68, 0xb8,0x3e,0xbc,0xc6,0x7e,0xb3,0x4f,0xa5,0x81,0x56,0x67,0xcc,0x65,0x8a,0x22,0x98, 0x7b,0x49,0x9e,0x2b,0xef,0x6b,0x9f,0x81,0x8e,0xe9,0xba,0xc8,0xc3,0xd3,0x47,0x1c, 0x9c,0x3e,0x26,0x12,0x41,0x41,0x14,0x5c,0x1d,0x44,0x89,0x5d,0x2a,0x12,0x7c,0xe, 0x40,0x72,0xa3,0x52,0x1,0xcb,0x63,0x8f,0x41,0x6b,0xb,0xee,0x4e,0xbe,0xe2,0xce, 0xe9,0x57,0xec,0x37,0xfb,0xbc,0x39,0x7c,0x83,0x2b,0xbd,0xeb,0xb4,0x2c,0x58,0xc8, 0x84,0x56,0xe7,0xc,0x7d,0x87,0x81,0x8d,0x69,0xbb,0x25,0xf7,0x8e,0x1e,0x70,0xff, 0xf8,0x21,0x8e,0x21,0xa,0x4,0x40,0xa1,0x48,0x5,0x17,0x23,0x5a,0xa2,0x4c,0xe1, 0x8b,0x2d,0x50,0x91,0xbc,0x43,0x94,0x56,0x2b,0x82,0x65,0x7a,0x78,0xb2,0x78,0xc2, 0x7f,0xe6,0x4f,0xa8,0xa5,0xc7,0x5b,0xa3,0x37,0xb9,0x3a,0xdc,0xa7,0xc7,0x98,0x2e, 0x75,0xdc,0x3a,0xbc,0xcd,0xc1,0xc9,0xe3,0x1c,0x58,0x72,0x52,0xd4,0x57,0x3d,0xca, 0xfa,0x8,0x42,0x4f,0x6b,0xa2,0xc5,0xed,0x63,0xe8,0x80,0xaa,0xe4,0xb,0x5b,0x3d, 0x28,0xb8,0xf8,0xf9,0x19,0x88,0x1e,0x79,0x30,0x7b,0xc8,0xc1,0xec,0x11,0x3f,0xdf, 0xff,0x29,0x7f,0xfc,0xf2,0x4f,0x79,0x12,0xe0,0x3c,0xa1,0x7a,0xfe,0xbf,0x3a,0x84, 0x1c,0xb7,0x5f,0x35,0x4,0xd,0xcc,0xcd,0xb6,0xb7,0x40,0xa4,0x0,0x30,0x2e,0xec, 0x93,0x9a,0xc7,0xe,0x47,0x11,0x6a,0x7a,0xd4,0xd2,0x43,0x5c,0x8a,0x8e,0x1c,0xd1, 0x12,0xae,0x0,0xcd,0x95,0x97,0xe4,0x9a,0x63,0xe,0xea,0x3e,0x41,0x15,0x27,0x1b, 0x1c,0xdb,0x1,0x8,0xaa,0x8a,0xe0,0x88,0xaf,0x68,0x80,0x90,0xdd,0x9d,0x26,0xf4, 0x11,0xf,0xb8,0xf9,0x7a,0x12,0x93,0x5b,0xee,0xed,0xba,0x2,0x3f,0xa7,0xbf,0x5c, 0x37,0x55,0x83,0xaa,0xb2,0x2a,0xfb,0xe2,0xf6,0xb3,0x1,0x20,0x88,0x12,0xc4,0x30, 0x2d,0x23,0x4d,0x56,0xa2,0x50,0xd1,0x68,0x1f,0x77,0xc1,0x2c,0xf7,0xd5,0xb,0xd3, 0xee,0x96,0x55,0x5e,0xe8,0xf7,0x35,0x80,0xc,0xa2,0x17,0x6a,0x6a,0xad,0xa,0x3b, 0xf9,0x7f,0xe6,0xb6,0x5d,0x3,0x41,0x3,0xaa,0x9,0x71,0x30,0x97,0x92,0x3c,0xd0, 0xd3,0x1,0x62,0x4a,0xb4,0xb4,0xd6,0x83,0x96,0x4a,0x12,0x86,0xa8,0x9c,0x9b,0xd4, 0xaa,0xfa,0x90,0x5b,0x53,0x87,0x7a,0x5d,0x79,0x46,0xbc,0xd2,0xdb,0x16,0x23,0xaa, 0x54,0x9,0x41,0x31,0x5b,0xb5,0x40,0xe9,0x49,0x8f,0xca,0x6b,0xa2,0x27,0x54,0x4, 0x17,0xc1,0x8a,0x18,0x11,0xc1,0x3c,0xad,0x19,0x58,0x8b,0xae,0x1c,0x21,0x54,0x4, 0xd,0xb8,0x78,0x31,0x2d,0xc1,0x85,0x8d,0xb5,0x1,0x40,0x45,0xd7,0x63,0xe8,0xe, 0x82,0xd2,0x78,0x83,0x3b,0x4,0xd7,0x95,0xe1,0xe2,0x18,0x58,0xee,0xf7,0x6a,0xa6, 0x5d,0x0,0x15,0x44,0x7c,0x3d,0xf3,0x99,0xfa,0xac,0x2d,0x29,0x3d,0x7a,0x2e,0xff, 0x73,0x0,0x54,0xb3,0x8e,0xca,0xec,0x57,0x52,0x53,0x51,0x91,0x48,0xb8,0x48,0x61, 0x20,0x97,0x6b,0x2,0x8e,0x10,0x3d,0xe6,0x29,0x28,0xf4,0xbb,0x64,0xd7,0x43,0xb3, 0xa0,0x75,0xe5,0xd7,0x9c,0xbf,0x3,0x5c,0xdc,0x47,0x36,0xa7,0xe0,0xe2,0x85,0x67, 0x0,0xd9,0x72,0xb3,0x87,0x7,0x55,0x70,0x3,0x51,0x44,0x1d,0x33,0xe8,0xbc,0xcb, 0x7d,0xbf,0x68,0x40,0xe5,0xba,0x92,0x80,0x48,0x76,0xb5,0xcc,0x42,0x11,0x31,0x6, 0xb2,0xd8,0x62,0x44,0x6,0x5f,0x1f,0x2e,0x19,0xed,0x6,0x9a,0x5e,0xa0,0x22,0x80, 0xe7,0xd6,0x64,0xe,0xad,0xf8,0x83,0x67,0x9d,0x8,0x24,0x4f,0xa8,0xa,0x86,0xac, 0x7d,0xc0,0x5,0x44,0x9c,0xa0,0xa1,0x54,0x9d,0x45,0x3a,0x9d,0x2f,0x68,0x4f,0x8d, 0xb5,0xf,0xbf,0x0,0x80,0x8e,0x30,0xeb,0x33,0x99,0x44,0x8e,0xea,0x5,0x57,0xbe, 0x53,0xb1,0x37,0x18,0xa1,0x8,0x2e,0x86,0x52,0xf8,0x15,0x47,0xc4,0x31,0x1,0x23, 0xad,0xc7,0x6b,0x43,0xed,0x80,0x88,0xe2,0xee,0x4c,0x17,0x73,0xba,0xa9,0xe3,0xad, 0x64,0x71,0xf1,0x12,0x23,0xfa,0xd9,0xdb,0xef,0x3,0xf0,0xe9,0xbf,0x3e,0x43,0x5a, 0xe5,0xf0,0xd1,0x94,0xa7,0x3a,0x63,0xb0,0x5b,0xf3,0xda,0x78,0x4c,0xa5,0x15,0x51, 0x4a,0x42,0x71,0x44,0xf3,0x3b,0xc2,0xba,0xca,0xb5,0xd8,0x1c,0x47,0x98,0xcc,0xe7, 0xf8,0x99,0xe2,0x6d,0x40,0xdc,0x80,0x84,0xb,0xf4,0x77,0x7,0x2c,0x8e,0x8b,0xee, 0xd8,0xb2,0x6e,0xde,0xf8,0x80,0x5f,0x7d,0xff,0x43,0x82,0x8,0x62,0xb0,0x38,0x8e, 0x3c,0x7c,0x70,0xcc,0xbf,0x9f,0x3e,0x63,0xbe,0x5c,0x52,0x49,0x20,0x68,0x20,0x48, 0xc8,0x95,0x6a,0x51,0x3a,0x79,0x1c,0xaa,0x38,0x60,0x78,0xb6,0x47,0x33,0x19,0x51, 0xc5,0x90,0x47,0x50,0xe0,0xb7,0xef,0xfd,0x6,0xbd,0xb6,0xdc,0xc8,0x75,0xa9,0xd7, 0xf2,0x35,0x2b,0x28,0x22,0x8a,0x4,0x68,0x86,0x15,0xe3,0xfe,0x8,0x41,0xb9,0x3b, 0xb9,0x3,0xa6,0xd4,0xd6,0xa3,0x67,0x3d,0x34,0x55,0x44,0x8f,0x24,0x8b,0x74,0x16, 0x59,0xbc,0x7a,0xbc,0xd1,0x9a,0x7a,0xb6,0xcb,0xe2,0x18,0x7e,0xf7,0xe3,0x8f,0x2e, 0xff,0x61,0x72,0xf3,0xc6,0x7,0x0,0x7c,0x76,0xef,0x2f,0x88,0x5,0xe2,0xcc,0x39, 0x3e,0x3b,0x83,0x3a,0x31,0xe8,0xc6,0x34,0x34,0xa8,0x7,0x9c,0x44,0x92,0xc4,0x2f, 0x6f,0xfc,0x62,0xfd,0xec,0x1f,0xe,0x7f,0xff,0xd2,0xb8,0xff,0xfb,0xa7,0x59,0xa9, 0xe2,0x35,0x79,0x35,0xbb,0x45,0xa7,0xc,0x19,0x96,0xbe,0x1b,0x5f,0x73,0xc,0xba, 0x19,0xab,0x66,0xf7,0xe5,0xe1,0xbe,0xf5,0x5f,0xc7,0xff,0x5,0x13,0xe2,0xd1,0x9a, 0xcb,0x2e,0x6e,0xe3,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33, 0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x34,0x37,0x3a,0x30,0x38,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xfc,0xb5,0xd9,0x18,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_View_Front.png 0x0,0x0,0x1,0x34, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x2d, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x31,0x50,0xaa,0x80, 0x5,0xc1,0x64,0x44,0xb1,0xed,0x3f,0x23,0x86,0x2,0x64,0x61,0x1a,0xb9,0x1,0xd9, 0x1d,0x8,0xab,0xe8,0xe0,0x6,0xca,0x15,0x30,0xd2,0x3e,0xb2,0x0,0x72,0xa4,0x8, 0x25,0x99,0x8,0x3,0x8b,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38, 0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61, 0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30, 0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x34,0x3a,0x35,0x31,0x2b,0x31,0x30, 0x3a,0x30,0x30,0x3c,0xe0,0x77,0xd6,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae, 0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_Rotate.png 0x0,0x0,0x4,0x55, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x2,0x40,0x50,0x4c,0x54, 0x45,0xff,0xff,0xff,0x3a,0x70,0x25,0x3e,0x76,0x29,0x3b,0x72,0x27,0x3b,0x72,0x26, 0x3b,0x71,0x26,0x3b,0x70,0x27,0x3a,0x6f,0x26,0x36,0x69,0x23,0x1f,0x6c,0x4,0x2d, 0x70,0x14,0x3e,0x8a,0x21,0x49,0x9c,0x29,0x55,0xa4,0x39,0x57,0xa4,0x39,0x49,0x9b, 0x2b,0x41,0x85,0x29,0x25,0x5b,0x13,0xd,0x48,0x0,0x34,0x65,0x22,0x20,0x72,0x2, 0x2b,0x7b,0xf,0x5b,0xa4,0x40,0xa8,0xd0,0x98,0xbd,0xdc,0xb2,0xb1,0xd5,0xa2,0xa0, 0xcd,0x90,0x87,0xbe,0x73,0x64,0xab,0x4c,0x4b,0x9c,0x2c,0x26,0x5c,0x12,0x1b,0x54, 0x7,0x1d,0x58,0x8,0x32,0x62,0x20,0x1e,0x79,0x0,0x2c,0x7f,0xe,0x9d,0xc9,0x8c, 0xf0,0xf8,0xed,0xd5,0xe7,0xce,0x8b,0xb0,0x7c,0x54,0x87,0x41,0x5b,0x87,0x4a,0x7f, 0xaa,0x70,0x9e,0xca,0x8c,0x75,0xb5,0x5e,0x4a,0x9d,0x2b,0x3f,0x7e,0x29,0x56,0xa6, 0x37,0x2c,0x87,0xa,0x60,0xa1,0x48,0xfe,0xff,0xfd,0x36,0x7f,0x1e,0x1a,0x66,0x0, 0x1a,0x5e,0x1,0x29,0x6b,0x11,0x30,0x72,0x18,0x46,0x77,0x34,0x9c,0xc7,0x8c,0x6e, 0xae,0x57,0x49,0x98,0x2c,0x54,0xa5,0x37,0x50,0x9b,0x34,0x3b,0x93,0x1a,0x63,0xa4, 0x4b,0x55,0x99,0x3a,0x19,0x74,0x0,0x27,0x6e,0xd,0x4b,0x85,0x36,0xaa,0xc8,0x9e, 0xb7,0xd9,0xab,0xa5,0xcc,0x96,0x52,0x9c,0x36,0x4f,0xa0,0x31,0x3b,0x73,0x27,0x39, 0x6e,0x25,0x31,0x6c,0x1a,0x45,0x9b,0x26,0x43,0x97,0x23,0x2b,0x88,0x8,0x7,0x5f, 0x0,0x29,0x78,0xd,0x67,0x99,0x54,0xcb,0xe0,0xc1,0xc3,0xde,0xb9,0x9c,0xc8,0x8c, 0x45,0x9a,0x26,0x3e,0x78,0x29,0x5c,0x8e,0x49,0x48,0x8e,0x2c,0x36,0x6c,0x21,0x30, 0x6c,0x1a,0x9,0x5f,0x0,0x2b,0x74,0x10,0x8b,0xb0,0x7e,0xd9,0xeb,0xd2,0x6f,0xb2, 0x56,0x41,0x7e,0x2a,0x66,0x94,0x55,0x91,0xc7,0x7e,0x48,0x9c,0x29,0x34,0x76,0x1b, 0x22,0x62,0xc,0xd,0x5b,0x0,0x2e,0x7d,0x11,0x64,0x96,0x53,0xb6,0xd3,0xac,0x44, 0x83,0x2c,0x6b,0x99,0x5a,0xca,0xe5,0xc1,0x56,0x9f,0x3b,0x4b,0x9b,0x2e,0x51,0x9f, 0x35,0x33,0x75,0x1b,0x29,0x6d,0x10,0xc,0x67,0x0,0x18,0x61,0x0,0x3c,0x88,0x20, 0x22,0x5c,0xc,0x44,0x8b,0x2a,0x47,0x83,0x32,0x70,0x9d,0x5f,0xd0,0xe7,0xc6,0xa7, 0xcc,0x99,0x41,0x92,0x23,0x4f,0x9d,0x32,0x4d,0x97,0x32,0x3c,0x75,0x28,0x26,0x6a, 0xd,0x1a,0x62,0x0,0x33,0x72,0x1c,0x41,0x7d,0x2a,0x37,0x78,0x1e,0x45,0x85,0x2c, 0x73,0xa2,0x62,0xdb,0xed,0xd4,0xc7,0xdf,0xbe,0x7e,0xb6,0x68,0x43,0x95,0x25,0x3c, 0x7b,0x25,0x46,0x85,0x2f,0x3c,0x95,0x1b,0x25,0x69,0xb,0x33,0x74,0x1b,0x51,0x9f, 0x33,0x52,0xa1,0x35,0x3c,0x85,0x20,0x1d,0x68,0x2,0x77,0xa6,0x66,0xe7,0xf5,0xe1, 0x82,0xb0,0x71,0xd2,0xe7,0xca,0x90,0xc2,0x7e,0x43,0x96,0x23,0x41,0x8d,0x26,0x3e, 0x81,0x26,0x40,0x81,0x27,0x42,0x89,0x27,0x4a,0x99,0x2c,0x61,0xa7,0x47,0x5c,0xa4, 0x42,0x1a,0x6d,0x0,0x58,0x91,0x42,0x2b,0x77,0x10,0x46,0x87,0x2e,0xc9,0xe0,0xc1, 0xb1,0xd4,0xa3,0x7e,0xb6,0x69,0x5b,0xa4,0x42,0x5c,0xa4,0x41,0x70,0xaf,0x59,0x7a, 0xb4,0x65,0x75,0xb1,0x5f,0x4f,0x95,0x34,0x23,0x74,0x6,0x48,0x8c,0x2f,0x19,0x6e, 0x0,0x3d,0x85,0x24,0x8c,0xb8,0x7b,0xb6,0xd7,0xaa,0xbc,0xda,0xb1,0xae,0xd1,0xa0, 0x9f,0xc9,0x8f,0x85,0xb9,0x71,0x4d,0x8f,0x33,0x24,0x78,0x5,0x4c,0x92,0x32,0x4e, 0x93,0x33,0x58,0x9a,0x3f,0x5a,0x9b,0x42,0x54,0x98,0x3b,0x4c,0x93,0x32,0x4b,0x91, 0x30,0xad,0x38,0x2a,0xee,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x0,0x88,0x5, 0x1d,0x48,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0, 0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x1,0x3,0x49,0x44,0x41,0x54,0x18, 0xd3,0x63,0x60,0x0,0x2,0x46,0x26,0x66,0x16,0x56,0x36,0x76,0xe,0x6,0x28,0xe0, 0xe4,0xe2,0xe6,0xe1,0xe5,0xe3,0x17,0x10,0x14,0x62,0x60,0x10,0x6,0xf2,0x45,0x44, 0xc5,0xc4,0x25,0x24,0xa5,0xa4,0x65,0x64,0xe5,0xe4,0x15,0x14,0x19,0x18,0x94,0x94, 0x55,0x54,0xd5,0xd4,0x35,0x34,0xb5,0xb4,0x75,0x74,0xf5,0xf4,0x59,0x18,0x18,0xc, 0xc,0x19,0x8c,0x8c,0x4d,0x4c,0xcd,0xcc,0x2d,0x2c,0xad,0xac,0x6d,0x58,0x18,0x6c, 0x19,0xec,0xec,0x1d,0x1c,0x19,0x18,0x9c,0x9c,0x5d,0x5c,0xdd,0xdc,0x3d,0x3c,0x19, 0xbc,0xbc,0x7d,0x7c,0xfd,0x80,0x26,0xf9,0x7,0x4,0x6,0x5,0x87,0x84,0x86,0x31, 0x84,0x47,0x44,0x46,0x41,0x2c,0x8b,0x8e,0x89,0x8d,0x8b,0x4f,0x60,0x48,0x4c,0x4a, 0x4e,0x49,0x4d,0x83,0x8,0xa5,0x67,0x64,0x66,0x31,0x64,0xe7,0xe4,0xe6,0xe5,0x17, 0x14,0x16,0x1,0xf9,0xc5,0x25,0xa5,0x65,0xe5,0xc,0x15,0x95,0x55,0xd5,0x35,0xb5, 0x75,0xf5,0xc,0xc,0xd,0x8d,0x4d,0xcd,0xc,0x2d,0xc,0xad,0x6d,0xed,0x1d,0x9d, 0x5d,0xdd,0x3c,0x3d,0xbd,0x7d,0xfd,0x13,0x26,0x4e,0x62,0x60,0x98,0x3c,0x65,0xea, 0xb4,0xe9,0x33,0x66,0xce,0x9a,0x3d,0x67,0xee,0xbc,0xf9,0x25,0xb,0x18,0x18,0x16, 0x2e,0x5a,0xb0,0x78,0xc9,0xd2,0x65,0xcb,0x57,0xac,0x5c,0xb5,0x7a,0xcd,0x5a,0xa0, 0x49,0xeb,0x18,0x18,0xd6,0x6f,0xd8,0xb8,0x69,0xf3,0x96,0xad,0xdb,0xb6,0xef,0x80, 0x79,0xd7,0x76,0xe7,0xae,0xdd,0x7b,0xf6,0xee,0xdb,0xf,0x62,0x3,0x0,0x93,0xf1, 0x49,0x6,0xe3,0x47,0x5a,0x3b,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61, 0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30, 0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30, 0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d, 0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x32,0x36,0x3a,0x33,0x31,0x2b,0x31, 0x30,0x3a,0x30,0x30,0xe0,0xd5,0x3a,0x55,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/DoubleLeftArrowHS.png 0x0,0x0,0x2,0x42, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0xbd,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xa6,0xc0,0x98,0xa7,0xc1,0x99,0x5a,0x6c,0x56,0xae,0xc8,0xa0, 0xd0,0xf0,0xbe,0x4b,0x5b,0x48,0xd7,0xf4,0xc7,0xbf,0xeb,0xa8,0x47,0x57,0x45,0x90, 0xab,0x83,0x80,0x96,0x74,0x93,0xa9,0x88,0x8d,0xa2,0x83,0x89,0x9c,0x7f,0x84,0x97, 0x7b,0xb4,0xce,0xa6,0xab,0xe0,0x91,0xa6,0xc9,0x94,0x60,0x7d,0x55,0xc0,0xdf,0xb0, 0xb9,0xe0,0xa6,0xae,0xd5,0x9d,0xa2,0xca,0x93,0x97,0xc0,0x89,0x3c,0x49,0x3a,0x9f, 0xb8,0x92,0xd5,0xf1,0xc6,0xc5,0xee,0xaf,0xad,0xe1,0x92,0xa3,0xd8,0x89,0x6d,0x86, 0x62,0x9f,0xc1,0x8f,0xc4,0xed,0xae,0x95,0xca,0x7e,0x86,0xbb,0x70,0x76,0xac,0x63, 0x5b,0x8b,0x4b,0x35,0x40,0x33,0x45,0x55,0x44,0x56,0x68,0x52,0x81,0xa6,0x6f,0xa5, 0xda,0x8b,0x8d,0xbd,0x76,0x84,0xb2,0x6f,0x45,0x53,0x42,0x86,0xb4,0x70,0x79,0xa8, 0x66,0x6b,0x9b,0x5a,0x5d,0x8e,0x4e,0x50,0x81,0x43,0x2c,0x36,0x2b,0x49,0x5a,0x47, 0x50,0x61,0x4d,0x75,0x9a,0x65,0x7b,0xab,0x68,0x3b,0x48,0x39,0x23,0x2b,0x22,0x1c, 0x22,0x1b,0x64,0x75,0x5f,0x5c,0x80,0x4f,0x32,0x3d,0x31,0xff,0xff,0xff,0x12,0x76, 0x42,0xa1,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0, 0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x3e,0x49,0x64,0x0,0xe3,0x0,0x0,0x0,0x7b, 0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x20,0xa,0x30,0x32,0xc1,0x8,0x28,0x9f, 0x91,0x19,0x4a,0x40,0xf9,0x2c,0xac,0x6c,0x10,0x2,0xc6,0x67,0xe7,0xe0,0xe4,0xe2, 0x6,0x12,0x3c,0xbc,0x7c,0xfc,0x40,0xbe,0x0,0x3b,0x87,0xa0,0x90,0xb0,0x8,0x87, 0xa0,0xa8,0x98,0xb8,0x84,0x24,0x3,0x83,0x94,0xb4,0x8c,0xac,0x9c,0xbc,0x82,0xa2, 0xac,0x9c,0x92,0xb2,0x8a,0xaa,0x1a,0x3,0x83,0xba,0x86,0xa6,0x96,0xb6,0x8e,0xae, 0xa6,0x96,0x9e,0xbe,0x81,0xa1,0x91,0x31,0xd0,0xc,0x13,0x53,0x33,0x73,0x49,0xb, 0x10,0xa1,0x66,0x6c,0x69,0x5,0x32,0xd5,0xc4,0xda,0x46,0xd,0x42,0xc0,0x80,0xb1, 0x9a,0x2d,0x94,0x80,0x8b,0x18,0xc3,0x8,0xb2,0x0,0x0,0xc1,0xcc,0xc,0x66,0xc1, 0xa1,0x98,0x25,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a, 0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31, 0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30, 0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d, 0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60, 0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsCenteredVerticalHS.png 0x0,0x0,0x1,0x9f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x48,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x6f,0x86,0xb0,0x5e,0x76,0xa4,0x44,0x61,0x94,0x69,0x82,0xad, 0xf5,0xfa,0xfb,0x5f,0x79,0xa5,0x64,0x7d,0xa9,0xf1,0xf6,0xfb,0xc8,0xd3,0xdf,0xec, 0xf3,0xfa,0xc1,0xd0,0xe0,0x56,0x70,0x9e,0xe1,0xec,0xf9,0xb6,0xc8,0xe3,0x4c,0x68, 0x99,0xd2,0xe2,0xf9,0xa5,0xbf,0xe6,0x35,0x49,0x63,0x49,0x64,0x96,0xc7,0xda,0xf9, 0x9e,0xbb,0xe8,0x95,0xb4,0xe4,0xff,0xff,0xff,0xd8,0xf3,0x9e,0x13,0x0,0x0,0x0, 0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b, 0x47,0x44,0x17,0xb,0xd6,0x98,0x8f,0x0,0x0,0x0,0x4d,0x49,0x44,0x41,0x54,0x18, 0xd3,0x9d,0xcd,0x49,0x12,0x80,0x20,0x10,0x3,0xc0,0x40,0x64,0x11,0xc1,0x65,0x14, 0xff,0xff,0x54,0xcb,0xd3,0x38,0x1e,0xc9,0xb1,0x93,0xaa,0x0,0xe3,0x71,0xde,0xd3, 0xc0,0x14,0x82,0x82,0x8b,0x44,0xca,0x33,0x3f,0x2d,0x11,0xcb,0xa2,0x90,0x32,0x51, 0xdb,0xaa,0x10,0xcb,0xf,0x6a,0x23,0xb6,0xfd,0x50,0x10,0x11,0x9c,0x57,0xb7,0xb7, 0xec,0xb7,0x5,0x79,0x67,0x63,0x79,0x0,0xf4,0x8,0x2,0x1f,0xef,0xba,0x52,0xbb, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5, 0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54, 0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c, 0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsLeftHS.png 0x0,0x0,0x2,0x8, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x9f,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x4,0x2,0x4,0xcb,0xcb,0xcb,0xc4,0xc4,0xc4,0xb8,0xb8,0xb8, 0xb0,0xb0,0xb0,0xa6,0xa6,0xa6,0x95,0x95,0x95,0xee,0xee,0xee,0xeb,0xeb,0xeb,0xe2, 0xe2,0xe2,0xd6,0xd6,0xd6,0x4e,0x4e,0x4e,0x7d,0x7d,0x7d,0x6c,0x6c,0x6c,0x58,0x58, 0x58,0x4d,0x4d,0x4d,0xaa,0xb5,0xc5,0xa7,0xb2,0xc2,0xa2,0xae,0xbf,0x9d,0xa9,0xba, 0x97,0xa4,0xb6,0x91,0x9e,0xb1,0x8b,0x98,0xab,0x83,0x91,0xa5,0x80,0x8e,0xa3,0xa9, 0xb4,0xc4,0xff,0xff,0xff,0xfd,0xfe,0xff,0xf8,0xfb,0xff,0xf2,0xf7,0xff,0xed,0xf4, 0xff,0xe6,0xf2,0xff,0xd7,0xe6,0xf7,0x63,0x73,0x89,0xa7,0xb2,0xc3,0xfb,0xfd,0xff, 0xe0,0xe6,0xed,0xd3,0xdd,0xe5,0xcc,0xd5,0xe2,0xc2,0xd1,0xe3,0xbc,0xcd,0xe4,0xb6, 0xca,0xe5,0x3b,0x4f,0x68,0x8f,0x9d,0xaf,0x59,0x6a,0x81,0x46,0x59,0x71,0x43,0x56, 0x6f,0x40,0x53,0x6d,0x40,0x54,0x6e,0x46,0x5a,0x72,0x3f,0x52,0x6c,0x35,0x49,0x63, 0x4b,0x65,0xbb,0xdd,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8, 0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x1b,0x2,0x60,0xd4,0xa4,0x0,0x0, 0x0,0x5f,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x20,0x2,0x30,0x32,0x32,0x30, 0x31,0xb3,0xb0,0xb2,0xb1,0x23,0x9,0x30,0x73,0x70,0x72,0x71,0xf3,0x20,0x9,0xb0, 0xf1,0xf2,0xf1,0xf3,0x8,0x20,0x9,0x60,0x98,0x21,0x28,0x24,0x2c,0x22,0x2a,0x26, 0x2e,0x21,0x9,0x13,0x90,0x92,0x96,0x91,0x95,0x93,0x57,0x50,0x54,0x82,0x9,0x28, 0xab,0xa8,0xaa,0xa9,0x6b,0x68,0x6a,0x69,0xc3,0x4,0x74,0x74,0xf5,0xf4,0xd,0xc, 0x8d,0x8c,0x4d,0x70,0x1a,0xca,0xc0,0x88,0x26,0xc0,0x8,0x1,0xb8,0x54,0x10,0x0, 0x0,0xff,0x29,0x5,0x98,0x2c,0x70,0xf7,0x53,0x0,0x0,0x0,0x25,0x74,0x45,0x58, 0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31, 0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31, 0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30, 0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32, 0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49, 0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_Scale.png 0x0,0x0,0x2,0x5f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0xae,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x32,0x79,0xb6,0x36,0x80,0xc2,0x39,0x83,0xc3,0x3f,0x87,0xc1, 0x1c,0x5f,0x9e,0x40,0x87,0xc1,0x39,0x84,0xc4,0x37,0x81,0xc2,0x24,0x7b,0xd1,0x30, 0x87,0xd6,0x30,0x74,0xaf,0x1e,0x64,0xa3,0x31,0x74,0xaf,0x32,0x8a,0xd8,0x26,0x7e, 0xd2,0x37,0x82,0xc2,0x30,0x8a,0xd8,0x4b,0x9e,0xdd,0x2c,0x6d,0xa7,0x4c,0xa0,0xdd, 0x32,0x8e,0xd9,0x33,0x8b,0xd8,0x3a,0x84,0xc4,0x30,0x74,0xb0,0x4b,0x9f,0xdd,0x3c, 0x98,0xde,0x5c,0xa8,0xdc,0x19,0x56,0x94,0x5d,0xa8,0xdc,0x40,0x9a,0xdf,0x4d,0xa1, 0xde,0x31,0x75,0xb0,0x40,0x88,0xc1,0x2d,0x6d,0xa8,0x5c,0xa7,0xdc,0x2e,0x6e,0xa8, 0x5e,0xa9,0xdc,0x2e,0x6e,0xa7,0x5f,0xaa,0xdc,0x2d,0x6d,0xa7,0x36,0x7d,0xb8,0x2f, 0x72,0xad,0x60,0xaa,0xdd,0x44,0x9d,0xe0,0x4f,0xa2,0xde,0x31,0x75,0xaf,0x3a,0x85, 0xc4,0x34,0x8b,0xd8,0x2d,0x6e,0xa8,0x50,0xa3,0xde,0x34,0x91,0xdb,0x35,0x8e,0xda, 0x3b,0x85,0xc4,0x35,0x8e,0xd9,0x29,0x81,0xd4,0x38,0x82,0xc3,0xff,0xff,0xff,0xe5, 0xd9,0xd2,0xe5,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66, 0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x39,0xd7,0x0,0x95,0x40,0x0,0x0,0x0, 0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b, 0xe,0x1b,0x0,0x0,0x0,0x92,0x49,0x44,0x41,0x54,0x18,0xd3,0x8d,0x8f,0xc9,0x12, 0x82,0x30,0x10,0x44,0x13,0x20,0x8a,0xd8,0xa,0xca,0xe6,0x12,0x20,0x44,0xc0,0x7d, 0x17,0xe5,0xff,0xbf,0x4c,0x9,0x39,0x7a,0xa0,0xf,0x73,0x78,0x55,0xf3,0xaa,0x9b, 0x90,0x1e,0xa1,0x86,0x69,0x31,0x42,0xd8,0x60,0x68,0x53,0x5,0x8c,0x91,0x33,0x6, 0x21,0x98,0x4c,0x5d,0x4f,0x1,0xd3,0x99,0xcd,0x7d,0xc0,0xf,0xc2,0x28,0x56,0xc0, 0x5a,0x2c,0x57,0x6b,0xce,0x93,0x34,0x13,0xb9,0x2,0xc,0x72,0x53,0x0,0x45,0x29, 0xc1,0xb4,0x16,0x1c,0xfa,0xfc,0x7,0x3f,0x5f,0x52,0x1,0xd5,0x76,0xa7,0x5f,0xf6, 0x87,0x20,0x2d,0x39,0x3f,0x9e,0xce,0x97,0x4e,0x7a,0xbd,0x85,0x99,0x4,0xee,0x8f, 0xe7,0xab,0x56,0xc0,0x76,0x23,0xd1,0x3a,0xc4,0xfb,0xd3,0x74,0xd5,0xbd,0x38,0x6f, 0xab,0xe7,0x75,0x43,0xfb,0x4c,0xfd,0x2,0x11,0x9b,0xb,0x15,0x3d,0x4d,0xd2,0x9c, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff, 0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54, 0x32,0x32,0x3a,0x32,0x38,0x3a,0x31,0x37,0x2b,0x31,0x30,0x3a,0x30,0x30,0xdf,0xe9, 0x38,0xa1,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_View_Top.png 0x0,0x0,0x1,0x2f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x28, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x31,0x50,0xaa,0x80, 0x5,0xc6,0x60,0xc4,0xb0,0xeb,0x3f,0x23,0x16,0x71,0x8,0x17,0x22,0x45,0x2d,0x37, 0x8c,0x10,0x5,0x8c,0x14,0xc7,0x26,0x0,0x24,0x57,0x7,0x1d,0xa0,0x11,0x24,0x71, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff, 0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54, 0x32,0x33,0x3a,0x31,0x35,0x3a,0x31,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0x92,0xcf, 0x2c,0x9c,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderMode_Wireframe.png 0x0,0x0,0x1,0x4f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x48, 0x49,0x44,0x41,0x54,0x28,0xcf,0xc5,0x91,0x41,0xe,0x0,0x30,0x4,0x4,0xad,0xf8, 0xff,0x97,0xf5,0x80,0x46,0xa2,0x38,0xd6,0x6d,0x33,0x7b,0x30,0x40,0x69,0x1e,0xc9, 0x1,0xa5,0xad,0x90,0x8c,0x15,0xb5,0xce,0x3d,0xb6,0xcc,0x33,0xf6,0x42,0x8f,0xef, 0x92,0x68,0x65,0x24,0xb6,0xed,0x6c,0x98,0x96,0xf9,0x5b,0x30,0x59,0x9e,0xb1,0x1b, 0xbd,0xae,0x10,0xe2,0xd8,0xde,0x7d,0x0,0x8a,0x9d,0x1d,0x23,0x7,0xcf,0xfa,0x4, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff, 0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54, 0x32,0x33,0x3a,0x31,0x34,0x3a,0x34,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0x35,0xed, 0x49,0xc6,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_CreateVolumeBrush.png 0x0,0x0,0x8,0x6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x6,0xfb,0x49,0x44,0x41,0x54,0x58,0xc3,0xc5,0x97,0x5d,0x88,0x5d,0x57, 0x15,0xc7,0x7f,0x6b,0xed,0xbd,0xcf,0xb9,0x1f,0xf3,0x99,0x49,0x27,0xc9,0xb4,0x4d, 0x4d,0x49,0xd3,0xc6,0x62,0x51,0xa9,0x58,0x91,0x4a,0x5b,0xdf,0xa,0xa5,0x5a,0xfa, 0x20,0x68,0x7d,0xf1,0x41,0x41,0x41,0xd0,0x6,0x84,0xfa,0x20,0x82,0x7d,0xd0,0xd2, 0x7,0xb5,0x58,0x5f,0x14,0x2a,0x88,0x10,0xb1,0xc4,0x17,0x8b,0xa0,0x4d,0xab,0x82, 0x2d,0x8a,0x6d,0x69,0xad,0xd1,0x9a,0xc6,0xa4,0x99,0x7c,0xcc,0x64,0x92,0xcc,0xcc, 0x9d,0xb9,0xf7,0x9c,0xb3,0xd7,0xf2,0xe1,0x4e,0x62,0x27,0x73,0x95,0xf6,0xc5,0x2c, 0xb8,0x70,0xcf,0xe5,0x9e,0xbd,0x7e,0xac,0xf5,0x5f,0xff,0xbd,0xb7,0xb8,0xbb,0x73, 0x15,0x43,0xaf,0x66,0x72,0x80,0xf8,0xf6,0x87,0xa7,0x1e,0x9e,0xfb,0xbf,0x25,0xfe, 0xec,0x63,0xf3,0x5b,0x1,0xde,0x49,0xec,0xfe,0xf0,0xa7,0xe9,0x61,0x78,0x6e,0x30, 0xab,0xc9,0x6e,0x98,0x65,0x1a,0xcf,0xc,0x5e,0x79,0xe6,0x1d,0xaf,0xf3,0xc4,0xe3, 0x77,0xf1,0xc5,0xaf,0x1c,0xde,0xc,0x70,0x89,0xea,0xca,0x38,0x7c,0xf0,0x0,0x3, 0x11,0xdc,0x8d,0x35,0xc,0x3b,0x77,0x9c,0x6d,0x4b,0x8b,0xdc,0xd8,0x94,0x9c,0x64, 0x9d,0xd3,0xed,0x88,0x4c,0x5f,0x43,0xf1,0x81,0xfb,0x50,0x4d,0x88,0x6,0x24,0x95, 0xdc,0xf7,0xc0,0xb7,0x47,0xae,0xf7,0xd4,0xc3,0x73,0x84,0x50,0xfc,0xef,0xa,0x1c, 0x3e,0x78,0x80,0x81,0xd5,0x54,0xd6,0x0,0x90,0xfb,0x3d,0xa6,0x16,0xde,0x62,0x6f, 0x15,0xd8,0x19,0xc6,0x41,0xb6,0xd3,0xf,0x35,0x37,0x79,0xc1,0x8d,0x95,0xb1,0x72, 0x72,0x81,0x5,0x3f,0xce,0xd9,0xb2,0x60,0x30,0xb9,0x8d,0x34,0xb3,0x9b,0x67,0x9e, 0xfe,0x1a,0xa8,0x62,0xc0,0xbd,0xf7,0x3f,0xba,0x69,0xfd,0x10,0xc2,0x68,0x80,0xc3, 0x7,0xf,0x70,0x71,0x70,0x81,0xaa,0xae,0x31,0xab,0xe8,0x2e,0x9d,0x65,0xef,0x0, 0x6e,0x8e,0xdb,0x11,0x66,0x20,0x41,0xbd,0x51,0x72,0x7,0xcc,0x9d,0xc6,0x33,0x49, 0x23,0xb3,0xd6,0x61,0x6a,0xd0,0x50,0x9f,0x59,0x60,0xf5,0xd4,0x49,0x96,0xda,0x89, 0xc1,0xc4,0xc,0x32,0x3d,0xc7,0xa1,0x9f,0x7f,0x95,0x9c,0x2b,0xea,0xaa,0xbf,0x91, 0x29,0x6e,0x5,0xf8,0xd1,0x93,0x9f,0x24,0x20,0x74,0x56,0x97,0xd9,0xd3,0x6f,0xd8, 0xaf,0xd3,0x74,0x75,0x3b,0x24,0xc1,0x53,0x81,0x75,0x26,0xa1,0x3d,0x86,0xb4,0xba, 0xc4,0xb2,0x8d,0x88,0x12,0x72,0x1f,0xed,0xf7,0x90,0x41,0xf,0xaa,0x1e,0xd6,0xbf, 0x40,0xee,0x5d,0xa4,0x53,0x41,0x67,0xe0,0xf8,0xc2,0x22,0xfd,0xd3,0xa7,0x58,0xe, 0xce,0x42,0xd3,0xb0,0x54,0x57,0x74,0x6f,0xf9,0xd8,0xf0,0xff,0x5b,0x2a,0xd0,0x54, 0x3c,0xb8,0x5c,0xd0,0x8d,0x3b,0x20,0xe6,0xe1,0x6f,0xd3,0xb3,0x70,0xe3,0xfb,0xa1, 0xec,0x22,0xb9,0xc1,0x73,0x83,0x5a,0x83,0xe5,0x1a,0x6d,0x2a,0xdc,0x13,0xa1,0x35, 0x46,0x2a,0xdb,0x88,0x4d,0x13,0x64,0x8e,0x54,0xf7,0xa9,0xfb,0xab,0xf4,0xcf,0xcf, 0x33,0x58,0x3a,0x4d,0x21,0x2d,0xe6,0x3a,0xdb,0x19,0xaf,0xd6,0x8,0xcb,0x7f,0x63, 0x25,0x57,0xb8,0xdb,0x56,0x80,0xa6,0x19,0x70,0xa2,0x5a,0xe1,0xba,0x8f,0xdc,0x4f, 0x27,0xb4,0xd1,0xd5,0xf3,0x10,0x13,0x14,0x6d,0xc4,0x33,0x6e,0x86,0xe0,0x38,0x80, 0x3b,0x38,0x8,0x20,0xee,0x48,0xce,0x28,0xc3,0x89,0x10,0x89,0x68,0x31,0x41,0x18, 0x17,0x5a,0x63,0x73,0xac,0xe6,0x1,0x6f,0xbc,0xf5,0xa,0x67,0xcf,0x1d,0x45,0xa5, 0x41,0xea,0x75,0x72,0xce,0x5b,0x1,0xb2,0x35,0x9c,0xcf,0x3d,0x16,0x9f,0xfd,0x1e, 0x93,0xbb,0x6f,0x63,0x6e,0xdf,0xdd,0x8c,0xef,0xba,0x85,0x70,0xf1,0x1c,0xe1,0xe2, 0x22,0x92,0x6b,0x5c,0x4,0xdc,0x87,0xe,0x26,0x82,0x3b,0xa8,0x28,0xaa,0x1,0x33, 0xc7,0xea,0x3c,0x9c,0x82,0xc9,0x5d,0x34,0x63,0x33,0xbc,0x71,0xe4,0x79,0x8e,0x1d, 0xf9,0x3d,0x34,0xeb,0x14,0x51,0x9,0x29,0xd2,0xaf,0xd6,0xb8,0x64,0xc0,0x9b,0x1, 0xea,0x8a,0x42,0x22,0x35,0x99,0x8b,0xff,0x7a,0x89,0xc5,0x37,0xff,0x8c,0x8e,0xcf, 0xb0,0xfb,0x83,0x9f,0x60,0x76,0xff,0xc7,0x29,0x62,0x8b,0x78,0xea,0x28,0x3a,0xff, 0x4f,0x50,0xc5,0x11,0x54,0x15,0xcb,0x86,0xe6,0x4c,0x1c,0xdf,0x41,0xdc,0x7d,0x33, 0xcb,0xfd,0x1e,0xaf,0xbd,0xf0,0xb,0x5e,0xfb,0xd3,0x21,0xa4,0x5e,0x25,0x21,0x14, 0x49,0x49,0x38,0xc1,0x8d,0x41,0x7f,0x95,0x61,0xed,0x46,0xb4,0x20,0x69,0xb,0x5c, 0x10,0x4,0x14,0xaa,0xe5,0x45,0x8e,0x3c,0xfb,0x24,0xaf,0xfe,0xf6,0x9,0xae,0xd9, 0x7f,0xf,0x7b,0x6e,0x7f,0x90,0xe9,0x3b,0x1f,0x80,0xa5,0x79,0xf4,0xc4,0xdf,0x49, 0xe7,0x4e,0xa2,0xbb,0xf6,0x52,0x5f,0xbb,0x8f,0xd5,0xd5,0xf3,0xbc,0x78,0xf8,0x29, 0x5e,0xfa,0xdd,0x4f,0xd0,0xa6,0x21,0xa9,0xd0,0xa,0x42,0xa,0x90,0xdc,0x48,0x26, 0x68,0x86,0xc1,0x60,0x15,0xd5,0x11,0x63,0x68,0xb9,0x26,0x49,0x17,0x61,0xb8,0x49, 0x38,0x8e,0xa9,0xe3,0xee,0xb8,0x39,0x67,0x5f,0xff,0xd,0x27,0xff,0xfa,0x6b,0x62, 0x7b,0x8a,0x3d,0x77,0x7c,0x8a,0x1b,0xde,0x77,0x2f,0x72,0xfd,0x4d,0xf4,0x56,0x2f, 0xf2,0xdc,0x4f,0xbf,0xce,0x2b,0x2f,0x1c,0x22,0x88,0x90,0x54,0x8,0x2a,0x14,0x2, 0x49,0x9c,0x4,0xa4,0xec,0x94,0x29,0xd2,0xea,0x4c,0x31,0xe8,0xaf,0xa0,0x61,0xc4, 0x18,0x3a,0x4e,0xd2,0x88,0xb8,0x80,0x9,0x6,0xb8,0x38,0x8e,0x93,0xc5,0xc9,0xee, 0x4,0x9c,0x5c,0xaf,0xf2,0xe6,0x8b,0x3f,0xe3,0xd8,0x5f,0xe,0x71,0xcf,0x17,0xe, 0xf2,0xdd,0x2f,0xdf,0x8e,0x28,0xe8,0x46,0x62,0x5,0xa2,0x40,0xc4,0x89,0x6,0xa5, 0x3a,0x65,0x2c,0x19,0x9b,0x98,0x25,0xb5,0xda,0xd4,0xd5,0x3c,0xd2,0x8c,0xa8,0x80, 0xaa,0x92,0x8,0x43,0x65,0x2b,0x60,0xe,0x1b,0x0,0xa6,0x8e,0x8b,0x50,0x76,0xb6, 0xa3,0xdd,0x49,0x4c,0x2,0x2e,0x6,0x6e,0xc4,0xa8,0x20,0x10,0xdc,0x89,0x40,0x11, 0x20,0xb9,0x53,0x8,0xc3,0x4f,0x28,0x99,0x98,0xde,0x49,0x19,0xb,0x3c,0x67,0x9a, 0xa6,0x42,0x64,0x84,0x6,0x82,0x46,0xa,0x22,0xea,0x82,0xd8,0x50,0x3,0xe,0x98, 0x39,0x1e,0xb,0xda,0x53,0x3b,0xc8,0x31,0x51,0x5b,0x3,0x9e,0xc9,0xe,0xb9,0x1e, 0x10,0x55,0xc1,0x7d,0x58,0xf6,0xe0,0x14,0x40,0xa1,0x90,0x70,0x4a,0x55,0xc6,0xba, 0xdb,0x28,0x42,0x42,0xcd,0x40,0xc0,0xac,0x1e,0x2d,0xc2,0x18,0x4a,0x92,0x45,0x14, 0x41,0x83,0x22,0x19,0x5c,0x40,0xca,0x82,0x72,0x7a,0x17,0x39,0x6,0x6,0x75,0x1f, 0x13,0xc5,0xdd,0x70,0x64,0xa8,0x1b,0x55,0x54,0x9c,0x20,0x4e,0x32,0xa7,0x50,0x28, 0x70,0xa,0x77,0x3a,0xad,0x71,0x5a,0xed,0x31,0x82,0x19,0xe1,0x92,0xd6,0xac,0x19, 0xd,0x90,0x8a,0x2e,0x45,0x15,0xc9,0x2e,0xa8,0x1b,0x28,0x88,0x6,0x8a,0xed,0xd7, 0xd2,0xc4,0x82,0x41,0xb3,0x4e,0xd6,0x84,0x19,0x78,0x0,0xcf,0x19,0x6b,0x6,0x14, 0x41,0x11,0x37,0xa2,0x40,0x11,0x84,0xc2,0x8d,0x52,0xa0,0xc,0x81,0x76,0x67,0x92, 0xb0,0xe1,0x1b,0x41,0x19,0xea,0xea,0x6d,0x87,0xb0,0x4d,0x0,0x45,0xd1,0xa1,0xac, 0x23,0x8d,0xb,0x41,0x87,0x56,0x19,0xc6,0xb7,0x61,0x9d,0x69,0xd6,0xab,0x75,0xa2, 0x44,0xb2,0x6c,0xe8,0xc1,0xc0,0x83,0x90,0xab,0xf5,0xd,0x0,0x88,0x96,0x29,0x80, 0xe4,0x50,0x88,0xd3,0x6e,0xb5,0x49,0xa9,0x24,0xe8,0x25,0xe3,0x52,0x54,0xe5,0xb2, 0xe4,0xb7,0x56,0x20,0xb5,0x48,0x22,0x88,0xa,0x62,0x19,0x4f,0x9,0x9b,0xdc,0x41, 0x2d,0x90,0x34,0x61,0x38,0x26,0x43,0x6d,0xba,0xa,0x78,0xa6,0xa9,0x7a,0x24,0x51, 0x4,0x28,0xe2,0xa5,0x16,0x8,0xd1,0x9d,0xa2,0xe8,0x12,0x83,0xa2,0xf8,0xb0,0xad, 0x2a,0xb8,0xb0,0x29,0xae,0x0,0x28,0x50,0xc9,0x4,0xc0,0xd5,0xb1,0xf6,0x14,0x52, 0x74,0xb1,0xa6,0x4f,0xd4,0x48,0xc6,0x30,0x9c,0xec,0x82,0x7b,0xc6,0x3d,0xd3,0xf4, 0x57,0x48,0x41,0x51,0x77,0xa,0x84,0x28,0x42,0xcc,0x90,0x44,0x48,0x65,0x8b,0xb0, 0x1,0x27,0x1b,0xae,0x79,0xe5,0x9,0x78,0xb3,0xf,0xb8,0x2,0x19,0x15,0x41,0x5c, 0x8,0x63,0x53,0xa0,0x1,0xd5,0x48,0x8,0x46,0x12,0x30,0x15,0xcc,0x15,0x2e,0x1, 0xac,0xad,0x90,0x54,0x9,0x38,0xd1,0x9c,0x84,0x91,0x82,0xc,0x47,0x32,0xb5,0xd1, 0x90,0x10,0x1c,0x15,0x41,0x43,0xa2,0xb1,0x6,0x32,0xc4,0xd3,0x23,0x0,0x1a,0xcf, 0x3c,0x97,0xcf,0x71,0x2b,0x2d,0xb6,0x85,0xe,0x5e,0x74,0x30,0x11,0x34,0x44,0x82, 0xa,0x96,0x95,0x68,0x82,0x11,0xb0,0xa6,0x26,0x86,0x88,0x55,0x6b,0x14,0x31,0x22, 0xd9,0x9,0xea,0x44,0x74,0xa8,0xf8,0xc,0xb1,0x6c,0xa3,0xc,0xfb,0x6e,0x39,0x33, 0xbf,0x7c,0x82,0xd7,0x97,0x16,0x8,0x95,0x8c,0xd6,0x80,0x5f,0x68,0x38,0x4a,0x8b, 0x23,0xd5,0xa,0xe3,0xd5,0x3c,0x1f,0x9a,0x1c,0xe7,0xda,0x99,0x3d,0x4,0x51,0x2c, 0x57,0x58,0x70,0xa2,0x8,0x46,0xc6,0x34,0xe0,0x18,0xde,0x54,0x43,0x1f,0x30,0x25, 0x8a,0x21,0x79,0xb8,0x8f,0x8,0x42,0x8c,0x9,0x6b,0x1a,0xde,0x5a,0x3a,0xce,0x1b, 0xcb,0x17,0x38,0xdb,0x37,0xbc,0x71,0x24,0xff,0x27,0xa7,0x8c,0xba,0x98,0xfc,0xf0, 0x91,0xbb,0xa9,0xf2,0x3a,0x39,0xf7,0x29,0xa2,0xf0,0xde,0xd9,0xeb,0xd9,0xbf,0xeb, 0x36,0x52,0xd9,0xa5,0x6a,0xfa,0x54,0x18,0x35,0x4e,0xed,0x99,0x30,0x39,0xcb,0xab, 0xbf,0x7c,0xc,0xac,0x46,0x73,0x4d,0xb4,0x86,0xd0,0xd4,0x88,0x18,0xeb,0x63,0xd3, 0x9c,0xa8,0x1b,0x16,0xd6,0x32,0xcd,0xa0,0xc6,0xaa,0x1a,0x77,0xe3,0xd6,0xbd,0xb3, 0xbc,0xd4,0x3b,0xcd,0xe3,0x3f,0xb0,0xd1,0x87,0xd2,0xcf,0x7f,0xeb,0x59,0x0,0xbe, 0x7f,0xe0,0xe,0xaa,0x2a,0xf3,0xf2,0x99,0x79,0x5e,0x5e,0x38,0xc5,0xd,0x53,0x53, 0xec,0x9b,0xdd,0xc7,0xd4,0xd4,0x75,0xb8,0x18,0xe6,0xd,0x38,0xc4,0x10,0x30,0xc, 0xf1,0x4c,0xd6,0x48,0xaf,0x3b,0xc1,0x72,0x9c,0xe0,0xbc,0x29,0xf5,0xda,0x2a,0xc1, 0xd6,0x70,0x8c,0x47,0x9f,0xee,0xf1,0xfc,0x43,0xc2,0xb1,0xff,0x26,0xc2,0x2b,0xe3, 0x4b,0xdf,0xf9,0xe3,0xe5,0xef,0x4f,0x3e,0x72,0x17,0x67,0xfa,0xc6,0xc2,0xfc,0x3f, 0x68,0x9f,0x3d,0xca,0x7b,0xa6,0x67,0xd9,0xb9,0xf3,0x66,0xdc,0x1a,0x54,0x94,0xba, 0x28,0x18,0xb4,0xae,0xa1,0x29,0xb7,0xb1,0xae,0x5,0xcd,0xfa,0x1a,0x69,0xbd,0x87, 0xc5,0xc4,0x47,0x7,0x8b,0x90,0xe0,0xf9,0x87,0x64,0x4b,0xe,0x79,0xb7,0x77,0xc3, 0x1f,0x7f,0xf3,0x3e,0xa4,0xc,0x68,0x8,0x84,0x22,0x30,0xe1,0xce,0xf2,0xf9,0x53, 0x48,0x67,0x86,0x9c,0x4a,0xbc,0xdf,0x50,0xf,0xd6,0xf9,0xdc,0x37,0x7e,0x75,0xf9, 0x9d,0xe7,0x3e,0x33,0x4c,0xbc,0xb1,0xff,0x70,0x6c,0xc7,0xae,0xcb,0x2d,0xd8,0x4, 0xf0,0x6e,0xae,0x66,0x61,0xc7,0x9d,0x20,0x82,0x88,0xe,0xcd,0x25,0xf,0xcf,0x83, 0xbe,0xf0,0x87,0x77,0xf4,0xfe,0x48,0x80,0xab,0x11,0x57,0xfd,0x76,0xfc,0x6f,0x7, 0x94,0x74,0x7e,0x3a,0x88,0x8e,0x64,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d, 0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31, 0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74, 0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32, 0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x34,0x37,0x3a,0x33,0x35,0x2b, 0x31,0x30,0x3a,0x30,0x30,0x13,0xed,0xbf,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Edit_UndoHS.png 0x0,0x0,0x2,0xad, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x14,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x93,0xb4,0xf6,0x93,0xb3,0xf5,0x9e,0xbb,0xf5,0xa7,0xc1,0xf5, 0xa9,0xc1,0xf5,0xaa,0xc2,0xf5,0x8e,0xb0,0xf5,0x8b,0xae,0xf5,0x81,0xa8,0xf4,0x7f, 0xa4,0xf4,0x9d,0xb9,0xf5,0x8b,0xaa,0xea,0xa6,0xc8,0xf5,0x8f,0xb1,0xf6,0x65,0x92, 0xee,0x44,0x70,0xc8,0x3b,0x65,0xb7,0x37,0x60,0xb4,0x47,0x78,0xdd,0x99,0xb7,0xf5, 0x81,0xa4,0xe9,0x9e,0xc0,0xf5,0x7f,0xa8,0xf5,0x90,0xb2,0xf6,0x5e,0x8c,0xe7,0x45, 0x70,0xc7,0x3e,0x68,0xbb,0x35,0x5d,0xac,0x44,0x6f,0xb5,0x39,0x5f,0xa7,0x56,0x88, 0xee,0xa5,0xc0,0xf5,0x73,0x99,0xe7,0x6a,0x9a,0xf3,0x71,0x9c,0xf4,0x59,0x8c,0xf1, 0x3a,0x63,0xb4,0x38,0x61,0xb0,0x35,0x5d,0xa9,0x50,0x7d,0xb7,0x31,0x58,0xa3,0x45, 0x77,0xdb,0x80,0xa5,0xf4,0x62,0x8e,0xe6,0x4b,0x82,0xec,0x5b,0x8d,0xf3,0x76,0x9c, 0xec,0x28,0x4b,0x92,0x34,0x5c,0xa8,0x20,0x40,0x7e,0x3e,0x6a,0xc2,0x45,0x76,0xdc, 0x80,0xa9,0xf4,0x52,0x83,0xe5,0x36,0x73,0xdf,0x49,0x82,0xea,0x61,0x8c,0xe2,0x7e, 0xa3,0xed,0x3e,0x69,0xc2,0x4a,0x7e,0xe6,0x83,0xa9,0xf4,0x42,0x78,0xe3,0x40,0x72, 0xd6,0x3a,0x69,0xc7,0x34,0x5f,0xb6,0x31,0x5a,0xad,0x28,0x4c,0x95,0x36,0x5e,0xaf, 0x3d,0x69,0xc1,0x50,0x84,0xeb,0x70,0x97,0xe3,0x27,0x4a,0x92,0x45,0x76,0xdb,0x66, 0x93,0xef,0x8d,0xb0,0xf5,0x38,0x64,0xbe,0x54,0x88,0xf0,0x56,0x7e,0xcf,0x5e,0x8e, 0xef,0x40,0x6f,0xd0,0x4f,0x84,0xf0,0x4e,0x79,0xd4,0x2a,0x50,0x9b,0x48,0x7b,0xe3, 0x4f,0x84,0xf2,0x48,0x74,0xd1,0x33,0x5a,0xaa,0x5a,0x8d,0xf3,0x43,0x74,0xd6,0x35, 0x5c,0xae,0xff,0xff,0xff,0xa5,0xcf,0xdf,0x6e,0x0,0x0,0x0,0x1,0x74,0x52,0x4e, 0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x5b,0x74, 0xbc,0x95,0x34,0x0,0x0,0x0,0x8f,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xc0, 0x1,0x18,0x99,0x98,0x59,0x58,0xd9,0x10,0x7c,0x76,0x76,0xe,0x4e,0x2e,0x6e,0x36, 0x88,0x8,0xf,0x2f,0x3,0x7,0x1f,0xbf,0x80,0xa0,0x90,0xb0,0x8,0x58,0x80,0x4d, 0x54,0x4c,0x5c,0x42,0x52,0x4a,0x5a,0x46,0x56,0x4e,0x5e,0x1,0xac,0x42,0x51,0x49, 0x59,0x45,0x55,0x4d,0x9d,0x41,0x43,0x53,0x4b,0x1b,0x2c,0xa0,0xa3,0xab,0xa7,0x6f, 0x60,0xc8,0xc0,0x60,0x64,0x6c,0x62,0xa,0x16,0x30,0x33,0xb7,0x50,0xb2,0xb4,0x2, 0xa,0x58,0xdb,0xd8,0x82,0x5,0xec,0xec,0x1d,0x1c,0x9d,0x9c,0x19,0x18,0x5c,0x5c, 0xdd,0xdc,0xe1,0xd6,0x82,0x8c,0xf7,0xf0,0xf4,0xf2,0x46,0x71,0x9b,0x8f,0xaf,0x1f, 0x32,0xd7,0x3f,0x20,0x30,0x28,0x18,0x59,0x20,0x24,0x34,0x2c,0x1c,0x45,0x43,0x44, 0x64,0x14,0x3,0x71,0x0,0x0,0x56,0x68,0x10,0x81,0xff,0x15,0xd1,0x2e,0x0,0x0, 0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74, 0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a, 0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69, 0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31, 0x3a,0x30,0x32,0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b, 0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderMode_Lit.png 0x0,0x0,0x1,0x7a, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x4,0x3,0x0,0x0,0x0,0xed,0xdd,0xe2,0x52, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x12,0x50,0x4c,0x54, 0x45,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xf2,0x0,0x0,0xff,0x21,0xff,0x0,0x8, 0xff,0xff,0xff,0xed,0x65,0xfe,0xad,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0, 0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x0,0x88,0x5,0x1d, 0x48,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe, 0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x49,0x49,0x44,0x41,0x54,0x8,0xd7, 0x63,0x60,0x40,0x2,0x82,0x40,0x20,0x0,0xa4,0x19,0x95,0x14,0x94,0x14,0x41,0xc, 0x21,0x26,0x26,0x26,0x61,0x1,0xa8,0x80,0xb1,0x0,0x54,0x80,0x59,0x0,0xa2,0x54, 0xd8,0x0,0xc8,0x10,0x61,0x61,0x61,0x1,0x8b,0x8,0xb8,0x38,0xb8,0x8,0x18,0x23, 0x8b,0x88,0x38,0xb8,0x38,0x60,0x51,0x63,0xc8,0x0,0x15,0x11,0x80,0x5a,0x29,0x88, 0xe4,0x4,0x0,0x9,0xa,0x7,0x9d,0xa,0xd5,0x35,0x17,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32, 0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a, 0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25, 0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0, 0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x34, 0x3a,0x33,0x35,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe,0xc0,0x5a,0x42,0x0,0x0,0x0, 0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/openHS.png 0x0,0x0,0x3,0x86, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0xb0,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x85,0x94,0xa4,0x81,0x91,0xa6,0x78,0x89,0xa1,0x87,0x95,0xaa, 0x7b,0x8c,0xa0,0x60,0x74,0x95,0x53,0x69,0x8d,0x6d,0x79,0x9e,0x82,0x91,0xa6,0x75, 0x84,0x9f,0x5f,0x74,0x94,0xac,0xa4,0x8f,0xb6,0xa9,0x88,0x6a,0x7b,0x98,0x54,0x6b, 0x8d,0x4f,0x69,0x90,0xda,0xd2,0xa0,0xf7,0xf0,0xab,0xf9,0xee,0xa6,0xfb,0xeb,0x9f, 0xaa,0xa1,0x8d,0xb0,0xa4,0x84,0x53,0x6a,0x8e,0x4f,0x68,0x91,0x4c,0x67,0x93,0xab, 0xa2,0x8e,0xf6,0xee,0xa7,0xfd,0xe8,0x98,0xfb,0xd4,0x71,0xa7,0x9e,0x89,0xa3,0x99, 0x86,0x9f,0x94,0x82,0x9a,0x90,0x7e,0x97,0x8c,0x7a,0x93,0x88,0x77,0xa8,0xa0,0x8b, 0xf6,0xea,0xa0,0xfe,0xe8,0x98,0xff,0xda,0x7a,0xff,0xd4,0x67,0xa5,0x9c,0x88,0xf3, 0xe6,0x9a,0xb9,0xac,0x8b,0xb7,0xaa,0x8a,0xb3,0xa6,0x88,0xaf,0xa3,0x86,0xaa,0x9f, 0x83,0xa6,0x9a,0x81,0xa1,0x95,0x7f,0x9d,0x91,0x7c,0x99,0x8e,0x7a,0x95,0x8b,0x79, 0xa3,0x9a,0x86,0xf2,0xe1,0x92,0xde,0xc4,0x80,0xb0,0xa7,0x8e,0xfd,0xde,0x81,0xff, 0xe0,0x84,0xff,0xdf,0x81,0xff,0xdd,0x7b,0xff,0xd8,0x74,0xff,0xd6,0x6b,0xd1,0xa9, 0x56,0x6f,0x62,0x4e,0x9f,0x95,0x83,0xf1,0xdc,0x89,0xff,0xe2,0x8c,0xb1,0xa8,0x8d, 0xc7,0xba,0x8c,0xff,0xd0,0x5f,0xff,0xcd,0x54,0xfc,0xc5,0x4b,0xf7,0xbb,0x41,0xdb, 0xa2,0x2e,0x6c,0x5e,0x47,0x9c,0x91,0x80,0xef,0xd7,0x81,0xe0,0xc5,0x7d,0xb0,0xa6, 0x8c,0xfe,0xdd,0x80,0xff,0xd3,0x68,0xff,0xd1,0x62,0xff,0xcd,0x58,0xfc,0xc7,0x4e, 0xf7,0xbe,0x46,0xf2,0xb6,0x3b,0xec,0xac,0x31,0x81,0x69,0x25,0x59,0x44,0x14,0x98, 0x8e,0x7d,0xec,0xd2,0x79,0xad,0xa4,0x8b,0xce,0xc2,0x89,0xff,0xd8,0x71,0xff,0xd3, 0x65,0xff,0xce,0x5c,0xfe,0xc9,0x51,0xfa,0xc1,0x49,0xf5,0xb9,0x3f,0xee,0xb0,0x34, 0xe9,0xa8,0x29,0xcd,0x85,0x10,0x5b,0x4b,0x22,0x34,0x27,0xe,0x95,0x8a,0x7a,0xd3, 0xbe,0x7e,0xae,0xa4,0x8a,0xff,0xdc,0x7e,0xff,0xcf,0x5f,0xff,0xcb,0x55,0xfa,0xc4, 0x4c,0xf5,0xbc,0x41,0xf0,0xb3,0x37,0xeb,0xaa,0x2e,0xe5,0xa0,0x24,0xd4,0x8c,0x13, 0x80,0x67,0x23,0x30,0x2a,0x1b,0x92,0x87,0x77,0xab,0xa1,0x89,0xd4,0xb2,0x6a,0xcd, 0x8f,0x0,0xc7,0x8c,0x4,0xbe,0x88,0x8,0xb4,0x82,0xf,0xa9,0x7c,0x15,0x9f,0x77, 0x1b,0x96,0x72,0x1f,0x5b,0x4a,0x21,0x37,0x30,0x1e,0x8f,0x84,0x75,0x8f,0x80,0x66, 0x87,0x79,0x60,0x7b,0x6e,0x57,0x61,0x56,0x44,0x52,0x48,0x39,0x43,0x3a,0x2e,0x35, 0x2e,0x25,0x29,0x22,0x1b,0x1e,0x19,0x14,0x16,0x12,0xe,0x18,0x13,0xe,0xff,0xff, 0xff,0x76,0x4f,0x93,0x58,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6, 0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x8f,0xf5,0x2,0x83,0xf9,0x0, 0x0,0x0,0xcc,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xc0,0x9,0x18,0x99,0x98, 0x59,0x58,0x91,0x5,0xd8,0xd8,0x19,0x38,0x38,0xb9,0xb8,0x19,0x78,0xc0,0x80,0x17, 0x22,0xc8,0xc7,0x2f,0xc0,0xc0,0x23,0x28,0x24,0x24,0x2c,0x22,0x2a,0x6,0x16,0x10, 0x97,0x90,0x64,0x90,0x92,0x6,0xf2,0x65,0x64,0xe5,0xe4,0x15,0x14,0x95,0x94,0x41, 0x82,0x2a,0xaa,0xc2,0x22,0x6a,0xea,0x1a,0x60,0x0,0x16,0xd0,0xd4,0x12,0x51,0xd3, 0xd6,0xd6,0xd1,0xd5,0xd3,0x37,0x30,0x34,0x32,0x36,0x51,0x66,0x30,0x35,0x93,0x31, 0xb7,0xb0,0xb4,0x2,0x2,0x6b,0x1b,0x5b,0x3b,0x7b,0x7,0x6,0x47,0x27,0x67,0x17, 0x57,0x5b,0xa0,0x7a,0x37,0x77,0xf,0x4f,0x2f,0x6f,0x7,0x6,0x1f,0x5f,0x3f,0xff, 0x80,0x40,0x8d,0xa0,0xe0,0x90,0xd0,0xb0,0xf0,0x88,0x48,0x6,0x86,0xa8,0xe8,0x98, 0xd8,0xb8,0xf8,0x84,0xc4,0xa4,0xe4,0x94,0xd4,0xb4,0xf4,0xc,0x6,0x86,0xcc,0xac, 0xec,0x9c,0xdc,0xbc,0xfc,0x82,0xc2,0xa2,0xe2,0x92,0xd2,0x32,0xa0,0x2d,0xe5,0x15, 0x95,0x55,0x55,0x55,0xd5,0x35,0xb5,0x75,0xf5,0xd,0x8d,0x4d,0x40,0x81,0xe6,0x96, 0xd6,0x36,0x87,0xf6,0x8e,0xce,0xae,0xee,0x9e,0xde,0x3e,0x6c,0x9e,0x6,0x0,0x25, 0x4,0x2c,0xf2,0x90,0x83,0x34,0xb1,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d, 0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31, 0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74, 0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32, 0x2d,0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31,0x3a,0x30,0x32,0x3a,0x35,0x36,0x2b, 0x31,0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/PlayHS.png 0x0,0x0,0x1,0x8a, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x3f,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x76,0xbf,0x6b,0x60,0x98,0x58,0x39,0x76,0x2f,0x5a,0x94,0x52, 0xb0,0xda,0xa3,0x53,0x90,0x4b,0x4c,0x8a,0x43,0x5a,0xa2,0x50,0x41,0x83,0x38,0x68, 0xb0,0x5d,0x3d,0x83,0x2f,0x2c,0x73,0x20,0x18,0x66,0xb,0x37,0x7c,0x2e,0xf,0x60, 0x4,0x2e,0x75,0x23,0x24,0x6f,0x1a,0x1b,0x68,0x11,0x14,0x63,0x9,0xff,0xff,0xff, 0xb3,0xbe,0xd8,0xe0,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8, 0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x14,0x92,0xdf,0xc9,0x35,0x0,0x0, 0x0,0x41,0x49,0x44,0x41,0x54,0x18,0xd3,0x7d,0xc8,0x41,0x12,0x40,0x30,0x10,0x5, 0xd1,0x3f,0x9,0x31,0x24,0x82,0xb8,0xff,0x5d,0xd9,0x91,0x2e,0xa5,0x77,0xaf,0xa5, 0xcf,0x8c,0x23,0xf0,0x84,0x88,0x33,0x8c,0x38,0xc9,0x70,0x26,0x33,0xef,0xce,0xbc, 0x78,0x2e,0x6b,0x79,0x46,0xbd,0xbd,0xbd,0xac,0x1d,0xd6,0x1,0xab,0xc1,0x3a,0x61, 0xd1,0xbf,0x5d,0xc2,0xda,0x1,0xa2,0xb9,0xd6,0x22,0x74,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32, 0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a, 0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25, 0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0, 0x32,0x30,0x31,0x32,0x2d,0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31,0x3a,0x30,0x32, 0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b,0x0,0x0,0x0, 0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_OtherOptions.png 0x0,0x0,0x1,0x43, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x3c, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x31,0xc,0xbc,0x2, 0x16,0x6,0x6,0x6,0x6,0x46,0x1c,0x2e,0xfd,0xcf,0x8,0x35,0xe1,0x3f,0x23,0x2e, 0x69,0xb8,0x15,0x98,0x4a,0x60,0x22,0x4c,0xe8,0x2,0xe8,0x3c,0x26,0x6c,0x82,0xc8, 0x8a,0x99,0x30,0xf5,0xa1,0x9a,0xc5,0x38,0x14,0x82,0x1a,0x0,0x39,0x65,0xe,0x1f, 0x85,0x15,0x81,0x80,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33, 0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x33,0x3a,0x33,0x35,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xec,0x1c,0x41,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/skip_backward.png 0x0,0x0,0x1,0x8c, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x9,0x70,0x48,0x59,0x73,0x0,0x0,0x4,0x9d,0x0,0x0,0x4,0x9d,0x1,0x7c,0x34, 0x6b,0xa1,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xd8,0x3,0xe,0xd,0x2f, 0x2f,0x24,0xd3,0xaf,0x66,0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0, 0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x1,0xc,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0xf8,0xff,0xff,0x3f,0x3,0x25,0x98,0x61,0x70,0x18,0x0,0x4,0xcc,0x2a, 0x2a,0x2a,0x7c,0x64,0x1b,0x20,0x27,0x27,0xf7,0x5d,0x41,0x41,0xe1,0x95,0x8c,0x8c, 0x8c,0x34,0xb2,0xa4,0xa2,0xa2,0xa2,0x3a,0x50,0xee,0x19,0x90,0x96,0x87,0x89,0xc9, 0xca,0xca,0x4a,0x1,0xd5,0x6e,0x93,0x97,0x97,0x3f,0x2,0x37,0x0,0xc8,0x79,0xc, 0xc4,0x6f,0x81,0x12,0xa,0x20,0xbe,0x92,0x92,0x12,0x3f,0x50,0xe3,0x42,0x20,0x7e, 0xa,0x35,0x5c,0x5c,0x4a,0x4a,0x8a,0xb,0x48,0x4f,0x4,0xaa,0x7b,0x0,0xc4,0xff, 0x81,0xf8,0x12,0x86,0x1,0x40,0xd3,0x95,0x81,0x8a,0xca,0x80,0xec,0xbb,0x40,0xfc, 0xf,0xaa,0xf0,0x1b,0x10,0xcb,0x2,0xc5,0x6f,0x1,0xe9,0xdf,0x50,0x31,0x4c,0x3, 0x80,0xa,0x3e,0x1,0xf1,0x4d,0x20,0xfb,0x3b,0x92,0xa2,0xff,0x40,0x17,0xfc,0x5, 0xd2,0x5f,0x91,0xc5,0x70,0xb9,0xe0,0x2f,0xd0,0x80,0x5f,0x58,0x14,0xfe,0xc3,0x22, 0x86,0xdd,0xb,0x40,0xdc,0xb,0xc4,0x77,0xd0,0x14,0xfe,0x0,0xe2,0xab,0x40,0xfc, 0x91,0xa0,0x1,0xa0,0x40,0x4,0xc6,0x84,0x10,0x90,0xbd,0x14,0x88,0x9f,0xc2,0xc2, 0x0,0x28,0xcc,0xd,0xf4,0x4a,0x1c,0x90,0xbe,0x1,0xe4,0xff,0xc2,0x65,0xc0,0x7b, 0x58,0x2c,0x40,0xa3,0x56,0xb,0xc8,0x3d,0x4,0x35,0x40,0x1c,0x24,0x6,0x4c,0x2b, 0xec,0x40,0xf1,0x4e,0xa8,0xe1,0x28,0x6,0xdc,0x3,0x4a,0x9c,0x1,0x29,0x40,0x4f, 0x28,0x40,0xb9,0xa,0x71,0x71,0x71,0x56,0x64,0x31,0x65,0x65,0x65,0x31,0xa0,0x78, 0xe3,0x20,0xca,0xb,0x94,0x60,0x0,0xae,0x39,0x28,0xce,0x1d,0x86,0x3e,0x7c,0x0, 0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Directory_16x16.png 0x0,0x0,0xc,0xcf, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13, 0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0xa,0x4d,0x69,0x43,0x43,0x50,0x50,0x68,0x6f, 0x74,0x6f,0x73,0x68,0x6f,0x70,0x20,0x49,0x43,0x43,0x20,0x70,0x72,0x6f,0x66,0x69, 0x6c,0x65,0x0,0x0,0x78,0xda,0x9d,0x53,0x77,0x58,0x93,0xf7,0x16,0x3e,0xdf,0xf7, 0x65,0xf,0x56,0x42,0xd8,0xf0,0xb1,0x97,0x6c,0x81,0x0,0x22,0x23,0xac,0x8,0xc8, 0x10,0x59,0xa2,0x10,0x92,0x0,0x61,0x84,0x10,0x12,0x40,0xc5,0x85,0x88,0xa,0x56, 0x14,0x15,0x11,0x9c,0x48,0x55,0xc4,0x82,0xd5,0xa,0x48,0x9d,0x88,0xe2,0xa0,0x28, 0xb8,0x67,0x41,0x8a,0x88,0x5a,0x8b,0x55,0x5c,0x38,0xee,0x1f,0xdc,0xa7,0xb5,0x7d, 0x7a,0xef,0xed,0xed,0xfb,0xd7,0xfb,0xbc,0xe7,0x9c,0xe7,0xfc,0xce,0x79,0xcf,0xf, 0x80,0x11,0x12,0x26,0x91,0xe6,0xa2,0x6a,0x0,0x39,0x52,0x85,0x3c,0x3a,0xd8,0x1f, 0x8f,0x4f,0x48,0xc4,0xc9,0xbd,0x80,0x2,0x15,0x48,0xe0,0x4,0x20,0x10,0xe6,0xcb, 0xc2,0x67,0x5,0xc5,0x0,0x0,0xf0,0x3,0x79,0x78,0x7e,0x74,0xb0,0x3f,0xfc,0x1, 0xaf,0x6f,0x0,0x2,0x0,0x70,0xd5,0x2e,0x24,0x12,0xc7,0xe1,0xff,0x83,0xba,0x50, 0x26,0x57,0x0,0x20,0x91,0x0,0xe0,0x22,0x12,0xe7,0xb,0x1,0x90,0x52,0x0,0xc8, 0x2e,0x54,0xc8,0x14,0x0,0xc8,0x18,0x0,0xb0,0x53,0xb3,0x64,0xa,0x0,0x94,0x0, 0x0,0x6c,0x79,0x7c,0x42,0x22,0x0,0xaa,0xd,0x0,0xec,0xf4,0x49,0x3e,0x5,0x0, 0xd8,0xa9,0x93,0xdc,0x17,0x0,0xd8,0xa2,0x1c,0xa9,0x8,0x0,0x8d,0x1,0x0,0x99, 0x28,0x47,0x24,0x2,0x40,0xbb,0x0,0x60,0x55,0x81,0x52,0x2c,0x2,0xc0,0xc2,0x0, 0xa0,0xac,0x40,0x22,0x2e,0x4,0xc0,0xae,0x1,0x80,0x59,0xb6,0x32,0x47,0x2,0x80, 0xbd,0x5,0x0,0x76,0x8e,0x58,0x90,0xf,0x40,0x60,0x0,0x80,0x99,0x42,0x2c,0xcc, 0x0,0x20,0x38,0x2,0x0,0x43,0x1e,0x13,0xcd,0x3,0x20,0x4c,0x3,0xa0,0x30,0xd2, 0xbf,0xe0,0xa9,0x5f,0x70,0x85,0xb8,0x48,0x1,0x0,0xc0,0xcb,0x95,0xcd,0x97,0x4b, 0xd2,0x33,0x14,0xb8,0x95,0xd0,0x1a,0x77,0xf2,0xf0,0xe0,0xe2,0x21,0xe2,0xc2,0x6c, 0xb1,0x42,0x61,0x17,0x29,0x10,0x66,0x9,0xe4,0x22,0x9c,0x97,0x9b,0x23,0x13,0x48, 0xe7,0x3,0x4c,0xce,0xc,0x0,0x0,0x1a,0xf9,0xd1,0xc1,0xfe,0x38,0x3f,0x90,0xe7, 0xe6,0xe4,0xe1,0xe6,0x66,0xe7,0x6c,0xef,0xf4,0xc5,0xa2,0xfe,0x6b,0xf0,0x6f,0x22, 0x3e,0x21,0xf1,0xdf,0xfe,0xbc,0x8c,0x2,0x4,0x0,0x10,0x4e,0xcf,0xef,0xda,0x5f, 0xe5,0xe5,0xd6,0x3,0x70,0xc7,0x1,0xb0,0x75,0xbf,0x6b,0xa9,0x5b,0x0,0xda,0x56, 0x0,0x68,0xdf,0xf9,0x5d,0x33,0xdb,0x9,0xa0,0x5a,0xa,0xd0,0x7a,0xf9,0x8b,0x79, 0x38,0xfc,0x40,0x1e,0x9e,0xa1,0x50,0xc8,0x3c,0x1d,0x1c,0xa,0xb,0xb,0xed,0x25, 0x62,0xa1,0xbd,0x30,0xe3,0x8b,0x3e,0xff,0x33,0xe1,0x6f,0xe0,0x8b,0x7e,0xf6,0xfc, 0x40,0x1e,0xfe,0xdb,0x7a,0xf0,0x0,0x71,0x9a,0x40,0x99,0xad,0xc0,0xa3,0x83,0xfd, 0x71,0x61,0x6e,0x76,0xae,0x52,0x8e,0xe7,0xcb,0x4,0x42,0x31,0x6e,0xf7,0xe7,0x23, 0xfe,0xc7,0x85,0x7f,0xfd,0x8e,0x29,0xd1,0xe2,0x34,0xb1,0x5c,0x2c,0x15,0x8a,0xf1, 0x58,0x89,0xb8,0x50,0x22,0x4d,0xc7,0x79,0xb9,0x52,0x91,0x44,0x21,0xc9,0x95,0xe2, 0x12,0xe9,0x7f,0x32,0xf1,0x1f,0x96,0xfd,0x9,0x93,0x77,0xd,0x0,0xac,0x86,0x4f, 0xc0,0x4e,0xb6,0x7,0xb5,0xcb,0x6c,0xc0,0x7e,0xee,0x1,0x2,0x8b,0xe,0x58,0xd2, 0x76,0x0,0x40,0x7e,0xf3,0x2d,0x8c,0x1a,0xb,0x91,0x0,0x10,0x67,0x34,0x32,0x79, 0xf7,0x0,0x0,0x93,0xbf,0xf9,0x8f,0x40,0x2b,0x1,0x0,0xcd,0x97,0xa4,0xe3,0x0, 0x0,0xbc,0xe8,0x18,0x5c,0xa8,0x94,0x17,0x4c,0xc6,0x8,0x0,0x0,0x44,0xa0,0x81, 0x2a,0xb0,0x41,0x7,0xc,0xc1,0x14,0xac,0xc0,0xe,0x9c,0xc1,0x1d,0xbc,0xc0,0x17, 0x2,0x61,0x6,0x44,0x40,0xc,0x24,0xc0,0x3c,0x10,0x42,0x6,0xe4,0x80,0x1c,0xa, 0xa1,0x18,0x96,0x41,0x19,0x54,0xc0,0x3a,0xd8,0x4,0xb5,0xb0,0x3,0x1a,0xa0,0x11, 0x9a,0xe1,0x10,0xb4,0xc1,0x31,0x38,0xd,0xe7,0xe0,0x12,0x5c,0x81,0xeb,0x70,0x17, 0x6,0x60,0x18,0x9e,0xc2,0x18,0xbc,0x86,0x9,0x4,0x41,0xc8,0x8,0x13,0x61,0x21, 0x3a,0x88,0x11,0x62,0x8e,0xd8,0x22,0xce,0x8,0x17,0x99,0x8e,0x4,0x22,0x61,0x48, 0x34,0x92,0x80,0xa4,0x20,0xe9,0x88,0x14,0x51,0x22,0xc5,0xc8,0x72,0xa4,0x2,0xa9, 0x42,0x6a,0x91,0x5d,0x48,0x23,0xf2,0x2d,0x72,0x14,0x39,0x8d,0x5c,0x40,0xfa,0x90, 0xdb,0xc8,0x20,0x32,0x8a,0xfc,0x8a,0xbc,0x47,0x31,0x94,0x81,0xb2,0x51,0x3,0xd4, 0x2,0x75,0x40,0xb9,0xa8,0x1f,0x1a,0x8a,0xc6,0xa0,0x73,0xd1,0x74,0x34,0xf,0x5d, 0x80,0x96,0xa2,0x6b,0xd1,0x1a,0xb4,0x1e,0x3d,0x80,0xb6,0xa2,0xa7,0xd1,0x4b,0xe8, 0x75,0x74,0x0,0x7d,0x8a,0x8e,0x63,0x80,0xd1,0x31,0xe,0x66,0x8c,0xd9,0x61,0x5c, 0x8c,0x87,0x45,0x60,0x89,0x58,0x1a,0x26,0xc7,0x16,0x63,0xe5,0x58,0x35,0x56,0x8f, 0x35,0x63,0x1d,0x58,0x37,0x76,0x15,0x1b,0xc0,0x9e,0x61,0xef,0x8,0x24,0x2,0x8b, 0x80,0x13,0xec,0x8,0x5e,0x84,0x10,0xc2,0x6c,0x82,0x90,0x90,0x47,0x58,0x4c,0x58, 0x43,0xa8,0x25,0xec,0x23,0xb4,0x12,0xba,0x8,0x57,0x9,0x83,0x84,0x31,0xc2,0x27, 0x22,0x93,0xa8,0x4f,0xb4,0x25,0x7a,0x12,0xf9,0xc4,0x78,0x62,0x3a,0xb1,0x90,0x58, 0x46,0xac,0x26,0xee,0x21,0x1e,0x21,0x9e,0x25,0x5e,0x27,0xe,0x13,0x5f,0x93,0x48, 0x24,0xe,0xc9,0x92,0xe4,0x4e,0xa,0x21,0x25,0x90,0x32,0x49,0xb,0x49,0x6b,0x48, 0xdb,0x48,0x2d,0xa4,0x53,0xa4,0x3e,0xd2,0x10,0x69,0x9c,0x4c,0x26,0xeb,0x90,0x6d, 0xc9,0xde,0xe4,0x8,0xb2,0x80,0xac,0x20,0x97,0x91,0xb7,0x90,0xf,0x90,0x4f,0x92, 0xfb,0xc9,0xc3,0xe4,0xb7,0x14,0x3a,0xc5,0x88,0xe2,0x4c,0x9,0xa2,0x24,0x52,0xa4, 0x94,0x12,0x4a,0x35,0x65,0x3f,0xe5,0x4,0xa5,0x9f,0x32,0x42,0x99,0xa0,0xaa,0x51, 0xcd,0xa9,0x9e,0xd4,0x8,0xaa,0x88,0x3a,0x9f,0x5a,0x49,0x6d,0xa0,0x76,0x50,0x2f, 0x53,0x87,0xa9,0x13,0x34,0x75,0x9a,0x25,0xcd,0x9b,0x16,0x43,0xcb,0xa4,0x2d,0xa3, 0xd5,0xd0,0x9a,0x69,0x67,0x69,0xf7,0x68,0x2f,0xe9,0x74,0xba,0x9,0xdd,0x83,0x1e, 0x45,0x97,0xd0,0x97,0xd2,0x6b,0xe8,0x7,0xe9,0xe7,0xe9,0x83,0xf4,0x77,0xc,0xd, 0x86,0xd,0x83,0xc7,0x48,0x62,0x28,0x19,0x6b,0x19,0x7b,0x19,0xa7,0x18,0xb7,0x19, 0x2f,0x99,0x4c,0xa6,0x5,0xd3,0x97,0x99,0xc8,0x54,0x30,0xd7,0x32,0x1b,0x99,0x67, 0x98,0xf,0x98,0x6f,0x55,0x58,0x2a,0xf6,0x2a,0x7c,0x15,0x91,0xca,0x12,0x95,0x3a, 0x95,0x56,0x95,0x7e,0x95,0xe7,0xaa,0x54,0x55,0x73,0x55,0x3f,0xd5,0x79,0xaa,0xb, 0x54,0xab,0x55,0xf,0xab,0x5e,0x56,0x7d,0xa6,0x46,0x55,0xb3,0x50,0xe3,0xa9,0x9, 0xd4,0x16,0xab,0xd5,0xa9,0x1d,0x55,0xbb,0xa9,0x36,0xae,0xce,0x52,0x77,0x52,0x8f, 0x50,0xcf,0x51,0x5f,0xa3,0xbe,0x5f,0xfd,0x82,0xfa,0x63,0xd,0xb2,0x86,0x85,0x46, 0xa0,0x86,0x48,0xa3,0x54,0x63,0xb7,0xc6,0x19,0x8d,0x21,0x16,0xc6,0x32,0x65,0xf1, 0x58,0x42,0xd6,0x72,0x56,0x3,0xeb,0x2c,0x6b,0x98,0x4d,0x62,0x5b,0xb2,0xf9,0xec, 0x4c,0x76,0x5,0xfb,0x1b,0x76,0x2f,0x7b,0x4c,0x53,0x43,0x73,0xaa,0x66,0xac,0x66, 0x91,0x66,0x9d,0xe6,0x71,0xcd,0x1,0xe,0xc6,0xb1,0xe0,0xf0,0x39,0xd9,0x9c,0x4a, 0xce,0x21,0xce,0xd,0xce,0x7b,0x2d,0x3,0x2d,0x3f,0x2d,0xb1,0xd6,0x6a,0xad,0x66, 0xad,0x7e,0xad,0x37,0xda,0x7a,0xda,0xbe,0xda,0x62,0xed,0x72,0xed,0x16,0xed,0xeb, 0xda,0xef,0x75,0x70,0x9d,0x40,0x9d,0x2c,0x9d,0xf5,0x3a,0x6d,0x3a,0xf7,0x75,0x9, 0xba,0x36,0xba,0x51,0xba,0x85,0xba,0xdb,0x75,0xcf,0xea,0x3e,0xd3,0x63,0xeb,0x79, 0xe9,0x9,0xf5,0xca,0xf5,0xe,0xe9,0xdd,0xd1,0x47,0xf5,0x6d,0xf4,0xa3,0xf5,0x17, 0xea,0xef,0xd6,0xef,0xd1,0x1f,0x37,0x30,0x34,0x8,0x36,0x90,0x19,0x6c,0x31,0x38, 0x63,0xf0,0xcc,0x90,0x63,0xe8,0x6b,0x98,0x69,0xb8,0xd1,0xf0,0x84,0xe1,0xa8,0x11, 0xcb,0x68,0xba,0x91,0xc4,0x68,0xa3,0xd1,0x49,0xa3,0x27,0xb8,0x26,0xee,0x87,0x67, 0xe3,0x35,0x78,0x17,0x3e,0x66,0xac,0x6f,0x1c,0x62,0xac,0x34,0xde,0x65,0xdc,0x6b, 0x3c,0x61,0x62,0x69,0x32,0xdb,0xa4,0xc4,0xa4,0xc5,0xe4,0xbe,0x29,0xcd,0x94,0x6b, 0x9a,0x66,0xba,0xd1,0xb4,0xd3,0x74,0xcc,0xcc,0xc8,0x2c,0xdc,0xac,0xd8,0xac,0xc9, 0xec,0x8e,0x39,0xd5,0x9c,0x6b,0x9e,0x61,0xbe,0xd9,0xbc,0xdb,0xfc,0x8d,0x85,0xa5, 0x45,0x9c,0xc5,0x4a,0x8b,0x36,0x8b,0xc7,0x96,0xda,0x96,0x7c,0xcb,0x5,0x96,0x4d, 0x96,0xf7,0xac,0x98,0x56,0x3e,0x56,0x79,0x56,0xf5,0x56,0xd7,0xac,0x49,0xd6,0x5c, 0xeb,0x2c,0xeb,0x6d,0xd6,0x57,0x6c,0x50,0x1b,0x57,0x9b,0xc,0x9b,0x3a,0x9b,0xcb, 0xb6,0xa8,0xad,0x9b,0xad,0xc4,0x76,0x9b,0x6d,0xdf,0x14,0xe2,0x14,0x8f,0x29,0xd2, 0x29,0xf5,0x53,0x6e,0xda,0x31,0xec,0xfc,0xec,0xa,0xec,0x9a,0xec,0x6,0xed,0x39, 0xf6,0x61,0xf6,0x25,0xf6,0x6d,0xf6,0xcf,0x1d,0xcc,0x1c,0x12,0x1d,0xd6,0x3b,0x74, 0x3b,0x7c,0x72,0x74,0x75,0xcc,0x76,0x6c,0x70,0xbc,0xeb,0xa4,0xe1,0x34,0xc3,0xa9, 0xc4,0xa9,0xc3,0xe9,0x57,0x67,0x1b,0x67,0xa1,0x73,0x9d,0xf3,0x35,0x17,0xa6,0x4b, 0x90,0xcb,0x12,0x97,0x76,0x97,0x17,0x53,0x6d,0xa7,0x8a,0xa7,0x6e,0x9f,0x7a,0xcb, 0x95,0xe5,0x1a,0xee,0xba,0xd2,0xb5,0xd3,0xf5,0xa3,0x9b,0xbb,0x9b,0xdc,0xad,0xd9, 0x6d,0xd4,0xdd,0xcc,0x3d,0xc5,0x7d,0xab,0xfb,0x4d,0x2e,0x9b,0x1b,0xc9,0x5d,0xc3, 0x3d,0xef,0x41,0xf4,0xf0,0xf7,0x58,0xe2,0x71,0xcc,0xe3,0x9d,0xa7,0x9b,0xa7,0xc2, 0xf3,0x90,0xe7,0x2f,0x5e,0x76,0x5e,0x59,0x5e,0xfb,0xbd,0x1e,0x4f,0xb3,0x9c,0x26, 0x9e,0xd6,0x30,0x6d,0xc8,0xdb,0xc4,0x5b,0xe0,0xbd,0xcb,0x7b,0x60,0x3a,0x3e,0x3d, 0x65,0xfa,0xce,0xe9,0x3,0x3e,0xc6,0x3e,0x2,0x9f,0x7a,0x9f,0x87,0xbe,0xa6,0xbe, 0x22,0xdf,0x3d,0xbe,0x23,0x7e,0xd6,0x7e,0x99,0x7e,0x7,0xfc,0x9e,0xfb,0x3b,0xfa, 0xcb,0xfd,0x8f,0xf8,0xbf,0xe1,0x79,0xf2,0x16,0xf1,0x4e,0x5,0x60,0x1,0xc1,0x1, 0xe5,0x1,0xbd,0x81,0x1a,0x81,0xb3,0x3,0x6b,0x3,0x1f,0x4,0x99,0x4,0xa5,0x7, 0x35,0x5,0x8d,0x5,0xbb,0x6,0x2f,0xc,0x3e,0x15,0x42,0xc,0x9,0xd,0x59,0x1f, 0x72,0x93,0x6f,0xc0,0x17,0xf2,0x1b,0xf9,0x63,0x33,0xdc,0x67,0x2c,0x9a,0xd1,0x15, 0xca,0x8,0x9d,0x15,0x5a,0x1b,0xfa,0x30,0xcc,0x26,0x4c,0x1e,0xd6,0x11,0x8e,0x86, 0xcf,0x8,0xdf,0x10,0x7e,0x6f,0xa6,0xf9,0x4c,0xe9,0xcc,0xb6,0x8,0x88,0xe0,0x47, 0x6c,0x88,0xb8,0x1f,0x69,0x19,0x99,0x17,0xf9,0x7d,0x14,0x29,0x2a,0x32,0xaa,0x2e, 0xea,0x51,0xb4,0x53,0x74,0x71,0x74,0xf7,0x2c,0xd6,0xac,0xe4,0x59,0xfb,0x67,0xbd, 0x8e,0xf1,0x8f,0xa9,0x8c,0xb9,0x3b,0xdb,0x6a,0xb6,0x72,0x76,0x67,0xac,0x6a,0x6c, 0x52,0x6c,0x63,0xec,0x9b,0xb8,0x80,0xb8,0xaa,0xb8,0x81,0x78,0x87,0xf8,0x45,0xf1, 0x97,0x12,0x74,0x13,0x24,0x9,0xed,0x89,0xe4,0xc4,0xd8,0xc4,0x3d,0x89,0xe3,0x73, 0x2,0xe7,0x6c,0x9a,0x33,0x9c,0xe4,0x9a,0x54,0x96,0x74,0x63,0xae,0xe5,0xdc,0xa2, 0xb9,0x17,0xe6,0xe9,0xce,0xcb,0x9e,0x77,0x3c,0x59,0x35,0x59,0x90,0x7c,0x38,0x85, 0x98,0x12,0x97,0xb2,0x3f,0xe5,0x83,0x20,0x42,0x50,0x2f,0x18,0x4f,0xe5,0xa7,0x6e, 0x4d,0x1d,0x13,0xf2,0x84,0x9b,0x85,0x4f,0x45,0xbe,0xa2,0x8d,0xa2,0x51,0xb1,0xb7, 0xb8,0x4a,0x3c,0x92,0xe6,0x9d,0x56,0x95,0xf6,0x38,0xdd,0x3b,0x7d,0x43,0xfa,0x68, 0x86,0x4f,0x46,0x75,0xc6,0x33,0x9,0x4f,0x52,0x2b,0x79,0x91,0x19,0x92,0xb9,0x23, 0xf3,0x4d,0x56,0x44,0xd6,0xde,0xac,0xcf,0xd9,0x71,0xd9,0x2d,0x39,0x94,0x9c,0x94, 0x9c,0xa3,0x52,0xd,0x69,0x96,0xb4,0x2b,0xd7,0x30,0xb7,0x28,0xb7,0x4f,0x66,0x2b, 0x2b,0x93,0xd,0xe4,0x79,0xe6,0x6d,0xca,0x1b,0x93,0x87,0xca,0xf7,0xe4,0x23,0xf9, 0x73,0xf3,0xdb,0x15,0x6c,0x85,0x4c,0xd1,0xa3,0xb4,0x52,0xae,0x50,0xe,0x16,0x4c, 0x2f,0xa8,0x2b,0x78,0x5b,0x18,0x5b,0x78,0xb8,0x48,0xbd,0x48,0x5a,0xd4,0x33,0xdf, 0x66,0xfe,0xea,0xf9,0x23,0xb,0x82,0x16,0x7c,0xbd,0x90,0xb0,0x50,0xb8,0xb0,0xb3, 0xd8,0xb8,0x78,0x59,0xf1,0xe0,0x22,0xbf,0x45,0xbb,0x16,0x23,0x8b,0x53,0x17,0x77, 0x2e,0x31,0x5d,0x52,0xba,0x64,0x78,0x69,0xf0,0xd2,0x7d,0xcb,0x68,0xcb,0xb2,0x96, 0xfd,0x50,0xe2,0x58,0x52,0x55,0xf2,0x6a,0x79,0xdc,0xf2,0x8e,0x52,0x83,0xd2,0xa5, 0xa5,0x43,0x2b,0x82,0x57,0x34,0x95,0xa9,0x94,0xc9,0xcb,0x6e,0xae,0xf4,0x5a,0xb9, 0x63,0x15,0x61,0x95,0x64,0x55,0xef,0x6a,0x97,0xd5,0x5b,0x56,0x7f,0x2a,0x17,0x95, 0x5f,0xac,0x70,0xac,0xa8,0xae,0xf8,0xb0,0x46,0xb8,0xe6,0xe2,0x57,0x4e,0x5f,0xd5, 0x7c,0xf5,0x79,0x6d,0xda,0xda,0xde,0x4a,0xb7,0xca,0xed,0xeb,0x48,0xeb,0xa4,0xeb, 0x6e,0xac,0xf7,0x59,0xbf,0xaf,0x4a,0xbd,0x6a,0x41,0xd5,0xd0,0x86,0xf0,0xd,0xad, 0x1b,0xf1,0x8d,0xe5,0x1b,0x5f,0x6d,0x4a,0xde,0x74,0xa1,0x7a,0x6a,0xf5,0x8e,0xcd, 0xb4,0xcd,0xca,0xcd,0x3,0x35,0x61,0x35,0xed,0x5b,0xcc,0xb6,0xac,0xdb,0xf2,0xa1, 0x36,0xa3,0xf6,0x7a,0x9d,0x7f,0x5d,0xcb,0x56,0xfd,0xad,0xab,0xb7,0xbe,0xd9,0x26, 0xda,0xd6,0xbf,0xdd,0x77,0x7b,0xf3,0xe,0x83,0x1d,0x15,0x3b,0xde,0xef,0x94,0xec, 0xbc,0xb5,0x2b,0x78,0x57,0x6b,0xbd,0x45,0x7d,0xf5,0x6e,0xd2,0xee,0x82,0xdd,0x8f, 0x1a,0x62,0x1b,0xba,0xbf,0xe6,0x7e,0xdd,0xb8,0x47,0x77,0x4f,0xc5,0x9e,0x8f,0x7b, 0xa5,0x7b,0x7,0xf6,0x45,0xef,0xeb,0x6a,0x74,0x6f,0x6c,0xdc,0xaf,0xbf,0xbf,0xb2, 0x9,0x6d,0x52,0x36,0x8d,0x1e,0x48,0x3a,0x70,0xe5,0x9b,0x80,0x6f,0xda,0x9b,0xed, 0x9a,0x77,0xb5,0x70,0x5a,0x2a,0xe,0xc2,0x41,0xe5,0xc1,0x27,0xdf,0xa6,0x7c,0x7b, 0xe3,0x50,0xe8,0xa1,0xce,0xc3,0xdc,0xc3,0xcd,0xdf,0x99,0x7f,0xb7,0xf5,0x8,0xeb, 0x48,0x79,0x2b,0xd2,0x3a,0xbf,0x75,0xac,0x2d,0xa3,0x6d,0xa0,0x3d,0xa1,0xbd,0xef, 0xe8,0x8c,0xa3,0x9d,0x1d,0x5e,0x1d,0x47,0xbe,0xb7,0xff,0x7e,0xef,0x31,0xe3,0x63, 0x75,0xc7,0x35,0x8f,0x57,0x9e,0xa0,0x9d,0x28,0x3d,0xf1,0xf9,0xe4,0x82,0x93,0xe3, 0xa7,0x64,0xa7,0x9e,0x9d,0x4e,0x3f,0x3d,0xd4,0x99,0xdc,0x79,0xf7,0x4c,0xfc,0x99, 0x6b,0x5d,0x51,0x5d,0xbd,0x67,0x43,0xcf,0x9e,0x3f,0x17,0x74,0xee,0x4c,0xb7,0x5f, 0xf7,0xc9,0xf3,0xde,0xe7,0x8f,0x5d,0xf0,0xbc,0x70,0xf4,0x22,0xf7,0x62,0xdb,0x25, 0xb7,0x4b,0xad,0x3d,0xae,0x3d,0x47,0x7e,0x70,0xfd,0xe1,0x48,0xaf,0x5b,0x6f,0xeb, 0x65,0xf7,0xcb,0xed,0x57,0x3c,0xae,0x74,0xf4,0x4d,0xeb,0x3b,0xd1,0xef,0xd3,0x7f, 0xfa,0x6a,0xc0,0xd5,0x73,0xd7,0xf8,0xd7,0x2e,0x5d,0x9f,0x79,0xbd,0xef,0xc6,0xec, 0x1b,0xb7,0x6e,0x26,0xdd,0x1c,0xb8,0x25,0xba,0xf5,0xf8,0x76,0xf6,0xed,0x17,0x77, 0xa,0xee,0x4c,0xdc,0x5d,0x7a,0x8f,0x78,0xaf,0xfc,0xbe,0xda,0xfd,0xea,0x7,0xfa, 0xf,0xea,0x7f,0xb4,0xfe,0xb1,0x65,0xc0,0x6d,0xe0,0xf8,0x60,0xc0,0x60,0xcf,0xc3, 0x59,0xf,0xef,0xe,0x9,0x87,0x9e,0xfe,0x94,0xff,0xd3,0x87,0xe1,0xd2,0x47,0xcc, 0x47,0xd5,0x23,0x46,0x23,0x8d,0x8f,0x9d,0x1f,0x1f,0x1b,0xd,0x1a,0xbd,0xf2,0x64, 0xce,0x93,0xe1,0xa7,0xb2,0xa7,0x13,0xcf,0xca,0x7e,0x56,0xff,0x79,0xeb,0x73,0xab, 0xe7,0xdf,0xfd,0xe2,0xfb,0x4b,0xcf,0x58,0xfc,0xd8,0xf0,0xb,0xf9,0x8b,0xcf,0xbf, 0xae,0x79,0xa9,0xf3,0x72,0xef,0xab,0xa9,0xaf,0x3a,0xc7,0x23,0xc7,0x1f,0xbc,0xce, 0x79,0x3d,0xf1,0xa6,0xfc,0xad,0xce,0xdb,0x7d,0xef,0xb8,0xef,0xba,0xdf,0xc7,0xbd, 0x1f,0x99,0x28,0xfc,0x40,0xfe,0x50,0xf3,0xd1,0xfa,0x63,0xc7,0xa7,0xd0,0x4f,0xf7, 0x3e,0xe7,0x7c,0xfe,0xfc,0x2f,0xf7,0x84,0xf3,0xfb,0x25,0xd2,0x9f,0x33,0x0,0x0, 0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8e,0x7c,0xfb,0x51,0x93,0x0,0x0, 0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x25,0x0,0x0,0x80,0x83,0x0,0x0, 0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0, 0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5,0x46,0x0,0x0,0x1,0xec,0x49,0x44, 0x41,0x54,0x78,0xda,0x6c,0x93,0xb1,0x6a,0x54,0x41,0x14,0x86,0xbf,0xdd,0x1b,0xb3, 0x68,0x62,0x2c,0x5c,0x4d,0x8a,0xa0,0x4,0x2d,0x24,0x55,0x9e,0xc2,0x3a,0xaf,0x91, 0xd2,0x4a,0xac,0x6c,0x5,0x1b,0xb1,0x30,0x8d,0x8f,0xa0,0xaf,0x21,0x8,0x5a,0xa8, 0x90,0x26,0x41,0x41,0xc1,0x48,0xd8,0x2c,0xee,0xc6,0xdc,0xbd,0x73,0xe7,0x9c,0xff, 0x58,0xdc,0xcd,0xdd,0x64,0x93,0x81,0xc3,0xcc,0xc0,0x9c,0xff,0x7c,0xff,0xcc,0x99, 0x4e,0x44,0x0,0x30,0xfc,0xf2,0xe2,0x90,0x88,0xc2,0x65,0x77,0x42,0x4e,0xc8,0x91, 0x1c,0xc9,0x90,0x5b,0xb3,0x77,0x43,0xb2,0x1f,0x92,0xef,0x3e,0x7c,0xfc,0xf6,0x25, 0xc0,0x2,0xb3,0xb1,0xd6,0xeb,0xaf,0x92,0xfe,0xe,0x90,0x8b,0x6b,0xb7,0x6e,0x33, 0xfc,0x67,0xac,0x3f,0x78,0x44,0xb1,0x30,0x3b,0x96,0x27,0xa3,0x8d,0x9f,0x1f,0xde, 0xed,0x0,0x97,0x4,0xe8,0xf5,0x57,0xe9,0xf5,0x57,0xb1,0xaa,0xa4,0x1c,0xfc,0x26, 0xfe,0xec,0xb1,0x9f,0x8c,0xf5,0xfb,0x1b,0x2c,0xad,0x2c,0x13,0x32,0xba,0xc5,0x2, 0x92,0x6f,0x9c,0xe5,0x74,0xb9,0x62,0x14,0x8b,0x3d,0x96,0xd6,0xee,0x21,0x19,0x96, 0x6b,0x7e,0x7d,0xdf,0x47,0xb9,0x42,0xb9,0xc4,0xf3,0x29,0x21,0x6f,0xcf,0xce,0x8, 0x22,0x8,0x82,0xd6,0xbf,0x4f,0xbd,0x7b,0x46,0x2,0xcf,0xa7,0xc8,0x53,0x13,0x57, 0x9,0x44,0x88,0x70,0x43,0xf2,0x66,0x9e,0xae,0x65,0x9,0x3a,0x81,0xd5,0x63,0xc2, 0x1a,0x81,0x90,0xb8,0x64,0x21,0x42,0xd3,0xaa,0x19,0xf7,0x8c,0x5b,0x8d,0x64,0xb8, 0x95,0xc8,0x26,0x78,0x1a,0x63,0x69,0x8c,0x55,0x63,0x16,0x6f,0x2e,0xf1,0xf5,0xfd, 0xf6,0x9b,0xb,0x2,0x92,0x90,0x67,0x64,0x75,0x1b,0xe1,0xd6,0x24,0xe7,0x9,0x56, 0x8d,0xb1,0x34,0xc2,0xd2,0x88,0xe5,0xfe,0xa,0x11,0xbe,0x33,0x47,0xe0,0xb8,0xd5, 0x4d,0xe4,0x84,0x5b,0xe3,0xd5,0xeb,0x9,0xb2,0x72,0x9a,0x7c,0x82,0xd5,0x27,0x2c, 0xae,0x3f,0x6f,0x6d,0xcc,0xee,0x40,0x42,0x56,0xe3,0x9e,0x91,0x4d,0x49,0xe4,0xc8, 0x4a,0xe8,0x80,0xd5,0x5,0xe1,0x35,0xf2,0xdc,0x5a,0xbe,0x20,0x20,0x35,0x4,0xe7, 0x45,0x42,0x8e,0x47,0x5,0x1d,0xf0,0xba,0x43,0x28,0x13,0xb2,0x69,0x41,0x9f,0xbb, 0x44,0xd9,0x14,0xfd,0xa2,0x5,0x59,0xd5,0x3c,0x9d,0x4d,0x90,0x55,0x84,0x8c,0x27, 0x9f,0x47,0x9c,0x7d,0x81,0x39,0x82,0x84,0x2c,0xcf,0x8,0x42,0x84,0x3b,0x11,0x5d, 0x42,0x45,0xfb,0x74,0x83,0x41,0xd9,0x5a,0x38,0x47,0xe0,0x78,0xae,0x1b,0x91,0x9c, 0x90,0xa5,0xa6,0xa9,0x42,0x97,0x3a,0xf5,0xf5,0xda,0x33,0x22,0x74,0x30,0x47,0x60, 0xe4,0xa3,0x43,0x3c,0x8c,0x20,0xa0,0xb,0x11,0xc1,0xe9,0x30,0x53,0x14,0xce,0x31, 0xde,0x76,0x2b,0x11,0x7,0xc0,0xee,0xbc,0x85,0xbb,0x96,0xca,0x4d,0xab,0xcb,0xcd, 0x9c,0xab,0x2d,0xcf,0x69,0x53,0xd2,0xd6,0xa7,0xbd,0xe1,0xf6,0x8d,0xeb,0xcb,0xdf, 0x9e,0xbe,0xfa,0x78,0x74,0xd5,0xbf,0xf9,0x3f,0x0,0xd3,0xcb,0xde,0x11,0x4c,0x3d, 0xd,0xf6,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_View_Isometric.png 0x0,0x0,0x1,0x33, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x2c, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x11,0x90,0x67,0x60, 0x81,0x31,0x18,0xd1,0x8c,0xfa,0xcf,0x88,0x55,0x9c,0xf1,0x3f,0x42,0x8a,0x48,0x2b, 0x46,0x88,0x2,0x78,0x40,0x11,0x19,0x92,0xb4,0x70,0x3,0x0,0x55,0x2c,0xa,0x1b, 0xf,0xc7,0xc2,0x5a,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33, 0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x34,0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xf9,0x47,0x49,0x58,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsBottomHS.png 0x0,0x0,0x2,0x10, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x9f,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xaa,0xb5,0xc5,0xa9,0xb4,0xc4,0xa7,0xb2,0xc3,0x8f,0x9d,0xaf, 0xa7,0xb2,0xc2,0xff,0xff,0xff,0xfb,0xfd,0xff,0x59,0x6a,0x81,0xa2,0xae,0xbf,0xfd, 0xfe,0xff,0xe0,0xe6,0xed,0x46,0x59,0x71,0x4,0x2,0x4,0xcb,0xcb,0xcb,0xc4,0xc4, 0xc4,0xa6,0xa6,0xa6,0x9d,0xa9,0xba,0xf8,0xfb,0xff,0xd3,0xdd,0xe5,0x43,0x56,0x6f, 0xee,0xee,0xee,0x7d,0x7d,0x7d,0x97,0xa4,0xb6,0xf2,0xf7,0xff,0xcc,0xd5,0xe2,0x40, 0x53,0x6d,0xb8,0xb8,0xb8,0xeb,0xeb,0xeb,0x6c,0x6c,0x6c,0x91,0x9e,0xb1,0xed,0xf4, 0xff,0xc2,0xd1,0xe3,0x40,0x54,0x6e,0xb0,0xb0,0xb0,0xe2,0xe2,0xe2,0x58,0x58,0x58, 0x8b,0x98,0xab,0xe6,0xf2,0xff,0xbc,0xcd,0xe4,0x46,0x5a,0x72,0xd6,0xd6,0xd6,0x4e, 0x4e,0x4e,0x83,0x91,0xa5,0xd7,0xe6,0xf7,0xb6,0xca,0xe5,0x3f,0x52,0x6c,0x95,0x95, 0x95,0x4d,0x4d,0x4d,0x80,0x8e,0xa3,0x63,0x73,0x89,0x3b,0x4f,0x68,0x35,0x49,0x63, 0x45,0x3b,0xf3,0xeb,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8, 0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x6,0x61,0x66,0xb8,0x7d,0x0,0x0, 0x0,0x67,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x20,0x12,0x30,0x32,0x31,0xb3, 0xa0,0x8,0xb0,0xb2,0xb1,0x73,0xa0,0x8,0x70,0x72,0x71,0xf3,0x30,0x30,0xf0,0x42, 0x38,0x7c,0xfc,0x2,0xc,0x82,0x42,0xc2,0x22,0x70,0x1,0x7e,0x51,0x31,0x6,0x71, 0x9,0x49,0x29,0xb8,0x80,0xb4,0x8c,0x2c,0x83,0x9c,0xbc,0x82,0x22,0x5c,0x40,0x49, 0x59,0x85,0x41,0x55,0x4d,0x5d,0x3,0x2e,0x20,0xa0,0xa9,0xc5,0xa0,0xad,0xa3,0xab, 0xc7,0xc0,0xcb,0xb,0x11,0xd1,0xd7,0x32,0x60,0x30,0x34,0x32,0x36,0x81,0xab,0xc0, 0x0,0xbc,0x48,0x0,0xbb,0x0,0x1,0x0,0x0,0x63,0xcb,0x7,0x4c,0x74,0x18,0xcd, 0x8d,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72, 0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54, 0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c, 0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d, 0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39, 0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3, 0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderFlag_Shadows.png 0x0,0x0,0x1,0x67, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x60, 0x49,0x44,0x41,0x54,0x28,0xcf,0x85,0x50,0x41,0xe,0xc0,0x30,0x8,0x82,0xa6,0x67, 0xff,0xff,0x4e,0x3f,0xc0,0xe,0x9d,0xd1,0x2d,0xd3,0x71,0xa2,0x85,0x8,0x4a,0x21, 0xc0,0xa4,0x10,0x83,0xed,0x14,0xf3,0xb3,0xbe,0x29,0x0,0x54,0x15,0xd3,0x24,0x2, 0xab,0x93,0x1,0x91,0x2,0x16,0x7e,0xb0,0xc2,0xd9,0x45,0xdc,0xda,0x4f,0xc9,0x69, 0xcd,0xef,0xe9,0xcf,0xe,0x33,0x76,0x10,0x7b,0x8d,0x72,0x96,0x8,0x6b,0x72,0xfc, 0x1c,0xca,0xda,0x1a,0x76,0xe,0xe5,0xec,0xc,0xce,0xb2,0xc5,0xd8,0x61,0xc2,0x5, 0x4a,0xf0,0x2a,0x15,0x84,0x8c,0x82,0xe6,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74, 0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33, 0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b, 0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58, 0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31, 0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x33,0x3a,0x32,0x36, 0x2b,0x31,0x30,0x3a,0x30,0x30,0x11,0x5e,0x5b,0x38,0x0,0x0,0x0,0x0,0x49,0x45, 0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsRightHS.png 0x0,0x0,0x2,0x9, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x96,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xff,0xff,0xff,0xcb,0xcb,0xcb,0xc4,0xc4,0xc4,0xb8,0xb8,0xb8, 0xb0,0xb0,0xb0,0xa6,0xa6,0xa6,0x95,0x95,0x95,0x4,0x2,0x4,0xee,0xee,0xee,0xeb, 0xeb,0xeb,0xe2,0xe2,0xe2,0xd6,0xd6,0xd6,0x4e,0x4e,0x4e,0x7d,0x7d,0x7d,0x6c,0x6c, 0x6c,0x58,0x58,0x58,0x4d,0x4d,0x4d,0x8b,0x98,0xab,0xaa,0xb5,0xc5,0xa7,0xb2,0xc2, 0xa2,0xae,0xbf,0x9d,0xa9,0xba,0x97,0xa4,0xb6,0x91,0x9e,0xb1,0x83,0x91,0xa5,0x80, 0x8e,0xa3,0xa9,0xb4,0xc4,0xfd,0xfe,0xff,0xf8,0xfb,0xff,0xf2,0xf7,0xff,0xed,0xf4, 0xff,0xe6,0xf2,0xff,0xd7,0xe6,0xf7,0x63,0x73,0x89,0xa7,0xb2,0xc3,0xfb,0xfd,0xff, 0xe0,0xe6,0xed,0xd3,0xdd,0xe5,0xcc,0xd5,0xe2,0xc2,0xd1,0xe3,0xbc,0xcd,0xe4,0xb6, 0xca,0xe5,0x3b,0x4f,0x68,0x8f,0x9d,0xaf,0x59,0x6a,0x81,0x46,0x59,0x71,0x43,0x56, 0x6f,0x40,0x53,0x6d,0x35,0x49,0x63,0x71,0x5c,0xff,0x13,0x0,0x0,0x0,0x1,0x74, 0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44, 0x1,0xff,0x2,0x2d,0xde,0x0,0x0,0x0,0x69,0x49,0x44,0x41,0x54,0x18,0xd3,0x63, 0x60,0xc0,0xe,0x18,0xd1,0xf8,0x4c,0xcc,0x2c,0xac,0x6c,0xec,0xc,0x1c,0x1c,0x30, 0x1,0x66,0x4e,0x2e,0x6e,0x1e,0x5e,0x24,0x1,0x36,0x3e,0x7e,0x1,0x5e,0x41,0x24, 0x1,0x6,0x4e,0x20,0x16,0x82,0x9,0x8,0x8b,0x88,0x8a,0x89,0x4b,0x8,0x49,0x4a, 0x9,0x41,0x5,0xa4,0x19,0x65,0x64,0xe5,0xe4,0x15,0x14,0x95,0x60,0x2,0xca,0x2a, 0xaa,0x6a,0xea,0x1a,0x9a,0x5a,0xda,0x30,0x1,0x1d,0x5d,0x3d,0x7d,0x3,0x3,0x43, 0x43,0x43,0x64,0x43,0x21,0x0,0x55,0x80,0x3,0x49,0x80,0x3,0x2,0xf0,0xa8,0xc0, 0xb,0x0,0x9f,0x1d,0x6,0xc4,0xf2,0x3b,0xe8,0xb7,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30, 0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30, 0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32, 0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a, 0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0, 0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/PauseHS.png 0x0,0x0,0x1,0x95, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x4e,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x8d,0xb3,0xfd,0x8a,0xb0,0xfa,0x6e,0x95,0xe2,0xd5,0xe1,0xfc, 0x2d,0x55,0xaa,0x86,0xad,0xf6,0xda,0xe5,0xfb,0x25,0x4e,0xa2,0x81,0xa8,0xf3,0xd3, 0xe1,0xfb,0x1e,0x46,0x9a,0x7d,0xa3,0xef,0xc8,0xd7,0xfb,0x16,0x3e,0x92,0x78,0x9e, 0xea,0xbb,0xd0,0xf9,0xf,0x36,0x8b,0x74,0x9b,0xe7,0xaf,0xc9,0xf9,0x9,0x30,0x85, 0x70,0x97,0xe3,0xa0,0xbc,0xf3,0x5,0x2c,0x81,0x6,0x2d,0x82,0xff,0xff,0xff,0x25, 0xe0,0x1,0xe8,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66, 0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x19,0xec,0x6e,0xb5,0x88,0x0,0x0,0x0, 0x3d,0x49,0x44,0x41,0x54,0x18,0xd3,0xad,0xc3,0xc9,0xd,0x80,0x20,0x0,0x45,0x41, 0x4,0x41,0xdc,0x0,0x71,0xc1,0xfe,0x2b,0x35,0x79,0x87,0x5f,0x0,0x71,0x92,0x31, 0xe6,0x27,0x83,0x75,0x14,0x3b,0x7a,0x4a,0x98,0x22,0x65,0x5e,0x56,0xca,0xb6,0x27, 0x4a,0x2e,0x7,0xa5,0x9e,0x17,0xe5,0x7e,0x1a,0xc5,0xbd,0x8d,0x9d,0x3e,0xf,0x97, 0x2,0x91,0xb8,0xc1,0xe,0xd7,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61, 0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30, 0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30, 0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d, 0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31,0x3a,0x30,0x32,0x3a,0x35,0x36,0x2b,0x31, 0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderMode_Unlit.png 0x0,0x0,0x1,0x69, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x4,0x3,0x0,0x0,0x0,0xed,0xdd,0xe2,0x52, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x12,0x50,0x4c,0x54, 0x45,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xd9,0x1e,0x5b,0xff,0x32,0xff,0x0,0x0, 0xff,0xff,0xff,0x12,0x3a,0x36,0x72,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0, 0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x0,0x88,0x5,0x1d, 0x48,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe, 0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x38,0x49,0x44,0x41,0x54,0x8,0xd7, 0x63,0x60,0x40,0x2,0x82,0x40,0x20,0x0,0xa4,0x19,0x95,0x94,0x94,0x14,0x41,0xc, 0x21,0x20,0x43,0x58,0x0,0x2a,0x60,0x2c,0x0,0x15,0x0,0x31,0x40,0x4a,0xc1,0xc, 0x11,0x17,0x17,0x17,0xd2,0x18,0x86,0xc,0x50,0x86,0x0,0xd4,0x4a,0x41,0x24,0x27, 0x0,0x0,0x26,0xa1,0xc,0x45,0x53,0x1d,0x60,0x33,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30, 0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30, 0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32, 0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x34,0x3a, 0x34,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0xf0,0x4a,0x77,0x48,0x0,0x0,0x0,0x0, 0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/play.png 0x0,0x0,0x1,0x6, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x54,0x50,0x4c,0x54,0x45,0xff,0xff,0xff,0x1f,0x1f,0x1f,0x21,0x21, 0x21,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x0,0x0,0x0,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1e,0x1e,0x1e,0x20,0x20,0x20,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x20,0x20,0x20,0x1e, 0x1e,0x1e,0x1f,0x1f,0x1f,0x1b,0x1b,0x1b,0x1e,0x1e,0x1e,0x24,0x24,0x24,0x1f,0x1f, 0x1f,0x1d,0x1d,0x1d,0x20,0x20,0x20,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1f,0x1f,0x1f,0x2b,0x2b,0x2b,0x1c,0x1c,0x1c,0x1f,0x1f,0x1f,0x11,0x27,0x71,0xfc, 0x0,0x0,0x0,0x1b,0x74,0x52,0x4e,0x53,0x0,0xcb,0x17,0xd3,0x84,0x4,0xdf,0x73, 0xfb,0xd2,0x4a,0xf0,0xb9,0xe3,0xfd,0x1c,0x8f,0x7,0xd6,0x58,0xf1,0x5b,0xd5,0x52, 0x8d,0x6,0x1b,0x9a,0x18,0x9,0x4f,0x0,0x0,0x0,0x46,0x49,0x44,0x41,0x54,0x78, 0x5e,0x95,0x8f,0x37,0xe,0xc0,0x40,0xc,0xc3,0x2e,0xbd,0xf7,0x1e,0xfe,0xff,0x9f, 0x99,0x9,0xdc,0x12,0x8e,0x84,0x21,0xc9,0x21,0x46,0x95,0x6,0x93,0x95,0x79,0x21, 0x91,0x50,0x37,0xad,0x5,0x74,0xfd,0x64,0x1,0xc3,0xbc,0x58,0x30,0xae,0x9b,0x5, 0xec,0x87,0x2f,0xce,0xcb,0x19,0xf7,0xe3,0x96,0x37,0xb2,0xc3,0x4b,0xfd,0xcb,0x1f, 0x3e,0x47,0x79,0x5,0xd2,0xc6,0x9e,0x60,0xb4,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_ShapeSphere.png 0x0,0x0,0x7,0x64, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x6,0x59,0x49,0x44,0x41,0x54,0x58,0xc3,0x9d,0x97,0xcb,0x8e,0x24,0x57, 0x11,0x86,0xbf,0x38,0x97,0xcc,0xac,0xaa,0xee,0xf1,0x34,0x63,0x86,0x8b,0x11,0x2c, 0xbc,0x44,0x80,0x31,0xc2,0x62,0xc3,0x16,0x9,0x71,0xd9,0x80,0x64,0x16,0x2c,0x58, 0xc0,0x8a,0x1d,0x4f,0xc3,0x13,0x80,0xbc,0x41,0x2,0x79,0xe3,0xd,0x1b,0xb,0x9, 0x34,0x92,0xb9,0xec,0x78,0x0,0x64,0xc1,0xc,0xee,0x9e,0xee,0xae,0xac,0xcc,0x3c, 0x97,0x60,0x11,0x27,0xab,0x7a,0xcc,0x48,0x33,0x72,0x49,0xd1,0x59,0x5d,0x99,0xe7, 0xc4,0x1f,0x11,0x7f,0xfc,0x27,0x52,0x78,0xc9,0x8f,0xfe,0x6a,0xa7,0x4,0x81,0x8, 0x44,0x7,0xc1,0x41,0xe7,0x20,0xf8,0x66,0x1,0x42,0x4,0x1f,0xa1,0xa,0xf2,0x8b, 0x7f,0xca,0xcb,0xec,0xfb,0xc2,0x87,0xf4,0x97,0x5b,0x25,0x0,0x9d,0x34,0x73,0xd0, 0x37,0xe7,0x5d,0x80,0x21,0xc0,0xd0,0x41,0xec,0xc1,0x77,0x40,0x84,0x1a,0x80,0x0, 0x2a,0xc8,0xdb,0x7f,0x92,0x4f,0x4,0x40,0x7f,0xde,0x2b,0xc1,0x41,0x14,0xe8,0x5, 0x7a,0xcc,0x71,0xef,0x60,0xeb,0xe0,0x95,0x0,0xe7,0x1,0x86,0x1,0xe2,0xce,0x2c, 0xec,0xc0,0x6f,0xc,0x44,0x16,0x38,0x14,0x98,0x2b,0x4c,0x23,0xf2,0xe3,0x3f,0xca, 0x4b,0x3,0xd0,0x9f,0xf5,0x4a,0xa4,0x45,0x2b,0x30,0x34,0x0,0x83,0x83,0xb,0x7, 0x17,0xde,0xa2,0xee,0x37,0xd0,0x9f,0x43,0x7f,0x1f,0xba,0xb,0x88,0x17,0x10,0xce, 0x40,0x6,0x50,0x81,0x9a,0xe0,0x30,0xc2,0xf5,0xd,0x1c,0x46,0xe4,0x7b,0xbf,0x97, 0x17,0x2,0xd0,0x9f,0x76,0x7a,0x8a,0x5a,0x60,0xc0,0x0,0x6c,0x4,0x3e,0x2d,0x70, 0xde,0x9c,0xf,0x3,0x6c,0x5e,0x81,0xe1,0x1,0xc,0xf,0xa1,0xff,0x1c,0x74,0xf, 0x21,0xdc,0x7,0xb7,0x5,0x1c,0xd4,0x19,0x96,0x6b,0x98,0x9e,0xc0,0x47,0x8f,0xe1, 0xe6,0xa,0xf9,0xee,0xef,0x9e,0xf1,0x19,0xee,0xfe,0x53,0x7f,0x12,0x55,0x5,0xc4, 0x29,0xf8,0x76,0x37,0x8,0x44,0x85,0x4f,0x1,0xdb,0xc6,0x81,0xce,0x43,0x3f,0xc0, 0x70,0xe,0x9b,0x57,0x61,0xf3,0x1a,0xc,0x5f,0x84,0xee,0x35,0x88,0xf,0x4e,0x0, 0xca,0xc,0xfd,0x15,0xc4,0x7b,0xe0,0x3a,0x50,0x45,0xdf,0xfd,0xa1,0xca,0xf7,0xff, 0x20,0xff,0x7,0x20,0xff,0x28,0x28,0x28,0x38,0x31,0xe7,0xab,0x5,0x85,0xb3,0x56, 0x82,0x20,0x8d,0xfd,0xd1,0x0,0xf4,0xe7,0x2d,0x3,0x9f,0x87,0xcd,0x97,0xa0,0xfb, 0x2,0x84,0x7,0xe0,0x36,0xa7,0xc,0xe4,0xfb,0xe0,0x7a,0x50,0x85,0x8b,0x9,0xe6, 0x11,0x7d,0xe7,0xdb,0x2a,0x6f,0xbf,0x2f,0x1f,0xcb,0x80,0xa2,0x22,0x88,0x28,0x38, 0x1a,0x10,0xb5,0xb6,0xdb,0x2,0xbe,0x1,0xb,0x2,0xd1,0x1b,0xeb,0xbb,0x9d,0xd5, 0xbe,0x7b,0x8,0xf1,0xb3,0x10,0x3f,0x3,0xfe,0x3e,0x48,0xf,0x22,0xa0,0xc9,0x9c, 0x53,0xa1,0x8c,0x90,0x2e,0xe1,0xfc,0xbf,0x30,0xee,0x8e,0x5e,0x1d,0xc0,0xfc,0x3, 0xa7,0x55,0x8d,0x37,0xe6,0x1c,0x70,0x6a,0x36,0x28,0x48,0xfb,0xee,0x57,0x20,0x1e, 0x42,0x67,0x8c,0xf,0x67,0x10,0xce,0x21,0xdc,0x3,0x7f,0x6e,0xe9,0x77,0x3d,0x48, 0x7,0xb2,0x1,0xb7,0x3,0x7f,0xcf,0xee,0xc7,0x33,0xd8,0x6e,0x20,0x3a,0xf4,0x37, 0x6f,0xe9,0x31,0x3,0x55,0x41,0xd0,0x23,0x23,0x55,0x40,0x44,0x8c,0xa2,0x41,0x1b, 0x5d,0xef,0x0,0x71,0x80,0x73,0xe0,0x2,0x48,0x3c,0x39,0x24,0x80,0xb8,0x13,0xb7, 0xc5,0x81,0x4,0x70,0xd1,0x38,0xe0,0xa2,0xad,0x19,0x5c,0xb,0x1d,0xdc,0xf5,0x77, 0x44,0x73,0x55,0xaa,0x82,0xa2,0xa8,0xe8,0xb1,0x24,0x78,0xa3,0x45,0xfb,0x73,0xea, 0x1b,0xc1,0xd2,0x2a,0x15,0x28,0xa0,0xcd,0xa8,0x56,0xeb,0x3b,0x65,0xb5,0xdf,0xa, 0x90,0xed,0x59,0x29,0x10,0x2a,0x68,0x46,0x7f,0xfd,0xba,0x86,0x5a,0xdb,0x5e,0xda, 0xd6,0xea,0xdd,0xc5,0x62,0x17,0x95,0xd3,0x4d,0xd5,0xb6,0x61,0x82,0x3a,0x41,0x1d, 0xa1,0xde,0x36,0x1b,0x2d,0x23,0xc7,0xb5,0x19,0xea,0x1,0xea,0x1e,0xca,0xad,0x5d, 0xeb,0x4,0xb2,0xd8,0x1e,0x4e,0x9,0xa5,0xaa,0x69,0x77,0x55,0x82,0x8a,0x2d,0x5d, 0xa3,0x68,0x1,0x50,0x80,0x2a,0x50,0x5b,0x34,0x35,0x41,0x99,0xa0,0xec,0xa1,0x5c, 0x41,0x7e,0xd2,0xc8,0x37,0xd8,0x22,0x19,0x8c,0x84,0x75,0x81,0xf2,0x14,0xf2,0x63, 0x7b,0x26,0x5d,0x42,0xbe,0x31,0x50,0xba,0x40,0xc9,0x84,0x52,0x41,0xab,0x22,0x55, 0xa8,0x55,0xd1,0xda,0x22,0xae,0x8d,0x1c,0xa5,0x1,0x28,0x15,0x8a,0x40,0x2e,0x50, 0x56,0x0,0xd7,0x6d,0xe3,0xb3,0x13,0xdb,0x75,0xf,0xb2,0x6d,0x0,0x66,0xc8,0x97, 0xb0,0x7c,0x8,0xf3,0xbf,0x60,0x79,0xc,0xe9,0xa,0xf2,0xd8,0xf6,0xc8,0x84,0x5c, 0xa1,0x16,0x90,0xa2,0x94,0x22,0x84,0x15,0x44,0xb5,0x72,0x91,0x5,0xb2,0x42,0xc2, 0xae,0xb9,0x40,0x4e,0x90,0x46,0xf0,0x4f,0x9b,0xe3,0x60,0xa5,0x29,0x23,0x84,0x27, 0x20,0xbb,0x56,0x82,0xd9,0x1c,0x2e,0xff,0x81,0xc3,0x87,0x30,0xfd,0x1b,0xe6,0x2b, 0x58,0x46,0x48,0xb,0xe4,0x15,0x0,0xe6,0x2c,0x16,0x25,0x14,0xc1,0x15,0xcb,0x8, 0x65,0x75,0x2a,0x90,0x14,0x96,0x6a,0x87,0x53,0x4c,0xe0,0x67,0x70,0x37,0x20,0xde, 0x9c,0xd7,0xd9,0xd2,0xed,0xef,0x59,0xfb,0xd1,0x4a,0x90,0x6f,0x61,0xbe,0x84,0xe9, 0x23,0x98,0x2e,0x61,0xbe,0x86,0xc3,0xa1,0x1,0xa8,0x56,0x82,0xac,0xc6,0x97,0x98, 0x20,0x24,0xc5,0x77,0x82,0x14,0x45,0xb2,0x58,0xe4,0x4b,0x13,0xa4,0x59,0x8d,0xc1, 0xa1,0x80,0x5b,0x2c,0xcd,0x28,0xd4,0x6c,0x25,0x49,0x4f,0xc1,0xef,0xac,0x25,0x15, 0xfb,0x3d,0x1f,0x60,0xd9,0xc3,0x7c,0xb,0x87,0x3d,0x4c,0x23,0xec,0x13,0x2c,0x5, 0x72,0x21,0xd4,0x6a,0x3e,0x6a,0x2,0x1f,0x20,0x34,0x10,0x2e,0xa,0x9a,0x15,0x49, 0xd,0xc4,0x8c,0x39,0xf7,0x1c,0x7b,0xd8,0x22,0xaf,0xad,0x2c,0x13,0xb8,0xeb,0xa6, 0x9,0x36,0xb,0x50,0xa,0xe4,0xc5,0xa2,0x9d,0x67,0x98,0x17,0x98,0x12,0xdc,0x54, 0x74,0xa9,0xb0,0x28,0xa1,0x2a,0xe4,0x6a,0x5d,0x2a,0xfe,0x34,0xd4,0xb8,0xa0,0x88, 0x37,0x39,0x96,0xd0,0xa4,0xd9,0x61,0xbd,0x2f,0x6b,0x87,0xa8,0xa5,0xaf,0x2b,0xe0, 0x17,0xf0,0xa3,0x9,0xd,0xbe,0x1,0xa8,0x66,0xa9,0xc0,0x92,0x61,0xae,0xe8,0x4d, 0x85,0x83,0xa2,0x53,0x85,0xd4,0x0,0xd4,0x6a,0x20,0xd4,0x81,0xf3,0x96,0x9,0x17, 0x40,0x82,0xe2,0xdb,0xe1,0x24,0xa2,0x96,0x72,0x1,0xb4,0x11,0xa7,0xe8,0x89,0x1b, 0x21,0x9b,0x44,0x4b,0xd3,0x72,0x15,0xbb,0x5f,0xc,0xa4,0x2e,0xa,0xb3,0xa2,0x57, 0x50,0x47,0x45,0xf,0x8a,0x24,0x25,0xac,0x2,0x94,0xab,0x9d,0x9e,0x22,0x6,0x42, 0x9c,0x59,0x27,0xd,0x84,0x34,0x10,0xb4,0x16,0x2d,0x15,0x92,0x83,0xae,0xb6,0x63, 0xbb,0x82,0x2f,0x27,0x29,0x56,0x39,0xb6,0xb1,0x66,0x60,0x11,0xea,0x35,0x94,0x5b, 0x25,0x8f,0x8a,0xce,0xe0,0xa,0x4,0xef,0xec,0x4b,0xa9,0x96,0x89,0x55,0x6,0xd6, 0x3d,0x14,0xe8,0x50,0xbc,0xa,0x6e,0x4d,0x7b,0x11,0x24,0x63,0xa8,0xe7,0x36,0x2f, 0x78,0x69,0x65,0xaa,0xc7,0xc5,0xda,0x3a,0x49,0x13,0xd4,0xbd,0x90,0xf6,0xca,0xb2, 0x37,0x19,0x20,0xb7,0x99,0xf6,0xf5,0xbf,0x20,0xff,0x78,0xd3,0x8e,0x80,0x54,0xac, 0xa4,0x75,0xe5,0x57,0xb3,0x8d,0x42,0xdf,0x94,0xd2,0x55,0xd3,0xc,0x5d,0x3b,0x24, 0x82,0xf8,0x76,0x52,0x3a,0x3b,0xd2,0x4d,0x84,0x4,0x55,0x41,0x93,0x50,0xe,0xb0, 0x8c,0xca,0xb4,0x87,0x79,0xf,0x65,0x56,0x3c,0xc2,0xab,0xbf,0x3d,0x48,0x0,0x8e, 0xb3,0xe7,0xa4,0xb0,0xa4,0x56,0x8e,0xa,0xa9,0xf1,0x27,0x65,0xd8,0x66,0xe8,0xb2, 0x12,0x93,0xe0,0x7b,0x3b,0xd8,0xa4,0x3,0xbc,0xa2,0x41,0x10,0xa7,0x68,0x2b,0x95, 0xaa,0x89,0x59,0x4d,0x90,0x17,0x65,0x9e,0xe0,0xd0,0xba,0x70,0x99,0xc0,0x57,0xe8, 0xe3,0xc7,0x66,0xc2,0xbf,0xbe,0x81,0xde,0x2c,0x30,0x66,0xcb,0x82,0xf3,0xf6,0xd0, 0x30,0xc0,0x6e,0x63,0xc7,0xf8,0x66,0x80,0x61,0x3,0xb1,0x17,0x1b,0x7,0xa2,0x20, 0xc1,0xba,0x7,0x27,0xa8,0x58,0xd4,0x55,0xa1,0x64,0x21,0x2d,0x30,0xcd,0xe6,0x78, 0x1c,0xcd,0xb9,0xa8,0x4d,0xf2,0x5f,0x7e,0x6f,0x79,0x76,0x22,0xda,0x78,0x48,0xde, 0xf4,0x21,0x15,0x23,0x76,0x2a,0x30,0x67,0x98,0x16,0x18,0xa7,0x6,0x60,0x84,0xbe, 0x57,0xba,0x5e,0x8,0x51,0xf1,0x41,0xc,0x80,0x80,0x8a,0x52,0xab,0x92,0x8b,0xb0, 0x24,0x98,0x67,0xe5,0x70,0x10,0xe,0x93,0x92,0x16,0xeb,0xe2,0x4d,0x14,0xe2,0x9d, 0x39,0xec,0x99,0x9,0xf5,0xef,0x6f,0xa0,0xfb,0x4,0xd7,0xb,0x4c,0x2d,0x13,0xb4, 0x1,0x28,0x86,0x36,0xa,0x46,0xe8,0x3a,0xfb,0x1e,0xa2,0xe0,0xbd,0x65,0xb,0x69, 0x91,0x57,0x48,0x59,0x58,0x92,0x32,0x2f,0x6,0xa4,0x14,0x9b,0xe4,0x76,0x9d,0xb0, 0xed,0xe1,0xeb,0xef,0x67,0x79,0x2e,0x0,0x80,0xf,0xbe,0x86,0x8e,0x9,0x8e,0xe5, 0xa8,0x6d,0x62,0x72,0x36,0x4,0x5,0xdf,0x26,0xb2,0x66,0xce,0x89,0x75,0x1e,0x50, 0x55,0x9a,0xf6,0x28,0x39,0xb,0xb5,0x1a,0x1f,0x3b,0x2f,0x9c,0xf5,0xb0,0xed,0x85, 0x6f,0xfe,0x39,0x3f,0xe3,0xf3,0xb9,0x2f,0x26,0x1f,0x7c,0x15,0x1d,0x33,0xdc,0x36, 0x10,0x4b,0x69,0x42,0xb5,0x2e,0x92,0x67,0x6d,0xdd,0x45,0xdb,0x0,0xa3,0x4d,0xad, 0x83,0xb7,0x94,0x9f,0xd,0xb0,0xed,0x84,0xb7,0x1e,0x95,0x17,0xbf,0x98,0xdc,0x2d, 0xc7,0x98,0xe0,0x90,0xed,0xec,0x98,0xf2,0xa9,0x4d,0xd7,0x16,0x3d,0xee,0xa0,0x27, 0x30,0xde,0x9,0xc1,0x41,0x1f,0x60,0xdb,0xc3,0x36,0xa,0xbb,0x1e,0xde,0x7c,0x54, 0x5f,0xfe,0xd5,0xec,0xee,0xe7,0xd1,0x57,0xd0,0xa9,0x49,0xf9,0x7a,0x4d,0xf5,0xa4, 0x11,0x77,0x33,0x12,0xda,0x3b,0xcb,0x10,0xa1,0xf,0x42,0x1f,0xe1,0x5b,0x7f,0xd3, 0x4f,0xf6,0x72,0xfa,0x3c,0x6e,0x4c,0xcd,0x79,0x69,0x0,0xb4,0xa5,0x5b,0x9a,0x8, 0x7a,0x81,0xe0,0x85,0x4d,0x84,0x6f,0xbc,0xc0,0xf1,0xfa,0xf9,0x1f,0xd6,0x53,0x87, 0x8a,0xab,0x7c,0xae,0xc2,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38, 0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61, 0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30, 0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x34,0x34,0x3a,0x35,0x33,0x2b,0x31,0x30, 0x3a,0x30,0x30,0x5d,0x65,0x38,0x85,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae, 0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/MultiplePagesHH.png 0x0,0x0,0x3,0xb0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0xbc,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x94,0xa3,0xb4,0x8e,0x9b,0xaa,0x80,0x8f,0x9d,0x7e,0x8e,0x9c, 0x7f,0x8e,0x9c,0x7f,0x8e,0x9d,0x78,0x88,0x97,0x95,0xa3,0xb4,0x88,0x96,0xa5,0x7f, 0x8e,0x9d,0x80,0x8f,0x9e,0x7f,0x8f,0x9d,0x80,0x8f,0x9d,0x78,0x88,0x97,0x5d,0x6f, 0x80,0xb9,0xc3,0xd1,0xd0,0xd7,0xe1,0xcf,0xd6,0xe0,0xce,0xd5,0xe0,0xcd,0xd4,0xdf, 0xcc,0xd3,0xde,0xcb,0xd3,0xde,0xca,0xd2,0xde,0xc2,0xcb,0xd7,0xec,0xf0,0xf9,0xd9, 0xe0,0xed,0xda,0xe0,0xec,0xd7,0xde,0xea,0xd5,0xdb,0xe8,0xcf,0xd6,0xe2,0xd5,0xdb, 0xe7,0xda,0xe1,0xed,0xce,0xd5,0xe2,0xd8,0xde,0xea,0xe4,0xe8,0xef,0xd0,0xd6,0xe0, 0xe3,0xe7,0xf3,0xd9,0xdf,0xeb,0xf1,0xf3,0xf7,0xea,0xed,0xf2,0xeb,0xee,0xf3,0xdd, 0xe1,0xe8,0xac,0xb6,0xc7,0xdb,0xe0,0xec,0xb3,0xbd,0xcc,0xe0,0xe4,0xec,0xe1,0xe6, 0xf0,0xdb,0xe1,0xeb,0xd7,0xdd,0xe6,0xdc,0xe2,0xea,0xe2,0xe5,0xed,0xa9,0xb4,0xc4, 0xdd,0xe2,0xed,0xb1,0xbb,0xc9,0xde,0xe3,0xea,0xce,0xd5,0xdf,0xde,0xe4,0xed,0xd7, 0xdd,0xea,0xe8,0xeb,0xf4,0xd5,0xdc,0xe6,0xda,0xe1,0xeb,0xdf,0xe2,0xed,0xa7,0xb2, 0xc3,0xd8,0xde,0xeb,0xde,0xe2,0xed,0xb0,0xb9,0xc8,0xdd,0xe2,0xe9,0xc9,0xd1,0xe0, 0xd8,0xdc,0xe9,0xc7,0xcf,0xdc,0xcb,0xd2,0xe0,0xcb,0xd0,0xe0,0xa2,0xae,0xbe,0xca, 0xd2,0xe1,0xab,0xb6,0xc4,0xdc,0xe1,0xe8,0xcc,0xd4,0xdf,0xd6,0xdf,0xea,0xb2,0xc1, 0xd2,0xa7,0xb4,0xc6,0x9f,0xad,0xc0,0x9e,0xac,0xbf,0x99,0xa8,0xbb,0xae,0xbc,0xcc, 0xb4,0xc2,0xd3,0x99,0xa7,0xbb,0xb3,0xc0,0xd0,0xd6,0xdd,0xe6,0xd0,0xdb,0xe9,0xcc, 0xd5,0xe4,0xdc,0xe2,0xec,0xd9,0xe0,0xea,0xd6,0xdd,0xe8,0xc8,0xd0,0xdc,0xad,0xba, 0xcc,0xcd,0xd6,0xe5,0xaf,0xbd,0xce,0xd2,0xda,0xe4,0xd1,0xdc,0xe9,0xf1,0xf4,0xf7, 0xe2,0xe7,0xed,0xe6,0xeb,0xf0,0xe5,0xe8,0xee,0xa1,0xaf,0xc0,0xa6,0xb4,0xc4,0xd4, 0xdc,0xe5,0xc9,0xd1,0xdd,0xd5,0xdf,0xeb,0xe9,0xec,0xf3,0xd5,0xdc,0xe5,0xda,0xe1, 0xea,0xe0,0xe3,0xed,0xa3,0xb0,0xc1,0xdf,0xe3,0xed,0xa9,0xb6,0xc6,0xd7,0xde,0xe7, 0xca,0xd2,0xdd,0xd9,0xe2,0xed,0xd3,0xda,0xe8,0xe7,0xea,0xf4,0xd4,0xdc,0xe7,0xd9, 0xe0,0xeb,0xde,0xe1,0xed,0xa3,0xb1,0xc2,0xd5,0xdc,0xea,0xdd,0xe0,0xed,0xac,0xb8, 0xc8,0xda,0xe1,0xe9,0xde,0xe6,0xef,0xba,0xc6,0xd6,0xb9,0xc2,0xd1,0xad,0xb8,0xc8, 0xae,0xb8,0xc9,0xaa,0xb3,0xc5,0xa5,0xb2,0xc3,0xbc,0xc7,0xd7,0xa9,0xb3,0xc5,0xae, 0xba,0xc9,0xdd,0xe3,0xeb,0xdf,0xe5,0xeb,0xd3,0xda,0xe2,0xcd,0xd5,0xdd,0xcb,0xd3, 0xdb,0xd3,0xdb,0xe2,0xd5,0xdc,0xe4,0xd1,0xd8,0xde,0xff,0xff,0xff,0x0,0xa9,0xdd, 0xa6,0x0,0x0,0x0,0x10,0x74,0x52,0x4e,0x53,0x0,0x8f,0x8f,0x8f,0x8f,0x8f,0x8f, 0x8f,0x7f,0x7f,0x7f,0x7f,0x7f,0x7f,0x81,0x48,0xd6,0xbb,0x1f,0xea,0x0,0x0,0x0, 0x1,0x62,0x4b,0x47,0x44,0x93,0xe1,0x3,0xdf,0xb6,0x0,0x0,0x0,0xdb,0x49,0x44, 0x41,0x54,0x18,0xd3,0x63,0x10,0x10,0x14,0x12,0x16,0x11,0x15,0x13,0x13,0x7,0x2, 0x31,0x31,0x9,0x46,0x6,0x41,0x49,0x29,0x69,0x19,0x59,0x39,0x79,0x5,0x20,0xa9, 0xa8,0xa4,0xcc,0xc4,0xa0,0xa2,0xaa,0xa6,0xae,0xa1,0xa9,0xa5,0xad,0x3,0x22,0x75, 0xf5,0x98,0x19,0x84,0xf4,0xd,0x34,0xd,0x8d,0x8c,0x4d,0x4c,0x41,0xa4,0x99,0x39, 0xb,0x83,0x85,0xa5,0x95,0xb5,0x8d,0xad,0x9d,0xbd,0x3,0x90,0x74,0x74,0x72,0x6, 0xa,0x18,0xb9,0xb8,0xba,0xb9,0x7b,0x78,0x7a,0x81,0x48,0x6f,0x1f,0x16,0x6,0x5f, 0x3f,0xff,0x80,0xc0,0xa0,0xe0,0x90,0x50,0x20,0x19,0x16,0x1e,0xc1,0xca,0x20,0x16, 0x19,0x15,0x1d,0x13,0x1b,0x17,0x9f,0x0,0x22,0x13,0x93,0xd8,0x18,0xc4,0x93,0x6d, 0x53,0x52,0xd3,0xd2,0x33,0xa2,0x41,0x64,0x66,0x16,0x1b,0x43,0x76,0x8e,0x55,0x6e, 0x5e,0x7e,0x41,0xa1,0x1a,0x90,0x2c,0x2a,0x2e,0x61,0x65,0x28,0x2d,0x2b,0xaf,0xa8, 0xac,0xaa,0xae,0xa9,0x5,0x92,0x75,0xf5,0xd,0x40,0x81,0xc6,0xa6,0xe6,0x96,0xd6, 0xb6,0xf6,0xe,0x20,0xd9,0xd9,0xd5,0xcd,0xc2,0x20,0xd1,0xd3,0xdb,0xd7,0xdf,0xdf, 0x3f,0x61,0x2,0x88,0x9c,0x38,0x89,0x9d,0x81,0x83,0x93,0x8b,0x1b,0x8,0x78,0x78, 0x40,0x24,0x2f,0x1f,0x3f,0x3,0x41,0x0,0x0,0x3e,0xeb,0x3c,0xf8,0x3c,0xc9,0xfe, 0xa5,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72, 0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54, 0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c, 0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d, 0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39, 0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3, 0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_CreateAdditiveBrush.png 0x0,0x0,0x8,0x2f, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x7,0x24,0x49,0x44,0x41,0x54,0x58,0xc3,0xc5,0x97,0x5b,0x88,0x5e,0x57, 0x15,0xc7,0x7f,0x6b,0x5f,0xce,0x77,0x9b,0xfb,0x64,0x26,0xd3,0x49,0x9b,0x76,0x62, 0xda,0xa6,0x89,0x16,0x11,0x94,0x42,0x55,0x9a,0xb6,0x20,0x96,0x86,0x52,0xa9,0x52, 0x10,0x44,0xf1,0xc1,0x7,0x85,0x3e,0x94,0x8a,0xef,0x95,0xa,0x5a,0x7d,0xf0,0x82, 0xa,0xc5,0x40,0x7d,0x51,0x42,0x91,0xa0,0x68,0x10,0xb5,0xa9,0x28,0x15,0xdb,0x42, 0x7a,0x89,0xb1,0x4d,0x4c,0x83,0x6d,0x66,0x9a,0x99,0xdc,0x66,0xe6,0xbb,0x9d,0xef, 0x9c,0xbd,0x96,0xf,0xe7,0x33,0x9a,0xe4,0x43,0xda,0x17,0xb3,0xe0,0x70,0x2e,0x9c, 0xbd,0xd7,0xff,0xfc,0xd7,0x7f,0xfd,0xcf,0xde,0x62,0x66,0xc6,0x35,0xc,0x77,0x2d, 0x93,0x3,0x84,0xff,0xbe,0x59,0x7c,0x7a,0xcf,0xff,0x2d,0xf1,0xf2,0xe7,0x8e,0x5e, 0xd,0xe0,0xdd,0xc4,0x67,0xb7,0x3f,0x8c,0x76,0x2,0xa5,0x95,0x14,0x9a,0xd0,0x64, 0x24,0x55,0x52,0x69,0x1c,0xca,0x7f,0xf1,0xae,0xe7,0xb9,0xeb,0x7,0x5f,0xe0,0xf0, 0x97,0xf7,0x5f,0xe,0xe0,0xdf,0xa8,0xae,0x8c,0xc7,0xe,0x3f,0x8e,0xe4,0x19,0x6a, 0x8a,0x76,0x85,0x7f,0xea,0x49,0xce,0xcd,0x1c,0x67,0x69,0x47,0x8d,0xb7,0x4f,0xf7, 0x28,0xdf,0x99,0x64,0x4e,0x6e,0x62,0x5f,0xf6,0x10,0xd1,0x79,0xbc,0x4,0x6a,0x52, 0xe3,0x9b,0xfb,0x1e,0x1d,0x39,0xdf,0xe2,0xd3,0x7b,0xc8,0x7c,0xf8,0xdf,0xc,0x3c, 0x76,0xf8,0x71,0x8a,0xdc,0x28,0x7,0x95,0x46,0x3b,0xe9,0x2c,0x6f,0x4f,0xbd,0xca, 0xe2,0x4e,0xb8,0x75,0x61,0x1c,0xd8,0x42,0xb7,0x5f,0x30,0x76,0x73,0x46,0xb1,0x43, 0xb9,0xb0,0x79,0x94,0xe3,0x6b,0x3d,0x74,0x75,0x82,0x99,0xfc,0x6,0xb6,0xc7,0x9b, 0xf8,0xda,0xa1,0x6f,0xe3,0xf0,0xa0,0xc2,0x13,0xf7,0x3d,0x72,0xd9,0xfc,0xde,0xfb, 0xd1,0x0,0x1e,0x3b,0xfc,0x38,0x17,0xd7,0xfb,0x14,0x83,0x92,0x81,0x96,0xac,0xb6, 0x4e,0x30,0xb9,0xb3,0xc3,0xed,0xb7,0x6e,0x61,0x49,0xa6,0x30,0x60,0x50,0x24,0x8a, 0x32,0x81,0x81,0xaa,0x51,0x94,0x89,0x5a,0xc,0x5c,0x37,0xdf,0xa4,0x3f,0xd5,0x67, 0x50,0xfc,0x9d,0x23,0xed,0x57,0x28,0xcf,0x8f,0x31,0x9b,0x5f,0xcf,0xa2,0x6c,0xe7, 0xd1,0x83,0xdf,0x62,0x90,0xa,0xfa,0x45,0x3e,0x4c,0x3c,0x2,0xc0,0x83,0x3f,0x79, 0x4,0xf1,0xc6,0x46,0x73,0x5,0xb7,0xb4,0xc6,0x7,0x6e,0x9b,0x66,0x57,0xab,0x1, 0x34,0x9,0x96,0xd1,0xd2,0x49,0xea,0x8c,0x51,0x93,0x16,0x59,0x68,0x80,0x38,0x7a, 0xbe,0x4f,0xc7,0x75,0x68,0x4b,0x87,0xd,0x3a,0x9c,0xd7,0x8b,0xac,0xa7,0x75,0xb4, 0x9,0xd6,0xcc,0xc9,0xed,0x4,0xc7,0xfa,0xc7,0xe8,0x6c,0x40,0xb9,0x16,0x19,0x9c, 0x17,0x3e,0xde,0xfa,0x24,0x1d,0xe9,0x5d,0xd,0x60,0x40,0xce,0xae,0x87,0xce,0x30, 0xdd,0x6a,0xa2,0x2c,0x0,0x30,0xc9,0x3c,0x3b,0xf9,0x20,0xd,0x5a,0xa8,0x94,0x14, 0x56,0x92,0x5c,0x49,0xa1,0x5,0xb9,0x1b,0x10,0x2d,0xd2,0xf2,0x63,0xc4,0xd8,0x60, 0x5c,0xa6,0x99,0xf3,0x8b,0xf4,0x63,0x9f,0xcd,0xa2,0xcd,0x4a,0x7f,0x99,0xb5,0xfc, 0x1d,0x26,0xb2,0x3a,0xef,0x5b,0xdc,0xc2,0xc5,0xf1,0x2e,0x2f,0xf9,0xe3,0xc,0x36, 0x4b,0x74,0x68,0x3f,0x97,0x1,0xc8,0xcb,0x1,0xc7,0xdf,0x3a,0xc7,0xe7,0xaf,0x7f, 0x80,0xc9,0x66,0x83,0xb6,0xbb,0x40,0x20,0x52,0xa7,0x81,0x4a,0x42,0x4d,0x41,0xc, 0xc,0xc,0x43,0x0,0x11,0xaa,0x67,0x92,0x30,0xa7,0xa0,0x89,0x28,0x81,0x29,0x37, 0x81,0xf7,0xc2,0xb6,0xfa,0x22,0x1b,0xed,0x9c,0x17,0x4f,0xfc,0x8d,0x93,0xab,0x2b, 0x94,0x2e,0xd1,0x93,0x3e,0x29,0xa5,0xab,0x1,0x94,0x29,0xb1,0x7a,0xa1,0xc3,0x37, 0xce,0x7e,0x8f,0xdb,0x27,0x6f,0xe7,0x13,0x8b,0x7b,0xd9,0x31,0xbe,0x8b,0xb6,0x3f, 0xc7,0xa6,0x3f,0x4b,0x29,0x5,0x98,0x54,0xc9,0x1d,0x38,0x4,0x67,0xe0,0x9d,0xc3, 0x3b,0x4f,0x52,0xc3,0x34,0x11,0xc4,0x33,0x25,0xd7,0xd1,0x2c,0x67,0xf9,0xc3,0x89, 0xe7,0xf9,0xd3,0xa9,0x17,0xe8,0xd1,0xc5,0x65,0x9e,0xe0,0x23,0xdd,0x7e,0x1f,0x1b, 0xc5,0xc0,0x20,0x15,0xd4,0xb3,0x40,0x5e,0x24,0x5e,0x5e,0x3f,0xc2,0xb,0x67,0x5f, 0x62,0xd6,0xcd,0xf3,0xe0,0xf6,0x7d,0xdc,0x3b,0x7f,0xf,0xad,0xac,0xce,0x6a,0x38, 0xc9,0x8a,0xfb,0x7,0x1,0x87,0x9a,0xe0,0x9c,0xc3,0xa9,0x82,0x4b,0x2c,0x84,0xad, 0x6c,0xb,0xb7,0xb2,0xbe,0xd1,0xe1,0xc0,0xd1,0x5f,0x72,0xf0,0xe8,0x21,0xda,0xd2, 0x46,0xa2,0xe1,0x32,0x87,0xc5,0x12,0xf5,0xd0,0xce,0xbb,0x8,0x32,0xba,0x4,0x63, 0x31,0x20,0x8,0x4e,0xaa,0x17,0xce,0xe,0xce,0xf0,0xc3,0xd7,0x9f,0xe2,0xfb,0xaf, 0x3d,0xc5,0xdd,0x73,0x7b,0x79,0x68,0xe9,0x1,0xee,0x98,0xfe,0x14,0x67,0x59,0x66, 0xd9,0xbd,0xc1,0xb9,0x78,0x9a,0x1b,0xdd,0x4e,0x16,0x8b,0x5b,0x58,0x6b,0x5f,0x60, 0xff,0x5f,0x7f,0xce,0x4f,0x8f,0x1c,0xa0,0x74,0x39,0x12,0x41,0xea,0x6,0x11,0x34, 0x26,0x24,0x2,0x4e,0x69,0xe7,0x5d,0xbc,0x73,0x57,0x3,0x28,0xb4,0x20,0x8b,0xbe, 0xaa,0xab,0x3,0x35,0x43,0xd5,0x30,0x53,0xcc,0x8c,0xdf,0xaf,0x3e,0xcb,0x6f,0x4f, 0x3f,0xcb,0x54,0x98,0xe2,0xe1,0xa5,0x4f,0x73,0xdf,0x8d,0xf7,0xb0,0x45,0x6e,0x66, 0xbd,0xb3,0xce,0x57,0x9f,0xfb,0x3a,0x7,0x5f,0x39,0x84,0x78,0x90,0x68,0x88,0x7, 0x32,0xc3,0xa2,0x41,0x34,0x2c,0x26,0x42,0xcd,0x33,0x55,0x9f,0x64,0x33,0xef,0x10, 0xdc,0x88,0x36,0x34,0x83,0x5a,0xc,0x88,0x48,0x45,0x91,0x82,0x99,0xa1,0x66,0x58, 0x2,0x4b,0x86,0x79,0x68,0xa7,0xe,0x3f,0x7b,0xf3,0x19,0xe,0x9e,0xfa,0x35,0x7, 0xee,0xde,0xcf,0x87,0xbe,0xbb,0x17,0x44,0x10,0x27,0x88,0x17,0x70,0x6,0xc1,0xb0, 0x90,0x20,0x24,0xac,0x66,0xd4,0x6a,0x81,0x85,0xb1,0x39,0x6a,0xb1,0xc1,0x72,0x91, 0xe3,0x65,0x4,0x3,0xce,0xb9,0x4b,0xc,0x88,0x54,0x4a,0x37,0x6c,0xc8,0x44,0x42, 0xcc,0xb1,0xa5,0x36,0xcd,0xa4,0x9b,0xc1,0xab,0x47,0x4d,0x50,0x14,0x17,0x1c,0x20, 0x98,0x4f,0x10,0x64,0xf8,0xe5,0x25,0x64,0x9,0x32,0xa5,0x96,0x45,0x16,0x27,0x16, 0xa8,0xd7,0x32,0x92,0x25,0x6,0xe5,0x0,0x91,0x11,0x1a,0x8,0xde,0x51,0xcb,0x2, 0xce,0xfd,0x47,0x3,0x36,0x74,0xbb,0x60,0x19,0x73,0x8d,0x5,0x62,0xaa,0x53,0x16, 0x46,0xc2,0x20,0x19,0x79,0x1a,0xe0,0xc2,0xb0,0x33,0xbc,0xc3,0x32,0x85,0xe1,0x61, 0x31,0xe1,0x6a,0x30,0x37,0x36,0x43,0x2d,0x8b,0xe0,0x14,0x7,0x14,0x9a,0x86,0x12, 0xbc,0x2,0x40,0x2d,0x44,0xea,0x31,0xe0,0x9d,0x54,0x22,0x11,0xc0,0x20,0x4a,0xc6, 0x6c,0xed,0x3a,0x2c,0x79,0xfa,0x79,0x81,0xd3,0x4a,0x1f,0x62,0x95,0x6e,0x5c,0x4, 0x73,0x82,0xf9,0xaa,0xd6,0x64,0x8a,0x65,0x9,0xc9,0x12,0xd3,0xcd,0x29,0x26,0xea, 0x63,0xe0,0xb5,0xd2,0x5,0x50,0x6a,0x39,0xba,0xb,0x5a,0xb1,0x41,0x2d,0xcb,0x71, 0x49,0xf0,0x4e,0x11,0xc0,0x8b,0x67,0x36,0xdb,0x86,0x2b,0x33,0x36,0xf3,0x1e,0x31, 0x39,0x50,0x5,0xb,0x24,0x53,0x72,0xcd,0x71,0x99,0x43,0x25,0x41,0x50,0x24,0x33, 0x34,0x2b,0xa1,0x36,0x14,0x5d,0x63,0x12,0x7c,0xe5,0x1b,0x78,0x2e,0xe9,0x8a,0x51, 0xc,0x34,0xb3,0x3a,0xf5,0x5a,0x20,0x94,0x42,0xe1,0x15,0x80,0x19,0x3f,0xc3,0x84, 0x4e,0xd3,0xee,0xf5,0xa8,0x85,0x80,0x26,0xc3,0xb4,0xaa,0x8d,0x98,0xa7,0x97,0x7a, 0xb8,0xac,0xb2,0xc4,0x14,0x12,0x64,0x9,0x89,0x9,0xc9,0x8c,0x66,0xa3,0x41,0x3d, 0xd6,0x30,0x6f,0xe0,0xc0,0xe3,0x30,0x37,0x2c,0x2d,0x23,0x8c,0xa8,0x1e,0x6b,0x64, 0xd1,0xe3,0x44,0x70,0x92,0xf0,0x16,0xd9,0xaa,0x5b,0x29,0xb,0xa8,0xc7,0x48,0x52, 0x43,0xb5,0x22,0x40,0x4c,0x48,0x18,0x9d,0xb2,0x8b,0x8b,0x80,0x80,0x65,0x52,0xb5, 0x5d,0x26,0x48,0x30,0xc6,0xb3,0x56,0x25,0x50,0x67,0x38,0x57,0x75,0x89,0x5e,0xb1, 0x2,0xbd,0xc,0x40,0x16,0xb3,0xaa,0xf6,0xbe,0xaa,0xf1,0x94,0x4e,0xd1,0x92,0x16, 0x5d,0xed,0x93,0x42,0xa0,0x48,0x5a,0xd9,0x6d,0x12,0xa,0x53,0x92,0xc1,0x66,0xb9, 0x89,0x8b,0xe,0x73,0x8a,0x64,0x20,0x41,0x90,0x0,0x2e,0xa,0xf5,0x58,0x27,0xf8, 0x4a,0x4b,0x4e,0x2a,0xd7,0xac,0xd8,0x4f,0xa3,0x1,0xb8,0x21,0x3a,0x19,0x76,0xc1, 0xb8,0x9f,0x22,0xe2,0x89,0x2e,0x50,0x7a,0xa5,0x1e,0xc1,0x54,0x40,0x1d,0x8e,0x44, 0x69,0xb0,0x59,0x6e,0x54,0x22,0xf4,0x60,0x1,0x2c,0x2,0xb1,0x12,0x64,0x33,0x34, 0x88,0x2e,0x62,0x52,0x31,0x10,0x5d,0x64,0x50,0x96,0xc0,0x0,0xc2,0xca,0xd5,0x0, 0x52,0x69,0x3c,0xff,0xdc,0x79,0x76,0xec,0xa9,0x31,0x37,0xd3,0xa4,0x69,0x4d,0x44, 0x85,0xe8,0x2,0xea,0xab,0xc4,0x16,0x4,0xd4,0x23,0x5a,0xe0,0x3,0x74,0xb5,0x4b, 0xc8,0x3c,0x26,0x9,0xf3,0x82,0x5,0x87,0x7a,0xc5,0x79,0x68,0x84,0x6,0xc1,0x39, 0x70,0x82,0x6a,0xe2,0x8d,0xe5,0x15,0xd6,0x8e,0xe5,0x88,0x8f,0xd8,0x28,0x6,0x4a, 0xbb,0x40,0xfd,0xe4,0x56,0x5e,0x7f,0xbd,0xc3,0x8b,0xe3,0x2b,0xdc,0xf9,0xe1,0x71, 0xde,0xbf,0x6d,0x89,0x9a,0x77,0xa8,0xe,0x50,0xb5,0xca,0x68,0x34,0xe1,0xd4,0x33, 0x30,0x65,0x60,0x39,0x2e,0x54,0xeb,0x7b,0xb,0x43,0x7,0x13,0x41,0x44,0x88,0x21, 0x92,0xb4,0xe4,0xf8,0xdb,0xa7,0xb9,0x78,0xa2,0x44,0x57,0x43,0xd5,0x1,0xd2,0xbd, 0x94,0x53,0x46,0x6d,0x4c,0xf6,0xfe,0xf8,0x7e,0x7a,0x83,0x92,0x7e,0x1a,0x20,0x99, 0x70,0xc3,0xee,0x49,0x3e,0x7a,0xdb,0x6e,0xc6,0x62,0x8b,0xce,0xa0,0xcf,0x60,0xa0, 0x94,0x85,0x31,0x28,0x12,0x5b,0xfc,0x56,0x9e,0x7c,0xed,0x49,0xa,0x4a,0x4a,0x97, 0xa3,0xa1,0x44,0x7d,0x41,0x29,0xca,0x78,0x6f,0x9e,0xf2,0xad,0x3a,0x69,0xcd,0x28, 0xca,0x9c,0x42,0x73,0xd4,0x94,0xf9,0x3d,0xb,0xbc,0x73,0xc4,0xa1,0xdf,0x79,0x75, 0xf4,0xa2,0xf4,0xd9,0x2f,0xfd,0xa,0x80,0x3b,0xbe,0x7f,0x2f,0x69,0x60,0x2c,0xbf, 0xdc,0xe1,0xc0,0xcb,0x2f,0x31,0x75,0x63,0x9d,0xdd,0xb7,0x2c,0xb2,0x63,0xea,0x7a, 0x72,0x53,0x9c,0x96,0x80,0xe1,0x83,0x43,0xd5,0x91,0xc4,0x21,0x29,0x32,0xde,0x99, 0x67,0x62,0x63,0x16,0x77,0xa1,0x4e,0xbb,0x38,0x4f,0xd7,0x77,0x51,0x83,0xce,0x13, 0x6b,0x8c,0xfd,0x51,0xe0,0xd4,0xc2,0x68,0x11,0x5e,0x19,0x7f,0xf9,0xca,0xef,0x2e, 0x5d,0xdf,0xf5,0xa3,0xfb,0xd1,0x33,0x9e,0x63,0x6b,0xe7,0x79,0xa3,0x71,0x81,0xf9, 0x9b,0x5a,0xec,0x5a,0x58,0xa2,0xb4,0x84,0x77,0xe,0x29,0x5a,0xcc,0xe5,0xdb,0x99, 0x29,0x67,0xc9,0x7a,0x4d,0xba,0x65,0x9b,0x4e,0x6c,0x13,0x35,0xd2,0xbb,0xf3,0x4d, 0x80,0x2a,0xf9,0x15,0x21,0xef,0x75,0x6f,0xb8,0x6f,0xff,0x67,0xf0,0xd2,0xc0,0x3b, 0x8f,0xf7,0x19,0x36,0xd1,0x63,0x65,0xe3,0xc,0xb3,0x32,0x4b,0x2d,0xb5,0x28,0xad, 0x47,0xaf,0xe8,0xf2,0x9b,0x2f,0x3e,0x73,0x69,0xcc,0xd8,0x73,0xc3,0xc4,0xc3,0xd3, 0xc4,0xa9,0xdd,0x97,0x4a,0x70,0x19,0x80,0xf7,0xb2,0x35,0xfb,0x98,0xff,0x8,0x82, 0xab,0x7e,0x5a,0xe6,0x50,0x4a,0x92,0x26,0xfe,0x6c,0x2f,0xbe,0xab,0xf1,0x23,0x1, 0x5c,0x8b,0xb8,0xe6,0xbb,0xe3,0x7f,0x1,0x96,0x75,0x7c,0x7b,0xf1,0x35,0xc0,0xbb, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff, 0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54, 0x32,0x32,0x3a,0x34,0x36,0x3a,0x32,0x38,0x2b,0x31,0x30,0x3a,0x30,0x30,0x51,0x52, 0xb5,0x5b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_Select.png 0x0,0x0,0x2,0x9, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x87,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xb9,0xae,0x51,0xa9,0xa0,0x51,0xfb,0xe9,0x4f,0xac,0xa3,0x51, 0xad,0xa5,0x51,0xfc,0xe9,0x4f,0xb0,0xa7,0x51,0xf5,0xe3,0x50,0xee,0xdd,0x50,0xc7, 0xbb,0x50,0xd1,0xc4,0x50,0xb4,0xab,0x51,0x60,0x60,0x60,0x78,0x78,0x78,0x79,0x79, 0x79,0x64,0x64,0x64,0x5a,0x5a,0x5a,0x50,0x50,0x50,0x95,0x95,0x95,0xc9,0xc9,0xc9, 0xbb,0xbb,0xbb,0x89,0x89,0x89,0x59,0x59,0x59,0x68,0x68,0x68,0xe4,0xe4,0xe4,0xe6, 0xe6,0xe6,0x8b,0x8b,0x8b,0x5b,0x5b,0x5b,0x5e,0x5e,0x5e,0xb5,0xb5,0xb5,0xc7,0xc7, 0xc7,0xd1,0xd1,0xd1,0x85,0x85,0x85,0x58,0x58,0x58,0x61,0x61,0x61,0xc1,0xc1,0xc1, 0xdb,0xdb,0xdb,0x5d,0x5d,0x5d,0xcc,0xcc,0xcc,0x7f,0x7f,0x7f,0x62,0x62,0x62,0x94, 0x94,0x94,0x5f,0x5f,0x5f,0xff,0xff,0xff,0x17,0xe,0x97,0x91,0x0,0x0,0x0,0x1, 0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47, 0x44,0x2c,0xba,0xdd,0x71,0xab,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0, 0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x63,0x49, 0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x64,0x62,0x66,0x61,0x66,0x65,0x63,0x67,0x63, 0x61,0x80,0x0,0xe,0x36,0x28,0xe0,0x84,0xa,0xb0,0xc0,0x4,0xd8,0xa9,0xa8,0x82, 0x91,0x8b,0x1b,0x2,0x79,0x18,0x50,0x1,0x2f,0x1f,0xbf,0x80,0xa0,0x10,0x92,0x80, 0xa0,0xb0,0x88,0xa8,0x98,0x38,0x92,0x80,0x90,0x84,0xa4,0x94,0xb4,0xc,0xb2,0x1e, 0x59,0x39,0x79,0x5,0x45,0x64,0x3d,0x42,0x4a,0xca,0x2a,0xaa,0x8a,0x6a,0xc8,0xa6, 0x8,0xf1,0xab,0xa8,0x6b,0xa0,0xd8,0x24,0xa4,0xa9,0xa5,0x8d,0x6a,0xb7,0x90,0xac, 0x10,0x0,0xaa,0xac,0x6,0x74,0xc9,0x4b,0x9b,0xcc,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30, 0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30, 0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32, 0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x32,0x37,0x3a, 0x35,0x34,0x2b,0x31,0x30,0x3a,0x30,0x30,0x9b,0x40,0x77,0x4b,0x0,0x0,0x0,0x0, 0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/FullScreenHH.png 0x0,0x0,0x4,0x8b, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x2,0x52,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x96,0xa7,0xbc,0x98,0xa9,0xbf,0x99,0xaa,0xc0,0x9c,0xac,0xc1, 0x94,0xa6,0xbc,0x98,0xa8,0xbe,0x90,0xa1,0xb9,0x8d,0x9e,0xb6,0x8f,0x9f,0xb7,0x88, 0x9a,0xb2,0x8b,0x9b,0xb4,0x91,0xa1,0xb8,0x8d,0x9e,0xb5,0x86,0x97,0xae,0x64,0x77, 0x8c,0xba,0xc4,0xd2,0xd9,0xdf,0xe8,0xd1,0xd8,0xe3,0xc2,0xcc,0xda,0xd6,0xdc,0xe6, 0xcd,0xd5,0xe1,0xbf,0xc9,0xd8,0xd1,0xd9,0xe4,0xc7,0xd0,0xde,0xb9,0xc4,0xd4,0xcc, 0xd4,0xe1,0xc4,0xcd,0xdc,0xb8,0xc3,0xd4,0xcb,0xd4,0xe2,0xbb,0xc5,0xd4,0x71,0x83, 0x95,0x72,0x83,0x96,0x74,0x85,0x97,0x70,0x82,0x95,0x66,0x7a,0x8f,0x5c,0x70,0x86, 0x59,0x6c,0x84,0x5a,0x6c,0x85,0x59,0x6c,0x85,0x58,0x6b,0x85,0x58,0x6a,0x85,0x5a, 0x6d,0x85,0x99,0xa7,0xb8,0x8f,0x9d,0xac,0x7e,0x8d,0x9d,0x75,0x86,0x97,0x73,0x85, 0x99,0x61,0x75,0x8a,0x5a,0x6e,0x84,0x5b,0x6d,0x85,0x5a,0x6c,0x85,0x59,0x6c,0x85, 0x59,0x6b,0x85,0x58,0x6b,0x85,0x58,0x6a,0x85,0x5b,0x6d,0x86,0x5b,0x6e,0x82,0xbc, 0xc5,0xd3,0xdd,0xe2,0xea,0xd4,0xdb,0xe5,0xc4,0xce,0xdb,0xd9,0xdf,0xe9,0xd0,0xd7, 0xe3,0xc1,0xca,0xd9,0xd5,0xdc,0xe7,0xcc,0xd4,0xe1,0xbd,0xc7,0xd7,0xd1,0xd8,0xe4, 0xc8,0xd1,0xdf,0xbb,0xc5,0xd6,0xcf,0xd7,0xe4,0xbe,0xc8,0xd6,0xc1,0xca,0xd7,0xe7, 0xeb,0xf1,0xca,0xd3,0xdf,0xe4,0xe8,0xf0,0xdb,0xe0,0xea,0xc8,0xd1,0xde,0xe1,0xe6, 0xef,0xd6,0xdd,0xe8,0xc3,0xcd,0xdc,0xdc,0xe2,0xec,0xd2,0xd9,0xe6,0xc0,0xcb,0xda, 0xd8,0xdf,0xeb,0xc6,0xcf,0xdc,0xbb,0xc5,0xd3,0xd4,0xda,0xe5,0xcc,0xd5,0xe1,0xd8, 0xdf,0xe8,0xde,0xe4,0xeb,0xe0,0xe6,0xec,0xde,0xe3,0xea,0xd8,0xdf,0xe7,0xd9,0xe0, 0xe9,0xd4,0xdc,0xe7,0xcd,0xd6,0xe4,0xcc,0xd5,0xe4,0xb4,0xc0,0xd1,0xcf,0xd7,0xe2, 0xef,0xf2,0xf7,0xcc,0xd7,0xf0,0xc8,0xd4,0xef,0xc6,0xd3,0xef,0xc4,0xd2,0xef,0xc1, 0xd0,0xee,0xbe,0xcd,0xee,0xb7,0xc9,0xec,0xb0,0xc5,0xef,0xc5,0xd2,0xe9,0xcb,0xd3, 0xdf,0xd3,0xdb,0xe5,0xe5,0xeb,0xf4,0xb1,0xc4,0xec,0xcd,0xdb,0xf9,0xc9,0xd8,0xf7, 0xb9,0xcc,0xf4,0xa9,0xc0,0xf0,0x9d,0xb6,0xeb,0x90,0xab,0xe6,0x74,0x99,0xe6,0xb6, 0xc8,0xe8,0xcc,0xd5,0xe0,0xe5,0xea,0xf4,0xba,0xcb,0xee,0xe1,0xea,0xfe,0xdd,0xe8, 0xfd,0xca,0xd9,0xf9,0xb8,0xcb,0xf4,0xab,0xc0,0xef,0x9f,0xb5,0xe9,0x7a,0x9e,0xe8, 0xb1,0xc5,0xe8,0xd3,0xda,0xe5,0xe4,0xe9,0xf3,0xb8,0xc9,0xed,0xdc,0xe6,0xfc,0xd8, 0xe3,0xfb,0xc3,0xd3,0xf7,0xb8,0xca,0xf3,0xa5,0xb9,0xea,0x7a,0x9d,0xe7,0xae,0xc2, 0xe8,0xe7,0xea,0xf1,0xdc,0xe2,0xea,0xce,0xd6,0xe1,0xe1,0xe7,0xf3,0xa8,0xbe,0xea, 0xc3,0xd5,0xf9,0xbc,0xcf,0xf8,0xb0,0xc6,0xf6,0xa4,0xbd,0xf2,0x93,0xae,0xec,0x72, 0x91,0xdd,0x5a,0x85,0xde,0xac,0xc2,0xe9,0xba,0xc4,0xd3,0xdc,0xe1,0xea,0xd3,0xda, 0xe4,0xc3,0xcd,0xdb,0xdd,0xe5,0xf2,0x9a,0xb3,0xe6,0x9e,0xb8,0xf0,0x93,0xaf,0xed, 0x84,0xa3,0xe7,0x75,0x96,0xe0,0x65,0x88,0xd9,0x51,0x76,0xcd,0x50,0x7c,0xd7,0xaa, 0xc0,0xe9,0xb8,0xc3,0xd2,0xd1,0xd9,0xe4,0xc2,0xcc,0xda,0xc4,0xcd,0xda,0xdd,0xe5, 0xf4,0x9d,0xb5,0xe7,0x8f,0xab,0xe7,0x85,0xa4,0xe5,0x78,0x9a,0xe2,0x6b,0x90,0xdf, 0x5f,0x87,0xdc,0x54,0x7f,0xd7,0x5d,0x89,0xe1,0xd1,0xd7,0xe1,0xbf,0xc8,0xd5,0xbc, 0xc6,0xd3,0xcc,0xd6,0xe4,0xc9,0xd5,0xe9,0xc1,0xcf,0xe7,0xbd,0xcc,0xe7,0xb8,0xc9, 0xe8,0xb3,0xc6,0xe8,0xaf,0xc4,0xe8,0xac,0xc1,0xe9,0xad,0xc2,0xea,0xa3,0xb5,0xd4, 0xff,0xff,0xff,0x9a,0x26,0x4f,0xca,0x0,0x0,0x0,0x3a,0x74,0x52,0x4e,0x53,0x0, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x20,0x11,0xe2, 0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe2,0xe4,0x7f,0x8f, 0x8f,0x8f,0x8f,0x8f,0x8f,0x8f,0x8f,0x8f,0x8f,0x8f,0x7f,0x7f,0x7f,0x7f,0x7f,0x7f, 0x7f,0x7f,0x7f,0x7f,0x7f,0x7f,0x7f,0x81,0x48,0x21,0x84,0x65,0x89,0x0,0x0,0x0, 0x1,0x62,0x4b,0x47,0x44,0xc5,0x63,0xb,0x2b,0x77,0x0,0x0,0x0,0xf6,0x49,0x44, 0x41,0x54,0x18,0xd3,0x63,0x60,0x64,0x62,0x66,0x61,0x65,0x64,0x63,0xe7,0xe0,0xe4, 0xe2,0xe6,0xe1,0xe5,0xe3,0x67,0x10,0x10,0x14,0x12,0x16,0x11,0x15,0x13,0x97,0x90, 0x94,0x92,0x96,0x91,0x95,0x93,0x67,0xb0,0xb2,0xb6,0xb1,0xb5,0xb3,0x77,0x70,0x74, 0x72,0x76,0x71,0x75,0x73,0xf7,0x50,0x60,0xf0,0xf4,0xb2,0xf6,0xf6,0xf1,0xf5,0xf3, 0xf,0x8,0xc,0xa,0xe,0x9,0xd,0x53,0x64,0x8,0xb7,0x8e,0xb0,0x8d,0x8c,0x8a, 0x8e,0x89,0x8d,0x8b,0x4f,0x48,0x4c,0x4a,0x56,0x2,0xb,0xa4,0xa4,0xa6,0xa5,0x67, 0x64,0x66,0x65,0xe7,0xe4,0xe6,0x29,0x83,0xb4,0xe4,0x17,0x14,0x16,0x15,0x97,0x94, 0x96,0x95,0x57,0x54,0x56,0xa9,0x80,0x55,0x54,0xd7,0xd4,0xd6,0xd5,0x37,0x34,0x36, 0x35,0xb7,0xb4,0xaa,0x2,0x5,0xda,0x6c,0xf3,0xdb,0x3b,0x3a,0xbb,0x8a,0xbb,0x7b, 0x7a,0xfb,0xfa,0xd5,0x18,0x3c,0x27,0x4c,0xcc,0x9f,0x34,0x79,0xca,0xd4,0x69,0xd3, 0x67,0xcc,0x9c,0x35,0x7b,0x8e,0x3a,0xc3,0xdc,0x79,0xf3,0x17,0x84,0x2d,0x5c,0xb4, 0x78,0xc9,0xd2,0x65,0xcb,0x57,0xac,0x5c,0xa5,0xc1,0xb0,0xda,0x77,0xcd,0xda,0x75, 0xeb,0x37,0x6c,0xdc,0xb4,0x79,0xcb,0xd6,0x6d,0xdb,0xe7,0x68,0x32,0x84,0xc7,0xee, 0xd8,0xb9,0x6b,0xf7,0x9e,0xbd,0xfb,0xf6,0x1f,0x38,0x78,0xe8,0xf0,0x11,0x2d,0x6, 0x6d,0x1d,0x5d,0x3d,0x3d,0x7d,0x3,0x43,0x23,0x63,0x13,0x53,0x33,0x73,0xb,0x4b, 0x6,0x82,0x0,0x0,0xf9,0x94,0x53,0xc5,0x2c,0x2b,0xb6,0x5c,0x0,0x0,0x0,0x25, 0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0, 0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31, 0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0, 0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79, 0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33, 0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0, 0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_Move.png 0x0,0x0,0x2,0xb2, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0xf0,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x18,0x50,0xa0,0x4d,0x95,0xd4,0x4c,0x94,0xd4,0x4b,0x93,0xd3, 0x48,0x9c,0xdf,0x46,0x9b,0xde,0x47,0x90,0xd2,0x24,0x5e,0xa9,0x29,0x68,0xb2,0x4d, 0x9d,0xde,0x4b,0x9b,0xdd,0x27,0x66,0xb2,0x23,0x5e,0xa9,0x29,0x66,0xb0,0x49,0x99, 0xdd,0x47,0x97,0xdc,0x27,0x64,0xb0,0x24,0x5d,0xa9,0x44,0x94,0xda,0x41,0x93,0xd9, 0x26,0x64,0xb0,0x22,0x5d,0xa9,0x46,0x8f,0xd1,0x25,0x64,0xb0,0x3f,0x90,0xd9,0x3c, 0x8d,0xd8,0x23,0x63,0xb0,0x25,0x62,0xaf,0x22,0x61,0xaf,0x36,0x7f,0xcb,0x3d,0x92, 0xda,0x34,0x88,0xd6,0x31,0x85,0xd5,0x36,0x86,0xd5,0x34,0x84,0xd4,0x33,0x81,0xd2, 0x32,0x7f,0xd0,0x26,0x76,0xcd,0x35,0x7c,0xc9,0x43,0x8c,0xd0,0x38,0x8e,0xd8,0x3a, 0x8b,0xd7,0x38,0x89,0xd6,0x2f,0x83,0xd4,0x2e,0x80,0xd2,0x32,0x81,0xd2,0x31,0x7f, 0xd0,0x31,0x7c,0xcf,0x2f,0x7a,0xce,0x23,0x72,0xca,0x34,0x7a,0xc7,0x3c,0x87,0xce, 0x24,0x63,0xb0,0x22,0x60,0xaf,0x21,0x5f,0xaf,0x23,0x61,0xae,0x21,0x5e,0xae,0x32, 0x77,0xc5,0x25,0x61,0xae,0x30,0x7c,0xcf,0x23,0x60,0xae,0x21,0x5c,0xa9,0x2e,0x78, 0xcc,0x2c,0x76,0xcb,0x23,0x5f,0xad,0x21,0x5d,0xae,0x2b,0x73,0xc9,0x2a,0x70,0xc7, 0x20,0x5c,0xad,0x21,0x5b,0xa8,0x31,0x75,0xc4,0x1f,0x68,0xc4,0x1d,0x65,0xc3,0x2e, 0x71,0xc2,0x30,0x73,0xc3,0x2f,0x72,0xc3,0x2,0x2,0x2,0x14,0x41,0x82,0xff,0xff, 0xff,0xe9,0xe,0x41,0xc5,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6, 0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x4f,0x6e,0x66,0x41,0x49,0x0, 0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1, 0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0xa3,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60, 0x80,0x0,0x46,0x46,0x6,0x14,0xc0,0xc8,0xc4,0x8c,0x22,0xc2,0xc8,0xc2,0xca,0xc6, 0x8e,0x2c,0xc2,0xc1,0xc9,0xc5,0xcd,0xc3,0x8b,0xac,0x84,0x8f,0x5f,0x40,0x10,0xa1, 0x5e,0x88,0x81,0x41,0x50,0x58,0x44,0x94,0x81,0x41,0xc,0xac,0x8b,0x51,0x9c,0x47, 0x50,0x50,0x42,0x52,0x4a,0x5a,0x46,0x46,0x56,0x8e,0x11,0xc4,0x97,0x17,0x16,0x91, 0x94,0x52,0x50,0x54,0x52,0x56,0x51,0x55,0x53,0x67,0x64,0x60,0xd4,0xd0,0x94,0x94, 0xd2,0xd2,0xd6,0xd1,0xd5,0xd3,0x37,0x30,0x34,0x32,0x6,0x29,0x31,0x31,0x95,0x91, 0x31,0x53,0xd1,0x37,0xb7,0xb0,0xb0,0xb4,0x82,0x18,0x22,0xc6,0xc0,0x60,0x6d,0x63, 0x68,0xcb,0xc0,0x60,0x7,0x75,0xa,0x90,0xb2,0xb0,0x77,0x70,0x4,0x33,0xa0,0x22, 0x76,0x4e,0xce,0x2e,0xae,0x6e,0x48,0x4e,0x65,0x74,0xf7,0xf0,0xf4,0x42,0xf5,0x8c, 0xb7,0xf,0xaa,0x77,0x7d,0xfd,0xfc,0x7c,0x21,0x2c,0x0,0x4,0xc6,0xf,0x3d,0x6a, 0xb6,0xe7,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a, 0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31, 0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30, 0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d, 0x32,0x38,0x54,0x32,0x32,0x3a,0x32,0x38,0x3a,0x30,0x34,0x2b,0x31,0x30,0x3a,0x30, 0x30,0x22,0xab,0x22,0xa2,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60, 0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Resource_16x16.png 0x0,0x0,0x2,0xd2, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13, 0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1, 0x8e,0x7c,0xfb,0x51,0x93,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a, 0x25,0x0,0x0,0x80,0x83,0x0,0x0,0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75, 0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5, 0x46,0x0,0x0,0x2,0x48,0x49,0x44,0x41,0x54,0x78,0xda,0x9c,0x52,0x4d,0x48,0x54, 0x51,0x18,0x3d,0xf7,0x35,0xa9,0xb8,0x48,0x43,0x89,0x9,0xc2,0xd9,0x24,0x65,0x8b, 0x68,0x35,0xfd,0x30,0x50,0x91,0x8b,0x92,0x28,0x23,0x68,0x53,0x94,0x25,0x18,0x42, 0x1b,0x17,0xd5,0x2a,0x28,0x22,0x26,0x66,0x55,0x10,0x2d,0xa2,0xb4,0xa4,0x16,0x45, 0x21,0x83,0x16,0x22,0x85,0xd3,0x80,0x25,0xb3,0xa9,0x8d,0x8c,0x26,0x8a,0x63,0x44, 0x46,0x4e,0x3a,0xbd,0x37,0xcf,0x37,0xef,0xbd,0x7b,0x4f,0x8b,0x37,0xbe,0x7c,0x24, 0x5,0x7d,0xf0,0x5d,0xb8,0x7c,0xf7,0x9e,0xef,0x7c,0xe7,0x7c,0x22,0x95,0x4a,0x11, 0xff,0x8,0x92,0x32,0x1a,0x8d,0x5e,0xa9,0xae,0xae,0x8e,0xff,0x51,0x4c,0xa5,0x52, 0x74,0x1d,0x87,0xae,0xeb,0x50,0x4a,0x97,0x52,0xba,0x54,0x4a,0x52,0x29,0x49,0xd7, 0x75,0xa8,0x94,0x64,0x26,0x93,0xe1,0xd0,0xd0,0x90,0x9c,0xfd,0xf2,0xb9,0x93,0x24, 0x56,0xa6,0x46,0x12,0x4,0x1,0x2,0x24,0x97,0x3b,0x2,0x0,0x34,0x4d,0x3,0x0, 0x38,0x8e,0x83,0x58,0x2c,0xa6,0x8d,0x8f,0x65,0x6f,0x4d,0x4f,0x4f,0x9f,0x59,0x49, 0x40,0x53,0x4a,0xe1,0x6f,0x20,0x0,0x50,0x2c,0x16,0x91,0x4e,0xa7,0xa1,0x94,0xaa, 0x98,0x9a,0x9a,0x7a,0xb8,0x12,0x20,0x44,0x12,0x20,0x41,0x0,0xf7,0xef,0xf5,0x5, 0xc6,0xeb,0xe8,0x3c,0xe,0x21,0x4,0x9a,0x9b,0xf,0x60,0xee,0xeb,0x1c,0x6c,0xdb, 0xc6,0xa7,0xc9,0xc9,0xc0,0x9b,0xd0,0x32,0x3,0x1,0xa0,0xbd,0xa3,0x15,0x2,0x2, 0x42,0x0,0xde,0xf1,0x9b,0x49,0x78,0x63,0x18,0x0,0x30,0x3e,0x31,0xb1,0x3a,0x40, 0x30,0x4,0x84,0x37,0x14,0x4,0x4,0x20,0x82,0xd5,0x5d,0x91,0xb5,0x75,0x67,0x6b, 0xb7,0xcd,0xcb,0x48,0xe4,0x99,0x26,0xa5,0x4,0xcb,0xb3,0x5f,0xea,0xba,0x8b,0xf3, 0xed,0x89,0xb2,0xc2,0x58,0x55,0x1b,0xe3,0xe7,0x22,0xac,0xd6,0xe8,0x7c,0xec,0xf9, 0x53,0xa8,0x99,0x99,0x13,0x1,0x6,0xb3,0xb9,0x39,0x34,0x44,0xc2,0xfe,0xa7,0xde, 0x9e,0x7e,0x8f,0x83,0x0,0xda,0xce,0x1d,0xc1,0xe2,0xc2,0xf,0x6c,0x30,0x6,0xf1, 0xe4,0xc2,0x3,0x9c,0xbc,0xd3,0x8e,0xaa,0x42,0xb6,0x1e,0xc9,0x64,0x92,0xa6,0x61, 0xd0,0x2c,0x16,0xb9,0x64,0x16,0x69,0x2d,0x99,0xb4,0xac,0x25,0x96,0x2c,0x8b,0x76, 0xa9,0x44,0xc7,0x2e,0xd1,0x71,0x6c,0xe6,0xbf,0x7f,0x63,0xba,0xbb,0x8d,0xce,0xec, 0x6d,0xa6,0xbb,0xdb,0xb8,0xb3,0x21,0x54,0x47,0x12,0x9a,0xeb,0xba,0xfe,0x52,0xf4, 0xbd,0x18,0xc6,0xab,0x81,0x11,0xcf,0x15,0x3f,0x81,0xc2,0x42,0x1e,0x63,0xfd,0x97, 0xb1,0x67,0x7f,0x13,0xde,0xbf,0xfe,0x80,0x8b,0x57,0x1f,0xd7,0x8f,0xe6,0x9c,0xbc, 0x6f,0xe3,0xb2,0xb,0x95,0x95,0x15,0xb0,0xac,0x92,0x7f,0xef,0x7d,0xf4,0x12,0x25, 0x4b,0xc7,0xf6,0x75,0x6f,0xb1,0x63,0x8b,0x8b,0x77,0xc3,0x59,0xe4,0xd6,0xec,0xc5, 0x68,0xae,0x27,0xef,0x2f,0x52,0xa1,0x50,0x0,0xcb,0x76,0x1d,0x3c,0xb4,0x1b,0x47, 0x8f,0xed,0xf3,0xbb,0x9f,0x3a,0xdd,0x82,0xad,0x8d,0xb5,0xd8,0xbc,0xa9,0x11,0x1f, 0x27,0x42,0x68,0x3a,0x1c,0x87,0xed,0xaa,0x80,0x23,0x9a,0xae,0xeb,0xe5,0x45,0xf2, 0x3e,0xf9,0xf4,0x3d,0xe9,0x31,0xf0,0x66,0x4,0x83,0x93,0x55,0x68,0x6a,0xb9,0x81, 0x9a,0x9a,0xf5,0xd0,0x75,0x3d,0xb8,0x7,0xa6,0x69,0x96,0x29,0xb,0x50,0x78,0xea, 0x7b,0xc6,0x13,0x10,0x40,0xfc,0xfa,0x35,0x40,0x8,0x8,0x21,0x40,0x12,0xa6,0x69, 0x6,0x1,0xc,0xc3,0xc0,0xcd,0x44,0x2,0xff,0x1b,0xbf,0x6,0x0,0xb0,0x2e,0x91, 0xe2,0xbb,0x1e,0xc0,0x2c,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60, 0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/saveHS.png 0x0,0x0,0x3,0x20, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x4d,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xb7,0xb6,0xf5,0xb3,0xb2,0xf3,0xae,0xad,0xf1,0xa8,0xa7,0xee, 0xa2,0xa1,0xea,0x9b,0x9a,0xe7,0x94,0x93,0xe4,0x8f,0x8e,0xe0,0x88,0x87,0xdd,0x81, 0x80,0xda,0x7b,0x7a,0xd6,0x75,0x74,0xd3,0x70,0x6f,0xd1,0xbe,0xbd,0xff,0x93,0x92, 0xf8,0xff,0xff,0xff,0xf6,0xf8,0xfb,0x4b,0x58,0xbe,0x59,0x58,0xb0,0xad,0xac,0xf0, 0x8a,0x89,0xef,0xea,0xee,0xf6,0x3f,0x52,0xb8,0x33,0x33,0x67,0x56,0x55,0xaa,0xa7, 0xa6,0xed,0x81,0x80,0xe6,0xde,0xe5,0xf0,0x34,0x4d,0xb3,0x7a,0x79,0xdf,0x53,0x52, 0xa4,0x9f,0x9e,0xe9,0x77,0x76,0xdc,0xd2,0xdb,0xea,0x28,0x47,0xad,0x72,0x71,0xd7, 0x50,0x4f,0x9f,0x98,0x97,0xe5,0x6e,0x6d,0xd3,0xc6,0xd1,0xe5,0x1c,0x41,0xa7,0x67, 0x67,0xcc,0x4d,0x4d,0x9a,0x92,0x91,0xe2,0x67,0x66,0xcc,0xbd,0xca,0xe1,0x11,0x3b, 0xa1,0x5c,0x5d,0xc2,0x4a,0x4a,0x94,0x8b,0x8a,0xdf,0xbc,0xbb,0xff,0xb7,0xb6,0xff, 0x60,0x63,0xc9,0x56,0x5e,0xc4,0x5c,0x5d,0xc1,0x54,0x56,0xba,0x47,0x47,0x8f,0x84, 0x83,0xdb,0xb4,0xb3,0xff,0xae,0xad,0xff,0xa4,0xa3,0xfc,0x8f,0x8e,0xf4,0x87,0x86, 0xec,0x6c,0x6b,0xd1,0x4c,0x50,0xb2,0x44,0x44,0x89,0x7c,0x7b,0xd7,0xaa,0xa9,0xff, 0xa0,0x9f,0xfb,0x94,0x93,0xf5,0x4b,0x5b,0x71,0x52,0x62,0x76,0x5b,0x6a,0x7d,0x4c, 0x4f,0xb2,0x44,0x49,0xaa,0x41,0x41,0x83,0x76,0x75,0xd4,0xa0,0x9f,0xff,0x91,0x90, 0xf5,0x34,0x3c,0x47,0xce,0xd9,0xe9,0xd4,0xdd,0xec,0x67,0x74,0x85,0x43,0x4b,0xae, 0x3c,0x42,0xa3,0x3e,0x3e,0x7d,0x9a,0x99,0xff,0x68,0x78,0x8d,0xd8,0xe0,0xed,0xe0, 0xe7,0xf1,0x73,0x7f,0x8f,0x35,0x41,0xa3,0x3c,0x42,0xa2,0x35,0x3d,0x9c,0x3c,0x3b, 0x78,0x6c,0x6b,0xcf,0x8f,0x8e,0xf3,0x24,0x44,0xaa,0x21,0x32,0x47,0xab,0xb4,0xc3, 0xb3,0xbb,0xc6,0xbc,0xc1,0xca,0xc4,0xc8,0xce,0x48,0x4d,0x56,0x33,0x3e,0x9e,0x36, 0x3d,0x9c,0x31,0x39,0x98,0x39,0x39,0x72,0x65,0x64,0xc3,0x37,0x36,0x6e,0x5b,0xe0, 0x16,0x38,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0, 0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x10,0x95,0xb2,0xd,0x2c,0x0,0x0,0x0,0xc9, 0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xc0,0x0,0x8c,0x8c,0x4c,0xcc,0x2c,0xac, 0x6c,0xec,0x1c,0x9c,0x5c,0xdc,0x3c,0xbc,0x40,0x1,0x26,0x3e,0x7e,0x1,0x8,0x10, 0x14,0x12,0x16,0x6,0xa,0x88,0xf0,0x89,0x42,0xf9,0x62,0xe2,0x12,0x92,0x40,0x1, 0x29,0x3e,0x69,0x28,0x5f,0x46,0x56,0x4e,0x1e,0x28,0xa0,0xc0,0xa7,0x8,0xe5,0x2b, 0x29,0xab,0xa8,0x2,0x5,0xd4,0xf8,0xd4,0xa1,0x7c,0xd,0x4d,0x2d,0x6d,0xa0,0x80, 0xe,0x9f,0x2e,0x94,0xaf,0xa7,0x6f,0x60,0x8,0x14,0x30,0x32,0x36,0x31,0x35,0x13, 0x12,0x97,0x55,0xd6,0xd4,0x37,0xb7,0xb0,0x4,0xa,0x58,0x59,0xdb,0xd8,0xda,0xd9, 0x4b,0xcb,0xa9,0x38,0x98,0x5b,0x38,0x3a,0x1,0x5,0x9c,0x5d,0x5c,0xdd,0xdc,0x81, 0xc0,0xc3,0xd3,0xc2,0xcb,0xdb,0x7,0x28,0xe0,0xeb,0xe7,0x6f,0xef,0xce,0x10,0x10, 0x18,0x14,0x1c,0xe2,0x1d,0x1a,0x6,0x14,0xe0,0xd,0xb7,0x97,0x76,0xf,0x88,0x88, 0x8c,0x8a,0x8e,0x89,0x8d,0x8b,0x7,0xa,0x24,0x24,0x4a,0x27,0x25,0xa7,0xa4,0xa6, 0xa5,0x67,0x64,0x66,0x65,0xe7,0x80,0x4,0x72,0x25,0xe5,0x55,0xb5,0xd,0x2d,0x9d, 0x7c,0xe2,0xe3,0x73,0xf2,0x30,0x3d,0xf,0x0,0x1d,0xc3,0x22,0xd1,0xce,0x70,0xa2, 0x47,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72, 0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54, 0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64, 0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d, 0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x32,0x2d,0x32,0x39, 0x54,0x31,0x31,0x3a,0x30,0x32,0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa, 0xbb,0x4c,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/RefreshDocViewHS.png 0x0,0x0,0x2,0x1e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x96,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xb2,0xc2,0xd8,0xae,0xbe,0xd4,0xa9,0xb9,0xcf,0xa4,0xb3,0xc9, 0xff,0xff,0xff,0x9c,0xab,0xc0,0x36,0x4a,0x64,0xaf,0xbf,0xd5,0xad,0xb9,0xc9,0xba, 0xc5,0xd4,0xab,0xbb,0xd1,0x70,0x99,0x23,0xce,0xd6,0xcc,0x7f,0x8f,0xa4,0x3a,0x4e, 0x67,0xa7,0xb6,0xcc,0xe1,0xe9,0xce,0x57,0x7b,0x10,0xae,0xb9,0xca,0x93,0xa2,0xb7, 0xa3,0xb2,0xc8,0xc6,0xd5,0xaa,0x52,0x76,0x11,0xdb,0xe2,0xd0,0xe9,0xed,0xf5,0x35, 0x49,0x63,0x9e,0xae,0xc3,0xf9,0xfa,0xfc,0xee,0xf1,0xf7,0xe1,0xe7,0xf1,0x9a,0xa9, 0xbe,0xfc,0xfd,0xfe,0xf2,0xf5,0xf9,0xda,0xe1,0xee,0x96,0xa5,0xba,0xec,0xf1,0xde, 0xf7,0xf8,0xfb,0xd5,0xe1,0xc4,0xd3,0xdb,0xeb,0xbc,0xcb,0xbc,0xcb,0xd5,0xe7,0xe5, 0xed,0xd7,0x4f,0x6a,0x10,0xdc,0xe3,0xef,0xd1,0xd9,0xea,0xc4,0xcf,0xe4,0xd5,0xdd, 0xec,0xc9,0xd3,0xe6,0xbd,0xca,0xe1,0x67,0x9d,0xf2,0x1e,0x0,0x0,0x0,0x1,0x74, 0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44, 0x5,0xf8,0x6f,0xe9,0xc7,0x0,0x0,0x0,0x7e,0x49,0x44,0x41,0x54,0x18,0xd3,0x6d, 0xcf,0x61,0x13,0x42,0x40,0x10,0x80,0xe1,0x23,0x4b,0xb4,0x51,0x1c,0x45,0xa5,0x44, 0x8a,0xa2,0xfa,0xff,0x7f,0xae,0xe5,0xac,0xcc,0xd4,0xfb,0x6d,0x9f,0x9b,0xdb,0x99, 0x15,0xe2,0x37,0xad,0x4b,0x9f,0x19,0xc6,0x8,0xd0,0x67,0x5a,0x2c,0x73,0x5,0xb6, 0xc3,0xb2,0xe8,0x67,0x5c,0xba,0x9e,0xa5,0x60,0x5,0xb0,0x46,0x44,0x3f,0x90,0x3, 0x84,0xf4,0x1c,0xc1,0x66,0x1b,0xcb,0x44,0xc1,0x8e,0x0,0x60,0x7f,0x48,0x19,0x8e, 0xdd,0x8a,0x53,0x86,0x67,0x86,0x1c,0xa0,0xc0,0x4b,0x89,0x57,0x6,0x49,0x5f,0xa8, 0x5b,0x35,0x81,0xfa,0x1e,0x3f,0x9a,0x76,0x2,0xb4,0xf1,0xf9,0x7a,0x7f,0x41,0xe, 0x31,0x24,0x63,0x7f,0x4e,0x17,0x1f,0x10,0x81,0x9,0xf8,0xf6,0xb4,0x85,0xa4,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61, 0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30, 0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64, 0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31, 0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98, 0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderMode_LightingOnly.png 0x0,0x0,0x1,0x6e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x67, 0x49,0x44,0x41,0x54,0x28,0xcf,0x7d,0x50,0x49,0x12,0xc0,0x30,0x8,0x2,0xa7,0xff, 0xff,0x32,0x3d,0x24,0x56,0x6c,0x16,0x2f,0xc6,0x28,0x8b,0x52,0xb8,0xc7,0xe3,0x5, 0x97,0x69,0x31,0xd6,0xb6,0xe8,0x23,0xe1,0x6d,0x11,0x10,0x29,0x1f,0x99,0xb0,0x42, 0x77,0x99,0x29,0xb1,0x43,0x67,0xa6,0xb6,0xe6,0x92,0xcd,0x4c,0xe,0x86,0x42,0xa6, 0x58,0x78,0x49,0xe5,0x77,0x79,0x89,0x54,0xea,0x1e,0xca,0x8b,0xad,0x59,0x2c,0x3e, 0x12,0xdd,0x52,0x91,0x7f,0x22,0x82,0x0,0x69,0x3c,0x7e,0x59,0xd0,0xd9,0x43,0xee, 0x73,0xbc,0x43,0x3b,0xd4,0x2d,0x5e,0x66,0x9f,0x56,0x7,0xfb,0x2,0xcd,0xbb,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61, 0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30, 0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64, 0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32, 0x33,0x3a,0x31,0x34,0x3a,0x32,0x33,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa1,0xba,0x6f, 0xe6,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_ShapeCube.png 0x0,0x0,0x7,0x6e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x6,0x63,0x49,0x44,0x41,0x54,0x58,0xc3,0x95,0x97,0xcb,0x8e,0x1c,0x49, 0x15,0x86,0xbf,0xff,0x44,0x64,0xd6,0xad,0x2f,0xe5,0x6e,0x5f,0xc1,0x20,0x73,0x13, 0xb,0x23,0x46,0xac,0x40,0x42,0x1a,0x9,0xc4,0x86,0xed,0x68,0xe6,0x1,0xe0,0x31, 0x78,0x15,0x24,0x5e,0x0,0x90,0x66,0x3b,0x1b,0xc4,0x82,0x7,0x18,0x84,0xc4,0x66, 0x66,0x18,0x1,0xb6,0xb0,0x1b,0x9b,0x76,0x55,0x77,0x75,0x55,0x65,0x66,0xc4,0x61, 0x11,0x59,0x97,0xb6,0xdb,0xc2,0x54,0xe9,0x54,0x64,0xa6,0x32,0xe3,0xff,0xe3,0x3f, 0xff,0x39,0x19,0x25,0x77,0xf7,0xdf,0xbd,0xe4,0x9d,0x3e,0x57,0x8d,0xf3,0xc5,0xd3, 0x86,0x6f,0x1d,0x1a,0xd3,0xe8,0x9c,0xbd,0x58,0x31,0x4f,0xe2,0x85,0x1b,0xdf,0xfb, 0xf6,0x98,0x3a,0xea,0xdd,0x26,0x2,0x3e,0x3c,0x2d,0x63,0xfc,0x5f,0x37,0x7e,0xf1, 0xbc,0xe3,0xfc,0xbc,0xe3,0xce,0x50,0x1c,0xd6,0xe2,0xbd,0x63,0x23,0x1a,0x74,0xc9, 0xf1,0xec,0x9c,0xd6,0xc6,0xed,0x28,0x5e,0x3d,0x5d,0xb1,0x72,0x31,0x4f,0x50,0x8d, 0x3,0xdf,0x7d,0x50,0xbd,0x13,0x91,0x37,0x8,0xb8,0xc3,0x1f,0xfe,0xb2,0xa4,0x59, 0x65,0x86,0x26,0x86,0x11,0xc6,0x95,0x98,0x5d,0x39,0xb3,0x25,0x3c,0x9d,0x83,0x80, 0x9c,0x9d,0xcb,0x59,0x26,0x54,0x10,0xa3,0x13,0xa2,0x61,0x41,0x98,0xc4,0xc5,0xcb, 0x96,0x3f,0x9d,0xb5,0x34,0x19,0x3c,0x88,0xc7,0x5f,0xaf,0xb9,0x3f,0xd,0x6f,0x27, 0xf0,0xd9,0xb3,0x96,0x4f,0x3f,0x5f,0x73,0x79,0x91,0x90,0x17,0x0,0xf5,0x3f,0x32, 0x90,0x1,0x6,0x32,0x81,0xca,0xb9,0xbb,0xd3,0x5c,0x26,0x2c,0x7a,0x89,0xe0,0xfd, 0x43,0x40,0x6,0xcf,0x40,0x76,0x3c,0xc3,0x93,0x7f,0xb5,0x0,0x58,0x80,0x93,0x69, 0xe4,0xfd,0xc7,0xc3,0x32,0x21,0x20,0x77,0xf7,0xc7,0x1f,0xfe,0x91,0xf1,0x77,0xbe, 0x46,0x75,0x6f,0x4a,0xca,0x5,0x14,0x1,0x26,0x14,0xf6,0xc6,0xb0,0x3b,0x7,0x27, 0x2d,0x1b,0x14,0xd,0x5,0x43,0x66,0x5b,0x70,0x32,0x78,0x72,0x3c,0x1,0xa9,0x90, 0x20,0x39,0x26,0xc1,0x62,0xce,0xe2,0xb3,0xbf,0xf1,0xe7,0xdf,0xfc,0x64,0xa7,0xc0, 0xab,0xcf,0xff,0xcd,0xec,0xcb,0x5,0x71,0x3c,0x65,0xf2,0xe8,0x1e,0xf5,0x83,0x43, 0x74,0x1c,0x69,0x53,0x46,0x51,0x28,0x8,0x22,0xfd,0xa8,0xa2,0x86,0x9c,0xbc,0x72, 0x14,0x81,0x50,0xce,0x71,0xb6,0x60,0xde,0x6d,0x46,0x27,0xd2,0xd1,0x3e,0x7b,0xc6, 0xf2,0xef,0x4f,0x58,0xbe,0x98,0x21,0xfc,0x6,0xf,0x8,0x52,0x9b,0xb9,0xfc,0xc7, 0x15,0xe1,0x2c,0x50,0x1d,0x8d,0x19,0x3f,0xac,0xd1,0x11,0x74,0x72,0x9a,0xc6,0x51, 0xa0,0x0,0x1a,0x40,0x1,0x91,0x79,0x39,0x2f,0xa2,0x14,0xd9,0x93,0x97,0x4b,0xcb, 0x19,0xdd,0xd9,0x33,0x5e,0x3d,0x3d,0xc3,0xbb,0xe,0x72,0xda,0x29,0x75,0x8d,0x80, 0xfa,0x1f,0x6d,0xe,0x85,0x27,0x58,0xbf,0x82,0xda,0x2,0xa3,0x7,0x62,0x3a,0x85, 0x76,0x91,0x59,0x9c,0x39,0xab,0x8b,0xde,0x7,0x69,0xe3,0x13,0xdf,0xae,0x22,0x84, 0xe,0x16,0xe7,0xac,0x5f,0xbe,0xa0,0xbd,0x5c,0x14,0x50,0x5,0x8,0xc5,0x5c,0x72, 0xe1,0x37,0x2a,0xb0,0x61,0xb2,0x31,0x92,0xfa,0x8,0xfd,0x38,0x14,0x7,0xf7,0x22, 0x77,0xde,0x33,0x6c,0x2d,0x2e,0xbe,0xec,0x38,0xfb,0x6b,0x62,0xf9,0x1f,0x27,0xd4, 0x60,0x71,0x49,0xee,0xe6,0xac,0x2e,0xa,0xa8,0x27,0xc7,0xaa,0xa,0x4f,0x82,0xe4, 0x6c,0xdd,0xed,0xea,0xf3,0x74,0x3,0x1,0xed,0x1f,0x48,0xc5,0xf5,0x56,0xcc,0x47, 0xa0,0x18,0x50,0x30,0x3c,0x31,0x6e,0xdd,0xab,0x79,0xf4,0x3,0x63,0xfe,0xa4,0xe5, 0xd3,0x8f,0xff,0x49,0xb7,0x76,0x70,0x47,0x31,0x16,0x23,0xaa,0xa4,0xa3,0x0,0x7b, 0xf1,0x83,0x40,0xb9,0x4f,0xd5,0x75,0x2,0xda,0x83,0x2f,0xc7,0xea,0x2f,0xc9,0xca, 0xb1,0x4c,0x7d,0x14,0x91,0xa4,0x92,0xaf,0xe1,0x41,0xb1,0x94,0x45,0x3,0x77,0xdc, 0x5,0x79,0x93,0xa2,0xd,0x9a,0x3,0x79,0x37,0xa7,0xeb,0x66,0x5,0xb6,0x2,0x6c, 0x6e,0xdc,0x84,0xbd,0x79,0xd,0xc0,0x10,0x66,0xc2,0x2a,0x2b,0xa5,0xe9,0x8e,0xbc, 0x5f,0x6d,0xe,0xa0,0x8c,0xc8,0xb8,0xca,0xf1,0x36,0x15,0x6f,0x2a,0xb0,0xd3,0x7e, 0x1f,0xe8,0x6,0x61,0xf6,0x13,0xb5,0xbd,0x66,0x51,0xf8,0xe6,0x1,0xcf,0x60,0x86, 0x52,0xc6,0x65,0x38,0xa1,0x6f,0xe,0xa1,0x54,0xe,0xbd,0xf,0x6e,0xf4,0xc0,0xfe, 0xbb,0xa4,0xf7,0xc,0xbe,0xa7,0xc4,0x1e,0xfe,0xd6,0xab,0x52,0x91,0xbf,0x8,0x0, 0x6e,0x60,0x8e,0xcb,0x10,0x86,0x23,0x7c,0x6f,0x14,0x6f,0x53,0x60,0x83,0xc6,0xce, 0xb0,0xfb,0x24,0xc8,0x1b,0x3f,0xf9,0x96,0x8c,0xf6,0x14,0x90,0x9,0x77,0xef,0xdb, 0xaf,0xa,0xa0,0x6f,0x54,0x11,0x72,0xc3,0x71,0x5c,0x5e,0x4,0xd9,0x27,0x50,0x26, 0xec,0xeb,0x54,0x7e,0x5d,0xf5,0x3e,0x6d,0xe6,0x4e,0xe9,0x39,0x62,0xd3,0x7b,0x2, 0x10,0xc,0x62,0xb5,0x53,0xc0,0xb3,0x95,0x36,0xdc,0x13,0x70,0x37,0xdc,0x84,0x5b, 0x6f,0x6e,0xec,0x5a,0x16,0xe3,0x56,0xef,0x7d,0x21,0xe4,0x5b,0x52,0x9b,0x2c,0x6, 0x17,0xc1,0xe9,0xc3,0x9,0x65,0x2a,0x82,0xa0,0xaa,0xcb,0x2a,0x3c,0x97,0xb7,0xa4, 0xb,0xb2,0x4a,0x15,0x6e,0x49,0x6c,0x14,0x78,0x9b,0x7,0xd4,0x7f,0xb7,0x79,0x5, 0x82,0x44,0x40,0x5b,0xf0,0xb8,0x9,0x44,0x74,0x30,0x9,0x37,0x18,0x54,0xa5,0x14, 0xdd,0x21,0xa5,0xb2,0x9c,0x4,0xe4,0x2c,0xb2,0x43,0xee,0x49,0x64,0x8a,0xba,0xee, 0xaf,0x75,0x42,0x6d,0xdb,0x70,0x59,0x79,0x90,0x63,0x56,0x56,0x17,0xe5,0x54,0x40, 0xe5,0xa2,0x72,0xa8,0x1d,0x6a,0x77,0x2a,0x54,0x9a,0xa4,0xc4,0x70,0x20,0xdc,0xcb, 0xea,0xb3,0x41,0x92,0x48,0x88,0xe4,0x65,0xcc,0x6e,0x24,0xf7,0xad,0xa3,0x3d,0xe7, 0x9b,0x14,0x28,0xe0,0xa6,0x1d,0x70,0x34,0xa7,0x32,0xa8,0x80,0xc1,0xd,0x61,0x80, 0x19,0x4c,0xea,0x7e,0xf5,0x59,0x74,0x9d,0x48,0x40,0xe7,0xea,0xa3,0x80,0xb,0x2b, 0xaa,0x28,0x5f,0x2b,0xb7,0xb8,0x35,0x9b,0xca,0x64,0x9b,0x88,0x41,0x54,0x26,0x6a, 0x83,0x81,0xc1,0x50,0x25,0x46,0x38,0x43,0x60,0x48,0x21,0xdb,0x49,0x1c,0xf4,0xa, 0x74,0x9,0x3a,0x13,0xad,0x4a,0x34,0x8,0x43,0xb4,0x6e,0xdb,0x8a,0x4a,0x49,0x64, 0xbd,0x9e,0x82,0xbe,0xb5,0x6e,0x15,0x8,0x10,0x3,0xd4,0xd1,0x19,0x4,0x18,0x86, 0x1e,0x5c,0x30,0x92,0x18,0x9,0x6,0xfd,0xbd,0xc9,0xe0,0x70,0x50,0x72,0xdd,0x25, 0x68,0x83,0x68,0x64,0x34,0x94,0xca,0x69,0xdc,0xb7,0xe0,0xdd,0xa6,0x15,0xe9,0x8d, 0xb7,0xe1,0x46,0x7e,0x11,0x82,0x88,0x26,0xaa,0x0,0x75,0x10,0x83,0x8,0xa3,0x50, 0x62,0x6c,0x30,0xb2,0x32,0x9e,0xc,0x20,0x27,0xe3,0x32,0x65,0xe,0x6,0x46,0xf2, 0xb2,0x51,0x6d,0x43,0xd9,0xb3,0x4,0xd1,0xb7,0x1f,0xb6,0xbd,0xc0,0x51,0x49,0x41, 0x7a,0xbd,0xc,0xb5,0xdd,0x81,0x95,0xba,0xe,0x25,0x5,0x75,0x84,0x41,0x14,0x83, 0x28,0xe,0x2a,0x71,0xef,0xc0,0xb8,0x3b,0x35,0x4e,0xf,0x2,0x75,0x14,0x16,0x44, 0x33,0x31,0x8e,0x1e,0x1d,0x70,0x7e,0xd1,0x72,0x7e,0xd1,0x71,0xb5,0x4a,0x4,0x15, 0xe9,0xb5,0x2d,0xc3,0x52,0x92,0xe5,0xd5,0x24,0x3a,0x6e,0xa8,0x82,0xcd,0xe6,0x73, 0x9f,0xc4,0x64,0x2c,0xee,0xdf,0x31,0xee,0x7f,0xc5,0x38,0xbd,0x25,0x6,0xc3,0xe2, 0x8b,0xab,0xc6,0x69,0x52,0xd9,0x64,0xe6,0xce,0x19,0x4f,0x22,0xc3,0x71,0xe4,0xde, 0x1d,0xb8,0xbc,0xea,0x38,0x9f,0xb7,0xbc,0x9c,0x35,0x9c,0xcf,0x20,0xe5,0x4d,0xa8, 0x2f,0x4b,0xc7,0x94,0x6f,0xf0,0x0,0x25,0x5,0xc3,0xa3,0xc8,0xad,0x87,0x35,0x77, 0xbf,0x5a,0x31,0x3d,0x9,0x8c,0x26,0xd0,0xe1,0x5c,0xac,0xa1,0xc5,0xa9,0x92,0x51, 0x45,0x27,0x84,0xa2,0x40,0x4e,0xce,0x62,0x5d,0x6a,0x3b,0x39,0x24,0x19,0xc3,0x49, 0xcd,0x69,0x5d,0x31,0x3a,0xca,0x9c,0xcf,0x5b,0xce,0x67,0xd,0x79,0xd6,0xd0,0xe6, 0x8e,0xe0,0x99,0x4c,0xb8,0x4e,0x60,0x70,0x72,0xc0,0xe8,0xce,0x29,0x7,0x77,0xa7, 0x8c,0xc6,0x23,0x6c,0x14,0x58,0x26,0x27,0x5c,0x65,0x64,0x86,0x85,0xb2,0x5a,0x9, 0xdc,0x33,0x39,0xab,0x5c,0x33,0xc8,0xc9,0x59,0x37,0xa5,0xc3,0xe5,0xc,0x6d,0x86, 0x75,0xb,0xcb,0x16,0x96,0xd,0x24,0x5,0xc2,0x68,0xc8,0x30,0xd6,0xe4,0x55,0x86, 0x45,0x4b,0xbe,0x6a,0xaf,0x13,0x78,0xf8,0xd3,0xef,0x73,0xf1,0x7c,0x41,0x97,0x8d, 0xf5,0xca,0x9,0x38,0xb5,0x65,0xba,0x68,0x74,0xb5,0x93,0x5a,0xc8,0x2d,0xe4,0xd0, 0xb7,0x58,0x84,0xdc,0x71,0xeb,0xb7,0xdf,0x79,0xf3,0x1e,0x28,0x5b,0x71,0xef,0x20, 0xb7,0xe5,0xb9,0xae,0x81,0xae,0x71,0x9a,0x15,0x74,0x1d,0x28,0x46,0x26,0x47,0xbb, 0x3e,0x20,0x77,0x77,0x69,0xd7,0x19,0x7e,0xf8,0xab,0x67,0x7e,0x90,0x61,0x32,0x88, 0x1c,0x8e,0x8d,0x5b,0xc7,0x81,0xa3,0x43,0x71,0x30,0x11,0xa3,0x91,0x18,0xd4,0xa2, 0x8a,0xc2,0x62,0xd9,0x8c,0x78,0x72,0x96,0xb3,0x35,0x19,0x48,0xc9,0xe9,0x92,0xb3, 0x6a,0x9d,0xc5,0xda,0x59,0xac,0x32,0xf3,0xab,0xcc,0xa2,0xcd,0x24,0xc1,0x8f,0x7e, 0x7c,0xc4,0x37,0xbe,0x39,0xe1,0xa3,0xdb,0x92,0xf7,0xfd,0xf8,0xd,0x2,0xfb,0x9f, 0x5f,0xfc,0x7a,0xe6,0x3e,0xcf,0x4c,0xf,0xc5,0xd1,0x44,0x1c,0x1f,0x19,0xc3,0x81, 0x88,0xb1,0x84,0x99,0xf0,0xec,0x2c,0x67,0xd,0xd9,0x9d,0x94,0xa0,0xe9,0x9c,0xab, 0x75,0x66,0xbe,0x74,0xe6,0xeb,0x4c,0x38,0xe,0xfc,0xec,0xe7,0xe5,0x9f,0xe8,0x47, 0xb7,0x77,0x38,0xef,0x44,0x0,0xe0,0xb7,0x2f,0xca,0x8d,0x9f,0x7c,0x3c,0xe7,0x30, 0x67,0x6e,0x4f,0x3,0xe3,0xa1,0x38,0x9c,0x84,0x2d,0x81,0xab,0xd9,0x1a,0x77,0xb8, 0x5c,0x66,0x16,0x6b,0xe7,0x6c,0x91,0x79,0xff,0x83,0x53,0x86,0xc3,0xdd,0x7f,0x80, 0x7d,0xf0,0xff,0x8b,0xc0,0xeb,0x44,0x0,0x3e,0xf9,0xfd,0x8c,0x63,0xc1,0xdd,0x93, 0x40,0x14,0x5c,0x9e,0x37,0x9c,0x5f,0x26,0x9e,0x37,0xc6,0x7,0xbf,0x3c,0xbd,0x11, 0xf0,0xf5,0xcf,0x86,0xc0,0x7f,0x1,0x70,0x52,0x56,0x22,0x26,0xc5,0x2,0xb4,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61, 0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30, 0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64, 0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32, 0x32,0x3a,0x34,0x33,0x3a,0x33,0x37,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8d,0x99,0xe, 0x68,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_View_Perspective.png 0x0,0x0,0x1,0x53, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x4c, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x11,0x90,0x67,0x60, 0x81,0x50,0x8c,0x18,0x6,0xfd,0x67,0xc4,0x90,0x61,0xfc,0xf,0x11,0x86,0x9,0x41, 0x94,0x60,0xb1,0xe2,0x3f,0x23,0x4c,0x37,0x51,0x6e,0x20,0xd6,0x91,0xc8,0x0,0xd5, 0xc1,0x2c,0xb8,0x24,0x61,0xee,0x40,0x53,0x80,0xec,0x3c,0x6a,0x39,0x12,0x6a,0x29, 0xaa,0xc3,0x90,0x2d,0x62,0xa4,0x38,0xb2,0x8,0x2a,0x0,0x0,0x5a,0xf0,0x12,0x21, 0x20,0xc7,0xc8,0xcb,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33, 0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x35,0x3a,0x30,0x33,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xc,0x5d,0x3,0xa5,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_ShapeCone.png 0x0,0x0,0x5,0x16, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x4,0xb,0x49,0x44,0x41,0x54,0x58,0xc3,0xbd,0x96,0xcf,0x8b,0x9b,0x45, 0x18,0xc7,0x3f,0x33,0xf3,0xbe,0xc9,0xbb,0xc9,0x26,0x4d,0x93,0x6e,0xdd,0xae,0x6b, 0xff,0x5,0x6f,0xfd,0x2b,0xbc,0x48,0x41,0x41,0x4f,0x16,0x41,0x44,0x3c,0x2a,0x5e, 0x7a,0xaa,0x37,0xf1,0xa4,0x22,0x3d,0x89,0xa2,0x5e,0x84,0x7a,0x50,0x3c,0x8a,0xa0, 0xe0,0x45,0xf0,0xa2,0x82,0x17,0x6f,0x55,0xa8,0xa8,0xdd,0xe4,0x4d,0xde,0xf7,0x9d, 0x5f,0x8f,0x87,0xc9,0xba,0x6d,0xcc,0xa6,0xc9,0x6e,0xb7,0x3,0x9,0xbc,0xf0,0x32, 0xf3,0x79,0x3f,0xdf,0x67,0x9e,0x19,0x64,0xc9,0x60,0x8d,0xf1,0xbb,0xfd,0x48,0x5e, 0xff,0xf8,0xc9,0xb5,0xde,0x5,0x90,0x63,0x86,0x5e,0x77,0x82,0xc5,0xf1,0xf3,0x6f, 0xbf,0x70,0xe7,0xef,0x3f,0xb9,0x76,0x73,0x67,0x6d,0x88,0x65,0xe3,0xc4,0x0,0xdf, 0xfc,0xf0,0x2d,0x48,0xc6,0x78,0x32,0x3e,0xcd,0xfa,0x27,0x3,0xb8,0xdd,0x7c,0x28, 0xc6,0x68,0xa2,0x53,0x34,0xb3,0x53,0x9,0x38,0x19,0xc0,0xbb,0x9f,0xbf,0x47,0xbb, 0xdd,0xc6,0xd6,0x81,0x6a,0x12,0x79,0xea,0x4d,0x75,0x62,0x8a,0x13,0x1,0x4c,0xeb, 0x92,0x41,0xaf,0x4f,0xd3,0x78,0xea,0x52,0xb0,0xa7,0xb0,0xb0,0x31,0xc0,0xf5,0x5b, 0x57,0xa4,0xdb,0x29,0x30,0xc6,0xe0,0x9c,0xa7,0x99,0x9,0xbe,0x81,0xa7,0xdf,0xe2, 0x44,0x14,0x1b,0x3,0xfc,0x7a,0xfb,0x27,0x2e,0x8d,0x2e,0xd1,0xd8,0x6,0xe7,0x2, 0xde,0xa,0xcd,0x14,0xec,0xec,0x11,0x19,0x28,0x8a,0x36,0xfb,0x3b,0xfb,0x94,0x55, 0x89,0xf,0x9e,0xe0,0xa1,0x99,0x42,0x70,0x8f,0x0,0xe0,0x99,0xf7,0x8d,0xf4,0x3b, 0x3d,0x86,0xbd,0x11,0x65,0x55,0x12,0x7c,0x40,0x22,0xb8,0xa,0x7c,0x3,0x57,0xdf, 0xde,0x3c,0x86,0x6c,0xa3,0x97,0x33,0xc3,0xee,0x70,0x8f,0x3c,0xcb,0x99,0x56,0x33, 0x7c,0x88,0x48,0x4,0x1f,0x92,0x85,0x18,0xcf,0xd0,0xc0,0xf3,0x1f,0x20,0x79,0x9e, 0xf1,0xc4,0xce,0x65,0xac,0xb7,0x54,0x75,0x45,0x8c,0x11,0x41,0x8,0xe,0xec,0x14, 0x24,0xc2,0x73,0x37,0x37,0xb3,0xb0,0xb6,0x1,0x63,0xc,0x9d,0x56,0x87,0xfd,0xd1, 0x65,0xca,0xba,0xa4,0xb6,0x96,0x38,0xff,0xe4,0x18,0x52,0x11,0xfa,0x6,0x94,0x3a, 0x23,0x3,0xc6,0x68,0xce,0x77,0x87,0x8c,0x7a,0x17,0x19,0x4f,0xef,0x62,0x9d,0xe3, 0xbf,0x73,0x4b,0xc0,0x56,0xe0,0x6a,0xe0,0x2c,0x0,0x5e,0xfc,0x4c,0x49,0x96,0x19, 0x1e,0x1b,0xec,0xd1,0x69,0x75,0x38,0x98,0x1d,0xe0,0xbc,0x23,0xce,0x1,0x44,0x20, 0xd8,0x4,0x1,0xf0,0xc2,0x27,0xeb,0xc7,0xb0,0x56,0x4,0x46,0x2b,0x72,0xd3,0xe6, 0xf1,0xe1,0x65,0x44,0x60,0x52,0x8d,0xf1,0x3e,0xa4,0x95,0xe7,0x23,0x78,0x70,0xb3, 0x14,0x87,0x69,0x3d,0x44,0x3,0xaf,0x7e,0x89,0x18,0xa3,0xe8,0x16,0x3d,0x76,0x7, 0xfb,0x58,0xdf,0x30,0xad,0xa6,0x78,0xef,0xef,0x5d,0x9f,0x18,0x93,0x81,0xe0,0x40, 0x6b,0xb8,0xf6,0xe9,0x7a,0x16,0x1e,0x8,0xa0,0xb4,0xc2,0xe8,0x8c,0x41,0x77,0xc8, 0xb0,0xbb,0xc3,0xcc,0x96,0x54,0x4d,0x45,0x8,0xb,0x7b,0xee,0xb0,0x1f,0xd8,0xf4, 0xd8,0xde,0x7e,0x48,0x6,0xb4,0x56,0xe4,0x59,0x8b,0x8b,0xfd,0x3d,0xb6,0x5a,0x5d, 0x26,0xf5,0x98,0xc6,0x35,0x84,0x18,0xe0,0x9e,0x8f,0x14,0x1,0xd7,0xa4,0x18,0x24, 0x82,0x5a,0xb3,0xbc,0x57,0xbe,0xf6,0xda,0xd7,0x4a,0xb4,0x56,0x14,0xf9,0x16,0xbb, 0xfd,0x7d,0x8c,0xce,0x98,0x54,0x63,0xec,0x7c,0xb,0x2e,0x3a,0xe,0xe,0x9a,0x19, 0x44,0x9f,0xb6,0xe3,0xcb,0x5f,0x3c,0x38,0x86,0x95,0x0,0x4a,0x83,0x56,0x86,0x6e, 0xd1,0xe3,0x42,0x6f,0xf,0x91,0xc8,0xa4,0x3e,0xc0,0x7a,0x4f,0x8c,0xb,0x73,0xb, 0x44,0x7,0x4d,0x99,0x62,0x10,0x1,0x6d,0x4e,0x61,0xe0,0xfa,0xf7,0x88,0xd6,0x90, 0x9b,0x9c,0x73,0x9d,0x11,0xe7,0x8a,0x21,0x2e,0x38,0xca,0x7a,0x8c,0xf7,0xf3,0x1e, 0xb0,0xc0,0x10,0x63,0x6a,0xc9,0xb6,0x4e,0x0,0x4a,0xc3,0x4b,0xb7,0x56,0x5b,0x38, 0xde,0x80,0x2,0xad,0x14,0xad,0xbc,0x60,0xd4,0xdd,0xa5,0xc8,0x3a,0x58,0x5f,0x33, 0xad,0xa7,0x38,0xef,0x13,0xc0,0x42,0xd3,0x91,0x8,0xbe,0x3e,0xaa,0x3,0x80,0x7c, 0x6b,0xb5,0x81,0x63,0xfb,0x80,0x52,0xa0,0x94,0xa1,0x9d,0x75,0xb8,0xd0,0xdd,0x43, 0x6b,0xc3,0xcc,0x4d,0xa9,0x6c,0x75,0x4,0x70,0x7f,0x2,0x88,0x24,0xfd,0x76,0xde, 0xf,0xe,0xe7,0xd9,0xd8,0xc0,0x8d,0x1f,0x11,0xad,0x14,0x99,0xce,0xe8,0xb4,0x7a, 0xc,0xb6,0x2e,0x22,0x22,0x4c,0x9b,0x31,0x8d,0xab,0x53,0xf,0x58,0x66,0x56,0x52, 0x1,0x1e,0xf6,0x3,0x24,0x99,0x7c,0xe5,0xab,0xe3,0x63,0x58,0xa,0xa0,0x54,0xfa, 0xcb,0x4c,0x9b,0x5e,0xfb,0x3c,0x9d,0xbc,0x47,0x88,0x3e,0x15,0xa0,0xb3,0xf8,0xe0, 0x39,0x6e,0xca,0xe8,0x8f,0xee,0x7,0x87,0x92,0x56,0x6d,0xc9,0xe5,0x0,0x80,0x52, 0x8a,0x56,0xd6,0xa6,0x5f,0x8c,0xd0,0xca,0x60,0x43,0x4d,0x59,0x1f,0x60,0x9d,0x23, 0xac,0x38,0xf8,0x63,0x9c,0xf7,0x83,0xfa,0xa8,0xe,0x56,0xc5,0x90,0x2d,0x9f,0x44, 0xa3,0xd1,0xb4,0xb2,0x82,0xed,0xd6,0x0,0x17,0xd3,0x57,0x4f,0x6d,0x49,0x88,0xff, 0xcf,0xff,0xde,0x8,0x24,0xa6,0x3a,0x70,0x55,0xb2,0x61,0x72,0x28,0x8a,0xd,0xd, 0x78,0x6b,0x68,0xe,0xfa,0xe4,0x71,0x40,0x66,0xda,0xcc,0xdc,0x98,0xb2,0xb9,0x4b, 0xe3,0x2b,0x24,0xca,0x7d,0x87,0xd0,0xc2,0xfa,0x48,0x4c,0x27,0xa3,0xab,0xd3,0x25, 0x45,0x5b,0xd8,0xde,0xda,0x10,0x40,0xa2,0x26,0x36,0x2d,0xb2,0x7a,0x9f,0x7e,0xbe, 0x47,0xb7,0xbd,0x8d,0x8b,0x8e,0xc6,0x3a,0x62,0x54,0x88,0x28,0x50,0x49,0xad,0xd6, 0x60,0x4c,0xfa,0x29,0x95,0x0,0xdc,0xc,0xca,0x3f,0xa0,0xbe,0x3,0x84,0xd5,0x57, 0xb5,0xa5,0x11,0x74,0xb2,0xb,0x4c,0x44,0xa3,0x94,0xc2,0x5,0x4b,0xab,0xd5,0x47, 0x2b,0x43,0x5d,0x5,0xaa,0x99,0xc2,0x56,0xa,0x25,0xd0,0xe9,0x42,0xa7,0xa5,0xb0, 0x5b,0x50,0xfe,0x3,0xcd,0x4c,0x10,0x1,0xf1,0x9,0x44,0x24,0x6d,0xc7,0x60,0x37, 0x4,0x78,0xe3,0xca,0x6d,0x5,0xf0,0xdd,0x5f,0xcf,0x4a,0x61,0x32,0xa2,0xa,0xd8, 0xd0,0x10,0x62,0x24,0x2e,0x1e,0x42,0xa4,0x82,0x35,0x46,0xa3,0x54,0x4,0x89,0x69, 0x61,0xf,0xf5,0x14,0xde,0xb9,0x9a,0xda,0xd5,0xd,0x59,0xbe,0x6f,0xfe,0x5,0xdf, 0x18,0x6a,0x2f,0xb7,0x71,0x4c,0x11,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d, 0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31, 0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74, 0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32, 0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x34,0x34,0x3a,0x33,0x37,0x2b, 0x31,0x30,0x3a,0x30,0x30,0x6f,0x45,0x15,0x11,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/pause.png 0x0,0x0,0x0,0xe5, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x9,0x70,0x48,0x59,0x73,0x0,0x0,0x4,0x9d,0x0,0x0,0x4,0x9d,0x1,0x7c,0x34, 0x6b,0xa1,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xd8,0x3,0xe,0xd,0x37, 0x1a,0xf0,0x7b,0xf3,0x1c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0, 0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x65,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0xf8,0xff,0xff,0x3f,0x3,0x25,0x98,0x81,0xaa,0x6,0xa8,0xa8,0xa8,0xb0, 0x2b,0x28,0x28,0x48,0x80,0x30,0x90,0xcd,0x7,0x56,0x0,0x1,0x2c,0x30,0x71,0x39, 0x39,0x39,0x41,0x9c,0x6,0xc8,0xcb,0xcb,0x3f,0x1,0xe2,0xd7,0x50,0xfc,0x2,0x24, 0x6,0xd4,0x0,0xc2,0x37,0x81,0xf8,0x2d,0x54,0xfc,0x29,0x3e,0x3,0xae,0x3,0xf1, 0x7f,0x28,0xbe,0xe,0x15,0x3,0xe1,0xa3,0x48,0xe2,0x8f,0x47,0xd,0x18,0xf6,0x6, 0x5c,0x45,0x4a,0x48,0xb7,0x70,0x24,0xa4,0xf7,0xb4,0x4b,0xca,0x3,0x92,0x1b,0x1, 0x3,0xb3,0x2a,0x68,0x60,0x12,0x9b,0xc0,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/DeleteHS.png 0x0,0x0,0x2,0xf3, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x44,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x4a,0x49,0x49,0x48,0x4a,0x49,0x48,0x49,0x49,0x4a,0x4a,0x49, 0x41,0x41,0x44,0x43,0x44,0x45,0x42,0x43,0x43,0x4b,0x4a,0x4b,0x4b,0x4c,0x4b,0x3a, 0x3d,0x40,0x52,0x51,0x50,0x47,0x47,0x46,0x3e,0x3f,0x42,0x37,0x39,0x3d,0x3f,0x40, 0x44,0x48,0x48,0x49,0x4d,0x4b,0x4b,0x24,0x29,0x31,0x3b,0x3f,0x42,0x4b,0x4a,0x4a, 0x40,0x40,0x42,0x40,0x41,0x44,0x3a,0x3c,0x3f,0x3e,0x3f,0x40,0x4f,0x4d,0x4b,0x4d, 0x4d,0x4c,0x35,0x38,0x3d,0x47,0x49,0x49,0x3d,0x3f,0x42,0x35,0x35,0x37,0x2a,0x2e, 0x34,0x3f,0x40,0x43,0x3e,0x3e,0x42,0x4c,0x4d,0x4d,0x39,0x3a,0x3f,0x3a,0x3a,0x3e, 0x3d,0x3c,0x3c,0x2e,0x31,0x34,0x26,0x2a,0x30,0x3b,0x3d,0x3d,0x3f,0x3f,0x42,0x36, 0x37,0x3b,0x32,0x33,0x36,0x31,0x33,0x32,0x26,0x2a,0x2d,0x23,0x27,0x2d,0x2f,0x30, 0x34,0x2e,0x2f,0x34,0x39,0x3a,0x3d,0x2e,0x2f,0x32,0x20,0x23,0x29,0x33,0x34,0x34, 0x26,0x27,0x2c,0x2d,0x2e,0x31,0x34,0x35,0x38,0x2a,0x2b,0x2d,0x31,0x32,0x35,0x26, 0x28,0x2b,0x28,0x29,0x2b,0x14,0x16,0x19,0x1e,0x1f,0x24,0x30,0x31,0x33,0x25,0x27, 0x2b,0x28,0x2b,0x2d,0x1d,0x20,0x23,0x1e,0x21,0x25,0x19,0x18,0x1a,0xc,0xe,0xe, 0xf,0x12,0x14,0x1f,0x22,0x26,0x30,0x30,0x33,0x25,0x2a,0x30,0x28,0x30,0x38,0x1e, 0x21,0x26,0x18,0x1b,0x21,0x2c,0x2d,0x31,0x2b,0x2d,0x2f,0xc,0x10,0x10,0x9,0x9, 0xb,0x2d,0x2f,0x31,0x19,0x1c,0x20,0x1c,0x21,0x26,0x1a,0x1d,0x20,0x16,0x18,0x20, 0x25,0x26,0x2b,0x24,0x26,0x28,0x9,0xb,0xd,0x4,0x4,0x3,0x24,0x24,0x25,0xd, 0x10,0x11,0x27,0x2d,0x34,0x10,0x10,0x12,0x14,0x14,0x16,0x12,0x13,0x17,0x1f,0x20, 0x23,0x8,0xa,0xc,0xc,0xe,0x10,0x10,0x10,0x11,0x36,0x36,0x39,0xb,0xd,0xa, 0x27,0x2e,0x37,0x1c,0x1f,0x25,0x5,0x6,0x7,0x0,0x1,0x2,0x3,0x4,0x4,0x2, 0x2,0x2,0xff,0xff,0xff,0x6b,0x1f,0x55,0x9e,0x0,0x0,0x0,0x1,0x74,0x52,0x4e, 0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x6b,0x52, 0x65,0xa5,0x98,0x0,0x0,0x0,0xa5,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x60, 0x64,0x62,0x66,0x61,0x40,0x2,0xac,0x6c,0xac,0xec,0x1c,0x9c,0x60,0x26,0x17,0x37, 0xf,0x48,0x80,0x95,0x97,0x8f,0x5f,0x40,0x10,0xc8,0x12,0x12,0x16,0x11,0x5,0x2b, 0x61,0x15,0x13,0x97,0x90,0x94,0x62,0x90,0x96,0x91,0x95,0x93,0x87,0xea,0x62,0x55, 0x50,0x54,0x52,0x56,0x51,0x55,0x53,0x87,0x99,0xa3,0xa1,0xc9,0xab,0xa5,0xad,0xa3, 0xab,0x87,0x64,0xb4,0xbe,0x81,0xa1,0x91,0x31,0x12,0xdf,0xc4,0xd4,0x4c,0xdf,0xdc, 0x2,0xc1,0xb7,0xb4,0x32,0xb5,0xb6,0xb1,0xb5,0xb3,0x87,0xf1,0x1d,0x1c,0x9d,0xcc, 0x9c,0x5d,0x5c,0xdd,0xdc,0x3d,0x20,0x7c,0x4f,0x2f,0x6f,0x1f,0x5f,0x6,0x6,0x3f, 0xff,0x80,0xc0,0x20,0xb0,0x40,0x70,0x48,0x68,0x58,0x38,0x90,0x8e,0x8,0x8b,0x8c, 0x8a,0x6,0xd2,0x31,0xb1,0x71,0xf1,0x9,0x89,0x20,0x99,0xa4,0xe4,0x94,0x54,0x10, 0x9d,0x96,0x9e,0x91,0x9,0x35,0x2d,0x8b,0x81,0x8,0x0,0x0,0x31,0xd9,0x17,0x48, 0x30,0xa6,0x39,0xc3,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30, 0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33, 0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/skip_forward.png 0x0,0x0,0x1,0x80, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x9,0x70,0x48,0x59,0x73,0x0,0x0,0x4,0x9d,0x0,0x0,0x4,0x9d,0x1,0x7c,0x34, 0x6b,0xa1,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xd8,0x3,0xe,0xd,0x2f, 0x21,0xc3,0x6b,0x82,0x61,0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0, 0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x1,0x0,0x49,0x44,0x41,0x54,0x38, 0xcb,0x63,0xf8,0xff,0xff,0x3f,0x3,0x25,0x98,0x61,0x68,0x1a,0xa0,0xa2,0xa2,0xc2, 0xc7,0xc0,0xc0,0xc0,0xc,0x37,0x40,0x5e,0x5e,0xfe,0x88,0x82,0x82,0xc2,0x36,0x59, 0x59,0x59,0x29,0x98,0x22,0x45,0x45,0x45,0x79,0x39,0x39,0xb9,0x67,0x40,0x5a,0x1d, 0x59,0xb3,0x8c,0x8c,0x8c,0x34,0x50,0xed,0x2b,0xa0,0xdc,0x77,0x64,0x3,0x2e,0x1, 0xf1,0x7f,0x20,0x7e,0x0,0x94,0x9c,0x28,0x25,0x25,0xc5,0x5,0xa4,0xc5,0x41,0x8a, 0x80,0xf8,0x29,0x10,0x2f,0x54,0x52,0x52,0xe2,0x7,0xa9,0x5,0x8a,0x2b,0x0,0xd5, 0xbd,0x5,0xe2,0xc7,0xd8,0xc,0x0,0xe1,0xdf,0x40,0x35,0xb7,0x80,0xb4,0x2c,0x10, 0x7f,0x83,0x8a,0xfd,0x3,0xe2,0xbb,0x40,0xf1,0x32,0xa0,0x2b,0x95,0x9,0x19,0x0, 0xc3,0x5f,0x81,0x36,0xff,0x45,0x13,0xfb,0xe,0x34,0xe4,0x26,0x10,0x7f,0x22,0xc6, 0x0,0x98,0xcd,0x28,0x62,0x40,0xcd,0xbf,0x80,0xf4,0x5f,0x42,0x6,0x7c,0x4,0xe2, 0xab,0x40,0xfc,0x3,0x4d,0xfc,0xe,0x10,0xf7,0xe2,0xf3,0xc2,0x2f,0xa0,0xd,0x37, 0x80,0x4e,0x8f,0x3,0xd2,0xdc,0x48,0x61,0xf0,0x14,0x88,0x97,0x2,0x63,0x40,0x8, 0x5f,0x20,0x82,0x42,0xbb,0x13,0x18,0xc7,0xec,0xd0,0xd0,0x16,0x7,0x19,0x0,0xa4, 0xf,0x1,0xc5,0xb5,0x60,0xd1,0x8,0x35,0xe0,0x3d,0xba,0x1,0x8d,0xca,0xca,0xca, 0x62,0xc8,0xf1,0x2d,0x2e,0x2e,0xce,0xa,0x14,0xaf,0xc0,0x92,0x88,0xd8,0x81,0x6, 0x9e,0x1,0xca,0xdd,0x1b,0xc2,0x79,0x1,0x19,0x3,0x0,0x80,0x64,0x28,0xce,0x10, 0xb9,0xd6,0x73,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/EditCodeHS.png 0x0,0x0,0x3,0x2b, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x56,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xa3,0xb2,0xc8,0xa5,0xb4,0xca,0xa6,0xb5,0xcb,0xa4,0xb3,0xc9, 0xa3,0xb2,0xc7,0xa1,0xb0,0xc6,0x9f,0xae,0xc3,0x9d,0xac,0xc1,0x9b,0xaa,0xbf,0x99, 0xa8,0xbd,0x97,0xa6,0xbb,0x95,0xa4,0xb9,0x94,0xa3,0xb8,0x93,0xa2,0xb7,0xff,0xff, 0xff,0xfb,0xfc,0xfe,0xf7,0xf9,0xfb,0xf2,0xf4,0xfa,0xed,0xf0,0xf7,0xe4,0xea,0xf3, 0x36,0x4a,0x64,0xa5,0xb4,0xc9,0x65,0xa3,0x66,0xad,0xb4,0xc0,0x64,0xa2,0x66,0xf2, 0xf5,0xfa,0xec,0xf0,0xf7,0xe6,0xeb,0xf4,0xda,0xe2,0xee,0xfc,0xfc,0xfd,0xf7,0xf8, 0xfc,0xf2,0xf5,0xf9,0xdf,0xe5,0xf1,0xa0,0xaf,0xc5,0x65,0x80,0xb4,0x88,0x8e,0x96, 0xa3,0xb0,0xc2,0x87,0x8e,0x96,0x86,0x8e,0x96,0xf2,0xf4,0xf9,0xec,0xef,0xf7,0xdf, 0xe5,0xf2,0xd8,0xdf,0xef,0xd1,0xdb,0xea,0x36,0x49,0x63,0x9c,0xab,0xc1,0xf7,0xf8, 0xfb,0xe6,0xea,0xf4,0xd7,0xdf,0xee,0xd0,0xd9,0xeb,0xc6,0xd1,0xe6,0x35,0x4a,0x63, 0x98,0xa7,0xbd,0xd7,0xde,0xee,0xd6,0xdd,0xed,0x86,0x8d,0x96,0x85,0x8c,0x95,0xd0, 0xd9,0xec,0xc9,0xd3,0xe8,0xba,0xc7,0xe0,0xf7,0xf9,0xfc,0xec,0xf0,0xf6,0xe5,0xeb, 0xf4,0xd8,0xdf,0xee,0xc8,0xd3,0xe8,0xc1,0xcc,0xe5,0xad,0xbd,0xdb,0x36,0x4a,0x63, 0x65,0x7f,0xb4,0x64,0x7f,0xb4,0xd5,0xdd,0xed,0x63,0x7e,0xb3,0xd7,0xdf,0xef,0xd1, 0xd9,0xeb,0xc1,0xcd,0xe5,0xb9,0xc6,0xe1,0xa1,0xb3,0xd6,0xfb,0xfc,0xfd,0xed,0xef, 0xf7,0xd7,0xdc,0xdd,0xce,0xd7,0xdf,0xc0,0xcd,0xde,0xb6,0xc5,0xde,0xac,0xbf,0xde, 0xa6,0xba,0xdb,0xa3,0xb5,0xd8,0x35,0x49,0x63,0x54,0x67,0x7f,0x4f,0x62,0x7a,0x4a, 0x5d,0x76,0x46,0x59,0x73,0x42,0x55,0x6e,0x3e,0x52,0x6b,0x3a,0x4e,0x67,0x38,0x4b, 0x65,0x88,0x98,0xae,0xdd,0xe3,0xef,0xe1,0xe7,0xf2,0xd7,0xdf,0xed,0x59,0x6b,0x83, 0x8b,0x9b,0xb7,0xa6,0xb7,0xd9,0x46,0x59,0x72,0x77,0x8b,0xae,0x92,0xa6,0xd0,0x87, 0x9e,0xcc,0x69,0x7a,0x92,0x63,0x75,0x8c,0x5e,0x70,0x87,0x54,0x66,0x7f,0x4a,0x5d, 0x75,0x41,0x54,0x6e,0x3e,0x51,0x6a,0xc6,0xd4,0x46,0xfd,0x0,0x0,0x0,0x1,0x74, 0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44, 0xf,0x18,0xba,0x0,0xd9,0x0,0x0,0x0,0xcb,0x49,0x44,0x41,0x54,0x18,0xd3,0x63, 0x60,0x40,0x7,0x8c,0x4c,0xcc,0x4c,0x2c,0xac,0x6c,0xec,0x1c,0x9c,0x5c,0xdc,0x3c, 0xbc,0x7c,0x40,0x1,0x7e,0x28,0x10,0x10,0x14,0x12,0x16,0x11,0x65,0x60,0x10,0xe3, 0xe7,0x17,0x17,0x17,0x97,0x10,0x17,0x97,0x94,0x92,0x96,0x91,0x15,0x85,0xab,0x90, 0x93,0x57,0x90,0x96,0x51,0x4,0x9,0x28,0xf1,0x2b,0x2b,0xab,0xa8,0xaa,0xa9,0x6b, 0x68,0xca,0x68,0x69,0xeb,0xe8,0x32,0x30,0xe8,0x81,0xe5,0xf5,0x85,0xa4,0xd,0x14, 0xd,0x8d,0x8c,0x4d,0x18,0x18,0x4c,0xf9,0x55,0xcc,0xd4,0xcc,0x2d,0x2c,0x81,0xf2, 0x56,0xd6,0x36,0x40,0x1,0x1e,0xa0,0xbc,0xad,0x90,0x9d,0xbd,0x96,0x83,0x91,0xa3, 0x93,0xb3,0xb,0x3,0x3,0x1f,0xbf,0xab,0x9b,0xbb,0x87,0x8c,0xa2,0xa7,0x97,0xb5, 0xb7,0x8f,0x2f,0x50,0x5,0x9f,0x9f,0xa0,0x94,0xbf,0x81,0x56,0x40,0x60,0x50,0x70, 0x48,0x68,0x58,0x38,0x50,0x40,0x5f,0x3,0x68,0x5f,0x44,0x64,0x54,0x74,0x4c,0x6c, 0x5c,0x3c,0x50,0x20,0x3c,0x21,0x31,0x29,0x39,0x25,0xd5,0x39,0x2d,0x3d,0x23,0x33, 0xb,0x2c,0x10,0x9e,0x9d,0x93,0x1b,0x9e,0x17,0x99,0x1f,0x5e,0x50,0x18,0x17,0xce, 0x40,0x4,0x0,0x0,0x2d,0xc8,0x23,0xbd,0xa8,0xd2,0x9e,0xa1,0x0,0x0,0x0,0x25, 0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0, 0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31, 0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0, 0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79, 0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33, 0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0, 0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/BreakpointHS.png 0x0,0x0,0x3,0x33, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x77,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xca,0xc6,0xbc,0x9f,0x9b,0x85,0xa4,0x9b,0x88,0x79,0x75,0x6e, 0xb8,0xb6,0xaf,0x8d,0x84,0x77,0xa9,0x9f,0x87,0xf5,0xe0,0x83,0xa0,0x96,0x83,0xa9, 0xa0,0x87,0xb1,0xa9,0x9b,0xa3,0x9a,0x87,0xf6,0xe1,0x83,0xff,0xea,0x90,0xa1,0x98, 0x83,0xf7,0xe1,0x85,0xd0,0xc9,0xbd,0x9f,0x94,0x81,0xfe,0xe9,0x8f,0xa4,0x9b,0x87, 0xa1,0x95,0x82,0xa2,0x98,0x86,0x98,0x8d,0x7c,0xa1,0x9b,0x8e,0x9c,0x91,0x7e,0xfe, 0xe9,0x8e,0xa2,0x97,0x81,0xff,0xe9,0x90,0x9e,0x91,0x7d,0xfe,0xea,0x90,0x9f,0x95, 0x81,0x97,0x8d,0x79,0x90,0x82,0x6d,0x9e,0x92,0x79,0xfe,0xe8,0x90,0x98,0x8a,0x74, 0xfd,0xe9,0x8e,0x97,0x89,0x75,0xfa,0xe2,0x88,0x85,0x77,0x62,0x9e,0x94,0x81,0xb7, 0xb2,0xa1,0x87,0x75,0x5f,0xfe,0xe8,0x8e,0x9a,0x8f,0x71,0xfa,0xe3,0x8a,0x96,0x85, 0x68,0xfa,0xe4,0x89,0x8c,0x7a,0x65,0xf6,0xe1,0x84,0x72,0x63,0x4e,0xa2,0x98,0x85, 0xf0,0xdc,0x83,0xaa,0x9e,0x80,0x7c,0x68,0x50,0xfc,0xe6,0x8a,0xba,0xa8,0x70,0xf2, 0xd9,0x7d,0xc1,0xac,0x6d,0xf3,0xdd,0x7f,0xa8,0x93,0x66,0xf2,0xd8,0x7b,0x6b,0x5b, 0x46,0x72,0x5b,0x40,0xeb,0xd6,0x80,0xf1,0xdb,0x7c,0x97,0x80,0x50,0xf7,0xe2,0x87, 0xef,0xdb,0x82,0xf0,0xda,0x7c,0xef,0xd8,0x79,0xee,0xd8,0x75,0xf0,0xd9,0x79,0xe6, 0xce,0x6a,0x63,0x52,0x3c,0xa5,0x9b,0x89,0xeb,0xd2,0x73,0xea,0xcf,0x6e,0xef,0xd7, 0x80,0xf2,0xda,0x82,0xf1,0xd8,0x7f,0xec,0xd5,0x7b,0xe8,0xd1,0x77,0xe8,0xce,0x6f, 0xd9,0xb9,0x57,0x5c,0x4b,0x37,0x9b,0x91,0x7d,0xe5,0xc9,0x68,0xe6,0xca,0x6e,0xea, 0xd1,0x77,0xed,0xd5,0x7a,0xeb,0xd3,0x78,0xe2,0xc8,0x66,0xd0,0xad,0x47,0xc0,0x9d, 0x3e,0x59,0x4a,0x34,0xac,0xa9,0x90,0x77,0x60,0x47,0xd1,0xb4,0x53,0xcf,0xb0,0x50, 0xd5,0xb6,0x52,0xd2,0xb0,0x4c,0xcc,0xa9,0x42,0xc9,0xa4,0x3c,0x88,0x6e,0x3c,0x73, 0x5e,0x47,0xa0,0x86,0x81,0x7d,0x68,0x51,0xab,0x8e,0x44,0xbb,0x9a,0x41,0xc1,0x9e, 0x3e,0xb5,0x94,0x38,0x79,0x63,0x33,0x49,0x3d,0x2a,0x76,0x5e,0x48,0x7e,0x67,0x47, 0x7e,0x6e,0x57,0x5c,0x4f,0x3a,0x39,0x2d,0x1b,0x35,0x29,0x17,0x42,0x37,0x20,0x5c, 0x48,0x32,0x74,0x59,0x41,0xff,0xff,0xff,0xdc,0xed,0x7a,0x37,0x0,0x0,0x0,0x1, 0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47, 0x44,0x7c,0xd1,0xb6,0x20,0x5f,0x0,0x0,0x0,0xb2,0x49,0x44,0x41,0x54,0x18,0xd3, 0x63,0x60,0xc0,0xe,0x18,0x99,0x98,0x59,0x58,0x91,0xf8,0x6c,0xec,0xcc,0x1c,0x9c, 0x5c,0xdc,0x8,0x1,0x1e,0x5e,0x66,0x3e,0x7e,0x1,0x66,0x41,0xb8,0x80,0x90,0xb0, 0x8,0x9f,0xa8,0xb0,0x98,0xb8,0x4,0x4c,0x40,0x52,0x4a,0x5a,0x46,0x56,0x4e,0x9e, 0x43,0x1,0x26,0xa0,0x28,0xac,0xa4,0xac,0xa2,0xaa,0xa6,0xae,0x1,0xe2,0xc8,0x6b, 0x6a,0x6a,0x69,0xeb,0xe8,0xea,0xe9,0x1b,0x18,0x1a,0x19,0x3,0xf9,0xcc,0x26,0xa6, 0xbc,0x66,0xe6,0x16,0x96,0x56,0xd6,0x36,0xb6,0x76,0xf6,0x20,0x15,0xcc,0xe,0x8e, 0x4e,0xce,0x2e,0xae,0x6e,0xee,0x1e,0x9e,0x5e,0xde,0x60,0x3,0x7c,0x1c,0x7c,0xfd, 0xfc,0x3,0x2,0x83,0x82,0x43,0x42,0xc3,0x20,0x46,0x86,0x3b,0x44,0x44,0x46,0x45, 0xc7,0xc4,0xc6,0xc5,0x27,0x40,0x4,0x12,0x93,0x1c,0x92,0x53,0x52,0xd3,0xd2,0x33, 0x32,0xb3,0xa0,0xb6,0x66,0xe7,0x38,0xe4,0xe6,0xe5,0x17,0x14,0x16,0x15,0xc3,0xdc, 0x51,0x52,0x5a,0x56,0x5e,0x51,0x59,0x55,0x8d,0xcd,0xdf,0x0,0x6,0x5a,0x1f,0x6b, 0x5,0x52,0xc6,0x33,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30, 0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33, 0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_CreateEntity.png 0x0,0x0,0x5,0xc3, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x4,0xb8,0x49,0x44,0x41,0x54,0x58,0xc3,0xed,0x96,0x6d,0x68,0x56,0x65, 0x18,0xc7,0x7f,0xf7,0x7d,0xce,0x79,0xf6,0x3c,0x8f,0xcc,0xf9,0xee,0x5a,0x73,0xf9, 0xb8,0x89,0x93,0x69,0x44,0x19,0x19,0x32,0x14,0x45,0xa7,0x4e,0x49,0x90,0x70,0x11, 0x14,0x81,0x86,0x7d,0x28,0x32,0xfb,0x54,0x83,0x4a,0x43,0x3f,0xf5,0xf2,0xa5,0x4f, 0x5a,0x42,0x10,0x98,0x20,0xb8,0x50,0x6c,0x48,0xa5,0x8c,0x21,0xa6,0x85,0x24,0xc3, 0x89,0xe,0xd7,0x9c,0x2f,0x7b,0xd3,0x67,0x9b,0xcf,0xeb,0x79,0xb9,0xfa,0x70,0xce, 0xf3,0x6c,0xd3,0x39,0x37,0x89,0xec,0x83,0xd7,0x87,0xc3,0x7d,0x5f,0xe7,0x77,0x5f, 0xf7,0xff,0x5c,0xe7,0xba,0x5f,0x94,0x88,0x8,0x8f,0xd1,0xf4,0xe3,0x9c,0x1c,0x40, 0x3d,0xea,0xc0,0xbd,0x6f,0x2e,0x92,0xa2,0xa8,0xaf,0x3f,0x99,0x15,0x3e,0xfc,0xf6, 0xc2,0x23,0xc5,0x9a,0xf0,0xa0,0xb7,0xd7,0xc6,0xa4,0xaa,0x6c,0x12,0xb1,0x8a,0x5, 0x2c,0x5b,0xb5,0xe,0x80,0xe6,0x5f,0x8e,0xd3,0x7e,0xe5,0x12,0xe7,0xaf,0xde,0xe5, 0xbb,0x13,0xed,0x13,0x8a,0x39,0x21,0xf8,0xab,0xad,0x55,0x32,0xbb,0xb8,0x98,0xa5, 0xcb,0x6b,0x98,0x59,0x5c,0x42,0xba,0xef,0x2a,0x0,0xe1,0xe9,0x31,0x7a,0x6e,0xdd, 0xe0,0xf4,0x6f,0x3f,0xd3,0xdd,0xdd,0xc5,0x8e,0xfd,0x2d,0xe3,0x8e,0x3b,0x2e,0x70, 0xcf,0x1b,0xb,0x65,0x5a,0x51,0x94,0x65,0x2b,0x6b,0x29,0xaf,0x7a,0x8e,0xf4,0xed, 0xe,0x52,0xdd,0x17,0x11,0xd7,0xf6,0x83,0x18,0x16,0x91,0x59,0xb,0x9,0x4f,0x2b, 0xa3,0xad,0xe5,0x3c,0xcd,0xbf,0x1e,0xe3,0x76,0x7f,0x92,0x8f,0xbe,0xbf,0xf8,0xd0, 0xf8,0x63,0x2,0xdb,0x6a,0x9e,0x91,0xaa,0xd2,0x28,0x2f,0xad,0xa8,0x61,0xf1,0x92, 0x6a,0x70,0x92,0xa4,0x7b,0x5b,0x51,0xd6,0x24,0x8a,0xca,0xab,0x31,0xa,0xc2,0x0, 0xb8,0x99,0x34,0xfd,0x6d,0x4d,0x88,0x9d,0x20,0x3c,0xa3,0x12,0xcc,0x28,0x17,0xce, 0x35,0x71,0xe6,0x64,0x23,0x2d,0x9d,0x49,0xf6,0x35,0xfe,0xad,0x26,0x2c,0xe0,0x8b, 0xb7,0x16,0x48,0xe5,0xb3,0x2f,0xb0,0x6c,0xf5,0x26,0xc2,0x91,0x30,0x99,0xbe,0xcb, 0x38,0xa9,0x3e,0x44,0x84,0xc2,0xd8,0xa,0xbc,0xc4,0x4d,0x3c,0x7b,0x10,0x0,0x1d, 0x2a,0x44,0x47,0x8a,0x19,0x6c,0x3f,0x85,0x52,0xa,0x33,0x32,0x9d,0x82,0xe9,0xf3, 0x49,0xa7,0xd2,0x34,0x9f,0x38,0x42,0xeb,0x5f,0x7f,0xb0,0xf3,0xc0,0x25,0x35,0x2e, 0x1,0x9f,0xbf,0x3e,0x5f,0xca,0x2b,0xca,0xa9,0xae,0xd9,0xcc,0x53,0x65,0x73,0xc9, 0xc4,0xaf,0x93,0x1d,0xec,0xf4,0x51,0xa5,0x40,0x40,0x59,0x51,0xc4,0x4e,0xfa,0x7d, 0x0,0x11,0xdf,0xe7,0x24,0xf3,0x7d,0x10,0x42,0x85,0xa5,0x14,0x4c,0x79,0x9a,0x9b, 0x1d,0xed,0x34,0x35,0x1e,0xa6,0xed,0x4a,0x1b,0xf5,0x3f,0x5c,0x56,0xa3,0xa,0xd8, 0xba,0xba,0x4c,0x96,0x54,0xce,0x62,0xf9,0x86,0x3a,0x2a,0x9f,0x7f,0x19,0x7b,0xb0, 0xb,0xbb,0xbf,0x3,0xcf,0x73,0x83,0x89,0x54,0x7e,0x48,0x66,0xa0,0x1b,0xcf,0xf5, 0x50,0x81,0x0,0x11,0x1,0xa5,0x88,0x4c,0x9d,0x1d,0x4c,0xe,0x20,0x20,0x82,0xd6, 0x6,0x56,0x51,0x19,0x56,0xe1,0x6c,0x5a,0xff,0x3c,0xcd,0xa9,0xa3,0x7,0x39,0xd7, 0xda,0xcd,0xfe,0x13,0x1d,0x2a,0x2f,0xe0,0xeb,0x6d,0x8b,0x65,0xd5,0x2b,0x75,0x54, 0xbd,0xb8,0x2,0x25,0x19,0xec,0x81,0x6b,0xfe,0x17,0xe6,0xbe,0x7a,0x44,0xa2,0x14, 0xae,0x9d,0x66,0xe0,0x46,0x1b,0x8e,0x9d,0x6,0xc0,0xb4,0xc2,0x4c,0x2e,0xa9,0xc0, 0x8,0x15,0xc,0x13,0x30,0x94,0x9,0xf0,0x33,0x64,0x4d,0x9e,0x83,0xa8,0x2,0x5a, 0xce,0x9e,0xe4,0x97,0x86,0x83,0xbc,0xbf,0xef,0x82,0x32,0x1,0x42,0xa6,0x62,0x51, 0xed,0x16,0xe8,0x6b,0x83,0x74,0x1c,0x2b,0x1c,0x86,0x70,0x24,0x98,0x57,0x81,0xe, 0x44,0xa8,0x20,0x1e,0x10,0x99,0x51,0x32,0x4c,0xa0,0x4,0x7e,0x19,0x62,0x44,0x40, 0x3c,0xbf,0x9d,0xd3,0xef,0xf4,0xa2,0xc2,0x53,0x58,0x54,0xbb,0x85,0xa6,0x63,0x3f, 0xfa,0xe2,0x1,0x12,0x59,0xe1,0x9b,0xed,0x9b,0xb0,0xb3,0x59,0x6c,0xdb,0xa6,0x74, 0xee,0x3c,0x5c,0x27,0x3,0x8e,0x8d,0xe7,0xb9,0xc4,0x7,0x92,0x78,0x9e,0x9f,0x72, 0xcf,0xf3,0x70,0x6c,0x9b,0x39,0xb1,0x18,0x8e,0x93,0xf5,0x19,0xd7,0x19,0x95,0x29, 0x8d,0xc5,0x70,0xed,0xe1,0x71,0x12,0x78,0x9e,0x60,0x59,0x26,0x29,0x47,0xdd,0x5f, 0x84,0xc7,0x76,0x6f,0x94,0xf5,0xef,0x6e,0x87,0xde,0x2e,0xd2,0x77,0xef,0x60,0x27, 0x7,0xb0,0x13,0x83,0x28,0x2f,0xc3,0xe9,0xb3,0x9d,0xd4,0xd6,0x37,0xa8,0xa3,0xbb, 0x36,0x4a,0xed,0x7b,0xef,0x40,0xef,0xad,0x51,0x98,0xeb,0xd4,0xd6,0x1f,0x19,0x17, 0xf3,0xc0,0x55,0x70,0xf8,0xe3,0x3a,0x59,0xba,0x66,0x9,0xa9,0x78,0x1c,0x3b,0xd5, 0x8f,0x93,0x49,0xd0,0xd3,0x2b,0xac,0xdc,0x79,0x40,0xd,0x31,0x6b,0x64,0xe9,0x9a, 0xb5,0xa4,0xe2,0x77,0xb0,0x53,0x71,0x9c,0x4c,0x92,0x9e,0xde,0x38,0x2b,0x77,0x1e, 0x9e,0x10,0x93,0xff,0x5,0x23,0x96,0x85,0x86,0x92,0x8a,0x39,0x24,0xbb,0xc,0x52, 0xfd,0xe,0x4e,0x22,0x4b,0x4f,0x6f,0xe6,0x1e,0x46,0x5,0x8c,0x22,0xd5,0x6f,0xe3, 0x24,0x6c,0x7a,0x7a,0x99,0x30,0x3,0xa3,0x1d,0xc7,0x41,0x1,0x89,0x8,0xe2,0x49, 0x50,0xd4,0x32,0x6,0x33,0xb2,0xf0,0xc7,0x62,0x46,0xe3,0x1e,0x78,0x1f,0xc8,0x2d, 0xa0,0xb1,0xec,0xdf,0x60,0x1e,0xfb,0x85,0xe4,0x89,0x80,0xff,0x9f,0x0,0x11,0xb9, 0xbf,0xe8,0x45,0x8d,0xc2,0xc8,0x3d,0x3e,0x1e,0xca,0x8c,0x4b,0xc0,0xcc,0x92,0x59, 0x88,0xeb,0x80,0x4,0xa7,0x9d,0x52,0x44,0xa3,0xc6,0x3d,0x4c,0xc9,0x30,0x86,0x80, 0xb1,0x26,0xcc,0xdc,0x27,0xe0,0xc8,0x27,0xeb,0xa4,0xba,0x6e,0x35,0x92,0x4d,0xa3, 0x35,0x58,0x21,0xb,0x33,0x14,0xa6,0x22,0x16,0xa2,0xe1,0xb3,0xd,0xe2,0x33,0xeb, 0xa5,0xba,0x6e,0xf3,0x30,0x26,0x84,0x19,0xa,0x33,0x7f,0xde,0x54,0x1a,0x76,0x6d, 0xf4,0x99,0x4f,0xd7,0x4b,0xf5,0x6b,0x3e,0x63,0x68,0xb0,0xa,0x72,0xcc,0x34,0x7e, 0xa,0x98,0x9c,0xe5,0x73,0x7b,0xa8,0x7e,0xad,0x98,0x4a,0x70,0xb2,0x36,0x9e,0xe7, 0x9f,0xef,0x4a,0x69,0x94,0x52,0x28,0xad,0xd1,0x86,0x42,0xa1,0x10,0xf1,0x70,0x1d, 0xd7,0x4f,0x31,0x3e,0x83,0x56,0x68,0xad,0xd1,0x5a,0xf9,0x77,0x16,0x4f,0x70,0x5d, 0x17,0x9,0xe2,0xe4,0x62,0x69,0xad,0x30,0xc,0x8d,0xed,0xba,0xbc,0xba,0xfb,0xb8, 0x82,0x61,0x5b,0xb1,0xa5,0x15,0x9b,0x3e,0xd8,0x1,0x99,0x34,0xb8,0xe,0x78,0xe, 0xb8,0x2e,0xb8,0xe,0xe2,0x39,0x88,0xeb,0xe2,0xba,0xe,0xe2,0x3a,0x78,0xae,0x7f, 0x2,0xe6,0xfc,0x9e,0xeb,0x4,0x7d,0x37,0xf0,0xf9,0x8c,0xeb,0x3a,0x88,0xe3,0x91, 0xdf,0x8e,0x94,0xc2,0x50,0x8a,0xe6,0xdf,0x3b,0x47,0x66,0xe0,0x50,0xfd,0x3a,0x59, 0x55,0x1d,0xc3,0xb6,0x1d,0xc4,0xf3,0x86,0x5e,0x2a,0x85,0x32,0x4c,0xb4,0x36,0x51, 0x86,0x89,0x32,0x8c,0xa1,0xb6,0xe,0xfa,0x86,0x81,0xd2,0x26,0x46,0xde,0xa7,0xd1, 0xf9,0xb6,0xcf,0xa0,0x4d,0xd0,0x6,0x18,0x26,0x98,0x16,0x84,0x43,0x1c,0xda,0xfb, 0x25,0x5b,0xf6,0x34,0xfa,0x17,0x92,0x68,0xd8,0xa2,0xf9,0xcc,0x35,0x3f,0xf5,0xa3, 0x59,0x50,0xcd,0x43,0x6f,0xe5,0x81,0xcc,0x48,0xdf,0x10,0x9b,0x7b,0x2a,0x14,0x4a, 0x2b,0xa2,0x91,0xd0,0x43,0x57,0xc8,0x13,0xfb,0x4f,0xec,0x1f,0xa9,0xac,0x9f,0x45, 0x2b,0x33,0x56,0xfc,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65, 0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d, 0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30, 0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74, 0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33, 0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x35,0x36,0x3a,0x31,0x34,0x2b,0x31,0x30,0x3a, 0x30,0x30,0xd9,0xf3,0x7,0xc,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_LocalCoordSystem.png 0x0,0x0,0x1,0x2e, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x27, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x31,0x50,0x51,0x1, 0xe3,0x7f,0xc6,0xff,0x94,0x99,0x30,0x84,0x15,0xb0,0xa0,0x72,0x61,0x21,0xf1,0x9f, 0x11,0x5d,0x64,0x20,0x1d,0x9,0x0,0x16,0xaf,0x6,0x1f,0xed,0xf3,0x8,0x49,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61, 0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30, 0x3a,0x30,0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64, 0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32, 0x32,0x3a,0x33,0x30,0x3a,0x31,0x30,0x2b,0x31,0x30,0x3a,0x30,0x30,0xc8,0x17,0x99, 0x1b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/camera.png 0x0,0x0,0x3,0x66, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0xf,0x8,0x3,0x0,0x0,0x0,0xda,0xad,0xbf,0x1d, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x65,0x50,0x4c,0x54, 0x45,0xff,0x0,0xff,0xe5,0xe5,0xe5,0xca,0xca,0xca,0xad,0xad,0xad,0xa9,0xa9,0xa9, 0x9c,0x9c,0x9c,0xbd,0xbd,0xbd,0xc3,0xc3,0xc3,0xcc,0xcc,0xcc,0xbc,0xbc,0xbc,0xbb, 0xbb,0xbb,0xc7,0xc7,0xc7,0xc4,0xc4,0xc4,0xf1,0xf1,0xf1,0xdd,0xdd,0xdd,0x98,0x98, 0x98,0x86,0x86,0x86,0x94,0x94,0x94,0x81,0x81,0x81,0x96,0x96,0x96,0x69,0x69,0x69, 0xbf,0xbf,0xbf,0xfe,0xfe,0xfe,0xd8,0xd8,0xd8,0xa3,0xa3,0xa3,0xe8,0xe8,0xe8,0xa7, 0xa7,0xa7,0xd2,0xd2,0xd2,0x9d,0x9d,0x9d,0x65,0x65,0x65,0x59,0x59,0x59,0x63,0x63, 0x63,0x92,0x92,0x92,0xd6,0xd6,0xd6,0xee,0xee,0xee,0xd4,0xd4,0xd4,0xb9,0xb9,0xb9, 0x8c,0x8c,0x8c,0x95,0x95,0x95,0xac,0xac,0xac,0xc9,0xc9,0xc9,0x9b,0x9b,0x9b,0x8f, 0x8f,0x8f,0x84,0x84,0x84,0x43,0x43,0x43,0xc5,0xc5,0xc5,0xcd,0xcd,0xcd,0xde,0xde, 0xde,0xd3,0xd3,0xd3,0xb2,0xb2,0xb2,0xb5,0xb5,0xb5,0x77,0x77,0x77,0x88,0x88,0x88, 0xd9,0xd9,0xd9,0x40,0x40,0x40,0xb6,0xb6,0xb6,0xdb,0xdb,0xdb,0xda,0xda,0xda,0x6b, 0x6b,0x6b,0x53,0x53,0x53,0x5f,0x5f,0x5f,0x72,0x72,0x72,0x99,0x99,0x99,0x90,0x90, 0x90,0xd7,0xd7,0xd7,0xe2,0xe2,0xe2,0x5e,0x5e,0x5e,0x49,0x49,0x49,0x39,0x76,0xa3, 0x49,0x51,0x58,0xd0,0xd0,0xd0,0xa0,0xa0,0xa0,0x8d,0x8d,0x8d,0xc0,0xc0,0xc0,0xcb, 0xcb,0xcb,0x50,0x50,0x50,0x0,0x5a,0xc0,0x46,0x59,0x6c,0x54,0x54,0x54,0x8b,0x8b, 0x8b,0xbe,0xbe,0xbe,0xd1,0xd1,0xd1,0x53,0x56,0x5c,0x44,0x44,0x44,0x6d,0x6d,0x6d, 0xae,0xae,0xae,0x89,0x89,0x89,0xef,0xef,0xef,0x82,0x82,0x82,0x4f,0x4f,0x4f,0x4e, 0x4e,0x4e,0xc1,0xc1,0xc1,0xba,0xba,0xba,0xf4,0xf4,0xf4,0xdc,0xdc,0xdc,0xa4,0xa4, 0xa4,0x91,0x91,0x91,0x83,0x83,0x83,0x5c,0x5c,0x5c,0x4d,0x4d,0x4d,0xaf,0xaf,0xaf, 0xc6,0xc6,0xc6,0xec,0xec,0xec,0xf2,0xf2,0xf2,0x42,0x42,0x42,0x52,0x52,0x52,0xc8, 0xc8,0xc8,0x8a,0x8a,0x8a,0xb8,0xb8,0xb8,0xd5,0xd5,0xd5,0x5d,0x5d,0x5d,0x67,0x67, 0x67,0x8e,0x8e,0x8e,0x5a,0x5a,0x5a,0xe0,0xe0,0xe0,0x9f,0x9f,0x9f,0x80,0x80,0x80, 0xb3,0xb3,0xb3,0xff,0xff,0xff,0x57,0xa3,0xd0,0x3,0x0,0x0,0x0,0x1,0x62,0x4b, 0x47,0x44,0x76,0x31,0x63,0xc9,0x41,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc3,0x0,0x0,0xe,0xc3,0x1,0xc7,0x6f,0xa8,0x64,0x0,0x0,0x0,0xef, 0x49,0x44,0x41,0x54,0x8,0xd7,0x63,0x60,0x0,0x3,0x46,0x26,0x66,0x16,0x56,0x56, 0x36,0x76,0x10,0x9b,0x83,0x93,0x8b,0x9b,0x99,0x87,0x97,0x8f,0x5f,0x40,0x50,0x48, 0x58,0x84,0x81,0x41,0x54,0x4c,0x5c,0x42,0x52,0x42,0x4a,0x5a,0x94,0x55,0x46,0x56, 0x4e,0x5e,0x44,0x96,0x41,0x41,0x51,0x49,0x59,0x45,0x95,0x85,0x45,0x4d,0x5d,0x43, 0x53,0x48,0x4b,0x5b,0x87,0x41,0x57,0x8f,0x4b,0xdf,0x40,0xd7,0xd0,0x88,0x51,0xdd, 0xd8,0xc4,0xd4,0x50,0xc1,0x8c,0xc1,0x5c,0xd7,0xc2,0x42,0xda,0xd2,0x54,0x59,0xc1, 0xca,0xda,0xc6,0x56,0xcf,0xce,0x8c,0xc1,0x9e,0xdd,0xc1,0x41,0x4f,0xda,0xd1,0xc1, 0xc9,0xd9,0xc5,0x55,0xce,0xcd,0xdd,0x8c,0xc1,0xc3,0x53,0x59,0xd9,0xcb,0x8b,0x51, 0x43,0xce,0xdb,0xc7,0xd7,0x8f,0x49,0xca,0x8c,0xc1,0x3f,0x20,0x30,0x90,0x5b,0x5a, 0x92,0xcb,0xda,0x2c,0x28,0x38,0xc4,0x2b,0xd4,0x8c,0x21,0x8c,0x53,0x4f,0x8f,0x4b, 0x3a,0x9c,0x2b,0x22,0x32,0xca,0xda,0x8e,0x8f,0xc5,0x8c,0xc1,0xd6,0x30,0x5a,0x23, 0x46,0x3a,0x36,0x2e,0x3e,0x21,0x51,0xc6,0x2d,0x3e,0x29,0x99,0x41,0x53,0x2f,0x25, 0x55,0xc5,0x2b,0x2d,0x3d,0xcd,0x4d,0x2d,0x24,0x23,0xd3,0x8a,0x95,0x21,0x2b,0x9b, 0xdb,0x2d,0xc7,0x31,0x37,0x25,0x2f,0x23,0x33,0xbf,0x20,0x6,0xe4,0x17,0xf6,0x10, 0x1,0xe3,0x42,0x38,0xf,0x4,0x8a,0x8a,0xf3,0x93,0x4a,0x4a,0x61,0x3c,0x0,0x7f, 0xb3,0x2b,0xf0,0xfd,0xc8,0x15,0x80,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64, 0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d, 0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31, 0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74, 0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30, 0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b, 0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e, 0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Back_16x16.png 0x0,0x0,0x2,0xf5, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13, 0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a, 0x25,0x0,0x0,0x80,0x83,0x0,0x0,0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75, 0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5, 0x46,0x0,0x0,0x2,0x7b,0x49,0x44,0x41,0x54,0x78,0xda,0x9c,0x93,0x3b,0x4c,0x93, 0x51,0x18,0x86,0x1f,0xda,0x42,0x29,0x52,0xb9,0x14,0x24,0xb6,0x8a,0x5c,0x84,0x20, 0x81,0x4,0x30,0x2a,0xb,0x86,0xe2,0xa0,0x93,0x21,0x71,0x84,0xe8,0xe2,0x84,0xb, 0x1b,0x9,0x89,0xc6,0x84,0x44,0x65,0x72,0x51,0x71,0x60,0x21,0x41,0x13,0x37,0xe2, 0xe0,0x2d,0x24,0xc,0x2e,0xc,0x5a,0x1c,0x20,0x86,0x4b,0x40,0xa0,0x41,0xcb,0xb5, 0x2d,0xfd,0xdb,0xfe,0xfd,0xcf,0xc5,0x1,0xfa,0xc7,0x46,0x27,0xdf,0xf1,0x24,0xcf, 0x73,0xce,0xf7,0xe6,0x7c,0x79,0x5a,0x6b,0xb2,0xe9,0x99,0xe,0xfa,0xb5,0x9b,0x3b, 0xc0,0x23,0xfe,0xce,0x30,0x30,0x31,0xd3,0x35,0xb3,0xf5,0xe7,0x61,0x5e,0x56,0xd0, 0x33,0x1d,0x6c,0xd7,0x6e,0x42,0x1e,0x8f,0x9b,0x1b,0x25,0x5d,0x54,0x3a,0xa,0xd9, 0x49,0xad,0xb2,0x9f,0xe,0xb3,0x91,0x58,0x63,0x21,0xbe,0x4d,0x99,0xab,0x5,0xd3, 0x2b,0x3b,0x66,0xba,0x66,0xe6,0x72,0x4,0x59,0xb8,0xbb,0xf2,0xa,0xad,0x9e,0xda, 0x23,0x30,0x15,0x66,0x2f,0xf5,0x83,0xb4,0x4c,0xd8,0xb7,0x1d,0x5a,0x19,0x66,0xd7, 0xa3,0xf8,0xcf,0x37,0xd9,0x12,0xc7,0xf1,0xb3,0x43,0xd7,0x2a,0x2e,0x51,0xe3,0x3c, 0xc1,0x7a,0x3c,0xc4,0x7a,0x2c,0x44,0x75,0x71,0x3,0x23,0x97,0x3f,0x10,0xc,0xf4, 0xd9,0x2,0x6f,0x7e,0x1,0x57,0x6b,0x7d,0x44,0xe6,0x37,0x43,0xc1,0xcf,0xc1,0x4e, 0x0,0x7,0xd0,0x2b,0x44,0x8c,0x72,0x2d,0xd9,0x88,0x7f,0x63,0x23,0x3e,0x47,0x73, 0x59,0x27,0x7d,0xd,0xf,0xf1,0xb8,0xbc,0x94,0xbb,0x3,0x39,0x45,0x14,0x38,0x1d, 0x94,0x53,0x8a,0x35,0x7f,0xd8,0x96,0x15,0x3c,0xbf,0x50,0xe8,0x63,0x3d,0xfe,0x95, 0x48,0x72,0x85,0x8b,0x95,0xd7,0xe9,0x6f,0x1c,0x1,0x20,0x6c,0x2c,0xf2,0x6e,0x63, 0xcc,0x86,0x2d,0xad,0x88,0xca,0x34,0x67,0x9a,0xa2,0xc4,0x8c,0xe8,0x18,0x80,0xb, 0xc0,0x23,0xf,0x30,0xb4,0x45,0x67,0xd5,0x4d,0x1b,0x6,0x58,0x8e,0x7e,0x21,0x18, 0xe8,0x7,0x40,0x68,0x85,0xa5,0x25,0xaf,0x56,0x9f,0x92,0x90,0x16,0x3f,0x13,0x3b, 0x1c,0x9,0x24,0x48,0x6d,0xe1,0x2b,0xf4,0xe7,0xc0,0x40,0xce,0xfc,0xd9,0xbc,0x5c, 0x1e,0x25,0xa9,0x4,0x79,0xda,0x71,0x2c,0x30,0x81,0x22,0xd8,0x4b,0x6f,0x31,0xb9, 0x74,0xdf,0x96,0x24,0x45,0x9c,0xf7,0xe1,0x9,0x0,0x52,0x4a,0xa0,0xd1,0xc7,0x23, 0x98,0x58,0x5a,0x22,0x4c,0x81,0x3d,0xc2,0xa1,0x99,0xc1,0xeb,0x2e,0x60,0x36,0xf2, 0x16,0x5,0xdc,0x6e,0x1c,0xa1,0xc8,0x75,0x12,0x9f,0xdb,0xcf,0x93,0x85,0x41,0x84, 0x56,0x18,0xca,0x22,0xad,0x24,0x19,0x2d,0x39,0x94,0x16,0x55,0xce,0xb3,0x64,0x4b, 0xbc,0xb7,0x18,0x39,0xb0,0x4b,0xfa,0xb8,0xf5,0x86,0x17,0xdf,0x87,0x0,0xe8,0x3e, 0x7d,0x8b,0xbb,0xd,0xf,0xd8,0x17,0x26,0x49,0x25,0x88,0x49,0x93,0xb8,0xcc,0x60, 0xac,0x48,0x44,0x44,0xd,0x65,0x5,0x53,0x65,0xb4,0xf0,0xcb,0x30,0x88,0xcb,0x34, 0x29,0x25,0x98,0xa,0xbf,0x66,0x74,0x7e,0x10,0x0,0x5f,0x61,0x0,0x43,0x59,0x1c, 0x8,0x93,0x94,0x12,0xc4,0x84,0x89,0x63,0xd9,0x3,0x30,0x69,0xff,0xc4,0xa2,0x1, 0x67,0xbb,0xbf,0xbe,0x32,0x54,0xd7,0x9c,0x8f,0x76,0x69,0x92,0x4a,0x90,0x54,0x16, 0x75,0xde,0x66,0x96,0x13,0xab,0xec,0x5b,0xfb,0x24,0xa5,0x20,0xad,0x4,0xe2,0x13, 0x54,0x8b,0x9a,0x8e,0x95,0xf1,0xb5,0xb9,0x9c,0x5d,0x28,0x1a,0x70,0xb6,0xb7,0xd6, 0xb7,0x85,0x76,0x8b,0x97,0xf0,0x56,0xe7,0x93,0x54,0x82,0x94,0x12,0x64,0x94,0xc4, 0x50,0x16,0x62,0x53,0xe3,0x9d,0x2f,0xa5,0x44,0x95,0xda,0x70,0x8e,0xe0,0x58,0xe2, 0x7,0x7a,0x2b,0x3c,0xa7,0x86,0x77,0x53,0xdb,0x1,0x65,0x81,0xcc,0x28,0xce,0xe5, 0xd7,0x0,0x3c,0x3,0x1e,0xaf,0x8c,0xaf,0xfd,0x7b,0x1b,0xff,0x37,0xbf,0x7,0x0, 0xe3,0xbd,0x53,0x0,0x73,0x9d,0x6f,0xea,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbar_WorldCoordSystem.png 0x0,0x0,0x1,0x38, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x31, 0x49,0x44,0x41,0x54,0x28,0xcf,0x63,0xfc,0xcf,0x80,0x1f,0x30,0x31,0x50,0x51,0x1, 0xe3,0x7f,0xc6,0xff,0xe8,0x2c,0x2a,0x5b,0x1,0x33,0x9e,0xda,0xbe,0x40,0x31,0x91, 0xf1,0x3f,0x3,0xc3,0x7f,0x46,0x8,0x49,0x23,0x2b,0xa8,0x13,0xe,0x24,0x2b,0x0, 0x0,0x8d,0x4,0xc,0x1b,0x1,0x80,0xc8,0xfa,0x0,0x0,0x0,0x25,0x74,0x45,0x58, 0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31, 0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32, 0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30, 0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x33,0x30,0x3a,0x33, 0x38,0x2b,0x31,0x30,0x3a,0x30,0x30,0xb9,0xdd,0xd0,0x1,0x0,0x0,0x0,0x0,0x49, 0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/NewDirectory_16x16.png 0x0,0x0,0x2,0xf5, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13, 0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1, 0x8e,0x7c,0xfb,0x51,0x93,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a, 0x25,0x0,0x0,0x80,0x83,0x0,0x0,0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75, 0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5, 0x46,0x0,0x0,0x2,0x6b,0x49,0x44,0x41,0x54,0x78,0xda,0xa4,0x93,0xcb,0x6f,0x4d, 0x71,0x10,0xc7,0x3f,0xe7,0xde,0x73,0xab,0xaa,0x52,0xf5,0xa8,0xa4,0x11,0x2d,0xad, 0x36,0x48,0xa9,0x20,0x11,0x9,0xb1,0x13,0x12,0xd4,0x46,0x24,0x96,0x56,0x16,0x12, 0x3b,0xb,0x1b,0xfe,0x1,0x56,0x56,0x22,0x1e,0x61,0x21,0x2c,0x44,0x84,0x44,0x10, 0x44,0x22,0xda,0x45,0x2d,0x88,0x68,0xd1,0x78,0x53,0xda,0xdb,0xde,0x73,0x7e,0xaf, 0xf3,0x7b,0x59,0xb4,0x9e,0x2b,0x89,0x49,0x66,0x31,0xc9,0x7c,0xbe,0xf3,0xcd,0x64, 0x26,0x89,0x31,0xf2,0x3f,0x91,0xfe,0x4b,0xd3,0xf0,0xd5,0xe5,0x67,0x5b,0x16,0xb5, 0xde,0x6e,0x6a,0xdb,0xc0,0xcb,0x87,0x97,0xce,0x74,0x6e,0xdc,0xb1,0x5f,0x7e,0x1b, 0x12,0x1f,0x86,0x5f,0x2f,0xfe,0x27,0x81,0xf6,0x15,0xdd,0xa7,0x3f,0x8e,0xbc,0xbd, 0xd3,0xd4,0x35,0xb7,0x52,0x3f,0x7f,0x3d,0xcc,0x6c,0x3f,0x37,0xfa,0xf6,0x6e,0xde, 0xda,0xb1,0xa4,0x2f,0x1d,0xbc,0x71,0xa0,0xf7,0x75,0xb5,0x7b,0xf0,0x6f,0xa8,0xa1, 0x62,0xb6,0x6e,0xdb,0x73,0xf8,0x16,0x40,0xa5,0x79,0xe5,0xe6,0xb6,0xd6,0xad,0x86, 0x59,0x7b,0x2b,0x73,0x3a,0x96,0x40,0x63,0x2f,0xed,0x9b,0xea,0x1a,0x51,0xef,0x7d, 0x72,0xe5,0xc2,0x89,0xb8,0x65,0x4b,0x7,0x8d,0xd,0x53,0x66,0x42,0xc8,0xf0,0xe2, 0xb,0x37,0xef,0x59,0xea,0xca,0xea,0xd8,0xae,0x7d,0x47,0x8e,0xe,0x5d,0x6e,0xb7, 0xf5,0xb,0xd6,0xa5,0x2d,0xab,0xf,0x31,0xa3,0x79,0xd,0xfa,0xdb,0x3d,0xbe,0x3e, 0x3d,0x43,0xd9,0x8e,0xf4,0x27,0x97,0xcf,0x1f,0xff,0xb5,0xc5,0x18,0x9,0x31,0x12, 0x63,0x24,0x86,0xa9,0xc,0x31,0xd0,0xd3,0x6d,0x58,0xda,0xd9,0x4c,0x63,0xcb,0x76, 0x74,0xf6,0x99,0xfa,0xd9,0x29,0x21,0x1f,0x90,0x25,0xfb,0xf9,0x60,0xea,0x83,0x67, 0x77,0xdf,0xda,0x3f,0xec,0xc7,0x92,0xa4,0x6c,0x15,0x38,0x41,0xe2,0x4,0x51,0xbe, 0xe4,0xe3,0xd3,0xeb,0x34,0xac,0x6d,0xa0,0x3a,0xf4,0x80,0x85,0x5d,0xbd,0xbc,0x7a, 0x74,0x71,0x66,0x6b,0xdb,0xc2,0x37,0xa9,0x77,0x7e,0xa,0xa,0x7a,0x1a,0x16,0x94, 0xb,0x5,0x45,0x8d,0xc4,0xe6,0x60,0x73,0xc6,0xde,0x3d,0x63,0xc1,0xbc,0xe5,0x14, 0xef,0xef,0x93,0x98,0x21,0xde,0xf5,0x8f,0x70,0x6d,0xa0,0x27,0xd9,0xe9,0x1e,0xaf, 0x2a,0x85,0x10,0x7e,0x4e,0x2e,0x51,0x50,0xb6,0x86,0xc4,0xe6,0x24,0x4e,0x80,0x95, 0x78,0x93,0xd3,0xd4,0xd4,0x86,0xd7,0x16,0x3d,0x3a,0x6,0xa3,0x91,0x4f,0x2f,0x9e, 0x30,0xf2,0x41,0xb3,0xac,0xef,0xf9,0x89,0xd4,0x59,0xff,0x73,0x72,0xe2,0xa,0x70, 0x39,0x89,0x15,0x44,0x2b,0x89,0x26,0x23,0x68,0x89,0x53,0x19,0x5e,0x65,0x78,0x95, 0xe3,0xac,0x42,0x5b,0x98,0x9c,0xa8,0x4d,0x1d,0x92,0x77,0x9e,0xe8,0xd,0x69,0xc, 0xe0,0x24,0x89,0x53,0x44,0x2b,0x88,0x3a,0xc7,0x1b,0x85,0xd7,0x62,0x3a,0x33,0x9c, 0x16,0xc4,0x42,0x23,0x74,0x4a,0x75,0x5a,0xa0,0xe4,0xbc,0x27,0x78,0x3,0xfe,0x7, 0x9c,0x11,0x8d,0xc0,0x17,0x12,0xaf,0x5,0x4e,0x67,0x38,0x9d,0x63,0x95,0x24,0x14, 0x9a,0x42,0x1b,0x44,0x51,0x61,0x62,0xf2,0x37,0x7,0x84,0x82,0xc4,0x4b,0xa2,0xad, 0x11,0x4d,0x8e,0x2f,0xc4,0x2f,0x58,0xe5,0x78,0x25,0x8,0x85,0xc2,0x28,0x89,0x2d, 0xc,0xd2,0xd6,0x51,0xcb,0xb2,0x69,0x1,0xef,0x29,0x94,0x26,0x1f,0x1f,0x46,0x7f, 0x7d,0x81,0x91,0xe3,0x4,0x2b,0x31,0xda,0x20,0x94,0x45,0xc8,0x48,0x4d,0x4,0xbc, 0xb3,0x4,0xef,0x90,0xb6,0xe,0x65,0x53,0x32,0x21,0x7e,0x8,0x4,0x4e,0x9e,0xea, 0xa7,0x96,0xe5,0x54,0x27,0xea,0x19,0xaf,0xce,0x62,0x6c,0xbc,0xa0,0x3a,0x21,0xa9, 0x65,0x12,0x29,0xd5,0x5f,0x47,0x6e,0xfe,0xa8,0x92,0xff,0x7d,0xe7,0xef,0x3,0x0, 0x63,0x0,0x97,0xd8,0x35,0xe7,0xa1,0x6d,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44, 0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/HighlightHH.png 0x0,0x0,0x4,0xbf, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x2,0x2b,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xc0,0xc2,0x0,0xcf,0xcf,0x0,0xa0,0x9a,0x15,0xc0,0xc1,0x0, 0x6b,0x5d,0x4,0xfe,0xff,0x3b,0x7e,0x6b,0x8,0xfe,0xff,0x3a,0x21,0x1c,0x1,0xcd, 0xce,0x9,0x23,0x0,0x0,0xff,0xff,0x41,0xd6,0xd3,0x32,0xc0,0xc0,0x0,0xee,0xea, 0x35,0xc3,0xc1,0x0,0x9f,0xb6,0x0,0xc9,0xc4,0x26,0xfd,0xf7,0x37,0xc4,0xc0,0x0, 0x32,0x2c,0x0,0x9c,0x82,0xc,0xfd,0xf8,0x31,0xf8,0xf3,0x37,0xcd,0xc2,0x9,0xc9, 0xb8,0x1a,0xce,0xca,0x31,0xc7,0xb9,0x0,0xba,0xb6,0x2e,0xce,0xc4,0x16,0xdb,0xd6, 0x37,0xdd,0xdd,0x3d,0x5b,0x59,0x16,0x93,0x91,0x23,0xa3,0x9f,0x28,0xc0,0xc1,0x0, 0xc2,0xc2,0x0,0xce,0xcb,0x1,0xda,0xde,0x0,0xc0,0xc1,0x0,0xc1,0xc1,0x0,0xe3, 0xe0,0x49,0x80,0x7b,0xb,0xbf,0xc0,0x0,0xc1,0xc1,0x0,0xb6,0xa4,0x13,0x3b,0x30, 0x0,0xfe,0xff,0x3b,0xfd,0xfe,0x3a,0xf8,0xf9,0x39,0xdf,0xe0,0x34,0xdc,0xdd,0x33, 0xfc,0xfd,0x3c,0xd4,0xd7,0x33,0xd7,0xd6,0x31,0xad,0x93,0xf,0x6f,0x5e,0x5,0xfe, 0xff,0x3a,0xfe,0xff,0x3a,0xfc,0xfe,0x3a,0xef,0xf0,0x37,0xa4,0xa4,0x27,0x91,0x91, 0x1c,0xc2,0xc1,0x1a,0xbb,0xa1,0x16,0x5b,0x4d,0x5,0x0,0x0,0x0,0xfe,0xff,0x3a, 0xfd,0xff,0x3a,0xfd,0xff,0x3a,0xc7,0xc9,0x0,0xbe,0xbe,0x0,0xcf,0xcd,0x2b,0xd6, 0xcb,0x32,0xd0,0xcb,0x2b,0xc0,0xc1,0x0,0xc0,0xc0,0x0,0xaf,0x94,0x10,0x64,0x57, 0x9,0xe9,0xe5,0x2e,0xf3,0xf0,0x34,0xca,0xc7,0x30,0xbe,0xbf,0x0,0xc1,0xc0,0x0, 0xb7,0x9b,0x11,0x58,0x49,0x7,0x0,0x0,0x0,0xfe,0xf9,0x30,0xf7,0xf3,0x31,0xea, 0xe6,0x36,0xc1,0xbe,0x0,0xd8,0xd4,0x2d,0xbf,0xa2,0x12,0x9f,0x84,0xc,0x2,0x2, 0x0,0xee,0xeb,0x2f,0xf8,0xf3,0x30,0xfd,0xf7,0x39,0xbc,0xb9,0x0,0xd8,0xd4,0x27, 0xbd,0xa0,0x12,0xa3,0x87,0xe,0xfe,0xf8,0x30,0xfc,0xf7,0x33,0xf6,0xf1,0x39,0xc6, 0xbc,0x0,0xe6,0xdc,0x35,0xb5,0x99,0x12,0x95,0x7a,0xc,0xff,0xf9,0x25,0xff,0xf9, 0x2d,0xff,0xfa,0x31,0xc2,0xbe,0x2f,0xbc,0xad,0x0,0xda,0xce,0x1f,0xb8,0x9e,0x12, 0x8d,0x7a,0x10,0xb4,0xb4,0x1e,0xfe,0xf8,0x28,0xfd,0xf7,0x29,0xfe,0xf8,0x2c,0xff, 0xfa,0x31,0xfb,0xf6,0x37,0xe5,0xe0,0x38,0x9e,0x9a,0x28,0xcb,0xc0,0x12,0xd9,0xce, 0x22,0xe0,0xd9,0x29,0xdb,0xd6,0x27,0xe6,0xe0,0x28,0xfe,0xf8,0x2e,0xfe,0xf9,0x31, 0xfe,0xf8,0x36,0xdc,0xd7,0x36,0xd9,0xd4,0x37,0xb2,0xb7,0x43,0xed,0xea,0x3b,0xf3, 0xf0,0x3b,0xe6,0xe2,0x37,0xf7,0xf2,0x3a,0xfe,0xf9,0x3b,0xff,0xf9,0x3b,0xfb,0xf5, 0x3b,0xed,0xe8,0x39,0xdf,0xda,0x37,0x96,0x92,0x25,0x5f,0x5d,0x17,0x87,0x85,0x20, 0xb8,0xb4,0x2c,0xeb,0xe6,0x39,0xfa,0xf5,0x3e,0xfd,0xf8,0x3f,0xf4,0xee,0x3d,0xcf, 0xca,0x33,0x97,0x93,0x25,0xd7,0xd7,0x2b,0xd7,0xd6,0x2c,0xf8,0xf4,0x82,0xf0,0xe1, 0x46,0xf4,0xe4,0x47,0xe4,0xc9,0x1e,0xe0,0xdf,0x4a,0xf8,0xf3,0x83,0xf4,0xe3,0x47, 0xe4,0xca,0x20,0xf8,0xf3,0x81,0xc2,0xa9,0x19,0xd7,0xd5,0x2b,0xf8,0xf3,0x82,0xf8, 0xf2,0x82,0xf3,0xe3,0x47,0xe3,0xc9,0x1e,0xf8,0xf2,0x81,0xe3,0xc8,0x1e,0xf8,0xf1, 0x7e,0xf2,0xe0,0x3a,0xe2,0xc8,0x1e,0xf2,0xed,0x35,0xe6,0xd4,0x2a,0xd7,0xbc,0x11, 0xe2,0xd3,0x2a,0xed,0xe3,0x2d,0xea,0xe4,0x36,0xff,0xff,0xff,0x6c,0x32,0xf4,0x5d, 0x0,0x0,0x0,0x9c,0x74,0x52,0x4e,0x53,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c,0x86,0x55,0x1, 0x16,0xa9,0xe8,0x4a,0x17,0xaa,0xb1,0xb,0xe,0x2c,0x7a,0x85,0x83,0x7e,0xb4,0xfe, 0xe3,0x1c,0xa,0x80,0x75,0x80,0x82,0x9a,0xf5,0xfe,0xa4,0xc,0x4,0x18,0x3,0x14, 0xa6,0xfe,0xf7,0x61,0x17,0xaa,0xfe,0xb2,0xb4,0xe8,0x4a,0xc,0xa6,0xf4,0xa6,0x15, 0x25,0xec,0x80,0x59,0xf3,0xe8,0x59,0xb,0x1c,0xe8,0x80,0x18,0xd8,0xe8,0x55,0x27, 0xec,0x80,0x27,0xe7,0xe7,0x53,0x2,0x22,0xaa,0x74,0xc,0xa7,0xf6,0x71,0x1a,0x1b, 0x26,0x7f,0xdc,0xfc,0xaa,0x16,0x19,0xda,0xfc,0xe5,0xe5,0xe5,0xe8,0xfc,0xaa,0x17, 0x1,0x4a,0x8c,0xd8,0xe4,0xe5,0xe5,0xe5,0xe7,0xb2,0x73,0x19,0x3,0x19,0x1c,0x1c, 0x1c,0x1c,0x1c,0xe,0xb1,0x88,0x98,0x27,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44, 0xb8,0x4d,0xbf,0x26,0xf6,0x0,0x0,0x0,0xef,0x49,0x44,0x41,0x54,0x18,0xd3,0x63, 0x60,0x80,0x1,0x46,0x15,0x55,0x35,0x75,0x26,0x6,0x4,0x5f,0x43,0x73,0x8e,0x96, 0x36,0x33,0x9c,0xcf,0xa2,0xa3,0x3b,0x77,0xde,0x7c,0x3d,0x7d,0x56,0x6,0x6,0x36, 0x3,0x43,0x23,0x63,0x13,0x53,0x33,0xf3,0x79,0xb,0x16,0x5a,0x58,0xb2,0x33,0x70, 0x58,0x59,0xdb,0xd8,0xda,0xd9,0x3b,0x2c,0x5a,0xbc,0x64,0xa9,0xa3,0x93,0x33,0x27, 0x3,0x87,0x8b,0xab,0x1b,0x97,0xbb,0x87,0xe7,0xb2,0x25,0xb,0x97,0x7b,0x79,0x73, 0xf3,0x80,0xcd,0xf3,0xf1,0x5d,0xb1,0x72,0xc9,0x42,0x3f,0xff,0x80,0xc0,0x20,0x5e, 0x20,0x9f,0x2f,0x38,0x64,0xc5,0xaa,0xd5,0x6b,0x42,0xc3,0xc2,0x23,0x22,0xa3,0xf8, 0x19,0x18,0x4,0x4,0xa3,0x63,0xd6,0x2e,0x59,0x17,0x1b,0x17,0x2f,0x94,0x90,0x98, 0x24,0xcc,0xc0,0x20,0x92,0x9c,0xb2,0x7e,0xc9,0x9a,0xd4,0x34,0x51,0x31,0xf1,0xf4, 0x8c,0x4c,0x9,0x6,0x6,0xc9,0xac,0xec,0xd,0x1b,0x73,0x72,0x19,0xa4,0xf2,0xf2, 0xb,0x36,0x15,0x4a,0x33,0xc8,0x14,0x15,0x6f,0xde,0x52,0x52,0x5a,0x56,0x5e,0x51, 0x59,0x55,0x5d,0x53,0x2b,0xcb,0x20,0x57,0x57,0xbf,0x75,0x5b,0x43,0x63,0x53,0x73, 0x4b,0xeb,0xf6,0xb6,0x76,0x79,0x6,0x6,0x85,0x8e,0xce,0xae,0xee,0x9e,0xde,0xbe, 0xfe,0x9,0x13,0x27,0x4d,0x56,0x4,0x7b,0x43,0x69,0xca,0xd4,0x69,0xd3,0x67,0xcc, 0x9c,0x35,0x5b,0x99,0x1,0x1b,0x0,0x0,0x57,0x2,0x47,0x93,0xf5,0x40,0xd8,0x34, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65, 0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32, 0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5, 0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f, 0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54, 0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c, 0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Toolbox_ShapeCylinder.png 0x0,0x0,0x5,0x6a, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x6,0x62,0x4b,0x47, 0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,0xa7,0x93,0x0,0x0,0x0,0x9,0x70, 0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b, 0x0,0x0,0x4,0x5f,0x49,0x44,0x41,0x54,0x58,0xc3,0xad,0x96,0xbb,0x8e,0x1c,0x45, 0x14,0x86,0xbf,0x53,0xd5,0xdd,0xd3,0xf7,0x99,0xdd,0xb5,0xa5,0xb5,0xbd,0x6b,0x7, 0x4,0x48,0x48,0x4,0x88,0x8,0x62,0x24,0xe4,0xc,0x5e,0x80,0x90,0x90,0xc7,0x40, 0x20,0x2,0xe4,0x84,0xc0,0x9,0xbc,0x86,0x3,0x3f,0x0,0x22,0x1,0x9,0x8b,0x4, 0x21,0xe4,0x9b,0x90,0xd0,0x22,0xcb,0xf6,0xae,0xa7,0x2f,0x55,0x87,0xa0,0x7a,0x2e, 0x7b,0xf1,0xf4,0x68,0xed,0xe,0x46,0x9a,0x99,0x52,0x9f,0xaf,0xfe,0xfa,0xcf,0x7f, 0x4a,0x54,0x55,0x79,0xcd,0x23,0x22,0x2,0x70,0x3b,0xf9,0x5e,0x5b,0x7f,0x8c,0xa2, 0x58,0x13,0x61,0xa3,0x88,0x38,0x8e,0x99,0xa4,0x29,0x69,0x9e,0x51,0x54,0x5,0xe5, 0xac,0xa2,0xde,0xad,0xa9,0x76,0x2b,0xb2,0x3a,0xc5,0xc6,0xc2,0x97,0xdf,0xbd,0x23, 0x0,0x1b,0x6b,0x8c,0x1,0x7c,0x62,0xbf,0x51,0x4f,0xf,0x12,0x8a,0xc7,0x51,0x42, 0x92,0xa4,0xa4,0x59,0x4e,0x56,0xe4,0x14,0x55,0x49,0x39,0x2d,0x28,0x67,0x25,0xc5, 0x4e,0x41,0x31,0xcd,0xc9,0xea,0x9,0x49,0x91,0x90,0x64,0x96,0xcf,0xbf,0x9a,0x6e, 0xac,0x11,0xb1,0xe1,0xb9,0x6d,0xee,0x68,0x4f,0x83,0x95,0x18,0x63,0xc,0x91,0x4d, 0x98,0x24,0x29,0x59,0x56,0x50,0x94,0x15,0x45,0x5d,0x52,0x4e,0x4b,0x8a,0x59,0x1e, 0xa,0x4f,0x53,0xb2,0x7a,0xc2,0xa4,0x88,0x49,0x72,0x4b,0x34,0xb1,0xdc,0xfb,0x71, 0xae,0x9b,0x6a,0x6c,0x4,0xb0,0x92,0x60,0xc4,0x80,0x55,0xac,0x8d,0x48,0x92,0x94, 0x3c,0x2b,0x28,0xaa,0x8a,0xb2,0xae,0x29,0xa7,0x5,0xc5,0x2c,0x27,0x9f,0xa6,0x64, 0xd3,0x9,0x59,0x95,0x30,0xa9,0x62,0x26,0xa5,0x25,0x4e,0x2d,0x36,0x11,0xc4,0xa, 0x97,0x6,0xc8,0xb3,0x8a,0xb6,0x6d,0x30,0x56,0x88,0x93,0x98,0x2c,0xcb,0x28,0xab, 0x8a,0x6a,0xa7,0xa6,0xde,0xa9,0x28,0x76,0x32,0x8a,0xd9,0x84,0x6c,0x9a,0x90,0x4d, 0x63,0xd2,0x2a,0x62,0x52,0x46,0x4c,0x4a,0x43,0x9c,0x1a,0xc4,0xa,0xcf,0x9e,0xb6, 0x1b,0xcb,0x98,0x4d,0x0,0x7,0xef,0xde,0x20,0x4d,0xa,0x12,0x53,0x90,0x46,0x5, 0x79,0x5a,0x51,0xd5,0x35,0x3b,0x7b,0x35,0xbb,0xfb,0x25,0x57,0x6e,0x64,0xec,0x1d, 0xa6,0x5c,0x39,0x4c,0xd8,0x3b,0x8c,0xd9,0x3b,0x8c,0xd8,0x3b,0x30,0xec,0x5d,0x37, 0xec,0x5e,0x17,0xc4,0xb7,0xdc,0xff,0xf6,0xcf,0xcb,0x2b,0x90,0x95,0x19,0xd9,0x41, 0xcf,0xb3,0x7f,0x5e,0x90,0x9a,0x6b,0x4c,0x92,0x9c,0x2c,0xcf,0x28,0xa6,0x29,0xf5, 0xd5,0x84,0xe9,0x7e,0x42,0x79,0x25,0xa6,0xd8,0xb1,0xa4,0xb5,0x65,0x52,0x58,0x92, 0x4c,0xf0,0x4e,0xf9,0xfd,0xde,0x11,0xf7,0xef,0x3c,0xe1,0xe4,0xc8,0x5d,0x1e,0xc0, 0x88,0xc5,0x5a,0xcb,0x73,0x9e,0xf0,0xf4,0xe8,0x1,0xe5,0xcb,0x3d,0xf6,0xe7,0x87, 0x5c,0xf3,0xd7,0x68,0xed,0x55,0x7c,0x3c,0x43,0xe2,0x92,0x24,0xcf,0x98,0x66,0x86, 0x62,0xa6,0x18,0xa3,0x3c,0xfe,0xfd,0x15,0x7f,0xfd,0xfc,0x2,0xef,0x41,0x36,0x5b, 0x60,0x33,0x0,0x28,0xc6,0x58,0x8c,0x58,0x40,0x38,0x3e,0x79,0xc6,0xdf,0xf,0x5f, 0xf1,0xe4,0xd1,0x23,0x1e,0xfc,0x52,0xb3,0x3b,0xdb,0xe7,0xe0,0xe6,0x2d,0x3e,0xfc, 0xf4,0x16,0x37,0xdf,0xcf,0xb8,0x7a,0x2b,0xc6,0x7b,0xf8,0xef,0x71,0x8b,0x8c,0x55, 0xde,0xc6,0x3,0x22,0x82,0x31,0x11,0x46,0xc,0x82,0xb0,0xde,0x4f,0x8a,0xa2,0xaa, 0xa8,0x2,0x2,0xc6,0xa,0xc6,0xa,0x28,0xf4,0x8d,0xd2,0xb7,0x1e,0xf5,0xa,0xf2, 0x6,0x0,0x20,0x41,0x1,0x63,0x40,0x4,0x19,0xde,0xa6,0xc3,0x87,0xaa,0xe2,0xbd, 0xc7,0x3b,0xd,0xc5,0x8,0xbf,0x75,0x8d,0xa7,0x6f,0x7d,0x58,0xa8,0x9b,0x2b,0x6c, 0x4,0x50,0x14,0x63,0xc,0x22,0x16,0x19,0xbe,0x9f,0x56,0xc0,0xa3,0x4b,0x0,0x50, 0x5,0xf5,0xd0,0xcd,0x15,0xd7,0xad,0xa0,0x36,0x3d,0xd1,0xd8,0x2,0x23,0x76,0x80, 0x90,0x95,0x9a,0xc3,0xce,0xfc,0x9a,0x2,0xde,0x87,0xbf,0xbc,0x83,0xae,0xf1,0xb8, 0xce,0x7,0xa0,0xb1,0xf7,0x8f,0x1,0x58,0x63,0x31,0x26,0x98,0xf0,0xb4,0x36,0x61, 0x87,0xde,0xeb,0xa9,0x23,0xf0,0x4e,0xe9,0xe7,0x3e,0x28,0xa0,0x4,0x59,0x2e,0xb, 0xd0,0xf7,0xed,0xd0,0x5,0xe6,0xbc,0xab,0x55,0x57,0x1e,0xe8,0x7,0x5,0x34,0xc0, 0x74,0x73,0xc5,0xf5,0x3a,0x5a,0x7c,0x14,0xa0,0x69,0x4f,0x6,0x13,0xda,0x0,0xb0, 0xc6,0x10,0x36,0x17,0x3c,0xe0,0x9c,0x47,0x5d,0xd8,0xb1,0xef,0xa1,0x9b,0x7,0x28, 0xdd,0x82,0x61,0x23,0xc0,0xbc,0x39,0x46,0x86,0x4e,0x10,0x39,0xbf,0x54,0x2f,0xf0, 0x80,0xeb,0x95,0x76,0xee,0x57,0xa,0xa8,0xbf,0x3c,0xc0,0x49,0xf3,0x3c,0x2c,0x32, 0x76,0x68,0xc1,0x33,0x3e,0xd0,0x85,0x7,0x42,0xcf,0xab,0x82,0xeb,0x94,0x7e,0x3e, 0xf8,0x2,0xb8,0xdb,0x7e,0xb4,0x31,0x9,0x36,0x2,0xfc,0xf4,0xc7,0x17,0x22,0x22, 0x58,0xb1,0xa7,0xbb,0x80,0x61,0x73,0xaa,0xe1,0x8,0xfa,0xa1,0xe0,0x0,0xd0,0x35, 0x41,0x95,0xd1,0x16,0x18,0x3,0x58,0x2c,0x79,0xdd,0x11,0xb0,0xa6,0x40,0x30,0xe1, 0x0,0x30,0xf,0x9e,0xd8,0x86,0x60,0x14,0x40,0x84,0xb,0x4d,0xc8,0x32,0x8a,0x87, 0x20,0x1a,0x5a,0xb1,0x6f,0x95,0xbe,0xf1,0xf8,0x2d,0x42,0x68,0x4b,0x5,0xd6,0x4d, 0x78,0xba,0xd,0x16,0x26,0x74,0xce,0xe3,0x5d,0x38,0x96,0xbe,0x55,0xba,0x56,0x97, 0x9e,0x78,0xb,0xa,0xac,0xcd,0x83,0x53,0xfb,0x67,0x15,0x46,0x4e,0x97,0x9d,0xb0, 0x50,0x40,0xdd,0xd8,0x9b,0xb7,0x5,0x40,0xb0,0x66,0x61,0xc2,0xb3,0x61,0x14,0xb2, 0xc0,0xf5,0xab,0x63,0x58,0xc,0x22,0x55,0xdd,0xc6,0x83,0xe3,0x0,0x8a,0x62,0x64, 0x38,0x82,0xb,0x3c,0xb0,0x34,0xe1,0x42,0x81,0x26,0xf8,0x40,0xbd,0x22,0x6f,0x9a, 0x84,0xcb,0x45,0x43,0x1c,0x5f,0x8,0xa8,0x2b,0x0,0x75,0xa1,0x3,0x5c,0x17,0x4c, 0xf8,0x56,0x14,0x58,0x2,0x2c,0xc3,0x68,0x5d,0x7e,0x5d,0x8e,0x63,0xef,0x14,0xd7, 0x43,0xd7,0x84,0x51,0xcc,0x16,0x83,0x68,0x2b,0x80,0xbe,0x6f,0x7,0xf,0x98,0xe1, 0x82,0xb7,0xe,0xa1,0x78,0x55,0x9c,0x5b,0x85,0x51,0xb7,0x36,0x9,0x75,0x8b,0x5b, 0xd9,0x28,0x40,0xdb,0x37,0xc8,0xd0,0x5,0x67,0x4d,0xa8,0x30,0x74,0x41,0x50,0x61, 0x11,0x42,0xae,0xf,0x26,0x7c,0x2b,0x49,0xd8,0x75,0xf3,0x65,0x2b,0x9e,0xbf,0xdf, 0x2d,0x82,0x28,0x4c,0xbf,0x5,0x80,0x1f,0x6,0xd1,0xdd,0xe3,0x8f,0x47,0x35,0x18, 0x5,0xf8,0xe1,0xd7,0xcf,0xa4,0xef,0x5b,0x80,0xf3,0xa,0xc,0x3e,0x70,0xbd,0xa7, 0x6d,0x3c,0xcd,0xb1,0x67,0xfe,0xd2,0xd1,0x35,0x6e,0x2b,0x3,0xc2,0x16,0x57,0x32, 0x80,0x7f,0x8f,0x1e,0xd3,0x34,0xaf,0x82,0xac,0x67,0x3d,0xe0,0x3d,0x6d,0xd3,0x71, 0xf4,0xf0,0x84,0xb4,0x88,0xf0,0xce,0x73,0xe3,0xbd,0x9c,0xaf,0x7f,0xfb,0x60,0xab, 0x7b,0xf9,0xff,0xb0,0x62,0xb5,0x79,0xd4,0x13,0xa3,0x84,0x0,0x0,0x0,0x25,0x74, 0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32, 0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a, 0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25, 0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0, 0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x38,0x54,0x32,0x32,0x3a,0x34,0x34, 0x3a,0x30,0x34,0x2b,0x31,0x30,0x3a,0x30,0x30,0xd0,0x22,0x8,0x6f,0x0,0x0,0x0, 0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsCenteredHorizontalHS.png 0x0,0x0,0x1,0x91, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x48,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x6f,0x86,0xb0,0x69,0x82,0xad,0x64,0x7d,0xa9,0x5f,0x79,0xa5, 0x56,0x70,0x9e,0x35,0x49,0x63,0xf5,0xfa,0xfb,0xf1,0xf6,0xfb,0xec,0xf3,0xfa,0xe1, 0xec,0xf9,0x44,0x61,0x94,0x4c,0x68,0x99,0x49,0x64,0x96,0x5e,0x76,0xa4,0xd2,0xe2, 0xf9,0xc7,0xda,0xf9,0x9e,0xbb,0xe8,0xc8,0xd3,0xdf,0xc1,0xd0,0xe0,0xb6,0xc8,0xe3, 0xa5,0xbf,0xe6,0x95,0xb4,0xe4,0xff,0xff,0xff,0xf4,0xf8,0x95,0x51,0x0,0x0,0x0, 0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b, 0x47,0x44,0x17,0xb,0xd6,0x98,0x8f,0x0,0x0,0x0,0x3f,0x49,0x44,0x41,0x54,0x18, 0xd3,0x63,0x60,0xa0,0x16,0x60,0x64,0x62,0x66,0x61,0x65,0x43,0x12,0x60,0x61,0xe7, 0xe0,0xe4,0x42,0x16,0xe0,0x6,0x1,0x36,0xfc,0x26,0xb0,0xb0,0xf2,0xf0,0xc2,0xd5, 0xf0,0x1,0x4d,0xe0,0xe4,0xe2,0x17,0x10,0x44,0x8,0x8,0x9,0xb,0x8b,0x88,0xa, 0x8a,0xb1,0x21,0x1b,0x49,0xc0,0x58,0x92,0x0,0x0,0xfe,0xf5,0x2,0x37,0x7e,0x81, 0xcb,0x8a,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63, 0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34, 0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c, 0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a, 0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31, 0x39,0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30, 0xe3,0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Alerts.png 0x0,0x0,0x2,0x49, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13, 0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a, 0x25,0x0,0x0,0x80,0x83,0x0,0x0,0xf9,0xff,0x0,0x0,0x80,0xe9,0x0,0x0,0x75, 0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a,0x98,0x0,0x0,0x17,0x6f,0x92,0x5f,0xc5, 0x46,0x0,0x0,0x1,0xcf,0x49,0x44,0x41,0x54,0x78,0xda,0xc4,0x93,0x3b,0x68,0x14, 0x51,0x14,0x86,0xff,0x3b,0xce,0x6c,0x58,0x77,0xa3,0xe0,0x8a,0x9a,0x46,0x62,0x91, 0xd5,0x42,0x30,0x95,0x44,0xc1,0x57,0x1d,0xd0,0x56,0x1b,0x1b,0x63,0x6d,0xa7,0x8d, 0x85,0x8f,0xc6,0xce,0x5a,0xd0,0x25,0x85,0xb8,0x20,0x88,0x68,0x65,0xc0,0x58,0x28, 0xa6,0x88,0x16,0x86,0xb8,0x59,0x37,0x26,0xec,0xc6,0xcc,0x3e,0xdc,0xd9,0x9d,0xb9, 0xf3,0xda,0x99,0xb9,0x77,0xee,0x5c,0x2b,0xc1,0xcd,0x6,0x23,0x6c,0xe1,0xf,0xa7, 0x39,0xfc,0xe7,0x83,0xff,0xdc,0x7b,0x88,0x94,0x12,0xc3,0x48,0xc1,0x90,0x52,0xb7, 0x6b,0xbe,0x79,0x71,0xff,0xfc,0xf1,0x89,0xd1,0x79,0xcf,0x34,0x48,0x87,0xfa,0xb0, 0xbb,0x16,0x29,0x6d,0xb0,0xc9,0x9b,0xf7,0x8a,0x4b,0x3,0x66,0x29,0x65,0x5f,0x15, 0x9f,0xdc,0x99,0xfe,0x51,0x7a,0x24,0x7a,0xd6,0x9c,0x94,0xe2,0x93,0x94,0xe2,0xb3, 0xc,0xda,0xb3,0xb2,0xf0,0xf0,0x1a,0xbb,0x7e,0xf5,0xd2,0xc5,0xad,0xfe,0x81,0x8, 0x27,0xf2,0xea,0xd3,0xb1,0xf1,0xbc,0x92,0xce,0xee,0x1,0x62,0xf,0x8,0x75,0x24, 0x61,0x17,0xe7,0x26,0x99,0x36,0x96,0x71,0x9f,0xfd,0x43,0x84,0x44,0xa8,0xea,0x8, 0x20,0x1c,0x88,0xb0,0x8b,0xc8,0x6b,0x82,0x99,0xcb,0xe0,0x3d,0x1d,0xcc,0x75,0xd8, 0x8e,0x0,0xdf,0x76,0x43,0x10,0x6,0x11,0x1a,0x8,0x6d,0x1d,0xb1,0x5d,0x81,0xd3, 0xa9,0xa1,0xf5,0xd3,0x81,0x36,0xc2,0xd3,0x3b,0xbe,0x2,0x63,0xcc,0x42,0x12,0x83, 0x7,0x2e,0x62,0xbf,0x81,0x80,0xea,0xa8,0x6d,0xba,0xb0,0x28,0x47,0x9b,0xc6,0xe2, 0xaf,0x80,0xb9,0x57,0x77,0x4f,0xe5,0xe,0x64,0xf2,0xd6,0xda,0x22,0x6a,0xe5,0x35, 0x54,0x56,0x29,0x2a,0xd5,0x14,0xaa,0x9b,0x4,0x4b,0x65,0xe,0x5,0xbb,0xd2,0x97, 0xcf,0xee,0x9d,0xfa,0x73,0x86,0xfc,0xfe,0x48,0xab,0x85,0xdb,0x17,0xb4,0x63,0xc1, 0xdb,0x23,0x27,0xaf,0x28,0x32,0x6a,0x22,0xe1,0x16,0xc0,0x3d,0xd8,0xad,0xaf,0xf0, 0x69,0x1d,0x91,0xe7,0xe0,0xfd,0x2,0xc5,0xb7,0x75,0x37,0xf9,0xbe,0x62,0x9c,0x79, 0xf9,0xc5,0x5e,0xe8,0xdb,0x41,0x27,0xd3,0x7e,0x77,0x7a,0xea,0x6,0x64,0x50,0x86, 0xb0,0x4b,0x88,0xc3,0x26,0xcc,0x86,0x8e,0xb6,0xc1,0x60,0x3b,0x1,0xea,0x2d,0x1f, 0x3c,0x16,0x10,0xca,0x6e,0xe5,0xe0,0xf8,0xe1,0x8f,0x0,0x48,0x1f,0x60,0xa5,0x6a, 0x2c,0x2f,0xde,0x9a,0xd9,0x4f,0xa9,0x67,0x46,0x91,0x40,0x36,0xcb,0x52,0x9a,0xb2, 0x6f,0xa2,0x61,0x72,0x78,0x3e,0xf3,0x0,0xa2,0x9,0x21,0xd5,0x44,0x42,0x68,0x29, 0xcd,0x19,0x88,0xb0,0x55,0x1b,0xcf,0x47,0xa7,0x8b,0xf3,0x47,0x5f,0xaf,0xd7,0x7b, 0x24,0x77,0x28,0x37,0xf3,0xe0,0xf1,0x87,0xc2,0x76,0x3e,0xf2,0xdf,0x8f,0x69,0x68, 0xc0,0xaf,0x1,0x0,0x4e,0x7f,0xa,0x5c,0x6c,0x12,0xf0,0x11,0x0,0x0,0x0,0x0, 0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/DoubleRightArrowHS.png 0x0,0x0,0x2,0xe, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x93,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x9c,0xb4,0x90,0xa6,0xc0,0x98,0x93,0xaa,0x89,0x84,0x97,0x7b, 0x99,0xb0,0x8d,0x8c,0xa1,0x82,0xb8,0xe1,0xa5,0xa2,0xbc,0x95,0x84,0x98,0x7c,0xbb, 0xe5,0xa8,0x96,0xc7,0x80,0x95,0xac,0x8a,0xc9,0xf1,0xb4,0xc4,0xee,0xae,0xbf,0xea, 0xaa,0xb9,0xe4,0xa4,0xb6,0xe0,0xa3,0x8c,0xc1,0x76,0x80,0xb2,0x6d,0xb0,0xd4,0x9f, 0x99,0xb1,0x8d,0xc6,0xef,0xb1,0xad,0xe2,0x93,0xa3,0xd8,0x8b,0x98,0xcd,0x81,0x80, 0xb5,0x6c,0x74,0xaa,0x62,0x64,0x92,0x56,0x67,0x76,0x60,0xbe,0xe9,0xa9,0x86,0xb3, 0x73,0x7d,0xaa,0x6a,0x74,0xa0,0x62,0x6a,0x97,0x5a,0x4e,0x77,0x43,0x1c,0x22,0x1b, 0x66,0x88,0x59,0x35,0x41,0x34,0x23,0x2b,0x22,0x2c,0x36,0x2b,0x35,0x40,0x33,0x3c, 0x49,0x3a,0x60,0x8d,0x51,0x2f,0x3a,0x2e,0x36,0x42,0x35,0x7f,0x92,0x78,0x25,0x2d, 0x24,0xff,0xff,0xff,0x9,0x0,0x18,0x1,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53, 0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x30,0xae,0xdc, 0x2d,0xe4,0x0,0x0,0x0,0x71,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0x20,0xa, 0x30,0x32,0x21,0x48,0x30,0x60,0x66,0x61,0x85,0x93,0x60,0xc0,0xc6,0xe,0x62,0x43, 0x48,0x6,0xe,0x46,0x66,0x36,0x4e,0x2e,0x6e,0x16,0x1e,0x30,0x9,0x14,0x61,0xe4, 0xe5,0xe3,0x17,0x10,0x14,0x12,0x66,0x11,0x1,0x93,0xa2,0xc,0xcc,0x62,0xe2,0x12, 0x92,0x42,0x52,0xd2,0x32,0xb2,0x10,0x92,0x81,0x4d,0x4e,0x5e,0x41,0x51,0x49,0x5a, 0x59,0x45,0x15,0x4c,0xaa,0x31,0x70,0xaa,0x6b,0x68,0x6a,0x69,0x2b,0xab,0xe8,0x80, 0x49,0x5d,0x88,0x2d,0x7a,0x60,0x96,0x1e,0x9c,0xcf,0xa0,0xa7,0xa2,0xf,0x27,0x21, 0x2,0x1a,0x8,0x92,0xc,0x0,0x0,0xc8,0x74,0xa,0x3f,0x97,0xe1,0x9d,0x24,0x0, 0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61, 0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30, 0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59, 0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64, 0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39,0x54,0x31, 0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3,0x3c,0x98, 0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AnimateHS.png 0x0,0x0,0x2,0xd1, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0xb,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0x81,0x8d,0xa0,0x7e,0x8a,0x9c,0x7d,0x88,0x9a,0x67,0x70,0x80, 0x62,0x6c,0x7a,0x5f,0x68,0x75,0x7c,0x88,0x99,0xff,0xff,0xff,0x76,0x81,0x92,0x73, 0x7e,0x8e,0x70,0x7b,0x8b,0x6d,0x77,0x87,0x6a,0x74,0x83,0x66,0x70,0x7e,0x63,0x6c, 0x7a,0x60,0x69,0x76,0x59,0x61,0x6e,0x77,0x82,0x93,0x74,0x7f,0x8f,0x71,0x7b,0x8b, 0xf5,0xf8,0xfd,0x59,0x62,0x6e,0x56,0x5e,0x6a,0x52,0x5a,0x66,0x71,0x7c,0x8c,0x6b, 0x75,0x84,0xe7,0xed,0xfa,0x53,0x5b,0x66,0x4c,0x53,0x5e,0x6b,0x75,0x85,0x68,0x72, 0x81,0x65,0x6e,0x7c,0xd7,0xe1,0xf6,0x4c,0x54,0x5e,0x49,0x50,0x5a,0x45,0x4c,0x56, 0x65,0x6f,0x7d,0x5e,0x67,0x75,0xc7,0xd5,0xf2,0x46,0x4d,0x56,0x3f,0x45,0x4e,0x5c, 0x64,0x71,0x58,0x60,0x6d,0xb9,0xca,0xef,0x3c,0x42,0x4a,0x38,0x3e,0x46,0x52,0x59, 0x65,0x4e,0x55,0x61,0x4b,0x52,0x5c,0x47,0x4e,0x58,0x44,0x4a,0x54,0x40,0x46,0x4f, 0x3d,0x42,0x4b,0x39,0x3e,0x47,0x32,0x37,0x3e,0x4f,0x56,0x61,0x4b,0x52,0x5d,0x33, 0x38,0x3f,0x2f,0x34,0x3b,0x2c,0x30,0x36,0x45,0x4b,0x55,0x2d,0x31,0x37,0x26,0x2a, 0x2f,0x42,0x48,0x51,0x3e,0x44,0x4d,0x27,0x2a,0x30,0x23,0x27,0x2c,0x20,0x23,0x28, 0x38,0x3d,0x45,0x21,0x24,0x29,0x1b,0x1d,0x21,0x35,0x3a,0x42,0x32,0x36,0x3d,0x1b, 0x1e,0x22,0x18,0x1b,0x1e,0x16,0x18,0x1b,0x28,0x2c,0x32,0x25,0x29,0x2e,0x22,0x25, 0x2a,0x1f,0x22,0x26,0x1c,0x1e,0x22,0x19,0x1b,0x1f,0x11,0x12,0x15,0x29,0x2d,0x32, 0x27,0x2b,0x32,0x13,0x16,0x19,0xf,0x10,0x12,0xc,0xe,0xf,0x31,0xe,0x2e,0x1e, 0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0,0x0, 0x1,0x62,0x4b,0x47,0x44,0x8,0x86,0xde,0x95,0x7a,0x0,0x0,0x0,0x9,0x70,0x48, 0x59,0x73,0x0,0x0,0xb,0x12,0x0,0x0,0xb,0x12,0x1,0xd2,0xdd,0x7e,0xfc,0x0, 0x0,0x0,0xa7,0x49,0x44,0x41,0x54,0x18,0xd3,0x65,0xcf,0xc5,0x16,0xc2,0x50,0xc, 0x4,0xd0,0xe2,0xc1,0x29,0x5a,0xa4,0x68,0x91,0xe2,0x5e,0xa4,0xb8,0x43,0x71,0xfd, 0xff,0x2f,0xe1,0x30,0x6f,0x49,0x36,0xc9,0xdc,0xcd,0x9c,0x70,0xdc,0xff,0xe8,0xf4, 0x6,0x76,0x18,0x4d,0x66,0x6c,0xb,0x59,0x6d,0x76,0x87,0xd3,0xe5,0xf6,0x10,0xf, 0xf0,0xfa,0xfc,0xf4,0x9b,0x40,0x30,0x24,0x0,0xc2,0x14,0x41,0x8e,0xc6,0x48,0x4, 0xc4,0x13,0x49,0xe4,0x54,0x3a,0x23,0x1,0xb2,0x94,0x43,0xce,0x17,0x48,0x6,0x98, 0x8b,0x25,0xe4,0xb2,0x5c,0xa9,0x2,0x78,0xaa,0xd5,0x1b,0xcd,0x56,0xbb,0xd3,0x25, 0x5,0x20,0xf4,0xfa,0xac,0x65,0x30,0x54,0x1,0x22,0x8d,0x58,0xcb,0x98,0x26,0x0, 0x69,0x3a,0x63,0x2d,0xf3,0xc5,0x12,0x20,0xd3,0x8a,0xb5,0xac,0x69,0x3,0xa8,0x6e, 0x77,0xac,0x65,0x7f,0xd0,0x0,0xa,0xa9,0xc7,0xd3,0xf9,0x72,0xbd,0x69,0x74,0x7, 0xa8,0x8f,0x27,0xfb,0xf6,0xf5,0xfe,0x70,0xdc,0x17,0xe4,0x2f,0x15,0x50,0x1b,0x75, 0xfd,0xd5,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63, 0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34, 0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c, 0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a, 0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x32,0x2d,0x32, 0x39,0x54,0x31,0x31,0x3a,0x30,0x32,0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30, 0xa,0xbb,0x4c,0x3b,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/AlignObjectsTopHS.png 0x0,0x0,0x2,0x0, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x9c,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xcb,0xcb,0xcb,0xc4,0xc4,0xc4,0xa6,0xa6,0xa6,0xaa,0xb5,0xc5, 0xa9,0xb4,0xc4,0xa7,0xb2,0xc3,0x8f,0x9d,0xaf,0xee,0xee,0xee,0x7d,0x7d,0x7d,0xa7, 0xb2,0xc2,0xff,0xff,0xff,0xfb,0xfd,0xff,0x59,0x6a,0x81,0xb8,0xb8,0xb8,0xeb,0xeb, 0xeb,0x6c,0x6c,0x6c,0xa2,0xae,0xbf,0xfd,0xfe,0xff,0xe0,0xe6,0xed,0x46,0x59,0x71, 0xb0,0xb0,0xb0,0xe2,0xe2,0xe2,0x58,0x58,0x58,0x9d,0xa9,0xba,0xf8,0xfb,0xff,0xd3, 0xdd,0xe5,0x43,0x56,0x6f,0xd6,0xd6,0xd6,0x4e,0x4e,0x4e,0x97,0xa4,0xb6,0xf2,0xf7, 0xff,0xcc,0xd5,0xe2,0x40,0x53,0x6d,0x95,0x95,0x95,0x4d,0x4d,0x4d,0x91,0x9e,0xb1, 0xed,0xf4,0xff,0xc2,0xd1,0xe3,0x40,0x54,0x6e,0x8b,0x98,0xab,0xe6,0xf2,0xff,0xbc, 0xcd,0xe4,0x46,0x5a,0x72,0x83,0x91,0xa5,0xd7,0xe6,0xf7,0xb6,0xca,0xe5,0x3f,0x52, 0x6c,0x80,0x8e,0xa3,0x63,0x73,0x89,0x3b,0x4f,0x68,0x35,0x49,0x63,0xbf,0x8d,0xc6, 0x4c,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0,0x0, 0x0,0x1,0x62,0x4b,0x47,0x44,0xb,0x1f,0xd7,0xc4,0xc0,0x0,0x0,0x0,0x5a,0x49, 0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xa0,0xd,0x60,0x64,0x62,0x66,0x60,0x61,0x65, 0x63,0x87,0xb,0x30,0x71,0x70,0x32,0x70,0x71,0xf3,0xf0,0xc2,0x5,0xf8,0xf8,0x5, 0x18,0x4,0x85,0x84,0x45,0xe0,0x2,0xa2,0x62,0xe2,0xc,0x12,0x92,0x52,0xd2,0x70, 0x1,0x66,0x19,0x59,0x6,0x39,0x79,0x5,0x45,0xb8,0x80,0x92,0xac,0x32,0x83,0x8a, 0xaa,0x9a,0x3a,0x8a,0x4d,0x1a,0x9a,0x5a,0xda,0x28,0x2,0x3a,0xba,0x7a,0xfa,0x28, 0x2,0x6,0x86,0x46,0xc6,0xc4,0xba,0x1b,0x0,0x1,0x7,0x5,0x51,0x5,0xfb,0xe0, 0xbb,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72, 0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54, 0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c, 0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d, 0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30,0x31,0x30,0x2d,0x30,0x33,0x2d,0x31,0x39, 0x54,0x31,0x30,0x3a,0x33,0x34,0x3a,0x32,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe3, 0x3c,0x98,0xbd,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_View_Side.png 0x0,0x0,0x1,0x58, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x51, 0x49,0x44,0x41,0x54,0x28,0xcf,0xb5,0x91,0x31,0xe,0x0,0x20,0x8,0x3,0x29,0xf1, 0xff,0x5f,0xc6,0x81,0x18,0x28,0xa2,0x8b,0xd1,0x89,0xa4,0xe7,0x59,0x15,0x26,0xf7, 0xa5,0xf2,0xa,0x8c,0x18,0x91,0x4e,0x33,0x1c,0xd,0x1e,0x5,0xac,0x7b,0x1c,0xbb, 0x8b,0xd7,0x47,0x8e,0xa9,0x43,0x8f,0xc1,0xa4,0x17,0x2e,0xa4,0x18,0x6a,0xc5,0x54, 0x12,0x86,0xf6,0x51,0xe9,0x16,0xe,0x31,0xa8,0x2c,0xdf,0x4a,0x9,0xfe,0x7f,0xd6, 0x4,0xf,0x9d,0x19,0x1f,0x9c,0xb8,0x39,0xc3,0x0,0x0,0x0,0x25,0x74,0x45,0x58, 0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31, 0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x32, 0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30, 0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a,0x31,0x35,0x3a,0x31, 0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0x57,0x68,0x12,0x12,0x0,0x0,0x0,0x0,0x49, 0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/UpDirectory_16x16.png 0x0,0x0,0x2,0xa1, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x6,0x0,0x0,0x0,0x1f,0xf3,0xff,0x61, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xaf,0xc8,0x37,0x5,0x8a,0xe9, 0x0,0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x53,0x6f,0x66,0x74,0x77,0x61,0x72,0x65, 0x0,0x41,0x64,0x6f,0x62,0x65,0x20,0x49,0x6d,0x61,0x67,0x65,0x52,0x65,0x61,0x64, 0x79,0x71,0xc9,0x65,0x3c,0x0,0x0,0x2,0x33,0x49,0x44,0x41,0x54,0x78,0xda,0x74, 0x53,0x3d,0x6f,0xd3,0x50,0x14,0x3d,0xfe,0x28,0x49,0x68,0x48,0x1b,0x95,0x6,0x83, 0x48,0xb,0x2d,0x53,0xba,0xb4,0x5d,0x60,0x67,0x63,0x2a,0x3,0x2c,0xfc,0x2,0x86, 0x8,0x31,0x1,0x52,0x5,0xb,0x42,0x88,0xad,0x8,0xc4,0x80,0x90,0xd8,0xd9,0x91, 0x18,0x18,0xab,0x8,0x44,0x7,0x40,0x62,0x1,0x1a,0x40,0x88,0x36,0x56,0x92,0xc6, 0xc8,0x38,0xb5,0xdf,0x17,0xef,0xc3,0xb1,0xea,0x8,0x9e,0x75,0x74,0xdf,0xf3,0x7b, 0xe7,0xbc,0x73,0xaf,0xaf,0x5d,0x21,0x4,0xfa,0xef,0xef,0xef,0x40,0x8,0x87,0x71, 0x3a,0x2b,0x38,0x83,0x2,0xd7,0xa0,0xb0,0x6c,0x17,0xf2,0x5,0x8e,0xcc,0x2d,0xe1, 0x62,0xeb,0x31,0x5e,0x5f,0x7a,0x63,0xe1,0xc0,0x70,0xd3,0xe8,0x15,0x8e,0x1e,0x43, 0x3c,0xe8,0x82,0x33,0x8e,0x89,0xa9,0x19,0x44,0xbc,0x80,0xda,0xf1,0x3a,0x1c,0xd7, 0x1c,0xb9,0xf0,0xf2,0x6,0xba,0xb,0x6d,0x9c,0x7f,0x71,0x56,0x1c,0x14,0xb1,0x47, 0x13,0x25,0x50,0x39,0xb3,0x84,0xf2,0xfc,0x22,0x18,0x8d,0x30,0xdc,0xde,0xc4,0xaf, 0x1f,0xdf,0x11,0x6,0x81,0x26,0x17,0xe7,0x5,0x56,0xa6,0x57,0x51,0x5f,0xad,0x6a, 0x91,0x71,0x7,0xd9,0x70,0xe,0x15,0x30,0xe9,0xcd,0xa1,0xbf,0xfd,0x1,0x16,0x63, 0xb8,0xbc,0x79,0x4f,0x93,0xab,0x95,0xe9,0xec,0xcc,0x48,0x84,0xc5,0x56,0xcd,0x38, 0x90,0x75,0x50,0x8f,0xca,0x59,0x83,0x11,0x9,0x8a,0xab,0x9f,0x9f,0xe9,0xed,0x64, 0xd7,0x10,0x2b,0xe5,0x32,0x66,0xab,0x33,0xe8,0x7f,0x8d,0xe0,0x4e,0xd8,0x70,0xa, 0xc2,0x77,0xd,0x9f,0x43,0x30,0xaa,0xb,0xa7,0x63,0x3a,0x7f,0x74,0xfa,0xa,0x6c, 0x99,0x6d,0xb3,0xf3,0x5c,0x13,0x39,0xe5,0xe8,0x75,0x2,0xc4,0x11,0xc1,0xab,0xb5, 0x96,0x95,0xa5,0xa0,0x4,0xc,0x29,0x25,0x53,0xa2,0xe7,0x82,0x27,0xe0,0xa9,0xed, 0x30,0x88,0x10,0xfe,0xe,0xe1,0xb7,0x43,0xb5,0xbc,0x9b,0x2b,0x22,0xe7,0xdc,0xd8, 0xa6,0x49,0x6,0xe5,0x64,0xaf,0xd3,0xc6,0x40,0x42,0x8d,0xdd,0x9f,0x3e,0x3a,0xdf, 0x2,0x34,0x27,0x3d,0x3c,0xc0,0xc2,0x7a,0x4e,0x40,0x8,0x26,0x2b,0x9f,0x18,0x90, 0x58,0xc6,0xd8,0xf4,0x41,0x32,0xc4,0x1d,0xa7,0x65,0x1c,0xf4,0x8,0x9a,0xa5,0x13, 0x38,0xb7,0xf2,0x14,0x3c,0xde,0xcb,0xf7,0x81,0x50,0xe,0x14,0x59,0xbb,0x48,0x9d, 0x48,0x81,0xdb,0xc5,0x2d,0x58,0xd4,0x6,0xb,0x5d,0x5c,0x9b,0xf2,0xb0,0x58,0x74, 0x31,0x4a,0x39,0x27,0xa0,0xe,0xb3,0xd4,0xfa,0x48,0x44,0x75,0xe3,0xfa,0xe0,0x14, 0x1c,0xcb,0x42,0xfd,0x64,0x49,0xae,0xd5,0x3b,0x6a,0x4,0xe4,0x5e,0x3e,0x5,0xb9, 0x61,0xac,0x8f,0xa5,0xa0,0x22,0x93,0xa0,0x43,0x89,0x7d,0x7d,0xee,0xfa,0x56,0x0, 0xd5,0xfe,0xff,0x70,0x10,0xeb,0x9b,0x33,0x7,0xfa,0xd3,0x4a,0x8,0x4b,0x12,0x9d, 0x8c,0xd0,0xed,0x46,0xb9,0x14,0xec,0x91,0x25,0x46,0x12,0x23,0x42,0x62,0x7d,0xb3, 0xfe,0xa9,0x4,0x1b,0x6f,0x54,0x3c,0xf4,0x6e,0x29,0x81,0x2f,0x63,0xe,0x28,0x88, 0xbf,0x3,0x26,0xa8,0xee,0x48,0x25,0xab,0x6c,0xfe,0xe9,0x13,0x38,0xe,0x43,0xf, 0x2c,0xeb,0x56,0x19,0x15,0xf9,0xc9,0x78,0xa,0x35,0x1a,0x47,0xd,0x9a,0x44,0xd, 0x42,0xf6,0x97,0x65,0x1d,0x1a,0xb2,0x37,0x96,0xdf,0x7d,0xea,0xaf,0x1d,0x2e,0x95, 0x3f,0xde,0xdc,0x78,0xeb,0xe3,0x3f,0xe3,0xaf,0x0,0x3,0x0,0x9d,0x7b,0xa6,0x1f, 0x2b,0xdb,0x1a,0xdf,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Viewport_RenderFlag_WireframeOverlay.png 0x0,0x0,0x1,0x5c, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x4,0x0,0x0,0x0,0xb5,0xfa,0x37,0xea, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0x2,0x62,0x4b,0x47, 0x44,0x0,0xff,0x87,0x8f,0xcc,0xbf,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0, 0x0,0xe,0xc4,0x0,0x0,0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x55, 0x49,0x44,0x41,0x54,0x28,0xcf,0x85,0x91,0x41,0x12,0xc0,0x30,0x8,0x2,0x8b,0xe3, 0xff,0xbf,0x4c,0xf,0xc6,0x8c,0xa9,0xc5,0x78,0x73,0x58,0x15,0x12,0xf0,0x99,0xcb, 0x6b,0x83,0x46,0x13,0x5e,0x65,0xa2,0xe3,0xa6,0xe5,0xe8,0x6d,0x96,0x17,0xa0,0xe5, 0x6d,0x12,0x32,0x8c,0xa7,0x5b,0x95,0xc6,0x94,0xf0,0xb,0x8c,0xf,0x15,0xd3,0xe0, 0xf7,0xdc,0x6,0x88,0x9e,0xe6,0x72,0x22,0xf0,0x3,0xa8,0xf3,0xb9,0xd,0x14,0xee, 0x13,0xc6,0xed,0xbb,0x5f,0xcb,0xbe,0x25,0x27,0xaf,0xae,0x1,0xb8,0x0,0x0,0x0, 0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65, 0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30, 0x31,0x3a,0x30,0x32,0x2b,0x31,0x30,0x3a,0x30,0x30,0xbd,0x64,0xff,0xc4,0x0,0x0, 0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66, 0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x33,0x2d,0x32,0x33,0x54,0x32,0x33,0x3a, 0x31,0x33,0x3a,0x34,0x35,0x2b,0x31,0x30,0x3a,0x30,0x30,0xe6,0xd9,0x48,0x22,0x0, 0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/NewDocumentHS.png 0x0,0x0,0x2,0x9c, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x0,0xed,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xff,0xff,0x67,0xff,0xff,0x54,0xff,0x9b,0x0,0xff,0xd3,0x0, 0xff,0xfe,0x4f,0xff,0xff,0x58,0xff,0xd8,0xd,0xfa,0x79,0x0,0xff,0xff,0x95,0xff, 0xb4,0x0,0xff,0xd6,0x0,0xff,0xf5,0x3d,0xff,0xdb,0xb,0xff,0xa0,0x0,0xff,0xb1, 0x0,0xf0,0xd9,0x3b,0xae,0xbe,0xd4,0xa9,0xb9,0xcf,0xa4,0xb3,0xc9,0xfa,0x8c,0x0, 0xff,0x95,0x0,0xff,0x91,0x0,0xff,0xff,0xff,0xff,0xff,0xa8,0xff,0x9a,0x0,0xff, 0xa8,0x0,0x9c,0xab,0xc0,0x36,0x4a,0x64,0xff,0xe7,0x13,0xff,0x92,0x0,0xff,0xde, 0x5,0xff,0xbf,0x0,0xff,0xf8,0x31,0xff,0xe3,0x1c,0x95,0xa4,0xb9,0xba,0xc5,0xd4, 0xff,0xfc,0x4c,0xff,0xff,0x7f,0x93,0xa2,0xb7,0xff,0xf4,0x3e,0xff,0x9d,0x0,0xff, 0xdc,0x2,0xff,0xff,0x99,0xfb,0xfc,0xfd,0xff,0xed,0x2c,0xff,0xdb,0xe,0xff,0xae, 0x0,0xff,0xe4,0x1f,0xff,0xed,0x79,0xff,0xf4,0x9b,0xfe,0xfe,0xfe,0xf5,0xf7,0xfa, 0xe9,0xed,0xf5,0x35,0x49,0x63,0x9e,0xae,0xc3,0xf9,0xfa,0xfc,0xee,0xf1,0xf7,0xe1, 0xe7,0xf1,0x9a,0xa9,0xbe,0xfc,0xfd,0xfe,0xf2,0xf5,0xf9,0xe6,0xeb,0xf4,0xda,0xe1, 0xee,0x96,0xa5,0xba,0xf7,0xf8,0xfb,0xeb,0xef,0xf6,0xdf,0xe5,0xf0,0xd3,0xdb,0xeb, 0xf0,0xf3,0xf8,0xe3,0xe9,0xf2,0xd8,0xdf,0xed,0xcb,0xd5,0xe7,0xdc,0xe3,0xef,0xd1, 0xd9,0xea,0xc4,0xcf,0xe4,0xd5,0xdd,0xec,0xc9,0xd3,0xe6,0xbd,0xca,0xe1,0x42,0xbf, 0x9f,0xce,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0,0x40,0xe6,0xd8,0x66,0x0, 0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x17,0xb,0xd6,0x98,0x8f,0x0,0x0,0x0,0xa5, 0x49,0x44,0x41,0x54,0x18,0xd3,0x4d,0xcd,0x57,0x3,0xc1,0x30,0x14,0x86,0xe1,0xa0, 0x48,0x5a,0xbb,0x38,0x54,0xec,0x11,0xa3,0x36,0xb5,0xf7,0x9e,0xff,0xff,0xe7,0x68, 0x4a,0xaa,0xef,0xdd,0x79,0x2e,0xbe,0x83,0x10,0x72,0xb9,0x3d,0x92,0xd7,0x87,0xec, 0xfc,0x98,0xc8,0xa,0xc1,0x1,0x1b,0x82,0x4,0x87,0xc2,0x98,0x44,0xa2,0x31,0x55, 0xb5,0x20,0x9e,0x48,0x42,0x4a,0x4e,0x6b,0x0,0x19,0x6a,0x89,0x92,0xcd,0x49,0xf9, 0x42,0xb1,0x4,0x50,0xae,0x58,0x52,0x25,0x58,0x93,0x31,0xa9,0x1,0x30,0x4a,0xa9, 0x9,0x75,0x4c,0x1a,0x4d,0x82,0x5b,0x0,0x3a,0x63,0x1c,0x50,0xbb,0xd3,0xed,0xf5, 0x7,0x0,0xc3,0xd1,0x98,0x19,0xdf,0x47,0x13,0xe0,0x4d,0x67,0x73,0x1,0xb,0x7e, 0x2f,0x57,0xeb,0x8d,0x80,0x2d,0x87,0xdd,0xfe,0x70,0x14,0xc0,0xcc,0x5b,0x3f,0x9d, 0x2f,0x57,0x7,0x98,0x8b,0xb7,0xfb,0xc3,0x1,0xe6,0xe2,0xf3,0xf5,0xfe,0x3,0xfb, 0x25,0xc0,0xb0,0x43,0x1f,0x1a,0xf9,0x18,0xaf,0x78,0x25,0xa2,0xa9,0x0,0x0,0x0, 0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65, 0x0,0x32,0x30,0x31,0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30, 0x31,0x3a,0x32,0x31,0x2b,0x31,0x30,0x3a,0x30,0x30,0xce,0xa9,0xe2,0x24,0x0,0x0, 0x0,0x25,0x74,0x45,0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66, 0x79,0x0,0x32,0x30,0x31,0x32,0x2d,0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31,0x3a, 0x30,0x32,0x3a,0x35,0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b,0x0, 0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/icons/Edit_RedoHS.png 0x0,0x0,0x2,0x98, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0x10,0x0,0x0,0x0,0x10,0x8,0x3,0x0,0x0,0x0,0x28,0x2d,0xf,0x53, 0x0,0x0,0x0,0x4,0x67,0x41,0x4d,0x41,0x0,0x0,0xb1,0x8f,0xb,0xfc,0x61,0x5, 0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0, 0x20,0x63,0x48,0x52,0x4d,0x0,0x0,0x7a,0x26,0x0,0x0,0x80,0x84,0x0,0x0,0xfa, 0x0,0x0,0x0,0x80,0xe8,0x0,0x0,0x75,0x30,0x0,0x0,0xea,0x60,0x0,0x0,0x3a, 0x98,0x0,0x0,0x17,0x70,0x9c,0xba,0x51,0x3c,0x0,0x0,0x1,0x2,0x50,0x4c,0x54, 0x45,0x0,0x0,0x0,0xaa,0xc2,0xf5,0xa9,0xc1,0xf5,0xa7,0xc1,0xf5,0x9e,0xbb,0xf5, 0x8c,0xaf,0xf4,0x79,0xa1,0xf4,0x9d,0xb9,0xf5,0x7f,0xa4,0xf4,0x81,0xa8,0xf4,0x85, 0xaa,0xf4,0x78,0xa2,0xf4,0x79,0xa2,0xf4,0x99,0xb7,0xf5,0x47,0x79,0xe0,0x37,0x60, 0xb4,0x3a,0x64,0xb6,0x40,0x6d,0xc7,0x64,0x93,0xf3,0x71,0x9c,0xf4,0x71,0x9d,0xf4, 0xa6,0xc8,0xf5,0x40,0x72,0xd6,0xa5,0xc0,0xf5,0x56,0x88,0xee,0x36,0x5b,0x9f,0x44, 0x6e,0xaf,0x35,0x5d,0xac,0x36,0x5f,0xb3,0x63,0x93,0xf3,0x67,0x99,0xf3,0x6b,0x9d, 0xf4,0x9e,0xc0,0xf5,0x3b,0x69,0xc7,0x80,0xa5,0xf4,0x45,0x77,0xdc,0x27,0x4a,0x8c, 0x50,0x7d,0xb7,0x35,0x5d,0xa9,0x33,0x5b,0xa7,0x2c,0x50,0x9b,0x55,0x89,0xf1,0x6a, 0x9a,0xf3,0x34,0x5f,0xb5,0x80,0xa9,0xf4,0x45,0x77,0xde,0x26,0x49,0x8e,0x20,0x40, 0x7e,0x34,0x5c,0xa8,0x28,0x4b,0x92,0x76,0x9c,0xec,0x5b,0x8d,0xf3,0x4b,0x82,0xec, 0x2e,0x55,0xa3,0x83,0xa9,0xf4,0x4b,0x7f,0xe8,0x28,0x4b,0x93,0x94,0xb5,0xf5,0x49, 0x82,0xea,0x36,0x73,0xdf,0x28,0x4c,0x95,0x70,0x97,0xe3,0x51,0x85,0xec,0x32,0x59, 0xac,0x3a,0x69,0xc7,0x34,0x5f,0xb6,0x2e,0x54,0xa4,0x25,0x46,0x8a,0x8d,0xb0,0xf5, 0x66,0x93,0xef,0x45,0x76,0xdb,0x27,0x4a,0x92,0x56,0x7e,0xcf,0x54,0x88,0xf0,0x38, 0x64,0xbe,0x2a,0x50,0x9b,0x4f,0x7b,0xd6,0x4f,0x84,0xf0,0x40,0x6f,0xd0,0x5e,0x8e, 0xef,0x4c,0x79,0xd9,0x50,0x85,0xf3,0x48,0x7b,0xe3,0x4b,0x80,0xea,0x5a,0x8d,0xf3, 0xff,0xff,0xff,0xfd,0x66,0xd9,0x13,0x0,0x0,0x0,0x1,0x74,0x52,0x4e,0x53,0x0, 0x40,0xe6,0xd8,0x66,0x0,0x0,0x0,0x1,0x62,0x4b,0x47,0x44,0x55,0x93,0x4,0xb8, 0x33,0x0,0x0,0x0,0x8c,0x49,0x44,0x41,0x54,0x18,0xd3,0x63,0x60,0xc0,0x4,0x8c, 0x4c,0xcc,0x2c,0xac,0x6c,0x48,0x7c,0x46,0x76,0xe,0x4e,0x2e,0x6e,0x1e,0x84,0x0, 0x2f,0x1f,0xbf,0x80,0xa0,0x90,0xb0,0x8,0x83,0xa8,0x18,0x58,0x40,0x5c,0x42,0x52, 0x4a,0x5a,0x5a,0x46,0x56,0x4e,0x5e,0x41,0x91,0x11,0x24,0xa0,0xa4,0xac,0xa2,0xca, 0xa0,0xa6,0xae,0xa1,0x29,0xac,0xa5,0xd,0x56,0xa1,0xa3,0xab,0xa7,0xcf,0xc0,0x60, 0x60,0x68,0x64,0x6c,0x62,0xa,0x16,0x30,0x33,0xb7,0x0,0xa,0x58,0x5a,0x6a,0x59, 0x59,0xdb,0x80,0x5,0x6c,0xed,0xec,0x81,0x2,0x62,0xe,0x8e,0x4e,0x36,0xce,0x60, 0x1,0x17,0x57,0x37,0x77,0x90,0x65,0x8,0x87,0x78,0x78,0x7a,0xa1,0xba,0xd4,0xdb, 0xc7,0xd7,0xcf,0x1f,0x55,0x24,0x20,0x30,0x8,0xcd,0x3b,0xc1,0x21,0xc,0xc4,0x3, 0x0,0x37,0x85,0xf,0x84,0x11,0xb3,0xe7,0xee,0x0,0x0,0x0,0x25,0x74,0x45,0x58, 0x74,0x64,0x61,0x74,0x65,0x3a,0x63,0x72,0x65,0x61,0x74,0x65,0x0,0x32,0x30,0x31, 0x33,0x2d,0x30,0x38,0x2d,0x31,0x34,0x54,0x32,0x30,0x3a,0x30,0x31,0x3a,0x30,0x31, 0x2b,0x31,0x30,0x3a,0x30,0x30,0x8c,0x8c,0xe5,0x59,0x0,0x0,0x0,0x25,0x74,0x45, 0x58,0x74,0x64,0x61,0x74,0x65,0x3a,0x6d,0x6f,0x64,0x69,0x66,0x79,0x0,0x32,0x30, 0x31,0x32,0x2d,0x30,0x32,0x2d,0x32,0x39,0x54,0x31,0x31,0x3a,0x30,0x32,0x3a,0x35, 0x36,0x2b,0x31,0x30,0x3a,0x30,0x30,0xa,0xbb,0x4c,0x3b,0x0,0x0,0x0,0x0,0x49, 0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // D:/Projects/GameEngineDev/Engine/Source/Editor/Resources/qdarkstylesheet.qss 0x0,0x0,0x10,0x60, 0x0, 0x0,0x53,0x6f,0x78,0x9c,0xed,0x1c,0x6b,0x73,0xdb,0xb8,0xf1,0xbb,0x7f,0x5,0x2e, 0xf9,0x12,0xa7,0x92,0xad,0xa7,0x1f,0xcc,0x5d,0x67,0x64,0x5b,0x8a,0x35,0xb5,0x2d, 0x47,0x56,0x92,0x66,0x3a,0x9d,0xc,0x45,0x51,0x16,0x2f,0x14,0xc1,0x90,0xd4,0xd9, 0xbe,0x9b,0xfb,0xef,0x5d,0xbc,0x28,0x0,0x4,0x5f,0x8a,0x93,0x9b,0x76,0x1a,0x25, 0x76,0x48,0x0,0xfb,0xc6,0x62,0xb1,0x58,0xe8,0xf0,0xf5,0x1e,0x7a,0x8d,0x66,0x2b, 0x17,0x5d,0x8f,0x67,0xe8,0xca,0x73,0xdc,0x20,0x76,0xd1,0x2b,0x78,0xd8,0x87,0x6, 0xd2,0x76,0x8e,0xc3,0xa7,0xc8,0xbb,0x5f,0x25,0xe8,0x95,0xb3,0x8f,0x7e,0xee,0xb4, 0xda,0xdd,0x26,0xfc,0xe8,0xfd,0x1d,0xfd,0x7c,0x8e,0x7d,0x2f,0x40,0x17,0x9b,0xaf, 0x1b,0x37,0xe,0xf0,0xd3,0xdf,0xf9,0x88,0x5b,0x37,0x5a,0x7b,0x71,0xec,0xe1,0x0, 0x79,0x31,0x5a,0xb9,0x91,0x3b,0x7f,0x42,0xf7,0x91,0x1d,0x24,0xee,0xa2,0x81,0x96, 0x91,0xeb,0x22,0xbc,0x44,0xce,0xca,0x8e,0xee,0xdd,0x6,0x4a,0x30,0xb2,0x83,0x27, 0x14,0xba,0x51,0xc,0x3,0xf0,0x3c,0xb1,0xbd,0xc0,0xb,0xee,0x91,0x8d,0x1c,0xc0, 0x4c,0xe0,0x41,0xe7,0x64,0x5,0x90,0x62,0xbc,0x4c,0x1e,0xec,0xc8,0x85,0xfe,0xb, 0x64,0xc7,0x31,0x76,0x3c,0x1b,0x40,0xa2,0x5,0x76,0x36,0x6b,0x37,0x48,0xec,0x84, 0xa0,0x5c,0x7a,0xbe,0x1b,0xa3,0x57,0x9,0xb0,0xf4,0xe2,0x8e,0x8f,0x78,0xb1,0x4f, 0xf1,0x2c,0x5c,0xdb,0x27,0x0,0x81,0x68,0xd2,0x2c,0x5a,0xd1,0x83,0x97,0xac,0xf0, 0x26,0x41,0x91,0x1b,0x27,0x91,0xe7,0x10,0x30,0xd,0xe8,0xe4,0xf8,0x9b,0x5,0xa1, 0x44,0x34,0xfb,0xde,0xda,0xe3,0x48,0xc8,0x70,0x2a,0x94,0x98,0xc0,0x3,0xd0,0x9b, 0x18,0x58,0x21,0x4,0x37,0xd0,0x1a,0x2f,0xbc,0x25,0xf9,0xed,0x52,0xfe,0xc2,0xcd, 0xdc,0xf7,0xe2,0x55,0x3,0x2d,0x3c,0x2,0x7d,0xbe,0x49,0xe0,0x65,0x4c,0x5e,0x52, 0x59,0x37,0x8,0x37,0x87,0x38,0x42,0xb1,0xeb,0x53,0xe2,0x0,0x88,0x7,0xc,0x50, 0xa6,0xb7,0x34,0xd2,0x6e,0x4,0x51,0x48,0x84,0x9b,0x70,0x71,0xc5,0xe4,0xcd,0xc3, 0xa,0xaf,0x55,0x7e,0x3c,0x4a,0xd5,0x72,0x13,0x5,0x80,0xd8,0xa5,0xc3,0x16,0x18, 0xc4,0x47,0xf1,0xfe,0xea,0x3a,0x9,0x79,0x43,0x46,0x2c,0xb1,0xef,0xe3,0x7,0xc2, 0xa3,0x83,0x83,0x85,0x47,0x58,0x8b,0xad,0x3d,0x61,0x11,0xf6,0x1c,0xff,0xe6,0x52, 0xa6,0x98,0xfe,0x3,0x9c,0x0,0xcd,0x8c,0x10,0xa2,0x8f,0x70,0xab,0x67,0xde,0x14, 0xaf,0x6c,0xdf,0x47,0x73,0x97,0xb,0xf,0x50,0x7b,0x1,0x81,0x46,0xde,0xa,0xbe, 0x22,0x42,0x44,0x9c,0x80,0x35,0x78,0xb6,0x8f,0x42,0x1c,0x51,0xac,0x3a,0xbf,0x7, 0x8c,0x8a,0xcb,0x21,0xba,0x9b,0x8c,0x66,0x1f,0x7,0xd3,0x21,0x1a,0xdf,0xa1,0xdb, 0xe9,0xe4,0xc3,0xf8,0x62,0x78,0x81,0x5e,0xc,0xee,0xe0,0xf9,0x45,0x3,0x7d,0x1c, 0xcf,0x2e,0x27,0xef,0x67,0x8,0x7a,0x4c,0x7,0x37,0xb3,0x4f,0x68,0x32,0x42,0x83, 0x9b,0x4f,0xe8,0x1f,0xe3,0x9b,0x8b,0x6,0x1a,0xfe,0xf3,0x76,0x3a,0xbc,0xbb,0x43, 0x93,0x29,0x81,0x36,0xbe,0xbe,0xbd,0x1a,0xf,0xe1,0xf5,0xf8,0xe6,0xfc,0xea,0xfd, 0xc5,0xf8,0xe6,0x2d,0x3a,0x83,0xa1,0x37,0x13,0x30,0xfc,0x31,0x58,0x3c,0xc0,0x9d, 0x4d,0x28,0x4e,0xe,0x6d,0x3c,0xbc,0x23,0xf0,0xae,0x87,0xd3,0xf3,0x4b,0x78,0x1c, 0x9c,0x8d,0xaf,0xc6,0xb3,0x4f,0xd,0x2,0x6b,0x34,0x9e,0xdd,0x10,0xc8,0xa3,0xc9, 0x14,0xd,0xd0,0xed,0x60,0x3a,0x1b,0x9f,0xbf,0xbf,0x1a,0x4c,0xd1,0xed,0xfb,0xe9, 0xed,0xe4,0x6e,0x8,0x44,0x5c,0x0,0xe4,0x9b,0xf1,0xcd,0x68,0xa,0x88,0x86,0xd7, 0xc3,0x9b,0xd9,0x1,0x20,0x86,0x77,0x68,0xf8,0x1,0x1e,0xd0,0xdd,0xe5,0xe0,0xea, 0x8a,0x60,0x23,0xe0,0x6,0xef,0x81,0x8d,0x29,0x21,0x14,0x9d,0x4f,0x6e,0x3f,0x4d, 0xc7,0x6f,0x2f,0x67,0xe8,0x72,0x72,0x75,0x31,0x84,0x97,0x67,0x43,0xa0,0x6f,0x70, 0x76,0x35,0x64,0xd8,0x80,0xbb,0xf3,0xab,0xc1,0xf8,0xba,0x81,0x2e,0x6,0xd7,0x83, 0xb7,0x43,0x3a,0x6a,0x2,0x80,0x28,0x93,0xa4,0x27,0x23,0x13,0x7d,0xbc,0x1c,0x92, 0xb7,0x4,0xeb,0x0,0xfe,0x9e,0xcf,0xc6,0x93,0x1b,0xc2,0xcf,0xf9,0xe4,0x66,0x36, 0x85,0xc7,0x6,0xb0,0x3b,0x9d,0xa5,0xa3,0x3f,0x8e,0xef,0x86,0xd,0x34,0x98,0x8e, 0xef,0x88,0x64,0x46,0xd3,0xc9,0x35,0xe5,0x94,0x48,0x17,0x6,0x4d,0x28,0x1c,0x18, 0x7a,0x33,0x64,0x80,0x88,0xe4,0x55,0x5,0x41,0x17,0xf2,0xfc,0xfe,0x6e,0x98,0xc2, 0x44,0x17,0xc3,0xc1,0x15,0x80,0x3,0x6d,0xdd,0xe8,0xa,0x3d,0x80,0x17,0x87,0x7b, 0x7b,0xef,0x6e,0x23,0x7c,0xf,0x33,0x2f,0x3e,0xb3,0x23,0x6b,0x85,0x23,0xef,0x77, 0xc,0x53,0xd9,0x47,0x7f,0xec,0x21,0xf8,0x33,0xc7,0xd1,0xc2,0x8d,0x2c,0xd4,0xe, 0x1f,0xc1,0x80,0x7d,0x6f,0x81,0x5e,0x76,0x7,0xdd,0xd3,0xee,0xe9,0x1b,0xda,0x9c, 0xb8,0x8f,0x49,0xd3,0xf6,0xbd,0xfb,0xc0,0x42,0x30,0x9d,0x12,0x37,0x62,0xef,0x43, 0x7b,0x41,0xa6,0x2e,0x1d,0xc7,0xde,0xcc,0x6d,0xe7,0xcb,0x7d,0x84,0x37,0xc1,0xc2, 0x42,0x2f,0xc1,0x7f,0x8d,0xda,0xa3,0x37,0x7b,0x7f,0xaa,0xd8,0x2d,0x67,0xb5,0x9, 0xbe,0x18,0x88,0x48,0xc7,0x36,0x1d,0xec,0x63,0x20,0xe7,0x2b,0x38,0x3e,0x17,0xfc, 0x57,0x64,0x2f,0x3c,0x40,0xfb,0x2a,0xe,0x23,0xd7,0x5e,0x58,0x91,0xbb,0xf4,0x61, 0x7a,0x35,0xd0,0x63,0xdb,0x6a,0x37,0xd0,0x53,0xdb,0x6a,0x1d,0xf4,0x7b,0x7d,0x78, 0xee,0xd0,0xe7,0x8e,0xd5,0x82,0x39,0x98,0xe0,0xd0,0x6a,0xa1,0xe8,0x7e,0x6e,0xbf, 0xea,0x9c,0x34,0xd0,0xd1,0x51,0x3,0xb5,0xdb,0xd0,0xdc,0xe9,0xf7,0xf7,0x79,0x73, 0x9b,0x35,0x77,0x8f,0x1b,0xe8,0x4,0xfe,0xb5,0x7b,0x47,0xac,0x79,0x9f,0xd0,0xbc, 0xf7,0x6e,0x86,0xb1,0x3f,0xf3,0xc2,0xbd,0x4a,0x32,0xca,0x52,0xf,0xb0,0x5f,0x9d, 0x2,0x25,0xed,0x56,0x87,0xa0,0x3e,0xde,0x7f,0xc3,0x7a,0xf2,0xe6,0x87,0x95,0x97, 0xb8,0x79,0x72,0xc4,0xa1,0xed,0x78,0xc9,0x93,0x85,0x3a,0xad,0x16,0x23,0xe6,0xa3, 0xb7,0xb8,0x77,0x13,0x4e,0xb,0x7,0x11,0x7b,0xfe,0x6f,0x42,0x17,0x59,0xfc,0x2f, 0xbb,0xad,0xce,0xa8,0x33,0x62,0xcd,0xe0,0xf7,0x5c,0xea,0x72,0x9b,0x99,0x8e,0x2f, 0x8f,0x4f,0x4e,0x8e,0x4f,0xe7,0x7a,0x3f,0xe,0x65,0xee,0x43,0xff,0x2c,0xa,0xdf, 0xb,0x2d,0x2e,0x92,0x37,0x92,0x78,0x9a,0xde,0xda,0xbe,0x77,0x2d,0xf0,0x54,0x1, 0xe7,0xd,0x5c,0x3a,0xd1,0xa2,0x85,0x14,0x3e,0x2c,0xe0,0x7d,0xd,0x26,0x0,0xe4, 0xef,0xe5,0x69,0xff,0xdd,0x15,0xd5,0xfe,0x5b,0xa1,0x7d,0xa2,0x6e,0xd4,0xa2,0xfa, 0x26,0xbf,0x40,0xd9,0xf4,0x9,0x7e,0xb5,0x1b,0x8c,0x76,0xa2,0x53,0xd4,0x42,0x9c, 0x21,0xae,0x64,0xd4,0x16,0x2f,0xf6,0x15,0xf9,0x73,0xc6,0x74,0x9a,0x98,0x0,0xdc, 0xc5,0xf,0x25,0x8b,0x10,0x71,0xed,0x6,0x1b,0x98,0x1e,0xb9,0x78,0x15,0x75,0x6a, 0x6,0x20,0x8d,0xb7,0x28,0x1b,0x19,0x28,0x16,0x4a,0x20,0x34,0x88,0x43,0x70,0xfa, 0x41,0x62,0x18,0x90,0xcf,0xb7,0x36,0xb2,0x64,0x2a,0x64,0x1,0x87,0x64,0xde,0x6f, 0xe1,0xd6,0x9d,0x45,0x8a,0x75,0x66,0x6d,0x72,0xd,0xee,0xc1,0x3,0xa3,0xc6,0x49, 0x82,0xd7,0x56,0x33,0x9d,0x40,0x7c,0x4a,0x89,0x6,0xfa,0x5e,0xd0,0x56,0x8d,0x14, 0xc3,0x1c,0x63,0xc8,0x60,0x52,0xca,0xd0,0x80,0x4d,0x58,0xd6,0x39,0x4c,0xd1,0xa3, 0xaf,0xf5,0xd8,0xaa,0x24,0x9d,0xeb,0xd0,0x5,0x75,0x5b,0xf0,0x43,0xfc,0x47,0x61, 0xc8,0x77,0x97,0x9,0x7,0x63,0xa6,0x55,0x56,0xa,0x3a,0x7c,0x4d,0xa2,0x2a,0x37, 0x82,0x40,0x2,0xde,0x39,0x24,0xe4,0x88,0xb6,0x53,0x99,0x8f,0x26,0xeb,0x80,0x4a, 0x92,0xae,0xf4,0xdc,0x99,0x1,0x41,0x95,0x3d,0xf7,0xf5,0x7e,0x2f,0x7b,0x2d,0xf2, 0x29,0xf5,0x3f,0x4,0xd0,0x0,0x82,0x91,0xc8,0x76,0x92,0x31,0xa0,0xfd,0xe0,0xb9, 0xf,0x1c,0x92,0xed,0xc3,0x62,0x12,0x40,0x7c,0x99,0x75,0x4b,0xa5,0xda,0xc8,0xca, 0x44,0xb1,0x24,0xe6,0x8f,0xc8,0x2c,0xdd,0xc4,0x16,0xea,0x6a,0x86,0xc1,0x7d,0xad, 0xc4,0xe3,0x12,0xe2,0xdb,0xb8,0x81,0x52,0xeb,0xa5,0xcf,0xb9,0xa6,0x42,0x17,0x8e, 0x1e,0xac,0x2b,0x27,0x6c,0x5d,0x11,0x4b,0x86,0x3d,0xd7,0xc0,0x9d,0xaf,0x5c,0xe7, 0xcb,0x19,0x7e,0x4c,0x5f,0x4c,0x81,0x22,0x7c,0xb6,0x1,0xb3,0xc,0x8c,0x38,0x98, 0xeb,0x24,0xc0,0x88,0xa3,0x19,0x42,0xbc,0x98,0xef,0x12,0xc4,0xa,0xab,0x30,0xd6, 0x51,0x8d,0xa6,0x19,0x27,0x4f,0x3e,0xf8,0x5f,0x4a,0x77,0xe9,0xfc,0x2d,0x12,0x9d, 0xc1,0xe9,0xbc,0x5,0x7a,0x42,0xe0,0x4e,0x8d,0x23,0xaa,0xc1,0x3d,0xd6,0x4c,0x9e, 0x7a,0xc5,0x8e,0xfb,0xa8,0x42,0xb6,0xac,0xc4,0x4b,0x7c,0x97,0x23,0x80,0xa0,0x16, 0x26,0x5b,0x12,0x61,0xbf,0x9,0xe1,0x3,0x9d,0x6a,0x6c,0xf4,0x1b,0xbd,0x39,0xc4, 0x31,0x8d,0xb4,0xc1,0x7d,0xe1,0xd0,0x14,0xb5,0xf0,0x29,0xd6,0x6e,0xe9,0x2e,0x83, 0x86,0xe1,0xa2,0x41,0xb6,0xdd,0x3b,0x7,0x0,0xfb,0x3,0x88,0x41,0x14,0x95,0x65, 0x5,0x55,0xe2,0x1f,0x19,0x1c,0x35,0x10,0xe3,0x10,0x57,0x2e,0x47,0xde,0x57,0x85, 0x3,0xeb,0x7,0xc0,0x6a,0x13,0x80,0xe2,0x3f,0xbb,0xa8,0xf2,0x28,0x1b,0xa7,0x55, 0x59,0xd6,0xda,0xca,0xb2,0xd6,0xd2,0x96,0x35,0x36,0xcd,0xa5,0x65,0xad,0x77,0x2, 0x9f,0xa3,0x7d,0x9d,0x59,0x6b,0x5,0x7b,0x1a,0xb0,0xc4,0xc,0xd3,0xcf,0x49,0xcc, 0x51,0xab,0x3f,0xea,0x8f,0x94,0x35,0x16,0x3e,0x47,0x7c,0xe9,0x5f,0x83,0x99,0x3d, 0x78,0x8b,0x64,0x95,0x71,0xad,0xa9,0x88,0x52,0xcf,0x2d,0x11,0xe,0x66,0xd5,0xa4, 0x41,0x4c,0x96,0x74,0x25,0xea,0xd9,0x44,0xfe,0x2b,0xeb,0xf0,0x6b,0x1c,0x7f,0x26, 0x4b,0x42,0x7c,0x18,0x39,0x87,0xd4,0x98,0x3e,0xdb,0x51,0x84,0x1f,0x3e,0xb,0x2f, 0x7a,0x10,0x6,0xf7,0x9c,0x20,0x4e,0xcc,0xd6,0x8,0x53,0x3,0x48,0xdf,0x18,0x6d, 0x9a,0x82,0xcd,0xb4,0xeb,0x53,0x42,0x63,0x3,0xec,0x7b,0x57,0x36,0xc8,0x5c,0xc9, 0xe7,0x22,0x4b,0x74,0x86,0x2f,0x23,0x17,0x4,0x6a,0x5d,0x26,0xc,0xba,0x60,0x71, 0x64,0xa3,0xac,0x57,0xba,0x48,0xd7,0x51,0xda,0x33,0x70,0x59,0x59,0x57,0x65,0xca, 0xe2,0x7c,0xa2,0xb2,0x6e,0xd5,0x19,0xdd,0xaa,0xf5,0x2f,0xd2,0xe6,0x26,0x6c,0x52, 0xf4,0x12,0xf9,0x2a,0x7f,0xb,0xfc,0x10,0x64,0xba,0x18,0x62,0xd4,0x74,0xd5,0xcc, 0x8,0x31,0x24,0xcc,0xe7,0x81,0x27,0x76,0xa2,0x75,0x28,0x2,0x2e,0xd,0x5,0x4d, 0x24,0x9e,0x53,0xd7,0x87,0xb5,0x4d,0xfb,0x84,0xea,0xe,0x55,0x56,0x46,0x66,0x85, 0x60,0xab,0x3,0xff,0xb5,0xf3,0xea,0x60,0xf6,0xd9,0xdf,0x91,0xdb,0x72,0x8f,0x2d, 0xc,0x72,0x27,0x97,0xad,0x53,0x5e,0x36,0x25,0x36,0xe1,0xf3,0xfb,0x39,0xe0,0x6c, 0x67,0x5f,0x2d,0xd1,0x5f,0x8d,0x1,0x32,0x63,0x9e,0x9f,0x5,0xb6,0x8f,0xda,0xd9, 0x59,0xb,0x2e,0x8a,0x5c,0x75,0xda,0x87,0xfa,0xaf,0x7a,0xda,0xfa,0x71,0x4a,0x2a, 0xd6,0x52,0xa1,0x8b,0x56,0x19,0xac,0xa9,0xcc,0xbf,0x4c,0x87,0xa9,0x8b,0x16,0xe4, 0xe7,0x3a,0xe8,0x5c,0x27,0x51,0xea,0x9e,0xcd,0xa0,0x53,0xe7,0x5c,0x5,0xf0,0xbb, 0x99,0xfb,0x98,0x54,0xdf,0x2d,0x55,0xda,0x4f,0x2a,0x51,0xfb,0xad,0x6f,0x7b,0x41, 0x65,0x24,0x25,0x58,0x6a,0xef,0x19,0x2e,0x5d,0x1b,0x9a,0xc9,0xce,0x19,0xe4,0xc2, 0xb6,0xf5,0x5,0x99,0xa2,0xe2,0x8d,0xb3,0xba,0x1,0xea,0x15,0x50,0x70,0xe4,0x90, 0xf,0xa3,0x20,0xdd,0xc8,0x96,0x24,0x3,0xa8,0xf9,0x78,0xbf,0xbb,0x6f,0x23,0x2f, 0xe4,0xbb,0xb6,0x7c,0xfb,0x8e,0xa1,0xe3,0x3d,0x74,0x34,0x84,0xc4,0x9d,0x4c,0x48, 0x2c,0xd2,0x2e,0x7b,0xef,0xae,0x41,0x15,0x1f,0xbd,0x0,0x6c,0x8f,0x48,0x23,0xb4, 0x23,0x3b,0xc1,0xf5,0x32,0x67,0xd9,0xec,0xab,0x2e,0xe,0x92,0x48,0x31,0xed,0xa7, 0x99,0x80,0x16,0x36,0x3d,0xf3,0x51,0xf3,0x5e,0x26,0xaa,0xd2,0x24,0x67,0xc5,0x85, 0x13,0xd6,0x4d,0xb6,0xd1,0x61,0xab,0x26,0x5b,0x34,0xdb,0x69,0x3e,0xfb,0x65,0xff, 0xe4,0xe8,0xf8,0x78,0xce,0xd6,0x50,0xbe,0x8a,0xb6,0xe,0xfa,0x22,0x4d,0x26,0xf2, 0xda,0xbc,0xdb,0x7e,0x4d,0x9e,0x4b,0xe2,0x5,0x55,0x24,0x4c,0x13,0x34,0x99,0xa4, 0xeb,0x20,0x55,0x59,0xfe,0x7e,0xd3,0x64,0xa4,0xe5,0x4,0x2a,0xd9,0xb1,0xb6,0x9e, 0x34,0x8b,0xa4,0x38,0x81,0x50,0xb7,0xa7,0x24,0x5b,0x2c,0x50,0xd,0x78,0x11,0xa2, 0x13,0x87,0xd8,0x32,0x39,0x26,0xcd,0xeb,0xb0,0x9,0x78,0x17,0xd5,0xc6,0xe7,0x6d, 0xf2,0x29,0x4d,0x78,0x99,0x45,0x59,0xe0,0x5,0x2a,0x53,0x9c,0x6b,0xe3,0x5f,0x9, 0x28,0xdb,0x4f,0x8f,0x4a,0x18,0xd9,0x8f,0x10,0x61,0x1d,0xf4,0x1b,0xc8,0x79,0x62, 0xff,0xa1,0x6f,0x97,0xe2,0xed,0x52,0x7e,0x2b,0x48,0x69,0x1f,0xa8,0x1,0xda,0x41, 0x27,0x35,0x2e,0xf5,0x7d,0x57,0xf0,0x4b,0xdf,0xee,0xab,0x4e,0x42,0x95,0xac,0x9e, 0xfa,0x4c,0x9d,0x5e,0x7a,0x38,0xb0,0x75,0xe3,0xa9,0x9b,0xd9,0x32,0xff,0x9d,0x74, 0xc0,0x1d,0xcd,0xa9,0xee,0x67,0x4e,0x45,0x38,0x69,0x56,0x85,0x39,0xf7,0x73,0xac, 0x2d,0xc5,0xf9,0x50,0xd,0xc,0x96,0xe7,0xc8,0x45,0x12,0x3c,0x9f,0xac,0x34,0xf2, 0x30,0xc1,0x57,0xe,0x5a,0x8a,0xa1,0x9b,0x86,0xab,0xc6,0xc7,0xbc,0xb9,0xc1,0x99, 0xd3,0x6e,0x73,0xfc,0xc8,0x9d,0x79,0x1e,0x34,0xb1,0x7e,0xe4,0xcf,0x3e,0x6d,0x85, 0x31,0x50,0xdc,0xeb,0xf5,0x18,0x82,0x51,0x64,0xaf,0xdd,0x82,0x74,0x1c,0x5d,0x8d, 0x12,0x9b,0x90,0xaf,0x9c,0xa0,0x65,0xb3,0xad,0xe4,0xb4,0xf,0xc2,0x8e,0x82,0x13, 0xd1,0xd3,0xee,0x49,0xf7,0x44,0x37,0x3c,0xb5,0x8b,0x64,0x7c,0x4b,0x8,0xaf,0x9a, 0xf,0x5c,0xfb,0x73,0xec,0x2f,0x14,0x34,0x86,0x6c,0x58,0xe9,0x62,0x79,0xb9,0x6, 0x35,0x26,0x30,0x7e,0x6e,0x47,0xa9,0x8c,0x33,0x0,0x45,0xb0,0x54,0xa,0xee,0x43, 0x31,0x38,0x79,0x5,0xab,0x4e,0x22,0x1d,0x55,0x5,0x68,0x75,0x32,0x65,0x90,0xb1, 0x64,0x5b,0xb7,0x9b,0x78,0xa5,0xf8,0x97,0x4a,0xa7,0xa2,0xdf,0x23,0xcf,0x29,0x19, 0x9f,0x88,0x5e,0xb4,0xad,0x6a,0x1a,0x24,0xd,0x7a,0xa7,0x3d,0x75,0xf7,0x9d,0x4d, 0xcf,0x8b,0xb5,0x8f,0xe2,0x49,0x37,0xbd,0xda,0x89,0x56,0xb6,0x41,0x3b,0x32,0xd2, 0xd2,0xd9,0x85,0x9b,0xe7,0x1c,0x5f,0xbc,0x95,0x70,0x66,0x4a,0x56,0x71,0xbc,0x65, 0xc2,0x30,0xa4,0x22,0x9e,0x59,0x18,0x25,0xc9,0x7d,0xd2,0x70,0xf8,0xda,0xe0,0x36, 0x5e,0x1f,0xaa,0xa1,0x6d,0x9f,0x7c,0xb8,0x47,0xc3,0xeb,0x39,0x6,0x8f,0xc6,0x5, 0x51,0x70,0xae,0xae,0x1e,0x5d,0x96,0xec,0x47,0x9e,0xfb,0xac,0x26,0x7b,0x1a,0x24, 0xe5,0xbe,0x8f,0xd3,0x8c,0x89,0xe0,0x46,0xec,0xcb,0x25,0x8d,0xf3,0x37,0xe9,0xe1, 0x47,0xe8,0x5,0x52,0x47,0x71,0x36,0x25,0x9e,0xc5,0xc6,0x28,0x5,0x24,0xef,0x96, 0x74,0x58,0x74,0x1b,0x23,0x6,0x46,0xae,0xbb,0x7d,0x2e,0x5f,0xa3,0xc,0x13,0x5d, 0x61,0xa4,0x68,0x5f,0x74,0xd4,0x39,0x3a,0x39,0xee,0x1a,0xec,0x4a,0x17,0x5b,0x66, 0x2f,0x50,0xa4,0xe5,0x9e,0x4d,0x3e,0x2a,0x19,0x28,0xef,0xc0,0xb3,0x9a,0x19,0xd4, 0xd9,0x1d,0x96,0xd1,0x57,0xbb,0x5e,0xa1,0x72,0xc5,0x42,0x2a,0x73,0x6b,0x11,0xe1, 0xb0,0x49,0x32,0x1,0x62,0x56,0x64,0xb3,0xb,0x5c,0xb2,0xc5,0x9,0x18,0x39,0x57, 0xae,0xe4,0x39,0x65,0xe1,0x10,0xdd,0x8,0x4b,0x6e,0x69,0xae,0x85,0xb6,0x71,0xc6, 0x17,0x76,0x4,0xa2,0xb0,0x9f,0xb2,0x1d,0xf2,0x66,0x19,0x31,0x6,0xe6,0x21,0xf2, 0x34,0xc0,0x1d,0x8e,0xa9,0x93,0x26,0x91,0x34,0x2d,0xa2,0x44,0x4d,0xf5,0x12,0x76, 0x79,0x20,0x2d,0x52,0x39,0x69,0x6e,0x61,0xb3,0x2a,0x67,0x98,0x7c,0xdc,0x5c,0x23, 0xe7,0xa4,0x2d,0x5,0x5a,0xb0,0xfa,0x8c,0x5,0x32,0xc5,0x27,0x89,0x9a,0x27,0x42, 0x7f,0x64,0xe7,0x71,0x27,0x6f,0x7d,0x30,0xee,0xe1,0xab,0xd5,0x9f,0x54,0xca,0x1a, 0x65,0xed,0xc5,0xe8,0x6e,0x75,0x67,0xba,0x9,0x9b,0x73,0x39,0x82,0xc9,0xa2,0xcf, 0xd4,0xde,0x18,0xa6,0x96,0x5c,0x86,0x65,0x9c,0x59,0xec,0xf4,0x5b,0x4c,0x2e,0x13, 0x21,0xd4,0x48,0x7e,0x20,0x29,0xec,0xac,0xc8,0x44,0x49,0x9a,0x6f,0xcc,0x2e,0x3d, 0xdb,0x54,0x64,0xba,0x85,0x28,0xe8,0x83,0x97,0xcb,0xd2,0xd8,0xb2,0x28,0xd9,0x5f, 0x72,0x34,0xfb,0x67,0x1,0xe9,0xca,0x5a,0x56,0x39,0x79,0x4d,0xf3,0x29,0x19,0x98, 0xdb,0xe9,0x6b,0x60,0x56,0x9a,0xdb,0x5,0x22,0x91,0x1d,0xc7,0x72,0xf9,0xd,0xfe, 0x68,0x47,0xb1,0xe8,0xee,0x69,0x27,0xf,0xb4,0xf7,0xee,0xca,0x9e,0xbb,0xbe,0x16, 0x20,0xb4,0xd2,0x69,0xbc,0x2d,0x5a,0x92,0xab,0x70,0xac,0xd0,0xe,0xdc,0xf2,0x22, 0x57,0x5e,0xba,0xb3,0x2d,0xbf,0xfb,0x1a,0xc2,0x8a,0x6,0x3b,0x94,0xa7,0xe6,0x22, 0xb2,0x1f,0xce,0xec,0x98,0x15,0x30,0x9a,0x22,0xc9,0x74,0x72,0x33,0x0,0xc6,0x9a, 0x1e,0x42,0xa6,0x34,0x7d,0xe4,0xa,0x2b,0x3e,0xca,0x72,0x7c,0x1c,0xbb,0x7c,0xa, 0xa2,0x52,0xc3,0xa5,0xbd,0x25,0xad,0x14,0x96,0xeb,0x91,0x51,0x4d,0x92,0x69,0x35, 0x4,0xc4,0xd2,0xe9,0x99,0x89,0x92,0x9c,0x12,0x4d,0x8b,0xd7,0xd5,0xf6,0xfb,0xb4, 0x60,0x56,0xfc,0x68,0xed,0xe7,0xfb,0xc4,0x5c,0xc,0x7c,0x39,0x51,0xdd,0x39,0x2b, 0x8f,0xeb,0xf1,0x7f,0x82,0xc4,0xc3,0xd7,0x68,0x36,0xb9,0x45,0x4d,0x74,0x36,0x99, 0xcd,0x26,0xd7,0x68,0x36,0x38,0xbb,0x23,0x55,0x6d,0x29,0xe0,0xc4,0x9e,0x5b,0x24, 0x8c,0x28,0xc8,0x18,0xd5,0xf5,0xff,0x15,0xf3,0xb3,0x72,0xe4,0xd4,0xd6,0x56,0x32, 0x92,0xb5,0x1d,0xf4,0x4f,0xfb,0xa7,0xfb,0x3b,0x6d,0xd8,0x8a,0x23,0xd5,0xcc,0xa, 0xa7,0xe6,0x42,0x59,0x45,0xa4,0x1e,0xe3,0xd0,0x28,0x28,0x2f,0xc4,0xc9,0x9,0x82, 0x64,0x5,0x12,0x39,0x33,0xc4,0xff,0x17,0x75,0x81,0xa8,0x79,0xb0,0x58,0x28,0xed, 0xe2,0x80,0x52,0x33,0x6c,0xcb,0xb7,0xe3,0x4,0x42,0xbf,0xac,0x1e,0x68,0x8b,0x52, 0x84,0x2a,0xc8,0x6a,0x99,0x21,0x2d,0xbd,0x28,0x4e,0xac,0x9f,0x44,0x5,0xa8,0x19, 0xa8,0xd6,0x49,0x85,0xcf,0x64,0xda,0xca,0x23,0x55,0x1f,0x65,0x32,0x11,0xb9,0xf2, 0x6f,0x2b,0x98,0xe2,0x4a,0x52,0x1d,0x8f,0x99,0x38,0xa1,0x2b,0x23,0x79,0xbc,0xb1, 0x6,0x85,0x2,0xdc,0x2e,0x44,0xf2,0xb1,0x66,0x3a,0x59,0xe8,0xbb,0xf5,0x6f,0x57, 0xc3,0xd1,0xc,0x1c,0x1c,0xbb,0x9a,0x62,0xf4,0x6f,0x44,0xec,0xdf,0x79,0xd6,0xb5, 0x33,0xb3,0xae,0xf5,0xd,0xb3,0x2e,0x33,0x8f,0xb8,0x61,0x66,0x82,0xf5,0x8a,0x29, 0x1e,0x4d,0x25,0x66,0xf,0xf7,0x2d,0xbb,0x38,0x59,0xda,0xec,0x4e,0xd6,0x8f,0x73, 0x72,0xed,0xff,0x4e,0x71,0x57,0x71,0x71,0xd9,0x3e,0xba,0xb0,0x29,0x3,0x35,0x66, 0x25,0xe7,0x6c,0x97,0x49,0x49,0x51,0xd5,0xf6,0x6b,0xc,0x61,0xd,0xa,0x35,0x95, 0xd4,0x24,0x92,0xa1,0x33,0x53,0x29,0xbc,0xbb,0x4a,0x26,0x62,0xa9,0x76,0x7e,0xa2, 0xc2,0xec,0x9b,0x45,0xde,0x6e,0x40,0x23,0x79,0x6e,0xca,0x5,0xa1,0xa5,0xa1,0xf8, 0x11,0xe0,0x23,0x23,0x2,0xaa,0xd2,0x9a,0xf0,0xb3,0x35,0x87,0x55,0xc8,0x17,0x3b, 0x91,0x5a,0xf4,0x67,0xf6,0x2f,0x55,0x18,0xa9,0x8e,0xa9,0xa0,0x28,0x96,0x6e,0x43, 0x2e,0xb0,0xf3,0x85,0xed,0x43,0xf2,0x77,0x20,0xbd,0x56,0x77,0xd4,0xe5,0xd9,0x5, 0x5a,0xe8,0x3e,0xb7,0xa3,0x26,0x8b,0x8f,0x9,0x9e,0x4a,0xc1,0x7f,0x3a,0x2e,0xc0, 0xd1,0xda,0xf6,0xf3,0x7,0x82,0xcd,0x1,0x49,0x52,0x56,0x67,0x4b,0xa1,0x1a,0x94, 0x43,0x34,0x20,0x37,0x2d,0x7d,0x6c,0x27,0x62,0x6f,0x92,0xc7,0x4a,0xce,0x2d,0x21, 0x83,0x57,0xa8,0xb5,0x57,0x29,0x22,0x33,0x3d,0xf3,0xcc,0x23,0x96,0x75,0xc8,0xdc, 0x2f,0x34,0x6f,0x5f,0xda,0xad,0x12,0xa9,0x88,0xad,0x4a,0x11,0xc2,0x9c,0xdd,0xc, 0x11,0x53,0x33,0xfd,0x61,0xbc,0x2e,0x59,0x48,0x92,0xc8,0x92,0x37,0xc8,0xfa,0x11, 0x27,0x72,0x42,0xb9,0x38,0x55,0x5e,0x90,0xd0,0x92,0xe1,0x5a,0x73,0x50,0x84,0xb3, 0xb2,0xe4,0x70,0x50,0x6b,0xca,0xdb,0x9,0x1a,0xec,0x4c,0xd2,0xaa,0x64,0x6c,0x29, 0xc0,0x14,0xa2,0x1d,0x83,0xaa,0xe7,0x3e,0x48,0x28,0xb6,0x7e,0xb2,0x17,0xbf,0x62, 0x2f,0x88,0x9b,0xe4,0x62,0x92,0x62,0x64,0x5,0xe5,0x71,0xbb,0x20,0xfa,0x8e,0x78, 0x7e,0x22,0x88,0x9c,0x95,0xe7,0x2f,0xa0,0x27,0x7b,0xfa,0x11,0x68,0xb,0xb0,0x52, 0xf3,0x5d,0x34,0xc,0x83,0x58,0x8b,0x3a,0x56,0x1e,0x5a,0x9a,0x82,0x60,0x70,0x3e, 0x33,0x38,0x45,0xe4,0xe1,0x90,0x83,0x36,0xd3,0x68,0x22,0x2e,0x3b,0x44,0x21,0xad, 0x2a,0x6d,0x4,0xcc,0x37,0x9,0x2e,0x4d,0xa7,0xd7,0x16,0x9f,0xe2,0x79,0x2a,0xa, 0xb1,0x89,0x3,0xc9,0xab,0xef,0x22,0xcb,0x7c,0x7a,0x8b,0x25,0xca,0xa9,0xad,0x23, 0xd7,0x2c,0xb1,0xc2,0x31,0xf1,0xbb,0x85,0x69,0x94,0x94,0x7a,0xe9,0xd2,0xe,0x5b, 0xaa,0x4d,0x1d,0x50,0x9e,0x1f,0x87,0xc8,0x99,0xff,0xe5,0xd4,0xc8,0x77,0x8e,0xe5, 0x0,0x6d,0x44,0xff,0xec,0x19,0x88,0x2d,0xa3,0xb5,0x8c,0xd4,0x72,0x4a,0x85,0x57, 0x36,0x51,0xc4,0xcb,0x54,0xc0,0x79,0x83,0x27,0xb7,0x60,0x4,0x0,0xa9,0x7d,0x49, 0x5f,0xe4,0x61,0x4f,0x4c,0x8b,0x8b,0x72,0x8a,0x21,0x5d,0x63,0x55,0x2f,0xa,0xa4, 0x6b,0x75,0x2f,0x2d,0x9d,0xe1,0x34,0xe5,0x15,0xab,0xc8,0x38,0x76,0x3f,0x68,0x3c, 0x68,0xf1,0x23,0x95,0xc6,0xb6,0xea,0xc,0xbd,0xb4,0x4f,0xc8,0x47,0x3e,0x7c,0xec, 0x90,0x8f,0x92,0x63,0xcc,0x95,0x86,0x48,0x53,0xa7,0x47,0xb8,0x69,0x9a,0x5a,0xab, 0x25,0x84,0x1d,0x4d,0x2f,0x57,0xe,0xc7,0xba,0x1c,0xb8,0x6e,0xb4,0xe2,0x95,0x6a, 0xb4,0x54,0x57,0x4c,0x2b,0x73,0xae,0x59,0xa6,0x18,0x9d,0xa0,0x1d,0xd5,0x92,0x55, 0x88,0xa6,0xa8,0x1f,0xa8,0x96,0x16,0x55,0x4c,0xb1,0x5a,0xb6,0x21,0x7c,0xee,0x77, 0x48,0xd4,0xb9,0xbc,0x5e,0x14,0xb5,0xa,0xb2,0xba,0x59,0xdc,0x52,0x5c,0x28,0xef, 0x29,0xd6,0x6e,0xb0,0x31,0x87,0x85,0xa6,0x22,0x82,0x4c,0x61,0x90,0xa9,0x6c,0x51, 0xc3,0x9b,0x3a,0xa3,0x1c,0xac,0xe6,0xe8,0xb7,0x22,0x4e,0x76,0x74,0xae,0x62,0xfc, 0x57,0x88,0xc3,0x4d,0x78,0x8d,0x17,0xee,0x2f,0x2f,0xda,0x2f,0xfe,0x8d,0xfe,0x20, 0x37,0xcf,0x71,0xe0,0x3f,0xd1,0xb,0xe7,0xf4,0xe6,0x34,0xed,0x77,0x4b,0xba,0x91, 0xcc,0x55,0x26,0x9,0x41,0xc,0x9b,0xc,0x5a,0xdb,0x5f,0x5c,0xf4,0x60,0xb3,0x81, 0xe4,0x2b,0x69,0x28,0x64,0xc4,0xf7,0x18,0xfc,0xa6,0xba,0x19,0x71,0x67,0x17,0xc4, 0xed,0x3a,0x88,0xa1,0x1b,0x69,0xd9,0x1e,0x60,0xc6,0x68,0xee,0xfa,0xf8,0x1,0x91, 0xaf,0xfd,0xd9,0x10,0x3d,0x52,0xd4,0xfc,0xb,0x8e,0x74,0xec,0x6b,0xa0,0x92,0x65, 0xed,0xcc,0x6a,0x21,0xa,0x29,0x32,0xc2,0xdc,0x2c,0x16,0xbb,0xbd,0x5b,0x94,0xc2, 0x62,0x3d,0x80,0xfc,0x36,0xfc,0x8f,0x4d,0x36,0xf4,0x37,0x7a,0x84,0x42,0xb8,0xe5, 0x5f,0x3,0xf0,0xb,0xd5,0x2,0xf9,0xb6,0x20,0xec,0xd0,0x6f,0x76,0x62,0xdf,0x40, 0x44,0x84,0x26,0xa6,0xe7,0x91,0xc1,0xc8,0x19,0xb,0x74,0xbb,0x4b,0x38,0xa8,0x59, 0x3f,0x60,0x6,0x44,0xc3,0x12,0x2,0x8d,0xf9,0x12,0xa2,0x22,0x5e,0xb8,0xc5,0xb5, 0x15,0xaf,0xbc,0x65,0x82,0xbc,0x4,0xd9,0x68,0xe,0x3f,0xb9,0x5d,0x48,0xc5,0x8, 0xc,0x58,0x5a,0x3a,0x2a,0x56,0xde,0x9d,0xa,0x50,0xf8,0x89,0x86,0x54,0x83,0xc2, 0x88,0x39,0x91,0x72,0x2c,0xbe,0x6b,0xd8,0x7b,0x65,0x7c,0xcc,0x7d,0xe4,0x2d,0x48, 0x4,0xb2,0xad,0x3c,0xe2,0x17,0x29,0xca,0xb7,0x64,0x12,0x16,0x98,0xd9,0xdb,0x6b, 0x1f,0xe6,0x1a,0xd7,0x56,0x86,0x34,0xf5,0x5b,0x37,0xb2,0x91,0x8c,0xe4,0xab,0xd4, 0x10,0x46,0xb8,0xa8,0x82,0xd8,0x25,0x37,0x74,0xd1,0xb1,0xa7,0xe1,0x90,0xed,0x24, 0xde,0x6f,0x6e,0x41,0xbc,0x94,0x76,0xc8,0xb,0xb8,0x58,0x87,0x5d,0xa8,0xda,0xcb, 0x93,0x1e,0x9b,0x76,0x19,0xa5,0x49,0x37,0xed,0x95,0x94,0xa8,0x24,0x65,0xc3,0x2d, 0x9c,0x2c,0x65,0x35,0xaf,0xe1,0x54,0xbb,0x81,0x93,0xa7,0x7b,0xf2,0xde,0xf4,0xf5, 0x4c,0x39,0xd4,0x5a,0xdb,0x4b,0x68,0xec,0x70,0x47,0xb1,0x31,0x63,0x37,0xe2,0xea, 0x20,0xd8,0xd7,0x8a,0xac,0xc5,0x84,0x35,0xdd,0x14,0x2a,0x4,0x68,0x0,0x93,0xf9, 0x66,0x1a,0x23,0x0,0xe9,0x82,0x73,0x31,0xe9,0x72,0x47,0x33,0xf1,0xa9,0x8f,0xa9, 0x4c,0x7d,0xde,0x8d,0x79,0x6,0x49,0x67,0xc0,0xc,0x44,0x54,0xd1,0xab,0xa7,0x9, 0xd2,0x9d,0x17,0x83,0x9,0xb1,0x3c,0x3f,0xcf,0x5c,0x12,0x7f,0x48,0x2a,0xd7,0xd8, 0xe2,0x84,0x23,0x70,0x8c,0xa9,0xdf,0x23,0xeb,0x8d,0x8c,0x74,0x5b,0x73,0x51,0xba, 0xa9,0x33,0xfa,0x6b,0x19,0x96,0x28,0x6b,0xa9,0x5c,0x4e,0x23,0x57,0x6d,0x50,0xd7, 0x70,0x8e,0xa3,0xc0,0x8d,0x84,0xcb,0x16,0x33,0xa7,0xd2,0xc4,0xa9,0x17,0xae,0xb5, 0x94,0x85,0x8b,0x7e,0x7b,0x88,0x3d,0xcf,0x45,0x54,0xef,0xc0,0xf9,0x7f,0xe4,0x34, 0xa6,0xe0,0x74,0x2c,0x5b,0x38,0xc9,0x12,0xe6,0x92,0x2c,0x53,0xc7,0xcc,0x42,0x30, 0xf,0x66,0x84,0xe7,0x78,0xbf,0xbb,0x28,0x7d,0xf,0x9d,0x62,0xc4,0xb,0xa8,0xe9, 0x25,0x8,0x8b,0xf7,0xe2,0x97,0x20,0x90,0xc1,0xf8,0xf9,0x2d,0x8d,0x64,0x13,0xa7, 0xdf,0x1b,0x55,0x6d,0x6b,0x65,0x8c,0xd6,0xff,0xfc,0xf,0xc,0xe5,0x4e,0x25, }; static const unsigned char qt_resource_name[] = { // qdarkstyle 0x0,0xa, 0x9,0x24,0x4d,0x25, 0x0,0x71, 0x0,0x64,0x0,0x61,0x0,0x72,0x0,0x6b,0x0,0x73,0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65, // editor 0x0,0x6, 0x6,0xbb,0xb,0x62, 0x0,0x65, 0x0,0x64,0x0,0x69,0x0,0x74,0x0,0x6f,0x0,0x72, // qss_icons 0x0,0x9, 0x9,0x5f,0x97,0x13, 0x0,0x71, 0x0,0x73,0x0,0x73,0x0,0x5f,0x0,0x69,0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x73, // rc 0x0,0x2, 0x0,0x0,0x7,0x83, 0x0,0x72, 0x0,0x63, // Vsepartoolbar.png 0x0,0x11, 0x8,0xc4,0x6a,0xa7, 0x0,0x56, 0x0,0x73,0x0,0x65,0x0,0x70,0x0,0x61,0x0,0x72,0x0,0x74,0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // up_arrow_disabled.png 0x0,0x15, 0xf,0xf3,0xc0,0x7, 0x0,0x75, 0x0,0x70,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x5f,0x0,0x64,0x0,0x69,0x0,0x73,0x0,0x61,0x0,0x62,0x0,0x6c,0x0,0x65,0x0,0x64, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // close.png 0x0,0x9, 0x6,0x98,0x83,0x27, 0x0,0x63, 0x0,0x6c,0x0,0x6f,0x0,0x73,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // down_arrow.png 0x0,0xe, 0x4,0xa2,0xfc,0xa7, 0x0,0x64, 0x0,0x6f,0x0,0x77,0x0,0x6e,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // transparent.png 0x0,0xf, 0xc,0xe2,0x68,0x67, 0x0,0x74, 0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x73,0x0,0x70,0x0,0x61,0x0,0x72,0x0,0x65,0x0,0x6e,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // branch_closed-on.png 0x0,0x14, 0x6,0x5e,0x2c,0x7, 0x0,0x62, 0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68,0x0,0x5f,0x0,0x63,0x0,0x6c,0x0,0x6f,0x0,0x73,0x0,0x65,0x0,0x64,0x0,0x2d,0x0,0x6f,0x0,0x6e,0x0,0x2e, 0x0,0x70,0x0,0x6e,0x0,0x67, // Hsepartoolbar.png 0x0,0x11, 0x8,0x8c,0x6a,0xa7, 0x0,0x48, 0x0,0x73,0x0,0x65,0x0,0x70,0x0,0x61,0x0,0x72,0x0,0x74,0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // branch_open-on.png 0x0,0x12, 0x7,0x8f,0x9d,0x27, 0x0,0x62, 0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68,0x0,0x5f,0x0,0x6f,0x0,0x70,0x0,0x65,0x0,0x6e,0x0,0x2d,0x0,0x6f,0x0,0x6e,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // right_arrow_disabled.png 0x0,0x18, 0x3,0x8e,0xde,0x67, 0x0,0x72, 0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x5f,0x0,0x64,0x0,0x69,0x0,0x73,0x0,0x61,0x0,0x62, 0x0,0x6c,0x0,0x65,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // undock.png 0x0,0xa, 0x5,0x95,0xde,0x27, 0x0,0x75, 0x0,0x6e,0x0,0x64,0x0,0x6f,0x0,0x63,0x0,0x6b,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Hmovetoolbar.png 0x0,0x10, 0x1,0x0,0xca,0xa7, 0x0,0x48, 0x0,0x6d,0x0,0x6f,0x0,0x76,0x0,0x65,0x0,0x74,0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // up_arrow.png 0x0,0xc, 0x6,0xe6,0xe6,0x67, 0x0,0x75, 0x0,0x70,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // branch_open.png 0x0,0xf, 0x6,0x53,0x25,0xa7, 0x0,0x62, 0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68,0x0,0x5f,0x0,0x6f,0x0,0x70,0x0,0x65,0x0,0x6e,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // left_arrow_disabled.png 0x0,0x17, 0xc,0x65,0xce,0x7, 0x0,0x6c, 0x0,0x65,0x0,0x66,0x0,0x74,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x5f,0x0,0x64,0x0,0x69,0x0,0x73,0x0,0x61,0x0,0x62,0x0,0x6c, 0x0,0x65,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // stylesheet-vline.png 0x0,0x14, 0xb,0xc5,0xd7,0xc7, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x73,0x0,0x68,0x0,0x65,0x0,0x65,0x0,0x74,0x0,0x2d,0x0,0x76,0x0,0x6c,0x0,0x69,0x0,0x6e,0x0,0x65,0x0,0x2e, 0x0,0x70,0x0,0x6e,0x0,0x67, // branch_closed.png 0x0,0x11, 0xb,0xda,0x30,0xa7, 0x0,0x62, 0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68,0x0,0x5f,0x0,0x63,0x0,0x6c,0x0,0x6f,0x0,0x73,0x0,0x65,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // left_arrow.png 0x0,0xe, 0xe,0xde,0xfa,0xc7, 0x0,0x6c, 0x0,0x65,0x0,0x66,0x0,0x74,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // right_arrow.png 0x0,0xf, 0x2,0x9f,0x5,0x87, 0x0,0x72, 0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // checkbox.png 0x0,0xc, 0x4,0x56,0x23,0x67, 0x0,0x63, 0x0,0x68,0x0,0x65,0x0,0x63,0x0,0x6b,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // stylesheet-branch-end.png 0x0,0x19, 0x8,0x3e,0xcc,0x7, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x73,0x0,0x68,0x0,0x65,0x0,0x65,0x0,0x74,0x0,0x2d,0x0,0x62,0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68, 0x0,0x2d,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // stylesheet-branch-more.png 0x0,0x1a, 0x1,0x21,0xeb,0x47, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x73,0x0,0x68,0x0,0x65,0x0,0x65,0x0,0x74,0x0,0x2d,0x0,0x62,0x0,0x72,0x0,0x61,0x0,0x6e,0x0,0x63,0x0,0x68, 0x0,0x2d,0x0,0x6d,0x0,0x6f,0x0,0x72,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Vmovetoolbar.png 0x0,0x10, 0x1,0x7,0x4a,0xa7, 0x0,0x56, 0x0,0x6d,0x0,0x6f,0x0,0x76,0x0,0x65,0x0,0x74,0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // down_arrow_disabled.png 0x0,0x17, 0xc,0xab,0x51,0x7, 0x0,0x64, 0x0,0x6f,0x0,0x77,0x0,0x6e,0x0,0x5f,0x0,0x61,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x5f,0x0,0x64,0x0,0x69,0x0,0x73,0x0,0x61,0x0,0x62,0x0,0x6c, 0x0,0x65,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // sizegrip.png 0x0,0xc, 0x6,0x41,0x40,0x87, 0x0,0x73, 0x0,0x69,0x0,0x7a,0x0,0x65,0x0,0x67,0x0,0x72,0x0,0x69,0x0,0x70,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // icons 0x0,0x5, 0x0,0x6f,0xa6,0x53, 0x0,0x69, 0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x73, // style_dark 0x0,0xa, 0x2,0xba,0xf0,0x8b, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x5f,0x0,0x64,0x0,0x61,0x0,0x72,0x0,0x6b, // scrollbar.png 0x0,0xd, 0xb,0xd7,0x90,0xe7, 0x0,0x73, 0x0,0x63,0x0,0x72,0x0,0x6f,0x0,0x6c,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // border3.png 0x0,0xb, 0xc,0x88,0x86,0x7, 0x0,0x62, 0x0,0x6f,0x0,0x72,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x33,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // style_debug.css 0x0,0xf, 0x9,0xf1,0x14,0xc3, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x5f,0x0,0x64,0x0,0x65,0x0,0x62,0x0,0x75,0x0,0x67,0x0,0x2e,0x0,0x63,0x0,0x73,0x0,0x73, // border2.png 0x0,0xb, 0xc,0x87,0x86,0x7, 0x0,0x62, 0x0,0x6f,0x0,0x72,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x32,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // border.png 0x0,0xa, 0xa,0xc8,0x7a,0x47, 0x0,0x62, 0x0,0x6f,0x0,0x72,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // style.css 0x0,0x9, 0x0,0x28,0xbf,0x23, 0x0,0x73, 0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x2e,0x0,0x63,0x0,0x73,0x0,0x73, // Toolbox_CreateSubtractiveBrush.png 0x0,0x22, 0x8,0xf5,0xd9,0x47, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x43,0x0,0x72,0x0,0x65,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x53,0x0,0x75,0x0,0x62, 0x0,0x74,0x0,0x72,0x0,0x61,0x0,0x63,0x0,0x74,0x0,0x69,0x0,0x76,0x0,0x65,0x0,0x42,0x0,0x72,0x0,0x75,0x0,0x73,0x0,0x68,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // Viewport_View_Front.png 0x0,0x17, 0x6,0x8f,0x58,0x67, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x5f,0x0,0x46,0x0,0x72,0x0,0x6f, 0x0,0x6e,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_Rotate.png 0x0,0x12, 0xe,0xf8,0xf0,0x7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x52,0x0,0x6f,0x0,0x74,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // DoubleLeftArrowHS.png 0x0,0x15, 0xe,0x8f,0xb4,0x27, 0x0,0x44, 0x0,0x6f,0x0,0x75,0x0,0x62,0x0,0x6c,0x0,0x65,0x0,0x4c,0x0,0x65,0x0,0x66,0x0,0x74,0x0,0x41,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x48,0x0,0x53, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AlignObjectsCenteredVerticalHS.png 0x0,0x22, 0x4,0xb8,0xd4,0xc7, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x43,0x0,0x65,0x0,0x6e,0x0,0x74,0x0,0x65, 0x0,0x72,0x0,0x65,0x0,0x64,0x0,0x56,0x0,0x65,0x0,0x72,0x0,0x74,0x0,0x69,0x0,0x63,0x0,0x61,0x0,0x6c,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // AlignObjectsLeftHS.png 0x0,0x16, 0x5,0x78,0x55,0xe7, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x4c,0x0,0x65,0x0,0x66,0x0,0x74,0x0,0x48, 0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_Scale.png 0x0,0x11, 0x8,0x45,0x5c,0xc7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x53,0x0,0x63,0x0,0x61,0x0,0x6c,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_View_Top.png 0x0,0x15, 0x1,0x63,0x8f,0xa7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x5f,0x0,0x54,0x0,0x6f,0x0,0x70, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderMode_Wireframe.png 0x0,0x21, 0x7,0x10,0xde,0xa7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x4d,0x0,0x6f, 0x0,0x64,0x0,0x65,0x0,0x5f,0x0,0x57,0x0,0x69,0x0,0x72,0x0,0x65,0x0,0x66,0x0,0x72,0x0,0x61,0x0,0x6d,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_CreateVolumeBrush.png 0x0,0x1d, 0xb,0x51,0x60,0x27, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x43,0x0,0x72,0x0,0x65,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x56,0x0,0x6f,0x0,0x6c, 0x0,0x75,0x0,0x6d,0x0,0x65,0x0,0x42,0x0,0x72,0x0,0x75,0x0,0x73,0x0,0x68,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Edit_UndoHS.png 0x0,0xf, 0x2,0x9e,0xf0,0xe7, 0x0,0x45, 0x0,0x64,0x0,0x69,0x0,0x74,0x0,0x5f,0x0,0x55,0x0,0x6e,0x0,0x64,0x0,0x6f,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderMode_Lit.png 0x0,0x1b, 0x8,0x93,0xae,0xa7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x4d,0x0,0x6f, 0x0,0x64,0x0,0x65,0x0,0x5f,0x0,0x4c,0x0,0x69,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // openHS.png 0x0,0xa, 0x2,0xdc,0x9a,0xc7, 0x0,0x6f, 0x0,0x70,0x0,0x65,0x0,0x6e,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // PlayHS.png 0x0,0xa, 0xd,0xe0,0xb2,0x47, 0x0,0x50, 0x0,0x6c,0x0,0x61,0x0,0x79,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_OtherOptions.png 0x0,0x19, 0x0,0xd0,0x36,0x7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x4f,0x0,0x74,0x0,0x68,0x0,0x65,0x0,0x72,0x0,0x4f,0x0,0x70,0x0,0x74, 0x0,0x69,0x0,0x6f,0x0,0x6e,0x0,0x73,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // skip_backward.png 0x0,0x11, 0x2,0x60,0x93,0x67, 0x0,0x73, 0x0,0x6b,0x0,0x69,0x0,0x70,0x0,0x5f,0x0,0x62,0x0,0x61,0x0,0x63,0x0,0x6b,0x0,0x77,0x0,0x61,0x0,0x72,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Directory_16x16.png 0x0,0x13, 0xa,0x55,0xf6,0x67, 0x0,0x44, 0x0,0x69,0x0,0x72,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x6f,0x0,0x72,0x0,0x79,0x0,0x5f,0x0,0x31,0x0,0x36,0x0,0x78,0x0,0x31,0x0,0x36,0x0,0x2e,0x0,0x70, 0x0,0x6e,0x0,0x67, // Viewport_View_Isometric.png 0x0,0x1b, 0xd,0xbb,0x9e,0xc7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x5f,0x0,0x49,0x0,0x73,0x0,0x6f, 0x0,0x6d,0x0,0x65,0x0,0x74,0x0,0x72,0x0,0x69,0x0,0x63,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AlignObjectsBottomHS.png 0x0,0x18, 0xc,0xae,0x3a,0xa7, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x42,0x0,0x6f,0x0,0x74,0x0,0x74,0x0,0x6f, 0x0,0x6d,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderFlag_Shadows.png 0x0,0x1f, 0x3,0x88,0xee,0x87, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x46,0x0,0x6c, 0x0,0x61,0x0,0x67,0x0,0x5f,0x0,0x53,0x0,0x68,0x0,0x61,0x0,0x64,0x0,0x6f,0x0,0x77,0x0,0x73,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AlignObjectsRightHS.png 0x0,0x17, 0x0,0xe2,0xfd,0x7, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x52,0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74, 0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // PauseHS.png 0x0,0xb, 0x9,0x7b,0x4e,0x67, 0x0,0x50, 0x0,0x61,0x0,0x75,0x0,0x73,0x0,0x65,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderMode_Unlit.png 0x0,0x1d, 0x7,0xfe,0x30,0xc7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x4d,0x0,0x6f, 0x0,0x64,0x0,0x65,0x0,0x5f,0x0,0x55,0x0,0x6e,0x0,0x6c,0x0,0x69,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // play.png 0x0,0x8, 0x2,0x8c,0x59,0xa7, 0x0,0x70, 0x0,0x6c,0x0,0x61,0x0,0x79,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_ShapeSphere.png 0x0,0x17, 0xb,0x23,0xc,0x67, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x53,0x0,0x68,0x0,0x61,0x0,0x70,0x0,0x65,0x0,0x53,0x0,0x70,0x0,0x68,0x0,0x65, 0x0,0x72,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // MultiplePagesHH.png 0x0,0x13, 0x1,0x89,0x6f,0xa7, 0x0,0x4d, 0x0,0x75,0x0,0x6c,0x0,0x74,0x0,0x69,0x0,0x70,0x0,0x6c,0x0,0x65,0x0,0x50,0x0,0x61,0x0,0x67,0x0,0x65,0x0,0x73,0x0,0x48,0x0,0x48,0x0,0x2e,0x0,0x70, 0x0,0x6e,0x0,0x67, // Toolbox_CreateAdditiveBrush.png 0x0,0x1f, 0x7,0x6a,0x9,0xc7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x43,0x0,0x72,0x0,0x65,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x41,0x0,0x64,0x0,0x64, 0x0,0x69,0x0,0x74,0x0,0x69,0x0,0x76,0x0,0x65,0x0,0x42,0x0,0x72,0x0,0x75,0x0,0x73,0x0,0x68,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_Select.png 0x0,0x12, 0xd,0xf7,0x95,0x7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x53,0x0,0x65,0x0,0x6c,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // FullScreenHH.png 0x0,0x10, 0x1,0xed,0x30,0x87, 0x0,0x46, 0x0,0x75,0x0,0x6c,0x0,0x6c,0x0,0x53,0x0,0x63,0x0,0x72,0x0,0x65,0x0,0x65,0x0,0x6e,0x0,0x48,0x0,0x48,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_Move.png 0x0,0x10, 0x3,0xc2,0x35,0x47, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x4d,0x0,0x6f,0x0,0x76,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Resource_16x16.png 0x0,0x12, 0xc,0x4d,0x85,0xe7, 0x0,0x52, 0x0,0x65,0x0,0x73,0x0,0x6f,0x0,0x75,0x0,0x72,0x0,0x63,0x0,0x65,0x0,0x5f,0x0,0x31,0x0,0x36,0x0,0x78,0x0,0x31,0x0,0x36,0x0,0x2e,0x0,0x70,0x0,0x6e, 0x0,0x67, // saveHS.png 0x0,0xa, 0x9,0xdd,0x66,0xc7, 0x0,0x73, 0x0,0x61,0x0,0x76,0x0,0x65,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // RefreshDocViewHS.png 0x0,0x14, 0x2,0x8,0xc3,0xa7, 0x0,0x52, 0x0,0x65,0x0,0x66,0x0,0x72,0x0,0x65,0x0,0x73,0x0,0x68,0x0,0x44,0x0,0x6f,0x0,0x63,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x48,0x0,0x53,0x0,0x2e, 0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderMode_LightingOnly.png 0x0,0x24, 0x5,0x5e,0x84,0x47, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x4d,0x0,0x6f, 0x0,0x64,0x0,0x65,0x0,0x5f,0x0,0x4c,0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74,0x0,0x69,0x0,0x6e,0x0,0x67,0x0,0x4f,0x0,0x6e,0x0,0x6c,0x0,0x79,0x0,0x2e, 0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_ShapeCube.png 0x0,0x15, 0x0,0xf3,0xf6,0x7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x53,0x0,0x68,0x0,0x61,0x0,0x70,0x0,0x65,0x0,0x43,0x0,0x75,0x0,0x62,0x0,0x65, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_View_Perspective.png 0x0,0x1d, 0x2,0x3c,0xd1,0x7, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x5f,0x0,0x50,0x0,0x65,0x0,0x72, 0x0,0x73,0x0,0x70,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x69,0x0,0x76,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_ShapeCone.png 0x0,0x15, 0x1,0x33,0xf6,0x27, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x53,0x0,0x68,0x0,0x61,0x0,0x70,0x0,0x65,0x0,0x43,0x0,0x6f,0x0,0x6e,0x0,0x65, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // pause.png 0x0,0x9, 0xc,0x98,0xba,0x47, 0x0,0x70, 0x0,0x61,0x0,0x75,0x0,0x73,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // DeleteHS.png 0x0,0xc, 0x0,0x8e,0xe,0x7, 0x0,0x44, 0x0,0x65,0x0,0x6c,0x0,0x65,0x0,0x74,0x0,0x65,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // skip_forward.png 0x0,0x10, 0x4,0x23,0xc,0xe7, 0x0,0x73, 0x0,0x6b,0x0,0x69,0x0,0x70,0x0,0x5f,0x0,0x66,0x0,0x6f,0x0,0x72,0x0,0x77,0x0,0x61,0x0,0x72,0x0,0x64,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // EditCodeHS.png 0x0,0xe, 0xf,0xc7,0xe,0xe7, 0x0,0x45, 0x0,0x64,0x0,0x69,0x0,0x74,0x0,0x43,0x0,0x6f,0x0,0x64,0x0,0x65,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // BreakpointHS.png 0x0,0x10, 0x8,0x8a,0xb5,0x7, 0x0,0x42, 0x0,0x72,0x0,0x65,0x0,0x61,0x0,0x6b,0x0,0x70,0x0,0x6f,0x0,0x69,0x0,0x6e,0x0,0x74,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_CreateEntity.png 0x0,0x18, 0x6,0xd7,0x6a,0x27, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x43,0x0,0x72,0x0,0x65,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x45,0x0,0x6e,0x0,0x74, 0x0,0x69,0x0,0x74,0x0,0x79,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_LocalCoordSystem.png 0x0,0x1c, 0x5,0xe6,0x99,0x7, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x4c,0x0,0x6f,0x0,0x63,0x0,0x61,0x0,0x6c,0x0,0x43,0x0,0x6f,0x0,0x6f,0x0,0x72, 0x0,0x64,0x0,0x53,0x0,0x79,0x0,0x73,0x0,0x74,0x0,0x65,0x0,0x6d,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // camera.png 0x0,0xa, 0xc,0x91,0x67,0x27, 0x0,0x63, 0x0,0x61,0x0,0x6d,0x0,0x65,0x0,0x72,0x0,0x61,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Back_16x16.png 0x0,0xe, 0x4,0xb,0xc,0xe7, 0x0,0x42, 0x0,0x61,0x0,0x63,0x0,0x6b,0x0,0x5f,0x0,0x31,0x0,0x36,0x0,0x78,0x0,0x31,0x0,0x36,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbar_WorldCoordSystem.png 0x0,0x1c, 0xa,0x0,0x5e,0x87, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x61,0x0,0x72,0x0,0x5f,0x0,0x57,0x0,0x6f,0x0,0x72,0x0,0x6c,0x0,0x64,0x0,0x43,0x0,0x6f,0x0,0x6f,0x0,0x72, 0x0,0x64,0x0,0x53,0x0,0x79,0x0,0x73,0x0,0x74,0x0,0x65,0x0,0x6d,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // NewDirectory_16x16.png 0x0,0x16, 0xa,0x7f,0x91,0xe7, 0x0,0x4e, 0x0,0x65,0x0,0x77,0x0,0x44,0x0,0x69,0x0,0x72,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x6f,0x0,0x72,0x0,0x79,0x0,0x5f,0x0,0x31,0x0,0x36,0x0,0x78,0x0,0x31, 0x0,0x36,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // HighlightHH.png 0x0,0xf, 0x3,0x2f,0x97,0x47, 0x0,0x48, 0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74,0x0,0x48,0x0,0x48,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Toolbox_ShapeCylinder.png 0x0,0x19, 0xb,0x8b,0xe0,0x87, 0x0,0x54, 0x0,0x6f,0x0,0x6f,0x0,0x6c,0x0,0x62,0x0,0x6f,0x0,0x78,0x0,0x5f,0x0,0x53,0x0,0x68,0x0,0x61,0x0,0x70,0x0,0x65,0x0,0x43,0x0,0x79,0x0,0x6c,0x0,0x69, 0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AlignObjectsCenteredHorizontalHS.png 0x0,0x24, 0x5,0xb7,0x83,0x27, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x43,0x0,0x65,0x0,0x6e,0x0,0x74,0x0,0x65, 0x0,0x72,0x0,0x65,0x0,0x64,0x0,0x48,0x0,0x6f,0x0,0x72,0x0,0x69,0x0,0x7a,0x0,0x6f,0x0,0x6e,0x0,0x74,0x0,0x61,0x0,0x6c,0x0,0x48,0x0,0x53,0x0,0x2e, 0x0,0x70,0x0,0x6e,0x0,0x67, // Alerts.png 0x0,0xa, 0x9,0xbf,0x52,0xc7, 0x0,0x41, 0x0,0x6c,0x0,0x65,0x0,0x72,0x0,0x74,0x0,0x73,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // DoubleRightArrowHS.png 0x0,0x16, 0x0,0x4c,0xef,0x27, 0x0,0x44, 0x0,0x6f,0x0,0x75,0x0,0x62,0x0,0x6c,0x0,0x65,0x0,0x52,0x0,0x69,0x0,0x67,0x0,0x68,0x0,0x74,0x0,0x41,0x0,0x72,0x0,0x72,0x0,0x6f,0x0,0x77,0x0,0x48, 0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AnimateHS.png 0x0,0xd, 0x9,0x76,0x27,0x27, 0x0,0x41, 0x0,0x6e,0x0,0x69,0x0,0x6d,0x0,0x61,0x0,0x74,0x0,0x65,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // AlignObjectsTopHS.png 0x0,0x15, 0xc,0xe,0x64,0xc7, 0x0,0x41, 0x0,0x6c,0x0,0x69,0x0,0x67,0x0,0x6e,0x0,0x4f,0x0,0x62,0x0,0x6a,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x73,0x0,0x54,0x0,0x6f,0x0,0x70,0x0,0x48,0x0,0x53, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_View_Side.png 0x0,0x16, 0xf,0xad,0xd9,0x27, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x5f,0x0,0x53,0x0,0x69,0x0,0x64, 0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // UpDirectory_16x16.png 0x0,0x15, 0xa,0x57,0x16,0x67, 0x0,0x55, 0x0,0x70,0x0,0x44,0x0,0x69,0x0,0x72,0x0,0x65,0x0,0x63,0x0,0x74,0x0,0x6f,0x0,0x72,0x0,0x79,0x0,0x5f,0x0,0x31,0x0,0x36,0x0,0x78,0x0,0x31,0x0,0x36, 0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Viewport_RenderFlag_WireframeOverlay.png 0x0,0x28, 0xe,0xbf,0xf5,0x27, 0x0,0x56, 0x0,0x69,0x0,0x65,0x0,0x77,0x0,0x70,0x0,0x6f,0x0,0x72,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x6e,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x46,0x0,0x6c, 0x0,0x61,0x0,0x67,0x0,0x5f,0x0,0x57,0x0,0x69,0x0,0x72,0x0,0x65,0x0,0x66,0x0,0x72,0x0,0x61,0x0,0x6d,0x0,0x65,0x0,0x4f,0x0,0x76,0x0,0x65,0x0,0x72, 0x0,0x6c,0x0,0x61,0x0,0x79,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // NewDocumentHS.png 0x0,0x11, 0x2,0xe1,0x9,0x27, 0x0,0x4e, 0x0,0x65,0x0,0x77,0x0,0x44,0x0,0x6f,0x0,0x63,0x0,0x75,0x0,0x6d,0x0,0x65,0x0,0x6e,0x0,0x74,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // Edit_RedoHS.png 0x0,0xf, 0x2,0x9e,0x6e,0xe7, 0x0,0x45, 0x0,0x64,0x0,0x69,0x0,0x74,0x0,0x5f,0x0,0x52,0x0,0x65,0x0,0x64,0x0,0x6f,0x0,0x48,0x0,0x53,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, // qdarkstylesheet.qss 0x0,0x13, 0x2,0x60,0x82,0x63, 0x0,0x71, 0x0,0x64,0x0,0x61,0x0,0x72,0x0,0x6b,0x0,0x73,0x0,0x74,0x0,0x79,0x0,0x6c,0x0,0x65,0x0,0x73,0x0,0x68,0x0,0x65,0x0,0x65,0x0,0x74,0x0,0x2e,0x0,0x71, 0x0,0x73,0x0,0x73, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x1, // :/editor 0x0,0x0,0x0,0x1a,0x0,0x2,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1e, // :/qdarkstyle 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1d, // :/qss_icons 0x0,0x0,0x0,0x2c,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x4, // :/qss_icons/rc 0x0,0x0,0x0,0x44,0x0,0x2,0x0,0x0,0x0,0x18,0x0,0x0,0x0,0x5, // :/qss_icons/rc/Hmovetoolbar.png 0x0,0x0,0x1,0xd4,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x9,0xba, // :/qss_icons/rc/Vmovetoolbar.png 0x0,0x0,0x3,0x9c,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x12,0x73, // :/qss_icons/rc/stylesheet-branch-more.png 0x0,0x0,0x3,0x62,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x11,0xb9, // :/qss_icons/rc/right_arrow.png 0x0,0x0,0x2,0xe8,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xe,0xd6, // :/qss_icons/rc/right_arrow_disabled.png 0x0,0x0,0x1,0x84,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x7,0x4a, // :/qss_icons/rc/checkbox.png 0x0,0x0,0x3,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xf,0x7a, // :/qss_icons/rc/down_arrow.png 0x0,0x0,0x0,0xbe,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x3,0xd7, // :/qss_icons/rc/undock.png 0x0,0x0,0x1,0xba,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x7,0xee, // :/qss_icons/rc/sizegrip.png 0x0,0x0,0x3,0xf6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x14,0x5, // :/qss_icons/rc/branch_open.png 0x0,0x0,0x2,0x18,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb,0x41, // :/qss_icons/rc/branch_closed-on.png 0x0,0x0,0x1,0x4,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5,0x47, // :/qss_icons/rc/close.png 0x0,0x0,0x0,0xa6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x1,0x62, // :/qss_icons/rc/up_arrow.png 0x0,0x0,0x1,0xfa,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xa,0x9f, // :/qss_icons/rc/branch_open-on.png 0x0,0x0,0x1,0x5a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x6,0xb0, // :/qss_icons/rc/stylesheet-branch-end.png 0x0,0x0,0x3,0x2a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x10,0xd5, // :/qss_icons/rc/Hsepartoolbar.png 0x0,0x0,0x1,0x32,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5,0xde, // :/qss_icons/rc/Vsepartoolbar.png 0x0,0x0,0x0,0x4e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, // :/qss_icons/rc/stylesheet-vline.png 0x0,0x0,0x2,0x70,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xc,0x95, // :/qss_icons/rc/branch_closed.png 0x0,0x0,0x2,0x9e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xd,0x88, // :/qss_icons/rc/left_arrow_disabled.png 0x0,0x0,0x2,0x3c,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb,0xeb, // :/qss_icons/rc/down_arrow_disabled.png 0x0,0x0,0x3,0xc2,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x13,0x5b, // :/qss_icons/rc/transparent.png 0x0,0x0,0x0,0xe0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x4,0x80, // :/qss_icons/rc/left_arrow.png 0x0,0x0,0x2,0xc6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xe,0x2c, // :/qss_icons/rc/up_arrow_disabled.png 0x0,0x0,0x0,0x76,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0xbf, // :/qdarkstyle/qdarkstylesheet.qss 0x0,0x0,0x10,0x24,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0xd6,0xf8, // :/editor/icons 0x0,0x0,0x4,0x14,0x0,0x2,0x0,0x0,0x0,0x3c,0x0,0x0,0x0,0x26, // :/editor/style_dark 0x0,0x0,0x4,0x24,0x0,0x2,0x0,0x0,0x0,0x6,0x0,0x0,0x0,0x20, // :/editor/style_dark/style.css 0x0,0x0,0x4,0xd4,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x1d,0xfc, // :/editor/style_dark/style_debug.css 0x0,0x0,0x4,0x7a,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x16,0xda, // :/editor/style_dark/border.png 0x0,0x0,0x4,0xba,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x1c,0x87, // :/editor/style_dark/scrollbar.png 0x0,0x0,0x4,0x3e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x14,0x8a, // :/editor/style_dark/border2.png 0x0,0x0,0x4,0x9e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x1b,0x74, // :/editor/style_dark/border3.png 0x0,0x0,0x4,0x5e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x15,0x78, // :/editor/icons/DoubleRightArrowHS.png 0x0,0x0,0xe,0x9e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xc5,0x70, // :/editor/icons/DeleteHS.png 0x0,0x0,0xc,0x2e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x9a,0xeb, // :/editor/icons/Viewport_OtherOptions.png 0x0,0x0,0x7,0xb4,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x4b,0x73, // :/editor/icons/AlignObjectsRightHS.png 0x0,0x0,0x8,0xf6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5f,0xd3, // :/editor/icons/Toolbox_ShapeCube.png 0x0,0x0,0xb,0x76,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x8c,0x1f, // :/editor/icons/Toolbox_ShapeCone.png 0x0,0x0,0xb,0xe6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x94,0xe8, // :/editor/icons/Viewport_View_Top.png 0x0,0x0,0x6,0x68,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x37,0x9c, // :/editor/icons/MultiplePagesHH.png 0x0,0x0,0x9,0xd0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x6d,0x58, // :/editor/icons/FullScreenHH.png 0x0,0x0,0xa,0x6a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x7b,0x4c, // :/editor/icons/RefreshDocViewHS.png 0x0,0x0,0xa,0xfa,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x88,0x8b, // :/editor/icons/Viewport_View_Perspective.png 0x0,0x0,0xb,0xa6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x93,0x91, // :/editor/icons/skip_backward.png 0x0,0x0,0x7,0xec,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x4c,0xba, // :/editor/icons/play.png 0x0,0x0,0x9,0x86,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x64,0xe6, // :/editor/icons/Edit_RedoHS.png 0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xd4,0x5c, // :/editor/icons/Edit_UndoHS.png 0x0,0x0,0x7,0x20,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x42,0x2c, // :/editor/icons/openHS.png 0x0,0x0,0x7,0x80,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x46,0x5b, // :/editor/icons/NewDocumentHS.png 0x0,0x0,0xf,0xd8,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xd1,0xbc, // :/editor/icons/HighlightHH.png 0x0,0x0,0xd,0xda,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb7,0x5d, // :/editor/icons/Viewport_RenderFlag_Shadows.png 0x0,0x0,0x8,0xb2,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5e,0x68, // :/editor/icons/Toolbar_Move.png 0x0,0x0,0xa,0x90,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x7f,0xdb, // :/editor/icons/Back_16x16.png 0x0,0x0,0xd,0x48,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb0,0x2f, // :/editor/icons/skip_forward.png 0x0,0x0,0xc,0x4c,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x9d,0xe2, // :/editor/icons/AlignObjectsCenteredVerticalHS.png 0x0,0x0,0x5,0xc4,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x31,0x8a, // :/editor/icons/Viewport_RenderMode_LightingOnly.png 0x0,0x0,0xb,0x28,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x8a,0xad, // :/editor/icons/AlignObjectsLeftHS.png 0x0,0x0,0x6,0xe,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x33,0x2d, // :/editor/icons/AlignObjectsCenteredHorizontalHS.png 0x0,0x0,0xe,0x36,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xc1,0x8e, // :/editor/icons/Toolbar_LocalCoordSystem.png 0x0,0x0,0xc,0xf0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xab,0x93, // :/editor/icons/Viewport_View_Front.png 0x0,0x0,0x5,0x36,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x29,0xb3, // :/editor/icons/Toolbox_CreateEntity.png 0x0,0x0,0xc,0xba,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xa5,0xcc, // :/editor/icons/Viewport_RenderMode_Wireframe.png 0x0,0x0,0x6,0x98,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x38,0xcf, // :/editor/icons/Toolbox_CreateAdditiveBrush.png 0x0,0x0,0x9,0xfc,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x71,0xc, // :/editor/icons/Viewport_RenderMode_Unlit.png 0x0,0x0,0x9,0x46,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x63,0x79, // :/editor/icons/Toolbar_Scale.png 0x0,0x0,0x6,0x40,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x35,0x39, // :/editor/icons/BreakpointHS.png 0x0,0x0,0xc,0x94,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xa2,0x95, // :/editor/icons/Viewport_RenderMode_Lit.png 0x0,0x0,0x7,0x44,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x44,0xdd, // :/editor/icons/Toolbox_CreateSubtractiveBrush.png 0x0,0x0,0x4,0xec,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x22,0xfc, // :/editor/icons/AnimateHS.png 0x0,0x0,0xe,0xd0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xc7,0x82, // :/editor/icons/PauseHS.png 0x0,0x0,0x9,0x2a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x61,0xe0, // :/editor/icons/Alerts.png 0x0,0x0,0xe,0x84,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xc3,0x23, // :/editor/icons/saveHS.png 0x0,0x0,0xa,0xe0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x85,0x67, // :/editor/icons/Toolbar_WorldCoordSystem.png 0x0,0x0,0xd,0x6a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb3,0x28, // :/editor/icons/Directory_16x16.png 0x0,0x0,0x8,0x14,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x4e,0x4a, // :/editor/icons/UpDirectory_16x16.png 0x0,0x0,0xf,0x52,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xcd,0xb7, // :/editor/icons/NewDirectory_16x16.png 0x0,0x0,0xd,0xa8,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xb4,0x64, // :/editor/icons/Toolbox_ShapeSphere.png 0x0,0x0,0x9,0x9c,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x65,0xf0, // :/editor/icons/Toolbox_CreateVolumeBrush.png 0x0,0x0,0x6,0xe0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x3a,0x22, // :/editor/icons/Toolbox_ShapeCylinder.png 0x0,0x0,0xd,0xfe,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xbc,0x20, // :/editor/icons/AlignObjectsTopHS.png 0x0,0x0,0xe,0xf0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xca,0x57, // :/editor/icons/Resource_16x16.png 0x0,0x0,0xa,0xb6,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x82,0x91, // :/editor/icons/camera.png 0x0,0x0,0xd,0x2e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xac,0xc5, // :/editor/icons/pause.png 0x0,0x0,0xc,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x9a,0x2, // :/editor/icons/AlignObjectsBottomHS.png 0x0,0x0,0x8,0x7c,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5c,0x54, // :/editor/icons/Viewport_View_Isometric.png 0x0,0x0,0x8,0x40,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x5b,0x1d, // :/editor/icons/PlayHS.png 0x0,0x0,0x7,0x9a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x49,0xe5, // :/editor/icons/Toolbar_Select.png 0x0,0x0,0xa,0x40,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x79,0x3f, // :/editor/icons/DoubleLeftArrowHS.png 0x0,0x0,0x5,0x94,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x2f,0x44, // :/editor/icons/Viewport_RenderFlag_WireframeOverlay.png 0x0,0x0,0xf,0x82,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xd0,0x5c, // :/editor/icons/Toolbar_Rotate.png 0x0,0x0,0x5,0x6a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x2a,0xeb, // :/editor/icons/Viewport_View_Side.png 0x0,0x0,0xf,0x20,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xcc,0x5b, // :/editor/icons/EditCodeHS.png 0x0,0x0,0xc,0x72,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x9f,0x66, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources)() { QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (0x01, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources)() { QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (0x01, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources)(); } } dummy; } <file_sep>/Engine/Source/Engine/World.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/World.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Brush.h" #include "Engine/Entity.h" #include "Engine/ParticleSystemRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" World::World() { m_worldBoundingBox = AABox::Zero; m_worldBoundingSphere = Sphere::Zero; m_pPhysicsWorld = new Physics::PhysicsWorld(); m_pRenderWorld = new RenderWorld(); m_nextEntityID = 1; m_gameTime = 0.0f; } World::~World() { DebugAssert(m_observers.GetSize() == 0); DebugAssert(m_activeEntities.GetSize() == 0); DebugAssert(m_activeAsyncEntities.GetSize() == 0); // clean up emitters while (m_temporaryParticleEffects.GetSize() > 0) { TemporaryParticleEffect &effect = m_temporaryParticleEffects[m_temporaryParticleEffects.GetSize() - 1]; m_pRenderWorld->RemoveRenderable(effect.pRenderProxy); effect.pRenderProxy->Release(); m_temporaryParticleEffects.RemoveBack(); } delete m_pPhysicsWorld; // render world destruction should come from the render thread //RENDERER_QUEUE_BLOCKING_LAMBDA_COMMAND([this]() { m_pRenderWorld->Release(); //}); } void World::QueueRemoveEntity(Entity *pEntity) { if (m_removeQueue.Contains(pEntity)) return; m_removeQueue.Add(pEntity); } void World::AddObserver(const void *identifier, const float3 &location /* = float3::Zero */) { for (ObserverEntry &observer : m_observers) { if (observer.Key == identifier) { observer.Value = location; return; } } m_observers.Add(ObserverEntry(identifier, location)); } void World::UpdateObserver(const void *identifier, const float3 &location) { for (ObserverEntry &observer : m_observers) { if (observer.Key == identifier) { observer.Value = location; return; } } } void World::RemoveObserver(const void *identifier) { for (uint32 i = 0; i < m_observers.GetSize(); i++) { if (m_observers[i].Key == identifier) { m_observers.OrderedRemove(i); return; } } } void World::BeginFrame(float deltaTime) { m_gameTime += deltaTime; } void World::UpdateAsync(float deltaTime) { // update physics world async m_pPhysicsWorld->UpdateAsync(deltaTime); // update active entities async for (uint32 i = 0; i < m_activeAsyncEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeAsyncEntities[i]; updateData.TimeSinceLastUpdate += deltaTime; if (updateData.TimeSinceLastUpdate >= updateData.UpdateInterval) { float timeSinceEntityLastUpdate = updateData.TimeSinceLastUpdate; updateData.TimeSinceLastUpdate = 0.0f; updateData.pEntity->UpdateAsync(timeSinceEntityLastUpdate); } } } void World::Update(float deltaTime) { // update physics world m_pPhysicsWorld->Update(deltaTime); // update active entities for (uint32 i = 0; i < m_activeEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeEntities[i]; updateData.TimeSinceLastUpdate += deltaTime; if (updateData.TimeSinceLastUpdate >= updateData.UpdateInterval) { float timeSinceEntityLastUpdate = updateData.TimeSinceLastUpdate; updateData.TimeSinceLastUpdate = 0.0f; updateData.pEntity->Update(timeSinceEntityLastUpdate); } } // update particle systems UpdateTemporaryParticleEffects(deltaTime); } void World::EndFrame() { // remove anything that has to die while (m_removeQueue.GetSize() > 0) { Entity *pEntity = m_removeQueue[0]; // slow.. fixme at some point m_removeQueue.PopFront(); // invoke remove RemoveEntity(pEntity); } } void World::RegisterEntityForUpdate(Entity *pEntity, float interval) { // check for existing for (uint32 i = 0; i < m_activeEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeEntities[i]; if (updateData.pEntity == pEntity) { updateData.UpdateInterval = interval; return; } } // create new EntityUpdateData updateData; updateData.pEntity = pEntity; updateData.UpdateInterval = interval; updateData.TimeSinceLastUpdate = 0.0f; m_activeEntities.Add(updateData); // re-sort SortActiveEntities(); } void World::RegisterEntityForAsyncUpdate(Entity *pEntity, float interval) { // check for existing for (uint32 i = 0; i < m_activeAsyncEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeAsyncEntities[i]; if (updateData.pEntity == pEntity) { updateData.UpdateInterval = interval; return; } } // create new EntityUpdateData updateData; updateData.pEntity = pEntity; updateData.UpdateInterval = interval; updateData.TimeSinceLastUpdate = 0.0f; m_activeAsyncEntities.Add(updateData); // re-sort SortActiveAsyncEntities(); } void World::UnregisterEntityForUpdate(Entity *pEntity) { for (uint32 i = 0; i < m_activeEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeEntities[i]; if (updateData.pEntity == pEntity) { m_activeEntities.FastRemove(i); SortActiveEntities(); return; } } } void World::UnregisterEntityForAsyncUpdate(Entity *pEntity) { for (uint32 i = 0; i < m_activeAsyncEntities.GetSize(); i++) { EntityUpdateData &updateData = m_activeAsyncEntities[i]; if (updateData.pEntity == pEntity) { m_activeAsyncEntities.FastRemove(i); SortActiveAsyncEntities(); return; } } } void World::SortActiveEntities() { } void World::SortActiveAsyncEntities() { } bool World::RayCast(const Ray &ray, Entity **ppHitEntity, float3 *pContactNormal, float3 *pContactPoint) { const Physics::PhysicsProxy *pHitPhysicsProxy; if (!m_pPhysicsWorld->RayCast(ray, &pHitPhysicsProxy, pContactNormal, pContactPoint)) return false; if (ppHitEntity != nullptr) *ppHitEntity = (pHitPhysicsProxy != nullptr && pHitPhysicsProxy->GetEntityID() != 0) ? GetEntityByID(pHitPhysicsProxy->GetEntityID()) : nullptr; return true; } void World::SpawnParticleEmitter(const ParticleSystem *pParticleSystem, float lifeSpan, const float3 &location, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const float3 &initialVelocity /* = float3::Zero */, float mass /* = 0.0f */) { TemporaryParticleEffect effect; effect.pRenderProxy = new ParticleSystemRenderProxy(pParticleSystem, 0); effect.BaseTransform = Transform(location, rotation, scale); effect.TimeRemaining = lifeSpan; effect.HasVelocity = (initialVelocity.SquaredLength() > Y_FLT_EPSILON); effect.Velocity = initialVelocity; effect.Mass = mass; m_temporaryParticleEffects.Add(effect); m_pRenderWorld->AddRenderable(effect.pRenderProxy); } void World::UpdateTemporaryParticleEffects(float deltaTime) { for (uint32 i = 0; i < m_temporaryParticleEffects.GetSize(); ) { TemporaryParticleEffect &effect = m_temporaryParticleEffects[i]; if (deltaTime >= effect.TimeRemaining) { m_pRenderWorld->RemoveRenderable(effect.pRenderProxy); effect.pRenderProxy->Release(); m_temporaryParticleEffects.OrderedRemove(i); continue; } // handle velocity if (effect.HasVelocity) { // affect position effect.BaseTransform.SetPosition(effect.BaseTransform.GetPosition() + effect.Velocity * deltaTime); // apply gravity if (effect.Mass != 0.0f) effect.Velocity += m_pPhysicsWorld->GetGravity() * (effect.Mass * deltaTime); } effect.TimeRemaining -= deltaTime; effect.pRenderProxy->Update(&effect.BaseTransform, deltaTime); i++; } } <file_sep>/Engine/Source/D3D12Renderer/D3D12CVars.h #pragma once #include "Engine/Common.h" namespace CVars { // D3D11 CVars extern CVar r_d3d12_force_warp; extern CVar r_d3d12_break_on_error; } <file_sep>/Engine/CMakeLists.txt # libraries add_subdirectory(Source/Core) add_subdirectory(Source/MathLib) add_subdirectory(Source/Engine) add_subdirectory(Source/Renderer) add_subdirectory(Source/GameFramework) if(WITH_RENDERER_D3D11) add_subdirectory(Source/D3D11Renderer) endif() if(WITH_RENDERER_OPENGL) add_subdirectory(Source/OpenGLRenderer) endif() if(WITH_RENDERER_OPENGLES2) add_subdirectory(Source/OpenGLES2Renderer) endif() if(WITH_RESOURCECOMPILER) add_subdirectory(Source/ResourceCompiler) add_subdirectory(Source/ResourceCompilerInterface) if(WITH_RESOURCECOMPILER_STANDALONE) add_subdirectory(Source/ResourceCompilerStandalone) endif() endif() if(WITH_MAPCOMPILER) add_subdirectory(Source/MapCompiler) if(WITH_MAPCOMPILER_STANDALONE) add_subdirectory(Source/MapCompilerStandalone) endif() endif() if(WITH_CONTENTCONVERTER) add_subdirectory(Source/ContentConverter) if(WITH_CONTENTCONVERTER_STANDALONE) add_subdirectory(Source/ContentConverterStandalone) endif() endif() if(WITH_BASEGAME) add_subdirectory(Source/BaseGame) endif() if(WITH_BLOCKENGINE) add_subdirectory(Source/BlockEngine) endif() <file_sep>/DemoGame/Source/DemoGame/DemoUtilities.h #pragma once #include "Engine/Common.h" #include "Engine/Entity.h" #include "Engine/Material.h" class DirectionalLightEntity; namespace DemoUtilities { // create a plane shape Entity *CreatePlaneShape(World *pWorld, const float3 &normal, const float3 &origin, float size, const Material *pMaterial, float textureRepeatInterval = 1.0f, uint32 shadowFlags = ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // create sun light DirectionalLightEntity *CreateSunLight(World *pWorld, const float3 &color = float3(1.0f, 1.0f, 1.0f), const float brightness = 1.0f, const float ambientContribution = 0.2f, const float3 &rotation = float3(45.0f, 0.0f, 0.0f)); } // namespace DemoUtilties<file_sep>/Engine/Source/Engine/Entity.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Entity.h" #include "Engine/Component.h" #include "Engine/ComponentTypeInfo.h" #include "Engine/World.h" Log_SetChannel(Entity); DEFINE_ENTITY_TYPEINFO(Entity, SCRIPT_OBJECT_FLAG_TABLED); BEGIN_ENTITY_PROPERTIES(Entity) PROPERTY_TABLE_MEMBER_UINT("Mobility", PROPERTY_FLAG_READ_ONLY, offsetof(Entity, m_mobility), nullptr, nullptr) PROPERTY_TABLE_MEMBER("Position", PROPERTY_TYPE_FLOAT3, 0, PropertyCallbackGetPosition, nullptr, PropertyCallbackSetPosition, nullptr, nullptr, nullptr) PROPERTY_TABLE_MEMBER("Rotation", PROPERTY_TYPE_QUATERNION, 0, PropertyCallbackGetRotation, nullptr, PropertyCallbackSetRotation, nullptr, nullptr, nullptr) PROPERTY_TABLE_MEMBER("Scale", PROPERTY_TYPE_FLOAT3, 0, PropertyCallbackGetScale, nullptr, PropertyCallbackSetScale, nullptr, nullptr, nullptr) END_ENTITY_PROPERTIES() BEGIN_ENTITY_SCRIPT_FUNCTIONS(Entity) DEFINE_ENTITY_SCRIPT_FUNCTION("GetEntityID", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(uint32, Entity, GetEntityID)) DEFINE_ENTITY_SCRIPT_FUNCTION("GetEntityName", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(const char *, Entity, GetEntityName)) DEFINE_ENTITY_SCRIPT_FUNCTION("GetPosition", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(float3, Entity, GetPosition)) DEFINE_ENTITY_SCRIPT_FUNCTION("GetRotation", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(Quaternion, Entity, GetRotation)) DEFINE_ENTITY_SCRIPT_FUNCTION("GetScale", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_RET(float3, Entity, GetScale)) DEFINE_ENTITY_SCRIPT_FUNCTION("SetPosition", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P1(Entity, SetPosition, float3)) DEFINE_ENTITY_SCRIPT_FUNCTION("SetRotation", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P1(Entity, SetRotation, Quaternion)) DEFINE_ENTITY_SCRIPT_FUNCTION("SetScale", MAKE_SCRIPT_PROXY_LAMBDA_THISPTR_P1(Entity, SetScale, float3)) END_ENTITY_SCRIPT_FUNCTIONS() Entity::Entity(const EntityTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_entityID(0), m_mobility(ENTITY_MOBILITY_STATIC), m_transform(Transform::Identity), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_pWorld(nullptr), m_pWorldData(nullptr), m_registeredUpdateCount(0), m_registeredUpdateInterval(Y_FLT_MAX), m_registeredAsyncUpdateCount(0), m_registeredAsyncUpdateInterval(Y_FLT_MAX) { } Entity::~Entity() { DebugAssert(m_pWorld == NULL); // detach all components for (uint32 i = 0; i < m_components.GetSize(); i++) { Component *pComponent = m_components[i]; pComponent->OnRemoveFromEntity(this); pComponent->Release(); } } bool Entity::Initialize(uint32 entityID, const String &entityName) { DebugAssert(entityID != 0); m_entityID = entityID; m_entityName = entityName; return true; } void Entity::OnAddToWorld(World *pWorld) { DebugAssert(m_pWorld == nullptr); // set world pointer m_pWorld = pWorld; // if previously registered for updates, set it up if (m_registeredUpdateCount > 0) pWorld->RegisterEntityForUpdate(this, m_registeredUpdateInterval); if (m_registeredAsyncUpdateCount > 0) pWorld->RegisterEntityForAsyncUpdate(this, m_registeredAsyncUpdateInterval); // broadcast to script CallScriptMethod("OnSpawn"); // broadcast to components for (uint32 i = 0; i < m_components.GetSize(); i++) m_components[i]->OnAddToWorld(pWorld); } void Entity::OnRemoveFromWorld(World *pWorld) { DebugAssert(m_pWorld == pWorld); // broadcast to components for (uint32 i = 0; i < m_components.GetSize(); i++) m_components[i]->OnRemoveFromWorld(pWorld); // broadcast to script CallScriptMethod("OnDespawn"); // null world pointer m_pWorld = nullptr; } void Entity::OnTransformChange() { // broadcast to components for (uint32 i = 0; i < m_components.GetSize(); i++) { Component *pComponent = m_components[i]; pComponent->OnEntityTransformChange(); } } void Entity::OnComponentBoundsChange() { // use the current bounding box as a fallback, this should really be overriden by derived classes AABox boundingBox; Sphere boundingSphere; if (GetComponentBounds(boundingBox, boundingSphere)) { boundingBox.Merge(m_boundingBox); boundingSphere.Merge(boundingSphere); SetBounds(boundingBox, boundingSphere, false); } } void Entity::OnAction(Entity *pInitiator, uint32 action) { // pass to script CallScriptMethod("OnAction", pInitiator, action); } bool Entity::SetTransform(const Transform &transform) { // position can be changed if not in world if (IsInWorld() && GetMobility() == ENTITY_MOBILITY_STATIC) return false; // update transform m_transform = transform; OnTransformChange(); return true; } void Entity::Update(float timeSinceLastUpdate) { // update any components for (uint32 i = 0; i < m_components.GetSize(); i++) m_components[i]->Update(timeSinceLastUpdate); } void Entity::UpdateAsync(float timeSinceLastUpdate) { // update any components for (uint32 i = 0; i < m_components.GetSize(); i++) m_components[i]->UpdateAsync(timeSinceLastUpdate); } void Entity::RegisterForUpdates(float interval /* = 0.0f */) { DebugAssert(interval >= 0.0f); if (interval < m_registeredUpdateInterval || !m_registeredUpdateCount) { m_registeredUpdateInterval = Min(m_registeredUpdateInterval, interval); if (m_pWorld != nullptr) m_pWorld->RegisterEntityForUpdate(this, interval); } m_registeredUpdateCount++; } void Entity::RegisterForAsyncUpdates(float interval /* = 0.0f */) { DebugAssert(interval >= 0.0f); if (interval < m_registeredAsyncUpdateInterval || m_registeredAsyncUpdateCount == 0) { m_registeredAsyncUpdateInterval = Min(m_registeredAsyncUpdateInterval, interval); if (m_pWorld != nullptr) m_pWorld->RegisterEntityForAsyncUpdate(this, interval); } m_registeredAsyncUpdateCount++; } void Entity::UnregisterForUpdates() { Assert(m_registeredUpdateCount > 0); if ((--m_registeredUpdateCount) == 0) { if (m_pWorld != nullptr) m_pWorld->UnregisterEntityForUpdate(this); } } void Entity::UnregisterForAsyncUpdates() { Assert(m_registeredAsyncUpdateCount > 0); if ((--m_registeredAsyncUpdateCount) == 0) { if (m_pWorld != nullptr) m_pWorld->UnregisterEntityForAsyncUpdate(this); } } bool Entity::SetPosition(const float3 &position) { // position can be changed if not in world if (IsInWorld() && GetMobility() == ENTITY_MOBILITY_STATIC) return false; Transform transform(m_transform); transform.SetPosition(position); return SetTransform(transform); } bool Entity::SetRotation(const Quaternion &rotation) { // position can be changed if not in world if (IsInWorld() && GetMobility() == ENTITY_MOBILITY_STATIC) return false; Transform transform(m_transform); transform.SetRotation(rotation); return SetTransform(transform); } bool Entity::SetScale(const float3 &scale) { // position can be changed if not in world if (IsInWorld() && GetMobility() == ENTITY_MOBILITY_STATIC) return false; Transform transform(m_transform); transform.SetScale(scale); return SetTransform(transform); } void Entity::AddComponent(Component *pComponent) { DebugAssert(pComponent->GetEntity() == nullptr); #ifdef Y_BUILD_CONFIG_DEBUG uint32 i; for (i = 0; i < m_components.GetSize(); i++) DebugAssert(m_components[i] != pComponent); #endif m_components.Add(pComponent); pComponent->AddRef(); pComponent->OnAddToEntity(this); // in world? if (m_pWorld != nullptr) pComponent->OnAddToWorld(m_pWorld); // changed bounding box? AABox mergedBoundingBox(m_boundingBox); Sphere mergedBoundingSphere(m_boundingSphere); mergedBoundingBox.Merge(pComponent->GetBoundingBox()); mergedBoundingSphere.Merge(pComponent->GetBoundingSphere()); if (mergedBoundingBox != m_boundingBox || mergedBoundingSphere != m_boundingSphere) SetBounds(mergedBoundingBox, mergedBoundingSphere, false); } void Entity::RemoveComponent(Component *pComponent) { for (uint32 i = 0; i < m_components.GetSize(); i++) { if (m_components[i] == pComponent) { // removing a component while it is in world is perfectly legal, so cater for this case if (m_pWorld != nullptr) pComponent->OnRemoveFromWorld(m_pWorld); // call removed function pComponent->OnRemoveFromEntity(this); pComponent->Release(); // remove it from our array, and destroy the component m_components.OrderedRemove(i); // merge bounds OnComponentBoundsChange(); return; } } Panic("Attempting to remove component from entity that is not in list."); } bool Entity::GetComponentBounds(AABox &boundingBox, Sphere &boundingSphere) { if (m_components.GetSize() == 0) return false; boundingBox = m_components[0]->GetBoundingBox(); boundingSphere = m_components[0]->GetBoundingSphere(); for (uint32 i = 1; i < m_components.GetSize(); i++) { boundingBox.Merge(m_components[i]->GetBoundingBox()); boundingSphere.Merge(m_components[i]->GetBoundingSphere()); } return true; } void Entity::SetBounds(const AABox &boundingBox, const Sphere &boundingSphere, bool mergeWithComponents /* = true */) { AABox mergedBoundingBox; Sphere mergedBoundingSphere; if (mergeWithComponents && GetComponentBounds(mergedBoundingBox, mergedBoundingSphere)) { mergedBoundingBox.Merge(boundingBox); mergedBoundingSphere.Merge(boundingSphere); if (mergedBoundingBox != m_boundingBox || mergedBoundingSphere != m_boundingSphere) { m_boundingBox = mergedBoundingBox; m_boundingSphere = mergedBoundingSphere; if (m_pWorld != nullptr) m_pWorld->MoveEntity(this); } } else { if (boundingBox != m_boundingBox || boundingSphere != m_boundingSphere) { m_boundingBox = boundingBox; m_boundingSphere = boundingSphere; if (m_pWorld != nullptr) m_pWorld->MoveEntity(this); } } } bool Entity::PropertyCallbackGetPosition(Entity *pObjectPtr, const void *pUserData, float3 *pValuePtr) { *pValuePtr = pObjectPtr->GetPosition(); return true; } bool Entity::PropertyCallbackSetPosition(Entity *pObjectPtr, const void *pUserData, const float3 *pValuePtr) { if (pObjectPtr->IsInWorld()) { // pass through return pObjectPtr->SetPosition(*pValuePtr); } else { pObjectPtr->m_transform.SetPosition(*pValuePtr); return true; } } bool Entity::PropertyCallbackGetRotation(Entity *pObjectPtr, const void *pUserData, Quaternion *pValuePtr) { *pValuePtr = pObjectPtr->GetRotation(); return true; } bool Entity::PropertyCallbackSetRotation(Entity *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr) { if (pObjectPtr->IsInWorld()) { // pass through return pObjectPtr->SetRotation(*pValuePtr); } else { pObjectPtr->m_transform.SetRotation(*pValuePtr); return true; } } bool Entity::PropertyCallbackGetScale(Entity *pObjectPtr, const void *pUserData, float3 *pValuePtr) { *pValuePtr = pObjectPtr->GetScale(); return true; } bool Entity::PropertyCallbackSetScale(Entity *pObjectPtr, const void *pUserData, const float3 *pValuePtr) { if (pObjectPtr->IsInWorld()) { // pass through return pObjectPtr->SetScale(*pValuePtr); } else { pObjectPtr->m_transform.SetScale(*pValuePtr); return true; } } // bool Entity::InitializeEntityPropertiesFromTable(Entity *pEntity, const PropertyTable *pPropertyTable) // { // // for each property in our type // const EntityTypeInfo *pEntityTypeInfo = pEntity->GetEntityTypeInfo(); // for (uint32 propertyIndex = 0; propertyIndex < pEntityTypeInfo->GetPropertyCount(); propertyIndex++) // { // const PROPERTY_DECLARATION *pPropertyDeclaration = pEntityTypeInfo->GetPropertyDeclarationByIndex(propertyIndex); // // // attempt to find a value in the property table // const String *propertyValue = pPropertyTable->GetPropertyValuePointer(pPropertyDeclaration->Name); // if (propertyValue == nullptr) // continue; // // // set the value // if (!SetPropertyValueFromString(pEntity, pPropertyDeclaration, *propertyValue)) // { // Log_WarningPrintf("Failed to initialize entity '%s' property '%s' to value '%s'", pEntityTypeInfo->GetTypeName(), pPropertyDeclaration->Name, propertyValue); // continue; // } // } // // return true; // } SIMDVector4f EncodeUInt32ToColor(uint32 EntityId) { float val[4]; val[0] = float(EntityId & 0xFF) / 255.0f; val[1] = float((EntityId >> 8) & 0xFF) / 255.0f; val[2] = float((EntityId >> 16) & 0xFF) / 255.0f; val[3] = float(EntityId >> 24) / 255.0f; return SIMDVector4f(val); } uint32 DecodeUInt32FromColorR8G8B8A8(const void *pValue) { uint32 intValue = *(uint32 *)pValue; uint32 ret; // ret = ((intValue >> 24)) | // (((intValue >> 16) & 0xFF) << 8) | // (((intValue >> 8) & 0xFF) << 16) | // ((intValue & 0xFF) << 24); ret = intValue; return ret; } uint32 DecodeUInt32IdFromColor(const float4 &EncodedColor) { uint32 ret; ret = ((uint32(EncodedColor.x * 255.0f) & 0xFF)) | ((uint32(EncodedColor.y * 255.0f) & 0xFF) << 8) | ((uint32(EncodedColor.z * 255.0f) & 0xFF) << 16) | ((uint32(EncodedColor.w * 255.0f) & 0xFF) << 24); return ret; } <file_sep>/Editor/Source/Editor/preprocess.sh MOC=/usr/lib64/qt5/bin/moc UIC=/usr/lib64/qt5/bin/uic RCC=/usr/lib64/qt5/bin/rcc echo Preprocessing... $MOC -b Editor/PrecompiledHeader.h -o moc_Editor.cpp Editor.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorCreateTerrainDialog.cpp EditorCreateTerrainDialog.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorMapWindow.cpp EditorMapWindow.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorProgressDialog.cpp EditorProgressDialog.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorPropertyEditorWidget.cpp EditorPropertyEditorWidget.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorRendererSwapChainWidget.cpp EditorRendererSwapChainWidget.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorResourcePreviewWidget.cpp EditorResourcePreviewWidget.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorResourceSaveDialog.cpp EditorResourceSaveDialog.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorResourceSelectionDialog.cpp EditorResourceSelectionDialog.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorResourceSelectionDialogModel.cpp EditorResourceSelectionDialogModel.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorResourceSelectionWidget.cpp EditorResourceSelectionWidget.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorBlockMeshEditor.cpp EditorStaticBlockMeshEditor.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorViewport.cpp EditorViewport.h $MOC -b Editor/PrecompiledHeader.h -o moc_EditorVirtualFileSystemModel.cpp EditorVirtualFileSystemModel.h $UIC -o ui_EditorProgressDialog.h EditorProgressDialog.ui $UIC -o ui_EditorCreateTerrainDialog.h EditorCreateTerrainDialog.ui $RCC -o rcc_Editor.cpp Resources/editor.qrc echo Done. <file_sep>/Engine/Source/ContentConverter/OBJImporter.cpp #include "ContentConverter/PrecompiledHeader.h" #include "ContentConverter/OBJImporter.h" #include "Engine/ResourceManager.h" #include "ResourceCompiler/MaterialGenerator.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "Core/MeshUtilties.h" // for map building #include "MapCompiler/MapSource.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" OBJImporter::OBJImporter(ProgressCallbacks *pProgressCallbacks) : BaseImporter(pProgressCallbacks) { m_uSourceLineNumber = 0; } OBJImporter::~OBJImporter() { } void OBJImporter::SetDefaultOptions(OBJImporterOptions *pOptions) { pOptions->ImportMaterials = true; pOptions->DefaultMaterialName = "materials/engine/default"; pOptions->BuildCollisionShapeType = "trianglemesh"; pOptions->UseSmoothingGroups = true; pOptions->TransformMatrix.SetIdentity(); pOptions->CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; pOptions->FlipWinding = false; pOptions->CenterMeshes = StaticMeshGenerator::CenterOrigin_Count; pOptions->MergeGroups = true; } bool OBJImporter::Execute(const OBJImporterOptions *pOptions) { Timer t; uint32 i; bool Result = false; if (pOptions->InputFileName.IsEmpty() || pOptions->MeshDirectory.IsEmpty() || (pOptions->ImportMaterials && pOptions->MaterialDirectory.IsEmpty())) { m_pProgressCallbacks->ModalError("One or more required parameters not set."); return false; } // store options m_pOptions = pOptions; m_pProgressCallbacks->SetProgressRange(6); m_pProgressCallbacks->SetProgressValue(0); m_pProgressCallbacks->SetStatusText("Parsing source..."); m_pProgressCallbacks->PushState(); if (!ParseSource()) { m_pProgressCallbacks->PopState(); goto EXIT; } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(1); m_pProgressCallbacks->DisplayFormattedInformation("ParseSource(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); m_pProgressCallbacks->SetStatusText("Parsing materials..."); m_pProgressCallbacks->PushState(); if (!ParseMaterials()) { m_pProgressCallbacks->PopState(); return false;; } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(2); m_pProgressCallbacks->DisplayFormattedInformation("ParseMaterials(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); m_pProgressCallbacks->SetStatusText("Generating materials..."); m_pProgressCallbacks->PushState(); if (!GenerateMaterials()) { m_pProgressCallbacks->PopState(); goto EXIT; } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(3); m_pProgressCallbacks->DisplayFormattedInformation("GenerateMaterials(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); if (m_pOptions->MergeGroups) { m_pProgressCallbacks->SetStatusText("Merging groups..."); MergeGroups(); m_pProgressCallbacks->DisplayFormattedInformation("MergeGroups(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); } m_pProgressCallbacks->SetStatusText("Generating triangles..."); m_pProgressCallbacks->PushState(); if (!GenerateTriangles()) { m_pProgressCallbacks->PopState(); goto EXIT; } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(4); m_pProgressCallbacks->DisplayFormattedInformation("GenerateTriangles(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); m_pProgressCallbacks->SetStatusText("Writing output..."); m_pProgressCallbacks->PushState(); if (!WriteOutput()) { m_pProgressCallbacks->PopState(); goto EXIT; } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(5); m_pProgressCallbacks->DisplayFormattedInformation("WriteOutput(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); m_pProgressCallbacks->SetStatusText("Generating map..."); m_pProgressCallbacks->PushState(); if (m_pOptions->OutputMapName.GetLength() > 0) { if (!WriteMap()) { m_pProgressCallbacks->PopState(); goto EXIT; } m_pProgressCallbacks->DisplayFormattedInformation("WriteMap(): %.4f msec", t.GetTimeMilliseconds()); t.Reset(); } m_pProgressCallbacks->PopState(); m_pProgressCallbacks->SetProgressValue(6); Result = true; EXIT: for (i = 0; i < m_arrSourceMaterialLibraries.GetSize(); i++) delete m_arrSourceMaterialLibraries[i]; m_arrSourceMaterialLibraries.Clear(); for (i = 0; i < m_arrSourceMaterialNames.GetSize(); i++) delete m_arrSourceMaterialNames[i]; m_arrSourceMaterialNames.Clear(); for (i = 0; i < m_arrSourceGroups.GetSize(); i++) delete m_arrSourceGroups[i]; m_arrSourceGroups.Clear(); for (i = 0; i < m_arrOutputMeshes.GetSize(); i++) delete m_arrOutputMeshes[i]; m_arrOutputMeshes.Clear(); m_arrOutputMaterials.Clear(); return Result; } void OBJImporter::PrintSourceError(const char *Format, ...) { va_list ap; va_start(ap, Format); String Message; Message.Format("%s:%u: ", m_pOptions->InputFileName.GetCharArray(), m_uSourceLineNumber); Message.AppendFormattedStringVA(Format, ap); va_end(ap); m_pProgressCallbacks->DisplayError(Message.GetCharArray()); } void OBJImporter::PrintSourceWarning(const char *Format, ...) { va_list ap; va_start(ap, Format); String Message; Message.Format("%s:%u: ", m_pOptions->InputFileName.GetCharArray(), m_uSourceLineNumber); Message.AppendFormattedStringVA(Format, ap); va_end(ap); m_pProgressCallbacks->DisplayWarning(Message.GetCharArray()); } bool OBJImporter::ParseSource() { uint32 i, j; ByteStream *pInputStream; if (!ByteStream_OpenFileStream(m_pOptions->InputFileName, BYTESTREAM_OPEN_READ, &pInputStream)) { m_pProgressCallbacks->DisplayFormattedError("Could not open input file \"%s\"", m_pOptions->InputFileName.GetCharArray()); return false; } TextReader Reader(pInputStream); char Line[1024]; int32 CurrentMaterialIndex = -1; SourceGroup *pCurrentSourceGroup = NULL; uint32 CurrentSmoothingGroups = 1; uint32 TotalFaceCount = 0; bool Result = true; while (Reader.ReadLine(Line, countof(Line))) { m_pProgressCallbacks->UpdateProgressFromStream(pInputStream); m_uSourceLineNumber++; Y_strstrip(Line, "\r\n\t "); // skip comments if (Line[0] == '#') continue; // tokenize char *Tokens[128]; uint32 nTokens; nTokens = Y_strsplit3(Line, ' ', Tokens, countof(Tokens)); if (nTokens < 1) continue; // switch depending on token // reference material library if (!Y_stricmp(Tokens[0], "mtllib")) { if (nTokens < 2) { PrintSourceError("At least one material library must be provided."); Result = false; break; } for (i = 1; i < nTokens; i++) m_arrSourceMaterialLibraries.Add(new String(Tokens[i])); } // vertex declaration else if (!Y_stricmp(Tokens[0], "v")) { if (nTokens < 4) { PrintSourceError("Vertex must have three components."); Result = false; break; } float3 v; v.x = Y_strtofloat(Tokens[1]); v.y = Y_strtofloat(Tokens[2]); v.z = Y_strtofloat(Tokens[3]); m_arrSourceVertices.Add(v); } // texcoord declaration else if (!Y_stricmp(Tokens[0], "vt")) { if (nTokens < 3) { PrintSourceError("Texcoord must have three components."); Result = false; break; } float2 v; v.x = Y_strtofloat(Tokens[1]); v.y = Y_strtofloat(Tokens[2]); m_arrSourceTexCoords.Add(v); } // vertex normal declaration, ignore these for now else if (!Y_stricmp(Tokens[0], "vn")) { } // set face group else if (!Y_stricmp(Tokens[0], "g")) { if (nTokens < 2) { PrintSourceError("Expected a group name."); Result = false; break; } if (nTokens > 2) { PrintSourceError("More than one face group unsupported."); Result = false; break; } for (i = 0; i < m_arrSourceGroups.GetSize(); i++) { if (m_arrSourceGroups[i]->Name.CompareInsensitive(Tokens[1])) { pCurrentSourceGroup = m_arrSourceGroups[i]; break; } } if (i == m_arrSourceGroups.GetSize()) { pCurrentSourceGroup = new SourceGroup(); pCurrentSourceGroup->Name.Assign(Tokens[1]); m_arrSourceGroups.Add(pCurrentSourceGroup); } } // set smoothing group else if (!Y_stricmp(Tokens[0], "s")) { if (nTokens < 2) { PrintSourceError("Expected a smoothing group mask or 'off'"); Result = false; break; } if (!Y_stricmp(Tokens[1], "off")) CurrentSmoothingGroups = 0; else CurrentSmoothingGroups = Y_strtouint32(Tokens[1]); } // set face material else if (!Y_stricmp(Tokens[0], "usemtl")) { if (nTokens < 2) { PrintSourceError("A material name must be specified."); Result = false; break; } for (i = 0; i < m_arrSourceMaterialNames.GetSize(); i++) { if (m_arrSourceMaterialNames[i]->CompareInsensitive(Tokens[1])) break; } if (i == m_arrSourceMaterialNames.GetSize()) m_arrSourceMaterialNames.Add(new String(Tokens[1])); CurrentMaterialIndex = i; } // face declaration else if (!Y_stricmp(Tokens[0], "f")) { if (nTokens < 4) { PrintSourceError("A face must have at least three vertices."); Result = false; break; } if ((nTokens - 1) > OBJIMPORTER_MAX_VERTICES_PER_FACE) { PrintSourceError("Too many vertices in face (%u), max is %u", (nTokens - 1), (uint32)OBJIMPORTER_MAX_VERTICES_PER_FACE); Result = false; break; } // determine group if (pCurrentSourceGroup == NULL) { DebugAssert(m_arrSourceGroups.GetSize() == 0); pCurrentSourceGroup = new SourceGroup(); pCurrentSourceGroup->Name = "Ungrouped"; m_arrSourceGroups.Add(pCurrentSourceGroup); } // determine material index if (CurrentMaterialIndex < 0) { m_arrSourceMaterialNames.Add(new String()); CurrentMaterialIndex = 0; } // determine num vertices uint32 NumVertices = nTokens - 1; // face struct SourceFace f; f.MaterialIndex = CurrentMaterialIndex; f.SmoothingGroups = CurrentSmoothingGroups; f.NumVertices = NumVertices; // components int32 VertexIndex[OBJIMPORTER_MAX_VERTICES_PER_FACE]; //int32 NormalIndex[OBJIMPORTER_MAX_VERTICES_PER_FACE]; int32 TexIndex[OBJIMPORTER_MAX_VERTICES_PER_FACE]; //bool FaceHasNormal = true; bool FaceHasTex = true; // vertices char *ComponentTokens[3]; for (i = 0; i < NumVertices; i++) { uint32 c = Y_strsplit(Tokens[i + 1], '/', ComponentTokens, countof(ComponentTokens)); for (j = 0; j < c; j++) Y_strstrip(ComponentTokens[j], " \r\n\t"); if (c == 3) { VertexIndex[i] = Y_strtoint32(ComponentTokens[0]); // possible to have no texcoord index if (*ComponentTokens[1] == '\0') FaceHasTex = false; else TexIndex[i] = Y_strtoint32(ComponentTokens[1]); //NormalIndex[i] = Y_strtoint32(ComponentTokens[2]); } else if (c == 2) { //FaceHasNormal = false; VertexIndex[i] = Y_strtoint32(ComponentTokens[0]); TexIndex[i] = Y_strtoint32(ComponentTokens[1]); } else if (c == 1) { //FaceHasNormal = false; FaceHasTex = false; VertexIndex[i] = Y_strtoint32(ComponentTokens[0]); } else { PrintSourceError("Parse error in face."); Result = false; break; } } for (i = 0; i < NumVertices; i++) { if (VertexIndex[i] == 0 || VertexIndex[i] > (int32)m_arrSourceVertices.GetSize() || (VertexIndex[i] < 0 && ((-VertexIndex[i]) > (int32)m_arrSourceVertices.GetSize()))) { PrintSourceError("Vertex position index out of range."); Result = false; break; } f.VertexIndicies[i] = (VertexIndex[i] < 0) ? (m_arrSourceVertices.GetSize() - ((uint32)-VertexIndex[i])) : VertexIndex[i] - 1; // if (FaceHasNormal) // { // if (NormalIndex[i] == 0 || NormalIndex[i] > (int32)m_arrVertexNormals.GetSize() || (NormalIndex[i] < 0 && ((-NormalIndex[i]) > (int32)m_arrVertexNormals.GetSize()))) // { // PrintSourceError("Vertex normal index out of range."); // return false; // } // // Face.NormalIndex[i] = (NormalIndex[i] < 0) ? (m_arrVertexNormals.GetSize() - ((uint32)-NormalIndex[i])) : NormalIndex[i] - 1; // } // else // { // Face.NormalIndex[i] = -1; // } if (FaceHasTex) { if (TexIndex[i] == 0 || TexIndex[i] > (int32)m_arrSourceTexCoords.GetSize() || (TexIndex[i] < 0 && ((-TexIndex[i]) > (int32)m_arrSourceTexCoords.GetSize()))) { PrintSourceError("Vertex texcoord index out of range."); Result = false; break; } f.TexCoordIndices[i] = (TexIndex[i] < 0) ? (m_arrSourceTexCoords.GetSize() - ((uint32)-TexIndex[i])) : TexIndex[i] - 1; } else { f.TexCoordIndices[i] = -1; } } for (; i < OBJIMPORTER_MAX_VERTICES_PER_FACE; i++) { f.VertexIndicies[i] = -1; f.TexCoordIndices[i] = -1; } // add it pCurrentSourceGroup->Faces.Add(f); TotalFaceCount++; } else { PrintSourceWarning("Unknown command: '%s'", Tokens[0]); } } pInputStream->Release(); if (!Result) return false; m_pProgressCallbacks->DisplayFormattedInformation("Source has %u vertices, %u texcoords, %u faces in %u groups.", (uint32)m_arrSourceVertices.GetSize(), (uint32)m_arrSourceTexCoords.GetSize(), TotalFaceCount, (uint32)m_arrSourceGroups.GetSize()); return true; } void OBJImporter::PrintMaterialError(uint32 i, const char *Format, ...) { va_list ap; va_start(ap, Format); String Message; Message.Format("%s:%u: ", m_arrSourceMaterialLibraries[i]->GetCharArray(), m_uSourceLineNumber); Message.AppendFormattedStringVA(Format, ap); va_end(ap); m_pProgressCallbacks->DisplayError(Message.GetCharArray()); } void OBJImporter::PrintMaterialWarning(uint32 i, const char *Format, ...) { va_list ap; va_start(ap, Format); String Message; Message.Format("%s:%u: ", m_arrSourceMaterialLibraries[i]->GetCharArray(), m_uSourceLineNumber); Message.AppendFormattedStringVA(Format, ap); va_end(ap); m_pProgressCallbacks->DisplayWarning(Message.GetCharArray()); } bool OBJImporter::ParseMaterials() { uint32 i; for (i = 0; i < m_arrSourceMaterialLibraries.GetSize(); i++) { String MaterialLibraryPath; FileSystem::BuildPathRelativeToFile(MaterialLibraryPath, m_pOptions->InputFileName, m_arrSourceMaterialLibraries[i]->GetCharArray(), false, false); FileSystem::BuildOSPath(MaterialLibraryPath); ByteStream *pInputStream = FileSystem::OpenFile(MaterialLibraryPath.GetCharArray(), BYTESTREAM_OPEN_READ); if (pInputStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open input material file \"%s\"", MaterialLibraryPath.GetCharArray()); return false; } TextReader Reader(pInputStream); char Line[1024]; SourceMaterial *pCurrentMaterial = NULL; bool Result = true; m_uSourceLineNumber = 0; while (Reader.ReadLine(Line, countof(Line))) { m_uSourceLineNumber++; Y_strstrip(Line, "\r\n\t "); // skip comments if (Line[0] == '#') continue; // tokenize char *Tokens[128]; uint32 nTokens; nTokens = Y_strsplit3(Line, ' ', Tokens, countof(Tokens)); if (nTokens < 1) continue; // switch depending on token // new material if (!Y_stricmp(Tokens[0], "newmtl")) { pCurrentMaterial = new SourceMaterial(); pCurrentMaterial->Name.Assign(Tokens[1]); pCurrentMaterial->AmbientColor = float3::One; pCurrentMaterial->DiffuseColor = float3::One; pCurrentMaterial->SpecularColor = float3::One; pCurrentMaterial->EmissiveColor = float3::Zero; pCurrentMaterial->AlphaColor = 1.0f; pCurrentMaterial->Shininess = 10.0f; pCurrentMaterial->Illum = 2; // todo check dupe names m_arrSourceMaterials.Add(pCurrentMaterial); m_pProgressCallbacks->DisplayFormattedInformation("New source material: '%s'", pCurrentMaterial->Name.GetCharArray()); } else { if (pCurrentMaterial == NULL) { PrintMaterialError(i, "No material currently being defined."); Result = false; break; } // ambient color if (!Y_stricmp(Tokens[0], "Ka")) { if (nTokens < 4) { PrintMaterialError(i, "Color has must three elements."); Result = false; break; } pCurrentMaterial->AmbientColor.x = Y_strtofloat(Tokens[1]); pCurrentMaterial->AmbientColor.y = Y_strtofloat(Tokens[2]); pCurrentMaterial->AmbientColor.z = Y_strtofloat(Tokens[3]); } // diffuse color else if (!Y_stricmp(Tokens[0], "Kd")) { if (nTokens < 4) { PrintMaterialError(i, "Color has must three elements."); Result = false; break; } pCurrentMaterial->DiffuseColor.x = Y_strtofloat(Tokens[1]); pCurrentMaterial->DiffuseColor.y = Y_strtofloat(Tokens[2]); pCurrentMaterial->DiffuseColor.z = Y_strtofloat(Tokens[3]); } // specular color else if (!Y_stricmp(Tokens[0], "Ks")) { if (nTokens < 4) { PrintMaterialError(i, "Color has must three elements."); Result = false; break; } pCurrentMaterial->SpecularColor.x = Y_strtofloat(Tokens[1]); pCurrentMaterial->SpecularColor.y = Y_strtofloat(Tokens[2]); pCurrentMaterial->SpecularColor.z = Y_strtofloat(Tokens[3]); } // shininess else if (!Y_stricmp(Tokens[0], "Ns")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } pCurrentMaterial->Shininess = Y_strtofloat(Tokens[1]); } // emissive color else if (!Y_stricmp(Tokens[0], "Ke")) { if (nTokens < 4) { PrintMaterialError(i, "Color has must three elements."); Result = false; break; } pCurrentMaterial->EmissiveColor.x = Y_strtofloat(Tokens[1]); pCurrentMaterial->EmissiveColor.y = Y_strtofloat(Tokens[2]); pCurrentMaterial->EmissiveColor.z = Y_strtofloat(Tokens[3]); } // transparency else if (!Y_stricmp(Tokens[0], "d")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } pCurrentMaterial->AlphaColor = Y_strtofloat(Tokens[1]); } // illum else if (!Y_stricmp(Tokens[0], "illum")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } pCurrentMaterial->Illum = Y_strtouint32(Tokens[1]); } // ambient map else if (!Y_stricmp(Tokens[0], "map_Ka")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } FileSystem::BuildPathRelativeToFile(pCurrentMaterial->AmbientMap, MaterialLibraryPath.GetCharArray(), Tokens[1]); } // diffuse map else if (!Y_stricmp(Tokens[0], "map_Kd")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } FileSystem::BuildPathRelativeToFile(pCurrentMaterial->DiffuseMap, MaterialLibraryPath.GetCharArray(), Tokens[1]); } // specular map else if (!Y_stricmp(Tokens[0], "map_Ks")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } FileSystem::BuildPathRelativeToFile(pCurrentMaterial->SpecularMap, MaterialLibraryPath.GetCharArray(), Tokens[1]); } // alpha map else if (!Y_stricmp(Tokens[0], "map_d")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } FileSystem::BuildPathRelativeToFile(pCurrentMaterial->AlphaMap, MaterialLibraryPath.GetCharArray(), Tokens[1]); } // bump map else if (!Y_stricmp(Tokens[0], "map_bump") || !Y_stricmp(Tokens[0], "bump")) { if (nTokens < 2) { PrintMaterialError(i, "Missing parameter."); Result = false; break; } FileSystem::BuildPathRelativeToFile(pCurrentMaterial->BumpMap, MaterialLibraryPath.GetCharArray(), Tokens[1]); } // unk else if (!Y_stricmp(Tokens[0], "Ni")) { } // unk else if (!Y_stricmp(Tokens[0], "Tr")) { } // unk else if (!Y_stricmp(Tokens[0], "Tf")) { } else { PrintMaterialWarning(i, "Unknown command '%s'", Tokens[0]); } } } pInputStream->Release(); if (!Result) return false; } return true; } bool OBJImporter::ImportMaterialTexture(const String &inputFileName, String &outputFullName, TEXTURE_USAGE usage, const String &maskTexture /* = EmptyString */) { SmallString outputTextureName; PathString outputFileName; // copy name and remove extension int32 startLength = (int32)outputTextureName.GetLength(); int32 lastSegment = Max(inputFileName.RFind('\\'), inputFileName.RFind('/')); if (lastSegment > 0) outputTextureName.AppendString(inputFileName.GetCharArray() + lastSegment + 1); else outputTextureName.AppendString(inputFileName); int32 extensionStartPos = outputTextureName.RFind('.'); if (extensionStartPos >= startLength) outputTextureName.Erase(extensionStartPos); // sanitize name Resource::SanitizeResourceName(outputTextureName); // generate full name outputFullName.Format("%s/%s%s", m_pOptions->MaterialDirectory.GetCharArray(), m_pOptions->MaterialPrefix.GetCharArray(), outputTextureName.GetCharArray()); outputFileName.Format("%s.tex.zip", outputFullName.GetCharArray()); // see if it's already been written FILESYSTEM_STAT_DATA statData; if (g_pVirtualFileSystem->StatFile(outputFileName, &statData)) { m_pProgressCallbacks->DisplayFormattedWarning("Texture '%s' already exists, not overwriting.", outputTextureName.GetCharArray()); return true; } // log it m_pProgressCallbacks->DisplayFormattedInformation("Importing texture at '%s' as '%s'", inputFileName.GetCharArray(), outputFullName.GetCharArray()); // build texture converter options TextureImporterOptions TIOptions; TextureImporter::SetDefaultOptions(&TIOptions); TIOptions.InputFileNames.Add(inputFileName); if (maskTexture.GetLength() > 0) TIOptions.InputMaskFileNames.Add(maskTexture); TIOptions.OutputName = outputFullName; TIOptions.Type = TEXTURE_TYPE_2D; TIOptions.Usage = usage; TIOptions.AddressU = TEXTURE_ADDRESS_MODE_WRAP; TIOptions.AddressV = TEXTURE_ADDRESS_MODE_WRAP; TIOptions.AddressW = TEXTURE_ADDRESS_MODE_WRAP; TIOptions.Optimize = false; TIOptions.Compile = false; // push state m_pProgressCallbacks->PushState(); // create texture converter and run it TextureImporter TImporter(m_pProgressCallbacks); bool result = TImporter.Execute(&TIOptions); // pop state m_pProgressCallbacks->PopState(); return result; } bool OBJImporter::GenerateMaterials() { String fileName; // if we're not generating materials, we'll just create one, the default, and change all the indicies if (!m_pOptions->ImportMaterials) { m_arrOutputMaterials.Add(m_pOptions->DefaultMaterialName); for (uint32 i = 0; i < m_arrSourceGroups.GetSize(); i++) { for (uint32 j = 0; j < m_arrSourceGroups[i]->Faces.GetSize(); j++) m_arrSourceGroups[i]->Faces[j].MaterialIndex = 0; } return true; } // importing materials... for (uint32 i = 0; i < m_arrSourceMaterials.GetSize(); i++) { SourceMaterial *pSourceMaterial = m_arrSourceMaterials[i]; // generate output material name SmallString outputMaterialName; outputMaterialName.AppendString(pSourceMaterial->Name); Resource::SanitizeResourceName(outputMaterialName); // append dir/prefix outputMaterialName.PrependFormattedString("%s/%s", m_pOptions->MaterialDirectory.GetCharArray(), m_pOptions->MaterialPrefix.GetCharArray()); // build filename to material SmallString outputMaterialFileName; outputMaterialFileName.Format("%s.mtl.xml", outputMaterialName.GetCharArray()); // does it already exist? FILESYSTEM_STAT_DATA statData; if (g_pVirtualFileSystem->StatFile(outputMaterialFileName, &statData)) { m_pProgressCallbacks->DisplayFormattedWarning("Material '%s' already exists, not overwriting.", outputMaterialName.GetCharArray()); pSourceMaterial->OutputName = outputMaterialName; continue; } SmallString DiffuseMapTextureName; SmallString SpecularMapTextureName; SmallString AlphaMapTextureName; SmallString NormalMapTextureName; // convert texture names and possibly import them if (pSourceMaterial->DiffuseMap.GetLength() > 0 && !ImportMaterialTexture(pSourceMaterial->DiffuseMap, DiffuseMapTextureName, TEXTURE_USAGE_COLOR_MAP, pSourceMaterial->AlphaMap)) m_pProgressCallbacks->DisplayFormattedWarning("Failed to import diffuse map texture '%s'", pSourceMaterial->DiffuseMap.GetCharArray()); if (pSourceMaterial->SpecularMap.GetLength() > 0 && !ImportMaterialTexture(pSourceMaterial->SpecularMap, SpecularMapTextureName, TEXTURE_USAGE_GLOSS_MAP)) m_pProgressCallbacks->DisplayFormattedWarning("Failed to import specular map texture '%s'", pSourceMaterial->SpecularMap.GetCharArray()); if (pSourceMaterial->BumpMap.GetLength() > 0 && !ImportMaterialTexture(pSourceMaterial->BumpMap, NormalMapTextureName, TEXTURE_USAGE_HEIGHT_MAP)) m_pProgressCallbacks->DisplayFormattedWarning("Failed to import bump map texture '%s'", pSourceMaterial->AlphaMap.GetCharArray()); // determine parent material MaterialGenerator materialGenerator; if ((AlphaMapTextureName.GetLength() > 0 || pSourceMaterial->AlphaColor != 1.0f)) { if (NormalMapTextureName.GetLength() > 0) materialGenerator.Create("shaders/engine/simple_transparent_normalmap"); else materialGenerator.Create("shaders/engine/simple_transparent"); if (AlphaMapTextureName.GetLength() > 0) { materialGenerator.SetShaderStaticSwitchParameterByName("UseAlphaMap", true); materialGenerator.SetShaderTextureParameterStringByName("AlphaMap", AlphaMapTextureName.GetCharArray()); } else { materialGenerator.SetShaderStaticSwitchParameterByName("UseAlphaMap", false); materialGenerator.SetShaderUniformParameterByName("AlphaCoefficient", SHADER_PARAMETER_TYPE_FLOAT, &pSourceMaterial->AlphaColor); } } else { if (NormalMapTextureName.GetLength() > 0) materialGenerator.Create("shaders/engine/simple_normalmap"); else materialGenerator.Create("shaders/engine/simple"); } // normalmaps if (NormalMapTextureName.GetLength() > 0) materialGenerator.SetShaderTextureParameterStringByName("NormalMap", NormalMapTextureName.GetCharArray()); // diffusemaps if (DiffuseMapTextureName.GetLength() > 0) { materialGenerator.SetShaderStaticSwitchParameterByName("UseDiffuseMap", true); materialGenerator.SetShaderTextureParameterStringByName("DiffuseMap", DiffuseMapTextureName.GetCharArray()); } else { materialGenerator.SetShaderStaticSwitchParameterByName("UseDiffuseMap", false); materialGenerator.SetShaderUniformParameterByName("DiffuseColor", SHADER_PARAMETER_TYPE_FLOAT3, &pSourceMaterial->DiffuseColor); } // specularmaps if (SpecularMapTextureName.GetLength() > 0) { materialGenerator.SetShaderStaticSwitchParameterByName("UseSpecularMap", true); materialGenerator.SetShaderTextureParameterStringByName("SpecularMap", SpecularMapTextureName.GetCharArray()); } else { materialGenerator.SetShaderStaticSwitchParameterByName("UseSpecularMap", false); float sc = Max(pSourceMaterial->SpecularColor.x, Max(pSourceMaterial->SpecularColor.y, pSourceMaterial->SpecularColor.z)); materialGenerator.SetShaderUniformParameterByName("SpecularCoefficient", SHADER_PARAMETER_TYPE_FLOAT, &sc); } // write material ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputMaterialFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open material file '%s' for writing.", outputMaterialFileName.GetCharArray()); pSourceMaterial->OutputName = m_pOptions->DefaultMaterialName; continue; } // write it materialGenerator.SaveToXML(pStream); pStream->Release(); // store name pSourceMaterial->OutputName = outputMaterialName; // log it m_pProgressCallbacks->DisplayFormattedInformation("Created OBJ material '%s' as '%s'", pSourceMaterial->Name.GetCharArray(), outputMaterialName.GetCharArray()); } // bind to model for (uint32 i = 0; i < m_arrSourceMaterialNames.GetSize(); i++) { const SourceMaterial *pSourceMaterial = NULL; for (uint32 j = 0; j < m_arrSourceMaterials.GetSize(); j++) { if (m_arrSourceMaterials[j]->Name.CompareInsensitive(*m_arrSourceMaterialNames[i])) { pSourceMaterial = m_arrSourceMaterials[j]; break; } } if (pSourceMaterial == NULL) { m_pProgressCallbacks->DisplayFormattedWarning("Could not find referenced material '%s'. Setting to default.", m_arrSourceMaterialNames[i]->GetCharArray()); m_arrOutputMaterials.Add(m_pOptions->DefaultMaterialName); continue; } m_arrOutputMaterials.Add(pSourceMaterial->OutputName); } return true; } void OBJImporter::MergeGroups() { DebugAssert(m_arrSourceGroups.GetSize() > 0); m_pProgressCallbacks->DisplayFormattedInformation("merging %u groups", m_arrSourceGroups.GetSize()); SourceGroup *pMergedGroup = new SourceGroup(); pMergedGroup->Name = "merged"; for (uint32 i = 0; i < m_arrSourceGroups.GetSize(); i++) { m_pProgressCallbacks->DisplayFormattedInformation(" merging group '%s'", m_arrSourceGroups[i]->Name.GetCharArray()); pMergedGroup->Faces.AddRange(m_arrSourceGroups[i]->Faces.GetBasePointer(), m_arrSourceGroups[i]->Faces.GetSize()); delete m_arrSourceGroups[i]; } m_arrSourceGroups.Clear(); m_arrSourceGroups.Add(pMergedGroup); } bool OBJImporter::GenerateTriangles() { uint32 totalVertexCount = 0; uint32 totalTriangleCount = 0; PODArray<uint32> GeneratedVertexSmoothingGroups; GeneratedVertexSmoothingGroups.Reserve(m_arrSourceVertices.GetSize()); bool FlipWinding = false; float4x4 ConversionMatrix(float4x4::Identity); // coordinate system change if (m_pOptions->CoordinateSystem != ENGINE_COORDINATE_SYSTEM) ConversionMatrix = m_pOptions->TransformMatrix * float4x4::MakeCoordinateSystemConversionMatrix(m_pOptions->CoordinateSystem, ENGINE_COORDINATE_SYSTEM, &FlipWinding); else ConversionMatrix = m_pOptions->TransformMatrix; if (m_pOptions->FlipWinding) FlipWinding = !FlipWinding; m_pProgressCallbacks->SetProgressRange(m_arrSourceGroups.GetSize()); m_pProgressCallbacks->SetProgressValue(0); for (uint32 i = 0; i < m_arrSourceGroups.GetSize(); i++) { const SourceGroup *pSourceGroup = m_arrSourceGroups[i]; m_pProgressCallbacks->DisplayFormattedInformation(" processing group '%s'...", pSourceGroup->Name.GetCharArray()); OutputMesh *pMesh = new OutputMesh(); pMesh->Vertices.Reserve(m_arrSourceVertices.GetSize()); pMesh->Triangles.Reserve(pMesh->Triangles.GetSize() + pSourceGroup->Faces.GetSize() * OBJIMPORTER_MAX_VERTICES_PER_FACE); pMesh->Translation.SetZero(); m_arrOutputMeshes.Add(pMesh); GeneratedVertexSmoothingGroups.Clear(); // generate mesh name pMesh->Name = pSourceGroup->Name; Resource::SanitizeResourceName(pMesh->Name); pMesh->Name.PrependFormattedString("%s/%s", m_pOptions->MeshDirectory.GetCharArray(), m_pOptions->MeshPrefix.GetCharArray()); // add faces for (uint32 j = 0; j < pSourceGroup->Faces.GetSize(); j++) { const SourceFace *pSourceFace = &pSourceGroup->Faces[j]; // add vertices uint32 OutputVertexIndicies[OBJIMPORTER_MAX_VERTICES_PER_FACE]; for (uint32 k = 0; k < pSourceFace->NumVertices; k++) { DebugAssert((uint32)pSourceFace->VertexIndicies[k] < m_arrSourceVertices.GetSize()); float3 SourceVertex = m_arrSourceVertices[pSourceFace->VertexIndicies[k]]; float2 SourceTexCoord = float2::Zero; if (pSourceFace->TexCoordIndices[k] >= 0) { DebugAssert((uint32)pSourceFace->TexCoordIndices[k] < m_arrSourceTexCoords.GetSize()); SourceTexCoord = m_arrSourceTexCoords[pSourceFace->TexCoordIndices[k]]; } // apply transform SourceVertex = (ConversionMatrix * float4(SourceVertex, 1.0f)).xyz(); // if smoothing groups are enabled, search for a matching vertex, otherwise insert a new one uint32 l; if (m_pOptions->UseSmoothingGroups && pSourceFace->SmoothingGroups != 0) { for (l = 0; l < pMesh->Vertices.GetSize(); l++) { if ((GeneratedVertexSmoothingGroups[l] & pSourceFace->SmoothingGroups) != 0 && pMesh->Vertices[l].Position == SourceVertex && pMesh->Vertices[l].TexCoord == SourceTexCoord) { GeneratedVertexSmoothingGroups[l] |= pSourceFace->SmoothingGroups; break; } } } else { l = pMesh->Vertices.GetSize(); } if (l == pMesh->Vertices.GetSize()) { // add a new one OutputVertex ov; ov.Position = SourceVertex; ov.TexCoord = SourceTexCoord; pMesh->Vertices.Add(ov); GeneratedVertexSmoothingGroups.Add(pSourceFace->SmoothingGroups); totalVertexCount++; } // and store OutputVertexIndicies[k] = l; } // add indices for (uint32 k = 2; k < pSourceFace->NumVertices; k++) { OutputTriangle tri; if (FlipWinding) { tri.Indices[0] = OutputVertexIndicies[0]; tri.Indices[1] = OutputVertexIndicies[k]; tri.Indices[2] = OutputVertexIndicies[k - 1]; } else { tri.Indices[0] = OutputVertexIndicies[0]; tri.Indices[1] = OutputVertexIndicies[k - 1]; tri.Indices[2] = OutputVertexIndicies[k]; } tri.MaterialIndex = pSourceFace->MaterialIndex; pMesh->Triangles.Add(tri); totalTriangleCount++; } // reduce storage size pMesh->Vertices.Shrink(); pMesh->Triangles.Shrink(); } m_pProgressCallbacks->SetProgressValue(i); } m_pProgressCallbacks->DisplayFormattedInformation("Generated %u vertices, %u triangles.", totalVertexCount, totalTriangleCount); return true; } bool OBJImporter::WriteOutput() { String outputMeshName; String outputMeshFileName; PODArray<int32> batchIndices; batchIndices.Reserve(m_arrOutputMaterials.GetSize()); for (uint32 i = 0; i < m_arrOutputMeshes.GetSize(); i++) { OutputMesh *pOutputMesh = m_arrOutputMeshes[i]; batchIndices.Clear(); for (uint32 j = 0; j < m_arrOutputMaterials.GetSize(); j++) batchIndices.Add(-1); // create new mesh StaticMeshGenerator staticMeshGenerator; staticMeshGenerator.Create((m_arrSourceTexCoords.GetSize() > 0), false); uint32 lodIndex = staticMeshGenerator.AddLOD(); // vertices const OutputVertex *pSourceVertex = pOutputMesh->Vertices.GetBasePointer(); for (uint32 j = 0; j < pOutputMesh->Vertices.GetSize(); j++) { staticMeshGenerator.AddVertex(lodIndex, pSourceVertex->Position, float3::Zero, float3::Zero, float3::Zero, pSourceVertex->TexCoord, 0); pSourceVertex++; } // triangles const OutputTriangle *pSourceTriangle = pOutputMesh->Triangles.GetBasePointer(); for (uint32 j = 0; j < pOutputMesh->Triangles.GetSize(); j++) { int32 batchIndex = batchIndices[pSourceTriangle->MaterialIndex]; if (batchIndex < 0) { batchIndex = staticMeshGenerator.AddBatch(lodIndex, m_arrOutputMaterials[pSourceTriangle->MaterialIndex]); batchIndices[pSourceTriangle->MaterialIndex] = batchIndex; } staticMeshGenerator.AddTriangle(lodIndex, batchIndex, pSourceTriangle->Indices[0], pSourceTriangle->Indices[1], pSourceTriangle->Indices[2]); pSourceTriangle++; } // center mesh? if (m_pOptions->CenterMeshes != StaticMeshGenerator::CenterOrigin_Count) staticMeshGenerator.CenterMesh((StaticMeshGenerator::CenterOrigin)m_pOptions->CenterMeshes, &pOutputMesh->Translation); // calculate tangent space vectors, bounds and batches staticMeshGenerator.GenerateTangents(0); staticMeshGenerator.CalculateBounds(); // build collision shape if (m_pOptions->BuildCollisionShapeType.CompareInsensitive("box")) { // build box staticMeshGenerator.BuildBoxCollisionShape(); } else if (m_pOptions->BuildCollisionShapeType.CompareInsensitive("sphere")) { // build sphere staticMeshGenerator.BuildSphereCollisionShape(); } else if (m_pOptions->BuildCollisionShapeType.CompareInsensitive("trianglemesh")) { // build triangle mesh staticMeshGenerator.BuildTriangleMeshCollisionShape(); } else if (m_pOptions->BuildCollisionShapeType.CompareInsensitive("convexhull")) { // build convex hull staticMeshGenerator.BuildConvexHullCollisionShape(); } else if (!m_pOptions->BuildCollisionShapeType.CompareInsensitive("none")) { m_pProgressCallbacks->DisplayFormattedWarning("invalid collision shape type: '%s', assuming none", m_pOptions->BuildCollisionShapeType.GetCharArray()); } // write out outputMeshFileName.Format("%s.staticmesh.xml", pOutputMesh->Name.GetCharArray()); ByteStream *pStream = g_pVirtualFileSystem->OpenFile(outputMeshFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE); if (pStream == NULL) { m_pProgressCallbacks->DisplayFormattedError("Could not open mesh output file '%s'", outputMeshFileName.GetCharArray()); continue; } if (!staticMeshGenerator.SaveToXML(pStream)) { m_pProgressCallbacks->DisplayFormattedError("Failed to save static mesh to XML file '%s'", outputMeshFileName.GetCharArray()); pStream->Release(); continue; } pStream->Release(); } return true; } bool OBJImporter::WriteMap() { // get template for StaticMeshBrush const ObjectTemplate *pStaticMeshTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("StaticMeshBrush"); if (pStaticMeshTemplate == nullptr) { m_pProgressCallbacks->DisplayError("Failed to get StaticMeshBrush template."); return false; } // create map MapSource *pMapSource = new MapSource(); pMapSource->Create(); // create objects for each mesh for (uint32 i = 0; i < m_arrOutputMeshes.GetSize(); i++) { OutputMesh *pOutputMesh = m_arrOutputMeshes[i]; // create entity MapSourceEntityData *pEntityData = pMapSource->CreateEntityFromTemplate(pStaticMeshTemplate); DebugAssert(pEntityData != nullptr); // set mesh name property pEntityData->SetPropertyValue("StaticMeshName", pOutputMesh->Name); // work out the transform float3 offsetPosition((pOutputMesh->Translation.SquaredLength() > 0.0f) ? -pOutputMesh->Translation : pOutputMesh->Translation); pEntityData->SetPropertyValueFloat3("Position", offsetPosition); } // write out the map bool result = pMapSource->SaveAs(m_pOptions->OutputMapName, m_pProgressCallbacks); delete pMapSource; return result; } <file_sep>/Engine/Source/GameFramework/RotationInterpolatorComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/RotationInterpolatorComponent.h" #include "Engine/Entity.h" Log_SetChannel(RotationInterpolatorComponent); DEFINE_COMPONENT_TYPEINFO(RotationInterpolatorComponent); DEFINE_COMPONENT_GENERIC_FACTORY(RotationInterpolatorComponent); BEGIN_COMPONENT_PROPERTIES(RotationInterpolatorComponent) PROPERTY_TABLE_MEMBER_FLOAT("MoveDuration", 0, offsetof(RotationInterpolatorComponent, m_moveDuration), PropertyCallbackOnMoveDurationChange, nullptr) PROPERTY_TABLE_MEMBER_FLOAT("PauseDuration", 0, offsetof(RotationInterpolatorComponent, m_pauseDuration),PropertyCallbackOnMoveDurationChange, nullptr) PROPERTY_TABLE_MEMBER_BOOL("ReverseCycle", 0, offsetof(RotationInterpolatorComponent, m_reverseCycle), PropertyCallbackOnReverseCycleChange, nullptr) PROPERTY_TABLE_MEMBER_UINT("RepeatCount", 0, offsetof(RotationInterpolatorComponent, m_repeatCount), PropertyCallbackOnRepeatCountChange, nullptr) PROPERTY_TABLE_MEMBER_UINT("EasingFunction", 0, offsetof(RotationInterpolatorComponent, m_easingFunction), PropertyCallbackOnEasingFunctionChange, nullptr) PROPERTY_TABLE_MEMBER_BOOL("AutoActivate", 0, offsetof(RotationInterpolatorComponent, m_autoActivate), PropertyCallbackOnAutoActivateChange, nullptr) END_COMPONENT_PROPERTIES() RotationInterpolatorComponent::RotationInterpolatorComponent(const ComponentTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_moveDuration(1.0f), m_pauseDuration(0.0f), m_reverseCycle(true), m_repeatCount(0), m_easingFunction(EasingFunction::Linear), m_autoActivate(true), m_active(false), m_interpolator(Quaternion::Identity, Quaternion::Identity, m_moveDuration, m_pauseDuration, m_reverseCycle, m_repeatCount, (EasingFunction::Type)m_easingFunction) { } RotationInterpolatorComponent::~RotationInterpolatorComponent() { } void RotationInterpolatorComponent::SetMoveDuration(float moveDuration) { if (m_moveDuration == moveDuration) return; m_moveDuration = moveDuration; PropertyCallbackOnMoveDurationChange(this); } void RotationInterpolatorComponent::SetPauseDuration(float pauseDuration) { if (m_pauseDuration == pauseDuration) return; m_pauseDuration = pauseDuration; PropertyCallbackOnPauseDurationChange(this); } void RotationInterpolatorComponent::SetReverseCycle(bool autoReverse) { if (m_reverseCycle == autoReverse) return; m_reverseCycle = autoReverse; PropertyCallbackOnReverseCycleChange(this); } void RotationInterpolatorComponent::SetRepeatCount(uint32 repeatCount) { if (m_repeatCount == repeatCount) return; m_repeatCount = repeatCount; PropertyCallbackOnRepeatCountChange(this); } void RotationInterpolatorComponent::SetEasingFunction(EasingFunction::Type easingFunction) { if (m_easingFunction == (uint32)easingFunction) return; m_easingFunction = (uint32)easingFunction; PropertyCallbackOnEasingFunctionChange(this); } void RotationInterpolatorComponent::SetAutoActivate(bool autoActivate) { if (m_autoActivate == autoActivate) return; m_autoActivate = autoActivate; PropertyCallbackOnAutoActivateChange(this); } void RotationInterpolatorComponent::Create(const Quaternion &rotationAmount /* = Quaternion::Identity */, float moveDuration /* = 1.0f */, float pauseDuration /* = 0.0f */, bool reverseCycle /* = true */, uint32 repeatCount /* = 0 */, EasingFunction::Type easingFunction /* = EasingFunction::Linear */, bool autoActivate /* = true */) { DebugAssert(moveDuration > 0.0f); m_localPosition = float3::Zero; m_localRotation = rotationAmount; m_localScale = float3::One; m_moveDuration = moveDuration; m_pauseDuration = pauseDuration; m_reverseCycle = reverseCycle; m_repeatCount = repeatCount; m_easingFunction = (uint32)easingFunction; m_autoActivate = autoActivate; Initialize(); } void RotationInterpolatorComponent::Reset() { m_interpolator.Reset(); if (m_pEntity != nullptr) m_pEntity->SetRotation(m_interpolator.GetCurrentValue()); } void RotationInterpolatorComponent::Activate() { if (!m_active) { m_active = true; if (IsAttachedToEntity()) m_pEntity->RegisterForUpdates(0.0f); } } void RotationInterpolatorComponent::Deactivate() { m_active = false; } bool RotationInterpolatorComponent::Initialize() { if (!BaseClass::Initialize()) return false; // initialize the interpolator DebugAssert(m_easingFunction < EasingFunction::TypeCount); m_interpolator.SetValues(Quaternion::Identity, m_localRotation); m_interpolator.SetMoveDuration(m_moveDuration); m_interpolator.SetPauseDuration(m_pauseDuration); m_interpolator.SetReverseCycle(m_reverseCycle); m_interpolator.SetRepeatCount(m_repeatCount); m_interpolator.SetFunction((EasingFunction::Type)m_easingFunction); m_interpolator.Reset(); return true; } void RotationInterpolatorComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // extract the starting position from the entity's current position m_interpolator.SetValues(m_pEntity->GetRotation(), m_pEntity->GetRotation() * m_localRotation); m_interpolator.Reset(); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate && pEntity->IsInWorld()) pEntity->RegisterForUpdates(0.0f); } void RotationInterpolatorComponent::OnRemoveFromEntity(Entity *pEntity) { // ensure we're deactivated m_active = false; // nuke the starting position m_interpolator.SetValues(m_pEntity->GetRotation(), m_localRotation); m_interpolator.Reset(); BaseClass::OnRemoveFromEntity(pEntity); } void RotationInterpolatorComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate || m_active) m_pEntity->RegisterForUpdates(0.0f); } void RotationInterpolatorComponent::OnRemoveFromWorld(World *pWorld) { BaseClass::OnRemoveFromWorld(pWorld); } void RotationInterpolatorComponent::OnLocalTransformChange() { BaseClass::OnLocalTransformChange(); // update the ending position only, the starting position will still be valid m_interpolator.SetEndValue(m_interpolator.GetStartValue() * m_localRotation); } void RotationInterpolatorComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // is this an actual change of entity position? if (m_pEntity->GetRotation() != m_interpolator.GetCurrentValue()) { // update the starting position, and ending position m_interpolator.SetValues(m_pEntity->GetRotation(), m_pEntity->GetRotation() * m_localRotation); } } void RotationInterpolatorComponent::Update(float timeSinceLastUpdate) { // this is where the magic happens if (!m_active && m_autoActivate) Activate(); // active? if (m_active) { // update interpolator m_interpolator.Update(timeSinceLastUpdate); // and the position if it should be updated if (m_pEntity->GetRotation() != m_interpolator.GetCurrentValue()) m_pEntity->SetRotation(m_interpolator.GetCurrentValue()); //Log_DevPrintf("value = %s", StringConverter::Vector3fToString(m_interpolator.GetCurrentValue().GetEulerAngles()).GetCharArray()); // if all cycles are complete, deactivate ourselves if (!m_interpolator.IsActive()) m_active = false; } } void RotationInterpolatorComponent::PropertyCallbackOnMoveDurationChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_interpolator.SetMoveDuration(pComponent->m_moveDuration); pComponent->Reset(); } void RotationInterpolatorComponent::PropertyCallbackOnPauseDurationChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_interpolator.SetPauseDuration(pComponent->m_pauseDuration); pComponent->Reset(); } void RotationInterpolatorComponent::PropertyCallbackOnReverseCycleChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_interpolator.SetReverseCycle(pComponent->m_reverseCycle); pComponent->Reset(); } void RotationInterpolatorComponent::PropertyCallbackOnRepeatCountChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { pComponent->m_interpolator.SetRepeatCount(pComponent->m_repeatCount); pComponent->Reset(); } void RotationInterpolatorComponent::PropertyCallbackOnEasingFunctionChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { DebugAssert(pComponent->m_easingFunction < EasingFunction::TypeCount); pComponent->m_interpolator.SetFunction((EasingFunction::Type)pComponent->m_easingFunction); pComponent->Reset(); } void RotationInterpolatorComponent::PropertyCallbackOnAutoActivateChange(RotationInterpolatorComponent *pComponent, const void *pUserData /*= nullptr*/) { if (pComponent->m_autoActivate && !pComponent->m_active && pComponent->IsAttachedToEntity()) pComponent->m_pEntity->RegisterForUpdates(0.0f); } <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2Defines.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2Common.h" #include "OpenGLES2Renderer/OpenGLES2GPUTexture.h" Log_SetChannel(OpenGLES2RenderBackend); #define GL_ERROR_NAME(s) Y_NameTable_Entry(#s, s) Y_Define_NameTable(NameTables::GLESErrors) GL_ERROR_NAME(GL_NO_ERROR) GL_ERROR_NAME(GL_INVALID_ENUM) GL_ERROR_NAME(GL_INVALID_VALUE) GL_ERROR_NAME(GL_INVALID_OPERATION) GL_ERROR_NAME(GL_STACK_OVERFLOW) GL_ERROR_NAME(GL_STACK_UNDERFLOW) GL_ERROR_NAME(GL_OUT_OF_MEMORY) Y_NameTable_End() GLenum g_eGLES2LastError = GL_NO_ERROR; void GLES2Renderer_PrintError(const char *Format, ...) { char buffer[1024]; va_list ap; va_start(ap, Format); Y_vsnprintf(buffer, countof(buffer), Format, ap); va_end(ap); if (g_eGLES2LastError != GL_NO_ERROR) Log_ErrorPrintf("%s%s (0x%X)", buffer, NameTable_GetNameString(NameTables::GLESErrors, g_eGLES2LastError), g_eGLES2LastError); else Log_ErrorPrintf("%sno error", buffer); } struct OpenGLTextureFormatMapping { GLint GLInternalFormat; GLenum GLFormat; GLenum GLType; bool IsCompressed; }; static const OpenGLTextureFormatMapping s_OpenGLTextureFormatMapping[PIXEL_FORMAT_COUNT] = { // // GLInternalFormat // GLFormat // GLType // IsCompressed { 0, 0, 0, false }, // PIXEL_FORMAT_R8_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R8_SINT { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R8_SNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8_SINT { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8_SNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8B8A8_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8B8A8_SINT { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R8G8B8A8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8B8A8_SNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R9G9B9E5_SHAREDEXP { 0, 0, 0, false }, // PIXEL_FORMAT_R10G10B10A2_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R10G10B10A2_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R11G11B10_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R16_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R16_SINT { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, false }, // PIXEL_FORMAT_R16_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R16_SNORM { GL_LUMINANCE, GL_LUMINANCE, GL_HALF_FLOAT_OES, false }, // PIXEL_FORMAT_R16_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16_SINT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16_SNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16B16A16_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16B16A16_SINT { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16B16A16_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_R16G16B16A16_SNORM { GL_RGBA, GL_RGBA, GL_HALF_FLOAT_OES, false }, // PIXEL_FORMAT_R16G16B16A16_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R32_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32_SINT { GL_LUMINANCE, GL_LUMINANCE, GL_FLOAT, false }, // PIXEL_FORMAT_R32_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32_SINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32B32_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32B32_SINT { GL_RGB, GL_RGB, GL_FLOAT, false }, // PIXEL_FORMAT_R32G32B32_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32B32A32_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32B32A32_SINT { 0, 0, 0, false }, // PIXEL_FORMAT_R32G32B32A32_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_B8G8R8A8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB { 0, 0, 0, false }, // PIXEL_FORMAT_B8G8R8X8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB { 0, 0, 0, false }, // PIXEL_FORMAT_B5G6R5_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_B5G5R5A1_UNORM { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC1_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_BC1_UNORM_SRGB { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC2_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_BC2_UNORM_SRGB { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true }, // PIXEL_FORMAT_BC3_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_BC3_UNORM_SRGB { 0, 0, 0, true }, // PIXEL_FORMAT_BC4_UNORM { 0, 0, 0, true }, // PIXEL_FORMAT_BC4_SNORM { 0, 0, 0, true }, // PIXEL_FORMAT_BC5_UNORM { 0, 0, 0, true }, // PIXEL_FORMAT_BC5_SNORM { 0, 0, 0, true }, // PIXEL_FORMAT_BC6H_UF16 { 0, 0, 0, true }, // PIXEL_FORMAT_BC6H_SF16 { 0, 0, 0, true }, // PIXEL_FORMAT_BC7_UNORM { 0, 0, 0, true }, // PIXEL_FORMAT_BC7_UNORM_SRGB { GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // PIXEL_FORMAT_D16_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_D24_UNORM_S8_UINT { GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // PIXEL_FORMAT_D32_FLOAT { 0, 0, 0, false }, // PIXEL_FORMAT_D32_FLOAT_S8X24_UINT { 0, 0, 0, false }, // PIXEL_FORMAT_R8G8B8_UNORM { 0, 0, 0, false }, // PIXEL_FORMAT_B8G8R8_UNORM }; bool OpenGLES2TypeConversion::GetOpenGLTextureFormat(PIXEL_FORMAT PixelFormat, GLint *pGLInternalFormat, GLenum *pGLFormat, GLenum *pGLType) { DebugAssert(PixelFormat < PIXEL_FORMAT_COUNT); const OpenGLTextureFormatMapping *pMapping = &s_OpenGLTextureFormatMapping[PixelFormat]; if (pMapping->GLFormat == 0) return false; if (pGLInternalFormat != nullptr) *pGLInternalFormat = pMapping->GLInternalFormat; if (pGLFormat != nullptr) *pGLFormat = pMapping->GLFormat; if (pGLType != nullptr) *pGLType = pMapping->GLType; return true; } struct OpenGLUniformShaderVertexElementTypeVAOMapping { GPU_VERTEX_ELEMENT_TYPE VertexElementType; bool IntegerType; GLenum GLType; GLint GLSize; GLboolean GLNormalized; }; static const OpenGLUniformShaderVertexElementTypeVAOMapping s_OpenGLUniformShaderVertexElementTypeVAOMapping[] = { // VertexElementType IntegerType GLType GLSize GLNormalized { GPU_VERTEX_ELEMENT_TYPE_BYTE, true, GL_BYTE, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_BYTE2, true, GL_BYTE, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_BYTE4, true, GL_BYTE, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE, true, GL_UNSIGNED_BYTE, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE2, true, GL_UNSIGNED_BYTE, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UBYTE4, true, GL_UNSIGNED_BYTE, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF, false, GL_HALF_FLOAT_OES, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF2, false, GL_HALF_FLOAT_OES, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_HALF4, false, GL_HALF_FLOAT_OES, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT, false, GL_FLOAT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT2, false, GL_FLOAT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT3, false, GL_FLOAT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_FLOAT4, false, GL_FLOAT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT, true, GL_INT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT2, true, GL_INT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT3, true, GL_INT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_INT4, true, GL_INT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT, true, GL_UNSIGNED_INT, 1, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT2, true, GL_UNSIGNED_INT, 2, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT3, true, GL_UNSIGNED_INT, 3, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_UINT4, true, GL_UNSIGNED_INT, 4, GL_FALSE }, { GPU_VERTEX_ELEMENT_TYPE_SNORM4, false, GL_BYTE, 4, GL_TRUE }, { GPU_VERTEX_ELEMENT_TYPE_UNORM4, false, GL_UNSIGNED_BYTE, 4, GL_TRUE }, }; void OpenGLES2TypeConversion::GetOpenGLVAOTypeAndSizeForVertexElementType(GPU_VERTEX_ELEMENT_TYPE elementType, bool *pIntegerType, GLenum *pGLType, GLint *pGLSize, GLboolean *pGLNormalized) { uint32 i; for (i = 0; i < countof(s_OpenGLUniformShaderVertexElementTypeVAOMapping); i++) { const OpenGLUniformShaderVertexElementTypeVAOMapping *pTypeMapping = &s_OpenGLUniformShaderVertexElementTypeVAOMapping[i]; if (pTypeMapping->VertexElementType == elementType) { *pIntegerType = pTypeMapping->IntegerType; *pGLType = pTypeMapping->GLType; *pGLSize = pTypeMapping->GLSize; *pGLNormalized = pTypeMapping->GLNormalized; return; } } Panic("Unhandled case!"); } GLenum OpenGLES2TypeConversion::GetOpenGLComparisonFunc(GPU_COMPARISON_FUNC ComparisonFunc) { static const GLenum OpenGLComparisonFuncs[GPU_COMPARISON_FUNC_COUNT] = { GL_NEVER, // RENDERER_COMPARISON_FUNC_NEVER GL_LESS, // RENDERER_COMPARISON_FUNC_LESS GL_EQUAL, // RENDERER_COMPARISON_FUNC_EQUAL GL_LEQUAL, // RENDERER_COMPARISON_FUNC_LESS_EQUAL GL_GREATER, // RENDERER_COMPARISON_FUNC_GREATER GL_NOTEQUAL, // RENDERER_COMPARISON_FUNC_NOT_EQUAL GL_GEQUAL, // RENDERER_COMPARISON_FUNC_GREATER_EQUAL GL_ALWAYS, // RENDERER_COMPARISON_FUNC_ALWAYS }; DebugAssert(ComparisonFunc < GPU_COMPARISON_FUNC_COUNT); return OpenGLComparisonFuncs[ComparisonFunc]; } GLenum OpenGLES2TypeConversion::GetOpenGLComparisonMode(TEXTURE_FILTER Filter) { DebugAssert(Filter < TEXTURE_FILTER_COUNT); //if (Filter >= TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT && Filter <= TEXTURE_FILTER_COMPARISON_ANISOTROPIC) //return GL_COMPARE_REF_TO_TEXTURE; //else return GL_NONE; } GLenum OpenGLES2TypeConversion::GetOpenGLTextureMinFilter(TEXTURE_FILTER Filter, bool hasMips) { static const GLenum OpenGLMinFilters[TEXTURE_FILTER_COUNT] = { GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_MAG_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_MIN_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_ANISOTROPIC GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR GL_NEAREST_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT GL_NEAREST_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR_MIPMAP_NEAREST, // TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR GL_LINEAR_MIPMAP_LINEAR, // TEXTURE_FILTER_COMPARISON_ANISOTROPIC }; DebugAssert(Filter < TEXTURE_FILTER_COUNT); GLenum glFilter = OpenGLMinFilters[Filter]; if (!hasMips) { if (glFilter == GL_NEAREST_MIPMAP_NEAREST || glFilter == GL_NEAREST_MIPMAP_LINEAR) glFilter = GL_NEAREST; else glFilter = GL_LINEAR; } return glFilter; } GLenum OpenGLES2TypeConversion::GetOpenGLTextureMagFilter(TEXTURE_FILTER Filter) { static const GLenum GLOpenMagFilters[TEXTURE_FILTER_COUNT] = { GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT GL_NEAREST, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT GL_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR GL_LINEAR, // RENDERER_TEXTURE_FILTER_ANISOTROPIC }; DebugAssert(Filter < TEXTURE_FILTER_COUNT); return GLOpenMagFilters[Filter]; } GLenum OpenGLES2TypeConversion::GetOpenGLTextureWrap(TEXTURE_ADDRESS_MODE AddressMode) { static const GLenum OpenGLTextureAddresses[TEXTURE_ADDRESS_MODE_COUNT] = { GL_REPEAT, // RENDERER_TEXTURE_ADDRESS_WRAP GL_MIRRORED_REPEAT, // RENDERER_TEXTURE_ADDRESS_MIRROR GL_CLAMP_TO_EDGE, // RENDERER_TEXTURE_ADDRESS_CLAMP GL_CLAMP_TO_EDGE, // RENDERER_TEXTURE_ADDRESS_BORDER // FIXME GL_MIRRORED_REPEAT, // RENDERER_TEXTURE_ADDRESS_MIRROR_ONCE // FIXME }; DebugAssert(AddressMode < TEXTURE_ADDRESS_MODE_COUNT); return OpenGLTextureAddresses[AddressMode]; } GLenum OpenGLES2TypeConversion::GetOpenGLCullFace(RENDERER_CULL_MODE CullMode) { static const GLenum OpenGLCullModes[RENDERER_CULL_MODE_COUNT] = { GL_BACK, // RENDERER_CULL_NONE GL_FRONT, // RENDERER_CULL_FRONT GL_BACK, // RENDERER_CULL_BACK }; DebugAssert(CullMode < RENDERER_CULL_MODE_COUNT); return OpenGLCullModes[CullMode]; } GLenum OpenGLES2TypeConversion::GetOpenGLStencilOp(RENDERER_STENCIL_OP StencilOp) { static const GLenum OpenGLStencilOps[RENDERER_STENCIL_OP_COUNT] = { GL_KEEP, // RENDERER_STENCIL_OP_KEEP GL_ZERO, // RENDERER_STENCIL_OP_ZERO GL_REPLACE, // RENDERER_STENCIL_OP_REPLACE GL_INCR_WRAP, // RENDERER_STENCIL_OP_INCREMENT_CLAMPED GL_DECR_WRAP, // RENDERER_STENCIL_OP_DECREMENT_CLAMPED GL_INVERT, // RENDERER_STENCIL_OP_INVERT GL_INCR, // RENDERER_STENCIL_OP_INCREMENT GL_DECR, // RENDERER_STENCIL_OP_DECREMENT }; DebugAssert(StencilOp < RENDERER_STENCIL_OP_COUNT); return OpenGLStencilOps[StencilOp]; } GLenum OpenGLES2TypeConversion::GetOpenGLBlendEquation(RENDERER_BLEND_OP BlendOp) { static const GLenum OpenGLBlendEquations[RENDERER_BLEND_OP_COUNT] = { GL_FUNC_ADD, // RENDERER_BLEND_OP_ADD GL_FUNC_SUBTRACT, // RENDERER_BLEND_OP_SUBTRACT GL_FUNC_REVERSE_SUBTRACT, // RENDERER_BLEND_OP_REV_SUBTRACT GL_FUNC_ADD, // RENDERER_BLEND_OP_MIN FIXME GL_FUNC_ADD, // RENDERER_BLEND_OP_MAX FIXME }; DebugAssert(BlendOp < RENDERER_BLEND_OP_COUNT); return OpenGLBlendEquations[BlendOp]; } GLenum OpenGLES2TypeConversion::GetOpenGLBlendFunc(RENDERER_BLEND_OPTION BlendFactor) { static const GLenum OpenGLBlendFuncs[RENDERER_BLEND_OPTION_COUNT] = { GL_ZERO, // RENDERER_BLEND_ZERO GL_ONE, // RENDERER_BLEND_ONE GL_SRC_COLOR, // RENDERER_BLEND_SRC_COLOR GL_ONE_MINUS_SRC_COLOR, // RENDERER_BLEND_INV_SRC_COLOR GL_SRC_ALPHA, // RENDERER_BLEND_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA, // RENDERER_BLEND_INV_SRC_ALPHA GL_DST_ALPHA, // RENDERER_BLEND_DEST_ALPHA GL_ONE_MINUS_DST_ALPHA, // RENDERER_BLEND_INV_DEST_ALPHA GL_DST_COLOR, // RENDERER_BLEND_DEST_COLOR GL_ONE_MINUS_DST_COLOR, // RENDERER_BLEND_INV_DEST_COLOR GL_SRC_ALPHA_SATURATE, // RENDERER_BLEND_SRC_ALPHA_SAT GL_CONSTANT_COLOR, // RENDERER_BLEND_BLEND_FACTOR GL_ONE_MINUS_CONSTANT_COLOR, // RENDERER_BLEND_INV_BLEND_FACTOR GL_ZERO, // RENDERER_BLEND_SRC1_COLOR FIXME GL_ZERO, // RENDERER_BLEND_INV_SRC1_COLOR FIXME GL_ZERO, // RENDERER_BLEND_SRC1_ALPHA FIXME GL_ZERO, // RENDERER_BLEND_INV_SRC1_ALPHA FIXME }; DebugAssert(BlendFactor < RENDERER_BLEND_OPTION_COUNT); return OpenGLBlendFuncs[BlendFactor]; } GLenum OpenGLES2TypeConversion::GetOpenGLTextureTarget(TEXTURE_TYPE textureType) { switch (textureType) { case TEXTURE_TYPE_2D: return GL_TEXTURE_2D; case TEXTURE_TYPE_CUBE: return GL_TEXTURE_CUBE_MAP; } Panic("Unhandled type"); return GL_TEXTURE_2D; } GLenum OpenGLES2Helpers::GetOpenGLTextureTarget(GPUTexture *pGPUTexture) { if (pGPUTexture == NULL) return 0; switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE2D: return GL_TEXTURE_2D; case GPU_RESOURCE_TYPE_TEXTURECUBE: return GL_TEXTURE_CUBE_MAP; } return 0; } GLuint OpenGLES2Helpers::GetOpenGLTextureId(GPUTexture *pGPUTexture) { if (pGPUTexture == NULL) return 0; switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<OpenGLES2GPUTexture2D *>(pGPUTexture)->GetGLTextureId(); case GPU_RESOURCE_TYPE_TEXTURECUBE: return static_cast<OpenGLES2GPUTextureCube *>(pGPUTexture)->GetGLTextureId(); } return 0; } void OpenGLES2Helpers::BindOpenGLTexture(GPUTexture *pGPUTexture) { if (pGPUTexture == nullptr) { glBindTexture(GL_TEXTURE_2D, 0); return; } switch (pGPUTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE2D: glBindTexture(GL_TEXTURE_2D, static_cast<OpenGLES2GPUTexture2D *>(pGPUTexture)->GetGLTextureId()); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: glBindTexture(GL_TEXTURE_CUBE_MAP, static_cast<OpenGLES2GPUTextureCube *>(pGPUTexture)->GetGLTextureId()); break; } } void OpenGLES2Helpers::GLUniformWrapper(SHADER_PARAMETER_TYPE type, GLuint location, GLuint arraySize, const void *pValue) { // Invoke the appropriate glUniform() command switch (type) { case SHADER_PARAMETER_TYPE_BOOL: glUniform1iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL2: glUniform2iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL3: glUniform3iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_BOOL4: glUniform4iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT: glUniform1iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT2: glUniform2iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT3: glUniform3iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; case SHADER_PARAMETER_TYPE_INT4: glUniform4iv(location, arraySize, reinterpret_cast<const GLint *>(pValue)); break; // case SHADER_PARAMETER_TYPE_UINT: // glUniform1uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); // break; // // case SHADER_PARAMETER_TYPE_UINT2: // glUniform2uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); // break; // // case SHADER_PARAMETER_TYPE_UINT3: // glUniform3uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); // break; // // case SHADER_PARAMETER_TYPE_UINT4: // glUniform4uiv(location, arraySize, reinterpret_cast<const GLuint *>(pValue)); // break; case SHADER_PARAMETER_TYPE_FLOAT: glUniform1fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT2: glUniform2fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3: glUniform3fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT4: glUniform4fv(location, arraySize, reinterpret_cast<const GLfloat *>(pValue)); break; #if defined(Y_PLATFORM_HTML5) // WebGL does not support in-flight transposition. We have to handle it ourselves. case SHADER_PARAMETER_TYPE_FLOAT2X2: { const float *source = reinterpret_cast<const float *>(pValue); for (uint32 i = 0; i < arraySize; i++) { float transposed[4]; transposed[0] = source[0]; transposed[2] = source[1]; transposed[1] = source[2]; transposed[3] = source[3]; glUniformMatrix2fv(location + i, 1, GL_FALSE, transposed); source += 4; } } break; case SHADER_PARAMETER_TYPE_FLOAT3X3: { const float *source = reinterpret_cast<const float *>(pValue); for (uint32 i = 0; i < arraySize; i++) { float transposed[9]; transposed[0] = source[0]; transposed[3] = source[1]; transposed[6] = source[2]; transposed[1] = source[3]; transposed[4] = source[4]; transposed[7] = source[5]; transposed[2] = source[6]; transposed[5] = source[7]; transposed[8] = source[8]; glUniformMatrix3fv(location + i, 1, GL_FALSE, transposed); source += 9; } } break; // SHADER_PARAMETER_TYPE_FLOAT3X4 unsupported case SHADER_PARAMETER_TYPE_FLOAT4X4: { const float *source = reinterpret_cast<const float *>(pValue); for (uint32 i = 0; i < arraySize; i++) { float transposed[16]; transposed[0] = source[0]; transposed[4] = source[1]; transposed[8] = source[2]; transposed[12] = source[3]; transposed[1] = source[4]; transposed[5] = source[5]; transposed[9] = source[6]; transposed[13] = source[7]; transposed[2] = source[8]; transposed[6] = source[9]; transposed[10] = source[10]; transposed[14] = source[11]; transposed[3] = source[12]; transposed[7] = source[13]; transposed[11] = source[14]; transposed[15] = source[15]; glUniformMatrix4fv(location + i, 1, GL_FALSE, transposed); source += 16; } } break; #else // Y_PLATFORM_HTML5 case SHADER_PARAMETER_TYPE_FLOAT2X2: glUniformMatrix2fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; case SHADER_PARAMETER_TYPE_FLOAT3X3: glUniformMatrix3fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; // case SHADER_PARAMETER_TYPE_FLOAT3X4: // glUniformMatrix4x3fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); // break; case SHADER_PARAMETER_TYPE_FLOAT4X4: glUniformMatrix4fv(location, arraySize, GL_TRUE, reinterpret_cast<const GLfloat *>(pValue)); break; #endif // Y_PLATFORM_HTML5 } } void OpenGLES2Helpers::SetObjectDebugName(GLenum type, GLuint id, const char *debugName) { #if defined(GL_KHR_debug) && defined(Y_BUILD_CONFIG_DEBUG) if (GLAD_GL_KHR_debug) { uint32 length = Y_strlen(debugName); if (length > 0) glObjectLabelKHR(type, id, length, debugName); } #endif } <file_sep>/Engine/Source/Engine/Physics/PhysicsWorld.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/PhysicsProxy.h" #include "Engine/Physics/BulletHeaders.h" #include "Engine/Physics/CollisionObject.h" #include "Engine/EngineCVars.h" Log_SetChannel(PhysicsWorld); namespace Physics { PhysicsWorld::PhysicsWorld() : m_gravity(0.0f, 0.0f, -10.0f), m_pBulletWorld(nullptr), m_pBulletCollisionConfiguration(nullptr), m_pBulletCollisionDispatcher(nullptr), m_pBulletBroadphase(nullptr), m_pBulletGhostPairCallback(nullptr) { m_pBulletCollisionConfiguration = new btDefaultCollisionConfiguration(); m_pBulletCollisionDispatcher = new btCollisionDispatcher(m_pBulletCollisionConfiguration); m_pBulletBroadphase = new btDbvtBroadphase(); m_pBulletSolver = new btSequentialImpulseConstraintSolver(); m_pBulletWorld = new btDiscreteDynamicsWorld(m_pBulletCollisionDispatcher, m_pBulletBroadphase, m_pBulletSolver, m_pBulletCollisionConfiguration); m_pBulletWorld->setGravity(Float3ToBulletVector(m_gravity)); m_pBulletWorld->setForceUpdateAllAabbs(false); // why the hell is this on by default? m_pBulletGhostPairCallback = new btGhostPairCallback(); m_pBulletBroadphase->getOverlappingPairCache()->setInternalGhostPairCallback(m_pBulletGhostPairCallback); } PhysicsWorld::~PhysicsWorld() { /* // remove everything in queues for (uint32 i = 0; i < m_addQueue.GetSize(); i++) { CollisionObject *pCollisionObject = m_addQueue[i]; pCollisionObject->m_pPhysicsWorld = NULL; for (uint32 j = 0; j < m_removeQueue.GetSize(); j++) { if (m_removeQueue[j] == pCollisionObject) { m_removeQueue.OrderedRemove(j); break; } } pCollisionObject->Release(); } m_addQueue.Obliterate(); for (uint32 i = 0; i < m_removeQueue.GetSize(); i++) { CollisionObject *pCollisionObject = m_removeQueue[i]; CollisionObjectList::Iterator itr; for (itr = m_collisionObjects.Begin(); !itr.AtEnd(); itr.Forward()) { if (*itr == pCollisionObject) break; } Assert(!itr.AtEnd()); m_collisionObjects.Erase(itr); pCollisionObject->OnRemovedFromPhysicsWorld(this); pCollisionObject->m_pPhysicsWorld = NULL; pCollisionObject->Release(); } m_removeQueue.Obliterate(); */ // remove everything in world while (m_collisionObjects.GetSize() > 0) { PhysicsProxy *pPhysicsProxy = m_collisionObjects.PopBack(); pPhysicsProxy->OnRemovedFromPhysicsWorld(this); pPhysicsProxy->Release(); } // the synch queue can just be wiped m_synchronizationQueue.Obliterate(); // cleanup bullet delete m_pBulletWorld; delete m_pBulletSolver; delete m_pBulletBroadphase; delete m_pBulletCollisionDispatcher; delete m_pBulletCollisionConfiguration; delete m_pBulletGhostPairCallback; } void PhysicsWorld::SetGravity(const float3 &gravity) { m_gravity = gravity; // update bullet m_pBulletWorld->setGravity(Float3ToBulletVector(m_gravity)); } void PhysicsWorld::AddObject(PhysicsProxy *pPhysicsProxy) { /* DebugAssert(pCollisionObject->m_pPhysicsWorld == NULL); uint32 i; for (i = 0; i < m_addQueue.GetSize(); i++) { if (m_addQueue[i] == pCollisionObject) break; } if (i == m_addQueue.GetSize()) { pCollisionObject->AddRef(); m_addQueue.Add(pCollisionObject); }*/ DebugAssert(m_collisionObjects.IndexOf(pPhysicsProxy) < 0); m_collisionObjects.Add(pPhysicsProxy); pPhysicsProxy->OnAddedToPhysicsWorld(this); } void PhysicsWorld::RemoveObject(PhysicsProxy *pPhysicsProxy) { /* DebugAssert(pCollisionObject->m_pPhysicsWorld == this); uint32 i; for (i = 0; i < m_removeQueue.GetSize(); i++) { if (m_removeQueue[i] == pCollisionObject) break; } if (i == m_removeQueue.GetSize()) m_removeQueue.Add(pCollisionObject);*/ DebugAssert(pPhysicsProxy->GetPhysicsWorld() == this); int32 arrayIndex = m_collisionObjects.IndexOf(pPhysicsProxy); DebugAssert(arrayIndex >= 0); m_collisionObjects.OrderedRemove(arrayIndex); pPhysicsProxy->OnRemovedFromPhysicsWorld(this); } void PhysicsWorld::QueueObjectSynchronization(PhysicsProxy *pPhysicsProxy) { // bullet can have more than one simulation run in a frame, therefore this can actually be called >1 times if (m_synchronizationQueue.Contains(pPhysicsProxy)) return; m_synchronizationQueue.Add(pPhysicsProxy); } void PhysicsWorld::UpdateAsync(float timeSinceLastUpdate) { const float fixedTimeStep = 1.0f / CVars::physics_fps.GetFloat(); m_pBulletWorld->stepSimulation(timeSinceLastUpdate, 10, fixedTimeStep); } void PhysicsWorld::Update(float timeSinceLastUpdate) { // sync objects for (uint32 i = 0; i < m_synchronizationQueue.GetSize(); i++) m_synchronizationQueue[i]->OnSynchronize(); m_synchronizationQueue.Clear(); } bool PhysicsWorld::RayCast(const Ray &ray) const { const PhysicsProxy *pContactObject; float3 contactNormal; float3 contactPoint; return RayCast(ray, &pContactObject, &contactNormal, &contactPoint); } bool PhysicsWorld::RayCast(const Ray &ray, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const { btVector3 rayFrom(Float3ToBulletVector(ray.GetOrigin())); btVector3 rayTo(Float3ToBulletVector(ray.GetEnd())); btCollisionWorld::ClosestRayResultCallback result(rayFrom, rayTo); m_pBulletWorld->rayTest(rayFrom, rayTo, result); if (!result.hasHit()) return false; *ppContactObject = reinterpret_cast<const PhysicsProxy *>(result.m_collisionObject->getUserPointer()); *pContactNormal = BulletVector3ToFloat3(result.m_hitNormalWorld); *pContactPoint = BulletVector3ToFloat3(result.m_hitPointWorld); return true; } bool PhysicsWorld::TestAABoxIntersection(const AABox &box) const { const PhysicsProxy *pContactObject; float3 contactNormal; float3 contactPoint; return TestAABoxIntersection(box, &pContactObject, &contactNormal, &contactPoint); } bool PhysicsWorld::TestAABoxIntersection(const AABox &box, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const { /* struct ResultCallback : public btBroadphaseAabbCallback { ResultCallback(btCollisionWorld *collisionWorld, const AABox &box) : pCollisionWorld(collisionWorld), bulletBoxShape(Float3ToBulletVector(box.GetExtents()) * 0.5f) { bulletCollisionObject.setCollisionShape(&bulletBoxShape); bulletCollisionObject.setWorldTransform(btTransform(btQuaternion::getIdentity(), Float3ToBulletVector(box.GetCenter()))); } virtual bool process(const btBroadphaseProxy* proxy) { // find the bullet object btCollisionObject *pBulletCollisionObject = reinterpret_cast<btCollisionObject *>(proxy->m_clientObject); DebugAssert(pBulletCollisionObject != nullptr); // collide the two objects } btCollisionWorld *pCollisionWorld; btBoxShape bulletBoxShape; btCollisionObject bulletCollisionObject; btCollisionWorld::ClosestConvexResultCallback result; };*/ // create a temporary bullet shape on the stack // construct a bullet transform for the box (ie center of it) float3 boxExtents(box.GetExtents()); float3 boxCenter(box.GetCenter()); btBoxShape bulletBoxShape(Float3ToBulletVector(boxExtents) * 0.5f); btTransform bulletTransform(btQuaternion::getIdentity(), Float3ToBulletVector(boxCenter)); // sweep it against the world btCollisionWorld::ClosestConvexResultCallback result(Float3ToBulletVector(boxCenter), Float3ToBulletVector(boxCenter)); m_pBulletWorld->convexSweepTest(&bulletBoxShape, bulletTransform, bulletTransform, result); // got a result? if (!result.hasHit()) return false; // store results *ppContactObject = reinterpret_cast<const PhysicsProxy *>(result.m_hitCollisionObject->getUserPointer()); *pContactNormal = BulletVector3ToFloat3(result.m_hitNormalWorld); *pContactPoint = BulletVector3ToFloat3(result.m_hitPointWorld); return true; } bool PhysicsWorld::TestSphereIntersection(const Sphere &sphere) const { const PhysicsProxy *pContactObject; float3 contactNormal; float3 contactPoint; return TestSphereIntersection(sphere, &pContactObject, &contactNormal, &contactPoint); } bool PhysicsWorld::TestSphereIntersection(const Sphere &sphere, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint) const { // create a temporary bullet shape on the stack // construct a bullet transform for the box (ie center of it) btSphereShape bulletBoxShape(sphere.GetRadius()); btTransform bulletTransform(btQuaternion::getIdentity(), Float3ToBulletVector(sphere.GetCenter())); // sweep it against the world btCollisionWorld::ClosestConvexResultCallback result(Float3ToBulletVector(sphere.GetCenter()), Float3ToBulletVector(sphere.GetCenter())); m_pBulletWorld->convexSweepTest(&bulletBoxShape, bulletTransform, bulletTransform, result); // got a result? if (!result.hasHit()) return false; // store results *ppContactObject = reinterpret_cast<const PhysicsProxy *>(result.m_hitCollisionObject->getUserPointer()); *pContactNormal = BulletVector3ToFloat3(result.m_hitNormalWorld); *pContactPoint = BulletVector3ToFloat3(result.m_hitPointWorld); return true; } bool PhysicsWorld::SweepBox(const float3 &boxHalfExtents, const float3 &from, const float3 &to, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint, float *pHitFraction) const { // create a temporary bullet shape on the stack // construct a bullet transform for the box (ie center of it) btBoxShape bulletBoxShape(Float3ToBulletVector(boxHalfExtents)); btTransform bulletTransformFrom(btQuaternion::getIdentity(), Float3ToBulletVector(from)); btTransform bulletTransformTo(btQuaternion::getIdentity(), Float3ToBulletVector(to)); // sweep it against the world btCollisionWorld::ClosestConvexResultCallback result(bulletTransformFrom.getOrigin(), bulletTransformTo.getOrigin()); m_pBulletWorld->convexSweepTest(&bulletBoxShape, bulletTransformFrom, bulletTransformTo, result); // got a result? if (!result.hasHit()) return false; // store results *ppContactObject = reinterpret_cast<const PhysicsProxy *>(result.m_hitCollisionObject->getUserPointer()); *pContactNormal = BulletVector3ToFloat3(result.m_hitNormalWorld); *pContactPoint = BulletVector3ToFloat3(result.m_hitPointWorld); *pHitFraction = result.m_closestHitFraction; return true; } bool PhysicsWorld::SweepSphere(const float radius, const float3 &from, const float3 &to, const PhysicsProxy **ppContactObject, float3 *pContactNormal, float3 *pContactPoint, float *pHitFraction) const { // create a temporary bullet shape on the stack // construct a bullet transform for the box (ie center of it) btSphereShape bulletSphereShape(radius); btTransform bulletTransformFrom(btQuaternion::getIdentity(), Float3ToBulletVector(from)); btTransform bulletTransformTo(btQuaternion::getIdentity(), Float3ToBulletVector(to)); // sweep it against the world btCollisionWorld::ClosestConvexResultCallback result(bulletTransformFrom.getOrigin(), bulletTransformTo.getOrigin()); m_pBulletWorld->convexSweepTest(&bulletSphereShape, bulletTransformFrom, bulletTransformTo, result); // got a result? if (!result.hasHit()) return false; // store results *ppContactObject = reinterpret_cast<const PhysicsProxy *>(result.m_hitCollisionObject->getUserPointer()); *pContactNormal = BulletVector3ToFloat3(result.m_hitNormalWorld); *pContactPoint = BulletVector3ToFloat3(result.m_hitPointWorld); *pHitFraction = result.m_closestHitFraction; return true; } void PhysicsWorld::ApplyRadialForce(const float3 &center, float radius, float amount, float falloffRate) { // find aabbs in range btVector3 minAABB(Float3ToBulletVector(center) - btVector3(radius, radius, radius)); btVector3 maxAABB(Float3ToBulletVector(center) + btVector3(radius, radius, radius)); // callback struct OurBroadphaseAABBCallback : public btBroadphaseAabbCallback { btVector3 forceCenter; float forceAmount; float radiusSquared; OurBroadphaseAABBCallback(const btVector3 &forceCenter_, float forceAmount_, float radiusSquared_) : forceCenter(forceCenter_), forceAmount(forceAmount_), radiusSquared(radiusSquared_) { } virtual bool process(const btBroadphaseProxy *proxy) override { const btCollisionObject *object = reinterpret_cast<const btCollisionObject *>(proxy->m_clientObject); if (object != nullptr && object->getInternalType() == btCollisionObject::CO_RIGID_BODY) { btRigidBody *rigidBody = const_cast<btRigidBody *>(static_cast<const btRigidBody *>(object)); // skip anything out of range if ((rigidBody->getCenterOfMassPosition() - forceCenter).length2() < radiusSquared) { // transform to rigid body local space btVector3 forceCenterLocalSpace(rigidBody->getCenterOfMassTransform().invXform(forceCenter)); // get force vector btVector3 forceVector(-forceCenterLocalSpace.normalized() * forceAmount); // apply force vector if (forceVector.length2() > Y_FLT_EPSILON) { //Log_DevPrintf("apply %s, rel pos %s", StringConverter::Float3ToString(BulletVector3ToFloat3(forceVector)).GetCharArray(), StringConverter::Float3ToString(BulletVector3ToFloat3(forceCenterLocalSpace)).GetCharArray()); rigidBody->applyImpulse(forceVector, forceCenterLocalSpace); rigidBody->activate(); } } } return true; } }; OurBroadphaseAABBCallback callback(Float3ToBulletVector(center), amount, Math::Square(radius)); m_pBulletWorld->getBroadphase()->aabbTest(minAABB, maxAABB, callback); } void PhysicsWorld::UpdateSingleObject(CollisionObject *pCollisionObject) { m_pBulletWorld->updateSingleAabb(pCollisionObject->GetBulletCollisionObject()); WakeObjectsInBox(pCollisionObject->GetBoundingBox()); } void PhysicsWorld::WakeObjectsInBox(const AABox &box) { // find aabbs in range btVector3 minAABB(Float3ToBulletVector(box.GetMinBounds())); btVector3 maxAABB(Float3ToBulletVector(box.GetMaxBounds())); // callback struct WakeObjectAABBCallback : public btBroadphaseAabbCallback { virtual bool process(const btBroadphaseProxy *proxy) override { const btCollisionObject *object = reinterpret_cast<const btCollisionObject *>(proxy->m_clientObject); if (object != nullptr && object->getInternalType() == btCollisionObject::CO_RIGID_BODY) { btRigidBody *rigidBody = const_cast<btRigidBody *>(static_cast<const btRigidBody *>(object)); if (rigidBody->getActivationState() == ISLAND_SLEEPING) rigidBody->activate(); } return true; } }; // instantiate callback and run it WakeObjectAABBCallback callback; m_pBulletWorld->getBroadphase()->aabbTest(minAABB, maxAABB, callback); } } // namespace Physics <file_sep>/Engine/Source/Renderer/WorldRenderers/SSMShadowMapRenderer.h #pragma once #include "Renderer/RendererTypes.h" #include "Renderer/RenderQueue.h" class Camera; class RenderWorld; class SSMShadowMapRenderer { public: struct ShadowMapData { bool IsActive; GPUTexture2D *pShadowMapTexture; GPUDepthStencilBufferView *pShadowMapDSV; float4x4 ViewProjectionMatrix; }; public: SSMShadowMapRenderer(uint32 shadowMapResolution = 256, PIXEL_FORMAT shadowMapFormat = PIXEL_FORMAT_D16_UNORM); virtual ~SSMShadowMapRenderer(); const uint32 GetShadowMapResolution() const { return m_shadowMapResolution; } const PIXEL_FORMAT GetShadowMapFormat() const { return m_shadowMapFormat; } bool AllocateShadowMap(ShadowMapData *pShadowMapData); void FreeShadowMap(ShadowMapData *pShadowMapData); void DrawDirectionalShadowMap(GPUContext *pGPUContext, ShadowMapData *pShadowMapData, const RenderWorld *pRenderWorld, const Camera *pViewCamera, float shadowDistance, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); void DrawSpotShadowMap(GPUContext *pGPUContext, ShadowMapData *pShadowMapData, const RenderWorld *pRenderWorld, const Camera *pViewCamera, float shadowDistance, const RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight); private: uint32 m_shadowMapResolution; PIXEL_FORMAT m_shadowMapFormat; RenderQueue m_renderQueue; }; <file_sep>/Engine/Source/Engine/TerrainQuadTree.h #pragma once #include "Engine/Common.h" #include "Engine/TerrainTypes.h" #include "Engine/TerrainLayerList.h" class BinaryWriter; class TerrainManager; class TerrainSection; class TerrainQuadTreeNode; class TerrainQuadTreeQuery; class TerrainSectionQuadTree { public: friend class TerrainQuadTreeNode; friend class TerrainQuadTreeQuery; public: TerrainSectionQuadTree(const TerrainSection *pSection); ~TerrainSectionQuadTree(); const TerrainSection *GetSection() const { return m_pSection; } uint32 GetLODCount() const { return m_LODCount; } uint32 GetNodeCount() const { return m_nNodes; } const TerrainQuadTreeNode *GetTopLevelNode() const { return m_pNodes; } // building static bool Build(const TerrainParameters *pParameters, const TerrainSection *pSection, ByteStream *pOutputStream, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // loading bool LoadFromStream(ByteStream *pStream); // updating. if oldHeight is unknown, Y_FLT_INFINITE can be passed void UpdateMinMaxHeight(uint32 pointX, uint32 pointY, float newHeight, float oldHeight, bool *pNeedsRebuild); // saving bool SaveToStream(ByteStream *pOutputStream) const; // enumerate overlapping nodes template<typename CALLBACK_TYPE> void EnumerateNodesOverlappingBox(const AABox &searchBounds, uint32 maxLODLevel, CALLBACK_TYPE callback) const; // ray cast into quadtree template<typename CALLBACK_TYPE> void EnumerateNodesIntersectingRay(const Ray &ray, uint32 maxLODLevel, CALLBACK_TYPE callback) const; // find sections to render with callback template<typename CALLBACK_TYPE> void EnumerateNodesToRender(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], CALLBACK_TYPE callback) const; private: // building static void BuildTopLevel(TerrainQuadTreeNode *pNodeBuffer, uint32 &currentNodeIndex, uint32 allocatedNodeCount, const TerrainParameters *pParameters, const TerrainSection *pSection, ProgressCallbacks *pProgressCallbacks); static void BuildChildrenRecursive(TerrainQuadTreeNode *pNodeBuffer, uint32 &currentNodeIndex, uint32 allocatedNodeCount, TerrainQuadTreeNode *pSplittingNode, const TerrainParameters *pParameters, const TerrainSection *pSection, ProgressCallbacks *pProgressCallbacks); static bool SaveNodeBuffer(ByteStream *pStream, TerrainQuadTreeNode *pNodeBuffer, uint32 nodeCount, uint32 LODCount); // updating void UpdateMinMaxHeightRecursive(TerrainQuadTreeNode *pNode, uint32 pointX, uint32 pointY, float newHeight, float oldHeight, bool &needsRebuild); template<typename CALLBACK_TYPE> void RecursiveEnumerateNodesOverlappingBox(const AABox &searchBounds, uint32 maxLODLevel, CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode, bool parentCompletelyInBox) const; template<typename CALLBACK_TYPE> void RecursiveEnumerateNodesIntersectingRay(const Ray &ray, uint32 maxLODLevel, CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode) const; template<typename CALLBACK_TYPE> bool RecursiveEnumerateNodesToRender(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode, bool parentCompletelyInFrustum) const; private: const TerrainSection *m_pSection; uint32 m_LODCount; TerrainQuadTreeNode *m_pNodes; uint32 m_nNodes; }; class TerrainQuadTreeNode { friend class TerrainSectionQuadTree; public: enum ChildReference { ChildReferenceTopLeft, ChildReferenceTopRight, ChildReferenceBottomLeft, ChildReferenceBottomRight, }; public: const uint32 GetLODLevel() const { return m_LODLevel; } const uint32 GetStartQuadX() const { return m_startQuadX; } const uint32 GetStartQuadY() const { return m_startQuadY; } const uint32 GetNodeSize() const { return m_nodeSize; } const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } const bool IsLeafNode() const { return m_isLeafNode; } const bool IsFlat() const { return m_isFlat; } const TerrainQuadTreeNode *GetChildNode(uint32 child) const { DebugAssert(child < 4); return m_pChildNodes[child]; } private: // arrangement is strange yes, but it's best for memory usage (struct packing-wise) this way // child nodes TerrainQuadTreeNode *m_pChildNodes[4]; // bounds of this node AABox m_boundingBox; Sphere m_boundingSphere; // node parameters uint32 m_LODLevel; // point indices uint32 m_startQuadX; uint32 m_startQuadY; // node size in *quads* uint32 m_nodeSize; // leaf node flag bool m_isLeafNode; // reduce to single quad flag bool m_isFlat; }; class TerrainQuadTreeQuery { public: enum DRAW_FLAGS { DrawFlagTopLeft = (1 << 0), DrawFlagTopRight = (1 << 1), DrawFlagBottomLeft = (1 << 2), DrawFlagBottomRight = (1 << 3), DrawFlagSingleQuad = (1 << 4), DrawFlagAll = (DrawFlagTopLeft | DrawFlagTopRight | DrawFlagBottomLeft | DrawFlagBottomRight), }; struct SelectedNode { const TerrainSection *pSection; const TerrainQuadTreeNode *pNode; uint32 DrawFlags; }; public: TerrainQuadTreeQuery(); ~TerrainQuadTreeQuery(); void Invoke(const TerrainSection *const *ppSections, uint32 nSections, const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS]); const SelectedNode &GetSelectedNode(uint32 i) const { return m_selectedNodes[i]; } const uint32 GetSelectedNodeCount() const { return m_selectedNodes.GetSize(); } private: typedef MemArray<SelectedNode> SelectedNodeArray; SelectedNodeArray m_selectedNodes; bool ProcessNode(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], const TerrainSection *pSection, const TerrainQuadTreeNode *pNode, bool parentCompletelyInFrustum); }; template<typename CALLBACK_TYPE> void TerrainSectionQuadTree::EnumerateNodesOverlappingBox(const AABox &searchBounds, uint32 maxLODLevel, CALLBACK_TYPE callback) const { // start recursion const TerrainQuadTreeNode *pTopLevelNode = m_pNodes; if (pTopLevelNode->GetLODLevel() >= maxLODLevel) RecursiveEnumerateNodesOverlappingBox<CALLBACK_TYPE>(searchBounds, maxLODLevel, callback, pTopLevelNode); } template<typename CALLBACK_TYPE> void TerrainSectionQuadTree::RecursiveEnumerateNodesOverlappingBox(const AABox &searchBounds, uint32 maxLODLevel, CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode, bool parentCompletelyInBox) const { bool thisCompletelyInBox = parentCompletelyInBox; if (!parentCompletelyInBox) { thisCompletelyInBox = pNode->GetBoundingBox().ContainsAABox(searchBounds); if (!thisCompletelyInBox && !pNode->GetBoundingBox().AABoxIntersection(searchBounds)) return; } // stopping at this level? if (pNode->IsLeafNode() || maxLODLevel == pNode->GetLODLevel()) { callback(pNode); return; } // test children const TerrainQuadTreeNode *pChildNode; if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopLeft)) != NULL) RecursiveEnumerateNodesOverlappingBox<CALLBACK_TYPE>(searchBounds, maxLODLevel, callback, pChildNode, thisCompletelyInBox); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopRight)) != NULL) RecursiveEnumerateNodesOverlappingBox<CALLBACK_TYPE>(searchBounds, maxLODLevel, callback, pChildNode, thisCompletelyInBox); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomLeft)) != NULL) RecursiveEnumerateNodesOverlappingBox<CALLBACK_TYPE>(searchBounds, maxLODLevel, callback, pChildNode, thisCompletelyInBox); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomRight)) != NULL) RecursiveEnumerateNodesOverlappingBox<CALLBACK_TYPE>(searchBounds, maxLODLevel, callback, pChildNode, thisCompletelyInBox); } template<typename CALLBACK_TYPE> void TerrainSectionQuadTree::EnumerateNodesIntersectingRay(const Ray &ray, uint32 maxLODLevel, CALLBACK_TYPE callback) const { // start recursion const TerrainQuadTreeNode *pTopLevelNode = m_pNodes; if (pTopLevelNode->GetLODLevel() >= maxLODLevel) RecursiveEnumerateNodesIntersectingRay<CALLBACK_TYPE>(ray, maxLODLevel, callback, pTopLevelNode); } template<typename CALLBACK_TYPE> void TerrainSectionQuadTree::RecursiveEnumerateNodesIntersectingRay(const Ray &ray, uint32 maxLODLevel, CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode) const { if (!ray.AABoxIntersection(pNode->GetBoundingBox())) return; // stopping at this level? if (pNode->IsLeafNode() || maxLODLevel == pNode->GetLODLevel()) { callback(pNode); return; } // test children const TerrainQuadTreeNode *pChildNode; if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopLeft)) != NULL) RecursiveEnumerateNodesIntersectingRay<CALLBACK_TYPE>(ray, maxLODLevel, callback, pChildNode); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopRight)) != NULL) RecursiveEnumerateNodesIntersectingRay<CALLBACK_TYPE>(ray, maxLODLevel, callback, pChildNode); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomLeft)) != NULL) RecursiveEnumerateNodesIntersectingRay<CALLBACK_TYPE>(ray, maxLODLevel, callback, pChildNode); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomRight)) != NULL) RecursiveEnumerateNodesIntersectingRay<CALLBACK_TYPE>(ray, maxLODLevel, callback, pChildNode); } template<typename CALLBACK_TYPE> void TerrainSectionQuadTree::EnumerateNodesToRender(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], CALLBACK_TYPE callback) const { // frustum intersect the top level node const TerrainQuadTreeNode *pTopLevelNode = GetTopLevelNode(); Frustum::IntersectionType intersectionType = cameraFrustum.AABoxIntersectionType(pTopLevelNode->GetBoundingBox()); if (intersectionType != Frustum::INTERSECTION_TYPE_OUTSIDE) { bool completelyInFrustum = (intersectionType == Frustum::INTERSECTION_TYPE_INTERSECTS); RecursiveEnumerateNodesToRender<CALLBACK_TYPE>(cameraPosition, cameraFrustum, visibilityRanges, callback, pTopLevelNode, completelyInFrustum); } } template<typename CALLBACK_TYPE> bool TerrainSectionQuadTree::RecursiveEnumerateNodesToRender(const float3 &cameraPosition, const Frustum &cameraFrustum, const float visibilityRanges[TERRAIN_MAX_RENDER_LODS], CALLBACK_TYPE callback, const TerrainQuadTreeNode *pNode, bool parentCompletelyInFrustum) const { // frustum test it Frustum::IntersectionType intersectionType; if (parentCompletelyInFrustum) { // shortcut when parent is entirely in frustum intersectionType = Frustum::INTERSECTION_TYPE_INSIDE; } else { // have to calculate box and test it intersectionType = cameraFrustum.AABoxIntersectionType(pNode->GetBoundingBox()); } // outside frustum? if (intersectionType == Frustum::INTERSECTION_TYPE_OUTSIDE) { // return true to consume the node, preventing the parent from drawing it return true; } // out of range for this lod level? Sphere cameraSphere(cameraPosition, visibilityRanges[pNode->GetLODLevel()]); if (!pNode->GetBoundingBox().SphereIntersection(cameraSphere)) return false; // has lower levels? uint32 drawFlags = 0; if (pNode->IsLeafNode()) { // at lowest lod level, draw the whole thing //if (pNode->IsFlat()) //callback(pNode, TerrainQuadTreeQuery::DRAW_FLAG_SINGLE_QUAD); //else callback(pNode, TerrainQuadTreeQuery::DrawFlagAll); } else { // out of range for next lod level, if the parent is they all will be cameraSphere.SetRadius(visibilityRanges[pNode->GetLODLevel() - 1]); if (pNode->GetBoundingBox().SphereIntersection(cameraSphere)) { // test each of the children const TerrainQuadTreeNode *pChildNode; bool completelyInFrustum = (intersectionType == Frustum::INTERSECTION_TYPE_INSIDE); if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopLeft)) != NULL && !RecursiveEnumerateNodesToRender<CALLBACK_TYPE>(cameraPosition, cameraFrustum, visibilityRanges, callback, pChildNode, completelyInFrustum)) { drawFlags |= TerrainQuadTreeQuery::DrawFlagTopLeft; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceTopRight)) != NULL && !RecursiveEnumerateNodesToRender<CALLBACK_TYPE>(cameraPosition, cameraFrustum, visibilityRanges, callback, pChildNode, completelyInFrustum)) { drawFlags |= TerrainQuadTreeQuery::DrawFlagTopRight; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomLeft)) != NULL && !RecursiveEnumerateNodesToRender<CALLBACK_TYPE>(cameraPosition, cameraFrustum, visibilityRanges, callback, pChildNode, completelyInFrustum)) { drawFlags |= TerrainQuadTreeQuery::DrawFlagBottomLeft; } if ((pChildNode = pNode->GetChildNode(TerrainQuadTreeNode::ChildReferenceBottomRight)) != NULL && !RecursiveEnumerateNodesToRender<CALLBACK_TYPE>(cameraPosition, cameraFrustum, visibilityRanges, callback, pChildNode, completelyInFrustum)) { drawFlags |= TerrainQuadTreeQuery::DrawFlagBottomRight; } if (drawFlags != 0) callback(pNode, drawFlags); } else { // draw everything at this level callback(pNode, TerrainQuadTreeQuery::DrawFlagAll); } } // consume node return true; } <file_sep>/Engine/Source/BlockEngine/BlockWorld.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorld.h" #include "BlockEngine/BlockWorldSection.h" #include "BlockEngine/BlockWorldChunk.h" #include "BlockEngine/BlockWorldChunkRenderProxy.h" #include "BlockEngine/BlockWorldMesher.h" #include "BlockEngine/BlockEngineCVars.h" #include "BlockEngine/BlockWorldGenerator.h" #include "BlockEngine/BlockDrawTemplate.h" #include "Engine/ResourceManager.h" #include "Engine/Entity.h" #include "Engine/Engine.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/RigidBody.h" #include "Engine/Physics/BoxCollisionShape.h" #include "Renderer/RenderWorld.h" #include "Core/FIFVolume.h" Log_SetChannel(BlockWorld); #define USE_FIF 1 static const char *BLOCK_WORLD_INDEX_FILE_NAME = "index.bin"; static const char *BLOCK_WORLD_GLOBAL_ENTITIES_FILE_NAME = "global_entities.bin"; BlockWorld::BlockWorld() : World(), m_pFIFVolume(nullptr), m_pPalette(nullptr), m_pBlockDrawTemplate(nullptr), m_chunkSize(0), m_sectionSize(0), m_lodLevels(0), m_sectionSizeInBlocks(0), m_minSectionX(0), m_minSectionY(0), m_maxSectionX(0), m_maxSectionY(0), m_sectionCountX(0), m_sectionCountY(0), m_sectionCount(0), m_ppSections(nullptr), m_chunksMeshingInProgress(0), m_pGenerator(nullptr) { } BlockWorld::~BlockWorld() { // clear out animations for (uint32 blockAnimationIndex = 0; blockAnimationIndex < m_blockAnimations.GetSize(); blockAnimationIndex++) { BlockAnimation *pAnimation = &m_blockAnimations[blockAnimationIndex]; if (pAnimation->pRigidBody != nullptr) { m_pPhysicsWorld->RemoveObject(pAnimation->pRigidBody); pAnimation->pRigidBody->Release(); } m_pRenderWorld->RemoveRenderable(pAnimation->pRenderProxy); pAnimation->pRenderProxy->Release(); // todo: set block if it's still being animated? } delete m_pGenerator; SAFE_RELEASE(m_pBlockDrawTemplate); // unload sections UnloadAllSections(); for (int32 i = 0; i < m_sectionCount; i++) delete m_ppSections[i]; delete[] m_ppSections; // clean out entities while (m_globalEntityReferences.GetSize() > 0) { BlockWorldEntityReference &ref = m_globalEntityReferences[m_globalEntityReferences.GetSize() - 1]; RemoveEntity(ref.pEntity); } DebugAssert(m_entityHashTable.GetMemberCount() == 0); if (m_pPalette != nullptr) m_pPalette->Release(); #ifdef USE_FIF if (m_pFIFVolume != nullptr) delete m_pFIFVolume; #endif } bool BlockWorld::IsValidChunkSize(uint32 chunkSize, uint32 sectionSize, uint32 lodCount) { if (sectionSize <= 0 || chunkSize <= 0 || lodCount <= 0) return false; if (!Y_ispow2(chunkSize)) return false; if ((chunkSize >> (lodCount - 1)) == 0 || (sectionSize >> (lodCount - 1)) == 0) { return false; } return true; } int32 BlockWorld::GetSectionArrayIndex(int32 sectionX, int32 sectionY, int32 minSectionX, int32 minSectionY, int32 maxSectionX, int32 maxSectionY) { return ((sectionY - minSectionY) * (maxSectionX - minSectionX)) + (sectionX - minSectionX); } int32 BlockWorld::GetSectionArrayIndex(int32 sectionX, int32 sectionY) const { DebugAssert(sectionX >= m_minSectionX && sectionX <= m_maxSectionX && sectionY >= m_minSectionY && sectionY <= m_maxSectionY); return ((sectionY - m_minSectionY) * m_sectionCountX) + (sectionX - m_minSectionX); } bool BlockWorld::AllocateIndex() { m_sectionSizeInBlocks = m_chunkSize * m_sectionSize; m_renderGroupsPerSectionXY = m_sectionSize >> (m_lodLevels - 1); m_sectionCountX = m_maxSectionX - m_minSectionX + 1; m_sectionCountY = m_maxSectionY - m_minSectionY + 1; m_sectionCount = m_sectionCountX * m_sectionCountY; // allocate bitset m_availableSectionMask.Resize((uint32)m_sectionCount); m_availableSectionMask.Clear(); // and the array m_ppSections = new BlockWorldSection *[m_sectionCount]; Y_memzero(m_ppSections, sizeof(BlockWorldSection *)* m_sectionCount); // update world bounds AABox blockWorldBoundingBox = CalculateBlockWorldBoundingBox(); m_worldBoundingBox = blockWorldBoundingBox; m_worldBoundingSphere = Sphere::FromAABox(blockWorldBoundingBox); // create draw template if (g_pRenderer != nullptr) { m_pBlockDrawTemplate = new BlockDrawTemplate(m_pPalette); if (!m_pBlockDrawTemplate->Initialize()) return false; } return true; } void BlockWorld::ResizeIndex(int32 newMinSectionX, int32 newMinSectionY, int32 newMaxSectionX, int32 newMaxSectionY) { int32 newSectionCountX = (newMaxSectionX - newMinSectionX) + 1; int32 newSectionCountY = (newMaxSectionY - newMinSectionY) + 1; int32 newSectionCount = newSectionCountX * newSectionCountY; DebugAssert(newMinSectionX <= m_minSectionX && newMinSectionY <= m_minSectionY); DebugAssert(newMaxSectionX >= m_maxSectionX && newMaxSectionY >= m_maxSectionY); DebugAssert(newSectionCountX > 0 && newSectionCountY > 0); // build new bitset and array BitSet32 newAvailableSectionMask(newSectionCount); newAvailableSectionMask.Clear(); BlockWorldSection **ppNewSectionArray = new BlockWorldSection *[newSectionCount]; Y_memzero(ppNewSectionArray, sizeof(BlockWorldSection *) * newSectionCount); // fill new bitset/array for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 oldIndex = ((sectionY - m_minSectionY) * m_sectionCountX) + (sectionX - m_minSectionX); DebugAssert(oldIndex >= 0 && oldIndex < m_sectionCount); if (m_availableSectionMask.TestBit((uint32)oldIndex)) { int32 newIndex = ((sectionY - newMinSectionY) * newSectionCountX) + (sectionX - newMinSectionX); DebugAssert(newIndex >= 0 && newIndex < newSectionCount); newAvailableSectionMask.SetBit((uint32)newIndex); ppNewSectionArray[newIndex] = m_ppSections[oldIndex]; } } } // swap everything over m_minSectionX = newMinSectionX; m_minSectionY = newMinSectionY; m_maxSectionX = newMaxSectionX; m_maxSectionY = newMaxSectionY; m_sectionCountX = newSectionCountX; m_sectionCountY = newSectionCountY; m_sectionCount = newSectionCount; delete[] m_ppSections; m_ppSections = ppNewSectionArray; m_availableSectionMask.Swap(newAvailableSectionMask); // update world bounds AABox blockWorldBoundingBox = CalculateBlockWorldBoundingBox(); m_worldBoundingBox.Merge(blockWorldBoundingBox); m_worldBoundingSphere.Merge(Sphere::FromAABox(blockWorldBoundingBox)); // rewrite the index to file if (!SaveIndex()) Log_WarningPrint("BlockWorld::ResizeIndex: Failed to save resized index."); } bool BlockWorld::IsVisibilityBlockingBlockValue(BlockWorldBlockType blockValue, CUBE_FACE checkFace /* = CUBE_FACE_COUNT */) const { // fastpath for zero blocks if (blockValue == 0) return false; // coloured blocks always block and are always cubic if (blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) return true; // extract block type const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // transparent blocks can't block visibility, not entirely anyway return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) != 0; } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // slabs can block visibility, but not on the top face if (checkFace == CUBE_FACE_TOP) return false; // transparent blocks can't block visibility, not entirely anyway return (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) != 0; } else { // nothing else blocks return false; } } bool BlockWorld::IsLightBlockingBlockValue(BlockWorldBlockType blockValue, CUBE_FACE checkFace /* = CUBE_FACE_COUNT */) const { // fastpath for zero blocks if (blockValue == 0) return false; // coloured blocks always block and are always cubic if (blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) return true; // extract block type const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); // is not cube? if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; // or visibility-blocking/solid if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) return true; // not blocking return false; } AABox BlockWorld::CalculateSectionBoundingBox(int32 sectionSize, int32 chunkSize, int32 sectionX, int32 sectionY) { int32 minX = (sectionX * sectionSize * chunkSize); int32 maxX = ((sectionX + 1) * sectionSize * chunkSize); int32 minY = (sectionY * sectionSize * chunkSize); int32 maxY = ((sectionY + 1) * sectionSize * chunkSize); return AABox((float)minX, (float)minY, Y_FLT_MIN, (float)maxX, (float)maxY, Y_FLT_MAX); } AABox BlockWorld::CalculateSectionBoundingBox(int32 sectionSize, int32 chunkSize, int32 sectionX, int32 sectionY, int32 minChunkZ, int32 maxChunkZ) { int32 minX = (sectionX * sectionSize * chunkSize); int32 maxX = ((sectionX + 1) * sectionSize * chunkSize); int32 minY = (sectionY * sectionSize * chunkSize); int32 maxY = ((sectionY + 1) * sectionSize * chunkSize); int32 minZ = (minChunkZ * chunkSize); int32 maxZ = ((maxChunkZ + 1) * chunkSize); return AABox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); } AABox BlockWorld::CalculateChunkBoundingBox(int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ) { // then add the chunks int32 minX = chunkX * chunkSize; int32 minY = chunkY * chunkSize; int32 minZ = chunkZ * chunkSize; // work out max int32 maxX = minX + chunkSize; int32 maxY = minY + chunkSize; int32 maxZ = minZ + chunkSize; // return result return AABox(static_cast<float>(minX), static_cast<float>(minY), static_cast<float>(minZ), static_cast<float>(maxX), static_cast<float>(maxY), static_cast<float>(maxZ)); } AABox BlockWorld::CalculateChunkBoundingBox(int32 chunkSize, int32 sectionSize, int32 sectionX, int32 sectionY, int32 lodLevel, int32 relativeChunkX, int32 relativeChunkY, int32 relativeChunkZ) { int32 realChunkSize = (chunkSize << lodLevel); // find start x,y of section int32 sectionStartX = sectionX * (sectionSize * chunkSize); int32 sectionStartY = sectionY * (sectionSize * chunkSize); // add in chunk position int32 minX = sectionStartX + relativeChunkX * realChunkSize; int32 minY = sectionStartY + relativeChunkY * realChunkSize; int32 minZ = relativeChunkZ * realChunkSize; // find the max int32 maxX = minX + realChunkSize; int32 maxY = minY + realChunkSize; int32 maxZ = minZ + realChunkSize; // return result return AABox(static_cast<float>(minX), static_cast<float>(minY), static_cast<float>(minZ), static_cast<float>(maxX), static_cast<float>(maxY), static_cast<float>(maxZ)); } AABox BlockWorld::CalculateBlockWorldBoundingBox() const { int32 minX = m_minSectionX * m_sectionSizeInBlocks; int32 minY = m_minSectionY * m_sectionSizeInBlocks; int32 maxX = (m_maxSectionX + 1) * m_sectionSizeInBlocks; int32 maxY = (m_maxSectionY + 1) * m_sectionSizeInBlocks; return AABox((float)minX, (float)minY, Y_FLT_MIN, (float)maxX, (float)maxY, Y_FLT_MAX); } // hack hack! #define div(numerator, denominator) { ((numerator) / (denominator)), ((numerator) % (denominator)) } void BlockWorld::SplitCoordinates(int32 *sectionX, int32 *sectionY, int32 *localChunkX, int32 *localChunkY, int32 *localChunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 chunkSize, int32 sectionSize, int32 bx, int32 by, int32 bz) { int32 sx, sy; int32 lcx, lcy, lcz; int32 lx, ly, lz; int32 sectionSizeInBlocks = chunkSize * sectionSize; // x axis if (bx >= 0) { div_t res = div(bx, sectionSizeInBlocks); div_t res2 = div(res.rem, chunkSize); sx = res.quot; lcx = res2.quot; lx = res2.rem; } else { div_t res = div(bx + 1, sectionSizeInBlocks); div_t res2 = div((sectionSizeInBlocks - 1) + res.rem, chunkSize); sx = res.quot - 1; lcx = res2.quot; lx = res2.rem; } // y axis if (by >= 0) { div_t res = div(by, sectionSizeInBlocks); div_t res2 = div(res.rem, chunkSize); sy = res.quot; lcy = res2.quot; ly = res2.rem; } else { div_t res = div(by + 1, sectionSizeInBlocks); div_t res2 = div((sectionSizeInBlocks - 1) + res.rem, chunkSize); sy = res.quot - 1; lcy = res2.quot; ly = res2.rem; } // z axis if (bz >= 0) { div_t res2 = div(bz, chunkSize); lcz = res2.quot; lz = res2.rem; } else { div_t res = div(bz + 1, chunkSize); lcz = res.quot - 1; lz = (chunkSize - 1) + res.rem; } DebugAssert(lcx < sectionSize && lcy < sectionSize); DebugAssert(lx < chunkSize && ly < chunkSize && lz < chunkSize); //Log_DevPrintf("%i %i %i -> %i %i : %i %i %i : %i %i %i", bx, by, bz, sx, sy, lcx, lcy, lcz, lx, ly, lz); *sectionX = sx; *sectionY = sy; *localChunkX = lcx; *localChunkY = lcy; *localChunkZ = lcz; *localX = (uint32)lx; *localY = (uint32)ly; *localZ = (uint32)lz; } void BlockWorld::SplitCoordinates(int32 *chunkX, int32 *chunkY, int32 *chunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 chunkSize, int32 bx, int32 by, int32 bz) { int32 cx, cy, cz; int32 lx, ly, lz; // x axis if (bx >= 0) { div_t res = div(bx, chunkSize); cx = res.quot; lx = res.rem; } else { div_t res = div(bx + 1, chunkSize); cx = res.quot - 1; lx = (chunkSize - 1) + res.rem; } // y axis if (by >= 0) { div_t res = div(by, chunkSize); cy = res.quot; ly = res.rem; } else { div_t res = div(by + 1, chunkSize); cy = res.quot - 1; ly = (chunkSize - 1) + res.rem;; } // z axis if (bz >= 0) { div_t res = div(bz, chunkSize); cz = res.quot; lz = res.rem; } else { div_t res = div(bz + 1, chunkSize); cz = res.quot - 1; lz = (chunkSize - 1) + res.rem; } DebugAssert(lx < chunkSize && ly < chunkSize && lz < chunkSize); //Log_DevPrintf("%i %i %i -> %i %i %i : %i %i %i", bx, by, bz, cx, cy, cz, lx, ly, lz); *chunkX = cx; *chunkY = cy; *chunkZ = cz; *localX = lx; *localY = ly; *localZ = lz; } #undef div void BlockWorld::ConvertChunkBlockCoordinatesToGlobalCoordinates(int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ, int32 blockX, int32 blockY, int32 blockZ, int32 *pGlobalBlockX, int32 *pGlobalBlockY, int32 *pGlobalBlockZ) { if (chunkX >= 0) *pGlobalBlockX = chunkX * chunkSize + blockX; else *pGlobalBlockX = (chunkX + 1) * chunkSize - (chunkSize - blockX); if (chunkY >= 0) *pGlobalBlockY = chunkY * chunkSize + blockY; else *pGlobalBlockY = (chunkY + 1) * chunkSize - (chunkSize - blockY); if (chunkZ >= 0) *pGlobalBlockZ = chunkZ * chunkSize + blockZ; else *pGlobalBlockZ = (chunkZ + 1) * chunkSize - (chunkSize - blockZ); } void BlockWorld::CalculateRelativeChunkCoordinates(int32 *sectionX, int32 *sectionY, int32 *relativeChunkX, int32 *relativeChunkY, int32 *relativeChunkZ, int32 sectionSize, int32 chunkSize, int32 chunkX, int32 chunkY, int32 chunkZ) { // x axis if (chunkX >= 0) { div_t res = div(chunkX, sectionSize); *sectionX = res.quot; *relativeChunkX = res.rem; } else { div_t res = div(chunkX + 1, sectionSize); *sectionX = res.quot - 1; *relativeChunkX = (sectionSize - 1) + res.rem; } // y axis if (chunkY >= 0) { div_t res = div(chunkY, sectionSize); *sectionY = res.quot; *relativeChunkY = res.rem; } else { div_t res = div(chunkY + 1, sectionSize); *sectionY = res.quot - 1; *relativeChunkY = (sectionSize - 1) + res.rem; } // z is easy, copy across *relativeChunkZ = chunkZ; } void BlockWorld::SplitCoordinates(int32 *sectionX, int32 *sectionY, int32 *localChunkX, int32 *localChunkY, int32 *localChunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 bx, int32 by, int32 bz) const { SplitCoordinates(sectionX, sectionY, localChunkX, localChunkY, localChunkZ, localX, localY, localZ, m_chunkSize, m_sectionSize, bx, by, bz); } void BlockWorld::SplitCoordinates(int32 *chunkX, int32 *chunkY, int32 *chunkZ, int32 *localX, int32 *localY, int32 *localZ, int32 bx, int32 by, int32 bz) const { SplitCoordinates(chunkX, chunkY, chunkZ, localX, localY, localZ, m_chunkSize, bx, by, bz); } void BlockWorld::CalculateRelativeChunkCoordinates(int32 *sectionX, int32 *sectionY, int32 *relativeChunkX, int32 *relativeChunkY, int32 *relativeChunkZ, int32 chunkX, int32 chunkY, int32 chunkZ) const { CalculateRelativeChunkCoordinates(sectionX, sectionY, relativeChunkX, relativeChunkY, relativeChunkZ, m_sectionSize, m_chunkSize, chunkX, chunkY, chunkZ); } int3 BlockWorld::CalculatePointForPosition(const float3 &position) const { return int3(Math::Truncate(position.x) - ((position.x < 0.0f) ? 1 : 0), Math::Truncate(position.y) - ((position.y < 0.0f) ? 1 : 0), Math::Truncate(position.z) - ((position.z < 0.0f) ? 1 : 0)); } void BlockWorld::CalculateSectionForPosition(int32 *sx, int32 *sy, const float3 &position) const { // convert to block coordinates int3 blockCoordinates(CalculatePointForPosition(position)); // convert to sections if (blockCoordinates.x >= 0) *sx = blockCoordinates.x / m_sectionSizeInBlocks; else *sx = ((blockCoordinates.x + 1) / m_sectionSizeInBlocks) - 1; if (blockCoordinates.y >= 0) *sy = blockCoordinates.y / m_sectionSizeInBlocks; else *sy = ((blockCoordinates.y + 1) / m_sectionSizeInBlocks) - 1; } void BlockWorld::CalculateChunkForPosition(int32 *cx, int32 *cy, int32 *cz, const float3 &position) const { // convert to block coordinates int3 blockCoordinates(CalculatePointForPosition(position)); // convert to chunks if (blockCoordinates.x >= 0) *cx = blockCoordinates.x / m_chunkSize; else *cx = ((blockCoordinates.x + 1) / m_chunkSize) - 1; if (blockCoordinates.y >= 0) *cy = blockCoordinates.y / m_chunkSize; else *cy = ((blockCoordinates.y + 1) / m_chunkSize) - 1; if (blockCoordinates.z >= 0) *cz = blockCoordinates.z / m_chunkSize; else *cz = ((blockCoordinates.z + 1) / m_chunkSize) - 1; } void BlockWorld::GetSectionStatus(bool *available, bool *loaded, int32 sectionX, int32 sectionY, int32 requiredLODLevel /* = Y_INT32_MAX */) const { // section in-range? if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) { // query generator if (m_pGenerator != nullptr) *available = m_pGenerator->CanGenerateSection(sectionX, sectionY); else *available = false; *loaded = false; return; } // test section availablity int32 sectionArrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (!m_availableSectionMask.TestBit(sectionArrayIndex)) { // query generator if (m_pGenerator != nullptr) *available = m_pGenerator->CanGenerateSection(sectionX, sectionY); else *available = false; *loaded = false; return; } // chunk is available *available = true; // check loaded status *loaded = (m_ppSections[sectionArrayIndex] != nullptr && m_ppSections[sectionArrayIndex]->GetLoadedLODLevel() <= requiredLODLevel); } bool BlockWorld::IsSectionAvailable(int32 sectionX, int32 sectionY) const { bool available, loaded; GetSectionStatus(&available, &loaded, sectionX, sectionY, 0); return available; } bool BlockWorld::IsSectionLoaded(int32 sectionX, int32 sectionY, int32 requiredLODLevel /* = Y_INT32_MAX */) const { bool available, loaded; GetSectionStatus(&available, &loaded, sectionX, sectionY, requiredLODLevel); return loaded; } void BlockWorld::GetChunkStatus(bool *available, bool *loaded, int32 chunkX, int32 chunkY, int32 chunkZ, int32 requiredLODLevel) const { // convert to section + relative chunk int32 sectionX, sectionY; int32 relativeChunkX, relativeChunkY, relativeChunkZ; CalculateRelativeChunkCoordinates(&sectionX, &sectionY, &relativeChunkX, &relativeChunkY, &relativeChunkZ, chunkX, chunkY, chunkZ); // section in-range? if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) { *available = false; *loaded = false; return; } // test section availablity int32 sectionArrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (!m_availableSectionMask.TestBit(sectionArrayIndex)) { *available = false; *loaded = false; return; } // get section const BlockWorldSection *pSection = GetSection(sectionX, sectionY); if (pSection == nullptr) { // let's assume it's available, but we won't know for sure until it's loaded *available = true; *loaded = false; return; } // use highest loaded lod as a reference, adjust relative chunk coordinates for lod int32 checkLodLevel = Min(requiredLODLevel, pSection->GetLODLevels() - 1); DebugAssert(relativeChunkX >= 0 && relativeChunkY >= 0); relativeChunkX >>= checkLodLevel; relativeChunkY >>= checkLodLevel; relativeChunkZ >>= checkLodLevel; // test for section if ((*available = pSection->GetChunkAvailability(relativeChunkX, relativeChunkY, relativeChunkZ)) == true) { // chunk is available, so set the loaded status to whether the lod is loaded (the chunk should be present) DebugAssert(pSection->GetChunk(relativeChunkX, relativeChunkY, relativeChunkZ) != nullptr); *loaded = (pSection->GetLoadedLODLevel() <= checkLodLevel); } else { // chunk not available, so thus not loaded *loaded = false; } } bool BlockWorld::IsChunkAvailable(int32 chunkX, int32 chunkY, int32 chunkZ) const { bool available, loaded; GetChunkStatus(&available, &loaded, chunkX, chunkY, chunkZ, Y_INT32_MAX); return available; } bool BlockWorld::IsChunkLoaded(int32 chunkX, int32 chunkY, int32 chunkZ, int32 requiredLODLevel /* = Y_INT32_MAX */) const { bool available, loaded; GetChunkStatus(&available, &loaded, chunkX, chunkY, chunkZ, requiredLODLevel); return available; } const BlockWorldSection *BlockWorld::GetSection(int32 sectionX, int32 sectionY) const { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return nullptr; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); return m_ppSections[sectionIndex]; } BlockWorldSection *BlockWorld::GetSection(int32 sectionX, int32 sectionY) { if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return nullptr; int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); return m_ppSections[sectionIndex]; } const BlockWorldChunk *BlockWorld::GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) const { // convert to section + relative chunk int32 sectionX, sectionY; int32 relativeChunkX, relativeChunkY, relativeChunkZ; CalculateRelativeChunkCoordinates(&sectionX, &sectionY, &relativeChunkX, &relativeChunkY, &relativeChunkZ, chunkX, chunkY, chunkZ); // test for section const BlockWorldSection *pSection = GetSection(sectionX, sectionY); return (pSection != nullptr) ? pSection->SafeGetChunk(relativeChunkX, relativeChunkY, relativeChunkZ) : nullptr; } BlockWorldChunk *BlockWorld::GetChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { // convert to section + relative chunk int32 sectionX, sectionY; int32 relativeChunkX, relativeChunkY, relativeChunkZ; CalculateRelativeChunkCoordinates(&sectionX, &sectionY, &relativeChunkX, &relativeChunkY, &relativeChunkZ, chunkX, chunkY, chunkZ); // test for section BlockWorldSection *pSection = GetSection(sectionX, sectionY); return (pSection != nullptr) ? pSection->SafeGetChunk(relativeChunkX, relativeChunkY, relativeChunkZ) : nullptr; } bool BlockWorld::IsChunkNeighboursLoaded(const BlockWorldChunk *pChunk, int32 lodLevel) const { const BlockWorldSection *pSection = pChunk->GetSection(); // neighbour chunk on x axis if (pChunk->GetRelativeChunkX() == 0) { if (IsSectionAvailable(pSection->GetSectionX() - 1, pSection->GetSectionY()) && !IsSectionLoaded(pSection->GetSectionX() - 1, pSection->GetSectionY(), lodLevel)) return false; } else if (pChunk->GetRelativeChunkX() == (m_sectionSize - 1)) { if (IsSectionAvailable(pSection->GetSectionX() + 1, pSection->GetSectionY()) && !IsSectionLoaded(pSection->GetSectionX() + 1, pSection->GetSectionY(), lodLevel)) return false; } // neighbour chunk on y axis if (pChunk->GetRelativeChunkY() == 0) { if (IsSectionAvailable(pSection->GetSectionX(), pSection->GetSectionY() - 1) && !IsSectionLoaded(pSection->GetSectionX(), pSection->GetSectionY() - 1, lodLevel)) return false; } else if (pChunk->GetRelativeChunkY() == (m_sectionSize - 1)) { if (IsSectionAvailable(pSection->GetSectionX(), pSection->GetSectionY() + 1) && !IsSectionLoaded(pSection->GetSectionX(), pSection->GetSectionY() + 1, lodLevel)) return false; } // neighbours present or not edge chunk return true; } bool BlockWorld::EnsureChunkNeighboursLoaded(const BlockWorldChunk *pChunk, int32 lodLevel) { const BlockWorldSection *pSection = pChunk->GetSection(); int32 sectionX, sectionY; // neighbour chunk on x axis if (pChunk->GetRelativeChunkX() == 0) { sectionX = pSection->GetSectionX() - 1; sectionY = pSection->GetSectionY(); if (IsSectionAvailable(sectionX, sectionY) && !IsSectionLoaded(sectionX, sectionY, lodLevel) && !LoadSection(sectionX, sectionY, lodLevel, false)) return false; } else if (pChunk->GetRelativeChunkX() == (m_sectionSize - 1)) { sectionX = pSection->GetSectionX() + 1; sectionY = pSection->GetSectionY(); if (IsSectionAvailable(sectionX, sectionY) && !IsSectionLoaded(sectionX, sectionY, lodLevel) && !LoadSection(sectionX, sectionY, lodLevel, false)) return false; } // neighbour chunk on y axis if (pChunk->GetRelativeChunkY() == 0) { sectionX = pSection->GetSectionX(); sectionY = pSection->GetSectionY() - 1; if (IsSectionAvailable(sectionX, sectionY) && !IsSectionLoaded(sectionX, sectionY, lodLevel) && !LoadSection(sectionX, sectionY, lodLevel, false)) return false; } else if (pChunk->GetRelativeChunkY() == (m_sectionSize - 1)) { sectionX = pSection->GetSectionX(); sectionY = pSection->GetSectionY() + 1; if (IsSectionAvailable(sectionX, sectionY) && !IsSectionLoaded(sectionX, sectionY, lodLevel) && !LoadSection(sectionX, sectionY, lodLevel, false)) return false; } // neighbours present or not edge chunk return true; } ByteStream *BlockWorld::OpenWorldFile(const char *fileName, uint32 access) { ByteStream *pStream; #ifdef USE_FIF pStream = m_pFIFVolume->OpenFile(fileName, access); #else PathString fullFileName; fullFileName.Format("%s/%s", m_basePath.GetCharArray(), fileName); pStream = g_pVirtualFileSystem->OpenFile(fullFileName, access); #endif if (pStream == nullptr) Log_ErrorPrintf("BlockWorld::OpenWorldFile: Failed to open file '%s' with access %X", fileName, access); return pStream; } bool BlockWorld::Create(const char *basePath, const BlockPalette *pPalette, int32 chunkSize, int32 sectionSize, int32 lodLevels) { if (!IsValidChunkSize(chunkSize, sectionSize, lodLevels)) return false; // save path m_basePath = basePath; #ifdef USE_FIF // open stream AutoReleasePtr<ByteStream> pFIFStream = g_pVirtualFileSystem->OpenFile(SmallString::FromFormat("%s.fif", basePath), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); //AutoReleasePtr<ByteStream> pTraceStream = g_pVirtualFileSystem->OpenFile(SmallString::FromFormat("%s.fif.trace", basePath), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); AutoReleasePtr<ByteStream> pTraceStream = nullptr; if (pFIFStream == nullptr || (m_pFIFVolume = FIFVolume::CreateVolume(pFIFStream, pTraceStream)) == nullptr) { Log_ErrorPrintf("BlockWorld::Create: Failed to create '%s'.", m_basePath.GetCharArray()); return false; } #endif m_pPalette = pPalette; m_pPalette->AddRef(); m_chunkSize = chunkSize; m_sectionSize = sectionSize; m_lodLevels = lodLevels; m_minSectionX = m_maxSectionX = 0; m_minSectionY = m_minSectionY = 0; AllocateIndex(); return SaveIndex(); } bool BlockWorld::Load(const char *basePath) { // save path m_basePath = basePath; #ifdef USE_FIF // open stream AutoReleasePtr<ByteStream> pFIFStream = g_pVirtualFileSystem->OpenFile(SmallString::FromFormat("%s.fif", basePath), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_SEEKABLE); if (pFIFStream == nullptr || (m_pFIFVolume = FIFVolume::OpenVolume(pFIFStream)) == nullptr) { Log_ErrorPrintf("BlockWorld::Create: Failed to open '%s'.", m_basePath.GetCharArray()); return false; } #else m_basePath = basePath; #endif // load the index if (!LoadIndex()) { Log_ErrorPrintf("BlockWorld::Load(%s): failed to load index", basePath); return false; } return true; } bool BlockWorld::LoadIndex() { AutoReleasePtr<ByteStream> pIndexStream = OpenWorldFile(BLOCK_WORLD_INDEX_FILE_NAME, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pIndexStream == nullptr) return false; BinaryReader binaryReader(pIndexStream); SmallString paletteName; bool readResult = true; readResult &= binaryReader.SafeReadCString(&paletteName); readResult &= binaryReader.SafeReadInt32(&m_chunkSize); readResult &= binaryReader.SafeReadInt32(&m_sectionSize); readResult &= binaryReader.SafeReadInt32(&m_lodLevels); if (!readResult || (m_pPalette = g_pResourceManager->GetBlockPalette(paletteName)) == nullptr || !IsValidChunkSize(m_chunkSize, m_sectionSize, m_lodLevels)) return false; readResult &= binaryReader.SafeReadInt32(&m_minSectionX); readResult &= binaryReader.SafeReadInt32(&m_minSectionY); readResult &= binaryReader.SafeReadInt32(&m_maxSectionX); readResult &= binaryReader.SafeReadInt32(&m_maxSectionY); if (!readResult || m_minSectionX > m_maxSectionX || m_minSectionY > m_maxSectionY) return false; // allocate index AllocateIndex(); // read index uint32 nAvailableSections; if (!binaryReader.SafeReadUInt32(&nAvailableSections)) return false; for (uint32 j = 0; j < nAvailableSections; j++) { int32 sectionX, sectionY; readResult &= binaryReader.SafeReadInt32(&sectionX); readResult &= binaryReader.SafeReadInt32(&sectionY); if (!readResult || sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) return false; int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask.TestBit((uint32)arrayIndex)) return false; m_availableSectionMask.SetBit((uint32)arrayIndex); } // handle animation-in-progress block type const BlockPalette::BlockType *pAnimationInProgressBlockType = m_pPalette->GetBlockTypeByName("ANIMATION_IN_PROGRESS_BLOCK"); m_animationInProgressBlockType = (pAnimationInProgressBlockType != nullptr) ? (BlockWorldBlockType)pAnimationInProgressBlockType->BlockTypeIndex : 0; if (m_animationInProgressBlockType == 0) Log_WarningPrintf("BlockWorld::LoadIndex: Animation in progress block does not exist, fluidity may be impacted as a result."); return true; } bool BlockWorld::SaveIndex() { ByteStream *pIndexStream = OpenWorldFile(BLOCK_WORLD_INDEX_FILE_NAME, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pIndexStream == nullptr) return false; BinaryWriter binaryWriter(pIndexStream); bool writeResult = true; writeResult &= binaryWriter.SafeWriteCString(m_pPalette->GetName()); writeResult &= binaryWriter.SafeWriteInt32(m_chunkSize); writeResult &= binaryWriter.SafeWriteInt32(m_sectionSize); writeResult &= binaryWriter.SafeWriteInt32(m_lodLevels); writeResult &= binaryWriter.SafeWriteInt32(m_minSectionX); writeResult &= binaryWriter.SafeWriteInt32(m_minSectionY); writeResult &= binaryWriter.SafeWriteInt32(m_maxSectionX); writeResult &= binaryWriter.SafeWriteInt32(m_maxSectionY); uint32 availableSectionCount = 0; for (int32 i = 0; i < m_sectionCount; i++) { if (m_availableSectionMask[i]) availableSectionCount++; } writeResult &= binaryWriter.SafeWriteUInt32(availableSectionCount); // todo: optimize this to writing a bitmask for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask[arrayIndex]) { writeResult &= binaryWriter.SafeWriteInt32(sectionX); writeResult &= binaryWriter.SafeWriteInt32(sectionY); } } } if (!writeResult) pIndexStream->Discard(); else writeResult = pIndexStream->Commit(); pIndexStream->Release(); return writeResult; } bool BlockWorld::LoadGlobalEntities() { return true; } bool BlockWorld::SaveGlobalEntities() { return false; } bool BlockWorld::LoadSection(int32 sectionX, int32 sectionY, int32 lodLevel, bool unloadHigherLODs) { Timer loadTimer; // handle section generation if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY || // section is out-of-range !m_availableSectionMask.TestBit(GetSectionArrayIndex(sectionX, sectionY))) // section is not generated { // we only generate at lod0 for now.. fix this later if (lodLevel != 0) return false; // can it be generated? if (m_pGenerator == nullptr || !m_pGenerator->CanGenerateSection(sectionX, sectionY)) return false; // calculate the block range int32 blockStartX = sectionX * m_sectionSizeInBlocks; int32 blockStartY = sectionY * m_sectionSizeInBlocks; int32 blockEndX = blockStartX + m_sectionSizeInBlocks - 1; int32 blockEndY = blockStartY + m_sectionSizeInBlocks - 1; // get block range int32 minBlockZ, maxBlockZ; if (!m_pGenerator->GetZRange(blockStartX, blockStartY, blockEndX, blockEndY, &minBlockZ, &maxBlockZ)) return false; // convert to chunks int32 minChunkZ = minBlockZ / m_chunkSize; int32 maxChunkZ = maxBlockZ / m_chunkSize; // create the section BlockWorldSection *pSection = CreateSection(sectionX, sectionY, minChunkZ, maxChunkZ); if (pSection == nullptr) return false; // set to generating state pSection->SetLoadState(BlockWorldSection::LoadState_Generating); // log it Log_DevPrintf("BlockWorld::LoadSection: Generating section [%i, %i]... (block Z range %i - %i)", sectionX, sectionY, minBlockZ, maxBlockZ); if (!m_pGenerator->GenerateBlocks(blockStartX, blockStartY, blockEndX, blockEndY)) { // delete the section Log_ErrorPrintf("BlockWorld::LoadSection: Failed to generate section [%i, %i]. Deleting section.", sectionX, sectionY); DeleteSection(sectionX, sectionY); return false; } // force a load update pSection->SetLoadState(BlockWorldSection::LoadState_Changed); pSection->RebuildLODs(m_lodLevels); // flag the section as unchanged since it can be regenerated quite easily... this will screw with lods forcing a regen if it changed among other things... //pSection->SetUnchanged(); Log_DevPrintf("BlockWorld::LoadSection: Generated section [%i, %i] in %.3f ms", sectionX, sectionY, loadTimer.GetTimeMilliseconds()); return true; } DebugAssert(sectionX >= m_minSectionX && sectionX <= m_maxSectionX && sectionY >= m_minSectionY && sectionY <= m_maxSectionY); int32 sectionIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(sectionIndex >= 0); // section is either loaded at a bad lod, or not loaded at all BlockWorldSection *pSection = m_ppSections[sectionIndex]; if (pSection != nullptr && pSection->GetLoadedLODLevel() <= lodLevel) { if (unloadHigherLODs && pSection->GetLoadedLODLevel() < lodLevel) { // squish any pending mesh requests at a higher lod pSection->EnumerateChunks([this, lodLevel, pSection](BlockWorldChunk *pChunk) { // do we want to remove the render model if the lod is higher? it won't hurt, since it doesn't have any link to the data.. if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_Pending) { for (PendingMeshingChunk &pendingChunk : m_pendingChunks) { if (pendingChunk.pChunk == pChunk) { if (pendingChunk.NewLODLevel > lodLevel) pendingChunk.NewLODLevel = lodLevel; break; } } } }); // save the section if it's changed and we're going from lod0 if (pSection->IsChanged() && pSection->GetLoadedLODLevel() == 0) { if (!SaveSection(pSection)) Log_WarningPrintf("BlockWorld::LoadSection: SaveSection(%i, %i) failed, changes to this section are now lost", sectionX, sectionY); } // actually unload the lods Log_DevPrintf("BlockWorld::LoadSection: Section [%i, %i] unloading lods (lod %i -> %i)", sectionX, sectionY, pSection->GetLoadedLODLevel(), lodLevel); pSection->UnloadLODs(lodLevel); } return true; } // open file for section ByteStream *pStream = OpenWorldFile(SmallString::FromFormat("%i_%i.section", sectionX, sectionY), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) return false; // create/load new section int32 oldLODLevel = (pSection != nullptr) ? pSection->GetLoadedLODLevel() : m_lodLevels; if (pSection == nullptr) { pSection = new BlockWorldSection(this, sectionX, sectionY); if (!pSection->LoadFromStream(pStream, lodLevel)) { // failed to load new lods pSection->Release(); pStream->Release(); return false; } // add it to the loaded list m_ppSections[sectionIndex] = pSection; m_loadedSections.Add(pSection); } else { // load it up if (!pSection->LoadLODs(pStream, lodLevel)) { // failed to load new lods pStream->Release(); return false; } } // stream no longer needed pStream->Release(); // events Log_DevPrintf("BlockWorld::LoadSection: Loaded section [%i, %i] at lod %i (from lod %i)... in %.3f ms", sectionX, sectionY, lodLevel, oldLODLevel, loadTimer.GetTimeMilliseconds()); return true; } void BlockWorld::UnloadSection(int32 sectionX, int32 sectionY) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(arrayIndex >= 0); // if it's not loaded, bail out early if (m_ppSections[arrayIndex] == nullptr) return; // load index BlockWorldSection *pSection = m_ppSections[arrayIndex]; int32 loadedSectionIndex = m_loadedSections.IndexOf(pSection); DebugAssert(loadedSectionIndex >= 0); // save changes to the section if (pSection->GetLoadedLODLevel() == 0 && pSection->IsChanged() && !SaveSection(sectionX, sectionY)) Log_WarningPrintf("BlockWorld::UnloadSection: SaveSection(%i, %i) failed, changes to this section are now lost", sectionX, sectionY); // kill any pending meshing for (uint32 i = 0; i < m_pendingChunks.GetSize();) { if (m_pendingChunks[i].pSection == pSection) { m_pendingChunks.FastRemove(i); continue; } else { i++; } } // unload it m_ppSections[arrayIndex] = nullptr; m_loadedSections.FastRemove(loadedSectionIndex); pSection->Release(); } BlockWorldSection *BlockWorld::CreateSection(int32 sectionX, int32 sectionY, int32 minChunkZ, int32 maxChunkZ) { // resize index if necessary if (sectionX < m_minSectionX || sectionX > m_maxSectionX || sectionY < m_minSectionY || sectionY > m_maxSectionY) ResizeIndex(Min(sectionX, m_minSectionX), Min(sectionY, m_minSectionY), Max(sectionX, m_maxSectionX), Max(sectionY, m_maxSectionY)); // get index and ensure it doesn't already exist int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); DebugAssert(m_ppSections[arrayIndex] == nullptr); if (m_availableSectionMask.TestBit(arrayIndex)) { Log_ErrorPrintf("BlockWorld::CreateSection: Section [%i, %i] already exists", sectionX, sectionY); return nullptr; } // create the section BlockWorldSection *pSection = new BlockWorldSection(this, sectionX, sectionY); pSection->Create(minChunkZ, maxChunkZ); // store section m_availableSectionMask.SetBit(arrayIndex); m_ppSections[arrayIndex] = pSection; m_loadedSections.Add(pSection); // save the index, and an empty copy of this section if (!SaveIndex() || !SaveSection(pSection)) Log_WarningPrintf("BlockWorld::CreateSection: Failed to save index or section [%i, %i]", sectionX, sectionY); // done Log_DevPrintf("BlockWorld::CreateSection: Section [%i, %i] created", sectionX, sectionY); return pSection; } void BlockWorld::DeleteSection(int32 sectionX, int32 sectionY) { if (!IsSectionAvailable(sectionX, sectionY)) { Log_ErrorPrintf("BlockWorld::DeleteSection: Section [%u, %u] does not exist", sectionX, sectionY); return; } // delete the section uint32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); BlockWorldSection *pSection = m_ppSections[arrayIndex]; if (pSection != nullptr) { // kill any pending meshing for (uint32 i = 0; i < m_pendingChunks.GetSize();) { if (m_pendingChunks[i].pSection == pSection) { m_pendingChunks.FastRemove(i); continue; } else { i++; } } // unload section delete pSection; m_ppSections[arrayIndex] = nullptr; } // set unavailable m_availableSectionMask.UnsetBit(arrayIndex); } bool BlockWorld::SaveSection(int32 sectionX, int32 sectionY) { // get section BlockWorldSection *pSection = GetSection(sectionX, sectionY); if (pSection == nullptr) return false; return SaveSection(pSection); } bool BlockWorld::SaveSection(BlockWorldSection *pSection) { Log_DevPrintf("Saving section %i,%i", pSection->GetSectionX(), pSection->GetSectionY()); DebugAssert(pSection->GetLoadState() == BlockWorldSection::LoadState_Changed); // open file ByteStream *pStream = OpenWorldFile(SmallString::FromFormat("%i_%i.section", pSection->GetSectionX(), pSection->GetSectionY()), BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_CREATE_PATH | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_STREAMED | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_ATOMIC_UPDATE); if (pStream == nullptr) return false; if (!pSection->SaveToStream(pStream)) { Log_ErrorPrintf("BlockWorld::SaveSection: Failed to save section %i,%i", pSection->GetSectionX(), pSection->GetSectionY()); pStream->Discard(); pStream->Release(); return false; } pStream->Commit(); pStream->Release(); pSection->SetLoadState(BlockWorldSection::LoadState_Loaded); return true; } void BlockWorld::DeleteAllSections() { for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (!m_availableSectionMask[arrayIndex]) continue; DeleteSection(sectionX, sectionY); } } // resize back to (0,0) delete[] m_ppSections; m_ppSections = nullptr; m_minSectionX = m_maxSectionX = 0; m_minSectionY = m_maxSectionY = 0; AllocateIndex(); } bool BlockWorld::LoadAllSections(int32 maxLODLevel /* = 0 */, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { maxLODLevel = Min(maxLODLevel, m_lodLevels - 1); pProgressCallbacks->SetFormattedStatusText("Loading block terrain sections up to LOD %u", maxLODLevel); pProgressCallbacks->SetProgressRange(m_sectionCount); pProgressCallbacks->SetProgressValue(0); pProgressCallbacks->SetCancellable(false); for (int32 sectionX = m_minSectionX; sectionX <= m_maxSectionX; sectionX++) { for (int32 sectionY = m_minSectionY; sectionY <= m_maxSectionY; sectionY++) { int32 arrayIndex = GetSectionArrayIndex(sectionX, sectionY); if (m_availableSectionMask.TestBit(arrayIndex) && (m_ppSections[arrayIndex] == nullptr || m_ppSections[arrayIndex]->GetLoadedLODLevel() > maxLODLevel)) { if (!LoadSection(sectionX, sectionY, maxLODLevel, false)) return false; } pProgressCallbacks->IncrementProgressValue(); } } return true; } void BlockWorld::UnloadAllSections() { while (m_loadedSections.GetSize() > 0) UnloadSection(m_loadedSections[0]->GetSectionX(), m_loadedSections[0]->GetSectionY()); } bool BlockWorld::SaveChangedSections() { for (BlockWorldSection *pSection : m_loadedSections) { if (pSection->IsChanged()) { if (!SaveSection(pSection->GetSectionX(), pSection->GetSectionY())) return false; } } return true; } BlockWorldChunk *BlockWorld::CreateChunk(int32 chunkX, int32 chunkY, int32 chunkZ) { int32 sectionX, sectionY; int32 relativeChunkX, relativeChunkY, relativeChunkZ; CalculateRelativeChunkCoordinates(&sectionX, &sectionY, &relativeChunkX, &relativeChunkY, &relativeChunkZ, chunkX, chunkY, chunkZ); BlockWorldSection *pSection = GetSection(sectionX, sectionY); if (pSection == nullptr || pSection->GetLoadedLODLevel() != 0) { if (IsSectionAvailable(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY, 0, false)) return nullptr; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); } else { if ((pSection = CreateSection(sectionX, sectionY, chunkZ, chunkZ)) == nullptr) return nullptr; } } DebugAssert(!pSection->GetChunkAvailability(relativeChunkX, relativeChunkY, relativeChunkZ)); BlockWorldChunk *pChunk = pSection->CreateChunk(relativeChunkX, relativeChunkY, relativeChunkZ); if (pChunk == nullptr) return nullptr; OnChunkLoaded(pSection, pChunk); return pChunk; } BlockWorldChunk *BlockWorld::GetWritableChunk(int32 chunkX, int32 chunkY, int32 chunkZ, bool allowCreate /* = true */) { int32 sectionX, sectionY; int32 relativeChunkX, relativeChunkY, relativeChunkZ; CalculateRelativeChunkCoordinates(&sectionX, &sectionY, &relativeChunkX, &relativeChunkY, &relativeChunkZ, chunkX, chunkY, chunkZ); BlockWorldSection *pSection = GetSection(sectionX, sectionY); if (pSection == nullptr || pSection->GetLoadedLODLevel() != 0) { if (IsSectionAvailable(sectionX, sectionY)) { if (!LoadSection(sectionX, sectionY, 0, false)) return nullptr; pSection = GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); } else { if (!allowCreate || (pSection = CreateSection(sectionX, sectionY, chunkZ, chunkZ)) == nullptr) return nullptr; } } if (!pSection->GetChunkAvailability(relativeChunkX, relativeChunkY, relativeChunkZ)) { if (!allowCreate) return nullptr; BlockWorldChunk *pChunk = pSection->CreateChunk(relativeChunkX, relativeChunkY, relativeChunkZ); if (pChunk == nullptr) return nullptr; OnChunkLoaded(pSection, pChunk); return pChunk; } else { return pSection->GetChunk(relativeChunkX, relativeChunkY, relativeChunkZ); } } void BlockWorld::OnChunkLoaded(BlockWorldSection *pSection, BlockWorldChunk *pChunk) { // add collision object to physics world m_pPhysicsWorld->AddObject(pChunk->GetCollisionObject()); } void BlockWorld::OnChunkUnloaded(BlockWorldSection *pSection, BlockWorldChunk *pChunk) { DebugAssert(pChunk->GetMeshState() != BlockWorldChunk::MeshState_InProgress); // remove from pending mesh queue if it is pending if (pChunk->IsMeshPending()) { for (uint32 index = 0; index < m_pendingChunks.GetSize(); index++) { if (m_pendingChunks[index].pChunk == pChunk) { m_pendingChunks.FastRemove(index); break; } } } // remove render proxy if there is one created BlockWorldChunkRenderProxy *pRenderProxy = pChunk->GetRenderProxy(); if (pRenderProxy != nullptr) m_pRenderWorld->RemoveRenderable(pRenderProxy); // remove collision object m_pPhysicsWorld->RemoveObject(pChunk->GetCollisionObject()); } const BlockWorldBlockType BlockWorld::GetBlockValue(int32 bx, int32 by, int32 bz) const { // determine chunks int32 sx, sy; int32 lcx, lcy, lcz; int32 lx, ly, lz; SplitCoordinates(&sx, &sy, &lcx, &lcy, &lcz, &lx, &ly, &lz, bx, by, bz); // get section const BlockWorldSection *pSection = GetSection(sx, sy); if (pSection == nullptr || pSection->GetLoadedLODLevel() > 0) return 0; // get chunk const BlockWorldChunk *pChunk = pSection->SafeGetChunk(lcx, lcy, lcz); if (pChunk == nullptr) return 0; // get value return pChunk->GetBlock(0, lx, ly, lz); } bool BlockWorld::ClearBlock(int32 bx, int32 by, int32 bz) { return SetBlockType(bx, by, bz, 0, BLOCK_WORLD_BLOCK_ROTATION_NORTH, false); } bool BlockWorld::SetBlockType(int32 bx, int32 by, int32 bz, BlockWorldBlockType blockType, BLOCK_WORLD_BLOCK_ROTATION blockRotation /* = BLOCK_WORLD_BLOCK_ROTATION_NORTH */, bool createNonExistantChunks /* = false */) { DebugAssert(blockType == 0 || m_pPalette->GetBlockType(blockType)->IsAllocated); // determine chunks int32 chunkX, chunkY, chunkZ; int32 localX, localY, localZ; SplitCoordinates(&chunkX, &chunkY, &chunkZ, &localX, &localY, &localZ, bx, by, bz); // find chunk BlockWorldChunk *pChunk = GetWritableChunk(chunkX, chunkY, chunkZ, (createNonExistantChunks && blockType != 0)); if (pChunk == nullptr) return false; // if no change in block value, skip everything. this works because the top bit will be clear on both sides if appropriate BlockWorldBlockType oldBlockValue = pChunk->GetBlock(0, localX, localY, localZ); BLOCK_WORLD_BLOCK_ROTATION oldBlockRotation = (BLOCK_WORLD_BLOCK_ROTATION)pChunk->GetBlockRotation(0, localX, localY, localZ); if (oldBlockValue == blockType && oldBlockRotation == blockRotation) return true; // lookup old and new block types const BlockPalette::BlockType *pOldBlockType = (oldBlockValue != 0) ? m_pPalette->GetBlockType((uint32)oldBlockValue) : nullptr; const BlockPalette::BlockType *pNewBlockType = (blockType != 0) ? m_pPalette->GetBlockType((uint32)blockType) : nullptr; // commit the value to this chunk pChunk->SetBlock(0, localX, localY, localZ, blockType); pChunk->SetBlockRotation(0, localX, localY, localZ, (uint8)blockRotation); // only call block changed methods when not generating if (pChunk->GetSection()->GetLoadState() != BlockWorldSection::LoadState_Generating) OnBlockChanged(pChunk, localX, localY, localZ); // if we're changing block types, we need to look at neighbouring chunks if (pNewBlockType != pOldBlockType && pNewBlockType != nullptr && pOldBlockType != nullptr && pNewBlockType->Flags != pOldBlockType->Flags) { // enure it's an edge block if (localX == 0 || localX == (m_chunkSize - 1) || localY == 0 || localY == (m_chunkSize - 1) || localZ == 0 || localZ == (m_chunkSize - 1)) OnEdgeBlockChanged(pChunk, localX, localY, localZ); } // if the old block value was an emitter, unspread it's light if ((pOldBlockType != nullptr && (pOldBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCK_LIGHT_EMITTER)) || (IsLightBlockingBlockValue(blockType) && pChunk->GetBlockLight(0, localX, localY, localZ) > 0)) { UnspreadBlockLighting(pChunk, localX, localY, localZ); } // if the new block type is an emitter, spread it's light if (pNewBlockType != nullptr && (pNewBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCK_LIGHT_EMITTER)) SpreadBlockLighting(pChunk, localX, localY, localZ, (uint8)pNewBlockType->BlockLightEmitterSettings.Radius); // changing from an empty block to a solid block bool oldBlockSolid = (oldBlockValue != 0) ? ((pOldBlockType != nullptr) ? ((pOldBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE) != 0) : true) : false; bool newBlockSolid = (blockType != 0) ? ((pNewBlockType != nullptr) ? ((pNewBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE) != 0) : true) : false; if (oldBlockSolid != newBlockSolid) { // bit of a hack for now, if the chunk isn't renderable, don't bother updating physics if (pChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending && pChunk->GetRenderLODLevel() != m_lodLevels) { // wake any physics objects in-range //m_pPhysicsWorld->WakeObjectsInBox(AABox((float)bx, (float)by, (float)bz, (float)(bx + 1), (float)(by + 1), (float)(bz + 1))); m_pPhysicsWorld->UpdateSingleObject(pChunk->GetCollisionObject()); } } return true; } void BlockWorld::OnEdgeBlockChanged(BlockWorldChunk *pChunk, int32 lx, int32 ly, int32 lz) { const int32 chunkSizeMinusOne = m_chunkSize - 1; const int32 chunkX = pChunk->GetGlobalChunkX(); const int32 chunkY = pChunk->GetGlobalChunkY(); const int32 chunkZ = pChunk->GetGlobalChunkZ(); BlockWorldChunk *pNeighbourChunk; if (lx == 0 && (pNeighbourChunk = GetChunk(chunkX - 1, chunkY, chunkZ)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); if (lx == chunkSizeMinusOne && (pNeighbourChunk = GetChunk(chunkX + 1, chunkY, chunkZ)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); if (ly == 0 && (pNeighbourChunk = GetChunk(chunkX, chunkY - 1, chunkZ)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); if (ly == chunkSizeMinusOne && (pNeighbourChunk = GetChunk(chunkX, chunkY + 1, chunkZ)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); if (lz == 0 && (pNeighbourChunk = GetChunk(chunkX, chunkY, chunkZ - 1)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); if (lz == chunkSizeMinusOne && (pNeighbourChunk = GetChunk(chunkX, chunkY, chunkZ + 1)) != nullptr && pNeighbourChunk->GetRenderLODLevel() != m_lodLevels && pNeighbourChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending) QueueSingleChunkForMeshing(pNeighbourChunk, pNeighbourChunk->GetRenderLODLevel()); } void BlockWorld::OnBlockChanged(BlockWorldChunk *pChunk, int32 lx, int32 ly, int32 lz) { // set the changed flag on the section pChunk->GetSection()->SetLoadState(BlockWorldSection::LoadState_Changed); // update child lods //pSection->UpdateChunkLODLevels(pChunk, 0, lx, ly, lz); pChunk->UpdateLODs(0, lx, ly, lz); // queue for meshing, even if we're pending insertion, it'll result in a double meshing but it'll be up to date if (pChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending && pChunk->GetRenderLODLevel() != m_lodLevels) QueueSingleChunkForMeshing(pChunk, pChunk->GetRenderLODLevel()); } bool BlockWorld::SetBlockBit(int32 x, int32 y, int32 z, BlockWorldBlockType bit) { // determine chunks int32 sx, sy; int32 lcx, lcy, lcz; int32 lx, ly, lz; SplitCoordinates(&sx, &sy, &lcx, &lcy, &lcz, &lx, &ly, &lz, x, y, z); // get section/chunk, we only modify lod 0 BlockWorldSection *pSection = GetSection(sx, sy); if (pSection == nullptr || pSection->GetLoadedLODLevel() != 0) return false; // get the chunk, we don't create nonexistant chunks BlockWorldChunk *pChunk = pSection->SafeGetChunk(lcx, lcy, lcz); if (pChunk == nullptr) return false; // don't change the value if the bit is already set BlockWorldBlockType currentValue = pChunk->GetBlock(0, lx, ly, lz); if (currentValue != 0 && (currentValue & bit) == 0) { // add the bit pChunk->SetBlock(0, lx, ly, lz, currentValue | bit); OnBlockChanged(pChunk, lx, ly, lz); } return true; } bool BlockWorld::ClearBlockBit(int32 x, int32 y, int32 z, BlockWorldBlockType bit) { // determine chunks int32 sx, sy; int32 lcx, lcy, lcz; int32 lx, ly, lz; SplitCoordinates(&sx, &sy, &lcx, &lcy, &lcz, &lx, &ly, &lz, x, y, z); // get section/chunk, we only modify lod 0 BlockWorldSection *pSection = GetSection(sx, sy); if (pSection == nullptr || pSection->GetLoadedLODLevel() != 0) return false; // get the chunk, we don't create nonexistant chunks BlockWorldChunk *pChunk = pSection->SafeGetChunk(lcx, lcy, lcz); if (pChunk == nullptr) return false; // don't change the value if the bit is already cleared BlockWorldBlockType currentValue = pChunk->GetBlock(0, lx, ly, lz); if (currentValue != 0 && (currentValue & bit) != 0) { // add the bit pChunk->SetBlock(0, lx, ly, lz, currentValue & ~bit); OnBlockChanged(pChunk, lx, ly, lz); } return true; } int32 BlockWorld::CalculateSectionLODForViewer(int32 sectionX, int32 sectionY, const float3 &viewerPosition) { /* float3 sectionCenter(pSection->GetBoundingBox().GetCenter()); float currentDistanceSq = Math::Square((float)(m_sectionSizeInBlocks * 2)); float distanceToSectionSq = pSection->GetBoundingBox().GetCenter().xy().SquaredDistance(viewerPosition.xy()); int32 lodLevel; for (lodLevel = 0; lodLevel < m_lodLevels; lodLevel++) { if (distanceToSectionSq < currentDistanceSq) break; //currentDistanceSq *= 4.0f; currentDistanceSq = Math::Square((float)((m_sectionSizeInBlocks * 2) << (lodLevel + 1))); } //Log_DevPrintf("Section[%i,%i] dist = %.3f, lod = %i", pSection->GetSectionX(), pSection->GetSectionY(), Math::Sqrt(distanceToSectionSq), lodLevel); return lodLevel;*/ //float3 sectionCenter(pSection->GetBoundingBox().GetCenter()); //float distanceToSectionSq = pSection->GetBoundingBox().GetCenter().xy().SquaredDistance(viewerPosition.xy()); const int32 VIEW_DISTANCE_IN_CHUNKS = 10; //float dx = Min(Math::Abs(static_cast<float>(sectionX * m_sectionSizeInBlocks) - viewerPosition.x), Math::Abs(static_cast<float>((sectionX + 1) * m_sectionSizeInBlocks) - viewerPosition.x)); //float dy = Min(Math::Abs(static_cast<float>(sectionY * m_sectionSizeInBlocks) - viewerPosition.y), Math::Abs(static_cast<float>((sectionY + 1) * m_sectionSizeInBlocks) - viewerPosition.y)); float dx = Math::Abs(static_cast<float>(sectionX * m_sectionSizeInBlocks + m_sectionSizeInBlocks / 2) - viewerPosition.x); float dy = Math::Abs(static_cast<float>(sectionY * m_sectionSizeInBlocks + m_sectionSizeInBlocks / 2) - viewerPosition.y); float squaredDistance = Math::Sqrt((dx * dx) + (dy * dy)); // current distance //float viewDistanceForLOD = (float)Math::Square(m_sectionSizeInBlocks * VIEW_DISTANCE_IN_SECTIONS); float viewDistanceForLOD = (float)(m_chunkSize * VIEW_DISTANCE_IN_CHUNKS); int32 lodLevel; for (lodLevel = 0; lodLevel < m_lodLevels; lodLevel++) { if (squaredDistance <= viewDistanceForLOD) break; // multiplied by 2, then 2 again because each chunk covers twice the space viewDistanceForLOD *= (float)(2 << lodLevel); } // lodlevel //Log_DevPrintf("Section[%i,%i] dist = %.3f, lod = %i", sectionX, sectionY, Math::Sqrt(squaredDistance), lodLevel); //Log_DevPrintf("Section[%i,%i] dist = %.3f, lod = %i", sectionX, sectionY, squaredDistance, lodLevel); return lodLevel; } void BlockWorld::LoadNewInRangeSections() { // number of sections in each direction from the observer that we will check for // TODO: move load/visible radius to cvar, unload/lod change timer for sections to avoid jarring const int32 SECTION_LOAD_RADIUS = 32; // loop through observers for (const ObserverEntry &observer : m_observers) { // start by finding the section the observer is sitting in int32 observerSectionX, observerSectionY; CalculateSectionForPosition(&observerSectionX, &observerSectionY, observer.Value); // find start/end section indices int32 startSectionX = Math::Clamp(observerSectionX - SECTION_LOAD_RADIUS, m_minSectionX, m_maxSectionX); int32 startSectionY = Math::Clamp(observerSectionY - SECTION_LOAD_RADIUS, m_minSectionY, m_maxSectionY); int32 endSectionX = Math::Clamp(observerSectionX + SECTION_LOAD_RADIUS, m_minSectionX, m_maxSectionX); int32 endSectionY = Math::Clamp(observerSectionY + SECTION_LOAD_RADIUS, m_minSectionY, m_maxSectionY); // do both positive and negative directions for (int32 checkSectionX = startSectionX; checkSectionX <= endSectionX; checkSectionX++) { for (int32 checkSectionY = startSectionY; checkSectionY <= endSectionY; checkSectionY++) { int32 checkSectionLOD = CalculateSectionLODForViewer(checkSectionX, checkSectionY, observer.Value); if (checkSectionLOD == m_lodLevels) continue; // section exists? if (!IsSectionAvailable(checkSectionX, checkSectionY)) continue; // check the section is present, loaded BlockWorldSection *pSection = GetSection(checkSectionX, checkSectionY); if (pSection == nullptr || pSection->GetLoadedLODLevel() > checkSectionLOD) { if (!LoadSection(checkSectionX, checkSectionY, checkSectionLOD, false)) continue; } } } } } void BlockWorld::UnloadOutOfRangeSections(float timeSinceLastUpdate) { for (uint32 loadedSectionIndex = 0; loadedSectionIndex < m_loadedSections.GetSize(); ) { BlockWorldSection *pSection = m_loadedSections[loadedSectionIndex]; int32 sectionLOD = m_lodLevels; for (const ObserverEntry &observer : m_observers) sectionLOD = Min(sectionLOD, CalculateSectionLODForViewer(pSection->GetSectionX(), pSection->GetSectionY(), observer.Value)); if (sectionLOD == m_lodLevels) { UnloadSection(pSection->GetSectionX(), pSection->GetSectionY()); continue; } // drop the loaded lod down as well if (pSection->GetLoadedLODLevel() < sectionLOD) { // prevent unloading the section while the new lod is still being processed if (pSection->GetChunksPendingMeshing() == 0) LoadSection(pSection->GetSectionX(), pSection->GetSectionY(), sectionLOD, true); } loadedSectionIndex++; } } void BlockWorld::StreamSections(float timeSinceLastUpdate) { // calculate the view ranges for each section at each lod level int32 viewRanges[BLOCK_WORLD_MAX_LOD_LEVELS]; viewRanges[0] = CVars::r_block_world_section_load_radius.GetInt(); for (int32 i = 1; i < m_lodLevels; i++) viewRanges[i] = viewRanges[i - 1] * 2; // square each view range to avoid sqrt later on int32 searchRadius = viewRanges[m_lodLevels - 1]; for (int32 i = 0; i < m_lodLevels; i++) viewRanges[i] = Math::Square(viewRanges[i]); // calculate the global chunk of each observer int2 *observerSections = (int2 *)alloca(sizeof(int2) * m_observers.GetSize()); uint32 observerCount = 0; for (uint32 i = 0; i < m_observers.GetSize(); i++) { int2 observerSection; CalculateSectionForPosition(&observerSection.x, &observerSection.y, m_observers[i].Value); // collapse duplicate entries uint32 matchIndex = 0; for (; matchIndex < observerCount; matchIndex++) { if (observerSections[matchIndex] == observerSection) break; } if (matchIndex == observerCount) observerSections[observerCount++] = observerSection; } // phase 1: unload any sections that are out of range, that way we don't waste time checking sections that we just loaded for (uint32 loadedSectionIndex = 0; loadedSectionIndex < m_loadedSections.GetSize(); ) { BlockWorldSection *pSection = m_loadedSections[loadedSectionIndex]; // find the smallest distance to this section int2 sectionCoordinates(pSection->GetSectionX(), pSection->GetSectionY()); int32 minSectionRange = Y_INT32_MAX; for (uint32 i = 0; i < observerCount; i++) { int3 sectionDiff(sectionCoordinates - observerSections[i]); int32 sectionRange = sectionDiff.x * sectionDiff.x + sectionDiff.y * sectionDiff.y; minSectionRange = Min(minSectionRange, sectionRange); } // find the section lod level int32 sectionLODLevel; for (sectionLODLevel = 0; sectionLODLevel < m_lodLevels; sectionLODLevel++) { if (minSectionRange <= viewRanges[sectionLODLevel]) break; } // is the current lod correct? if (pSection->GetLoadedLODLevel() != sectionLODLevel) { // if we are currently meshing and the new lod is lower (higher numerically), we can't do anything yet if (sectionLODLevel > pSection->GetLoadedLODLevel() && pSection->GetChunksPendingMeshing() != 0) { loadedSectionIndex++; continue; } // handle unloading a section if (sectionLODLevel == m_lodLevels) { UnloadSection(pSection->GetSectionX(), pSection->GetSectionY()); continue; } // update the lod LoadSection(pSection->GetSectionX(), pSection->GetSectionY(), sectionLODLevel, true); } // next section loadedSectionIndex++; } // phase 2: search for searchRange sections around each observer's section, and only load those that aren't loaded (streaming to new lods is done above) m_queuedLoadSections.Clear(); for (uint32 observerIndex = 0; observerIndex < observerCount; observerIndex++) { // find start/end section indices //int32 startSectionX = Math::Clamp(observerSections[observerIndex].x - searchRadius, m_minSectionX, m_maxSectionX); //int32 startSectionY = Math::Clamp(observerSections[observerIndex].y - searchRadius, m_minSectionY, m_maxSectionY); //int32 endSectionX = Math::Clamp(observerSections[observerIndex].x + searchRadius, m_minSectionX, m_maxSectionX); //int32 endSectionY = Math::Clamp(observerSections[observerIndex].y + searchRadius, m_minSectionY, m_maxSectionY); int32 startSectionX = (observerSections[observerIndex].x - searchRadius); int32 startSectionY = (observerSections[observerIndex].y - searchRadius); int32 endSectionX = (observerSections[observerIndex].x + searchRadius); int32 endSectionY = (observerSections[observerIndex].y + searchRadius); // do both positive and negative directions for (int32 checkSectionX = startSectionX; checkSectionX <= endSectionX; checkSectionX++) { for (int32 checkSectionY = startSectionY; checkSectionY <= endSectionY; checkSectionY++) { BlockWorldSection *pSection = GetSection(checkSectionX, checkSectionY); if (pSection != nullptr || !IsSectionAvailable(checkSectionX, checkSectionY)) continue; // yay, a new section to load. // find the smallest distance to this section int2 sectionCoordinates(checkSectionX, checkSectionY); int32 minSectionRange = Y_INT32_MAX; for (uint32 i = 0; i < observerCount; i++) { int3 sectionDiff(sectionCoordinates - observerSections[i]); int32 sectionRange = sectionDiff.x * sectionDiff.x + sectionDiff.y * sectionDiff.y; minSectionRange = Min(minSectionRange, sectionRange); } // find the section lod level int32 sectionLODLevel; for (sectionLODLevel = 0; sectionLODLevel < m_lodLevels; sectionLODLevel++) { if (minSectionRange <= viewRanges[sectionLODLevel]) break; } // should be in range to at least one observer since we're here if (sectionLODLevel == m_lodLevels) continue; // queue for loading QueuedSectionLoad sectionLoction = { checkSectionX, checkSectionY, sectionLODLevel, minSectionRange }; m_queuedLoadSections.Add(sectionLoction); } } } // sort them uint32 maxSectionsToLoad = CVars::r_block_world_max_sections_per_frame.GetUInt(); uint32 sectionsLoaded = 0; m_queuedLoadSections.Sort([](const QueuedSectionLoad *left, const QueuedSectionLoad *right) { return (left->ViewRange - right->ViewRange); }); for (QueuedSectionLoad &sectionLocation : m_queuedLoadSections) { // force load anything with a distance of zero, safe to break after since the zeros will be ordered at the front if (sectionLocation.ViewRange == 0 || sectionsLoaded < maxSectionsToLoad) { LoadSection(sectionLocation.SectionX, sectionLocation.SectionY, sectionLocation.LODLevel, false); sectionsLoaded++; } else { // no point searching any more break; } } } void BlockWorld::TransitionLoadedChunkRenderLODs() { // calculate view ranges for each lod level int32 viewRanges[BLOCK_WORLD_MAX_LOD_LEVELS]; viewRanges[0] = CVars::r_block_world_visible_radius.GetInt(); for (int32 i = 1; i < m_lodLevels; i++) viewRanges[i] = viewRanges[i - 1] * 2; // square each view range to avoid sqrt later on for (int32 i = 0; i < m_lodLevels; i++) viewRanges[i] = Math::Square(viewRanges[i]); // calculate the global chunk of each observer uint32 observerCount = m_observers.GetSize(); int3 *observerChunks = (int3 *)alloca(sizeof(int3) * observerCount); for (uint32 i = 0; i < observerCount; i++) CalculateChunkForPosition(&observerChunks[i].x, &observerChunks[i].y, &observerChunks[i].z, m_observers[i].Value); // for each loaded section, find if we need to switch the lod level for (BlockWorldSection *pSection : m_loadedSections) { // enumerate chunks pSection->EnumerateChunks([this, &viewRanges, observerCount, observerChunks, pSection](BlockWorldChunk *pChunk) { // find range in chunks to chunk int3 chunkCoordinates(pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ()); int32 minChunkRange = Y_INT32_MAX; for (uint32 i = 0; i < observerCount; i++) { int3 chunkDiff(chunkCoordinates - observerChunks[i]); int32 chunkRange = chunkDiff.x * chunkDiff.x + chunkDiff.y * chunkDiff.y; minChunkRange = Min(minChunkRange, chunkRange); } // find the chunk render level int32 chunkRenderLevel; for (chunkRenderLevel = 0; chunkRenderLevel < m_lodLevels; chunkRenderLevel++) { if (minChunkRange <= viewRanges[chunkRenderLevel]) break; } // cap at loaded lod level chunkRenderLevel = Max(chunkRenderLevel, pChunk->GetLoadedLODLevel()); // level changed? if (pChunk->GetRenderLODLevel() != chunkRenderLevel) { // can't do anything for chunks that are pending insertion, have to wait for that to finish first. if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_InProgress) return; // chunk out of view completely? if (chunkRenderLevel == m_lodLevels) { // remove the chunk's mesh RemoveChunkMesh(pChunk); } else { // if the chunk's neighbours aren't loaded, we can't change the level either if (!IsChunkNeighboursLoaded(pChunk, chunkRenderLevel)) return; // mesh the chunk at the new lod QueueSingleChunkForMeshing(pChunk, chunkRenderLevel); } } }); } } void BlockWorld::RemoveChunkMesh(BlockWorldChunk *pChunk) { BlockWorldChunkRenderProxy *pRenderProxy = pChunk->GetRenderProxy(); if (pRenderProxy != nullptr) { //Log_DevPrintf("BlockWorld::RemoveSectionMeshes: Removed render proxy for section[%i,%i] chunk [%i,%i,%i] lod %i", pSection->GetSectionX(), pSection->GetSectionY(), pSearchChunk->GetGlobalChunkStartX(), pSearchChunk->GetGlobalChunkStartY(), pSearchChunk->GetGlobalChunkStartZ(), pSearchChunk->GetLODLevel()); m_pRenderWorld->RemoveRenderable(pRenderProxy); // remove the chunk pChunk->SetRenderProxy(nullptr); pRenderProxy->Release(); } // is it pending? if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_Pending) { for (uint32 i = 0; i < m_pendingChunks.GetSize(); i++) { if (m_pendingChunks[i].pChunk == pChunk) { m_pendingChunks.FastRemove(i); break; } } } // clear mesh state pChunk->SetMeshState(BlockWorldChunk::MeshState_Idle); pChunk->SetRenderLODLevel(m_lodLevels); } void BlockWorld::RemoveSectionMeshes(BlockWorldSection *pSection) { pSection->EnumerateChunks([this, pSection](BlockWorldChunk *pSearchChunk) { RemoveChunkMesh(pSearchChunk); }); } void BlockWorld::QueueSingleChunkForMeshing(BlockWorldChunk *pChunk, int32 lodLevel) { BlockWorldSection *pSection = pChunk->GetSection(); DebugAssert(lodLevel < m_lodLevels); // mesh is pending? if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_Pending) { // search the pending list, and switch the lod level for (PendingMeshingChunk &pendingChunk : m_pendingChunks) { if (pendingChunk.pChunk == pChunk) { pChunk->SetRenderLODLevel(lodLevel); pendingChunk.NewLODLevel = lodLevel; return; } } } else if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_InProgress) { // in progress in background, switch the state and bail pChunk->SetMeshState(BlockWorldChunk::MeshState_InProgressWithChanges); return; } // shouldn't be pending to be here.. this is more of a catcher of messed-up internal state DebugAssert(pChunk->GetMeshState() != BlockWorldChunk::MeshState_InProgress); DebugAssert(pChunk->GetMeshState() != BlockWorldChunk::MeshState_Pending); // queue it PendingMeshingChunk pendingChunk; pendingChunk.pSection = pSection; pendingChunk.pChunk = pChunk; pendingChunk.ViewCenter = pChunk->GetBoundingBox().GetCenter(); pendingChunk.MinimumViewDistance = Y_FLT_INFINITE; pendingChunk.OldLODLevel = pChunk->GetRenderLODLevel(); pendingChunk.NewLODLevel = lodLevel; m_pendingChunks.Add(pendingChunk); // add to section's pending chunk count pSection->AddChunkPendingMeshing(); pChunk->SetMeshState(BlockWorldChunk::MeshState_Pending); pChunk->SetRenderLODLevel(lodLevel); } void BlockWorld::SortPendingMeshChunks() { if (m_pendingChunks.IsEmpty()) return; // for each chunk in the pending list, calculate it's minimum view distance to any observers for (PendingMeshingChunk &pmc : m_pendingChunks) { float minDistance = Y_FLT_INFINITE; for (const ObserverEntry &observer : m_observers) minDistance = Min(minDistance, pmc.ViewCenter.SquaredDistance(observer.Value)); pmc.MinimumViewDistance = minDistance; } // sort the array according to this m_pendingChunks.Sort([](const BlockWorld::PendingMeshingChunk *left, const BlockWorld::PendingMeshingChunk *right) { return Math::CompareResult(left->MinimumViewDistance, right->MinimumViewDistance); }); } void BlockWorld::MeshSingleChunk(BlockWorldSection *pSection, BlockWorldChunk *pChunk, int32 lodLevel) { DebugAssert(pChunk->GetMeshState() == BlockWorldChunk::MeshState_Pending); // switch mesh state to in-progress pChunk->SetMeshState(BlockWorldChunk::MeshState_InProgress); m_chunksMeshingInProgress++; // grab the data from the chunk and adjacent chunks QUEUE_ASYNC_LAMBDA_COMMAND([this, pSection, pChunk, lodLevel]() { BlockWorldMesher *pBuilder = BlockWorldChunkRenderProxy::CreateMesher(this, pSection, pChunk, lodLevel); // if this chunk is new, we can push it to the background if (pChunk->GetRenderProxy() == nullptr) { // kick off the mesh operation in background QUEUE_BACKGROUND_LAMBDA_COMMAND([this, pSection, pChunk, lodLevel, pBuilder]() { Timer meshTimer; // mesh away pBuilder->GenerateMesh(); if (meshTimer.GetTimeMilliseconds() > 30.0f) Log_PerfPrintf("Background meshing of chunk %i/%i/%i lod %u took %.4fms", pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), lodLevel, meshTimer.GetTimeMilliseconds()); // anything generated? if (pBuilder->GetOutputBatchCount() == 0 && pBuilder->GetOutputLightCount() == 0 && pBuilder->GetOutputMeshInstancesCount() == 0) { // wipe out the builder delete pBuilder; } else { // create the render proxy and bring it into the world BlockWorldChunkRenderProxy *pRenderProxy = nullptr; pRenderProxy = BlockWorldChunkRenderProxy::CreateForChunk(0, this, pSection, pChunk, lodLevel, pBuilder); pChunk->SetRenderProxy(pRenderProxy); m_pRenderWorld->AddRenderable(pRenderProxy); } // update the state on the main thread QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, pSection, pChunk, lodLevel]() { // section has one less chunk outstanding pSection->RemoveChunkPendingMeshing(); m_chunksMeshingInProgress--; // has something re-queued us? if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_InProgressWithChanges) { // queue chunk for meshing QueueSingleChunkForMeshing(pChunk, lodLevel); } else { // clear state pChunk->SetMeshState(BlockWorldChunk::MeshState_Idle); } }); }); } else { Timer meshTimer; // mesh away pBuilder->GenerateMesh(); if (meshTimer.GetTimeMilliseconds() > 30.0f) Log_PerfPrintf("Async meshing of chunk %i/%i/%i lod %u took %.4fms", pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), lodLevel, meshTimer.GetTimeMilliseconds()); // this a re-mesh, so it must be done on the main thread QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, pSection, pChunk, lodLevel, pBuilder]() { BlockWorldChunkRenderProxy *pRenderProxy = pChunk->GetRenderProxy(); DebugAssert(pRenderProxy != nullptr); // anything generated? if (pBuilder->GetOutputBatchCount() == 0 && pBuilder->GetOutputLightCount() == 0 && pBuilder->GetOutputMeshInstancesCount() == 0) { delete pBuilder; // clear render proxy if one exists m_pRenderWorld->RemoveRenderable(pRenderProxy); pChunk->SetRenderProxy(nullptr); pRenderProxy->Release(); } else { // update the mesh on it pRenderProxy->RebuildForChunk(this, pSection, pChunk, lodLevel, pBuilder); } // section has one less chunk outstanding pSection->RemoveChunkPendingMeshing(); m_chunksMeshingInProgress--; // has something re-queued us? if (pChunk->GetMeshState() == BlockWorldChunk::MeshState_InProgressWithChanges) { // queue chunk for meshing QueueSingleChunkForMeshing(pChunk, lodLevel); } else { // clear state pChunk->SetMeshState(BlockWorldChunk::MeshState_Idle); } }); } }); } void BlockWorld::ProcessPendingMeshChunks() { if (m_pendingChunks.IsEmpty()) { #if 0 for (BlockWorldSection *pSection : m_loadedSections) { for (int32 lod = pSection->GetLoadedLODLevel(); lod < m_lodLevels; lod++) { pSection->EnumerateChunks(lod, [](BlockWorldChunk *pChunk) { DebugAssert(pChunk->GetMeshState() == BlockWorldChunk::MeshState_Idle); }); } } #endif return; } // todo: limit this rate //uint32 chunksToMesh = m_pendingMeshChunks.GetSize(); //uint32 chunksToMesh = Min(m_pendingChunks.GetSize(), (uint32)1); uint32 chunksToMesh = CVars::r_block_world_max_chunks_per_frame.GetUInt(); uint32 chunksMeshed = 0; uint32 pendingChunkIndex = 0; for (; pendingChunkIndex < m_pendingChunks.GetSize(); pendingChunkIndex++) { // mesh a chunk! PendingMeshingChunk &pmc = m_pendingChunks[pendingChunkIndex]; BlockWorldSection *pSection = pmc.pSection; // meshing a single chunk BlockWorldChunk *pChunk = pmc.pChunk; int32 lodLevel = pmc.NewLODLevel; /*QUEUE_ASYNC_LAMBDA_COMMAND([this, pSection, pChunk, lodLevel]() { MeshSingleChunk(pSection, pChunk, lodLevel); });*/ // mesh chunk MeshSingleChunk(pSection, pChunk, lodLevel); // remove from list //pSection->RemoveChunkPendingMeshing(); chunksMeshed++; if (chunksMeshed == chunksToMesh) { // this increment is necessary so that the pending entry is removed pendingChunkIndex++; break; } } // remove the chunks that were meshed if (pendingChunkIndex != 0) m_pendingChunks.RemoveRange(0, pendingChunkIndex); } bool BlockWorld::RayCastBlock(const Ray &ray, int32 *pBlockX, int32 *pBlockY, int32 *pBlockZ, CUBE_FACE *pBlockFace, BlockWorldBlockType *pBlockValue, float *pDistance) const { // this is rather crude and can definitely be optimized with an octree to further eliminate tests // also, the current hit distance can be compared against when testing the section, to skip further tests // hit information const BlockWorldSection *pHitSection = nullptr; const BlockWorldChunk *pHitChunk = nullptr; int32 hitBlockX = 0, hitBlockY = 0, hitBlockZ = 0; BlockWorldBlockType hitBlockValue = 0; CUBE_FACE hitBlockFace = CUBE_FACE_COUNT; float hitBlockDistance = Y_FLT_INFINITE; // get bounding box of ray AABox rayBoundingBox(ray.GetAABox()); // transform to section indices, clamp to actual section range int32 minSectionX = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBox.GetMinBounds().x / (float)m_sectionSizeInBlocks)), m_minSectionX, m_maxSectionX); int32 minSectionY = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBox.GetMinBounds().y / (float)m_sectionSizeInBlocks)), m_minSectionY, m_maxSectionY); int32 maxSectionX = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBox.GetMaxBounds().x / (float)m_sectionSizeInBlocks)), m_minSectionX, m_maxSectionX); int32 maxSectionY = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBox.GetMaxBounds().y / (float)m_sectionSizeInBlocks)), m_minSectionY, m_maxSectionY); // iterate over these sections for (int32 sectionY = minSectionY; sectionY <= maxSectionY; sectionY++) { for (int32 sectionX = minSectionX; sectionX <= maxSectionX; sectionX++) { // loaded at lod0? also check if it hits the section const BlockWorldSection *pSection = GetSection(sectionX, sectionY); if (pSection == nullptr || pSection->GetLoadedLODLevel() != 0 || ray.AABoxIntersectionTime(pSection->GetBoundingBox()) >= hitBlockDistance) continue; // move the search range into section space float3 rayBoundingBoxMinSectionSpace(rayBoundingBox.GetMinBounds() - pSection->GetBoundingBox().GetMinBounds()); float3 rayBoundingBoxMaxSectionSpace(rayBoundingBox.GetMaxBounds() - pSection->GetBoundingBox().GetMinBounds()); // convert to chunks int32 minChunkX = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinSectionSpace.x / (float)m_chunkSize)), 0, m_sectionSize - 1); int32 minChunkY = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinSectionSpace.y / (float)m_chunkSize)), 0, m_sectionSize - 1); int32 minChunkZ = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinSectionSpace.z / (float)m_chunkSize)), pSection->GetMinChunkZ(), pSection->GetMaxChunkZ()); int32 maxChunkX = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxSectionSpace.x / (float)m_chunkSize)), 0, m_sectionSize - 1); int32 maxChunkY = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxSectionSpace.y / (float)m_chunkSize)), 0, m_sectionSize - 1); int32 maxChunkZ = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxSectionSpace.z / (float)m_chunkSize)), pSection->GetMinChunkZ(), pSection->GetMaxChunkZ()); // iterate through these chunks for (int32 chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { for (int32 chunkY = minChunkY; chunkY <= maxChunkY; chunkY++) { for (int32 chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { // ensure chunk exists and actually intersects const BlockWorldChunk *pChunk = pSection->GetChunk(chunkX, chunkY, chunkZ); if (pChunk == nullptr || ray.AABoxIntersectionTime(pChunk->GetBoundingBox()) >= hitBlockDistance) continue; // we hit the chunk, so move the search range into chunk space float3 rayBoundingBoxMinChunkSpace(rayBoundingBox.GetMinBounds() - pChunk->GetBasePosition()); float3 rayBoundingBoxMaxChunkSpace(rayBoundingBox.GetMaxBounds() - pChunk->GetBasePosition()); // convert to blocks int32 minBlockX = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinChunkSpace.x)), 0, m_chunkSize - 1); int32 minBlockY = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinChunkSpace.y)), 0, m_chunkSize - 1); int32 minBlockZ = Math::Clamp(Math::Truncate(Math::Floor(rayBoundingBoxMinChunkSpace.z)), 0, m_chunkSize - 1); int32 maxBlockX = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxChunkSpace.x)), 0, m_chunkSize - 1); int32 maxBlockY = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxChunkSpace.y)), 0, m_chunkSize - 1); int32 maxBlockZ = Math::Clamp(Math::Truncate(Math::Ceil(rayBoundingBoxMaxChunkSpace.z)), 0, m_chunkSize - 1); // iterate through blocks for (int32 blockZ = minBlockZ; blockZ <= maxBlockZ; blockZ++) { for (int32 blockY = minBlockY; blockY <= maxBlockY; blockY++) { for (int32 blockX = minBlockX; blockX <= maxBlockX; blockX++) { // get block value BlockWorldBlockType blockValue = pChunk->GetBlock(0, blockX, blockY, blockZ); if (blockValue == 0) continue; // get block coordinates float3 blockMinBounds(pChunk->GetBasePosition() + float3((float)blockX, (float)blockY, (float)blockZ)); float3 blockMaxBounds(blockMinBounds + 1.0f); // test an intersection :: todo: move this test to local chunk space instead of world space for accuracy? float thisBlockHitTime; CUBE_FACE thisBlockHitFace; if (!ray.AABoxIntersectionTimeFace(blockMinBounds, blockMaxBounds, &thisBlockHitTime, &thisBlockHitFace)) continue; // less than current? if (thisBlockHitTime < hitBlockDistance) { pHitSection = pSection; pHitChunk = pChunk; hitBlockX = blockX; hitBlockY = blockY; hitBlockZ = blockZ; hitBlockValue = blockValue; hitBlockFace = thisBlockHitFace; hitBlockDistance = thisBlockHitTime; } } } } } } } } } // did we hit anything? if (pHitSection == nullptr) return false; // convert local coordinates to global coordinates ConvertChunkBlockCoordinatesToGlobalCoordinates(m_chunkSize, pHitChunk->GetGlobalChunkX(), pHitChunk->GetGlobalChunkY(), pHitChunk->GetGlobalChunkZ(), hitBlockX, hitBlockY, hitBlockZ, pBlockX, pBlockY, pBlockZ); *pBlockFace = hitBlockFace; *pBlockValue = hitBlockValue; *pDistance = hitBlockDistance; int tsx, tsy, tcx, tcy, tcz, tbx, tby, tbz; SplitCoordinates(&tsx, &tsy, &tcx, &tcy, &tcz, &tbx, &tby, &tbz, *pBlockX, *pBlockY, *pBlockZ); DebugAssert(tsx == pHitSection->GetSectionX() && tsy == pHitSection->GetSectionY() && tcx == pHitChunk->GetRelativeChunkX() && tcy == pHitChunk->GetRelativeChunkY() && tcz == pHitChunk->GetRelativeChunkZ() && tbx == hitBlockX && tby == hitBlockY && tbz == hitBlockZ); return true; } void BlockWorld::AddBrush(Brush *pObject) { Panic("Brushes are not supported in BlockWorld"); } void BlockWorld::RemoveBrush(Brush *pObject) { Panic("Brushes are not supported in BlockWorld"); } const Entity *BlockWorld::GetEntityByID(uint32 EntityId) const { // lookup in hash table const EntityHashTable::Member *pEntityData = m_entityHashTable.Find(EntityId); if (pEntityData == nullptr) return nullptr; return pEntityData->Value; } Entity *BlockWorld::GetEntityByID(uint32 EntityId) { // lookup in hash table const EntityHashTable::Member *pEntityData = m_entityHashTable.Find(EntityId); if (pEntityData == nullptr) return nullptr; return pEntityData->Value; } void BlockWorld::AddEntity(Entity *pEntity) { DebugAssert(pEntity->GetEntityID() != 0); DebugAssert(GetEntityByID(pEntity->GetEntityID()) == nullptr); // entity added routine pEntity->AddRef(); pEntity->OnAddToWorld(this); OnLoadEntity(pEntity); // handle global entities BlockWorldSection *pSection = nullptr; if (pEntity->GetMobility() != ENTITY_MOBILITY_GLOBAL) { // find it a section int32 newSectionX, newSectionY; CalculateSectionForPosition(&newSectionX, &newSectionY, pEntity->GetBoundingBox().GetCenter()); // sections not at lod0 are useless pSection = GetSection(newSectionX, newSectionY); if (pSection != nullptr && pSection->GetLoadedLODLevel() != 0) pSection = nullptr; } // add to section if (pSection != nullptr) { // add him to the section pSection->AddEntity(pEntity); pEntity->SetWorldData(pSection); } else { // add to global list BlockWorldEntityReference entityRef; entityRef.pEntity = pEntity; entityRef.EntityID = pEntity->GetEntityID(); entityRef.BoundingBox = pEntity->GetBoundingBox(); entityRef.BoundingSphere = pEntity->GetBoundingSphere(); m_globalEntityReferences.Add(entityRef); pEntity->SetWorldData(nullptr); } // update bounds m_worldBoundingBox.Merge(pEntity->GetBoundingBox()); m_worldBoundingSphere.Merge(pEntity->GetBoundingSphere()); } void BlockWorld::MoveEntity(Entity *pEntity) { // find the section it lives in BlockWorldSection *pOldSection = reinterpret_cast<BlockWorldSection *>(pEntity->GetWorldData()); DebugAssert(pOldSection == nullptr || m_loadedSections.Contains(pOldSection)); // update bounds m_worldBoundingBox.Merge(pEntity->GetBoundingBox()); m_worldBoundingSphere.Merge(pEntity->GetBoundingSphere()); // handle global entities BlockWorldSection *pNewSection = nullptr; if (pEntity->GetMobility() != ENTITY_MOBILITY_GLOBAL) { // moving to a new section? int32 newSectionX, newSectionY; CalculateSectionForPosition(&newSectionX, &newSectionY, pEntity->GetBoundingBox().GetCenter()); // changed? save a lookup if it hasn't if (pOldSection != nullptr && pOldSection->GetSectionX() == newSectionX && pOldSection->GetSectionY() == newSectionY) { pOldSection->MoveEntity(pEntity); return; } // sections that aren't at lod0 are useless pNewSection = GetSection(newSectionX, newSectionY); if (pNewSection != nullptr && pNewSection->GetLoadedLODLevel() != 0) pNewSection = nullptr; } // did we previously not have a section? if (pOldSection == nullptr) { // removing or updating from global list? for (uint32 idx = 0; idx < m_globalEntityReferences.GetSize(); idx++) { if (m_globalEntityReferences[idx].pEntity == pEntity) { if (pNewSection != nullptr) { // we have a new section, so remove from the global list m_globalEntityReferences.FastRemove(idx); break; } else { // update the global list, and bail out m_globalEntityReferences[idx].BoundingBox = pEntity->GetBoundingBox(); m_globalEntityReferences[idx].BoundingSphere = pEntity->GetBoundingSphere(); return; } } } } else { // removing from section pOldSection->RemoveEntity(pEntity); } // move into the new section if (pNewSection != nullptr) { // add it pNewSection->AddEntity(pEntity); pEntity->SetWorldData(pNewSection); } else { // add to global list BlockWorldEntityReference entityRef; entityRef.pEntity = pEntity; entityRef.EntityID = pEntity->GetEntityID(); entityRef.BoundingBox = pEntity->GetBoundingBox(); entityRef.BoundingSphere = pEntity->GetBoundingSphere(); m_globalEntityReferences.Add(entityRef); pEntity->SetWorldData(nullptr); } } void BlockWorld::UpdateEntity(Entity *pEntity) { BlockWorldSection *pSection = reinterpret_cast<BlockWorldSection *>(pEntity->GetWorldData()); DebugAssert(pSection == nullptr || m_loadedSections.Contains(pSection)); // if we're in a section, flag it as changed if (pSection != nullptr && pSection->GetLoadState() == BlockWorldSection::LoadState_Loaded) pSection->SetLoadState(BlockWorldSection::LoadState_Changed); } void BlockWorld::RemoveEntity(Entity *pEntity) { DebugAssert(GetEntityByID(pEntity->GetEntityID()) == pEntity); // find the section it lives in BlockWorldSection *pSection = reinterpret_cast<BlockWorldSection *>(pEntity->GetWorldData()); DebugAssert(pSection == nullptr || m_loadedSections.Contains(pSection)); // remove from hash tables, update lists, etc OnUnloadEntity(pEntity); // remove from section if (pSection != nullptr) { pSection->RemoveEntity(pEntity); } else { for (uint32 idx = 0; idx < m_globalEntityReferences.GetSize(); idx++) { if (m_globalEntityReferences[idx].pEntity == pEntity) { m_globalEntityReferences.FastRemove(idx); break; } } } // delete entity pEntity->OnRemoveFromWorld(this); pEntity->Release(); } void BlockWorld::OnLoadEntity(Entity *pEntity) { // add it to the hash table DebugAssert(m_entityHashTable.Find(pEntity->GetEntityID()) == nullptr); m_entityHashTable.Insert(pEntity->GetEntityID(), pEntity); } void BlockWorld::OnUnloadEntity(Entity *pEntity) { // ensure it isn't in the active queues for (uint32 j = 0; j < m_activeEntities.GetSize(); j++) { if (m_activeEntities[j].pEntity == pEntity) { m_activeEntities.FastRemove(j); SortActiveEntities(); break; } } for (uint32 j = 0; j < m_activeAsyncEntities.GetSize(); j++) { if (m_activeAsyncEntities[j].pEntity == pEntity) { m_activeAsyncEntities.FastRemove(j); SortActiveAsyncEntities(); break; } } // ensure it isn't in the removal queue int32 removeQueueIndex = m_removeQueue.IndexOf(pEntity); if (removeQueueIndex >= 0) m_removeQueue.FastRemove(removeQueueIndex); // remove from hash table BlockWorld::EntityHashTable::Member *pHashTableMember = m_entityHashTable.Find(pEntity->GetEntityID()); DebugAssert(pHashTableMember != nullptr); m_entityHashTable.Remove(pHashTableMember); } void BlockWorld::BeginFrame(float deltaTime) { World::BeginFrame(deltaTime); } void BlockWorld::UpdateAsync(float deltaTime) { World::UpdateAsync(deltaTime); ProcessPendingMeshChunks(); } void BlockWorld::Update(float deltaTime) { World::Update(deltaTime); UpdateBlockAnimations(deltaTime); //UnloadOutOfRangeSections(deltaTime); //LoadNewInRangeSections(); StreamSections(deltaTime); TransitionLoadedChunkRenderLODs(); SortPendingMeshChunks(); } void BlockWorld::EndFrame() { World::EndFrame(); } struct BlockLightingUpdateNode { inline BlockLightingUpdateNode() {} inline BlockLightingUpdateNode(BlockWorldChunk *pChunk_, int32 x_, int32 y_, int32 z_) : pChunk(pChunk_), x(x_), y(y_), z(z_), level(0) {} inline BlockLightingUpdateNode(BlockWorldChunk *pChunk_, int32 x_, int32 y_, int32 z_, uint8 level_) : pChunk(pChunk_), x(x_), y(y_), z(z_), level(level_) {} inline BlockLightingUpdateNode(const BlockLightingUpdateNode &copy) { Y_memcpy(this, &copy, sizeof(*this)); } inline void Set(BlockWorldChunk *pChunk_, int32 x_, int32 y_, int32 z_) { pChunk = pChunk_; x = x_; y = y_; z = z_; level = 0; } inline void Set(BlockWorldChunk *pChunk_, int32 x_, int32 y_, int32 z_, uint8 level_) { pChunk = pChunk_; x = x_; y = y_; z = z_; level = level_; } BlockWorldChunk *pChunk; int32 x; int32 y; int32 z; uint8 level; ////////////////////////////////////////////////////////////////////////// inline bool GetLeftNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (x == 0) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX() - 1, pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), true)) == nullptr) return false; node->Set(pAdjChunk, chunkSizeMinusOne, this->y, this->z); } else { node->Set(this->pChunk, this->x - 1, this->y, this->z); } return true; } inline bool GetRightNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (x == chunkSizeMinusOne) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX() + 1, pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), true)) == nullptr) return false; node->Set(pAdjChunk, 0, this->y, this->z); } else { node->Set(this->pChunk, this->x + 1, this->y, this->z); } return true; } inline bool GetBackNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (y == 0) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY() - 1, pChunk->GetGlobalChunkZ(), true)) == nullptr) return false; node->Set(pAdjChunk, this->x, chunkSizeMinusOne, this->z); } else { node->Set(this->pChunk, this->x, this->y - 1, this->z); } return true; } inline bool GetFrontNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (y == chunkSizeMinusOne) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY() + 1, pChunk->GetGlobalChunkZ(), true)) == nullptr) return false; node->Set(pAdjChunk, this->x, 0, this->z); } else { node->Set(this->pChunk, this->x, this->y + 1, this->z); } return true; } inline bool GetBottomNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (z == 0) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ() - 1, true)) == nullptr) return false; node->Set(pAdjChunk, this->x, this->y, chunkSizeMinusOne); } else { node->Set(this->pChunk, this->x, this->y, this->z - 1); } return true; } inline bool GetTopNode(BlockWorld *pWorld, BlockLightingUpdateNode *node) const { int32 chunkSizeMinusOne = pWorld->GetChunkSize() - 1; if (z == chunkSizeMinusOne) { BlockWorldChunk *pAdjChunk; if ((pAdjChunk = pWorld->GetWritableChunk(pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ() + 1, true)) == nullptr) return false; node->Set(pAdjChunk, this->x, this->y, 0); } else { node->Set(this->pChunk, this->x, this->y, this->z + 1); } return true; } ////////////////////////////////////////////////////////////////////////// inline bool SpreadToNode(BlockWorld *pWorld, uint8 lightLevel) { // light cannot spread to translucent nodes BlockWorldBlockType blockValue = pChunk->GetBlock(0, x, y, z); if (pWorld->IsLightBlockingBlockValue(blockValue)) return false; // check lightlevel is within threshold uint8 currentLightLevel = pChunk->GetBlockLight(0, x, y, z); if ((currentLightLevel + 2) <= lightLevel) { // update the light level of this node pChunk->SetBlockLight(0, x, y, z, lightLevel - 1); pWorld->OnBlockChanged(pChunk, x, y, z); this->level = lightLevel - 1; //Log_DevPrintf(" -- spread to [%i,%i,%i] %i,%i,%i %u", pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), x, y, z, level); return true; } return false; } inline int32 UnspreadFromNode(BlockWorld *pWorld, uint8 lightLevel) { // check lightlevel is within threshold uint8 currentLightLevel = pChunk->GetBlockLight(0, x, y, z); if (currentLightLevel != 0 && currentLightLevel < lightLevel) { // set light level of node to zero, and store the level for future use pChunk->SetBlockLight(0, x, y, z, 0); pWorld->OnBlockChanged(pChunk, x, y, z); this->level = currentLightLevel; return -1; } else if (currentLightLevel >= lightLevel) { this->level = currentLightLevel; return 1; } return 0; } }; void BlockWorld::SpreadBlockLighting(BlockWorldChunk *pChunk, int32 x, int32 y, int32 z, uint8 lightLevel) { //Log_DevPrintf("SPREAD BLOCK LIGHTING: [%i,%i,%i] %i,%i,%i %u", pChunk->GetGlobalChunkX(), pChunk->GetGlobalChunkY(), pChunk->GetGlobalChunkZ(), x, y, z, lightLevel); // set light of node pChunk->SetBlockLight(0, x, y, z, lightLevel); OnBlockChanged(pChunk, x, y, z); // create queue and push node to it (this is gonna have a lot of memmoves.. use a better container) MemArray<BlockLightingUpdateNode> queue(128); queue.Add(BlockLightingUpdateNode(pChunk, x, y, z, lightLevel)); // while the queue has elements while (!queue.IsEmpty()) { // retrieve the front node from the queue BlockLightingUpdateNode node; queue.PopFront(&node); // spread it to each neighbor BlockLightingUpdateNode neighbourNode; if (node.GetLeftNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); if (node.GetRightNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); if (node.GetBackNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); if (node.GetFrontNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); if (node.GetBottomNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); if (node.GetTopNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) queue.Add(neighbourNode); } } void BlockWorld::UnspreadBlockLighting(BlockWorldChunk *pChunk, int32 x, int32 y, int32 z) { // create queue and push node to it (this is gonna have a lot of memmoves.. use a better container) MemArray<BlockLightingUpdateNode> removeQueue(128); MemArray<BlockLightingUpdateNode> updateQueue(128); removeQueue.Add(BlockLightingUpdateNode(pChunk, x, y, z, pChunk->GetBlockLight(0, x, y, z))); // clear light of node pChunk->SetBlockLight(0, x, y, z, 0); OnBlockChanged(pChunk, x, y, z); // while the queue has elements while (!removeQueue.IsEmpty()) { // retrieve the front node from the queue BlockLightingUpdateNode node; removeQueue.PopFront(&node); // create neighbour node BlockLightingUpdateNode neighbourNode; int32 unspreadResult; // spread it to each neighbor if (node.GetLeftNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } if (node.GetRightNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } if (node.GetBackNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } if (node.GetFrontNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } if (node.GetBottomNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } if (node.GetTopNode(this, &neighbourNode)) { unspreadResult = neighbourNode.UnspreadFromNode(this, node.level); if (unspreadResult < 0) removeQueue.Add(neighbourNode); else if (unspreadResult > 0) updateQueue.Add(neighbourNode); } } // process remaining propagation nodes while (!updateQueue.IsEmpty()) { // retrieve the front node from the queue BlockLightingUpdateNode node; updateQueue.PopFront(&node); // spread it to each neighbor BlockLightingUpdateNode neighbourNode; if (node.GetLeftNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); if (node.GetRightNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); if (node.GetBackNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); if (node.GetFrontNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); if (node.GetBottomNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); if (node.GetTopNode(this, &neighbourNode) && neighbourNode.SpreadToNode(this, node.level)) updateQueue.Add(neighbourNode); } } bool BlockWorld::CreateAnimatedPhysicsBlock(const float3 &basePosition, const Quaternion &rotation, BlockWorldBlockType blockValue, const float3 &forceVector, float despawnTime /*= 5.0f*/) { // lookup block info const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) return false; // transform Transform animationTransform(basePosition, rotation, float3::One); // create render proxy BlockDrawTemplate::BlockRenderProxy *pRenderProxy = m_pBlockDrawTemplate->CreateBlockRenderProxy(blockValue, 0, animationTransform.GetTransformMatrix4x4(), 0); if (pRenderProxy == nullptr) return false; // calculate the physics block size float3 physicsBlockExtents(1.0f); // create the collision shape and rigid body AutoReleasePtr<Physics::BoxCollisionShape> pCollisionShape = new Physics::BoxCollisionShape(physicsBlockExtents * 0.5f, physicsBlockExtents * 0.5f); Physics::RigidBody *pRigidBody = new Physics::RigidBody(0, pCollisionShape, animationTransform); // add to world m_pRenderWorld->AddRenderable(pRenderProxy); m_pPhysicsWorld->AddObject(pRigidBody); // create physics block BlockAnimation blockAnimation; blockAnimation.BlockType = blockValue; blockAnimation.LocationX = Math::Truncate(basePosition.x); blockAnimation.LocationY = Math::Truncate(basePosition.y); blockAnimation.LocationZ = Math::Truncate(basePosition.z); blockAnimation.pRenderProxy = pRenderProxy; blockAnimation.LastTransform = animationTransform; blockAnimation.LifeTime = despawnTime; blockAnimation.TimeRemaining = despawnTime; blockAnimation.pRigidBody = pRigidBody; blockAnimation.AnimationFunction = EasingFunction::Linear; blockAnimation.AnimationStartTransform = Transform::Identity; blockAnimation.AnimationEndTransform = Transform::Identity; blockAnimation.SetAfterCompletion = false; m_blockAnimations.Add(blockAnimation); // apply the impulse if (forceVector.SquaredLength() > 0.0f) static_cast<Physics::RigidBody *>(pRigidBody)->ApplyCentralImpulse(forceVector); Log_DevPrintf("BlockWorld::CreateAnimatedPhysicsBlock: spawned '%s' at '%s'", pBlockType->Name.GetCharArray(), StringConverter::Vector3fToString(basePosition).GetCharArray()); return true; } bool BlockWorld::CreateAnimatedPhysicsBlock(int32 x, int32 y, int32 z, const float3 &forceVector, bool removeBlock /*= true*/, float despawnTime /*= 5.0f*/) { // retrieve the block value BlockWorldBlockType blockValue = GetBlockValue(x, y, z); if (blockValue == 0) return false; // calculate base position for this block float3 basePosition((float)x, (float)y, (float)z); // create physics block bool result = CreateAnimatedPhysicsBlock(basePosition, Quaternion::Identity, blockValue, forceVector, despawnTime); // remove the block from the world? if (removeBlock) ClearBlock(x, y, z); // done return result; } bool BlockWorld::CreateBlockAnimation(BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation, const Transform &startTransform, const Transform &endTransform, float spawnTime /* = 1.0f */, EasingFunction::Type easingFunction /* = EasingFunction::Linear */, bool setAfterSpawn /* = false */, int32 setBlockX /* = 0 */, int32 setBlockY /* = 0 */, int32 setBlockZ /* = 0 */) { // create render proxy const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); BlockDrawTemplate::BlockRenderProxy *pRenderProxy = m_pBlockDrawTemplate->CreateBlockRenderProxy(blockValue, 0, startTransform.GetTransformMatrix4x4(), 0); if (pRenderProxy == nullptr) return false; // add to world m_pRenderWorld->AddRenderable(pRenderProxy); // create physics block BlockAnimation blockAnimation; blockAnimation.BlockType = blockValue; blockAnimation.LocationX = setBlockX; blockAnimation.LocationY = setBlockY; blockAnimation.LocationZ = setBlockZ; blockAnimation.Rotation = blockRotation; blockAnimation.pRenderProxy = pRenderProxy; blockAnimation.LastTransform = startTransform; blockAnimation.LifeTime = spawnTime; blockAnimation.TimeRemaining = spawnTime; blockAnimation.pRigidBody = nullptr; blockAnimation.AnimationFunction = easingFunction; blockAnimation.AnimationStartTransform = startTransform; blockAnimation.AnimationEndTransform = endTransform; blockAnimation.SetAfterCompletion = setAfterSpawn; m_blockAnimations.Add(blockAnimation); Log_DevPrintf("BlockWorld::CreateBlockAnimation: spawned '%s' at '%s' moving to '%s'", pBlockType->Name.GetCharArray(), StringConverter::TransformToString(startTransform).GetCharArray(), StringConverter::TransformToString(endTransform).GetCharArray()); // if setting afterwards, mark it as animation in progress if (setAfterSpawn) SetBlockType(setBlockX, setBlockY, setBlockZ, m_animationInProgressBlockType, BLOCK_WORLD_BLOCK_ROTATION_NORTH, true); return true; } void BlockWorld::SetBlockWithAnimation(int32 blockX, int32 blockY, int32 blockZ, BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation, const Transform &startTransform, float spawnTime /* = 1.0f */, EasingFunction::Type easingFunction /* = EasingFunction::Linear */, bool setAfterSpawn /* = true */) { // create end location float3 endLocation((float)blockX, (float)blockY, (float)blockZ); Transform endTransform(endLocation, Quaternion::Identity, float3::One); // pass through if (!CreateBlockAnimation(blockValue, blockRotation, startTransform, endTransform, spawnTime, easingFunction, setAfterSpawn, blockX, blockY, blockZ) && setAfterSpawn) { // still set it anyway SetBlockType(blockX, blockY, blockZ, blockValue, blockRotation, true); } } void BlockWorld::SetBlockWithAnimation(int32 blockX, int32 blockY, int32 blockZ, BlockWorldBlockType blockValue, BLOCK_WORLD_BLOCK_ROTATION blockRotation) { // find the longest direction, up to a certain point, where there is no block const int32 MAX_RANGE = 2; const int32 values[CUBE_FACE_COUNT][3] = { { 1, 0, 0 }, // right { -1, 0, 0 }, // left { 0, 1, 0 }, // back { 0, -1, 0 }, // front { 0, 0, 1 }, // top { 0, 0, -1 }, // bottom }; int32 bestSourceX, bestSourceY, bestSourceZ; int32 bestDirectionSteps = -1; for (int32 i = 0; i < CUBE_FACE_COUNT; i++) { int32 dirX = values[i][0]; int32 dirY = values[i][1]; int32 dirZ = values[i][2]; int32 stepCount = -1; for (int32 steps = 1; steps <= MAX_RANGE; steps++) { int32 searchBlockX = blockX + dirX * steps; int32 searchBlockY = blockY + dirY * steps; int32 searchBlockZ = blockZ + dirZ * steps; if (GetBlockValue(searchBlockX, searchBlockY, searchBlockZ) == 0) stepCount = steps; else break; } if (stepCount < bestDirectionSteps) { // no point trying any more continue; } else if (stepCount == bestDirectionSteps) { // random chance to use this direction if (!g_pEngine->GetRandomNumberGenerator()->NextBoolean(50.0f)) continue; } bestSourceX = blockX + dirX * stepCount; bestSourceY = blockY + dirY * stepCount; bestSourceZ = blockZ + dirZ * stepCount; bestDirectionSteps = stepCount; } if (bestDirectionSteps < 0) { // just set the block, can't animate it from anywhere SetBlockType(blockX, blockY, blockZ, blockValue, blockRotation, true); } else { // use an animation float3 sourceLocation((float)bestSourceX, (float)bestSourceY, (float)bestSourceZ); SetBlockWithAnimation(blockX, blockY, blockZ, blockValue, blockRotation, Transform(sourceLocation, Quaternion::Identity, float3::One), 0.2f, EasingFunction::Quadratic, true); } } void BlockWorld::UpdateBlockAnimations(float deltaTime) { static const float BLOCK_START_FADEOUT_TIME = 1.0f; for (uint32 blockAnimationIndex = 0; blockAnimationIndex < m_blockAnimations.GetSize();) { BlockAnimation *pAnimation = &m_blockAnimations[blockAnimationIndex]; // update time remaining pAnimation->TimeRemaining -= deltaTime; // physics block? if (pAnimation->pRigidBody != nullptr) { // handle timeouts if (pAnimation->TimeRemaining <= 0.0f) { m_pPhysicsWorld->RemoveObject(pAnimation->pRigidBody); pAnimation->pRigidBody->Release(); m_pRenderWorld->RemoveRenderable(pAnimation->pRenderProxy); pAnimation->pRenderProxy->Release(); m_blockAnimations.OrderedRemove(blockAnimationIndex); continue; } // pull the transform from the rigid body, test if it's changed, if so, update the render proxy Transform newTransform(pAnimation->pRigidBody->GetTransform()); if (newTransform != pAnimation->LastTransform) pAnimation->pRenderProxy->SetTransform(newTransform.GetTransformMatrix4x4()); // handle fade-out if (pAnimation->TimeRemaining <= BLOCK_START_FADEOUT_TIME) { float opacity = Math::Saturate(pAnimation->TimeRemaining / BLOCK_START_FADEOUT_TIME); pAnimation->pRenderProxy->SetTintColor(MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, Math::Truncate(opacity * 255.0f))); } } // spawn block? else { // handle timeouts if (pAnimation->TimeRemaining <= 0.0f) { // handle set after spawn if (pAnimation->SetAfterCompletion) { // we keep the animation around for one more frame, to allow the chunk to re-mesh SetBlockType(pAnimation->LocationX, pAnimation->LocationY, pAnimation->LocationZ, pAnimation->BlockType, BLOCK_WORLD_BLOCK_ROTATION_NORTH, true); pAnimation->SetAfterCompletion = false; pAnimation->TimeRemaining = 0.0f; } else { // remove it m_pRenderWorld->RemoveRenderable(pAnimation->pRenderProxy); pAnimation->pRenderProxy->Release(); m_blockAnimations.OrderedRemove(blockAnimationIndex); continue; } } // update the transform float factor = EasingFunction::GetCoefficient(pAnimation->AnimationFunction, 1.0f - (pAnimation->TimeRemaining / pAnimation->LifeTime)); Transform newTransform(Transform::LinearInterpolate(pAnimation->AnimationStartTransform, pAnimation->AnimationEndTransform, factor)); pAnimation->pRenderProxy->SetTransform(newTransform.GetTransformMatrix4x4()); } // next block blockAnimationIndex++; } } <file_sep>/Editor/Source/Editor/EditorTest.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/Editor.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorTerrainEditMode.h" #include "Editor/EditorResourceSelectionDialog.h" #include "Editor/EditorProgressDialog.h" #include "Editor/BlockMeshEditor/EditorBlockMeshEditor.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/StaticMeshEditor/EditorStaticMeshEditor.h" #include "Editor/SkeletalAnimationEditor/EditorSkeletalAnimationEditor.h" #include "Editor/ResourceBrowser/EditorStaticMeshImportDialog.h" #include "Engine/ResourceManager.h" #include "Engine/TerrainRendererCDLOD.h" #include "Engine/TerrainQuadTree.h" #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "Core/Image.h" #include "Core/ImageCodec.h" Log_SetChannel(EditorTest); #if Y_COMPILER_MSVC #pragma warning(disable: 4505) // warning C4505: 'TestEditorResourceSelectionDialog' : unreferenced local function has been removed #endif static void TestEditorResourceSelectionDialog() { EditorResourceSelectionDialog *dlg = new EditorResourceSelectionDialog(NULL); dlg->setModal(true); dlg->exec(); if (dlg->GetReturnValueResourceType() != NULL) Log_DevPrintf("Selected %s %s", dlg->GetReturnValueResourceType()->GetTypeName(), dlg->GetReturnValueResourceName().GetCharArray()); else Log_DevPrintf("Selected nothing"); delete dlg; } static void OpenAMap() { EditorMapWindow *pMapWindow = g_pEditor->GetMapWindow(0); DebugAssert(pMapWindow != NULL && pMapWindow->IsMapOpen()); pMapWindow->CloseMap(); #if defined(Y_PLATFORM_WINDOWS) //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Data\\testgame\\maps\\empty.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Data\\testgame\\maps\\test_terrain.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Documentation\\MCWorlds\\maps\\mc_test7.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Data\\testgame\\maps\\sponza.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Data\\testgame\\maps\\blah.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\Data\\testgame\\maps\\test_terrain.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\test_entity.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\mctest3.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\mctest3_l.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\onemesh.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\test_terrain3.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\platformer-set1.map"); //pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\jazz_o.map"); pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\test_objects.map"); #elif defined(Y_PLATFORM_LINUX) //pMapWindow->OpenMap("/home/user/dev/yage/Data/testgame/maps/empty.map"); //pMapWindow->OpenMap("/home/user/dev/yage/Documentation/MCWorlds/maps.mc_test7.map"); //pMapWindow->OpenMap("/home/user/dev/yage/Data/testgame/maps/sponza.map"); #endif if (!pMapWindow->IsMapOpen()) pMapWindow->NewMap(); } static void OpenSponzaMap() { EditorMapWindow *pMapWindow = g_pEditor->GetMapWindow(0); DebugAssert(pMapWindow != NULL && pMapWindow->IsMapOpen()); pMapWindow->CloseMap(); #if defined(Y_PLATFORM_WINDOWS) pMapWindow->OpenMap("D:\\Projects\\GameEngineDev\\TestGame\\Data\\maps\\sponza.map"); #elif defined(Y_PLATFORM_LINUX) pMapWindow->OpenMap("/home/user/dev/yage/Data/testgame/maps/sponza.map"); #endif } static void SetRendererPlatform() { #if defined(Y_PLATFORM_WINDOWS) //g_pConsole->SetCVarByName("r_platform", "D3D11"); //g_pConsole->SetCVarByName("r_d3d11_force_ref", "1"); //g_pConsole->SetCVarByName("r_d3d11_force_warp", "1"); //g_pConsole->SetCVarByName("r_platform", "OpenGL"); //g_pConsole->SetCVarByName("r_dump_shaders", "1"); g_pConsole->SetCVarByName("r_dump_shaders", "0"); #elif defined(Y_PLATFORM_LINUX) //g_pConsole->SetCVarByName("r_platform", "OpenGL"); //g_pConsole->SetCVarByName("r_dump_shaders", "1"); g_pConsole->SetCVarByName("r_dump_shaders", "0"); #endif } static void DecompressImageFileToB64(const char *path, const char *outPath) { AutoReleasePtr<ByteStream> pStream = FileSystem::OpenFile(path, BYTESTREAM_OPEN_READ); if (pStream == NULL) return; ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(path, pStream); if (pCodec == NULL) return; Image outImage; if (!pCodec->DecodeImage(&outImage, path, pStream) || !outImage.ConvertPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM)) { return; } uint32 len = Y_getencodedbase64length(outImage.GetDataSize()); String base64; base64.Resize(len); uint32 outlen = Y_makebase64(outImage.GetData(), outImage.GetDataSize(), base64, base64.GetLength() + 1); if (outlen != len) return; AutoReleasePtr<ByteStream> pOutStream = FileSystem::OpenFile(outPath, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE); if (pOutStream == NULL) return; pOutStream->Write2(base64.GetCharArray(), base64.GetLength()); } static void EmptyTerrain() { EditorMapWindow *pMapWindow = g_pEditor->GetMapWindow(0); DebugAssert(pMapWindow != NULL && pMapWindow->IsMapOpen()); //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 128, 4, Y_INT32_MIN, Y_INT32_MAX, 0)) //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 512, 5, -4000, 4000, 0)) //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 128, 4, -500, 500, 0)) if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 128, 5, -500, 500, 0)) //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 512, 5, 0, 1000, 0)) return; EditorTerrainEditMode *pTerrainEditMode = pMapWindow->GetMap()->GetTerrainEditMode(); DebugAssert(pTerrainEditMode != nullptr); // create center section pTerrainEditMode->CreateSection(0, 0, 0.0f, 0); //pTerrainEditMode->CreateSection(1, 0, 0.0f, 0); //pTerrainEditMode->CreateSection(0, 1, 0.0f, 0); //pTerrainEditMode->CreateSection(1, 1, 0.0f, 0); //g_pConsole->SetCVarByName("r_terrain_show_nodes", "1"); //pMapWindow->GetMap()->GetTerrainEditMode()->SetPointHeight(1, 1, 2.0f); //pMapWindow->GetMap()->GetTerrainEditMode()->SetPointHeight(1, 2, 2.0f); //pMapWindow->GetMap()->GetTerrainEditMode()->SetPointHeight(2, 1, 2.0f); //pMapWindow->GetMap()->GetTerrainEditMode()->SetPointHeight(2, 2, 2.0f); pMapWindow->GetViewport(0)->GetViewController().SetPerspectiveMaxSpeed(10.0f); pMapWindow->GetViewport(0)->GetViewController().SetDrawDistance(400.0f); } static void SetHeights() { const float heightStep = 1.0f; const int32 layerCountToSplit = 3; EditorMapWindow *pMapWindow = g_pEditor->GetMapWindow(0); DebugAssert(pMapWindow != NULL && pMapWindow->IsMapOpen()); //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 128, 4, Y_INT32_MIN, Y_INT32_MAX, 0)) if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 512, 5, -4000, 4000, 0)) //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 128, 4, -500, 500, 0)) //if (!pMapWindow->GetMap()->CreateTerrain(nullptr, TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32, 1, 8, 1, -100, 100, 0)) return; MapSourceTerrainData *pTerrainData = pMapWindow->GetMap()->GetMapSource()->GetTerrainData(); if (pTerrainData == NULL) return; EditorProgressDialog progressDialog(pMapWindow); progressDialog.show(); // create center section pTerrainData->CreateSection(0, 0, 0.0f, 0, &progressDialog); pTerrainData->CreateSection(1, 0, 0.0f, 0, &progressDialog); /*for (uint32 i = 0; i < 4; i++) { for (uint32 j = 0; j < 4; j++) pTerrainManager->CreateSection(j, i, &progressDialog); }*/ int32 terrainMinX = pTerrainData->GetMinSectionX() * (int32)pTerrainData->GetParameters()->SectionSize; int32 terrainMinY = pTerrainData->GetMinSectionY() * (int32)pTerrainData->GetParameters()->SectionSize; int32 terrainSizeX = pTerrainData->GetSectionCountX() * (int32)pTerrainData->GetParameters()->SectionSize; int32 terrainSizeY = pTerrainData->GetSectionCountY() * (int32)pTerrainData->GetParameters()->SectionSize; int32 layerInterval = terrainSizeY / layerCountToSplit + 1; float currentHeight = 0.0f; uint8 currentLayer = 0; progressDialog.SetStatusText("Filling terrain..."); progressDialog.SetProgressRange(terrainSizeY); progressDialog.SetProgressValue(0); for (int32 y = 0; y < terrainSizeY; y++) { for (int32 x = 0; x < terrainSizeX; x++) { //int32 x =0; pTerrainData->SetPointHeight(x + terrainMinX, y + terrainMinY, currentHeight); pTerrainData->AddPointLayerWeight(x + terrainMinX, y + terrainMinY, currentLayer, 1.0f); } if (currentLayer != 1) currentHeight += heightStep; if (y > 0 && (y % layerInterval) == 0) currentLayer++; progressDialog.IncrementProgressValue(); } pTerrainData->RebuildQuadTree(pTerrainData->GetParameters()->LODCount, &progressDialog); g_pConsole->SetCVarByName("r_terrain_show_nodes", "1"); pMapWindow->GetViewport(0)->GetViewController().SetPerspectiveMaxSpeed(10.0f); } static void TestStaticBlockMeshEditor() { EditorBlockMeshEditor *pEditor = new EditorBlockMeshEditor(); //if (!pEditor->Create(g_pResourceManager->GetDefaultBlockMeshBlockList())) //Panic("fail"); //EditorProgressDialog progressDialog(pEditor); //progressDialog.show(); if (!pEditor->Load("models/test/house")) //if (!pEditor->Load("models/test/test2", &progressDialog)) Panic("Fail"); pEditor->show(); pEditor->SetWidget(EditorBlockMeshEditor::WIDGET_PLACE_BLOCKS); pEditor->SetPlaceBlockWidgetBlockType(1); } static void TestStaticMeshEditor() { EditorStaticMeshEditor *pEditor = new EditorStaticMeshEditor(); //pEditor->Create("models/test/test"); //pEditor->Create("models/test/house"); if (pEditor->Load("models/suburb_assets/house_mid")) pEditor->show(); //else //delete pEditor; } static void TestSkeletalAnimationEditor() { EditorSkeletalAnimationEditor *editor = new EditorSkeletalAnimationEditor(); if (editor->Load("models/ninja/ninja_jump")) //if (editor->Load("models/mario/mario")) editor->show(); else delete editor; } static void TestStaticMeshImporter() { EditorStaticMeshImportDialog *id = new EditorStaticMeshImportDialog(nullptr); id->show(); } void RunEditorTestBedsPreStartup() { SetRendererPlatform(); } void RunEditorTestBeds() { //TestEditorResourceSelectionDialog(); //DecompressImageFileToB64("D:\\Untitled.png", "D:\\untitled.txt"); //DecompressImageFileToB64("D:\\Untitled2.png", "D:\\untitled2.txt"); //DecompressImageFileToB64("D:\\Untitled3.png", "D:\\untitled3.txt"); //OpenAMap(); //EmptyTerrain(); //SetHeights(); //TestStaticBlockMeshEditor(); //TestStaticMeshEditor(); //TestSkeletalAnimationEditor(); //OpenSponzaMap(); } <file_sep>/Engine/Source/MathLib/Vectoru.h #pragma once #include "MathLib/Common.h" #include "MathLib/VectorShuffles.h" // interoperability between int/vector types struct Vector2i; struct Vector2ui; struct Vector3i; struct Vector3ui; struct Vector4i; struct Vector4ui; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector2u { // constructors inline Vector2u() {} inline Vector2u(uint32 x_, uint32 y_) : x(x_), y(y_) {} inline Vector2u(uint32 *p) : x(p[0]), y(p[1]) {} inline Vector2u(const Vector2u &v) : x(v.x), y(v.y) {} Vector2u(const Vector2ui &v); // setters void Set(uint32 x_, uint32 y_) { x = x_; y = y_; } void Set(const Vector2u &v) { x = v.x; y = v.y; } void Set(const Vector2ui &v); void SetZero() { x = y = 0; } // load/store void Load(const uint32 *v) { x = v[0]; y = v[1]; } void Store(uint32 *v) const { v[0] = x; v[1] = y; } // new vector Vector2u operator+(const Vector2u &v) const { return Vector2u(x + v.x, y + v.y); } Vector2u operator-(const Vector2u &v) const { return Vector2u(x - v.x, y - v.y); } Vector2u operator*(const Vector2u &v) const { return Vector2u(x * v.x, y * v.y); } Vector2u operator/(const Vector2u &v) const { return Vector2u(x / v.x, y / v.y); } Vector2u operator%(const Vector2u &v) const { return Vector2u(x % v.x, y % v.y); } Vector2u operator&(const Vector2u &v) const { return Vector2u(x & v.x, y & v.y); } Vector2u operator|(const Vector2u &v) const { return Vector2u(x | v.x, y | v.y); } Vector2u operator^(const Vector2u &v) const { return Vector2u(x ^ v.x, y ^ v.y); } // scalar operators Vector2u operator+(const uint32 v) const { return Vector2u(x + v, y + v); } Vector2u operator-(const uint32 v) const { return Vector2u(x - v, y - v); } Vector2u operator*(const uint32 v) const { return Vector2u(x * v, y * v); } Vector2u operator/(const uint32 v) const { return Vector2u(x / v, y / v); } Vector2u operator%(const uint32 v) const { return Vector2u(x % v, y % v); } Vector2u operator&(const uint32 v) const { return Vector2u(x & v, y & v); } Vector2u operator|(const uint32 v) const { return Vector2u(x | v, y | v); } Vector2u operator^(const uint32 v) const { return Vector2u(x ^ v, y ^ v); } // no params Vector2u operator~() const { return Vector2u(~x, ~y); } // comparison operators bool operator==(const Vector2u &v) const { return (x == v.x && y == v.y); } bool operator!=(const Vector2u &v) const { return (x != v.x || y != v.y); } bool operator<=(const Vector2u &v) const { return (x <= v.x && y <= v.y); } bool operator>=(const Vector2u &v) const { return (x >= v.x && y >= v.y); } bool operator<(const Vector2u &v) const { return (x < v.x && y < v.y); } bool operator>(const Vector2u &v) const { return (x > v.x && y > v.y); } // modifies this vector Vector2u &operator+=(const Vector2u &v) { x += v.x; y += v.y; return *this; } Vector2u &operator-=(const Vector2u &v) { x -= v.x; y -= v.y; return *this; } Vector2u &operator*=(const Vector2u &v) { x *= v.x; y *= v.y; return *this; } Vector2u &operator/=(const Vector2u &v) { x /= v.x; y /= v.y; return *this; } Vector2u &operator%=(const Vector2u &v) { x %= v.x; y %= v.y; return *this; } Vector2u &operator&=(const Vector2u &v) { x &= v.x; y &= v.y; return *this; } Vector2u &operator|=(const Vector2u &v) { x |= v.x; y |= v.y; return *this; } Vector2u &operator^=(const Vector2u &v) { x ^= v.x; y ^= v.y; return *this; } Vector2u &operator=(const Vector2u &v) { x = v.x; y = v.y; return *this; } // scalar operators Vector2u &operator+=(const uint32 v) { x += v; y += v; return *this; } Vector2u &operator-=(const uint32 v) { x -= v; y -= v; return *this; } Vector2u &operator*=(const uint32 v) { x *= v; y *= v; return *this; } Vector2u &operator/=(const uint32 v) { x /= v; y /= v; return *this; } Vector2u &operator%=(const uint32 v) { x %= v; y %= v; return *this; } Vector2u &operator&=(const uint32 v) { x &= v; y &= v; return *this; } Vector2u &operator|=(const uint32 v) { x |= v; y |= v; return *this; } Vector2u &operator^=(const uint32 v) { x ^= v; y ^= v; return *this; } Vector2u &operator=(const uint32 v) { x = v; y = v; return *this; } // Vector2ui Vector2u &operator=(const Vector2ui &v); // index accessors const uint32 &operator[](uint32 i) const { return (&x)[i]; } uint32 &operator[](uint32 i) { return (&x)[i]; } operator const uint32 *() const { return &x; } operator uint32 *() { return &x; } // to vectorx Vector2ui GetVector2ui() const; // partial comparisons bool AnyLess(const Vector2u &v) const { return (x < v.x || y < v.y); } bool AnyGreater(const Vector2u &v) const { return (x > v.x || y > v.y); } //bool NearEqual(const uint2 &v, uint32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon); } // modification functions Vector2u Min(const Vector2u &v) const { return Vector2u((x > v.x) ? v.x : x, (y > v.y) ? v.y : y); } Vector2u Max(const Vector2u &v) const { return Vector2u((x < v.x) ? v.x : x, (y < v.y) ? v.y : y); } Vector2u Clamp(const Vector2u &lBounds, const Vector2u &uBounds) const { return Min(uBounds).Max(lBounds); } Vector2u Saturate() const { return Clamp(Zero, One); } Vector2u Snap(const Vector2u &v) const { return Vector2u(Math::Snap(x, v.x), Math::Snap(y, v.y)); } // swap void Swap(Vector2u &v) { uint32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; } // maximum of all components uint32 MinOfComponents() const { return ::Min(x, y); } uint32 MaxOfComponents() const { return ::Max(x, y); } // shuffles template<int V0, int V1> Vector2u Shuffle2() const { const uint32 *pv = (const uint32 *)&x; Vector2u result; result.x = pv[V0]; result.y = pv[V1]; return result; } VECTOR2_SHUFFLE_FUNCTIONS(Vector2u); //---------------------------------------------------------------------- union { struct { uint32 x, y; }; struct { uint32 r, g; }; uint32 ele[2]; }; //---------------------------------------------------------------------- static const Vector2u &Zero, &One; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector3u { // constructors inline Vector3u() {} inline Vector3u(uint32 x_, uint32 y_, uint32 z_) : x(x_), y(y_), z(z_) {} inline Vector3u(uint32 *p) : x(p[0]), y(p[1]), z(p[2]) {} inline Vector3u(const Vector2u &v, uint32 z_ = 0) : x(v.x), y(v.y), z(z_) {} inline Vector3u(const Vector3u &v) : x(v.x), y(v.y), z(v.z) {} Vector3u(const Vector3ui &v); // setters void Set(uint32 x_, uint32 y_, uint32 z_) { x = x_; y = y_; z = z_; } void Set(const Vector2u &v, uint32 z_ = 0) { x = v.x; y = v.y; z = z_; } void Set(const Vector3u &v) { x = v.x; y = v.y; z = v.z; } void Set(const Vector3ui &v); void SetZero() { x = y = z = 0; } // load/store void Load(const uint32 *v) { x = v[0]; y = v[1]; z = v[2]; } void Store(uint32 *v) const { v[0] = x; v[1] = y; v[2] = z;} // new vector Vector3u operator+(const Vector3u &v) const { return Vector3u(x + v.x, y + v.y, z + v.z); } Vector3u operator-(const Vector3u &v) const { return Vector3u(x - v.x, y - v.y, z - v.z); } Vector3u operator*(const Vector3u &v) const { return Vector3u(x * v.x, y * v.y, z * v.z); } Vector3u operator/(const Vector3u &v) const { return Vector3u(x / v.x, y / v.y, z / v.z); } Vector3u operator%(const Vector3u &v) const { return Vector3u(x % v.x, y % v.y, z % v.z); } Vector3u operator&(const Vector3u &v) const { return Vector3u(x & v.x, y & v.y, z & v.z); } Vector3u operator|(const Vector3u &v) const { return Vector3u(x | v.x, y | v.y, z | v.z); } Vector3u operator^(const Vector3u &v) const { return Vector3u(x ^ v.x, y ^ v.y, z ^ v.z); } // scalar operators Vector3u operator+(const uint32 v) const { return Vector3u(x + v, y + v, z + v); } Vector3u operator-(const uint32 v) const { return Vector3u(x - v, y - v, z - v); } Vector3u operator*(const uint32 v) const { return Vector3u(x * v, y * v, z * v); } Vector3u operator/(const uint32 v) const { return Vector3u(x / v, y / v, z / v); } Vector3u operator%(const uint32 v) const { return Vector3u(x % v, y % v, z % v); } Vector3u operator&(const uint32 v) const { return Vector3u(x & v, y & v, z & v); } Vector3u operator|(const uint32 v) const { return Vector3u(x | v, y | v, z | v); } Vector3u operator^(const uint32 v) const { return Vector3u(x ^ v, y ^ v, z ^ v); } // no params Vector3u operator~() const { return Vector3u(~x, ~y, ~z); } // comparison operators bool operator==(const Vector3u &v) const { return (x == v.x && y == v.y && z == v.z); } bool operator!=(const Vector3u &v) const { return (x != v.x || y != v.y || z != v.z); } bool operator<=(const Vector3u &v) const { return (x <= v.x && y <= v.y && z <= v.z); } bool operator>=(const Vector3u &v) const { return (x >= v.x && y >= v.y && z >= v.z); } bool operator<(const Vector3u &v) const { return (x < v.x && y < v.y && z < v.z); } bool operator>(const Vector3u &v) const { return (x > v.x && y > v.y && z > v.z); } // modifies this vector Vector3u &operator+=(const Vector3u &v) { x += v.x; y += v.y; z += v.z; return *this; } Vector3u &operator-=(const Vector3u &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3u &operator*=(const Vector3u &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } Vector3u &operator/=(const Vector3u &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } Vector3u &operator%=(const Vector3u &v) { x %= v.x; y %= v.y; z %= v.z; return *this; } Vector3u &operator&=(const Vector3u &v) { x &= v.x; y &= v.y; z &= v.z; return *this; } Vector3u &operator|=(const Vector3u &v) { x |= v.x; y |= v.y; z |= v.z; return *this; } Vector3u &operator^=(const Vector3u &v) { x ^= v.x; y ^= v.y; z ^= v.z; return *this; } Vector3u &operator=(const Vector3u &v) { x = v.x; y = v.y; z = v.z; return *this; } // scalar operators Vector3u &operator+=(const uint32 v) { x += v; y += v; z += v; return *this; } Vector3u &operator-=(const uint32 v) { x -= v; y -= v; z -= v; return *this; } Vector3u &operator*=(const uint32 v) { x *= v; y *= v; z *= v; return *this; } Vector3u &operator/=(const uint32 v) { x /= v; y /= v; z /= v; return *this; } Vector3u &operator%=(const uint32 v) { x %= v; y %= v; z %= v; return *this; } Vector3u &operator&=(const uint32 v) { x &= v; y &= v; z &= v; return *this; } Vector3u &operator|=(const uint32 v) { x |= v; y |= v; z |= v; return *this; } Vector3u &operator^=(const uint32 v) { x ^= v; y ^= v; z ^= v; return *this; } Vector3u &operator=(const uint32 v) { x = v; y = v; z = v; return *this; } // vector3i Vector3u &operator=(const Vector3i &v); // index accessors const uint32 &operator[](uint32 i) const { return (&x)[i]; } uint32 &operator[](uint32 i) { return (&x)[i]; } operator const uint32 *() const { return &x; } operator uint32 *() { return &x; } // to vectorx Vector3ui GetVector3ui() const; // partial comparisons bool AnyLess(const Vector3u &v) const { return (x < v.x || y < v.y || z < v.z); } bool AnyGreater(const Vector3u &v) const { return (x > v.x || y > v.y || z > v.z); } //bool NearEqual(const uint3 &v, uint32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon || abs(z - v.z) <= Epsilon); } // modification functions Vector3u Min(const Vector3u &v) const { return Vector3u((x > v.x) ? v.x : x, (y > v.y) ? v.y : y, (z > v.z) ? v.z : z); } Vector3u Max(const Vector3u &v) const { return Vector3u((x < v.x) ? v.x : x, (y < v.y) ? v.y : y, (z < v.z) ? v.z : z); } Vector3u Clamp(const Vector3u &lBounds, const Vector3u &uBounds) const { return Min(uBounds).Max(lBounds); } Vector3u Saturate() const { return Clamp(Zero, One); } Vector3u Snap(const Vector3u &v) const { return Vector3u(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z)); } // swap void Swap(Vector3u &v) { uint32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; tmp = v.z; v.z = z; z = tmp; } // maximum of all components uint32 MinOfComponents() const { return ::Min(x, ::Min(y, z)); } uint32 MaxOfComponents() const { return ::Max(x, ::Max(y, z)); } // shuffles template<int V0, int V1> Vector2u Shuffle2() const { const uint32 *pv = (const uint32 *)&x; Vector2u result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3u Shuffle3() const { const uint32 *pv = (const uint32 *)&x; Vector3u result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } VECTOR3_SHUFFLE_FUNCTIONS(Vector2u, Vector3u); //---------------------------------------------------------------------- union { struct { uint32 x, y, z; }; struct { uint32 r, g, b; }; uint32 ele[3]; }; //---------------------------------------------------------------------- static const Vector3u &Zero, &One; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct Vector4u { // constructors inline Vector4u() {} inline Vector4u(uint32 x_, uint32 y_, uint32 z_, uint32 w_) : x(x_), y(y_), z(z_), w(w_) {} inline Vector4u(uint32 *p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) {} inline Vector4u(const Vector2u &v, uint32 z_ = 0, uint32 w_ = 0) : x(v.x), y(v.y), z(z_), w(w_) {} inline Vector4u(const Vector3u &v, uint32 w_ = 0) : x(v.x), y(v.y), z(v.z), w(w_) {} inline Vector4u(const Vector4u &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} Vector4u(const Vector4ui &v); // setters void Set(uint32 x_, uint32 y_, uint32 z_, uint32 w_) { x = x_; y = y_; z = z_; w = w_; } void Set(const Vector2u &v, uint32 z_ = 0, uint32 w_ = 0) { x = v.x; y = v.y; z = z_; w = w_; } void Set(const Vector3u &v, uint32 w_ = 0) { x = v.x; y = v.y; z = v.z; w = w_; } void Set(const Vector4u &v) { x = v.x; y = v.y; z = v.z; w = v.w; } void Set(const Vector4ui &v); void SetZero() { x = y = z = w = 0; } // load/store void Load(const uint32 *v) { x = v[0]; y = v[1]; z = v[2]; w = v[3]; } void Store(uint32 *v) const { v[0] = x; v[1] = y; v[2] = z; v[3] = w; } // new vector Vector4u operator+(const Vector4u &v) const { return Vector4u(x + v.x, y + v.y, z + v.z, w + v.w); } Vector4u operator-(const Vector4u &v) const { return Vector4u(x - v.x, y - v.y, z - v.z, w - v.w); } Vector4u operator*(const Vector4u &v) const { return Vector4u(x * v.x, y * v.y, z * v.z, w * v.w); } Vector4u operator/(const Vector4u &v) const { return Vector4u(x / v.x, y / v.y, z / v.z, w / v.w); } Vector4u operator%(const Vector4u &v) const { return Vector4u(x % v.x, y % v.y, z % v.z, w % v.w); } Vector4u operator&(const Vector4u &v) const { return Vector4u(x & v.x, y & v.y, z & v.z, w & v.w); } Vector4u operator|(const Vector4u &v) const { return Vector4u(x | v.x, y | v.y, z | v.z, w | v.w); } Vector4u operator^(const Vector4u &v) const { return Vector4u(x ^ v.x, y ^ v.y, z ^ v.z, w ^ v.w); } // scalar operators Vector4u operator+(const uint32 v) const { return Vector4u(x + v, y + v, z + v, w + v); } Vector4u operator-(const uint32 v) const { return Vector4u(x - v, y - v, z - v, w - v); } Vector4u operator*(const uint32 v) const { return Vector4u(x * v, y * v, z * v, w * v); } Vector4u operator/(const uint32 v) const { return Vector4u(x / v, y / v, z / v, w / v); } Vector4u operator%(const uint32 v) const { return Vector4u(x % v, y % v, z % v, w % v); } Vector4u operator&(const uint32 v) const { return Vector4u(x & v, y & v, z & v, w & v); } Vector4u operator|(const uint32 v) const { return Vector4u(x | v, y | v, z | v, w | v); } Vector4u operator^(const uint32 v) const { return Vector4u(x ^ v, y ^ v, z ^ v, w ^ v); } // no params Vector4u operator~() const { return Vector4u(~x, ~y, ~z, ~w); } // comparison operators bool operator==(const Vector4u &v) const { return (x == v.x && y == v.y && z == v.z && w == v.w); } bool operator!=(const Vector4u &v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); } bool operator<=(const Vector4u &v) const { return (x <= v.x && y <= v.y && z <= v.z && w <= v.w); } bool operator>=(const Vector4u &v) const { return (x >= v.x && y >= v.y && z >= v.z && w >= v.w); } bool operator<(const Vector4u &v) const { return (x < v.x && y < v.y && z < v.z && w < v.w); } bool operator>(const Vector4u &v) const { return (x > v.x && y > v.y && z > v.z && w > v.w); } // modifies this vector Vector4u &operator+=(const Vector4u &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } Vector4u &operator-=(const Vector4u &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } Vector4u &operator*=(const Vector4u &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } Vector4u &operator/=(const Vector4u &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } Vector4u &operator%=(const Vector4u &v) { x %= v.x; y %= v.y; z %= v.z; w %= v.w; return *this; } Vector4u &operator&=(const Vector4u &v) { x &= v.x; y &= v.y; z &= v.z; w &= v.w; return *this; } Vector4u &operator|=(const Vector4u &v) { x |= v.x; y |= v.y; z |= v.z; w |= v.w; return *this; } Vector4u &operator^=(const Vector4u &v) { x ^= v.x; y ^= v.y; z ^= v.z; w ^= v.w; return *this; } Vector4u &operator=(const Vector4u &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } // scalar operators Vector4u &operator+=(const uint32 v) { x += v; y += v; z += v; w += v; return *this; } Vector4u &operator-=(const uint32 v) { x -= v; y -= v; z -= v; w -= v; return *this; } Vector4u &operator*=(const uint32 v) { x *= v; y *= v; z *= v; w *= v; return *this; } Vector4u &operator/=(const uint32 v) { x /= v; y /= v; z /= v; w /= v; return *this; } Vector4u &operator%=(const uint32 v) { x %= v; y %= v; z %= v; w %= v; return *this; } Vector4u &operator&=(const uint32 v) { x &= v; y &= v; z &= v; w &= v; return *this; } Vector4u &operator|=(const uint32 v) { x |= v; y |= v; z |= v; w |= v; return *this; } Vector4u &operator^=(const uint32 v) { x ^= v; y ^= v; z ^= v; w ^= v; return *this; } Vector4u &operator=(const uint32 v) { x = v; y = v; z = v; w = v; return *this; } // vector4i Vector4u &operator=(const Vector4i &v); // index accessors const uint32 &operator[](uint32 i) const { return (&x)[i]; } uint32 &operator[](uint32 i) { return (&x)[i]; } operator const uint32 *() const { return &x; } operator uint32 *() { return &x; } // to vectorx Vector4ui GetVector4ui() const; // partial comparisons bool AnyLess(const Vector4u &v) const { return (x < v.x || y < v.y || z < v.z || w < v.w); } bool AnyGreater(const Vector4u &v) const { return (x > v.x || y > v.y || z > v.z || w > v.w); } //bool NearEqual(const uint4 &v, uint32 Epsilon) const { return (abs(x - v.x) <= Epsilon || abs(y - v.y) <= Epsilon || abs(z - v.z) <= Epsilon || abs(w - v.w) < Epsilon); } // modification functions Vector4u Min(const Vector4u &v) const { return Vector4u((x > v.x) ? v.x : x, (y > v.y) ? v.y : y, (z > v.z) ? v.z : z, (w > v.w) ? v.w : w); } Vector4u Max(const Vector4u &v) const { return Vector4u((x < v.x) ? v.x : x, (y < v.y) ? v.y : y, (z < v.z) ? v.z : z, (w < v.w) ? v.w : w); } Vector4u Clamp(const Vector4u &lBounds, const Vector4u &uBounds) const { return Min(uBounds).Max(lBounds); } Vector4u Saturate() const { return Clamp(Zero, One); } Vector4u Snap(const Vector4u &v) const { return Vector4u(Math::Snap(x, v.x), Math::Snap(y, v.y), Math::Snap(z, v.z), Math::Snap(w, v.w)); } // swap void Swap(Vector4u &v) { uint32 tmp; tmp = v.x; v.x = x; x = tmp; tmp = v.y; v.y = y; y = tmp; tmp = v.z; v.z = z; z = tmp; tmp = v.w; v.w = w; w = tmp; } // maximum of all components uint32 MinOfComponents() const { return ::Min(x, ::Min(y, ::Min(z, w))); } uint32 MaxOfComponents() const { return ::Max(x, ::Max(y, ::Max(z, w))); } // shuffles template<int V0, int V1> Vector2u Shuffle2() const { const uint32 *pv = (const uint32 *)&x; Vector2u result; result.x = pv[V0]; result.y = pv[V1]; return result; } template<int V0, int V1, int V2> Vector3u Shuffle3() const { const uint32 *pv = (const uint32 *)&x; Vector3u result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; return result; } template<int V0, int V1, int V2, int V3> Vector4u Shuffle4() const { const uint32 *pv = (const uint32 *)&x; Vector4u result; result.x = pv[V0]; result.y = pv[V1]; result.z = pv[V2]; result.w = pv[V3]; return result; } VECTOR4_SHUFFLE_FUNCTIONS(Vector2u, Vector3u, Vector4u); //---------------------------------------------------------------------- union { struct { uint32 x, y, z, w; }; struct { uint32 r, g, b, a; }; uint32 ele[4]; }; //---------------------------------------------------------------------- static const Vector4u &Zero, &One; }; <file_sep>/Engine/Source/MathLib/Plane.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" class Plane { public: Plane() {} Plane(const Vector3f &normal, const float dist) : a(normal.x), b(normal.y), c(normal.z), d(dist) {} Plane(const float &a_, const float &b_, const float &c_, const float &d_) : a(a_), b(b_), c(c_), d(d_) {} Plane(const float *p) : a(p[0]), b(p[1]), c(p[2]), d(p[3]) {} Plane(const Plane &v) : a(v.a), b(v.b), c(v.c), d(v.d) {} // convert plane to vector const Vector3f &GetNormal() const { return reinterpret_cast<const Vector3f &>(a); } const float &GetDistance() const { return d; } // setters void Set(const float &a_, const float &b_, const float &c_, const float &d_) { a = a_; b = b_; c = c_; d = d_; } Plane Normalize(); Plane NormalizeEst(); void NormalizeInPlace(); void NormalizeEstInPlace(); // distance from the plane to the specified point. float Distance(const Vector3f &p) const; // compare operators bool operator==(const Plane &v) const { return a == v.a && b == v.b && c == v.c && d == v.d; } bool operator!=(const Plane &v) const { return a != v.a && b != v.b && c != v.c && d != v.d; } // modifies this plane Plane &operator=(const Plane &v) { a = v.a; b = v.b; c = v.c; d = v.d; return *this; } Plane &operator=(const float *p) { a = p[0]; b = p[1]; c = p[2]; d = p[3]; return *this; } // calculate plane from a point and a normal static Plane FromPointAndNormal(const Vector3f &Point, const Vector3f &Normal); // calculate plane from a triangle static Plane FromTriangle(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2); // calculate intersection point of three planes static Vector3f CalculateThreePlaneIntersectionPoint(const Plane &p1, const Plane &p2, const Plane &p3); public: float a, b, c, d; }; <file_sep>/Editor/Source/Editor/EditorIconLibrary.h #pragma once #include "Editor/Common.h" class EditorIconLibrary { public: EditorIconLibrary(); ~EditorIconLibrary(); // load icons bool PreloadIcons(); // keyed icons const QIcon &GetIconByName(const char *key, uint32 size = 16) const; // gets a QIcon for the specified resource type const QIcon &GetIconForResourceType(const ResourceTypeInfo *pResourceTypeInfo, uint32 size = 16) const; // helper functions const QIcon &GetListViewDirectoryIcon(uint32 size = 16) const { return GetIconByName("Directory", size); } private: bool LoadIcon(const char *name, uint32 size) const; typedef CIStringHashTable<QIcon> IconTable; mutable IconTable m_iconTable; QIcon m_defaultIcon; }; <file_sep>/Engine/Source/Renderer/ShaderProgram.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderComponent.h" #include "Renderer/VertexFactory.h" #include "Renderer/Renderer.h" #include "Engine/MaterialShader.h" Log_SetChannel(ShaderProgram); ShaderProgram::ShaderProgram(GPUShaderProgram *pGPUProgram, uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) : m_pBaseShaderTypeInfo(pBaseShaderTypeInfo), m_pVertexFactoryTypeInfo(pVertexFactoryTypeInfo), m_pMaterialShader(pMaterialShader), m_globalShaderFlags(globalShaderFlags), m_baseShaderFlags(baseShaderFlags), m_vertexFactoryFlags(vertexFactoryFlags), m_materialShaderFlags(materialShaderFlags), m_pGPUProgram(pGPUProgram), m_pBaseShaderParameterMap(nullptr), m_pVertexFactoryParameterMap(nullptr), m_pMaterialShaderUniformParameterMap(nullptr), m_pMaterialShaderTextureParameterMap(nullptr) { GenerateBaseShaderParameterMap(); if (m_pVertexFactoryTypeInfo != nullptr) GenerateVertexFactoryParameterMap(); if (m_pMaterialShader != nullptr) { GenerateMaterialShaderUniformParameterMap(); GenerateMaterialShaderTextureParameterMap(); } } ShaderProgram::~ShaderProgram() { delete[] m_pMaterialShaderTextureParameterMap; delete[] m_pMaterialShaderUniformParameterMap; delete[] m_pVertexFactoryParameterMap; delete[] m_pBaseShaderParameterMap; //m_pGPUProgram->Release(); uint32 newRefCount = m_pGPUProgram->Release(); DebugAssert(newRefCount == 0); UNREFERENCED_PARAMETER(newRefCount); } void ShaderProgram::GenerateBaseShaderParameterMap() { uint32 nParameterBindings = m_pBaseShaderTypeInfo->GetParameterBindingCount(); uint32 programParameterCount = m_pGPUProgram->GetParameterCount(); if (nParameterBindings == 0 || programParameterCount == 0) return; const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBinding = m_pBaseShaderTypeInfo->GetParameterBindings(); m_pBaseShaderParameterMap = new int32[nParameterBindings]; for (uint32 parameterBindingIndex = 0; parameterBindingIndex < nParameterBindings; parameterBindingIndex++, pParameterBinding++) { // lookup a parameter in the program, this needs to be optimized uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < programParameterCount; parameterIndex++) { const char *parameterName; SHADER_PARAMETER_TYPE parameterType; uint32 arraySize; m_pGPUProgram->GetParameterInformation(parameterIndex, &parameterName, &parameterType, &arraySize); if (Y_strcmp(parameterName, pParameterBinding->ParameterName) == 0) { // check type if (parameterType != pParameterBinding->ExpectedType) Log_WarningPrintf("ShaderMap::Program::GenerateBaseShaderParameterMap: Parameter '%s' type mismatch (expected %s got %s)", parameterName, NameTable_GetNameString(NameTables::ShaderParameterType, pParameterBinding->ExpectedType), NameTable_GetNameString(NameTables::ShaderParameterType, parameterType)); break; } } if (parameterIndex != programParameterCount) m_pBaseShaderParameterMap[parameterBindingIndex] = static_cast<int32>(parameterIndex); else m_pBaseShaderParameterMap[parameterBindingIndex] = -1; } } void ShaderProgram::GenerateVertexFactoryParameterMap() { uint32 nParameterBindings = m_pVertexFactoryTypeInfo->GetParameterBindingCount(); uint32 programParameterCount = m_pGPUProgram->GetParameterCount(); if (nParameterBindings == 0 || programParameterCount == 0) return; const SHADER_COMPONENT_PARAMETER_BINDING *pParameterBinding = m_pVertexFactoryTypeInfo->GetParameterBindings(); m_pVertexFactoryParameterMap = new int32[nParameterBindings]; for (uint32 parameterBindingIndex = 0; parameterBindingIndex < nParameterBindings; parameterBindingIndex++, pParameterBinding++) { // lookup a parameter in the program, this needs to be optimized uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < programParameterCount; parameterIndex++) { const char *parameterName; SHADER_PARAMETER_TYPE parameterType; uint32 arraySize; m_pGPUProgram->GetParameterInformation(parameterIndex, &parameterName, &parameterType, &arraySize); if (Y_strcmp(parameterName, pParameterBinding->ParameterName) == 0) { // check type if (parameterType != pParameterBinding->ExpectedType) Log_WarningPrintf("ShaderMap::Program::GenerateVertexFactoryParameterMap: Parameter '%s' type mismatch (expected %s got %s)", parameterName, NameTable_GetNameString(NameTables::ShaderParameterType, pParameterBinding->ExpectedType), NameTable_GetNameString(NameTables::ShaderParameterType, parameterType)); break; } } if (parameterIndex != programParameterCount) m_pVertexFactoryParameterMap[parameterBindingIndex] = static_cast<int32>(parameterIndex); else m_pVertexFactoryParameterMap[parameterBindingIndex] = -1; } } void ShaderProgram::GenerateMaterialShaderUniformParameterMap() { uint32 nUniformBindings = m_pMaterialShader->GetUniformParameterCount(); uint32 programParameterCount = m_pGPUProgram->GetParameterCount(); if (nUniformBindings == 0 || programParameterCount == 0) return; m_pMaterialShaderUniformParameterMap = new int32[nUniformBindings]; for (uint32 uniformIndex = 0; uniformIndex < nUniformBindings; uniformIndex++) { const MaterialShader::UniformParameter *pUniformParameter = m_pMaterialShader->GetUniformParameter(uniformIndex); SmallString shaderParameterName; shaderParameterName.Format("MTLUniformParameter_%s", pUniformParameter->Name.GetCharArray()); uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < programParameterCount; parameterIndex++) { const char *parameterName; SHADER_PARAMETER_TYPE parameterType; uint32 arraySize; m_pGPUProgram->GetParameterInformation(parameterIndex, &parameterName, &parameterType, &arraySize); if (Y_strcmp(parameterName, shaderParameterName) == 0) { // check type if (parameterType != pUniformParameter->Type) Log_WarningPrintf("ShaderMap::Program::GenerateMaterialShaderUniformParameterMap: Parameter '%s' type mismatch (expected %s got %s)", parameterName, NameTable_GetNameString(NameTables::ShaderParameterType, pUniformParameter->Type), NameTable_GetNameString(NameTables::ShaderParameterType, parameterType)); break; } } if (parameterIndex != programParameterCount) m_pMaterialShaderUniformParameterMap[uniformIndex] = static_cast<int32>(parameterIndex); else m_pMaterialShaderUniformParameterMap[uniformIndex] = -1; } } void ShaderProgram::GenerateMaterialShaderTextureParameterMap() { // get texture parameter count uint32 nTextureParameters = m_pMaterialShader->GetTextureParameterCount(); uint32 programParameterCount = m_pGPUProgram->GetParameterCount(); if (nTextureParameters == 0 || programParameterCount == 0) return; // post processed materials adds a few textures -- todo turn this into "material system parameters" static const char *postProcessParameterNames[] = { "MTLPostProcessParameter_SceneColor", "MTLPostProcessParameter_SceneDepth" }; if (m_pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) nTextureParameters += countof(postProcessParameterNames); // alloc m_pMaterialShaderTextureParameterMap = new int32[nTextureParameters]; for (uint32 textureIndex = 0; textureIndex < m_pMaterialShader->GetTextureParameterCount(); textureIndex++) { const MaterialShader::TextureParameter *pTextureParameter = m_pMaterialShader->GetTextureParameter(textureIndex); SmallString shaderParameterName; shaderParameterName.Format("MTLTextureParameter_%s", pTextureParameter->Name.GetCharArray()); uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < programParameterCount; parameterIndex++) { const char *parameterName; SHADER_PARAMETER_TYPE parameterType; uint32 arraySize; m_pGPUProgram->GetParameterInformation(parameterIndex, &parameterName, &parameterType, &arraySize); if (Y_strcmp(parameterName, shaderParameterName) == 0) { /*// check type if (parameterType != pTextureParameter->Type) Log_WarningPrintf("ShaderMap::Program::GenerateMaterialShaderTextureParameterMap: Parameter '%s' type mismatch (expected %s got %s)", parameterName, NameTable_GetNameString(NameTables::ShaderParameterType, pTextureParameter->Type), NameTable_GetNameString(NameTables::ShaderParameterType, parameterType));*/ break; } } if (parameterIndex != programParameterCount) m_pMaterialShaderTextureParameterMap[textureIndex] = static_cast<int32>(parameterIndex); else m_pMaterialShaderTextureParameterMap[textureIndex] = -1; } // add post processed textures if (m_pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) { for (uint32 i = 0; i < countof(postProcessParameterNames); i++) { uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < programParameterCount; parameterIndex++) { const char *parameterName; SHADER_PARAMETER_TYPE parameterType; uint32 arraySize; m_pGPUProgram->GetParameterInformation(parameterIndex, &parameterName, &parameterType, &arraySize); if (Y_strcmp(parameterName, postProcessParameterNames[i]) == 0) break; } if (parameterIndex != programParameterCount) m_pMaterialShaderTextureParameterMap[m_pMaterialShader->GetTextureParameterCount() + i] = static_cast<int32>(parameterIndex); else m_pMaterialShaderTextureParameterMap[m_pMaterialShader->GetTextureParameterCount() + i] = -1; } } } int32 ShaderProgram::Compare(const ShaderProgram *a, const ShaderProgram *b) { ptrdiff_t diff; if ((diff = a->m_pBaseShaderTypeInfo - b->m_pBaseShaderTypeInfo) != 0) return (int32)diff; if ((diff = a->m_pVertexFactoryTypeInfo - b->m_pVertexFactoryTypeInfo) != 0) return (int32)diff; if ((diff = a->m_pMaterialShader - b->m_pMaterialShader) != 0) return (int32)diff; int32 fdiff; if ((fdiff = (int32)a->m_globalShaderFlags - (int32)b->m_globalShaderFlags) != 0) return (int32)diff; if ((fdiff = (int32)a->m_baseShaderFlags - (int32)b->m_baseShaderFlags) != 0) return (int32)diff; if ((fdiff = (int32)a->m_vertexFactoryFlags - (int32)b->m_vertexFactoryFlags) != 0) return (int32)diff; if ((fdiff = (int32)a->m_materialShaderFlags - (int32)b->m_materialShaderFlags) != 0) return (int32)diff; // Hashing would be better than this.... return 0; } void ShaderProgram::SetBaseShaderParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterValue(m_pBaseShaderParameterMap[index], type, pValue); } void ShaderProgram::SetBaseShaderParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterValueArray(m_pBaseShaderParameterMap[index], type, pValues, firstElement, numElements); } void ShaderProgram::SetBaseShaderParameterStruct(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterStruct(m_pBaseShaderParameterMap[index], pValue, valueSize); } void ShaderProgram::SetBaseShaderParameterStructArray(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterStructArray(m_pBaseShaderParameterMap[index], pValue, valueSize, firstElement, numElements); } void ShaderProgram::SetBaseShaderParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterResource(m_pBaseShaderParameterMap[index], pResource); } void ShaderProgram::SetBaseShaderParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const { DebugAssert(index < m_pBaseShaderTypeInfo->GetParameterBindingCount()); if (m_pBaseShaderParameterMap[index] >= 0) pCommandList->SetShaderParameterTexture(m_pBaseShaderParameterMap[index], pTexture, pSamplerState); } void ShaderProgram::SetVertexFactoryParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterValue(m_pVertexFactoryParameterMap[index], type, pValue); } void ShaderProgram::SetVertexFactoryParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterValueArray(m_pVertexFactoryParameterMap[index], type, pValues, firstElement, numElements); } void ShaderProgram::SetVertexFactoryParameterStruct(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterStruct(m_pVertexFactoryParameterMap[index], pValue, valueSize); } void ShaderProgram::SetVertexFactoryParameterStructArray(GPUCommandList *pCommandList, uint32 index, const void *pValue, uint32 valueSize, uint32 firstElement, uint32 numElements) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterStructArray(m_pVertexFactoryParameterMap[index], pValue, valueSize, firstElement, numElements); } void ShaderProgram::SetVertexFactoryParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterResource(m_pVertexFactoryParameterMap[index], pResource); } void ShaderProgram::SetVertexFactoryParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const { DebugAssert(index < m_pVertexFactoryTypeInfo->GetParameterBindingCount()); if (m_pVertexFactoryParameterMap[index] >= 0) pCommandList->SetShaderParameterTexture(m_pVertexFactoryParameterMap[index], pTexture, pSamplerState); } void ShaderProgram::SetMaterialParameterValue(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValue) const { DebugAssert(index < m_pMaterialShader->GetUniformParameterCount()); if (m_pMaterialShaderUniformParameterMap[index] >= 0) pCommandList->SetShaderParameterValue(m_pMaterialShaderUniformParameterMap[index], type, pValue); } void ShaderProgram::SetMaterialParameterValueArray(GPUCommandList *pCommandList, uint32 index, SHADER_PARAMETER_TYPE type, const void *pValues, uint32 firstElement, uint32 numElements) const { DebugAssert(index < m_pMaterialShader->GetUniformParameterCount()); if (m_pMaterialShaderUniformParameterMap[index] >= 0) pCommandList->SetShaderParameterValueArray(m_pMaterialShaderUniformParameterMap[index], type, pValues, firstElement, numElements); } void ShaderProgram::SetMaterialParameterResource(GPUCommandList *pCommandList, uint32 index, GPUResource *pResource) const { DebugAssert(index < m_pMaterialShader->GetTextureParameterCount()); if (m_pMaterialShaderTextureParameterMap[index] >= 0) pCommandList->SetShaderParameterResource(m_pMaterialShaderTextureParameterMap[index], pResource); } void ShaderProgram::SetMaterialParameterTexture(GPUCommandList *pCommandList, uint32 index, GPUTexture *pTexture, GPUSamplerState *pSamplerState) const { DebugAssert(index < m_pMaterialShader->GetTextureParameterCount() + (m_pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) * 2); if (m_pMaterialShaderTextureParameterMap[index] >= 0) pCommandList->SetShaderParameterTexture(m_pMaterialShaderTextureParameterMap[index], pTexture, pSamplerState); } <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUOutputBuffer.h #pragma once #include "D3D12Renderer/D3D12Common.h" #include "D3D12Renderer/D3D12DescriptorHeap.h" class D3D12GPUOutputBuffer : public GPUOutputBuffer { public: virtual ~D3D12GPUOutputBuffer(); // virtual methods virtual uint32 GetWidth() const override { return m_width; } virtual uint32 GetHeight() const override { return m_height; } virtual void SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) override; // creation static D3D12GPUOutputBuffer *Create(D3D12GPUDevice *pDevice, IDXGIFactory4 *pDXGIFactory, ID3D12Device *pD3DDevice, ID3D12CommandQueue *pCommandQueue, HWND hWnd, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilFormat, RENDERER_VSYNC_TYPE vsyncType); // views HWND GetHWND() const { return m_hWnd; } ID3D12Device *GetD3DDevice() const { return m_pD3DDevice; } IDXGISwapChain3 *GetDXGISwapChain() const { return m_pDXGISwapChain; } PIXEL_FORMAT GetBackBufferFormat() const { return m_backBufferFormat; } PIXEL_FORMAT GetDepthStencilBufferFormat() const { return m_depthStencilFormat; } DXGI_FORMAT GetBackBufferDXGIFormat() const { return m_backBufferDXGIFormat; } DXGI_FORMAT GetDepthStencilBufferDXGIFormat() const { return m_depthStencilDXGIFormat; } // current backbuffer access ID3D12Resource *GetCurrentBackBufferResource() const; D3D12_CPU_DESCRIPTOR_HANDLE GetCurrentBackBufferViewDescriptorCPUHandle() const; bool UpdateCurrentBackBuffer(); // DS access ID3D12Resource *GetDepthStencilBufferResource() const { return m_pDepthStencilBuffer; } D3D12_CPU_DESCRIPTOR_HANDLE GetDepthStencilBufferViewDescriptorCPUHandle() const { return m_depthStencilViewDescriptor.CPUHandle; } bool HasDepthStencilBuffer() const { return (m_pDepthStencilBuffer != nullptr); } // resizing void InternalResizeBuffers(uint32 width, uint32 height, RENDERER_VSYNC_TYPE vsyncType); bool InternalCreateBuffers(); void InternalReleaseBuffers(); private: D3D12GPUOutputBuffer(D3D12GPUDevice *pDevice, ID3D12Device *pD3DDevice, IDXGISwapChain3 *pDXGISwapChain, HWND hWnd, uint32 width, uint32 height, PIXEL_FORMAT backBufferFormat, PIXEL_FORMAT depthStencilFormat, DXGI_FORMAT backBufferDXGIFormat, DXGI_FORMAT depthStencilDXGIFormat, RENDERER_VSYNC_TYPE vsyncType); D3D12GPUDevice *m_pDevice; ID3D12Device *m_pD3DDevice; IDXGISwapChain3 *m_pDXGISwapChain; HWND m_hWnd; uint32 m_width; uint32 m_height; PIXEL_FORMAT m_backBufferFormat; PIXEL_FORMAT m_depthStencilFormat; DXGI_FORMAT m_backBufferDXGIFormat; DXGI_FORMAT m_depthStencilDXGIFormat; uint32 m_currentBackBufferIndex; PODArray<ID3D12Resource *> m_backBuffers; ID3D12Resource *m_pDepthStencilBuffer; D3D12DescriptorHandle m_renderTargetViewsDescriptorStart; D3D12DescriptorHandle m_depthStencilViewDescriptor; }; <file_sep>/Engine/Source/ContentConverter/FontImporter.h #pragma once #include "ContentConverter/BaseImporter.h" #include "Engine/DataFormats.h" #include "Engine/Font.h" #define USE_FREETYPE2 1 struct FontImporterOptions { String InputFileName; uint32 SubFontIndex; String OutputName; bool AppendToFile; FONT_TYPE Type; uint32 RenderWidth; uint32 RenderHeight; PODArray<uint32> UnicodeCodePointSet; }; class BinaryBlob; class FontGenerator; class FontImporter : public BaseImporter { public: FontImporter(ProgressCallbacks *pProgressCallbacks); virtual ~FontImporter(); // assuming 96 dpi, convert points to pixels static uint32 ConvertPointsToPixels(float pointSize); // parse a font size with suffix, e.g. 12pt or 16px static bool ParseFontSizeString(uint32 *pOutPixels, const char *value); // list all the sub fonts in a font static void ListSubFonts(const char *fileName, ProgressCallbacks *pProgressCallbacks); // list available sizes in a bitmap font static void ListFontSizes(const char *fileName, uint32 subFontIndex, ProgressCallbacks *pProgressCallbacks); static void SetDefaultOptions(FontImporterOptions *pOptions); static bool AddCharacterSet(FontImporterOptions *pOptions, const char *blockName); static bool IsWhitespace(uint32 codePoint); bool Execute(const FontImporterOptions *pOptions); private: bool ReadInputFile(const char *fileName, uint32 subFontIndex, uint32 characterWidth, uint32 characterHeight); bool CreateNewGenerator(FONT_TYPE type); bool OpenExistingGenerator(const char *fontName); bool AddCharacters(const uint32 *pCharacters, uint32 nCharacters); bool AddBitmapCharacter(uint32 codePoint); bool AddSignedDistanceFieldCharacter(uint32 codePoint); bool SaveGenerator(const char *fontName); FontGenerator *m_pGenerator; uint32 m_renderWidth; uint32 m_renderHeight; #ifdef USE_FREETYPE2 void *m_pFreeTypeLibrary; void *m_pFreeTypeFace; bool m_fontIsBitmap; #else BinaryBlob *m_pInputFile; #endif }; <file_sep>/Engine/Source/Core/ImageCodecJPEG.cpp #include "Core/PrecompiledHeader.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/ByteStream.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Log.h" //Log_SetChannel(ImageCodecJPEG); #if 0 #include <cstdio> #include <jpeglib.h> #include <jversion.h> #pragma comment(lib, "libjpeg.lib") class ImageCodecJPEG : public ImageCodec { public: // Returns the name of the image codec const char *GetCodecName() const { return "libjpeg " JVERSION " " JCOPYRIGHT; } // Decodes the image. bool DecodeImage(Image *pOutputImage, const char *FileName, ByteStream *pInputStream, const PropertyList &decoderOptions = PropertyList::EmptyPropertyList) { // allocate memory and read in the stream uint32 CompressedDataSize = (uint32)pInputStream->GetSize(); uint32 BytesRead; byte *pCompressedData = (byte *)Y_malloc(CompressedDataSize); if ((BytesRead = pInputStream->Read(pCompressedData, CompressedDataSize)) != CompressedDataSize) { Log_ErrorPrintf("ImageCodecJPEG::DecodeImage: Only read %u of %u bytes.", BytesRead, CompressedDataSize); Y_free(pCompressedData); return false; } // todo custom error handler jpeg_decompress_struct DecompressStruct; jpeg_error_mgr ErrorMgr; DecompressStruct.err = jpeg_std_error(&ErrorMgr); jpeg_create_decompress(&DecompressStruct); jpeg_mem_src(&DecompressStruct, pCompressedData, CompressedDataSize); bool Result = false; if (jpeg_read_header(&DecompressStruct, TRUE) == JPEG_HEADER_OK) { if (jpeg_start_decompress(&DecompressStruct) == TRUE) { // set up the image uint32 Width = DecompressStruct.output_width; uint32 Height = DecompressStruct.output_height; if (DecompressStruct.out_color_space != JCS_RGB) { Log_ErrorPrintf("ImageCodecJPEG::DecodeImage: Unknown colorspace %u.", DecompressStruct.out_color_space); } else { pOutputImage->Create(PIXEL_FORMAT_R8G8B8_UNORM, Width, Height); byte *pPixels = (byte *)pOutputImage->GetData(); uint32 i; for (i = 0; i < Height; i++) { if (jpeg_read_scanlines(&DecompressStruct, (JSAMPARRAY)&pPixels, 1) != 1) break; pPixels += Width * 3; } if (i != Height) { Log_ErrorPrintf("ImageCodecJPEG::DecodeImage: Only decoded %u of %u scan lines.", i, Height); pOutputImage->Delete(); } else { Result = true; } } } jpeg_finish_decompress(&DecompressStruct); } // free up the jpeg and image data jpeg_destroy_decompress(&DecompressStruct); Y_free(pCompressedData); // return result return Result; } // Encodes the image. bool EncodeImage(const char *FileName, ByteStream *pOutputStream, const Image *pInputImage, const PropertyList &encoderOptions = PropertyList::EmptyPropertyList) { return false; } }; static ImageCodecJPEG g_ImageCodecJPEG; ImageCodec *__GetImageCodecJPEG() { return &g_ImageCodecJPEG; } #endif <file_sep>/Engine/Source/Engine/Physics/RigidBody.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/RigidBody.h" #include "Engine/Physics/CollisionShape.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/BulletHeaders.h" namespace Physics { class RigidBody::MotionState : public btMotionState { public: BT_DECLARE_ALIGNED_ALLOCATOR(); MotionState(const btTransform &transform, RigidBody *pRigidBody) : m_transform(transform), m_pRigidBody(pRigidBody) { } virtual void getWorldTransform(btTransform& worldTrans) const override { worldTrans = m_transform; } virtual void setWorldTransform(const btTransform& worldTrans) { m_transform = worldTrans; DebugAssert(m_pRigidBody->IsInWorld()); m_pRigidBody->GetPhysicsWorld()->QueueObjectSynchronization(m_pRigidBody); } void setWorldTransformNoCallback(const btTransform& worldTrans) { m_transform = worldTrans; } protected: btTransform m_transform; RigidBody *m_pRigidBody; }; RigidBody::RigidBody(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform) : CollisionObject(entityID, pCollisionShape, transform), m_isMovable(false), m_mass(1.0f), m_pMotionState(nullptr), m_pBulletRigidBody(nullptr), m_updateTransformCallbackFunction(nullptr), m_pUpdateTransformCallbackUserData(nullptr) { // only convex objects can be movable rigid bodies btCollisionShape *pBulletCollisionShape = m_pCollisionShape->GetBulletShape(); btVector3 localInertia(0.0f, 0.0f, 0.0f); m_isMovable = pBulletCollisionShape->isConvex(); if (m_isMovable) pBulletCollisionShape->calculateLocalInertia(m_mass, localInertia); // fix up it's transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // create motion state m_pMotionState = new MotionState(bulletTransform, this); // create construction info btRigidBody::btRigidBodyConstructionInfo rbConstructionInfo(m_mass, m_pMotionState, pBulletCollisionShape, localInertia); rbConstructionInfo.m_friction = 0.5f; rbConstructionInfo.m_rollingFriction = 0.0f; // create the rigid body m_pBulletRigidBody = new btRigidBody(rbConstructionInfo); m_pBulletRigidBody->setUserPointer(reinterpret_cast<void *>(this)); // update bounding box from object UpdateBoundingBox(); } RigidBody::~RigidBody() { delete m_pBulletRigidBody; delete m_pMotionState; } btCollisionObject *RigidBody::GetBulletCollisionObject() const { return static_cast<btCollisionObject *>(m_pBulletRigidBody); } void RigidBody::OnCollisionShapeChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet m_pBulletRigidBody->setCollisionShape(m_pCollisionShape->GetBulletShape()); m_pBulletRigidBody->setWorldTransform(bulletTransform); m_pMotionState->setWorldTransform(bulletTransform); // update aabb UpdateBoundingBox(); // clear forces and stuff ResetRigidBodyState(); } void RigidBody::OnTransformChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet, motion state only, since it will get pulled back next iteration m_pMotionState->setWorldTransform(bulletTransform); // fix up our copy of the aabb manually, since the collision object still contains the old transform btVector3 aabbMin, aabbMax; m_pCollisionShape->GetBulletShape()->getAabb(bulletTransform, aabbMin, aabbMax); m_boundingBox.SetBounds(BulletVector3ToFloat3(aabbMin), BulletVector3ToFloat3(aabbMax)); // clear forces and stuff ResetRigidBodyState(); } void RigidBody::OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) { PhysicsProxy::OnAddedToPhysicsWorld(pPhysicsWorld); pPhysicsWorld->GetBulletWorld()->addRigidBody(m_pBulletRigidBody); } void RigidBody::OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) { pPhysicsWorld->GetBulletWorld()->removeRigidBody(m_pBulletRigidBody); PhysicsProxy::OnRemovedFromPhysicsWorld(pPhysicsWorld); } void RigidBody::OnSynchronize() { // retrieve bullet transform btTransform bulletTransform; m_pMotionState->getWorldTransform(bulletTransform); // reverse the object's transform and update our transform copy ConvertBulletTransformToWorldTransform(bulletTransform, &m_transform); // update our aabb btVector3 aabbMin, aabbMax; m_pCollisionShape->GetBulletShape()->getAabb(bulletTransform, aabbMin, aabbMax); m_boundingBox.SetBounds(BulletVector3ToFloat3(aabbMin), BulletVector3ToFloat3(aabbMax)); // invoke game callback if (m_updateTransformCallbackFunction != nullptr) m_updateTransformCallbackFunction(m_pUpdateTransformCallbackUserData, m_transform); } void RigidBody::ResetRigidBodyState() { btCollisionShape *pBulletCollisionShape = m_pCollisionShape->GetBulletShape(); btVector3 localInertia(0.0f, 0.0f, 0.0f); m_isMovable = pBulletCollisionShape->isConvex(); if (m_isMovable) pBulletCollisionShape->calculateLocalInertia(m_mass, localInertia); // before setting it, for non-movable objects, kill all velocity if (!m_isMovable) m_pBulletRigidBody->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f)); m_pBulletRigidBody->setMassProps(m_mass, localInertia); // force it active, that way it'll settle in its new position m_pBulletRigidBody->activate(); } void RigidBody::SetMass(float mass) { m_mass = mass; ResetRigidBodyState(); } void RigidBody::SetCallbackFunction(UpdateTransformCallbackFunction callback, void *pUserData) { m_updateTransformCallbackFunction = callback; m_pUpdateTransformCallbackUserData = pUserData; } void RigidBody::ApplyCentralImpulse(const float3 &direction) { if (!IsInWorld()) return; m_pBulletRigidBody->applyCentralImpulse(Float3ToBulletVector(direction)); m_pBulletRigidBody->activate(); } void RigidBody::ResetForces() { if (!IsInWorld()) return; m_pBulletRigidBody->clearForces(); } void RigidBody::ResetVelocity() { m_pBulletRigidBody->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f)); m_pBulletRigidBody->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f)); } } // namespace Physics <file_sep>/Engine/Source/MapCompiler/CMakeLists.txt set(HEADER_FILES Common.h MapCompiler.h MapSourceGeometryData.h MapSource.h MapSourceTerrainData.h ) set(SOURCE_FILES MapCompiler.cpp MapSource.cpp MapSourceGeometryData.cpp MapSourceTerrainData.cpp ) include_directories(${ENGINE_BASE_DIRECTORY}) add_library(EngineMapCompiler STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineMapCompiler EngineMain EngineCore) <file_sep>/Engine/Source/OpenGLRenderer/PrecompiledHeader.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" <file_sep>/Engine/Source/Engine/Profiling.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/SDLHeaders.h" #include "Engine/ResourceManager.h" #include "Renderer/Renderer.h" Log_SetChannel(Profiling); #ifdef WITH_PROFILER #define MICROPROFILE_IMPL 1 #define MICROPROFILEUI_IMPL 1 #define MICROPROFILE_WEBSERVER 0 #define MICROPROFILE_CONTEXT_SWITCH_TRACE 0 #ifdef Y_COMPILER_MSVC #pragma warning(push) #pragma warning(disable: 4127) // warning C4127: conditional expression is constant #pragma warning(disable: 4512) // warning C4512: 'MicroProfileScopeLock' : assignment operator could not be generated #pragma warning(disable: 4244) // warning C4244: 'argument' : conversion from 'float' to 'int', possible loss of data #pragma warning(disable: 4245) // warning C4245: '=' : conversion from 'int' to 'uint32_t', signed/unsigned mismatch #pragma warning(disable: 4018) // warning C4018: '<' : signed/unsigned mismatch #pragma warning(disable: 4389) // warning C4389: '==' : signed/unsigned mismatch #pragma warning(disable: 4267) // warning C4267: 'initializing' : conversion from 'size_t' to 'uint32_t', possible loss of data (Engine\Profiling.cpp) #pragma warning(disable: 4456) // warning C4456: declaration of 'nLen' hides previous local declaration (compiling source file Engine\Profiling.cpp) #pragma warning(disable: 4457) // warning C4457: declaration of 'nWidth' hides function parameter #include "microprofile.h" #include "microprofileui.h" #pragma warning(pop) #else #include "microprofile.h" #include "microprofileui.h" #endif #include "Engine/Profiling.h" #define TIMESTAMP_QUERY_COUNT (8<<10) // 8192 static MiniGUIContext s_profilerGUIContext; static bool s_GPUTimingInitialized = false; static GPUQuery *s_pGPUTimestampQueries[TIMESTAMP_QUERY_COUNT] = { nullptr }; static GPUQuery *s_pGPUFrequencyQuery = nullptr; static bool s_GPUTimingAvailable = false; static uint32 s_lastGPUTimestampQuery = 0; static uint64 s_lastGPUFrequency = 1; static void InitializeGPUTiming() { DebugAssert(Renderer::IsOnRenderThread()); if (!s_GPUTimingInitialized) { s_GPUTimingInitialized = true; // create gpu frequency query s_pGPUFrequencyQuery = g_pRenderer->CreateQuery(GPU_QUERY_TYPE_FREQUENCY); if (s_pGPUFrequencyQuery == nullptr) { Log_ErrorPrintf("InitializeGPUTiming: Failed to create GPU frequency query."); s_GPUTimingAvailable = false; return; } // create timestamp queries for (uint32 i = 0; i < TIMESTAMP_QUERY_COUNT; i++) { if ((s_pGPUTimestampQueries[i] = g_pRenderer->CreateQuery(GPU_QUERY_TYPE_TIMESTAMP)) == nullptr) { for (uint32 j = 0; j < i; j++) { s_pGPUTimestampQueries[j]->Release(); s_pGPUTimestampQueries[j] = nullptr; } Log_ErrorPrintf("InitializeGPUTiming: Failed to create GPU timestamp queries."); s_pGPUFrequencyQuery->Release(); s_pGPUFrequencyQuery = nullptr; s_GPUTimingAvailable = false; return; } } s_GPUTimingAvailable = true; // kick off frequency query g_pRenderer->GetGPUContext()->BeginQuery(s_pGPUFrequencyQuery); } } void Profiling::Initialize() { MicroProfileInit(); MicroProfileInitUI(); MicroProfileSetEnableAllGroups(true); MicroProfileSetDisplayMode(MP_DRAW_OFF); MicroProfileTogglePause(); QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([]() { s_profilerGUIContext.SetGPUContext(g_pRenderer->GetGPUContext()); s_profilerGUIContext.SetAlphaBlendingEnabled(true); s_profilerGUIContext.SetAlphaBlendingMode(MiniGUIContext::ALPHABLENDING_MODE_STRAIGHT); }); } void Profiling::StartFrame() { } bool Profiling::HandleSDLEvent(const void *pEvent) { if (!g_MicroProfile.nDisplay) return false; const SDL_Event *pSDLEvent = reinterpret_cast<const SDL_Event *>(pEvent); switch (pSDLEvent->type) { case SDL_MOUSEMOTION: MicroProfileMousePosition(pSDLEvent->motion.x, pSDLEvent->motion.y, 0); return true; case SDL_MOUSEWHEEL: { int mx, my; SDL_GetMouseState(&mx, &my); MicroProfileMousePosition(mx, my, pSDLEvent->wheel.y); return true; } case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { uint32 mask = SDL_GetMouseState(nullptr, nullptr); bool left = (mask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; bool right = (mask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; MicroProfileMouseButton((uint32_t)left, (uint32_t)right); return true; } case SDL_KEYDOWN: case SDL_KEYUP: MicroProfileModKey((uint32_t)((SDL_GetModState() & (KMOD_LCTRL | KMOD_RCTRL)) != 0)); return false; } return false; } bool Profiling::GetProfilerEnabled() { return (g_MicroProfile.nRunning != 0); } void Profiling::SetProfilerEnabled(bool enabled) { //DebugAssert(IsOnMainThread()); if (g_MicroProfile.nRunning == (uint32_t)enabled) { if (g_MicroProfile.nToggleRunning) g_MicroProfile.nToggleRunning = false; return; } else { if (g_MicroProfile.nToggleRunning) return; MicroProfileTogglePause(); } } bool Profiling::IsProfilerDisplayEnabled() { return (g_MicroProfile.nDisplay != MP_DRAW_OFF); } bool Profiling::SetProfilerDisplay(uint32 mode) { //DebugAssert(IsOnMainThread()); MicroProfileSetDisplayMode(mode); return (g_MicroProfile.nDisplay == MP_DRAW_DETAILED); } bool Profiling::ToggleProfilerDisplay() { //DebugAssert(IsOnMainThread()); MicroProfileToggleDisplayMode(); return (g_MicroProfile.nDisplay == MP_DRAW_DETAILED); } void Profiling::HideProfilerDisplay() { //DebugAssert(IsOnMainThread()); MicroProfileSetDisplayMode(MP_DRAW_OFF); } void Profiling::DrawDisplay() { DebugAssert(Renderer::IsOnRenderThread()); GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); if (g_MicroProfile.nDisplay) { pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetFullViewport(); const RENDERER_VIEWPORT *pViewport = pGPUContext->GetViewport(); s_profilerGUIContext.SetViewportDimensions(pViewport->Width, pViewport->Height); s_profilerGUIContext.PushManualFlush(); MicroProfileDraw(pViewport->Width, pViewport->Height); s_profilerGUIContext.PopManualFlush(); } // this is on the render thread, so it's as good time as any to poll the frequency if (g_MicroProfile.nRunning && s_GPUTimingAvailable) { // end frequency query pGPUContext->EndQuery(s_pGPUFrequencyQuery); // get results GPU_QUERY_GETDATA_RESULT result = pGPUContext->GetQueryData(s_pGPUFrequencyQuery, &s_lastGPUFrequency, sizeof(s_lastGPUFrequency), 0); while (result == GPU_QUERY_GETDATA_RESULT_NOT_READY) result = pGPUContext->GetQueryData(s_pGPUFrequencyQuery, &s_lastGPUFrequency, sizeof(s_lastGPUFrequency), 0); if (result != GPU_QUERY_GETDATA_RESULT_OK) { // error? Log_WarningPrintf("Profiling::DrawDisplay: Polling GPU frequency failed."); s_lastGPUFrequency = 1; } else if (s_lastGPUFrequency == 0) { Log_WarningPrintf("Profiling::DrawDisplay: GPU frequency changed, timestamps will be incorrect."); s_lastGPUFrequency = 1; } // kick off next frequency query pGPUContext->BeginQuery(s_pGPUFrequencyQuery); } } void Profiling::EndFrame() { // activating? if (!g_MicroProfile.nRunning && g_MicroProfile.nToggleRunning && !s_GPUTimingInitialized) { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([]() { InitializeGPUTiming(); }); } // pass through - force execution on render thread if (g_MicroProfile.nRunning || g_MicroProfile.nToggleRunning) { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([]() { MicroProfileFlip(nullptr); }); } } ////////////////////////////////////////////////////////////////////////// void MicroProfileDrawText(int nX, int nY, uint32_t nColor, const char* pText, uint32_t nNumCharacters) { static const Font *pFont = g_pResourceManager->GetFont("resources/engine/fonts/microprofile"); s_profilerGUIContext.DrawTextAt(nX, nY, pFont, 10, nColor, pText); } void MicroProfileDrawBox(int nX, int nY, int nX1, int nY1, uint32_t nColor, MicroProfileBoxType type) { MINIGUI_RECT rect(nX, nX1, nY, nY1); if (type == MicroProfileBoxTypeBar) { // draw gradient box uint32 r = (nColor >> 16) & 0xFF; uint32 g = (nColor >> 8) & 0xFF; uint32 b = (nColor) & 0xFF; uint32 maxIntensity = Max(Max(r, Max(g, b)), (uint32)30); uint32 minIntensity = Min(Min(r, Min(g, b)), (uint32)180); uint32 r0 = ((r + maxIntensity) / 2) & 0xFF; uint32 g0 = ((g + maxIntensity) / 2) & 0xFF; uint32 b0 = ((b + maxIntensity) / 2) & 0xFF; uint32 r1 = ((r + minIntensity) / 2) & 0xFF; uint32 g1 = ((g + minIntensity) / 2) & 0xFF; uint32 b1 = ((b + minIntensity) / 2) & 0xFF; uint32 colorTop = MAKE_COLOR_R8G8B8A8_UNORM(r0, g0, b0, (nColor >> 24)); uint32 colorBottom = MAKE_COLOR_R8G8B8A8_UNORM(r1, g1, b1, (nColor >> 24)); s_profilerGUIContext.DrawFilledRect(&rect, colorTop, colorTop, colorBottom, colorBottom); } else { // draw flat box s_profilerGUIContext.DrawFilledRect(&rect, nColor); } } void MicroProfileDrawLine2D(uint32_t nVertices, float* pVertices, uint32_t nColor) { DebugAssert(nVertices > 2); int2 lastVertex((int32)pVertices[0], (int32)pVertices[1]); for (uint32 i = 2; i < nVertices; i += 2) { // @todo remove float-int conversion int2 thisVertex((int32)pVertices[i], (int32)pVertices[i + 1]); s_profilerGUIContext.DrawLine(lastVertex, thisVertex, nColor); lastVertex = thisVertex; } } uint32_t MicroProfileGpuInsertTimeStamp(void *pContext) { if (!s_GPUTimingAvailable) return (uint32_t)-1; // get context GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); DebugAssert(Renderer::IsOnRenderThread()); // get query uint32 queryIndex = s_lastGPUTimestampQuery; GPUQuery *pThisQuery = s_pGPUTimestampQueries[queryIndex]; s_lastGPUTimestampQuery = (s_lastGPUTimestampQuery + 1) % countof(s_pGPUTimestampQueries); // issue begin/end pGPUContext->BeginQuery(pThisQuery); pGPUContext->EndQuery(pThisQuery); return queryIndex; } uint64_t MicroProfileGpuGetTimeStamp(uint32_t nKey) { if (!s_GPUTimingAvailable || nKey == (uint32_t)-1) return 0; GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); DebugAssert(Renderer::IsOnRenderThread()); // get query DebugAssert(nKey < countof(s_pGPUTimestampQueries) && s_pGPUTimestampQueries[nKey] != nullptr); GPUQuery *pThisQuery = s_pGPUTimestampQueries[nKey]; uint64_t timestampValue; // read results GPU_QUERY_GETDATA_RESULT result = pGPUContext->GetQueryData(pThisQuery, &timestampValue, sizeof(timestampValue), 0); while (result == GPU_QUERY_GETDATA_RESULT_NOT_READY) result = pGPUContext->GetQueryData(pThisQuery, &timestampValue, sizeof(timestampValue), 0); // return result return (result == GPU_QUERY_GETDATA_RESULT_OK) ? timestampValue : 0; } uint64_t MicroProfileTicksPerSecondGpu() { return s_lastGPUFrequency; } int MicroProfileGetGpuTickReference(int64_t* pOutCPU, int64_t* pOutGpu) { return 0; } // const char* MicroProfileGetThreadName() // { // return "Thread"; // } #else // WITH_PROFILER #include "Engine/Profiling.h" void Profiling::Initialize() { } void Profiling::StartFrame() { } bool Profiling::HandleSDLEvent(const void *pEvent) { return false; } bool Profiling::GetProfilerEnabled() { return false; } void Profiling::SetProfilerEnabled(bool enabled) { } bool Profiling::IsProfilerDisplayEnabled() { return false; } bool Profiling::SetProfilerDisplay(uint32 mode) { return false; } bool Profiling::ToggleProfilerDisplay() { return false; } void Profiling::HideProfilerDisplay() { } void Profiling::DrawDisplay() { } void Profiling::EndFrame() { } #endif // WITH_PROFILER <file_sep>/Editor/Source/Editor/MapEditor/EditorMapWindow.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorHelpers.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/MapEditor/EditorEditMode.h" #include "Editor/MapEditor/EditorMapEditMode.h" #include "Editor/MapEditor/EditorEntityEditMode.h" #include "Editor/MapEditor/EditorGeometryEditMode.h" #include "Editor/MapEditor/EditorTerrainEditMode.h" #include "Editor/MapEditor/EditorCreateTerrainDialog.h" #include "Editor/MapEditor/EditorWorldOutlinerWidget.h" #include "Editor/EditorProgressDialog.h" #include "Editor/EditorCVars.h" #include "Editor/EditorPropertyEditorDialog.h" #include "Editor/EditorPropertyEditorWidget.h" #include "Editor/EditorHelpers.h" #include "Engine/Entity.h" #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "Editor/MapEditor/ui_EditorMapWindow.h" Log_SetChannel(EditorMapWindow); EditorMapWindow::EditorMapWindow() : QMainWindow(), m_ui(new Ui_EditorMapWindow()), m_pOpenMap(NULL), m_referenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM_WORLD), m_editMode(EDITOR_EDIT_MODE_NONE), m_pActiveEditModePointer(NULL), m_viewportLayout(EDITOR_VIEWPORT_LAYOUT_COUNT), m_pActiveViewport(NULL) { m_ui->CreateUI(this); ConnectUIEvents(); g_pEditor->AddMapWindow(this); // add log callback Log::GetInstance().RegisterCallback(LogCallback, reinterpret_cast<void *>(this)); } EditorMapWindow::~EditorMapWindow() { // remove log callback Log::GetInstance().UnregisterCallback(LogCallback, reinterpret_cast<void *>(this)); g_pEditor->RemoveMapWindow(this); DebugAssert(m_pOpenMap == NULL); delete m_ui; } const EditorWorldOutlinerWidget *EditorMapWindow::GetWorldOutlinerWidget() const { return m_ui->worldOutliner; } const EditorResourceBrowserWidget *EditorMapWindow::GetResourceBrowserWidget() const { return m_ui->resourceBrowser; } const EditorPropertyEditorWidget *EditorMapWindow::GetPropertyEditorWidget() const { return m_ui->propertyEditor; } EditorWorldOutlinerWidget *EditorMapWindow::GetWorldOutlinerWidget() { return m_ui->worldOutliner; } EditorResourceBrowserWidget * EditorMapWindow::GetResourceBrowserWidget() { return m_ui->resourceBrowser; } EditorPropertyEditorWidget *EditorMapWindow::GetPropertyEditorWidget() { return m_ui->propertyEditor; } bool EditorMapWindow::NewMap() { DebugAssert(m_pOpenMap == NULL); g_pEditor->BlockFrameExecution(); m_pOpenMap = new EditorMap(this); if (!m_pOpenMap->CreateMap() || !OnMapOpened()) { delete m_pOpenMap; m_pOpenMap = NULL; g_pEditor->UnblockFrameExecution(); return false; } g_pEditor->UnblockFrameExecution(); return true; } bool EditorMapWindow::OpenMap(const char *fileName) { DebugAssert(m_pOpenMap == NULL); g_pEditor->BlockFrameExecution(); // setup progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); m_pOpenMap = new EditorMap(this); if (!m_pOpenMap->OpenMap(fileName) || !OnMapOpened(&progressDialog)) { delete m_pOpenMap; m_pOpenMap = NULL; g_pEditor->UnblockFrameExecution(); return false; } g_pEditor->UnblockFrameExecution(); return true; } bool EditorMapWindow::SaveMap() { g_pEditor->BlockFrameExecution(); // setup progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); bool result = m_pOpenMap->SaveMap(NULL, &progressDialog); g_pEditor->UnblockFrameExecution(); return result; } bool EditorMapWindow::SaveMapAs(const char *newFileName) { // setup progress dialog EditorProgressDialog progressDialog(this); progressDialog.show(); if (!m_pOpenMap->SaveMap(newFileName, &progressDialog)) return false; m_ui->OnMapFileNameChanged(m_pOpenMap); return true; } void EditorMapWindow::CloseMap() { DebugAssert(m_pOpenMap != NULL); g_pEditor->BlockFrameExecution(); DeleteAllViewports(); m_viewportLayout = EDITOR_VIEWPORT_LAYOUT_COUNT; m_pActiveEditModePointer->Deactivate(); m_pActiveEditModePointer = NULL; // update ui { m_ui->propertyEditor->ClearProperties(); m_ui->worldOutliner->Clear(); m_ui->actionFileSaveMap->setEnabled(false); m_ui->actionFileSaveMapAs->setEnabled(false); m_ui->actionFileCloseMap->setEnabled(false); m_ui->actionEditUndo->setEnabled(false); m_ui->actionEditRedo->setEnabled(false); m_ui->actionEditReferenceCoordinateSystemLocal->setEnabled(false); m_ui->actionEditReferenceCoordinateSystemWorld->setEnabled(false); m_ui->actionViewWorldOutliner->setEnabled(false); m_ui->actionViewToolbox->setEnabled(false); m_ui->actionViewPropertyEditor->setEnabled(false); m_ui->menuViewViewportLayout->setEnabled(false); m_ui->menuInsert->setEnabled(false); m_ui->menuInsertEntity->setEnabled(false); m_ui->actionToolsCreateTerrain->setEnabled(false); m_ui->actionToolsDeleteTerrain->setEnabled(false); m_ui->actionToolsMapEditor->setEnabled(false); m_ui->actionToolsEntityEditor->setEnabled(false); m_ui->actionToolsGeometryEditor->setEnabled(false); m_ui->actionToolsTerrainEditor->setEnabled(false); // clear out everything in the tool window while (m_ui->toolboxTabWidget->count() > 0) { int index = m_ui->toolboxTabWidget->count() - 1; QWidget *widget = m_ui->toolboxTabWidget->widget(index); BlockSignalsForCall(m_ui->toolboxTabWidget)->removeTab(index); delete widget; } // hide windows m_ui->ToggleWorldOutliner(false); m_ui->ToggleToolbox(false); m_ui->TogglePropertyEditor(false); if (m_ui->closedMapBlankPanel == NULL) { m_ui->closedMapBlankPanel = new QWidget(m_ui->mainWindow, 0); m_ui->mainWindow->setCentralWidget(m_ui->closedMapBlankPanel); } m_ui->OnMapFileNameChanged(NULL); } delete m_pOpenMap; m_pOpenMap = NULL; g_pEditor->UnblockFrameExecution(); } void EditorMapWindow::SetReferenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM referenceCoordinateSystem) { DebugAssert(m_pOpenMap != NULL); DebugAssert(referenceCoordinateSystem < EDITOR_REFERENCE_COORDINATE_SYSTEM_COUNT); if (m_referenceCoordinateSystem != referenceCoordinateSystem) { m_referenceCoordinateSystem = referenceCoordinateSystem; // update entity edit mode if (m_editMode == EDITOR_EDIT_MODE_ENTITY) m_pOpenMap->GetEntityEditMode()->UpdateSelectionAxis(); } // update ui m_ui->OnReferenceCoordinateSystemChanged(referenceCoordinateSystem); } void EditorMapWindow::SetEditMode(EDITOR_EDIT_MODE mode) { DebugAssert(m_pOpenMap != NULL); if (mode == m_editMode) { m_ui->UpdateUIForEditMode(mode); return; } // get new mode pointer EditorEditMode *pNewEditModePointer; switch (mode) { case EDITOR_EDIT_MODE_MAP: pNewEditModePointer = m_pOpenMap->GetMapEditMode(); break; case EDITOR_EDIT_MODE_ENTITY: pNewEditModePointer = m_pOpenMap->GetEntityEditMode(); break; case EDITOR_EDIT_MODE_GEOMETRY: pNewEditModePointer = m_pOpenMap->GetGeometryEditMode(); break; case EDITOR_EDIT_MODE_TERRAIN: pNewEditModePointer = m_pOpenMap->GetTerrainEditMode(); break; default: pNewEditModePointer = NULL; break; } // not created? if (pNewEditModePointer == NULL) { // revert mode m_ui->UpdateUIForEditMode(m_editMode); return; } // update edit mode var m_editMode = mode; // clear stuff from current edit mode m_pActiveEditModePointer->Deactivate(); // clear property editor m_ui->propertyEditor->ClearProperties(); // set pointer, and activate it m_pActiveEditModePointer = pNewEditModePointer; m_pActiveEditModePointer->Activate(); // update ui m_ui->UpdateUIForEditMode(mode); // redraw all viewports RedrawAllViewports(); } EditorMapViewport *EditorMapWindow::CreateViewport(EDITOR_CAMERA_MODE cameraMode, EDITOR_RENDER_MODE renderMode, uint32 flags) { DebugAssert(m_pOpenMap != NULL); // find a free slot uint32 viewportId; for (viewportId = 0; viewportId < m_viewports.GetSize(); viewportId++) { if (m_viewports[viewportId] == NULL) break; } // create it EditorMapViewport *pViewport = new EditorMapViewport(this, m_pOpenMap, viewportId, cameraMode, renderMode, flags); // add to list if (viewportId >= m_viewports.GetSize()) m_viewports.Resize(viewportId + 1); m_viewports[viewportId] = pViewport; // update streaming OnViewportCameraChange(pViewport); // return it return pViewport; } void EditorMapWindow::SetActiveViewport(EditorMapViewport *pViewport) { m_pActiveViewport = pViewport; // update status bar UpdateStatusBarCameraFields(); } void EditorMapWindow::SetViewportLayout(EDITOR_VIEWPORT_LAYOUT layout) { if (m_viewportLayout == layout) return; m_viewportLayout = layout; DeleteAllViewports(); EditorMapViewport *pViewport; switch (layout) { case EDITOR_VIEWPORT_LAYOUT_1X1: { pViewport = CreateViewport(EDITOR_CAMERA_MODE_PERSPECTIVE, EDITOR_RENDER_MODE_FULLBRIGHT, EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS | EDITOR_VIEWPORT_FLAG_ENABLE_DEBUG_INFO); setCentralWidget(pViewport); } break; case EDITOR_VIEWPORT_LAYOUT_2X2: { } break; } } void EditorMapWindow::RedrawAllViewports() { for (uint32 i = 0; i < m_viewports.GetSize(); i++) { EditorMapViewport *pViewport = m_viewports[i]; if (pViewport != NULL) pViewport->FlagForRedraw(); } } void EditorMapWindow::DeleteAllViewports() { setCentralWidget(NULL); for (uint32 i = 0; i < m_viewports.GetSize(); i++) delete m_viewports[i]; m_viewports.Clear(); } void EditorMapWindow::OnViewportCameraChange(EditorMapViewport *pViewport) { m_pOpenMap->OnViewportCameraChange(); if (m_pActiveViewport == pViewport) UpdateStatusBarCameraFields(); } bool EditorMapWindow::OnMapOpened(ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // set none edit mode m_editMode = EDITOR_EDIT_MODE_MAP; m_pActiveEditModePointer = m_pOpenMap->GetMapEditMode(); m_pActiveEditModePointer->Activate(); // create viewports SetViewportLayout(EDITOR_VIEWPORT_LAYOUT_1X1); // update ui { m_ui->actionFileSaveMap->setEnabled(true); m_ui->actionFileSaveMapAs->setEnabled(true); m_ui->actionFileCloseMap->setEnabled(true); m_ui->actionEditUndo->setEnabled(true); m_ui->actionEditRedo->setEnabled(true); m_ui->actionEditReferenceCoordinateSystemLocal->setEnabled(true); m_ui->actionEditReferenceCoordinateSystemWorld->setEnabled(true); m_ui->actionViewWorldOutliner->setEnabled(true); m_ui->actionViewToolbox->setEnabled(true); m_ui->actionViewPropertyEditor->setEnabled(true); m_ui->menuViewViewportLayout->setEnabled(true); m_ui->menuInsert->setEnabled(true); m_ui->menuInsertEntity->setEnabled(true); m_ui->actionToolsMapEditor->setEnabled(true); m_ui->actionToolsEntityEditor->setEnabled(true); m_ui->actionToolsGeometryEditor->setEnabled(true); if (m_ui->closedMapBlankPanel != NULL) { delete m_ui->closedMapBlankPanel; m_ui->closedMapBlankPanel = NULL; } m_ui->OnMapFileNameChanged(m_pOpenMap); // update grid snap options in status bar BlockSignalsForCall(m_ui->statusBarGridSnapEnabled)->setChecked(m_pOpenMap->GetGridSnapEnabled()); BlockSignalsForCall(m_ui->statusBarGridSnapInterval)->setValue(m_pOpenMap->GetGridSnapInterval()); BlockSignalsForCall(m_ui->statusBarGridLinesVisible)->setChecked(m_pOpenMap->GetGridLinesVisible()); BlockSignalsForCall(m_ui->statusBarGridLinesInterval)->setValue(m_pOpenMap->GetGridLinesInterval()); // create edit mode uis m_ui->toolboxTabWidget->addTab(m_pOpenMap->GetMapEditMode()->CreateUI(m_ui->toolboxTabWidget), QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png")), tr("Map")); m_ui->toolboxTabWidget->addTab(m_pOpenMap->GetEntityEditMode()->CreateUI(m_ui->toolboxTabWidget), QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png")), tr("Entity")); m_ui->toolboxTabWidget->addTab(m_pOpenMap->GetGeometryEditMode()->CreateUI(m_ui->toolboxTabWidget), QIcon(QStringLiteral(":/editor/icons/HighlightHH.png")), tr("Geometry")); // has terrain? if (m_pOpenMap->HasTerrain()) { m_ui->toolboxTabWidget->addTab(m_pOpenMap->GetTerrainEditMode()->CreateUI(m_ui->toolboxTabWidget), QIcon(QStringLiteral(":/editor/icons/BreakpointHS.png")), tr("Terrain")); m_ui->actionToolsTerrainEditor->setEnabled(true); m_ui->actionToolsCreateTerrain->setEnabled(false); m_ui->actionToolsDeleteTerrain->setEnabled(true); } else { m_ui->toolboxTabWidget->addTab(new QWidget(m_ui->toolboxTabWidget), QIcon(QStringLiteral(":/editor/icons/BreakpointHS.png")), tr("Terrain")); m_ui->toolboxTabWidget->setTabEnabled(3, false); m_ui->actionToolsTerrainEditor->setEnabled(false); m_ui->actionToolsCreateTerrain->setEnabled(true); m_ui->actionToolsDeleteTerrain->setEnabled(false); } m_ui->UpdateUIForEditMode(EDITOR_EDIT_MODE_MAP); m_ui->ToggleWorldOutliner(true); m_ui->ToggleToolbox(true); m_ui->TogglePropertyEditor(true); } // set focus to our only viewport DebugAssert(m_viewports.GetSize() > 0); m_viewports[0]->SetFocus(); // set reference coordinate system SetReferenceCoordinateSystem(EDITOR_REFERENCE_COORDINATE_SYSTEM_WORLD); //EditorPropertyEditorDialog *w = new EditorPropertyEditorDialog(this); //w->PopulateForTable(g_pEditor->GetPropertyTemplates()->MapPropertyTemplate, m_pOpenMap->GetMapSource()->GetProperties()); //w->show(); // done return true; } void EditorMapWindow::LogCallback(void *pUserParam, const char *channelName, const char *functionName, LOGLEVEL level, const char *message) { static bool reentrant = false; if (!reentrant) { reentrant = true; // hackfix to prevent the stupid thing from making the window massive QString tempString(message); if (tempString.length() > 100) tempString.truncate(100); reinterpret_cast<EditorMapWindow *>(pUserParam)->m_ui->statusBarMainText->setText(tempString); reentrant = false; } } void EditorMapWindow::closeEvent(QCloseEvent *pCloseEvent) { if (IsMapOpen()) { OnActionFileCloseMapTriggered(); if (IsMapOpen()) { // use selected cancel pCloseEvent->ignore(); return; } } // accept event QMainWindow::closeEvent(pCloseEvent); } void EditorMapWindow::ConnectUIEvents() { connect(m_ui->actionFileNewMap, SIGNAL(triggered()), this, SLOT(OnActionFileNewMapTriggered())); connect(m_ui->actionFileOpenMap, SIGNAL(triggered()), this, SLOT(OnActionFileOpenMapTriggered())); connect(m_ui->actionFileSaveMap, SIGNAL(triggered()), this, SLOT(OnActionFileSaveMapTriggered())); connect(m_ui->actionFileSaveMapAs, SIGNAL(triggered()), this, SLOT(OnActionFileSaveMapAsTriggered())); connect(m_ui->actionFileCloseMap, SIGNAL(triggered()), this, SLOT(OnActionFileCloseMapTriggered())); connect(m_ui->actionFileExit, SIGNAL(triggered()), this, SLOT(OnActionFileExitTriggered())); connect(m_ui->actionEditReferenceCoordinateSystemLocal, SIGNAL(triggered(bool)), this, SLOT(OnActionEditReferenceCoordinateSystemLocalTriggered(bool))); connect(m_ui->actionEditReferenceCoordinateSystemWorld, SIGNAL(triggered(bool)), this, SLOT(OnActionEditReferenceCoordinateSystemWorldTriggered(bool))); connect(m_ui->actionToolsCreateTerrain, SIGNAL(triggered()), this, SLOT(OnActionToolsCreateTerrainTriggered())); connect(m_ui->actionToolsDeleteTerrain, SIGNAL(triggered()), this, SLOT(OnActionToolsDeleteTerrainTriggered())); connect(m_ui->actionViewWorldOutliner, SIGNAL(triggered(bool)), this, SLOT(OnActionViewWorldOutlinerTriggered(bool))); connect(m_ui->worldOutlinerDock, SIGNAL(visibilityChanged(bool)), this, SLOT(OnActionViewWorldOutlinerTriggered(bool))); connect(m_ui->actionViewResourceBrowser, SIGNAL(triggered(bool)), this, SLOT(OnActionViewResourceBrowserTriggered(bool))); connect(m_ui->resourceBrowserDock, SIGNAL(visibilityChanged(bool)), this, SLOT(OnActionViewResourceBrowserTriggered(bool))); connect(m_ui->actionViewToolbox, SIGNAL(triggered(bool)), this, SLOT(OnActionViewToolboxTriggered(bool))); connect(m_ui->toolboxTabWidget, SIGNAL(visibilityChanged(bool)), this, SLOT(OnActionViewToolboxTriggered(bool))); connect(m_ui->actionViewPropertyEditor, SIGNAL(triggered(bool)), this, SLOT(OnActionViewPropertyEditorTriggered(bool))); connect(m_ui->propertyEditorDockWidget, SIGNAL(visibilityChanged(bool)), this, SLOT(OnActionViewPropertyEditorTriggered(bool))); connect(m_ui->actionViewThemeNone, SIGNAL(triggered()), this, SLOT(OnActionViewThemeNone())); connect(m_ui->actionViewThemeDark, SIGNAL(triggered()), this, SLOT(OnActionViewThemeDark())); connect(m_ui->actionViewThemeDarkOther, SIGNAL(triggered()), this, SLOT(OnActionViewThemeDarkOther())); connect(m_ui->actionToolsMapEditor, SIGNAL(triggered(bool)), this, SLOT(OnActionToolsMapEditModeTriggered(bool))); connect(m_ui->actionToolsEntityEditor, SIGNAL(triggered(bool)), this, SLOT(OnActionToolsEntityEditModeTriggered(bool))); connect(m_ui->actionToolsGeometryEditor, SIGNAL(triggered(bool)), this, SLOT(OnActionToolsGeometryEditModeTriggered(bool))); connect(m_ui->actionToolsTerrainEditor, SIGNAL(triggered(bool)), this, SLOT(OnActionToolsHeightfieldTerrainEditModeTriggered(bool))); connect(m_ui->statusBarGridSnapEnabled, SIGNAL(toggled(bool)), this, SLOT(OnStatusBarGridSnapEnabledToggled(bool))); connect(m_ui->statusBarGridSnapInterval, SIGNAL(valueChanged(double)), this, SLOT(OnStatusBarGridSnapIntervalChanged(double))); connect(m_ui->statusBarGridLinesVisible, SIGNAL(toggled(bool)), this, SLOT(OnStatusBarGridLinesVisibleToggled(bool))); connect(m_ui->statusBarGridLinesInterval, SIGNAL(valueChanged(double)), this, SLOT(OnStatusBarGridLinesIntervalChanged(double))); connect(m_ui->worldOutliner, SIGNAL(OnEntitySelected(const EditorMapEntity *)), this, SLOT(OnWorldOutlinerEntitySelected(const EditorMapEntity *))); connect(m_ui->worldOutliner, SIGNAL(OnEntityActivated(const EditorMapEntity *)), this, SLOT(OnWorldOutlinerEntityActivated(const EditorMapEntity *))); connect(m_ui->toolboxTabWidget, SIGNAL(currentChanged(int)), this, SLOT(OnToolboxTabWidgetCurrentChanged(int))); connect(m_ui->propertyEditor, SIGNAL(OnPropertyValueChange(const char *, const char *)), this, SLOT(OnPropertyEditorPropertyChanged(const char *, const char *))); connect(g_pEditor, SIGNAL(OnFrameExecution(float)), this, SLOT(OnFrameExecutionTriggered(float))); } void EditorMapWindow::UpdateStatusBarCameraFields() { float3 cameraPosition((m_pActiveViewport != nullptr) ? m_pActiveViewport->GetViewController().GetCameraPosition() : float3::Zero); float3 cameraDirection((m_pActiveViewport != nullptr) ? m_pActiveViewport->GetViewController().GetCameraForwardDirection() : float3::Zero); SmallString str; str.Format("Camera Position: %.5f %.5f %.5f", cameraPosition.x, cameraPosition.y, cameraPosition.z); m_ui->statusBarCameraPosition->setText(EditorHelpers::ConvertStringToQString(str)); str.Format("Camera Direction: %.5f %.5f %.5f", cameraDirection.x, cameraDirection.y, cameraDirection.z); m_ui->statusBarCameraDirection->setText(EditorHelpers::ConvertStringToQString(str)); } void EditorMapWindow::UpdateStatusBarFPSField() { TinyString str; str.Format("%.4f FPS", g_pEditor->GetEditorFPS()); m_ui->statusBarFPS->setText(EditorHelpers::ConvertStringToQString(str)); } void EditorMapWindow::OnActionFileNewMapTriggered() { if (IsMapOpen()) { OnActionFileCloseMapTriggered(); if (IsMapOpen()) { // use selected cancel, since the map is still open return; } } NewMap(); } void EditorMapWindow::OnActionFileOpenMapTriggered() { g_pEditor->BlockFrameExecution(); QString filename = QFileDialog::getOpenFileName(this, tr("Open Map..."), QStringLiteral(""), tr("Map Files (*.map)"), NULL, 0); if (filename.isEmpty()) { g_pEditor->UnblockFrameExecution(); return; } if (IsMapOpen()) { OnActionFileCloseMapTriggered(); if (IsMapOpen()) { // use selected cancel, since the map is still open g_pEditor->UnblockFrameExecution(); return; } } OpenMap(ConvertQStringToString(filename)); g_pEditor->UnblockFrameExecution(); } void EditorMapWindow::OnActionFileSaveMapTriggered() { if (!IsMapOpen()) return; if (m_pOpenMap->GetMapFileName().GetLength() == 0) { // map has never been saved, so assume save as behaviour instead OnActionFileSaveMapAsTriggered(); return; } SaveMap(); } void EditorMapWindow::OnActionFileSaveMapAsTriggered() { if (!IsMapOpen()) return; g_pEditor->BlockFrameExecution(); QString filename = QFileDialog::getSaveFileName(this, tr("Save Map As..."), QStringLiteral(""), tr("Map Files (*.map)"), NULL, 0); if (filename.isEmpty()) { g_pEditor->UnblockFrameExecution(); return; } SaveMapAs(ConvertQStringToString(filename)); g_pEditor->UnblockFrameExecution(); } void EditorMapWindow::OnActionFileCloseMapTriggered() { if (!IsMapOpen()) return; if (m_pOpenMap->GetMapSource()->IsChanged()) { g_pEditor->BlockFrameExecution(); int result = QMessageBox::question(this, tr("Save open map?"), tr("The current open map is changed, do you wish to save the changes made to it?"), (QMessageBox::StandardButtons)(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel), QMessageBox::Yes); g_pEditor->UnblockFrameExecution(); if (result == QMessageBox::Yes) OnActionFileSaveMapTriggered(); else if (result == QMessageBox::Cancel) return; } CloseMap(); } void EditorMapWindow::OnActionFileExitTriggered() { if (IsMapOpen()) { OnActionFileCloseMapTriggered(); if (IsMapOpen()) { // cancel pressed if we are here return; } } g_pEditor->Exit(); } void EditorMapWindow::OnActionViewWorldOutlinerTriggered(bool checked) { m_ui->ToggleWorldOutliner(checked); } void EditorMapWindow::OnActionViewResourceBrowserTriggered(bool checked) { m_ui->ToggleResourceBrowser(checked); } void EditorMapWindow::OnActionViewToolboxTriggered(bool checked) { m_ui->ToggleToolbox(checked); } void EditorMapWindow::OnActionViewPropertyEditorTriggered(bool checked) { m_ui->TogglePropertyEditor(checked); } void EditorMapWindow::OnActionToolsCreateTerrainTriggered() { //DebugAssert(!m_pOpenMap->GetMapSource()->HasTerrain()); EditorCreateTerrainDialog createDialog(this); if (!createDialog.exec()) return; // create it /* m_pOpenMap->CreateTerrain(createDialog.GetLayerList(), createDialog.GetSectionSize(), createDialog.GetUnitsPerPoint(), createDialog.GetQuadTreeNodeSize(), createDialog.GetTextureRepeatInterval(), createDialog.GetStorageFormat(), createDialog.GetMinHeight(), createDialog.GetMaxHeight(), createDialog.GetBaseHeight()); // create initial section? if (createDialog.GetCreateCenterSection()) m_pOpenMap->CreateTerrainSection(0, 0); */ } void EditorMapWindow::OnActionToolsDeleteTerrainTriggered() { // DebugAssert(m_pOpenMap->GetMapSource()->HasTerrain()); // if (QMessageBox::question(this, tr("Delete Terrain"), tr("Are you sure you wish to delete the terrain for this map?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) // return; // // // delete it // m_pOpenMap->DeleteTerrain(); } void EditorMapWindow::OnActionToolsCreateBlockTerrainTriggered() { } void EditorMapWindow::OnActionToolsDeleteBlockTerrainTriggered() { } void EditorMapWindow::OnStatusBarGridSnapEnabledToggled(bool checked) { if (m_pOpenMap != nullptr) m_pOpenMap->SetGridSnapEnabled(checked); } void EditorMapWindow::OnStatusBarGridSnapIntervalChanged(double value) { if (m_pOpenMap != nullptr) m_pOpenMap->SetGridSnapInterval((float)value); } void EditorMapWindow::OnStatusBarGridLinesVisibleToggled(bool checked) { if (m_pOpenMap != nullptr) m_pOpenMap->SetGridLinesVisible(checked); } void EditorMapWindow::OnStatusBarGridLinesIntervalChanged(double value) { if (m_pOpenMap != nullptr) m_pOpenMap->SetGridLinesInterval((float)value); } void EditorMapWindow::OnWorldOutlinerEntitySelected(const EditorMapEntity *pEntity) { if (pEntity != nullptr) { if (m_editMode != EDITOR_EDIT_MODE_ENTITY) SetEditMode(EDITOR_EDIT_MODE_ENTITY); m_pOpenMap->GetEntityEditMode()->ClearSelection(); m_pOpenMap->GetEntityEditMode()->AddSelection(const_cast<EditorMapEntity *>(pEntity)); RedrawAllViewports(); } } void EditorMapWindow::OnWorldOutlinerEntityActivated(const EditorMapEntity *pEntity) { if (pEntity != nullptr) { if (m_editMode != EDITOR_EDIT_MODE_ENTITY) SetEditMode(EDITOR_EDIT_MODE_ENTITY); m_pOpenMap->GetEntityEditMode()->ClearSelection(); m_pOpenMap->GetEntityEditMode()->AddSelection(const_cast<EditorMapEntity *>(pEntity)); if (m_pActiveViewport != nullptr) m_pOpenMap->GetEntityEditMode()->MoveViewportCameraToEntity(m_pActiveViewport, pEntity); RedrawAllViewports(); } } void EditorMapWindow::OnToolboxTabWidgetCurrentChanged(int index) { if (index < 0) return; // set new edit mode EDITOR_EDIT_MODE newEditMode = (EDITOR_EDIT_MODE)(index + 1); DebugAssert(newEditMode < EDITOR_EDIT_MODE_COUNT); SetEditMode(newEditMode); } void EditorMapWindow::OnPropertyEditorPropertyChanged(const char *propertyName, const char *propertyValue) { m_pActiveEditModePointer->OnPropertyEditorPropertyChanged(propertyName, propertyValue); } void EditorMapWindow::OnFrameExecutionTriggered(float timeSinceLastFrame) { if (m_pOpenMap != nullptr) { bool viewportDrawn = false; // update map m_pOpenMap->Update(timeSinceLastFrame); // draw viewports for (uint32 i = 0; i < m_viewports.GetSize(); i++) viewportDrawn |= m_viewports[i]->Draw(timeSinceLastFrame); // update fps if (viewportDrawn) UpdateStatusBarFPSField(); } } <file_sep>/Engine/Source/GameFramework/SpriteComponent.cpp #include "GameFramework/PrecompiledHeader.h" <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUDevice.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" #include "OpenGLES2Renderer/OpenGLES2ConstantLibrary.h" #include "Engine/EngineCVars.h" Log_SetChannel(OpenGLES2RenderBackend); OpenGLES2GPUDevice::OpenGLES2GPUDevice(SDL_GLContext pSDLGLContext, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, PIXEL_FORMAT outputBackBufferFormat, PIXEL_FORMAT outputDepthStencilFormat) : m_pSDLGLContext(pSDLGLContext) , m_pImmediateContext(nullptr) , m_featureLevel(featureLevel) , m_texturePlatform(texturePlatform) , m_outputBackBufferFormat(outputBackBufferFormat) , m_outputDepthStencilFormat(outputDepthStencilFormat) , m_constantLibrary(featureLevel) { } OpenGLES2GPUDevice::~OpenGLES2GPUDevice() { DebugAssert(m_pImmediateContext == nullptr); // nuke GL context SDL_GL_MakeCurrent(nullptr, nullptr); SDL_GL_DeleteContext(m_pSDLGLContext); } RENDERER_PLATFORM OpenGLES2GPUDevice::GetPlatform() const { return RENDERER_PLATFORM_OPENGLES2; } RENDERER_FEATURE_LEVEL OpenGLES2GPUDevice::GetFeatureLevel() const { return m_featureLevel; } TEXTURE_PLATFORM OpenGLES2GPUDevice::GetTexturePlatform() const { return m_texturePlatform; } void OpenGLES2GPUDevice::GetCapabilities(RendererCapabilities *pCapabilities) const { // run glget calls uint32 maxTextureAnisotropy = 0; uint32 maxVertexAttributes = 0; uint32 maxTextureUnits = 0; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, reinterpret_cast<GLint *>(&maxTextureAnisotropy)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast<GLint *>(&maxVertexAttributes)); glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, reinterpret_cast<GLint *>(&maxTextureUnits)); pCapabilities->MaxTextureAnisotropy = maxTextureAnisotropy; pCapabilities->MaximumVertexBuffers = maxVertexAttributes; pCapabilities->MaximumConstantBuffers = 0; pCapabilities->MaximumTextureUnits = maxTextureUnits; pCapabilities->MaximumSamplers = maxTextureUnits; pCapabilities->MaximumRenderTargets = 1; pCapabilities->MaxTextureAnisotropy = maxTextureAnisotropy; pCapabilities->SupportsCommandLists = false; pCapabilities->SupportsMultithreadedResourceCreation = false; pCapabilities->SupportsDrawBaseVertex = false; pCapabilities->SupportsDepthTextures = true; pCapabilities->SupportsTextureArrays = false; pCapabilities->SupportsCubeMapTextureArrays = false; pCapabilities->SupportsGeometryShaders = false; pCapabilities->SupportsSinglePassCubeMaps = false; pCapabilities->SupportsInstancing = false; } bool OpenGLES2GPUDevice::CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat /*= NULL*/) const { // @TODO return true; } void OpenGLES2GPUDevice::CorrectProjectionMatrix(float4x4 &projectionMatrix) const { float4x4 scaleMatrix(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); float4x4 biasMatrix(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); projectionMatrix = biasMatrix * scaleMatrix * projectionMatrix; } float OpenGLES2GPUDevice::GetTexelOffset() const { return 0.0f; } void OpenGLES2GPUDevice::BindMutatorTextureUnit() { if (m_pImmediateContext != nullptr) m_pImmediateContext->BindMutatorTextureUnit(); } void OpenGLES2GPUDevice::RestoreMutatorTextureUnit() { if (m_pImmediateContext != nullptr) m_pImmediateContext->RestoreMutatorTextureUnit(); } void OpenGLES2GPUDevice::BeginResourceBatchUpload() { } void OpenGLES2GPUDevice::EndResourceBatchUpload() { } // ------------------ OpenGLES2GPURasterizerState::OpenGLES2GPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) : GPURasterizerState(pRasterizerStateDesc) { m_GLCullFace = OpenGLES2TypeConversion::GetOpenGLCullFace(pRasterizerStateDesc->CullMode); m_GLCullEnabled = (pRasterizerStateDesc->CullMode != RENDERER_CULL_NONE) ? true : false; m_GLFrontFace = (pRasterizerStateDesc->FrontCounterClockwise) ? GL_CCW : GL_CW; m_GLScissorTestEnable = pRasterizerStateDesc->ScissorEnable; } OpenGLES2GPURasterizerState::~OpenGLES2GPURasterizerState() { } void OpenGLES2GPURasterizerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLES2GPURasterizerState::SetDebugName(const char *name) { } void OpenGLES2GPURasterizerState::Apply() { glCullFace(m_GLCullFace); (m_GLCullEnabled) ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); glFrontFace(m_GLFrontFace); (m_GLScissorTestEnable) ? glEnable(GL_SCISSOR_TEST) : glDisable(GL_SCISSOR_TEST); } void OpenGLES2GPURasterizerState::Unapply() { glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glDisable(GL_SCISSOR_TEST); } GPURasterizerState *OpenGLES2GPUDevice::CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) { return new OpenGLES2GPURasterizerState(pRasterizerStateDesc); } OpenGLES2GPUDepthStencilState::OpenGLES2GPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) : GPUDepthStencilState(pDepthStencilStateDesc) { m_GLDepthTestEnable = pDepthStencilStateDesc->DepthTestEnable; m_GLDepthMask = (pDepthStencilStateDesc->DepthWriteEnable) ? GL_TRUE : GL_FALSE; m_GLDepthFunc = OpenGLES2TypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->DepthFunc); m_GLStencilTestEnable = pDepthStencilStateDesc->StencilTestEnable; m_GLStencilReadMask = pDepthStencilStateDesc->StencilReadMask; m_GLStencilWriteMask = pDepthStencilStateDesc->StencilWriteMask; m_GLStencilFuncFront = OpenGLES2TypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->StencilFrontFace.CompareFunc); m_GLStencilOpFrontFail = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.FailOp); m_GLStencilOpFrontDepthFail = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.DepthFailOp); m_GLStencilOpFrontPass = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilFrontFace.PassOp); m_GLStencilFuncBack = OpenGLES2TypeConversion::GetOpenGLComparisonFunc(pDepthStencilStateDesc->StencilBackFace.CompareFunc); m_GLStencilOpBackFail = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.FailOp); m_GLStencilOpBackDepthFail = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.DepthFailOp); m_GLStencilOpBackPass = OpenGLES2TypeConversion::GetOpenGLStencilOp(pDepthStencilStateDesc->StencilBackFace.PassOp); } OpenGLES2GPUDepthStencilState::~OpenGLES2GPUDepthStencilState() { } void OpenGLES2GPUDepthStencilState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLES2GPUDepthStencilState::SetDebugName(const char *name) { } void OpenGLES2GPUDepthStencilState::Apply(uint8 StencilRef) { (m_GLDepthTestEnable) ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glDepthMask(m_GLDepthMask); glDepthFunc(m_GLDepthFunc); (m_GLStencilTestEnable) ? glEnable(GL_STENCIL_TEST) : glDisable(GL_STENCIL_TEST); glStencilFuncSeparate(GL_FRONT, m_GLStencilFuncFront, StencilRef, m_GLStencilReadMask); glStencilOpSeparate(GL_FRONT, m_GLStencilOpFrontFail, m_GLStencilOpFrontDepthFail, m_GLStencilOpFrontPass); glStencilFuncSeparate(GL_BACK, m_GLStencilFuncBack, StencilRef, m_GLStencilReadMask); glStencilOpSeparate(GL_BACK, m_GLStencilOpBackFail, m_GLStencilOpBackDepthFail, m_GLStencilOpBackPass); glStencilMask(m_GLStencilWriteMask); } void OpenGLES2GPUDepthStencilState::Unapply() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); glDisable(GL_STENCIL_TEST); glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, 0, 0xFF); glStencilOpSeparate(GL_FRONT_AND_BACK, GL_KEEP, GL_KEEP, GL_KEEP); glStencilMask(0xFF); } GPUDepthStencilState *OpenGLES2GPUDevice::CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) { return new OpenGLES2GPUDepthStencilState(pDepthStencilStateDesc); } OpenGLES2GPUBlendState::OpenGLES2GPUBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) : GPUBlendState(pBlendStateDesc) { m_GLBlendEnable = pBlendStateDesc->BlendEnable; m_GLBlendEquationRGB = OpenGLES2TypeConversion::GetOpenGLBlendEquation(pBlendStateDesc->BlendOp); m_GLBlendEquationAlpha = OpenGLES2TypeConversion::GetOpenGLBlendEquation(pBlendStateDesc->BlendOpAlpha); m_GLBlendFuncSrcRGB = OpenGLES2TypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->SrcBlend); m_GLBlendFuncSrcAlpha = OpenGLES2TypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->SrcBlendAlpha); m_GLBlendFuncDstRGB = OpenGLES2TypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->DestBlend); m_GLBlendFuncDstAlpha = OpenGLES2TypeConversion::GetOpenGLBlendFunc(pBlendStateDesc->DestBlendAlpha); m_GLColorWritesEnabled = pBlendStateDesc->ColorWriteEnable; } OpenGLES2GPUBlendState::~OpenGLES2GPUBlendState() { } void OpenGLES2GPUBlendState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = 0; } void OpenGLES2GPUBlendState::SetDebugName(const char *name) { } void OpenGLES2GPUBlendState::Apply() { (m_GLBlendEnable) ? glEnable(GL_BLEND) : glDisable(GL_BLEND); glBlendEquationSeparate(m_GLBlendEquationRGB, m_GLBlendEquationAlpha); glBlendFuncSeparate(m_GLBlendFuncSrcRGB, m_GLBlendFuncDstRGB, m_GLBlendFuncSrcAlpha, m_GLBlendFuncDstAlpha); (m_GLColorWritesEnabled) ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } void OpenGLES2GPUBlendState::Unapply() { glDisable(GL_BLEND); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } GPUBlendState *OpenGLES2GPUDevice::CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) { return new OpenGLES2GPUBlendState(pBlendStateDesc); } // stubs GPUSamplerState *OpenGLES2GPUDevice::CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateSamplerState: Unsupported on GLES"); return nullptr; } GPUQuery *OpenGLES2GPUDevice::CreateQuery(GPU_QUERY_TYPE type) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateQuery: Unsupported on GLES"); return nullptr; } GPUTexture1D *OpenGLES2GPUDevice::CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture1D: Unsupported on GLES"); return nullptr; } GPUTexture1DArray *OpenGLES2GPUDevice::CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture1DArray: Unsupported on GLES"); return nullptr; } GPUTexture2DArray *OpenGLES2GPUDevice::CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture2DArray: Unsupported on GLES"); return nullptr; } GPUTexture3D *OpenGLES2GPUDevice::CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */, const uint32 *pInitialDataSlicePitch /* = NULL */) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture3D: Unsupported on GLES"); return nullptr; } GPUTextureCubeArray *OpenGLES2GPUDevice::CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = NULL */, const uint32 *pInitialDataPitch /* = NULL */) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTextureCubeArray: Unsupported on GLES"); return nullptr; } GPUComputeView *OpenGLES2GPUDevice::CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateComputeView: Unsupported on GLES"); return nullptr; } <file_sep>/Engine/Source/MathLib/Quaternion.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" #include "MathLib/Matrixf.h" #include "MathLib/SIMDVectorf.h" #include "MathLib/SIMDMatrixf.h" #include "MathLib/Angle.h" struct Quaternion { Quaternion() {} Quaternion(const float &x_, const float &y_, const float &z_, const float &w_) : x(x_), y(y_), z(z_), w(w_) {} Quaternion(const Vector4f &p) : x(p.x), y(p.y), z(p.z), w(p.w) {} Quaternion(const Quaternion &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} // load/store void Load(const float *v) { x = v[0]; y = v[1]; z = v[2]; w = v[3]; } void Store(float *v) const { v[0] = x; v[1] = y; v[2] = z; v[3] = w; } // setters void Set(const float &x_, const float &y_, const float &z_, const float &w_) { x = x_; y = y_; z = z_; w = w_; } void Set(const Vector4f &floatvec) { x = floatvec.x; y = floatvec.y; z = floatvec.z; w = floatvec.w; } void SetIdentity() { x = 0.0f; y = 0.0f; z = 0.0f; w = 1.0f; } // scalar functions float Length() const { return Y_sqrtf(x * x + y * y + z * z + w * w); } float Dot(const Quaternion &v) const { return x * x + y * y + z * z + w * w; } // access as array //const float &operator[](uint32 i) const { return (&x)[i]; } //float &operator[](uint32 i) { return (&x)[i]; } operator const float *() const { return &x; } operator float *() { return &x; } // quat functions Quaternion Normalize() const; Quaternion NormalizeEst() const; Quaternion Conjugate() const { return Quaternion(-x, -y, -z, w); } Quaternion Inverse() const { return Conjugate(); } // in-place functions void NormalizeInPlace(); void NormalizeEstInPlace(); void ConjugateInPlace(); void InvertInPlace(); // creates new quaternion Quaternion operator*(const Quaternion &q) const; // affects this quaternion Quaternion &operator*=(const Quaternion &q); Quaternion &operator=(const Quaternion &q) { x = q.x; y = q.y; z = q.z; w = q.w; return *this; } // comparitors bool operator==(const Quaternion &q) const; bool operator!=(const Quaternion &q) const; // rotate a vector SIMDVector3f operator*(const SIMDVector3f &v) const; Vector3f operator*(const Vector3f &v) const; // transforming back void GetAxisAngle(Vector3f &axis, Angle &angle) const; void GetAxes(Vector3f &xAxis, Vector3f &yAxis, Vector3f &zAxis) const; Vector3f GetEulerAngles() const; Vector4f GetVectorRepresentation() const; Matrix3x3f GetMatrix3x3() const; Matrix3x4f GetMatrix3x4() const; Matrix4x4f GetMatrix4x4() const; SIMDMatrix3x3f GetSIMDMatrix3() const; //SIMDMatrix3x3 GetSIMDMatrix3x4() const; SIMDMatrix4x4f GetSIMDMatrix4() const; // creators static Quaternion MakeRotationX(Angle angle) { return FromNormalizedAxisAngle(Vector3f::UnitX, angle); } static Quaternion MakeRotationY(Angle angle) { return FromNormalizedAxisAngle(Vector3f::UnitY, angle); } static Quaternion MakeRotationZ(Angle angle) { return FromNormalizedAxisAngle(Vector3f::UnitZ, angle); } static Quaternion FromEulerAngles(const Vector3f &v); static Quaternion FromEulerAngles(const Angle x, const Angle y, const Angle z); static Quaternion FromNormalizedAxisAngle(const Vector3f &axis, Angle angle); static Quaternion FromAxisAngle(const Vector3f &axis, Angle angle); static Quaternion FromAxes(const Vector3f &xAxis, const Vector3f &yAxis, const Vector3f &zAxis); static Quaternion FromFloat3x3(const Matrix3x3f &rotationMatrix); static Quaternion FromFloat3x4(const Matrix3x4f &rotationMatrix); static Quaternion FromFloat4x4(const Matrix4x4f &rotationMatrix); static Quaternion FromTwoVectors(const Vector3f &u, const Vector3f &v); static Quaternion FromTwoUnitVectors(const Vector3f &u, const Vector3f &v); // interpolation static Quaternion LinearInterpolate(const Quaternion &start, const Quaternion &end, float factor); // constants static const Quaternion &Identity; public: float x, y, z, w; }; <file_sep>/Engine/Source/Core/Common.h #pragma once // Pull in base lib common #include "YBaseLib/Common.h" // And the often-used stuff #include "YBaseLib/String.h" #include "YBaseLib/Memory.h" #include "YBaseLib/Atomic.h" <file_sep>/Editor/Source/Editor/EditorLightSimulator.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorLightSimulator.h" #include "Engine/ResourceManager.h" #include "Engine/Texture.h" #include "Renderer/RenderProxies/SpriteRenderProxy.h" #include "Renderer/RenderProxies/DirectionalLightRenderProxy.h" #include "Renderer/RenderProxies/PointLightRenderProxy.h" #include "Renderer/RenderWorld.h" EditorLightSimulator::EditorLightSimulator(uint32 entityID, RenderWorld *pRenderWorld) : m_lightType(LightType_Directional), m_pRenderWorld(pRenderWorld), m_showIndicator(true), m_pIndicatorRenderProxy(new SpriteRenderProxy(entityID)), m_color(float3::One), m_brightness(1.0f), m_castShadows(false), m_directionalLightDirection(float3::NegativeUnitZ), m_directionalLightAmbientFactor(0.2f), m_pDirectionalLightRenderProxy(new DirectionalLightRenderProxy(entityID)), m_pointLightLocation(float3::Zero), m_pointLightRange(16.0f), m_pointLightFalloff(1.0f), m_pPointLightRenderProxy(new PointLightRenderProxy(entityID)) { // set all settings UpdateIndicator(); UpdateProxies(); // add to render world m_pRenderWorld->AddRenderable(m_pIndicatorRenderProxy); m_pRenderWorld->AddRenderable(m_pDirectionalLightRenderProxy); m_pRenderWorld->AddRenderable(m_pPointLightRenderProxy); } EditorLightSimulator::~EditorLightSimulator() { // remove from world m_pRenderWorld->RemoveRenderable(m_pPointLightRenderProxy); m_pRenderWorld->RemoveRenderable(m_pDirectionalLightRenderProxy); m_pRenderWorld->RemoveRenderable(m_pIndicatorRenderProxy); // release hold on objects SAFE_RELEASE(m_pPointLightRenderProxy); SAFE_RELEASE(m_pDirectionalLightRenderProxy); SAFE_RELEASE(m_pIndicatorRenderProxy); } void EditorLightSimulator::UpdateProxies() { uint32 shadowFlags = (m_castShadows) ? (LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) : (0); if (m_lightType == LightType_Directional) { m_pDirectionalLightRenderProxy->SetEnabled(true); m_pPointLightRenderProxy->SetEnabled(false); m_pDirectionalLightRenderProxy->SetLightColor(m_color * m_brightness * (1.0f - m_directionalLightAmbientFactor)); m_pDirectionalLightRenderProxy->SetAmbientColor(m_color * m_brightness * m_directionalLightAmbientFactor); m_pDirectionalLightRenderProxy->SetShadowFlags(shadowFlags); m_pDirectionalLightRenderProxy->SetDirection(m_directionalLightDirection); } else if (m_lightType == LightType_Point) { m_pDirectionalLightRenderProxy->SetEnabled(true); m_pPointLightRenderProxy->SetEnabled(false); m_pPointLightRenderProxy->SetColor(m_color * m_brightness); m_pPointLightRenderProxy->SetShadowFlags(shadowFlags); m_pPointLightRenderProxy->SetPosition(m_pointLightLocation); m_pPointLightRenderProxy->SetRange(m_pointLightRange); m_pPointLightRenderProxy->SetFalloffExponent(m_pointLightFalloff); } else if (m_lightType == LightType_Spot) { m_pDirectionalLightRenderProxy->SetEnabled(false); m_pPointLightRenderProxy->SetEnabled(false); } } void EditorLightSimulator::ManipulateFromMouseMovement(const int2 &mousePositionDelta) { if (m_lightType == LightType_Directional) { // manipulating the x and z axises float rotX = (float)mousePositionDelta.x; float rotY = (float)mousePositionDelta.y; // rotate the current rotation Quaternion rotMod((m_directionalLightRotation * Quaternion::FromEulerAngles(rotX, rotY, 0.0f)).Normalize()); SetDirectionalLightRotation(rotMod); } else if (m_lightType == LightType_Point) { // move the light position, use 0.5 as a factor const float POS_FACTOR = 0.5; float modX = (float)mousePositionDelta.x * POS_FACTOR; float modY = (float)mousePositionDelta.y * POS_FACTOR; SetPointLightLocation(m_pointLightLocation + float3(modX, modY, 0.0f)); } else if (m_lightType == LightType_Spot) { } } void EditorLightSimulator::UpdateIndicator() { if (!m_showIndicator) { m_pIndicatorRenderProxy->SetVisibility(false); return; } if (m_lightType == LightType_Directional) { AutoReleasePtr<const Texture2D> pSpriteTexture = g_pResourceManager->GetTexture2D("textures/editor/light_directional"); if (pSpriteTexture == nullptr) pSpriteTexture = g_pResourceManager->GetDefaultTexture2D(); // calculate sprite position float3 spritePosition(m_directionalLightRotation * (float3::NegativeUnitZ * 5.0f)); m_pIndicatorRenderProxy->SetPosition(spritePosition); m_pIndicatorRenderProxy->SetTexture(pSpriteTexture); m_pIndicatorRenderProxy->SetSizeByDimensions(1.0f, 1.0f); m_pIndicatorRenderProxy->SetVisibility(true); } else if (m_lightType == LightType_Point) { AutoReleasePtr<const Texture2D> pSpriteTexture = g_pResourceManager->GetTexture2D("textures/editor/light_point"); if (pSpriteTexture == nullptr) pSpriteTexture = g_pResourceManager->GetDefaultTexture2D(); // calculate sprite position m_pIndicatorRenderProxy->SetPosition(m_pointLightLocation); m_pIndicatorRenderProxy->SetTexture(pSpriteTexture); m_pIndicatorRenderProxy->SetSizeByDimensions(1.0f, 1.0f); m_pIndicatorRenderProxy->SetVisibility(true); } else if (m_lightType == LightType_Spot) { AutoReleasePtr<const Texture2D> pSpriteTexture = g_pResourceManager->GetTexture2D("textures/editor/light_point"); if (pSpriteTexture == nullptr) pSpriteTexture = g_pResourceManager->GetDefaultTexture2D(); // calculate sprite position m_pIndicatorRenderProxy->SetPosition(float3::Zero); m_pIndicatorRenderProxy->SetTexture(pSpriteTexture); m_pIndicatorRenderProxy->SetSizeByDimensions(1.0f, 1.0f); m_pIndicatorRenderProxy->SetVisibility(true); } } <file_sep>/Engine/Source/GameFramework/StaticMeshBrush.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/StaticMeshBrush.h" #include "Engine/StaticMesh.h" #include "Engine/Engine.h" #include "Engine/World.h" #include "Engine/ResourceManager.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Renderer/RenderProxies/StaticMeshRenderProxy.h" #include "Renderer/RenderWorld.h" Log_SetChannel(StaticMeshBrush); DEFINE_OBJECT_TYPE_INFO(StaticMeshBrush); DEFINE_OBJECT_GENERIC_FACTORY(StaticMeshBrush); BEGIN_OBJECT_PROPERTY_MAP(StaticMeshBrush) PROPERTY_TABLE_MEMBER("StaticMeshName", PROPERTY_TYPE_STRING, 0, PropertyCallbackGetStaticMeshName, NULL, PropertyCallbackSetStaticMeshName, NULL, NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Visible", 0, offsetof(StaticMeshBrush, m_visible), NULL, NULL) PROPERTY_TABLE_MEMBER_BOOL("Collidable", 0, offsetof(StaticMeshBrush, m_collidable), NULL, NULL) PROPERTY_TABLE_MEMBER_UINT("ShadowFlags", 0, offsetof(StaticMeshBrush, m_shadowFlags), NULL, NULL) END_OBJECT_PROPERTY_MAP() StaticMeshBrush::StaticMeshBrush(const ObjectTypeInfo *pTypeInfo /* = &s_TypeInfo */) : BaseClass(pTypeInfo), m_pStaticMesh(nullptr), m_visible(true), m_shadowFlags(0), m_collidable(false), m_pRenderProxy(nullptr), m_pCollisionObject(nullptr) { } StaticMeshBrush::~StaticMeshBrush() { if (m_pRenderProxy != nullptr) m_pRenderProxy->Release(); if (m_pCollisionObject != nullptr) m_pCollisionObject->Release(); if (m_pStaticMesh != nullptr) m_pStaticMesh->Release(); } bool StaticMeshBrush::Create(const float3 &position /* = float3::Zero */, const Quaternion &rotation /* = Quaternion::Identity */, const float3 &scale /* = float3::One */, const StaticMesh *pStaticMesh /* = nullptr */, bool visible /* = true */, bool collidable /* = true */, uint32 shadowFlags /* = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS */) { m_transform.Set(position, rotation, scale); if (pStaticMesh != nullptr) { m_pStaticMesh = pStaticMesh; m_pStaticMesh->AddRef(); } else { m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); } m_visible = visible; m_collidable = collidable; m_shadowFlags = shadowFlags; return Initialize(); } bool StaticMeshBrush::Initialize() { // handle load errors if (m_pStaticMesh == nullptr) m_pStaticMesh = g_pResourceManager->GetDefaultStaticMesh(); // create render proxy if (m_visible) m_pRenderProxy = new StaticMeshRenderProxy(0, m_pStaticMesh, m_transform, m_shadowFlags); // and collision object if (m_collidable && m_pStaticMesh->GetCollisionShape() != nullptr) m_pCollisionObject = new Physics::StaticObject(0, m_pStaticMesh->GetCollisionShape(), m_transform); // calculate bounding box m_boundingBox = m_transform.TransformBoundingBox(m_pStaticMesh->GetBoundingBox()); m_boundingSphere = m_transform.TransformBoundingSphere(m_pStaticMesh->GetBoundingSphere()); return true; } void StaticMeshBrush::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->AddObject(m_pCollisionObject); if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->AddRenderable(m_pRenderProxy); } void StaticMeshBrush::OnRemoveFromWorld(World *pWorld) { if (m_pRenderProxy != nullptr) pWorld->GetRenderWorld()->RemoveRenderable(m_pRenderProxy); if (m_pCollisionObject != nullptr) pWorld->GetPhysicsWorld()->RemoveObject(m_pCollisionObject); BaseClass::OnRemoveFromWorld(pWorld); } bool StaticMeshBrush::PropertyCallbackGetStaticMeshName(ThisClass *pEntity, const void *pUserData, String *pValue) { pValue->Assign(pEntity->m_pStaticMesh->GetName()); return true; } bool StaticMeshBrush::PropertyCallbackSetStaticMeshName(ThisClass *pEntity, const void *pUserData, const String *pValue) { const StaticMesh *pStaticMesh = g_pResourceManager->GetStaticMesh(*pValue); if (pStaticMesh == NULL) return false; if (pEntity->m_pStaticMesh != NULL) pEntity->m_pStaticMesh->Release(); pEntity->m_pStaticMesh = pStaticMesh; return true; } <file_sep>/Editor/Source/Editor/EditorPropertyEditorWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorPropertyEditorWidget.h" #include "Editor/EditorResourceSelectionWidget.h" #include "Editor/EditorResourceSelectionDialog.h" #include "Editor/EditorVectorEditWidget.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMapEntity.h" #include "Editor/MapEditor/EditorEntityEditMode.h" #include "Editor/EditorHelpers.h" #include "MapCompiler/MapSource.h" Log_SetChannel(EditorPropertyEditorWidget); EditorPropertyEditorWidget::EditorPropertyEditorWidget(QWidget *pParent) : QWidget(pParent), m_supressPropertyUpdates(true) { CreateUI(); ConnectEvents(); } EditorPropertyEditorWidget::~EditorPropertyEditorWidget() { ClearProperties(); } void EditorPropertyEditorWidget::CreateUI() { QVBoxLayout *verticalLayout = new QVBoxLayout(this); verticalLayout->setContentsMargins(0, 0, 0, 0); verticalLayout->setMargin(0); // QGroupBox *titleFrame = new QGroupBox(this); // QHBoxLayout *titleLayout = new QHBoxLayout(titleFrame); // titleLayout->setContentsMargins(4, 0, 4, 0); // titleLayout->setAlignment(Qt::AlignTop); // // QLabel *titleIcon = new QLabel(titleFrame); // titleIcon->setPixmap(QPixmap(QStringLiteral(":/editor/icons/EditCodeHS.png"))); // titleIcon->setFixedSize(32, 32); // titleIcon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // titleLayout->addWidget(titleIcon); // // m_pTitleText = new QLabel(titleFrame); // m_pTitleText->setTextFormat(Qt::RichText); // //m_pTitleText->setText("<strong>hi</strong><br>Fooooo"); // titleLayout->addWidget(m_pTitleText); // // titleFrame->setMinimumSize(1, 48); // titleFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // titleFrame->setLayout(titleLayout); // verticalLayout->addWidget(titleFrame); QSplitter *splitter = new QSplitter(this); splitter->setOrientation(Qt::Vertical); m_pTreePropertyBrowser = new QtTreePropertyBrowser(splitter); m_pTreePropertyBrowser->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_pTreePropertyBrowser->setMinimumSize(1, 100); splitter->addWidget(m_pTreePropertyBrowser); m_pHelpText = new QTextEdit(splitter); m_pHelpText->setMinimumSize(1, 80); m_pHelpText->setAcceptRichText(true); m_pHelpText->setEnabled(false); m_pHelpText->setFrameShape(QFrame::Panel); m_pHelpText->setFrameShadow(QFrame::Sunken); splitter->addWidget(m_pHelpText); verticalLayout->addWidget(splitter, 1); setLayout(verticalLayout); m_pGroupPropertyManager = new QtGroupPropertyManager(m_pTreePropertyBrowser); m_pStringPropertyManager = new QtStringPropertyManager(m_pTreePropertyBrowser); m_pBoolPropertyManager = new QtBoolPropertyManager(m_pTreePropertyBrowser); m_pIntSpinBoxPropertyManager = new QtIntPropertyManager(m_pTreePropertyBrowser); m_pIntSliderPropertyManager = new QtIntPropertyManager(m_pTreePropertyBrowser); m_pDoubleSpinBoxPropertyManager = new QtDoublePropertyManager(m_pTreePropertyBrowser); m_pEnumPropertyManager = new QtEnumPropertyManager(m_pTreePropertyBrowser); m_pFlagPropertyManager = new QtFlagPropertyManager(m_pTreePropertyBrowser); m_pResourcePropertyManager = new EditorPropertyEditorResourcePropertyManager(m_pTreePropertyBrowser); m_pVectorPropertyManager = new EditorPropertyEditorVectorPropertyManager(m_pTreePropertyBrowser); // set default factories for the managers m_pTreePropertyBrowser->setFactoryForManager(m_pStringPropertyManager, new QtLineEditFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pBoolPropertyManager, new QtCheckBoxFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pIntSpinBoxPropertyManager, new QtSpinBoxFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pIntSliderPropertyManager, new QtSliderFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pDoubleSpinBoxPropertyManager, new QtDoubleSpinBoxFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pEnumPropertyManager, new QtEnumEditorFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pFlagPropertyManager->subBoolPropertyManager(), new QtCheckBoxFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pResourcePropertyManager, new EditorPropertyEditorResourceEditorFactory(m_pTreePropertyBrowser)); m_pTreePropertyBrowser->setFactoryForManager(m_pVectorPropertyManager, new EditorPropertyEditorVectorEditFactory(m_pTreePropertyBrowser)); } void EditorPropertyEditorWidget::ConnectEvents() { connect(m_pTreePropertyBrowser, SIGNAL(currentItemChanged(QtBrowserItem *)), this, SLOT(OnTreeBrowserCurrentItemChanged(QtBrowserItem *))); connect(m_pGroupPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pStringPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pBoolPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pIntSpinBoxPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pIntSliderPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pDoubleSpinBoxPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pEnumPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pFlagPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pResourcePropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); connect(m_pVectorPropertyManager, SIGNAL(propertyChanged(QtProperty *)), this, SLOT(OnPropertyManagerPropertyChanged(QtProperty *))); } // void EditorPropertyEditorWidget::SetTitleText(const char *titleText) // { // m_pTitleText->setText(titleText); // } bool EditorPropertyEditorWidget::AddProperty(const PropertyTemplateProperty *pPropertyDefinition, const char *currentValue) { QString propertyName(ConvertStringToQString(pPropertyDefinition->GetLabel())); PROPERTY_TYPE propertyType = pPropertyDefinition->GetType(); QtProperty *pProperty = NULL; QtAbstractPropertyManager *pPropertyManager = NULL; bool ownsPropertyManager = false; // suppress updates m_supressPropertyUpdates = true; PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE selectorType = (pPropertyDefinition->GetSelector() != NULL) ? pPropertyDefinition->GetSelector()->GetType() : PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_COUNT; switch (selectorType) { case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_RESOURCE: { const PropertyTemplateValueSelector_Resource *pResourceDefinition = static_cast<const PropertyTemplateValueSelector_Resource *>(pPropertyDefinition->GetSelector()); const ObjectTypeInfo *pObjectTypeInfo = ResourceTypeInfo::GetRegistry().GetTypeInfoByName(pResourceDefinition->GetResourceTypeName()); const ResourceTypeInfo *pResourceTypeInfo; if (pObjectTypeInfo != NULL && pObjectTypeInfo->IsDerived(OBJECT_TYPEINFO(Resource))) pResourceTypeInfo = static_cast<const ResourceTypeInfo *>(pObjectTypeInfo); else pResourceTypeInfo = NULL; pPropertyManager = m_pResourcePropertyManager; pProperty = m_pResourcePropertyManager->addProperty(propertyName); m_pResourcePropertyManager->setResourceType(pProperty, pResourceTypeInfo); } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SPINNER: { const PropertyTemplateValueSelector_Spinner *pSpinnerDefinition = static_cast<const PropertyTemplateValueSelector_Spinner *>(pPropertyDefinition->GetSelector()); switch (propertyType) { case PROPERTY_TYPE_INT: case PROPERTY_TYPE_UINT: { pPropertyManager = m_pIntSpinBoxPropertyManager; pProperty = m_pIntSpinBoxPropertyManager->addProperty(propertyName); m_pIntSpinBoxPropertyManager->setRange(pProperty, (int)pSpinnerDefinition->GetMinValue(), (int)pSpinnerDefinition->GetMaxValue()); m_pIntSpinBoxPropertyManager->setSingleStep(pProperty, (int)pSpinnerDefinition->GetIncrement()); } break; case PROPERTY_TYPE_FLOAT: { pPropertyManager = m_pDoubleSpinBoxPropertyManager; pProperty = m_pDoubleSpinBoxPropertyManager->addProperty(propertyName); m_pDoubleSpinBoxPropertyManager->setRange(pProperty, (double)pSpinnerDefinition->GetMinValue(), (double)pSpinnerDefinition->GetMaxValue()); m_pDoubleSpinBoxPropertyManager->setSingleStep(pProperty, (double)pSpinnerDefinition->GetIncrement()); } break; } } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SLIDER: { const PropertyTemplateValueSelector_Slider *pSliderDefinition = static_cast<const PropertyTemplateValueSelector_Slider *>(pPropertyDefinition->GetSelector()); switch (propertyType) { case PROPERTY_TYPE_INT: case PROPERTY_TYPE_UINT: { pPropertyManager = m_pIntSliderPropertyManager; pProperty = m_pIntSliderPropertyManager->addProperty(propertyName); m_pIntSliderPropertyManager->setRange(pProperty, (int)pSliderDefinition->GetMinValue(), (int)pSliderDefinition->GetMaxValue()); } break; } } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_CHOICE: { const PropertyTemplateValueSelector_Choice *pChoiceDefinition = static_cast<const PropertyTemplateValueSelector_Choice *>(pPropertyDefinition->GetSelector()); pPropertyManager = m_pEnumPropertyManager; pProperty = m_pEnumPropertyManager->addProperty(propertyName); QStringList enumNames; for (uint32 i = 0; i < pChoiceDefinition->GetChoiceCount(); i++) enumNames.append(ConvertStringToQString(pChoiceDefinition->GetChoice(i).Right)); m_pEnumPropertyManager->setEnumNames(pProperty, enumNames); } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_FLAGS: { const PropertyTemplateValueSelector_Flags *pFlagsDefinition = static_cast<const PropertyTemplateValueSelector_Flags *>(pPropertyDefinition->GetSelector()); pPropertyManager = m_pFlagPropertyManager; pProperty = m_pFlagPropertyManager->addProperty(propertyName); QStringList flagNames; for (uint32 i = 0; i < pFlagsDefinition->GetFlagCount(); i++) flagNames.append(ConvertStringToQString(pFlagsDefinition->GetFlag(i).Label)); m_pFlagPropertyManager->setFlagNames(pProperty, flagNames); } break; // default selectors default: { switch (propertyType) { case PROPERTY_TYPE_BOOL: { pPropertyManager = m_pBoolPropertyManager; pProperty = m_pBoolPropertyManager->addProperty(propertyName); } break; case PROPERTY_TYPE_STRING: { pPropertyManager = m_pStringPropertyManager; pProperty = m_pStringPropertyManager->addProperty(propertyName); } break; case PROPERTY_TYPE_FLOAT2: case PROPERTY_TYPE_FLOAT3: case PROPERTY_TYPE_FLOAT4: { pPropertyManager = m_pVectorPropertyManager; pProperty = m_pVectorPropertyManager->addProperty(propertyName); switch (propertyType) { case PROPERTY_TYPE_FLOAT2: m_pVectorPropertyManager->setNumComponents(pProperty, 2); break; case PROPERTY_TYPE_FLOAT3: m_pVectorPropertyManager->setNumComponents(pProperty, 3); break; case PROPERTY_TYPE_FLOAT4: m_pVectorPropertyManager->setNumComponents(pProperty, 4); break; } } break; case PROPERTY_TYPE_UINT: case PROPERTY_TYPE_INT: case PROPERTY_TYPE_FLOAT: case PROPERTY_TYPE_INT2: case PROPERTY_TYPE_INT3: case PROPERTY_TYPE_INT4: case PROPERTY_TYPE_QUATERNION: case PROPERTY_TYPE_TRANSFORM: { pPropertyManager = m_pStringPropertyManager; pProperty = m_pStringPropertyManager->addProperty(propertyName); } break; } } break; } if (pProperty == NULL) { // create a string property pProperty = m_pStringPropertyManager->addProperty(propertyName); pPropertyManager = m_pStringPropertyManager; } // add to our tracking list PropertyEntry propertyEntry; propertyEntry.PropertyName = pPropertyDefinition->GetName(); propertyEntry.pPropertyDefinition = pPropertyDefinition; propertyEntry.pProperty = pProperty; propertyEntry.pPropertyManager = pPropertyManager; propertyEntry.OwnsPropertyManager = ownsPropertyManager; m_properties.Add(propertyEntry); // does this property belong to a category? if (pPropertyDefinition->GetCategory().IsEmpty()) { // nope, so just add it to the root m_pTreePropertyBrowser->addProperty(pProperty); } else { // find the matching property header QString propertyCategory(ConvertStringToQString(pPropertyDefinition->GetCategory())); QtProperty *pCategoryProperty = nullptr; for (uint32 categoryIndex = 0; categoryIndex < m_categories.GetSize(); categoryIndex++) { if (m_categories[categoryIndex]->propertyName() == propertyCategory) { pCategoryProperty = m_categories[categoryIndex]; break; } } // found it? if (pCategoryProperty == nullptr) { // create it pCategoryProperty = m_pGroupPropertyManager->addProperty(propertyCategory); m_pTreePropertyBrowser->addProperty(pCategoryProperty); m_categories.Add(pCategoryProperty); } // add to this category pCategoryProperty->addSubProperty(pProperty); } // has a value? if (currentValue != nullptr) UpdatePropertyValue(pPropertyDefinition->GetName(), currentValue); // allow updates again m_pTreePropertyBrowser->setEnabled(true); m_supressPropertyUpdates = false; return true; } void EditorPropertyEditorWidget::AddPropertiesFromTemplate(const PropertyTemplate *pTemplate) { for (uint32 i = 0; i < pTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pPropertyDefinition = pTemplate->GetPropertyDefinition(i); // skip hidden properties if (pPropertyDefinition->GetFlags() & PROPERTY_TEMPLATE_PROPERTY_FLAG_HIDDEN) continue; // add it AddProperty(pPropertyDefinition, pPropertyDefinition->GetDefaultValue()); } } void EditorPropertyEditorWidget::ClearProperties() { m_supressPropertyUpdates = true; m_pTreePropertyBrowser->clear(); m_pTreePropertyBrowser->setEnabled(false); m_pHelpText->clear(); for (uint32 i = 0; i < m_properties.GetSize(); i++) { if (m_properties[i].OwnsPropertyManager) { m_pTreePropertyBrowser->unsetFactoryForManager(m_properties[i].pPropertyManager); delete m_properties[i].pPropertyManager; } } m_properties.Clear(); m_categories.Clear(); m_supressPropertyUpdates = false; m_pStringPropertyManager->clear(); m_pBoolPropertyManager->clear(); m_pIntSpinBoxPropertyManager->clear(); m_pIntSliderPropertyManager->clear(); m_pDoubleSpinBoxPropertyManager->clear(); m_pGroupPropertyManager->clear(); } void EditorPropertyEditorWidget::SetDestinationPropertyTable(PropertyTable *pPropertyTable) { m_pDestinationPropertyTable = pPropertyTable; } void EditorPropertyEditorWidget::UpdatePropertyValue(const char *propertyName, const char *propertyValue) { // find the property for (uint32 i = 0; i < m_properties.GetSize(); i++) { PropertyEntry *pPropertyEntry = &m_properties[i]; if (pPropertyEntry->PropertyName.Compare(propertyName)) { const PropertyTemplateProperty *pPropertyDefinition = pPropertyEntry->pPropertyDefinition; QtProperty *pProperty = pPropertyEntry->pProperty; // found it // update the property manager PROPERTY_TYPE propertyType = pPropertyDefinition->GetType(); PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE selectorType = (pPropertyDefinition->GetSelector() != NULL) ? pPropertyDefinition->GetSelector()->GetType() : PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_COUNT; switch (selectorType) { case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_RESOURCE: { m_supressPropertyUpdates = true; m_pResourcePropertyManager->setValue(pProperty, propertyValue); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SPINNER: { switch (propertyType) { case PROPERTY_TYPE_INT: case PROPERTY_TYPE_UINT: { int32 intValue = StringConverter::StringToInt32(propertyValue); m_supressPropertyUpdates = true; m_pIntSpinBoxPropertyManager->setValue(pProperty, intValue); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TYPE_FLOAT: { float floatValue = StringConverter::StringToFloat(propertyValue); m_supressPropertyUpdates = true; m_pDoubleSpinBoxPropertyManager->setValue(pProperty, (double)floatValue); m_supressPropertyUpdates = false; return; } break; } } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SLIDER: { switch (propertyType) { case PROPERTY_TYPE_INT: case PROPERTY_TYPE_UINT: { int32 intValue = StringConverter::StringToInt32(propertyValue); m_supressPropertyUpdates = true; m_pIntSliderPropertyManager->setValue(pProperty, intValue); m_supressPropertyUpdates = false; return; } break; } } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_CHOICE: { const PropertyTemplateValueSelector_Choice *pChoiceDefinition = static_cast<const PropertyTemplateValueSelector_Choice *>(pPropertyDefinition->GetSelector()); // map from our choice to the choice index uint32 choiceIndex = 0; for (uint32 j = 0; j < pChoiceDefinition->GetChoiceCount(); j++) { if (pChoiceDefinition->GetChoice(j).Left.Compare(propertyValue)) { choiceIndex = j; break; } } // alter in enum manager Log_DevPrintf("prop update %s: map choice '%s' to %u", pPropertyDefinition->GetName().GetCharArray(), propertyValue, choiceIndex); m_supressPropertyUpdates = true; m_pEnumPropertyManager->setValue(pProperty, (int)choiceIndex); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_FLAGS: { const PropertyTemplateValueSelector_Flags *pFlagsDefinition = static_cast<const PropertyTemplateValueSelector_Flags *>(pPropertyDefinition->GetSelector()); // map from our flags to the sequential flags uint32 ourMask = StringConverter::StringToUInt32(propertyValue); uint32 qtMask = 0; for (uint32 j = 0; j < pFlagsDefinition->GetFlagCount(); j++) { if (ourMask & pFlagsDefinition->GetFlag(j).Value) qtMask |= (1 << j); } // alter in enum manager Log_DevPrintf("prop update %s: map flags 0x%x to 0x%x", pPropertyDefinition->GetName().GetCharArray(), ourMask, qtMask); m_supressPropertyUpdates = true; m_pFlagPropertyManager->setValue(pProperty, ourMask); m_supressPropertyUpdates = false; return; } break; // default selectors default: { switch (propertyType) { case PROPERTY_TYPE_BOOL: { bool boolValue = StringConverter::StringToBool(propertyValue); m_supressPropertyUpdates = true; m_pBoolPropertyManager->setValue(pProperty, boolValue); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TYPE_STRING: { m_supressPropertyUpdates = true; m_pStringPropertyManager->setValue(pProperty, propertyValue); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TYPE_FLOAT2: case PROPERTY_TYPE_FLOAT3: case PROPERTY_TYPE_FLOAT4: { m_supressPropertyUpdates = true; m_pVectorPropertyManager->setValueString(pProperty, propertyValue); m_supressPropertyUpdates = false; return; } break; case PROPERTY_TYPE_UINT: case PROPERTY_TYPE_INT: case PROPERTY_TYPE_FLOAT: case PROPERTY_TYPE_INT2: case PROPERTY_TYPE_INT3: case PROPERTY_TYPE_INT4: case PROPERTY_TYPE_QUATERNION: case PROPERTY_TYPE_TRANSFORM: { m_supressPropertyUpdates = true; m_pStringPropertyManager->setValue(pProperty, propertyValue); m_supressPropertyUpdates = false; return; } break; } } break; } // if we get here, we were an invalid combination of selector/type. so assume string. DebugAssert(pPropertyEntry->pPropertyManager == m_pStringPropertyManager); m_supressPropertyUpdates = true; m_pStringPropertyManager->setValue(pProperty, propertyValue); m_supressPropertyUpdates = false; return; } } } void EditorPropertyEditorWidget::UpdatePropertyValueFromTable(const char *propertyName) { // retreive the value from the table, and update it DebugAssert(m_pDestinationPropertyTable != nullptr); UpdatePropertyValue(propertyName, m_pDestinationPropertyTable->GetPropertyValueDefaultString(propertyName)); } void EditorPropertyEditorWidget::OnTreeBrowserCurrentItemChanged(QtBrowserItem *pBrowserItem) { m_pHelpText->clear(); if (pBrowserItem == NULL) return; QtProperty *pProperty = pBrowserItem->property(); // find the property entry for the selection for (uint32 i = 0; i < m_properties.GetSize(); i++) { PropertyEntry *pEntry = &m_properties[i]; if (pEntry->pProperty == pProperty) { LargeString helpText; const PropertyTemplateProperty *pDefinition = pEntry->pPropertyDefinition; // add the title helpText.AppendFormattedString("<strong>%s</strong> (%s)<br>", pDefinition->GetName().GetCharArray(), NameTable_GetNameString(NameTables::PropertyType, pEntry->pPropertyDefinition->GetType())); // add the description helpText.AppendString(pDefinition->GetDescription()); helpText.AppendString("<br><br>"); // add the default value helpText.AppendFormattedString("<em>Default Value: %s</em>", pDefinition->GetDefaultValue().GetCharArray()); // set it m_pHelpText->setHtml(ConvertStringToQString(helpText)); return; } } // if we're here, it means it may be a category property, so just set it with that text QString categoryHelp; categoryHelp.append("<strong>"); categoryHelp.append(pProperty->propertyName()); categoryHelp.append("</strong>"); m_pHelpText->setHtml(categoryHelp); } void EditorPropertyEditorWidget::OnPropertyManagerPropertyChanged(QtProperty *pProperty) { if (m_supressPropertyUpdates || !pProperty->hasValue()) return; // try to get the real (final) value String finalName; SmallString finalValue; if (GetFinalPropertyValue(pProperty, &finalName, &finalValue)) { // signal the event OnPropertyValueChange(finalName, finalValue); } } bool EditorPropertyEditorWidget::GetFinalPropertyValue(const QtProperty *pProperty, String *pPropertyName, String *pPropertyValue) { // search for the property in the list for (uint32 i = 0; i < m_properties.GetSize(); i++) { const PropertyEntry &propertyEntry = m_properties[i]; if (propertyEntry.pProperty == pProperty) { // fix up property name pPropertyName->Assign(propertyEntry.pPropertyDefinition->GetName()); // some cases have to be changed if (propertyEntry.pPropertyDefinition->GetSelector() != nullptr) { PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE selectorType = propertyEntry.pPropertyDefinition->GetSelector()->GetType(); switch (selectorType) { case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_CHOICE: { // map the enum index to the choice index const PropertyTemplateValueSelector_Choice *pChoiceSelector = reinterpret_cast<const PropertyTemplateValueSelector_Choice *>(propertyEntry.pPropertyDefinition->GetSelector()); uint32 choiceIndex = (uint32)m_pEnumPropertyManager->value(pProperty); DebugAssert(choiceIndex < pChoiceSelector->GetChoiceCount()); pPropertyValue->Assign(pChoiceSelector->GetChoice(choiceIndex).Left); Log_DevPrintf("prop change %s :: map choice %u -> %s", propertyEntry.pPropertyDefinition->GetName().GetCharArray(), choiceIndex, pPropertyValue->GetCharArray()); return true; } break; case PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_FLAGS: { // map the flags in qt (starting at 1, 2) to our selector const PropertyTemplateValueSelector_Flags *pFlagsSelector = reinterpret_cast<const PropertyTemplateValueSelector_Flags *>(propertyEntry.pPropertyDefinition->GetSelector()); uint32 mask = (uint32)m_pFlagPropertyManager->value(pProperty); // start at the first one, iterate through uint32 finalMask = 0; for (uint32 j = 0; j < pFlagsSelector->GetFlagCount(); j++) { if (mask & (1 << j)) finalMask |= pFlagsSelector->GetFlag(j).Value; } // spit it out Log_DevPrintf("prop change %s :: map flags 0x%x -> 0x%x", propertyEntry.pPropertyDefinition->GetName().GetCharArray(), mask, finalMask); pPropertyValue->Assign(StringConverter::UInt32ToString(finalMask)); return true; } break; } } // no special treatment, just pass through as-is String propertyValueString(ConvertQStringToString(pProperty->valueText())); Log_DevPrintf("prop change %s -> %s", propertyEntry.pPropertyDefinition->GetName().GetCharArray(), propertyValueString.GetCharArray()); pPropertyValue->Assign(propertyValueString); return true; } } return false; } ////////////////////////////////////////////////////////////////////////// EditorPropertyEditorResourcePropertyManager::EditorPropertyEditorResourcePropertyManager(QObject *pParent /*= NULL*/) : QtAbstractPropertyManager(pParent) { } EditorPropertyEditorResourcePropertyManager::~EditorPropertyEditorResourcePropertyManager() { } QString EditorPropertyEditorResourcePropertyManager::value(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.constEnd()) return QString(); return itr->val; } const ResourceTypeInfo *EditorPropertyEditorResourcePropertyManager::resourceType(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.constEnd()) return NULL; return itr->pResourceTypeInfo; } void EditorPropertyEditorResourcePropertyManager::setValue(QtProperty *pProperty, const QString &value) { PropertyValueMap::iterator itr = m_values.find(pProperty); if (itr == m_values.end()) return; if (itr->val == value) return; itr->val = value; propertyChanged(pProperty); valueChanged(pProperty, itr->val); } void EditorPropertyEditorResourcePropertyManager::setResourceType(QtProperty *pProperty, const ResourceTypeInfo *pResourceTypeInfo) { PropertyValueMap::iterator itr = m_values.find(pProperty); if (itr == m_values.end()) return; if (itr->pResourceTypeInfo == pResourceTypeInfo) return; itr->pResourceTypeInfo = pResourceTypeInfo; propertyChanged(pProperty); } QString EditorPropertyEditorResourcePropertyManager::valueText(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.end()) return QString(); return itr->val; } void EditorPropertyEditorResourcePropertyManager::initializeProperty(QtProperty *pProperty) { m_values[pProperty] = Data(); } void EditorPropertyEditorResourcePropertyManager::uninitializeProperty(QtProperty *pProperty) { m_values.remove(pProperty); } EditorPropertyEditorResourceEditorFactory::EditorPropertyEditorResourceEditorFactory(QObject *pParent /*= NULL*/) : QtAbstractEditorFactory<EditorPropertyEditorResourcePropertyManager>(pParent) { } EditorPropertyEditorResourceEditorFactory::~EditorPropertyEditorResourceEditorFactory() { DebugAssert(m_createdEditors.size() == 0); } void EditorPropertyEditorResourceEditorFactory::connectPropertyManager(EditorPropertyEditorResourcePropertyManager *pManager) { connect(pManager, SIGNAL(valueChanged(QtProperty *, const QString &)), this, SLOT(slotManagerValueChanged(QtProperty *, const QString &))); } QWidget *EditorPropertyEditorResourceEditorFactory::createEditor(EditorPropertyEditorResourcePropertyManager *pManager, QtProperty *pProperty, QWidget *pParent) { EditorResourceSelectionWidget *pEdit = new EditorResourceSelectionWidget(pParent); PropertyToEditorListMap::iterator itr = m_createdEditors.find(pProperty); if (itr == m_createdEditors.end()) itr = m_createdEditors.insert(pProperty, EditorList()); itr->append(pEdit); m_editorToProperty.insert(pEdit, pProperty); pEdit->setResourceTypeInfo(pManager->resourceType(pProperty)); pEdit->setValue(pManager->value(pProperty)); connect(pEdit, SIGNAL(valueChanged(const QString &)), this, SLOT(slotEditorValueChanged(const QString &))); connect(pEdit, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *))); return pEdit; } void EditorPropertyEditorResourceEditorFactory::disconnectPropertyManager(EditorPropertyEditorResourcePropertyManager *pManager) { disconnect(pManager, SIGNAL(valueChanged(const QString &)), this, SLOT(slotManagerValueChanged(const QString &))); } void EditorPropertyEditorResourceEditorFactory::slotManagerValueChanged(QtProperty *pProperty, const QString &value) { if (!m_createdEditors.contains(pProperty)) return; QListIterator<EditorResourceSelectionWidget *> itEditor(m_createdEditors[pProperty]); while (itEditor.hasNext()) { EditorResourceSelectionWidget *editor = itEditor.next(); if (editor->getValue() != value) editor->setValue(value); } } void EditorPropertyEditorResourceEditorFactory::slotEditorValueChanged(const QString &value) { QObject *pSender = sender(); const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd(); for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor) { if (itEditor.key() == pSender) { QtProperty *property = itEditor.value(); EditorPropertyEditorResourcePropertyManager *manager = propertyManager(property); if (manager == NULL) return; manager->setValue(property, value); return; } } } void EditorPropertyEditorResourceEditorFactory::slotEditorDestroyed(QObject *pEditor) { const EditorToPropertyMap::iterator ecend = m_editorToProperty.end(); for (EditorToPropertyMap::iterator itEditor = m_editorToProperty.begin(); itEditor != ecend; ++itEditor) { if (itEditor.key() == pEditor) { EditorResourceSelectionWidget *editor = itEditor.key(); QtProperty *property = itEditor.value(); const PropertyToEditorListMap::iterator pit = m_createdEditors.find(property); if (pit != m_createdEditors.end()) { pit.value().removeAll(editor); if (pit.value().empty()) m_createdEditors.erase(pit); } m_editorToProperty.erase(itEditor); return; } } } ////////////////////////////////////////////////////////////////////////// EditorPropertyEditorVectorPropertyManager::EditorPropertyEditorVectorPropertyManager(QObject *pParent /*= NULL*/) : QtAbstractPropertyManager(pParent) { } EditorPropertyEditorVectorPropertyManager::~EditorPropertyEditorVectorPropertyManager() { } uint32 EditorPropertyEditorVectorPropertyManager::numComponents(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.constEnd()) return 4; return itr->numComponents; } QString EditorPropertyEditorVectorPropertyManager::valueString(const QtProperty *pProperty) const { return valueText(pProperty); } float4 EditorPropertyEditorVectorPropertyManager::valueVector(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.constEnd()) return float4::Zero; return itr->valueVector; } void EditorPropertyEditorVectorPropertyManager::setNumComponents(QtProperty *pProperty, uint32 nComponents) { PropertyValueMap::iterator itr = m_values.find(pProperty); if (itr == m_values.end()) return; if (itr->numComponents == nComponents) return; itr->numComponents = nComponents; propertyChanged(pProperty); } void EditorPropertyEditorVectorPropertyManager::setValueString(QtProperty *pProperty, const char *value) { PropertyValueMap::iterator itr = m_values.find(pProperty); if (itr == m_values.end()) return; float4 newValue(float4::Zero); switch (itr->numComponents) { case 1: newValue = float4(StringConverter::StringToFloat(value), 0.0f, 0.0f, 0.0f); break; case 2: newValue = float4(StringConverter::StringToFloat2(value), 0.0f, 0.0f); break; case 3: newValue = float4(StringConverter::StringToFloat3(value), 0.0f); break; case 4: newValue = StringConverter::StringToFloat4(value); break; } if (itr->valueVector == newValue) return; itr->valueVector = newValue; propertyChanged(pProperty); valueChanged(pProperty, newValue); } void EditorPropertyEditorVectorPropertyManager::setValueVector(QtProperty *pProperty, const float4 &value) { PropertyValueMap::iterator itr = m_values.find(pProperty); if (itr == m_values.end()) return; if (itr->valueVector == value) return; itr->valueVector = value; propertyChanged(pProperty); valueChanged(pProperty, value); } QString EditorPropertyEditorVectorPropertyManager::valueText(const QtProperty *pProperty) const { PropertyValueMap::const_iterator itr = m_values.constFind(pProperty); if (itr == m_values.constEnd()) return QString(); switch (itr->numComponents) { case 1: return ConvertStringToQString(StringConverter::FloatToString(itr->valueVector.x)); break; case 2: return ConvertStringToQString(StringConverter::Float2ToString(itr->valueVector.xy())); break; case 3: return ConvertStringToQString(StringConverter::Float3ToString(itr->valueVector.xyz())); break; case 4: return ConvertStringToQString(StringConverter::Float4ToString(itr->valueVector)); break; } return QString(); } void EditorPropertyEditorVectorPropertyManager::initializeProperty(QtProperty *pProperty) { m_values[pProperty] = Data(); } void EditorPropertyEditorVectorPropertyManager::uninitializeProperty(QtProperty *pProperty) { m_values.remove(pProperty); } EditorPropertyEditorVectorEditFactory::EditorPropertyEditorVectorEditFactory(QObject *pParent /*= NULL*/) : QtAbstractEditorFactory<EditorPropertyEditorVectorPropertyManager>(pParent) { } EditorPropertyEditorVectorEditFactory::~EditorPropertyEditorVectorEditFactory() { DebugAssert(m_createdEditors.size() == 0); } void EditorPropertyEditorVectorEditFactory::connectPropertyManager(EditorPropertyEditorVectorPropertyManager *pManager) { connect(pManager, SIGNAL(valueChanged(QtProperty *, const QString &)), this, SLOT(slotManagerValueChanged(QtProperty *, const QString &))); } QWidget *EditorPropertyEditorVectorEditFactory::createEditor(EditorPropertyEditorVectorPropertyManager *pManager, QtProperty *pProperty, QWidget *pParent) { EditorVectorEditWidget *pEdit = new EditorVectorEditWidget(pParent); PropertyToEditorListMap::iterator itr = m_createdEditors.find(pProperty); if (itr == m_createdEditors.end()) itr = m_createdEditors.insert(pProperty, EditorList()); itr->append(pEdit); m_editorToProperty.insert(pEdit, pProperty); pEdit->SetNumComponents(pManager->numComponents(pProperty)); float4 value(pManager->valueVector(pProperty)); pEdit->SetValue(value.x, value.y, value.z, value.w); connect(pEdit, SIGNAL(ValueChangedFloat4(const float4 &)), this, SLOT(slotEditorValueChanged(const float4 &))); connect(pEdit, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *))); return pEdit; } void EditorPropertyEditorVectorEditFactory::disconnectPropertyManager(EditorPropertyEditorVectorPropertyManager *pManager) { disconnect(pManager, SIGNAL(valueChanged(const float4 &)), this, SLOT(slotManagerValueChanged(const float4 &))); } void EditorPropertyEditorVectorEditFactory::slotManagerValueChanged(QtProperty *pProperty, const float4 &value) { if (!m_createdEditors.contains(pProperty)) return; QListIterator<EditorVectorEditWidget *> itEditor(m_createdEditors[pProperty]); while (itEditor.hasNext()) { EditorVectorEditWidget *editor = itEditor.next(); if (editor->GetValueFloat4() != value) editor->SetValue(value.x, value.y, value.z, value.w); } } void EditorPropertyEditorVectorEditFactory::slotEditorValueChanged(const float4 &value) { QObject *pSender = sender(); const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd(); for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor) { if (itEditor.key() == pSender) { QtProperty *property = itEditor.value(); EditorPropertyEditorVectorPropertyManager *manager = propertyManager(property); if (manager == NULL) return; manager->setValueVector(property, value); return; } } } void EditorPropertyEditorVectorEditFactory::slotEditorDestroyed(QObject *pEditor) { const EditorToPropertyMap::iterator ecend = m_editorToProperty.end(); for (EditorToPropertyMap::iterator itEditor = m_editorToProperty.begin(); itEditor != ecend; ++itEditor) { if (itEditor.key() == pEditor) { EditorVectorEditWidget *editor = itEditor.key(); QtProperty *property = itEditor.value(); const PropertyToEditorListMap::iterator pit = m_createdEditors.find(property); if (pit != m_createdEditors.end()) { pit.value().removeAll(editor); if (pit.value().empty()) m_createdEditors.erase(pit); } m_editorToProperty.erase(itEditor); return; } } } ////////////////////////////////////////////////////////////////////////// <file_sep>/Engine/Source/Engine/TerrainRendererCDLOD.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainRendererCDLOD.h" #include "Engine/TerrainQuadTree.h" #include "Engine/ResourceManager.h" #include "Engine/Camera.h" #include "Engine/Engine.h" #include "Engine/EngineCVars.h" #include "Engine/StaticMesh.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/RenderWorld.h" #include "Renderer/Shaders/OneColorShader.h" #include "Renderer/ShaderProgram.h" Log_SetChannel(TerrainRendererCDLOD); static const float DEFAULT_TERRAIN_QUADTREE_MORPH_START_RATIO = 0.70f; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TerrainRendererCDLOD_VertexFactory ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DEFINE_VERTEX_FACTORY_TYPE_INFO(TerrainRendererCDLOD_VertexFactory); BEGIN_SHADER_COMPONENT_PARAMETERS(TerrainRendererCDLOD_VertexFactory) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainPatchOffset", SHADER_PARAMETER_TYPE_FLOAT3) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainPatchSize", SHADER_PARAMETER_TYPE_FLOAT3) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainPatchOffsetInTextureSpace", SHADER_PARAMETER_TYPE_FLOAT2) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainPatchSizeInTextureSpace", SHADER_PARAMETER_TYPE_FLOAT2) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainHeightMapDimensions", SHADER_PARAMETER_TYPE_FLOAT4) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainGridDimensions", SHADER_PARAMETER_TYPE_FLOAT3) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainMorphConstants", SHADER_PARAMETER_TYPE_FLOAT4) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainHeightMapTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("TerrainHeightMapSampler", SHADER_PARAMETER_TYPE_SAMPLER_STATE) END_SHADER_COMPONENT_PARAMETERS() bool TerrainRendererCDLOD_VertexFactory::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { return true; } bool TerrainRendererCDLOD_VertexFactory::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { pParameters->SetVertexFactoryFileName("shaders/base/TerrainVertexFactory.hlsl"); return true; } uint32 TerrainRendererCDLOD_VertexFactory::GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]) { // create format declaration GPU_VERTEX_ELEMENT_DESC *pElementDesc = pElementsDesc; uint32 streamOffset; uint32 nElements = 0; uint32 nStreams = 0; // build stream 0 { streamOffset = 0; // position pElementDesc->Semantic = GPU_VERTEX_ELEMENT_SEMANTIC_POSITION; pElementDesc->SemanticIndex = 0; pElementDesc->Type = GPU_VERTEX_ELEMENT_TYPE_FLOAT2; pElementDesc->StreamIndex = nStreams; pElementDesc->StreamOffset = streamOffset; pElementDesc->InstanceStepRate = 0; streamOffset += sizeof(float3); pElementDesc++; nElements++; // end of stream nStreams++; } // done return nElements; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TerrainRendererCDLOD ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TerrainRendererCDLOD::TerrainRendererCDLOD(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList) : TerrainRenderer(TERRAIN_RENDERER_TYPE_CDLOD, pParameters, pLayerList), m_pSettingsUpdateCallback(MakeFunctorClass(this, &TerrainRendererCDLOD::OnSettingsChangedCallback)), m_settingsUpdatedFlag(false), m_gridSize(0), m_pVertexBuffer(NULL), m_pIndexBuffer(NULL), m_indexFormat(GPU_INDEX_FORMAT_UINT16), m_indexCount(0), m_indexCountPerSubQuad(0), m_indexCountSingleQuad(0), m_indexEndTL(0), m_indexEndTR(0), m_indexEndBL(0), m_indexEndBR(0), m_GPUResourcesCreated(false) { CVars::r_terrain_render_resolution_multiplier.AddChangeCallback(m_pSettingsUpdateCallback); } TerrainRendererCDLOD::~TerrainRendererCDLOD() { if (Renderer::IsOnRenderThread()) { TerrainRendererCDLOD::ReleaseGPUResources(); } else { QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this]() { TerrainRendererCDLOD::ReleaseGPUResources(); }); } CVars::r_terrain_render_resolution_multiplier.RemoveChangeCallback(m_pSettingsUpdateCallback); delete m_pSettingsUpdateCallback; } TerrainSectionRenderProxy *TerrainRendererCDLOD::CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) { // fixme properly TerrainSectionRenderProxyCDLOD *pRenderProxy = new TerrainSectionRenderProxyCDLOD(entityId, this, pSection); QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([&pRenderProxy]() { if (!pRenderProxy->CreateGPUResources()) { pRenderProxy->Release(); pRenderProxy = nullptr; } }); return pRenderProxy; } bool TerrainRendererCDLOD::CreateGPUResources() { if (m_settingsUpdatedFlag) { ReleaseGPUResources(); m_settingsUpdatedFlag = false; } if (m_GPUResourcesCreated) return true; bool result = true; if (m_pVertexBuffer == NULL || m_pIndexBuffer == NULL) { if (!CreateGridBuffers()) result = false; } m_GPUResourcesCreated = result; return result; } void TerrainRendererCDLOD::ReleaseGPUResources() { SAFE_RELEASE(m_pVertexBuffer); SAFE_RELEASE(m_pIndexBuffer); m_indexFormat = GPU_INDEX_FORMAT_UINT16; m_gridSize = 0; m_indexCount = 0; m_indexCountPerSubQuad = 0; m_indexEndTL = 0; m_indexEndTR = 0; m_indexEndBL = 0; m_indexEndBR = 0; m_indexCountSingleQuad = 0; m_GPUResourcesCreated = false; } bool TerrainRendererCDLOD::CreateGridBuffers() { // calculate grid size uint32 gridQuads = (m_parameters.SectionSize >> (m_parameters.LODCount - 1)); uint32 gridVertices = gridQuads + 1; DebugAssert(gridQuads > 0); // todo: render resolution multiplier // calculate the number of vertices, indices needed uint32 vertexSize = sizeof(float2); uint32 nVerticesRequired = gridVertices * gridVertices; uint32 nIndicesRequired = (gridQuads * gridQuads * 3 * 2) + 6; Log_DevPrintf("TerrainRendererCDLOD::CreateGridBuffers: Calculated grid size is %u vertices, %u quads", gridVertices, gridQuads); Log_DevPrintf("TerrainRendererCDLOD::CreateGridBuffers: %u vertices required, %u indices required", nVerticesRequired, nIndicesRequired); // fill vertices float2 *pVertices = new float2[nVerticesRequired]; uint32 nVertices = 0; for (uint32 y = 0; y < gridVertices; y++) { for (uint32 x = 0; x < gridVertices; x++) { // this is deliberately quads (vertices - 1) so that (quads) == 1.0 DebugAssert(nVertices < nVerticesRequired); pVertices[nVertices++].Set((float)x / (float)gridQuads, (float)y / (float)gridQuads); } } // fill indices GPU_INDEX_FORMAT indexFormat; uint16 *pIndices16 = NULL; uint32 *pIndices32 = NULL; uint32 nIndices = 0; uint32 halfGridQuads = gridQuads / 2; uint32 indexCountPerSubQuad = halfGridQuads * halfGridQuads * 6; uint32 indexCountSingleQuad = 6; uint32 indexEndTL; uint32 indexEndTR; uint32 indexEndBL; uint32 indexEndBR; // use 16bit? if (nVertices < 0xFFFF) { pIndices16 = new uint16[nIndicesRequired]; indexFormat = GPU_INDEX_FORMAT_UINT16; // top-left for (uint32 y = 0; y < halfGridQuads; y++) { for (uint32 x = 0; x < halfGridQuads; x++) { pIndices16[nIndices++] = (uint16)(x + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * (y + 1)); } } indexEndTL = nIndices; // Top right part for (uint32 y = 0; y < halfGridQuads; y++) { for (uint32 x = halfGridQuads; x < gridQuads; x++) { pIndices16[nIndices++] = (uint16)(x + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * (y + 1)); } } indexEndTR = nIndices; // Bottom left part for (uint32 y = halfGridQuads; y < gridQuads; y++) { for (uint32 x = 0; x < halfGridQuads; x++) { pIndices16[nIndices++] = (uint16)(x + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * (y + 1)); } } indexEndBL = nIndices; // Bottom right part for (uint32 y = halfGridQuads; y < gridQuads; y++) { for (uint32 x = halfGridQuads; x < gridQuads; x++) { pIndices16[nIndices++] = (uint16)(x + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)(x + gridVertices * (y + 1)); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * y); pIndices16[nIndices++] = (uint16)((x + 1) + gridVertices * (y + 1)); } } indexEndBR = nIndices; // single quad pIndices16[nIndices++] = (uint16)0; pIndices16[nIndices++] = (uint16)(gridQuads); pIndices16[nIndices++] = (uint16)(gridVertices * gridQuads); pIndices16[nIndices++] = (uint16)(gridVertices * gridQuads); pIndices16[nIndices++] = (uint16)(gridQuads); pIndices16[nIndices++] = (uint16)(gridQuads + (gridVertices * gridQuads)); } else { pIndices32 = new uint32[nIndicesRequired]; indexFormat = GPU_INDEX_FORMAT_UINT32; // top-left for (uint32 y = 0; y < halfGridQuads; y++) { for (uint32 x = 0; x < halfGridQuads; x++) { pIndices32[nIndices++] = (x + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * (y + 1)); } } indexEndTL = nIndices; // Top right part for (uint32 y = 0; y < halfGridQuads; y++) { for (uint32 x = halfGridQuads; x < gridQuads; x++) { pIndices32[nIndices++] = (x + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * (y + 1)); } } indexEndTR = nIndices; // Bottom left part for (uint32 y = halfGridQuads; y < gridQuads; y++) { for (uint32 x = 0; x < halfGridQuads; x++) { pIndices32[nIndices++] = (x + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * (y + 1)); } } indexEndBL = nIndices; // Bottom right part for (uint32 y = halfGridQuads; y < gridQuads; y++) { for (uint32 x = halfGridQuads; x < gridQuads; x++) { pIndices32[nIndices++] = (x + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = (x + gridVertices * (y + 1)); pIndices32[nIndices++] = ((x + 1) + gridVertices * y); pIndices32[nIndices++] = ((x + 1) + gridVertices * (y + 1)); } } indexEndBR = nIndices; // single quad pIndices32[nIndices++] = 0; pIndices32[nIndices++] = (gridQuads); pIndices32[nIndices++] = (gridVertices * gridQuads); pIndices32[nIndices++] = (gridVertices * gridQuads); pIndices32[nIndices++] = (gridQuads); pIndices32[nIndices++] = (gridQuads + (gridVertices * gridQuads)); } // should be equal DebugAssert(nVertices == nVerticesRequired && nIndices == nIndicesRequired); // create vertex buffer GPUBuffer *pVertexBuffer; GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, vertexSize * nVertices); if ((pVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, pVertices)) == NULL) { Log_ErrorPrintf("TerrainRendererCDLOD::CreateGridBuffers: Could not create grid vertex buffer."); delete[] pVertices; delete[] pIndices16; delete[] pIndices32; return false; } // create index buffer GPUBuffer *pIndexBuffer; GPU_BUFFER_DESC indexBufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, ((indexFormat == GPU_INDEX_FORMAT_UINT16) ? sizeof(uint16) : sizeof(uint32)) * nIndices); if ((pIndexBuffer = g_pRenderer->CreateBuffer(&indexBufferDesc, (indexFormat == GPU_INDEX_FORMAT_UINT16) ? (void *)pIndices16 : (void *)pIndices32)) == NULL) { Log_ErrorPrintf("TerrainRendererCDLOD::CreateGridBuffers: Could not create grid index buffer."); pVertexBuffer->Release(); delete[] pVertices; delete[] pIndices16; delete[] pIndices32; return false; } // store indices DebugAssert(m_pVertexBuffer == NULL && m_pIndexBuffer == NULL); m_pVertexBuffer = pVertexBuffer; m_pIndexBuffer = pIndexBuffer; m_indexFormat = indexFormat; m_gridSize = gridQuads; m_indexCount = nIndices; m_indexCountPerSubQuad = indexCountPerSubQuad; m_indexCountSingleQuad = indexCountSingleQuad; m_indexEndTL = indexEndTL; m_indexEndTR = indexEndTR; m_indexEndBL = indexEndBL; m_indexEndBR = indexEndBR; delete[] pVertices; delete[] pIndices16; delete[] pIndices32; #ifdef Y_BUILD_CONFIG_DEBUG // set debug names m_pVertexBuffer->SetDebugName("<terrain patch vertex data>"); m_pIndexBuffer->SetDebugName("<terrain patch index data>"); #endif return true; } bool TerrainRendererCDLOD::BindGridBuffers(GPUCommandList *pCommandList) const { if (!m_GPUResourcesCreated && !const_cast<TerrainRendererCDLOD *>(this)->CreateGPUResources()) return false; uint32 vertexBufferOffset = 0; uint32 vertexBufferStride = sizeof(float2); pCommandList->SetVertexBuffers(0, 1, &m_pVertexBuffer, &vertexBufferOffset, &vertexBufferStride); pCommandList->SetIndexBuffer(m_pIndexBuffer, m_indexFormat, 0); return true; } void TerrainRendererCDLOD::OnSettingsChangedCallback() { m_settingsUpdatedFlag = true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TerrainSectionRenderProxyCDLOD ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TerrainSectionRenderProxyCDLOD::TerrainSectionRenderProxyCDLOD(uint32 entityID, const TerrainRendererCDLOD *pRenderer, const TerrainSection *pSection) : TerrainSectionRenderProxy(entityID, pSection), m_pRenderer(pRenderer), m_pHeightMapTexture(nullptr), m_pNormalMapTexture(nullptr), m_pAlphaMapTexture(nullptr), m_pRenderMaterial(nullptr), m_pDetailInstanceBuffer(nullptr), m_GPUResourcesCreated(false) { Y_memzero(m_visibilityRanges, sizeof(m_visibilityRanges)); Y_memzero(m_morphStart, sizeof(m_morphStart)); Y_memzero(m_morphEnd, sizeof(m_morphEnd)); Y_memzero(m_morphConstants, sizeof(m_morphConstants)); // calculate bounding box SetBounds(pSection->GetBoundingBox(), Sphere::FromAABox(pSection->GetBoundingBox())); } TerrainSectionRenderProxyCDLOD::~TerrainSectionRenderProxyCDLOD() { SAFE_RELEASE(m_pDetailInstanceBuffer); SAFE_RELEASE(m_pRenderMaterial); SAFE_RELEASE(m_pAlphaMapTexture); SAFE_RELEASE(m_pNormalMapTexture); SAFE_RELEASE(m_pHeightMapTexture); } void TerrainSectionRenderProxyCDLOD::OnLayersModified() { DebugAssert(g_pRenderer->GetRenderThreadId() == Thread::GetCurrentThreadId()); if (m_GPUResourcesCreated) { SAFE_RELEASE(m_pRenderMaterial); SAFE_RELEASE(m_pAlphaMapTexture); m_GPUResourcesCreated = false; if (CreateAlphaMapTexture()) { if (CreateRenderMaterial()) m_GPUResourcesCreated = true; } } } void TerrainSectionRenderProxyCDLOD::OnPointHeightModified(uint32 x, uint32 y) { DebugAssert(g_pRenderer->GetRenderThreadId() == Thread::GetCurrentThreadId()); if (m_pHeightMapTexture == nullptr) return; // get source pointer const void *pHeightMapValues; uint32 heightMapValueSize; uint32 heightMapRowPitch; m_pSection->GetRawHeightMapData(&pHeightMapValues, &heightMapValueSize, &heightMapRowPitch); // align it to the correct position DebugAssert(x < m_pSection->GetPointCount() && y < m_pSection->GetPointCount()); const byte *pSourcePointer = reinterpret_cast<const byte *>(pHeightMapValues) + (y * heightMapRowPitch) + (x * heightMapValueSize); // write to texture g_pRenderer->GetGPUContext()->WriteTexture(m_pHeightMapTexture, pSourcePointer, heightMapValueSize, heightMapValueSize, 0, x, y, 1, 1); // update bounding box if (GetBoundingBox() != m_pSection->GetBoundingBox()) SetBounds(m_pSection->GetBoundingBox(), Sphere::FromAABox(m_pSection->GetBoundingBox())); } void TerrainSectionRenderProxyCDLOD::OnPointLayersModified(uint32 x, uint32 y) { DebugAssert(g_pRenderer->GetRenderThreadId() == Thread::GetCurrentThreadId()); if (m_pAlphaMapTexture == nullptr) return; // for each splat map, gather the texel at these coordinates, then write it if (m_pAlphaMapTexture->GetTextureType() == TEXTURE_TYPE_2D_ARRAY) { Panic("Fixme"); /* for (uint32 i = 0; i < textureArraySize; i++) { // gather the (up to) 4 texel values uint8 texelValues[4] = { 0, 0, 0, 0 }; for (uint32 j = 0; j < 4; j++) { uint32 layerIndex = i * 4 + j; if (layerIndex < m_pSection->GetUsedLayerCount()) texelValues[j] = m_pSection->GetRawLayerWeightValues(layerIndex)[(y * m_pSection->GetPointCount()) + x]; else break; } // write to texture g_pRenderer->GetMainContext()->WriteTexture(static_cast<GPUTexture2DArray *>(m_pAlphaMapTexture), &texelValues, sizeof(texelValues), sizeof(texelValues), i, 0, x, y, 1, 1); } */ } else { for (uint32 mapIndex = 0; mapIndex < m_pSection->GetSplatMapCount(); mapIndex++) { // get pointer const void *pSplatMapValues; uint32 splatMapValueSize; uint32 splatMapRowPitch; m_pSection->GetRawSplatMapData(mapIndex, &pSplatMapValues, &splatMapValueSize, &splatMapRowPitch); // align it to the correct position DebugAssert(x < m_pSection->GetPointCount() && y < m_pSection->GetPointCount()); const byte *pSourcePointer = reinterpret_cast<const byte *>(pSplatMapValues)+(y * splatMapRowPitch) + (x * splatMapValueSize); // write to the texture g_pRenderer->GetGPUContext()->WriteTexture(static_cast<GPUTexture2D *>(m_pAlphaMapTexture), pSourcePointer, splatMapValueSize, splatMapValueSize, 0, x, y, 1, 1); } } } bool TerrainSectionRenderProxyCDLOD::CreateGPUResources() { // can't render a section without any layers if (m_pSection->GetSplatMapCount() == 0) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Section has no splat maps. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // create height map texture if (!CreateHeightMapTexture()) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Failed to create height map texture. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // create normal map texture if (!CreateNormalMapTexture()) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Failed to create normal map texture. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // create alpha map texture if (!CreateAlphaMapTexture()) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Failed to create alpha map texture. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // create render materials if (!CreateRenderMaterial()) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Failed to create render material. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // create detail buffer if (!CreateDetailInstanceBuffer()) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateGPUResources: Failed to create detail instance buffer. [section %i, %i]", m_pSection->GetSectionX(), m_pSection->GetSectionY()); return false; } // done m_GPUResourcesCreated = true; return true; } bool TerrainSectionRenderProxyCDLOD::CreateHeightMapTexture() { static const PIXEL_FORMAT heightStorageTextureFormats[TERRAIN_HEIGHT_STORAGE_FORMAT_COUNT] = { PIXEL_FORMAT_UNKNOWN, // uint8 PIXEL_FORMAT_UNKNOWN, // uint16 PIXEL_FORMAT_R32_FLOAT, // float32 }; #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Timer uploadTimer; #endif // get pointers DebugAssert(m_pHeightMapTexture == NULL); // setup texture desc GPU_TEXTURE2D_DESC textureDesc; textureDesc.Width = textureDesc.Height = m_pSection->GetPointCount(); textureDesc.Format = heightStorageTextureFormats[m_pSection->GetHeightStorageFormat()]; textureDesc.Flags = GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_SHADER_BINDABLE; textureDesc.MipLevels = 1; // setup sampler state GPU_SAMPLER_STATE_DESC samplerStateDesc; samplerStateDesc.Filter = TEXTURE_FILTER_MIN_MAG_MIP_POINT; samplerStateDesc.AddressU = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.AddressV = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.AddressW = TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.BorderColor.SetZero(); samplerStateDesc.LODBias = 0; samplerStateDesc.MinLOD = Y_INT32_MIN; samplerStateDesc.MaxLOD = Y_INT32_MAX; samplerStateDesc.MaxAnisotropy = 1; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_NEVER; // get mip pitches const void *pHeightMapData; uint32 heightMapValueSize; uint32 heightMapRowPitch; m_pSection->GetRawHeightMapData(&pHeightMapData, &heightMapValueSize, &heightMapRowPitch); // create the texture object if ((m_pHeightMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, &pHeightMapData, &heightMapRowPitch)) == NULL) { Log_ErrorPrintf("TerrainSectionRendererDataCDLOD::CreateFloatHeightMapTexture: Failed to create height map texture."); return false; } // String str; // const float *pPtr = (const float *)pDataPointer; // for (uint32 i = 0; i < textureDesc.Height; i++) // { // str.Clear(); // // const float *start = pPtr; // for (uint32 j = 0; j < textureDesc.Width; j++) // str.AppendFormattedString("%.2f ", *(pPtr++)); // // DebugAssert(pPtr == ((float *)((byte *)start + dataPitch))); // Log_DevPrint(str.GetCharArray()); // } // set debug name #ifdef Y_BUILD_CONFIG_DEBUG m_pHeightMapTexture->SetDebugName(String::FromFormat("<terrain_cdlod_section_%i_%i_heightmap_lod_%u>", m_pSection->GetSectionX(), m_pSection->GetSectionY(), m_pSection->GetStorageLODLevel())); #endif #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Log_ProfilePrintf("PROFILE: Terrain section (%i,%i) heightmap upload took %.4fmsec (streamed LOD %u)", m_pSection->GetSectionX(), m_pSection->GetSectionY(), uploadTimer.GetTimeMilliseconds(), m_pSection->GetStorageLODLevel()); #endif return true; } bool TerrainSectionRenderProxyCDLOD::CreateNormalMapTexture() { #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Timer uploadTimer; #endif uint32 pointCount = m_pSection->GetPointCount(); DebugAssert(m_pNormalMapTexture == NULL); // while we are using a float32 heightmap, we still encode as a rgba8 texture const PIXEL_FORMAT pixelFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; uint32 rowPitch = PixelFormat_CalculateRowPitch(pixelFormat, pointCount); byte *pPixels = new byte[PixelFormat_CalculateImageSize(pixelFormat, pointCount, pointCount, 1)]; byte *pPixelPointer = pPixels; // store normals for (uint32 y = 0; y < pointCount; y++) { uint32 *pRowPointer = reinterpret_cast<uint32 *>(pPixelPointer); for (uint32 x = 0; x < pointCount; x++) { float3 normal(m_pSection->CalculateNormalAtPoint(x, y)); *(pRowPointer++) = PixelFormatHelpers::EncodeNormalAsRG8B8B8(normal); } pPixelPointer += rowPitch; } // create texture GPU_TEXTURE2D_DESC textureDesc(pointCount, pointCount, pixelFormat, GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_SHADER_BINDABLE, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 1, 16, GPU_COMPARISON_FUNC_NEVER); if ((m_pNormalMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, (const void **)&pPixels, &rowPitch)) == NULL) { Log_ErrorPrintf("TerrainSectionRendererDataCDLOD::CreateFloatNormalMapTexture: Failed to create GPU texture."); delete[] pPixels; return false; } // clear memory delete[] pPixels; // set debug name #ifdef Y_BUILD_CONFIG_DEBUG m_pNormalMapTexture->SetDebugName(String::FromFormat("<terrain_cdlod_section_%i_%i_normalmap_lod_%u>", m_pSection->GetSectionX(), m_pSection->GetSectionY(), m_pSection->GetStorageLODLevel())); #endif #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Log_ProfilePrintf("PROFILE: Terrain section (%i,%i) normalmap upload took %.4fmsec (streamed LOD %u)", m_pSection->GetSectionX(), m_pSection->GetSectionY(), uploadTimer.GetTimeMilliseconds(), m_pSection->GetStorageLODLevel()); #endif return true; } bool TerrainSectionRenderProxyCDLOD::CreateCombinedHeightNormalMapTexture() { uint32 pointCount = m_pSection->GetPointCount(); float minHeight = (float)m_pRenderer->GetTerrainParameters()->MinHeight; float maxHeight = (float)m_pRenderer->GetTerrainParameters()->MaxHeight; float heightRange = (maxHeight - minHeight); float inverseHeightRange = 1.0f / heightRange; DebugAssert(m_pHeightMapTexture == NULL); const PIXEL_FORMAT pixelFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; uint32 rowPitch = PixelFormat_CalculateRowPitch(pixelFormat, pointCount); byte *pPixels = new byte[PixelFormat_CalculateImageSize(pixelFormat, pointCount, pointCount, 1)]; byte *pPixelPointer = pPixels; // store height + normal for (uint32 y = 0; y < pointCount; y++) { uint32 *pRowPointer = reinterpret_cast<uint32 *>(pPixelPointer); for (uint32 x = 0; x < pointCount; x++) { float height = m_pSection->GetHeightMapValue(x, y); float3 normal(m_pSection->CalculateNormalAtPoint(x, y)); // clamp to range height = Math::Clamp(height, minHeight, maxHeight); // split to high and low parts float heightFraction = height * inverseHeightRange; float height16BitVal = heightFraction * 65535.0f; float heightHighPart = height16BitVal / 256.0f; float heightLowPart = Y_fmodf(height16BitVal, 256.0f); // encode to rgba value union { uint32 rgbaValue; uint8 pRGBABytes[4]; }; pRGBABytes[0] = (uint8)Math::Truncate(heightHighPart); pRGBABytes[1] = (uint8)Math::Truncate(heightLowPart); pRGBABytes[2] = (uint8)Math::Truncate(normal.x * 0.5f + 0.5f); pRGBABytes[3] = (uint8)Math::Truncate(normal.y * 0.5f + 0.5f); // store value *(pRowPointer++) = rgbaValue; } pPixelPointer += rowPitch; } // create texture GPU_TEXTURE2D_DESC textureDesc(pointCount, pointCount, pixelFormat, GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_SHADER_BINDABLE, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 1, 16, GPU_COMPARISON_FUNC_NEVER); if ((m_pHeightMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, (const void **)&pPixels, &rowPitch)) == NULL) { Log_ErrorPrintf("TerrainSectionRendererDataCDLOD::CreateFloatNormalMapTexture: Failed to create GPU texture."); delete[] pPixels; return false; } // set debug name #ifdef Y_BUILD_CONFIG_DEBUG m_pHeightMapTexture->SetDebugName(String::FromFormat("<terrain_cdlod_section_%i_%i_combinedmap_lod_%u>", m_pSection->GetSectionX(), m_pSection->GetSectionY(), m_pSection->GetStorageLODLevel())); #endif // also bind to normal map DebugAssert(m_pNormalMapTexture == NULL); m_pNormalMapTexture = m_pHeightMapTexture; m_pNormalMapTexture->AddRef(); delete[] pPixels; return true; } bool TerrainSectionRenderProxyCDLOD::CreateAlphaMapTexture() { if (m_pAlphaMapTexture != nullptr) return true; #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Timer uploadTimer; #endif static const PIXEL_FORMAT splatMapFormats[4 + 1] = { PIXEL_FORMAT_UNKNOWN, PIXEL_FORMAT_R8_UNORM, PIXEL_FORMAT_R8G8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM }; DebugAssert(m_pAlphaMapTexture == NULL); // calculate number of textures uint32 textureDimensions = m_pSection->GetPointCount(); uint32 nSplatMaps = m_pSection->GetSplatMapCount(); if (nSplatMaps == 0) return false; // setup sampler state GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_CLAMP, float4::Zero, 0.0f, 0, 0, 1, GPU_COMPARISON_FUNC_NEVER); // create splat maps for (uint32 mapIndex = 0; mapIndex < nSplatMaps; mapIndex++) { // get pointer const void *pDataPointer; uint32 valueSize; uint32 rowPitch; uint32 splatMapChannels; m_pSection->GetRawSplatMapData(mapIndex, &pDataPointer, &valueSize, &rowPitch); splatMapChannels = m_pSection->GetSplatMapChannelCount(mapIndex); DebugAssert(splatMapChannels < countof(splatMapFormats)); // create the texture GPU_TEXTURE2D_DESC textureDesc(textureDimensions, textureDimensions, splatMapFormats[splatMapChannels], GPU_TEXTURE_FLAG_WRITABLE | GPU_TEXTURE_FLAG_SHADER_BINDABLE, 1); m_pAlphaMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc, &pDataPointer, &rowPitch); // created? if (m_pAlphaMapTexture == NULL) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::CreateAlphaMapTexture: Failed to create alpha map texture."); return false; } #ifdef Y_BUILD_CONFIG_DEBUG // set debug name m_pAlphaMapTexture->SetDebugName(String::FromFormat("<terrain_cdlod_section_%i_%i_alphamap_lod_%u>", m_pSection->GetSectionX(), m_pSection->GetSectionY(), m_pSection->GetStorageLODLevel())); #endif // String str; // for (uint32 y = 0; y < textureDimensions; y++) // { // str.Clear(); // for (uint32 x = 0; x < textureDimensions; x++) // { // if (textureDesc.Format == PIXEL_FORMAT_R8_UNORM) // str.AppendFormattedString("%u ", *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize))); // else if (textureDesc.Format == PIXEL_FORMAT_R8G8_UNORM) // str.AppendFormattedString("%u/%u ", *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize)), *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize) + 1)); // else if (textureDesc.Format == PIXEL_FORMAT_R8G8B8A8_UNORM) // str.AppendFormattedString("%u/%u/%u/%u ", *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize)), *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize) + 1), *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize) + 2), *(((const byte *)pDataPointer) + (y * rowPitch) + (x * valueSize) + 3)); // } // Log_DevPrintf("%u: %s", y, str.GetCharArray()); // } // FIXME if (mapIndex == 0) break; } #ifdef PROFILE_TEXTURE_UPLOAD_TIMES Log_ProfilePrintf("PROFILE: Terrain section (%i,%i) alphamap upload took %.4fmsec (streamed LOD %u)", m_pSection->GetSectionX(), m_pSection->GetSectionY(), uploadTimer.GetTimeMilliseconds(), m_pSection->GetStorageLODLevel()); #endif return true; } bool TerrainSectionRenderProxyCDLOD::CreateRenderMaterial() { if (m_pRenderMaterial != nullptr) return true; // no layers == no render material if (m_pSection->GetSplatMapCount() == 0 || m_pAlphaMapTexture == nullptr || m_pNormalMapTexture == nullptr) return false; const TerrainLayerList *pLayerList = m_pRenderer->GetLayerList(); uint32 nPossibleLayers = m_pSection->GetSplatMapCount() * 4; // collect the layer indices int32 *pLayerIndices = (int32 *)alloca(sizeof(int32) * nPossibleLayers); uint32 nLayers = 0; for (uint32 mapIndex = 0; mapIndex < m_pSection->GetSplatMapCount(); mapIndex++) { for (uint32 channelIndex = 0; channelIndex < m_pSection->GetSplatMapChannelCount(mapIndex); channelIndex++) pLayerIndices[nLayers++] = m_pSection->GetSplatMapChannel(mapIndex, channelIndex); } // create the render material m_pRenderMaterial = pLayerList->CreateBaseLayerRenderMaterial(pLayerIndices, nLayers, m_pNormalMapTexture, &m_pAlphaMapTexture, 1); if (m_pRenderMaterial == nullptr) { Log_WarningPrintf("TerrainSectionRendererDataCDLOD::CreateRenderMaterial: Could not create materials. Using default material."); m_pRenderMaterial = g_pResourceManager->GetDefaultMaterial(); } // ok return true; } void TerrainSectionRenderProxyCDLOD::CalculateMorphConstants(float cameraNearDistance, float cameraFarDistance) const { uint32 LODCount = m_pSection->GetQuadTree()->GetLODCount(); // precalculate ratios float LODVisRangeDistRatios[TERRAIN_MAX_RENDER_LODS]; { float LODDistanceRatio = CVars::r_terrain_lod_distance_ratio.GetFloat(); float currentDetailBalance = 1.0f; for (uint32 i = 0; i < LODCount - 1; i++) { LODVisRangeDistRatios[i] = currentDetailBalance; if (i == 0) LODVisRangeDistRatios[i] *= 0.9f; currentDetailBalance *= LODDistanceRatio; } LODVisRangeDistRatios[LODCount - 1] = currentDetailBalance; for (uint32 i = 0; i < LODCount; i++) LODVisRangeDistRatios[i] /= currentDetailBalance; } // precalculate values { float cameraRange = cameraFarDistance - cameraNearDistance; float prevPos = cameraNearDistance; cameraRange = Min(cameraRange, CVars::r_terrain_view_distance.GetFloat()); for (uint32 i = 0; i < LODCount; i++) { m_visibilityRanges[i] = cameraNearDistance + LODVisRangeDistRatios[i] * cameraRange; m_morphEnd[i] = m_visibilityRanges[i]; prevPos = m_morphStart[i] = prevPos + (m_morphEnd[i] - prevPos) * DEFAULT_TERRAIN_QUADTREE_MORPH_START_RATIO; } } // calculate constants for (uint32 i = 0; i < LODCount; i++) { float start = m_morphStart[i]; float end = m_morphEnd[i]; //end = Math::Lerp(end, start, 0.01f); float diff = end - start; float invDiff = 1.0f / diff; m_morphConstants[i].Set(start, invDiff, end / diff, invDiff); } } void TerrainSectionRenderProxyCDLOD::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!CreateDeviceResources()) return; // Store the requested render passes. // Terrain does not currently cast shadows. But it can receieve them. // Replace with AO at some point per-vertex? uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT & ~(RENDER_PASS_SHADOW_MAP); // early exit? wantedRenderPasses &= pRenderQueue->GetAcceptingRenderPassMask(); if (wantedRenderPasses == 0) return; // calculate morph constants CalculateMorphConstants(pCamera->GetNearPlaneDistance(), pCamera->GetFarPlaneDistance()); // find sections to draw m_pSection->GetQuadTree()->EnumerateNodesToRender(pCamera->GetPosition(), pCamera->GetFrustum(), m_visibilityRanges, [this, pCamera, pRenderQueue, wantedRenderPasses](const TerrainQuadTreeNode *pNode, uint32 drawFlags) { // get pass mask uint32 renderPassMask = m_pRenderMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { // get center of the section, todo cache this? SIMDVector3f nodeMinBounds(pNode->GetBoundingBox().GetMinBounds()); SIMDVector3f nodeMaxBounds(pNode->GetBoundingBox().GetMaxBounds()); SIMDVector3f nodeCenter((nodeMaxBounds - nodeMinBounds) * 0.5f + nodeMinBounds); // get view distance float viewDistance = pCamera->CalculateDepthToPoint(nodeCenter); // create queue entry for base layer RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(TerrainRendererCDLOD_VertexFactory); queueEntry.pMaterial = m_pRenderMaterial; queueEntry.BoundingBox = pNode->GetBoundingBox(); queueEntry.RenderPassMask = renderPassMask; queueEntry.VertexFactoryFlags = 0; queueEntry.ViewDistance = viewDistance; queueEntry.TintColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); queueEntry.UserData[0] = 0; queueEntry.UserData[1] = drawFlags; queueEntry.UserDataPointer[0] = const_cast<void *>(reinterpret_cast<const void *>(pNode)); queueEntry.Layer = m_pRenderMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } }); // find detail batches to draw if (BuildDetailBatches(g_pRenderer->GetGPUContext(), pCamera->GetPosition())) { // get section center float3 sectionCenter(m_pSection->GetBoundingBox().GetCenter()); float sectionViewDistance = pCamera->CalculateDepthToPoint(sectionCenter); // add batches for (uint32 detailBatchIndex = 0; detailBatchIndex < m_detailBatches.GetSize(); detailBatchIndex++) { const DetailBatch &detailBatch = m_detailBatches[detailBatchIndex]; const TerrainSection::DetailMesh *pDetailMesh = m_pSection->GetDetailMesh(detailBatch.MeshIndex); const StaticMesh *pStaticMesh = pDetailMesh->pStaticMesh; // todo: select lod based on center of section distance uint32 meshLOD = 0; // add mesh batches const StaticMesh::LOD *pMeshLOD = pStaticMesh->GetLOD(meshLOD); for (uint32 meshBatchIndex = 0; meshBatchIndex < pMeshLOD->GetBatchCount(); meshBatchIndex++) { const StaticMesh::Batch *pMeshBatch = pMeshLOD->GetBatch(meshBatchIndex); const Material *pBatchMaterial = pStaticMesh->GetMaterial(pMeshBatch->MaterialIndex); // get pass mask uint32 renderPassMask = pBatchMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); if (renderPassMask != 0) { // create queue entry for base layer RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.pRenderProxy = this; queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(LocalVertexFactory); queueEntry.pMaterial = pBatchMaterial; queueEntry.BoundingBox = m_pSection->GetBoundingBox(); queueEntry.RenderPassMask = renderPassMask; queueEntry.VertexFactoryFlags = pStaticMesh->GetVertexFactoryFlags() | LOCAL_VERTEX_FACTORY_FLAG_INSTANCING_BY_MATRIX; queueEntry.ViewDistance = sectionViewDistance; queueEntry.TintColor = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); queueEntry.UserData[0] = 1 + detailBatchIndex; queueEntry.UserData[1] = meshLOD; queueEntry.UserData[2] = meshBatchIndex; queueEntry.Layer = m_pRenderMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } } } // debug info if (pRenderQueue->IsAcceptingDebugObjects() && CVars::r_terrain_show_nodes.GetBool()) pRenderQueue->AddDebugInfoObject(this); } void TerrainSectionRenderProxyCDLOD::SetupTerrainDraw(const TerrainQuadTreeNode *pNode, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { // precalculate these values, quadtree is always in lod0 sizes float inverseTextureSize = 1.0f / (float)(m_pSection->GetPointCount()); float nodeSizeInTextureSpace = (float)(pNode->GetNodeSize()) * inverseTextureSize; float textureStartU = (float)pNode->GetStartQuadX() * inverseTextureSize + 0.5f * inverseTextureSize; float textureStartV = (float)pNode->GetStartQuadY() * inverseTextureSize + 0.5f * inverseTextureSize; // uniforms float3 worldSpaceRectOffset(pNode->GetBoundingBox().GetMinBounds().xy(), (m_pSection->GetHeightStorageFormat() == TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32) ? 0.0f : (float)m_pRenderer->GetTerrainParameters()->MinHeight); float3 worldSpaceRectSize(pNode->GetBoundingBox().GetMaxBounds().xy() - pNode->GetBoundingBox().GetMinBounds().xy(), (m_pSection->GetHeightStorageFormat() == TERRAIN_HEIGHT_STORAGE_FORMAT_FLOAT32) ? 1.0f : (float)(m_pRenderer->GetTerrainParameters()->MaxHeight - m_pRenderer->GetTerrainParameters()->MinHeight)); float2 textureSpaceRectOffset(textureStartU, textureStartV); float2 textureSpaceRectSize(nodeSizeInTextureSpace, nodeSizeInTextureSpace); float2 heightmapDimensions((float)m_pSection->GetPointCount(), 1.0f / (float)m_pSection->GetPointCount()); float3 gridDimensions((float)m_pRenderer->GetGridSize(), (float)m_pRenderer->GetGridSize() * 0.5f, 2.0f / (float)m_pRenderer->GetGridSize()); float4 morphConstants(m_morphConstants[pNode->GetLODLevel()]); // set uniforms pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 0, SHADER_PARAMETER_TYPE_FLOAT3, &worldSpaceRectOffset); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 1, SHADER_PARAMETER_TYPE_FLOAT3, &worldSpaceRectSize); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 2, SHADER_PARAMETER_TYPE_FLOAT2, &textureSpaceRectOffset); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 3, SHADER_PARAMETER_TYPE_FLOAT2, &textureSpaceRectSize); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 4, SHADER_PARAMETER_TYPE_FLOAT2, &heightmapDimensions); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 5, SHADER_PARAMETER_TYPE_FLOAT3, &gridDimensions); pShaderProgram->SetVertexFactoryParameterValue(pCommandList, 6, SHADER_PARAMETER_TYPE_FLOAT4, &morphConstants); pShaderProgram->SetVertexFactoryParameterResource(pCommandList, 7, m_pHeightMapTexture); pShaderProgram->SetVertexFactoryParameterResource(pCommandList, 8, m_pHeightMapTexture); // setup draw m_pRenderer->BindGridBuffers(pCommandList); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); } void TerrainSectionRenderProxyCDLOD::InvokeTerrainDraw(GPUCommandList *pCommandList, uint32 drawFlags) const { #if 1 if (drawFlags == TerrainQuadTreeQuery::DrawFlagSingleQuad) { pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndBR(), m_pRenderer->GetGridIndexCountSingleQuad(), 0); } else if (drawFlags == TerrainQuadTreeQuery::DrawFlagAll) { pCommandList->DrawIndexed(0, m_pRenderer->GetGridIndexCountPerSubQuad() * 4, 0); } else { const uint32 gridIndexCountPerSubQuad = m_pRenderer->GetGridIndexCountPerSubQuad(); if (drawFlags & TerrainQuadTreeQuery::DrawFlagTopLeft) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagTopRight) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomLeft) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomRight) { // TL + TR + BL + BR pCommandList->DrawIndexed(0, gridIndexCountPerSubQuad * 4, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopLeft | TerrainQuadTreeQuery::DrawFlagTopRight | TerrainQuadTreeQuery::DrawFlagBottomLeft | TerrainQuadTreeQuery::DrawFlagBottomRight); } else { // TL + TR + BL pCommandList->DrawIndexed(0, gridIndexCountPerSubQuad * 3, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopLeft | TerrainQuadTreeQuery::DrawFlagTopRight | TerrainQuadTreeQuery::DrawFlagBottomLeft); } } else { // TL + TR pCommandList->DrawIndexed(0, gridIndexCountPerSubQuad * 2, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopLeft | TerrainQuadTreeQuery::DrawFlagTopRight); } } else { // TL pCommandList->DrawIndexed(0, gridIndexCountPerSubQuad, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopLeft); } } if (drawFlags & TerrainQuadTreeQuery::DrawFlagTopRight) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomLeft) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomRight) { // TR + BL + BR pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndTL(), gridIndexCountPerSubQuad * 3, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopRight | TerrainQuadTreeQuery::DrawFlagBottomLeft | TerrainQuadTreeQuery::DrawFlagBottomRight); } else { // TR + BL pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndTL(), gridIndexCountPerSubQuad * 2, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopRight | TerrainQuadTreeQuery::DrawFlagBottomLeft); } } else { // TR pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndTL(), gridIndexCountPerSubQuad, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagTopRight); } } if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomLeft) { if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomRight) { // BL + BR pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndTR(), gridIndexCountPerSubQuad * 2, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagBottomLeft | TerrainQuadTreeQuery::DrawFlagBottomRight); } else { // BL pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndTR(), gridIndexCountPerSubQuad, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagBottomLeft); } } if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomRight) { // BR pCommandList->DrawIndexed(m_pRenderer->GetGridIndexEndBL(), gridIndexCountPerSubQuad, 0); drawFlags &= ~(TerrainQuadTreeQuery::DrawFlagBottomRight); } } #elif 0 static const uint32 drawFlagsConst[4] = { TerrainQuadTreeQuery::DrawFlagTopLeft, TerrainQuadTreeQuery::DrawFlagTopRight, TerrainQuadTreeQuery::DrawFlagBottomLeft, TerrainQuadTreeQuery::DrawFlagBottomRight }; const uint32 gridIndexCountPerSubQuad = m_pRenderer->GetGridIndexCountPerSubQuad(); for (uint32 i = 0; i < 4; i++) { if (drawFlags & drawFlagsConst[i]) { uint32 batchStart = 0; switch (i) { case 1: batchStart = m_pRenderer->GetGridIndexEndTL(); break; case 2: batchStart = m_pRenderer->GetGridIndexEndTR(); break; case 3: batchStart = m_pRenderer->GetGridIndexEndBL(); break; } uint32 batchCount = gridIndexCountPerSubQuad; for (uint32 j = i + 1; j < 4; j++) { if (drawFlags & drawFlagsConst[j]) { batchCount += gridIndexCountPerSubQuad; drawFlags &= ~drawFlagsConst[j]; } } pDevice->DrawIndexed(batchStart, batchCount, 0); } } #else if (drawFlags & TerrainQuadTreeQuery::DrawFlagTopLeft) pDevice->DrawIndexed(0, m_pRenderer->GetGridIndexCountPerSubQuad(), 0); if (drawFlags & TerrainQuadTreeQuery::DrawFlagTopRight) pDevice->DrawIndexed(m_pRenderer->GetGridIndexEndTL(), m_pRenderer->GetGridIndexCountPerSubQuad(), 0); if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomLeft) pDevice->DrawIndexed(m_pRenderer->GetGridIndexEndTR(), m_pRenderer->GetGridIndexCountPerSubQuad(), 0); if (drawFlags & TerrainQuadTreeQuery::DrawFlagBottomRight) pDevice->DrawIndexed(m_pRenderer->GetGridIndexEndBL(), m_pRenderer->GetGridIndexCountPerSubQuad(), 0); #endif } void TerrainSectionRenderProxyCDLOD::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { // height layer? if (pQueueEntry->UserData[0] == 0) { const TerrainQuadTreeNode *pNode = reinterpret_cast<const TerrainQuadTreeNode *>(pQueueEntry->UserDataPointer[0]); SetupTerrainDraw(pNode, pCommandList, pShaderProgram); } else { SetupDetailBatchDraw(pQueueEntry->UserData[0] - 1, pQueueEntry->UserData[1], pQueueEntry->UserData[2], pCommandList, pShaderProgram); } } void TerrainSectionRenderProxyCDLOD::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { // base layer? if (pQueueEntry->UserData[0] == 0) { uint32 nodeDrawFlags = pQueueEntry->UserData[1]; InvokeTerrainDraw(pCommandList, nodeDrawFlags); } else { InvokeDetailBatchDraw(pQueueEntry->UserData[0] - 1, pQueueEntry->UserData[1], pQueueEntry->UserData[2], pCommandList); } } void TerrainSectionRenderProxyCDLOD::DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const { if (CVars::r_terrain_show_nodes.GetBool()) { pGUIContext->PushManualFlush(); pGUIContext->SetAlphaBlendingEnabled(false); /* SmallString text; text.Format("flags = %u node from %u,%u to %u,%u [lod %u] @ section (%i, %i)", drawFlags, pNode->GetStartQuadX(), pNode->GetStartQuadY(), pNode->GetStartQuadX() + pNode->GetNodeSize(), pNode->GetStartQuadY() + pNode->GetNodeSize(), pNode->GetLODLevel(), m_pSection->GetSectionX(), m_pSection->GetSectionY()); pGUIContext->DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), 12, 0, nodeCount * 13 + 32, text, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255), false, MINIGUI_HORIZONTAL_ALIGNMENT_RIGHT, MINIGUI_VERTICAL_ALIGNMENT_TOP); nodeCount++; */ // find sections to draw m_pSection->GetQuadTree()->EnumerateNodesToRender(pCamera->GetPosition(), pCamera->GetFrustum(), m_visibilityRanges, [this, pGUIContext](const TerrainQuadTreeNode *pNode, uint32 drawFlags) { float3 startLODColor(1.0f, 0.0f, 0.0f); float3 endLODColor(0.0f, 1.0f, 0.0f); float3 minBounds(pNode->GetBoundingBox().GetMinBounds()); float3 maxBounds(pNode->GetBoundingBox().GetMaxBounds()); float3 color(startLODColor.Lerp(endLODColor, (float)pNode->GetLODLevel() / (float)(m_pSection->GetQuadTree()->GetLODCount() - 1))); pGUIContext->Draw3DWireBox(minBounds, maxBounds, MAKE_COLOR_R8G8B8A8_UNORM(color.r * 255.0f, color.g * 255.0f, color.b * 255.0f, 255)); }); pGUIContext->PopManualFlush(); } } bool TerrainSectionRenderProxyCDLOD::CreateDetailInstanceBuffer() { DebugAssert(m_pDetailInstanceBuffer == nullptr); // count the number of total instances uint32 instanceCount = m_pSection->GetDetailMeshInstanceCount(); if (instanceCount == 0) return true; // allocate a buffer with enough space to fill these const uint32 INSTANCE_SIZE = sizeof(float3x4); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER | GPU_BUFFER_FLAG_MAPPABLE, INSTANCE_SIZE * instanceCount); m_pDetailInstanceBuffer = g_pRenderer->CreateBuffer(&bufferDesc, nullptr); if (m_pDetailInstanceBuffer == nullptr) { Log_ErrorPrint("TerrainSectionRenderProxyCDLOD::CreateDetailInstanceBuffer: Failed to allocate GPU buffer"); return false; } // reserve enough batches m_detailBatches.Reserve(m_pSection->GetDetailMeshCount()); Log_DevPrintf("allocate detail buffer size %s", StringConverter::SizeToHumanReadableString(bufferDesc.Size).GetCharArray()); return true; } bool TerrainSectionRenderProxyCDLOD::BuildDetailBatches(GPUCommandList *pCommandList, const float3 &eyePosition) const { // Fixme for command lists. return false; #if 0 // any detail instances? if (m_pDetailInstanceBuffer == nullptr) return false; // map the buffer byte *pBufferPtr; if (!pGPUContext->MapBuffer(m_pDetailInstanceBuffer, GPU_MAP_TYPE_WRITE_DISCARD, reinterpret_cast<void **>(&pBufferPtr))) { Log_ErrorPrintf("TerrainSectionRenderProxyCDLOD::BuildDetailBatches: Failed to map GPU buffer"); return false; } // batch info uint32 lastMesh = Y_UINT32_MAX; float cullDistanceSq = Y_FLT_INFINITE; DetailBatch detailBatch; Y_memzero(&detailBatch, sizeof(detailBatch)); m_detailBatches.Clear(); // loop through instances, grab those in range and add them to the buffer byte *pCurrentBufferPtr = pBufferPtr; for (uint32 meshInstanceIndex = 0; meshInstanceIndex < m_pSection->GetDetailMeshInstanceCount(); meshInstanceIndex++) { const TerrainSection::DetailMeshInstance *meshInstance = m_pSection->GetDetailMeshInstance(meshInstanceIndex); // new mesh index? if (meshInstance->MeshIndex != lastMesh) { if (detailBatch.InstanceCount > 0) m_detailBatches.Add(detailBatch); // get info for new mesh detailBatch.MeshIndex = meshInstance->MeshIndex; detailBatch.InstanceBufferOffset = static_cast<uint32>(pCurrentBufferPtr - pBufferPtr); detailBatch.InstanceCount = 0; lastMesh = meshInstance->MeshIndex; cullDistanceSq = Math::Square(m_pSection->GetDetailMesh(lastMesh)->DrawDistance); } // test distance float instanceDistanceSq = eyePosition.SquaredDistance(meshInstance->Position); if (instanceDistanceSq > cullDistanceSq) continue; // add it Y_memcpy(pCurrentBufferPtr, &meshInstance->TransformMatrix, sizeof(float3x4)); pCurrentBufferPtr += sizeof(float3x4); detailBatch.InstanceCount++; } // last batch if (detailBatch.InstanceCount > 0) m_detailBatches.Add(detailBatch); // unmap buffer pGPUContext->Unmapbuffer(m_pDetailInstanceBuffer, pBufferPtr); return (m_detailBatches.GetSize() > 0); #endif } void TerrainSectionRenderProxyCDLOD::SetupDetailBatchDraw(uint32 detailBatchIndex, uint32 meshLODIndex, uint32 meshBatchIndex, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { const DetailBatch &detailBatch = m_detailBatches[detailBatchIndex]; const TerrainSection::DetailMesh *pDetailMesh = m_pSection->GetDetailMesh(detailBatchIndex); const StaticMesh::LOD *pLOD = pDetailMesh->pStaticMesh->GetLOD(meshLODIndex); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); pCommandList->SetVertexBuffer(0, pLOD->GetVertexBuffers()->GetBuffer(0), pLOD->GetVertexBuffers()->GetBufferOffset(0), pLOD->GetVertexBuffers()->GetBufferStride(0)); pCommandList->SetVertexBuffer(1, m_pDetailInstanceBuffer, detailBatch.InstanceBufferOffset, sizeof(LocalVertexFactory::InstanceTransform)); pCommandList->SetIndexBuffer(pLOD->GetIndexBuffer(), pLOD->GetIndexFormat(), 0); } void TerrainSectionRenderProxyCDLOD::InvokeDetailBatchDraw(uint32 detailBatchIndex, uint32 meshLODIndex, uint32 meshBatchIndex, GPUCommandList *pCommandList) const { const DetailBatch &detailBatch = m_detailBatches[detailBatchIndex]; const TerrainSection::DetailMesh *pDetailMesh = m_pSection->GetDetailMesh(detailBatchIndex); const StaticMesh::Batch *pBatch = pDetailMesh->pStaticMesh->GetLOD(meshLODIndex)->GetBatch(meshBatchIndex); pCommandList->DrawIndexedInstanced(pBatch->StartIndex, pBatch->NumIndices, 0, detailBatch.InstanceCount); } <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUBuffer.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUBuffer.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "D3D11Renderer/D3D11GPUContext.h" Log_SetChannel(Renderer); D3D11GPUBuffer::D3D11GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, ID3D11Buffer *pD3DBuffer, ID3D11Buffer *pD3DStagingBuffer) : GPUBuffer(pBufferDesc), m_pD3DBuffer(pD3DBuffer), m_pD3DStagingBuffer(pD3DStagingBuffer), m_pMappedContext(NULL), m_pMappedPointer(NULL) { //static_cast<D3D11GPUDevice *>(g_pRenderer)->OnResourceCreated(this); } D3D11GPUBuffer::~D3D11GPUBuffer() { //static_cast<D3D11GPUDevice *>(g_pRenderer)->OnResourceReleased(this); DebugAssert(m_pMappedContext == NULL); SAFE_RELEASE(m_pD3DBuffer); } void D3D11GPUBuffer::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this) + sizeof(ID3D11Buffer); if (gpuMemoryUsage != nullptr) *gpuMemoryUsage = m_desc.Size; } void D3D11GPUBuffer::SetDebugName(const char *debugName) { D3D11Helpers::SetD3D11DeviceChildDebugName(m_pD3DBuffer, debugName); } GPUBuffer *D3D11GPUDevice::CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData /* = NULL */) { D3D11_BUFFER_DESC D3DBufferDesc; D3DBufferDesc.ByteWidth = pDesc->Size; D3DBufferDesc.BindFlags = 0; D3DBufferDesc.MiscFlags = 0; D3DBufferDesc.StructureByteStride = 0; if (pDesc->Flags & GPU_BUFFER_FLAG_MAPPABLE) { D3DBufferDesc.Usage = D3D11_USAGE_DYNAMIC; D3DBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } else if (pDesc->Flags & (GPU_BUFFER_FLAG_READABLE | GPU_BUFFER_FLAG_WRITABLE)) { D3DBufferDesc.Usage = D3D11_USAGE_DEFAULT; D3DBufferDesc.CPUAccessFlags = 0; } else { DebugAssert(pInitialData != NULL); D3DBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; D3DBufferDesc.CPUAccessFlags = 0; } if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER) D3DBufferDesc.BindFlags |= D3D11_BIND_VERTEX_BUFFER; if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_INDEX_BUFFER) D3DBufferDesc.BindFlags |= D3D11_BIND_INDEX_BUFFER; if (pDesc->Flags & GPU_BUFFER_FLAG_BIND_CONSTANT_BUFFER) D3DBufferDesc.BindFlags |= D3D11_BIND_CONSTANT_BUFFER; D3D11_SUBRESOURCE_DATA subResourceData; subResourceData.SysMemPitch = 0; subResourceData.SysMemSlicePitch = 0; subResourceData.pSysMem = pInitialData; HRESULT hResult; // create buffer ID3D11Buffer *pBuffer; hResult = m_pD3DDevice->CreateBuffer(&D3DBufferDesc, (pInitialData != NULL) ? &subResourceData : NULL, &pBuffer); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUDevice::CreateBuffer: Could not create buffer (%u bytes): %08X", pDesc->Size, hResult); return NULL; } // create staging buffer if needed ID3D11Buffer *pStagingBuffer; if (pDesc->Flags & GPU_BUFFER_FLAG_READABLE) { D3D11_BUFFER_DESC D3DStagingBufferDesc; D3DBufferDesc.ByteWidth = pDesc->Size; D3DBufferDesc.Usage = D3D11_USAGE_STAGING; D3DBufferDesc.BindFlags = 0; D3DBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;// | D3D11_CPU_ACCESS_WRITE; D3DBufferDesc.MiscFlags = 0; D3DBufferDesc.StructureByteStride = 0; hResult = m_pD3DDevice->CreateBuffer(&D3DStagingBufferDesc, NULL, &pStagingBuffer); if (FAILED(hResult)) { pBuffer->Release(); Log_ErrorPrintf("D3D11GPUDevice::CreateBuffer: Could not create staging buffer (%u bytes): %08X", pDesc->Size, hResult); return NULL; } } else { pStagingBuffer = NULL; } return new D3D11GPUBuffer(pDesc, pBuffer, pStagingBuffer); } bool D3D11GPUContext::ReadBuffer(GPUBuffer *pBuffer, void *pDestination, uint32 start, uint32 count) { D3D11GPUBuffer *pD3D11Buffer = static_cast<D3D11GPUBuffer *>(pBuffer); DebugAssert((start + count) <= pD3D11Buffer->GetDesc()->Size); DebugAssert(pD3D11Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_READABLE); // Copy from the GPU buffer to the staging buffer bool fullCopy = (start == 0 && count == pBuffer->GetDesc()->Size); if (fullCopy) { // as there isn't multiple mip levels we can copy the whole resource m_pD3DContext->CopyResource(pD3D11Buffer->GetD3DStagingBuffer(), pD3D11Buffer->GetD3DBuffer()); } else { // calculate box D3D11_BOX box = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->CopySubresourceRegion(pD3D11Buffer->GetD3DStagingBuffer(), 0, 0, 0, 0, pD3D11Buffer->GetD3DBuffer(), 0, &box); } // map the staging buffer into memory D3D11_MAPPED_SUBRESOURCE mappedSubresource; HRESULT hResult = m_pD3DContext->Map(pD3D11Buffer->GetD3DStagingBuffer(), 0, D3D11_MAP_READ, 0, &mappedSubresource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::ReadBuffer: Map of staging buffer failed with hResult %08X", hResult); return false; } // copy into our memory Y_memcpy(pDestination, mappedSubresource.pData, count); m_pD3DContext->Unmap(pD3D11Buffer->GetD3DStagingBuffer(), 0); return true; } bool D3D11GPUContext::WriteBuffer(GPUBuffer *pBuffer, const void *pSource, uint32 start, uint32 count) { D3D11GPUBuffer *pD3D11Buffer = static_cast<D3D11GPUBuffer *>(pBuffer); DebugAssert(pD3D11Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_WRITABLE); DebugAssert((start + count) <= pD3D11Buffer->GetDesc()->Size); bool fullCopy = (start == 0 && count == pBuffer->GetDesc()->Size); if (pD3D11Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE) { // Have to use map D3D11_MAPPED_SUBRESOURCE mappedSubresource; HRESULT hResult = m_pD3DContext->Map(pD3D11Buffer->GetD3DBuffer(), 0, (fullCopy) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE, 0, &mappedSubresource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::WriteBuffer: Map failed with HResult %08X", hResult); return false; } // write and unmap Y_memcpy(reinterpret_cast<byte *>(mappedSubresource.pData) + start, pSource, count); m_pD3DContext->Unmap(pD3D11Buffer->GetD3DBuffer(), 0); } else { // Use UpdateSubresource if (fullCopy) { // whole buffer m_pD3DContext->UpdateSubresource(pD3D11Buffer->GetD3DBuffer(), 0, NULL, pSource, 0, 0); } else { // partial buffer, use box D3D11_BOX box = { start, 0, 0, start + count, 1, 1 }; m_pD3DContext->UpdateSubresource(pD3D11Buffer->GetD3DBuffer(), 0, &box, pSource, 0, 0); } } return true; } bool D3D11GPUContext::MapBuffer(GPUBuffer *pBuffer, GPU_MAP_TYPE mapType, void **ppPointer) { D3D11GPUBuffer *pD3D11Buffer = static_cast<D3D11GPUBuffer *>(pBuffer); DebugAssert(pD3D11Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pD3D11Buffer->GetMappedContext() == NULL && pD3D11Buffer->GetMappedPointer() == NULL); D3D11_MAPPED_SUBRESOURCE mappedSubresource; HRESULT hResult = m_pD3DContext->Map(pD3D11Buffer->GetD3DBuffer(), 0, D3D11TypeConversion::MapTypetoD3D11MapType(mapType), 0, &mappedSubresource); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUContext::MapBuffer: Failed with HResult %08X", hResult); return false; } pD3D11Buffer->SetMappedContextPointer(this, mappedSubresource.pData); *ppPointer = mappedSubresource.pData; return true; } void D3D11GPUContext::Unmapbuffer(GPUBuffer *pBuffer, void *pPointer) { D3D11GPUBuffer *pD3D11Buffer = static_cast<D3D11GPUBuffer *>(pBuffer); DebugAssert(pD3D11Buffer->GetDesc()->Flags & GPU_BUFFER_FLAG_MAPPABLE); DebugAssert(pD3D11Buffer->GetMappedContext() == this && pD3D11Buffer->GetMappedPointer() == pPointer); m_pD3DContext->Unmap(pD3D11Buffer->GetD3DBuffer(), 0); pD3D11Buffer->SetMappedContextPointer(NULL, NULL); } <file_sep>/Engine/Source/ResourceCompiler/ShaderCompilerOpenGL.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ShaderCompilerOpenGL.h" #include "ResourceCompiler/ResourceCompiler.h" #include "OpenGLRenderer/OpenGLShaderCacheEntry.h" #include "OpenGLRenderer/OpenGLDefines.h" Log_SetChannel(ShaderCompilerOpenGL); static const HLSLTRANSLATOR_SHADER_STAGE s_shaderStageToTranslatorStage[SHADER_PROGRAM_STAGE_COUNT] = { HLSLTRANSLATOR_SHADER_STAGE_VERTEX, // SHADER_PROGRAM_STAGE_VERTEX_SHADER NUM_HLSLTRANSLATOR_SHADER_STAGES, // SHADER_PROGRAM_STAGE_HULL_SHADER NUM_HLSLTRANSLATOR_SHADER_STAGES, // SHADER_PROGRAM_STAGE_DOMAIN_SHADER HLSLTRANSLATOR_SHADER_STAGE_GEOMETRY, // SHADER_PROGRAM_STAGE_GEOMETRY_SHADER HLSLTRANSLATOR_SHADER_STAGE_PIXEL, // SHADER_PROGRAM_STAGE_PIXEL_SHADER NUM_HLSLTRANSLATOR_SHADER_STAGES, // SHADER_PROGRAM_STAGE_COMPUTE_SHADER }; ShaderCompilerOpenGL::ShaderCompilerOpenGL(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters) : ShaderCompiler(pCallbacks, pParameters) { Y_memzero(m_pOutputGLSL, sizeof(m_pOutputGLSL)); } ShaderCompilerOpenGL::~ShaderCompilerOpenGL() { for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_pOutputGLSL[i] != NULL) HLSLTranslator_FreeMemory(m_pOutputGLSL[i]); } } void ShaderCompilerOpenGL::AddDefinesForStage(SHADER_PROGRAM_STAGE stage, MemArray<HLSLTRANSLATOR_MACRO> &macroArray) { // stage-specific defines switch (stage) { case SHADER_PROGRAM_STAGE_VERTEX_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("VERTEX_SHADER", "1")); break; case SHADER_PROGRAM_STAGE_HULL_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("HULL_SHADER", "1")); break; case SHADER_PROGRAM_STAGE_DOMAIN_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("DOMAIN_SHADER", "1")); break; case SHADER_PROGRAM_STAGE_GEOMETRY_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("GEOMETRY_SHADER", "1")); break; case SHADER_PROGRAM_STAGE_PIXEL_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("PIXEL_SHADER", "1")); break; case SHADER_PROGRAM_STAGE_COMPUTE_SHADER: macroArray.Add(HLSLTRANSLATOR_MACRO("COMPUTE_SHADER", "1")); break; } // add defines to preprocessor for (uint32 i = 0; i < m_CompileMacros.GetSize(); i++) macroArray.Add(HLSLTRANSLATOR_MACRO(m_CompileMacros[i].Key, m_CompileMacros[i].Value)); } static bool IncludeOpenCallback(void *memoryContext, const char *includeFileName, bool systemInclude, char **outBuffer, unsigned int *outLength, void *context) { ShaderCompilerOpenGL *pCompiler = reinterpret_cast<ShaderCompilerOpenGL *>(context); DebugAssert(pCompiler != nullptr); void *pCodePointer; uint32 codeSize; if (!pCompiler->ReadIncludeFile(systemInclude, includeFileName, &pCodePointer, &codeSize)) return false; *outBuffer = reinterpret_cast<char *>(pCodePointer); *outLength = (size_t)codeSize; return true; } static void IncludeCloseCallback(void *memoryContext, char *buffer, void *context) { ShaderCompilerOpenGL *pCompiler = reinterpret_cast<ShaderCompilerOpenGL *>(context); DebugAssert(pCompiler != nullptr); pCompiler->FreeIncludeFile(reinterpret_cast<void *>(buffer)); } bool ShaderCompilerOpenGL::CompileShaderStage(SHADER_PROGRAM_STAGE stage, uint32 outputGLSLVersion, bool outputGLSLES) { Timer timer; // get source filename DebugAssert(s_shaderStageToTranslatorStage[stage] != NUM_HLSLTRANSLATOR_SHADER_STAGES); if (m_StageFileNames[stage].IsEmpty() || m_StageEntryPoints[stage].IsEmpty()) return false; // open the source file AutoReleasePtr<BinaryBlob> pSourceBlob = m_pResourceCompilerCallbacks->GetFileContents(m_StageFileNames[stage]); if (pSourceBlob == nullptr) { Log_ErrorPrintf("ShaderCompilerD3D11::CompileShaderStage: Could not open shader source file '%s'.", m_StageFileNames[stage].GetCharArray()); return false; } // get define list MemArray<HLSLTRANSLATOR_MACRO> macroArray; AddDefinesForStage(stage, macroArray); // preprocess the shader if (m_pDumpWriter != nullptr) { HLSLTRANSLATOR_OUTPUT *pPreprocessorOutput; if (!HLSLTranslator_PreprocessHLSL(m_StageFileNames[stage], reinterpret_cast<const char *>(pSourceBlob->GetDataPointer()), pSourceBlob->GetDataSize(), IncludeOpenCallback, IncludeCloseCallback, this, macroArray.GetBasePointer(), macroArray.GetSize(), &pPreprocessorOutput)) { Log_ErrorPrintf("Failed to preprocess source file \"%s\" for stage %s.", m_StageFileNames[stage].GetCharArray(), NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); m_pDumpWriter->WriteFormattedLine("Failed to preprocess source file \"%s\" for stage %s.", m_StageFileNames[stage].GetCharArray(), NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); if (pPreprocessorOutput->InfoLogLength > 0) { Log_ErrorPrint(pPreprocessorOutput->InfoLog); m_pDumpWriter->Write(pPreprocessorOutput->InfoLog, pPreprocessorOutput->InfoLogLength); } HLSLTranslator_FreeMemory(pPreprocessorOutput); return false; } m_pDumpWriter->WriteFormattedLine("Preprocessed HLSL for %s:", NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); m_pDumpWriter->WriteLine("====================================================================="); m_pDumpWriter->WriteWithLineNumbers(pPreprocessorOutput->OutputSource, pPreprocessorOutput->OutputSourceLength); m_pDumpWriter->WriteLine("====================================================================="); m_pDumpWriter->WriteLine(""); HLSLTranslator_FreeMemory(pPreprocessorOutput); } // generate compile flags uint32 compileFlags = HLSLTRANSLATOR_COMPILE_FLAG_GENERATE_REFLECTION; if (!(m_iShaderCompilerFlags & SHADER_COMPILER_FLAG_DISABLE_OPTIMIZATIONS)) compileFlags |= HLSLTRANSLATOR_COMPILE_FLAG_OPTIMIZATION_LEVEL_3 | HLSLTRANSLATOR_COMPILE_FLAG_OPTIMIZATION_LEVEL_2 | HLSLTRANSLATOR_COMPILE_FLAG_OPTIMIZATION_LEVEL_1; // translate code HLSLTRANSLATOR_GLSL_OUTPUT *pTranslatedGLSL; if (!HLSLTranslator_ConvertHLSLToGLSL(m_StageFileNames[stage], reinterpret_cast<const char *>(pSourceBlob->GetDataPointer()), pSourceBlob->GetDataSize(), IncludeOpenCallback, IncludeCloseCallback, this, m_StageEntryPoints[stage], s_shaderStageToTranslatorStage[stage], compileFlags, outputGLSLVersion, outputGLSLES, macroArray.GetBasePointer(), macroArray.GetSize(), &pTranslatedGLSL)) { Log_ErrorPrintf("Failed to translate source file \"%s\" for stage %s.", m_StageFileNames[stage].GetCharArray(), NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); if (m_pDumpWriter != nullptr) m_pDumpWriter->WriteFormattedLine("Failed to translate source file \"%s\" for stage %s.", m_StageFileNames[stage].GetCharArray(), NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); if (pTranslatedGLSL->InfoLogLength > 0) { Log_ErrorPrint(pTranslatedGLSL->InfoLog); if (m_pDumpWriter != nullptr) m_pDumpWriter->Write(pTranslatedGLSL->InfoLog, pTranslatedGLSL->InfoLogLength); } HLSLTranslator_FreeMemory(pTranslatedGLSL); return false; } Log_DevPrintf(" Translating HLSL->GLSL[%s] took %.3f msec", NameTable_GetNameString(NameTables::ShaderProgramStage, stage), timer.GetTimeMilliseconds()); timer.Reset(); // write translated code if (m_pDumpWriter != nullptr) { m_pDumpWriter->WriteFormattedLine("Translated GLSL for %s:", NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); m_pDumpWriter->WriteLine("====================================================================="); m_pDumpWriter->WriteWithLineNumbers(pTranslatedGLSL->OutputSource, pTranslatedGLSL->OutputSourceLength); m_pDumpWriter->WriteLine("====================================================================="); m_pDumpWriter->WriteLine(""); m_pDumpWriter->WriteFormattedLine("Reflection for %s:", NameTable_GetNameString(NameTables::ShaderProgramStage, stage)); m_pDumpWriter->WriteLine("====================================================================="); { const HLSLTRANSLATOR_GLSL_SHADER_REFLECTION *pReflection = pTranslatedGLSL->Reflection; m_pDumpWriter->WriteFormattedLine("Inputs (%u): ", pReflection->InputCount); for (uint32 i = 0; i < pReflection->InputCount; i++) { const HLSLTRANSLATOR_GLSL_SHADER_INPUT *pInput = &pReflection->Inputs[i]; m_pDumpWriter->WriteFormattedLine(" %u: name:'%s', semanticname:'%s', semanticindex:%u, type:0x%X, location:%d", i, pInput->VariableName, (pInput->SemanticName != nullptr) ? pInput->SemanticName : "", pInput->SemanticIndex, pInput->Type, pInput->ExplicitLocation); } m_pDumpWriter->WriteLine(""); m_pDumpWriter->WriteFormattedLine("Outputs (%u): ", pReflection->OutputCount); for (uint32 i = 0; i < pReflection->OutputCount; i++) { const HLSLTRANSLATOR_GLSL_SHADER_OUTPUT *pOutput = &pReflection->Outputs[i]; m_pDumpWriter->WriteFormattedLine(" %u: name:'%s', semanticname:'%s', semanticindex:%u, type:0x%X, location:%d", i, pOutput->VariableName, (pOutput->SemanticName != nullptr) ? pOutput->SemanticName : "", pOutput->SemanticIndex, pOutput->Type, pOutput->ExplicitLocation); } m_pDumpWriter->WriteLine(""); m_pDumpWriter->WriteFormattedLine("Uniform Blocks (%u): ", pReflection->UniformBlockCount); for (uint32 i = 0; i < pReflection->UniformBlockCount; i++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM_BLOCK *pBlock = &pReflection->UniformBlocks[i]; m_pDumpWriter->WriteFormattedLine(" %u: blockname:'%s', instancename:'%s', size:%u, location:%d, fields: %u:", i, pBlock->BlockName, (pBlock->InstanceName != nullptr) ? pBlock->InstanceName : "", pBlock->TotalSize, pBlock->ExplicitLocation, pBlock->FieldCount); for (uint32 j = 0; j < pBlock->FieldCount; j++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM_BLOCK_FIELD *pField = &pBlock->Fields[j]; m_pDumpWriter->WriteFormattedLine(" %u: name:'%s', type:0x%X, arraysize:%d, offset:%u, size:%u, stride:%u, rowmajor:%u", j, pField->VariableName, pField->Type, pField->ArraySize, pField->OffsetInBuffer, pField->SizeInBytes, pField->ArrayStride, (uint32)pField->RowMajor); } } m_pDumpWriter->WriteLine(""); m_pDumpWriter->WriteFormattedLine("Uniforms (%u): ", pReflection->UniformCount); for (uint32 i = 0; i < pReflection->UniformCount; i++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM *pField = &pReflection->Uniforms[i]; m_pDumpWriter->WriteFormattedLine(" %u: name:'%s', samplername:'%s', type:0x%X, arraysize:%d, location:%d", i, pField->VariableName, (pField->SamplerVariableName != nullptr) ? pField->SamplerVariableName : "", pField->Type, pField->ArraySize, pField->ExplicitLocation); } m_pDumpWriter->WriteLine(""); } m_pDumpWriter->WriteLine("====================================================================="); } m_pOutputGLSL[stage] = pTranslatedGLSL; return true; } static bool MapOpenGLUniformTypeToShaderParameterType(GLenum glType, SHADER_PARAMETER_TYPE *pParameterType, OPENGL_SHADER_BIND_TARGET *pBindTarget) { struct Mapping { GLenum GLType; SHADER_PARAMETER_TYPE ShaderParameterType; OPENGL_SHADER_BIND_TARGET BindTarget; }; static const Mapping mapping[] = { // GLType ShaderParameterType { GL_FLOAT, SHADER_PARAMETER_TYPE_FLOAT, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_VEC2, SHADER_PARAMETER_TYPE_FLOAT2, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_VEC3, SHADER_PARAMETER_TYPE_FLOAT3, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_VEC4, SHADER_PARAMETER_TYPE_FLOAT4, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_INT, SHADER_PARAMETER_TYPE_INT, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_INT_VEC2, SHADER_PARAMETER_TYPE_INT2, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_INT_VEC3, SHADER_PARAMETER_TYPE_INT3, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_INT_VEC4, SHADER_PARAMETER_TYPE_INT4, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_UNSIGNED_INT, SHADER_PARAMETER_TYPE_UINT, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_UNSIGNED_INT_VEC2, SHADER_PARAMETER_TYPE_UINT2, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_UNSIGNED_INT_VEC3, SHADER_PARAMETER_TYPE_UINT3, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_UNSIGNED_INT_VEC4, SHADER_PARAMETER_TYPE_UINT4, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_BOOL, SHADER_PARAMETER_TYPE_BOOL, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_MAT2, SHADER_PARAMETER_TYPE_FLOAT2X2, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_MAT3, SHADER_PARAMETER_TYPE_FLOAT3X3, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_FLOAT_MAT4x3, SHADER_PARAMETER_TYPE_FLOAT3X4, OPENGL_SHADER_BIND_TARGET_UNIFORM }, // <-- because matrices are transposed as they go into gl, float3x4 becomes float4x3 { GL_FLOAT_MAT4, SHADER_PARAMETER_TYPE_FLOAT4X4, OPENGL_SHADER_BIND_TARGET_UNIFORM }, { GL_SAMPLER_1D, SHADER_PARAMETER_TYPE_TEXTURE1D, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_1D_ARRAY, SHADER_PARAMETER_TYPE_TEXTURE1DARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D, SHADER_PARAMETER_TYPE_TEXTURE2D, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D_ARRAY, SHADER_PARAMETER_TYPE_TEXTURE2DARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D_MULTISAMPLE, SHADER_PARAMETER_TYPE_TEXTURE2DMS, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D_MULTISAMPLE_ARRAY, SHADER_PARAMETER_TYPE_TEXTURE2DMSARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_3D, SHADER_PARAMETER_TYPE_TEXTURE3D, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_CUBE, SHADER_PARAMETER_TYPE_TEXTURECUBE, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_CUBE_MAP_ARRAY, SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_BUFFER, SHADER_PARAMETER_TYPE_TEXTUREBUFFER, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_1D_SHADOW, SHADER_PARAMETER_TYPE_TEXTURE1D, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_1D_ARRAY_SHADOW, SHADER_PARAMETER_TYPE_TEXTURE1DARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D_SHADOW, SHADER_PARAMETER_TYPE_TEXTURE2D, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_2D_ARRAY_SHADOW, SHADER_PARAMETER_TYPE_TEXTURE2DARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_CUBE_SHADOW, SHADER_PARAMETER_TYPE_TEXTURECUBE, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, { GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW, SHADER_PARAMETER_TYPE_TEXTURECUBEARRAY, OPENGL_SHADER_BIND_TARGET_TEXTURE_UNIT }, }; for (uint32 i = 0; i < countof(mapping); i++) { if (mapping[i].GLType == glType) { *pParameterType = mapping[i].ShaderParameterType; *pBindTarget = mapping[i].BindTarget; return true; } } return false; } bool ShaderCompilerOpenGL::ReflectShaderStage(SHADER_PROGRAM_STAGE stage) { const HLSLTRANSLATOR_GLSL_OUTPUT *pOutput = m_pOutputGLSL[stage]; const HLSLTRANSLATOR_GLSL_SHADER_REFLECTION *pReflection = pOutput->Reflection; DebugAssert(pReflection != nullptr); if (stage == SHADER_PROGRAM_STAGE_VERTEX_SHADER) { // pull in vertex attributes and map the glsl names to attribute locations for (uint32 inInputIndex = 0; inInputIndex < pReflection->InputCount; inInputIndex++) { const HLSLTRANSLATOR_GLSL_SHADER_INPUT *programAttribute = &pReflection->Inputs[inInputIndex]; // parse the name. it should start with in_ const char *currentNamePtr = programAttribute->VariableName; if (Y_strnicmp(programAttribute->VariableName, "in_", 3) == 0) currentNamePtr += 3; else if (Y_strnicmp(programAttribute->VariableName, "attribute_", 10) == 0) currentNamePtr += 10; else { Log_ErrorPrintf("OpenGLShaderCompiler::ReflectShaderStage: Invalid attribute variable name: %s", programAttribute->VariableName); return false; } // figure out which semantic it maps to uint32 semantic; for (semantic = 0; semantic < GPU_VERTEX_ELEMENT_SEMANTIC_COUNT; semantic++) { const char *semanticNameString = NameTable_GetNameString(NameTables::GPUVertexElementSemantic, semantic); uint32 semanticNameLength = Y_strlen(semanticNameString); if (Y_strncmp(currentNamePtr, semanticNameString, semanticNameLength) == 0) { // match, so strip the name out currentNamePtr += semanticNameLength; break; } } // found match? if (semantic == GPU_VERTEX_ELEMENT_SEMANTIC_COUNT) { Log_ErrorPrintf("OpenGLShaderCompiler::ReflectShaderStage: Invalid attribute semantic: %s", currentNamePtr); return false; } // find the semantic index, if it is the end-of-string, assume zero uint32 semanticIndex = 0; if (*currentNamePtr != '\0') semanticIndex = StringConverter::StringToUInt32(currentNamePtr); // temp Log_DevPrintf("attrib '%s' -> semantic %s index %u", programAttribute->VariableName, NameTable_GetNameString(NameTables::GPUVertexElementSemantic, semantic), semanticIndex); // add an entry OpenGLShaderCacheEntryVertexAttribute outAttrib; outAttrib.NameLength = Y_strlen(programAttribute->VariableName); outAttrib.SemanticName = semantic; outAttrib.SemanticIndex = semanticIndex; m_vertexAttributes.Add(outAttrib); m_vertexAttributeNames.Add(programAttribute->VariableName); } } // map uniform buffers on GL3+ if (m_eRendererFeatureLevel > RENDERER_FEATURE_LEVEL_ES2) { for (uint32 inUniformBufferIndex = 0; inUniformBufferIndex < pReflection->UniformBlockCount; inUniformBufferIndex++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM_BLOCK *programUniformBlock = &pReflection->UniformBlocks[inUniformBufferIndex]; // TODO: Check uniform block signatures match uint32 constantBufferIndex; for (constantBufferIndex = 0; constantBufferIndex < m_uniformBlocks.GetSize(); constantBufferIndex++) { if (m_uniformBlockNames[constantBufferIndex].Compare(programUniformBlock->BlockName)) break; } if (constantBufferIndex != m_uniformBlocks.GetSize()) continue; // Determine if the buffer should be allocated locally bool isLocal = (Y_strncmp(programUniformBlock->BlockName, "__LocalConstantBuffer_", 22) == 0); uint32 parameterIndex = m_parameters.GetSize(); // Allocate a parameter for this buffer OpenGLShaderCacheEntryParameter outParameter; outParameter.NameLength = Y_strlen(programUniformBlock->BlockName); outParameter.SamplerNameLength = 0; outParameter.Type = SHADER_PARAMETER_TYPE_CONSTANT_BUFFER; outParameter.UniformBlockIndex = -1; outParameter.UniformBlockOffset = 0; outParameter.ArraySize = 0; outParameter.ArrayStride = 0; outParameter.BindTarget = OPENGL_SHADER_BIND_TARGET_UNIFORM_BUFFER; m_parameters.Add(outParameter); m_parameterNames.Add(programUniformBlock->BlockName); m_parameterSamplerNames.Add(EmptyString); // Allocate a constant buffer entry OpenGLShaderCacheEntryUniformBlock outUniformBuffer; outUniformBuffer.NameLength = Y_strlen(programUniformBlock->BlockName); outUniformBuffer.Size = programUniformBlock->TotalSize; outUniformBuffer.ParameterIndex = parameterIndex; outUniformBuffer.IsLocal = isLocal; m_uniformBlocks.Add(outUniformBuffer); m_uniformBlockNames.Add(programUniformBlock->BlockName); // If it is a local buffer, allocate parameters for each of its fields if (isLocal) { for (uint32 fieldIndex = 0; fieldIndex < programUniformBlock->FieldCount; fieldIndex++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM_BLOCK_FIELD *programField = &programUniformBlock->Fields[fieldIndex]; // convert to a parameter type SHADER_PARAMETER_TYPE parameterType; OPENGL_SHADER_BIND_TARGET bindTarget; if (!MapOpenGLUniformTypeToShaderParameterType(programField->Type, &parameterType, &bindTarget)) { Log_ErrorPrintf("OpenGLShaderCompiler::ReflectProgram: Failed to map GL type %u (%s uniform block %s) to a parameter type.", programField->Type, programField->VariableName, programUniformBlock->BlockName); return false; } // create parameter OpenGLShaderCacheEntryParameter fieldParameter; fieldParameter.NameLength = Y_strlen(programField->VariableName); fieldParameter.Type = parameterType; fieldParameter.UniformBlockIndex = constantBufferIndex; fieldParameter.UniformBlockOffset = programField->OffsetInBuffer; fieldParameter.ArraySize = (programField->ArraySize < 0) ? 0 : (uint32)programField->ArraySize; fieldParameter.ArrayStride = programField->ArrayStride; #if 0 // follow alignment rules and align the field to the next vec4 uint32 valueSize = ShaderParameterValueTypeSize(parameterType); uint32 valueSizeRemainder = (valueSize % 16); if (valueSizeRemainder != 0) fieldParameter.ArrayStride = valueSize + (16 - valueSizeRemainder); else fieldParameter.ArrayStride = valueSize; #endif // should be binding to uniform only DebugAssert(bindTarget == OPENGL_SHADER_BIND_TARGET_UNIFORM); // remaining fields fieldParameter.BindTarget = OPENGL_SHADER_BIND_TARGET_COUNT; m_parameters.Add(outParameter); m_parameterNames.Add(programField->VariableName); m_parameterSamplerNames.Add(EmptyString); } } } } // map uniforms across for (uint32 inUniformIndex = 0; inUniformIndex < pReflection->UniformCount; inUniformIndex++) { const HLSLTRANSLATOR_GLSL_SHADER_UNIFORM *programUniform = &pReflection->Uniforms[inUniformIndex]; // check for already existing // @TODO ensure types etc match uint32 parameterIndex; for (parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { if (m_parameterNames[parameterIndex].Compare(programUniform->VariableName)) break; } if (parameterIndex != m_parameters.GetSize()) continue; // convert to a parameter type SHADER_PARAMETER_TYPE parameterType; OPENGL_SHADER_BIND_TARGET bindTarget; if (!MapOpenGLUniformTypeToShaderParameterType(programUniform->Type, &parameterType, &bindTarget)) { Log_ErrorPrintf("OpenGLShaderCompiler::ReflectProgram: Failed to map GL type %u (uniform %s) to a parameter type.", programUniform->Type, programUniform->VariableName); return false; } // create parameter OpenGLShaderCacheEntryParameter outParameter; outParameter.NameLength = Y_strlen(programUniform->VariableName); outParameter.SamplerNameLength = (programUniform->SamplerVariableName != nullptr) ? Y_strlen(programUniform->SamplerVariableName) : 0; outParameter.Type = parameterType; outParameter.UniformBlockIndex = -1; outParameter.UniformBlockOffset = 0; outParameter.ArraySize = (programUniform->ArraySize < 0) ? 0 : (uint32)programUniform->ArraySize; // follow alignment rules and align the field to the next vec4 uint32 valueSize = ShaderParameterValueTypeSize(parameterType); uint32 valueSizeRemainder = (valueSize % 16); if (valueSizeRemainder != 0) outParameter.ArrayStride = valueSize + (16 - valueSizeRemainder); else outParameter.ArrayStride = valueSize; // remaining fields outParameter.BindTarget = bindTarget; m_parameters.Add(outParameter); m_parameterNames.Add(programUniform->VariableName); if (programUniform->SamplerVariableName != nullptr) m_parameterSamplerNames.Add(programUniform->SamplerVariableName); else m_parameterSamplerNames.Add(EmptyString); } // map outputs if (stage == SHADER_PROGRAM_STAGE_PIXEL_SHADER && m_eRendererFeatureLevel > RENDERER_FEATURE_LEVEL_ES2) { for (uint32 inOutputIndex = 0; inOutputIndex < pReflection->OutputCount; inOutputIndex++) { const HLSLTRANSLATOR_GLSL_SHADER_OUTPUT *programOutput = &pReflection->Outputs[inOutputIndex]; // parse the name. it should start with out_COLOR const char *currentNamePtr = programOutput->VariableName; if (Y_strnicmp(programOutput->VariableName, "out_COLOR", 9) == 0) currentNamePtr += 9; else if (Y_strnicmp(programOutput->VariableName, "out_Target", 10) == 0) currentNamePtr += 10; else { Log_ErrorPrintf("OpenGLShaderCompiler::ReflectProgram: Invalid output variable name: %s", programOutput->VariableName); return false; } // find the semantic index, if it is the end-of-string, assume zero uint32 renderTargetIndex = 0; if (*currentNamePtr != '\0') renderTargetIndex = StringConverter::StringToUInt32(currentNamePtr); // temp Log_DevPrintf("output '%s' -> render target %u", programOutput->VariableName, renderTargetIndex); // add an entry OpenGLShaderCacheEntryFragmentData outFragData; outFragData.NameLength = Y_strlen(programOutput->VariableName); outFragData.RenderTargetIndex = renderTargetIndex; m_fragDatas.Add(outFragData); m_fragDataNames.Add(programOutput->VariableName); } } return true; } bool ShaderCompilerOpenGL::InternalCompile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) { Timer compileTimer, stageCompileTimer; float compileTimeCompile, compileTimeReflect; bool result = false; // Create code arrays. stageCompileTimer.Reset(); compileTimeCompile = 0.0f; compileTimeReflect = 0.0f; // glsl versions for feature levels static const uint32 featureLevelGLSLVersions[RENDERER_FEATURE_LEVEL_COUNT] = { 330, // RENDERER_FEATURE_LEVEL_ES2 330, // RENDERER_FEATURE_LEVEL_ES3 330, // RENDERER_FEATURE_LEVEL_SM4 330//450 // RENDERER_FEATURE_LEVEL_SM5 }; static const uint32 featureLevelGLSLVersionsES[RENDERER_FEATURE_LEVEL_COUNT] = { 100, // RENDERER_FEATURE_LEVEL_ES2 300, // RENDERER_FEATURE_LEVEL_ES3 300, // RENDERER_FEATURE_LEVEL_SM4 300//450 // RENDERER_FEATURE_LEVEL_SM5 }; // create compiler bool compileGLSLES = (m_eRendererPlatform == RENDERER_PLATFORM_OPENGLES2); uint32 compileGLSLVersion = (!compileGLSLES) ? featureLevelGLSLVersions[m_eRendererFeatureLevel] : featureLevelGLSLVersionsES[m_eRendererFeatureLevel]; // compile stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (m_StageEntryPoints[stageIndex].GetLength() > 0) { if (!CompileShaderStage((SHADER_PROGRAM_STAGE)stageIndex, compileGLSLVersion, compileGLSLES)) goto CLEANUP; float stageCompileTime = (float)stageCompileTimer.GetTimeMilliseconds(); Log_DevPrintf(" Compiled stage %s in %.3f msec", NameTable_GetNameString(NameTables::ShaderProgramStage, stageIndex), stageCompileTime); compileTimeCompile += stageCompileTime; stageCompileTimer.Reset(); } } // reflect stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (m_pOutputGLSL[stageIndex] != nullptr) { if (!ReflectShaderStage((SHADER_PROGRAM_STAGE)stageIndex)) goto CLEANUP; float stageReflectTime = (float)stageCompileTimer.GetTimeMilliseconds(); Log_DevPrintf(" Reflected stage %s in %.3f msec", NameTable_GetNameString(NameTables::ShaderProgramStage, stageIndex), stageReflectTime); compileTimeReflect += stageReflectTime; stageCompileTimer.Reset(); } } #if 1 // Dump out variables for (uint32 atttributeIndex = 0; atttributeIndex < m_vertexAttributes.GetSize(); atttributeIndex++) Log_DevPrintf("Shader Vertex Attribute [%u] : %s", atttributeIndex, m_vertexAttributeNames[atttributeIndex].GetCharArray()); for (uint32 constantBufferIndex = 0; constantBufferIndex < m_uniformBlocks.GetSize(); constantBufferIndex++) Log_DevPrintf("Shader Constant Buffer [%u] : %s, %u bytes, local: %s", constantBufferIndex, m_uniformBlockNames[constantBufferIndex].GetCharArray(), m_uniformBlocks[constantBufferIndex].Size, (m_uniformBlocks[constantBufferIndex].IsLocal) ? "yes" : "no"); for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) Log_DevPrintf("Shader Parameter [%u] : %s, type %s", parameterIndex, m_parameterNames[parameterIndex].GetCharArray(), NameTable_GetNameString(NameTables::ShaderParameterType, m_parameters[parameterIndex].Type)); for (uint32 fragDataIndex = 0; fragDataIndex < m_fragDatas.GetSize(); fragDataIndex++) Log_DevPrintf("Shader Fragment Output [%u] : %s, render target %u", fragDataIndex, m_fragDataNames[fragDataIndex].GetCharArray(), m_fragDatas[fragDataIndex].RenderTargetIndex); #endif // write output if (!WriteOutput(pByteCodeStream)) goto CLEANUP; // Compile succeded. result = true; Log_DevPrintf("Shader successfully compiled. Took %.3f msec (Compile: %.3f msec, Reflect: %.3f msec, Write: %.3f msec)", (float)compileTimer.GetTimeMilliseconds(), compileTimeCompile, compileTimeReflect, stageCompileTimer.GetTimeMilliseconds()); CLEANUP: // cleanup stages for (uint32 stageIndex = 0; stageIndex < SHADER_PROGRAM_STAGE_COUNT; stageIndex++) { if (m_pOutputGLSL[stageIndex] != nullptr) { HLSLTranslator_FreeMemory(m_pOutputGLSL[stageIndex]); m_pOutputGLSL[stageIndex] = nullptr; } } return result; } bool ShaderCompilerOpenGL::WriteOutput(ByteStream *pByteCodeStream) { // binary writer BinaryWriter binaryWriter(pByteCodeStream); // make debug name SmallString debugName; //debugName.Format("%s", m_p) // construct header OpenGLShaderCacheEntryHeader header; header.Signature = OPENGL_SHADER_CACHE_ENTRY_HEADER; header.Platform = m_eRendererPlatform; header.FeatureLevel = m_eRendererFeatureLevel; header.VertexAttributeCount = m_vertexAttributes.GetSize(); header.UniformBlockCount = m_uniformBlocks.GetSize(); header.ParameterCount = m_parameters.GetSize(); header.FragmentDataCount = m_fragDatas.GetSize(); header.DebugNameLength = debugName.GetLength(); for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) header.StageSize[i] = (m_pOutputGLSL[i] != nullptr) ? m_pOutputGLSL[i]->OutputSourceLength : 0; // write header binaryWriter.WriteBytes(&header, sizeof(header)); // write stage code for (uint32 i = 0; i < SHADER_PROGRAM_STAGE_COUNT; i++) { if (m_pOutputGLSL[i] != nullptr) binaryWriter.WriteBytes(m_pOutputGLSL[i]->OutputSource, m_pOutputGLSL[i]->OutputSourceLength); } // write attributes for (uint32 attributeIndex = 0; attributeIndex < m_vertexAttributes.GetSize(); attributeIndex++) { binaryWriter.WriteBytes(&m_vertexAttributes[attributeIndex], sizeof(OpenGLShaderCacheEntryVertexAttribute)); binaryWriter.WriteFixedString(m_vertexAttributeNames[attributeIndex], m_vertexAttributes[attributeIndex].NameLength); } // write uniform blocks for (uint32 uniformBlockIndex = 0; uniformBlockIndex < m_uniformBlocks.GetSize(); uniformBlockIndex++) { binaryWriter.WriteBytes(&m_uniformBlocks[uniformBlockIndex], sizeof(OpenGLShaderCacheEntryUniformBlock)); binaryWriter.WriteFixedString(m_uniformBlockNames[uniformBlockIndex], m_uniformBlocks[uniformBlockIndex].NameLength); } // write parameters for (uint32 parameterIndex = 0; parameterIndex < m_parameters.GetSize(); parameterIndex++) { binaryWriter.WriteBytes(&m_parameters[parameterIndex], sizeof(OpenGLShaderCacheEntryParameter)); binaryWriter.WriteFixedString(m_parameterNames[parameterIndex], m_parameters[parameterIndex].NameLength); if (m_parameters[parameterIndex].SamplerNameLength > 0) binaryWriter.WriteFixedString(m_parameterSamplerNames[parameterIndex], m_parameters[parameterIndex].SamplerNameLength); } // write outputs for (uint32 fragDataIndex = 0; fragDataIndex < m_fragDatas.GetSize(); fragDataIndex++) { binaryWriter.WriteBytes(&m_fragDatas[fragDataIndex], sizeof(OpenGLShaderCacheEntryFragmentData)); binaryWriter.WriteFixedString(m_fragDataNames[fragDataIndex], m_fragDatas[fragDataIndex].NameLength); } // write debug name if (header.DebugNameLength > 0) binaryWriter.WriteFixedString(debugName, header.DebugNameLength); // done Log_DevPrintf("OpenGLShaderCompiler::WriteOutput: %u attributes, %u constant buffers, %u parameters, %u outputs mapped, total size: %u bytes", m_vertexAttributes.GetSize(), m_uniformBlocks.GetSize(), m_parameters.GetSize(), m_fragDatas.GetSize(), (uint32)pByteCodeStream->GetSize()); return !binaryWriter.InErrorState(); } ShaderCompiler *ShaderCompiler::CreateOpenGLShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters) { return new ShaderCompilerOpenGL(pCallbacks, pParameters); } <file_sep>/Engine/Source/Engine/BlockMeshCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" class BlockMesh; class BlockMeshVolume; class BlockMeshCollisionShape : public Physics::CollisionShape { public: BlockMeshCollisionShape(const BlockMesh *pBlockMesh); virtual ~BlockMeshCollisionShape(); // Virtual methods virtual const Physics::COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual Physics::CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: const BlockMesh *m_pBlockMesh; const BlockMeshVolume *m_pBlockVolume; const BlockMeshCollisionShape *m_pOriginalShape; class btBlockMeshCollisionShape *m_pBulletShape; float3 m_scale; AABox m_boundingBox; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12Helpers.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12Helpers.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUTexture.h" #include "D3D12Renderer/D3D12GPUBuffer.h" Log_SetChannel(D3D12RenderBackend); static const DXGI_FORMAT s_PixelFormatToDXGIFormat[PIXEL_FORMAT_COUNT] = { DXGI_FORMAT_R8_UINT, // PIXEL_FORMAT_R8_UINT DXGI_FORMAT_R8_SINT, // PIXEL_FORMAT_R8_SINT DXGI_FORMAT_R8_UNORM, // PIXEL_FORMAT_R8_UNORM DXGI_FORMAT_R8_SNORM, // PIXEL_FORMAT_R8_SNORM DXGI_FORMAT_R8G8_UINT, // PIXEL_FORMAT_R8G8_UINT DXGI_FORMAT_R8G8_SINT, // PIXEL_FORMAT_R8G8_SINT DXGI_FORMAT_R8G8_UNORM, // PIXEL_FORMAT_R8G8_UNORM DXGI_FORMAT_R8G8_SNORM, // PIXEL_FORMAT_R8G8_SNORM DXGI_FORMAT_R8G8B8A8_UINT, // PIXEL_FORMAT_R8G8B8A8_UINT DXGI_FORMAT_R8G8B8A8_SINT, // PIXEL_FORMAT_R8G8B8A8_SINT DXGI_FORMAT_R8G8B8A8_UNORM, // PIXEL_FORMAT_R8G8B8A8_UNORM DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB DXGI_FORMAT_R8G8B8A8_SNORM, // PIXEL_FORMAT_R8G8B8A8_SNORM DXGI_FORMAT_R9G9B9E5_SHAREDEXP, // PIXEL_FORMAT_R9G9B9E5_SHAREDEXP DXGI_FORMAT_R10G10B10A2_UINT, // PIXEL_FORMAT_R10G10B10A2_UINT DXGI_FORMAT_R10G10B10A2_UNORM, // PIXEL_FORMAT_R10G10B10A2_UNORM DXGI_FORMAT_R11G11B10_FLOAT, // PIXEL_FORMAT_R11G11B10_FLOAT DXGI_FORMAT_R16_UINT, // PIXEL_FORMAT_R16_UINT DXGI_FORMAT_R16_SINT, // PIXEL_FORMAT_R16_SINT DXGI_FORMAT_R16_UNORM, // PIXEL_FORMAT_R16_UNORM DXGI_FORMAT_R16_SNORM, // PIXEL_FORMAT_R16_SNORM DXGI_FORMAT_R16_FLOAT, // PIXEL_FORMAT_R16_FLOAT DXGI_FORMAT_R16G16_UINT, // PIXEL_FORMAT_R16G16_UINT DXGI_FORMAT_R16G16_SINT, // PIXEL_FORMAT_R16G16_SINT DXGI_FORMAT_R16G16_UNORM, // PIXEL_FORMAT_R16G16_UNORM DXGI_FORMAT_R16G16_SNORM, // PIXEL_FORMAT_R16G16_SNORM DXGI_FORMAT_R16G16_FLOAT, // PIXEL_FORMAT_R16G16_FLOAT DXGI_FORMAT_R16G16B16A16_UINT, // PIXEL_FORMAT_R16G16B16A16_UINT DXGI_FORMAT_R16G16B16A16_SINT, // PIXEL_FORMAT_R16G16B16A16_SINT DXGI_FORMAT_R16G16B16A16_UNORM, // PIXEL_FORMAT_R16G16B16A16_UNORM DXGI_FORMAT_R16G16B16A16_SNORM, // PIXEL_FORMAT_R16G16B16A16_SNORM DXGI_FORMAT_R16G16B16A16_FLOAT, // PIXEL_FORMAT_R16G16B16A16_FLOAT DXGI_FORMAT_R32_UINT, // PIXEL_FORMAT_R32_UINT DXGI_FORMAT_R32_SINT, // PIXEL_FORMAT_R32_SINT DXGI_FORMAT_R32_FLOAT, // PIXEL_FORMAT_R32_FLOAT DXGI_FORMAT_R32G32_UINT, // PIXEL_FORMAT_R32G32_UINT DXGI_FORMAT_R32G32_SINT, // PIXEL_FORMAT_R32G32_SINT DXGI_FORMAT_R32G32_FLOAT, // PIXEL_FORMAT_R32G32_FLOAT DXGI_FORMAT_R32G32B32_UINT, // PIXEL_FORMAT_R32G32B32_UINT DXGI_FORMAT_R32G32B32_SINT, // PIXEL_FORMAT_R32G32B32_SINT DXGI_FORMAT_R32G32B32_FLOAT, // PIXEL_FORMAT_R32G32B32_FLOAT DXGI_FORMAT_R32G32B32A32_UINT, // PIXEL_FORMAT_R32G32B32A32_UINT DXGI_FORMAT_R32G32B32A32_SINT, // PIXEL_FORMAT_R32G32B32A32_SINT DXGI_FORMAT_R32G32B32A32_FLOAT, // PIXEL_FORMAT_R32G32B32A32_FLOAT DXGI_FORMAT_B8G8R8A8_UNORM, // PIXEL_FORMAT_B8G8R8A8_UNORM DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, // PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB DXGI_FORMAT_B8G8R8X8_UNORM, // PIXEL_FORMAT_B8G8R8X8_UNORM DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, // PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB DXGI_FORMAT_B5G6R5_UNORM, // PIXEL_FORMAT_B5G6R5_UNORM DXGI_FORMAT_B5G5R5A1_UNORM, // PIXEL_FORMAT_B5G5R5A1_UNORM DXGI_FORMAT_BC1_UNORM, // PIXEL_FORMAT_BC1_UNORM DXGI_FORMAT_BC1_UNORM_SRGB, // PIXEL_FORMAT_BC1_UNORM_SRGB DXGI_FORMAT_BC2_UNORM, // PIXEL_FORMAT_BC2_UNORM DXGI_FORMAT_BC2_UNORM_SRGB, // PIXEL_FORMAT_BC2_UNORM_SRGB DXGI_FORMAT_BC3_UNORM, // PIXEL_FORMAT_BC3_UNORM DXGI_FORMAT_BC3_UNORM_SRGB, // PIXEL_FORMAT_BC3_UNORM_SRGB DXGI_FORMAT_BC4_UNORM, // PIXEL_FORMAT_BC4_UNORM DXGI_FORMAT_BC4_SNORM, // PIXEL_FORMAT_BC4_SNORM DXGI_FORMAT_BC5_UNORM, // PIXEL_FORMAT_BC5_UNORM DXGI_FORMAT_BC5_SNORM, // PIXEL_FORMAT_BC5_SNORM DXGI_FORMAT_BC6H_UF16, // PIXEL_FORMAT_BC6H_UF16 DXGI_FORMAT_BC6H_SF16, // PIXEL_FORMAT_BC6H_SF16 DXGI_FORMAT_BC7_UNORM, // PIXEL_FORMAT_BC7_UNORM DXGI_FORMAT_BC7_UNORM_SRGB, // PIXEL_FORMAT_BC7_UNORM_SRGB DXGI_FORMAT_D16_UNORM, // PIXEL_FORMAT_D16_UNORM DXGI_FORMAT_D24_UNORM_S8_UINT, // PIXEL_FORMAT_D24_UNORM_S8_UINT DXGI_FORMAT_D32_FLOAT, // PIXEL_FORMAT_D32_FLOAT DXGI_FORMAT_D32_FLOAT_S8X24_UINT, // PIXEL_FORMAT_D32_FLOAT_S8X24_UINT DXGI_FORMAT_UNKNOWN, // PIXEL_FORMAT_R8G8B8_UNORM DXGI_FORMAT_UNKNOWN, // PIXEL_FORMAT_B8G8R8_UNORM }; static const D3D12_COMPARISON_FUNC s_D3D12ComparisonFuncs[GPU_COMPARISON_FUNC_COUNT] = { D3D12_COMPARISON_FUNC_NEVER, // RENDERER_COMPARISON_FUNC_NEVER D3D12_COMPARISON_FUNC_LESS, // RENDERER_COMPARISON_FUNC_LESS D3D12_COMPARISON_FUNC_EQUAL, // RENDERER_COMPARISON_FUNC_EQUAL D3D12_COMPARISON_FUNC_LESS_EQUAL, // RENDERER_COMPARISON_FUNC_LESS_EQUAL D3D12_COMPARISON_FUNC_GREATER, // RENDERER_COMPARISON_FUNC_GREATER D3D12_COMPARISON_FUNC_NOT_EQUAL, // RENDERER_COMPARISON_FUNC_NOT_EQUAL D3D12_COMPARISON_FUNC_GREATER_EQUAL, // RENDERER_COMPARISON_FUNC_GREATER_EQUAL D3D12_COMPARISON_FUNC_ALWAYS, // RENDERER_COMPARISON_FUNC_ALWAYS }; DXGI_FORMAT D3D12Helpers::PixelFormatToDXGIFormat(PIXEL_FORMAT Format) { return (Format < PIXEL_FORMAT_COUNT) ? s_PixelFormatToDXGIFormat[Format] : DXGI_FORMAT_UNKNOWN; } PIXEL_FORMAT D3D12Helpers::DXGIFormatToPixelFormat(DXGI_FORMAT Format) { uint32 i; for (i = 0; i < PIXEL_FORMAT_COUNT; i++) { if (s_PixelFormatToDXGIFormat[i] == Format) return (PIXEL_FORMAT)i; } return PIXEL_FORMAT_UNKNOWN; } void D3D12Helpers::SetD3D12ObjectName(ID3D12Object *pObject, const char *debugName) { #ifdef Y_BUILD_CONFIG_DEBUG uint32 nameLength = Y_strlen(debugName); if (nameLength > 0) { wchar_t *buffer = (wchar_t *)alloca(sizeof(wchar_t) * nameLength + sizeof(wchar_t)); mbstowcs(buffer, debugName, nameLength); buffer[nameLength] = 0; pObject->SetName(buffer); } #endif } bool D3D12Helpers::FillD3D12RasterizerStateDesc(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerState, D3D12_RASTERIZER_DESC *pOutRasterizerDesc) { static const D3D12_FILL_MODE D3D11FillModes[RENDERER_FILL_MODE_COUNT] = { D3D12_FILL_MODE_WIREFRAME, // RENDERER_FILL_WIREFRAME D3D12_FILL_MODE_SOLID, // RENDERER_FILL_SOLID }; static const D3D12_CULL_MODE D3D11CullModes[RENDERER_CULL_MODE_COUNT] = { D3D12_CULL_MODE_NONE, // RENDERER_CULL_NONE D3D12_CULL_MODE_FRONT, // RENDERER_CULL_FRONT D3D12_CULL_MODE_BACK, // RENDERER_CULL_BACK }; DebugAssert(pRasterizerState->FillMode < RENDERER_FILL_MODE_COUNT); DebugAssert(pRasterizerState->CullMode < RENDERER_CULL_MODE_COUNT); pOutRasterizerDesc->FillMode = D3D11FillModes[pRasterizerState->FillMode]; pOutRasterizerDesc->CullMode = D3D11CullModes[pRasterizerState->CullMode]; pOutRasterizerDesc->FrontCounterClockwise = pRasterizerState->FrontCounterClockwise ? TRUE : FALSE; pOutRasterizerDesc->DepthBias = pRasterizerState->DepthBias; pOutRasterizerDesc->DepthBiasClamp = 0; pOutRasterizerDesc->SlopeScaledDepthBias = pRasterizerState->SlopeScaledDepthBias; pOutRasterizerDesc->DepthClipEnable = pRasterizerState->DepthClipEnable ? TRUE : FALSE; //pOutRasterizerDesc->ScissorEnable = pRasterizerState->ScissorEnable ? TRUE : FALSE; pOutRasterizerDesc->MultisampleEnable = FALSE; pOutRasterizerDesc->AntialiasedLineEnable = FALSE; pOutRasterizerDesc->ForcedSampleCount = 0; pOutRasterizerDesc->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; return true; } bool D3D12Helpers::FillD3D12DepthStencilStateDesc(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState, D3D12_DEPTH_STENCIL_DESC *pOutDepthStencilDesc) { static const D3D12_STENCIL_OP D3D11StencilOps[RENDERER_STENCIL_OP_COUNT] = { D3D12_STENCIL_OP_KEEP, // RENDERER_STENCIL_OP_KEEP D3D12_STENCIL_OP_ZERO, // RENDERER_STENCIL_OP_ZERO D3D12_STENCIL_OP_REPLACE, // RENDERER_STENCIL_OP_REPLACE D3D12_STENCIL_OP_INCR_SAT, // RENDERER_STENCIL_OP_INCREMENT_CLAMPED D3D12_STENCIL_OP_DECR_SAT, // RENDERER_STENCIL_OP_DECREMENT_CLAMPED D3D12_STENCIL_OP_INVERT, // RENDERER_STENCIL_OP_INVERT D3D12_STENCIL_OP_INCR, // RENDERER_STENCIL_OP_INCREMENT D3D12_STENCIL_OP_DECR, // RENDERER_STENCIL_OP_DECREMENT }; DebugAssert(pDepthStencilState->DepthFunc < GPU_COMPARISON_FUNC_COUNT); pOutDepthStencilDesc->DepthEnable = pDepthStencilState->DepthTestEnable ? TRUE : FALSE; pOutDepthStencilDesc->DepthWriteMask = pDepthStencilState->DepthWriteEnable ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO; pOutDepthStencilDesc->DepthFunc = s_D3D12ComparisonFuncs[pDepthStencilState->DepthFunc]; DebugAssert(pDepthStencilState->StencilFrontFace.FailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.DepthFailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.PassOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.CompareFunc < GPU_COMPARISON_FUNC_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.FailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.DepthFailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.PassOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.CompareFunc < GPU_COMPARISON_FUNC_COUNT); pOutDepthStencilDesc->StencilEnable = pDepthStencilState->StencilTestEnable ? TRUE : FALSE; pOutDepthStencilDesc->StencilReadMask = pDepthStencilState->StencilReadMask; pOutDepthStencilDesc->StencilWriteMask = pDepthStencilState->StencilWriteMask; pOutDepthStencilDesc->FrontFace.StencilFailOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.FailOp]; pOutDepthStencilDesc->FrontFace.StencilDepthFailOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.DepthFailOp]; pOutDepthStencilDesc->FrontFace.StencilPassOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.PassOp]; pOutDepthStencilDesc->FrontFace.StencilFunc = s_D3D12ComparisonFuncs[pDepthStencilState->StencilFrontFace.CompareFunc]; pOutDepthStencilDesc->BackFace.StencilFailOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.FailOp]; pOutDepthStencilDesc->BackFace.StencilDepthFailOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.DepthFailOp]; pOutDepthStencilDesc->BackFace.StencilPassOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.PassOp]; pOutDepthStencilDesc->BackFace.StencilFunc = s_D3D12ComparisonFuncs[pDepthStencilState->StencilBackFace.CompareFunc]; return true; } bool D3D12Helpers::FillD3D12BlendStateDesc(const RENDERER_BLEND_STATE_DESC *pBlendState, D3D12_BLEND_DESC *pOutBlendDesc) { static const D3D12_BLEND D3D12BlendOptions[RENDERER_BLEND_OPTION_COUNT] = { D3D12_BLEND_ZERO, // RENDERER_BLEND_ZERO D3D12_BLEND_ONE, // RENDERER_BLEND_ONE D3D12_BLEND_SRC_COLOR, // RENDERER_BLEND_SRC_COLOR D3D12_BLEND_INV_SRC_COLOR, // RENDERER_BLEND_INV_SRC_COLOR D3D12_BLEND_SRC_ALPHA, // RENDERER_BLEND_SRC_ALPHA D3D12_BLEND_INV_SRC_ALPHA, // RENDERER_BLEND_INV_SRC_ALPHA D3D12_BLEND_DEST_ALPHA, // RENDERER_BLEND_DEST_ALPHA D3D12_BLEND_INV_DEST_ALPHA, // RENDERER_BLEND_INV_DEST_ALPHA D3D12_BLEND_DEST_COLOR, // RENDERER_BLEND_DEST_COLOR D3D12_BLEND_INV_DEST_COLOR, // RENDERER_BLEND_INV_DEST_COLOR D3D12_BLEND_SRC_ALPHA_SAT, // RENDERER_BLEND_SRC_ALPHA_SAT D3D12_BLEND_BLEND_FACTOR, // RENDERER_BLEND_BLEND_FACTOR D3D12_BLEND_INV_BLEND_FACTOR, // RENDERER_BLEND_INV_BLEND_FACTOR D3D12_BLEND_SRC1_COLOR, // RENDERER_BLEND_SRC1_COLOR D3D12_BLEND_INV_SRC1_COLOR, // RENDERER_BLEND_INV_SRC1_COLOR D3D12_BLEND_SRC1_ALPHA, // RENDERER_BLEND_SRC1_ALPHA D3D12_BLEND_INV_SRC1_ALPHA, // RENDERER_BLEND_INV_SRC1_ALPHA }; static const D3D12_BLEND_OP D3D12BlendOps[RENDERER_BLEND_OP_COUNT] = { D3D12_BLEND_OP_ADD, // RENDERER_BLEND_OP_ADD D3D12_BLEND_OP_SUBTRACT, // RENDERER_BLEND_OP_SUBTRACT D3D12_BLEND_OP_REV_SUBTRACT, // RENDERER_BLEND_OP_REV_SUBTRACT D3D12_BLEND_OP_MIN, // RENDERER_BLEND_OP_MIN D3D12_BLEND_OP_MAX, // RENDERER_BLEND_OP_MAX }; DebugAssert(pBlendState->SrcBlend < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->BlendOp < RENDERER_BLEND_OP_COUNT); DebugAssert(pBlendState->DestBlend < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->SrcBlendAlpha < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->BlendOpAlpha < RENDERER_BLEND_OP_COUNT); DebugAssert(pBlendState->DestBlendAlpha < RENDERER_BLEND_OPTION_COUNT); pOutBlendDesc->AlphaToCoverageEnable = FALSE; pOutBlendDesc->IndependentBlendEnable = FALSE; for (uint32 i = 0; i < 8; i++) { pOutBlendDesc->RenderTarget[i].BlendEnable = pBlendState->BlendEnable ? TRUE : FALSE; pOutBlendDesc->RenderTarget[i].LogicOpEnable = FALSE; pOutBlendDesc->RenderTarget[i].SrcBlend = D3D12BlendOptions[pBlendState->SrcBlend]; pOutBlendDesc->RenderTarget[i].BlendOp = D3D12BlendOps[pBlendState->BlendOp]; pOutBlendDesc->RenderTarget[i].DestBlend = D3D12BlendOptions[pBlendState->DestBlend]; pOutBlendDesc->RenderTarget[i].SrcBlendAlpha = D3D12BlendOptions[pBlendState->SrcBlendAlpha]; pOutBlendDesc->RenderTarget[i].BlendOpAlpha = D3D12BlendOps[pBlendState->BlendOpAlpha]; pOutBlendDesc->RenderTarget[i].DestBlendAlpha = D3D12BlendOptions[pBlendState->DestBlendAlpha]; pOutBlendDesc->RenderTarget[i].LogicOp = D3D12_LOGIC_OP_CLEAR; pOutBlendDesc->RenderTarget[i].RenderTargetWriteMask = pBlendState->ColorWriteEnable ? D3D12_COLOR_WRITE_ENABLE_ALL : 0; } return true; } bool D3D12Helpers::FillD3D12SamplerStateDesc(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, D3D12_SAMPLER_DESC *pOutSamplerStateDesc) { static const D3D12_FILTER D3D12TextureFilters[TEXTURE_FILTER_COUNT] = { D3D12_FILTER_MIN_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_MIN_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR D3D12_FILTER_ANISOTROPIC, // RENDERER_TEXTURE_FILTER_ANISOTROPIC D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR D3D12_FILTER_COMPARISON_ANISOTROPIC, // RENDERER_TEXTURE_FILTER_ANISOTROPIC }; static const D3D12_TEXTURE_ADDRESS_MODE D3D12TextureAddresses[TEXTURE_ADDRESS_MODE_COUNT] = { D3D12_TEXTURE_ADDRESS_MODE_WRAP, // RENDERER_TEXTURE_ADDRESS_WRAP D3D12_TEXTURE_ADDRESS_MODE_MIRROR, // RENDERER_TEXTURE_ADDRESS_MIRROR D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // RENDERER_TEXTURE_ADDRESS_CLAMP D3D12_TEXTURE_ADDRESS_MODE_BORDER, // RENDERER_TEXTURE_ADDRESS_BORDER D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, // RENDERER_TEXTURE_ADDRESS_MIRROR_ONCE }; DebugAssert(pSamplerStateDesc->Filter < TEXTURE_FILTER_COUNT); DebugAssert(pSamplerStateDesc->AddressU < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->AddressV < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->AddressW < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->ComparisonFunc < GPU_COMPARISON_FUNC_COUNT); pOutSamplerStateDesc->Filter = D3D12TextureFilters[pSamplerStateDesc->Filter]; pOutSamplerStateDesc->AddressU = D3D12TextureAddresses[pSamplerStateDesc->AddressU]; pOutSamplerStateDesc->AddressV = D3D12TextureAddresses[pSamplerStateDesc->AddressV]; pOutSamplerStateDesc->AddressW = D3D12TextureAddresses[pSamplerStateDesc->AddressW]; Y_memcpy(pOutSamplerStateDesc->BorderColor, &pSamplerStateDesc->BorderColor, sizeof(float) * 4); pOutSamplerStateDesc->MipLODBias = pSamplerStateDesc->LODBias; pOutSamplerStateDesc->MinLOD = (float)pSamplerStateDesc->MinLOD; pOutSamplerStateDesc->MaxLOD = (float)pSamplerStateDesc->MaxLOD; pOutSamplerStateDesc->MaxAnisotropy = pSamplerStateDesc->MaxAnisotropy; pOutSamplerStateDesc->ComparisonFunc = s_D3D12ComparisonFuncs[pSamplerStateDesc->ComparisonFunc]; return true; } D3D12_PRIMITIVE_TOPOLOGY D3D12Helpers::GetD3D12PrimitiveTopology(DRAW_TOPOLOGY topology) { static const D3D12_PRIMITIVE_TOPOLOGY D3D12Topologies[DRAW_TOPOLOGY_COUNT] = { D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, // DRAW_TOPOLOGY_UNDEFINED D3D_PRIMITIVE_TOPOLOGY_POINTLIST, // DRAW_TOPOLOGY_POINTS D3D_PRIMITIVE_TOPOLOGY_LINELIST, // DRAW_TOPOLOGY_LINE_LIST D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, // DRAW_TOPOLOGY_LINE_STRIP D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // DRAW_TOPOLOGY_TRIANGLE_LIST D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, // DRAW_TOPOLOGY_TRIANGLE_STRIP }; DebugAssert(topology < countof(D3D12Topologies)); return D3D12Topologies[topology]; } D3D12_PRIMITIVE_TOPOLOGY_TYPE D3D12Helpers::GetD3D12PrimitiveTopologyType(DRAW_TOPOLOGY topology) { static const D3D12_PRIMITIVE_TOPOLOGY_TYPE D3D12ToplogyTypes[DRAW_TOPOLOGY_COUNT] = { D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED, // DRAW_TOPOLOGY_UNDEFINED D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT, // DRAW_TOPOLOGY_POINTS D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, // DRAW_TOPOLOGY_LINE_LIST D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, // DRAW_TOPOLOGY_LINE_STRIP D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, // DRAW_TOPOLOGY_TRIANGLE_LIST D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, // DRAW_TOPOLOGY_TRIANGLE_STRIP }; DebugAssert(topology < countof(D3D12ToplogyTypes)); return D3D12ToplogyTypes[topology]; } bool D3D12Helpers::GetResourceSRVHandle(GPUResource *pResource, D3D12DescriptorHandle *pHandle) { if (pResource == nullptr) return false; switch (pResource->GetResourceType()) { #if 0 case GPU_RESOURCE_TYPE_TEXTURE1D: *pHandle = static_cast<D3D12GPUTexture1D *>(pResource)->GetD3DSRV(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: *pHandle = static_cast<D3D12GPUTexture1DArray *>(pResource)->GetD3DSRV(); return (!pHandle->IsNull()); #endif case GPU_RESOURCE_TYPE_TEXTURE2D: *pHandle = static_cast<D3D12GPUTexture2D *>(pResource)->GetSRVHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: *pHandle = static_cast<D3D12GPUTexture2DArray *>(pResource)->GetSRVHandle(); return (!pHandle->IsNull()); #if 0 case GPU_RESOURCE_TYPE_TEXTURE3D: *pHandle = static_cast<D3D12GPUTexture3D *>(pResource)->GetSRVHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURECUBE: *pHandle = static_cast<D3D12GPUTextureCube *>(pResource)->GetSRVHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: *pHandle = static_cast<D3D12GPUTextureCubeArray *>(pResource)->GetSRVHandle(); return (!pHandle->IsNull()); #endif } return false; } bool D3D12Helpers::GetResourceSamplerHandle(GPUResource *pResource, D3D12DescriptorHandle *pHandle) { if (pResource == nullptr) return false; switch (pResource->GetResourceType()) { #if 0 case GPU_RESOURCE_TYPE_TEXTURE1D: *pHandle = static_cast<D3D12GPUTexture1D *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: *pHandle = static_cast<D3D12GPUTexture1DArray *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); #endif case GPU_RESOURCE_TYPE_TEXTURE2D: *pHandle = static_cast<D3D12GPUTexture2D *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: *pHandle = static_cast<D3D12GPUTexture2DArray *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); #if 0 case GPU_RESOURCE_TYPE_TEXTURE3D: *pHandle = static_cast<D3D12GPUTexture3D *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURECUBE: *pHandle = static_cast<D3D12GPUTextureCube *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: *pHandle = static_cast<D3D12GPUTextureCubeArray *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); #endif case GPU_RESOURCE_TYPE_SAMPLER_STATE: *pHandle = static_cast<D3D12GPUSamplerState *>(pResource)->GetSamplerHandle(); return (!pHandle->IsNull()); } return false; } bool D3D12Helpers::GetOptimizedClearValue(PIXEL_FORMAT format, D3D12_CLEAR_VALUE *pValue) { pValue->Format = PixelFormatToDXGIFormat(format); if (PixelFormatHelpers::IsDepthFormat(format)) { pValue->DepthStencil.Depth = 1.0f; pValue->DepthStencil.Stencil = 0; } else { pValue->Color[0] = 0.0f; pValue->Color[1] = 0.0f; pValue->Color[2] = 0.0f; pValue->Color[3] = 0.0f; } return true; } D3D12_RESOURCE_STATES D3D12Helpers::GetResourceDefaultState(GPUResource *pResource) { switch (pResource->GetResourceType()) { case GPU_RESOURCE_TYPE_BUFFER: return static_cast<D3D12GPUBuffer *>(pResource)->GetDefaultResourceState(); case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<D3D12GPUTexture2D *>(pResource)->GetDefaultResourceState(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<D3D12GPUTexture2DArray *>(pResource)->GetDefaultResourceState(); } return D3D12_RESOURCE_STATE_GENERIC_READ; } <file_sep>/Engine/Source/Engine/TerrainRendererCDLOD.h #pragma once #include "Engine/TerrainRenderer.h" #include "Engine/TerrainQuadTree.h" #include "Renderer/RenderProxy.h" #include "Renderer/RendererTypes.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/VertexFactory.h" class ShaderProgram; class TerrainRendererCDLOD; class TerrainSectionRenderProxyCDLOD; class TerrainRendererCDLOD_VertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(TerrainRendererCDLOD_VertexFactory, VertexFactory); public: static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); // setup for drawing //static void SetShaderUniforms(GPUShaderProgram *pShaderProgram, const TerrainManager *pTerrainManager, const TerrainSection *pSection, int32 sectionX, int32 sectionY, uint32 nodeOffset[2], uint32 nodeSize); }; class TerrainRendererCDLOD : public TerrainRenderer { public: TerrainRendererCDLOD(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList); virtual ~TerrainRendererCDLOD(); // create a render proxy for a section virtual TerrainSectionRenderProxy *CreateSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) override; // gpu resources virtual bool CreateGPUResources() override; virtual void ReleaseGPUResources() override; // readers for renderproxy bool BindGridBuffers(GPUCommandList *pCommandList) const; uint32 GetGridSize() const { return m_gridSize; } uint32 GetGridIndexCount() const { return m_indexCount; } uint32 GetGridIndexCountPerSubQuad() const { return m_indexCountPerSubQuad; } uint32 GetGridIndexCountSingleQuad() const { return m_indexCountSingleQuad; } uint32 GetGridIndexEndTL() const { return m_indexEndTL; } uint32 GetGridIndexEndTR() const { return m_indexEndTR; } uint32 GetGridIndexEndBL() const { return m_indexEndBL; } uint32 GetGridIndexEndBR() const { return m_indexEndBR; } protected: bool CreateGridBuffers(); void OnSettingsChangedCallback(); // callback to update settings Functor *m_pSettingsUpdateCallback; volatile bool m_settingsUpdatedFlag; // gpu resources uint32 m_gridSize; GPUBuffer *m_pVertexBuffer; GPUBuffer *m_pIndexBuffer; GPU_INDEX_FORMAT m_indexFormat; uint32 m_indexCount; uint32 m_indexCountPerSubQuad; uint32 m_indexCountSingleQuad; uint32 m_indexEndTL; uint32 m_indexEndTR; uint32 m_indexEndBL; uint32 m_indexEndBR; bool m_GPUResourcesCreated; }; class TerrainSectionRenderProxyCDLOD : public TerrainSectionRenderProxy { friend class TerrainRendererCDLOD; public: TerrainSectionRenderProxyCDLOD(uint32 entityID, const TerrainRendererCDLOD *pRenderer, const TerrainSection *pSection); ~TerrainSectionRenderProxyCDLOD(); // create textures bool CreateGPUResources(); // virtual update methods for TerrainSectionRenderProxy virtual void OnLayersModified() override; virtual void OnPointHeightModified(uint32 x, uint32 y) override; virtual void OnPointLayersModified(uint32 x, uint32 y) override; // resources accessors GPUTexture2D *GetHeightMapTexture() const { return m_pHeightMapTexture; } GPUTexture2D *GetNormalMapTexture() const { return m_pNormalMapTexture; } GPUTexture *GetAlphaMapTexture() const { return m_pAlphaMapTexture; } const Material *GetRenderMaterial() const { return m_pRenderMaterial; } // RenderProxy methods virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual void DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const override; private: // texture creators bool CreateHeightMapTexture(); bool CreateNormalMapTexture(); bool CreateCombinedHeightNormalMapTexture(); bool CreateAlphaMapTexture(); bool CreateRenderMaterial(); bool CreateDetailInstanceBuffer(); // helpers void CalculateMorphConstants(float cameraNearDistance, float cameraFarDistance) const; void SetupTerrainDraw(const TerrainQuadTreeNode *pNode, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const; void InvokeTerrainDraw(GPUCommandList *pCommandList, uint32 drawFlags) const; bool BuildDetailBatches(GPUCommandList *pCommandList, const float3 &eyePosition) const; void SetupDetailBatchDraw(uint32 detailBatchIndex, uint32 meshLODIndex, uint32 meshBatchIndex, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const; void InvokeDetailBatchDraw(uint32 detailBatchIndex, uint32 meshLODIndex, uint32 meshBatchIndex, GPUCommandList *pCommandList) const; // vars const TerrainRendererCDLOD *m_pRenderer; GPUTexture2D *m_pHeightMapTexture; GPUTexture2D *m_pNormalMapTexture; GPUTexture *m_pAlphaMapTexture; const Material *m_pRenderMaterial; bool m_GPUResourcesCreated; //bool m_layersChanged; //bool m_heightChanged; //bool m_weightChanged; // detail buffer GPUBuffer *m_pDetailInstanceBuffer; struct DetailBatch { uint32 MeshIndex; uint32 InstanceBufferOffset; uint32 InstanceCount; }; mutable MemArray<DetailBatch> m_detailBatches; // guaranteed to be valid for the current context draw only // morphing constants mutable float m_visibilityRanges[TERRAIN_MAX_RENDER_LODS]; mutable float m_morphStart[TERRAIN_MAX_RENDER_LODS]; mutable float m_morphEnd[TERRAIN_MAX_RENDER_LODS]; mutable float4 m_morphConstants[TERRAIN_MAX_RENDER_LODS]; }; <file_sep>/Engine/Source/MathLib/Ray.cpp #include "MathLib/Ray.h" #include "MathLib/Plane.h" #include "MathLib/AABox.h" #include "MathLib/Sphere.h" #include "MathLib/CollisionDetection.h" #include "MathLib/SIMDVectorf.h" #include "YBaseLib/Assert.h" Ray::Ray(const Ray &copyRay) : m_Origin(copyRay.m_Origin), m_End(copyRay.m_End), m_Direction(copyRay.m_Direction), m_InverseDirection(copyRay.m_InverseDirection), m_Distance(copyRay.m_Distance) { } Ray::Ray(const Vector3f &orgin, const Vector3f &direction, float maxDistance) { SIMDVector3f vec_direction(direction); m_Origin = orgin; m_End = SIMDVector3f(orgin) + vec_direction * maxDistance; m_Direction = direction; m_InverseDirection = SIMDVector3f::One / vec_direction; m_Distance = maxDistance; } Ray::Ray(const Vector3f &start, const Vector3f &end) { m_Origin = start; m_End = end; SIMDVector3f rayVector(SIMDVector3f(end) - SIMDVector3f(start)); DebugAssert(rayVector.SquaredLength() > 0.0f); m_Direction = rayVector.Normalize(); m_InverseDirection = SIMDVector3f::One / rayVector; m_Distance = rayVector.Length(); } AABox Ray::GetAABox() const { SIMDVector3f vec_origin(m_Origin); SIMDVector3f vec_end(m_End); return AABox(vec_origin.Min(vec_end), vec_origin.Max(vec_end)); } bool Ray::AABoxIntersection(const AABox &aaBox) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, aaBox.GetMinBounds(), aaBox.GetMaxBounds()); } bool Ray::AABoxIntersection(const AABox &aaBox, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, aaBox.GetMinBounds(), aaBox.GetMaxBounds(), contactNormal, contactPoint); } bool Ray::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, minBounds, maxBounds); } bool Ray::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, minBounds, maxBounds, contactNormal, contactPoint); } float Ray::AABoxIntersectionTime(const AABox &aaBox) const { Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, aaBox.GetMinBounds(), aaBox.GetMaxBounds(), contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } float Ray::AABoxIntersectionTime(const Vector3f &minBounds, const Vector3f &maxBounds) const { Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsAABox(m_Origin, m_Direction, m_Distance, minBounds, maxBounds, contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } bool Ray::AABoxIntersectionTimeFace(const AABox &aaBox, float *pContactTime, CUBE_FACE *pContactFace) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_InverseDirection, m_Distance, aaBox.GetMinBounds(), aaBox.GetMaxBounds(), pContactTime, pContactFace); } bool Ray::AABoxIntersectionTimeFace(const Vector3f &minBounds, const Vector3f &maxBounds, float *pContactTime, CUBE_FACE *pContactFace) const { return CollisionDetection::RayIntersectsAABox(m_Origin, m_InverseDirection, m_Distance, minBounds, maxBounds, pContactTime, pContactFace); } bool Ray::PlaneIntersection(const Plane &intersectPlane) { return CollisionDetection::RayIntersectsPlane(m_Origin, m_Direction, m_Distance, intersectPlane.GetNormal(), intersectPlane.GetDistance()); } bool Ray::PlaneIntersection(const Plane &intersectPlane, Vector3f &contactNormal, Vector3f &contactPoint) { return CollisionDetection::RayIntersectsPlane(m_Origin, m_Direction, m_Distance, intersectPlane.GetNormal(), intersectPlane.GetDistance(), contactNormal, contactPoint); } float Ray::PlaneIntersectionTime(const Plane &intersectPlane) { Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsPlane(m_Origin, m_Direction, m_Distance, intersectPlane.GetNormal(), intersectPlane.GetDistance(), contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } bool Ray::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0 = SIMDVector3f(v1) - vec_v0; SIMDVector3f vec_e1 = SIMDVector3f(v2) - vec_v0; return CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, vec_e0, vec_e1); } bool Ray::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0 = SIMDVector3f(v1) - vec_v0; SIMDVector3f vec_e1 = SIMDVector3f(v2) - vec_v0; return CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, vec_e0, vec_e1, contactNormal, contactPoint); } bool Ray::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1) const { return CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, e0, e1); } bool Ray::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, e0, e1, contactNormal, contactPoint); } float Ray::TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0 = SIMDVector3f(v1) - vec_v0; SIMDVector3f vec_e1 = SIMDVector3f(v2) - vec_v0; Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, vec_e0, vec_e1, contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } float Ray::TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1) { Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsTriangle(m_Origin, m_Direction, m_Distance, v0, v1, v2, e0, e1, contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } bool Ray::SphereIntersection(const Sphere &sphere) { return CollisionDetection::RayIntersectsSphere(m_Origin, m_Direction, m_Distance, sphere.GetCenter(), sphere.GetRadius()); } bool Ray::SphereIntersection(const Sphere &sphere, Vector3f &contactNormal, Vector3f &contactPoint) { return CollisionDetection::RayIntersectsSphere(m_Origin, m_Direction, m_Distance, sphere.GetCenter(), sphere.GetRadius(), contactNormal, contactPoint); } float Ray::SphereIntersectionTime(const Sphere &sphere) { Vector3f contactNormal, contactPoint; if (CollisionDetection::RayIntersectsSphere(m_Origin, m_Direction, m_Distance, sphere.GetCenter(), sphere.GetRadius(), contactNormal, contactPoint)) return (contactPoint - m_Origin).Length(); else return Y_FLT_INFINITE; } <file_sep>/Engine/Source/GameFramework/StaticMeshComponent.h #pragma once #include "Engine/Component.h" #include "Engine/StaticMesh.h" namespace Physics { class CollisionObject; } class StaticMeshRenderProxy; class StaticMeshComponent : public Component { DECLARE_COMPONENT_TYPEINFO(StaticMeshComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(StaticMeshComponent); public: StaticMeshComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~StaticMeshComponent(); // property accessors const bool IsVisible() const { return m_visible; } const bool IsCollidable() const { return m_collidable; } const StaticMesh *GetStaticMesh() const { return m_pStaticMesh; } const uint32 GetShadowFlags() const { return m_shadowFlags; } // property setters void SetVisible(bool visible); void SetCollidable(bool enabled); void SetStaticMesh(const StaticMesh *pStaticMesh); void SetShadowFlags(uint32 shadowFlags); // External creation method void Create(const float3 &localPosition = float3::Zero, const Quaternion &localRotation = Quaternion::Identity, const float3 &localScale = float3::One, const StaticMesh *pStaticMesh = nullptr, bool visible = true, bool collidable = true, uint32 shadowFlags = ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); // Component events virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; private: // property callbacks static bool PropertyCallbackGetMeshName(ThisClass *pComponent, const void *pUserData, String *pValue); static bool PropertyCallbackSetMeshName(ThisClass *pComponent, const void *pUserData, const String *pValue); static void PropertyCallbackStaticMeshChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackVisibleChanged(ThisClass *pEntity, const void *pUserData = nullptr); static void PropertyCallbackCollidableChanged(ThisClass *pEntity, const void *pUserData = nullptr); // vars const StaticMesh *m_pStaticMesh; bool m_visible; bool m_collidable; uint32 m_shadowFlags; // render proxy StaticMeshRenderProxy *m_pRenderProxy; // physics proxy Physics::CollisionObject *m_pCollisionObject; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUBuffer.h #pragma once #include "D3D12Renderer/D3D12Common.h" class D3D12GPUBuffer : public GPUBuffer { public: D3D12GPUBuffer(const GPU_BUFFER_DESC *pBufferDesc, D3D12GPUDevice *pDevice, ID3D12Resource *pD3DResource, D3D12_RESOURCE_STATES defaultResourceState); virtual ~D3D12GPUBuffer(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *debugName) override; ID3D12Resource *GetD3DResource() { return m_pD3DResource; } ID3D12Resource *GetMapResource() const { return m_pD3DMapResource; } GPU_MAP_TYPE GetMapType() const { return m_mapType; } void SetMapResource(ID3D12Resource *pResource, GPU_MAP_TYPE mapType) { m_pD3DMapResource = pResource; m_mapType = mapType; } D3D12_RESOURCE_STATES GetDefaultResourceState() const { return m_defaultResourceState; } ID3D12Resource *CreateUploadResource(ID3D12Device *pD3DDevice, uint32 size) const; ID3D12Resource *CreateReadbackResource(ID3D12Device *pD3DDevice, uint32 size) const; private: D3D12GPUDevice *m_pDevice; ID3D12Resource *m_pD3DResource; ID3D12Resource *m_pD3DMapResource; D3D12_RESOURCE_STATES m_defaultResourceState; GPU_MAP_TYPE m_mapType; }; <file_sep>/Editor/Source/Editor/EditorVectorEditWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorVectorEditWidget.h" #include "Editor/EditorHelpers.h" EditorVectorEditWidget::EditorVectorEditWidget(QWidget *pParent /*= NULL*/) : QWidget(pParent), m_numComponents(4), m_x(0.0f), m_y(0.0f), m_z(0.0f), m_w(0.0f) { m_pLineEdit = new QLineEdit(this); m_pLineEdit->setDisabled(true); m_pBrowseButton = new QPushButton(this); m_pBrowseButton->setText(tr("...")); m_pBrowseButton->setMinimumSize(16, 16); m_pBrowseButton->setMaximumSize(20, 16777215); m_pPopupPanel = nullptr; QHBoxLayout *hbox = new QHBoxLayout(this); hbox->setMargin(0); hbox->setSpacing(0); hbox->addWidget(m_pLineEdit, 1); hbox->addWidget(m_pBrowseButton, 0); setLayout(hbox); connect(m_pBrowseButton, SIGNAL(clicked()), this, SLOT(OnExpandButtonClicked())); UpdateLineEdit(); } EditorVectorEditWidget::~EditorVectorEditWidget() { delete m_pPopupPanel; } QString EditorVectorEditWidget::GetValueString() const { QString valueString; DebugAssert(m_numComponents > 0 && m_numComponents <= 4); switch (m_numComponents) { case 1: valueString = ConvertStringToQString(StringConverter::FloatToString(m_x)); break; case 2: valueString = ConvertStringToQString(StringConverter::Float2ToString(float2(m_x, m_y))); break; case 3: valueString = ConvertStringToQString(StringConverter::Float3ToString(float3(m_x, m_y, m_z))); break; case 4: valueString = ConvertStringToQString(StringConverter::Float4ToString(float4(m_x, m_y, m_z, m_w))); break; } return valueString; } void EditorVectorEditWidget::SetNumComponents(uint32 numComponents) { DebugAssert(numComponents > 0 && numComponents <= 4); m_numComponents = numComponents; } void EditorVectorEditWidget::SetValue(float x /*= 0.0f*/, float y /*= 0.0f*/, float z /*= 0.0f*/, float w /*= 0.0f*/) { m_x = x; m_y = y; m_z = z; m_w = w; UpdateLineEdit(); // lazy way to force it to update if (m_pPopupPanel != nullptr && m_pPopupPanel->isVisible()) OnExpandButtonClicked(); } void EditorVectorEditWidget::UpdateLineEdit() { m_pLineEdit->setText(GetValueString()); } void EditorVectorEditWidget::EmitValueChangedSignals() { ValueChangedFloat2(float2(m_x, m_y)); ValueChangedFloat3(float3(m_x, m_y, m_z)); ValueChangedFloat4(float4(m_x, m_y, m_z, m_w)); ValueChangedString(GetValueString()); } void EditorVectorEditWidget::OnExpandButtonClicked() { if (m_pPopupPanel != nullptr) delete m_pPopupPanel; // create the editor panel QWidget *pPopupPanel = new QWidget(nullptr, Qt::Popup | Qt::FramelessWindowHint); pPopupPanel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); pPopupPanel->setFixedSize(200, 34 + m_numComponents * 30); // create form layout QFormLayout *formLayout = new QFormLayout(pPopupPanel); formLayout->setRowWrapPolicy(QFormLayout::DontWrapRows); QDoubleSpinBox *pSpinBox; QDoubleSpinBox *pFocusSpinBox; // create each component // x pSpinBox = new QDoubleSpinBox(pPopupPanel); pSpinBox->setRange(Y_FLT_MIN, Y_FLT_MAX); pSpinBox->setDecimals(7); pSpinBox->setSingleStep(0.1); pSpinBox->setValue(m_x); connect(pSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnPopupPanelXChanged(double))); formLayout->addRow("&X: ", pSpinBox); pFocusSpinBox = pSpinBox; // y if (m_numComponents > 1) { pSpinBox = new QDoubleSpinBox(pPopupPanel); pSpinBox->setRange(Y_FLT_MIN, Y_FLT_MAX); pSpinBox->setDecimals(7); pSpinBox->setSingleStep(0.1); pSpinBox->setValue(m_y); connect(pSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnPopupPanelYChanged(double))); formLayout->addRow("&Y: ", pSpinBox); // z if (m_numComponents > 2) { pSpinBox = new QDoubleSpinBox(pPopupPanel); pSpinBox->setRange(Y_FLT_MIN, Y_FLT_MAX); pSpinBox->setDecimals(7); pSpinBox->setSingleStep(0.1); pSpinBox->setValue(m_z); connect(pSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnPopupPanelZChanged(double))); formLayout->addRow("&Z: ", pSpinBox); // w if (m_numComponents > 3) { pSpinBox = new QDoubleSpinBox(pPopupPanel); pSpinBox->setRange(Y_FLT_MIN, Y_FLT_MAX); pSpinBox->setDecimals(7); pSpinBox->setSingleStep(0.1); pSpinBox->setValue(m_w); connect(pSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnPopupPanelWChanged(double))); formLayout->addRow("&W: ", pSpinBox); } } } // normalize button QPushButton *pNormalizeButton = new QPushButton(pPopupPanel); pNormalizeButton->setText(tr("Normalize")); connect(pNormalizeButton, SIGNAL(clicked()), this, SLOT(OnPopupPanelNormalizeClicked())); formLayout->addRow(pNormalizeButton); // set layout pPopupPanel->setLayout(formLayout); // set pointer m_pPopupPanel = pPopupPanel; // move it into position and show m_pPopupPanel->move(m_pBrowseButton->mapToGlobal(QPoint(0, m_pBrowseButton->height()))); m_pPopupPanel->show(); // foxus it pFocusSpinBox->setFocus(); } void EditorVectorEditWidget::OnPopupPanelXChanged(double value) { m_x = (float)value; UpdateLineEdit(); EmitValueChangedSignals(); } void EditorVectorEditWidget::OnPopupPanelYChanged(double value) { m_y = (float)value; UpdateLineEdit(); EmitValueChangedSignals(); } void EditorVectorEditWidget::OnPopupPanelZChanged(double value) { m_z = (float)value; UpdateLineEdit(); EmitValueChangedSignals(); } void EditorVectorEditWidget::OnPopupPanelWChanged(double value) { m_w = (float)value; UpdateLineEdit(); EmitValueChangedSignals(); } void EditorVectorEditWidget::OnPopupPanelNormalizeClicked() { float length = m_x * m_x; if (m_numComponents > 1) { length += m_y * m_y; if (m_numComponents > 2) { length += m_z * m_z; if (m_numComponents > 3) length += m_w * m_w; } } if (Math::NearEqual(length, 0.0f, Y_FLT_EPSILON)) return; length = Math::Sqrt(length); m_x /= length; m_y /= length; m_z /= length; m_w /= length; UpdateLineEdit(); EmitValueChangedSignals(); // lazy way to force it to update if (m_pPopupPanel != nullptr && m_pPopupPanel->isVisible()) OnExpandButtonClicked(); } <file_sep>/Engine/Source/Engine/Defines.h #pragma once // Engine coordinate system #define ENGINE_COORDINATE_SYSTEM COORDINATE_SYSTEM_Z_UP_RH //--------------------------------- Drawing -------------------------------- enum RENDER_PASS { //RENDER_PASS_Z_PREPASS = (1 << 0), // z pre-pass RENDER_PASS_LIGHTMAP = (1 << 1), // lightmaps RENDER_PASS_EMISSIVE = (1 << 2), // emissive RENDER_PASS_STATIC_LIGHTING = (1 << 3), // light from static lights, applied dynamically RENDER_PASS_DYNAMIC_LIGHTING = (1 << 4), // light from dynamic lights, applied dynamically RENDER_PASS_SHADOWED_LIGHTING = (1 << 5), // light from dynamic lights that cast shadows, applied dynamically RENDER_PASS_SHADOW_MAP = (1 << 6), // shadow map occluders RENDER_PASS_OCCLUSION_CULLING_PROXY = (1 << 7), // occlusion culling occluder pass RENDER_PASS_TINT = (1 << 8), RENDER_PASS_POST_DRAW = (1 << 9), // Combination enums. // Base passes RENDER_PASSES_DEFAULT = RENDER_PASS_SHADOW_MAP | RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING, // Render passes that are determined by material properties. RENDER_PASSES_AFFECTED_BY_MATERIAL = RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING, // Lighting render passes, used for masking out lights. RENDER_PASSES_LIGHTING = RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING, }; enum RENDER_LAYER { RENDER_LAYER_NONE = (0), RENDER_LAYER_CSG_GEOMETRY = (1 << 0), RENDER_LAYER_STATIC_GEOMETRY = (1 << 1), RENDER_LAYER_DYNAMIC_GEOMETRY = (1 << 2), RENDER_LAYER_EDITOR_VISUALS = (1 << 3), RENDER_LAYER_GAME_GROUP = RENDER_LAYER_CSG_GEOMETRY | RENDER_LAYER_STATIC_GEOMETRY | RENDER_LAYER_DYNAMIC_GEOMETRY, }; enum MATERIAL_DEBUG_MODE { MATERIAL_DEBUG_MODE_NONE, MATERIAL_DEBUG_MODE_NORMALS, MATERIAL_DEBUG_MODE_FACE_NORMALS, MATERIAL_DEBUG_MODE_DIFFUSE_COLOR, MATERIAL_DEBUG_MODE_SPECULAR_COEFFICIENT, MATERIAL_DEBUG_MODE_COUNT, }; enum LIGHTING_DEBUG_MODE { LIGHTING_DEBUG_MODE_FLAT, LIGHTING_DEBUG_MODE_DETAIL, LIGHTING_DEBUG_MODE_COUNT, }; enum MATERIAL_BLENDING_MODE { MATERIAL_BLENDING_MODE_NONE, MATERIAL_BLENDING_MODE_ADDITIVE, MATERIAL_BLENDING_MODE_STRAIGHT, MATERIAL_BLENDING_MODE_PREMULTIPLIED, MATERIAL_BLENDING_MODE_MASKED, MATERIAL_BLENDING_MODE_SOFTMASKED, MATERIAL_BLENDING_MODE_COUNT, }; enum MATERIAL_LIGHTING_TYPE { MATERIAL_LIGHTING_TYPE_EMISSIVE, MATERIAL_LIGHTING_TYPE_REFLECTIVE, MATERIAL_LIGHTING_TYPE_REFLECTIVE_EMISSIVE, MATERIAL_LIGHTING_TYPE_REFLECTIVE_TWO_SIDED, MATERIAL_LIGHTING_TYPE_COUNT, }; enum MATERIAL_LIGHTING_MODEL { MATERIAL_LIGHTING_MODEL_PHONG, MATERIAL_LIGHTING_MODEL_BLINN_PHONG, MATERIAL_LIGHTING_MODEL_PHYSICALLY_BASED, MATERIAL_LIGHTING_MODEL_CUSTOM, MATERIAL_LIGHTING_MODEL_COUNT, }; enum MATERIAL_LIGHTING_NORMAL_SPACE { MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE, MATERIAL_LIGHTING_NORMAL_SPACE_TANGENT_SPACE, MATERIAL_LIGHTING_NORMAL_SPACE_COUNT, }; enum MATERIAL_RENDER_MODE { MATERIAL_RENDER_MODE_NORMAL, MATERIAL_RENDER_MODE_WIREFRAME, MATERIAL_RENDER_MODE_POST_PROCESS, MATERIAL_RENDER_MODE_COUNT, }; enum MATERIAL_RENDER_LAYER { MATERIAL_RENDER_LAYER_SKYBOX, MATERIAL_RENDER_LAYER_NORMAL, MATERIAL_RENDER_LAYER_COUNT, }; enum MAP_SKY_TYPE { MAP_SKY_TYPE_SKYBOX, MAP_SKY_TYPE_SKYSPHERE, MAP_SKY_TYPE_SKYDOME, MAP_SKY_TYPE_COUNT, }; namespace NameTables { Y_Declare_NameTable(MaterialBlendingMode); Y_Declare_NameTable(MaterialLightingType); Y_Declare_NameTable(MaterialLightingModel); Y_Declare_NameTable(MaterialLightingNormalSpace); Y_Declare_NameTable(MaterialRenderMode); Y_Declare_NameTable(MaterialRenderLayer); } #define MATERIAL_MAX_PARAMETER_NAME_LENGTH (256) #define MATERIAL_MAX_STATIC_SWITCH_COUNT (16) //-------------------------------- Lighting -------------------------------- enum LIGHT_TYPE { LIGHT_TYPE_DIRECTIONAL, LIGHT_TYPE_POINT, LIGHT_TYPE_SPOT, LIGHT_TYPE_VOLUMETRIC, LIGHT_TYPE_COUNT, }; enum LIGHT_SHADOW_FLAG { LIGHT_SHADOW_FLAG_CAST_STATIC_SHADOWS = (1 << 0), LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS = (1 << 1), }; enum ENTITY_SHADOW_FLAGS { ENTITY_SHADOW_FLAG_CAST_STATIC_SHADOWS = (1 << 0), ENTITY_SHADOW_FLAG_RECEIVE_STATIC_SHADOWS = (1 << 1), ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS = (1 << 2), ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS = (1 << 3), }; enum VOLUMETRIC_LIGHT_PRIMITIVE { VOLUMETRIC_LIGHT_PRIMITIVE_BOX, VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE, VOLUMETRIC_LIGHT_PRIMITIVE_COUNT, }; //-------------------------------- Textures -------------------------------- enum TEXTURE_TYPE { TEXTURE_TYPE_1D, TEXTURE_TYPE_2D, TEXTURE_TYPE_3D, TEXTURE_TYPE_CUBE, TEXTURE_TYPE_1D_ARRAY, TEXTURE_TYPE_2D_ARRAY, TEXTURE_TYPE_CUBE_ARRAY, TEXTURE_TYPE_DEPTH, TEXTURE_TYPE_COUNT, }; enum TEXTURE_USAGE { TEXTURE_USAGE_NONE, TEXTURE_USAGE_COLOR_MAP, TEXTURE_USAGE_GLOSS_MAP, TEXTURE_USAGE_ALPHA_MAP, TEXTURE_USAGE_NORMAL_MAP, TEXTURE_USAGE_HEIGHT_MAP, TEXTURE_USAGE_UI_ASSET, TEXTURE_USAGE_UI_LUMINANCE_ASSET, TEXTURE_USAGE_COUNT, }; enum TEXTURE_FILTER { TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR, TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR, TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT, TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_FILTER_MIN_MAG_MIP_LINEAR, TEXTURE_FILTER_ANISOTROPIC, TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_POINT, TEXTURE_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, TEXTURE_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, TEXTURE_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, TEXTURE_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, TEXTURE_FILTER_COMPARISON_ANISOTROPIC, TEXTURE_FILTER_COUNT, }; enum TEXTURE_ADDRESS_MODE { TEXTURE_ADDRESS_MODE_WRAP, TEXTURE_ADDRESS_MODE_MIRROR, TEXTURE_ADDRESS_MODE_CLAMP, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_MIRROR_ONCE, TEXTURE_ADDRESS_MODE_COUNT, }; enum CUBEMAP_FACE { CUBEMAP_FACE_POSITIVE_X, CUBEMAP_FACE_NEGATIVE_X, CUBEMAP_FACE_POSITIVE_Y, CUBEMAP_FACE_NEGATIVE_Y, CUBEMAP_FACE_POSITIVE_Z, CUBEMAP_FACE_NEGATIVE_Z, CUBEMAP_FACE_COUNT, }; enum TEXTURE_PLATFORM { TEXTURE_PLATFORM_DXTC, TEXTURE_PLATFORM_PVRTC, TEXTURE_PLATFORM_ATC, TEXTURE_PLATFORM_ETC, TEXTURE_PLATFORM_ES2_NOTC, TEXTURE_PLATFORM_ES2_DXTC, NUM_TEXTURE_PLATFORMS }; #define TEXTURE_MAX_MIPMAP_COUNT (15) namespace NameTables { Y_Declare_NameTable(TextureType); Y_Declare_NameTable(TextureClassNames); Y_Declare_NameTable(TextureUsage); Y_Declare_NameTable(TextureFilter); Y_Declare_NameTable(TextureAddressMode); Y_Declare_NameTable(TexturePlatform); Y_Declare_NameTable(TexturePlatformFileExtension); } //-------------------------------- CSG ------------------------------- enum CSG_OPERATOR { CSG_OPERATOR_ADD, // "Union" CSG_OPERATOR_SUBTRACT, // "Difference" CSG_OPERATOR_INTERSECTION, CSG_OPERATOR_DEINTERSECTION, CSG_OPERATOR_COUNT, }; namespace NameTables { Y_Declare_NameTable(CSGOperator); } <file_sep>/Engine/Source/ResourceCompiler/TerrainLayerListGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/TerrainLayerListGenerator.h" #include "ResourceCompiler/TextureGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/Engine.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" #include "Core/ChunkFileWriter.h" #include "Core/Image.h" #include "Core/ImageCodec.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "YBaseLib/ZipArchive.h" Log_SetChannel(TerrainLayerListGenerator); static const PIXEL_FORMAT TERRAIN_LAYER_LIST_INTERNAL_FORMAT = PIXEL_FORMAT_R8G8B8_UNORM; TerrainLayerListGenerator::TerrainLayerListGenerator() : m_baseLayerNormalMapping(false), m_baseLayerBaseMapResolution(256), m_baseLayerNormalMapResolution(256) { for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { m_baseLayers[i].Index = i; m_baseLayers[i].Allocated = false; m_baseLayers[i].TextureRepeatInterval = 0; m_baseLayers[i].pBaseMap = nullptr; m_baseLayers[i].pNormalMap = nullptr; } } TerrainLayerListGenerator::~TerrainLayerListGenerator() { for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { delete m_baseLayers[i].pBaseMap; delete m_baseLayers[i].pNormalMap; } } void TerrainLayerListGenerator::Create(uint32 diffuseMapSize, uint32 normalMapSize) { DebugAssert(diffuseMapSize > 0 && normalMapSize > 0); m_baseLayerBaseMapResolution = diffuseMapSize; m_baseLayerNormalMapResolution = normalMapSize; // create the default layer CreateBaseLayer("default"); } void TerrainLayerListGenerator::CreateCopy(const TerrainLayerListGenerator *pGenerator) { m_baseLayerNormalMapping = pGenerator->m_baseLayerNormalMapping; m_baseLayerBaseMapResolution = pGenerator->m_baseLayerBaseMapResolution; m_baseLayerNormalMapResolution = pGenerator->m_baseLayerNormalMapResolution; for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { const BaseLayer *pSourceBaseLayer = &pGenerator->m_baseLayers[i]; BaseLayer *pDestinationBaseLayer = &m_baseLayers[i]; delete pDestinationBaseLayer->pBaseMap; delete pDestinationBaseLayer->pNormalMap; pDestinationBaseLayer->Allocated = pSourceBaseLayer->Allocated; if (pDestinationBaseLayer->Allocated) { pDestinationBaseLayer->Name = pSourceBaseLayer->Name; pDestinationBaseLayer->TextureRepeatInterval = pSourceBaseLayer->TextureRepeatInterval; DebugAssert(pSourceBaseLayer->pBaseMap != nullptr); pDestinationBaseLayer->pBaseMap = new Image(); pDestinationBaseLayer->pBaseMap->Copy(*pSourceBaseLayer->pBaseMap); if (pSourceBaseLayer->pNormalMap != nullptr) { pDestinationBaseLayer->pNormalMap = new Image(); pDestinationBaseLayer->pNormalMap->Copy(*pSourceBaseLayer->pNormalMap); } else { pDestinationBaseLayer->pNormalMap = nullptr; } } else { pDestinationBaseLayer->Name.Obliterate(); pDestinationBaseLayer->TextureRepeatInterval = 0; pDestinationBaseLayer->pBaseMap = nullptr; pDestinationBaseLayer->pNormalMap = nullptr; } } } bool TerrainLayerListGenerator::Load(const char *FileName, ByteStream *pStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { pProgressCallbacks->SetStatusText("Opening archive..."); // open zip archive ZipArchive *pArchive = ZipArchive::OpenArchiveReadOnly(pStream); if (pArchive == NULL) { Log_ErrorPrintf("TerrainLayerListGenerator::Load: Could not load '%s': Could not open as archive.", FileName); delete pArchive; return false; } // load data pProgressCallbacks->SetProgressRange(1); pProgressCallbacks->SetProgressValue(0); // load base layers { pProgressCallbacks->PushState(); pProgressCallbacks->SetStatusText("Loading base layers..."); if (!LoadBaseLayers(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("TerrainLayerListGenerator::Load: Could not load '%s': Could not load base layers.", FileName); pProgressCallbacks->PopState(); delete pArchive; return false; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(1); } // done delete pArchive; return true; } bool TerrainLayerListGenerator::LoadBaseLayers(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) { AutoReleasePtr<ByteStream> pBaseLayersStream = pArchive->OpenFile("baselayers.xml", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pBaseLayersStream == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::LoadBlockTypes: Could not open baselayers.xml."); return false; } // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pBaseLayersStream, "baselayers.xml")) { xmlReader.PrintError("failed to create XML reader"); return false; } // skip to correct node if (!xmlReader.SkipToElement("baselayers")) { xmlReader.PrintError("failed to skip to baselayers element"); return false; } // read attributes { const char *baseMapSizeStr = xmlReader.FetchAttribute("base-map-resolution"); const char *normalMapSizeStr = xmlReader.FetchAttribute("normal-map-resolution"); const char *normalMapEnabledStr = xmlReader.FetchAttribute("normal-map-enabled"); if (baseMapSizeStr == NULL || normalMapSizeStr == NULL || normalMapEnabledStr == NULL) { xmlReader.PrintError("missing texture size attributes"); return false; } m_baseLayerNormalMapping = StringConverter::StringToBool(normalMapEnabledStr); m_baseLayerBaseMapResolution = StringConverter::StringToUInt32(baseMapSizeStr); m_baseLayerNormalMapResolution = StringConverter::StringToUInt32(normalMapSizeStr); if (m_baseLayerBaseMapResolution == 0 || m_baseLayerNormalMapResolution == 0) { xmlReader.PrintError("invalid texture size attributes"); return false; } } // read nodes uint32 layerCount = 0; if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 baseLayersSelection = xmlReader.Select("baselayer"); if (baseLayersSelection < 0) return false; // read in all fields const char *layerIndex = xmlReader.FetchAttribute("index"); const char *layerName = xmlReader.FetchAttribute("name"); const char *textureRepeatIntervalStr = xmlReader.FetchAttribute("texture-repeat-interval"); if (layerIndex == NULL || layerName == NULL || textureRepeatIntervalStr == NULL) { xmlReader.PrintError("incomplete base layer declaration"); return false; } // check name isn't used if (GetBaseLayerIndexByName(layerName) >= 0) { xmlReader.PrintError("layer name '%s' already used.", layerName); return false; } // convert index to int uint32 intLayerIndex = StringConverter::StringToUInt32(layerIndex); if (intLayerIndex >= TERRAIN_MAX_LAYERS || m_baseLayers[intLayerIndex].Allocated) { xmlReader.PrintError("layer index index out of range, or already used"); return false; } // fill in data BaseLayer *pBaseLayer = &m_baseLayers[intLayerIndex]; pBaseLayer->Allocated = true; pBaseLayer->Name = layerName; pBaseLayer->TextureRepeatInterval = StringConverter::StringToUInt32(textureRepeatIntervalStr); layerCount++; // read the rest of the node if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; // read textures if (!LoadBaseLayerTextures(pArchive, pBaseLayer, pProgressCallbacks)) { xmlReader.PrintError("failed to load any textures for this layer"); return false; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "baselayers") == 0); break; } else { UnreachableCode(); } } } // should have at least one return (layerCount > 0); } bool TerrainLayerListGenerator::LoadBaseLayerTextures(ZipArchive *pArchive, BaseLayer *pBaseLayer, ProgressCallbacks *pProgressCallbacks) { SmallString filename; // search for a diffuse map { filename.Format("baselayer_%u_base.png", pBaseLayer->Index); AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(filename, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(filename, pStream); if (pCodec == nullptr) return false; Image *pImage = new Image(); if (!pCodec->DecodeImage(pImage, filename, pStream)) { delete pImage; return false; } pBaseLayer->pBaseMap = pImage; } // search for a normal map { filename.Format("baselayer_%u_normal.png", pBaseLayer->Index); AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(filename, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pStream != nullptr) { ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(filename, pStream); if (pCodec == nullptr) return false; Image *pImage = new Image(); if (!pCodec->DecodeImage(pImage, filename, pStream)) { delete pImage; return false; } pBaseLayer->pNormalMap = pImage; } } return true; } bool TerrainLayerListGenerator::Save(ByteStream *pStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) const { // open zip archive ZipArchive *pArchive = ZipArchive::CreateArchive(pStream); if (pArchive == nullptr) { Log_ErrorPrintf("TerrainLayerListGenerator::Save: Could not create archive"); return false; } // save data pProgressCallbacks->SetProgressRange(2); pProgressCallbacks->SetProgressValue(0); // save base layers { pProgressCallbacks->PushState(); pProgressCallbacks->SetStatusText("Saving base layers..."); if (!SaveBaseLayers(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("TerrainLayerListGenerator::Save: Could not save base layers."); pProgressCallbacks->PopState(); delete pArchive; return false; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(1); } // commit archive { pProgressCallbacks->SetStatusText("Writing archive..."); if (!pArchive->CommitChanges()) { Log_ErrorPrintf("TerrainLayerListGenerator::Save: Could not commit archive"); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(2); } delete pArchive; return true; } bool TerrainLayerListGenerator::SaveBaseLayers(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const { AutoReleasePtr<ByteStream> pBaseLayersStream = pArchive->OpenFile("baselayers.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pBaseLayersStream == NULL) return false; // create xml writer XMLWriter xmlWriter; if (!xmlWriter.Create(pBaseLayersStream)) return false; // write root element xmlWriter.StartElement("baselayers"); { // write attributes xmlWriter.WriteAttribute("base-map-resolution", StringConverter::UInt32ToString(m_baseLayerBaseMapResolution)); xmlWriter.WriteAttribute("normal-map-enabled", StringConverter::BoolToString(m_baseLayerNormalMapping)); xmlWriter.WriteAttribute("normal-map-resolution", StringConverter::UInt32ToString(m_baseLayerNormalMapResolution)); // write nodes for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { const BaseLayer *pBaseLayer = &m_baseLayers[i]; if (!pBaseLayer->Allocated) continue; xmlWriter.StartElement("baselayer"); { xmlWriter.WriteAttribute("index", StringConverter::UInt32ToString(i)); xmlWriter.WriteAttribute("name", pBaseLayer->Name); xmlWriter.WriteAttribute("texture-repeat-interval", StringConverter::UInt32ToString(pBaseLayer->TextureRepeatInterval)); } xmlWriter.EndElement(); // </baselayer> // write textures if (!SaveBaseLayerTextures(pArchive, pBaseLayer, pProgressCallbacks)) return false; } } xmlWriter.EndElement(); // </baselayers> return (!xmlWriter.InErrorState() && !pBaseLayersStream->InErrorState()); } bool TerrainLayerListGenerator::SaveBaseLayerTextures(ZipArchive *pArchive, const BaseLayer *pBaseLayer, ProgressCallbacks *pProgressCallbacks) const { SmallString filename; DebugAssert(pBaseLayer->pBaseMap != nullptr); // search for a diffuse map { filename.Format("baselayer_%u_base.png", pBaseLayer->Index); AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(filename, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(filename, pStream); if (pCodec == nullptr) return false; if (!pCodec->EncodeImage(filename, pStream, pBaseLayer->pBaseMap)) return false; } // search for a normal map if (pBaseLayer->pNormalMap != nullptr) { filename.Format("baselayer_%u_normal.png", pBaseLayer->Index); AutoReleasePtr<ByteStream> pStream = pArchive->OpenFile(filename, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pStream == nullptr) return false; ImageCodec *pCodec = ImageCodec::GetImageCodecForStream(filename, pStream); if (pCodec == nullptr) return false; if (!pCodec->EncodeImage(filename, pStream, pBaseLayer->pNormalMap)) return false; } return true; } int32 TerrainLayerListGenerator::GetBaseLayerIndexByName(const char *layerName) const { for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { if (m_baseLayers[i].Allocated && m_baseLayers[i].Name.Compare(layerName)) return (int32)i; } return -1; } const TerrainLayerListGenerator::BaseLayer *TerrainLayerListGenerator::GetBaseLayerByName(const char *layerName) const { int32 layerIndex = GetBaseLayerIndexByName(layerName); return (layerIndex >= 0) ? &m_baseLayers[layerIndex] : nullptr; } TerrainLayerListGenerator::BaseLayer *TerrainLayerListGenerator::GetBaseLayerByName(const char *layerName) { int32 layerIndex = GetBaseLayerIndexByName(layerName); return (layerIndex >= 0) ? &m_baseLayers[layerIndex] : nullptr; } TerrainLayerListGenerator::BaseLayer *TerrainLayerListGenerator::CreateBaseLayer(const char *layerName) { Assert(GetBaseLayerIndexByName(layerName) < 0); uint32 index; for (index = 0; index < TERRAIN_MAX_LAYERS; index++) { if (!m_baseLayers[index].Allocated) break; } if (index == TERRAIN_MAX_LAYERS) return nullptr; BaseLayer *pBaseLayer = &m_baseLayers[index]; pBaseLayer->Allocated = true; pBaseLayer->Name = layerName; pBaseLayer->pBaseMap = nullptr; pBaseLayer->pNormalMap = nullptr; pBaseLayer->TextureRepeatInterval = 1; // use a 1x1 white image for the base map pBaseLayer->pBaseMap = new Image(); pBaseLayer->pBaseMap->Create(TERRAIN_LAYER_LIST_INTERNAL_FORMAT, 1, 1, 1); Y_memset(pBaseLayer->pBaseMap->GetData(), 0xFF, pBaseLayer->pBaseMap->GetDataSize()); // done return pBaseLayer; } void TerrainLayerListGenerator::DeleteBaseLayer(uint32 index) { Assert(index < TERRAIN_MAX_LAYERS && m_baseLayers[index].Allocated); BaseLayer *pBaseLayer = &m_baseLayers[index]; delete pBaseLayer->pBaseMap; delete pBaseLayer->pNormalMap; pBaseLayer->Name.Obliterate(); pBaseLayer->pBaseMap = nullptr; pBaseLayer->pNormalMap = nullptr; pBaseLayer->TextureRepeatInterval = 0; } bool TerrainLayerListGenerator::SetBaseLayerBaseMap(uint32 index, const Image *pImage) { BaseLayer *pBaseLayer = &m_baseLayers[index]; DebugAssert(pBaseLayer->Allocated); Image *pNewImage = nullptr; if (pImage != nullptr) { pNewImage = new Image(); if (pImage->GetPixelFormat() != TERRAIN_LAYER_LIST_INTERNAL_FORMAT) { if (!pNewImage->CopyAndConvertPixelFormat(*pImage, TERRAIN_LAYER_LIST_INTERNAL_FORMAT)) { delete pNewImage; return false; } } else { pNewImage->Copy(*pImage); } } delete pBaseLayer->pBaseMap; pBaseLayer->pBaseMap = pNewImage; return true; } bool TerrainLayerListGenerator::SetBaseLayerNormalMap(uint32 index, const Image *pImage) { BaseLayer *pBaseLayer = &m_baseLayers[index]; DebugAssert(pBaseLayer->Allocated); Image *pNewImage = nullptr; if (pImage != nullptr) { pNewImage = new Image(); if (pImage->GetPixelFormat() != TERRAIN_LAYER_LIST_INTERNAL_FORMAT) { if (!pNewImage->CopyAndConvertPixelFormat(*pImage, TERRAIN_LAYER_LIST_INTERNAL_FORMAT)) { delete pNewImage; return false; } } else { pNewImage->Copy(*pImage); } } delete pBaseLayer->pNormalMap; pBaseLayer->pNormalMap = pNewImage; return true; } class TerrainLayerListCompiler { public: TerrainLayerListCompiler(const TerrainLayerListGenerator *pGenerator); ~TerrainLayerListCompiler(); bool Compile(ByteStream *pOutputStream); private: struct TextureEntry { uint32 Index; TextureGenerator GeneratedTexture; }; struct BaseLayerEntry { uint32 Index; String Name; uint32 TextureRepeatInterval; int32 BaseTextureIndex; int32 BaseTextureArrayIndex; int32 NormalTextureIndex; int32 NormalTextureArrayIndex; }; bool CopyResizeInsertNullNormalMapTexture(uint32 resolution, TextureEntry *pDestinationTexture, int32 *pArrayIndex, int32 *pTextureIndex); bool CopyResizeInsertTexture(const Image *pImage, uint32 resolution, TextureEntry *pDestinationTexture, int32 *pArrayIndex, int32 *pTextureIndex); bool CompileBaseLayer(const TerrainLayerListGenerator::BaseLayer *pBaseLayer); bool GenerateTextureMipmaps(); bool WriteHeader(ByteStream *pStream); bool WriteTextures(ByteStream *pStream, ChunkFileWriter &cfw); bool WriteBaseLayers(ByteStream *pStream, ChunkFileWriter &cfw); const TerrainLayerListGenerator *m_pGenerator; PODArray<TextureEntry *> m_textures; PODArray<BaseLayerEntry *> m_baseLayers; int32 m_baseLayerCombinedBaseTexture; int32 m_baseLayerCombinedNormalTexture; int32 m_baseLayerCombinedNormalTextureNullArrayIndex; }; TerrainLayerListCompiler::TerrainLayerListCompiler(const TerrainLayerListGenerator *pGenerator) : m_pGenerator(pGenerator), m_baseLayerCombinedBaseTexture(-1), m_baseLayerCombinedNormalTexture(-1), m_baseLayerCombinedNormalTextureNullArrayIndex(-1) { } TerrainLayerListCompiler::~TerrainLayerListCompiler() { for (uint32 i = 0; i < m_textures.GetSize(); i++) delete m_textures[i]; for (uint32 i = 0; i < m_baseLayers.GetSize(); i++) delete m_baseLayers[i]; } bool TerrainLayerListCompiler::Compile(ByteStream *pOutputStream) { // add block types for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { const TerrainLayerListGenerator::BaseLayer *pBaseLayer = &m_pGenerator->m_baseLayers[i]; if (!pBaseLayer->Allocated) continue; if (!CompileBaseLayer(pBaseLayer)) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to compile base layer %u (%s)", i, pBaseLayer->Name.GetCharArray()); return false; } } if (!GenerateTextureMipmaps()) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to generate texture mipmaps."); return false; } if (!WriteHeader(pOutputStream)) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to write header."); return false; } // initialize chunk file writer ChunkFileWriter cfw; if (!cfw.Initialize(pOutputStream, DF_TERRAIN_LAYER_LIST_CHUNK_COUNT)) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to initialize chunk file writer."); return false; } if (!WriteTextures(pOutputStream, cfw)) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to write textures."); return false; } if (!WriteBaseLayers(pOutputStream, cfw)) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to write base layers."); return false; } // close chunk writer if (!cfw.Close() || pOutputStream->InErrorState()) { Log_ErrorPrintf("TerrainLayerListCompiler::Compile: Failed to close chunk file writer."); return false; } Log_DevPrintf("TerrainLayerListCompiler::Compile: Layer list compiled, size = %u bytes", (uint32)pOutputStream->GetSize()); return true; } bool TerrainLayerListCompiler::CopyResizeInsertNullNormalMapTexture(uint32 resolution, TextureEntry *pDestinationTexture, int32 *pArrayIndex, int32 *pTextureIndex) { // create a 1x1 rgb8 image, with the z set to 1 Image tempImage; tempImage.Create(TERRAIN_LAYER_LIST_INTERNAL_FORMAT, 1, 1, 1); tempImage.GetData()[0] = 0x00; tempImage.GetData()[1] = 0x00; tempImage.GetData()[2] = 0xFF; // pass through return CopyResizeInsertTexture(&tempImage, resolution, pDestinationTexture, pArrayIndex, pTextureIndex); } bool TerrainLayerListCompiler::CopyResizeInsertTexture(const Image *pImage, uint32 resolution, TextureEntry *pDestinationTexture, int32 *pArrayIndex, int32 *pTextureIndex) { // texture exists? bool isFirstImage = false; if (pDestinationTexture == nullptr) { // create it pDestinationTexture = new TextureEntry(); pDestinationTexture->Index = m_textures.GetSize(); m_textures.Add(pDestinationTexture); isFirstImage = true; // create the actual texture if (!pDestinationTexture->GeneratedTexture.Create(TEXTURE_TYPE_2D_ARRAY, TERRAIN_LAYER_LIST_INTERNAL_FORMAT, resolution, resolution, 1, 1)) return false; // set properties on it pDestinationTexture->GeneratedTexture.SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->GeneratedTexture.SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->GeneratedTexture.SetGenerateMipmaps(true); } // ensure it's in the correct format Image *pTempImage = new Image(); if (pImage->GetPixelFormat() == TERRAIN_LAYER_LIST_INTERNAL_FORMAT) { // just copy it in pTempImage->Copy(*pImage); } else { if (!pTempImage->CopyAndConvertPixelFormat(*pImage, TERRAIN_LAYER_LIST_INTERNAL_FORMAT)) { delete pTempImage; return false; } } // ensure it's the correct dimensions if ((pTempImage->GetWidth() != resolution || pTempImage->GetHeight() != resolution) && !pTempImage->Resize(IMAGE_RESIZE_FILTER_LANCZOS3, resolution, resolution, 1)) { delete pTempImage; return false; } // insert it into the texture bool result; int32 arrayIndex; if (isFirstImage) { arrayIndex = 0; result = pDestinationTexture->GeneratedTexture.SetImage(0, pTempImage); } else { arrayIndex = pDestinationTexture->GeneratedTexture.GetArraySize(); result = pDestinationTexture->GeneratedTexture.AddImage(pTempImage); } delete pTempImage; if (!result) return false; // store results *pArrayIndex = arrayIndex; *pTextureIndex = pDestinationTexture->Index; return true; } bool TerrainLayerListCompiler::CompileBaseLayer(const TerrainLayerListGenerator::BaseLayer *pBaseLayer) { BaseLayerEntry *pBaseLayerEntry = new BaseLayerEntry(); pBaseLayerEntry->Index = pBaseLayer->Index; pBaseLayerEntry->Name = pBaseLayer->Name; pBaseLayerEntry->TextureRepeatInterval = pBaseLayer->TextureRepeatInterval; pBaseLayerEntry->BaseTextureIndex = -1; pBaseLayerEntry->BaseTextureArrayIndex = -1; pBaseLayerEntry->NormalTextureIndex = -1; pBaseLayerEntry->NormalTextureArrayIndex = -1; m_baseLayers.Add(pBaseLayerEntry); // is normal mapping enabled? if (m_pGenerator->IsBaseLayerNormalMappingEnabled()) { // does this layer even have a normal map? if (pBaseLayer->pNormalMap != nullptr) { // add it to the combined texture if (m_baseLayerCombinedNormalTexture >= 0) { // add it to the combined texture if (!CopyResizeInsertTexture(pBaseLayer->pNormalMap, m_pGenerator->m_baseLayerNormalMapResolution, m_textures[m_baseLayerCombinedNormalTexture], &pBaseLayerEntry->NormalTextureArrayIndex, &m_baseLayerCombinedNormalTexture)) return false; } else { // create the combined texture if (!CopyResizeInsertTexture(pBaseLayer->pNormalMap, m_pGenerator->m_baseLayerNormalMapResolution, nullptr, &pBaseLayerEntry->NormalTextureArrayIndex, &m_baseLayerCombinedNormalTexture)) return false; } pBaseLayerEntry->NormalTextureIndex = m_baseLayerCombinedNormalTexture; } else { // use a 1x1 normal map with z pointing out if (m_baseLayerCombinedNormalTextureNullArrayIndex < 0) { // has combined texture? if (m_baseLayerCombinedNormalTexture >= 0) { // add it to the combined texture if (!CopyResizeInsertNullNormalMapTexture(m_pGenerator->m_baseLayerNormalMapResolution, m_textures[m_baseLayerCombinedNormalTexture], &m_baseLayerCombinedNormalTextureNullArrayIndex, &m_baseLayerCombinedNormalTexture)) return false; } else { // create the combined texture if (!CopyResizeInsertNullNormalMapTexture(m_pGenerator->m_baseLayerNormalMapResolution, nullptr, &m_baseLayerCombinedNormalTextureNullArrayIndex, &m_baseLayerCombinedNormalTexture)) return false; } } pBaseLayerEntry->NormalTextureIndex = m_baseLayerCombinedNormalTexture; pBaseLayerEntry->NormalTextureArrayIndex = m_baseLayerCombinedNormalTextureNullArrayIndex; } } // add the base layer to the combined texture if (m_baseLayerCombinedBaseTexture >= 0) { // add it to the combined texture if (!CopyResizeInsertTexture(pBaseLayer->pBaseMap, m_pGenerator->m_baseLayerNormalMapResolution, m_textures[m_baseLayerCombinedBaseTexture], &pBaseLayerEntry->BaseTextureArrayIndex, &m_baseLayerCombinedBaseTexture)) return false; } else { // create the combined texture if (!CopyResizeInsertTexture(pBaseLayer->pBaseMap, m_pGenerator->m_baseLayerNormalMapResolution, nullptr, &pBaseLayerEntry->BaseTextureArrayIndex, &m_baseLayerCombinedBaseTexture)) return false; } // store the texture index pBaseLayerEntry->BaseTextureIndex = m_baseLayerCombinedBaseTexture; return true; } bool TerrainLayerListCompiler::GenerateTextureMipmaps() { uint32 i; for (i = 0; i < m_textures.GetSize(); i++) { TextureEntry *pSourceTextureEntry = m_textures[i]; TextureGenerator &sourceTextureGenerator = pSourceTextureEntry->GeneratedTexture; if (!sourceTextureGenerator.GenerateMipmaps()) return false; } return true; } bool TerrainLayerListCompiler::WriteHeader(ByteStream *pStream) { // determine array size uint32 baseLayerArraySize = 0; uint32 baseLayerCount = 0; for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { if (m_pGenerator->m_baseLayers[i].Allocated) { baseLayerArraySize = i + 1; baseLayerCount++; } } // write it out to the file DF_TERRAIN_LAYER_LIST_HEADER header; header.Magic = DF_TERRAIN_LAYER_LIST_HEADER_MAGIC; header.HeaderSize = sizeof(header); header.TextureCount = m_textures.GetSize(); header.BaseLayerArraySize = baseLayerArraySize; header.BaseLayerCount = baseLayerCount; header.CombinedBaseLayerBaseTextureIndex = m_baseLayerCombinedBaseTexture; header.CombinedBaseLayerNormalTextureIndex = m_baseLayerCombinedNormalTexture; if (!pStream->Write2(&header, sizeof(header))) return false; return true; } bool TerrainLayerListCompiler::WriteTextures(ByteStream *pStream, ChunkFileWriter &cfw) { // for textures cfw.BeginChunk(DF_TERRAIN_LAYER_LIST_CHUNK_TEXTURES); if (m_textures.GetSize() > 0) { ByteStream **ppGeneratedTextureStreams = new ByteStream *[m_textures.GetSize()]; uint32 nGeneratedTextureStreams = 0; uint32 nUsedTextureStreams = 0; for (uint32 i = 0; i < m_textures.GetSize(); i++) { Log_DevPrintf("Compiling terrain layer list internal texture %u...", i); // TEMP m_textures[i]->GeneratedTexture.SetEnableTextureCompression(false); ppGeneratedTextureStreams[nGeneratedTextureStreams] = ByteStream_CreateGrowableMemoryStream(NULL, 0); if (!m_textures[nGeneratedTextureStreams]->GeneratedTexture.Compile(ppGeneratedTextureStreams[nGeneratedTextureStreams])) { delete[] ppGeneratedTextureStreams; return false; } nGeneratedTextureStreams++; } uint32 currentTextureOffset = sizeof(DF_TERRAIN_LAYER_LIST_TEXTURE) * m_textures.GetSize(); for (uint32 i = 0; i < m_textures.GetSize(); i++) { DF_TERRAIN_LAYER_LIST_TEXTURE outTexture; outTexture.TextureOffset = currentTextureOffset; outTexture.TextureSize = (uint32)ppGeneratedTextureStreams[nUsedTextureStreams]->GetSize(); currentTextureOffset += outTexture.TextureSize; nUsedTextureStreams++; cfw.WriteChunkData(&outTexture, sizeof(outTexture)); } // write texture data DebugAssert(nUsedTextureStreams == nGeneratedTextureStreams); for (uint32 i = 0; i < nUsedTextureStreams; i++) { static const uint32 CHUNKSIZE = 4096; byte buffer[CHUNKSIZE]; ByteStream *pTextureStream = ppGeneratedTextureStreams[i]; uint32 remaining = (uint32)pTextureStream->GetSize(); pTextureStream->SeekAbsolute(0); while (remaining > 0) { uint32 toCopy = Min(CHUNKSIZE, remaining); if (!pTextureStream->Read2(buffer, toCopy)) { delete[] ppGeneratedTextureStreams; return false; } remaining -= toCopy; cfw.WriteChunkData(buffer, toCopy); } pTextureStream->Release(); } delete[] ppGeneratedTextureStreams; } cfw.EndChunk(); return true; } bool TerrainLayerListCompiler::WriteBaseLayers(ByteStream *pStream, ChunkFileWriter &cfw) { // for block types cfw.BeginChunk(DF_TERRAIN_LAYER_LIST_CHUNK_BASE_LAYERS); for (uint32 i = 0; i < m_baseLayers.GetSize(); i++) { const BaseLayerEntry *inBaseLayer = m_baseLayers[i]; DF_TERRAIN_LAYER_LIST_BASE_LAYER outBaseLayer; outBaseLayer.LayerIndex = inBaseLayer->Index; outBaseLayer.NameStringIndex = cfw.AddString(inBaseLayer->Name); outBaseLayer.TextureRepeatInterval = inBaseLayer->TextureRepeatInterval; outBaseLayer.BaseTextureIndex = inBaseLayer->BaseTextureIndex; outBaseLayer.BaseTextureArrayIndex = inBaseLayer->BaseTextureArrayIndex; outBaseLayer.NormalTextureIndex = inBaseLayer->NormalTextureIndex; outBaseLayer.NormalTextureArrayIndex = inBaseLayer->NormalTextureArrayIndex; cfw.WriteChunkData(&outBaseLayer, sizeof(outBaseLayer)); } cfw.EndChunk(); return true; } bool TerrainLayerListGenerator::Compile(ByteStream *pOutputStream) const { TerrainLayerListCompiler compiler(this); return compiler.Compile(pOutputStream); } // Interface BinaryBlob *ResourceCompiler::CompileTerrainLayerList(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.layerlist.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileTerrainLayerList: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); TerrainLayerListGenerator *pGenerator = new TerrainLayerListGenerator(); if (!pGenerator->Load(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Engine/ArcBallCamera.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ArcBallCamera.h" //Log_SetChannel(ArcBallCamera); ArcBallCamera::ArcBallCamera() : Camera() { m_target.SetZero(); m_eyeDistance = 1.0f; } ArcBallCamera::~ArcBallCamera() { } void ArcBallCamera::Reset() { m_position.SetZero(); m_rotation.SetIdentity(); m_target.SetZero(); m_eyeDistance = 1.0f; UpdateViewMatrix(); UpdateFrustum(); } void ArcBallCamera::RotateFromMouseMovement(int32 mouseDiffX, int32 mouseDiffY) { m_rotation = (m_rotation * Quaternion::FromEulerAngles(float(-mouseDiffY), 0.0f, float(-mouseDiffX))).Normalize(); UpdateArcBallViewMatrix(); } void ArcBallCamera::Update(const float &dt) { } void ArcBallCamera::UpdateArcBallViewMatrix() { m_position = m_target + m_rotation * float3(0.0f, m_eyeDistance, 0.0f); UpdateViewMatrix(); UpdateFrustum(); } // Vector3 ArcBallCamera::MapToSphere(const Vector2i &p) const // { // DebugAssert(m_iViewportWidth > 0 && m_iViewportHeight > 0); // Vector2 windowSize = Vector2(float(m_iViewportWidth - 1), float(m_iViewportHeight - 1)); // Vector2 scaler = Vector2::One / (windowSize * 0.5f); // // Vector2 temp = Vector2((float)p.x, (float)p.y) * scaler; // temp.x = temp.x - 1.0f; // temp.y = 1.0f - temp.y; // // float length = temp.SquaredLength(); // if (length > 1.0f) // { // float norm = 1.0f / Math::Sqrt(length); // return Vector3(temp, norm); // } // else // { // return Vector3(temp, Math::Sqrt(1.0f - length)); // } // } // <file_sep>/Engine/Source/ResourceCompiler/ResourceCompiler.h #pragma once #include "ResourceCompiler/Common.h" #include "ResourceCompiler/ResourceCompilerCallbacks.h" struct ShaderCompilerParameters; namespace ResourceCompiler { BinaryBlob *CompileTexture(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name); BinaryBlob *CompileMaterialShader(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileMaterial(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileFont(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name); BinaryBlob *CompileBlockPalette(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name); BinaryBlob *CompileStaticMesh(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileBlockMesh(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileSkeleton(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileSkeletalMesh(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileSkeletalAnimation(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileParticleSystem(ResourceCompilerCallbacks *pCallbacks, const char *name); BinaryBlob *CompileTerrainLayerList(ResourceCompilerCallbacks *pCallbacks, const char *name); bool CompileShader(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters, ByteStream *pByteCodeStream, ByteStream *pInfoLogStream); } <file_sep>/Editor/Source/Editor/moc_EditorResourceSaveDialog.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorResourceSaveDialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorResourceSaveDialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorResourceSaveDialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorResourceSaveDialog_t { QByteArrayData data[14]; char stringdata[269]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorResourceSaveDialog_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorResourceSaveDialog_t qt_meta_stringdata_EditorResourceSaveDialog = { { QT_MOC_LITERAL(0, 0, 24), // "EditorResourceSaveDialog" QT_MOC_LITERAL(1, 25, 28), // "OnDirectoryComboBoxActivated" QT_MOC_LITERAL(2, 54, 0), // "" QT_MOC_LITERAL(3, 55, 4), // "text" QT_MOC_LITERAL(4, 60, 19), // "OnBackButtonPressed" QT_MOC_LITERAL(5, 80, 26), // "OnUpDirectoryButtonPressed" QT_MOC_LITERAL(6, 107, 28), // "OnMakeDirectoryButtonPressed" QT_MOC_LITERAL(7, 136, 23), // "OnTreeViewItemActivated" QT_MOC_LITERAL(8, 160, 5), // "index" QT_MOC_LITERAL(9, 166, 21), // "OnTreeViewItemClicked" QT_MOC_LITERAL(10, 188, 29), // "OnResourceNameEditTextChanged" QT_MOC_LITERAL(11, 218, 8), // "contents" QT_MOC_LITERAL(12, 227, 19), // "OnSaveButtonClicked" QT_MOC_LITERAL(13, 247, 21) // "OnCancelButtonClicked" }, "EditorResourceSaveDialog\0" "OnDirectoryComboBoxActivated\0\0text\0" "OnBackButtonPressed\0OnUpDirectoryButtonPressed\0" "OnMakeDirectoryButtonPressed\0" "OnTreeViewItemActivated\0index\0" "OnTreeViewItemClicked\0" "OnResourceNameEditTextChanged\0contents\0" "OnSaveButtonClicked\0OnCancelButtonClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorResourceSaveDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 9, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 59, 2, 0x08 /* Private */, 4, 0, 62, 2, 0x08 /* Private */, 5, 0, 63, 2, 0x08 /* Private */, 6, 0, 64, 2, 0x08 /* Private */, 7, 1, 65, 2, 0x08 /* Private */, 9, 1, 68, 2, 0x08 /* Private */, 10, 1, 71, 2, 0x08 /* Private */, 12, 0, 74, 2, 0x08 /* Private */, 13, 0, 75, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QString, 3, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QModelIndex, 8, QMetaType::Void, QMetaType::QModelIndex, 8, QMetaType::Void, QMetaType::QString, 11, QMetaType::Void, QMetaType::Void, 0 // eod }; void EditorResourceSaveDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorResourceSaveDialog *_t = static_cast<EditorResourceSaveDialog *>(_o); switch (_id) { case 0: _t->OnDirectoryComboBoxActivated((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->OnBackButtonPressed(); break; case 2: _t->OnUpDirectoryButtonPressed(); break; case 3: _t->OnMakeDirectoryButtonPressed(); break; case 4: _t->OnTreeViewItemActivated((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 5: _t->OnTreeViewItemClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; case 6: _t->OnResourceNameEditTextChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 7: _t->OnSaveButtonClicked(); break; case 8: _t->OnCancelButtonClicked(); break; default: ; } } } const QMetaObject EditorResourceSaveDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_EditorResourceSaveDialog.data, qt_meta_data_EditorResourceSaveDialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorResourceSaveDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorResourceSaveDialog::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorResourceSaveDialog.stringdata)) return static_cast<void*>(const_cast< EditorResourceSaveDialog*>(this)); return QDialog::qt_metacast(_clname); } int EditorResourceSaveDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 9) qt_static_metacall(this, _c, _id, _a); _id -= 9; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 9) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 9; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/ResourceCompiler/ShaderCompiler.h #pragma once #include "ResourceCompiler/Common.h" #include "ResourceCompiler/ResourceCompilerCallbacks.h" #include "Renderer/RendererTypes.h" #include "Renderer/ShaderCompilerFrontend.h" class MaterialShaderGenerator; class ShaderGraphCompiler; class ShaderCompiler { public: ShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters); virtual ~ShaderCompiler(); // accessors const RENDERER_PLATFORM GetRendererPlatform() const { return m_eRendererPlatform; } const RENDERER_FEATURE_LEVEL GetRendererFeatureLevel() const { return m_eRendererFeatureLevel; } const uint32 GetShaderCompilerFlags() const { return m_iShaderCompilerFlags; } // intemediary functions void AddCompileMacro(const char *macroName, const char *macroValue); // compile bool Compile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream); // add material shader defines to shader graph void SetupShaderGraphCompiler(MaterialShaderGenerator *pMaterialShaderSource, ShaderGraphCompiler *pCompiler) const; // Helper methods for reading various include files. bool ReadIncludeFile(bool systemInclude, const char *filename, void **ppOutFileContents, uint32 *pOutFileLength); void FreeIncludeFile(void *pFileContents); // Platform entry points static ShaderCompiler *CreateD3D11ShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters); static ShaderCompiler *CreateOpenGLShaderCompiler(ResourceCompilerCallbacks *pCallbacks, const ShaderCompilerParameters *pParameters); protected: // actual compile method virtual bool InternalCompile(ByteStream *pByteCodeStream, ByteStream *pInfoLogStream) = 0; // add material shader defines void AddMaterialShaderDefines(); // in parameters ResourceCompilerCallbacks *m_pResourceCompilerCallbacks; BinaryBlob *m_pMaterialShaderCode; RENDERER_PLATFORM m_eRendererPlatform; RENDERER_FEATURE_LEVEL m_eRendererFeatureLevel; uint32 m_iShaderCompilerFlags; uint32 m_iMaterialShaderFlags; String m_StageFileNames[SHADER_PROGRAM_STAGE_COUNT]; String m_StageEntryPoints[SHADER_PROGRAM_STAGE_COUNT]; String m_VertexFactoryFileName; String m_MaterialShaderName; Array<ShaderCompilerParameters::PreprocessorMacro> m_CompileMacros; TextWriter *m_pDumpWriter; }; <file_sep>/Engine/Source/Engine/TerrainSectionCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" #include "Engine/TerrainSection.h" class TerrainSectionCollisionShape : public Physics::CollisionShape { public: TerrainSectionCollisionShape(const TerrainParameters *pParameters, const TerrainSection *pSectionData); ~TerrainSectionCollisionShape(); virtual const Physics::COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual Physics::CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; // get the transform for the specified parameters and section static Transform GetSectionTransform(const TerrainParameters *pParameters, const TerrainSection *pSectionData); private: AABox m_boundingBox; const TerrainSection *m_pSectionData; btCollisionShape *m_pBulletShape; }; <file_sep>/Engine/Source/D3D11Renderer/D3D11Defines.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11Common.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "D3D11Renderer/D3D11GPUTexture.h" Log_SetChannel(D3D11GPUDevice); Y_Define_NameTable(NameTables::D3DFeatureLevels) Y_NameTable_VEntry(D3D_FEATURE_LEVEL_9_1, "D3D_FEATURE_LEVEL_9_1") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_9_2, "D3D_FEATURE_LEVEL_9_2") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_9_3, "D3D_FEATURE_LEVEL_9_3") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_10_0, "D3D_FEATURE_LEVEL_10_0") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_10_1, "D3D_FEATURE_LEVEL_10_1") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_11_0, "D3D_FEATURE_LEVEL_11_0") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_11_1, "D3D_FEATURE_LEVEL_11_0") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_12_0, "D3D_FEATURE_LEVEL_12_0") Y_NameTable_VEntry(D3D_FEATURE_LEVEL_12_1, "D3D_FEATURE_LEVEL_12_1") Y_NameTable_End() static const DXGI_FORMAT s_PixelFormatToDXGIFormat[PIXEL_FORMAT_COUNT] = { DXGI_FORMAT_R8_UINT, // PIXEL_FORMAT_R8_UINT DXGI_FORMAT_R8_SINT, // PIXEL_FORMAT_R8_SINT DXGI_FORMAT_R8_UNORM, // PIXEL_FORMAT_R8_UNORM DXGI_FORMAT_R8_SNORM, // PIXEL_FORMAT_R8_SNORM DXGI_FORMAT_R8G8_UINT, // PIXEL_FORMAT_R8G8_UINT DXGI_FORMAT_R8G8_SINT, // PIXEL_FORMAT_R8G8_SINT DXGI_FORMAT_R8G8_UNORM, // PIXEL_FORMAT_R8G8_UNORM DXGI_FORMAT_R8G8_SNORM, // PIXEL_FORMAT_R8G8_SNORM DXGI_FORMAT_R8G8B8A8_UINT, // PIXEL_FORMAT_R8G8B8A8_UINT DXGI_FORMAT_R8G8B8A8_SINT, // PIXEL_FORMAT_R8G8B8A8_SINT DXGI_FORMAT_R8G8B8A8_UNORM, // PIXEL_FORMAT_R8G8B8A8_UNORM DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB DXGI_FORMAT_R8G8B8A8_SNORM, // PIXEL_FORMAT_R8G8B8A8_SNORM DXGI_FORMAT_R9G9B9E5_SHAREDEXP, // PIXEL_FORMAT_R9G9B9E5_SHAREDEXP DXGI_FORMAT_R10G10B10A2_UINT, // PIXEL_FORMAT_R10G10B10A2_UINT DXGI_FORMAT_R10G10B10A2_UNORM, // PIXEL_FORMAT_R10G10B10A2_UNORM DXGI_FORMAT_R11G11B10_FLOAT, // PIXEL_FORMAT_R11G11B10_FLOAT DXGI_FORMAT_R16_UINT, // PIXEL_FORMAT_R16_UINT DXGI_FORMAT_R16_SINT, // PIXEL_FORMAT_R16_SINT DXGI_FORMAT_R16_UNORM, // PIXEL_FORMAT_R16_UNORM DXGI_FORMAT_R16_SNORM, // PIXEL_FORMAT_R16_SNORM DXGI_FORMAT_R16_FLOAT, // PIXEL_FORMAT_R16_FLOAT DXGI_FORMAT_R16G16_UINT, // PIXEL_FORMAT_R16G16_UINT DXGI_FORMAT_R16G16_SINT, // PIXEL_FORMAT_R16G16_SINT DXGI_FORMAT_R16G16_UNORM, // PIXEL_FORMAT_R16G16_UNORM DXGI_FORMAT_R16G16_SNORM, // PIXEL_FORMAT_R16G16_SNORM DXGI_FORMAT_R16G16_FLOAT, // PIXEL_FORMAT_R16G16_FLOAT DXGI_FORMAT_R16G16B16A16_UINT, // PIXEL_FORMAT_R16G16B16A16_UINT DXGI_FORMAT_R16G16B16A16_SINT, // PIXEL_FORMAT_R16G16B16A16_SINT DXGI_FORMAT_R16G16B16A16_UNORM, // PIXEL_FORMAT_R16G16B16A16_UNORM DXGI_FORMAT_R16G16B16A16_SNORM, // PIXEL_FORMAT_R16G16B16A16_SNORM DXGI_FORMAT_R16G16B16A16_FLOAT, // PIXEL_FORMAT_R16G16B16A16_FLOAT DXGI_FORMAT_R32_UINT, // PIXEL_FORMAT_R32_UINT DXGI_FORMAT_R32_SINT, // PIXEL_FORMAT_R32_SINT DXGI_FORMAT_R32_FLOAT, // PIXEL_FORMAT_R32_FLOAT DXGI_FORMAT_R32G32_UINT, // PIXEL_FORMAT_R32G32_UINT DXGI_FORMAT_R32G32_SINT, // PIXEL_FORMAT_R32G32_SINT DXGI_FORMAT_R32G32_FLOAT, // PIXEL_FORMAT_R32G32_FLOAT DXGI_FORMAT_R32G32B32_UINT, // PIXEL_FORMAT_R32G32B32_UINT DXGI_FORMAT_R32G32B32_SINT, // PIXEL_FORMAT_R32G32B32_SINT DXGI_FORMAT_R32G32B32_FLOAT, // PIXEL_FORMAT_R32G32B32_FLOAT DXGI_FORMAT_R32G32B32A32_UINT, // PIXEL_FORMAT_R32G32B32A32_UINT DXGI_FORMAT_R32G32B32A32_SINT, // PIXEL_FORMAT_R32G32B32A32_SINT DXGI_FORMAT_R32G32B32A32_FLOAT, // PIXEL_FORMAT_R32G32B32A32_FLOAT DXGI_FORMAT_B8G8R8A8_UNORM, // PIXEL_FORMAT_B8G8R8A8_UNORM DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, // PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB DXGI_FORMAT_B8G8R8X8_UNORM, // PIXEL_FORMAT_B8G8R8X8_UNORM DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, // PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB DXGI_FORMAT_B5G6R5_UNORM, // PIXEL_FORMAT_B5G6R5_UNORM DXGI_FORMAT_B5G5R5A1_UNORM, // PIXEL_FORMAT_B5G5R5A1_UNORM DXGI_FORMAT_BC1_UNORM, // PIXEL_FORMAT_BC1_UNORM DXGI_FORMAT_BC1_UNORM_SRGB, // PIXEL_FORMAT_BC1_UNORM_SRGB DXGI_FORMAT_BC2_UNORM, // PIXEL_FORMAT_BC2_UNORM DXGI_FORMAT_BC2_UNORM_SRGB, // PIXEL_FORMAT_BC2_UNORM_SRGB DXGI_FORMAT_BC3_UNORM, // PIXEL_FORMAT_BC3_UNORM DXGI_FORMAT_BC3_UNORM_SRGB, // PIXEL_FORMAT_BC3_UNORM_SRGB DXGI_FORMAT_BC4_UNORM, // PIXEL_FORMAT_BC4_UNORM DXGI_FORMAT_BC4_SNORM, // PIXEL_FORMAT_BC4_SNORM DXGI_FORMAT_BC5_UNORM, // PIXEL_FORMAT_BC5_UNORM DXGI_FORMAT_BC5_SNORM, // PIXEL_FORMAT_BC5_SNORM DXGI_FORMAT_BC6H_UF16, // PIXEL_FORMAT_BC6H_UF16 DXGI_FORMAT_BC6H_SF16, // PIXEL_FORMAT_BC6H_SF16 DXGI_FORMAT_BC7_UNORM, // PIXEL_FORMAT_BC7_UNORM DXGI_FORMAT_BC7_UNORM_SRGB, // PIXEL_FORMAT_BC7_UNORM_SRGB DXGI_FORMAT_D16_UNORM, // PIXEL_FORMAT_D16_UNORM DXGI_FORMAT_D24_UNORM_S8_UINT, // PIXEL_FORMAT_D24_UNORM_S8_UINT DXGI_FORMAT_D32_FLOAT, // PIXEL_FORMAT_D32_FLOAT DXGI_FORMAT_D32_FLOAT_S8X24_UINT, // PIXEL_FORMAT_D32_FLOAT_S8X24_UINT DXGI_FORMAT_UNKNOWN, // PIXEL_FORMAT_R8G8B8_UNORM DXGI_FORMAT_UNKNOWN, // PIXEL_FORMAT_B8G8R8_UNORM }; static const D3D11_COMPARISON_FUNC s_D3D11ComparisonFuncs[GPU_COMPARISON_FUNC_COUNT] = { D3D11_COMPARISON_NEVER, // RENDERER_COMPARISON_FUNC_NEVER D3D11_COMPARISON_LESS, // RENDERER_COMPARISON_FUNC_LESS D3D11_COMPARISON_EQUAL, // RENDERER_COMPARISON_FUNC_EQUAL D3D11_COMPARISON_LESS_EQUAL, // RENDERER_COMPARISON_FUNC_LESS_EQUAL D3D11_COMPARISON_GREATER, // RENDERER_COMPARISON_FUNC_GREATER D3D11_COMPARISON_NOT_EQUAL, // RENDERER_COMPARISON_FUNC_NOT_EQUAL D3D11_COMPARISON_GREATER_EQUAL, // RENDERER_COMPARISON_FUNC_GREATER_EQUAL D3D11_COMPARISON_ALWAYS, // RENDERER_COMPARISON_FUNC_ALWAYS }; const char *D3D11TypeConversion::D3DFeatureLevelToString(D3D_FEATURE_LEVEL FeatureLevel) { return NameTable_GetNameString(NameTables::D3DFeatureLevels, FeatureLevel, "D3D_FEATURE_LEVEL_UNKNOWN"); } DXGI_FORMAT D3D11TypeConversion::PixelFormatToDXGIFormat(PIXEL_FORMAT Format) { return (Format < PIXEL_FORMAT_COUNT) ? s_PixelFormatToDXGIFormat[Format] : DXGI_FORMAT_UNKNOWN; } PIXEL_FORMAT D3D11TypeConversion::DXGIFormatToPixelFormat(DXGI_FORMAT Format) { uint32 i; for (i = 0; i < PIXEL_FORMAT_COUNT; i++) { if (s_PixelFormatToDXGIFormat[i] == Format) return (PIXEL_FORMAT)i; } return PIXEL_FORMAT_UNKNOWN; } D3D11_MAP D3D11TypeConversion::MapTypetoD3D11MapType(GPU_MAP_TYPE MapType) { static const D3D11_MAP D3D11MapTypes[GPU_MAP_TYPE_COUNT] = { D3D11_MAP_READ, // RENDERER_MAP_READ D3D11_MAP_READ_WRITE, // RENDERER_MAP_READ_WRITE D3D11_MAP_WRITE, // RENDERER_MAP_WRITE D3D11_MAP_WRITE_DISCARD, // RENDERER_MAP_WRITE_DISCARD D3D11_MAP_WRITE_NO_OVERWRITE, // RENDERER_MAP_WRITE_NO_OVERWRITE }; DebugAssert(MapType < GPU_MAP_TYPE_COUNT); return D3D11MapTypes[MapType]; } const char *D3D11TypeConversion::VertexElementSemanticToString(GPU_VERTEX_ELEMENT_SEMANTIC semantic) { // lookup table for semantics static const char *elementSemanticNameStrings[GPU_VERTEX_ELEMENT_SEMANTIC_COUNT] = { "POSITION", // GPU_VERTEX_ELEMENT_SEMANTIC_POSITION "TEXCOORD", // GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD "COLOR", // GPU_VERTEX_ELEMENT_SEMANTIC_COLOR "TANGENT", // GPU_VERTEX_ELEMENT_SEMANTIC_TANGENT "BINORMAL", // GPU_VERTEX_ELEMENT_SEMANTIC_BINORMAL "NORMAL", // GPU_VERTEX_ELEMENT_SEMANTIC_NORMAL "POINTSIZE", // GPU_VERTEX_ELEMENT_SEMANTIC_POINTSIZE "BLENDINDICES", // GPU_VERTEX_ELEMENT_SEMANTIC_BLENDINDICES "BLENDWEIGHTS", // GPU_VERTEX_ELEMENT_SEMANTIC_BLENDWEIGHTS }; DebugAssert(semantic < GPU_VERTEX_ELEMENT_SEMANTIC_COUNT); return elementSemanticNameStrings[semantic]; } const char *D3D11TypeConversion::VertexElementTypeToShaderTypeString(GPU_VERTEX_ELEMENT_TYPE type) { // lookup table for types static const char *elementTypeNameStrings[GPU_VERTEX_ELEMENT_TYPE_COUNT] = { "int", // GPU_VERTEX_ELEMENT_TYPE_BYTE "int2", // GPU_VERTEX_ELEMENT_TYPE_BYTE2 "int4", // GPU_VERTEX_ELEMENT_TYPE_BYTE4 "uint", // GPU_VERTEX_ELEMENT_TYPE_UBYTE "uint2", // GPU_VERTEX_ELEMENT_TYPE_UBYTE2 "uint4", // GPU_VERTEX_ELEMENT_TYPE_UBYTE4 "half", // GPU_VERTEX_ELEMENT_TYPE_HALF "half2", // GPU_VERTEX_ELEMENT_TYPE_HALF2 "half4", // GPU_VERTEX_ELEMENT_TYPE_HALF4 "float", // GPU_VERTEX_ELEMENT_TYPE_FLOAT "float2", // GPU_VERTEX_ELEMENT_TYPE_FLOAT2 "float3", // GPU_VERTEX_ELEMENT_TYPE_FLOAT3 "float4", // GPU_VERTEX_ELEMENT_TYPE_FLOAT4 "int", // GPU_VERTEX_ELEMENT_TYPE_INT "int2", // GPU_VERTEX_ELEMENT_TYPE_INT2 "int3", // GPU_VERTEX_ELEMENT_TYPE_INT3 "int4", // GPU_VERTEX_ELEMENT_TYPE_INT4 "uint", // GPU_VERTEX_ELEMENT_TYPE_UINT "uint2", // GPU_VERTEX_ELEMENT_TYPE_UINT2 "uint3", // GPU_VERTEX_ELEMENT_TYPE_UINT3 "uint4", // GPU_VERTEX_ELEMENT_TYPE_UINT4 "float4", // GPU_VERTEX_ELEMENT_TYPE_SNORM4 "float4", // GPU_VERTEX_ELEMENT_TYPE_UNORM4 }; DebugAssert(type < GPU_VERTEX_ELEMENT_TYPE_COUNT); return elementTypeNameStrings[type]; } DXGI_FORMAT D3D11TypeConversion::VertexElementTypeToDXGIFormat(GPU_VERTEX_ELEMENT_TYPE type) { // lookup table for types static const DXGI_FORMAT elementTypeNameStrings[GPU_VERTEX_ELEMENT_TYPE_COUNT] = { DXGI_FORMAT_R8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE DXGI_FORMAT_R8G8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE2 DXGI_FORMAT_R8G8B8A8_SINT, // GPU_VERTEX_ELEMENT_TYPE_BYTE4 DXGI_FORMAT_R8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE DXGI_FORMAT_R8G8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE2 DXGI_FORMAT_R8G8B8A8_UINT, // GPU_VERTEX_ELEMENT_TYPE_UBYTE4 DXGI_FORMAT_R16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF DXGI_FORMAT_R16G16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF2 DXGI_FORMAT_R16G16B16A16_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_HALF4 DXGI_FORMAT_R32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT DXGI_FORMAT_R32G32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT2 DXGI_FORMAT_R32G32B32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT3 DXGI_FORMAT_R32G32B32A32_FLOAT, // GPU_VERTEX_ELEMENT_TYPE_FLOAT4 DXGI_FORMAT_R32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT DXGI_FORMAT_R32G32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT2 DXGI_FORMAT_R32G32B32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT3 DXGI_FORMAT_R32G32B32A32_SINT, // GPU_VERTEX_ELEMENT_TYPE_INT4 DXGI_FORMAT_R32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT DXGI_FORMAT_R32G32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT2 DXGI_FORMAT_R32G32B32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT3 DXGI_FORMAT_R32G32B32A32_UINT, // GPU_VERTEX_ELEMENT_TYPE_UINT4 DXGI_FORMAT_R8G8B8A8_SNORM, // GPU_VERTEX_ELEMENT_TYPE_SNORM4 DXGI_FORMAT_R8G8B8A8_UNORM, // GPU_VERTEX_ELEMENT_TYPE_UNORM4 }; DebugAssert(type < GPU_VERTEX_ELEMENT_TYPE_COUNT); return elementTypeNameStrings[type]; } ID3D11RasterizerState *D3D11Helpers::CreateD3D11RasterizerState(ID3D11Device *pD3DDevice, const RENDERER_RASTERIZER_STATE_DESC *pRasterizerState) { static const D3D11_FILL_MODE D3D11FillModes[RENDERER_FILL_MODE_COUNT] = { D3D11_FILL_WIREFRAME, // RENDERER_FILL_WIREFRAME D3D11_FILL_SOLID, // RENDERER_FILL_SOLID }; static const D3D11_CULL_MODE D3D11CullModes[RENDERER_CULL_MODE_COUNT] = { D3D11_CULL_NONE, // RENDERER_CULL_NONE D3D11_CULL_FRONT, // RENDERER_CULL_FRONT D3D11_CULL_BACK, // RENDERER_CULL_BACK }; DebugAssert(pRasterizerState->FillMode < RENDERER_FILL_MODE_COUNT); DebugAssert(pRasterizerState->CullMode < RENDERER_CULL_MODE_COUNT); D3D11_RASTERIZER_DESC RasterizerDesc; RasterizerDesc.FillMode = D3D11FillModes[pRasterizerState->FillMode]; RasterizerDesc.CullMode = D3D11CullModes[pRasterizerState->CullMode]; RasterizerDesc.FrontCounterClockwise = pRasterizerState->FrontCounterClockwise ? TRUE : FALSE; RasterizerDesc.DepthBias = pRasterizerState->DepthBias; RasterizerDesc.DepthBiasClamp = 0; RasterizerDesc.SlopeScaledDepthBias = pRasterizerState->SlopeScaledDepthBias; RasterizerDesc.DepthClipEnable = pRasterizerState->DepthClipEnable ? TRUE : FALSE; RasterizerDesc.ScissorEnable = pRasterizerState->ScissorEnable ? TRUE : FALSE; RasterizerDesc.MultisampleEnable = FALSE; RasterizerDesc.AntialiasedLineEnable = FALSE; ID3D11RasterizerState *pD3DRasterizerState; HRESULT hResult = pD3DDevice->CreateRasterizerState(&RasterizerDesc, &pD3DRasterizerState); if (SUCCEEDED(hResult)) { return pD3DRasterizerState; } else { Log_WarningPrintf("CreateRasterizerState failed with HResult %08X", hResult); return nullptr; } } ID3D11DepthStencilState *D3D11Helpers::CreateD3D11DepthStencilState(ID3D11Device *pD3DDevice, const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilState) { static const D3D11_STENCIL_OP D3D11StencilOps[RENDERER_STENCIL_OP_COUNT] = { D3D11_STENCIL_OP_KEEP, // RENDERER_STENCIL_OP_KEEP D3D11_STENCIL_OP_ZERO, // RENDERER_STENCIL_OP_ZERO D3D11_STENCIL_OP_REPLACE, // RENDERER_STENCIL_OP_REPLACE D3D11_STENCIL_OP_INCR_SAT, // RENDERER_STENCIL_OP_INCREMENT_CLAMPED D3D11_STENCIL_OP_DECR_SAT, // RENDERER_STENCIL_OP_DECREMENT_CLAMPED D3D11_STENCIL_OP_INVERT, // RENDERER_STENCIL_OP_INVERT D3D11_STENCIL_OP_INCR, // RENDERER_STENCIL_OP_INCREMENT D3D11_STENCIL_OP_DECR, // RENDERER_STENCIL_OP_DECREMENT }; DebugAssert(pDepthStencilState->DepthFunc < GPU_COMPARISON_FUNC_COUNT); D3D11_DEPTH_STENCIL_DESC DepthStencilDesc; DepthStencilDesc.DepthEnable = pDepthStencilState->DepthTestEnable ? TRUE : FALSE; DepthStencilDesc.DepthWriteMask = pDepthStencilState->DepthWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; DepthStencilDesc.DepthFunc = s_D3D11ComparisonFuncs[pDepthStencilState->DepthFunc]; DebugAssert(pDepthStencilState->StencilFrontFace.FailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.DepthFailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.PassOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilFrontFace.CompareFunc < GPU_COMPARISON_FUNC_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.FailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.DepthFailOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.PassOp < RENDERER_STENCIL_OP_COUNT); DebugAssert(pDepthStencilState->StencilBackFace.CompareFunc < GPU_COMPARISON_FUNC_COUNT); DepthStencilDesc.StencilEnable = pDepthStencilState->StencilTestEnable ? TRUE : FALSE; DepthStencilDesc.StencilReadMask = pDepthStencilState->StencilReadMask; DepthStencilDesc.StencilWriteMask = pDepthStencilState->StencilWriteMask; DepthStencilDesc.FrontFace.StencilFailOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.FailOp]; DepthStencilDesc.FrontFace.StencilDepthFailOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.DepthFailOp]; DepthStencilDesc.FrontFace.StencilPassOp = D3D11StencilOps[pDepthStencilState->StencilFrontFace.PassOp]; DepthStencilDesc.FrontFace.StencilFunc = s_D3D11ComparisonFuncs[pDepthStencilState->StencilFrontFace.CompareFunc]; DepthStencilDesc.BackFace.StencilFailOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.FailOp]; DepthStencilDesc.BackFace.StencilDepthFailOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.DepthFailOp]; DepthStencilDesc.BackFace.StencilPassOp = D3D11StencilOps[pDepthStencilState->StencilBackFace.PassOp]; DepthStencilDesc.BackFace.StencilFunc = s_D3D11ComparisonFuncs[pDepthStencilState->StencilBackFace.CompareFunc]; ID3D11DepthStencilState *pD3DDepthStencilState; HRESULT hResult = pD3DDevice->CreateDepthStencilState(&DepthStencilDesc, &pD3DDepthStencilState); if (SUCCEEDED(hResult)) { return pD3DDepthStencilState; } else { Log_WarningPrintf("CreateDepthStencilState failed with HResult %08X", hResult); return nullptr; } } ID3D11BlendState *D3D11Helpers::CreateD3D11BlendState(ID3D11Device *pD3DDevice, const RENDERER_BLEND_STATE_DESC *pBlendState) { static const D3D11_BLEND D3D11BlendOptions[RENDERER_BLEND_OPTION_COUNT] = { D3D11_BLEND_ZERO, // RENDERER_BLEND_ZERO D3D11_BLEND_ONE, // RENDERER_BLEND_ONE D3D11_BLEND_SRC_COLOR, // RENDERER_BLEND_SRC_COLOR D3D11_BLEND_INV_SRC_COLOR, // RENDERER_BLEND_INV_SRC_COLOR D3D11_BLEND_SRC_ALPHA, // RENDERER_BLEND_SRC_ALPHA D3D11_BLEND_INV_SRC_ALPHA, // RENDERER_BLEND_INV_SRC_ALPHA D3D11_BLEND_DEST_ALPHA, // RENDERER_BLEND_DEST_ALPHA D3D11_BLEND_INV_DEST_ALPHA, // RENDERER_BLEND_INV_DEST_ALPHA D3D11_BLEND_DEST_COLOR, // RENDERER_BLEND_DEST_COLOR D3D11_BLEND_INV_DEST_COLOR, // RENDERER_BLEND_INV_DEST_COLOR D3D11_BLEND_SRC_ALPHA_SAT, // RENDERER_BLEND_SRC_ALPHA_SAT D3D11_BLEND_BLEND_FACTOR, // RENDERER_BLEND_BLEND_FACTOR D3D11_BLEND_INV_BLEND_FACTOR, // RENDERER_BLEND_INV_BLEND_FACTOR D3D11_BLEND_SRC1_COLOR, // RENDERER_BLEND_SRC1_COLOR D3D11_BLEND_INV_SRC1_COLOR, // RENDERER_BLEND_INV_SRC1_COLOR D3D11_BLEND_SRC1_ALPHA, // RENDERER_BLEND_SRC1_ALPHA D3D11_BLEND_INV_SRC1_ALPHA, // RENDERER_BLEND_INV_SRC1_ALPHA }; static const D3D11_BLEND_OP D3D11BlendOps[RENDERER_BLEND_OP_COUNT] = { D3D11_BLEND_OP_ADD, // RENDERER_BLEND_OP_ADD D3D11_BLEND_OP_SUBTRACT, // RENDERER_BLEND_OP_SUBTRACT D3D11_BLEND_OP_REV_SUBTRACT, // RENDERER_BLEND_OP_REV_SUBTRACT D3D11_BLEND_OP_MIN, // RENDERER_BLEND_OP_MIN D3D11_BLEND_OP_MAX, // RENDERER_BLEND_OP_MAX }; DebugAssert(pBlendState->SrcBlend < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->BlendOp < RENDERER_BLEND_OP_COUNT); DebugAssert(pBlendState->DestBlend < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->SrcBlendAlpha < RENDERER_BLEND_OPTION_COUNT); DebugAssert(pBlendState->BlendOpAlpha < RENDERER_BLEND_OP_COUNT); DebugAssert(pBlendState->DestBlendAlpha < RENDERER_BLEND_OPTION_COUNT); D3D11_BLEND_DESC BlendDesc; BlendDesc.AlphaToCoverageEnable = FALSE; BlendDesc.IndependentBlendEnable = FALSE; for (uint32 i = 0; i < 8; i++) { BlendDesc.RenderTarget[i].BlendEnable = pBlendState->BlendEnable ? TRUE : FALSE; BlendDesc.RenderTarget[i].RenderTargetWriteMask = pBlendState->ColorWriteEnable ? D3D10_COLOR_WRITE_ENABLE_ALL : 0; BlendDesc.RenderTarget[i].SrcBlend = D3D11BlendOptions[pBlendState->SrcBlend]; BlendDesc.RenderTarget[i].BlendOp = D3D11BlendOps[pBlendState->BlendOp]; BlendDesc.RenderTarget[i].DestBlend = D3D11BlendOptions[pBlendState->DestBlend]; BlendDesc.RenderTarget[i].SrcBlendAlpha = D3D11BlendOptions[pBlendState->SrcBlendAlpha]; BlendDesc.RenderTarget[i].BlendOpAlpha = D3D11BlendOps[pBlendState->BlendOpAlpha]; BlendDesc.RenderTarget[i].DestBlendAlpha = D3D11BlendOptions[pBlendState->DestBlendAlpha]; } ID3D11BlendState *pD3DBlendState; HRESULT hResult = pD3DDevice->CreateBlendState(&BlendDesc, &pD3DBlendState); if (SUCCEEDED(hResult)) { return pD3DBlendState; } else { Log_WarningPrintf("CreateBlendState failed with HResult %08X", hResult); return nullptr; } } ID3D11SamplerState *D3D11Helpers::CreateD3D11SamplerState(ID3D11Device *pD3DDevice, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { static const D3D11_FILTER D3D11TextureFilters[TEXTURE_FILTER_COUNT] = { D3D11_FILTER_MIN_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR D3D11_FILTER_ANISOTROPIC, // RENDERER_TEXTURE_FILTER_ANISOTROPIC D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_POINT D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, // RENDERER_TEXTURE_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, // RENDERER_TEXTURE_FILTER_MIN_MAG_MIP_LINEAR D3D11_FILTER_COMPARISON_ANISOTROPIC, // RENDERER_TEXTURE_FILTER_ANISOTROPIC }; static const D3D11_TEXTURE_ADDRESS_MODE D3D11TextureAddresses[TEXTURE_ADDRESS_MODE_COUNT] = { D3D11_TEXTURE_ADDRESS_WRAP, // RENDERER_TEXTURE_ADDRESS_WRAP D3D11_TEXTURE_ADDRESS_MIRROR, // RENDERER_TEXTURE_ADDRESS_MIRROR D3D11_TEXTURE_ADDRESS_CLAMP, // RENDERER_TEXTURE_ADDRESS_CLAMP D3D11_TEXTURE_ADDRESS_BORDER, // RENDERER_TEXTURE_ADDRESS_BORDER D3D11_TEXTURE_ADDRESS_MIRROR_ONCE, // RENDERER_TEXTURE_ADDRESS_MIRROR_ONCE }; DebugAssert(pSamplerStateDesc->Filter < TEXTURE_FILTER_COUNT); DebugAssert(pSamplerStateDesc->AddressU < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->AddressV < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->AddressW < TEXTURE_ADDRESS_MODE_COUNT); DebugAssert(pSamplerStateDesc->ComparisonFunc < GPU_COMPARISON_FUNC_COUNT); D3D11_SAMPLER_DESC SamplerDesc; SamplerDesc.Filter = D3D11TextureFilters[pSamplerStateDesc->Filter]; SamplerDesc.AddressU = D3D11TextureAddresses[pSamplerStateDesc->AddressU]; SamplerDesc.AddressV = D3D11TextureAddresses[pSamplerStateDesc->AddressV]; SamplerDesc.AddressW = D3D11TextureAddresses[pSamplerStateDesc->AddressW]; Y_memcpy(SamplerDesc.BorderColor, &pSamplerStateDesc->BorderColor, sizeof(float) * 4); SamplerDesc.MipLODBias = pSamplerStateDesc->LODBias; SamplerDesc.MinLOD = (float)pSamplerStateDesc->MinLOD; SamplerDesc.MaxLOD = (float)pSamplerStateDesc->MaxLOD; SamplerDesc.MaxAnisotropy = pSamplerStateDesc->MaxAnisotropy; SamplerDesc.ComparisonFunc = s_D3D11ComparisonFuncs[pSamplerStateDesc->ComparisonFunc]; // create the state ID3D11SamplerState *pSamplerState; HRESULT hResult = pD3DDevice->CreateSamplerState(&SamplerDesc, &pSamplerState); if (FAILED(hResult)) { Log_WarningPrintf("CreateSamplerState failed with HResult %08X", hResult); return nullptr; } return pSamplerState; } ID3D11ShaderResourceView *D3D11Helpers::GetResourceShaderResourceView(GPUResource *pResource) { if (pResource == nullptr) return nullptr; switch (pResource->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE1D: return static_cast<D3D11GPUTexture1D *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: return static_cast<D3D11GPUTexture1DArray *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<D3D11GPUTexture2D *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<D3D11GPUTexture2DArray *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURE3D: return static_cast<D3D11GPUTexture3D *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURECUBE: return static_cast<D3D11GPUTextureCube *>(pResource)->GetD3DSRV(); case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: return static_cast<D3D11GPUTextureCubeArray *>(pResource)->GetD3DSRV(); } return nullptr; } ID3D11SamplerState *D3D11Helpers::GetResourceSamplerState(GPUResource *pResource) { if (pResource == nullptr) return nullptr; switch (pResource->GetResourceType()) { case GPU_RESOURCE_TYPE_SAMPLER_STATE: return static_cast<D3D11SamplerState *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURE1D: return static_cast<D3D11GPUTexture1D *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURE1DARRAY: return static_cast<D3D11GPUTexture1DArray *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURE2D: return static_cast<D3D11GPUTexture2D *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURE2DARRAY: return static_cast<D3D11GPUTexture2DArray *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURE3D: return static_cast<D3D11GPUTexture3D *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURECUBE: return static_cast<D3D11GPUTextureCube *>(pResource)->GetD3DSamplerState(); case GPU_RESOURCE_TYPE_TEXTURECUBEARRAY: return static_cast<D3D11GPUTextureCubeArray *>(pResource)->GetD3DSamplerState(); } return nullptr; } void D3D11Helpers::SetD3D11DeviceChildDebugName(ID3D11DeviceChild *pDeviceChild, const char *debugName) { #ifdef Y_BUILD_CONFIG_DEBUG uint32 nameLength = Y_strlen(debugName); if (nameLength > 0) pDeviceChild->SetPrivateData(WKPDID_D3DDebugObjectName, nameLength, debugName); #endif } <file_sep>/Engine/Source/D3D12Renderer/D3D12DescriptorHeap.h #pragma once #include "D3D12Renderer/D3D12Common.h" struct D3D12DescriptorHandle { D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle; D3D12_CPU_DESCRIPTOR_HANDLE CPUHandle; D3D12_DESCRIPTOR_HEAP_TYPE Type; uint32 StartIndex; uint32 DescriptorCount; uint32 IncrementSize; // constructors D3D12DescriptorHandle() { Y_memzero(this, sizeof(*this)); } D3D12DescriptorHandle(const D3D12DescriptorHandle &handle) { Y_memcpy(this, &handle, sizeof(*this)); } D3D12DescriptorHandle &operator=(const D3D12DescriptorHandle &handle) { Y_memcpy(this, &handle, sizeof(*this)); return *this; } void Clear() { Y_memzero(this, sizeof(*this)); } // Helper functions D3D12_CPU_DESCRIPTOR_HANDLE GetOffsetCPUHandle(uint32 index) const; D3D12_GPU_DESCRIPTOR_HANDLE GetOffsetGPUHandle(uint32 index) const; bool IsNull() const { return (DescriptorCount == 0); } // Get this handle operator D3D12_CPU_DESCRIPTOR_HANDLE () const { return CPUHandle; } operator D3D12_GPU_DESCRIPTOR_HANDLE () const { return GPUHandle; } // Comparisons bool operator==(const D3D12DescriptorHandle &handle) const { return (CPUHandle.ptr == handle.CPUHandle.ptr && Type == handle.Type); } bool operator|=(const D3D12DescriptorHandle &handle) const { return (CPUHandle.ptr != handle.CPUHandle.ptr || Type != handle.Type); } }; class D3D12DescriptorHeap { public: ~D3D12DescriptorHeap(); static D3D12DescriptorHeap *Create(ID3D12Device *pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 descriptorCount, bool cpuOnly); ID3D12DescriptorHeap *GetD3DHeap() const { return m_pD3DDescriptorHeap; } bool Allocate(D3D12DescriptorHandle *handle); bool AllocateRange(uint32 count, D3D12DescriptorHandle *handle); void Free(D3D12DescriptorHandle &handle); private: D3D12DescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE type, uint32 descriptorCount, ID3D12DescriptorHeap *pD3DDescriptorHeap, uint32 incrementSize); D3D12_DESCRIPTOR_HEAP_TYPE m_type; uint32 m_descriptorCount; ID3D12DescriptorHeap *m_pD3DDescriptorHeap; D3D12_CPU_DESCRIPTOR_HANDLE m_CPUHandleStart; D3D12_GPU_DESCRIPTOR_HANDLE m_GPUHandleStart; BitSet32 m_allocationMap; uint32 m_incrementSize; Mutex m_mutex; }; <file_sep>/Engine/Source/GameFramework/SpriteComponent.h /* enum SYNCHRONIZATION_MASK { SYNCHRONIZATION_MASK_VISIBILITY_BIT = (1 << 0), SYNCHRONIZATION_MASK_TEXTURE_BIT = (1 << 1), SYNCHRONIZATION_MASK_POSITION_BIT = (1 << 2), SYNCHRONIZATION_MASK_SIZE_BIT = (1 << 3), SYNCHRONIZATION_MASK_SHADOW_FLAGS_BIT = (1 << 4), SYNCHRONIZATION_MASK_TINT_BIT = (1 << 5), }; */ <file_sep>/Engine/Source/Renderer/WorldRenderers/DeferredShadingWorldRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/DeferredShadingWorldRenderer.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/WorldRenderers/CubeMapShadowMapRenderer.h" #include "Renderer/Renderer.h" #include "Renderer/RenderWorld.h" #include "Renderer/ShaderProgram.h" #include "Renderer/ShaderProgramSelector.h" #include "Renderer/Shaders/DepthOnlyShader.h" #include "Renderer/Shaders/ForwardShadingShaders.h" #include "Renderer/Shaders/DeferredShadingShaders.h" #include "Renderer/Shaders/SSAOShader.h" #include "Engine/Material.h" #include "Engine/EngineCVars.h" #include "Engine/Texture.h" #include "Engine/ResourceManager.h" #include "Engine/Profiling.h" #include "MathLib/CollisionDetection.h" #include "Core/MeshUtilties.h" Log_SetChannel(DeferredShadingWorldRenderer); DeferredShadingWorldRenderer::DeferredShadingWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : CompositingWorldRenderer(pGPUContext, pOptions), m_pDirectionalShadowMapRenderer(nullptr), m_pPointShadowMapRenderer(nullptr), m_pSpotShadowMapRenderer(nullptr), m_lastDirectionalLightIndex(0xFFFFFFFF), m_lastPointLightIndex(0xFFFFFFFF), m_lastSpotLightIndex(0xFFFFFFFF), m_lastVolumetricLightIndex(0xFFFFFFFF), m_directionalLightShaderFlags(DirectionalLightShader::CalculateFlags(pOptions->EnableShadows, pOptions->EnableHardwareShadowFiltering, pOptions->ShadowMapFiltering, pOptions->ShowShadowMapCascades)), m_pointLightShaderFlags(PointLightShader::CalculateFlags(pOptions->EnableShadows, pOptions->EnableHardwareShadowFiltering)), m_spotLightShaderFlags(0), m_pSceneColorBuffer(nullptr), m_pSceneColorBufferCopy(nullptr), m_pSceneDepthBuffer(nullptr), m_pSceneDepthBufferCopy(nullptr), m_pGBuffer0(nullptr), m_pGBuffer1(nullptr), m_pGBuffer2(nullptr), m_pPointLightVolumeVertexBuffer(nullptr), m_pSpotLightVolumeVertexBuffer(nullptr), m_pointLightVolumeVertexCount(0), m_pSSAOProgram(nullptr) { // render passes that we can draw static const uint32 availableRenderPassMask = RENDER_PASS_LIGHTMAP | RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING | RENDER_PASS_OCCLUSION_CULLING_PROXY | RENDER_PASS_TINT; // set up render queue m_renderQueue.SetAcceptingLights(true); m_renderQueue.SetAcceptingRenderPassMask(availableRenderPassMask); m_renderQueue.SetAcceptingOccluders((pOptions->EnableOcclusionCulling | pOptions->EnableOcclusionPredication) != 0); m_renderQueue.SetAcceptingDebugObjects(pOptions->ShowDebugInfo); } DeferredShadingWorldRenderer::~DeferredShadingWorldRenderer() { // release intermediate buffers ReleaseIntermediateBuffer(m_pSceneColorBuffer); ReleaseIntermediateBuffer(m_pSceneDepthBuffer); ReleaseIntermediateBuffer(m_pGBuffer0); ReleaseIntermediateBuffer(m_pGBuffer1); ReleaseIntermediateBuffer(m_pGBuffer2); // delete cached shadow maps for (uint32 i = 0; i < m_directionalShadowMaps.GetSize(); i++) { m_pDirectionalShadowMapRenderer->FreeShadowMap(m_directionalShadowMaps[i]); delete m_directionalShadowMaps[i]; } m_directionalShadowMaps.Clear(); for (uint32 i = 0; i < m_pointShadowMaps.GetSize(); i++) { m_pPointShadowMapRenderer->FreeShadowMap(m_pointShadowMaps[i]); delete m_pointShadowMaps[i]; } m_pointShadowMaps.Clear(); for (uint32 i = 0; i < m_spotShadowMaps.GetSize(); i++) { m_spotShadowMaps[i]->pShadowMapTexture->Release(); } m_spotShadowMaps.Clear(); // delete shadow map renderers delete m_pDirectionalShadowMapRenderer; delete m_pPointShadowMapRenderer; delete m_pSpotShadowMapRenderer; // delete light volume vertex buffers SAFE_RELEASE(m_pSpotLightVolumeVertexBuffer); SAFE_RELEASE(m_pPointLightVolumeVertexBuffer); } bool DeferredShadingWorldRenderer::Initialize() { if (!CompositingWorldRenderer::Initialize()) return false; // find programs if ((m_pSSAOProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(SSAOShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr || (m_pSSAOApplyProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(SSAOApplyShader), 0, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0)) == nullptr) { return false; } // allocate intermediate buffers if ((m_pSceneColorBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, LIGHTBUFFER_FORMAT, 1)) == nullptr || (m_pSceneDepthBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, DEPTHBUFFER_FORMAT, 1)) == nullptr || (m_pGBuffer0 = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, GBUFFER0_FORMAT, 1)) == nullptr || (m_pGBuffer1 = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, GBUFFER1_FORMAT, 1)) == nullptr || (m_pGBuffer2 = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, GBUFFER2_FORMAT, 1)) == nullptr) { return false; } #ifdef Y_BUILD_CONFIG_DEBUG m_pSceneColorBuffer->pTexture->SetDebugName("Deferred Light Buffer"); m_pSceneDepthBuffer->pTexture->SetDebugName("Deferred Depth Buffer"); m_pGBuffer0->pTexture->SetDebugName("Deferred GBuffer 0"); m_pGBuffer1->pTexture->SetDebugName("Deferred GBuffer 1"); m_pGBuffer2->pTexture->SetDebugName("Deferred GBuffer 2"); #endif // point light volume vertex buffer { float3 *pVertices; uint32 nVertices; MeshUtilites::CreateSphere(&pVertices, &nVertices); DebugAssert(nVertices > 0); // can be passed straight through to the gpu, ehh on float3 alignment GPU_BUFFER_DESC vertexBufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER, nVertices * sizeof(float3)); if ((m_pPointLightVolumeVertexBuffer = g_pRenderer->CreateBuffer(&vertexBufferDesc, pVertices)) == nullptr) { delete[] pVertices; return false; } // set vertex count m_pointLightVolumeVertexCount = nVertices; delete[] pVertices; } // create shadow map renderers if (m_options.EnableShadows) { m_pDirectionalShadowMapRenderer = new DirectionalShadowMapRenderer(m_options.DirectionalShadowMapResolution, m_options.ShadowMapPixelFormat, m_options.ShadowMapCascadeCount, 0.95f); m_pPointShadowMapRenderer = new PointShadowMapRenderer(m_options.PointShadowMapResolution, m_options.ShadowMapPixelFormat); m_pSpotShadowMapRenderer = new SpotShadowMapRenderer(m_options.SpotShadowMapResolution, m_options.ShadowMapPixelFormat); } // all done return true; } void DeferredShadingWorldRenderer::DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawWorld", MICROPROFILE_COLOR(255, 100, 100)); // add the main camera //RENDER_PROFILER_ADD_CAMERA(pRenderProfiler, &pViewParameters->ViewCamera, "World View Camera"); // culling FillRenderQueue(&pViewParameters->ViewCamera, pRenderWorld); // draw shadow maps DrawShadowMaps(pRenderWorld, pViewParameters); // pull occlusion results back from gpu if (m_options.EnableOcclusionCulling) CollectOcclusionCullingResults(); else if (m_options.EnableOcclusionPredication) BindOcclusionQueriesToQueueEntries(); // draw main passes QueuePrimaryRenderPass([this, pRenderWorld, pViewParameters](GPUCommandList *pCommandList) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "MainRenderPass", MICROPROFILE_COLOR(100, 150, 75)); // clear render targets { // need a seperate viewport, skip color clear it'll be done when gbuffers are combined RENDERER_VIEWPORT bufferViewport(0, 0, m_options.RenderWidth, m_options.RenderHeight, 0.0f, 1.0f); pCommandList->SetRenderTargets(0, nullptr, m_pSceneDepthBuffer->pDSV); pCommandList->SetViewport(&bufferViewport); pCommandList->ClearTargets(false, true, true); // set up view-dependent constants GPUContextConstants *pConstants = pCommandList->GetConstants(); pConstants->SetFromCamera(pViewParameters->ViewCamera, false); pConstants->SetWorldTime(pViewParameters->WorldTime, false); pConstants->CommitChanges(); } // depth prepass if (m_options.EnableDepthPrepass) DrawDepthPrepass(pCommandList, pViewParameters); // gbuffer DrawGBuffers(pCommandList, pViewParameters); // if occlusion culling is enabled, draw proxies if ((m_options.EnableOcclusionCulling | m_options.EnableOcclusionPredication) != 0) DrawOcclusionCullingProxies(pCommandList, &pViewParameters->ViewCamera); // draw lights DrawLights(pCommandList, pViewParameters); // unlit objects //DrawUnlitObjects(pCommandList, pViewParameters); // apply AO if (m_options.EnableSSAO) ApplyAmbientOcclusion(pCommandList, pViewParameters); // apply fog if (pViewParameters->FogMode != RENDERER_FOG_MODE_NONE) ApplyFog(pCommandList, pViewParameters); // transparent objects DrawPostProcessAndTranslucentObjects(pCommandList, pViewParameters); }); // complete all passes and queue to device ExecuteRenderPasses(); // tonemap to present buffer ApplyFinalCompositePostProcess(pViewParameters, m_pSceneColorBuffer->pTexture, pRenderTargetView); // debug info - draw to backbuffer if (m_pGUIContext != nullptr) { if (m_options.ShowDebugInfo) DrawDebugInfo(&pViewParameters->ViewCamera); if (m_options.ShowIntermediateBuffers) DrawIntermediateBuffers(); } // frame complete m_pGPUContext->ClearState(true, true, true, true); OnFrameComplete(); } void DeferredShadingWorldRenderer::GetRenderStats(RenderStats *pRenderStats) const { CompositingWorldRenderer::GetRenderStats(pRenderStats); pRenderStats->ShadowMapCount = 0; for (uint32 i = 0; i < m_directionalShadowMaps.GetSize(); i++) { if (m_directionalShadowMaps[i]->IsActive) pRenderStats->ShadowMapCount++; } for (uint32 i = 0; i < m_pointShadowMaps.GetSize(); i++) { if (m_pointShadowMaps[i]->IsActive) pRenderStats->ShadowMapCount++; } for (uint32 i = 0; i < m_spotShadowMaps.GetSize(); i++) { if (m_spotShadowMaps[i]->IsActive) pRenderStats->ShadowMapCount++; } } void DeferredShadingWorldRenderer::OnFrameComplete() { CompositingWorldRenderer::OnFrameComplete(); // clear last indices m_lastDirectionalLightIndex = 0xFFFFFFFF; m_lastPointLightIndex = 0xFFFFFFFF; m_lastSpotLightIndex = 0xFFFFFFFF; m_lastVolumetricLightIndex = 0xFFFFFFFF; } void DeferredShadingWorldRenderer::DrawShadowMaps(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawShadowMaps", MICROPROFILE_COLOR(255, 100, 255)); // clear all shadow map states for (uint32 i = 0; i < m_directionalShadowMaps.GetSize(); i++) m_directionalShadowMaps[i]->IsActive = false; for (uint32 i = 0; i < m_pointShadowMaps.GetSize(); i++) m_pointShadowMaps[i]->IsActive = false; for (uint32 i = 0; i < m_spotShadowMaps.GetSize(); i++) m_spotShadowMaps[i]->IsActive = false; // directional lights { RenderQueue::DirectionalLightArray &directionalLights = m_renderQueue.GetDirectionalLightArray(); for (uint32 i = 0; i < directionalLights.GetSize(); i++) { RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight = &directionalLights[i]; if (pLight->ShadowFlags & LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) DrawDirectionalShadowMap(pRenderWorld, pViewParameters, pLight); } } // point lights { RenderQueue::PointLightArray &pointLights = m_renderQueue.GetPointLightArray(); for (uint32 i = 0; i < pointLights.GetSize(); i++) { RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight = &pointLights[i]; if (pLight->ShadowFlags & LIGHT_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS) DrawPointShadowMap(pRenderWorld, pViewParameters, pLight); } } // clear shaders/targets since the targets will be bound to inputs m_pGPUContext->ClearState(true, false, false, true); } bool DeferredShadingWorldRenderer::DrawDirectionalShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { if (m_pDirectionalShadowMapRenderer == nullptr) return false; // find a free directional shadow map uint32 shadowMapIndex = 0; for (; shadowMapIndex < m_directionalShadowMaps.GetSize(); shadowMapIndex++) { if (!m_directionalShadowMaps[shadowMapIndex]->IsActive) break; } // none found? if (shadowMapIndex == m_directionalShadowMaps.GetSize()) { // allocate it DirectionalShadowMapRenderer::ShadowMapData *pShadowMapData = new DirectionalShadowMapRenderer::ShadowMapData(); if (!m_pDirectionalShadowMapRenderer->AllocateShadowMap(pShadowMapData)) { delete pShadowMapData; return false; } m_directionalShadowMaps.Add(pShadowMapData); } // get shadow map data pointer DirectionalShadowMapRenderer::ShadowMapData *pShadowMapData = m_directionalShadowMaps[shadowMapIndex]; pShadowMapData->IsActive = true; // bind the shadow map to the light pLight->ShadowMapIndex = shadowMapIndex; // pass on to the sm renderer QueueSecondaryRenderPass([this, pRenderWorld, pViewParameters, pLight, pShadowMapData](GPUCommandList *pCommandList) { m_pDirectionalShadowMapRenderer->DrawShadowMap(pCommandList, pShadowMapData, &pViewParameters->ViewCamera, pViewParameters->MaximumShadowViewDistance, pRenderWorld, pLight); }); // add debug view AddDebugBufferView(pShadowMapData->pShadowMapTexture, "DirectionalShadowMap"); // ok return true; } bool DeferredShadingWorldRenderer::DrawPointShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight) { if (m_pPointShadowMapRenderer == nullptr) return false; // find a free directional shadow map uint32 shadowMapIndex = 0; for (; shadowMapIndex < m_pointShadowMaps.GetSize(); shadowMapIndex++) { if (!m_pointShadowMaps[shadowMapIndex]->IsActive) break; } // none found? if (shadowMapIndex == m_pointShadowMaps.GetSize()) { // allocate it PointShadowMapRenderer::ShadowMapData *pShadowMapData = new PointShadowMapRenderer::ShadowMapData(); if (!m_pPointShadowMapRenderer->AllocateShadowMap(pShadowMapData)) return false; m_pointShadowMaps.Add(pShadowMapData); } // get shadow map data pointer PointShadowMapRenderer::ShadowMapData *pShadowMapData = m_pointShadowMaps[shadowMapIndex]; pShadowMapData->IsActive = true; // bind the shadow map to the light pLight->ShadowMapIndex = shadowMapIndex; // pass on to the sm renderer QueueSecondaryRenderPass([this, pRenderWorld, pViewParameters, pLight, pShadowMapData](GPUCommandList *pCommandList) { m_pPointShadowMapRenderer->DrawShadowMap(pCommandList, pShadowMapData, &pViewParameters->ViewCamera, pViewParameters->MaximumShadowViewDistance, pRenderWorld, pLight); }); // ok return true; } bool DeferredShadingWorldRenderer::DrawSpotShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight) { return false; } void DeferredShadingWorldRenderer::SetCommonShaderProgramParameters(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram) { pQueueEntry->pMaterial->BindDeviceResources(pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, pCommandList, pShaderProgram); // post process material? const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); if (pMaterialShader->GetRenderMode() == MATERIAL_RENDER_MODE_POST_PROCESS) { // set post process textures DebugAssert(m_pSceneColorBufferCopy != nullptr && m_pSceneDepthBufferCopy != nullptr); const uint32 BASE_INDEX = pMaterialShader->GetTextureParameterCount(); pShaderProgram->SetMaterialParameterTexture(pCommandList, BASE_INDEX + 0, m_pSceneColorBufferCopy->pTexture, nullptr); pShaderProgram->SetMaterialParameterTexture(pCommandList, BASE_INDEX + 1, m_pSceneDepthBufferCopy->pTexture, nullptr); } } uint32 DeferredShadingWorldRenderer::DrawBasePassForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool depthWrites, GPU_COMPARISON_FUNC depthFunc) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); uint32 renderPassMask = pQueueEntry->RenderPassMask; // base pass flags uint32 basePassFlags = 0; // emissive if (renderPassMask & RENDER_PASS_EMISSIVE) basePassFlags |= BasePassShader::WITH_EMISSIVE; // lightmap else if (renderPassMask & RENDER_PASS_LIGHTMAP) basePassFlags |= BasePassShader::WITH_LIGHTMAP; // nothing for base pass else return 0; // should have flags DebugAssert(basePassFlags != 0); // draw base pass ShaderProgram *pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(BasePassShader), basePassFlags, pQueueEntry); if (pShaderProgram != nullptr) { // set states pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, depthWrites, depthFunc), 0); // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); SetBlendingModeForMaterial(pCommandList, pQueueEntry); SetCommonShaderProgramParameters(pCommandList, pViewParameters, pQueueEntry, pShaderProgram); // draw away pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, pCommandList); } // done return 1; } void DeferredShadingWorldRenderer::DrawEmptyPassForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // get shader ShaderProgram *pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(BasePassShader), 0, pQueueEntry); if (pShaderProgram != nullptr) { // set initial states pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); SetBlendingModeForMaterial(pCommandList, pQueueEntry); SetCommonShaderProgramParameters(pCommandList, pViewParameters, pQueueEntry, pShaderProgram); // draw it pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, pCommandList); } } uint32 DeferredShadingWorldRenderer::DrawForwardLightPassesForObject(GPUCommandList *pCommandList, const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool useAdditiveBlending, bool depthWrites, GPU_COMPARISON_FUNC depthFunc) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); const bool staticLightMask = ((pQueueEntry->RenderPassMask & RENDER_PASS_STATIC_LIGHTING) != 0); const uint32 renderPassMask = pQueueEntry->RenderPassMask; ShaderProgram *pShaderProgram; uint32 drawnLights = 0; // draw lights macro #define DRAW_LIGHT() MULTI_STATEMENT_MACRO_BEGIN \ if (drawnLights == 0) \ { \ pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); \ pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, depthWrites, depthFunc), 0); \ if (useAdditiveBlending) \ SetAdditiveBlendingModeForMaterial(pCommandList, pQueueEntry); \ else \ SetBlendingModeForMaterial(pCommandList, pQueueEntry); \ } \ else if (drawnLights == 1) \ { \ if (!useAdditiveBlending) \ SetAdditiveBlendingModeForMaterial(pCommandList, pQueueEntry); \ if (depthWrites) \ pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, false, GPU_COMPARISON_FUNC_EQUAL), 0); \ } \ SetCommonShaderProgramParameters(pCommandList, pViewParameters, pQueueEntry, pShaderProgram); \ pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, pCommandList); \ drawnLights++; \ MULTI_STATEMENT_MACRO_END // draw directional lights RenderQueue::DirectionalLightArray &directionalLights = m_renderQueue.GetDirectionalLightArray(); for (uint32 lightIndex = 0; lightIndex < directionalLights.GetSize(); lightIndex++) { const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight = &directionalLights[lightIndex]; const bool usingShadowMap = (pLight->ShadowMapIndex >= 0 && (renderPassMask & RENDER_PASS_SHADOWED_LIGHTING)); // mask static lights on static objects away if ((pLight->Static & staticLightMask) != pLight->Static) continue; // get shader flags uint32 directionalLightShaderFlags = m_directionalLightShaderFlags; if (!usingShadowMap) directionalLightShaderFlags &= ~DirectionalLightShader::SHADOW_BITS_MASK; // get shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(DirectionalLightShader), directionalLightShaderFlags, pQueueEntry)) == nullptr) continue; // bind shader and set parameters pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); // using shadow map? note: we need the shadow map data to set the constant buffer up, even if this object does not use it const DirectionalShadowMapRenderer::ShadowMapData *pShadowMapData = (pLight->ShadowMapIndex >= 0) ? m_directionalShadowMaps[pLight->ShadowMapIndex] : nullptr; // set constant buffer parameters if (m_lastDirectionalLightIndex != lightIndex) { DirectionalLightShader::SetLightParameters(pCommandList, pLight, pShadowMapData); m_lastDirectionalLightIndex = lightIndex; } // and the shadow map textures if (pShadowMapData) DirectionalLightShader::SetProgramParameters(pCommandList, pShaderProgram, pLight, pShadowMapData); // draw light DRAW_LIGHT(); } // draw point lights RenderQueue::PointLightArray &pointLights = m_renderQueue.GetPointLightArray(); const RENDER_QUEUE_POINT_LIGHT_ENTRY *queuedLights[PointLightListShader::MAX_LIGHTS]; uint32 queuedLightCount = 0; for (uint32 lightIndex = 0; lightIndex < pointLights.GetSize(); lightIndex++) { const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLight = &pointLights[lightIndex]; const bool usingShadowMap = (pLight->ShadowMapIndex >= 0 && (renderPassMask & RENDER_PASS_SHADOWED_LIGHTING)); // mask static lights on static objects away if ((pLight->Static & staticLightMask) != pLight->Static) continue; // test if it intersects the renderable if (!CollisionDetection::AABoxIntersectsSphere(pQueueEntry->BoundingBox.GetMinBounds(), pQueueEntry->BoundingBox.GetMaxBounds(), pLight->Position, pLight->Range)) continue; // we only draw shadowed lights immediately, otherwise queue if (!usingShadowMap) { if (queuedLightCount == PointLightListShader::MAX_LIGHTS) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightListShader), 0, pQueueEntry)) != nullptr) { // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); // initialize light pointers for (uint32 queuedLightIndex = 0; queuedLightIndex < queuedLightCount; queuedLightIndex++) PointLightListShader::SetLightParameters(pCommandList, queuedLightIndex, queuedLights[queuedLightIndex]); // commit parameters, and draw PointLightListShader::SetActiveLightCount(pCommandList, queuedLightCount); PointLightListShader::CommitParameters(pCommandList); DRAW_LIGHT(); } queuedLightCount = 0; } // add to queued light list queuedLights[queuedLightCount++] = pLight; continue; } // get shader flags uint32 pointLightShaderFlags = m_pointLightShaderFlags; if (!usingShadowMap) pointLightShaderFlags &= ~PointLightShader::SHADOW_BITS_MASK; // get shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightShader), pointLightShaderFlags, pQueueEntry)) == nullptr) continue; // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); // using shadow map? note: we need the shadow map data to set the constant buffer up, even if this object does not use it const PointShadowMapRenderer::ShadowMapData *pShadowMapData = (pLight->ShadowMapIndex >= 0) ? m_pointShadowMaps[pLight->ShadowMapIndex] : nullptr; // set constant buffer parameters if (m_lastPointLightIndex != lightIndex) { PointLightShader::SetLightParameters(pCommandList, pLight, pShadowMapData); m_lastPointLightIndex = lightIndex; } // set program parameters PointLightShader::SetProgramParameters(pCommandList, pShaderProgram, pLight, pShadowMapData); // draw light DRAW_LIGHT(); } // if there's only one remaining light, we can use the fast shader, otherwise use the multi-light shader if (queuedLightCount == 1) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightShader), 0, pQueueEntry)) != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); PointLightShader::SetLightParameters(pCommandList, queuedLights[0], nullptr); DRAW_LIGHT(); } } else if (queuedLightCount > 0) { if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(PointLightListShader), 0, pQueueEntry)) != nullptr) { // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); // initialize light pointers for (uint32 queuedLightIndex = 0; queuedLightIndex < queuedLightCount; queuedLightIndex++) PointLightListShader::SetLightParameters(pCommandList, queuedLightIndex, queuedLights[queuedLightIndex]); // commit parameters, and draw PointLightListShader::SetActiveLightCount(pCommandList, queuedLightCount); PointLightListShader::CommitParameters(pCommandList); DRAW_LIGHT(); } } // draw volumetric lights RenderQueue::VolumetricLightArray &volumetricLights = m_renderQueue.GetVolumetricLightArray(); for (uint32 lightIndex = 0; lightIndex < volumetricLights.GetSize(); lightIndex++) { const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLight = &volumetricLights[lightIndex]; // test with bounding box, meh. if (!CollisionDetection::AABoxIntersectsSphere(pQueueEntry->BoundingBox.GetMinBounds(), pQueueEntry->BoundingBox.GetMaxBounds(), pLight->Position, pLight->Range)) { continue; } // get shader flags uint32 volumetricShaderFlags = VolumetricLightShader::GetTypeFlagsForPrimitive(pLight->Primitive); // find shader if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(VolumetricLightShader), volumetricShaderFlags, pQueueEntry)) == NULL) continue; // bind shader pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); // and parameters if (m_lastVolumetricLightIndex != lightIndex) { VolumetricLightShader::SetLightParameters(pCommandList, pLight); m_lastVolumetricLightIndex = lightIndex; } // set program parameters VolumetricLightShader::SetProgramParameters(pCommandList, pShaderProgram, pLight); // draw light DRAW_LIGHT(); } #undef DRAW_LIGHT return drawnLights; } void DeferredShadingWorldRenderer::DrawDepthPrepass(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawDepthPrepass", MICROPROFILE_COLOR(255, 100, 100)); ShaderProgramSelector shaderSelector(m_globalShaderFlags); shaderSelector.SetBaseShader(OBJECT_TYPEINFO(DepthOnlyShader), 0); // Everything here uses the normal rasterizer state, so set that up here. pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoColorWrites()); pCommandList->SetRenderTargets(0, nullptr, m_pSceneDepthBuffer->pDSV); // Iterate over renderables RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask == 0) continue; // get material const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // ignore materials that don't write depth values for the prepass if (!pMaterialShader->GetDepthWrites()) continue; // set states pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); // For now, only masked materials are drawn with clipping shaderSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); shaderSelector.SetMaterial((pQueueEntry->pMaterial->GetShader()->GetBlendMode() == MATERIAL_BLENDING_MODE_MASKED) ? pQueueEntry->pMaterial : nullptr); // only continue with shader ShaderProgram *pShaderProgram = shaderSelector.MakeActive(pCommandList); if (pShaderProgram != nullptr) { pCommandList->SetPredication(pQueueEntry->pPredicate); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, pCommandList); } } // clear predication pCommandList->SetPredication(nullptr); } void DeferredShadingWorldRenderer::DrawUnlitObjects(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawUnlitObjects", MICROPROFILE_COLOR(255, 20, 255)); // Bind light buffer and depth buffer. pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, m_pSceneDepthBuffer->pDSV); // Iterate over renderables. RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { if (pQueueEntry->RenderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP)) { pCommandList->SetPredication(pQueueEntry->pPredicate); if (DrawBasePassForObject(pCommandList, pViewParameters, pQueueEntry, !m_options.EnableDepthPrepass, (CVars::r_depth_prepass.GetBool()) ? GPU_COMPARISON_FUNC_LESS_EQUAL : GPU_COMPARISON_FUNC_LESS) > 0) continue; } } // clear predication pCommandList->SetPredication(nullptr); } void DeferredShadingWorldRenderer::DrawGBuffers(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawGBuffers", MICROPROFILE_COLOR(50, 150, 255)); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd; ShaderProgramSelector shaderSelector(m_globalShaderFlags); // Bind the light buffer and clear it with the fog colour pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); pCommandList->ClearTargets(true, false, false, PixelFormatHelpers::ConvertSRGBToLinear(pViewParameters->FogColor)); // Switch to only the gbuffers. GPURenderTargetView *pGBufferRenderTargets[] = { m_pGBuffer0->pRTV, m_pGBuffer1->pRTV, m_pGBuffer2->pRTV }; pCommandList->SetRenderTargets(countof(pGBufferRenderTargets), pGBufferRenderTargets, m_pSceneDepthBuffer->pDSV); pCommandList->ClearTargets(true, false, false, float4::Zero); // Iterate over renderables. /*pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { // skip occlusion-culled objects, objects that have to be drawn as emissive/lightmap, they are done afterwards if (pQueueEntry->RenderPassMask == 0 || (pQueueEntry->RenderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP))) continue; // we only have to write the pixels that have have to be lit to the buffer, since the depth buffer is already "complete" at this point if (pQueueEntry->RenderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) { GPUShaderProgram *pShaderProgram = GetShaderPermutation(OBJECT_TYPEINFO(DeferredGBufferShader), 0, pQueueEntry); if (pShaderProgram != nullptr) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // set states pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, false, false)); pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, !CVars::r_depth_prepass.GetBool(), (CVars::r_depth_prepass.GetBool()) ? GPU_COMPARISON_FUNC_LESS_EQUAL : GPU_COMPARISON_FUNC_LESS), 0); // bind/draw pCommandList->SetShaderProgram(pShaderProgram); SetBlendingModeForMaterial(pCommandList, pQueueEntry); SetCommonShaderProgramParameters(pCommandList, pViewParameters, pQueueEntry, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(pViewParameters, pQueueEntry, pCommandList); } } }*/ // Switch render targets to include the light buffer, for drawing emissive and lightmapped objects GPURenderTargetView *pLightBufferGBufferRenderTargets[] = { m_pGBuffer0->pRTV, m_pGBuffer1->pRTV, m_pGBuffer2->pRTV, m_pSceneColorBuffer->pRTV }; pCommandList->SetRenderTargets(countof(pLightBufferGBufferRenderTargets), pLightBufferGBufferRenderTargets, m_pSceneDepthBuffer->pDSV); pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { uint32 shaderFlags = DeferredGBufferShader::WITH_LIGHTBUFFER; if (pQueueEntry->RenderPassMask == 0) continue; if (pQueueEntry->RenderPassMask & RENDER_PASS_LIGHTMAP) shaderFlags |= DeferredGBufferShader::WITH_LIGHTMAP; if (!(pQueueEntry->RenderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING))) shaderFlags |= DeferredGBufferShader::NO_ALBEDO; // update selector shaderSelector.SetBaseShader(OBJECT_TYPEINFO(DeferredGBufferShader), shaderFlags); shaderSelector.SetQueueEntry(pQueueEntry); // get shader ShaderProgram *pShaderProgram = shaderSelector.MakeActive(pCommandList); if (pShaderProgram != nullptr) { const MaterialShader *pMaterialShader = pQueueEntry->pMaterial->GetShader(); // set states pCommandList->SetRasterizerState(pMaterialShader->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); pCommandList->SetDepthStencilState(pMaterialShader->SelectDepthStencilState(true, !CVars::r_depth_prepass.GetBool(), (CVars::r_depth_prepass.GetBool()) ? GPU_COMPARISON_FUNC_LESS_EQUAL : GPU_COMPARISON_FUNC_LESS), 0); // bind SetBlendingModeForMaterial(pCommandList, pQueueEntry); pQueueEntry->pRenderProxy->SetupForDraw(&pViewParameters->ViewCamera, pQueueEntry, pCommandList, pShaderProgram); // set predication as the last step to avoid duplicate calls pCommandList->SetPredication(pQueueEntry->pPredicate); // draw pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, pCommandList); } } // clear predication pCommandList->SetPredication(nullptr); // add them for debugging AddDebugBufferView(m_pGBuffer0, "GBuffer0", false); AddDebugBufferView(m_pGBuffer1, "GBuffer1", false); AddDebugBufferView(m_pGBuffer2, "GBuffer2", false); } void DeferredShadingWorldRenderer::ApplyAmbientOcclusion(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "SSAO", MICROPROFILE_COLOR(75, 20, 150)); IntermediateBuffer *pSSAOBuffer = RequestIntermediateBuffer(m_options.RenderWidth, m_options.RenderHeight, PIXEL_FORMAT_R8_UNORM, 1); if (pSSAOBuffer == nullptr) return; IntermediateBuffer *pDownscaledSSAOBuffer = RequestIntermediateBuffer(m_options.RenderWidth / 2, m_options.RenderHeight / 2, PIXEL_FORMAT_R8_UNORM, 1); if (pDownscaledSSAOBuffer == nullptr) { ReleaseIntermediateBuffer(pSSAOBuffer); return; } // run ssao shader { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "Generate SSAO", MICROPROFILE_COLOR(75, 20, 150)); pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); pCommandList->SetRenderTargets(1, &pSSAOBuffer->pRTV, nullptr); pCommandList->SetShaderProgram(m_pSSAOProgram->GetGPUProgram()); SSAOShader::SetProgramParameters(pCommandList, m_pSSAOProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer1->pTexture); g_pRenderer->DrawFullScreenQuad(pCommandList); } // downsample the AO buffer { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "Downsample SSAO", MICROPROFILE_COLOR(20, 75, 150)); ScaleTexture(pCommandList, pSSAOBuffer->pTexture, pDownscaledSSAOBuffer->pRTV, true, false); } // unbind source/dest from state pCommandList->ClearState(true, false, false, true); // draw/blend to light buffer { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "Apply SSAO", MICROPROFILE_COLOR(20, 150, 75)); pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStatePremultipliedAlpha()); pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); pCommandList->SetShaderProgram(m_pSSAOApplyProgram->GetGPUProgram()); SSAOApplyShader::SetProgramParameters(pCommandList, m_pSSAOApplyProgram, pDownscaledSSAOBuffer->pTexture); g_pRenderer->DrawFullScreenQuad(pCommandList); } // clear shader resources out pCommandList->ClearState(true, false, false, false); // release downsampled buffer AddDebugBufferView(pDownscaledSSAOBuffer, "SSAO", true); ReleaseIntermediateBuffer(pSSAOBuffer); } void DeferredShadingWorldRenderer::ApplyFog(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "ApplyFog", MICROPROFILE_COLOR(50, 42, 150)); // draw/blend to light buffer pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAlphaBlending()); pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); // blend ao ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredFogShader), DeferredFogShader::GetFlagsForMode(pViewParameters->FogMode), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredFogShader::SetProgramParameters(pCommandList, pShaderProgram, pViewParameters, m_pSceneDepthBuffer->pTexture); g_pRenderer->DrawFullScreenQuad(pCommandList); } // clear shader resources out pCommandList->ClearState(true, false, false, false); } void DeferredShadingWorldRenderer::DrawLights(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawLights", MICROPROFILE_COLOR(42, 100, 25)); // bind the light buffer without any depth buffer, and clear it pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); // use light volumes DrawLights_DirectionalLights(pCommandList, pViewParameters); DrawLights_PointLights_ByLightVolumes(pCommandList, pViewParameters); //DrawLights_PointLights_Tiled(pCommandList, pViewParameters); // draw wireframe overlay if (m_options.ShowWireframeOverlay) { pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, m_pSceneDepthBuffer->pDSV); DrawWireframeOverlay(pCommandList, &pViewParameters->ViewCamera, &m_renderQueue.GetOpaqueRenderables()); } } void DeferredShadingWorldRenderer::DrawLights_DirectionalLights(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawLights_DirectionalLights", MICROPROFILE_COLOR(42, 25, 100)); // setup state for directional lights -- possibly use stencil buffer for pixels that have to be shaded?? pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false, GPU_COMPARISON_FUNC_ALWAYS), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive()); pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_STRIP); // draw directional lights for (const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY &currentLight : m_renderQueue.GetDirectionalLightArray()) { // apply shadow flags uint32 shaderFlags = 0; if (currentLight.ShadowMapIndex >= 0) shaderFlags = DeferredDirectionalLightShader::CalculateShadowFlags(m_options.EnableShadows, m_options.EnableHardwareShadowFiltering, m_options.ShadowMapFiltering, m_options.ShowShadowMapCascades); // get shader ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredDirectionalLightShader), shaderFlags, g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributes(), g_pRenderer->GetFixedResources()->GetFullScreenQuadVertexAttributeCount(), nullptr, 0); if (pShaderProgram == nullptr) continue; // apply shader parameters pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredDirectionalLightShader::SetBufferParameters(pCommandList, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture); DeferredDirectionalLightShader::SetLightParameters(pCommandList, pShaderProgram, pViewParameters, &currentLight); if (currentLight.ShadowMapIndex >= 0) DeferredDirectionalLightShader::SetShadowParameters(pCommandList, pShaderProgram, m_directionalShadowMaps[currentLight.ShadowMapIndex]); DeferredDirectionalLightShader::CommitParameters(pCommandList, pShaderProgram); // draw a fullscreen quad //m_pGPUContext->Draw(0, 4); g_pRenderer->DrawFullScreenQuad(pCommandList); } // clear the shader state, ensuring the buffers are unbound from input pCommandList->ClearState(true, false, false, false); } void DeferredShadingWorldRenderer::DrawLights_PointLights_ByLightVolumes(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawLights_PointLights_ByLightVolumes", MICROPROFILE_COLOR(25, 90, 100)); pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false, GPU_COMPARISON_FUNC_ALWAYS), 0); pCommandList->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive()); pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); pCommandList->SetVertexBuffer(0, m_pPointLightVolumeVertexBuffer, 0, sizeof(float3)); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // light queue ShaderProgram *pShaderProgram; uint32 queuedLightCount[2] = { 0, 0 }; const RENDER_QUEUE_POINT_LIGHT_ENTRY *queuedLights[2][DeferredPointLightListShader::MAX_LIGHTS]; // draw point lights for (const RENDER_QUEUE_POINT_LIGHT_ENTRY &currentLight : m_renderQueue.GetPointLightArray()) { // check if we are inside the light volume, if so, precaution needs to be taken bool insideLightVolume = pViewParameters->ViewCamera.GetPosition().SquaredDistance(currentLight.Position) < (Math::Square(currentLight.Range) + 1.0f); // queue non-shadowed lights if (currentLight.ShadowMapIndex < 0) { // flush queue if (queuedLightCount[insideLightVolume] == DeferredPointLightListShader::MAX_LIGHTS) { // use front-face culling if inside light volume, otherwise back-face culling pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, (insideLightVolume) ? RENDERER_CULL_FRONT : RENDERER_CULL_BACK, false, false, false)); // get shader pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredPointLightListShader), 0, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredPointLightListShader::SetBufferParameters(pCommandList, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture); for (uint32 i = 0; i < DeferredPointLightListShader::MAX_LIGHTS; i++) DeferredPointLightListShader::SetLightParameters(pCommandList, pShaderProgram, pViewParameters, i, queuedLights[insideLightVolume][i]); // draw the light volume pCommandList->DrawInstanced(0, m_pointLightVolumeVertexCount, DeferredPointLightListShader::MAX_LIGHTS); } // done queuedLightCount[insideLightVolume] = 0; } // add to queue queuedLights[insideLightVolume][queuedLightCount[insideLightVolume]++] = &currentLight; continue; } // use front-face culling if inside light volume, otherwise back-face culling pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, (insideLightVolume) ? RENDERER_CULL_FRONT : RENDERER_CULL_BACK, false, false, false)); // apply shadow flags uint32 shaderFlags = DeferredPointLightShader::CalculateShadowFlags(m_options.EnableShadows, m_options.EnableHardwareShadowFiltering); // get shader pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredPointLightShader), shaderFlags, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (pShaderProgram == nullptr) continue; // set program parameters pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredPointLightShader::SetBufferParameters(pCommandList, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture); DeferredPointLightShader::SetLightParameters(pCommandList, pShaderProgram, pViewParameters, &currentLight); DeferredPointLightShader::SetShadowParameters(pCommandList, pShaderProgram, m_pointShadowMaps[currentLight.ShadowMapIndex]); // draw the light volume pCommandList->Draw(0, m_pointLightVolumeVertexCount); } // flush the queues for (uint32 queueIndex = 0; queueIndex < 2; queueIndex++) { uint32 lightCount = queuedLightCount[queueIndex]; if (lightCount == 0) continue; // use front-face culling if inside light volume, otherwise back-face culling pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, (queueIndex) ? RENDERER_CULL_FRONT : RENDERER_CULL_BACK, false, false, false)); // get shader pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredPointLightListShader), 0, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (pShaderProgram != nullptr) { pCommandList->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredPointLightListShader::SetBufferParameters(pCommandList, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture); for (uint32 i = 0; i < lightCount; i++) DeferredPointLightListShader::SetLightParameters(pCommandList, pShaderProgram, pViewParameters, i, queuedLights[queueIndex][i]); // draw the light volume pCommandList->DrawInstanced(0, m_pointLightVolumeVertexCount, lightCount); } } // clear the shader state, ensuring the buffers are unbound from input pCommandList->ClearState(true, false, false, false); } void DeferredShadingWorldRenderer::DrawLights_PointLights_Tiled(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { #if 0 MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawLights_PointLights_Tiled", MAKE_COLOR_R8G8B8_UNORM(25, 90, 100)); // setup for drawing volumes m_pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); m_pGPUContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false, GPU_COMPARISON_FUNC_ALWAYS), 0); m_pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive()); m_pGPUContext->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); m_pGPUContext->SetVertexBuffer(0, m_pPointLightVolumeVertexBuffer, 0, sizeof(float3)); m_pGPUContext->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); // find lights m_tiledPointLights.Clear(); for (const RENDER_QUEUE_POINT_LIGHT_ENTRY &currentLight : m_renderQueue.GetPointLightArray()) { // queue non-shadowed lights if (currentLight.ShadowMapIndex < 0) { m_tiledPointLights.Emplace(currentLight.Position, currentLight.InverseRange, currentLight.LightColor, currentLight.FalloffExponent); continue; } // draw shadowed lights // check if we are inside the light volume, if so, precaution needs to be taken bool insideLightVolume = pViewParameters->ViewCamera.GetPosition().SquaredDistance(currentLight.Position) < (Math::Square(currentLight.Range) + 1.0f); if (insideLightVolume) { // use front-face culling m_pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_FRONT, false, false, false)); } else { // use back-face culling m_pGPUContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false, false)); } // apply shadow flags uint32 shaderFlags = 0; if (currentLight.ShadowMapIndex >= 0) shaderFlags = DeferredPointLightShader::CalculateShadowFlags(m_options.EnableShadows, m_options.EnableHardwareShadowFiltering); // get shader ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredPointLightShader), shaderFlags, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (pShaderProgram == nullptr) continue; // set program parameters m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredPointLightShader::SetBufferParameters(m_pGPUContext, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture); DeferredPointLightShader::SetLightParameters(m_pGPUContext, pShaderProgram, pViewParameters, &currentLight); if (currentLight.ShadowMapIndex >= 0) DeferredPointLightShader::SetShadowParameters(m_pGPUContext, pShaderProgram, &m_pointShadowMaps[currentLight.ShadowMapIndex]); // draw the light volume m_pGPUContext->Draw(0, m_pointLightVolumeVertexCount); } // if there's no tiled lights to draw, bail out if (m_tiledPointLights.IsEmpty()) return; // calculate tile counts const uint32 tileSize = DeferredTiledPointLightShader::TILE_SIZE; uint32 tileCountX = m_options.RenderWidth / tileSize + (((m_options.RenderWidth % tileSize) != 0) ? 1 : 0); uint32 tileCountY = m_options.RenderHeight / tileSize + (((m_options.RenderHeight % tileSize) != 0) ? 1 : 0);; // get tiled shader ShaderProgram *pShaderProgram = g_pRenderer->GetShaderProgram(0, OBJECT_TYPEINFO(DeferredTiledPointLightShader), 0, g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributes(), g_pRenderer->GetFixedResources()->GetPositionOnlyVertexAttributeCount(), nullptr, 0); if (pShaderProgram != nullptr) { // drop the render targets, the compute shader accesses them directly m_pGPUContext->SetRenderTargets(0, nullptr, nullptr); // fill common shader information m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); DeferredTiledPointLightShader::SetProgramParameters(m_pGPUContext, pShaderProgram, tileCountX, tileCountY); DeferredTiledPointLightShader::SetBufferParameters(m_pGPUContext, pShaderProgram, m_pSceneDepthBuffer->pTexture, m_pGBuffer0->pTexture, m_pGBuffer1->pTexture, m_pGBuffer2->pTexture, nullptr /* FIXME SHOULD BE COPY */); // dispatch until we consume all lights for (uint32 baseLightIndex = 0; baseLightIndex < m_tiledPointLights.GetSize(); baseLightIndex += DeferredTiledPointLightShader::MAX_LIGHTS_PER_DISPATCH) { // calculate light count uint32 passLightCount = Min(m_tiledPointLights.GetSize() - baseLightIndex, DeferredTiledPointLightShader::MAX_LIGHTS_PER_DISPATCH); // set light information DeferredTiledPointLightShader::SetLights(m_pGPUContext, pShaderProgram, m_tiledPointLights.GetBasePointer() + baseLightIndex, passLightCount); DeferredTiledPointLightShader::CommitParameters(m_pGPUContext, pShaderProgram); // invoke compute shader m_pGPUContext->Dispatch(tileCountX, tileCountY, 1); // temporary until refactor: blend back to the main light buffer m_pGPUContext->ClearState(true, false, false, false); m_pGPUContext->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, nullptr); m_pGPUContext->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateAdditive()); //g_pRenderer->BlitTextureUsingShader(m_pGPUContext, m_pLightBufferCopy, 0, 0, m_targetWidth, m_targetHeight, 0, 0, 0, m_targetWidth, m_targetHeight, RENDERER_FRAMEBUFFER_BLIT_RESIZE_FILTER_NEAREST, RENDERER_FRAMEBUFFER_BLIT_BLEND_MODE_ADDITIVE); } } // clear state, since the output buffer is bound as a uav this'll cause issues when we next bind it as a render target m_pGPUContext->ClearState(true, false, false, true); #endif } void DeferredShadingWorldRenderer::DrawPostProcessAndTranslucentObjects(GPUCommandList *pCommandList, const ViewParameters *pViewParameters) { RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry; RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd; MICROPROFILE_SCOPEI("DeferredShadingWorldRenderer", "DrawPostProcessAndTranslucentObjects", MICROPROFILE_COLOR(90, 25, 80)); // set render target to the light buffer pCommandList->SetRenderTargets(1, &m_pSceneColorBuffer->pRTV, m_pSceneDepthBuffer->pDSV); // Draw post process objects before translucent if (m_renderQueue.GetPostProcessRenderables().GetSize() > 0) { // acquire copy of scene colour + depth m_pSceneColorBufferCopy = RequestIntermediateBufferMatching(m_pSceneColorBuffer); m_pSceneDepthBufferCopy = RequestIntermediateBufferMatching(m_pSceneDepthBuffer); pCommandList->CopyTexture(m_pSceneColorBuffer->pTexture, m_pSceneColorBufferCopy->pTexture); pCommandList->CopyTexture(m_pSceneDepthBuffer->pTexture, m_pSceneDepthBufferCopy->pTexture); // Draw objects pQueueEntry = m_renderQueue.GetPostProcessRenderables().GetBasePointer(); pQueueEntryEnd = m_renderQueue.GetPostProcessRenderables().GetBasePointer() + m_renderQueue.GetPostProcessRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { uint32 renderPassMask = pQueueEntry->RenderPassMask; uint32 drawCount = 0; // skip anything without any passes if (renderPassMask == 0) continue; // draw base pass? if (renderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount = DrawBasePassForObject(pCommandList, pViewParameters, pQueueEntry, false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw light passes? if (renderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pCommandList, pViewParameters, pQueueEntry, (drawCount != 0), false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw blank pass if there is no draw calls for this object if (drawCount == 0) DrawEmptyPassForObject(pCommandList, pViewParameters, pQueueEntry); } // release intermediate buffers ReleaseIntermediateBuffer(m_pSceneDepthBufferCopy); ReleaseIntermediateBuffer(m_pSceneColorBufferCopy); m_pSceneDepthBufferCopy = nullptr; m_pSceneColorBufferCopy = nullptr; // draw wireframe overlay if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(pCommandList, &pViewParameters->ViewCamera, &m_renderQueue.GetPostProcessRenderables()); } // Draw translucent objects pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { uint32 renderPassMask = pQueueEntry->RenderPassMask; uint32 drawCount = 0; // skip anything without any passes if (renderPassMask == 0) continue; // draw base pass? if (renderPassMask & (RENDER_PASS_EMISSIVE | RENDER_PASS_LIGHTMAP | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount = DrawBasePassForObject(pCommandList, pViewParameters, pQueueEntry, false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw light passes? if (renderPassMask & (RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING)) drawCount += DrawForwardLightPassesForObject(pCommandList, pViewParameters, pQueueEntry, (drawCount != 0), false, GPU_COMPARISON_FUNC_LESS_EQUAL); // draw blank pass if there is no draw calls for this object if (drawCount == 0) DrawEmptyPassForObject(pCommandList, pViewParameters, pQueueEntry); } // draw wireframe overlay if (m_options.ShowWireframeOverlay) DrawWireframeOverlay(pCommandList, &pViewParameters->ViewCamera, &m_renderQueue.GetTranslucentRenderables()); } void DeferredShadingWorldRenderer::DrawDebugInfo(const Camera *pCamera) { CompositingWorldRenderer::DrawDebugInfo(pCamera); } <file_sep>/Engine/Source/MathLib/AABox.cpp #include "MathLib/AABox.h" #include "MathLib/Matrixf.h" #include "MathLib/CollisionDetection.h" #include "MathLib/Transform.h" #include "MathLib/Sphere.h" #include "YBaseLib/Assert.h" #include "YBaseLib/Memory.h" static const float __AABoxZero[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; static const float __AABoxMaxSize[] = { -Y_FLT_MAX, -Y_FLT_MAX, -Y_FLT_MAX, Y_FLT_MAX, Y_FLT_MAX, Y_FLT_MAX }; const AABox &AABox::Zero = reinterpret_cast<const AABox &>(__AABoxZero); const AABox &AABox::MaxSize = reinterpret_cast<const AABox &>(__AABoxMaxSize); AABox::AABox(const Vector3f &vLow, const Vector3f &vHigh) { DebugAssert(vLow <= vHigh); m_minBounds = vLow; m_maxBounds = vHigh; } AABox::AABox(const AABox &rCopy) { DebugAssert(rCopy.m_minBounds <= rCopy.m_maxBounds); m_minBounds = rCopy.GetMinBounds(); m_maxBounds = rCopy.GetMaxBounds(); } AABox::AABox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { DebugAssert(minX <= maxX && minY <= maxY && minZ <= maxZ); m_minBounds.Set(minX, minY, minZ); m_maxBounds.Set(maxX, maxY, maxZ); } AABox::AABox(const Vector3f &position) { m_minBounds = position; m_maxBounds = position; } void AABox::SetBounds(const AABox &bounds) { m_minBounds = bounds.m_minBounds; m_maxBounds = bounds.m_maxBounds; } void AABox::SetBounds(const Vector3f &position) { m_minBounds = position; m_maxBounds = position; } void AABox::SetBounds(const Vector3f &vLow, const Vector3f &vHigh) { DebugAssert(vLow <= vHigh); m_minBounds = vLow; m_maxBounds = vHigh; } void AABox::SetBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { DebugAssert(minX <= maxX && minY <= maxY && minZ <= maxZ); m_minBounds.Set(minX, minY, minZ); m_maxBounds.Set(maxX, maxY, maxZ); } void AABox::SetZero() { m_minBounds.SetZero(); m_maxBounds.SetZero(); } void AABox::Merge(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { SIMDVector3f v_minBounds(minX, minY, minZ); SIMDVector3f v_maxBounds(maxX, maxY, maxZ); m_minBounds = SIMDVector3f(m_minBounds).Min(v_minBounds); m_minBounds = SIMDVector3f(m_minBounds).Min(v_maxBounds); m_maxBounds = SIMDVector3f(m_maxBounds).Max(v_minBounds); m_maxBounds = SIMDVector3f(m_maxBounds).Max(v_maxBounds); } void AABox::Merge(const Vector3f &minBounds, const Vector3f &maxBounds) { SIMDVector3f v_minBounds(minBounds); SIMDVector3f v_maxBounds(maxBounds); m_minBounds = SIMDVector3f(m_minBounds).Min(v_minBounds); m_minBounds = SIMDVector3f(m_minBounds).Min(v_maxBounds); m_maxBounds = SIMDVector3f(m_maxBounds).Max(v_minBounds); m_maxBounds = SIMDVector3f(m_maxBounds).Max(v_maxBounds); } void AABox::Merge(const Vector3f &vPoint) { m_minBounds = SIMDVector3f(m_minBounds).Min(vPoint); m_maxBounds = SIMDVector3f(m_maxBounds).Max(vPoint); } void AABox::Merge(const AABox &box) { Merge(box.GetMinBounds()); Merge(box.GetMaxBounds()); } AABox AABox::Merge(const AABox &left, const AABox &right) { AABox newBox(left); newBox.Merge(right); return newBox; } int32 AABox::ContainsAABox(const AABox &rOtherBox) const { SIMDVector3f vecMinBounds(m_minBounds); SIMDVector3f vecMaxBounds(m_maxBounds); SIMDVector3f vecOtherMinBounds(rOtherBox.m_minBounds); SIMDVector3f vecOtherMaxBounds(rOtherBox.m_maxBounds); if (vecMinBounds <= vecOtherMinBounds && vecMaxBounds >= vecOtherMaxBounds) return 1; else if (vecOtherMinBounds <= vecMinBounds && vecOtherMaxBounds >= vecMaxBounds) return -1; else return 0; } bool AABox::ContainsPoint(const Vector3f &Point) const { return (Point >= m_minBounds && Point <= m_maxBounds); } bool AABox::AABoxIntersection(const AABox &aabOther) const { return CollisionDetection::AABoxIntersectsAABox(m_minBounds, m_maxBounds, aabOther.m_minBounds, aabOther.m_maxBounds); } bool AABox::AABoxIntersection(const AABox &aabOther, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::AABoxIntersectsAABox(m_minBounds, m_maxBounds, aabOther.m_minBounds, aabOther.m_maxBounds, contactNormal, contactPoint); } bool AABox::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const { return CollisionDetection::AABoxIntersectsAABox(m_minBounds, m_maxBounds, minBounds, maxBounds); } bool AABox::AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::AABoxIntersectsAABox(m_minBounds, m_maxBounds, minBounds, maxBounds, contactNormal, contactPoint); } bool AABox::SphereIntersection(const Sphere &sphOther) const { return CollisionDetection::AABoxIntersectsSphere(m_minBounds, m_maxBounds, sphOther.GetCenter(), sphOther.GetRadius()); } bool AABox::SphereIntersection(const Sphere &sphOther, Vector3f &contactNormal, Vector3f &contactPoint) const { return CollisionDetection::AABoxIntersectsSphere(m_minBounds, m_maxBounds, sphOther.GetCenter(), sphOther.GetRadius(), contactNormal, contactPoint); } bool AABox::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); return CollisionDetection::AABoxIntersectsTriangle(m_minBounds, m_maxBounds, v0, v1, v2, vec_e0, vec_e1, vec_normal); } bool AABox::TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); return CollisionDetection::AABoxIntersectsTriangle(m_minBounds, m_maxBounds, v0, v1, v2, vec_e0, vec_e1, vec_normal, contactNormal, contactPoint); } float AABox::TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const { SIMDVector3f vec_v0(v0); SIMDVector3f vec_e0(SIMDVector3f(v1) - vec_v0); SIMDVector3f vec_e1(SIMDVector3f(v2) - vec_v0); SIMDVector3f vec_normal(vec_e0.Cross(vec_e1).Normalize()); Vector3f contactNormal, contactPoint; if (CollisionDetection::AABoxIntersectsTriangle(m_minBounds, m_maxBounds, v0, v1, v2, vec_e0, vec_e1, vec_normal, contactNormal, contactPoint)) return (SIMDVector3f(contactPoint) - GetCenter()).Length(); else return Y_FLT_INFINITE; } void AABox::GetCornerPoints(Vector3f *pVertices) const { pVertices[0].Set(m_minBounds.x, m_minBounds.y, m_minBounds.z); pVertices[1].Set(m_minBounds.x, m_minBounds.y, m_maxBounds.z); pVertices[2].Set(m_minBounds.x, m_maxBounds.y, m_minBounds.z); pVertices[3].Set(m_minBounds.x, m_maxBounds.y, m_maxBounds.z); pVertices[4].Set(m_maxBounds.x, m_minBounds.y, m_minBounds.z); pVertices[5].Set(m_maxBounds.x, m_minBounds.y, m_maxBounds.z); pVertices[6].Set(m_maxBounds.x, m_maxBounds.y, m_minBounds.z); pVertices[7].Set(m_maxBounds.x, m_maxBounds.y, m_maxBounds.z); } void AABox::GetCornerPoints(SIMDVector3f *pVertices) const { pVertices[0].Set(m_minBounds.x, m_minBounds.y, m_minBounds.z); pVertices[1].Set(m_minBounds.x, m_minBounds.y, m_maxBounds.z); pVertices[2].Set(m_minBounds.x, m_maxBounds.y, m_minBounds.z); pVertices[3].Set(m_minBounds.x, m_maxBounds.y, m_maxBounds.z); pVertices[4].Set(m_maxBounds.x, m_minBounds.y, m_minBounds.z); pVertices[5].Set(m_maxBounds.x, m_minBounds.y, m_maxBounds.z); pVertices[6].Set(m_maxBounds.x, m_maxBounds.y, m_minBounds.z); pVertices[7].Set(m_maxBounds.x, m_maxBounds.y, m_maxBounds.z); } void AABox::ApplyTransform(const Transform &transform) { Vector3f cornerPoints[8]; GetCornerPoints(cornerPoints); for (uint32 i = 0; i < 8; i++) cornerPoints[i] = transform.TransformPoint(cornerPoints[i]); SetBounds(cornerPoints[0], cornerPoints[0]); for (uint32 i = 1; i < 8; i++) Merge(cornerPoints[i]); } void AABox::ApplyTransform(const Matrix3x3f &transform) { Vector3f cornerPoints[8]; GetCornerPoints(cornerPoints); for (uint32 i = 0; i < 8; i++) cornerPoints[i] = transform * cornerPoints[i]; SetBounds(cornerPoints[0], cornerPoints[0]); for (uint32 i = 1; i < 8; i++) Merge(cornerPoints[i]); } void AABox::ApplyTransform(const Matrix3x4f &transform) { Vector3f cornerPoints[8]; GetCornerPoints(cornerPoints); for (uint32 i = 0; i < 8; i++) cornerPoints[i] = transform.TransformPoint(cornerPoints[i]); SetBounds(cornerPoints[0], cornerPoints[0]); for (uint32 i = 1; i < 8; i++) Merge(cornerPoints[i]); } void AABox::ApplyTransform(const Matrix4x4f &transform) { SIMDMatrix4x4f vecTransformMatrix(transform); // fastpath // if (TransformMatrix == Matrix4::Identity) // return AABox(*this); // slowpath SIMDVector3f cornerPoints[8]; GetCornerPoints(cornerPoints); for (uint32 i = 0; i < 8; i++) cornerPoints[i] = vecTransformMatrix.TransformPoint(cornerPoints[i]); SetBounds(cornerPoints[0], cornerPoints[0]); for (uint32 i = 1; i < 8; i++) Merge(cornerPoints[i]); } AABox AABox::GetTransformed(const Transform &transform) const { AABox transformed(*this); transformed.ApplyTransform(transform); return transformed; } AABox AABox::GetTransformed(const Matrix3x3f &transform) const { AABox transformed(*this); transformed.ApplyTransform(transform); return transformed; } AABox AABox::GetTransformed(const Matrix3x4f &transform) const { AABox transformed(*this); transformed.ApplyTransform(transform); return transformed; } AABox AABox::GetTransformed(const Matrix4x4f &transform) const { AABox transformed(*this); transformed.ApplyTransform(transform); return transformed; } SIMDVector3f AABox::GetCenter() const { //return Vector3(((MaxBounds - MinBounds) * 0.5f + MinBounds); // optimized case SIMDVector3f lmin = m_minBounds; SIMDVector3f lmax = m_maxBounds; SIMDVector3f ret = lmax; ret -= lmin; ret *= 0.5f; ret += lmin; return ret; } SIMDVector3f AABox::GetExtents() const { return (SIMDVector3f(m_maxBounds) - SIMDVector3f(m_minBounds)); } bool AABox::operator==(const AABox &Other) const { return SIMDVector3f(m_minBounds) == SIMDVector3f(Other.m_minBounds) && SIMDVector3f(m_maxBounds) == SIMDVector3f(Other.m_maxBounds); } bool AABox::operator!=(const AABox &Other) const { return SIMDVector3f(m_minBounds) != SIMDVector3f(Other.m_minBounds) || SIMDVector3f(m_maxBounds) != SIMDVector3f(Other.m_maxBounds); } AABox &AABox::operator=(const AABox &rCopy) { DebugAssert(rCopy.GetMinBounds() <= rCopy.GetMaxBounds()); m_minBounds = rCopy.GetMinBounds(); m_maxBounds = rCopy.GetMaxBounds(); return *this; } AABox AABox::FromPoints(const SIMDVector3f *pPoints, uint32 nPoints) { Assert(nPoints > 0); SIMDVector3f minBounds(pPoints[0]); SIMDVector3f maxBounds(minBounds); uint32 i; for (i = 1; i < nPoints; i++) { const SIMDVector3f point(pPoints[i]); minBounds = minBounds.Min(point); maxBounds = maxBounds.Max(point); } return AABox(minBounds, maxBounds); } AABox AABox::FromPoints(const Vector3f *pPoints, uint32 nPoints) { Assert(nPoints > 0); SIMDVector3f minBounds(pPoints[0]); SIMDVector3f maxBounds(minBounds); uint32 i; for (i = 1; i < nPoints; i++) { const SIMDVector3f point(pPoints[i]); minBounds = minBounds.Min(point); maxBounds = maxBounds.Max(point); } return AABox(minBounds, maxBounds); } AABox AABox::FromSphere(const Sphere &sphere) { SIMDVector3f center(SIMDVector3f(sphere.GetCenter())); return AABox(center - sphere.GetRadius(), center + sphere.GetRadius()); } Sphere AABox::GetSphere() const { return Sphere::FromAABox(*this); } <file_sep>/DemoGame/Source/DemoGame/ImGuiDemo.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/ImGuiDemo.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(SkeletalAnimationDemo); static const char *MODEL_LIST = "Ninja\0Mario\0\0"; ImGuiDemo::ImGuiDemo(DemoGame *pDemoGame) : BaseDemoGameState(pDemoGame) { } ImGuiDemo::~ImGuiDemo() { } void ImGuiDemo::OnSwitchedIn() { BaseDemoGameState::OnSwitchedIn(); if (!m_uiActive) ToggleUI(); } bool ImGuiDemo::OnWindowEvent(const union SDL_Event *event) { // block events from closing UI return false; } void ImGuiDemo::OnRenderThreadBeginFrame(float deltaTime) { BaseDemoGameState::OnRenderThreadBeginFrame(deltaTime); // Clear targets. Have to do since no worldrenderer. GPUContext *pGPUContext = m_pDemoGame->GetGPUContext(); pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetFullViewport(); pGPUContext->ClearTargets(true, true, true); } void ImGuiDemo::DrawUI(float deltaTime) { BaseDemoGameState::DrawUI(deltaTime); ImGui::ShowTestWindow(); } bool LaunchpadGameState::InvokeImGuiDemo() { return RunDemo(new ImGuiDemo(m_pDemoGame)); } <file_sep>/Engine/Source/ResourceCompiler/StaticMeshGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Core/PropertyTable.h" #include "Engine/StaticMesh.h" namespace Physics { class CollisionShapeGenerator; } class StaticMeshGenerator { public: struct Vertex { float3 Position; float3 Tangent; float3 Binormal; float3 Normal; float3 TexCoord; uint32 Color; }; struct Triangle { uint32 Indices[3]; }; struct Batch { String MaterialName; MemArray<Triangle> Triangles; }; struct LOD { MemArray<Vertex> Vertices; PODArray<Batch *> Batches; }; enum CenterOrigin { CenterOrigin_Center, CenterOrigin_CenterBottom, CenterOrigin_Count, }; enum CollisionShapeType { CollisionShapeType_None, CollisionShapeType_Box, CollisionShapeType_Sphere, CollisionShapeType_TriangleMesh, CollisionShapeType_ConvexHull, CollisionShapeType_Count, }; public: StaticMeshGenerator(); ~StaticMeshGenerator(); // Accessors const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } const Vertex *GetVertex(uint32 lod, uint32 i) const { return &m_lods[lod]->Vertices[i]; } const uint32 GetVertexCount(uint32 lod) const { return m_lods[lod]->Vertices.GetSize(); } const Triangle *GetTriangle(uint32 lod, uint32 batchIndex, uint32 i) const { return &m_lods[lod]->Batches[batchIndex]->Triangles[i]; } const uint32 GetTriangleCount(uint32 lod, uint32 batchIndex) const { return m_lods[lod]->Batches[batchIndex]->Triangles.GetSize(); } const Batch *GetBatch(uint32 lod, uint32 i) const { return m_lods[lod]->Batches[i]; } const uint32 GetBatchCount(uint32 lod) const { return m_lods[lod]->Batches.GetSize(); } const LOD *GetLOD(uint32 i) const { return m_lods[i]; } const uint32 GetLODCount() const { return m_lods.GetSize(); } const Physics::CollisionShapeGenerator *GetCollisionShape() const { return m_pCollisionShapeGenerator; } // properties const PropertyTable *GetPropertyTable() const { return &m_properties; } bool GetVertexTextureCoordinatesEnabled() const; bool GetVertexColorsEnabled() const; void SetVertexTextureCoordinatesEnabled(bool enabled); void SetVertexColorsEnabled(bool enabled); uint32 GetVertexTextureCoordinateComponentCount() const; void SetVertexTextureCoordinateComponentCount(uint32 components); // Creation interface bool Create(bool enableVertexTextureCoordinates = true, bool enableVertexColors = false, uint32 textureCoordinateComponents = 2); // GPU data adding interface uint32 AddLOD(); uint32 AddVertex(uint32 lod, const float3 &position, const float3 &tangent = float3::UnitX, const float3 &binormal = float3::UnitY, const float3 &normal = float3::UnitZ, const float3 &texCoord = float3::Zero, const uint32 color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); uint32 AddBatch(uint32 lod, const char *materialName); uint32 AddTriangle(uint32 lod, uint32 batchIndex, const uint32 i0, const uint32 i1, const uint32 i2); // Loading interface (from XML) bool LoadFromXML(const char *FileName, ByteStream *pStream); // Output interface bool IsCompleteMesh() const; bool SaveToXML(ByteStream *pStream) const; bool Compile(ByteStream *pStream) const; // Copy another mesh void Copy(const StaticMeshGenerator *pGenerator); // Mesh Operations void CalculateBounds(); void GenerateTangents(uint32 LODIndex); void JoinBatches(); //void RemoveDuplicateVertices(); //void RemoveUnusedTriangles(); void CenterMesh(CenterOrigin origin = CenterOrigin_Center, float3 *pOffset = nullptr); void FlipTriangleWinding(); // Collision Shape Generators bool BuildCollisionShape(CollisionShapeType type); bool BuildBoxCollisionShape(); bool BuildSphereCollisionShape(); bool BuildTriangleMeshCollisionShape(uint32 buildFromLOD = 0); bool BuildConvexHullCollisionShape(uint32 buildFromLOD = 0); void SetCollisionShape(Physics::CollisionShapeGenerator *pGenerator); void RemoveCollisionShape(); private: void InternalBuildTriangleMeshCollisionShape(uint32 buildFromLOD); AABox m_boundingBox; Sphere m_boundingSphere; PropertyTable m_properties; Physics::CollisionShapeGenerator *m_pCollisionShapeGenerator; PODArray<LOD *> m_lods; }; <file_sep>/Engine/Source/Renderer/Shaders/SSAOShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/SSAOShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" #include "Engine/Texture.h" DEFINE_SHADER_COMPONENT_INFO(SSAOShader); BEGIN_SHADER_COMPONENT_PARAMETERS(SSAOShader) DEFINE_SHADER_COMPONENT_PARAMETER("RandomTextureScale", SHADER_PARAMETER_TYPE_FLOAT2) DEFINE_SHADER_COMPONENT_PARAMETER("RandomTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("DepthBuffer", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("NormalsTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void SSAOShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pDepthBuffer, GPUTexture2D *pNormalsTexture) { // get random texture, and scale it const Texture2D *pRandomTexture = g_pRenderer->GetFixedResources()->GetRandomTexture(); float2 randomTextureScale((float)pCommandList->GetViewport()->Width / (float)pRandomTexture->GetWidth(), (float)pCommandList->GetViewport()->Height / (float)pRandomTexture->GetHeight()); // set parameters pShaderProgram->SetBaseShaderParameterValue(pCommandList, 0, SHADER_PARAMETER_TYPE_FLOAT2, &randomTextureScale); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 1, pRandomTexture->GetGPUTexture(), nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 2, pDepthBuffer, nullptr); pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 3, pNormalsTexture, nullptr); } bool SSAOShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool SSAOShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/SSAOShader.hlsl", "PSMain"); // need view ray from VS pParameters->AddPreprocessorMacro("GENERATE_VIEW_RAY", "1"); return true; } DEFINE_SHADER_COMPONENT_INFO(SSAOApplyShader); BEGIN_SHADER_COMPONENT_PARAMETERS(SSAOApplyShader) DEFINE_SHADER_COMPONENT_PARAMETER("AOTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) END_SHADER_COMPONENT_PARAMETERS() void SSAOApplyShader::SetProgramParameters(GPUCommandList *pCommandList, ShaderProgram *pShaderProgram, GPUTexture2D *pAOTexture) { pShaderProgram->SetBaseShaderParameterTexture(pCommandList, 0, pAOTexture, nullptr); } bool SSAOApplyShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool SSAOApplyShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/SSAOApplyShader.hlsl", "PSMain"); return true; } <file_sep>/DemoGame/Source/DemoGame/DemoCamera.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/DemoCamera.h" #include "Engine/World.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/SDLHeaders.h" Log_SetChannel(DemoCamera); DemoCamera::DemoCamera() : Camera(), m_moved(false), m_clippingEnabled(false), m_fCameraSpeed(1.0f), m_pWorld(nullptr), m_moveDirection(float3::Zero) { } DemoCamera::~DemoCamera() { } void DemoCamera::Move(const float3 &direction, float distance) { float3 D(direction * distance); if (D.SquaredLength() < Y_FLT_EPSILON) return; m_position += D; UpdateViewMatrix(); UpdateFrustum(); } void DemoCamera::ModPitch(float Amount) { // rotate around local x axis Rotate(m_rotation * float3::UnitX, Amount); } void DemoCamera::ModYaw(float Amount) { // rotate around fixed yaw axis Rotate(float3::UnitZ, Amount); } void DemoCamera::ModRoll(float Amount) { // rotate it Rotate(m_rotation * float3::UnitY, Amount); } void DemoCamera::Rotate(const float3 &axis, float angle) { Rotate(Quaternion::FromAxisAngle(axis, angle)); } void DemoCamera::Rotate(const Quaternion &rotation) { m_rotation = rotation * m_rotation; m_rotation.NormalizeInPlace(); UpdateViewMatrix(); UpdateFrustum(); //float3 eulerAngles(m_rotation.GetEulerAngles()); //Log_DevPrintf("new rotation eular angles: %s", StringConverter::Float3ToString(float3(Math::RadiansToDegrees(eulerAngles.x), Math::RadiansToDegrees(eulerAngles.y), Math::DegreesToRadians(eulerAngles.z))).GetCharArray()); } void DemoCamera::Update(const float &dt) { float moveDistance = m_fCameraSpeed * dt * ((m_turbo) ? 5.0f : 1.0f); float3 moveVector((m_rotation * m_moveDirection) * moveDistance); if (m_clippingEnabled && m_pWorld != NULL) { static const float gravity = 9.8f; const float PLAYER_WIDTH = 1.0f; //const float PLAYER_HEIGHT = 2.0f; const Physics::PhysicsProxy *pContactObject; float3 contactNormal; float3 contactPoint; float contactHitFraction; // new position float3 newPosition(m_position); if (moveVector.SquaredLength() > 0.0f) { // push a sphere if (m_pWorld->GetPhysicsWorld()->SweepSphere(PLAYER_WIDTH * 0.5f, newPosition, newPosition + moveVector, &pContactObject, &contactNormal, &contactPoint, &contactHitFraction)) { // alter position Log_DevPrintf("hit fraction %f", contactHitFraction); newPosition = newPosition - moveVector * contactHitFraction; } else { // no hit newPosition = newPosition + moveVector; } } // // apply gravity // moveVector = float3(0.0f, 0.0f, -9.8f) * dt; // // // push a sphere // if (m_pWorld->GetPhysicsWorld()->SweepSphere(PLAYER_WIDTH * 0.5f, newPosition, newPosition + moveVector, &pContactObject, &contactNormal, &contactPoint, &contactHitFraction)) // { // // alter position // Log_DevPrintf("gravity hit fraction %f", contactHitFraction); // newPosition = newPosition - moveVector * contactHitFraction; // } // else // { // // no hit // newPosition = newPosition + moveVector; // } // update position SetPosition(newPosition); } else { if (moveVector.SquaredLength() > Y_FLT_EPSILON) SetPosition(m_position + moveVector); } } bool DemoCamera::HandleSDLEvent(const union SDL_Event *pEvent) { if ((pEvent->type == SDL_KEYDOWN || pEvent->type == SDL_KEYUP) && !pEvent->key.repeat) { switch (pEvent->key.keysym.sym) { case SDLK_w: m_moveDirection += (pEvent->type == SDL_KEYDOWN) ? float3::UnitY : float3::NegativeUnitY; return true; case SDLK_s: m_moveDirection -= (pEvent->type == SDL_KEYDOWN) ? float3::UnitY : float3::NegativeUnitY; return true; case SDLK_d: m_moveDirection += (pEvent->type == SDL_KEYDOWN) ? float3::UnitX : float3::NegativeUnitX; return true; case SDLK_a: m_moveDirection -= (pEvent->type == SDL_KEYDOWN) ? float3::UnitX : float3::NegativeUnitX; return true; case SDLK_q: m_moveDirection += (pEvent->type == SDL_KEYDOWN) ? float3::UnitZ : float3::NegativeUnitZ; return true; case SDLK_e: m_moveDirection -= (pEvent->type == SDL_KEYDOWN) ? float3::UnitZ : float3::NegativeUnitZ; return true; case SDLK_LSHIFT: m_turbo = (pEvent->type == SDL_KEYDOWN); return true; } } else if (pEvent->type == SDL_MOUSEMOTION) { if (pEvent->motion.xrel != 0) ModYaw((float)-pEvent->motion.xrel); if (pEvent->motion.yrel != 0) ModPitch((float)-pEvent->motion.yrel); return true; } return false; } <file_sep>/Engine/Source/GameFramework/InterpolatorComponent.h #pragma once #include "Engine/Component.h" class InterpolatorComponent : public Component { DECLARE_COMPONENT_TYPEINFO(InterpolatorComponent, Component); DECLARE_COMPONENT_GENERIC_FACTORY(InterpolatorComponent); public: InterpolatorComponent(const ComponentTypeInfo *pTypeInfo = &s_typeInfo); virtual ~InterpolatorComponent(); // Property accessors const float GetMoveDuration() const { return m_moveDuration; } const float GetPauseDuration() const { return m_pauseDuration; } const bool GetReverseCycle() const { return m_reverseCycle; } const uint32 GetRepeatCount() const { return m_repeatCount; } const EasingFunction::Type GetEasingFunction() const { return (EasingFunction::Type)m_easingFunction; } const bool GetAutoActivate() const { return m_autoActivate; } // Property mutators void SetMoveDuration(float moveDuration); void SetPauseDuration(float pauseDuration); void SetReverseCycle(bool autoReverse); void SetRepeatCount(uint32 repeatCount); void SetEasingFunction(EasingFunction::Type easingFunction); void SetAutoActivate(bool autoActivate); // Creator void Create(const float3 &moveAmount = float3::Zero, const Quaternion &rotationAmount = Quaternion::Identity, const float3 &scaleAmount = float3::One, float moveDuration = 1.0f, float pauseDuration = 0.0f, bool reverseCycle = true, uint32 repeatCount = 0, EasingFunction::Type easingFunction = EasingFunction::Linear, bool autoActivate = true); // Reset to the initial state void Reset(); // Activate/resume the mover void Activate(); // Deactivate/pause the mover void Deactivate(); // Events virtual bool Initialize() override; virtual void OnAddToEntity(Entity *pEntity) override; virtual void OnRemoveFromEntity(Entity *pEntity) override; virtual void OnAddToWorld(World *pWorld) override; virtual void OnRemoveFromWorld(World *pWorld) override; virtual void OnLocalTransformChange() override; virtual void OnEntityTransformChange() override; virtual void Update(float timeSinceLastUpdate) override; private: float m_moveDuration; float m_pauseDuration; bool m_reverseCycle; uint32 m_repeatCount; uint32 m_easingFunction; bool m_autoActivate; bool m_active; Interpolator<float3> m_positionInterpolator; Interpolator<Quaternion> m_rotationInterpolator; Interpolator<float3> m_scaleInterpolator; // which interpolators are enabled enum ActiveInterpolator { ActiveInterpolator_Position = 1, ActiveInterpolator_Rotation = 2, ActiveInterpolator_Scale = 4, }; uint32 m_activeInterpolatorMask; void UpdateActiveInterpolators(); // property callbacks static void PropertyCallbackOnMoveDurationChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnPauseDurationChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnReverseCycleChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnRepeatCountChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnEasingFunctionChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); static void PropertyCallbackOnAutoActivateChange(InterpolatorComponent *pComponent, const void *pUserData = nullptr); };<file_sep>/Engine/Source/GameFramework/PositionInterpolatorComponent.cpp #include "GameFramework/PrecompiledHeader.h" #include "GameFramework/PositionInterpolatorComponent.h" #include "Engine/Entity.h" DEFINE_COMPONENT_TYPEINFO(PositionInterpolatorComponent); DEFINE_COMPONENT_GENERIC_FACTORY(PositionInterpolatorComponent); BEGIN_COMPONENT_PROPERTIES(PositionInterpolatorComponent) END_COMPONENT_PROPERTIES() PositionInterpolatorComponent::PositionInterpolatorComponent(const ComponentTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_moveDuration(1.0f), m_pauseDuration(0.0f), m_reverseCycle(true), m_repeatCount(0), m_easingFunction(EasingFunction::Linear), m_autoActivate(true), m_active(false), m_interpolator(float3::Zero, float3::Zero, m_moveDuration, m_pauseDuration, m_reverseCycle, m_repeatCount, m_easingFunction) { } PositionInterpolatorComponent::~PositionInterpolatorComponent() { } void PositionInterpolatorComponent::SetMoveDuration(float moveDuration) { if (m_moveDuration == moveDuration) return; m_moveDuration = moveDuration; m_interpolator.SetMoveDuration(moveDuration); Reset(); } void PositionInterpolatorComponent::SetPauseDuration(float pauseDuration) { if (m_pauseDuration == pauseDuration) return; m_pauseDuration = pauseDuration; m_interpolator.SetPauseDuration(pauseDuration); Reset(); } void PositionInterpolatorComponent::SetReverseCycle(bool autoReverse) { if (m_reverseCycle == autoReverse) return; m_reverseCycle = autoReverse; m_interpolator.SetReverseCycle(autoReverse); Reset(); } void PositionInterpolatorComponent::SetRepeatCount(uint32 repeatCount) { if (m_repeatCount == repeatCount) return; m_repeatCount = repeatCount; m_interpolator.SetRepeatCount(repeatCount); Reset(); } void PositionInterpolatorComponent::SetEasingFunction(EasingFunction::Type easingFunction) { if (m_easingFunction == easingFunction) return; m_easingFunction = easingFunction; m_interpolator.SetFunction(easingFunction); Reset(); } void PositionInterpolatorComponent::SetAutoActivate(bool autoActivate) { if (m_autoActivate == autoActivate) return; m_autoActivate = autoActivate; if (autoActivate && !m_active && IsAttachedToEntity()) m_pEntity->RegisterForUpdates(0.0f); } void PositionInterpolatorComponent::Create(const float3 &moveVector /* = float3::UnitZ */, float moveDuration /* = 1.0f */, float pauseDuration /* = 0.0f */, bool reverseCycle /* = true */, uint32 repeatCount /* = 0 */, EasingFunction::Type easingFunction /* = EasingFunction::Linear */, bool autoActivate /* = true */) { DebugAssert(moveVector.SquaredLength() > 0.0f && moveDuration > 0.0f); m_localPosition = moveVector; m_localRotation = Quaternion::Identity; m_localScale = float3::One; m_moveDuration = moveDuration; m_pauseDuration = pauseDuration; m_reverseCycle = reverseCycle; m_repeatCount = repeatCount; m_easingFunction = easingFunction; m_autoActivate = autoActivate; Initialize(); } void PositionInterpolatorComponent::Reset() { m_interpolator.Reset(); if (m_pEntity != nullptr) m_pEntity->SetPosition(m_interpolator.GetCurrentValue()); } void PositionInterpolatorComponent::Activate() { if (!m_active) { m_active = true; if (IsAttachedToEntity()) m_pEntity->RegisterForUpdates(0.0f); } } void PositionInterpolatorComponent::Deactivate() { m_active = false; } bool PositionInterpolatorComponent::Initialize() { if (!BaseClass::Initialize()) return false; // initialize the interpolator m_interpolator.SetValues(float3::Zero, m_localPosition); m_interpolator.SetMoveDuration(m_moveDuration); m_interpolator.SetPauseDuration(m_pauseDuration); m_interpolator.SetReverseCycle(m_reverseCycle); m_interpolator.SetRepeatCount(m_repeatCount); m_interpolator.SetFunction(m_easingFunction); m_interpolator.Reset(); return true; } void PositionInterpolatorComponent::OnAddToEntity(Entity *pEntity) { BaseClass::OnAddToEntity(pEntity); // extract the starting position from the entity's current position m_interpolator.SetValues(pEntity->GetPosition(), pEntity->GetPosition() + m_localPosition); m_interpolator.Reset(); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate && pEntity->IsInWorld()) pEntity->RegisterForUpdates(0.0f); } void PositionInterpolatorComponent::OnRemoveFromEntity(Entity *pEntity) { // ensure we're deactivated m_active = false; // nuke the starting position m_interpolator.SetValues(float3::Zero, m_localPosition); m_interpolator.Reset(); BaseClass::OnRemoveFromEntity(pEntity); } void PositionInterpolatorComponent::OnAddToWorld(World *pWorld) { BaseClass::OnAddToWorld(pWorld); // if autostarting, ensure the entity is registered for ticks every frame if (m_autoActivate || m_active) m_pEntity->RegisterForUpdates(0.0f); } void PositionInterpolatorComponent::OnRemoveFromWorld(World *pWorld) { BaseClass::OnRemoveFromWorld(pWorld); } void PositionInterpolatorComponent::OnLocalTransformChange() { BaseClass::OnLocalTransformChange(); // update the ending position only, the starting position will still be valid m_interpolator.SetEndValue(m_interpolator.GetStartValue() + m_localPosition); } void PositionInterpolatorComponent::OnEntityTransformChange() { BaseClass::OnEntityTransformChange(); // is this an actual change of entity position? if (m_pEntity->GetPosition() != m_interpolator.GetCurrentValue()) { // update the starting position, and ending position m_interpolator.SetValues(m_pEntity->GetPosition(), m_pEntity->GetPosition() + m_localPosition); } } void PositionInterpolatorComponent::Update(float timeSinceLastUpdate) { // this is where the magic happens if (!m_active && m_autoActivate) Activate(); // active? if (m_active) { // update interpolator m_interpolator.Update(timeSinceLastUpdate); // and the position if it should be updated if (m_pEntity->GetPosition() != m_interpolator.GetCurrentValue()) m_pEntity->SetPosition(m_interpolator.GetCurrentValue()); // if all cycles are complete, deactivate ourselves if (!m_interpolator.IsActive()) m_active = false; } } <file_sep>/Engine/Source/BlockEngine/BlockWorldVertexFactory.h #pragma once #include "Renderer/VertexFactory.h" class BlockWorldVertexFactory : public VertexFactory { DECLARE_VERTEX_FACTORY_TYPE_INFO(BlockWorldVertexFactory, VertexFactory); public: #pragma pack(push, 1) struct Vertex { float3 Position; float3 TexCoord; uint32 Color; //float3 Tangent; //float3 Binormal; //float3 Normal; uint32 TangentAndSign; uint32 Normal; Vertex() {} Vertex(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal); Vertex(const float3 &position, const float3 &texcoord, uint32 color, uint32 packedTangentAndSign, uint32 packedNormal); Vertex(const Vertex &v) { Y_memcpy(this, &v, sizeof(*this)); } void Set(const float3 &position, const float3 &texcoord, uint32 color, const float3 &tangent, const float3 &binormal, const float3 &normal); void Set(const float3 &position, const float3 &texcoord, uint32 color, uint32 packedTangentAndSign, uint32 packedNormal); }; #pragma pack(pop) public: static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); static uint32 GetVertexElementsDesc(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, uint32 flags, GPU_VERTEX_ELEMENT_DESC pElementsDesc[GPU_INPUT_LAYOUT_MAX_ELEMENTS]); }; <file_sep>/Engine/Source/MathLib/Vectorh.cpp #include "MathLib/Vectorh.h" #include "MathLib/Vectorf.h" Vector2h::Vector2h(const Vector2f &v) : x((v.x)), y((v.y)) {} Vector2h::operator Vector2f() const { return Vector2f((x), (y)); } Vector3h::Vector3h(const Vector3f &v) : x((v.x)), y((v.y)), z((v.z)) {} Vector3h::operator Vector3f() const { return Vector3f((x), (y), (z)); } Vector4h::Vector4h(const Vector4f &v) : x((v.x)), y((v.y)), z((v.z)), w((v.w)) {} Vector4h::operator Vector4f() const { return Vector4f((x), (y), (z), (w)); } <file_sep>/Engine/Source/Engine/BlockMeshVolume.h #pragma once #include "Engine/Common.h" #include "Engine/BlockPalette.h" #include "MathLib/CollisionDetection.h" typedef uint8 BlockVolumeBlockType; class BlockMeshVolume { public: BlockMeshVolume(); BlockMeshVolume(const BlockPalette *pPalette, float scale, const int3 &minCoordinates, const int3 &maxCoordinates); BlockMeshVolume(const BlockMeshVolume &copy); ~BlockMeshVolume(); const BlockPalette *GetPalette() const { return m_pPalette; } const float GetScale() const { return m_scale; } const int3 &GetMinCoordinates() const { return m_minCoordinates; } const int3 &GetMaxCoordinates() const { return m_maxCoordinates; } const uint32 GetWidth() const { return m_width; } const uint32 GetLength() const { return m_length; } const uint32 GetHeight() const { return m_height; } const BlockVolumeBlockType *GetData() const { return m_pData; } // calculate the bounding box AABox CalculateBoundingBox() const; // calculate the active bounding box AABox CalculateActiveBoundingBox() const; // get volume data pointer BlockVolumeBlockType *GetData() { return m_pData; } // settings void SetPalette(const BlockPalette *pPalette); void SetScale(float scale) { m_scale = scale; } // block management BlockVolumeBlockType GetBlock(int32 x, int32 y, int32 z) const; void SetBlock(int32 x, int32 y, int32 z, BlockVolumeBlockType value); // block management via vectors BlockVolumeBlockType GetBlock(const int3 &blockPosition) const { return GetBlock(blockPosition.x, blockPosition.y, blockPosition.z); } void SetBlock(const int3 &blockPosition, BlockVolumeBlockType value) { SetBlock(blockPosition.x, blockPosition.y, blockPosition.z, value); } // get active (nonzero) coordinate range bool GetActiveCoordinatesRange(int3 *pMinActiveCoordinates, int3 *pMaxActiveCoordinates) const; // clear mesh void Clear(); // resize mesh void Resize(const int3 &newMinCoordinates, const int3 &newMaxCoordinates); // center the mesh void Center(); // shrink the mesh to the minimum size possible void Shrink(); // move blocks void MoveBlock(const int3 &blockCoordinates, const int3 &moveDelta); void MoveBlocks(const int3 &selectionMin, const int3 &selectionMax, const int3 &moveDelta); // raycasting bool RayCastTime(const Ray &ray, int3 *pIntersectingBlock, float *pIntersectionTime, bool exitAtFirstIntersection = false) const; bool RayCastTimeFace(const Ray &ray, int3 *pIntersectingBlock, float *pIntersectionTime, CUBE_FACE *pIntersectingFace, bool exitAtFirstIntersection = false) const; // collision helpers // callback is in format of callback(const int3 &blockLocation) template<typename CALLBACK_TYPE> void EnumerateBlocksInBox(const AABox &box, CALLBACK_TYPE callback) const; // callback is in format of callback(const int3 &blockLocation) template<typename CALLBACK_TYPE> void EnumerateBlocksInSphere(const Sphere &sphere, CALLBACK_TYPE callback) const; // callback is in format of callback(const int3 &blockLocation, const float3 &contactNormal, const float3 &contactPoint) template<typename CALLBACK_TYPE> void EnumerateBlocksIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const; // callback is in format of callback(const int3 &blockLocation, const float3 &contactNormal, const float3 &contactPoint) template<typename CALLBACK_TYPE> void EnumerateBlocksIntersectingSphere(const Sphere &sphere, CALLBACK_TYPE callback) const; // callback is in format of callback(const float3 vertices[3]) template<typename CALLBACK_TYPE> void EnumerateTrianglesIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const; // copy operator BlockMeshVolume &operator=(const BlockMeshVolume &copy); private: const BlockPalette *m_pPalette; float m_scale; int3 m_minCoordinates; int3 m_maxCoordinates; uint32 m_width, m_length, m_height; BlockVolumeBlockType *m_pData; }; template<typename CALLBACK_TYPE> void BlockMeshVolume::EnumerateBlocksInBox(const AABox &box, CALLBACK_TYPE callback) const { // get the range to search float inverseScale = 1.0f / m_scale; SIMDVector3f boxMinBounds(box.GetMinBounds()); SIMDVector3f boxMaxBounds(box.GetMaxBounds()); SIMDVector3f minSearchFloat(boxMinBounds * inverseScale); SIMDVector3f maxSearchFloat(boxMaxBounds * inverseScale); SIMDVector3i minSearch(SIMDVector3i(Math::Truncate(Math::Floor(minSearchFloat.x)), Math::Truncate(Math::Floor(minSearchFloat.y)), Math::Truncate(Math::Floor(minSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); SIMDVector3i maxSearch(SIMDVector3i(Math::Truncate(Math::Ceil(maxSearchFloat.x)), Math::Truncate(Math::Ceil(maxSearchFloat.y)), Math::Truncate(Math::Ceil(maxSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); // search blocks for (int32 z = minSearch.z; z <= maxSearch.z; z++) { for (int32 y = minSearch.y; y <= maxSearch.y; y++) { for (int32 x = minSearch.z; x <= maxSearch.z; x++) { BlockVolumeBlockType blockType = GetBlock(x, y, z); if (blockType == 0) continue; callback(int3(x, y, z)); } } } } template<typename CALLBACK_TYPE> void BlockMeshVolume::EnumerateBlocksInSphere(const Sphere &sphere, CALLBACK_TYPE callback) const { // get the range to search float inverseScale = 1.0f / m_scale; AABox sphereBox(AABox::FromSphere(sphere)); SIMDVector3f sphereBoxMinBounds(sphereBox.GetMinBounds()); SIMDVector3f sphereBoxMaxBounds(sphereBox.GetMaxBounds()); SIMDVector3f minSearchFloat(sphereBoxMinBounds * inverseScale); SIMDVector3f maxSearchFloat(sphereBoxMaxBounds * inverseScale); SIMDVector3i minSearch(SIMDVector3i(Math::Truncate(Math::Floor(minSearchFloat.x)), Math::Truncate(Math::Floor(minSearchFloat.y)), Math::Truncate(Math::Floor(minSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); SIMDVector3i maxSearch(SIMDVector3i(Math::Truncate(Math::Ceil(maxSearchFloat.x)), Math::Truncate(Math::Ceil(maxSearchFloat.y)), Math::Truncate(Math::Ceil(maxSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); // search blocks for (int32 z = minSearch.z; z <= maxSearch.z; z++) { for (int32 y = minSearch.y; y <= maxSearch.y; y++) { for (int32 x = minSearch.z; x <= maxSearch.z; x++) { BlockVolumeBlockType blockType = GetBlock(x, y, z); if (blockType == 0) continue; callback(int3(x, y, z)); } } } } template<typename CALLBACK_TYPE> void BlockMeshVolume::EnumerateBlocksIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const { // get the range to search float inverseScale = 1.0f / m_scale; SIMDVector3f boxMinBounds(box.GetMinBounds()); SIMDVector3f boxMaxBounds(box.GetMaxBounds()); SIMDVector3f minSearchFloat(boxMinBounds * inverseScale); SIMDVector3f maxSearchFloat(boxMaxBounds * inverseScale); SIMDVector3i minSearch(SIMDVector3i(Math::Truncate(Math::Floor(minSearchFloat.x)), Math::Truncate(Math::Floor(minSearchFloat.y)), Math::Truncate(Math::Floor(minSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); SIMDVector3i maxSearch(SIMDVector3i(Math::Truncate(Math::Ceil(maxSearchFloat.x)), Math::Truncate(Math::Ceil(maxSearchFloat.y)), Math::Truncate(Math::Ceil(maxSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); // search blocks for (int32 z = minSearch.z; z <= maxSearch.z; z++) { for (int32 y = minSearch.y; y <= maxSearch.y; y++) { for (int32 x = minSearch.z; x <= maxSearch.z; x++) { BlockVolumeBlockType blockType = GetBlock(x, y, z); if (blockType == 0) continue; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType((uint32)blockType); if (pBlockType != NULL && pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // calculate bounds of block SIMDVector3f blockMinBounds(SIMDVector3f((float)x, (float)y, (float)z) * m_scale); SIMDVector3f blockMaxBounds(blockMinBounds + m_scale); float3 contactNormal, contactPoint; // intersects? if (CollisionDetection::AABoxIntersectsAABox(boxMinBounds, boxMaxBounds, blockMinBounds, blockMaxBounds, contactNormal, contactPoint)) { contactPoint *= m_scale; callback(int3(x, y, z), contactNormal, contactPoint); } } } } } } template<typename CALLBACK_TYPE> void BlockMeshVolume::EnumerateBlocksIntersectingSphere(const Sphere &sphere, CALLBACK_TYPE callback) const { // get the range to search float inverseScale = 1.0f / m_scale; SIMDVector3f sphereCenter(sphere.GetCenter()); float sphereRadius = sphere.GetRadius(); AABox sphereBox(AABox::FromSphere(sphere)); SIMDVector3f sphereBoxMinBounds(sphereBox.GetMinBounds()); SIMDVector3f sphereBoxMaxBounds(sphereBox.GetMaxBounds()); SIMDVector3f minSearchFloat(sphereBoxMinBounds * inverseScale); SIMDVector3f maxSearchFloat(sphereBoxMaxBounds * inverseScale); SIMDVector3i minSearch(SIMDVector3i(Math::Truncate(Math::Floor(minSearchFloat.x)), Math::Truncate(Math::Floor(minSearchFloat.y)), Math::Truncate(Math::Floor(minSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); SIMDVector3i maxSearch(SIMDVector3i(Math::Truncate(Math::Ceil(maxSearchFloat.x)), Math::Truncate(Math::Ceil(maxSearchFloat.y)), Math::Truncate(Math::Ceil(maxSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); // search blocks for (int32 z = minSearch.z; z <= maxSearch.z; z++) { for (int32 y = minSearch.y; y <= maxSearch.y; y++) { for (int32 x = minSearch.z; x <= maxSearch.z; x++) { BlockVolumeBlockType blockType = GetBlock(x, y, z); if (blockType == 0) continue; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType((uint32)blockType); if (pBlockType != NULL && pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // calculate bounds of block SIMDVector3f blockMinBounds(SIMDVector3f((float)x, (float)y, (float)z) * m_scale); SIMDVector3f blockMaxBounds(blockMinBounds + m_scale); float3 contactNormal, contactPoint; // intersects? if (CollisionDetection::SphereIntersectsBox(sphereCenter, sphereRadius, blockMinBounds, blockMaxBounds, contactNormal, contactPoint)) { contactPoint *= m_scale; callback(int3(x, y, z), contactNormal, contactPoint); } } } } } } template<typename CALLBACK_TYPE> void BlockMeshVolume::EnumerateTrianglesIntersectingBox(const AABox &box, CALLBACK_TYPE callback) const { // get the range to search float scale = m_scale; float inverseScale = 1.0f / scale; SIMDVector3f boxMinBounds(box.GetMinBounds()); SIMDVector3f boxMaxBounds(box.GetMaxBounds()); SIMDVector3f minSearchFloat(boxMinBounds * inverseScale); SIMDVector3f maxSearchFloat(boxMaxBounds * inverseScale); SIMDVector3i minSearch(SIMDVector3i(Math::Truncate(Math::Floor(minSearchFloat.x)), Math::Truncate(Math::Floor(minSearchFloat.y)), Math::Truncate(Math::Floor(minSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); SIMDVector3i maxSearch(SIMDVector3i(Math::Truncate(Math::Ceil(maxSearchFloat.x)), Math::Truncate(Math::Ceil(maxSearchFloat.y)), Math::Truncate(Math::Ceil(maxSearchFloat.z))).Clamp(m_minCoordinates, m_maxCoordinates)); // search blocks for (int32 z = minSearch.z; z <= maxSearch.z; z++) { for (int32 y = minSearch.y; y <= maxSearch.y; y++) { for (int32 x = minSearch.z; x <= maxSearch.z; x++) { BlockVolumeBlockType blockType = GetBlock(x, y, z); if (blockType == 0) continue; const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType((uint32)blockType); if (pBlockType != NULL && pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // calculate bounds of block float sx = (float)x * scale; float sy = (float)y * scale; float sz = (float)z * scale; SIMDVector3f blockMinBounds(sx, sy, sz); SIMDVector3f blockMaxBounds(blockMinBounds + m_scale); // intersects? if (CollisionDetection::AABoxIntersectsAABox(boxMinBounds, boxMaxBounds, blockMinBounds, blockMaxBounds)) { // generate block triangles float3 blockVertices[8] = { float3( sx, sy, sz ), // bottom-front-left float3( sx + scale, sy, sz ), // bottom-front-right float3( sx, sy + scale, sz ), // bottom-back-left float3( sx + scale, sy + scale, sz ), // bottom-back-right float3( sx, sy, sz + scale ), // top-front-left float3( sx + scale, sy, sz + scale ), // top-front-right float3( sx, sy + scale, sz + scale ), // top-back-left float3( sx + scale, sy + scale, sz + scale ) // top-back-right }; float3 triangleVerticesA[3]; float3 triangleVerticesB[3]; // right face triangleVerticesA[0] = blockVertices[5]; triangleVerticesA[1] = blockVertices[1]; triangleVerticesA[2] = blockVertices[3]; triangleVerticesB[0] = blockVertices[5]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[7]; callback(triangleVerticesA); callback(triangleVerticesB); // left face triangleVerticesA[0] = blockVertices[4]; triangleVerticesA[1] = blockVertices[0]; triangleVerticesA[2] = blockVertices[2]; triangleVerticesB[0] = blockVertices[2]; triangleVerticesB[1] = blockVertices[4]; triangleVerticesB[2] = blockVertices[6]; callback(triangleVerticesA); callback(triangleVerticesB); // back face triangleVerticesA[0] = blockVertices[6]; triangleVerticesA[1] = blockVertices[7]; triangleVerticesA[2] = blockVertices[2]; triangleVerticesB[0] = blockVertices[7]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[2]; callback(triangleVerticesA); callback(triangleVerticesB); // front face triangleVerticesA[0] = blockVertices[0]; triangleVerticesA[1] = blockVertices[5]; triangleVerticesA[2] = blockVertices[4]; triangleVerticesB[0] = blockVertices[4]; triangleVerticesB[1] = blockVertices[1]; triangleVerticesB[2] = blockVertices[5]; callback(triangleVerticesA); callback(triangleVerticesB); // top face triangleVerticesA[0] = blockVertices[6]; triangleVerticesA[1] = blockVertices[5]; triangleVerticesA[2] = blockVertices[7]; triangleVerticesB[0] = blockVertices[6]; triangleVerticesB[1] = blockVertices[4]; triangleVerticesB[2] = blockVertices[5]; callback(triangleVerticesA); callback(triangleVerticesB); // bottom face triangleVerticesA[0] = blockVertices[0]; triangleVerticesA[1] = blockVertices[2]; triangleVerticesA[2] = blockVertices[3]; triangleVerticesB[0] = blockVertices[2]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[1]; callback(triangleVerticesA); callback(triangleVerticesB); } } } } } } <file_sep>/Engine/Source/MathLib/SIMDMatrixi_scalar.h #include "MathLib/Common.h" #include "YBaseLib/Assert.h" #if 0 struct int2x2; struct int3x3; struct int3x4; struct int4x4; struct SIMDMatrix2i { SIMDMatrix2i() {} // set everything at once SIMDMatrix2i(const int32 E00, const int32 E01, const int32 E10, const int32 E11); // sets the diagonal to the specified value (1 == identity) SIMDMatrix2i(const int32 Diagonal); // assumes row-major packing order with vectors in columns SIMDMatrix2i(const int32 *p); // copy SIMDMatrix2i(const SIMDMatrix2i &v); // downscaling/from floatx SIMDMatrix2i(const int2x2 &v); // setters void Set(const int32 E00, const int32 E01, const int32 E10, const int32 E11); void SetIdentity(); void SetZero(); // column accessors Vector2i GetColumn(uint32 j) const; void SetColumn(uint32 j, const Vector2i &v); // for converting to/from opengl matrices void SetTranspose(const int32 *pElements); void GetTranspose(int32 *pElements) const; // new matrix SIMDMatrix2i Transpose() const; // in-place void TransposeInPlace(); // to intx const int2x2 &GetInt2x2() const { return reinterpret_cast<const int2x2 &>(*this); } int2x2 &GetInt2x2() { return reinterpret_cast<int2x2 &>(*this); } const int2 &GetRowInt2(uint32 i) const { return reinterpret_cast<const int2 &>(Row[i]); } int2 GetColumnInt2(uint32 i) const; operator const int2x2 &() const { return reinterpret_cast<const int2x2 &>(*this); } operator int2x2 &() { return reinterpret_cast<int2x2 &>(*this); } // row/field accessors const Vector2i &operator[](uint32 i) const { DebugAssert(i < 4); return reinterpret_cast<const Vector2i &>(Row[i]); } const Vector2i &GetRow(uint32 i) const { DebugAssert(i < 4); return reinterpret_cast<const Vector2i &>(Row[i]); } const int32 &operator()(uint32 i, uint32 j) const { DebugAssert(i < 4 && j < 4); return Row[i][j]; } Vector2i &operator[](uint32 i) { DebugAssert(i < 4); return reinterpret_cast<Vector2i &>(Row[i]); } void SetRow(uint32 i, const Vector2i &v) { DebugAssert(i < 4); reinterpret_cast<Vector2i &>(Row[i]) = v; } int32 &operator()(uint32 i, uint32 j) { DebugAssert(i < 4 && j < 4); return Row[i][j]; } // assignment operators SIMDMatrix2i &operator=(const SIMDMatrix2i &v); SIMDMatrix2i &operator=(const int32 Diagonal); SIMDMatrix2i &operator=(const int32 *p); SIMDMatrix2i &operator=(const int2x2 &v); // various operators SIMDMatrix2i &operator*=(const SIMDMatrix2i &v); SIMDMatrix2i &operator*=(const int32 v); SIMDMatrix2i operator*(const SIMDMatrix2i &v) const; SIMDMatrix2i operator*(int32 v) const; SIMDMatrix2i operator-() const; // matrix * vector Vector2i operator*(const Vector2i &v) const; // constants static const SIMDMatrix2i &Zero, &Identity; public: union { int32 Elements[4]; int32 Row[2][2]; struct { int32 m00, m01; int32 m10, m11; }; }; }; #endif <file_sep>/Editor/Source/Editor/BlockMeshEditor/ui_EditorBlockMeshEditor.h #pragma once class Ui_EditorBlockMeshEditor { public: QMainWindow *mainWindow; // actions QAction *actionSaveMesh; QAction *actionSaveMeshAs; QAction *actionClose; QAction *actionEditUndo; QAction *actionEditRedo; QAction *actionCameraPerspective; QAction *actionCameraArcball; QAction *actionCameraIsometric; QAction *actionViewWireframe; QAction *actionViewUnlit; QAction *actionViewLit; QAction *actionViewFlagShadows; QAction *actionViewFlagWireframeOverlay; QAction *actionWidgetCamera; QAction *actionWidgetSelectBlocks; QAction *actionWidgetSelectArea; QAction *actionWidgetPlaceBlocks; QAction *actionWidgetDeleteBlocks; QAction *actionWidgetLightManipulator; // menus QMenu *menuMesh; QMenu *menuEdit; QMenu *menuCamera; QMenu *menuView; QMenu *menuWidget; QMenu *menuHelp; // toolbar items QComboBox *activeLODComboBox; // left pane EditorRendererSwapChainWidget *swapChainWidget; // right pane // camera mode QDockWidget *cameraDock; // select blocks mode QDockWidget *selectBlocksAreaDock; // place blocks mode QDockWidget *placeBlocksDock; QTabWidget *placeBlocksWidget; QWidget *placeBlocksWidgetPaletteIconsWidget; FlowLayout *placeBlocksWidgetPaletteIconsFlowLayout; QToolButton *placeBlocksWidgetPaletteIcons[BLOCK_MESH_MAX_BLOCK_TYPES]; QListWidget *placeBlocksWidgetPaletteList; // delete blocks mode QDockWidget *deleteBlocksDock; // light manipulator mode QDockWidget *lightManipulatorDock; // widgets QMenuBar *menubar; QToolBar *toolbar; QStatusBar *statusBar; QLabel *statusBarMainText; QLabel *statusBarMeshSize; QProgressBar *statusBarProgressBar; QLabel *statusBarFPS; void CreateUI(QMainWindow *pMainWindow) { static const char *TRANSLATION_CONTEXT = "EditorBlockMeshEditor"; //QVBoxLayout *verticalLayout; mainWindow = pMainWindow; mainWindow->resize(800, 600); actionSaveMesh = new QAction(pMainWindow); actionSaveMesh->setIcon(QIcon(QStringLiteral(":/editor/icons/saveHS.png"))); actionSaveMesh->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Save Mesh")); actionSaveMeshAs = new QAction(pMainWindow); actionSaveMeshAs->setIcon(QIcon(QStringLiteral(":/editor/icons/saveHS.png"))); actionSaveMeshAs->setText(QApplication::translate(TRANSLATION_CONTEXT, "Save Mesh &As")); actionClose = new QAction(pMainWindow); actionClose->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Close")); actionEditUndo = new QAction(pMainWindow); actionEditUndo->setIcon(QIcon(QStringLiteral(":/editor/icons/Edit_UndoHS.png"))); actionEditUndo->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Undo")); actionEditRedo = new QAction(pMainWindow); actionEditRedo->setIcon(QIcon(QStringLiteral(":/editor/icons/Edit_RedoHS.png"))); actionEditRedo->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Redo")); actionCameraPerspective = new QAction(pMainWindow); actionCameraPerspective->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Perspective.png"))); actionCameraPerspective->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Perspective Camera")); actionCameraPerspective->setCheckable(true); actionCameraArcball = new QAction(pMainWindow); actionCameraArcball->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Side.png"))); actionCameraArcball->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Arcball Camera")); actionCameraArcball->setCheckable(true); actionCameraIsometric = new QAction(pMainWindow); actionCameraIsometric->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_View_Isometric.png"))); actionCameraIsometric->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Isometric Camera")); actionCameraIsometric->setCheckable(true); actionViewWireframe = new QAction(pMainWindow); actionViewWireframe->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Wireframe.png"))); actionViewWireframe->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Wireframe View")); actionViewWireframe->setCheckable(true); actionViewUnlit = new QAction(pMainWindow); actionViewUnlit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Unlit.png"))); actionViewUnlit->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Unlit View")); actionViewUnlit->setCheckable(true); actionViewLit = new QAction(pMainWindow); actionViewLit->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderMode_Lit.png"))); actionViewLit->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Lit View")); actionViewLit->setCheckable(true); actionViewFlagShadows = new QAction(pMainWindow); actionViewFlagShadows->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_Shadows.png"))); actionViewFlagShadows->setText(QApplication::translate(TRANSLATION_CONTEXT, "Enable &Shadows")); actionViewFlagShadows->setCheckable(true); actionViewFlagWireframeOverlay = new QAction(pMainWindow); actionViewFlagWireframeOverlay->setIcon(QIcon(QStringLiteral(":/editor/icons/Viewport_RenderFlag_WireframeOverlay.png"))); actionViewFlagWireframeOverlay->setText(QApplication::translate(TRANSLATION_CONTEXT, "Enable Wireframe &Overlay")); actionViewFlagWireframeOverlay->setCheckable(true); actionWidgetCamera = new QAction(pMainWindow); actionWidgetCamera->setIcon(QIcon(QStringLiteral(":/editor/icons/camera.png"))); actionWidgetCamera->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Camera Widget")); actionWidgetCamera->setCheckable(true); actionWidgetSelectBlocks = new QAction(pMainWindow); actionWidgetSelectBlocks->setIcon(QIcon(QStringLiteral(":/editor/icons/EditCodeHS.png"))); actionWidgetSelectBlocks->setText(QApplication::translate(TRANSLATION_CONTEXT, "Select &Blocks Widget")); actionWidgetSelectBlocks->setCheckable(true); actionWidgetSelectArea = new QAction(pMainWindow); actionWidgetSelectArea->setIcon(QIcon(QStringLiteral(":/editor/icons/MultiplePagesHH.png"))); actionWidgetSelectArea->setText(QApplication::translate(TRANSLATION_CONTEXT, "Select &Area Widget")); actionWidgetSelectArea->setCheckable(true); actionWidgetPlaceBlocks = new QAction(pMainWindow); actionWidgetPlaceBlocks->setIcon(QIcon(QStringLiteral(":/editor/icons/BreakpointHS.png"))); actionWidgetPlaceBlocks->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Place Blocks Widget")); actionWidgetPlaceBlocks->setCheckable(true); actionWidgetDeleteBlocks = new QAction(pMainWindow); actionWidgetDeleteBlocks->setIcon(QIcon(QStringLiteral(":/editor/icons/DeleteHS.png"))); actionWidgetDeleteBlocks->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Delete Blocks Widget")); actionWidgetDeleteBlocks->setCheckable(true); actionWidgetLightManipulator = new QAction(pMainWindow); actionWidgetLightManipulator->setIcon(QIcon(QStringLiteral(":/editor/icons/Alerts.png"))); actionWidgetLightManipulator->setText(QApplication::translate(TRANSLATION_CONTEXT, "&Light Manipulator Widget")); actionWidgetLightManipulator->setCheckable(true); menuMesh = new QMenu(pMainWindow); menuMesh->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&Mesh")); menuMesh->addAction(actionSaveMesh); menuMesh->addAction(actionSaveMeshAs); menuMesh->addSeparator(); menuMesh->addAction(actionClose); menuEdit = new QMenu(pMainWindow); menuEdit->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&Edit")); menuEdit->addAction(actionEditUndo); menuEdit->addAction(actionEditRedo); menuCamera = new QMenu(pMainWindow); menuCamera->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&Camera")); menuCamera->addAction(actionCameraPerspective); menuCamera->addAction(actionCameraArcball); menuCamera->addAction(actionCameraIsometric); menuView = new QMenu(pMainWindow); menuView->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&View")); menuView->addAction(actionViewWireframe); menuView->addAction(actionViewUnlit); menuView->addAction(actionViewLit); menuView->addSeparator(); menuView->addAction(actionViewFlagShadows); menuView->addAction(actionViewFlagWireframeOverlay); menuWidget = new QMenu(pMainWindow); menuWidget->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&Widget")); menuWidget->addAction(actionWidgetCamera); menuWidget->addAction(actionWidgetSelectBlocks); menuWidget->addAction(actionWidgetSelectArea); menuWidget->addAction(actionWidgetPlaceBlocks); menuWidget->addAction(actionWidgetDeleteBlocks); menuWidget->addAction(actionWidgetLightManipulator); menuHelp = new QMenu(pMainWindow); menuHelp->setTitle(QApplication::translate(TRANSLATION_CONTEXT, "&Help")); menubar = new QMenuBar(pMainWindow); menubar->addMenu(menuMesh); menubar->addMenu(menuEdit); menubar->addMenu(menuCamera); menubar->addMenu(menuView); menubar->addMenu(menuWidget); menubar->addMenu(menuHelp); activeLODComboBox = new QComboBox(pMainWindow); activeLODComboBox->setEditable(false); toolbar = new QToolBar(pMainWindow); toolbar->setIconSize(QSize(16, 16)); toolbar->addAction(actionSaveMesh); toolbar->addSeparator(); toolbar->addAction(actionEditUndo); toolbar->addAction(actionEditRedo); toolbar->addSeparator(); toolbar->addWidget(activeLODComboBox); toolbar->addSeparator(); toolbar->addAction(actionCameraPerspective); toolbar->addAction(actionCameraArcball); toolbar->addAction(actionCameraIsometric); toolbar->addSeparator(); toolbar->addAction(actionViewWireframe); toolbar->addAction(actionViewUnlit); toolbar->addAction(actionViewLit); toolbar->addSeparator(); toolbar->addAction(actionViewFlagShadows); toolbar->addAction(actionViewFlagWireframeOverlay); toolbar->addSeparator(); toolbar->addAction(actionWidgetCamera); toolbar->addAction(actionWidgetSelectBlocks); toolbar->addAction(actionWidgetSelectArea); toolbar->addAction(actionWidgetPlaceBlocks); toolbar->addAction(actionWidgetDeleteBlocks); toolbar->addAction(actionWidgetLightManipulator); statusBar = new QStatusBar(pMainWindow); { statusBarMainText = new QLabel(statusBar); statusBar->addWidget(statusBarMainText, 1); statusBarMeshSize = new QLabel(statusBar); statusBar->addWidget(statusBarMeshSize); statusBarProgressBar = new QProgressBar(statusBar); statusBarProgressBar->setTextVisible(false); statusBarProgressBar->setFixedWidth(100); statusBarProgressBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); statusBarProgressBar->setRange(0, 1); statusBarProgressBar->setValue(1); statusBar->addWidget(statusBarProgressBar); statusBarFPS = new QLabel(statusBar); statusBar->addWidget(statusBarFPS); } swapChainWidget = new EditorRendererSwapChainWidget(pMainWindow); swapChainWidget->setFocusPolicy(Qt::FocusPolicy(Qt::TabFocus | Qt::ClickFocus)); swapChainWidget->setMouseTracking(true); cameraDock = new QDockWidget(pMainWindow); cameraDock->setWindowTitle(QApplication::translate(TRANSLATION_CONTEXT, "Camera Settings")); cameraDock->hide(); selectBlocksAreaDock = new QDockWidget(pMainWindow); selectBlocksAreaDock->setWindowTitle(QApplication::translate(TRANSLATION_CONTEXT, "Select Blocks/Area Settings")); selectBlocksAreaDock->hide(); placeBlocksDock = new QDockWidget(pMainWindow); placeBlocksWidget = new QTabWidget(placeBlocksDock); placeBlocksWidget->setTabsClosable(false); placeBlocksWidget->setTabPosition(QTabWidget::South); placeBlocksWidget->setTabShape(QTabWidget::Rounded); { placeBlocksWidgetPaletteIconsWidget = new QWidget(placeBlocksWidget); //placeBlocksWidgetPaletteIconsWidget->setStyleSheet(QStringLiteral("background-color: black;")); { placeBlocksWidgetPaletteIconsFlowLayout = new FlowLayout(placeBlocksWidgetPaletteIconsWidget, 0, 0, 0); Y_memzero(placeBlocksWidgetPaletteIcons, sizeof(placeBlocksWidgetPaletteIcons)); } placeBlocksWidgetPaletteIconsWidget->setLayout(placeBlocksWidgetPaletteIconsFlowLayout); placeBlocksWidget->addTab(placeBlocksWidgetPaletteIconsWidget, QApplication::translate(TRANSLATION_CONTEXT, "Icons")); placeBlocksWidgetPaletteList = new QListWidget(placeBlocksWidget); placeBlocksWidget->addTab(placeBlocksWidgetPaletteList, QApplication::translate(TRANSLATION_CONTEXT, "List")); } placeBlocksDock->setWindowTitle(QApplication::translate(TRANSLATION_CONTEXT, "Place Blocks Settings")); placeBlocksDock->setWidget(placeBlocksWidget); placeBlocksDock->hide(); deleteBlocksDock = new QDockWidget(pMainWindow); deleteBlocksDock->setWindowTitle(QApplication::translate(TRANSLATION_CONTEXT, "Delete Blocks Settings")); deleteBlocksDock->hide(); lightManipulatorDock = new QDockWidget(pMainWindow); lightManipulatorDock->setWindowTitle(QApplication::translate(TRANSLATION_CONTEXT, "Light Manipulator Settings")); lightManipulatorDock->hide(); pMainWindow->setMenuBar(menubar); pMainWindow->addToolBar(toolbar); pMainWindow->setCentralWidget(swapChainWidget); pMainWindow->setStatusBar(statusBar); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, cameraDock); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, selectBlocksAreaDock); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, placeBlocksDock); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, deleteBlocksDock); pMainWindow->addDockWidget(Qt::RightDockWidgetArea, lightManipulatorDock); QMetaObject::connectSlotsByName(pMainWindow); } void UpdateUIForOpenMesh(const char *meshName) { SmallString title; title.Format("Block Mesh Editor - %s", meshName); mainWindow->setWindowTitle(ConvertStringToQString(title)); } void UpdateUIForCameraMode(EDITOR_CAMERA_MODE cameraMode) { actionCameraPerspective->setChecked((cameraMode == EDITOR_CAMERA_MODE_PERSPECTIVE)); actionCameraArcball->setChecked((cameraMode == EDITOR_CAMERA_MODE_ARCBALL)); actionCameraIsometric->setChecked((cameraMode == EDITOR_CAMERA_MODE_ISOMETRIC)); } void UpdateUIForRenderMode(EDITOR_RENDER_MODE renderMode) { actionViewWireframe->setChecked((renderMode == EDITOR_RENDER_MODE_WIREFRAME)); actionViewUnlit->setChecked((renderMode == EDITOR_RENDER_MODE_FULLBRIGHT)); actionViewLit->setChecked((renderMode == EDITOR_RENDER_MODE_LIT)); } void UpdateUIForViewportFlags(uint32 viewportFlags) { actionViewFlagShadows->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) != 0); actionViewFlagWireframeOverlay->setChecked((viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) != 0); } void UpdateUIForWidget(EditorBlockMeshEditor::WIDGET widget) { (widget == EditorBlockMeshEditor::WIDGET_CAMERA) ? cameraDock->show() : cameraDock->hide(); (widget == EditorBlockMeshEditor::WIDGET_SELECT_BLOCKS || widget == EditorBlockMeshEditor::WIDGET_SELECT_AREA) ? selectBlocksAreaDock->show() : selectBlocksAreaDock->hide(); (widget == EditorBlockMeshEditor::WIDGET_PLACE_BLOCKS) ? placeBlocksDock->show() : placeBlocksDock->hide(); (widget == EditorBlockMeshEditor::WIDGET_DELETE_BLOCKS) ? deleteBlocksDock->show() : deleteBlocksDock->hide(); (widget == EditorBlockMeshEditor::WIDGET_LIGHT_MANIPULATOR) ? lightManipulatorDock->show() : lightManipulatorDock->hide(); actionWidgetCamera->setChecked((widget == EditorBlockMeshEditor::WIDGET_CAMERA)); actionWidgetSelectBlocks->setChecked((widget == EditorBlockMeshEditor::WIDGET_SELECT_BLOCKS)); actionWidgetSelectArea->setChecked((widget == EditorBlockMeshEditor::WIDGET_SELECT_AREA)); actionWidgetPlaceBlocks->setChecked((widget == EditorBlockMeshEditor::WIDGET_PLACE_BLOCKS)); actionWidgetDeleteBlocks->setChecked((widget == EditorBlockMeshEditor::WIDGET_DELETE_BLOCKS)); actionWidgetLightManipulator->setChecked((widget == EditorBlockMeshEditor::WIDGET_LIGHT_MANIPULATOR)); } void UpdateUIForLODCount(uint32 newLODCount, bool lastIsImposter) { SmallString caption; activeLODComboBox->clear(); for (uint32 i = 0; i < newLODCount; i++) { if (lastIsImposter && (i == newLODCount - 1)) caption.Format("Imposter LOD"); else caption.Format("LOD %u", i); activeLODComboBox->addItem(ConvertStringToQString(caption)); } } void UpdateUIForCurrentLOD(uint32 currentLOD) { DebugAssert(currentLOD < (uint32)activeLODComboBox->count()); activeLODComboBox->setCurrentIndex((int)currentLOD); } void UpdateUIAvailableBlockTypes(uint32 iconSize, const EditorBlockMeshEditor::AvailableBlockType *pAvailableBlockTypes, uint32 nAvailableBlockTypes) { // place blocks { // icons { // remove everything { QLayoutItem *pLayoutItem; while ((pLayoutItem = placeBlocksWidgetPaletteIconsFlowLayout->takeAt(0)) != NULL) placeBlocksWidgetPaletteIconsFlowLayout->removeItem(pLayoutItem); for (uint32 i = 0; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { delete placeBlocksWidgetPaletteIcons[i]; placeBlocksWidgetPaletteIcons[i] = NULL; } } for (uint32 i = 0; i < nAvailableBlockTypes; i++) { QToolButton *toolButton = new QToolButton(placeBlocksWidgetPaletteIconsWidget); toolButton->setFixedSize(iconSize + 2, iconSize + 2); toolButton->setIconSize(QSize(iconSize, iconSize)); toolButton->setIcon(pAvailableBlockTypes[i].BlockTypeIcon); toolButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); toolButton->setToolTip(ConvertStringToQString(pAvailableBlockTypes[i].BlockName)); toolButton->setCheckable(true); toolButton->setChecked(false); toolButton->setAutoRaise(true); placeBlocksWidgetPaletteIcons[i] = toolButton; placeBlocksWidgetPaletteIconsFlowLayout->addWidget(toolButton); QObject::connect(toolButton, SIGNAL(clicked(bool)), mainWindow, SLOT(OnPlaceBlockWidgetToolButtonClicked(bool))); } } // list { // remove everything placeBlocksWidgetPaletteList->clear(); placeBlocksWidgetPaletteList->setIconSize(QSize(iconSize, iconSize)); // add them for (uint32 i = 0; i < nAvailableBlockTypes; i++) placeBlocksWidgetPaletteList->addItem(new QListWidgetItem(pAvailableBlockTypes[i].BlockTypeIcon, ConvertStringToQString(pAvailableBlockTypes[i].BlockName))); } } /* placeBlocksDockWidgetPlaceBlockTypeComboBox->clear(); placeBlocksDockWidgetPlaceBlockTypeComboBox->setIconSize(QSize(iconSize, iconSize)); for (uint32 i = 0; i < nAvailableBlockTypes; i++) placeBlocksDockWidgetPlaceBlockTypeComboBox->addItem(pAvailableBlockTypes[i].BlockTypeIcon, Editor::ConvertStringToQString(pAvailableBlockTypes[i].BlockName)); */ } void UpdateUISelectedPlaceBlockType(const EditorBlockMeshEditor::AvailableBlockType *pAvailableBlockTypes, uint32 nAvailableBlockTypes, uint32 selectedIndex, EditorBlockMeshEditor::WIDGET currentWidget) { for (uint32 i = 0; i < nAvailableBlockTypes; i++) placeBlocksWidgetPaletteIcons[i]->setChecked(false); placeBlocksWidgetPaletteIcons[selectedIndex]->setChecked(true); placeBlocksWidgetPaletteList->setCurrentRow(selectedIndex); if (currentWidget == EditorBlockMeshEditor::WIDGET_PLACE_BLOCKS) { SmallString message; message.Format("Placing block: %s", pAvailableBlockTypes[selectedIndex].BlockName.GetCharArray()); statusBarMainText->setText(ConvertStringToQString(message)); } } void UpdateUIForMeshSize(uint32 meshWidth, uint32 meshLength, uint32 meshHeight) { SmallString sizeString; StringConverter::SizeToHumanReadableString(sizeString, sizeof(BlockVolumeBlockType) * meshWidth * meshLength * meshHeight); SmallString message; message.Format("Mesh Size: %u x %u x %u (%s)", meshWidth, meshLength, meshHeight, sizeString.GetCharArray()); statusBarMeshSize->setText(ConvertStringToQString(message)); } void UpdateUIForFPS(float fps) { SmallString message; message.Format("FPS: %.2f", fps); statusBarFPS->setText(ConvertStringToQString(message)); } }; <file_sep>/Engine/Source/Core/PropertyTemplate.cpp #include "Core/PrecompiledHeader.h" #include "Core/PropertyTemplate.h" #include "YBaseLib/StringConverter.h" #include "YBaseLib/XMLReader.h" PropertyTemplate::PropertyTemplate() { } PropertyTemplate::PropertyTemplate(const PropertyTemplate &from) { for (uint32 i = 0; i < from.m_propertyDefinitions.GetSize(); i++) { PropertyTemplateProperty *pPropertyClone = from.m_propertyDefinitions[i]->Clone(); DebugAssert(pPropertyClone != nullptr); m_propertyDefinitions.Add(pPropertyClone); } } PropertyTemplate::~PropertyTemplate() { for (uint32 i = 0; i < m_propertyDefinitions.GetSize(); i++) delete m_propertyDefinitions[i]; } const PropertyTemplateProperty *PropertyTemplate::GetPropertyDefinitionByName(const char *propertyName) const { for (uint32 i = 0; i < m_propertyDefinitions.GetSize(); i++) { if (m_propertyDefinitions[i]->GetName().CompareInsensitive(propertyName)) return m_propertyDefinitions[i]; } return NULL; } void PropertyTemplate::AddPropertyDefinition(PropertyTemplateProperty *pProperty) { DebugAssert(GetPropertyDefinitionByName(pProperty->GetName()) == nullptr); m_propertyDefinitions.Add(pProperty); } #ifdef HAVE_LIBXML2 bool PropertyTemplate::LoadFromStream(const char *FileName, ByteStream *pStream) { // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { xmlReader.PrintError("could not create xml reader"); return false; } // skip to entity-definition element if (!xmlReader.SkipToElement("propertytemplate")) { xmlReader.PrintError("could not skip to propertytemplate element"); return false; } if (!LoadFromXML(xmlReader)) return false; DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "propertytemplate") == 0); return true; } bool PropertyTemplate::LoadFromXML(XMLReader &xmlReader) { // read elements if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 propertiesSelection = xmlReader.Select("property"); if (propertiesSelection < 0) return false; switch (propertiesSelection) { // property case 0: { PropertyTemplateProperty *pPropertyDefinition = new PropertyTemplateProperty(); if (!pPropertyDefinition->ParseXML(xmlReader)) { delete pPropertyDefinition; return false; } // if it already exists, allow the override for (uint32 i = 0; i < m_propertyDefinitions.GetSize(); i++) { if (m_propertyDefinitions[i]->GetName() == pPropertyDefinition->GetName()) { xmlReader.PrintError("property already defined: '%s'", pPropertyDefinition->GetName().GetCharArray()); delete pPropertyDefinition; return false; } } m_propertyDefinitions.Add(pPropertyDefinition); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } else { UnreachableCode(); break; } } } return true; } #endif PropertyTemplateProperty::PropertyTemplateProperty() : m_eType(PROPERTY_TYPE_COUNT), m_flags(0), m_pSelector(NULL) { } PropertyTemplateProperty::~PropertyTemplateProperty() { if (m_pSelector != NULL) delete m_pSelector; } #ifdef HAVE_LIBXML2 bool PropertyTemplateProperty::ParseXML(XMLReader &xmlReader) { // we should be on a property element. DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "property") == 0); // read attributes const char *typeStr = xmlReader.FetchAttribute("type"); const char *nameStr = xmlReader.FetchAttribute("name"); if (typeStr == NULL || nameStr == NULL) { xmlReader.PrintError("incomplete property declaration"); return false; } // convert type, set name m_strName = nameStr; if (!NameTable_TranslateType(NameTables::PropertyType, typeStr, &m_eType, true)) { xmlReader.PrintError("invalid property type: '%s'", typeStr); return false; } // parse fields if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 propertySelection = xmlReader.Select("flags|category|label|description|default|selector"); if (propertySelection < 0) return false; switch (propertySelection) { // flags case 0: { uint32 flags = 0; if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 flagsSelection = xmlReader.Select("hidden|readonly"); if (flagsSelection < 0) return false; switch (flagsSelection) { // hidden case 0: flags |= PROPERTY_TEMPLATE_PROPERTY_FLAG_HIDDEN; break; // readonly case 1: flags |= PROPERTY_TEMPLATE_PROPERTY_FLAG_READONLY; break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "flags") == 0); break; } else { UnreachableCode(); break; } } } m_flags = flags; } break; // category case 1: m_strCategory = xmlReader.GetElementText(true); break; // label case 2: m_strLabel = xmlReader.GetElementText(true); break; // description case 3: m_strDescription = xmlReader.GetElementText(true); break; // default case 4: m_strDefaultValue = xmlReader.GetElementText(true); break; // selector case 5: { if (m_pSelector != NULL) { xmlReader.PrintError("selector already defined"); return false; } int32 selectorSelection = xmlReader.SelectAttribute("type", "resource|color|slider|spinner|choice|euler-angles|flags"); if (selectorSelection < 0) return false; PropertyTemplateValueSelector *pSelector = NULL; switch (selectorSelection) { // resource case 0: pSelector = new PropertyTemplateValueSelector_Resource(this); break; // color case 1: pSelector = new PropertyTemplateValueSelector_Color(this); break; // slider case 2: pSelector = new PropertyTemplateValueSelector_Slider(this); break; // spinner case 3: pSelector = new PropertyTemplateValueSelector_Spinner(this); break; // choice case 4: pSelector = new PropertyTemplateValueSelector_Choice(this); break; // euler-angles case 5: pSelector = new PropertyTemplateValueSelector_EulerAngles(this); break; // flags case 6: pSelector = new PropertyTemplateValueSelector_Flags(this); break; default: UnreachableCode(); break; } // parse it DebugAssert(pSelector != NULL); if (!pSelector->ParseXML(xmlReader)) { delete pSelector; return false; } // set selector m_pSelector = pSelector; } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "property") == 0); break; } else { UnreachableCode(); break; } } } return true; } #endif PropertyTemplateProperty *PropertyTemplateProperty::Clone() const { PropertyTemplateProperty *pClone = new PropertyTemplateProperty(); pClone->m_eType = m_eType; pClone->m_strName = m_strName; pClone->m_strCategory = m_strCategory; pClone->m_strLabel = m_strLabel; pClone->m_strDescription = m_strDescription; pClone->m_strDefaultValue = m_strDefaultValue; if (m_pSelector != NULL) { pClone->m_pSelector = m_pSelector->Clone(pClone); DebugAssert(pClone->m_pSelector != NULL); } return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector::PropertyTemplateValueSelector(const PropertyTemplateProperty *pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE type) : m_pOwner(pOwner), m_eType(type) { } PropertyTemplateValueSelector::~PropertyTemplateValueSelector() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Resource::PropertyTemplateValueSelector_Resource(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_RESOURCE) { } PropertyTemplateValueSelector_Resource::~PropertyTemplateValueSelector_Resource() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Resource::ParseXML(XMLReader &xmlReader) { const char *resourceTypeStr = xmlReader.FetchAttribute("resource-type"); if (resourceTypeStr == NULL) { xmlReader.PrintError("incomplete resource selector definition"); return false; } m_strResourceTypeName = resourceTypeStr; return xmlReader.SkipCurrentElement(); } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Resource::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Resource *pClone = new PropertyTemplateValueSelector_Resource(pOwner); pClone->m_strResourceTypeName = m_strResourceTypeName; return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Color::PropertyTemplateValueSelector_Color(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_COLOR) { } PropertyTemplateValueSelector_Color::~PropertyTemplateValueSelector_Color() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Color::ParseXML(XMLReader &xmlReader) { return xmlReader.SkipCurrentElement(); } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Color::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Color *pClone = new PropertyTemplateValueSelector_Color(pOwner); return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Slider::PropertyTemplateValueSelector_Slider(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SLIDER) { } PropertyTemplateValueSelector_Slider::~PropertyTemplateValueSelector_Slider() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Slider::ParseXML(XMLReader &xmlReader) { const char *minStr = xmlReader.FetchAttribute("min"); const char *maxStr = xmlReader.FetchAttribute("max"); if (minStr == NULL || maxStr == NULL) { xmlReader.PrintError("incomplete slider selector definition"); return false; } m_fMinValue = StringConverter::StringToFloat(minStr); m_fMaxValue = StringConverter::StringToFloat(maxStr); return xmlReader.SkipCurrentElement(); } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Slider::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Slider *pClone = new PropertyTemplateValueSelector_Slider(pOwner); pClone->m_fMinValue = m_fMinValue; pClone->m_fMaxValue = m_fMaxValue; return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Spinner::PropertyTemplateValueSelector_Spinner(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_SPINNER) { } PropertyTemplateValueSelector_Spinner::~PropertyTemplateValueSelector_Spinner() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Spinner::ParseXML(XMLReader &xmlReader) { const char *minStr = xmlReader.FetchAttribute("min"); const char *incrementStr = xmlReader.FetchAttribute("increment"); const char *maxStr = xmlReader.FetchAttribute("max"); m_fMinValue = (minStr != NULL) ? StringConverter::StringToFloat(minStr) : -Y_FLT_MAX; m_fIncrement = (incrementStr != NULL) ? StringConverter::StringToFloat(incrementStr) : 1.0f; m_fMaxValue = (maxStr != NULL) ? StringConverter::StringToFloat(maxStr) : Y_FLT_MAX; return xmlReader.SkipCurrentElement(); } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Spinner::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Spinner *pClone = new PropertyTemplateValueSelector_Spinner(pOwner); pClone->m_fMinValue = m_fMinValue; pClone->m_fIncrement = m_fIncrement; pClone->m_fMaxValue = m_fMaxValue; return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Choice::PropertyTemplateValueSelector_Choice(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_CHOICE) { } PropertyTemplateValueSelector_Choice::~PropertyTemplateValueSelector_Choice() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Choice::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 selectorSelection = xmlReader.Select("choice"); if (selectorSelection < 0) return false; switch (selectorSelection) { // choice case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr == NULL) { xmlReader.PrintError("incomplete choice declaration"); return false; } Choice choice; choice.Left = valueStr; choice.Right = xmlReader.GetElementText(true); m_Choices.Add(choice); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "selector") == 0); break; } else { UnreachableCode(); break; } } } m_Choices.Shrink(); return true; } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Choice::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Choice *pClone = new PropertyTemplateValueSelector_Choice(pOwner); if (m_Choices.GetSize() > 0) { pClone->m_Choices.Reserve(m_Choices.GetSize()); uint32 i; for (i = 0; i < m_Choices.GetSize(); i++) pClone->m_Choices.Add(Choice(m_Choices[i])); } return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_EulerAngles::PropertyTemplateValueSelector_EulerAngles(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_EULER_ANGLES) { } PropertyTemplateValueSelector_EulerAngles::~PropertyTemplateValueSelector_EulerAngles() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_EulerAngles::ParseXML(XMLReader &xmlReader) { return xmlReader.SkipCurrentElement(); } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_EulerAngles::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_EulerAngles *pClone = new PropertyTemplateValueSelector_EulerAngles(pOwner); return pClone; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PropertyTemplateValueSelector_Flags::PropertyTemplateValueSelector_Flags(const PropertyTemplateProperty *pOwner) : PropertyTemplateValueSelector(pOwner, PROPERTY_TEMPLATE_VALUE_SELECTOR_TYPE_FLAGS) { } PropertyTemplateValueSelector_Flags::~PropertyTemplateValueSelector_Flags() { } #ifdef HAVE_LIBXML2 bool PropertyTemplateValueSelector_Flags::ParseXML(XMLReader &xmlReader) { if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 selectorSelection = xmlReader.Select("flag"); if (selectorSelection < 0) return false; switch (selectorSelection) { // choice case 0: { const char *valueStr = xmlReader.FetchAttribute("value"); if (valueStr == NULL) { xmlReader.PrintError("incomplete flag declaration"); return false; } Flag flag; flag.Value = StringConverter::StringToUInt32(valueStr); if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 propertySelection = xmlReader.Select("label|description"); if (propertySelection < 0) return false; switch (propertySelection) { // label case 0: flag.Label = xmlReader.GetElementText(true); break; // description case 1: flag.Description = xmlReader.GetElementText(true); break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "flag") == 0); break; } else { UnreachableCode(); break; } } } m_Flags.Add(flag); } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "selector") == 0); break; } else { UnreachableCode(); break; } } } m_Flags.Shrink(); return true; } #endif PropertyTemplateValueSelector *PropertyTemplateValueSelector_Flags::Clone(const PropertyTemplateProperty *pOwner) { PropertyTemplateValueSelector_Flags *pClone = new PropertyTemplateValueSelector_Flags(pOwner); if (m_Flags.GetSize() > 0) { pClone->m_Flags.Reserve(m_Flags.GetSize()); uint32 i; for (i = 0; i < m_Flags.GetSize(); i++) pClone->m_Flags.Add(Flag(m_Flags[i])); } return pClone; } <file_sep>/Engine/Source/OpenGLRenderer/PrecompiledHeader.cpp #include "OpenGLRenderer/PrecompiledHeader.h" <file_sep>/Editor/Source/Editor/ResourceBrowser/EditorStaticMeshImportDialog.h #pragma once #include "Editor/Common.h" #include "Editor/EditorProgressCallbacks.h" class Ui_EditorStaticMeshImportDialog; class EditorStaticMeshImportDialog : public QDialog, private EditorProgressCallbacks { Q_OBJECT public: EditorStaticMeshImportDialog(QWidget *parent); virtual ~EditorStaticMeshImportDialog(); void SetMaterialDirectory(const QString &materialDirectory); private: Ui_EditorStaticMeshImportDialog *m_ui; private: // progress callbacks interface virtual void SetStatusText(const char *statusText) override; virtual void SetProgressRange(uint32 range) override; virtual void SetProgressValue(uint32 value) override; virtual void DisplayError(const char *message) override; virtual void DisplayWarning(const char *message) override; virtual void DisplayInformation(const char *message) override; virtual void DisplayDebugMessage(const char *message) override; virtual void closeEvent(QCloseEvent *pCloseEvent) override; void ConnectUIEvents(); void UpdateUIState(); private Q_SLOTS: void OnFileNameLineEditEditingFinished(); void OnFileNameBrowseClicked(); void OnImportButtonClicked(); void OnCloseButtonClicked(); }; <file_sep>/Engine/Source/ResourceCompiler/ObjectTemplate.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "Core/VirtualFileSystem.h" #include "YBaseLib/XMLReader.h" Log_SetChannel(ObjectTemplate); ObjectTemplate::ObjectTemplate() : m_pBaseClassTemplate(nullptr), m_canCreate(false) { } ObjectTemplate::~ObjectTemplate() { } bool ObjectTemplate::IsDerivedFrom(const ObjectTemplate *pTemplate) const { const ObjectTemplate *pCurrent = this; while (pCurrent != nullptr) { if (pCurrent == pTemplate) return true; pCurrent = pCurrent->GetBaseClassTemplate(); } return false; } bool ObjectTemplate::LoadFromStream(const char *FileName, ByteStream *pStream) { uint32 i; // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pStream, FileName)) { xmlReader.PrintError("could not create xml reader"); return false; } // skip to entity-definition element if (!xmlReader.SkipToElement("object-template")) { xmlReader.PrintError("could not skip to object-template element"); return false; } // read attributes const char *typeNameStr = xmlReader.FetchAttribute("name"); const char *baseTypeNameStr = xmlReader.FetchAttribute("base"); const char *canCreateStr = xmlReader.FetchAttribute("can-create"); if (typeNameStr == NULL || canCreateStr == NULL) { xmlReader.PrintError("incomplete entity definition"); return false; } // set name/can create m_typeName = typeNameStr; m_displayName = m_typeName; m_canCreate = StringConverter::StringToBool(canCreateStr); // handle base class if (baseTypeNameStr != NULL) { m_pBaseClassTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(baseTypeNameStr); if (m_pBaseClassTemplate == nullptr) { xmlReader.PrintError("could not get base class definition ('%s')", baseTypeNameStr); return false; } } // read elements if (!xmlReader.IsEmptyElement()) { for (; ;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 entityDefinitionSelection = xmlReader.Select("displayname|category|description|properties"); if (entityDefinitionSelection < 0) return false; switch (entityDefinitionSelection) { // displayname case 0: { if (xmlReader.IsEmptyElement()) continue; // get text m_displayName = xmlReader.GetElementText(true); } break; // category case 1: { if (xmlReader.IsEmptyElement()) continue; // get text m_categoryName = xmlReader.GetElementText(true); } break; // description case 2: { if (xmlReader.IsEmptyElement()) continue; // get text m_description = xmlReader.GetElementText(true); } break; // properties case 3: { if (!xmlReader.IsEmptyElement()) { if (!m_propertyTableTemplate.LoadFromXML(xmlReader)) return false; DebugAssert(Y_strcmp(xmlReader.GetNodeName(), "properties") == 0); } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "object-template") == 0); break; } else { UnreachableCode(); break; } } } // copy stuff across from base class if (m_pBaseClassTemplate != nullptr) { // copy properties across for (i = 0; i < m_pBaseClassTemplate->GetPropertyDefinitionCount(); i++) { const PropertyTemplateProperty *pBaseClassProperty = m_pBaseClassTemplate->GetPropertyDefinition(i); if (m_propertyTableTemplate.GetPropertyDefinitionByName(pBaseClassProperty->GetName())) { // property is overriden by child, ignore it continue; } PropertyTemplateProperty *pClonedPropertyDefinition = pBaseClassProperty->Clone(); DebugAssert(pClonedPropertyDefinition != NULL); m_propertyTableTemplate.AddPropertyDefinition(pClonedPropertyDefinition); } } Log_DevPrintf("Object template loaded: '%s' (base class '%s', %u properties)", m_typeName.GetCharArray(), (m_pBaseClassTemplate != nullptr) ? m_pBaseClassTemplate->GetTypeName().GetCharArray() : "none", m_propertyTableTemplate.GetPropertyDefinitionCount()); return true; } <file_sep>/Engine/Source/Renderer/Shaders/PlainShader.h #pragma once #include "Renderer/ShaderComponent.h" class GPUTexture; class Texture; class ShaderProgram; class PlainShader : public ShaderComponent { DECLARE_SHADER_COMPONENT_INFO(PlainShader, ShaderComponent); public: enum FLAGS { WITH_TEXTURE = (1 << 0), WITH_VERTEX_COLOR = (1 << 1), WITH_MATERIAL = (1 << 2), BLEND_TEXTURE_AND_VERTEX_COLOR = (1 << 3), }; public: PlainShader(const ShaderComponentTypeInfo *pTypeInfo = &s_TypeInfo) : BaseClass(pTypeInfo) {} static void SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture *pTexture); static void SetTexture(GPUContext *pContext, ShaderProgram *pShaderProgram, Texture *pTexture); static bool IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags); static bool FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters); }; <file_sep>/Engine/Source/D3D12Renderer/D3D12GPUDevice.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12Helpers.h" #include "D3D12Renderer/D3D12CVars.h" #include "Renderer/ShaderConstantBuffer.h" #include "Engine/EngineCVars.h" Log_SetChannel(D3D12RenderBackend); Y_DECLARE_THREAD_LOCAL(ID3D12GraphicsCommandList *) s_pCurrentThreadCopyCommandList = nullptr; Y_DECLARE_THREAD_LOCAL(D3D12GPUDevice::CopyCommandQueue *) s_pCurrentThreadCopyCommandQueue = nullptr; Y_DECLARE_THREAD_LOCAL(uint32) s_currentThreadCopyBatchCount = 0; static void DumpActiveObjects() { #ifdef Y_BUILD_CONFIG_DEBUG // dump remaining objects { HMODULE hDXGIDebugModule = GetModuleHandleA("dxgidebug.dll"); if (hDXGIDebugModule != NULL) { HRESULT(WINAPI *pDXGIGetDebugInterface)(REFIID riid, void **ppDebug); pDXGIGetDebugInterface = (HRESULT(WINAPI *)(REFIID, void **))GetProcAddress(hDXGIDebugModule, "DXGIGetDebugInterface"); if (pDXGIGetDebugInterface != NULL) { IDXGIDebug *pDXGIDebug; if (SUCCEEDED(pDXGIGetDebugInterface(__uuidof(pDXGIDebug), reinterpret_cast<void **>(&pDXGIDebug)))) { Log_DevPrint("=== Begin remaining DXGI and D3D object dump ==="); pDXGIDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL); Log_DevPrint("=== End remaining DXGI and D3D object dump ==="); pDXGIDebug->Release(); } } } // // real hackery, lets us paste a pointer from the above in and view it // ID3D12Resource *x = nullptr; // if (x != nullptr) // { // D3D12_RESOURCE_DESC d = x->GetDesc(); // Log_DevPrint(""); // } } #endif } D3D12GPUDevice::D3D12GPUDevice(HMODULE hD3D12Module, IDXGIFactory4 *pDXGIFactory, IDXGIAdapter3 *pDXGIAdapter, ID3D12Device *pD3DDevice, D3D_FEATURE_LEVEL D3DFeatureLevel, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, PIXEL_FORMAT outputBackBufferFormat, PIXEL_FORMAT outputDepthStencilFormat, uint32 frameLatency) : m_hD3D12Module(hD3D12Module) , m_pDXGIFactory(pDXGIFactory) , m_pDXGIAdapter(pDXGIAdapter) , m_pD3DDevice(pD3DDevice) , m_pD3DInfoQueue(nullptr) , m_D3DFeatureLevel(D3DFeatureLevel) , m_featureLevel(featureLevel) , m_texturePlatform(texturePlatform) , m_outputBackBufferFormat(outputBackBufferFormat) , m_outputDepthStencilFormat(outputDepthStencilFormat) , m_frameLatency(frameLatency) , m_pGraphicsCommandQueue(nullptr) , m_pImmediateContext(nullptr) , m_pLegacyGraphicsRootSignature(nullptr) , m_pLegacyComputeRootSignature(nullptr) , m_fnD3D12SerializeRootSignature(nullptr) , m_pDefaultRasterizerState(nullptr) , m_pDefaultDepthStencilState(nullptr) , m_pDefaultBlendState(nullptr) , m_pConstantBufferStorageHeap(nullptr) { Y_memzero(m_pCPUDescriptorHeaps, sizeof(m_pCPUDescriptorHeaps)); } D3D12GPUDevice::~D3D12GPUDevice() { DebugAssert(m_pImmediateContext == nullptr); // remove any scheduled resources (descriptors will be dropped anyways) delete m_pGraphicsCommandQueue; // cleanup constant buffers for (ConstantBufferStorage &constantBufferStorage : m_constantBufferStorage) { GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Free(constantBufferStorage.DescriptorHandle); if (constantBufferStorage.pResource != nullptr) constantBufferStorage.pResource->Release(); } SAFE_RELEASE(m_pConstantBufferStorageHeap); // cleanup default states SAFE_RELEASE(m_pDefaultBlendState); SAFE_RELEASE(m_pDefaultDepthStencilState); SAFE_RELEASE(m_pDefaultRasterizerState); // remove descriptor heaps m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]->Free(m_nullCBVDescriptorHandle); m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]->Free(m_nullSRVDescriptorHandle); m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]->Free(m_nullSamplerHandle); for (uint32 i = 0; i < countof(m_pCPUDescriptorHeaps); i++) { if (m_pCPUDescriptorHeaps[i] != nullptr) delete m_pCPUDescriptorHeaps[i]; } // signatures SAFE_RELEASE(m_pLegacyComputeRootSignature); SAFE_RELEASE(m_pLegacyGraphicsRootSignature); // // disable break on error, since each leaked object is a message // if (m_pD3DInfoQueue != nullptr && CVars::r_d3d12_break_on_error.GetBool() && IsDebuggerPresent()) // { // m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, FALSE); // m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, FALSE); // m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, FALSE); // } // dump objects before teardown Log_DevPrintf("Dumping active objects before teardown"); DumpActiveObjects(); // cleanup SAFE_RELEASE(m_pD3DInfoQueue); SAFE_RELEASE(m_pDXGIAdapter); SAFE_RELEASE(m_pDXGIFactory); SAFE_RELEASE(m_pD3DDevice); // dump objects before teardown Log_DevPrintf("Dumping active objects after teardown"); DumpActiveObjects(); // release handle to d3d12 FreeLibrary(m_hD3D12Module); } RENDERER_PLATFORM D3D12GPUDevice::GetPlatform() const { return RENDERER_PLATFORM_D3D12; } RENDERER_FEATURE_LEVEL D3D12GPUDevice::GetFeatureLevel() const { return m_featureLevel; } TEXTURE_PLATFORM D3D12GPUDevice::GetTexturePlatform() const { return m_texturePlatform; } void D3D12GPUDevice::GetCapabilities(RendererCapabilities *pCapabilities) const { pCapabilities->MaxTextureAnisotropy = D3D12_MAX_MAXANISOTROPY; pCapabilities->MaximumVertexBuffers = D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; pCapabilities->MaximumConstantBuffers = D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS; pCapabilities->MaximumTextureUnits = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS; pCapabilities->MaximumSamplers = D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS; pCapabilities->MaximumRenderTargets = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; pCapabilities->SupportsCommandLists = true; pCapabilities->SupportsMultithreadedResourceCreation = true; pCapabilities->SupportsDrawBaseVertex = true; pCapabilities->SupportsDepthTextures = true; pCapabilities->SupportsTextureArrays = (m_D3DFeatureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsCubeMapTextureArrays = (m_D3DFeatureLevel >= D3D_FEATURE_LEVEL_10_1); pCapabilities->SupportsGeometryShaders = (m_D3DFeatureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsSinglePassCubeMaps = (m_D3DFeatureLevel >= D3D_FEATURE_LEVEL_10_0); pCapabilities->SupportsInstancing = (m_D3DFeatureLevel >= D3D_FEATURE_LEVEL_10_0); } bool D3D12GPUDevice::CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat /*= NULL*/) const { DXGI_FORMAT DXGIFormat = D3D12Helpers::PixelFormatToDXGIFormat(PixelFormat); if (DXGIFormat == DXGI_FORMAT_UNKNOWN) { // use r8g8b8a8 if (CompatibleFormat != NULL) *CompatibleFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; return false; } if (CompatibleFormat != NULL) *CompatibleFormat = PixelFormat; return true; } void D3D12GPUDevice::CorrectProjectionMatrix(float4x4 &projectionMatrix) const { } float D3D12GPUDevice::GetTexelOffset() const { return 0.0f; } bool D3D12GPUDevice::CreateCommandQueues(uint32 copyCommandQueueCount) { // create graphics command queue m_pGraphicsCommandQueue = new D3D12CommandQueue(this, m_pD3DDevice, D3D12_COMMAND_LIST_TYPE_DIRECT, 2 * 1024 * 1024, 1024, 1024); if (!m_pGraphicsCommandQueue->Initialize()) return false; // create copy command queues m_copyCommandQueues.Resize(copyCommandQueueCount); for (uint32 i = 0; i < copyCommandQueueCount; i++) { D3D12CommandQueue *pCommandQueue = new D3D12CommandQueue(this, m_pD3DDevice, D3D12_COMMAND_LIST_TYPE_COPY, 0, 0, 0); if (!pCommandQueue->Initialize()) { delete pCommandQueue; return false; } m_copyCommandQueues[i].pCommandQueue = pCommandQueue; } // okay return true; } D3D12GPUDevice::CopyQueueReference::CopyQueueReference(D3D12GPUDevice *pDevice) : pDevice(pDevice) { if (s_pCurrentThreadCopyCommandList == nullptr) { pDevice->GetFreeCopyCommandQueue(); ContextNeedsRelease = true; } else { ContextNeedsRelease = false; } } D3D12GPUDevice::CopyQueueReference::~CopyQueueReference() { if (ContextNeedsRelease) pDevice->ReleaseCopyCommandQueue(); } bool D3D12GPUDevice::CopyQueueReference::HasContext() const { return true; } void D3D12GPUDevice::BeginResourceBatchUpload() { if ((s_currentThreadCopyBatchCount++) == 0) { // Have we got a copy queue? if (s_pCurrentThreadCopyCommandList == nullptr) GetFreeCopyCommandQueue(); } } void D3D12GPUDevice::EndResourceBatchUpload() { DebugAssert(s_currentThreadCopyBatchCount > 0); // Last one? if ((--s_currentThreadCopyBatchCount) == 0) { // Immediate context? if (s_pCurrentThreadCopyCommandQueue == nullptr) { // Assume at least one operation. DebugAssert(Renderer::IsOnRenderThread() && m_pImmediateContext != nullptr); m_pImmediateContext->m_commandCounter++; } else { // Release if it's a copy queue. ReleaseCopyCommandQueue(); } } } void D3D12GPUDevice::ResourceBarrier(ID3D12Resource *pResource, D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState) { // On graphics thread? if (s_pCurrentThreadCopyCommandQueue == nullptr) { // Issue as normal. D3D12_RESOURCE_BARRIER resourceBarrier = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, { pResource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, beforeState, afterState } }; DebugAssert(s_pCurrentThreadCopyCommandList != nullptr); s_pCurrentThreadCopyCommandList->ResourceBarrier(1, &resourceBarrier); } else { // Queue transition. // @TODO: Handle cases where the resources is released better. Destruction *should* be queued until // the next fence, which will have passed by the time the transition has happened, anyway. PendingResourceTransition transition = { pResource, beforeState, afterState }; m_pendingResourceTransitionLock.Lock(); m_pendingResourceTransitions.Add(transition); m_pendingResourceTransitionLock.Unlock(); } } void D3D12GPUDevice::ScheduleResourceForDeletion(ID3D12Pageable *pResource) { m_pGraphicsCommandQueue->ScheduleResourceForDeletion(pResource); } void D3D12GPUDevice::ScheduleDescriptorForDeletion(const D3D12DescriptorHandle &handle) { m_pGraphicsCommandQueue->ScheduleDescriptorForDeletion(handle); } void D3D12GPUDevice::ScheduleCopyResourceForDeletion(ID3D12Pageable *pResource) { // are we on the main thread? if (s_pCurrentThreadCopyCommandQueue == nullptr) { // release to graphics queue DebugAssert(s_pCurrentThreadCopyCommandList != nullptr); m_pGraphicsCommandQueue->ScheduleResourceForDeletion(pResource); } else { // release to copy queue s_pCurrentThreadCopyCommandQueue->pCommandQueue->ScheduleResourceForDeletion(pResource); } } void D3D12GPUDevice::GetFreeCopyCommandQueue() { DebugAssert(s_pCurrentThreadCopyCommandQueue == nullptr); DebugAssert(s_pCurrentThreadCopyCommandList == nullptr); // search for an unlocked queue first CopyCommandQueue *pCommandQueue = nullptr; for (CopyCommandQueue &queue : m_copyCommandQueues) { if (queue.Lock.TryLock()) { pCommandQueue = &queue; break; } } // failed, so just use the first one if (pCommandQueue == nullptr) { pCommandQueue = &m_copyCommandQueues[0]; pCommandQueue->Lock.Lock(); } // create a command list DebugAssert(pCommandQueue->pCommandAllocator == nullptr && pCommandQueue->pCommandList == nullptr); pCommandQueue->pCommandAllocator = pCommandQueue->pCommandQueue->RequestCommandAllocator(); pCommandQueue->pCommandList = pCommandQueue->pCommandQueue->RequestAndOpenCommandList(pCommandQueue->pCommandAllocator); // set thread-local pointers s_pCurrentThreadCopyCommandQueue = pCommandQueue; s_pCurrentThreadCopyCommandList = pCommandQueue->pCommandList; } void D3D12GPUDevice::ReleaseCopyCommandQueue() { DebugAssert(s_pCurrentThreadCopyCommandQueue != nullptr); DebugAssert(s_pCurrentThreadCopyCommandQueue->pCommandList == s_pCurrentThreadCopyCommandList); // close the command list CopyCommandQueue *pCopyQueue = s_pCurrentThreadCopyCommandQueue; HRESULT hResult = pCopyQueue->pCommandList->Close(); if (SUCCEEDED(hResult)) { // execute the commands pCopyQueue->pCommandQueue->ExecuteCommandList(pCopyQueue->pCommandList); pCopyQueue->pCommandQueue->ReleaseCommandList(pCopyQueue->pCommandList); } else { Log_WarningPrintf("Copy command list failed close with HRESULT %08X", hResult); pCopyQueue->pCommandQueue->ReleaseFailedCommandList(pCopyQueue->pCommandList); } // release allocator pCopyQueue->pCommandQueue->ReleaseCommandAllocator(pCopyQueue->pCommandAllocator); // wait for the queue to finish uint64 fenceValue = pCopyQueue->pCommandQueue->CreateSynchronizationPoint(); pCopyQueue->pCommandQueue->WaitForFence(fenceValue); pCopyQueue->pCommandQueue->ReleaseStaleResources(); // clear pointers s_pCurrentThreadCopyCommandList = nullptr; s_pCurrentThreadCopyCommandQueue = nullptr; pCopyQueue->pCommandAllocator = nullptr; pCopyQueue->pCommandList = nullptr; pCopyQueue->Lock.Unlock(); } bool D3D12GPUDevice::TransitionPendingResources(D3D12CommandQueue *pCommandQueue) { // get out as quickly as possible if there's no pending transitions. m_pendingResourceTransitionLock.Lock(); if (m_pendingResourceTransitions.IsEmpty()) { m_pendingResourceTransitionLock.Unlock(); return false; } // get a command allocator and list ID3D12CommandAllocator *pCommandAllocator = pCommandQueue->RequestCommandAllocator(); ID3D12GraphicsCommandList *pCommandList = pCommandQueue->RequestAndOpenCommandList(pCommandAllocator); //Log_DevPrintf("D3D12RenderBackend: Transitioning %u pending resources.", m_pendingResourceTransitions.GetSize()); // pass through to d3d. unfortunately this will be a period of contention, when // resources have to be transitioned, command list execution halts on all threads. D3D12_RESOURCE_BARRIER *pResourceBarriers = (D3D12_RESOURCE_BARRIER *)alloca(sizeof(D3D12_RESOURCE_BARRIER) * Min(m_pendingResourceTransitions.GetSize(), (uint32)256)); for (uint32 startIndex = 0; startIndex < m_pendingResourceTransitions.GetSize(); ) { uint32 nResourceBarriers = Min(m_pendingResourceTransitions.GetSize() - startIndex, (uint32)256); for (uint32 i = 0; i < nResourceBarriers; i++) { const PendingResourceTransition *pPendingTransition = &m_pendingResourceTransitions[startIndex + i]; D3D12_RESOURCE_BARRIER *pResourceBarrier = &pResourceBarriers[i]; pResourceBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; pResourceBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; pResourceBarrier->Transition.pResource = pPendingTransition->pResource; pResourceBarrier->Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; pResourceBarrier->Transition.StateBefore = pPendingTransition->BeforeState; pResourceBarrier->Transition.StateAfter = pPendingTransition->AfterState; } pCommandList->ResourceBarrier(nResourceBarriers, pResourceBarriers); startIndex += nResourceBarriers; } // allow re-queuing again. this will become an issue later on with multiple compute issuer threads though. m_pendingResourceTransitions.Clear(); m_pendingResourceTransitionLock.Unlock(); // execute commands. HRESULT hResult = pCommandList->Close(); if (SUCCEEDED(hResult)) { pCommandQueue->ExecuteCommandList(pCommandList); pCommandQueue->ReleaseCommandList(pCommandList); } else { Log_ErrorPrintf("Failed to close/execute command list. Resources will be left in an undefined state."); pCommandQueue->ReleaseFailedCommandList(pCommandList); } // release command allocator back. pCommandQueue->ReleaseCommandAllocator(pCommandAllocator); return true; } ID3D12GraphicsCommandList *D3D12GPUDevice::GetCurrentCopyCommandList() { return s_pCurrentThreadCopyCommandList; } D3D12GPUContext *D3D12GPUDevice::InitializeAndCreateContext() { // function pointers m_fnD3D12SerializeRootSignature = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)GetProcAddress(m_hD3D12Module, "D3D12SerializeRootSignature"); DebugAssert(m_fnD3D12SerializeRootSignature != nullptr); // debug device? if (CVars::r_use_debug_device.GetBool() && CVars::r_d3d12_break_on_error.GetBool() && IsDebuggerPresent()) { // enable d3d12 break-on-error HRESULT hResult = m_pD3DDevice->QueryInterface(IID_PPV_ARGS(&m_pD3DInfoQueue)); if (SUCCEEDED(hResult)) { // enable break on error m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE); m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE); m_pD3DInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); // stop these annoying warnings // D3D12 WARNING : ID3D12CommandList::ClearRenderTargetView : The clear values do not match those passed to resource creation.The clear operation is typically slower as a result; but will still clear to the desired value.[EXECUTION WARNING #820: CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE] //m_pD3DInfoQueue->SetBreakOnID(D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, FALSE); } // enable dxgi break-on-error HMODULE hDXGIDebugModule = GetModuleHandleA("dxgidebug.dll"); if (hDXGIDebugModule != NULL) { HRESULT(WINAPI *pDXGIGetDebugInterface)(REFIID riid, void **ppDebug); pDXGIGetDebugInterface = (HRESULT(WINAPI *)(REFIID, void **))GetProcAddress(hDXGIDebugModule, "DXGIGetDebugInterface"); if (pDXGIGetDebugInterface != NULL) { IDXGIInfoQueue *pDXGIInfoQueue; if (SUCCEEDED(pDXGIGetDebugInterface(__uuidof(pDXGIInfoQueue), reinterpret_cast<void **>(&pDXGIInfoQueue)))) { pDXGIInfoQueue->SetBreakOnSeverity(DXGI_DEBUG_ALL, DXGI_INFO_QUEUE_MESSAGE_SEVERITY_CORRUPTION, TRUE); pDXGIInfoQueue->SetBreakOnSeverity(DXGI_DEBUG_ALL, DXGI_INFO_QUEUE_MESSAGE_SEVERITY_ERROR, TRUE); pDXGIInfoQueue->SetBreakOnSeverity(DXGI_DEBUG_ALL, DXGI_INFO_QUEUE_MESSAGE_SEVERITY_WARNING, TRUE); pDXGIInfoQueue->Release(); } } } } // create legacy root descriptors if (!CreateLegacyRootSignatures()) return nullptr; // create descriptor heaps if (!CreateCPUDescriptorHeaps()) return nullptr; // create default states if (!CreateDefaultStates()) return nullptr; // create constant buffers if (!CreateConstantStorage()) return nullptr; // create queues if (!CreateCommandQueues(4)) return nullptr; // create context D3D12GPUContext *pContext = new D3D12GPUContext(this, m_pD3DDevice, m_pGraphicsCommandQueue); if (!pContext->Create()) { pContext->Release(); return false; } DebugAssert(m_pImmediateContext == pContext); return pContext; } void D3D12GPUDevice::SetImmediateContext(D3D12GPUContext *pContext) { // should only be done on render thread with the graphics context command list DebugAssert(Renderer::IsOnRenderThread()); m_pImmediateContext = pContext; } void D3D12GPUDevice::SetThreadCopyCommandQueue(ID3D12GraphicsCommandList *pCommandList) { // should only be done on render thread with the graphics context command list DebugAssert(Renderer::IsOnRenderThread() && s_pCurrentThreadCopyCommandQueue == nullptr); s_pCurrentThreadCopyCommandList = pCommandList; } bool D3D12GPUDevice::CreateLegacyRootSignatures() { HRESULT hResult; static const D3D12_DESCRIPTOR_RANGE descriptorRanges[] = { { D3D12_DESCRIPTOR_RANGE_TYPE_CBV, D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND }, { D3D12_DESCRIPTOR_RANGE_TYPE_SRV, D3D12_LEGACY_GRAPHICS_ROOT_SHADER_RESOURCE_SLOTS, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND }, { D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, D3D12_LEGACY_GRAPHICS_ROOT_SHADER_SAMPLER_SLOTS, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND }, { D3D12_DESCRIPTOR_RANGE_TYPE_UAV, D3D12_PS_CS_UAV_REGISTER_COUNT, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND } }; static const D3D12_ROOT_PARAMETER graphicsRootParameters[] = { // VS { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_VERTEX }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_VERTEX }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_VERTEX }, // HS { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_HULL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_HULL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_HULL }, // DS { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_DOMAIN }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_DOMAIN }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_DOMAIN }, // GS { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_GEOMETRY }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_GEOMETRY }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_GEOMETRY }, // PS { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_PIXEL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_PIXEL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_PIXEL }, // UAVs { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[3] }, D3D12_SHADER_VISIBILITY_PIXEL }, // Per-draw constant buffers { D3D12_ROOT_PARAMETER_TYPE_CBV, { D3D12_LEGACY_GRAPHICS_ROOT_CONSTANT_BUFFER_SLOTS, 0 }, D3D12_SHADER_VISIBILITY_ALL } }; static const D3D12_ROOT_PARAMETER computeRootParameters[] = { { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[0] }, D3D12_SHADER_VISIBILITY_ALL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[1] }, D3D12_SHADER_VISIBILITY_ALL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[2] }, D3D12_SHADER_VISIBILITY_ALL }, { D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, { 1, &descriptorRanges[3] }, D3D12_SHADER_VISIBILITY_ALL } }; D3D12_ROOT_SIGNATURE_DESC graphicsRootSignatureDesc = { countof(graphicsRootParameters), graphicsRootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT }; D3D12_ROOT_SIGNATURE_DESC computeRootSignatureDesc = { countof(computeRootParameters), computeRootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS }; // serialize it ID3DBlob *pRootSignatureBlob; ID3DBlob *pErrorBlob; // for graphics hResult = m_fnD3D12SerializeRootSignature(&graphicsRootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &pRootSignatureBlob, &pErrorBlob); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12SerializeRootSignature for graphics failed with hResult %08X", hResult); if (pErrorBlob != nullptr) { Log_ErrorPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } return false; } SAFE_RELEASE(pErrorBlob); hResult = m_pD3DDevice->CreateRootSignature(0, pRootSignatureBlob->GetBufferPointer(), pRootSignatureBlob->GetBufferSize(), IID_PPV_ARGS(&m_pLegacyGraphicsRootSignature)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateRootSignature for graphics failed with hResult %08X", hResult); pRootSignatureBlob->Release(); return false; } pRootSignatureBlob->Release(); // for compute hResult = m_fnD3D12SerializeRootSignature(&computeRootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &pRootSignatureBlob, &pErrorBlob); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12SerializeRootSignature for compute failed with hResult %08X", hResult); if (pErrorBlob != nullptr) { Log_ErrorPrint((const char *)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } return false; } SAFE_RELEASE(pErrorBlob); hResult = m_pD3DDevice->CreateRootSignature(0, pRootSignatureBlob->GetBufferPointer(), pRootSignatureBlob->GetBufferSize(), IID_PPV_ARGS(&m_pLegacyComputeRootSignature)); if (FAILED(hResult)) { Log_ErrorPrintf("CreateRootSignature for compute failed with hResult %08X", hResult); pRootSignatureBlob->Release(); return false; } pRootSignatureBlob->Release(); return true; } bool D3D12GPUDevice::CreateCPUDescriptorHeaps() { static const uint32 initialDescriptorHeapSize[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES] = { 16384, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV 1024, // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER 1024, // D3D12_DESCRIPTOR_HEAP_TYPE_RTV 1024 // D3D12_DESCRIPTOR_HEAP_TYPE_DSV }; static_assert(countof(initialDescriptorHeapSize) == countof(m_pCPUDescriptorHeaps), "descriptor heap type count"); for (uint32 i = 0; i < countof(initialDescriptorHeapSize); i++) { m_pCPUDescriptorHeaps[i] = D3D12DescriptorHeap::Create(m_pD3DDevice, (D3D12_DESCRIPTOR_HEAP_TYPE)i, initialDescriptorHeapSize[i], true); if (m_pCPUDescriptorHeaps[i] == nullptr) { Log_ErrorPrintf("Failed to allocate descriptor heap type %u", i); return false; } } // allocate null cbv m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]->Allocate(&m_nullCBVDescriptorHandle); m_pD3DDevice->CreateConstantBufferView(nullptr, m_nullCBVDescriptorHandle); // allocate null srv D3D12_SHADER_RESOURCE_VIEW_DESC nullSrvDesc = { DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING }; nullSrvDesc.Texture2D = { 0, 1, 0, 0.0f }; m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]->Allocate(&m_nullSRVDescriptorHandle); m_pD3DDevice->CreateShaderResourceView(nullptr, &nullSrvDesc, m_nullSRVDescriptorHandle); // allocate null sampler D3D12_SAMPLER_DESC samplerDesc = { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_WRAP, 0.0f, 1, D3D12_COMPARISON_FUNC_NEVER, { 0.0f, 0.0f, 0.0f, 0.0f }, 0.0f, Y_FLT_MAX }; m_pCPUDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]->Allocate(&m_nullSamplerHandle); m_pD3DDevice->CreateSampler(&samplerDesc, m_nullSamplerHandle); // done return true; } bool D3D12GPUDevice::CreateDefaultStates() { RENDERER_RASTERIZER_STATE_DESC rasterizerStateDesc; Renderer::FillDefaultRasterizerState(&rasterizerStateDesc); if ((m_pDefaultRasterizerState = static_cast<D3D12GPURasterizerState *>(CreateRasterizerState(&rasterizerStateDesc))) == nullptr) return false; RENDERER_DEPTHSTENCIL_STATE_DESC depthStencilStateDesc; Renderer::FillDefaultDepthStencilState(&depthStencilStateDesc); if ((m_pDefaultDepthStencilState = static_cast<D3D12GPUDepthStencilState *>(CreateDepthStencilState(&depthStencilStateDesc))) == nullptr) return false; RENDERER_BLEND_STATE_DESC blendStateDesc; Renderer::FillDefaultBlendState(&blendStateDesc); if ((m_pDefaultBlendState = static_cast<D3D12GPUBlendState *>(CreateBlendState(&blendStateDesc))) == nullptr) return false; return true; } bool D3D12GPUDevice::CreateConstantStorage() { HRESULT hResult; uint32 memoryUsage = 0; uint32 activeCount = 0; // allocate constant buffer storage const ShaderConstantBuffer::RegistryType *registry = ShaderConstantBuffer::GetRegistry(); m_constantBufferStorage.Resize(registry->GetNumTypes()); m_constantBufferStorage.ZeroContents(); for (uint32 i = 0; i < m_constantBufferStorage.GetSize(); i++) { // applicable to us? const ShaderConstantBuffer *declaration = registry->GetTypeInfoByIndex(i); if (declaration == nullptr) continue; if (declaration->GetPlatformRequirement() != RENDERER_PLATFORM_COUNT && declaration->GetPlatformRequirement() != RENDERER_PLATFORM_D3D12) continue; if (declaration->GetMinimumFeatureLevel() != RENDERER_FEATURE_LEVEL_COUNT && declaration->GetMinimumFeatureLevel() > m_featureLevel) continue; // set size so we know to allocate it later or on demand ConstantBufferStorage *pConstantBufferStorage = &m_constantBufferStorage[i]; pConstantBufferStorage->Size = ALIGNED_SIZE(declaration->GetBufferSize(), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT); // align next buffer to 64kb memoryUsage = (memoryUsage > 0) ? ALIGNED_SIZE(memoryUsage, D3D12_PLACED_CONSTANT_BUFFER_ALIGNMENT) : 0; memoryUsage += pConstantBufferStorage->Size; activeCount++; } // create a heap for the constant buffers D3D12_HEAP_DESC heapDesc = { memoryUsage, { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }, D3D12_PLACED_CONSTANT_BUFFER_ALIGNMENT, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; hResult = m_pD3DDevice->CreateHeap(&heapDesc, __uuidof(ID3D12Heap), (void **)&m_pConstantBufferStorageHeap); if (FAILED(hResult)) { Log_ErrorPrintf("Failed to create constant buffer heap: CreateHeap failed with hResult %08X", hResult); return false; } // preallocate constant buffers Log_DevPrintf("Preallocating %u constant buffers, total VRAM usage: %u bytes", activeCount, memoryUsage); uint32 currentOffset = 0; for (uint32 i = 0; i < m_constantBufferStorage.GetSize(); i++) { ConstantBufferStorage *pConstantBufferStorage = &m_constantBufferStorage[i]; if (pConstantBufferStorage->Size == 0) continue; // align buffer to 64kb currentOffset = (currentOffset > 0) ? ALIGNED_SIZE(currentOffset, D3D12_PLACED_CONSTANT_BUFFER_ALIGNMENT) : 0; // allocate resource in heap D3D12_RESOURCE_DESC resourceDesc = { D3D12_RESOURCE_DIMENSION_BUFFER, D3D12_PLACED_CONSTANT_BUFFER_ALIGNMENT, pConstantBufferStorage->Size, 1, 1, 1, DXGI_FORMAT_UNKNOWN, { 1, 0 }, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE }; hResult = m_pD3DDevice->CreatePlacedResource(m_pConstantBufferStorageHeap, currentOffset, &resourceDesc, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, nullptr, IID_PPV_ARGS(&pConstantBufferStorage->pResource)); if (FAILED(hResult)) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(i); Log_ErrorPrintf("Failed to allocate constant buffer %u (%s)", i, declaration->GetBufferName()); return false; } // allocate a handle for the view if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)->Allocate(&pConstantBufferStorage->DescriptorHandle)) { const ShaderConstantBuffer *declaration = ShaderConstantBuffer::GetRegistry()->GetTypeInfoByIndex(i); Log_ErrorPrintf("Failed to allocate constant buffer %u (%s)", i, declaration->GetBufferName()); SAFE_RELEASE(pConstantBufferStorage->pResource); return false; } // create a constant buffer view D3D12_CONSTANT_BUFFER_VIEW_DESC constantBufferViewDesc = { pConstantBufferStorage->pResource->GetGPUVirtualAddress(), pConstantBufferStorage->Size }; m_pD3DDevice->CreateConstantBufferView(&constantBufferViewDesc, pConstantBufferStorage->DescriptorHandle); // move buffer forward currentOffset += pConstantBufferStorage->Size; } return true; } ID3D12Resource *D3D12GPUDevice::GetConstantBufferResource(uint32 index) { DebugAssert(index < m_constantBufferStorage.GetSize()); return m_constantBufferStorage[index].pResource; } const D3D12DescriptorHandle *D3D12GPUDevice::GetConstantBufferDescriptor(uint32 index) const { DebugAssert(index < m_constantBufferStorage.GetSize()); return (m_constantBufferStorage[index].pResource != nullptr) ? &m_constantBufferStorage[index].DescriptorHandle : nullptr; } static const D3D12_COMPARISON_FUNC s_D3D12ComparisonFuncs[GPU_COMPARISON_FUNC_COUNT] = { D3D12_COMPARISON_FUNC_NEVER, // RENDERER_COMPARISON_FUNC_NEVER D3D12_COMPARISON_FUNC_LESS, // RENDERER_COMPARISON_FUNC_LESS D3D12_COMPARISON_FUNC_EQUAL, // RENDERER_COMPARISON_FUNC_EQUAL D3D12_COMPARISON_FUNC_LESS_EQUAL, // RENDERER_COMPARISON_FUNC_LESS_EQUAL D3D12_COMPARISON_FUNC_GREATER, // RENDERER_COMPARISON_FUNC_GREATER D3D12_COMPARISON_FUNC_NOT_EQUAL, // RENDERER_COMPARISON_FUNC_NOT_EQUAL D3D12_COMPARISON_FUNC_GREATER_EQUAL, // RENDERER_COMPARISON_FUNC_GREATER_EQUAL D3D12_COMPARISON_FUNC_ALWAYS, // RENDERER_COMPARISON_FUNC_ALWAYS }; D3D12GPUSamplerState::D3D12GPUSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, D3D12GPUDevice *pDevice, const D3D12DescriptorHandle &samplerHandle) : GPUSamplerState(pSamplerStateDesc) , m_pDevice(pDevice) , m_samplerHandle(samplerHandle) { m_pDevice->AddRef(); } D3D12GPUSamplerState::~D3D12GPUSamplerState() { m_pDevice->ScheduleDescriptorForDeletion(m_samplerHandle); m_pDevice->Release(); } void D3D12GPUSamplerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); } void D3D12GPUSamplerState::SetDebugName(const char *name) { } GPUSamplerState *D3D12GPUDevice::CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { D3D12_SAMPLER_DESC D3DSamplerDesc; if (!D3D12Helpers::FillD3D12SamplerStateDesc(pSamplerStateDesc, &D3DSamplerDesc)) { Log_ErrorPrintf("Invalid sampler state description"); return nullptr; } // allocate a descriptor D3D12DescriptorHandle descriptorHandle; if (!GetCPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)->Allocate(&descriptorHandle)) { Log_ErrorPrintf("Failed to allocate descriptor handle"); return false; } // fill descriptor m_pD3DDevice->CreateSampler(&D3DSamplerDesc, descriptorHandle); return new D3D12GPUSamplerState(pSamplerStateDesc, this, descriptorHandle); } D3D12GPURasterizerState::D3D12GPURasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc, const D3D12_RASTERIZER_DESC *pD3DRasterizerDesc) : GPURasterizerState(pRasterizerStateDesc) { Y_memcpy(&m_D3DRasterizerDesc, pD3DRasterizerDesc, sizeof(m_D3DRasterizerDesc)); } D3D12GPURasterizerState::~D3D12GPURasterizerState() { } void D3D12GPURasterizerState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); } void D3D12GPURasterizerState::SetDebugName(const char *name) { } GPURasterizerState *D3D12GPUDevice::CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) { D3D12_RASTERIZER_DESC D3DRasterizerDesc; if (!D3D12Helpers::FillD3D12RasterizerStateDesc(pRasterizerStateDesc, &D3DRasterizerDesc)) { Log_ErrorPrintf("Invalid rasterizer state description"); return nullptr; } return new D3D12GPURasterizerState(pRasterizerStateDesc, &D3DRasterizerDesc); } D3D12GPUDepthStencilState::D3D12GPUDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc, const D3D12_DEPTH_STENCIL_DESC *pD3DDepthStencilDesc) : GPUDepthStencilState(pDepthStencilStateDesc) { Y_memcpy(&m_D3DDepthStencilDesc, pD3DDepthStencilDesc, sizeof(m_D3DDepthStencilDesc)); } D3D12GPUDepthStencilState::~D3D12GPUDepthStencilState() { } void D3D12GPUDepthStencilState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); } void D3D12GPUDepthStencilState::SetDebugName(const char *name) { } GPUDepthStencilState *D3D12GPUDevice::CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) { D3D12_DEPTH_STENCIL_DESC D3DDepthStencilDesc; if (!D3D12Helpers::FillD3D12DepthStencilStateDesc(pDepthStencilStateDesc, &D3DDepthStencilDesc)) { Log_ErrorPrintf("Invalid depth-stencil state description"); return nullptr; } return new D3D12GPUDepthStencilState(pDepthStencilStateDesc, &D3DDepthStencilDesc); } D3D12GPUBlendState::D3D12GPUBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc, const D3D12_BLEND_DESC *pD3DBlendDesc) : GPUBlendState(pBlendStateDesc) { Y_memcpy(&m_D3DBlendDesc, pD3DBlendDesc, sizeof(m_D3DBlendDesc)); } D3D12GPUBlendState::~D3D12GPUBlendState() { } void D3D12GPUBlendState::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); } void D3D12GPUBlendState::SetDebugName(const char *name) { } GPUBlendState *D3D12GPUDevice::CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) { D3D12_BLEND_DESC D3DBlendDesc; if (!D3D12Helpers::FillD3D12BlendStateDesc(pBlendStateDesc, &D3DBlendDesc)) { Log_ErrorPrintf("Invalid blend state description"); return nullptr; } return new D3D12GPUBlendState(pBlendStateDesc, &D3DBlendDesc); } <file_sep>/Engine/Source/Engine/Physics/StaticObject.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Physics/StaticObject.h" #include "Engine/Physics/PhysicsWorld.h" #include "Engine/Physics/BulletHeaders.h" //Log_SetChannel(StaticObject); namespace Physics { StaticObject::StaticObject(uint32 entityID, const CollisionShape *pCollisionShape, const Transform &transform) : CollisionObject(entityID, pCollisionShape, transform), m_pBulletCollisionObject(nullptr) { // create bullet object m_pBulletCollisionObject = new btCollisionObject(); m_pBulletCollisionObject->setCollisionShape(m_pCollisionShape->GetBulletShape()); m_pBulletCollisionObject->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT); m_pBulletCollisionObject->forceActivationState(DISABLE_SIMULATION); m_pBulletCollisionObject->setUserPointer(reinterpret_cast<void *>(this)); // bullet doesn't zero these, so we do m_pBulletCollisionObject->setInterpolationLinearVelocity(btVector3(0.0f, 0.0f, 0.0f)); m_pBulletCollisionObject->setInterpolationAngularVelocity(btVector3(0.0f, 0.0f, 0.0f)); m_pBulletCollisionObject->setInterpolationWorldTransform(btTransform::getIdentity()); // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); m_pBulletCollisionObject->setWorldTransform(bulletTransform); // update our aabb from bullet UpdateBoundingBox(); } StaticObject::~StaticObject() { delete m_pBulletCollisionObject; } void StaticObject::OnAddedToPhysicsWorld(PhysicsWorld *pPhysicsWorld) { PhysicsProxy::OnAddedToPhysicsWorld(pPhysicsWorld); pPhysicsWorld->GetBulletWorld()->addCollisionObject(m_pBulletCollisionObject); } void StaticObject::OnRemovedFromPhysicsWorld(PhysicsWorld *pPhysicsWorld) { pPhysicsWorld->GetBulletWorld()->removeCollisionObject(m_pBulletCollisionObject); PhysicsProxy::OnRemovedFromPhysicsWorld(pPhysicsWorld); } btCollisionObject *Physics::StaticObject::GetBulletCollisionObject() const { return m_pBulletCollisionObject; } void Physics::StaticObject::OnCollisionShapeChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet m_pBulletCollisionObject->setCollisionShape(m_pCollisionShape->GetBulletShape()); m_pBulletCollisionObject->setWorldTransform(bulletTransform); // update aabb UpdateBoundingBox(); } void Physics::StaticObject::OnTransformChanged() { // fix up transform btTransform bulletTransform; ConvertWorldTransformToBulletTransform(m_transform, &bulletTransform); // update bullet m_pBulletCollisionObject->setWorldTransform(bulletTransform); // update aabb UpdateBoundingBox(); } } // namespace Physics <file_sep>/Editor/Source/Editor/ResourceBrowser/EditorStaticMeshImportDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/ResourceBrowser/EditorStaticMeshImportDialog.h" #include "Editor/ResourceBrowser/ui_EditorStaticMeshImportDialog.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" #include "ContentConverter/AssimpStaticMeshImporter.h" #include "ResourceCompiler/StaticMeshGenerator.h" #include "Editor/StaticMeshEditor/EditorStaticMeshEditor.h" EditorStaticMeshImportDialog::EditorStaticMeshImportDialog(QWidget *parent) : QDialog(parent), EditorProgressCallbacks(parent), m_ui(new Ui_EditorStaticMeshImportDialog()) { m_ui->setupUi(this); // minimum size setMinimumSize(100, 300); // fix up the ui m_ui->scaleVectorEdit->SetNumComponents(3); m_ui->scaleVectorEdit->SetValue(1.0f, 1.0f, 1.0f); ConnectUIEvents(); UpdateUIState(); } EditorStaticMeshImportDialog::~EditorStaticMeshImportDialog() { delete m_ui; } void EditorStaticMeshImportDialog::SetMaterialDirectory(const QString &materialDirectory) { m_ui->materialDirectoryLineEdit->setText(materialDirectory); } void EditorStaticMeshImportDialog::SetStatusText(const char *statusText) { m_ui->importerMessagesLabel->setText(statusText); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::SetProgressRange(uint32 range) { m_ui->progressBar->setRange(0, range); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::SetProgressValue(uint32 value) { m_ui->progressBar->setValue(value); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::DisplayError(const char *message) { m_ui->importerMessagesListWidget->addItem(ConvertStringToQString(SmallString::FromFormat("[E] %s", message))); m_ui->importerMessagesListWidget->scrollToBottom(); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::DisplayWarning(const char *message) { m_ui->importerMessagesListWidget->addItem(ConvertStringToQString(SmallString::FromFormat("[W] %s", message))); m_ui->importerMessagesListWidget->scrollToBottom(); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::DisplayInformation(const char *message) { m_ui->importerMessagesListWidget->addItem(ConvertStringToQString(SmallString::FromFormat("[I] %s", message))); m_ui->importerMessagesListWidget->scrollToBottom(); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::DisplayDebugMessage(const char *message) { m_ui->importerMessagesListWidget->addItem(ConvertStringToQString(SmallString::FromFormat("[D] %s", message))); m_ui->importerMessagesListWidget->scrollToBottom(); g_pEditor->ProcessBackgroundEvents(); } void EditorStaticMeshImportDialog::closeEvent(QCloseEvent *pCloseEvent) { QDialog::closeEvent(pCloseEvent); deleteLater(); } void EditorStaticMeshImportDialog::ConnectUIEvents() { connect(m_ui->fileNameLineEdit, SIGNAL(editingFinished()), this, SLOT(OnFileNameLineEditEditingFinished())); connect(m_ui->fileNameBrowseButton, SIGNAL(clicked()), this, SLOT(OnFileNameBrowseClicked())); connect(m_ui->importButton, SIGNAL(clicked()), this, SLOT(OnImportButtonClicked())); connect(m_ui->closeButton, SIGNAL(clicked()), this, SLOT(OnCloseButtonClicked())); } void EditorStaticMeshImportDialog::UpdateUIState() { String fileName(ConvertQStringToString(m_ui->fileNameLineEdit->text())); if (fileName.IsEmpty() || !FileSystem::FileExists(fileName)) { m_ui->importButton->setEnabled(false); m_ui->subObjectComboBox->setEnabled(false); m_ui->subObjectComboBox->clear(); return; } // try opening the file Array<String> subMeshNames; if (!AssimpStaticMeshImporter::GetFileSubMeshNames(fileName, subMeshNames, this)) { m_ui->importButton->setEnabled(false); m_ui->subObjectComboBox->setEnabled(false); m_ui->subObjectComboBox->clear(); return; } // add to combo box m_ui->subObjectComboBox->clear(); m_ui->subObjectComboBox->addItem(tr("* All Objects"), QVariant(-1)); for (uint32 i = 0; i < subMeshNames.GetSize(); i++) m_ui->subObjectComboBox->addItem(ConvertStringToQString(subMeshNames[i]), QVariant((int)i)); // enable everything m_ui->subObjectComboBox->setEnabled(true); m_ui->importButton->setEnabled(true); } void EditorStaticMeshImportDialog::OnFileNameLineEditEditingFinished() { UpdateUIState(); } void EditorStaticMeshImportDialog::OnFileNameBrowseClicked() { QString filename = QFileDialog::getOpenFileName(this, tr("Select Mesh File..."), QStringLiteral(""), tr("Static Mesh Formats (*.obj *.fbx *.ase *.3ds *.bsp *.md3 *.dae *.blend)"), NULL, 0); if (filename.isEmpty()) return; m_ui->fileNameLineEdit->setText(filename); UpdateUIState(); } void EditorStaticMeshImportDialog::OnImportButtonClicked() { AssimpStaticMeshImporter::Options options; AssimpStaticMeshImporter::SetDefaultOptions(&options); options.SourcePath = ConvertQStringToString(m_ui->fileNameLineEdit->text()); options.ImportMaterials = m_ui->importMaterialsCheckBox->isChecked(); options.MaterialDirectory = ConvertQStringToString(m_ui->materialDirectoryLineEdit->text()); options.MaterialPrefix = ConvertQStringToString(m_ui->materialPrefixLineEdit->text()); options.DefaultMaterialName = g_pEngine->GetDefaultMaterialName(); options.CoordinateSystem = (COORDINATE_SYSTEM)m_ui->coordinateSystemComboBox->currentIndex(); options.FlipFaceOrder = m_ui->flipWindingCheckBox->isChecked(); options.TransformMatrix = float4x4::MakeScaleMatrix(m_ui->scaleVectorEdit->GetValueFloat3()); options.BuildCollisionShapeType = m_ui->collisionShapeTypeComboBox->currentIndex(); // disable controls setEnabled(false); // create and run importer AssimpStaticMeshImporter *pImporter = new AssimpStaticMeshImporter(&options, this); if (!pImporter->Execute()) { DisplayError("Import failed. The error log may contain more information."); delete pImporter; setEnabled(true); return; } // set to full progress m_ui->progressBar->setRange(0, 1); m_ui->progressBar->setValue(1); setEnabled(true); // valid? if (!pImporter->GetOutputGenerator()->IsCompleteMesh()) { DisplayError("Import did not produce any usable meshes."); delete pImporter; return; } // spawn a static mesh editor EditorStaticMeshEditor *pStaticMeshEditor = new EditorStaticMeshEditor(); if (!pStaticMeshEditor->Create(pImporter->GetOutputGenerator(), nullptr, this)) { DisplayError("Failed to create editor."); delete pImporter; return; } pStaticMeshEditor->show(); // and cleanup delete pImporter; // close us if requested if (!m_ui->keepOpenAfterImportingCheckBox->isChecked()) OnCloseButtonClicked(); } void EditorStaticMeshImportDialog::OnCloseButtonClicked() { done(0); } <file_sep>/Engine/Source/Engine/Brush.h #pragma once #include "Engine/Common.h" class PropertyTable; class World; class Brush : public Object { DECLARE_OBJECT_TYPE_INFO(Brush, Object); DECLARE_OBJECT_PROPERTY_MAP(Brush); DECLARE_OBJECT_NO_FACTORY(Brush); public: Brush(const ObjectTypeInfo *pTypeInfo = &s_typeInfo); virtual ~Brush(); // Bounding volumes. const AABox &GetBoundingBox() const { return m_boundingBox; } const Sphere &GetBoundingSphere() const { return m_boundingSphere; } // World. World *GetWorld() const { return m_pWorld; } bool IsInWorld() const { return (m_pWorld != nullptr); } // Transform accessors. const Transform &GetTransform() const { return m_transform; } const float3 &GetPosition() const { return m_transform.GetPosition(); } const Quaternion &GetRotation() const { return m_transform.GetRotation(); } const float3 &GetScale() const { return m_transform.GetScale(); } // Virtual creation method for object types only. Not used by entity types. virtual bool Initialize() = 0; // Events virtual void OnAddToWorld(World *pWorld); virtual void OnRemoveFromWorld(World *pWorld); protected: // callbacks for property system static bool PropertyCallbackGetPosition(Brush *pObjectPtr, const void *pUserData, float3 *pValuePtr); static bool PropertyCallbackSetPosition(Brush *pObjectPtr, const void *pUserData, const float3 *pValuePtr); static bool PropertyCallbackGetRotation(Brush *pObjectPtr, const void *pUserData, Quaternion *pValuePtr); static bool PropertyCallbackSetRotation(Brush *pObjectPtr, const void *pUserData, const Quaternion *pValuePtr); static bool PropertyCallbackGetScale(Brush *pObjectPtr, const void *pUserData, float3 *pValuePtr); static bool PropertyCallbackSetScale(Brush *pObjectPtr, const void *pUserData, const float3 *pValuePtr); // World this object is located inside. World *m_pWorld; // Base object transform. Transform m_transform; // World-space bounds of the object. AABox m_boundingBox; Sphere m_boundingSphere; }; <file_sep>/Engine/Source/D3D12Renderer/D3D12CVars.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12Common.h" namespace CVars { // D3D11 cvars CVar r_d3d12_force_warp("r_d3d12_force_warp", CVAR_FLAG_REQUIRE_APP_RESTART, "0", "force WARP renderer for Direct3D 12", "bool"); CVar r_d3d12_break_on_error("r_d3d12_break_on_error", CVAR_FLAG_REQUIRE_APP_RESTART, "1", "when using debug runtime, break on error", "bool"); } <file_sep>/Engine/Source/Renderer/WorldRenderers/DebugNormalsWorldRenderer.h #pragma once #include "Renderer/WorldRenderers/SingleShaderWorldRenderer.h" class DebugNormalsWorldRenderer : public SingleShaderWorldRenderer { public: DebugNormalsWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~DebugNormalsWorldRenderer(); protected: virtual void DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) override; }; <file_sep>/Engine/Source/Renderer/RenderWorld.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" RenderWorld::RenderWorld() { } RenderWorld::~RenderWorld() { #if RENDER_WORLD_USE_LINKED_LIST for (NodeList::Iterator itr = m_nodes.Begin(); !itr.AtEnd(); ) { RenderProxy *pRenderProxy = itr->pRenderProxy; pRenderProxy->OnRemoveFromRenderWorld(this); pRenderProxy->m_pRenderWorld = NULL; pRenderProxy->Release(); itr = m_nodes.EraseIterator(itr); } #else while (m_nodes.GetSize() > 0) { Node &node = m_nodes[m_nodes.GetSize() - 1]; node.pRenderProxy->OnRemoveFromRenderWorld(this); node.pRenderProxy->m_pRenderWorld = nullptr; node.pRenderProxy->Release(); m_nodes.FastRemove(m_nodes.GetSize() - 1); } m_nodes.Obliterate(); #endif // should be empty Assert(m_nodes.GetSize() == 0); } void RenderWorld::AddRenderable(RenderProxy *pRenderProxy) { // bind it to the render world, that way any modifications that happen // to the proxy will be queued DebugAssert(pRenderProxy->m_pRenderWorld == nullptr); pRenderProxy->m_pRenderWorld = this; pRenderProxy->AddRef(); // queue the add command ReferenceCountedHolder<RenderWorld> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pRenderProxy, pThis]() { Node node; node.BoundingBox = pRenderProxy->GetBoundingBox(); node.BoundingSphere = pRenderProxy->GetBoundingSphere(); node.pRenderProxy = pRenderProxy; #if RENDER_WORLD_USE_LINKED_LIST pThis->m_nodes.PushBack(node); #else pThis->m_nodes.Add(node); #endif }); } void RenderWorld::RemoveRenderable(RenderProxy *pRenderProxy) { DebugAssert(pRenderProxy->m_pRenderWorld == this); ReferenceCountedHolder<RenderWorld> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pRenderProxy, pThis]() { #if RENDER_WORLD_USE_LINKED_LIST NodeList::Iterator itr; for (itr = m_nodes.Begin(); !itr.AtEnd(); itr.Forward()) { if (itr->pRenderProxy == pRenderProxy) break; } Assert(!itr.AtEnd()); pRenderProxy->OnRemoveFromRenderWorld(pThis); pThis->m_nodes.Erase(itr); pRenderProxy->m_pRenderWorld = NULL; pRenderProxy->Release(); #else for (uint32 i = 0; i < pThis->m_nodes.GetSize(); i++) { Node &node = pThis->m_nodes[i]; if (node.pRenderProxy == pRenderProxy) { pThis->m_nodes.FastRemove(i); pRenderProxy->m_pRenderWorld = NULL; pRenderProxy->Release(); return; } } Panic("Attempt to remove renderable not in render world"); #endif }); } void RenderWorld::MoveRenderable(RenderProxy *pRenderProxy) { DebugAssert(Renderer::IsOnRenderThread()); #if RENDER_WORLD_USE_LINKED_LIST NodeList::Iterator itr = m_nodes.Begin(); for (; !itr.AtEnd(); itr.Forward()) { if (itr->pRenderProxy == pRenderProxy) { itr->BoundingBox = pRenderProxy->GetBoundingBox(); itr->BoundingSphere = pRenderProxy->GetBoundingSphere(); return; } } #else for (uint32 i = 0; i < m_nodes.GetSize(); i++) { Node &node = m_nodes[i]; if (node.pRenderProxy == pRenderProxy) { node.BoundingBox = pRenderProxy->GetBoundingBox(); node.BoundingSphere = pRenderProxy->GetBoundingSphere(); return; } } #endif Panic("Attempting to update renderable not in world."); } <file_sep>/Engine/Source/ResourceCompiler/ClassTableGenerator.h #pragma once #include "ResourceCompiler/Common.h" #include "Core/Property.h" #include "Core/PropertyTable.h" class PropertyTemplate; class ClassTableGenerator { public: class Type { friend class ClassTableGenerator; public: struct PropertyDeclaration { uint32 Index; String Name; PROPERTY_TYPE Type; }; public: Type(uint32 index, const char *typeName); ~Type(); const uint32 GetIndex() const { return m_index; } const String &GetTypeName() const { return m_typeName; } const uint32 GetPropertyDeclarationCount() const { return m_properties.GetSize(); } const PropertyDeclaration *GetPropertyDeclarationByIndex(uint32 index) const { return m_properties[index]; } const PropertyDeclaration *GetPropertyDeclarationByName(const char *name) const; const PropertyDeclaration *AddPropertyDeclaration(const char *name, PROPERTY_TYPE type); private: uint32 m_index; String m_typeName; PODArray<PropertyDeclaration *> m_properties; }; public: ClassTableGenerator(); ~ClassTableGenerator(); const uint32 GetTypeCount() const { return m_types.GetSize(); } const Type *GetTypeByIndex(uint32 typeIndex) const { return m_types[typeIndex]; } const Type *GetTypeByName(const char *name) const; // new types const Type *CreateType(const char *name); // new type from property template const Type *CreateTypeFromPropertyTemplate(const char *name, const PropertyTemplate *pPropertyTemplate); // new type from property declaration list const Type *CreateTypeFromPropertyDeclarationList(const char *name, const PROPERTY_DECLARATION **ppProperties, uint32 nProperties); // compile bool Compile(ByteStream *pStream); // using the current state of this class table, serialize an object with a property table // the template is necessary due to any missing values being unknown bool SerializeObjectBinary(ByteStream *pStream, const char *typeName, const PropertyTemplate *pPropertyTemplate, const PropertyTable *pPropertyTable, uint32 *pTypeIndex, uint32 *pWrittenBytes) const; // serialize an individual object property string, converting it to its native type static bool SerializePropertyValueStringAsNativeType(PROPERTY_TYPE propertyType, const char *propertyValueString, ByteStream *pOutputStream, uint32 *pWrittenBytes); private: PODArray<Type *> m_types; }; <file_sep>/Engine/Source/OpenGLRenderer/OpenGLGPUTexture.h #pragma once #include "OpenGLRenderer/OpenGLCommon.h" class OpenGLGPUTexture1D : public GPUTexture1D { public: OpenGLGPUTexture1D(const GPU_TEXTURE1D_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTexture1D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTexture1DArray : public GPUTexture1DArray { public: OpenGLGPUTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTexture1DArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTexture2D : public GPUTexture2D { public: OpenGLGPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTexture2D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTexture2DArray : public GPUTexture2DArray { public: OpenGLGPUTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTexture2DArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTexture3D : public GPUTexture3D { public: OpenGLGPUTexture3D(const GPU_TEXTURE3D_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTexture3D(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTextureCube : public GPUTextureCube { public: OpenGLGPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTextureCube(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUTextureCubeArray : public GPUTextureCubeArray { public: OpenGLGPUTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pDesc, GLuint glTextureId); virtual ~OpenGLGPUTextureCubeArray(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLTextureId() const { return m_glTextureId; } private: GLuint m_glTextureId; }; class OpenGLGPUDepthTexture : public GPUDepthTexture { public: OpenGLGPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, GLuint glRenderBufferId); virtual ~OpenGLGPUDepthTexture(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; const GLuint GetGLRenderBufferId() const { return m_glRenderBufferId; } private: GLuint m_glRenderBufferId; }; class OpenGLGPURenderTargetView : public GPURenderTargetView { public: OpenGLGPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLuint textureName, bool multiLayer); virtual ~OpenGLGPURenderTargetView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; TEXTURE_TYPE GetTextureType() const { return m_textureType; } GLuint GetTextureName() const { return m_textureName; } bool IsMultiLayer() const { return m_multiLayer; } protected: TEXTURE_TYPE m_textureType; GLuint m_textureName; bool m_multiLayer; }; class OpenGLGPUDepthStencilBufferView : public GPUDepthStencilBufferView { public: OpenGLGPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLenum attachmentPoint, GLuint textureName, bool multiLayer); virtual ~OpenGLGPUDepthStencilBufferView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; TEXTURE_TYPE GetTextureType() const { return m_textureType; } GLenum GetAttachmentPoint() const { return m_attachmentPoint; } GLuint GetTextureName() const { return m_textureName; } bool IsMultiLayer() const { return m_multiLayer; } protected: TEXTURE_TYPE m_textureType; GLenum m_attachmentPoint; GLuint m_textureName; bool m_multiLayer; }; class OpenGLGPUComputeView : public GPUComputeView { public: OpenGLGPUComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc); virtual ~OpenGLGPUComputeView(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; protected: }; <file_sep>/Engine/Source/ResourceCompiler/ParticleSystemGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/ParticleSystemGenerator.h" #include "ResourceCompiler/ClassTableGenerator.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/DataFormats.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(ParticleSystemGenerator); const char *ParticleSystemGenerator::Emitter::Properties::MaxActiveParticles = "MaxActiveParticles"; const char *ParticleSystemGenerator::Emitter::Properties::UpdateInterval = "UpdateInterval"; const char *ParticleSystemGenerator::Emitter::Properties::SpawnRate = "SpawnRate"; const char *ParticleSystemGenerator::Emitter::Properties::SpawnCount = "SpawnCount"; ParticleSystemGenerator::Module::Module(const char *typeName) : m_typeName(typeName) { } ParticleSystemGenerator::Module::~Module() { } ParticleSystemGenerator::Emitter::Emitter(const char *name, const char *typeName) : m_name(name), m_typeName(typeName) { } ParticleSystemGenerator::Emitter::~Emitter() { for (uint32 i = 0; i < m_modules.GetSize(); i++) delete m_modules[i]; } const uint32 ParticleSystemGenerator::Emitter::GetMaxActiveParticles() const { return m_properties.GetPropertyValueDefaultUInt32(Properties::MaxActiveParticles, 1); } const float ParticleSystemGenerator::Emitter::GetUpdateInterval() const { return m_properties.GetPropertyValueDefaultFloat(Properties::UpdateInterval, 0.016f); } const float ParticleSystemGenerator::Emitter::GetSpawnRate() const { return m_properties.GetPropertyValueDefaultFloat(Properties::SpawnRate, 1.0f); } const uint32 ParticleSystemGenerator::Emitter::GetSpawnCount() const { return m_properties.GetPropertyValueDefaultUInt32(Properties::SpawnCount, 1); } void ParticleSystemGenerator::Emitter::SetName(const char *name) { m_name = name; } void ParticleSystemGenerator::Emitter::SetMaxActiveParticles(uint32 maxActiveParticles) { m_properties.SetPropertyValueUInt32(Properties::MaxActiveParticles, maxActiveParticles); } void ParticleSystemGenerator::Emitter::SetUpdateInterval(float updateInterval) { m_properties.SetPropertyValueFloat(Properties::UpdateInterval, updateInterval); } void ParticleSystemGenerator::Emitter::SetSpawnRate(float spawnRate) { m_properties.SetPropertyValueFloat(Properties::SpawnRate, spawnRate); } void ParticleSystemGenerator::Emitter::SetSpawnCount(uint32 spawnCount) { m_properties.SetPropertyValueUInt32(Properties::MaxActiveParticles, spawnCount); } const uint32 ParticleSystemGenerator::Emitter::GetModuleCount() const { return m_modules.GetSize(); } const ParticleSystemGenerator::Module *ParticleSystemGenerator::Emitter::GetModuleByIndex(uint32 index) const { return m_modules[index]; } ParticleSystemGenerator::Module *ParticleSystemGenerator::Emitter::GetModuleByIndex(uint32 index) { return m_modules[index]; } void ParticleSystemGenerator::Emitter::AddModule(Module *pModule) { m_modules.Add(pModule); } void ParticleSystemGenerator::Emitter::RemoveModule(Module *pModule) { int32 index = m_modules.IndexOf(pModule); DebugAssert(index >= 0); m_modules.OrderedRemove(index); } ParticleSystemGenerator::ParticleSystemGenerator() { } ParticleSystemGenerator::~ParticleSystemGenerator() { for (uint32 i = 0; i < m_emitters.GetSize(); i++) delete m_emitters[i]; } ParticleSystemGenerator::Emitter *ParticleSystemGenerator::CreateEmitter(const char *emitterName, const char *typeName) { return new Emitter(emitterName, typeName); } ParticleSystemGenerator::Module *ParticleSystemGenerator::CreateModule(const char *typeName) { return new Module(typeName); } bool ParticleSystemGenerator::LoadFromXML(const char *fileName, ByteStream *pStream) { XMLReader xmlReader; if (!xmlReader.Create(pStream, fileName)) return false; // find root element if (!xmlReader.SkipToElement("particlesystem")) return false; for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 particleSystemSelection = xmlReader.Select("emitter"); if (particleSystemSelection < 0) return false; switch (particleSystemSelection) { // emitter case 0: { const char *emitterNameStr = xmlReader.FetchAttribute("name"); const char *emitterTypeStr = xmlReader.FetchAttribute("type"); if (emitterNameStr == nullptr || emitterTypeStr == nullptr) { xmlReader.PrintError("missing emitter name/type"); return false; } if (xmlReader.IsEmptyElement()) { xmlReader.PrintError("invalid emitter declaration"); return false; } Emitter *pEmitter = new Emitter(emitterNameStr, emitterTypeStr); m_emitters.Add(pEmitter); // extract properties and modules for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 emitterSelection = xmlReader.Select("properties|modules"); if (emitterSelection < 0) return false; switch (emitterSelection) { // properties case 0: { if (!pEmitter->m_properties.LoadFromXML(xmlReader)) return false; DebugAssert(xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT && Y_stricmp(xmlReader.GetNodeName(), "properties") == 0); } break; // modules case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 modulesSelection = xmlReader.Select("module"); if (modulesSelection < 0) return false; const char *moduleTypeStr = xmlReader.FetchAttribute("type"); if (moduleTypeStr == nullptr) { xmlReader.PrintError("missing module type"); return false; } Module *pModule = new Module(moduleTypeStr); pEmitter->m_modules.Add(pModule); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 moduleSelection = xmlReader.Select("properties"); if (moduleSelection < 0) return false; if (!pModule->m_properties.LoadFromXML(xmlReader)) return false; DebugAssert(xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT && Y_stricmp(xmlReader.GetNodeName(), "properties") == 0); } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "module") == 0); break; } else { UnreachableCode(); return false; } } } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "modules") == 0); break; } else { UnreachableCode(); return false; } } } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "emitter") == 0); break; } else { UnreachableCode(); return false; } } // sanity checks if (pEmitter->GetModuleCount() == 0) { xmlReader.PrintError("Emitter declared without any modules"); return false; } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "particlesystem") == 0); break; } } // sanity check on system if (GetEmitterCount() == 0) { xmlReader.PrintError("particle system has no emitters"); return false; } return true; } bool ParticleSystemGenerator::SaveToXML(ByteStream *pStream) { return false; } const uint32 ParticleSystemGenerator::GetEmitterCount() const { return m_emitters.GetSize(); } const ParticleSystemGenerator::Emitter *ParticleSystemGenerator::GetEmitterByIndex(uint32 index) const { return m_emitters[index]; } ParticleSystemGenerator::Emitter *ParticleSystemGenerator::GetEmitterByIndex(uint32 index) { return m_emitters[index]; } const ParticleSystemGenerator::Emitter *ParticleSystemGenerator::GetEmitterByName(const char *name) const { for (uint32 i = 0; i < m_emitters.GetSize(); i++) { if (m_emitters[i]->GetName().Compare(name)) return m_emitters[i]; } return nullptr; } ParticleSystemGenerator::Emitter *ParticleSystemGenerator::GetEmitterByName(const char *name) { for (uint32 i = 0; i < m_emitters.GetSize(); i++) { if (m_emitters[i]->GetName().Compare(name)) return m_emitters[i]; } return nullptr; } bool ParticleSystemGenerator::Compile(ResourceCompilerCallbacks *pCallbacks, ByteStream *pStream) const { // write particle system header uint64 streamStartOffset = pStream->GetPosition(); uint64 endOffset; DF_PARTICLE_SYSTEM_HEADER systemHeader; systemHeader.Magic = DF_PARTICLE_SYSTEM_HEADER_MAGIC; systemHeader.HeaderSize = sizeof(systemHeader); systemHeader.ClassTableOffset = 0; systemHeader.ClassTableSize = 0; systemHeader.EmitterOffset = 0; systemHeader.EmitterCount = 0; if (!pStream->Write2(&systemHeader, sizeof(systemHeader))) return false; // create a class table ClassTableGenerator classTable; // for each emitter for (uint32 emitterIndex = 0; emitterIndex < m_emitters.GetSize(); emitterIndex++) { const Emitter *pEmitter = m_emitters[emitterIndex]; // lookup the class const ObjectTemplate *pEmitterTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pCallbacks, pEmitter->GetTypeName()); if (pEmitterTemplate == nullptr) { Log_ErrorPrintf("ParticleSystemGenerator::Compile: Emitter type '%s' is not known.", pEmitter->GetTypeName().GetCharArray()); return false; } // does it exist in the class table? const ClassTableGenerator::Type *pEmitterClassTableType = classTable.GetTypeByName(pEmitterTemplate->GetTypeName()); if (pEmitterClassTableType == nullptr) { // add it pEmitterClassTableType = classTable.CreateTypeFromPropertyTemplate(pEmitterTemplate->GetTypeName(), pEmitterTemplate->GetPropertyTemplate()); if (pEmitterClassTableType == nullptr) { Log_ErrorPrintf("ParticleSystemGenerator::Compile: Failed to add type '%s' to class table.", pEmitter->GetTypeName().GetCharArray()); return false; } } // add each of the modules for (uint32 moduleIndex = 0; moduleIndex < pEmitter->GetModuleCount(); moduleIndex++) { const Module *pModule = pEmitter->GetModuleByIndex(moduleIndex); // lookup the class const ObjectTemplate *pModuleTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pCallbacks, pModule->GetTypeName()); if (pModuleTemplate == nullptr) { Log_ErrorPrintf("ParticleSystemGenerator::Compile: Module type '%s' is not known.", pModule->GetTypeName().GetCharArray()); return false; } // does it exist in the class table? const ClassTableGenerator::Type *pModuleClassTableType = classTable.GetTypeByName(pModuleTemplate->GetTypeName()); if (pModuleClassTableType == nullptr) { // add it pModuleClassTableType = classTable.CreateTypeFromPropertyTemplate(pModuleTemplate->GetTypeName(), pModuleTemplate->GetPropertyTemplate()); if (pModuleClassTableType == nullptr) { Log_ErrorPrintf("ParticleSystemGenerator::Compile: Failed to add type '%s' to class table.", pModule->GetTypeName().GetCharArray()); return false; } } } } // write the class table { uint64 classTableStartOffset = pStream->GetPosition(); if (!classTable.Compile(pStream)) return false; // update sizes systemHeader.ClassTableOffset = static_cast<uint32>(classTableStartOffset - streamStartOffset); systemHeader.ClassTableSize = static_cast<uint32>(pStream->GetPosition() - classTableStartOffset); } // update pointer to start of emitters systemHeader.EmitterOffset = static_cast<uint32>(pStream->GetPosition() - streamStartOffset); // for each emitter for (uint32 emitterIndex = 0; emitterIndex < m_emitters.GetSize(); emitterIndex++) { const Emitter *pEmitter = m_emitters[emitterIndex]; // lookup the class const ObjectTemplate *pEmitterTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pCallbacks, pEmitter->GetTypeName()); DebugAssert(pEmitterTemplate != nullptr); // does it exist in the class table? const ClassTableGenerator::Type *pEmitterClassTableType = classTable.GetTypeByName(pEmitterTemplate->GetTypeName()); DebugAssert(pEmitterClassTableType != nullptr); // create the header for it uint64 emitterHeaderOffset = pStream->GetPosition(); DF_PARTICLE_SYSTEM_EMITTER_HEADER emitterHeader; emitterHeader.TotalSize = sizeof(emitterHeader); emitterHeader.TypeIndex = pEmitterClassTableType->GetIndex(); emitterHeader.PropertiesOffset = 0; emitterHeader.ModuleOffset = 0; emitterHeader.ModuleCount = 0; pStream->Write2(&emitterHeader, sizeof(emitterHeader)); // write emitter object uint32 bytesWritten; emitterHeader.PropertiesOffset = static_cast<uint32>(pStream->GetPosition() - streamStartOffset); if (!classTable.SerializeObjectBinary(pStream, pEmitterTemplate->GetTypeName(), pEmitterTemplate->GetPropertyTemplate(), pEmitter->GetPropertyTable(), &emitterHeader.TypeIndex, &bytesWritten)) return false; // update size emitterHeader.ModuleOffset = static_cast<uint32>(pStream->GetPosition() - streamStartOffset); emitterHeader.TotalSize += bytesWritten; // write each of the modules for (uint32 moduleIndex = 0; moduleIndex < pEmitter->GetModuleCount(); moduleIndex++) { const Module *pModule = pEmitter->GetModuleByIndex(moduleIndex); // lookup the class const ObjectTemplate *pModuleTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate(pCallbacks, pModule->GetTypeName()); DebugAssert(pModuleTemplate != nullptr); // does it exist in the class table? const ClassTableGenerator::Type *pModuleClassTableType = classTable.GetTypeByName(pModuleTemplate->GetTypeName()); DebugAssert(pModuleClassTableType != nullptr); // write module header uint64 moduleHeaderOffset = pStream->GetPosition(); DF_PARTICLE_SYSTEM_MODULE_HEADER moduleHeader; moduleHeader.TotalSize = sizeof(moduleHeader); moduleHeader.TypeIndex = pModuleClassTableType->GetIndex(); pStream->Write2(&moduleHeader, sizeof(moduleHeader)); // write module object if (!classTable.SerializeObjectBinary(pStream, pModuleTemplate->GetTypeName(), pModuleTemplate->GetPropertyTemplate(), pModule->GetPropertyTable(), &moduleHeader.TypeIndex, &bytesWritten)) return false; // update size moduleHeader.TotalSize += bytesWritten; emitterHeader.TotalSize += moduleHeader.TotalSize; emitterHeader.ModuleCount++; // fix up header endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(moduleHeaderOffset) || !pStream->Write2(&moduleHeader, sizeof(moduleHeader)) || !pStream->SeekAbsolute(endOffset)) return false; } // fix up header endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(emitterHeaderOffset) || !pStream->Write2(&emitterHeader, sizeof(emitterHeader)) || !pStream->SeekAbsolute(endOffset)) return false; // update emitter count systemHeader.EmitterCount++; } // rewrite system header endOffset = pStream->GetPosition(); if (!pStream->SeekAbsolute(streamStartOffset) || !pStream->Write2(&systemHeader, sizeof(systemHeader)) || !pStream->SeekAbsolute(endOffset)) return false; // done return true; } // Interface BinaryBlob *ResourceCompiler::CompileParticleSystem(ResourceCompilerCallbacks *pCallbacks, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.ParticleSystem.xml", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileMaterialShader: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); ParticleSystemGenerator *pGenerator = new ParticleSystemGenerator(); if (!pGenerator->LoadFromXML(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(pCallbacks, pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Renderer/WorldRenderers/MobileWorldRenderer.h #pragma once #include "Renderer/WorldRenderer.h" #include "Renderer/WorldRenderers/SSMShadowMapRenderer.h" class MobileWorldRenderer : public WorldRenderer { public: // aliased renderer types typedef SSMShadowMapRenderer DirectionalShadowMapRenderer; typedef SSMShadowMapRenderer SpotShadowMapRenderer; // render target formats static const PIXEL_FORMAT SCENE_COLOR_PIXEL_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; static const PIXEL_FORMAT SCENE_DEPTH_PIXEL_FORMAT = PIXEL_FORMAT_D16_UNORM; public: MobileWorldRenderer(GPUContext *pGPUContext, const Options *pOptions); virtual ~MobileWorldRenderer(); virtual bool Initialize() override; virtual void DrawWorld(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, GPURenderTargetView *pRenderTargetView, GPUDepthStencilBufferView *pDepthStencilBufferView) override; virtual void OnFrameComplete() override; private: // draw shadow maps from needed lights void DrawShadowMaps(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters); bool DrawDirectionalShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight); bool DrawSpotShadowMap(const RenderWorld *pRenderWorld, const ViewParameters *pViewParameters, RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLight); // set shader program parameters for queue entry void SetCommonShaderProgramParameters(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, ShaderProgram *pShaderProgram); // draw base pass for an object (emissive/lightmap/ambient light/main directional light) uint32 DrawBasePassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw forward light passes for an object uint32 DrawForwardLightPassesForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, bool useAdditiveBlending, bool depthWrites, GPU_COMPARISON_FUNC depthFunc); // draw a clear pass to set depth for an object void DrawEmptyPassForObject(const ViewParameters *pViewParameters, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); // draw z prepass void DrawDepthPrepass(const ViewParameters *pViewParameters); // draw opaque objects void DrawOpaqueObjects(const ViewParameters *pViewParameters); // draw lit/unlit translucent objects void DrawTranslucentObjects(const ViewParameters *pViewParameters); // finalize pass void DrawFinalPass(const ViewParameters *pViewParameters, GPURenderTargetView *pOutputRTV); // scene colour/depth textures //IntermediateBuffer *m_pSceneColorBuffer; //IntermediateBuffer *m_pSceneDepthBuffer; // shadow map renderers -- remove from heap DirectionalShadowMapRenderer *m_pDirectionalShadowMapRenderer; SpotShadowMapRenderer *m_pSpotShadowMapRenderer; // shadow map cache MemArray<DirectionalShadowMapRenderer::ShadowMapData> m_directionalShadowMaps; MemArray<SpotShadowMapRenderer::ShadowMapData> m_spotShadowMaps; // last rendered light indices, used to avoid buffer updates when not needed uint32 m_lastDirectionalLightIndex; uint32 m_lastPointLightIndex; uint32 m_lastSpotLightIndex; uint32 m_lastVolumetricLightIndex; // shader flags uint32 m_directionalLightShaderFlags; uint32 m_pointLightShaderFlags; uint32 m_spotLightShaderFlags; // composite shader ShaderProgram *m_pFinalCompositeShader; }; <file_sep>/Editor/Source/Editor/SimpleTreeModel.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/SimpleTreeModel.h" SimpleTreeModel::Item::Item(SimpleTreeModel *pModel, const Container *pParent, int parentIndex) : m_pModel(pModel), m_pParent(pParent), m_parentIndex(parentIndex), m_pFields(new QString[pModel->GetColumnCount()]), m_nColumns(pModel->GetColumnCount()), m_pUserData(nullptr) { } SimpleTreeModel::Item::~Item() { delete[] m_pFields; } QModelIndex SimpleTreeModel::Item::CreateIndexRelativeToParent(int column /* = 0 */) const { // work out the parent to emit from, make second level the top level const Item *pEmitFrom = this; if (m_pParent != nullptr && m_pParent->GetParent() == nullptr) pEmitFrom = nullptr; return m_pModel->createIndex(m_parentIndex, column, const_cast<Item *>(pEmitFrom)); } QModelIndex SimpleTreeModel::Item::CreateIndex(int column /* = 0 */) const { return m_pModel->createIndex(0, column, const_cast<Item *>(this)); } const QString SimpleTreeModel::Item::GetText(int column) const { Q_ASSERT(column >= 0 && column < m_nColumns); return m_pFields[column]; } void SimpleTreeModel::Item::SetText(int column, const QString text) { Q_ASSERT(column >= 0 && column < m_nColumns); m_pFields[column] = text; m_pModel->dataChanged(CreateIndexRelativeToParent(column), CreateIndexRelativeToParent(column)); } void SimpleTreeModel::Item::SetUserData(void *pUserData) { m_pUserData = pUserData; } SimpleTreeModel::Container::Container(SimpleTreeModel *pModel, Container *pParent, int parentIndex) : Item(pModel, pParent, parentIndex) { } SimpleTreeModel::Container::~Container() { for (int i = 0; i < m_items.size(); i++) delete m_items[i]; } SimpleTreeModel::Item *SimpleTreeModel::Container::CreateItem() { Item *pItem = new Item(m_pModel, this, m_items.size()); m_pModel->beginInsertRows(CreateIndex(), pItem->GetParentIndex(), pItem->GetParentIndex()); m_items.append(pItem); m_pModel->endInsertRows(); return pItem; } SimpleTreeModel::Container *SimpleTreeModel::Container::CreateContainer(const QString titleText) { Container *pContainer = new Container(m_pModel, this, m_items.size()); pContainer->SetTitle(titleText); m_pModel->beginInsertRows(CreateIndex(), pContainer->GetParentIndex(), pContainer->GetParentIndex()); m_items.append(pContainer); m_pModel->endInsertRows(); return pContainer; } const SimpleTreeModel::Item *SimpleTreeModel::Container::GetItem(int index) const { return (index >= 0 && index < m_items.size()) ? m_items[index] : nullptr; } SimpleTreeModel::Item * SimpleTreeModel::Container::GetItem(int index) { return (index >= 0 && index < m_items.size()) ? m_items[index] : nullptr; } int SimpleTreeModel::Container::FindItemIndexByPointer(const Item *pItem) const { for (int i = 0; i < m_items.size(); i++) { if (m_items[i] == pItem) return i; } return -1; } int SimpleTreeModel::Container::FindItemIndexByUserData(void *pUserData) const { for (int i = 0; i < m_items.size(); i++) { if (m_items[i]->GetUserData() == pUserData) return i; } return -1; } void SimpleTreeModel::Container::RemoveItem(Item *pItem) { int index = FindItemIndexByPointer(pItem); Q_ASSERT(index >= 0); return RemoveItem(index); } void SimpleTreeModel::Container::RemoveItem(int index) { Q_ASSERT(index >= 0 && index < m_items.size()); m_pModel->beginRemoveRows(CreateIndex(), index, index); Item *pItem = m_items[index]; m_items.removeAt(index); delete pItem; m_pModel->endRemoveRows(); } void SimpleTreeModel::Container::RemoveAllItems() { if (m_items.size() > 0) { m_pModel->beginRemoveRows(CreateIndex(), 0, m_items.size() - 1); for (int i = 0; i < m_items.size(); i++) delete m_items[i]; m_items.clear(); m_pModel->endRemoveRows(); } } SimpleTreeModel::SimpleTreeModel(int nColumns, QObject *pParent /*= nullptr*/) : QAbstractItemModel(pParent), m_nColumns(nColumns), m_pColumnNames(new QString[nColumns]), m_rootItem(this, nullptr, 0) { Q_ASSERT(nColumns > 0); } SimpleTreeModel::~SimpleTreeModel() { delete[] m_pColumnNames; } void SimpleTreeModel::SetColumnTitle(int i, const QString name) { Q_ASSERT(i < m_nColumns); m_pColumnNames[i] = name; } SimpleTreeModel::Container *SimpleTreeModel::CreateContainer(const QString titleText, Container *pContainer /*= nullptr*/) { if (pContainer != nullptr) return pContainer->CreateContainer(titleText); else return m_rootItem.CreateContainer(titleText); } SimpleTreeModel::Item *SimpleTreeModel::CreateItem(Container *pContainer /*= nullptr*/) { if (pContainer != nullptr) return pContainer->CreateItem(); else return m_rootItem.CreateItem(); } QModelIndex SimpleTreeModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex()*/) const { if (!hasIndex(row, column, parent)) return QModelIndex(); // root item? const Item *pItem; if (!parent.isValid()) pItem = &m_rootItem; else pItem = reinterpret_cast<Item *>(parent.internalPointer()); // should point to an item/container Q_ASSERT(pItem != nullptr && pItem->IsContainer()); // access this row index Q_ASSERT(row >= 0 && row < static_cast<const Container *>(pItem)->m_items.size()); return createIndex(row, column, static_cast<const Container *>(pItem)->m_items[row]); } QModelIndex SimpleTreeModel::parent(const QModelIndex &child) const { if (!child.isValid()) return QModelIndex(); // should point to an item/container const Item *pItem = reinterpret_cast<Item *>(child.internalPointer()); Q_ASSERT(pItem != nullptr); // look up parent, 'top-level', ie one level below the root items should not have a parent if (pItem->GetParent() == nullptr || pItem->GetParent() == &m_rootItem) return QModelIndex(); // create row return createIndex(pItem->GetParentIndex(), 0, const_cast<void *>(reinterpret_cast<const void *>(pItem->GetParent()))); } int SimpleTreeModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return 0; // root item? const Item *pItem; if (!parent.isValid()) pItem = &m_rootItem; else pItem = reinterpret_cast<Item *>(parent.internalPointer()); // should point to an item/container Q_ASSERT(pItem != nullptr && pItem->IsContainer()); // return row count return static_cast<const Container *>(pItem)->m_items.size(); } int SimpleTreeModel::columnCount(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return 0; return m_nColumns; } bool SimpleTreeModel::hasChildren(const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.column() > 0) return false; // root node if (!parent.isValid()) return true; // root item? const Item *pItem = reinterpret_cast<Item *>(parent.internalPointer()); // should point to an item/container Q_ASSERT(pItem != nullptr); // return true if it is a container return pItem->IsContainer(); } QVariant SimpleTreeModel::headerData(int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/) const { if (orientation == Qt::Horizontal) { if (role != Qt::DisplayRole) return QVariant(); if (section >= 0 && section < m_nColumns) return QVariant(m_pColumnNames[section]); else return QVariant(); } return QAbstractItemModel::headerData(section, orientation, role); } QVariant SimpleTreeModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole*/) const { if (!index.isValid()) return QVariant(); // should point to an item/container const Item *pItem = reinterpret_cast<Item *>(index.internalPointer()); Q_ASSERT(pItem != nullptr); // role? int column = index.column(); if (role == Qt::DisplayRole) { if (column >= 0 && column < m_nColumns) return pItem->m_pFields[column]; else return QVariant(); } return QVariant(); } <file_sep>/Engine/Source/ResourceCompiler/ShaderGraphNodeType.h #pragma once #include "ResourceCompiler/Common.h" #include "Renderer/RendererTypes.h" class ShaderGraphNode; typedef uint32 SHADER_GRAPH_VALUE_SWIZZLE; // common types #define SHADER_GRAPH_VALUE_SWIZZLE_NONE (((uint32)255 << 24) | ((uint32)255 << 16) | ((uint32)255 << 8) | ((uint32)255)) #define SHADER_GRAPH_VALUE_SWIZZLE_RGBA (((uint32)0 << 24) | ((uint32)1 << 16) | ((uint32)2 << 8) | ((uint32)3)) #define SHADER_GRAPH_VALUE_SWIZZLE_RGB (((uint32)0 << 24) | ((uint32)1 << 16) | ((uint32)2 << 8) | ((uint32)255)) #define SHADER_GRAPH_VALUE_SWIZZLE_RG (((uint32)0 << 24) | ((uint32)1 << 16) | ((uint32)255 << 8) | ((uint32)255)) #define SHADER_GRAPH_VALUE_SWIZZLE_R (((uint32)0 << 24) | ((uint32)255 << 16) | ((uint32)255 << 8) | ((uint32)255)) struct SHADER_GRAPH_NODE_INPUT { const char *Name; SHADER_PARAMETER_TYPE Type; const char *DefaultValue; bool Optional; }; struct SHADER_GRAPH_NODE_OUTPUT { const char *Name; SHADER_PARAMETER_TYPE Type; }; class ShaderGraphNodeTypeInfo : public ObjectTypeInfo { public: ShaderGraphNodeTypeInfo(const char *Name, const ObjectTypeInfo *pParentType, const PROPERTY_DECLARATION *pPropertyDeclarations, const SHADER_GRAPH_NODE_INPUT *pInputs, const SHADER_GRAPH_NODE_OUTPUT *pOutputs, const char *ShortName, const char *Description, ObjectFactory *pFactory); ~ShaderGraphNodeTypeInfo(); const char *GetShortName() const { return m_szShortName; } const char *GetDescription() const { return m_szDescription; } uint32 GetInputCount() const { return m_nInputs; } const SHADER_GRAPH_NODE_INPUT *GetInput(uint32 i) const { DebugAssert(i < m_nInputs); return &m_pInputs[i]; } uint32 GetOutputCount() const { return m_nOutputs; } const SHADER_GRAPH_NODE_OUTPUT *GetOutput(uint32 i) const { DebugAssert(i < m_nOutputs); return &m_pOutputs[i]; } protected: const char *m_szShortName; const char *m_szDescription; uint32 m_nInputs; const SHADER_GRAPH_NODE_INPUT *m_pInputs; uint32 m_nOutputs; const SHADER_GRAPH_NODE_OUTPUT *m_pOutputs; }; #define DECLARE_SHADER_GRAPH_NODE_TYPE_INFO(Type, ParentType) \ private: \ static ShaderGraphNodeTypeInfo s_typeInfo; \ static const PROPERTY_DECLARATION s_propertyDeclarations[]; \ static const SHADER_GRAPH_NODE_INPUT s_pInputs[]; \ static const SHADER_GRAPH_NODE_OUTPUT s_pOutputs[]; \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const ShaderGraphNodeTypeInfo *StaticTypeInfo() { return &s_typeInfo; } \ static ShaderGraphNodeTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } #define DECLARE_SHADER_GRAPH_NODE_GENERIC_FACTORY(Type) DECLARE_OBJECT_GENERIC_FACTORY(Type) #define DECLARE_SHADER_GRAPH_NODE_NO_FACTORY(Type) DECLARE_OBJECT_NO_FACTORY(Type) #define DEFINE_SHADER_GRAPH_NODE_TYPE_INFO(Type, ParentType, ShortName, Description) \ ShaderGraphNodeTypeInfo Type::s_typeInfo = ShaderGraphNodeTypeInfo(#Type, ParentType::StaticTypeInfo(), Type::s_propertyDeclarations, s_pInputs, s_pOutputs, ShortName, Description, Type::StaticFactory()); #define DEFINE_SHADER_GRAPH_NODE_GENERIC_FACTORY(Type) DEFINE_OBJECT_GENERIC_FACTORY(Type) #define BEGIN_SHADER_GRAPH_NODE_PROPERTIES(Type) \ const PROPERTY_DECLARATION Type::s_propertyDeclarations[] = { #define END_SHADER_GRAPH_NODE_PROPERTIES() \ PROPERTY_TABLE_MEMBER(NULL, PROPERTY_TYPE_COUNT, 0, NULL, NULL, NULL, NULL, NULL, NULL) \ }; #define DEFINE_SHADER_GRAPH_NODE_INPUTS(Type) \ const SHADER_GRAPH_NODE_INPUT Type::s_pInputs[] = { #define DEFINE_SHADER_GRAPH_NODE_INPUT_ENTRY(Name, Type, DefaultValue, Optional) \ { Name, Type, DefaultValue, Optional }, #define END_SHADER_GRAPH_NODE_INPUTS() \ { NULL, SHADER_PARAMETER_TYPE_COUNT, NULL, true } \ }; #define DEFINE_SHADER_GRAPH_NODE_OUTPUTS(Type) \ const SHADER_GRAPH_NODE_OUTPUT Type::s_pOutputs[] = { #define DEFINE_SHADER_GRAPH_NODE_OUTPUT_ENTRY(Name, Type) \ { Name, Type }, #define END_SHADER_GRAPH_NODE_OUTPUTS() \ { NULL, SHADER_PARAMETER_TYPE_COUNT } \ }; #define SHADER_GRAPH_NODE_TYPEINFO(Type) Type::StaticTypeInfo() #define SHADER_GRAPH_NODE_TYPEINFO_PTR(Ptr) Ptr->StaticTypeInfo() #define SHADER_GRAPH_NODE_MUTABLE_TYPEINFO(Type) Type::StaticMutableTypeInfo() #define SHADER_GRAPH_NODE_MUTABLE_TYPEINFO_PTR(Type) Type->StaticMutableTypeInfo() <file_sep>/Engine/Source/Renderer/ShaderProgramSelector.h #pragma once #include "Renderer/RendererTypes.h" class ShaderProgram; class GPUContext; class GPUResource; class GPUSamplerState; class ShaderComponentTypeInfo; class VertexFactoryTypeInfo; class GPUShaderProgram; class MaterialShader; class Material; struct RENDER_QUEUE_RENDERABLE_ENTRY; class ShaderProgramSelector { public: ShaderProgramSelector(uint32 baseGlobalFlags); // state switchers void SetGlobalFlags(uint32 globalFlags); void SetBaseShader(const ShaderComponentTypeInfo *pBaseShaderType, uint32 baseShaderFlags); void SetVertexFactory(const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags); void SetMaterial(const Material *pMaterial); // state switcher from render queue entry void SetQueueEntry(const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); // shader accessors ShaderProgram *MakeActive(GPUCommandList *pCommandList); private: enum DIRTY_FLAGS { DirtyGlobalFlags = (1 << 0), DirtyBaseShader = (1 << 1), DirtyVertexFactory = (1 << 2), DirtyMaterialShader = (1 << 3), DirtyMaterial = (1 << 4) }; const ShaderComponentTypeInfo *m_pBaseShaderType; const VertexFactoryTypeInfo *m_pVertexFactoryType; const Material *m_pMaterial; const MaterialShader *m_pMaterialShader; ShaderProgram *m_pCurrentProgram; uint32 m_baseGlobalFlags; uint32 m_globalShaderFlags; uint32 m_baseShaderFlags; uint32 m_vertexFactoryFlags; uint32 m_materialStaticSwitchMask; uint32 m_dirtyFlags; }; <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUOutputBuffer.cpp #include "D3D11Renderer/PrecompiledHeader.h" #include "D3D11Renderer/D3D11GPUOutputBuffer.h" #include "D3D11Renderer/D3D11GPUDevice.h" #include "Engine/SDLHeaders.h" Log_SetChannel(D3D11GPUOutputBuffer); // fix up a warning #ifdef SDL_VIDEO_DRIVER_WINDOWS #undef WIN32_LEAN_AND_MEAN #endif #include <SDL/SDL_syswm.h> static uint32 CalculateDXGISwapChainBufferCount(bool exclusiveFullscreen, RENDERER_VSYNC_TYPE vsyncType) { return 1 + ((IsCompositionActive() == FALSE || exclusiveFullscreen) ? 1 : 0) + ((vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING) ? 1 : 0); } D3D11GPUOutputBuffer::D3D11GPUOutputBuffer(ID3D11Device *pD3DDevice, IDXGISwapChain *pDXGISwapChain, HWND hWnd, uint32 width, uint32 height, DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType) : GPUOutputBuffer(vsyncType), m_pD3DDevice(pD3DDevice), m_pDXGISwapChain(pDXGISwapChain), m_hWnd(hWnd), m_width(width), m_height(height), m_backBufferFormat(backBufferFormat), m_depthStencilBufferFormat(depthStencilBufferFormat), m_pBackBufferTexture(nullptr), m_pRenderTargetView(nullptr), m_pDepthStencilBuffer(nullptr), m_pDepthStencilView(nullptr) { } D3D11GPUOutputBuffer::~D3D11GPUOutputBuffer() { if (m_pDepthStencilView != nullptr) m_pDepthStencilView->Release(); if (m_pDepthStencilBuffer != nullptr) m_pDepthStencilBuffer->Release(); if (m_pRenderTargetView != nullptr) m_pRenderTargetView->Release(); if (m_pBackBufferTexture != nullptr) m_pBackBufferTexture->Release(); m_pDXGISwapChain->Release(); m_pD3DDevice->Release(); } D3D11GPUOutputBuffer *D3D11GPUOutputBuffer::Create(IDXGIFactory *pDXGIFactory, ID3D11Device *pD3DDevice, HWND hWnd, DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthStencilBufferFormat, RENDERER_VSYNC_TYPE vsyncType) { // get client rect of the window RECT clientRect; GetClientRect(hWnd, &clientRect); uint32 width = Max(clientRect.right - clientRect.left, (LONG)1); uint32 height = Max(clientRect.bottom - clientRect.top, (LONG)1); // create swap chain DXGI_SWAP_CHAIN_DESC swapChainDesc; Y_memzero(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = backBufferFormat; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = CalculateDXGISwapChainBufferCount(false, vsyncType); swapChainDesc.OutputWindow = hWnd; swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; // create it IDXGISwapChain *pDXGISwapChain; HRESULT hResult = pDXGIFactory->CreateSwapChain(pD3DDevice, &swapChainDesc, &pDXGISwapChain); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUOutputBuffer::Create: CreateSwapChain failed with hResult %08X", hResult); return false; } // disable alt+enter, we handle it elsewhere hResult = pDXGIFactory->MakeWindowAssociation(swapChainDesc.OutputWindow, DXGI_MWA_NO_ALT_ENTER); if (FAILED(hResult)) Log_WarningPrintf("D3D11GPUOutputBuffer::Create: MakeWindowAssociation failed with hResult %08X.", hResult); // create object pD3DDevice->AddRef(); D3D11GPUOutputBuffer *pSwapChain = new D3D11GPUOutputBuffer(pD3DDevice, pDXGISwapChain, hWnd, width, height, backBufferFormat, depthStencilBufferFormat, vsyncType); if (!pSwapChain->InternalCreateBuffers()) { Log_ErrorPrintf("D3D11GPUOutputBuffer::Create: CreateRTVAndDepthStencilBuffer failed"); pSwapChain->Release(); return NULL; } return pSwapChain; } void D3D11GPUOutputBuffer::InternalResizeBuffers(uint32 width, uint32 height, RENDERER_VSYNC_TYPE vsyncType) { HRESULT hResult; // check if fullscreen state was lost BOOL newFullscreenState; hResult = m_pDXGISwapChain->GetFullscreenState(&newFullscreenState, nullptr); if (FAILED(hResult)) newFullscreenState = FALSE; // release resources InternalReleaseBuffers(); // calculate buffer count uint32 bufferCount = CalculateDXGISwapChainBufferCount((newFullscreenState == TRUE), m_vsyncType); Log_DevPrintf("D3D11GPUOutputBuffer::InternalResizeBuffers: New buffer count = %u", bufferCount); // invoke resize hResult = m_pDXGISwapChain->ResizeBuffers(bufferCount, width, height, m_backBufferFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); if (FAILED(hResult)) Panic("D3D11GPUOutputBuffer::ResizeBuffers: IDXGISwapChain::ResizeBuffers failed."); // update attributes m_width = width; m_height = height; m_vsyncType = vsyncType; // recreate textures if (!InternalCreateBuffers()) Panic("D3D11GPUOutputBuffer::ResizeBuffers: Failed to recreate texture objects on resized swap chain."); } bool D3D11GPUOutputBuffer::InternalCreateBuffers() { DebugAssert(m_pRenderTargetView == NULL && m_pDepthStencilBuffer == NULL && m_pDepthStencilView == NULL); // access the backbuffer texture ID3D11Texture2D *pBackBufferTexture; HRESULT hResult = m_pDXGISwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&pBackBufferTexture)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUOutputBuffer::CreateRTVAndDepthStencilBuffer: IDXGISwapChain::GetBuffer failed with hResult %08X", hResult); return false; } // get d3d texture desc D3D11_TEXTURE2D_DESC backBufferDesc; pBackBufferTexture->GetDesc(&backBufferDesc); // fixup dimensions m_width = backBufferDesc.Width; m_height = backBufferDesc.Height; // create RTV D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; rtvDesc.Format = backBufferDesc.Format; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; ID3D11RenderTargetView *pRenderTargetView; hResult = m_pD3DDevice->CreateRenderTargetView(pBackBufferTexture, &rtvDesc, &pRenderTargetView); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUOutputBuffer::CreateRTVAndDepthStencilBuffer: CreateRenderTargetView failed with hResult %08X", hResult); pBackBufferTexture->Release(); return false; } // create depth stencil ID3D11Texture2D *pDepthStencilBuffer = NULL; ID3D11DepthStencilView *pDepthStencilView = NULL; if (m_depthStencilBufferFormat != DXGI_FORMAT_UNKNOWN) { D3D11_TEXTURE2D_DESC depthStencilBufferDesc; Y_memcpy(&depthStencilBufferDesc, &backBufferDesc, sizeof(depthStencilBufferDesc)); depthStencilBufferDesc.Format = m_depthStencilBufferFormat; depthStencilBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilBufferDesc.CPUAccessFlags = 0; depthStencilBufferDesc.MiscFlags = 0; hResult = m_pD3DDevice->CreateTexture2D(&depthStencilBufferDesc, NULL, &pDepthStencilBuffer); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUOutputBuffer::CreateRTVAndDepthStencilBuffer: CreateTexture2D for DS failed with hResult %08X", hResult); pRenderTargetView->Release(); pBackBufferTexture->Release(); return false; } D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Format = m_depthStencilBufferFormat; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = 0; dsvDesc.Texture2D.MipSlice = 0; hResult = m_pD3DDevice->CreateDepthStencilView(pDepthStencilBuffer, &dsvDesc, &pDepthStencilView); if (FAILED(hResult)) { Log_ErrorPrintf("D3D11GPUOutputBuffer::CreateRTVAndDepthStencilBuffer: CreateDepthStencilView failed with hResult %08X", hResult); pDepthStencilBuffer->Release(); pRenderTargetView->Release(); pBackBufferTexture->Release(); return false; } } #ifdef Y_BUILD_CONFIG_DEBUG D3D11Helpers::SetD3D11DeviceChildDebugName(pBackBufferTexture, String::FromFormat("SwapChain backbuffer for hWnd %08X", (uint32)m_hWnd)); D3D11Helpers::SetD3D11DeviceChildDebugName(pRenderTargetView, String::FromFormat("SwapChain RTV for backbuffer for hWnd %08X", (uint32)m_hWnd)); if (m_pDepthStencilBuffer != NULL) { D3D11Helpers::SetD3D11DeviceChildDebugName(pBackBufferTexture, String::FromFormat("SwapChain depthstencil for hWnd %08X", (uint32)m_hWnd)); D3D11Helpers::SetD3D11DeviceChildDebugName(pRenderTargetView, String::FromFormat("SwapChainRTV for depthstencil for hWnd %08X", (uint32)m_hWnd)); } #endif m_pBackBufferTexture = pBackBufferTexture; m_pRenderTargetView = pRenderTargetView; m_pDepthStencilBuffer = pDepthStencilBuffer; m_pDepthStencilView = pDepthStencilView; return true; } void D3D11GPUOutputBuffer::InternalReleaseBuffers() { SAFE_RELEASE(m_pDepthStencilView); SAFE_RELEASE(m_pDepthStencilBuffer); SAFE_RELEASE(m_pRenderTargetView); SAFE_RELEASE(m_pBackBufferTexture); } void D3D11GPUOutputBuffer::SetVSyncType(RENDERER_VSYNC_TYPE vsyncType) { if (m_vsyncType == vsyncType) return; if (vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING || m_vsyncType == RENDERER_VSYNC_TYPE_TRIPLE_BUFFERING) InternalResizeBuffers(m_width, m_height, vsyncType); else m_vsyncType = vsyncType; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GPUOutputBuffer *D3D11GPUDevice::CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) { return D3D11GPUOutputBuffer::Create(m_pDXGIFactory, m_pD3DDevice, hWnd, m_swapChainBackBufferFormat, m_swapChainDepthStencilBufferFormat, vsyncType); } GPUOutputBuffer *D3D11GPUDevice::CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) { // retreive the hwnd from the sdl window SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(pSDLWindow, &info)) { Log_ErrorPrintf("D3D11RenderBackend::Create: SDL_GetWindowWMInfo failed: %s", SDL_GetError()); return false; } return D3D11GPUOutputBuffer::Create(m_pDXGIFactory, m_pD3DDevice, info.info.win.window, m_swapChainBackBufferFormat, m_swapChainDepthStencilBufferFormat, vsyncType); } <file_sep>/Engine/Source/ContentConverter/AssimpSceneImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiMesh; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class StaticMeshGenerator; class AssimpSceneImporter : public BaseImporter { public: struct Options { String SourcePath; String MeshDirectory; String MeshPrefix; String OutputMapName; bool ImportMaterials; String MaterialDirectory; String MaterialPrefix; String DefaultMaterialName; uint32 BuildCollisionShapeType; float4x4 TransformMatrix; COORDINATE_SYSTEM CoordinateSystem; uint32 CenterMeshes; // todo: split into multiple meshes, center mesh, origin, etc. }; public: AssimpSceneImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpSceneImporter(); static void SetDefaultOptions(Options *pOptions); bool Execute(); private: bool LoadScene(); bool CreateMaterials(); bool ParseScene(); bool ParseNode(const aiNode *pNode, const void *parentTransform); bool ParseMesh(const aiMesh *pMesh, StaticMeshGenerator *pOutputGenerator, uint32 lodIndex, const char *meshName); bool FinalizeMesh(StaticMeshGenerator *pOutputGenerator, const char *meshName); bool WriteMeshes(); bool WriteMap(); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; // global transform (coordinate system) float4x4 m_globalTransform; Array<String> m_materialMapping; struct OutputMesh { // pointer is a copy of the object in m_pScene, so no delete needed! const unsigned int *pSourceMeshes; uint32 nSourceMeshes; String MeshName; StaticMeshGenerator *pGenerator; float3 Offset; }; Array<OutputMesh> m_meshes; typedef HashTable<const aiMesh *, uint32> MeshGeneratorHashMap; MeshGeneratorHashMap m_aiMeshToOutputMesh; struct OutputMeshInstance { uint32 MeshIndex; float3 Position; Quaternion Rotation; float3 Scale; }; MemArray<OutputMeshInstance> m_meshInstances; }; <file_sep>/Engine/Source/D3D11Renderer/D3D11GPUDevice.h #pragma once #include "D3D11Renderer/D3D11Common.h" #include "D3D11Renderer/D3D11GPUContext.h" #include "D3D11Renderer/D3D11GPUOutputBuffer.h" class D3D11SamplerState : public GPUSamplerState { public: D3D11SamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, ID3D11SamplerState *pD3DSamplerState); virtual ~D3D11SamplerState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11SamplerState *GetD3DSamplerState() { return m_pD3DSamplerState; } private: ID3D11SamplerState *m_pD3DSamplerState; }; class D3D11RasterizerState : public GPURasterizerState { public: D3D11RasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc, ID3D11RasterizerState *pD3DRasterizerState); virtual ~D3D11RasterizerState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11RasterizerState *GetD3DRasterizerState() { return m_pD3DRasterizerState; } private: ID3D11RasterizerState *m_pD3DRasterizerState; }; class D3D11DepthStencilState : public GPUDepthStencilState { public: D3D11DepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc, ID3D11DepthStencilState *pD3DDepthStencilState); virtual ~D3D11DepthStencilState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11DepthStencilState *GetD3DDepthStencilState() { return m_pD3DDepthStencilState; } private: ID3D11DepthStencilState *m_pD3DDepthStencilState; }; class D3D11BlendState : public GPUBlendState { public: D3D11BlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc, ID3D11BlendState *pD3DBlendState); virtual ~D3D11BlendState(); virtual void GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const override; virtual void SetDebugName(const char *name) override; ID3D11BlendState *GetD3DBlendState() { return m_pD3DBlendState; } private: ID3D11BlendState *m_pD3DBlendState; }; class D3D11GPUDevice : public GPUDevice { public: D3D11GPUDevice(IDXGIFactory *pDXGIFactory, IDXGIAdapter *pDXGIAdapter, ID3D11Device *pD3DDevice, ID3D11Device1 *pD3DDevice1, D3D_FEATURE_LEVEL D3DFeatureLevel, RENDERER_FEATURE_LEVEL featureLevel, TEXTURE_PLATFORM texturePlatform, DXGI_FORMAT windowBackBufferFormat, DXGI_FORMAT windowDepthStencilFormat); virtual ~D3D11GPUDevice(); // private methods IDXGIFactory *GetDXGIFactory() const { return m_pDXGIFactory; } IDXGIAdapter *GetDXGIAdapter() const { return m_pDXGIAdapter; } ID3D11Device *GetD3DDevice() const { return m_pD3DDevice; } ID3D11Device1 *GetD3DDevice1() const { return m_pD3DDevice1; } DXGI_FORMAT GetSwapChainBackBufferFormat() const { return m_swapChainBackBufferFormat; } DXGI_FORMAT GetSwapChainDepthStencilBufferFormat() const { return m_swapChainDepthStencilBufferFormat; } // Device queries. virtual RENDERER_PLATFORM GetPlatform() const override final; virtual RENDERER_FEATURE_LEVEL GetFeatureLevel() const override final; virtual TEXTURE_PLATFORM GetTexturePlatform() const override final; virtual void GetCapabilities(RendererCapabilities *pCapabilities) const override final; virtual bool CheckTexturePixelFormatCompatibility(PIXEL_FORMAT PixelFormat, PIXEL_FORMAT *CompatibleFormat = nullptr) const override final; virtual void CorrectProjectionMatrix(float4x4 &projectionMatrix) const override final; virtual float GetTexelOffset() const override final; // Creates a swap chain on an existing window. virtual GPUOutputBuffer *CreateOutputBuffer(RenderSystemWindowHandle hWnd, RENDERER_VSYNC_TYPE vsyncType) override final; virtual GPUOutputBuffer *CreateOutputBuffer(SDL_Window *pSDLWindow, RENDERER_VSYNC_TYPE vsyncType) override final; // Resource creation virtual GPUQuery *CreateQuery(GPU_QUERY_TYPE type) override final; virtual GPUBuffer *CreateBuffer(const GPU_BUFFER_DESC *pDesc, const void *pInitialData = nullptr) override final; virtual GPUTexture1D *CreateTexture1D(const GPU_TEXTURE1D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture1DArray *CreateTexture1DArray(const GPU_TEXTURE1DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2D *CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture2DArray *CreateTexture2DArray(const GPU_TEXTURE2DARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTexture3D *CreateTexture3D(const GPU_TEXTURE3D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr, const uint32 *pInitialDataSlicePitch = nullptr) override final; virtual GPUTextureCube *CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUTextureCubeArray *CreateTextureCubeArray(const GPU_TEXTURECUBEARRAY_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData = nullptr, const uint32 *pInitialDataPitch = nullptr) override final; virtual GPUDepthTexture *CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) override final; virtual GPUSamplerState *CreateSamplerState(const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) override final; virtual GPURenderTargetView *CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilBufferView *CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) override final; virtual GPUComputeView *CreateComputeView(GPUResource *pResource, const GPU_COMPUTE_VIEW_DESC *pDesc) override final; virtual GPUDepthStencilState *CreateDepthStencilState(const RENDERER_DEPTHSTENCIL_STATE_DESC *pDepthStencilStateDesc) override final; virtual GPURasterizerState *CreateRasterizerState(const RENDERER_RASTERIZER_STATE_DESC *pRasterizerStateDesc) override final; virtual GPUBlendState *CreateBlendState(const RENDERER_BLEND_STATE_DESC *pBlendStateDesc) override final; virtual GPUShaderProgram *CreateGraphicsProgram(const GPU_VERTEX_ELEMENT_DESC *pVertexElements, uint32 nVertexElements, ByteStream *pByteCodeStream) override final; virtual GPUShaderProgram *CreateComputeProgram(ByteStream *pByteCodeStream) override final; // off-thread resource creation virtual void BeginResourceBatchUpload() override final; virtual void EndResourceBatchUpload() override final; private: IDXGIFactory *m_pDXGIFactory; IDXGIAdapter *m_pDXGIAdapter; ID3D11Device *m_pD3DDevice; ID3D11Device1 *m_pD3DDevice1; D3D_FEATURE_LEVEL m_D3DFeatureLevel; RENDERER_FEATURE_LEVEL m_featureLevel; TEXTURE_PLATFORM m_texturePlatform; DXGI_FORMAT m_swapChainBackBufferFormat; DXGI_FORMAT m_swapChainDepthStencilBufferFormat; }; <file_sep>/Engine/Source/Renderer/RenderProxies/VolumetricLightRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/VolumetricLightRenderProxy.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" VolumetricLightRenderProxy::VolumetricLightRenderProxy(uint32 entityId, bool enabled, const float3 &color, const float3 &position, float falloffRate) : RenderProxy(entityId), m_enabled(enabled), m_color(color), m_position(position), m_falloffRate(falloffRate), m_renderRange(1.0f), m_primitive(VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE), m_boxPrimitiveExtents(float3::Zero), m_spherePrimitiveRadius(1.0f) { UpdateBounds(); } VolumetricLightRenderProxy::~VolumetricLightRenderProxy() { } void VolumetricLightRenderProxy::UpdateBounds() { AABox boundingBox; Sphere boundingSphere; float renderRange; switch (m_primitive) { case VOLUMETRIC_LIGHT_PRIMITIVE_BOX: boundingBox.SetBounds(m_position - m_boxPrimitiveExtents, m_position + m_boxPrimitiveExtents); boundingSphere = Sphere::FromAABox(boundingBox); renderRange = m_boxPrimitiveExtents.Length(); break; case VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE: boundingSphere.SetCenterAndRadius(m_position, m_spherePrimitiveRadius); boundingBox = AABox::FromSphere(boundingSphere); renderRange = m_spherePrimitiveRadius; break; default: UnreachableCode(); return; } m_renderRange = renderRange; SetBounds(boundingBox, boundingSphere); } void VolumetricLightRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { // check enabled if (!m_enabled || !pRenderQueue->IsAcceptingLights()) return; RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY rcLight; rcLight.Position = m_position; rcLight.Range = m_renderRange; rcLight.LightColor = PixelFormatHelpers::ConvertSRGBToLinear(m_color); rcLight.Primitive = m_primitive; rcLight.FalloffRate = m_falloffRate; rcLight.BoxExtents = m_boxPrimitiveExtents; rcLight.SphereRadius = m_spherePrimitiveRadius; rcLight.Static = false; pRenderQueue->AddLight(&rcLight); } void VolumetricLightRenderProxy::SetEnabled(bool newEnabled) { if (!IsInWorld()) { m_enabled = newEnabled; } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newEnabled]() { pThis->m_enabled = newEnabled; }); } } void VolumetricLightRenderProxy::SetColor(const float3 &newColor) { if (!IsInWorld()) { m_color = newColor; } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, newColor]() { pThis->m_color = newColor; }); } } void VolumetricLightRenderProxy::SetPosition(const float3 &position) { if (!IsInWorld()) { m_position = position; UpdateBounds(); } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, position]() { pThis->m_position = position; pThis->UpdateBounds(); }); } } void VolumetricLightRenderProxy::SetFalloffRate(float falloffRate) { if (!IsInWorld()) { m_falloffRate = falloffRate; } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, falloffRate]() { pThis->m_falloffRate = falloffRate; }); } } void VolumetricLightRenderProxy::SetPrimitive(VOLUMETRIC_LIGHT_PRIMITIVE primitive) { if (!IsInWorld()) { DebugAssert(primitive < VOLUMETRIC_LIGHT_PRIMITIVE_COUNT); m_primitive = primitive; UpdateBounds(); } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, primitive]() { DebugAssert(primitive < VOLUMETRIC_LIGHT_PRIMITIVE_COUNT); pThis->m_primitive = primitive; pThis->UpdateBounds(); }); } } void VolumetricLightRenderProxy::SetBoxPrimitiveExtents(float3 boxExtents) { if (!IsInWorld()) { DebugAssert(m_primitive == VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE); m_boxPrimitiveExtents = boxExtents; UpdateBounds(); } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, boxExtents]() { DebugAssert(pThis->m_primitive == VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE); pThis->m_boxPrimitiveExtents = boxExtents; pThis->UpdateBounds(); }); } DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); } void VolumetricLightRenderProxy::SetSpherePrimitiveRadius(float sphereRadius) { if (!IsInWorld()) { DebugAssert(m_primitive == VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE); m_spherePrimitiveRadius = sphereRadius; UpdateBounds(); } else { ReferenceCountedHolder<VolumetricLightRenderProxy> pThis(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThis, sphereRadius]() { DebugAssert(pThis->m_primitive == VOLUMETRIC_LIGHT_PRIMITIVE_SPHERE); pThis->m_spherePrimitiveRadius = sphereRadius; pThis->UpdateBounds(); }); } } <file_sep>/Engine/Source/Renderer/ShaderCompilerFrontend.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderComponentTypeInfo.h" #include "Renderer/VertexFactoryTypeInfo.h" #include "Renderer/ShaderComponent.h" #include "Engine/MaterialShader.h" #include "ResourceCompilerInterface/ResourceCompilerInterface.h" #include "YBaseLib/CRC32.h" #include "YBaseLib/MD5Digest.h" Log_SetChannel(ShaderCompilerFrontend); // crc32 of all base shader sources static uint32 s_shaderStoreHash = 0; void ShaderCompilerFrontend::GenerateShaderHashCode(uint8 HashCode[16], uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { static const byte nullNamePlusFlags[5] = { 0, 0, 0, 0, 0 }; MD5Digest md5; // global shader flags md5.Update(&globalShaderFlags, sizeof(uint32)); // hash base shader name and flags if (pBaseShaderTypeInfo != NULL) { md5.Update(pBaseShaderTypeInfo->GetTypeName(), Y_strlen(pBaseShaderTypeInfo->GetTypeName())); md5.Update(&baseShaderFlags, sizeof(uint32)); } else { md5.Update(nullNamePlusFlags, sizeof(nullNamePlusFlags)); } // hash vertex factory name and flags if (pVertexFactoryTypeInfo != NULL) { md5.Update(pVertexFactoryTypeInfo->GetTypeName(), Y_strlen(pVertexFactoryTypeInfo->GetTypeName())); md5.Update(&vertexFactoryFlags, sizeof(uint32)); } else { md5.Update(nullNamePlusFlags, sizeof(nullNamePlusFlags)); } // hash material shader name and flags if (pMaterialShader != NULL) { md5.Update(pMaterialShader->GetName().GetCharArray(), pMaterialShader->GetName().GetLength()); md5.Update(&materialShaderFlags, sizeof(uint32)); } else { md5.Update(nullNamePlusFlags, sizeof(nullNamePlusFlags)); } // get digest md5.Final(HashCode); } static void AddGlobalShaderDefines(uint32 globalShaderFlags, ShaderCompilerParameters *pParameters) { if (globalShaderFlags & SHADER_GLOBAL_FLAG_MATERIAL_TINT) pParameters->AddPreprocessorMacro("MATERIAL_TINT", "1"); if (globalShaderFlags & SHADER_GLOBAL_FLAG_SHADER_QUALITY_HIGH) { pParameters->AddPreprocessorMacro("QUALITY_HIGH", "1"); pParameters->AddPreprocessorMacro("QUALITY_LEVEL", "3"); } else if (globalShaderFlags & SHADER_GLOBAL_FLAG_SHADER_QUALITY_MEDIUM) { pParameters->AddPreprocessorMacro("QUALITY_MEDIUM", "1"); pParameters->AddPreprocessorMacro("QUALITY_LEVEL", "2"); } else if (globalShaderFlags & SHADER_GLOBAL_FLAG_SHADER_QUALITY_LOW) { pParameters->AddPreprocessorMacro("QUALITY_LOW", "1"); pParameters->AddPreprocessorMacro("QUALITY_LEVEL", "1"); } if (globalShaderFlags & SHADER_GLOBAL_FLAG_USE_VERTEX_ID_QUADS) pParameters->AddPreprocessorMacro("USE_VERTEX_ID_QUADS", "1"); } static void AddMaterialShaderDefines(const MaterialShader *pMaterialShader, uint32 materialShaderFlags, ShaderCompilerParameters *pParameters) { // blendmode switch (pMaterialShader->GetBlendMode()) { case MATERIAL_BLENDING_MODE_NONE: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_NONE", "1"); break; case MATERIAL_BLENDING_MODE_ADDITIVE: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_ADDITIVE", "1"); break; case MATERIAL_BLENDING_MODE_STRAIGHT: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_STRAIGHT", "1"); break; case MATERIAL_BLENDING_MODE_PREMULTIPLIED: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_PREMULTIPLIED", "1"); break; case MATERIAL_BLENDING_MODE_MASKED: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_MASKED", "1"); break; case MATERIAL_BLENDING_MODE_SOFTMASKED: pParameters->AddPreprocessorMacro("MATERIAL_BLENDING_MODE_SOFTMASKED", "1"); break; default: UnreachableCode(); break; } // lightingtype switch (pMaterialShader->GetLightingType()) { case MATERIAL_LIGHTING_TYPE_EMISSIVE: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_TYPE_EMISSIVE", "1"); break; case MATERIAL_LIGHTING_TYPE_REFLECTIVE: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_TYPE_REFLECTIVE", "1"); break; case MATERIAL_LIGHTING_TYPE_REFLECTIVE_EMISSIVE: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_TYPE_REFLECTIVE_EMISSIVE", "1"); break; case MATERIAL_LIGHTING_TYPE_REFLECTIVE_TWO_SIDED: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_TYPE_REFLECTIVE_TWO_SIDED", "1"); break; default: UnreachableCode(); break; } // lightingmodel switch (pMaterialShader->GetLightingModel()) { case MATERIAL_LIGHTING_MODEL_PHONG: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_MODEL_PHONG", "1"); break; case MATERIAL_LIGHTING_MODEL_BLINN_PHONG: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_MODEL_BLINN_PHONG", "1"); break; case MATERIAL_LIGHTING_MODEL_PHYSICALLY_BASED: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_MODEL_PHYSICALLY_BASED", "1"); break; case MATERIAL_LIGHTING_MODEL_CUSTOM: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_MODEL_CUSTOM", "1"); break; default: UnreachableCode(); break; } // lighting normal space switch (pMaterialShader->GetLightingNormalSpace()) { case MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE", "1"); break; case MATERIAL_LIGHTING_NORMAL_SPACE_TANGENT_SPACE: pParameters->AddPreprocessorMacro("MATERIAL_LIGHTING_NORMAL_SPACE_TANGENT_SPACE", "1"); break; } // render mode switch (pMaterialShader->GetRenderMode()) { case MATERIAL_RENDER_MODE_NORMAL: pParameters->AddPreprocessorMacro("MATERIAL_RENDER_MODE_NORMAL", "1"); break; case MATERIAL_RENDER_MODE_WIREFRAME: pParameters->AddPreprocessorMacro("MATERIAL_RENDER_MODE_WIREFRAME", "1"); break; case MATERIAL_RENDER_MODE_POST_PROCESS: pParameters->AddPreprocessorMacro("MATERIAL_RENDER_MODE_POST_PROCESS", "1"); break; } // two-sided flag if (pMaterialShader->IsTwoSided()) pParameters->AddPreprocessorMacro("MATERIAL_RENDER_TWO_SIDED", "1"); // static switches -- since these are string allocated, they have to be pushed on the compiler parameters for (uint32 i = 0; i < pMaterialShader->GetStaticSwitchParameterCount(); i++) { const MaterialShader::StaticSwitchParameter *pStaticSwitchParameter = pMaterialShader->GetStaticSwitchParameter(i); if (materialShaderFlags & pStaticSwitchParameter->Mask) { SmallString staticSwitchMacro; staticSwitchMacro.Format("MTLStaticSwitch_%s", pStaticSwitchParameter->Name.GetCharArray()); TinyString staticSwitchValue; staticSwitchValue.AppendString("1"); pParameters->AddPreprocessorMacro(staticSwitchMacro, staticSwitchValue); } } } static void AddCommonDefines(RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags, ShaderCompilerParameters *pParameters) { switch (platform) { case RENDERER_PLATFORM_D3D11: pParameters->AddPreprocessorMacro("PLATFORM_D3D11", "1"); break; case RENDERER_PLATFORM_D3D12: pParameters->AddPreprocessorMacro("PLATFORM_D3D12", "1"); break; case RENDERER_PLATFORM_OPENGL: pParameters->AddPreprocessorMacro("PLATFORM_OPENGL", "1"); break; case RENDERER_PLATFORM_OPENGLES2: pParameters->AddPreprocessorMacro("PLATFORM_OPENGLES2", "1"); break; } // platform-specific defines switch (featureLevel) { case RENDERER_FEATURE_LEVEL_ES2: pParameters->AddPreprocessorMacro("FEATURE_LEVEL", "0"); break; case RENDERER_FEATURE_LEVEL_ES3: pParameters->AddPreprocessorMacro("FEATURE_LEVEL", "1"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_ES3", "1"); break; case RENDERER_FEATURE_LEVEL_SM4: pParameters->AddPreprocessorMacro("FEATURE_LEVEL", "2"); pParameters->AddPreprocessorMacro("SHADER_MODEL_VERSION", "4"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_ES3", "1"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_SM4", "1"); break; case RENDERER_FEATURE_LEVEL_SM5: pParameters->AddPreprocessorMacro("FEATURE_LEVEL", "3"); pParameters->AddPreprocessorMacro("SHADER_MODEL_VERSION", "5"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_ES3", "1"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_SM4", "1"); pParameters->AddPreprocessorMacro("HAS_FEATURE_LEVEL_SM5", "1"); break; } // which stages are present if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_VERTEX_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_VERTEX_SHADER", "1"); if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_HULL_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_HULL_SHADER", "1"); if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_DOMAIN_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_DOMAIN_SHADER", "1"); if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_PIXEL_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_PIXEL_SHADER", "1"); if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_GEOMETRY_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_GEOMETRY_SHADER", "1"); if (!pParameters->StageEntryPoints[SHADER_PROGRAM_STAGE_COMPUTE_SHADER].IsEmpty()) pParameters->AddPreprocessorMacro("HAS_COMPUTE_SHADER", "1"); // shader-specific defines if (pVertexFactoryTypeInfo != nullptr) pParameters->AddPreprocessorMacro("WITH_VERTEX_FACTORY", "1"); if (pMaterialShader != nullptr) pParameters->AddPreprocessorMacro("WITH_MATERIAL", "1"); } bool ShaderCompilerFrontend::CompileShader(ResourceCompilerInterface *pCompilerInterface, uint32 globalShaderFlags, RENDERER_PLATFORM platform, RENDERER_FEATURE_LEVEL featureLevel, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags, bool enableDebugInfo, ByteStream *pOutByteCodeStream, ByteStream *pOutInfoLogStream) { // work out compiler flags uint32 compilerFlags = 0; if (enableDebugInfo) compilerFlags |= SHADER_COMPILER_FLAG_ENABLE_DEBUG_INFO | SHADER_COMPILER_FLAG_DISABLE_OPTIMIZATIONS; // create parameter block ShaderCompilerParameters compilerParameters; compilerParameters.Platform = platform; compilerParameters.FeatureLevel = featureLevel; compilerParameters.CompilerFlags = compilerFlags; compilerParameters.EnableVerboseInfoLog = (pOutInfoLogStream != nullptr); compilerParameters.MaterialShaderName = (pMaterialShader != nullptr) ? pMaterialShader->GetName() : EmptyString; compilerParameters.MaterialShaderFlags = materialShaderFlags; // add global defines AddGlobalShaderDefines(globalShaderFlags, &compilerParameters); // fill from types if (!pBaseShaderTypeInfo->FillShaderCompilerParameters(globalShaderFlags, baseShaderFlags, vertexFactoryFlags, &compilerParameters) || (pVertexFactoryTypeInfo != nullptr && !pVertexFactoryTypeInfo->FillShaderCompilerParameters(globalShaderFlags, baseShaderFlags, vertexFactoryFlags, &compilerParameters))) { return false; } // material defines if (pMaterialShader != nullptr) AddMaterialShaderDefines(pMaterialShader, materialShaderFlags, &compilerParameters); // common defines AddCommonDefines(platform, featureLevel, pVertexFactoryTypeInfo, vertexFactoryFlags, pMaterialShader, materialShaderFlags, &compilerParameters); // create info log if requested if (pOutInfoLogStream != nullptr) { TextWriter textWriter(pOutInfoLogStream); textWriter.WriteLine("Shader Compiler"); textWriter.WriteFormattedLine("Platform: %s", NameTable_GetNameString(NameTables::RendererPlatform, platform)); textWriter.WriteFormattedLine("Feature Level: %s", NameTable_GetNameString(NameTables::RendererFeatureLevel, featureLevel)); textWriter.WriteFormattedLine("Base Shader: %s %08X", (pBaseShaderTypeInfo != NULL) ? pBaseShaderTypeInfo->GetTypeName() : "NULL", baseShaderFlags); textWriter.WriteFormattedLine("Vertex Factory: %s %08X", (pVertexFactoryTypeInfo != NULL) ? pVertexFactoryTypeInfo->GetTypeName() : "NULL", vertexFactoryFlags); textWriter.WriteFormattedLine("Material Shader: %s %08X", (pMaterialShader != NULL) ? pMaterialShader->GetName().GetCharArray() : "NULL", materialShaderFlags); textWriter.WriteLine(""); } // pass off to resource compiler return pCompilerInterface->CompileShader(&compilerParameters, pOutByteCodeStream, pOutInfoLogStream); } uint32 ShaderCompilerFrontend::GetShaderStoreHash() { return s_shaderStoreHash; } static void CalculateShaderStoreHash() { CRC32 crc; FileSystem::FindResultsArray fileList; if (g_pVirtualFileSystem->FindFiles("shaders/base", "*.hlsl", FILESYSTEM_FIND_FILES | FILESYSTEM_FIND_RECURSIVE, &fileList)) { for (uint32 i = 0; i < fileList.GetSize(); i++) { BinaryBlob *pBlob = g_pVirtualFileSystem->GetFileContents(fileList[i].FileName); if (pBlob != nullptr) { crc.HashBytes(pBlob->GetDataPointer(), pBlob->GetDataSize()); pBlob->Release(); } } } s_shaderStoreHash = crc.GetCRC(); } void ShaderCompilerFrontend::InitializeShaderCompilerSupport() { // not threadsafe.. whatever. static bool initialized = false; if (initialized) return; initialized = true; Log_DevPrintf("ShaderCompilerFrontend::InitializeShaderCompilerSupport()"); // calculate the crc of all base shader files CalculateShaderStoreHash(); Log_DevPrintf(" Shader store CRC = 0x%08X", s_shaderStoreHash); // calculate the parameters crc for each shader type uint32 nShaderComponentTypes = 0; for (uint32 typeIndex = 0; typeIndex < ShaderComponentTypeInfo::GetRegistry().GetNumTypes(); typeIndex++) { const ObjectTypeInfo *pObjectTypeInfo = ShaderComponentTypeInfo::GetRegistry().GetTypeInfoByIndex(typeIndex); if (pObjectTypeInfo == nullptr || !pObjectTypeInfo->IsDerived(OBJECT_TYPEINFO(ShaderComponent))) continue; // cast (messy..) ShaderComponentTypeInfo *pShaderComponentTypeInfo = const_cast<ShaderComponentTypeInfo *>(static_cast<const ShaderComponentTypeInfo *>(pObjectTypeInfo)); const SHADER_COMPONENT_PARAMETER_BINDING *pBindings = pShaderComponentTypeInfo->GetParameterBindings(); // calculate crc CRC32 crc; for (uint32 i = 0; i < pShaderComponentTypeInfo->GetParameterBindingCount(); i++) { uint32 typeAsInt = (uint32)pBindings[i].ExpectedType; crc.HashBytes(pBindings[i].ParameterName, Y_strlen(pBindings[i].ParameterName)); crc.HashBytes(&typeAsInt, sizeof(typeAsInt)); } pShaderComponentTypeInfo->SetParameterCRC(crc.GetCRC()); nShaderComponentTypes++; } Log_DevPrintf(" %u shader component types registered.", nShaderComponentTypes); } bool ShaderCompilerFrontend::RecalculateShaderStoreHash() { uint32 old = s_shaderStoreHash; CalculateShaderStoreHash(); return (old != s_shaderStoreHash); } <file_sep>/Editor/Source/Editor/BlockMeshEditor/EditorBlockMeshEditor.h #pragma once #include "Editor/Common.h" #include "Editor/EditorViewController.h" #include "ResourceCompiler/BlockMeshGenerator.h" #include "Engine/BlockPalette.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "Renderer/VertexFactories/PlainVertexFactory.h" #include "Renderer/MiniGUIContext.h" #include "Renderer/Renderer.h" #include "Renderer/WorldRenderer.h" #include "Core/Image.h" class EditorLightSimulator; class EditorBlockVolumeRenderProxy; class Ui_EditorBlockMeshEditor; class EditorBlockMeshEditor : public QMainWindow { Q_OBJECT public: enum STATE { STATE_NONE, STATE_MOVE_CAMERA, STATE_ROTATE_CAMERA, STATE_MANIPULATE_LIGHT, }; enum WIDGET { WIDGET_CAMERA, WIDGET_SELECT_BLOCKS, WIDGET_SELECT_AREA, WIDGET_PLACE_BLOCKS, WIDGET_DELETE_BLOCKS, WIDGET_LIGHT_MANIPULATOR, WIDGET_COUNT, }; struct AvailableBlockType { const BlockPalette::BlockType *pBlockType; String BlockName; QIcon BlockTypeIcon; }; public: EditorBlockMeshEditor(); ~EditorBlockMeshEditor(); // mainly for overlay drawing in edit modes EditorViewController &GetCamera() { return m_viewController; } MiniGUIContext &GetGUIContext() { return m_guiContext; } // render options accessors const EDITOR_CAMERA_MODE GetCameraMode() const { return m_viewController.GetCameraMode(); } const EDITOR_RENDER_MODE GetRenderMode() const { return m_renderMode; } const uint32 GetViewportFlags() const { return m_viewportFlags; } const bool HasViewportFlag(uint32 flag) const { return (m_viewportFlags & flag) != 0; } // mode setters void SetCameraMode(EDITOR_CAMERA_MODE cameraMode); void SetRenderMode(EDITOR_RENDER_MODE renderMode); void SetViewportFlag(uint32 flag); void ClearViewportFlag(uint32 flag); // creation/loading/saving bool Create(const char *meshName, const BlockPalette *pBlockList, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool Load(const char *meshName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool Save(ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); bool SaveAs(const char *meshName, ProgressCallbacks *pProgressCallbacks = ProgressCallbacks::NullProgressCallback); // generator const BlockMeshGenerator *GetBlockMeshGenerator() const { return m_pGenerator; } // current lod const uint32 GetCurrentLOD() const { return m_currentLOD; } void SetCurrentLOD(uint32 LOD); // tool management const WIDGET GetWidget() const { return m_eCurrentWidget; } void SetWidget(WIDGET t); // if in PLACE_BLOCKS widget mode const BlockVolumeBlockType GetPlaceBlockWidgetBlockType() const { return m_iPlaceBlockToolBlockType; } void SetPlaceBlockWidgetBlockType(BlockVolumeBlockType t); void SetNextPlaceBlockWidgetBlockType(); void SetPreviousPlaceBlockWidgetBlockType(); // if in SELECT_BLOCKS widget mode const uint32 GetSelectedBlockCount() const { return m_SelectedBlocks.GetSize(); } inline void SelectBlock(int32 x, int32 y, int32 z) { SelectBlock(Vector3i(x, y, z)); } inline void DeselectBlock(int32 x, int32 y, int32 z) { DeselectBlock(Vector3i(x, y, z)); } bool IsBlockSelected(const int3 &coords); void SelectBlock(const int3 &coords); void DeselectBlock(const int3 &coords); void DeselectAllBlocks(); // if in SELECT_AREA widget mode const int3 &GetSelectedAreaMinBounds() const { return m_SelectedArea[0]; } const int3 &GetSelectedAreaMaxBounds() const { return m_SelectedArea[1]; } void ExpandSelectionToHeight(); void ExpandSelection(const int3 &direction); void ClearSelectedArea(); // if in SELECT_BLOCKS or SELECT_AREA widget mode void MoveSelectedBlocks(const int3 &direction); // flag for redraw void FlagForRedraw() { m_bRedrawPending = true; } protected: // --- common initialization whether creating/loading --- bool Initialize(ProgressCallbacks *pProgressCallbacks); bool GenerateAvailableBlockTypes(ProgressCallbacks *pProgressCallbacks); // --- close event --- bool OnCloseAttempt(); void Deinitialize(); // retrieve the block position that is under the specified mouse position. bool GetBlockCoordinatesForMousePosition(int3 *pBlockCoordinates, CUBE_FACE *pFaceIndex, const int2 &mousePosition) const; bool GetPlaceBlockCoordinatesForMousePosition(int3 *pBlockCoordinates, const int2 &mousePosition) const; // resources bool CreateHardwareResources(); void ReleaseHardwareResources(); // events void Tick(const float dt); // --- draw methods --- void Draw(); void DrawView(); void DrawGrid(); void Draw3DOverlays(); // --- mesh methods --- void SetBlock(const int3 &blockPosition, BlockVolumeBlockType value); void CheckForMeshSizeChanges(); void UpdateMouseBlockCoordinates(); void UpdateMeshBounds(); void UpdateMeshView(); void UpdateSelectedBlocksView(); void UpdatePreviewMesh(BlockVolumeBlockType blockType); // --- ui --- Ui_EditorBlockMeshEditor *m_ui; // --- mesh --- const BlockPalette *m_pBlockList; BlockMeshGenerator *m_pGenerator; String m_meshName; String m_meshFileName; // --- block previews --- AvailableBlockType *m_pAvailableBlockTypes; uint32 m_nAvailableBlockTypes; // --- editor info --- EditorViewController m_viewController; EDITOR_RENDER_MODE m_renderMode; uint32 m_viewportFlags; // --- renderer stuff --- GPUOutputBuffer *m_pSwapChain; WorldRenderer *m_pWorldRenderer; MiniGUIContext m_guiContext; bool m_bHardwareResourcesCreated; bool m_bRedrawPending; // --- volumes --- BlockMeshVolume m_meshVolume; BlockMeshVolume m_selectedVolume; BlockMeshVolume m_previewVolume; // --- mesh render proxies --- RenderWorld *m_pRenderWorld; EditorLightSimulator *m_pLightSimulator; EditorBlockVolumeRenderProxy *m_pMeshRenderProxy; EditorBlockVolumeRenderProxy *m_pSelectedRenderProxy; EditorBlockVolumeRenderProxy *m_pPreviewRenderProxy; // --- tool info --- uint32 m_currentLOD; WIDGET m_eCurrentWidget; int3 m_MouseOverBlock; bool m_bMouseOverBlockSet; CUBE_FACE m_iMouseOverBlockFaceIndex; bool m_bMouseOverPlaceBlockSet; int3 m_MouseOverPlaceBlock; // -- place tool BlockVolumeBlockType m_iPlaceBlockToolBlockType; // -- select tool MemArray<int3> m_SelectedBlocks; // -- select area tool -- uint8 m_iSelectedAreaCount; int3 m_SelectedArea[2]; // --- key/button states --- STATE m_eCurrentState; uint32 m_iStateData; int2 m_lastMousePosition; //=================================================================================================================================================================== // UI Event Handlers //=================================================================================================================================================================== void ConnectUIEvents(); private: //void focusInEvent(QFocusEvent *pFocusEvent); void closeEvent(QCloseEvent *pCloseEvent); private Q_SLOTS: void OnActionSaveMeshClicked(); void OnActionSaveMeshAsClicked(); void OnActionCloseClicked(); void OnActionEditUndoClicked(); void OnActionEditRedoClicked(); void OnActionCameraPerspectiveTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_PERSPECTIVE); } void OnActionCameraArcballTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_ARCBALL); } void OnActionCameraIsometricTriggered(bool checked) { SetCameraMode(EDITOR_CAMERA_MODE_ISOMETRIC); } void OnActionViewWireframeTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_WIREFRAME); } void OnActionViewUnlitTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_FULLBRIGHT); } void OnActionViewLitTriggered(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_LIT); } void OnActionViewFlagShadowsTriggered(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS); } void OnActionViewFlagWireframeOverlayTriggered(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY); } void OnActionWidgetCameraTriggered(bool checked) { SetWidget(WIDGET_CAMERA); } void OnActionWidgetSelectBlocksTriggered(bool checked) { SetWidget(WIDGET_SELECT_BLOCKS); } void OnActionWidgetSelectAreaTriggered(bool checked) { SetWidget(WIDGET_SELECT_AREA); } void OnActionWidgetPlaceBlocksTriggered(bool checked) { SetWidget(WIDGET_PLACE_BLOCKS); } void OnActionWidgetDeleteBlocksTriggered(bool checked) { SetWidget(WIDGET_DELETE_BLOCKS); } void OnActionWidgetLightManipulatorTriggered(bool checked) { SetWidget(WIDGET_LIGHT_MANIPULATOR); } void OnPlaceBlockWidgetToolButtonClicked(bool checked); void OnPlaceBlockWidgetListWidgetItemClicked(QListWidgetItem *pItem); void OnSwapChainWidgetResized(); void OnSwapChainWidgetPaint(); void OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent); void OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent); void OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent); void OnSwapChainWidgetGainedFocusEvent(); void OnFrameExecutionTriggered(float timeSinceLastFrame); }; <file_sep>/Engine/Source/MathLib/HashTraits.h #pragma once #include "YBaseLib/HashTrait.h" struct Vector2f; struct Vector3f; struct Vector4f; DECLARE_HASHTRAIT_BYREF(Vector2f); DECLARE_HASHTRAIT_BYREF(Vector3f); DECLARE_HASHTRAIT_BYREF(Vector4f); struct Vector2i; struct Vector3i; struct Vector4i; DECLARE_HASHTRAIT_BYREF(Vector2i); DECLARE_HASHTRAIT_BYREF(Vector3i); DECLARE_HASHTRAIT_BYREF(Vector4i); struct Vector2u; struct Vector3u; struct Vector4u; DECLARE_HASHTRAIT_BYREF(Vector2u); DECLARE_HASHTRAIT_BYREF(Vector3u); DECLARE_HASHTRAIT_BYREF(Vector4u); <file_sep>/Engine/Source/Engine/ScriptObject.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ScriptObject.h" #include "Engine/ScriptManager.h" Log_SetChannel(ScriptObject); DEFINE_UNEXPOSED_SCRIPT_OBJECT_TYPEINFO(ScriptObject, 0); BEGIN_OBJECT_PROPERTY_MAP(ScriptObject) END_OBJECT_PROPERTY_MAP() ScriptObject::ScriptObject(const ScriptObjectTypeInfo *pTypeInfo /*= &s_typeInfo*/) : BaseClass(pTypeInfo), m_persistentScriptObjectReference(INVALID_SCRIPT_REFERENCE) { } ScriptObject::~ScriptObject() { if (m_persistentScriptObjectReference != INVALID_SCRIPT_REFERENCE) { g_pScriptManager->SetObjectReferencePointer(m_persistentScriptObjectReference, nullptr); g_pScriptManager->ReleaseReference(m_persistentScriptObjectReference); } } ScriptReferenceType ScriptObject::GetPersistentScriptObjectReference() const { if (m_persistentScriptObjectReference == INVALID_SCRIPT_REFERENCE) { const_cast<ScriptObject *>(this)->CreateScriptObject(); return m_persistentScriptObjectReference; } return m_persistentScriptObjectReference; } bool ScriptObject::CreateScriptObject() { DebugAssert(m_persistentScriptObjectReference == INVALID_SCRIPT_REFERENCE); // unexposed classes can't be created if (GetScriptObjectTypeInfo()->GetMetaTableReference() == INVALID_SCRIPT_REFERENCE) return false; // this one will always succeed, it's rather simple m_persistentScriptObjectReference = g_pScriptManager->AllocateAndReferenceObject(GetScriptObjectTypeInfo()->GetMetaTableReference(), ScriptUserDataTag_ScriptObject, this); return (m_persistentScriptObjectReference != INVALID_SCRIPT_REFERENCE); } bool ScriptObject::CreateScriptObject(const byte *pScript, uint32 scriptLength, const char *source /* = "text chunk" */) { // create the script object first if (!CreateScriptObject()) return false; // run the object script ScriptCallResult res = g_pScriptManager->RunObjectScript(m_persistentScriptObjectReference, pScript, scriptLength, source); if (res != ScriptCallResult_Success) { Log_ErrorPrintf("ScriptObject::CreateScriptObject: Running of environment script '%s' failed with %s.", source, NameTable_GetNameString(NameTables::ScriptCallResults, res)); return false; } // ran ok return true; } bool ScriptObject::CreateScriptObject(ScriptReferenceType environmentReference) { // create the script object first if (!CreateScriptObject()) return false; // todo: copy functions from environment reference to this object return false; } <file_sep>/Engine/Source/Core/PixelFormat.h #pragma once #include "Core/Common.h" #include "YBaseLib/NameTable.h" #include "MathLib/Vectorf.h" //#define MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a) ( ((uint32)(r) << 24) | ((uint32)(g) << 16) | ((uint32)(b) << 8) | ((uint32)(a)) ) #define MAKE_COLOR_R8G8B8A8_UNORM(r, g, b, a) ( ((uint32)(a) << 24) | ((uint32)(b) << 16) | ((uint32)(g) << 8) | ((uint32)(r)) ) #define MAKE_COLOR_R8G8B8A8_UNORM_INLINE_HEX(rgba) ( ((uint32)((rgba) & 0xff) << 24) | ((uint32)((rgba) >> 8) & 0xff << 16) | ((uint32)((rgba) >> 16) & 0xff << 8) | ((uint32)((rgba) >> 24) & 0xff) ) #define MAKE_COLOR_R8G8B8_UNORM(r, g, b) ((uint32)0xFF000000 | ((uint32)(b) << 16) | ((uint32)(g) << 8) | ((uint32)(r)) ) #define MAKE_COLOR_R8G8B8_UNORM_INLINE_HEX(rgb) ( (uint32)0xFF000000 | ((uint32)(rgba) & 0xff << 16) | ((uint32)((rgba) >> 8) & 0xff << 8) | ((uint32)((rgba) >> 16) & 0xff) ) enum PIXEL_CHANNEL { PIXEL_CHANNEL_RED, PIXEL_CHANNEL_GREEN, PIXEL_CHANNEL_BLUE, PIXEL_CHANNEL_ALPHA, }; enum PIXEL_FORMAT { //-------------------------------- Color Formats ------------------------------------ PIXEL_FORMAT_R8_UINT, PIXEL_FORMAT_R8_SINT, PIXEL_FORMAT_R8_UNORM, PIXEL_FORMAT_R8_SNORM, PIXEL_FORMAT_R8G8_UINT, PIXEL_FORMAT_R8G8_SINT, PIXEL_FORMAT_R8G8_UNORM, PIXEL_FORMAT_R8G8_SNORM, PIXEL_FORMAT_R8G8B8A8_UINT, PIXEL_FORMAT_R8G8B8A8_SINT, PIXEL_FORMAT_R8G8B8A8_UNORM, PIXEL_FORMAT_R8G8B8A8_UNORM_SRGB, PIXEL_FORMAT_R8G8B8A8_SNORM, PIXEL_FORMAT_R9G9B9E5_SHAREDEXP, PIXEL_FORMAT_R10G10B10A2_UINT, PIXEL_FORMAT_R10G10B10A2_UNORM, PIXEL_FORMAT_R11G11B10_FLOAT, PIXEL_FORMAT_R16_UINT, PIXEL_FORMAT_R16_SINT, PIXEL_FORMAT_R16_UNORM, PIXEL_FORMAT_R16_SNORM, PIXEL_FORMAT_R16_FLOAT, PIXEL_FORMAT_R16G16_UINT, PIXEL_FORMAT_R16G16_SINT, PIXEL_FORMAT_R16G16_UNORM, PIXEL_FORMAT_R16G16_SNORM, PIXEL_FORMAT_R16G16_FLOAT, PIXEL_FORMAT_R16G16B16A16_UINT, PIXEL_FORMAT_R16G16B16A16_SINT, PIXEL_FORMAT_R16G16B16A16_UNORM, PIXEL_FORMAT_R16G16B16A16_SNORM, PIXEL_FORMAT_R16G16B16A16_FLOAT, PIXEL_FORMAT_R32_UINT, PIXEL_FORMAT_R32_SINT, PIXEL_FORMAT_R32_FLOAT, PIXEL_FORMAT_R32G32_UINT, PIXEL_FORMAT_R32G32_SINT, PIXEL_FORMAT_R32G32_FLOAT, PIXEL_FORMAT_R32G32B32_UINT, PIXEL_FORMAT_R32G32B32_SINT, PIXEL_FORMAT_R32G32B32_FLOAT, PIXEL_FORMAT_R32G32B32A32_UINT, PIXEL_FORMAT_R32G32B32A32_SINT, PIXEL_FORMAT_R32G32B32A32_FLOAT, //----------------------- Color formats, swizzled for DX9 --------------------------- PIXEL_FORMAT_B8G8R8A8_UNORM, // known as ARGB32 PIXEL_FORMAT_B8G8R8A8_UNORM_SRGB, PIXEL_FORMAT_B8G8R8X8_UNORM, // known as XRGB32 PIXEL_FORMAT_B8G8R8X8_UNORM_SRGB, PIXEL_FORMAT_B5G6R5_UNORM, PIXEL_FORMAT_B5G5R5A1_UNORM, //-------------------------- Block Compression Formats ------------------------------ PIXEL_FORMAT_BC1_UNORM, // DXT1 in DX9 PIXEL_FORMAT_BC1_UNORM_SRGB, PIXEL_FORMAT_BC2_UNORM, // DXT3 in DX9 PIXEL_FORMAT_BC2_UNORM_SRGB, PIXEL_FORMAT_BC3_UNORM, // DXT5 in DX9 PIXEL_FORMAT_BC3_UNORM_SRGB, PIXEL_FORMAT_BC4_UNORM, PIXEL_FORMAT_BC4_SNORM, PIXEL_FORMAT_BC5_UNORM, PIXEL_FORMAT_BC5_SNORM, PIXEL_FORMAT_BC6H_UF16, PIXEL_FORMAT_BC6H_SF16, PIXEL_FORMAT_BC7_UNORM, PIXEL_FORMAT_BC7_UNORM_SRGB, //-------------------------------- Depth Format ------------------------------------- PIXEL_FORMAT_D16_UNORM, PIXEL_FORMAT_D24_UNORM_S8_UINT, PIXEL_FORMAT_D32_FLOAT, PIXEL_FORMAT_D32_FLOAT_S8X24_UINT, //----------------Other Formats, not necessarily available on GPU ------------------- PIXEL_FORMAT_R8G8B8_UNORM, PIXEL_FORMAT_B8G8R8_UNORM, //----------------------------------------------------------------------------------- PIXEL_FORMAT_COUNT, PIXEL_FORMAT_UNKNOWN = 999, }; // nametable namespace NameTables { Y_Declare_NameTable(PixelFormat); } struct PIXEL_FORMAT_INFO { const char *Name; // Name of pixel format uint32 BitsPerPixel; // Number of bits per pixel bool IsImageFormat; // If it can store colour/image data, true. false for other formats, e.g. depth/stencil. bool HasAlpha; // Has alpha channel. bool IsBlockCompressed; // True if the image uses block compression. uint32 BytesPerBlock; // If using block compression, the number of bytes per block. uint32 BlockSize; // If using block compression, the number of pixels in both dimensions for each block. PIXEL_FORMAT UncompressedFormat; // Internal format of compressed textures. PIXEL_FORMAT LinearFormat; // Whether the image format contains pixels in SRGB colour space. uint32 ColorMaskRed; uint32 ColorMaskGreen; uint32 ColorMaskBlue; uint32 ColorMaskAlpha; uint32 ColorBits; uint32 DepthBits; uint32 StencilBits; }; const char *PixelFormat_GetPixelFormatName(PIXEL_FORMAT Format); const PIXEL_FORMAT_INFO *PixelFormat_GetPixelFormatInfo(PIXEL_FORMAT Format); uint32 PixelFormat_CalculateRowPitch(PIXEL_FORMAT Format, uint32 uWidth); uint32 PixelFormat_CalculateSlicePitch(PIXEL_FORMAT Format, uint32 uWidth, uint32 uHeight); uint32 PixelFormat_CalculateImageNumRows(PIXEL_FORMAT Format, uint32 Width, uint32 Height); uint32 PixelFormat_CalculateImageSize(PIXEL_FORMAT Format, uint32 uWidth, uint32 uHeight, uint32 uDepth); bool PixelFormat_ConvertPixels(uint32 Width, uint32 Height, const void *SourcePixels, uint32 SourcePitch, PIXEL_FORMAT SourceFormat, void *DestinationPixels, uint32 DestinationPitch, PIXEL_FORMAT DestinationFormat, uint32 *DestinationPixelSize); void PixelFormat_FlipImageInPlace(void *pPixels, uint32 rowPitch, uint32 rowCount); void PixelFormat_FlipImage(void *pDestinationPixels, const void *pPixels, uint32 rowPitch, uint32 rowCount); namespace PixelFormatHelpers { bool IsSRGBFormat(PIXEL_FORMAT format); PIXEL_FORMAT GetSRGBFormat(PIXEL_FORMAT format); PIXEL_FORMAT GetLinearFormat(PIXEL_FORMAT format); bool IsDepthFormat(PIXEL_FORMAT format); Vector4f ConvertRGBAToFloat4(uint32 rgba); uint32 ConvertFloat4ToRGBA(const Vector4f &rgba); Vector3f DecodeNormalFromR8G8B8(uint32 rgb); uint32 EncodeNormalAsRG8B8B8(const Vector3f &normal); Vector3f ConvertLinearToSRGB(const Vector3f &color); Vector4f ConvertLinearToSRGB(const Vector4f &color); uint32 ConvertLinearToSRGB(const uint32 rgba); Vector3f ConvertSRGBToLinear(const Vector3f &color); Vector4f ConvertSRGBToLinear(const Vector4f &color); uint32 ConvertSRGBToLinear(const uint32 rgba); }; <file_sep>/Engine/Source/Engine/ParticleSystemModule.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/ParticleSystemModule.h" #include "Engine/ParticleSystemEmitter.h" DEFINE_OBJECT_TYPE_INFO(ParticleSystemModule); ParticleSystemModule::ParticleSystemModule(const ObjectTypeInfo *pTypeInfo /* = &s_typeInfo */) : BaseClass(pTypeInfo) { } ParticleSystemModule::~ParticleSystemModule() { } bool ParticleSystemModule::CreateParticle(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticle) const { return true; } void ParticleSystemModule::UpdateParticles(const ParticleSystemEmitter *pEmitter, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, ParticleData *pParticles, uint32 nParticles, float deltaTime) const { } <file_sep>/Engine/Source/BaseGame/LoadingScreenProgressCallbacks.cpp #include "BaseGame/PrecompiledHeader.h" #include "BaseGame/LoadingScreenProgressCallbacks.h" #include "Renderer/Renderer.h" #include "Renderer/MiniGUIContext.h" Log_SetChannel(LoadingScreenProgressCallbacks); LoadingScreenProgressCallbacks::LoadingScreenProgressCallbacks(uint32 offsetX /* = 0 */, uint32 offsetY /* = 0 */, uint32 fontHeight /* = 16 */, uint32 barWidth /* = 300 */, uint32 barHeight /* = 20 */) : m_offsetX(offsetX) , m_offsetY(offsetY) , m_fontHeight(fontHeight) , m_barWidth(barWidth) , m_barHeight(barHeight) { } LoadingScreenProgressCallbacks::~LoadingScreenProgressCallbacks() { } void LoadingScreenProgressCallbacks::PushState() { BaseProgressCallbacks::PushState(); } void LoadingScreenProgressCallbacks::PopState() { BaseProgressCallbacks::PopState(); Redraw(); } void LoadingScreenProgressCallbacks::SetCancellable(bool cancellable) { BaseProgressCallbacks::SetCancellable(cancellable); Redraw(); } void LoadingScreenProgressCallbacks::SetStatusText(const char *statusText) { BaseProgressCallbacks::SetStatusText(statusText); Redraw(); } void LoadingScreenProgressCallbacks::SetProgressRange(uint32 range) { uint32 lastRange = m_progressRange; BaseProgressCallbacks::SetProgressRange(range); if (m_progressRange != lastRange) Redraw(); } void LoadingScreenProgressCallbacks::SetProgressValue(uint32 value) { uint32 lastValue = m_progressValue; BaseProgressCallbacks::SetProgressValue(value); if (m_progressValue != lastValue && m_timeSinceLastDraw.GetTimeSeconds() >= 0.01f) { m_timeSinceLastDraw.Reset(); Redraw(); } } void LoadingScreenProgressCallbacks::DisplayError(const char *message) { Log_ErrorPrint(message); } void LoadingScreenProgressCallbacks::DisplayWarning(const char *message) { Log_WarningPrint(message); } void LoadingScreenProgressCallbacks::DisplayInformation(const char *message) { Log_InfoPrint(message); } void LoadingScreenProgressCallbacks::DisplayDebugMessage(const char *message) { Log_DevPrint(message); } void LoadingScreenProgressCallbacks::ModalError(const char *message) { Log_ErrorPrint(message); } bool LoadingScreenProgressCallbacks::ModalConfirmation(const char *message) { Log_InfoPrint(message); return false; } uint32 LoadingScreenProgressCallbacks::ModalPrompt(const char *message, uint32 nOptions, ...) { DebugAssert(nOptions > 0); Log_InfoPrint(message); return 0; } void LoadingScreenProgressCallbacks::Redraw() { // singlethreaded rendering? if (Renderer::IsOnRenderThread()) { RedrawRenderThread(); return; } // multithreaded rendering QUEUE_BLOCKING_RENDERER_LAMBA_COMMAND([this]() { RedrawRenderThread(); }); } void LoadingScreenProgressCallbacks::RedrawRenderThread() { GPUContext *pGPUContext = g_pRenderer->GetGPUContext(); MiniGUIContext *pGUIContext = g_pRenderer->GetGUIContext(); // assuming correct targets are already set MINIGUI_RECT rect; SmallString text; // calc percent float percentComplete = (m_progressRange > 0) ? ((float)m_progressValue / (float)m_progressRange) * 100.0f : 0.0f; if (percentComplete > 100.0f) percentComplete = 100.0f; // clear screen pGPUContext->SetRenderTargets(0, nullptr, nullptr); pGPUContext->SetFullViewport(); pGPUContext->ClearTargets(true, true, true, float4(0.0f, 0.0f, 0.2f, 1.0f)); pGUIContext->SetViewportDimensions(pGPUContext->GetViewport()); // start batching pGUIContext->PushManualFlush(); // draw the status text pGUIContext->DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), m_fontHeight, m_offsetX, m_offsetY, m_statusText); // draw percent next to it for now text.Format("%.2f%% complete", percentComplete); pGUIContext->DrawText(g_pRenderer->GetFixedResources()->GetDebugFont(), m_fontHeight, m_offsetX + m_barWidth + 2 + 20, m_offsetY + (m_fontHeight / 2) + 4 + 1 + (m_barHeight / 2), text); // draw the progress bar outline SET_MINIGUI_RECT(&rect, m_offsetX, m_offsetX + m_barWidth + 2, m_offsetY + m_fontHeight + 4, m_offsetY + m_fontHeight + 4 + m_barHeight + 2); pGUIContext->DrawRect(&rect, MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); // bar background rect.left++; rect.right--; rect.top++; rect.bottom--; pGUIContext->DrawFilledRect(&rect, MAKE_COLOR_R8G8B8A8_UNORM(112, 146, 190, 255)); // draw the bar itself if (percentComplete > 0.0f) { SET_MINIGUI_RECT(&rect, m_offsetX + 1, m_offsetX + (uint32)Math::Truncate(percentComplete * 0.01f * (float)m_barWidth), m_offsetY + m_fontHeight + 4 + 1, m_offsetY + m_fontHeight + 4 + m_barHeight + 1); pGUIContext->DrawFilledRect(&rect, MAKE_COLOR_R8G8B8A8_UNORM(255, 201, 14, 255)); } // flush ops pGUIContext->PopManualFlush(); pGUIContext->Flush(); // swap buffers pGPUContext->PresentOutputBuffer(GPU_PRESENT_BEHAVIOUR_IMMEDIATE); } <file_sep>/Engine/Dependancies/imgui/examples/sdl_opengl_example/imgui_impl_sdl.h // ImGui SDL2 binding with OpenGL // https://github.com/ocornut/imgui struct SDL_Window; typedef union SDL_Event SDL_Event; bool ImGui_ImplSdl_Init(SDL_Window *window); void ImGui_ImplSdl_Shutdown(); void ImGui_ImplSdl_NewFrame(SDL_Window *window); bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event); // Use if you want to reset your rendering device without losing ImGui state. void ImGui_ImplSdl_InvalidateDeviceObjects(); bool ImGui_ImplSdl_CreateDeviceObjects(); <file_sep>/Engine/Source/Core/ChunkDataFormat.h #pragma once #include "Core/Common.h" // Common chunk header usable for all types, and ChunkLoader class. // A ChunkSize of zero will assume that the chunk is not present. #define DF_CHUNKFILE_HEADER_MAGIC 0x4B484359 struct DF_CHUNKFILE_HEADER { uint32 Magic; uint32 HeaderSize; uint32 ChunkCount; uint64 TotalSize; uint64 StringsOffset; uint32 StringsSize; uint32 StringsCount; }; struct DF_CHUNKFILE_CHUNK_HEADER { uint64 ChunkOffset; uint32 ChunkSize; }; <file_sep>/Editor/Source/Editor/MapEditor/ui_EditorCreateTerrainDialog.h /******************************************************************************** ** Form generated from reading UI file 'EditorCreateTerrainDialog.ui' ** ** Created by: Qt User Interface Compiler version 5.4.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_EDITORCREATETERRAINDIALOG_H #define UI_EDITORCREATETERRAINDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QFormLayout> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QSpinBox> #include "Editor/EditorResourceSelectionWidget.h" QT_BEGIN_NAMESPACE class Ui_EditorCreateTerrainDialog { public: QGridLayout *gridLayout; QFormLayout *formLayout; QLabel *label; QLabel *label_2; EditorResourceSelectionWidget *layerListSelection; QLabel *label_3; QSpinBox *sectionSize; QLabel *label_6; QSpinBox *unitsPerPoint; QLabel *label_9; QSpinBox *patchSize; QLabel *label_5; QComboBox *heightFormat; QLabel *label_7; QSpinBox *minimumHeight; QLabel *label_4; QSpinBox *maximumHeight; QLabel *label_8; QSpinBox *baseHeight; QSpinBox *textureRepeatInterval; QCheckBox *createCenterSectionCheckBox; QLabel *label_10; QHBoxLayout *horizontalLayout_2; QSpacerItem *horizontalSpacer; QPushButton *createButton; QPushButton *cancelButton; void setupUi(QDialog *EditorCreateTerrainDialog) { if (EditorCreateTerrainDialog->objectName().isEmpty()) EditorCreateTerrainDialog->setObjectName(QStringLiteral("EditorCreateTerrainDialog")); EditorCreateTerrainDialog->resize(433, 347); gridLayout = new QGridLayout(EditorCreateTerrainDialog); gridLayout->setObjectName(QStringLiteral("gridLayout")); formLayout = new QFormLayout(); formLayout->setObjectName(QStringLiteral("formLayout")); formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); label = new QLabel(EditorCreateTerrainDialog); label->setObjectName(QStringLiteral("label")); formLayout->setWidget(0, QFormLayout::SpanningRole, label); label_2 = new QLabel(EditorCreateTerrainDialog); label_2->setObjectName(QStringLiteral("label_2")); formLayout->setWidget(1, QFormLayout::LabelRole, label_2); layerListSelection = new EditorResourceSelectionWidget(EditorCreateTerrainDialog); layerListSelection->setObjectName(QStringLiteral("layerListSelection")); formLayout->setWidget(1, QFormLayout::FieldRole, layerListSelection); label_3 = new QLabel(EditorCreateTerrainDialog); label_3->setObjectName(QStringLiteral("label_3")); formLayout->setWidget(2, QFormLayout::LabelRole, label_3); sectionSize = new QSpinBox(EditorCreateTerrainDialog); sectionSize->setObjectName(QStringLiteral("sectionSize")); formLayout->setWidget(2, QFormLayout::FieldRole, sectionSize); label_6 = new QLabel(EditorCreateTerrainDialog); label_6->setObjectName(QStringLiteral("label_6")); formLayout->setWidget(3, QFormLayout::LabelRole, label_6); unitsPerPoint = new QSpinBox(EditorCreateTerrainDialog); unitsPerPoint->setObjectName(QStringLiteral("unitsPerPoint")); formLayout->setWidget(3, QFormLayout::FieldRole, unitsPerPoint); label_9 = new QLabel(EditorCreateTerrainDialog); label_9->setObjectName(QStringLiteral("label_9")); formLayout->setWidget(4, QFormLayout::LabelRole, label_9); patchSize = new QSpinBox(EditorCreateTerrainDialog); patchSize->setObjectName(QStringLiteral("patchSize")); formLayout->setWidget(4, QFormLayout::FieldRole, patchSize); label_5 = new QLabel(EditorCreateTerrainDialog); label_5->setObjectName(QStringLiteral("label_5")); formLayout->setWidget(5, QFormLayout::LabelRole, label_5); heightFormat = new QComboBox(EditorCreateTerrainDialog); heightFormat->setObjectName(QStringLiteral("heightFormat")); formLayout->setWidget(5, QFormLayout::FieldRole, heightFormat); label_7 = new QLabel(EditorCreateTerrainDialog); label_7->setObjectName(QStringLiteral("label_7")); formLayout->setWidget(6, QFormLayout::LabelRole, label_7); minimumHeight = new QSpinBox(EditorCreateTerrainDialog); minimumHeight->setObjectName(QStringLiteral("minimumHeight")); formLayout->setWidget(6, QFormLayout::FieldRole, minimumHeight); label_4 = new QLabel(EditorCreateTerrainDialog); label_4->setObjectName(QStringLiteral("label_4")); formLayout->setWidget(7, QFormLayout::LabelRole, label_4); maximumHeight = new QSpinBox(EditorCreateTerrainDialog); maximumHeight->setObjectName(QStringLiteral("maximumHeight")); formLayout->setWidget(7, QFormLayout::FieldRole, maximumHeight); label_8 = new QLabel(EditorCreateTerrainDialog); label_8->setObjectName(QStringLiteral("label_8")); formLayout->setWidget(8, QFormLayout::LabelRole, label_8); baseHeight = new QSpinBox(EditorCreateTerrainDialog); baseHeight->setObjectName(QStringLiteral("baseHeight")); formLayout->setWidget(8, QFormLayout::FieldRole, baseHeight); textureRepeatInterval = new QSpinBox(EditorCreateTerrainDialog); textureRepeatInterval->setObjectName(QStringLiteral("textureRepeatInterval")); formLayout->setWidget(9, QFormLayout::FieldRole, textureRepeatInterval); createCenterSectionCheckBox = new QCheckBox(EditorCreateTerrainDialog); createCenterSectionCheckBox->setObjectName(QStringLiteral("createCenterSectionCheckBox")); formLayout->setWidget(10, QFormLayout::FieldRole, createCenterSectionCheckBox); label_10 = new QLabel(EditorCreateTerrainDialog); label_10->setObjectName(QStringLiteral("label_10")); formLayout->setWidget(9, QFormLayout::LabelRole, label_10); gridLayout->addLayout(formLayout, 0, 0, 1, 1); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); createButton = new QPushButton(EditorCreateTerrainDialog); createButton->setObjectName(QStringLiteral("createButton")); createButton->setDefault(true); horizontalLayout_2->addWidget(createButton); cancelButton = new QPushButton(EditorCreateTerrainDialog); cancelButton->setObjectName(QStringLiteral("cancelButton")); horizontalLayout_2->addWidget(cancelButton); gridLayout->addLayout(horizontalLayout_2, 1, 0, 1, 1); QWidget::setTabOrder(layerListSelection, sectionSize); QWidget::setTabOrder(sectionSize, unitsPerPoint); QWidget::setTabOrder(unitsPerPoint, patchSize); QWidget::setTabOrder(patchSize, heightFormat); QWidget::setTabOrder(heightFormat, minimumHeight); QWidget::setTabOrder(minimumHeight, maximumHeight); QWidget::setTabOrder(maximumHeight, baseHeight); QWidget::setTabOrder(baseHeight, textureRepeatInterval); QWidget::setTabOrder(textureRepeatInterval, createCenterSectionCheckBox); QWidget::setTabOrder(createCenterSectionCheckBox, createButton); QWidget::setTabOrder(createButton, cancelButton); retranslateUi(EditorCreateTerrainDialog); QMetaObject::connectSlotsByName(EditorCreateTerrainDialog); } // setupUi void retranslateUi(QDialog *EditorCreateTerrainDialog) { EditorCreateTerrainDialog->setWindowTitle(QApplication::translate("EditorCreateTerrainDialog", "Create Heightfield Terrain", 0)); label->setText(QApplication::translate("EditorCreateTerrainDialog", "To create heightfield terrain for this map, provide the following details:", 0)); label_2->setText(QApplication::translate("EditorCreateTerrainDialog", "Layer List: ", 0)); label_3->setText(QApplication::translate("EditorCreateTerrainDialog", "Section Size: \n" "(the size of each terrain texture)", 0)); label_6->setText(QApplication::translate("EditorCreateTerrainDialog", "Resolution:\n" "(world units per terrain point)", 0)); label_9->setText(QApplication::translate("EditorCreateTerrainDialog", "Patch Size: \n" "(minimum node size)", 0)); label_5->setText(QApplication::translate("EditorCreateTerrainDialog", "Height Format: ", 0)); label_7->setText(QApplication::translate("EditorCreateTerrainDialog", "Minimum Height: ", 0)); label_4->setText(QApplication::translate("EditorCreateTerrainDialog", "Maximum Height: ", 0)); label_8->setText(QApplication::translate("EditorCreateTerrainDialog", "Base Height:", 0)); createCenterSectionCheckBox->setText(QApplication::translate("EditorCreateTerrainDialog", "Create Center Section", 0)); label_10->setText(QApplication::translate("EditorCreateTerrainDialog", "Texture Repeat Interval:", 0)); createButton->setText(QApplication::translate("EditorCreateTerrainDialog", "Create", 0)); cancelButton->setText(QApplication::translate("EditorCreateTerrainDialog", "Cancel", 0)); } // retranslateUi }; namespace Ui { class EditorCreateTerrainDialog: public Ui_EditorCreateTerrainDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_EDITORCREATETERRAINDIALOG_H <file_sep>/Engine/Source/MathLib/SIMDVectori_scalar.h #pragma once #include "MathLib/Vectori.h" // interoperability between int/vector types struct Vector2i; struct Vector3i; struct Vector4i; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector2i : public Vector2i { // constructors inline SIMDVector2i() {} inline SIMDVector2i(int32 x_, int32 y_) : Vector2i(x_, y_) {} inline SIMDVector2i(const int32 *p) : Vector2i(p) {} inline SIMDVector2i(const SIMDVector2i &v) : Vector2i(v) {} inline SIMDVector2i(const Vector2i &v) : Vector2i(v) {} //---------------------------------------------------------------------- static const SIMDVector2i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector3i : public Vector3i { // constructors inline SIMDVector3i() {} inline SIMDVector3i(int32 x_, int32 y_, int32 z_) : Vector3i(x_, y_, z_) {} inline SIMDVector3i(const int32 *p) : Vector3i(p) {} inline SIMDVector3i(const SIMDVector2i &v, int32 z_ = 0) : Vector3i(v, z_) {} inline SIMDVector3i(const SIMDVector3i &v) : Vector3i(v) {} inline SIMDVector3i(const Vector3i &v) : Vector3i(v) {} //---------------------------------------------------------------------- static const SIMDVector3i &Zero, &One, &NegativeOne; }; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- struct SIMDVector4i : public Vector4i { // constructors inline SIMDVector4i() {} inline SIMDVector4i(int32 x_, int32 y_, int32 z_, int32 w_) : Vector4i(x_, y_, z_, w_) {} inline SIMDVector4i(const int32 *p) : Vector4i(p) {} inline SIMDVector4i(const SIMDVector2i &v, int32 z_ = 0, int32 w_ = 0) : Vector4i(v, z_) {} inline SIMDVector4i(const SIMDVector3i &v, int32 w_ = 0) : Vector4i(v, w_) {} inline SIMDVector4i(const SIMDVector4i &v) : Vector4i(v) {} inline SIMDVector4i(const Vector4i &v) : Vector4i(v) {} //---------------------------------------------------------------------- static const SIMDVector4i &Zero, &One, &NegativeOne; }; <file_sep>/Engine/Source/ResourceCompiler/BlockPaletteGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/BlockPaletteGenerator.h" #include "ResourceCompiler/TextureGenerator.h" #include "ResourceCompiler/ResourceCompiler.h" #include "Engine/Engine.h" #include "Engine/DataFormats.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" #include "YBaseLib/ZipArchive.h" #include "Core/ChunkFileWriter.h" #include "Core/ImageCodec.h" Log_SetChannel(BlockPaletteGenerator); static const PIXEL_FORMAT BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT = PIXEL_FORMAT_R8G8B8A8_UNORM; static const IMAGE_RESIZE_FILTER BLOCK_MESH_BLOCK_LIST_TEXTURE_RESIZE_FILTER = IMAGE_RESIZE_FILTER_LANCZOS3; static const uint32 BLOCK_MESH_BLOCK_LIST_TEXTURE_COMPRESSION_LEVEL = 6; namespace NameTables { Y_Define_NameTable(BlockMeshTextureBlending) Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_BLENDING_NONE, "none") Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_BLENDING_MASKED, "masked") Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT, "translucent") Y_NameTable_End() Y_Define_NameTable(BlockMeshTextureEffect) Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_EFFECT_NONE, "none") Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_EFFECT_SCROLL, "scroll") Y_NameTable_VEntry(BLOCK_MESH_TEXTURE_EFFECT_ANIMATION, "animation") Y_NameTable_End() } static void ResetBlockType(BlockPaletteGenerator::BlockType *pBlockType) { pBlockType->Name.Obliterate(); pBlockType->Flags = 0; pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE; for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) { BlockPaletteGenerator::BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[i]; pFaceDef->Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pFaceDef->Visual.Color = 0xFFFFFFFF; pFaceDef->Visual.TextureIndex = 0xFFFFFFFF; pFaceDef->Visual.MaterialName.Obliterate(); } pBlockType->SlabShapeSettings.Height = 1.0f; pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pBlockType->PlaneShapeSettings.Visual.Color = 0xFFFFFFFF; pBlockType->PlaneShapeSettings.Visual.TextureIndex = 0xFFFFFFFF; pBlockType->PlaneShapeSettings.Visual.MaterialName.Obliterate(); pBlockType->PlaneShapeSettings.OffsetX = 0.0f; pBlockType->PlaneShapeSettings.OffsetY = 0.0f; pBlockType->PlaneShapeSettings.BaseRotation = 0; pBlockType->PlaneShapeSettings.RepeatCount = 0; pBlockType->PlaneShapeSettings.RepeatRotation = 0; pBlockType->MeshShapeSettings.Scale = 1.0f; pBlockType->BlockLightEmitterSettings.Enabled = false; pBlockType->BlockLightEmitterSettings.Radius = 0; pBlockType->PointLightEmitterSettings.Enabled = false; pBlockType->PointLightEmitterSettings.Offset.SetZero(); pBlockType->PointLightEmitterSettings.Color = 0; pBlockType->PointLightEmitterSettings.Brightness = 0.0f; pBlockType->PointLightEmitterSettings.Range = 0.0f; pBlockType->PointLightEmitterSettings.Falloff = 0.0f; } BlockPaletteGenerator::BlockPaletteGenerator() : m_diffuseMapSize(0), m_specularMapSize(0), m_normalMapSize(0) { // reset blocks for (uint32 i = 0; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { m_blockTypes[i].BlockTypeIndex = i; ResetBlockType(&m_blockTypes[i]); m_allocatedBlockTypes[i] = false; } } BlockPaletteGenerator::~BlockPaletteGenerator() { uint32 i; for (i = 0; i < m_textures.GetSize(); i++) { Texture *pTexture = m_textures[i]; delete pTexture->pDiffuseMap; delete pTexture->pSpecularMap; delete pTexture->pNormalMap; } } void BlockPaletteGenerator::Create(uint32 diffuseMapSize, uint32 specularMapSize, uint32 normalMapSize) { // setup default/none block m_allocatedBlockTypes[0] = true; m_diffuseMapSize = diffuseMapSize; m_specularMapSize = specularMapSize; m_normalMapSize = normalMapSize; } bool BlockPaletteGenerator::Load(const char *FileName, ByteStream *pStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { pProgressCallbacks->SetStatusText("Opening archive..."); pProgressCallbacks->SetProgressRange(3); pProgressCallbacks->SetProgressValue(0); // open zip archive ZipArchive *pArchive = ZipArchive::OpenArchiveReadOnly(pStream); if (pArchive == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::Load: Could not load '%s': Could not open as archive.", FileName); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(1); pProgressCallbacks->SetStatusText("Loading textures..."); pProgressCallbacks->PushState(); // load textures from archive if (!LoadTextures(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("BlockPaletteGenerator::Load: Could not load '%s': Could not load textures.", FileName); pProgressCallbacks->PopState(); delete pArchive; return false; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(2); pProgressCallbacks->SetStatusText("Loading block types..."); // load xml if (!LoadXML(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("BlockPaletteGenerator::Load: Could not load '%s': Could not load XML.", FileName); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(3); delete pArchive; return true; } bool BlockPaletteGenerator::LoadTextures(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) { SmallString textureName; PathString textureFileName; FileSystem::FindResultsArray findResults; pArchive->FindFiles("textures", "*.xml", FILESYSTEM_FIND_RELATIVE_PATHS, &findResults); pProgressCallbacks->SetProgressRange(findResults.GetSize()); pProgressCallbacks->SetProgressValue(0); for (uint32 i = 0; i < findResults.GetSize(); i++) { const FILESYSTEM_FIND_DATA &findData = findResults[i]; pProgressCallbacks->SetFormattedStatusText("Loading texture from '%s'", findData.FileName); // parse texture name from the filename textureName.Assign(findData.FileName); DebugAssert(textureName.EndsWith(".xml", false)); textureName.Erase(-4); // texture object Texture *pTexture = new Texture(); pTexture->Index = m_textures.GetSize(); pTexture->Name = textureName; pTexture->Blending = BLOCK_MESH_TEXTURE_BLENDING_NONE; pTexture->Effect = BLOCK_MESH_TEXTURE_EFFECT_NONE; pTexture->AllowTextureFiltering = true; Y_memzero(pTexture->ScrollDirection, sizeof(pTexture->ScrollDirection)); pTexture->ScrollSpeed = 0.0f; pTexture->AnimationFrameCount = 0; pTexture->AnimationSpeed = 0.0f; pTexture->pDiffuseMap = nullptr; pTexture->pNormalMap = nullptr; pTexture->pSpecularMap = nullptr; m_textures.Add(pTexture); // parse the xml file { // open it textureFileName.Format("textures/%s.xml", textureName.GetCharArray()); AutoReleasePtr<ByteStream> pXMLStream = pArchive->OpenFile(textureFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pXMLStream == nullptr) { Log_ErrorPrintf("BlockPaletteGenerator::LoadTextures: Could not open file '%s'.", textureFileName.GetCharArray()); return false; } // parse it XMLReader xmlReader; if (!xmlReader.Create(pXMLStream, findData.FileName) || !xmlReader.SkipToElement("block-palette-texture")) { Log_ErrorPrintf("BlockPaletteGenerator::LoadTextures: Could not parse file '%s'.", textureFileName.GetCharArray()); return false; } // read elements if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 textureSelection = xmlReader.Select("blending|effect|filtering"); if (textureSelection < 0) return false; switch (textureSelection) { // blending case 0: { const char *blendingTypeStr = xmlReader.FetchAttribute("type"); if (blendingTypeStr == nullptr || !NameTable_TranslateType(NameTables::BlockMeshTextureBlending, blendingTypeStr, &pTexture->Blending, true)) { xmlReader.PrintError("missing type attribute"); return false; } } break; // effect case 1: { const char *effectTypeStr = xmlReader.FetchAttribute("type"); if (effectTypeStr == nullptr || !NameTable_TranslateType(NameTables::BlockMeshTextureEffect, effectTypeStr, &pTexture->Effect, true)) { xmlReader.PrintError("missing type attribute"); return false; } if (pTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_SCROLL) { const char *scrollDirectionStr = xmlReader.FetchAttribute("scroll-direction"); const char *scrollSpeedStr = xmlReader.FetchAttribute("scroll-speed"); if (scrollDirectionStr == nullptr || scrollSpeedStr == nullptr) { xmlReader.PrintError("missing scroll attributes"); return false; } StringConverter::StringToFloat2(scrollSpeedStr).Store(pTexture->ScrollDirection); pTexture->ScrollSpeed = StringConverter::StringToFloat(scrollSpeedStr); } else if (pTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_ANIMATION) { const char *animationFrameCountStr = xmlReader.FetchAttribute("animation-frames"); const char *animationSpeedStr = xmlReader.FetchAttribute("animation-speed"); if (animationFrameCountStr == nullptr || animationSpeedStr == nullptr) { xmlReader.PrintError("missing animation attributes"); return false; } pTexture->AnimationFrameCount = StringConverter::StringToUInt32(animationFrameCountStr); pTexture->AnimationSpeed = StringConverter::StringToFloat(animationSpeedStr); } if (!xmlReader.IsEmptyElement() && !xmlReader.SkipCurrentElement()) return false; } break; // filtering case 2: { const char *enabledStr = xmlReader.FetchAttributeDefault("enabled", "false"); pTexture->AllowTextureFiltering = StringConverter::StringToBool(enabledStr); } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "block-palette-texture") == 0); break; } else { UnreachableCode(); } } } } // get images ByteStream *pImageStream; // diffuse textureFileName.Format("textures/%s_diffuse.png", pTexture->Name.GetCharArray()); if ((pImageStream = pArchive->OpenFile(textureFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE)) != nullptr) { if ((pTexture->pDiffuseMap = LoadTextureImage(pImageStream, textureFileName)) == nullptr) { pImageStream->Release(); return false; } pImageStream->Release(); } // specular textureFileName.Format("textures/%s_specular.png", pTexture->Name.GetCharArray()); if ((pImageStream = pArchive->OpenFile(textureFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE)) != nullptr) { if ((pTexture->pSpecularMap = LoadTextureImage(pImageStream, textureFileName)) == nullptr) { pImageStream->Release(); return false; } pImageStream->Release(); } // normal textureFileName.Format("textures/%s_normal.png", pTexture->Name.GetCharArray()); if ((pImageStream = pArchive->OpenFile(textureFileName, BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE)) != nullptr) { if ((pTexture->pNormalMap = LoadTextureImage(pImageStream, textureFileName)) == nullptr) { pImageStream->Release(); return false; } pImageStream->Release(); } // did we get any images? if (pTexture->pDiffuseMap == nullptr && pTexture->pSpecularMap == nullptr && pTexture->pNormalMap == nullptr) { Log_ErrorPrintf("BlockPaletteGenerator::LoadTextures: No texture images loaded for texture '%s'", textureName.GetCharArray()); return false; } pProgressCallbacks->IncrementProgressValue(); } return true; } Image *BlockPaletteGenerator::LoadTextureImage(ByteStream *pStream, const char *filename) { Image *pDecodedImage = new Image(); ImageCodec *pImageCodec = ImageCodec::GetImageCodecForStream(filename, pStream); if (pImageCodec == NULL || !pImageCodec->DecodeImage(pDecodedImage, filename, pStream)) { Log_ErrorPrintf("BlockPaletteGenerator::LoadTextureImage: Could not decode texture file name '%s'.", filename); delete pDecodedImage; return nullptr; } // check image format if (pDecodedImage->GetPixelFormat() != BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT && !pDecodedImage->ConvertPixelFormat(BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT)) { Log_ErrorPrintf("BlockMeshBlockListGenerator::LoadTextures: Could not convert texture file name '%s' to internal format.", filename); delete pDecodedImage; return nullptr; } return pDecodedImage; } bool BlockPaletteGenerator::LoadXML(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) { AutoReleasePtr<ByteStream> pBlockTypesStream = pArchive->OpenFile("palette.xml", BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_SEEKABLE); if (pBlockTypesStream == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::LoadBlockTypes: Could not open palette.xml."); return false; } // create xml reader XMLReader xmlReader; if (!xmlReader.Create(pBlockTypesStream, "palette.xml")) { xmlReader.PrintError("failed to create XML reader"); return false; } // skip to correct node if (!xmlReader.SkipToElement("palette")) { xmlReader.PrintError("failed to skip to palette element"); return false; } // read attributes { const char *diffuseMapSizeStr = xmlReader.FetchAttribute("diffuse-map-size"); const char *specularMapSizeStr = xmlReader.FetchAttribute("specular-map-size"); const char *normalMapSizeStr = xmlReader.FetchAttribute("normal-map-size"); if (diffuseMapSizeStr == NULL || specularMapSizeStr == NULL || normalMapSizeStr == NULL) { xmlReader.PrintError("missing texture size attributes"); return false; } m_diffuseMapSize = StringConverter::StringToUInt32(diffuseMapSizeStr); m_specularMapSize = StringConverter::StringToUInt32(specularMapSizeStr); m_normalMapSize = StringConverter::StringToUInt32(normalMapSizeStr); if (m_diffuseMapSize == 0 || m_specularMapSize == 0 || m_normalMapSize == 0) { xmlReader.PrintError("invalid texture size attributes"); return false; } } if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 blockTypesSelection = xmlReader.Select("blocktype"); if (blockTypesSelection < 0) return false; switch (blockTypesSelection) { // blocktype case 0: { // read in all fields const char *blockTypeIndex = xmlReader.FetchAttribute("index"); const char *blockTypeName = xmlReader.FetchAttribute("name"); if (blockTypeIndex == NULL || blockTypeName == NULL || xmlReader.IsEmptyElement()) { xmlReader.PrintError("incomplete block type declaration"); return false; } // check name isn't used if (GetBlockTypeByName(blockTypeName) != nullptr) { xmlReader.PrintError("block name '%s' already used.", blockTypeName); return false; } // convert index to int uint32 intBlockTypeIndex = StringConverter::StringToUInt32(blockTypeIndex); if (intBlockTypeIndex == 0 || intBlockTypeIndex >= BLOCK_MESH_MAX_BLOCK_TYPES) { xmlReader.PrintError("block type index out of range."); return false; } // check for allocation if (m_allocatedBlockTypes[intBlockTypeIndex]) { xmlReader.PrintError("double declaration of blocktype %u, ignoring duplicate declaration", intBlockTypeIndex); continue; } // get blocktype ptr BlockType *pBlockType = &m_blockTypes[intBlockTypeIndex]; m_allocatedBlockTypes[intBlockTypeIndex] = true; // set up blocktype ptr pBlockType->Name = blockTypeName; pBlockType->Flags = 0; // read rest of element if (!xmlReader.IsEmptyElement()) { // read remaining info for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 blockTypeSelection = xmlReader.Select("flags|shape|block-light-emitter|point-light-emitter"); if (blockTypeSelection < 0) return false; switch (blockTypeSelection) { // flags case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 flagsSelection = xmlReader.Select("solid|cast-shadows"); if (flagsSelection < 0) return false; switch (flagsSelection) { // solid case 0: pBlockType->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_SOLID; break; // cast-shadows case 1: pBlockType->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS; break; } if (!xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "flags") == 0); break; } } } } // end case flags break; // shape case 1: { const char *shapeType = xmlReader.FetchAttribute("type"); if (shapeType == NULL) { xmlReader.PrintError("invalid shape type"); return false; } if (Y_stricmp(shapeType, "none") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_NONE; } else if (Y_stricmp(shapeType, "cube") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE; } else if (Y_stricmp(shapeType, "slab") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB; const char *slabHeightStr = xmlReader.FetchAttribute("height"); if (slabHeightStr == nullptr) { xmlReader.PrintError("missing attributes"); return false; } pBlockType->SlabShapeSettings.Height = StringConverter::StringToFloat(slabHeightStr); } else if (Y_stricmp(shapeType, "stairs") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS; } else if (Y_stricmp(shapeType, "plane") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE; } else if (Y_stricmp(shapeType, "mesh") == 0) { pBlockType->ShapeType = BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH; } else { xmlReader.PrintError("invalid shape type '%s'", shapeType); return false; } // none visuals can skip the faces element if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB || pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { if (xmlReader.IsEmptyElement()) { xmlReader.PrintError("incomplete cube visual declaration"); return false; } bool facesDefined[6]; Y_memzero(facesDefined, sizeof(facesDefined)); for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 shapeSelection = xmlReader.Select("flags|faces"); if (shapeSelection < 0) return false; switch (shapeSelection) { // flags case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 flagsSelection = xmlReader.Select("volume|untileable"); if (flagsSelection < 0) return false; switch (flagsSelection) { // volume case 0: pBlockType->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME; break; // untileable case 1: pBlockType->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_UNTILEABLE; break; } if (!xmlReader.SkipCurrentElement()) return false; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "flags") == 0); break; } } } } break; // faces case 1: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 faceIndex = xmlReader.Select("right|left|back|front|top|bottom"); if (faceIndex < 0) return false; DebugAssert(faceIndex < CUBE_FACE_COUNT); // read attributes const char *visualTypeStr = xmlReader.FetchAttribute("visual"); const char *colorStr = xmlReader.FetchAttribute("color"); const char *textureNameStr = xmlReader.FetchAttribute("texture-name"); const char *materialNameStr = xmlReader.FetchAttribute("material-name"); if (visualTypeStr == NULL || colorStr == NULL) { xmlReader.PrintError("missing visual type"); return false; } BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[faceIndex]; pFaceDef->Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT; pFaceDef->Visual.Color = StringConverter::StringToColor(colorStr); pFaceDef->Visual.TextureIndex = 0xFFFFFFFF; // type specific stuff if (Y_stricmp(visualTypeStr, "color") == 0) { pFaceDef->Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; } else if (Y_stricmp(visualTypeStr, "texture") == 0) { if (textureNameStr == NULL) { xmlReader.PrintError("texture-name is required."); return false; } for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (m_textures[i]->Name.Compare(textureNameStr)) { pFaceDef->Visual.TextureIndex = i; break; } } if (pFaceDef->Visual.TextureIndex == 0xFFFFFFFF) { xmlReader.PrintError("texture named '%s' not found", textureNameStr); return false; } pFaceDef->Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE; } else if (Y_stricmp(visualTypeStr, "material") == 0) { if (materialNameStr == nullptr) { xmlReader.PrintError("material-name is required"); return false; } pFaceDef->Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL; pFaceDef->Visual.MaterialName = materialNameStr; } else { xmlReader.PrintError("unknown visual type '%s'", visualTypeStr); return false; } facesDefined[faceIndex] = true; } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "faces") == 0); break; } } // end loop over faces } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "shape") == 0); break; } } // check faces are defined for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) { if (!facesDefined[i]) { xmlReader.PrintError("face not defined: %u", i); return true; } } } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { if (xmlReader.IsEmptyElement()) { xmlReader.PrintError("incomplete plane visual declaration"); return false; } // skip to settings element if (!xmlReader.NextToken() || xmlReader.Select("settings") < 0) return false; // read attributes const char *visualTypeStr = xmlReader.FetchAttribute("visual"); const char *colorStr = xmlReader.FetchAttribute("color"); const char *textureNameStr = xmlReader.FetchAttribute("texture-name"); const char *materialNameStr = xmlReader.FetchAttribute("material-name"); const char *xOffsetStr = xmlReader.FetchAttribute("offset-x"); const char *yOffsetStr = xmlReader.FetchAttribute("offset-y"); const char *widthStr = xmlReader.FetchAttribute("width"); const char *heightStr = xmlReader.FetchAttribute("height"); const char *baseRotationStr = xmlReader.FetchAttribute("base-rotation"); const char *repeatCountStr = xmlReader.FetchAttribute("repeat-count"); const char *repeatRotationStr = xmlReader.FetchAttribute("repeat-rotation"); if (visualTypeStr == NULL || colorStr == NULL || xOffsetStr == NULL || yOffsetStr == NULL || widthStr == NULL || heightStr == NULL || baseRotationStr == NULL || repeatCountStr == NULL || repeatRotationStr == NULL) { xmlReader.PrintError("missing attributes"); return false; } pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT; pBlockType->PlaneShapeSettings.Visual.Color = StringConverter::StringToColor(colorStr); pBlockType->PlaneShapeSettings.Visual.TextureIndex = 0xFFFFFFFF; if (Y_stricmp(visualTypeStr, "color") == 0) { pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; } else if (Y_stricmp(visualTypeStr, "texture") == 0) { if (textureNameStr == NULL) { xmlReader.PrintError("texture-name is required."); return false; } for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (m_textures[i]->Name.Compare(textureNameStr)) { pBlockType->PlaneShapeSettings.Visual.TextureIndex = i; break; } } if (pBlockType->PlaneShapeSettings.Visual.TextureIndex == 0xFFFFFFFF) { xmlReader.PrintError("texture named '%s' not found", textureNameStr); return false; } pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE; } else if (Y_stricmp(visualTypeStr, "material") == 0) { if (materialNameStr == nullptr) { xmlReader.PrintError("material-name is required"); return false; } pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL; pBlockType->PlaneShapeSettings.Visual.MaterialName = materialNameStr; } else { xmlReader.PrintError("unknown visual type '%s'", visualTypeStr); return false; } pBlockType->PlaneShapeSettings.OffsetX = StringConverter::StringToFloat(xOffsetStr); pBlockType->PlaneShapeSettings.OffsetY = StringConverter::StringToFloat(yOffsetStr); pBlockType->PlaneShapeSettings.Width = StringConverter::StringToFloat(widthStr); pBlockType->PlaneShapeSettings.Height = StringConverter::StringToFloat(heightStr); pBlockType->PlaneShapeSettings.BaseRotation = StringConverter::StringToFloat(baseRotationStr); pBlockType->PlaneShapeSettings.RepeatCount = StringConverter::StringToUInt32(repeatCountStr); pBlockType->PlaneShapeSettings.RepeatRotation = StringConverter::StringToFloat(repeatRotationStr); // skip the rest of the settings element if (!xmlReader.SkipCurrentElement() || !xmlReader.NextToken()) return false; // should be the end of the shape element DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "shape") == 0); } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { // skip to settings element if (!xmlReader.NextToken() || xmlReader.Select("settings") < 0) return false; // read attributes const char *nameStr = xmlReader.FetchAttribute("name"); const char *scaleStr = xmlReader.FetchAttribute("scale"); if (nameStr == NULL || scaleStr == NULL) { xmlReader.PrintError("missing attributes"); return false; } // insert mesh name and scale pBlockType->MeshShapeSettings.MeshName = nameStr; pBlockType->MeshShapeSettings.Scale = StringConverter::StringToFloat(scaleStr); // skip the rest of the settings element if (!xmlReader.SkipCurrentElement() || !xmlReader.NextToken()) return false; // should be the end of the shape element DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "shape") == 0); } else { // skip the rest of the shape element if (!xmlReader.SkipCurrentElement()) return false; } } // end case shape break; // block-light-emitter case 2: { const char *enabledStr = xmlReader.FetchAttribute("enabled"); const char *radiusStr = xmlReader.FetchAttribute("radius"); if (enabledStr == NULL || radiusStr == NULL) { xmlReader.PrintError("missing attributes"); return false; } // set properties pBlockType->BlockLightEmitterSettings.Enabled = StringConverter::StringToBool(enabledStr); pBlockType->BlockLightEmitterSettings.Radius = StringConverter::StringToUInt32(radiusStr); } // end case point-light-emitter break; // point-light-emitter case 3: { const char *enabledStr = xmlReader.FetchAttribute("enabled"); const char *offsetStr = xmlReader.FetchAttribute("offset"); const char *colorStr = xmlReader.FetchAttribute("color"); const char *brightnessStr = xmlReader.FetchAttribute("brightness"); const char *rangeStr = xmlReader.FetchAttribute("range"); const char *falloffStr = xmlReader.FetchAttribute("falloff"); if (enabledStr == NULL || offsetStr == NULL || colorStr == NULL || brightnessStr == NULL || rangeStr == NULL || falloffStr == NULL) { xmlReader.PrintError("missing attributes"); return false; } // set properties pBlockType->PointLightEmitterSettings.Enabled = StringConverter::StringToBool(enabledStr); pBlockType->PointLightEmitterSettings.Offset = StringConverter::StringToFloat3(offsetStr); pBlockType->PointLightEmitterSettings.Color = StringConverter::StringToColor(colorStr); pBlockType->PointLightEmitterSettings.Brightness = StringConverter::StringToFloat(brightnessStr); pBlockType->PointLightEmitterSettings.Range = StringConverter::StringToFloat(rangeStr); pBlockType->PointLightEmitterSettings.Falloff = StringConverter::StringToFloat(falloffStr); } // end case point-light-emitter break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "blocktype") == 0); break; } else { UnreachableCode(); } } // end blocktype loop } } break; default: UnreachableCode(); break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "palette") == 0); break; } else { UnreachableCode(); } } } /* // validate texture atlas indices for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { BlockType *pBlockType = &m_BlockTypes[i]; if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { for (uint32 j = 0; j < CUBE_FACE_COUNT; j++) { const BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[j]; if (pFaceDef->VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_STATIC_TEXTURE || pFaceDef->VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_HORIZONTAL_SCROLL_TEXTURE || pFaceDef->VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_VERTICAL_SCROLL_TEXTURE) { if (pFaceDef->TextureIndex >= m_Textures.GetSize()) { xmlReader.PrintError("block %u face %u has texture index out of range.", i, j); return false; } } } } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { if (pBlockType->PlaneShapeSettings.VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_STATIC_TEXTURE || pBlockType->PlaneShapeSettings.VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_HORIZONTAL_SCROLL_TEXTURE || pBlockType->PlaneShapeSettings.VisualType == BLOCK_MESH_BLOCK_TYPE_CUBE_VISUAL_TYPE_VERTICAL_SCROLL_TEXTURE) { if (pBlockType->PlaneShapeSettings.TextureIndex >= m_Textures.GetSize()) { xmlReader.PrintError("block %u plane has texture index out of range.", i); return false; } } } } */ return true; } bool BlockPaletteGenerator::Save(ByteStream *pStream, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) const { pProgressCallbacks->SetStatusText("Opening archive..."); pProgressCallbacks->SetProgressRange(4); pProgressCallbacks->SetProgressValue(0); ZipArchive *pArchive = ZipArchive::CreateArchive(pStream); if (pArchive == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::Save: Could not create archive."); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(1); pProgressCallbacks->SetStatusText("Saving textures..."); pProgressCallbacks->PushState(); // load textures from archive if (!SaveTextures(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("BlockPaletteGenerator::Save: Could not save textures."); pProgressCallbacks->PopState(); delete pArchive; return false; } pProgressCallbacks->PopState(); pProgressCallbacks->SetProgressValue(2); pProgressCallbacks->SetStatusText("Saving block types..."); // load xml if (!SaveXML(pArchive, pProgressCallbacks)) { Log_ErrorPrintf("BlockPaletteGenerator::Save: Could not save block types."); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(3); pProgressCallbacks->SetStatusText("Committing changes to archive..."); if (!pArchive->CommitChanges()) { Log_ErrorPrintf("BlockPaletteGenerator::Save: Could not commit changes."); delete pArchive; return false; } pProgressCallbacks->SetProgressValue(4); delete pArchive; return true; } bool BlockPaletteGenerator::SaveTextures(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const { if (m_textures.GetSize() == 0) return true; pProgressCallbacks->SetProgressRange(m_textures.GetSize()); pProgressCallbacks->SetProgressValue(0); // iterate textures PathString textureFileName; for (uint32 i = 0; i < m_textures.GetSize(); i++) { Texture *pTexture = m_textures[i]; pProgressCallbacks->SetFormattedStatusText("Saving texture '%s'...", pTexture->Name.GetCharArray()); // create texture xml textureFileName.Format("textures/%s.xml", pTexture->Name.GetCharArray()); { ByteStream *pXMLStream = pArchive->OpenFile(textureFileName, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_STREAMED); if (pXMLStream == nullptr) return false; XMLWriter xmlWriter; if (!xmlWriter.Create(pXMLStream)) { pXMLStream->Release(); return false; } xmlWriter.StartElement("block-palette-texture"); { xmlWriter.StartElement("blending"); { xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::BlockMeshTextureBlending, pTexture->Blending)); } xmlWriter.EndElement(); xmlWriter.StartElement("effect"); { xmlWriter.WriteAttribute("type", NameTable_GetNameString(NameTables::BlockMeshTextureEffect, pTexture->Effect)); if (pTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_SCROLL) { xmlWriter.WriteAttribute("scroll-direction", StringConverter::Float2ToString(pTexture->ScrollDirection)); xmlWriter.WriteAttribute("scroll-speed", StringConverter::FloatToString(pTexture->ScrollSpeed)); } else if (pTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_ANIMATION) { xmlWriter.WriteAttribute("animation-frames", StringConverter::UInt32ToString(pTexture->AnimationFrameCount)); xmlWriter.WriteAttribute("animation-speed", StringConverter::FloatToString(pTexture->AnimationSpeed)); } } xmlWriter.EndElement(); xmlWriter.StartElement("filtering"); xmlWriter.WriteAttribute("enabled", StringConverter::BoolToString(pTexture->AllowTextureFiltering)); xmlWriter.EndElement(); } xmlWriter.EndElement(); if (xmlWriter.InErrorState() || pXMLStream->InErrorState()) { xmlWriter.Close(); pXMLStream->Release(); return false; } xmlWriter.Close(); pXMLStream->Release(); } if (pTexture->pDiffuseMap != nullptr) { textureFileName.Format("textures/%s_diffuse.png", pTexture->Name.GetCharArray()); if (!SaveTexture(pArchive, pTexture->pDiffuseMap, textureFileName)) return false; } if (pTexture->pSpecularMap != nullptr) { textureFileName.Format("textures/%s_specular.png", pTexture->Name.GetCharArray()); if (!SaveTexture(pArchive, pTexture->pSpecularMap, textureFileName)) return false; } if (pTexture->pNormalMap != nullptr) { textureFileName.Format("textures/%s_normal.png", pTexture->Name.GetCharArray()); if (!SaveTexture(pArchive, pTexture->pNormalMap, textureFileName)) return false; } pProgressCallbacks->IncrementProgressValue(); } return true; } bool BlockPaletteGenerator::SaveTexture(ZipArchive *pArchive, const Image *pImage, const char *filename) const { // get codec ImageCodec *pImageCodec = ImageCodec::GetImageCodecForFileName(filename); if (pImageCodec == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::SaveTexture: Could not get codec for file name '%s'.", filename); return false; } // open the stream AutoReleasePtr<ByteStream> pTextureStream = pArchive->OpenFile(filename, BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pTextureStream == NULL) { Log_ErrorPrintf("BlockPaletteGenerator::SaveTexture: Could not open file name '%s'.", filename); return false; } // create property list PropertyTable imageEncodePropertyList; imageEncodePropertyList.SetPropertyValueUInt32(ImageCodecEncoderOptions::PNG_COMPRESSION_LEVEL, BLOCK_MESH_BLOCK_LIST_TEXTURE_COMPRESSION_LEVEL); // write the image out if (!pImageCodec->EncodeImage(filename, pTextureStream, pImage, imageEncodePropertyList)) { Log_ErrorPrintf("BlockPaletteGenerator::SaveTexture: Failed to encode image '%s'.", filename); return false; } return true; } bool BlockPaletteGenerator::SaveXML(ZipArchive *pArchive, ProgressCallbacks *pProgressCallbacks) const { SmallString tempString; AutoReleasePtr<ByteStream> pBlockTypesStream = pArchive->OpenFile("palette.xml", BYTESTREAM_OPEN_CREATE | BYTESTREAM_OPEN_WRITE | BYTESTREAM_OPEN_TRUNCATE | BYTESTREAM_OPEN_SEEKABLE); if (pBlockTypesStream == NULL) return false; // create xml writer XMLWriter xmlWriter; if (!xmlWriter.Create(pBlockTypesStream)) return false; // write root element xmlWriter.StartElement("palette"); { xmlWriter.WriteAttribute("diffuse-map-size", StringConverter::UInt32ToString(m_diffuseMapSize)); xmlWriter.WriteAttribute("specular-map-size", StringConverter::UInt32ToString(m_specularMapSize)); xmlWriter.WriteAttribute("normal-map-size", StringConverter::UInt32ToString(m_normalMapSize)); // for each block type for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { const BlockType *pBlockType = &m_blockTypes[i]; if (!m_allocatedBlockTypes[i]) continue; xmlWriter.StartElement("blocktype"); { xmlWriter.WriteAttributef("index", "%u", i); xmlWriter.WriteAttribute("name", pBlockType->Name); // flags xmlWriter.StartElement("flags"); { if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_SOLID) xmlWriter.WriteEmptyElement("solid"); if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS) xmlWriter.WriteEmptyElement("cast-shadows"); } xmlWriter.EndElement(); // <visual> xmlWriter.StartElement("shape"); { static const char *shapeNames[BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_COUNT] = { "none", "cube", "slab", "stairs", "plane", "mesh" }; static const char *visualNames[BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT] = { "color", "texture", "material" }; DebugAssert(pBlockType->ShapeType < BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_COUNT); xmlWriter.WriteAttribute("type", shapeNames[pBlockType->ShapeType]); if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB || pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) xmlWriter.WriteAttribute("height", StringConverter::FloatToString(pBlockType->SlabShapeSettings.Height)); xmlWriter.StartElement("flags"); { if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) xmlWriter.WriteEmptyElement("volume"); if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_UNTILEABLE) xmlWriter.WriteEmptyElement("untileable"); } xmlWriter.EndElement(); xmlWriter.StartElement("faces"); { for (uint32 j = 0; j < CUBE_FACE_COUNT; j++) { static const char *faceNames[CUBE_FACE_COUNT] = { "right", "left", "back", "front", "top", "bottom" }; xmlWriter.StartElement(faceNames[j]); { const BlockType::CubeShapeFace *pFaceDef = &pBlockType->CubeShapeFaces[j]; DebugAssert(pFaceDef->Visual.Type < BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT); xmlWriter.WriteAttribute("visual", visualNames[pFaceDef->Visual.Type]); xmlWriter.WriteAttribute("color", StringConverter::ColorToString(pFaceDef->Visual.Color)); if (pFaceDef->Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE) xmlWriter.WriteAttribute("texture-name", m_textures[pFaceDef->Visual.TextureIndex]->Name); else if (pFaceDef->Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL) xmlWriter.WriteAttribute("material-name", pFaceDef->Visual.MaterialName); } xmlWriter.EndElement(); } } xmlWriter.EndElement(); } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { xmlWriter.StartElement("settings"); { DebugAssert(pBlockType->PlaneShapeSettings.Visual.Type < BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COUNT); xmlWriter.WriteAttribute("visual", visualNames[pBlockType->PlaneShapeSettings.Visual.Type]); xmlWriter.WriteAttribute("color", StringConverter::ColorToString(pBlockType->PlaneShapeSettings.Visual.Color)); if (pBlockType->PlaneShapeSettings.Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE) xmlWriter.WriteAttribute("texture-name", m_textures[pBlockType->PlaneShapeSettings.Visual.TextureIndex]->Name); else if (pBlockType->PlaneShapeSettings.Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL) xmlWriter.WriteAttribute("material-name", pBlockType->PlaneShapeSettings.Visual.MaterialName); xmlWriter.WriteAttributef("offset-x", "%f", pBlockType->PlaneShapeSettings.OffsetX); xmlWriter.WriteAttributef("offset-y", "%f", pBlockType->PlaneShapeSettings.OffsetY); xmlWriter.WriteAttributef("width", "%f", pBlockType->PlaneShapeSettings.Width); xmlWriter.WriteAttributef("height", "%f", pBlockType->PlaneShapeSettings.Height); xmlWriter.WriteAttributef("base-rotation", "%f", pBlockType->PlaneShapeSettings.BaseRotation); xmlWriter.WriteAttributef("repeat-count", "%u", pBlockType->PlaneShapeSettings.RepeatCount); xmlWriter.WriteAttributef("repeat-rotation", "%f", pBlockType->PlaneShapeSettings.RepeatRotation); } xmlWriter.EndElement(); } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { xmlWriter.StartElement("settings"); { xmlWriter.WriteAttribute("name", pBlockType->MeshShapeSettings.MeshName); xmlWriter.WriteAttribute("scale", StringConverter::FloatToString(pBlockType->MeshShapeSettings.Scale)); } xmlWriter.EndElement(); } } xmlWriter.EndElement(); // </shape> xmlWriter.StartElement("block-light-emitter"); { xmlWriter.WriteAttribute("enabled", StringConverter::BoolToString(pBlockType->BlockLightEmitterSettings.Enabled)); xmlWriter.WriteAttribute("radius", StringConverter::UInt32ToString(pBlockType->BlockLightEmitterSettings.Radius)); } xmlWriter.EndElement(); // </block-light-emitter> xmlWriter.StartElement("point-light-emitter"); { xmlWriter.WriteAttribute("enabled", StringConverter::BoolToString(pBlockType->PointLightEmitterSettings.Enabled)); xmlWriter.WriteAttribute("offset", StringConverter::Float3ToString(pBlockType->PointLightEmitterSettings.Offset)); xmlWriter.WriteAttribute("color", StringConverter::ColorToString(pBlockType->PointLightEmitterSettings.Color)); xmlWriter.WriteAttribute("range", StringConverter::FloatToString(pBlockType->PointLightEmitterSettings.Range)); xmlWriter.WriteAttribute("brightness", StringConverter::FloatToString(pBlockType->PointLightEmitterSettings.Brightness)); xmlWriter.WriteAttribute("falloff", StringConverter::FloatToString(pBlockType->PointLightEmitterSettings.Falloff)); } xmlWriter.EndElement(); // </point-light-emitter> } xmlWriter.EndElement(); // </blocktype> } } xmlWriter.EndElement(); return (!xmlWriter.InErrorState() && !pBlockTypesStream->InErrorState()); } const BlockPaletteGenerator::BlockType *BlockPaletteGenerator::GetBlockTypeByName(const char *name) const { for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { if (m_allocatedBlockTypes[i] && m_blockTypes[i].Name.Compare(name)) return &m_blockTypes[i]; } return nullptr; } BlockPaletteGenerator::BlockType *BlockPaletteGenerator::GetBlockTypeByName(const char *name) { for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { if (m_allocatedBlockTypes[i] && m_blockTypes[i].Name.Compare(name)) return &m_blockTypes[i]; } return nullptr; } int32 BlockPaletteGenerator::FindBlockTypeByName(const char *name) const { for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { if (m_allocatedBlockTypes[i] && m_blockTypes[i].Name.Compare(name)) return (int32)i; } return -1; } BlockPaletteGenerator::BlockType *BlockPaletteGenerator::CreateBlockType(const char *blockName, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType, uint32 flags) { // ensure name is not used if (GetBlockTypeByName(blockName) != nullptr) return nullptr; // find a free slot for (uint32 slot = 1; slot < BLOCK_MESH_MAX_BLOCK_TYPES; slot++) { if (!m_allocatedBlockTypes[slot]) return CreateBlockType(slot, blockName, shapeType, flags); } // no slots return nullptr; } BlockPaletteGenerator::BlockType *BlockPaletteGenerator::CreateBlockType(uint32 blockTypeIndex, const char *blockName, BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE shapeType, uint32 flags) { uint32 i; DebugAssert(shapeType < BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_COUNT); if (blockTypeIndex == 0 || blockTypeIndex >= BLOCK_MESH_MAX_BLOCK_TYPES || m_allocatedBlockTypes[blockTypeIndex] || GetBlockTypeByName(blockName) != nullptr) return nullptr; BlockType *pBlockType = &m_blockTypes[blockTypeIndex]; m_allocatedBlockTypes[blockTypeIndex] = true; pBlockType->Name = blockName; pBlockType->Flags = flags; pBlockType->ShapeType = shapeType; switch (pBlockType->ShapeType) { case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE: { for (i = 0; i < CUBE_FACE_COUNT; i++) { pBlockType->CubeShapeFaces[i].Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pBlockType->CubeShapeFaces[i].Visual.Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); } } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB: { pBlockType->SlabShapeSettings.Height = 1.0f; for (i = 0; i < CUBE_FACE_COUNT; i++) { pBlockType->CubeShapeFaces[i].Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pBlockType->CubeShapeFaces[i].Visual.Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); } } break; case BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE: { pBlockType->PlaneShapeSettings.Visual.Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pBlockType->PlaneShapeSettings.Visual.Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); pBlockType->PlaneShapeSettings.OffsetX = 0.0f; pBlockType->PlaneShapeSettings.OffsetY = 0.0f; pBlockType->PlaneShapeSettings.BaseRotation = 0.0f; pBlockType->PlaneShapeSettings.RepeatCount = 1; pBlockType->PlaneShapeSettings.RepeatRotation = 0.0f; } break; } return pBlockType; } void BlockPaletteGenerator::RemoveBlockType(uint32 blockTypeIndex) { DebugAssert(blockTypeIndex < BLOCK_MESH_MAX_BLOCK_TYPES && m_allocatedBlockTypes[blockTypeIndex]); ResetBlockType(&m_blockTypes[blockTypeIndex]); m_allocatedBlockTypes[blockTypeIndex] = false; } const BlockPaletteGenerator::Texture *BlockPaletteGenerator::GetTextureByName(const char *name) const { for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (m_textures[i]->Name.CompareInsensitive(name)) return m_textures[i]; } return nullptr; } const BlockPaletteGenerator::Texture *BlockPaletteGenerator::CreateTexture(const char *textureName, BLOCK_MESH_TEXTURE_BLENDING blending, bool allowTextureFiltering) { DebugAssert(blending < BLOCK_MESH_TEXTURE_BLENDING_COUNT); for (uint32 i = 0; i < m_textures.GetSize(); i++) { if (m_textures[i]->Name.CompareInsensitive(textureName)) return nullptr; } Texture *pTexture = new Texture(); pTexture->Index = m_textures.GetSize(); pTexture->Name = textureName; pTexture->Blending = blending; pTexture->Effect = BLOCK_MESH_TEXTURE_EFFECT_NONE; pTexture->AllowTextureFiltering = allowTextureFiltering; Y_memzero(pTexture->ScrollDirection, sizeof(pTexture->ScrollDirection)); pTexture->ScrollSpeed = 0.0f; pTexture->AnimationFrameCount = 0; pTexture->AnimationSpeed = 0.0f; pTexture->pDiffuseMap = nullptr; pTexture->pNormalMap = nullptr; pTexture->pSpecularMap = nullptr; m_textures.Add(pTexture); return pTexture; } bool BlockPaletteGenerator::SetTextureDiffuseMap(uint32 textureIndex, const Image *pImage) { Texture *pTextureAtlas = m_textures[textureIndex]; // set new if (pImage != NULL) { bool result = true; Image *pNewImage = new Image(); if (pImage->GetPixelFormat() != BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT) result = pNewImage->CopyAndConvertPixelFormat(*pImage, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT); else pNewImage->Copy(*pImage); if (!result) { delete pNewImage; return false; } delete pTextureAtlas->pDiffuseMap; pTextureAtlas->pDiffuseMap = pNewImage; return true; } else { delete pTextureAtlas->pDiffuseMap; pTextureAtlas->pDiffuseMap = NULL; return true; } } bool BlockPaletteGenerator::SetTextureSpecularMap(uint32 textureIndex, const Image *pImage) { Texture *pTextureAtlas = m_textures[textureIndex]; // set new if (pImage != NULL) { bool result = true; Image *pNewImage = new Image(); if (pImage->GetPixelFormat() != BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT) result = pNewImage->CopyAndConvertPixelFormat(*pImage, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT); else pNewImage->Copy(*pImage); if (!result) { delete pNewImage; return false; } delete pTextureAtlas->pSpecularMap; pTextureAtlas->pSpecularMap = pNewImage; return true; } else { delete pTextureAtlas->pSpecularMap; pTextureAtlas->pSpecularMap = NULL; return true; } } bool BlockPaletteGenerator::SetTextureNormalMap(uint32 textureIndex, const Image *pImage) { Texture *pTexture = m_textures[textureIndex]; // set new if (pImage != NULL) { bool result = true; Image *pNewImage = new Image(); if (pImage->GetPixelFormat() != BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT) result = pNewImage->CopyAndConvertPixelFormat(*pImage, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT); else pNewImage->Copy(*pImage); if (!result) { delete pNewImage; return false; } delete pTexture->pNormalMap; pTexture->pNormalMap = pNewImage; return true; } else { delete pTexture->pNormalMap; pTexture->pNormalMap = NULL; return true; } } void BlockPaletteGenerator::SetTextureBlending(uint32 textureIndex, BLOCK_MESH_TEXTURE_BLENDING blending) { Texture *pTexture = m_textures[textureIndex]; pTexture->Blending = blending; } void BlockPaletteGenerator::SetTextureEffectNone(uint32 textureIndex) { Texture *pTexture = m_textures[textureIndex]; pTexture->Effect = BLOCK_MESH_TEXTURE_EFFECT_NONE; pTexture->ScrollDirection.SetZero(); pTexture->ScrollSpeed = 0.0f; pTexture->AnimationFrameCount = 0; pTexture->AnimationSpeed = 0.0f; } void BlockPaletteGenerator::SetTextureEffectScrolled(uint32 textureIndex, const float2 &scrollDirection, float scrollSpeed) { Texture *pTexture = m_textures[textureIndex]; pTexture->Effect = BLOCK_MESH_TEXTURE_EFFECT_SCROLL; pTexture->ScrollDirection = scrollDirection.Normalize(); pTexture->ScrollSpeed = scrollSpeed; pTexture->AnimationFrameCount = 0; pTexture->AnimationSpeed = 0.0f; } void BlockPaletteGenerator::SetTextureEffectAnimation(uint32 textureIndex, uint32 animationFrameCount, float animationSpeed) { Texture *pTexture = m_textures[textureIndex]; pTexture->Effect = BLOCK_MESH_TEXTURE_EFFECT_ANIMATION; pTexture->ScrollDirection.SetZero(); pTexture->ScrollSpeed = 0.0f; pTexture->AnimationFrameCount = animationFrameCount; pTexture->AnimationSpeed = animationSpeed; } BlockPaletteGenerator &BlockPaletteGenerator::operator=(const BlockPaletteGenerator &copyFrom) { Panic("Fixme"); /* uint32 i; for (i = 0; i < m_Textures.GetSize(); i++) { Texture *t = m_Textures[i]; if (t->DiffuseMapData != NULL) Y_free(t->DiffuseMapData); if (t->SpecularMapData != NULL) Y_free(t->SpecularMapData); if (t->NormalMapData != NULL) Y_free(t->NormalMapData); delete t; } m_Textures.Obliterate(); for (i = 0; i < copyFrom.m_Textures.GetSize(); i++) { const Texture *pSourceTexture = copyFrom.m_Textures[i]; Texture *pDestinationTexture = new Texture; pDestinationTexture->Index = pSourceTexture->Index; pDestinationTexture->Name = pSourceTexture->Name; if (pSourceTexture->DiffuseMapData != NULL) { pDestinationTexture->DiffuseMapData = (byte *)malloc(pSourceTexture->DiffuseMapDataSize); Y_memcpy(pDestinationTexture->DiffuseMapData, pSourceTexture->DiffuseMapData, pSourceTexture->DiffuseMapDataSize); pDestinationTexture->DiffuseMapDataSize = pSourceTexture->DiffuseMapDataSize; pDestinationTexture->DiffuseMapWidth = pSourceTexture->DiffuseMapWidth; pDestinationTexture->DiffuseMapHeight = pSourceTexture->DiffuseMapHeight; } else { pDestinationTexture->DiffuseMapData = NULL; pDestinationTexture->DiffuseMapDataSize = 0; pDestinationTexture->DiffuseMapWidth = 0; pDestinationTexture->DiffuseMapHeight = 0; } if (pSourceTexture->SpecularMapData != NULL) { pDestinationTexture->SpecularMapData = (byte *)malloc(pSourceTexture->SpecularMapDataSize); Y_memcpy(pDestinationTexture->SpecularMapData, pSourceTexture->SpecularMapData, pSourceTexture->SpecularMapDataSize); pDestinationTexture->SpecularMapDataSize = pSourceTexture->SpecularMapDataSize; pDestinationTexture->SpecularMapWidth = pSourceTexture->SpecularMapWidth; pDestinationTexture->SpecularMapHeight = pSourceTexture->SpecularMapHeight; } else { pDestinationTexture->SpecularMapData = NULL; pDestinationTexture->SpecularMapDataSize = 0; pDestinationTexture->SpecularMapWidth = 0; pDestinationTexture->SpecularMapHeight = 0; } if (pSourceTexture->NormalMapData != NULL) { pDestinationTexture->NormalMapData = (byte *)malloc(pSourceTexture->NormalMapDataSize); Y_memcpy(pDestinationTexture->NormalMapData, pSourceTexture->NormalMapData, pSourceTexture->NormalMapDataSize); pDestinationTexture->NormalMapDataSize = pSourceTexture->NormalMapDataSize; pDestinationTexture->NormalMapWidth = pSourceTexture->NormalMapWidth; pDestinationTexture->NormalMapHeight = pSourceTexture->NormalMapHeight; } else { pDestinationTexture->NormalMapData = NULL; pDestinationTexture->NormalMapDataSize = 0; pDestinationTexture->NormalMapWidth = 0; pDestinationTexture->NormalMapHeight = 0; } m_Textures.Add(pDestinationTexture); } const BlockType *pSourceBlockType = copyFrom.m_BlockTypes; BlockType *pDestinationBlockType = m_BlockTypes; for (i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++, pSourceBlockType++, pDestinationBlockType++) { ResetBlockType(pDestinationBlockType); m_bAllocatedBlockTypes[i] = copyFrom.m_bAllocatedBlockTypes[i]; if (m_bAllocatedBlockTypes[i]) { DebugAssert(pDestinationBlockType->BlockTypeIndex == pSourceBlockType->BlockTypeIndex); pDestinationBlockType->Name = pSourceBlockType->Name; pDestinationBlockType->Flags = pSourceBlockType->Flags; pDestinationBlockType->ShapeType = pSourceBlockType->ShapeType; if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) { const BlockType::CubeShapeFace *pSourceFace = &pSourceBlockType->CubeShapeFaces[i]; BlockType::CubeShapeFace *pDestinationFace = &pDestinationBlockType->CubeShapeFaces[i]; pDestinationFace->VisualType = pSourceFace->VisualType; pDestinationFace->Color = pSourceFace->Color; pDestinationFace->TextureIndex = pSourceFace->TextureIndex; pDestinationFace->TextureScrollSpeed = pSourceFace->TextureScrollSpeed; pDestinationFace->ExternalMaterialName = pSourceFace->ExternalMaterialName; } } else if (pDestinationBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { pDestinationBlockType->PlaneShapeSettings.VisualType = pSourceBlockType->PlaneShapeSettings.VisualType; pDestinationBlockType->PlaneShapeSettings.Color = pSourceBlockType->PlaneShapeSettings.Color; pDestinationBlockType->PlaneShapeSettings.TextureIndex = pSourceBlockType->PlaneShapeSettings.TextureIndex; pDestinationBlockType->PlaneShapeSettings.TextureScrollSpeed = pSourceBlockType->PlaneShapeSettings.TextureScrollSpeed; pDestinationBlockType->PlaneShapeSettings.ExternalMaterialName = pSourceBlockType->PlaneShapeSettings.ExternalMaterialName; pDestinationBlockType->PlaneShapeSettings.OffsetX = pSourceBlockType->PlaneShapeSettings.OffsetX; pDestinationBlockType->PlaneShapeSettings.OffsetY = pSourceBlockType->PlaneShapeSettings.OffsetY; pDestinationBlockType->PlaneShapeSettings.BaseRotation = pSourceBlockType->PlaneShapeSettings.BaseRotation; pDestinationBlockType->PlaneShapeSettings.RepeatCount = pSourceBlockType->PlaneShapeSettings.RepeatCount; pDestinationBlockType->PlaneShapeSettings.RepeatRotation = pSourceBlockType->PlaneShapeSettings.RepeatRotation; } } } */ return *this; } class BlockPaletteCompiler { public: BlockPaletteCompiler(const BlockPaletteGenerator *pGenerator); ~BlockPaletteCompiler(); bool Compile(TEXTURE_PLATFORM texturePlatform, ByteStream *pOutputStream); private: struct SourceTextureEntry { uint32 SourceIndex; uint32 MaterialIndex; uint32 TextureArrayIndex; float3 MinUV; float3 MaxUV; }; struct MaterialEntry { DF_BLOCK_PALETTE_MATERIAL_TYPE Type; uint32 Flags; String ExternalMaterialName; BLOCK_MESH_TEXTURE_BLENDING TextureBlending; BLOCK_MESH_TEXTURE_EFFECT TextureEffect; bool HasNormalMap; bool HasSpecularMap; int32 DiffuseMapTextureIndex; int32 SpecularMapTextureIndex; int32 NormalMapTextureIndex; uint32 TextureArraySize; uint32 TextureAtlasTileWidth; uint32 TextureAtlasTileHeight; uint32 TextureAtlasHPadding; uint32 TextureAtlasVPadding; uint32 TextureAtlasColumns; uint32 TextureAtlasRows; float2 ScrollDirection; float ScrollSpeed; //uint32 AnimationFrameCount; //float AnimationSpeed; }; struct BlockTypeEntry { uint32 BlockTypeIndex; String Name; uint32 Flags; BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE ShapeType; struct VisualParameters { BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE Type; uint32 MaterialIndex; uint32 Color; float3 MinUV; float3 MaxUV; float4 AtlasUVRange; }; struct CubeShapeFace { VisualParameters Visual; }; struct SlabShape { float Height; }; struct PlaneShape { VisualParameters Visual; float OffsetX; float OffsetY; float Width; float Height; float BaseRotation; uint32 RepeatCount; float RepeatRotation; }; struct MeshShape { uint32 MeshNameIndex; float Scale; }; struct BlockLightEmitter { uint32 Radius; }; struct PointLightEmitter { float3 Offset; uint32 Color; float Brightness; float Range; float Falloff; }; CubeShapeFace CubeShapeFaces[CUBE_FACE_COUNT]; SlabShape SlabSettings; PlaneShape PlaneSettings; MeshShape MeshSettings; BlockLightEmitter BlockLightEmitterSettings; PointLightEmitter PointLightEmitterSettings; }; bool GenerateMaterials(); bool GenerateTextureMipmaps(); bool ConvertTextureArraysToTextureAtlas(); bool CompileBlockType(const BlockPaletteGenerator::BlockType *pBlockType); bool CompileBlockTypeVisual(const BlockPaletteGenerator::BlockType::VisualParameters *pSourceVisual, BlockTypeEntry::VisualParameters *pDestinationVisual); bool WriteHeader(ByteStream *pStream); bool WriteBlockTypes(ByteStream *pStream, ChunkFileWriter &cfw); bool WriteTextures(ByteStream *pStream, ChunkFileWriter &cfw, TEXTURE_PLATFORM texturePlatform); bool WriteMaterials(ByteStream *pStream, ChunkFileWriter &cfw); bool WriteMeshes(ByteStream *pStream, ChunkFileWriter &cfw); const BlockPaletteGenerator *m_pGenerator; bool m_enableTextureCompression; bool m_enableMipGeneration; PODArray<SourceTextureEntry *> m_sourceTextures; PODArray<BlockTypeEntry *> m_blockTypes; PODArray<TextureGenerator *> m_textures; PODArray<MaterialEntry *> m_materials; PODArray<const String *> m_meshNames; }; BlockPaletteCompiler::BlockPaletteCompiler(const BlockPaletteGenerator *pGenerator) : m_pGenerator(pGenerator), m_enableTextureCompression(true), m_enableMipGeneration(true) { } BlockPaletteCompiler::~BlockPaletteCompiler() { uint32 i; for (i = 0; i < m_materials.GetSize(); i++) delete m_materials[i]; for (i = 0; i < m_textures.GetSize(); i++) delete m_textures[i]; for (i = 0; i < m_blockTypes.GetSize(); i++) delete m_blockTypes[i]; for (i = 0; i < m_sourceTextures.GetSize(); i++) delete m_sourceTextures[i]; } bool BlockPaletteCompiler::Compile(TEXTURE_PLATFORM texturePlatform, ByteStream *pOutputStream) { // settings //m_enableTextureCompression = true; //m_enableTextureCompression = false; //m_enableMipGeneration = true; //m_enableMipGeneration = false; // gen materials if (!GenerateMaterials()) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to generate materials."); return false; } // add block types for (uint32 i = 1; i < BLOCK_MESH_MAX_BLOCK_TYPES; i++) { const BlockPaletteGenerator::BlockType *pBlockType = m_pGenerator->GetBlockType(i); if (pBlockType == NULL) continue; if (!CompileBlockType(pBlockType)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to compile block type %u (%s)", i, pBlockType->Name.GetCharArray()); return false; } } // if (!ConvertTextureArraysToTextureAtlas()) // { // Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to convert texture arrays to atlases."); // return false; // } if (!WriteHeader(pOutputStream)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to write header."); return false; } // initialize chunk file writer ChunkFileWriter cfw; if (!cfw.Initialize(pOutputStream, DF_BLOCK_PALETTE_CHUNK_COUNT)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to initialize chunk file writer."); return false; } if (!WriteBlockTypes(pOutputStream, cfw)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to write block types."); return false; } if (!WriteTextures(pOutputStream, cfw, texturePlatform)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to write textures."); return false; } if (!WriteMaterials(pOutputStream, cfw)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to write materials."); return false; } if (!WriteMeshes(pOutputStream, cfw)) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to write meshes."); return false; } // close chunk writer if (!cfw.Close() || pOutputStream->InErrorState()) { Log_ErrorPrintf("BlockPaletteCompiler::Compile: Failed to close chunk file writer."); return false; } Log_DevPrintf("BlockPaletteCompiler::Compile: Block list compiled, size = %u bytes", (uint32)pOutputStream->GetSize()); return true; } bool BlockPaletteCompiler::GenerateMaterials() { // for each source texture... for (uint32 sourceTextureIndex = 0; sourceTextureIndex < m_pGenerator->GetTextureCount(); sourceTextureIndex++) { const BlockPaletteGenerator::Texture *pSourceTexture = m_pGenerator->GetTexture(sourceTextureIndex); // is it used anywhere? bool sourceTextureUsed = false; for (uint32 blockTypeIndex = 0; blockTypeIndex < BLOCK_MESH_MAX_BLOCK_TYPES; blockTypeIndex++) { const BlockPaletteGenerator::BlockType *pSourceBlockType = m_pGenerator->GetBlockType(blockTypeIndex); if (pSourceBlockType != NULL) { if (pSourceBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pSourceBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) { if (pSourceBlockType->CubeShapeFaces[i].Visual.TextureIndex == sourceTextureIndex) { sourceTextureUsed = true; break; } } } else if (pSourceBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { if (pSourceBlockType->PlaneShapeSettings.Visual.TextureIndex == sourceTextureIndex) sourceTextureUsed = true; } } if (sourceTextureUsed) break; } // if not, skip it if (!sourceTextureUsed) continue; // source texture has normal/specular map? bool sourceTextureHasNormalMap = (pSourceTexture->pNormalMap != nullptr); bool sourceTextureHasSpecularMap = (pSourceTexture->pSpecularMap != nullptr); // this texture is used somewhere, so it does have to be compiled // search for a material with these parameters already matching uint32 materialIndex; for (materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { MaterialEntry *pMaterialEntry = m_materials[materialIndex]; if (pMaterialEntry->HasNormalMap == sourceTextureHasNormalMap && pMaterialEntry->HasSpecularMap == sourceTextureHasSpecularMap && pMaterialEntry->TextureBlending == pSourceTexture->Blending && pMaterialEntry->TextureEffect == pSourceTexture->Effect) { // test for effect-specific parameters if (pMaterialEntry->TextureEffect == BLOCK_MESH_TEXTURE_EFFECT_SCROLL) { if (pMaterialEntry->ScrollDirection != pSourceTexture->ScrollDirection || pMaterialEntry->ScrollSpeed != pSourceTexture->ScrollSpeed) { // mismatch continue; } } else if (pMaterialEntry->TextureEffect == BLOCK_MESH_TEXTURE_EFFECT_ANIMATION) { //if (pMaterialEntry->) } // material matches break; } } // found one? MaterialEntry *pMaterialEntry; uint32 textureArrayIndex; if (materialIndex != m_materials.GetSize()) { pMaterialEntry = m_materials[materialIndex]; // if this material is not currently using a texture array, it will have to be now if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_WITH_NORMAL_MAP || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_WITH_NORMAL_MAP || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_WITH_NORMAL_MAP) { // switch it to a texture array if (pMaterialEntry->DiffuseMapTextureIndex >= 0) { DebugAssert(m_textures[pMaterialEntry->DiffuseMapTextureIndex]->GetTextureType() == TEXTURE_TYPE_2D); m_textures[pMaterialEntry->DiffuseMapTextureIndex]->ConvertToTextureArray(); } if (pMaterialEntry->SpecularMapTextureIndex >= 0) { DebugAssert(m_textures[pMaterialEntry->SpecularMapTextureIndex]->GetTextureType() == TEXTURE_TYPE_2D); m_textures[pMaterialEntry->SpecularMapTextureIndex]->ConvertToTextureArray(); } if (pMaterialEntry->NormalMapTextureIndex >= 0) { DebugAssert(m_textures[pMaterialEntry->NormalMapTextureIndex]->GetTextureType() == TEXTURE_TYPE_2D); m_textures[pMaterialEntry->NormalMapTextureIndex]->ConvertToTextureArray(); } // update the material type if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY; else if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_WITH_NORMAL_MAP) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ARRAY_WITH_NORMAL_MAP; else if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY; else if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_WITH_NORMAL_MAP) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ARRAY_WITH_NORMAL_MAP; else if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY; else if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_WITH_NORMAL_MAP) pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ARRAY_WITH_NORMAL_MAP; } // append this texture's images to the array textureArrayIndex = pMaterialEntry->TextureArraySize++; // add diffuse map if (pSourceTexture->pDiffuseMap != nullptr) { TextureGenerator *pDestinationTexture = m_textures[pMaterialEntry->DiffuseMapTextureIndex]; if (pSourceTexture->pDiffuseMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pDiffuseMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pDiffuseMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->AddImage(&tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize diffuse map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->AddImage(pSourceTexture->pDiffuseMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to append diffuse map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } // add specular map if (pSourceTexture->pSpecularMap != nullptr) { TextureGenerator *pDestinationTexture = m_textures[pMaterialEntry->SpecularMapTextureIndex]; if (pSourceTexture->pSpecularMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pSpecularMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pSpecularMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->AddImage(&tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize specular map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->AddImage(pSourceTexture->pSpecularMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to append specular map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } // add normal map if (pSourceTexture->pNormalMap != nullptr) { TextureGenerator *pDestinationTexture = m_textures[pMaterialEntry->NormalMapTextureIndex]; if (pSourceTexture->pNormalMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pNormalMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pNormalMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->AddImage(&tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize normal map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->AddImage(pSourceTexture->pNormalMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to append normal map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } } else { // have to create a new material pMaterialEntry = new MaterialEntry; materialIndex = m_materials.GetSize(); m_materials.Add(pMaterialEntry); // set the type of it if (pSourceTexture->Blending == BLOCK_MESH_TEXTURE_BLENDING_NONE) pMaterialEntry->Type = (sourceTextureHasNormalMap) ? DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_WITH_NORMAL_MAP : DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE; else if (pSourceTexture->Blending == BLOCK_MESH_TEXTURE_BLENDING_MASKED) pMaterialEntry->Type = (sourceTextureHasNormalMap) ? DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_WITH_NORMAL_MAP : DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE; else //if (pSourceTexture->Blending == BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT) pMaterialEntry->Type = (sourceTextureHasNormalMap) ? DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_WITH_NORMAL_MAP : DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE; // set flags pMaterialEntry->Flags = 0; if (pSourceTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_SCROLL) pMaterialEntry->Flags |= DF_BLOCK_PALETTE_MATERIAL_FLAG_SCROLLED_TEXTURE; else if (pSourceTexture->Effect == BLOCK_MESH_TEXTURE_EFFECT_ANIMATION) pMaterialEntry->Flags |= DF_BLOCK_PALETTE_MATERIAL_FLAG_ANIMATED_TEXTURE; // fill in common fields pMaterialEntry->TextureBlending = pSourceTexture->Blending; pMaterialEntry->TextureEffect = pSourceTexture->Effect; pMaterialEntry->HasNormalMap = sourceTextureHasNormalMap; pMaterialEntry->HasSpecularMap = sourceTextureHasSpecularMap; pMaterialEntry->DiffuseMapTextureIndex = -1; pMaterialEntry->SpecularMapTextureIndex = -1; pMaterialEntry->NormalMapTextureIndex = -1; pMaterialEntry->TextureArraySize = 1; pMaterialEntry->TextureAtlasTileWidth = 0; pMaterialEntry->TextureAtlasTileHeight = 0; pMaterialEntry->TextureAtlasHPadding = 0; pMaterialEntry->TextureAtlasVPadding = 0; pMaterialEntry->TextureAtlasColumns = 0; pMaterialEntry->TextureAtlasRows = 0; pMaterialEntry->ScrollDirection = pSourceTexture->ScrollDirection; pMaterialEntry->ScrollSpeed = pSourceTexture->ScrollSpeed; // texture array index will be 0 since we are the only texture for now textureArrayIndex = 0; // create diffuse map texture if (pSourceTexture->pDiffuseMap != nullptr) { TextureGenerator *pDestinationTexture = new TextureGenerator; pDestinationTexture->Create(TEXTURE_TYPE_2D, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, m_pGenerator->GetDiffuseMapSize(), m_pGenerator->GetDiffuseMapSize(), 1, 1); pDestinationTexture->SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureFilter((pSourceTexture->AllowTextureFiltering) ? TEXTURE_FILTER_ANISOTROPIC : TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR); pDestinationTexture->SetTextureUsage(TEXTURE_USAGE_COLOR_MAP); pDestinationTexture->SetSourcePremultipliedAlpha(false); pDestinationTexture->SetEnablePremultipliedAlpha((pSourceTexture->Blending == BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT)); pDestinationTexture->SetEnableTextureCompression(m_enableTextureCompression); pDestinationTexture->SetGenerateMipmaps(m_enableMipGeneration); pDestinationTexture->SetMipMapResizeFilter(IMAGE_RESIZE_FILTER_LANCZOS3); pDestinationTexture->SetSourceSRGB(true); pDestinationTexture->SetEnableSRGB(true); pMaterialEntry->DiffuseMapTextureIndex = (uint32)m_textures.GetSize(); m_textures.Add(pDestinationTexture); if (pSourceTexture->pDiffuseMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pDiffuseMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pDiffuseMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->SetImage(0, &tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize diffuse map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->SetImage(0, pSourceTexture->pDiffuseMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to set diffuse map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } // create specular map texture if (pSourceTexture->pSpecularMap != nullptr) { TextureGenerator *pDestinationTexture = new TextureGenerator; pDestinationTexture->Create(TEXTURE_TYPE_2D, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, m_pGenerator->GetSpecularMapSize(), m_pGenerator->GetSpecularMapSize(), 1, 1); pDestinationTexture->SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureFilter((pSourceTexture->AllowTextureFiltering) ? TEXTURE_FILTER_ANISOTROPIC : TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR); pDestinationTexture->SetTextureUsage(TEXTURE_USAGE_GLOSS_MAP); pDestinationTexture->SetSourcePremultipliedAlpha(false); pDestinationTexture->SetEnablePremultipliedAlpha(false); pDestinationTexture->SetEnableTextureCompression(m_enableTextureCompression); pDestinationTexture->SetGenerateMipmaps(m_enableMipGeneration); pDestinationTexture->SetMipMapResizeFilter(IMAGE_RESIZE_FILTER_LANCZOS3); pDestinationTexture->SetSourceSRGB(false); pDestinationTexture->SetEnableSRGB(false); pMaterialEntry->SpecularMapTextureIndex = (uint32)m_textures.GetSize(); m_textures.Add(pDestinationTexture); if (pSourceTexture->pSpecularMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pSpecularMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pSpecularMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->SetImage(0, &tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize specular map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->SetImage(0, pSourceTexture->pSpecularMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to set specular map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } // create normal map texture if (pSourceTexture->pNormalMap != nullptr) { TextureGenerator *pDestinationTexture = new TextureGenerator; pDestinationTexture->Create(TEXTURE_TYPE_2D, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, m_pGenerator->GetNormalMapSize(), m_pGenerator->GetNormalMapSize(), 1, 1); pDestinationTexture->SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_WRAP); pDestinationTexture->SetTextureFilter((pSourceTexture->AllowTextureFiltering) ? TEXTURE_FILTER_ANISOTROPIC : TEXTURE_FILTER_MIN_MAG_POINT_MIP_LINEAR); pDestinationTexture->SetTextureUsage(TEXTURE_USAGE_NORMAL_MAP); pDestinationTexture->SetSourcePremultipliedAlpha(false); pDestinationTexture->SetEnablePremultipliedAlpha(false); pDestinationTexture->SetEnableTextureCompression(m_enableTextureCompression); pDestinationTexture->SetGenerateMipmaps(m_enableMipGeneration); pDestinationTexture->SetMipMapResizeFilter(IMAGE_RESIZE_FILTER_LANCZOS3); pDestinationTexture->SetSourceSRGB(false); pDestinationTexture->SetEnableSRGB(false); pMaterialEntry->NormalMapTextureIndex = (uint32)m_textures.GetSize(); m_textures.Add(pDestinationTexture); if (pSourceTexture->pNormalMap->GetWidth() != pDestinationTexture->GetWidth() || pSourceTexture->pNormalMap->GetHeight() != pDestinationTexture->GetHeight()) { // copy and resize it Image tempImage; if (!tempImage.CopyAndResize(*pSourceTexture->pNormalMap, IMAGE_RESIZE_FILTER_LANCZOS3, pDestinationTexture->GetWidth(), pDestinationTexture->GetHeight(), 1) || !pDestinationTexture->SetImage(0, &tempImage)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to resize normal map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } else { // add as normal if (!pDestinationTexture->SetImage(0, pSourceTexture->pNormalMap)) { Log_ErrorPrintf("BlockPaletteCompiler::GenerateMaterials: Failed to set normal map for source texture '%s'", pSourceTexture->Name.GetCharArray()); return false; } } } } // now we have a material and texture array index, we can create the source texture info SourceTextureEntry *pSourceTextureEntry = new SourceTextureEntry; pSourceTextureEntry->SourceIndex = sourceTextureIndex; pSourceTextureEntry->MaterialIndex = materialIndex; pSourceTextureEntry->TextureArrayIndex = textureArrayIndex; pSourceTextureEntry->MinUV.Set(0.0f, 0.0f, (float)textureArrayIndex); pSourceTextureEntry->MaxUV.Set(1.0f, 1.0f, (float)textureArrayIndex); m_sourceTextures.Add(pSourceTextureEntry); } Log_DevPrintf("BlockPaletteCompiler::GenerateMaterials: Generated %u materials, %u textures", m_materials.GetSize(), m_textures.GetSize()); return true; } bool BlockPaletteCompiler::CompileBlockTypeVisual(const BlockPaletteGenerator::BlockType::VisualParameters *pSourceVisual, BlockTypeEntry::VisualParameters *pDestinationVisual) { if (pSourceVisual->Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL) { // find a matching external material uint32 materialIndex; for (materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { if (m_materials[materialIndex]->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL && m_materials[materialIndex]->ExternalMaterialName == pSourceVisual->MaterialName) break; } // not found? if (materialIndex == m_materials.GetSize()) { // create it MaterialEntry *pMaterialEntry = new MaterialEntry; pMaterialEntry->Type = DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL; pMaterialEntry->Flags = 0; pMaterialEntry->ExternalMaterialName = pSourceVisual->MaterialName; pMaterialEntry->TextureBlending = BLOCK_MESH_TEXTURE_BLENDING_COUNT; pMaterialEntry->TextureEffect = BLOCK_MESH_TEXTURE_EFFECT_NONE; pMaterialEntry->DiffuseMapTextureIndex = -1; pMaterialEntry->SpecularMapTextureIndex = -1; pMaterialEntry->NormalMapTextureIndex = -1; pMaterialEntry->TextureArraySize = 0; pMaterialEntry->TextureAtlasTileWidth = 0; pMaterialEntry->TextureAtlasTileHeight = 0; pMaterialEntry->TextureAtlasHPadding = 0; pMaterialEntry->TextureAtlasVPadding = 0; pMaterialEntry->TextureAtlasColumns = 0; pMaterialEntry->TextureAtlasRows = 0; pMaterialEntry->ScrollDirection.SetZero(); pMaterialEntry->ScrollSpeed = 0.0f; m_materials.Add(pMaterialEntry); } // return everything pDestinationVisual->Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL; pDestinationVisual->MaterialIndex = materialIndex; pDestinationVisual->Color = PixelFormatHelpers::ConvertSRGBToLinear(pSourceVisual->Color); pDestinationVisual->MinUV.Set(0.0f, 0.0f, 0.0f); pDestinationVisual->MaxUV.Set(1.0f, 1.0f, 0.0f); pDestinationVisual->AtlasUVRange.Set(0.0f, 0.0f, 0.0f, 0.0f); return true; } else if (pSourceVisual->Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR) { // is the colour translucent or not? DF_BLOCK_PALETTE_MATERIAL_TYPE searchMaterialType = ((pSourceVisual->Color >> 24) != 0xFF) ? DF_BLOCK_PALETTE_MATERIAL_TYPE_COLOR : DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_COLOR; // find matching material uint32 materialIndex; for (materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { if (m_materials[materialIndex]->Type == searchMaterialType) break; } if (materialIndex == m_materials.GetSize()) { // create it MaterialEntry *pMaterialEntry = new MaterialEntry; pMaterialEntry->Type = searchMaterialType; pMaterialEntry->Flags = 0; pMaterialEntry->TextureBlending = BLOCK_MESH_TEXTURE_BLENDING_COUNT; pMaterialEntry->TextureEffect = BLOCK_MESH_TEXTURE_EFFECT_NONE; pMaterialEntry->DiffuseMapTextureIndex = -1; pMaterialEntry->SpecularMapTextureIndex = -1; pMaterialEntry->NormalMapTextureIndex = -1; pMaterialEntry->TextureArraySize = 0; pMaterialEntry->TextureAtlasTileWidth = 0; pMaterialEntry->TextureAtlasTileHeight = 0; pMaterialEntry->TextureAtlasHPadding = 0; pMaterialEntry->TextureAtlasVPadding = 0; pMaterialEntry->TextureAtlasColumns = 0; pMaterialEntry->TextureAtlasRows = 0; pMaterialEntry->ScrollDirection.SetZero(); pMaterialEntry->ScrollSpeed = 0.0f; m_materials.Add(pMaterialEntry); } // return colour pDestinationVisual->Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_COLOR; pDestinationVisual->MaterialIndex = materialIndex; pDestinationVisual->Color = PixelFormatHelpers::ConvertSRGBToLinear(pSourceVisual->Color); pDestinationVisual->MinUV.Set(0.0f, 0.0f, 0.0f); pDestinationVisual->MaxUV.Set(1.0f, 1.0f, 0.0f); pDestinationVisual->AtlasUVRange.Set(0.0f, 0.0f, 0.0f, 0.0f); return true; } else if (pSourceVisual->Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE) { // find the matching source texture for (uint32 i = 0; i < m_sourceTextures.GetSize(); i++) { SourceTextureEntry *pSourceTextureEntry = m_sourceTextures[i]; if (pSourceTextureEntry->SourceIndex == pSourceVisual->TextureIndex) { // found it, copy through pDestinationVisual->Type = BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE; pDestinationVisual->MaterialIndex = pSourceTextureEntry->MaterialIndex; pDestinationVisual->Color = PixelFormatHelpers::ConvertSRGBToLinear(pSourceVisual->Color); // is this using a texture atlas? const MaterialEntry *pMaterialEntry = m_materials[pSourceTextureEntry->MaterialIndex]; if (pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TEXTURE_ATLAS_WITH_NORMAL_MAP || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_MASKED_TEXTURE_ATLAS_WITH_NORMAL_MAP || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS || pMaterialEntry->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_TEXTURE_ATLAS_WITH_NORMAL_MAP) { // fix up uvs pDestinationVisual->MinUV.Set(0.0f, 0.0f, 0.0f); pDestinationVisual->MaxUV.Set(1.0f, 1.0f, 0.0f); pDestinationVisual->AtlasUVRange.Set(pSourceTextureEntry->MinUV.x, pSourceTextureEntry->MinUV.y, pSourceTextureEntry->MaxUV.x, pSourceTextureEntry->MaxUV.y); } else { // copy uvs pDestinationVisual->MinUV = pSourceTextureEntry->MinUV; pDestinationVisual->MaxUV = pSourceTextureEntry->MaxUV; pDestinationVisual->AtlasUVRange.Set(0.0f, 0.0f, 0.0f, 0.0f); } return true; } } } // shouldn't be reached UnreachableCode(); return false; } bool BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas() { return false; /* uint32 i; uint32 textureIndex, arrayIndex, mipIndex, materialIndex; TextureEntry *pTextureEntry; for (textureIndex = 0; textureIndex < m_textures.GetSize(); textureIndex++) { pTextureEntry = m_textures[textureIndex]; if (pTextureEntry->GeneratedTexture.GetArraySize() > 1) { // found a texture array. TextureGenerator &textureGenerator = pTextureEntry->GeneratedTexture; uint32 tileWidth = textureGenerator.GetWidth(); uint32 tileHeight = textureGenerator.GetHeight(); uint32 tileCount = textureGenerator.GetArraySize(); Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Tile width: %u", tileWidth); Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Tile height: %u", tileHeight); Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Tile count: %u", tileCount); // padding size //uint32 paddingSize = 4; const uint32 paddingSize = 0; uint32 doublePaddingSize = paddingSize * 2; Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Padding: %u", paddingSize); // figure out how many columns and rows we'll need uint32 textureWidth, textureHeight; uint32 textureTileColumns, textureTileRows; // find the smallest texture size required to represent all of these columns and rows, with padding uint32 currentTextureSize = 1; for (;;) { if (currentTextureSize > 16384) { Log_WarningPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Skipping converting texture %u to atlas, size would exceed 16384", textureIndex); goto NEXTTEXTURE; } // enough to fit padding? if (currentTextureSize > paddingSize) { // using this texture size, how many tiles would we fit in each row/column uint32 fitTileCountX = (currentTextureSize - paddingSize) / (tileWidth + doublePaddingSize); uint32 fitTileCountY = (currentTextureSize - paddingSize) / (tileHeight + doublePaddingSize); // get total number of tiles uint32 nTotalTiles = fitTileCountX * fitTileCountY; if (nTotalTiles >= tileCount) { textureWidth = currentTextureSize; textureHeight = currentTextureSize; textureTileColumns = fitTileCountX; textureTileRows = fitTileCountY; Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Required rows/columns: %u x %u on a %u x %u texture", fitTileCountX, fitTileCountY, currentTextureSize, currentTextureSize); // reduce the height of the texture if it's not needed currentTextureSize = textureHeight; while (currentTextureSize > 1) { currentTextureSize /= 2; fitTileCountY = (currentTextureSize - paddingSize) / (tileHeight + doublePaddingSize); nTotalTiles = fitTileCountX * fitTileCountY; if (nTotalTiles >= tileCount) { textureHeight = currentTextureSize; textureTileRows = fitTileCountY; } else break; } if (textureWidth != textureHeight) Log_DevPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Reduced height of the texture to %u", textureHeight); // break out of upper loop break; } } // go to next pow2 currentTextureSize = Y_nextpow2(currentTextureSize + 1); } // calculate how many mip levels we can have uint32 nMipLevels = 0; uint32 currentWidth = textureWidth; uint32 currentHeight = textureHeight; uint32 currentTileWidth = tileWidth; uint32 currentTileHeight = tileHeight; uint32 currentPaddingSize = paddingSize; uint32 currentDoublePaddingSize = doublePaddingSize; for (; ;) { if ((currentPaddingSize + textureTileColumns * (currentTileWidth + currentDoublePaddingSize)) > currentWidth || (currentPaddingSize + textureTileRows * (currentTileHeight + currentDoublePaddingSize)) > currentHeight) { break; } if (currentWidth > 1) currentWidth /= 2; else break; if (currentHeight > 1) currentHeight /= 2; else break; if (currentTileWidth > 1) currentTileWidth /= 2; else break; if (currentTileHeight > 1) currentTileHeight /= 2; else break; if (currentPaddingSize > 1) { currentDoublePaddingSize = currentPaddingSize; currentPaddingSize /= 2; } else if (currentPaddingSize != 0) { break; } nMipLevels++; } DebugAssert(nMipLevels > 0); // create image array Image *pAtlasImages = new Image[nMipLevels]; // allocate images currentWidth = textureWidth; currentHeight = textureHeight; for (mipIndex = 0; mipIndex < nMipLevels; mipIndex++) { pAtlasImages[mipIndex].Create(BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, currentWidth, currentHeight, 1); // fill with white pixels (this will fill in the padding) Y_memset(pAtlasImages[mipIndex].GetData(), 0xFF, pAtlasImages[mipIndex].GetDataSize()); //Y_memset(pAtlasImages[mipIndex].GetData(), 0x00, pAtlasImages[mipIndex].GetDataSize()); if (currentWidth > 1) currentWidth /= 2; if (currentHeight > 1) currentHeight /= 2; } // copy in each image for (arrayIndex = 0; arrayIndex < textureGenerator.GetArraySize(); arrayIndex++) { // work out the row/column we're writing to uint32 tileRow = arrayIndex / textureTileColumns; uint32 tileColumn = arrayIndex % textureTileColumns; // get source image const Image *pOriginalSourceImage = textureGenerator.GetImage(arrayIndex, 0); // add each mip level currentWidth = textureWidth; currentHeight = textureHeight; currentTileWidth = tileWidth; currentTileHeight = tileHeight; currentPaddingSize = paddingSize; currentDoublePaddingSize = doublePaddingSize; for (mipIndex = 0; mipIndex < nMipLevels; mipIndex++) { // copy, and resize the image if necessary Image sourceImage; const Image *pMipImage = (mipIndex < textureGenerator.GetMipLevels()) ? textureGenerator.GetImage(arrayIndex, mipIndex) : NULL; if (pMipImage != NULL && pMipImage->GetWidth() == currentTileWidth && pMipImage->GetHeight() == currentTileHeight) { sourceImage.Copy(*pMipImage); } else { if (!sourceImage.CopyAndResize(*pOriginalSourceImage, IMAGE_RESIZE_FILTER_LANCZOS3, currentTileWidth, currentTileHeight, 1)) { Log_ErrorPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Failed to resize miplevel %u", mipIndex); delete[] pAtlasImages; return false; } } // get destination image Image &destinationImage = pAtlasImages[mipIndex]; // get destination pointer uint32 startX = currentPaddingSize + ((currentTileWidth + currentDoublePaddingSize) * tileColumn); uint32 startY = currentPaddingSize + ((currentTileHeight + currentDoublePaddingSize) * tileRow); // blit the pixels if (!destinationImage.Blit(startX, startY, sourceImage, 0, 0, currentTileWidth, currentTileHeight)) { Log_ErrorPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Failed to blit miplevel %u", mipIndex); delete[] pAtlasImages; return false; } // this is a bit of a hack, but due to texture filtering we're gonna repeat the first and last columns of the texture into the padding space. uint32 borderStartX, borderStartY; // left border borderStartX = startX - currentPaddingSize; borderStartY = startY; for (i = 0; i < currentPaddingSize; i++) destinationImage.Blit(borderStartX + i, borderStartY, sourceImage, 0, 0, 1, currentTileHeight); // right border borderStartX = startX + currentTileWidth; borderStartY = startY; for (i = 0; i < currentPaddingSize; i++) destinationImage.Blit(borderStartX + i, borderStartY, sourceImage, currentTileWidth - 1, 0, 1, currentTileHeight); // top border borderStartX = startX; borderStartY = startY - currentPaddingSize; for (i = 0; i < currentPaddingSize; i++) destinationImage.Blit(borderStartX, borderStartY + i, sourceImage, 0, 0, currentTileWidth, 1); // bottom border borderStartX = startX; borderStartY = startY + currentTileHeight; for (i = 0; i < currentPaddingSize; i++) destinationImage.Blit(borderStartX, borderStartY + i, sourceImage, 0, currentTileHeight - 1, currentTileWidth, 1); // halve everything for next miplevel if (currentWidth > 1) currentWidth /= 2; if (currentHeight > 1) currentHeight /= 2; if (currentTileWidth > 1) currentTileWidth /= 2; if (currentTileHeight > 1) currentTileHeight /= 2; if (currentPaddingSize > 1) { currentDoublePaddingSize = currentPaddingSize; currentPaddingSize /= 2; } } } // create the new atlas texture TextureEntry *pNewTextureEntry = new TextureEntry; pNewTextureEntry->TextureName = pTextureEntry->TextureName; if (!pNewTextureEntry->GeneratedTexture.Create(TEXTURE_TYPE_2D, BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, textureWidth, textureHeight, 1, nMipLevels, 1)) { Log_ErrorPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Failed to create texture generator."); delete[] pAtlasImages; delete pNewTextureEntry; return false; } // allocate and set miplevels TextureGenerator &generatedTexture = pNewTextureEntry->GeneratedTexture; for (mipIndex = 0; mipIndex < nMipLevels; mipIndex++) { if (!generatedTexture.SetImage(0, mipIndex, &pAtlasImages[mipIndex])) { Log_ErrorPrintf("BlockPaletteCompiler::ConvertTextureArraysToTextureAtlas: Failed to set miplevel %u", mipIndex); delete[] pAtlasImages; delete pNewTextureEntry; return false; } } // set max lod, and addressing modes generatedTexture.SetTextureFilter(TEXTURE_FILTER_MIN_MAG_MIP_POINT); generatedTexture.SetTextureAddressModeU(TEXTURE_ADDRESS_MODE_CLAMP); generatedTexture.SetTextureAddressModeV(TEXTURE_ADDRESS_MODE_CLAMP); // delete atlas images, no longer needed delete[] pAtlasImages; // set remaining fields pNewTextureEntry->IsTextureAtlas = true; pNewTextureEntry->TextureAtlasTileWidth = tileWidth; pNewTextureEntry->TextureAtlasTileHeight = tileHeight; pNewTextureEntry->TextureAtlasHPadding = paddingSize; pNewTextureEntry->TextureAtlasVPadding = paddingSize; pNewTextureEntry->TextureAtlasColumns = textureTileColumns; pNewTextureEntry->TextureAtlasRows = textureTileRows; // delete and swap delete pTextureEntry; m_textures[textureIndex] = pNewTextureEntry; // change any materials referencing this texture to be an atlas texture for (materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { MaterialEntry *pMaterialEntry = m_materials[materialIndex]; if (pMaterialEntry->AutoGenDiffuseMapTextureIndex == textureIndex || pMaterialEntry->AutoGenNormalMapTextureIndex == textureIndex || pMaterialEntry->AutoGenSpecularMapTextureIndex == textureIndex) { if (pMaterialEntry->MaterialType == DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_STATIC_TEXTURE_ARRAY) pMaterialEntry->MaterialType = DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_STATIC_TEXTURE_ATLAS; else if (pMaterialEntry->MaterialType == DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_SCROLLED_TEXTURE_ARRAY) pMaterialEntry->MaterialType = DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_SCROLLED_TEXTURE_ATLAS; else if (pMaterialEntry->MaterialType == DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_TEXTURE_ARRAY) pMaterialEntry->MaterialType = DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_STATIC_TEXTURE_ATLAS; else if (pMaterialEntry->MaterialType == DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SCROLLED_TEXTURE_ARRAY) pMaterialEntry->MaterialType = DF_BLOCK_PALETTE_MATERIAL_TYPE_AUTOGEN_TRANSPARENT_SCROLLED_TEXTURE_ATLAS; } } } NEXTTEXTURE: ; } ////////////////////////////////////////////////////////////////////////// // find a texture that's used const TextureEntry *pTextureEntry = NULL; if (pMaterialEntry->AutoGenDiffuseMapTextureIndex != 0xFFFFFFFF) pTextureEntry = m_textures[pMaterialEntry->AutoGenDiffuseMapTextureIndex]; else if (pMaterialEntry->AutoGenSpecularMapTextureIndex != 0xFFFFFFFF) pTextureEntry = m_textures[pMaterialEntry->AutoGenSpecularMapTextureIndex]; else if (pMaterialEntry->AutoGenNormalMapTextureIndex != 0xFFFFFFFF) pTextureEntry = m_textures[pMaterialEntry->AutoGenNormalMapTextureIndex]; // pull the image width/height, tile width/height uint32 tileIndex = inCubeFaceDef->TextureArrayIndex; uint32 imageWidth = pTextureEntry->GeneratedTexture.GetWidth(); uint32 imageHeight = pTextureEntry->GeneratedTexture.GetHeight(); uint32 tileWidth = pTextureEntry->TextureAtlasTileWidth; uint32 tileHeight = pTextureEntry->TextureAtlasTileHeight; uint32 paddingX = pTextureEntry->TextureAtlasHPadding; uint32 paddingY = pTextureEntry->TextureAtlasVPadding; uint32 columns = pTextureEntry->TextureAtlasColumns; uint32 rows = pTextureEntry->TextureAtlasRows; float inverseImageWidth = 1.0f / (float)imageWidth; float inverseImageHeight = 1.0f / (float)imageHeight; uint32 doublePaddingX = paddingX * 2; uint32 doublePaddingY = paddingY * 2; // work out tile column, and row DebugAssert(columns > 0 && rows > 0); uint32 tileColumn = tileIndex % columns; uint32 tileRow = tileIndex / columns; // calculate the rect of the atlas image uint32 startX = paddingX + ((tileWidth + doublePaddingX) * tileColumn); uint32 startY = paddingY + ((tileHeight + doublePaddingY) * tileRow); uint32 endX = startX + tileWidth; uint32 endY = startY + tileHeight; // work out the offset of the uvs //float uvOffsetX = 0.5f / (float)imageWidth; //float uvOffsetY = 0.5f / (float)imageHeight; const float uvOffsetX = 0.0f; const float uvOffsetY = 0.0f; // work out the uvs of it outCubeFaceDef->MinUV[0] = 0.0f; outCubeFaceDef->MinUV[1] = 0.0f; outCubeFaceDef->MaxUV[0] = 1.0f; outCubeFaceDef->MaxUV[1] = 1.0f; outCubeFaceDef->AtlasUVRange[0] = (float)startX * inverseImageWidth + uvOffsetX; outCubeFaceDef->AtlasUVRange[1] = (float)startY * inverseImageHeight + uvOffsetY; outCubeFaceDef->AtlasUVRange[2] = (float)(endX - startX) * inverseImageWidth - uvOffsetX; outCubeFaceDef->AtlasUVRange[3] = (float)(endY - startY) * inverseImageHeight - uvOffsetY; } ////////////////////////////////////////////////////////////////////////// return true;*/ } bool BlockPaletteCompiler::CompileBlockType(const BlockPaletteGenerator::BlockType *pBlockType) { // generate the main part of the block type entry BlockTypeEntry *pBTEntry = new BlockTypeEntry(); pBTEntry->BlockTypeIndex = pBlockType->BlockTypeIndex; pBTEntry->Name = pBlockType->Name; pBTEntry->Flags = 0; pBTEntry->ShapeType = pBlockType->ShapeType; // set flags if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_SOLID) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_SOLID | BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE; if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CAST_SHADOWS; if (pBlockType->BlockLightEmitterSettings.Enabled) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCK_LIGHT_EMITTER; if (pBlockType->PointLightEmitterSettings.Enabled) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_POINT_LIGHT_EMITTER; // set defaults on remaining fields Y_memzero(pBTEntry->CubeShapeFaces, sizeof(pBTEntry->CubeShapeFaces)); Y_memzero(&pBTEntry->SlabSettings, sizeof(pBTEntry->SlabSettings)); Y_memzero(&pBTEntry->PlaneSettings, sizeof(pBTEntry->PlaneSettings)); Y_memzero(&pBTEntry->MeshSettings, sizeof(pBTEntry->MeshSettings)); Y_memzero(&pBTEntry->BlockLightEmitterSettings, sizeof(pBTEntry->BlockLightEmitterSettings)); Y_memzero(&pBTEntry->PointLightEmitterSettings, sizeof(pBTEntry->PointLightEmitterSettings)); if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB || pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { // update flags // transparent + volume if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // cubes block visibility pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE | BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY; } else if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // slabs may not block visibility pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE | BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY; pBTEntry->SlabSettings.Height = pBlockType->SlabShapeSettings.Height; } else if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { // stairs don't block visibility pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE; } if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_VOLUME; if (pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_UNTILEABLE) pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_CUBE_SHAPE_UNTILEABLE; // do faces for (uint32 i = 0; i < CUBE_FACE_COUNT; i++) { const BlockPaletteGenerator::BlockType::CubeShapeFace *pSourceFace = &pBlockType->CubeShapeFaces[i]; BlockTypeEntry::CubeShapeFace *pDestinationFace = &pBTEntry->CubeShapeFaces[i]; if (pSourceFace->Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE && (m_pGenerator->GetTexture(pSourceFace->Visual.TextureIndex)->Blending == BLOCK_MESH_TEXTURE_BLENDING_MASKED || m_pGenerator->GetTexture(pSourceFace->Visual.TextureIndex)->Blending == BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT)) { pBTEntry->Flags &= ~(BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY); } else if (pSourceFace->Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_MATERIAL) { // assume materials don't block visibility pBTEntry->Flags &= ~(BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY); } // build visual if (!CompileBlockTypeVisual(&pSourceFace->Visual, &pDestinationFace->Visual)) return false; } } else if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { // build visual if (!CompileBlockTypeVisual(&pBlockType->PlaneShapeSettings.Visual, &pBTEntry->PlaneSettings.Visual)) return false; // is a visible block pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE; //if (pBlockType->PlaneShapeSettings.Visual.Type == BLOCK_MESH_BLOCK_TYPE_VISUAL_TYPE_TEXTURE && m_pGenerator->GetTexture(pBlockType->PlaneShapeSettings.Visual.TextureIndex)->Blending == BLOCK_MESH_TEXTURE_BLENDING_TRANSLUCENT) //pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY; pBTEntry->PlaneSettings.OffsetX = pBlockType->PlaneShapeSettings.OffsetX; pBTEntry->PlaneSettings.OffsetY = pBlockType->PlaneShapeSettings.OffsetY; pBTEntry->PlaneSettings.Width = pBlockType->PlaneShapeSettings.Width; pBTEntry->PlaneSettings.Height = pBlockType->PlaneShapeSettings.Height; pBTEntry->PlaneSettings.BaseRotation = pBlockType->PlaneShapeSettings.BaseRotation; pBTEntry->PlaneSettings.RepeatCount = pBlockType->PlaneShapeSettings.RepeatCount; pBTEntry->PlaneSettings.RepeatRotation = pBlockType->PlaneShapeSettings.RepeatRotation; } else if (pBTEntry->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { // look for the mesh in the list of names uint32 meshNameIndex = 0; while (meshNameIndex < m_meshNames.GetSize()) { if (m_meshNames[meshNameIndex]->CompareInsensitive(pBlockType->MeshShapeSettings.MeshName)) break; meshNameIndex++; } // add if not found if (meshNameIndex == m_meshNames.GetSize()) m_meshNames.Add(&pBlockType->MeshShapeSettings.MeshName); // set data pBTEntry->Flags |= BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE; pBTEntry->MeshSettings.MeshNameIndex = meshNameIndex; pBTEntry->MeshSettings.Scale = pBlockType->MeshShapeSettings.Scale; } // block light emitter if (pBlockType->BlockLightEmitterSettings.Enabled) pBTEntry->BlockLightEmitterSettings.Radius = pBlockType->BlockLightEmitterSettings.Radius; // point light emitter if (pBlockType->PointLightEmitterSettings.Enabled) { pBTEntry->PointLightEmitterSettings.Offset = pBlockType->PointLightEmitterSettings.Offset; pBTEntry->PointLightEmitterSettings.Color = PixelFormatHelpers::ConvertSRGBToLinear(pBlockType->PointLightEmitterSettings.Color); pBTEntry->PointLightEmitterSettings.Brightness = pBlockType->PointLightEmitterSettings.Brightness; pBTEntry->PointLightEmitterSettings.Range = pBlockType->PointLightEmitterSettings.Range; pBTEntry->PointLightEmitterSettings.Falloff = pBlockType->PointLightEmitterSettings.Falloff; } // Log_DevPrintf("BlockType '%s': [ %i, %i, %i, %i, %i, %i ], [ %i, %i, %i, %i, %i, %i ]", // pBTEntry->Name.GetCharArray(), // (int32)pBTEntry->FaceMaterialIndices[0], (int32)pBTEntry->FaceMaterialIndices[1], (int32)pBTEntry->FaceMaterialIndices[2], // (int32)pBTEntry->FaceMaterialIndices[3], (int32)pBTEntry->FaceMaterialIndices[4], (int32)pBTEntry->FaceMaterialIndices[5], // (int32)pBTEntry->FaceTextureArrayIndices[0], (int32)pBTEntry->FaceTextureArrayIndices[1], (int32)pBTEntry->FaceTextureArrayIndices[2], // (int32)pBTEntry->FaceTextureArrayIndices[3], (int32)pBTEntry->FaceTextureArrayIndices[4], (int32)pBTEntry->FaceTextureArrayIndices[5] // ); m_blockTypes.Add(pBTEntry); return true; } bool BlockPaletteCompiler::WriteHeader(ByteStream *pStream) { // write it out to the file DF_BLOCK_PALETTE_LIST_HEADER blockListHeader; blockListHeader.Magic = DF_BLOCK_PALETTE_HEADER_MAGIC; blockListHeader.HeaderSize = sizeof(blockListHeader); blockListHeader.BlockTypeCount = m_blockTypes.GetSize(); blockListHeader.TextureCount = m_textures.GetSize(); blockListHeader.MaterialCount = m_materials.GetSize(); blockListHeader.MeshCount = m_meshNames.GetSize(); if (!pStream->Write2(&blockListHeader, sizeof(blockListHeader))) return false; return true; } bool BlockPaletteCompiler::WriteBlockTypes(ByteStream *pStream, ChunkFileWriter &cfw) { // for block types cfw.BeginChunk(DF_BLOCK_PALETTE_CHUNK_BLOCK_TYPES); for (uint32 i = 0; i < m_blockTypes.GetSize(); i++) { const BlockTypeEntry *inBlockType = m_blockTypes[i]; DF_BLOCK_PALETTE_BLOCK_TYPE outBlockType; outBlockType.BlockTypeIndex = inBlockType->BlockTypeIndex; outBlockType.NameStringIndex = cfw.AddString(inBlockType->Name); outBlockType.Flags = inBlockType->Flags; outBlockType.ShapeType = inBlockType->ShapeType; // initialize defaults Y_memzero(outBlockType.CubeShapeFaces, sizeof(outBlockType.CubeShapeFaces)); // fill in data if (inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE || inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB || inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_STAIRS) { if (inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) outBlockType.SlabSettings.Height = inBlockType->SlabSettings.Height; for (uint32 j = 0; j < CUBE_FACE_COUNT; j++) { const BlockTypeEntry::CubeShapeFace *inCubeFaceDef = &inBlockType->CubeShapeFaces[j]; DF_BLOCK_PALETTE_BLOCK_TYPE::CubeShapeFace *outCubeFaceDef = &outBlockType.CubeShapeFaces[j]; outCubeFaceDef->Visual.Type = inCubeFaceDef->Visual.Type; outCubeFaceDef->Visual.MaterialIndex = inCubeFaceDef->Visual.MaterialIndex; outCubeFaceDef->Visual.Color = inCubeFaceDef->Visual.Color; inCubeFaceDef->Visual.MinUV.Store(outCubeFaceDef->Visual.MinUV); inCubeFaceDef->Visual.MaxUV.Store(outCubeFaceDef->Visual.MaxUV); inCubeFaceDef->Visual.AtlasUVRange.Store(outCubeFaceDef->Visual.AtlasUVRange); } } else if (inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_PLANE) { const BlockTypeEntry::PlaneShape *inPlaneSettings = &inBlockType->PlaneSettings; DF_BLOCK_PALETTE_BLOCK_TYPE::PlaneShape *outPlaneSettings = &outBlockType.PlaneSettings; outPlaneSettings->Visual.Type = inPlaneSettings->Visual.Type; outPlaneSettings->Visual.MaterialIndex = inPlaneSettings->Visual.MaterialIndex; outPlaneSettings->Visual.Color = inPlaneSettings->Visual.Color; inPlaneSettings->Visual.MinUV.Store(outPlaneSettings->Visual.MinUV); inPlaneSettings->Visual.MaxUV.Store(outPlaneSettings->Visual.MaxUV); inPlaneSettings->Visual.AtlasUVRange.Store(outPlaneSettings->Visual.AtlasUVRange); outPlaneSettings->OffsetX = inPlaneSettings->OffsetX; outPlaneSettings->OffsetY = inPlaneSettings->OffsetY; outPlaneSettings->Width = inPlaneSettings->Width; outPlaneSettings->Height = inPlaneSettings->Height; outPlaneSettings->BaseRotation = inPlaneSettings->BaseRotation; outPlaneSettings->RepeatCount = inPlaneSettings->RepeatCount; outPlaneSettings->RepeatRotation = inPlaneSettings->RepeatRotation; } else if (inBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { const BlockTypeEntry::MeshShape *inMeshSettings = &inBlockType->MeshSettings; DF_BLOCK_PALETTE_BLOCK_TYPE::MeshShape *outMeshSettings = &outBlockType.MeshSettings; outMeshSettings->MeshIndex = inMeshSettings->MeshNameIndex; outMeshSettings->Scale = inMeshSettings->Scale; } // block light emitter outBlockType.BlockLightEmitterSettings.Radius = inBlockType->BlockLightEmitterSettings.Radius; // point light emitter inBlockType->PointLightEmitterSettings.Offset.Store(outBlockType.PointLightEmitterSettings.Offset); outBlockType.PointLightEmitterSettings.Color = inBlockType->PointLightEmitterSettings.Color; outBlockType.PointLightEmitterSettings.Brightness = inBlockType->PointLightEmitterSettings.Brightness; outBlockType.PointLightEmitterSettings.Range = inBlockType->PointLightEmitterSettings.Range; outBlockType.PointLightEmitterSettings.Falloff = inBlockType->PointLightEmitterSettings.Falloff; cfw.WriteChunkData(&outBlockType, sizeof(outBlockType)); } cfw.EndChunk(); return true; } bool BlockPaletteCompiler::WriteTextures(ByteStream *pStream, ChunkFileWriter &cfw, TEXTURE_PLATFORM texturePlatform) { // strip alpha channels from non-blended diffuse textures, specular textures, and normal maps for (uint32 i = 0; i < m_materials.GetSize(); i++) { if (m_materials[i]->TextureBlending == BLOCK_MESH_TEXTURE_BLENDING_NONE && m_materials[i]->DiffuseMapTextureIndex >= 0 && !m_textures[m_materials[i]->DiffuseMapTextureIndex]->RemoveAlphaChannel()) { Log_ErrorPrintf("BlockPaletteCompiler::WriteTextures: Could not remove alpha channel from diffuse texture %u", i); return false; } if (m_materials[i]->SpecularMapTextureIndex >= 0 && !m_textures[m_materials[i]->SpecularMapTextureIndex]->RemoveAlphaChannel()) { Log_ErrorPrintf("BlockPaletteCompiler::WriteTextures: Could not remove alpha channel from specular texture %u", i); return false; } if (m_materials[i]->NormalMapTextureIndex >= 0 && !m_textures[m_materials[i]->NormalMapTextureIndex]->RemoveAlphaChannel()) { Log_ErrorPrintf("BlockPaletteCompiler::WriteTextures: Could not remove alpha channel from normal texture %u", i); return false; } } // for textures cfw.BeginChunk(DF_BLOCK_PALETTE_CHUNK_TEXTURES); if (m_textures.GetSize() > 0) { ByteStream **ppGeneratedTextureStreams = new ByteStream *[m_textures.GetSize()]; uint32 nGeneratedTextureStreams = 0; uint32 nUsedTextureStreams = 0; for (uint32 i = 0; i < m_textures.GetSize(); i++) { TextureGenerator *pTextureGenerator = m_textures[i]; Log_DevPrintf("BlockPaletteCompiler::WriteTextures: Compiling texture %u (%ux%u %u subtextures)", i, pTextureGenerator->GetWidth(), pTextureGenerator->GetHeight(), pTextureGenerator->GetArraySize()); ppGeneratedTextureStreams[nGeneratedTextureStreams] = ByteStream_CreateGrowableMemoryStream(NULL, 0); if (!pTextureGenerator->Compile(ppGeneratedTextureStreams[nGeneratedTextureStreams], texturePlatform)) { Log_ErrorPrintf("BlockPaletteCompiler::WriteTextures: Failed to compile texture %u", i); for (uint32 j = 0; j < i; j++) ppGeneratedTextureStreams[j]->Release(); delete[] ppGeneratedTextureStreams; return false; } nGeneratedTextureStreams++; } uint32 currentTextureOffset = sizeof(DF_BLOCK_PALETTE_TEXTURE) * m_textures.GetSize(); for (uint32 i = 0; i < m_textures.GetSize(); i++) { DF_BLOCK_PALETTE_TEXTURE outTexture; outTexture.TextureOffset = currentTextureOffset; outTexture.TextureSize = (uint32)ppGeneratedTextureStreams[nUsedTextureStreams]->GetSize(); currentTextureOffset += outTexture.TextureSize; nUsedTextureStreams++; cfw.WriteChunkData(&outTexture, sizeof(outTexture)); } // write texture data DebugAssert(nUsedTextureStreams == nGeneratedTextureStreams); for (uint32 i = 0; i < nUsedTextureStreams; i++) { static const uint32 CHUNKSIZE = 4096; byte buffer[CHUNKSIZE]; ByteStream *pTextureStream = ppGeneratedTextureStreams[i]; uint32 remaining = (uint32)pTextureStream->GetSize(); pTextureStream->SeekAbsolute(0); while (remaining > 0) { uint32 toCopy = Min(CHUNKSIZE, remaining); if (!pTextureStream->Read2(buffer, toCopy)) { delete[] ppGeneratedTextureStreams; return false; } remaining -= toCopy; cfw.WriteChunkData(buffer, toCopy); } pTextureStream->Release(); } delete[] ppGeneratedTextureStreams; } cfw.EndChunk(); return true; } bool BlockPaletteCompiler::WriteMaterials(ByteStream *pStream, ChunkFileWriter &cfw) { // for materials cfw.BeginChunk(DF_BLOCK_PALETTE_CHUNK_MATERIALS); for (uint32 i = 0; i < m_materials.GetSize(); i++) { const MaterialEntry *inMaterial = m_materials[i]; DF_BLOCK_PALETTE_MATERIAL outMaterial; outMaterial.MaterialType = inMaterial->Type; outMaterial.MaterialFlags = inMaterial->Flags; if (inMaterial->Type != DF_BLOCK_PALETTE_MATERIAL_TYPE_EXTERNAL) { SmallString materialName; materialName.AppendString("autogen:"); // build material name if (inMaterial->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_COLOR) materialName.AppendString("color"); else if (inMaterial->Type == DF_BLOCK_PALETTE_MATERIAL_TYPE_TRANSLUCENT_COLOR) materialName.AppendString("color:translucent"); else materialName.AppendFormattedString("texture:%s:%s", NameTable_GetNameString(NameTables::BlockMeshTextureBlending, inMaterial->TextureBlending), NameTable_GetNameString(NameTables::BlockMeshTextureEffect, inMaterial->TextureEffect)); outMaterial.MaterialNameStringIndex = cfw.AddString(materialName); } else { // use external material name outMaterial.MaterialNameStringIndex = cfw.AddString(inMaterial->ExternalMaterialName); } outMaterial.DiffuseMapTextureIndex = inMaterial->DiffuseMapTextureIndex; outMaterial.SpecularMapTextureIndex = inMaterial->SpecularMapTextureIndex; outMaterial.NormalMapTextureIndex = inMaterial->NormalMapTextureIndex; float2 textureScrollVector(inMaterial->ScrollDirection * inMaterial->ScrollSpeed); textureScrollVector.Store(outMaterial.TextureScrollVector); cfw.WriteChunkData(&outMaterial, sizeof(outMaterial)); } cfw.EndChunk(); return true; } bool BlockPaletteCompiler::WriteMeshes(ByteStream *pStream, ChunkFileWriter &cfw) { cfw.BeginChunk(DF_BLOCK_PALETTE_CHUNK_MESHES); for (uint32 i = 0; i < m_meshNames.GetSize(); i++) { DF_BLOCK_PALETTE_MESH outMesh; outMesh.MeshNameStringIndex = cfw.AddString(*m_meshNames[i]); cfw.WriteChunkData(&outMesh, sizeof(outMesh)); } cfw.EndChunk(); return true; } bool BlockPaletteGenerator::Compile(TEXTURE_PLATFORM texturePlatform, ByteStream *pOutputStream) const { BlockPaletteCompiler compiler(this); return compiler.Compile(texturePlatform, pOutputStream); } static bool LoadImportedAtlasTexture(Image *pDecodedImage, const char *textureFileName) { Log_DevPrintf("Loading texture atlas '%s'", textureFileName); AutoReleasePtr<ByteStream> pInputTextureStream = FileSystem::OpenFile(textureFileName, BYTESTREAM_OPEN_READ); if (pInputTextureStream == NULL) { Log_ErrorPrintf("Failed to open '%s'", textureFileName); return false; } ImageCodec *pImageCodec = ImageCodec::GetImageCodecForStream(textureFileName, pInputTextureStream); if (pImageCodec == NULL) return false; if (!pImageCodec->DecodeImage(pDecodedImage, textureFileName, pInputTextureStream)) return false; // convert to something usable if (pDecodedImage->GetPixelFormat() != BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT && !pDecodedImage->ConvertPixelFormat(BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT)) return false; return true; } static bool SplitImportedTextureAtlas(const Image *pAtlasImage, uint32 textureTileWidth, uint32 textureTileHeight, uint32 textureTileIndex, Image *pSplitImage) { Log_DevPrintf("Splitting texture atlas at tile %u", textureTileIndex); DebugAssert(pAtlasImage->GetPixelFormat() == BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT); // make sure the tile index is valid uint32 decodedImageTilesPerRow = pAtlasImage->GetWidth() / textureTileWidth; uint32 decodedImageRows = pAtlasImage->GetHeight() / textureTileHeight; uint32 tileRow = textureTileIndex / decodedImageTilesPerRow; uint32 tileCol = textureTileIndex % decodedImageTilesPerRow; if (tileRow >= decodedImageRows) return false; // create a new image using the texture tile width + height pSplitImage->Create(BLOCK_MESH_BLOCK_LIST_TEXTURE_INTERNAL_FORMAT, textureTileWidth, textureTileHeight, 1); // get start point in source image uint32 decodedImageRowPitch = pAtlasImage->GetDataRowPitch(); const byte *pDecodedImagePointer = pAtlasImage->GetData() + (tileRow * textureTileHeight * decodedImageRowPitch) + (4 * tileCol * textureTileWidth); // get start point in output image DebugAssert(pSplitImage->GetDataRowPitch() == 4 * textureTileWidth); uint32 splitImageRowPitch = pSplitImage->GetDataRowPitch(); byte *pSplitImagePointer = pSplitImage->GetData(); // blit the pixels for (uint32 i = 0; i < textureTileHeight; i++) { Y_memcpy(pSplitImagePointer, pDecodedImagePointer, 4 * textureTileWidth); pDecodedImagePointer += decodedImageRowPitch; pSplitImagePointer += splitImageRowPitch; } // all done return true; } bool BlockPaletteGenerator::ImportTextureAtlas(const char *namePrefix, const char *diffuseMapFileName, const char *specularMapFileName, const char *normalMapFileName, uint32 tilesWide, uint32 tilesHigh, const bool *pImportTileIndices, uint32 maxImportTileIndices, String *pOutTextureNames, uint32 maxOutTextureNames) { uint32 i; SmallString textureName; bool hasDiffuseMap; bool hasSpecularMap; bool hasNormalMap; int32 minImageWidth, minImageHeight; int32 maxImageWidth, maxImageHeight; Image diffuseMapImage; Image specularMapImage; Image normalMapImage; Image splitImage; // load the textures minImageWidth = minImageHeight = INT_MAX; maxImageWidth = maxImageHeight = -INT_MAX; // diffuse map hasDiffuseMap = (diffuseMapFileName != NULL); if (hasDiffuseMap) { if (!LoadImportedAtlasTexture(&diffuseMapImage, diffuseMapFileName)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to import diffuse map texture '%s'", diffuseMapFileName); return false; } minImageWidth = Min(minImageWidth, (int32)diffuseMapImage.GetWidth()); minImageHeight = Min(minImageHeight, (int32)diffuseMapImage.GetHeight()); maxImageWidth = Max(maxImageWidth, (int32)diffuseMapImage.GetWidth()); maxImageHeight = Max(maxImageWidth, (int32)diffuseMapImage.GetHeight()); } // specular map hasSpecularMap = (specularMapFileName != NULL); if (hasSpecularMap) { if (!LoadImportedAtlasTexture(&specularMapImage, specularMapFileName)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to import specular map texture '%s'", specularMapFileName); return false; } minImageWidth = Min(minImageWidth, (int32)specularMapImage.GetWidth()); minImageHeight = Min(minImageHeight, (int32)specularMapImage.GetHeight()); maxImageWidth = Max(maxImageWidth, (int32)specularMapImage.GetWidth()); maxImageHeight = Max(maxImageWidth, (int32)specularMapImage.GetHeight()); } // normal map hasNormalMap = (normalMapFileName != NULL); if (hasNormalMap) { if (!LoadImportedAtlasTexture(&normalMapImage, normalMapFileName)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to import normal map texture '%s'", normalMapFileName); return false; } minImageWidth = Min(minImageWidth, (int32)normalMapImage.GetWidth()); minImageHeight = Min(minImageHeight, (int32)normalMapImage.GetHeight()); maxImageWidth = Max(maxImageWidth, (int32)normalMapImage.GetWidth()); maxImageHeight = Max(maxImageWidth, (int32)normalMapImage.GetHeight()); } // no images? if (!hasDiffuseMap && !hasSpecularMap && !hasNormalMap) return false; // images should all be of the same dimension if (minImageWidth != maxImageWidth || minImageHeight != maxImageHeight) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: One or more textures are of differing dimensions: min (%i,%i) vs max (%i,%i)", minImageWidth, minImageHeight, maxImageWidth, maxImageHeight); return false; } // determine the number of tiles in the image uint32 imageWidth = (uint32)maxImageWidth; uint32 imageHeight = (uint32)maxImageHeight; uint32 tileWidth = imageWidth / tilesWide; uint32 tileHeight = imageHeight / tilesHigh; // determine total number of images uint32 nTotalTiles = tilesWide * tilesHigh; if (nTotalTiles < 1) return false; // import each image for (i = 0; i < nTotalTiles; i++) { if (pImportTileIndices != NULL && (i >= maxImportTileIndices || !pImportTileIndices[i])) continue; // create texture textureName.Format("%s_tile_%u", namePrefix, i); const Texture *pTexture = CreateTexture(textureName, BLOCK_MESH_TEXTURE_BLENDING_NONE, true); if (pTexture == nullptr) return false; // add maps to texture if (hasDiffuseMap) { if (!SplitImportedTextureAtlas(&diffuseMapImage, tileWidth, tileHeight, i, &splitImage) || !SetTextureDiffuseMap(pTexture->Index, &splitImage)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to split or set diffuse map tile %u", i); return false; } } if (hasSpecularMap) { if (!SplitImportedTextureAtlas(&specularMapImage, tileWidth, tileHeight, i, &splitImage) || !SetTextureDiffuseMap(pTexture->Index, &splitImage)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to split or set specular map tile %u", i); return false; } } if (hasNormalMap) { if (!SplitImportedTextureAtlas(&normalMapImage, tileWidth, tileHeight, i, &splitImage) || !SetTextureDiffuseMap(pTexture->Index, &splitImage)) { Log_ErrorPrintf("BlockPaletteGenerator::ImportTextureAtlas: Failed to split or set normal map tile %u", i); return false; } } // set imported index if (pOutTextureNames != NULL && i < maxOutTextureNames) pOutTextureNames[i] = m_textures[pTexture->Index]->Name; } // done return true; } // Interface BinaryBlob *ResourceCompiler::CompileBlockPalette(ResourceCompilerCallbacks *pCallbacks, TEXTURE_PLATFORM platform, const char *name) { SmallString sourceFileName; sourceFileName.Format("%s.blp.zip", name); BinaryBlob *pSourceData = pCallbacks->GetFileContents(sourceFileName); if (pSourceData == nullptr) { Log_ErrorPrintf("ResourceCompiler::CompileBlockPalette: Failed to read '%s'", sourceFileName.GetCharArray()); return nullptr; } ByteStream *pStream = ByteStream_CreateReadOnlyMemoryStream(pSourceData->GetDataPointer(), pSourceData->GetDataSize()); BlockPaletteGenerator *pGenerator = new BlockPaletteGenerator(); if (!pGenerator->Load(sourceFileName, pStream)) { delete pGenerator; pStream->Release(); pSourceData->Release(); return nullptr; } pStream->Release(); pSourceData->Release(); ByteStream *pOutputStream = ByteStream_CreateGrowableMemoryStream(); if (!pGenerator->Compile(platform, pOutputStream)) { pOutputStream->Release(); delete pGenerator; return nullptr; } BinaryBlob *pReturnBlob = BinaryBlob::CreateFromStream(pOutputStream); pOutputStream->Release(); delete pGenerator; return pReturnBlob; } <file_sep>/Engine/Source/Renderer/Shaders/DownsampleShader.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/Shaders/DownsampleShader.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderCompilerFrontend.h" #include "Renderer/ShaderProgram.h" DEFINE_SHADER_COMPONENT_INFO(DownsampleShader); BEGIN_SHADER_COMPONENT_PARAMETERS(DownsampleShader) DEFINE_SHADER_COMPONENT_PARAMETER("InputTexture", SHADER_PARAMETER_TYPE_TEXTURE2D) DEFINE_SHADER_COMPONENT_PARAMETER("MipLevel", SHADER_PARAMETER_TYPE_UINT) END_SHADER_COMPONENT_PARAMETERS() void DownsampleShader::SetProgramParameters(GPUContext *pContext, ShaderProgram *pShaderProgram, GPUTexture2D *pInputTexture, uint32 mipLevel) { pShaderProgram->SetBaseShaderParameterTexture(pContext, 0, pInputTexture, g_pRenderer->GetFixedResources()->GetPointSamplerState()); pShaderProgram->SetBaseShaderParameterValue(pContext, 1, SHADER_PARAMETER_TYPE_UINT, &mipLevel); } bool DownsampleShader::IsValidPermutation(uint32 globalShaderFlags, const ShaderComponentTypeInfo *pBaseShaderTypeInfo, uint32 baseShaderFlags, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const MaterialShader *pMaterialShader, uint32 materialShaderFlags) { if (pVertexFactoryTypeInfo != nullptr || pMaterialShader != nullptr) return false; return true; } bool DownsampleShader::FillShaderCompilerParameters(uint32 globalShaderFlags, uint32 baseShaderFlags, uint32 vertexFactoryFlags, ShaderCompilerParameters *pParameters) { // Requires feature level SM4 if (pParameters->FeatureLevel < RENDERER_FEATURE_LEVEL_SM4) return false; // Entry points pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_VERTEX_SHADER, "shaders/base/ScreenQuadVertexShader.hlsl", "Main"); pParameters->SetStageEntryPoint(SHADER_PROGRAM_STAGE_PIXEL_SHADER, "shaders/base/DownsamplePixelShader.hlsl", "PSMain"); // vertex elements -- if not generate on gpu /*static const GPU_VERTEX_ELEMENT_DESC screenQuadVertexElementDesc[] = { { GPU_VERTEX_ELEMENT_SEMANTIC_POSITION, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT3, 0, 0, 0 }, { GPU_VERTEX_ELEMENT_SEMANTIC_TEXCOORD, 0, GPU_VERTEX_ELEMENT_TYPE_FLOAT2, 0, sizeof(float3), 0 } }; for (uint32 i = 0; i < countof(screenQuadVertexElementDesc); i++) pShaderCompiler->AddVertexAttribute(&screenQuadVertexElementDesc[i]);*/ return true; } <file_sep>/Engine/Source/MathLib/CollisionDetection.cpp #include "MathLib/CollisionDetection.h" #include "MathLib/SIMDVectorf.h" bool CollisionDetection::PointInTriangle(const Vector3f &p, const Vector3f &v0, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal) { SIMDVector3f u(e0); SIMDVector3f v(e1); SIMDVector3f w = p - v0; SIMDVector3f vCrossW = v.Cross(w); SIMDVector3f vCrossU = v.Cross(u); if (vCrossW.Dot(vCrossU) < 0.0f) return false; SIMDVector3f uCrossW = u.Cross(w); SIMDVector3f uCrossV = u.Cross(v); if (uCrossW.Dot(uCrossV) < 0.0f) return false; float denon = uCrossV.Length(); float invDenom = 1.0f / denon; float r = vCrossW.Length() * invDenom; float t = uCrossW.Length() * invDenom; return (r <= 1.0f && t <= 1.0f && (r + t) <= 1.0f); } bool CollisionDetection::RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds) { bool inside = true; SIMDVector3f maxT(-1.0f, -1.0f, -1.0f); Vector3f hitLocation; if (rayOrigin.x < minBounds.x) { hitLocation.x = minBounds.x; inside = false; if (rayDirection.x != 0.0f) maxT.x = (minBounds.x - rayOrigin.x) / rayDirection.x; } else if (rayOrigin.x > maxBounds.x) { hitLocation.x = maxBounds.x; inside = false; if (rayDirection.x != 0.0f) maxT.x = (maxBounds.x - rayOrigin.x) / rayDirection.x; } if (rayOrigin.y < minBounds.y) { hitLocation.y = minBounds.y; inside = false; if (rayDirection.y != 0.0f) maxT.y = (minBounds.y - rayOrigin.y) / rayDirection.y; } else if (rayOrigin.y > maxBounds.y) { hitLocation.y = maxBounds.y; inside = false; if (rayDirection.y != 0.0f) maxT.y = (maxBounds.y - rayOrigin.y) / rayDirection.y; } if (rayOrigin.z < minBounds.z) { hitLocation.z = minBounds.z; inside = false; if (rayDirection.z != 0.0f) maxT.z = (minBounds.z - rayOrigin.z) / rayDirection.z; } else if (rayOrigin.z > maxBounds.z) { hitLocation.z = maxBounds.z; inside = false; if (rayDirection.z != 0.0f) maxT.z = (maxBounds.z - rayOrigin.z) / rayDirection.z; } if (inside) return true; uint32 plane = 0; if (maxT[1] > maxT[plane]) plane = 1; if (maxT[2] > maxT[plane]) plane = 2; if (maxT[plane] < 0.0f) return false; for (uint32 i = 0; i < 3; ++i) { if (i != plane) { hitLocation[i] = rayOrigin[i] + maxT[plane] * rayDirection[i]; if ((hitLocation[i] < minBounds[i]) || (hitLocation[i] > maxBounds[i])) { return false; } } } return (SIMDVector3f(hitLocation) - SIMDVector3f(rayOrigin)).SquaredLength() <= Math::Square(rayDistance); } bool CollisionDetection::RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) { bool inside = true; SIMDVector3f maxT(-1.0f, -1.0f, -1.0f); Vector3f hitLocation; if (rayOrigin.x < minBounds.x) { hitLocation.x = minBounds.x; inside = false; if (rayDirection.x != 0.0f) maxT.x = (minBounds.x - rayOrigin.x) / rayDirection.x; } else if (rayOrigin.x > maxBounds.x) { hitLocation.x = maxBounds.x; inside = false; if (rayDirection.x != 0.0f) maxT.x = (maxBounds.x - rayOrigin.x) / rayDirection.x; } if (rayOrigin.y < minBounds.y) { hitLocation.y = minBounds.y; inside = false; if (rayDirection.y != 0.0f) maxT.y = (minBounds.y - rayOrigin.y) / rayDirection.y; } else if (rayOrigin.y > maxBounds.y) { hitLocation.y = maxBounds.y; inside = false; if (rayDirection.y != 0.0f) maxT.y = (maxBounds.y - rayOrigin.y) / rayDirection.y; } if (rayOrigin.z < minBounds.z) { hitLocation.z = minBounds.z; inside = false; if (rayDirection.z != 0.0f) maxT.z = (minBounds.z - rayOrigin.z) / rayDirection.z; } else if (rayOrigin.z > maxBounds.z) { hitLocation.z = maxBounds.z; inside = false; if (rayDirection.z != 0.0f) maxT.z = (maxBounds.z - rayOrigin.z) / rayDirection.z; } if (inside) return true; uint32 plane = 0; if (maxT[1] > maxT[plane]) plane = 1; if (maxT[2] > maxT[plane]) plane = 2; if (maxT[plane] < 0.0f) return false; for (uint32 i = 0; i < 3; ++i) { if (i != plane) { hitLocation[i] = rayOrigin[i] + maxT[plane] * rayDirection[i]; if ((hitLocation[i] < minBounds[i]) || (hitLocation[i] > maxBounds[i])) { return false; } } } if ((SIMDVector3f(hitLocation) - SIMDVector3f(rayOrigin)).SquaredLength() > Math::Square(rayDistance)) return false; contactNormal.SetZero(); contactNormal[plane] = (rayDirection[plane] > 0.0f) ? -1.0f : 1.0f; contactPoint = hitLocation; return true; } bool CollisionDetection::RayIntersectsAABox(const Vector3f &rayOrigin, const Vector3f &inverseRayDirection, const float rayDistance, const Vector3f &minBounds, const Vector3f &maxBounds, float *pContactTime, CUBE_FACE *pContactFace) { static const uint32 faceIndices[3][2] = { { CUBE_FACE_LEFT, CUBE_FACE_RIGHT }, { CUBE_FACE_FRONT, CUBE_FACE_BACK }, { CUBE_FACE_BOTTOM, CUBE_FACE_TOP } }; SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_inverseRayDirection(inverseRayDirection); SIMDVector3f v1 = (SIMDVector3f(minBounds) - rayOrigin) * vec_inverseRayDirection; SIMDVector3f v2 = (SIMDVector3f(maxBounds) - rayOrigin) * vec_inverseRayDirection; uint32 i; float tmin = -Y_FLT_INFINITE, tmax = Y_FLT_INFINITE; uint32 minHitFace = 0, maxHitFace = 0; for (i = 0; i < 3; i++) { const uint32 *pFaceIndices = faceIndices[i]; const float &t1 = v1[i]; const float &t2 = v2[i]; if (t1 < t2) { if (t1 > tmin) { tmin = t1; minHitFace = pFaceIndices[0]; } if (t2 < tmax) { tmax = t2; maxHitFace = pFaceIndices[1]; } } else { if (t2 > tmin) { tmin = t2; minHitFace = pFaceIndices[1]; } if (t1 < tmax) { tmax = t1; maxHitFace = pFaceIndices[0]; } } } if (tmin < tmax) { if (tmin > 0) { if (tmin <= rayDistance) { *pContactTime = tmin; *pContactFace = (CUBE_FACE)minHitFace; return true; } } else if (tmax > 0) { if (tmax <= rayDistance) { *pContactTime = tmax; *pContactFace = (CUBE_FACE)maxHitFace; return true; } } } return false; } bool CollisionDetection::RayIntersectsSphere(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &sphereCenter, const float sphereRadius) { // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_rayDirection(rayDirection); float a = vec_rayDirection.Dot(vec_rayDirection); float b = 2.0f * vec_rayDirection.Dot(vec_rayOrigin); float c = vec_rayOrigin.Dot(vec_rayOrigin) - Math::Square(sphereRadius); float disc = Math::Square(b) - 4.0f * a * c; if (disc < 0.0f) return false; float discSqrt = Math::Sqrt(disc); float q; if (b < 0.0f) q = (-b - discSqrt) / 2.0f; else q = (-b + discSqrt) / 2.0f; float t0 = q / a; float t1 = c / q; if (t0 > t1) Swap(t0, t1); if (t1 < 0.0f) return false; if (t0 < 0.0f) return (t1 < rayDistance); else return (t0 < rayDistance); } bool CollisionDetection::RayIntersectsSphere(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &sphereCenter, const float sphereRadius, Vector3f &contactNormal, Vector3f &contactPoint) { // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_rayDirection(rayDirection); float a = vec_rayDirection.Dot(vec_rayDirection); float b = 2.0f * vec_rayDirection.Dot(vec_rayOrigin); float c = vec_rayOrigin.Dot(vec_rayOrigin) - Math::Square(sphereRadius); float disc = Math::Square(b) - 4.0f * a * c; if (disc < 0.0f) return false; float discSqrt = Math::Sqrt(disc); float q; if (b < 0.0f) q = (-b - discSqrt) / 2.0f; else q = (-b + discSqrt) / 2.0f; float t0 = q / a; float t1 = c / q; if (t0 > t1) Swap(t0, t1); if (t1 < 0.0f) return false; float t = (t0 < 0.0f) ? t1 : t0; if (t > rayDistance) return false; contactNormal = -rayDirection; contactPoint = vec_rayOrigin + vec_rayDirection * t; return true; } bool CollisionDetection::RayIntersectsPlane(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &planeNormal, const float planeDistance) { SIMDVector3f vec_planeNormal(planeNormal); float DdotN = SIMDVector3f(rayDirection).Dot(vec_planeNormal); if (DdotN >= 0.0f) return false; float OdotN = SIMDVector3f(rayOrigin).Dot(vec_planeNormal); if (Math::NearEqual(OdotN + planeDistance, 0.0f, Math::Epsilon<float>())) return true; float t = (planeDistance - OdotN) / DdotN; return (t >= 0.0f && t <= rayDistance); } bool CollisionDetection::RayIntersectsPlane(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint) { SIMDVector3f vec_planeNormal(planeNormal); SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_rayDirection(rayDirection); float DdotN = vec_rayDirection.Dot(vec_planeNormal); if (DdotN >= 0.0f) return false; float OdotN = vec_rayOrigin.Dot(vec_planeNormal); float t = 0.0f; if (Math::NearEqual(OdotN + planeDistance, 0.0f, Math::Epsilon<float>()) || (t = (planeDistance - OdotN) / DdotN) >= 0.0f) { contactNormal = planeNormal; contactPoint = vec_rayOrigin + vec_rayDirection * t; return true; } else { return false; } } bool CollisionDetection::RayIntersectsTriangle(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1) { SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_rayDirection(rayDirection); SIMDVector3f vec_e0(e0); SIMDVector3f vec_e1(e1); SIMDVector3f pvec = vec_rayDirection.Cross(vec_e1); float det = vec_e0.Dot(pvec); if (det <= 0.0f) return false; float invDet = 1.0f / det; SIMDVector3f tvec = vec_rayOrigin - v0; float u = tvec.Dot(pvec) * invDet; if (u < 0.0f || u > 1.0f) return false; SIMDVector3f qvec = tvec.Cross(vec_e0); float v = vec_rayDirection.Dot(qvec) * invDet; if (v < 0 || (u + v) > 1.0f) return false; float t = vec_e1.Dot(qvec) * invDet; return (t >= 0.0f && t <= rayDistance); } bool CollisionDetection::RayIntersectsTriangle(const Vector3f &rayOrigin, const Vector3f &rayDirection, const float rayDistance, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, Vector3f &contactNormal, Vector3f &contactPoint) { SIMDVector3f vec_rayOrigin(rayOrigin); SIMDVector3f vec_rayDirection(rayDirection); SIMDVector3f vec_e0(e0); SIMDVector3f vec_e1(e1); SIMDVector3f pvec = vec_rayDirection.Cross(vec_e1); float det = vec_e0.Dot(pvec); if (det <= 0.0f) return false; float invDet = 1.0f / det; SIMDVector3f tvec = vec_rayOrigin - v0; float u = tvec.Dot(pvec) * invDet; if (u < 0.0f || u > 1.0f) return false; SIMDVector3f qvec = tvec.Cross(vec_e0); float v = vec_rayDirection.Dot(qvec) * invDet; if (v < 0 || (u + v) > 1.0f) return false; float t = vec_e1.Dot(qvec) * invDet; if (t >= 0.0f && t <= rayDistance) { contactNormal = vec_e0.Cross(vec_e1).NormalizeEst(); contactPoint = vec_rayOrigin + vec_rayDirection * t; return true; } else { return false; } } bool CollisionDetection::AABoxIntersectsAABox(const Vector3f &AMinBounds, const Vector3f &AMaxBounds, const Vector3f &BMinBounds, const Vector3f &BMaxBounds) { SIMDVector3f M(AMinBounds); SIMDVector3f N(AMaxBounds); SIMDVector3f O(BMinBounds); SIMDVector3f P(BMaxBounds); if (M.AnyGreater(P) || O.AnyGreater(N)) return false; return true; } bool CollisionDetection::AABoxIntersectsAABox(const Vector3f &AMinBounds, const Vector3f &AMaxBounds, const Vector3f &BMinBounds, const Vector3f &BMaxBounds, Vector3f &contactNormal, Vector3f &contactPoint) { return false; } bool CollisionDetection::AABoxIntersectsSphere(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &sphereCenter, const float sphereRadius) { return SphereIntersectsBox(sphereCenter, sphereRadius, minBounds, maxBounds); } bool CollisionDetection::AABoxIntersectsSphere(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &sphereCenter, const float sphereRadius, Vector3f &contactNormal, Vector3f &contactPoint) { return false; } bool CollisionDetection::AABoxIntersectsPlane(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &planeNormal, const float planeDistance) { return false; } bool CollisionDetection::AABoxIntersectsPlane(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint) { return false; } bool CollisionDetection::AABoxIntersectsTriangle(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal) { return false; } bool CollisionDetection::AABoxIntersectsTriangle(const Vector3f &minBounds, const Vector3f &maxBounds, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal, Vector3f &contactNormal, Vector3f &contactPoint) { return false; } bool CollisionDetection::SphereIntersectsBox(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &minBounds, const Vector3f &maxBounds) { // http://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?page=4 float d = 0.0f; if (sphereCenter.x < minBounds.x) d += Math::Square(sphereCenter.x - minBounds.x); else if (sphereCenter.x > maxBounds.x) d += Math::Square(sphereCenter.x - maxBounds.x); if (sphereCenter.y < minBounds.y) d += Math::Square(sphereCenter.y - minBounds.y); else if (sphereCenter.y > maxBounds.y) d += Math::Square(sphereCenter.y - maxBounds.y); if (sphereCenter.z < minBounds.z) d += Math::Square(sphereCenter.z - minBounds.z); else if (sphereCenter.z > maxBounds.z) d += Math::Square(sphereCenter.z - maxBounds.z); return (d <= Math::Square(sphereRadius)); } bool CollisionDetection::SphereIntersectsBox(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) { Vector3f boxExtents(maxBounds - minBounds); Vector3f boxHalfExtents(boxExtents * 0.5f); Vector3f boxCenter(minBounds + boxHalfExtents); Vector3f sphereRelPos(sphereCenter - boxCenter); Vector3f closestPoint(sphereRelPos); closestPoint.x = Min(boxHalfExtents.x, closestPoint.x); closestPoint.x = Max(-boxHalfExtents.x, closestPoint.x); closestPoint.y = Min(boxHalfExtents.y, closestPoint.y); closestPoint.y = Max(-boxHalfExtents.y, closestPoint.y); closestPoint.z = Min(boxHalfExtents.z, closestPoint.z); closestPoint.z = Max(-boxHalfExtents.z, closestPoint.z); Vector3f relPosToPoint(sphereRelPos - closestPoint); float squaredDistance = relPosToPoint.SquaredLength(); if (squaredDistance > Math::Square(sphereRadius)) return false; float distance; Vector3f normal; if (squaredDistance <= Math::Epsilon<float>()) { float faceDist = boxHalfExtents.x - sphereRelPos.x; float minDist = faceDist; closestPoint.x = boxHalfExtents.x; normal.Set(1.0f, 0.0f, 0.0f); faceDist = boxHalfExtents.x + sphereRelPos.x; if (faceDist < minDist) { minDist = faceDist; closestPoint = sphereRelPos; closestPoint.x = -boxHalfExtents.x; normal.Set(-1.0f, 0.0f, 0.0f); } faceDist = boxHalfExtents.y - sphereRelPos.y; if (faceDist < minDist) { minDist = faceDist; closestPoint = sphereRelPos; closestPoint.y = boxHalfExtents.y; normal.Set(0.0f, 1.0f, 0.0f); } faceDist = boxHalfExtents.y + sphereRelPos.y; if (faceDist < minDist) { minDist = faceDist; closestPoint = sphereRelPos; closestPoint.y = -boxHalfExtents.y; normal.Set(0.0f, -1.0f, 0.0f); } faceDist = boxHalfExtents.z - sphereRelPos.z; if (faceDist < minDist) { minDist = faceDist; closestPoint = sphereRelPos; closestPoint.z = boxHalfExtents.z; normal.Set(0.0f, 0.0f, 1.0f); } faceDist = boxHalfExtents.z + sphereRelPos.z; if (faceDist < minDist) { minDist = faceDist; closestPoint = sphereRelPos; closestPoint.z = -boxHalfExtents.z; normal.Set(0.0f, 0.0f, -1.0f); } distance = minDist; } else { distance = Math::Sqrt(squaredDistance); normal = relPosToPoint / distance; } contactNormal = normal; contactPoint = closestPoint + boxCenter; return true; } bool CollisionDetection::SphereIntersectsSphere(const Vector3f &ACenter, const float ARadius, const Vector3f &BCenter, const float BRadius) { SIMDVector3f vec_ACenter(ACenter); SIMDVector3f vec_BCenter(BCenter); SIMDVector3f diff(vec_ACenter - vec_BCenter); float len = diff.Length(); if (len > (ARadius + BRadius)) return false; return true; } bool CollisionDetection::SphereIntersectsSphere(const Vector3f &ACenter, const float ARadius, const Vector3f &BCenter, const float BRadius, Vector3f &contactNormal, Vector3f &contactPoint) { SIMDVector3f vec_ACenter(ACenter); SIMDVector3f vec_BCenter(BCenter); SIMDVector3f diff(vec_ACenter - vec_BCenter); float len = diff.Length(); if (len > (ARadius + BRadius)) return false; SIMDVector3f normalOnSurfaceB(1.0f, 0.0f, 0.0f); if (len > Math::Epsilon<float>()) normalOnSurfaceB = diff / len; contactNormal = normalOnSurfaceB; contactPoint = vec_BCenter + normalOnSurfaceB * BRadius; return true; } bool CollisionDetection::SphereIntersectsPlane(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &planeNormal, const float planeDistance) { return false; } bool CollisionDetection::SphereIntersectsPlane(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &planeNormal, const float planeDistance, Vector3f &contactNormal, Vector3f &contactPoint) { return false; } bool CollisionDetection::SphereIntersectsTriangle(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal) { SIMDVector3f vec_sphereCenter(sphereCenter); SIMDVector3f vec_normal(normal); SIMDVector3f p1ToCenter(vec_sphereCenter - SIMDVector3f(v0)); float distanceFromPlane = p1ToCenter.Dot(vec_normal); if (distanceFromPlane < 0.0f) { distanceFromPlane = -distanceFromPlane; vec_normal = -vec_normal; } if (distanceFromPlane <= sphereRadius && PointInTriangle(sphereCenter, v0, e0, e1, vec_normal)) { SIMDVector3f contactPoint(vec_sphereCenter - vec_normal * distanceFromPlane); return ((vec_sphereCenter - contactPoint).SquaredLength() <= Math::Square(sphereRadius)); } return false; } bool CollisionDetection::SphereIntersectsTriangle(const Vector3f &sphereCenter, const float sphereRadius, const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, const Vector3f &normal, Vector3f &contactNormal, Vector3f &contactPoint) { SIMDVector3f vec_sphereCenter(sphereCenter); SIMDVector3f vec_normal(normal); SIMDVector3f p1ToCenter(vec_sphereCenter - SIMDVector3f(v0)); float distanceFromPlane = p1ToCenter.Dot(vec_normal); if (distanceFromPlane < 0.0f) { distanceFromPlane = -distanceFromPlane; vec_normal = -vec_normal; } if (distanceFromPlane <= sphereRadius && PointInTriangle(sphereCenter, v0, e0, e1, vec_normal)) { SIMDVector3f vec_contactPoint(vec_sphereCenter - vec_normal * distanceFromPlane); SIMDVector3f vec_contactToCenter(vec_sphereCenter - vec_contactPoint); float squaredDistance = vec_contactToCenter.SquaredLength(); if (squaredDistance <= Math::Square(sphereRadius)) { float distance = Math::Sqrt(squaredDistance); contactNormal = vec_contactToCenter / distance; contactPoint = vec_contactPoint; return true; } } return false; } float CollisionDetection::AABoxSweep(const Vector3f &movingBoxMinBounds, const Vector3f &movingBoxMaxBounds, const Vector3f &movingBoxDisplacement, const Vector3f &staticBoxMinBounds, const Vector3f &staticBoxMaxBounds) { //float3 AExtents(AMaxBounds - AMinBounds); //float3 BExtents(BMaxBounds - BMinBounds); //float3 ACenter float u0 = -Y_FLT_INFINITE; float u1 = Y_FLT_INFINITE; for (uint32 axis = 0; axis < 3; axis++) { if (staticBoxMaxBounds[axis] < movingBoxMinBounds[axis]) { if (movingBoxDisplacement[axis] < 0.0f) { float t0 = (staticBoxMaxBounds[axis] - movingBoxMinBounds[axis]) / movingBoxDisplacement[axis]; if (t0 > u0) u0 = t0; } else { return Y_FLT_INFINITE; } } else if (movingBoxMaxBounds[axis] < staticBoxMinBounds[axis]) { if (movingBoxDisplacement[axis] > 0.0f) { float t0 = (staticBoxMinBounds[axis] - movingBoxMaxBounds[axis]) / movingBoxDisplacement[axis]; if (t0 > u0) u0 = t0; } else { return Y_FLT_INFINITE; } } if (movingBoxMaxBounds[axis] > staticBoxMinBounds[axis] && movingBoxDisplacement[axis] < 0) { float t1 = (staticBoxMinBounds[axis] - movingBoxMaxBounds[axis]) / movingBoxDisplacement[axis]; if (t1 < u1) u1 = t1; } else if (staticBoxMaxBounds[axis] > movingBoxMinBounds[axis] && movingBoxDisplacement[axis] > 0) { float t1 = (staticBoxMaxBounds[axis] - movingBoxMinBounds[axis]) / movingBoxDisplacement[axis]; if (t1 < u1) u1 = t1; } } if (u0 <= u1 && u0 >= 0.0f && u0 <= 1.0f) return movingBoxDisplacement.Length() * u0; else return Y_FLT_INFINITE; } <file_sep>/Engine/Source/Engine/ScriptManager.h #pragma once #include "Engine/Common.h" #include "Engine/ScriptTypes.h" #include <lua.hpp> // Assert setup #ifdef Y_BUILD_CONFIG_DEBUG #define luaCheckOnMainThread() Assert(1) #define luaBackupStack(__state) int __stack_top_backup__ = lua_gettop(__state) //#define luaVerifyStack(__state, __offset) Assert(lua_gettop(__state) == (__stack_top_backup__) + (__offset)) #define luaVerifyStack(__state, __offset) if (lua_gettop(__state) != (__stack_top_backup__) + (__offset)) { ScriptManager::DumpScriptStack(__state); Panic("lua stack validation failed"); } #define luaVerifyUserType(__state, __offset, __metaTableReference) lua_getmetatable((__state), (__offset)); \ lua_rawgeti((__state), LUA_REGISTRYINDEX, (__metaTableReference)); \ Assert(lua_rawequal((__state), -1, -2)); \ lua_pop((__state), 2); #else #define luaCheckOnMainThread() #define luaBackupStack(__state) #define luaVerifyStack( __state, __offset) #define luaVerifyUserType(__state, __offset, __metaTableReference) #endif // Script args wrapper template<typename T> struct ScriptArg { static T Get(lua_State *L, int arg); static void Push(lua_State *L, const T &arg); }; // Script manager class ScriptManager { public: ScriptManager(); ~ScriptManager(); //========================================================================================================================================================================================================== // Initialization //========================================================================================================================================================================================================== bool Startup(); void Shutdown(); //========================================================================================================================================================================================================== // Helper Methods //========================================================================================================================================================================================================== // access the lua state lua_State *GetGlobalState() const { return m_state; } // generate a type error static int GenerateTypeError(lua_State *L, int narg, const char *type); static int GenerateTypeError(lua_State *L, int narg, ScriptReferenceType metaTableReference); // dump the current stack, top-to-bottom, to the log static int DumpScriptStack(lua_State *L); // dump a script traceback to the error log static int DumpScriptTraceback(lua_State *L); // Create an object reference, taking the object from the top of the stack. ScriptReferenceType CreateReference(lua_State *L); // Release an object reference, deleting it if no scripts are using it. void ReleaseReference(ScriptReferenceType objectReference); // Find memory usage of script state. size_t GetMemoryUsage() const; // Run a garbage collection step. void RunGCStep(); // Run a full garbage collection. void RunGCFull(); //========================================================================================================================================================================================================== // UserData Type Management //========================================================================================================================================================================================================== // Define a new user data type. If the type name is already in use, INVALID_SCRIPT_REFERENCE will be returned. An optional null-terminated list of preassigned functions can be provided. // A reference to the user data type's metatable will be returned, which is usable for the CheckUserDataType / PushNewUserDataType functions. Using the DefineTabledUserDataType // method will install wrappers so that the object can have arbritrary values set on it, with the table being allocated on-demand. ScriptReferenceType DefineUserDataType(const char *typeName, const SCRIPT_FUNCTION_TABLE_ENTRY *pMethods = nullptr, const SCRIPT_FUNCTION_TABLE_ENTRY *pMetaMethods = nullptr, ScriptNativeFunctionType constructor = nullptr, ScriptNativeFunctionType destructor = nullptr); ScriptReferenceType DefineTabledUserDataType(const char *typeName, const SCRIPT_FUNCTION_TABLE_ENTRY *pMethods = nullptr, const SCRIPT_FUNCTION_TABLE_ENTRY *pMetaMethods = nullptr, ScriptNativeFunctionType constructor = nullptr, ScriptNativeFunctionType destructor = nullptr); // Check whether the user data type matches the specified metatable reference, and returns the userdata pointer if so. static void *CheckUserDataTypeByMetaTable(lua_State *L, ScriptReferenceType metaTableReference, int arg); static void *CheckUserDataTypeByTag(lua_State *L, ScriptUserDataTag tag, int arg); // Pushes a new instance of the specified user data metatable. static void PushNewUserData(lua_State *L, ScriptReferenceType metaTableReference, ScriptUserDataTag tag, uint32 size, const void *data); ScriptReferenceType AllocateAndReferenceNewUserData(ScriptReferenceType metaTableReference, ScriptUserDataTag tag, uint32 size, const void *data); // Change the tag of an existing referenced userdata void SetUserDataReferenceTag(ScriptReferenceType reference, ScriptUserDataTag tag); //========================================================================================================================================================================================================== // Script Invocation //========================================================================================================================================================================================================== // Script runner ScriptCallResult RunScript(const byte *script, uint32 scriptLength, const char *source = "text chunk"); // Retrieves the number of return values after script execution. uint32 GetCallResultCount(); // Ends the script, cleaning up any return values. void EndCall(); // Call from a script native function, execution of the LUA thread will be paused and resumable later if it is a resumable call. Forward this return value back from the native function. int YieldThreadedCall(lua_State *L, const char *waitChannel = "", float timeout = DEFAULT_SCRIPT_TIMEOUT, ScriptThreadTimeoutAction timeoutAction = ScriptThreadTimeoutAction_Abort); // Retrieves the number of return values from a resumable script. uint32 GetThreadedCallResultCount(ScriptThread *pThread); // Prematurely ends the threaded call, cleaning up. void AbortThreadedCall(ScriptThread *pThread); // Ends the resumable script, cleaning up any return values. void EndThreadedCall(ScriptThread *pThread); //========================================================================================================================================================================================================== // Script Thread Management //==========================================================================================================================================================================================================/// const uint32 GetPauedThreadCount() const { return m_pausedThreads.GetSize(); } const ScriptThread *GetPausedThread(uint32 i) const { return m_pausedThreads[i]; } void CheckPausedThreadTimeout(float deltaTime); //========================================================================================================================================================================================================== // Script Object Management //==========================================================================================================================================================================================================/// // Pushes/creates a new instance of an object. static void PushNewObjectReference(lua_State *L, ScriptReferenceType metaTableReference, ScriptUserDataTag tag, const void *pObjectPointer); ScriptReferenceType AllocateAndReferenceObject(ScriptReferenceType metaTableReference, ScriptUserDataTag tag, const void *pObjectPointer); void SetObjectReferencePointer(ScriptReferenceType objectReference, const void *pObject); static void *CheckObjectTypeByMetaTable(lua_State *L, ScriptReferenceType metaTableReference, int arg); static void *CheckObjectTypeByTag(lua_State *L, ScriptUserDataTag tag, int arg); // Create an object's script environment, and hooks up any methods to the object's internal table. ScriptCallResult RunObjectScript(ScriptReferenceType objectReference, const byte *script, uint32 scriptLength, const char *source = "text chunk"); // Prepares an entity table object call. ScriptCallResult BeginObjectMethodCall(ScriptReferenceType objectReference, const char *methodName); // Invokes an entity table object call. ScriptCallResult InvokeObjectMethodCall(bool saveResults = false); // Prepares a resumable entity table object call. ScriptCallResult BeginThreadedObjectMethodCall(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName); // Invokes a resumable entity table object call. This same function is called when resuming a paused thread. ScriptCallResult ResumeThreadedObjectMethodCall(ScriptThread *pThread, bool saveResults = false); // Templated versions of the above for ease-of-use ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, bool saveResults = false); template<typename P1> ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, bool saveResults = false); template<typename P1, typename P2> ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, bool saveResults = false); template<typename P1, typename P2, typename P3> ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, bool saveResults = false); template<typename P1, typename P2, typename P3, typename P4> ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, bool saveResults = false); template<typename P1, typename P2, typename P3, typename P4, typename P5> ScriptCallResult CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, bool saveResults = false); // Templated versions of above for threaded calls ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, bool saveResults = false); template<typename P1> ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, bool saveResults = false); template<typename P1, typename P2> ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, bool saveResults = false); template<typename P1, typename P2, typename P3> ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, bool saveResults = false); template<typename P1, typename P2, typename P3, typename P4> ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, bool saveResults = false); template<typename P1, typename P2, typename P3, typename P4, typename P5> ScriptCallResult CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, bool saveResults = false); private: ////////////////////////////////////////////////////////////////////////// // Register known entity types as lua types void RegisterBuiltinFunctions(); void RegisterPrimitiveTypes(); void UnregisterPrimitiveTypes(); // Lock global variables from being modified void LockGlobals(); void UnlockGlobals(); ////////////////////////////////////////////////////////////////////////// // lua state lua_State *m_state; ////////////////////////////////////////////////////////////////////////// // paused threads PODArray<ScriptThread *> m_pausedThreads; private: DeclareNonCopyable(ScriptManager); }; extern ScriptManager *g_pScriptManager; ////////////////////////////////////////////////////////////////////////// // Wrapper around a pending coroutine class ScriptThread { friend ScriptManager; public: ScriptThread(lua_State *threadState, ScriptReferenceType threadReference); ~ScriptThread(); // Retreives the state of the thread. lua_State *GetThreadState() const { return m_pThreadState; } // Retreives the wait channel of the thread. const String &GetWaitChannel() const { return m_waitChannel; } // Retreives the timeout of the thread. float GetTimeout() const { return m_timeout; } // Resets the timeout of the thread. void ResetTimeout(float timeout = DEFAULT_SCRIPT_TIMEOUT) { m_timeout = timeout; } // Change the timeout action of the thread. ScriptThreadTimeoutAction GetTimeoutAction() const { return m_timeoutAction; } void SetTimeoutAction(ScriptThreadTimeoutAction timeoutAction) { m_timeoutAction = timeoutAction; } // Number of times this thread has been paused. uint32 GetYieldCount() const { return m_yieldCount; } private: // Pointer to thread state object lua_State *m_pThreadState; // Reference to the thread state object. This is necessary so that the LuA GC doesn't kill the state object. ScriptReferenceType m_threadReference; // Thread wait channel. String m_waitChannel; // Thread wait timeout. After this amount of time, the thread will perform the TimeoutAction action. float m_timeout; ScriptThreadTimeoutAction m_timeoutAction; // Number of times this thread has been paused. uint32 m_yieldCount; // noncopyable DeclareNonCopyable(ScriptThread); }; ////////////////////////////////////////////////////////////////////////// // Inlined versions of the above inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) res = InvokeObjectMethodCall(saveResults); return res; } template<typename P1> inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); res = InvokeObjectMethodCall(saveResults); } return res; } template<typename P1, typename P2> inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); res = InvokeObjectMethodCall(saveResults); } return res; } template<typename P1, typename P2, typename P3> inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); res = InvokeObjectMethodCall(saveResults); } return res; } template<typename P1, typename P2, typename P3, typename P4> inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); ScriptArg<P4>::Push(m_state, arg4); res = InvokeObjectMethodCall(saveResults); } return res; } template<typename P1, typename P2, typename P3, typename P4, typename P5> inline ScriptCallResult ScriptManager::CallObjectMethod(ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, bool saveResults /* = false */) { ScriptCallResult res = BeginObjectMethodCall(objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); ScriptArg<P4>::Push(m_state, arg4); ScriptArg<P5>::Push(m_state, arg5); res = InvokeObjectMethodCall(saveResults); } return res; } inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); return res; } template<typename P1> inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); } return res; } template<typename P1, typename P2> inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); } return res; } template<typename P1, typename P2, typename P3> inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); } return res; } template<typename P1, typename P2, typename P3, typename P4> inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); ScriptArg<P4>::Push(m_state, arg4); res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); } return res; } template<typename P1, typename P2, typename P3, typename P4, typename P5> inline ScriptCallResult ScriptManager::CallThreadedObjectMethod(ScriptThread **ppThread, ScriptReferenceType objectReference, const char *methodName, P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, bool saveResults /* = false */) { ScriptCallResult res = BeginThreadedObjectMethodCall(ppThread, objectReference, methodName); if (res == ScriptCallResult_Success) { ScriptArg<P1>::Push(m_state, arg1); ScriptArg<P2>::Push(m_state, arg2); ScriptArg<P3>::Push(m_state, arg3); ScriptArg<P4>::Push(m_state, arg4); ScriptArg<P5>::Push(m_state, arg5); res = ResumeThreadedObjectMethodCall(*ppThread, saveResults); } return res; } <file_sep>/Engine/Source/D3D12Renderer/PrecompiledHeader.h #pragma once #include "D3D12Renderer/D3D12Common.h" <file_sep>/Engine/Source/Engine/Physics/TriangleMeshCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" class btBvhTriangleMeshShape; namespace Physics { class TriangleMeshCollisionShape : public CollisionShape { friend class ScaledTriangleMeshCollisionShape; public: TriangleMeshCollisionShape(); virtual ~TriangleMeshCollisionShape(); // Virtual methods virtual const COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: AABox m_localBoundingBox; btBvhTriangleMeshShape *m_pTriangleMeshShape; }; } // namespace Physics <file_sep>/Engine/Source/Engine/BlockMeshBuilder.h #pragma once #include "Engine/Common.h" #include "Engine/BlockPalette.h" #include "Engine/BlockMeshVolume.h" class VertexBufferBindingArray; class GPUBuffer; class BlockMeshBuilder { public: enum NEIGHBOUR_VOLUME { NEIGHBOUR_VOLUME_LEFT, NEIGHBOUR_VOLUME_RIGHT, NEIGHBOUR_VOLUME_BACK, NEIGHBOUR_VOLUME_FRONT, NEIGHBOUR_VOLUME_BOTTOM, NEIGHBOUR_VOLUME_TOP, NEIGHBOUR_VOLUME_COUNT, }; struct Vertex { float3 Position; float3 TexCoord; float4 AtlasTexCoord; uint32 Color; uint8 FaceIndex; Vertex() { } Vertex(const float3 &position, const float3 &texcoord, const float4 &atlasTexCoord, uint32 color, uint8 faceIndex) { Position = position; TexCoord = texcoord; AtlasTexCoord = atlasTexCoord; Color = color; FaceIndex = faceIndex; } void Set(const float3 &position, const float3 &texcoord, const float4 &atlasTexCoord, uint32 color, uint8 faceIndex) { Position = position; TexCoord = texcoord; AtlasTexCoord = atlasTexCoord; Color = color; FaceIndex = faceIndex; } }; struct Triangle { uint32 MaterialIndex; uint32 FaceIndex; uint32 Indices[3]; Triangle() { } Triangle(uint32 materialIndex, uint32 faceIndex, uint32 i0, uint32 i1, uint32 i2) { MaterialIndex = materialIndex; FaceIndex = faceIndex; Indices[0] = i0; Indices[1] = i1; Indices[2] = i2; } void Set(uint32 materialIndex, uint32 faceIndex, uint32 i0, uint32 i1, uint32 i2) { MaterialIndex = materialIndex; FaceIndex = faceIndex; Indices[0] = i0; Indices[1] = i1; Indices[2] = i2; } }; struct Batch { uint32 MaterialIndex; uint32 StartIndex; uint32 NumIndices; bool DrawShadows; }; typedef MemArray<Vertex> VertexArray; typedef MemArray<Triangle> TriangleArray; typedef MemArray<Batch> BatchArray; public: BlockMeshBuilder(); ~BlockMeshBuilder(); // input data accessors const BlockPalette *GetPalette() const { return m_pPalette; } const uint32 GetWidth() const { return m_width; } const uint32 GetLength() const { return m_length; } const uint32 GetHeight() const { return m_height; } const BlockVolumeBlockType *GetBlockData() const { return m_pBlockData; } const BlockVolumeBlockType *GetNeighbourBlockData(NEIGHBOUR_VOLUME neighbour) const { DebugAssert(neighbour < NEIGHBOUR_VOLUME_COUNT); return m_pNeighbourBlockData[neighbour]; } const float3 &GetTranslation() const { return m_translation; } const float GetBlockScale() const { return m_scale; } // input data mutators void SetPalette(const BlockPalette *pBlockList) { m_pPalette = pBlockList;} void SetSize(uint32 meshWidth, uint32 meshLength, uint32 meshHeight) { m_width = meshWidth; m_length = meshLength; m_height = meshHeight; } void SetBlockData(const BlockVolumeBlockType *pBlockData) { m_pBlockData = pBlockData; } void SetNeighbourBlockData(NEIGHBOUR_VOLUME neighbour, const BlockVolumeBlockType *pBlockData) { DebugAssert(neighbour < NEIGHBOUR_VOLUME_COUNT); m_pNeighbourBlockData[neighbour] = pBlockData; } void SetTranslation(const float3 &basePosition) { m_translation = basePosition; } void SetScale(const float scale) { m_scale = scale; } void SetAmbientOcclusionEnabled(bool on) { m_ambientOcclusion = on; } void SetFromVolume(const BlockMeshVolume *pVolume); // output data const AABox &GetOutputBoundingBox() const { return m_outputBoundingBox; } const Sphere &GetOutputBoundingSphere() const { return m_outputBoundingSphere; } const VertexArray &GetOutputVertices() const { return m_outputVertices; } const uint32 GetOutputVertexCount() const { return m_outputVertices.GetSize(); } const TriangleArray &GetOutputTriangles() const { return m_outputTriangles; } const uint32 GetOutputTriangleCount() const { return m_outputTriangles.GetSize(); } const BatchArray &GetOutputBatches() const { return m_outputBatches; } const uint32 GetOutputBatchCount() const { return m_outputBatches.GetSize(); } // generate a render view of the chunk void GenerateMesh(); // generate a render view of the chunk, at the specified lod level void GenerateLODMesh(uint32 lodLevel); // generate collision mesh void GenerateCollisionMesh(); // generate a silhouette view of the chunk, used for shadow mapping void GenerateSilhouetteMesh(); // create gpu buffers for the generated data bool CreateGPUBuffers(VertexBufferBindingArray *pVertexBuffers, uint32 *pVertexFactoryFlags, GPUBuffer **ppIndexBuffer, GPU_INDEX_FORMAT *pIndexFormat, uint32 inVertexFactoryFlags); private: const BlockVolumeBlockType GetBlockValueAt(uint32 x, uint32 y, uint32 z) const; const BlockVolumeBlockType GetNeighbourBlockValueAt(NEIGHBOUR_VOLUME neighbour, uint32 x, uint32 y, uint32 z) const; const bool IsVisibleBlockAt(uint32 x, uint32 y, uint32 z) const; const bool IsVisibleNonTransparentBlockAt(uint32 x, uint32 y, uint32 z) const; const bool HasCubeLightBlockingBlockAt(uint32 x, uint32 y, uint32 z) const; const bool HasCubeVisibilityBlockingBlockAt(const BlockPalette::BlockType *pVolumeBlockType, int32 x, int32 y, int32 z) const; const uint32 CalculateCubeVertexColor(const BlockPalette::BlockType *pBlockType, const uint32 vertexIndex, const uint32 blockData, uint32 faceColor); void GenerateBlocks(float3 &outMinBounds, float3 &outMaxBounds); void GenerateCollisionBlocks(float3 &outMinBounds, float3 &outMaxBounds); void GenerateSilhouetteBlocks(float3 &outMinBounds, float3 &outMaxBounds); void OptimizeTriangleOrder(); void GenerateBatches(); // input data const BlockPalette *m_pPalette; uint32 m_width; uint32 m_length; uint32 m_height; const BlockVolumeBlockType *m_pBlockData; const BlockVolumeBlockType *m_pNeighbourBlockData[NEIGHBOUR_VOLUME_COUNT]; float3 m_translation; float m_scale; bool m_ambientOcclusion; // output data uint32 m_outputVertexFactoryFlags; AABox m_outputBoundingBox; Sphere m_outputBoundingSphere; VertexArray m_outputVertices; TriangleArray m_outputTriangles; BatchArray m_outputBatches; }; <file_sep>/Engine/Source/Renderer/RenderProxies/CompositeRenderProxy.h #pragma once #include "Renderer/Common.h" #include "Renderer/RenderProxy.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/RendererTypes.h" #include "Engine/BlockMesh.h" class Material; class CompositeRenderProxy : public RenderProxy { public: struct Batch { uint32 MaterialIndex; uint32 FirstIndex; uint32 IndexCount; }; public: CompositeRenderProxy(uint32 entityId, const Transform &transform); ~CompositeRenderProxy(); // manage objects uint32 AddObject(); void UpdateObject(uint32 objectId, const VertexFactoryTypeInfo *pVertexFactoryTypeInfo, uint32 vertexFactoryFlags, const void *pVertices, uint32 vertexSize, uint32 vertexCount, const void *pIndices, GPU_INDEX_FORMAT indexFormat, uint32 indexCount, const Material **ppMaterials, uint32 materialCount, const Batch *pBatches, uint32 batchCount, const AABox &boundingBox, const Sphere &boundingSphere); void UpdateObjectTintColor(uint32 objectId, bool tintEnabled, uint32 tintColor); void ClearObject(uint32 objectId); void DeleteObject(uint32 objectId); void DeleteAllObjects(); // update functions, can be called from game thread safely after adding to render world. void SetTransform(const Transform &transform); void SetTintColor(bool enabled, uint32 color = 0); void SetShadowFlags(uint32 shadowFlags); void SetVisibility(bool visible); virtual void QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; virtual bool CreateDeviceResources() const override; virtual void ReleaseDeviceResources() const override; void UpdateObjects(); private: enum UPDATE_OBJECT_FLAGS { UPDATE_OBJECT_FLAG_CREATE = (1 << 0), UPDATE_OBJECT_FLAG_BUFFERS = (1 << 1), UPDATE_OBJECT_FLAG_TINT = (1 << 2), UPDATE_OBJECT_FLAG_DELETE = (1 << 3), }; struct ObjectRecord { uint32 ObjectId; const VertexFactoryTypeInfo *pVertexFactoryTypeInfo; uint32 VertexFactoryFlags; GPUBuffer *pVertexBuffer; uint32 VertexStride; GPUBuffer *pIndexBuffer; GPU_INDEX_FORMAT IndexFormat; const Material **ppMaterials; uint32 MaterialCount; const Batch *pBatches; uint32 BatchCount; bool TintEnabled; uint32 TintColor; AABox BoundingBox; Sphere BoundingSphere; }; struct UpdateObjectRecord { uint32 ObjectId; uint32 UpdateFlags; const VertexFactoryTypeInfo *pVertexFactoryTypeInfo; uint32 VertexFactoryFlags; void *pVertices; uint32 VertexSize; uint32 VertexCount; void *pIndices; GPU_INDEX_FORMAT IndexFormat; uint32 IndexCount; const Material **ppMaterials; uint32 MaterialCount; Batch *pBatches; uint32 BatchCount; bool TintEnabled; uint32 TintColor; AABox BoundingBox; Sphere BoundingSphere; }; // sets the synchronization bit specified void SetSynchronizationBits(uint32 synchronizationBits); // updates objects, call from render thread void UpdateBounds(); // read/write from render thread. no access from game thread. bool m_Visibility; Transform m_Transform; float4x4 m_LocalToWorldMatrix; uint32 m_ShadowFlags; MemArray<ObjectRecord> m_objectRecords; uint32 m_nextObjectId; // gpu resources, also owned by render thread. mutable bool m_bGPUResourcesCreated; // read from render thread. write from game thread. MemArray<UpdateObjectRecord> m_updateObjectRecords; }; <file_sep>/Engine/Source/Core/CMakeLists.txt set(HEADER_FILES BSPTree.h ChunkDataFormat.h ChunkFileReader.h ChunkFileWriter.h ClassTableDataFormat.h ClassTable.h Common.h Console.h DDSFormat.h DDSReader.h DDSWriter.h DefinitionFile.h FIFVolume.h ImageCodec.h Image.h KDTree.h MeshUtilties.h Object.h ObjectSerializer.h ObjectTypeInfo.h PixelFormat.h PrecompiledHeader.h Property.h PropertyTable.h PropertyTemplate.h RandomNumberGenerator.h Resource.h ResourceTypeInfo.h TexturePacker.h TypeRegistry.h VirtualFileSystem.h XDisplay.h ) set(SOURCE_FILES ChunkFileReader.cpp ChunkFileWriter.cpp ClassTable.cpp Console.cpp DDSReader.cpp DDSWriter.cpp DefinitionFile.cpp FIFVolume.cpp ImageCodecBMP.cpp ImageCodec.cpp ImageCodecDDS.cpp ImageCodecDevIL.cpp ImageCodecFreeImage.cpp ImageCodecJPEG.cpp Image.cpp MeshUtilties.cpp Object.cpp ObjectSerializer.cpp ObjectTypeInfo.cpp PixelFormatConverters.cpp PixelFormat.cpp PrecompiledHeader.cpp Property.cpp PropertyTable.cpp PropertyTemplate.cpp RandomNumberGenerator.cpp Resource.cpp ResourceTypeInfo.cpp TexturePacker.cpp VirtualFileSystem.cpp XDisplay.cpp ) include_directories(${ENGINE_BASE_DIRECTORY} ${PCRE_INCLUDE_DIR}) set(EXTRA_LIBRARIES "") if(HAVE_SQUISH) LIST(APPEND EXTRA_LIBRARIES squish) endif() if(HAVE_FREEIMAGE) LIST(APPEND EXTRA_LIBRARIES freeimage) endif() add_library(EngineCore STATIC ${HEADER_FILES} ${SOURCE_FILES}) target_link_libraries(EngineCore fif SFMT YBaseLib EngineMathLib ${EXTRA_LIBRARIES} ${PCRE_LIBRARIES}) <file_sep>/Engine/Source/Engine/Physics/BoxCollisionShape.h #pragma once #include "Engine/Physics/CollisionShape.h" class btBoxShape; namespace Physics { class BoxCollisionShape : public CollisionShape { public: BoxCollisionShape(); BoxCollisionShape(const float3 &boxCenter, const float3 &halfExtents); ~BoxCollisionShape(); const float3 &GetBoxCenter() const { return m_center; } const float3 &GetHalfExtents() const { return m_halfExtents; } // Virtual methods virtual const COLLISION_SHAPE_TYPE GetType() const override; virtual const AABox &GetLocalBoundingBox() const override; virtual bool LoadFromStream(ByteStream *pStream, uint32 dataSize) override; virtual bool LoadFromData(const void *pData, uint32 dataSize) override; virtual CollisionShape *CreateScaledShape(const float3 &scale) const override; virtual void ApplyShapeTransform(btTransform &worldTransform) const override; virtual void ApplyInverseShapeTransform(btTransform &worldTransform) const override; virtual btCollisionShape *GetBulletShape() const override; private: AABox m_bounds; float3 m_center; float3 m_halfExtents; btBoxShape *m_pBulletShape; }; } // namespace Physics <file_sep>/Editor/Source/Editor/MapEditor/EditorTerrainEditMode.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorTerrainEditMode.h" #include "Editor/MapEditor/EditorMap.h" #include "Editor/MapEditor/EditorMapWindow.h" #include "Editor/MapEditor/EditorMapViewport.h" #include "Editor/EditorHelpers.h" #include "Editor/EditorProgressDialog.h" #include "Engine/Entity.h" #include "Engine/StaticMesh.h" #include "Engine/ResourceManager.h" #include "Engine/Texture.h" #include "Engine/EngineCVars.h" #include "Renderer/VertexFactories/LocalVertexFactory.h" #include "Renderer/VertexBufferBindingArray.h" #include "Renderer/RenderProxies/CompositeRenderProxy.h" #include "Renderer/RenderWorld.h" #include "MapCompiler/MapSource.h" #include "MapCompiler/MapSourceTerrainData.h" #include "ResourceCompiler/TerrainLayerListGenerator.h" Log_SetChannel(EditorTerrainEditMode); // helper function to create the default layer list TerrainLayerListGenerator *EditorTerrainEditMode::CreateEmptyLayerList() { TerrainLayerListGenerator *pGenerator = new TerrainLayerListGenerator(); pGenerator->Create(256, 256); // create the default layer const TerrainLayerListGenerator::BaseLayer *pBaseLayer = pGenerator->GetBaseLayerByName("default"); DebugAssert(pBaseLayer != nullptr); // load in the default texture { Image baseMap; AutoReleasePtr<const Texture2D> pTexture = g_pResourceManager->GetTexture2D("resources/editor/textures/default_terrain_base_map"); if (pTexture != nullptr && pTexture->ExportToImage(0, &baseMap)) { baseMap.ConvertPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM); baseMap.Resize(IMAGE_RESIZE_FILTER_LANCZOS3, pGenerator->GetBaseLayerBaseMapResolution(), pGenerator->GetBaseLayerBaseMapResolution(), 1); pGenerator->SetBaseLayerBaseMap(pBaseLayer->Index, &baseMap); } } // just for testing util editor is done #if 1 pBaseLayer = pGenerator->CreateBaseLayer("grass"); { Image baseMap; AutoReleasePtr<const Texture2D> pTexture = g_pResourceManager->GetTexture2D("textures/terrain/GrassGreenTexture0006"); if (pTexture != nullptr && pTexture->ExportToImage(0, &baseMap)) { baseMap.ConvertPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM); baseMap.Resize(IMAGE_RESIZE_FILTER_LANCZOS3, pGenerator->GetBaseLayerBaseMapResolution(), pGenerator->GetBaseLayerBaseMapResolution(), 1); pGenerator->SetBaseLayerBaseMap(pBaseLayer->Index, &baseMap); } } pBaseLayer = pGenerator->CreateBaseLayer("dirt"); { Image baseMap; AutoReleasePtr<const Texture2D> pTexture = g_pResourceManager->GetTexture2D("textures/terrain/Dirt00seamless"); if (pTexture != nullptr && pTexture->ExportToImage(0, &baseMap)) { baseMap.ConvertPixelFormat(PIXEL_FORMAT_R8G8B8_UNORM); baseMap.Resize(IMAGE_RESIZE_FILTER_LANCZOS3, pGenerator->GetBaseLayerBaseMapResolution(), pGenerator->GetBaseLayerBaseMapResolution(), 1); pGenerator->SetBaseLayerBaseMap(pBaseLayer->Index, &baseMap); } } #endif // done return pGenerator; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ui_EditorTerrainEditMode { QWidget *root; QWidget *buttonsPanel; QToolButton *buttonEditHeight; QToolButton *buttonEditDetails; QToolButton *buttonEditHoles; QToolButton *buttonEditSections; QToolButton *buttonEditLayers; QToolButton *buttonImportHeightmap; QToolButton *buttonSettings; QGroupBox *BrushPanel; QComboBox *BrushPanelBrushType; QDoubleSpinBox *BrushPanelBrushRadius; QDoubleSpinBox *BrushPanelBrushFalloff; QCheckBox *BrushPanelBrushInvert; QGroupBox *EditHeightPanel; QDoubleSpinBox *EditHeightPanelStepHeight; QGroupBox *EditLayersPanel; QDoubleSpinBox *EditLayersPanelStepWeight; QListWidget *EditLayersPanelLayerList; QPushButton *EditLayersPanelEditLayers; QWidget *EditDetailsPanel; QWidget *EditHolesPanel; QWidget *EditSectionsPanel; QGroupBox *EditSectionsNoSelection; QGroupBox *EditSectionsSectionInfo; QLabel *EditSectionsSectionInfoSectionX; QLabel *EditSectionsSectionInfoSectionY; QGroupBox *EditSectionsActiveSection; QLabel *EditSectionsActiveSectionNodeCount; QLabel *EditSectionsActiveSectionSplatMapCount; QListWidget *EditSectionsActiveSectionUsedLayerList; QGroupBox *EditSectionsActiveSectionOps; QPushButton *EditSectionsActiveSectionOpsDeleteLayers; QPushButton *EditSectionsActiveSectionOpsDeleteSection; QPushButton *EditSectionsActiveSectionOpsRebuildQuadTree; QPushButton *EditSectionsActiveSectionOpsRebuildSplatMap; QGroupBox *EditSectionsInactiveSection; QComboBox *EditSectionsInactiveSectionCreateLayer; QDoubleSpinBox *EditSectionsInactiveSectionCreateHeight; QGroupBox *EditSectionsInactiveSectionOps; QPushButton *EditSectionsInactiveSectionOpsCreateSection; QWidget *HeightmapImportPanel; QRadioButton *HeightmapImportPanelSourceTypeRaw8; QRadioButton *HeightmapImportPanelSourceTypeRaw16; QRadioButton *HeightmapImportPanelSourceTypeRawFloat; QRadioButton *HeightmapImportPanelSourceTypeImage; QPushButton *HeightmapImportPanelSource; QString HeightmapImportPanelSourceFileName; QLabel *HeightmapImportPanelSourcePreview; QLabel *HeightmapImportPanelSourceWidth; QLabel *HeightmapImportPanelSourceHeight; QSpinBox *HeightmapImportPanelDestinationStartSectionX; QSpinBox *HeightmapImportPanelDestinationStartSectionY; QDoubleSpinBox *HeightmapImportPanelDestinationMinHeight; QDoubleSpinBox *HeightmapImportPanelDestinationMaxHeight; QButtonGroup *HeightmapImportPanelScaleType; QRadioButton *HeightmapImportPanelScaleTypeNone; QRadioButton *HeightmapImportPanelScaleTypeDownscale; QRadioButton *HeightmapImportPanelScaleTypeUpscale; QSpinBox *HeightmapImportPanelScaleAmount; QLabel *HeightmapImportPanelResultSizeX; QLabel *HeightmapImportPanelResultSizeY; QPushButton *HeightmapImportPanelImport; QWidget *SettingsPanel; QSpinBox *SettingsPanelViewDistance; QSpinBox *SettingsPanelRenderResolutionMultiplier; QDoubleSpinBox *SettingsPanelLODDistanceRatio; QPushButton *SettingsPanelRebuildQuadtree; QPushButton *SettingsPanelRebuildSplatMaps; void CreateUI(QWidget *parentWidget) { QVBoxLayout *verticalLayout2; QFormLayout *formLayout; QLabel *label; // helpful bits QSizePolicy expandAndVerticalStretchSizePolicy; expandAndVerticalStretchSizePolicy.setHorizontalPolicy(QSizePolicy::Expanding); expandAndVerticalStretchSizePolicy.setVerticalPolicy(QSizePolicy::Expanding); expandAndVerticalStretchSizePolicy.setVerticalStretch(1); root = new QWidget(parentWidget); QVBoxLayout *rootLayout = new QVBoxLayout(root); rootLayout->setSpacing(2); rootLayout->setMargin(0); rootLayout->setContentsMargins(2, 2, 2, 2); // toolbar { buttonsPanel = new QWidget(root); buttonsPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); { verticalLayout2 = new QVBoxLayout(buttonsPanel); verticalLayout2->setSizeConstraint(QLayout::SetMaximumSize); verticalLayout2->setSpacing(0); verticalLayout2->setMargin(0); buttonEditHeight = new QToolButton(buttonsPanel); buttonEditHeight->setText(root->tr("Edit Height")); buttonEditHeight->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonEditHeight->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonEditHeight->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonEditHeight->setMaximumSize(QSize(16777215, 24)); buttonEditHeight->setCheckable(true); buttonEditHeight->setAutoRaise(true); verticalLayout2->addWidget(buttonEditHeight); buttonEditLayers = new QToolButton(buttonsPanel); buttonEditLayers->setText(root->tr("Edit Layers")); buttonEditLayers->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonEditLayers->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonEditLayers->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonEditLayers->setMaximumSize(QSize(16777215, 24)); buttonEditLayers->setCheckable(true); buttonEditLayers->setAutoRaise(true); verticalLayout2->addWidget(buttonEditLayers); buttonEditDetails = new QToolButton(buttonsPanel); buttonEditDetails->setText(root->tr("Edit Detail")); buttonEditDetails->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonEditDetails->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonEditDetails->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonEditDetails->setMaximumSize(QSize(16777215, 24)); buttonEditDetails->setCheckable(true); buttonEditDetails->setAutoRaise(true); verticalLayout2->addWidget(buttonEditDetails); buttonEditHoles = new QToolButton(buttonsPanel); buttonEditHoles->setText(root->tr("Edit Holes")); buttonEditHoles->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonEditHoles->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonEditHoles->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonEditHoles->setMaximumSize(QSize(16777215, 24)); buttonEditHoles->setCheckable(true); buttonEditHoles->setAutoRaise(true); verticalLayout2->addWidget(buttonEditHoles); buttonEditSections = new QToolButton(buttonsPanel); buttonEditSections->setText(root->tr("Edit Sections")); buttonEditSections->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonEditSections->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonEditSections->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonEditSections->setMaximumSize(QSize(16777215, 24)); buttonEditSections->setCheckable(true); buttonEditSections->setAutoRaise(true); verticalLayout2->addWidget(buttonEditSections); buttonImportHeightmap = new QToolButton(buttonsPanel); buttonImportHeightmap->setText(root->tr("Import Heightmap")); buttonImportHeightmap->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonImportHeightmap->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonImportHeightmap->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonImportHeightmap->setMaximumSize(QSize(16777215, 24)); buttonImportHeightmap->setCheckable(true); buttonImportHeightmap->setAutoRaise(true); verticalLayout2->addWidget(buttonImportHeightmap); buttonSettings = new QToolButton(buttonsPanel); buttonSettings->setText(root->tr("Terrain Settings")); buttonSettings->setIcon(QIcon(QStringLiteral(":/editor/icons/Toolbar_Select.png"))); buttonSettings->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttonSettings->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); buttonSettings->setMaximumSize(QSize(16777215, 24)); buttonSettings->setCheckable(true); buttonSettings->setAutoRaise(true); verticalLayout2->addWidget(buttonSettings); } buttonsPanel->setLayout(verticalLayout2); rootLayout->addWidget(buttonsPanel); } // brush settings BrushPanel = new QGroupBox(root->tr("Brush Settings"), root); BrushPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); { formLayout = new QFormLayout(BrushPanel); formLayout->setSizeConstraint(QLayout::SetMaximumSize); //formLayout->setSpacing(0); //formLayout->setMargin(0); BrushPanelBrushType = new QComboBox(BrushPanel); BrushPanelBrushType->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); BrushPanelBrushType->setMaximumSize(16777215, 24); formLayout->addRow(root->tr("Brush Type"), BrushPanelBrushType); BrushPanelBrushRadius = new QDoubleSpinBox(BrushPanel); BrushPanelBrushRadius->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); BrushPanelBrushRadius->setMaximumSize(16777215, 24); BrushPanelBrushRadius->setRange(0.1f, 64.0f); formLayout->addRow(root->tr("Brush Radius: "), BrushPanelBrushRadius); BrushPanelBrushFalloff = new QDoubleSpinBox(BrushPanel); BrushPanelBrushFalloff->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); BrushPanelBrushFalloff->setMaximumSize(16777215, 24); BrushPanelBrushFalloff->setRange(0.1f, 10.0f); formLayout->addRow(root->tr("Brush Falloff: "), BrushPanelBrushFalloff); BrushPanelBrushInvert = new QCheckBox(BrushPanel); BrushPanelBrushInvert->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); BrushPanelBrushInvert->setMaximumSize(16777215, 24); formLayout->addRow(root->tr("Invert Brush"), BrushPanelBrushInvert); BrushPanel->setLayout(formLayout); BrushPanel->hide(); rootLayout->addWidget(BrushPanel); } // edit terrain panel { EditHeightPanel = new QGroupBox(root->tr("Height Options"), root); formLayout = new QFormLayout(EditHeightPanel); EditHeightPanelStepHeight = new QDoubleSpinBox(EditHeightPanel); EditHeightPanelStepHeight->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); EditHeightPanelStepHeight->setMaximumSize(16777215, 24); EditHeightPanelStepHeight->setRange(0.1f, 16.0f); formLayout->addRow(root->tr("Height Step: "), EditHeightPanelStepHeight); EditHeightPanel->setLayout(formLayout); EditHeightPanel->hide(); rootLayout->addWidget(EditHeightPanel); } // edit layers panel { EditLayersPanel = new QGroupBox(root->tr("Layer Options"), root); formLayout = new QFormLayout(EditLayersPanel); formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow); EditLayersPanelStepWeight = new QDoubleSpinBox(EditLayersPanel); EditLayersPanelStepWeight->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); EditLayersPanelStepWeight->setMaximumSize(16777215, 24); EditLayersPanelStepWeight->setRange(0.1f, 1.0f); formLayout->addRow(root->tr("Weight Step: "), EditLayersPanelStepWeight); EditLayersPanelLayerList = new QListWidget(EditLayersPanel); EditLayersPanelLayerList->setSizePolicy(expandAndVerticalStretchSizePolicy); formLayout->addRow(new QLabel(root->tr("Layer List: "), EditLayersPanel)); formLayout->addRow(EditLayersPanelLayerList); EditLayersPanelEditLayers = new QPushButton(EditLayersPanel); EditLayersPanelEditLayers->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); EditLayersPanelEditLayers->setMaximumSize(16777215, 24); EditLayersPanelEditLayers->setText(root->tr("Edit Layers...")); formLayout->addRow(EditLayersPanelEditLayers); EditLayersPanel->setLayout(formLayout); EditLayersPanel->hide(); rootLayout->addWidget(EditLayersPanel, 1); } // edit details panel { EditDetailsPanel = new QWidget(root); EditDetailsPanel->hide(); rootLayout->addWidget(EditDetailsPanel); } // edit holes panel { EditHolesPanel = new QWidget(root); EditHolesPanel->hide(); rootLayout->addWidget(EditHolesPanel); } // edit sections panel { EditSectionsPanel = new QWidget(root); QVBoxLayout *editSectionsLayout = new QVBoxLayout(EditSectionsPanel); editSectionsLayout->setContentsMargins(0, 0, 0, 0); // no selection { EditSectionsNoSelection = new QGroupBox(root->tr("Section Info"), EditSectionsPanel); formLayout = new QFormLayout(EditSectionsNoSelection); formLayout->addRow(new QLabel(root->tr("No selection"), EditSectionsNoSelection)); EditSectionsNoSelection->setLayout(formLayout); editSectionsLayout->addWidget(EditSectionsNoSelection); } // section info { EditSectionsSectionInfo = new QGroupBox(root->tr("Section Info"), EditSectionsPanel); formLayout = new QFormLayout(EditSectionsSectionInfo); EditSectionsSectionInfoSectionX = new QLabel(EditSectionsSectionInfo); formLayout->addRow(root->tr("Section X: "), EditSectionsSectionInfoSectionX); EditSectionsSectionInfoSectionY = new QLabel(EditSectionsSectionInfo); formLayout->addRow(root->tr("Section Y: "), EditSectionsSectionInfoSectionY); EditSectionsSectionInfo->setLayout(formLayout); editSectionsLayout->addWidget(EditSectionsSectionInfo); } // active selection info { EditSectionsActiveSection = new QGroupBox(root->tr("Section Contents"), EditSectionsPanel); formLayout = new QFormLayout(EditSectionsActiveSection); EditSectionsActiveSectionNodeCount = new QLabel(EditSectionsActiveSection); formLayout->addRow(root->tr("Node Count: "), EditSectionsActiveSectionNodeCount); EditSectionsActiveSectionSplatMapCount = new QLabel(EditSectionsActiveSection); formLayout->addRow(root->tr("Splat Map Count: "), EditSectionsActiveSectionSplatMapCount); EditSectionsActiveSectionUsedLayerList = new QListWidget(EditSectionsActiveSection); formLayout->addRow(new QLabel(root->tr("Used Layers: "), EditSectionsActiveSection)); formLayout->addRow(EditSectionsActiveSectionUsedLayerList); EditSectionsActiveSection->setLayout(formLayout); EditSectionsActiveSection->hide(); editSectionsLayout->addWidget(EditSectionsActiveSection); } // active selection ops { EditSectionsActiveSectionOps = new QGroupBox(root->tr("Operations"), EditSectionsPanel); QVBoxLayout *vboxLayout = new QVBoxLayout(EditSectionsActiveSectionOps); EditSectionsActiveSectionOpsDeleteLayers = new QPushButton(root->tr("Delete Layers..."), EditSectionsActiveSectionOps); vboxLayout->addWidget(EditSectionsActiveSectionOpsDeleteLayers); EditSectionsActiveSectionOpsDeleteSection = new QPushButton(root->tr("Delete Section"), EditSectionsActiveSectionOps); vboxLayout->addWidget(EditSectionsActiveSectionOpsDeleteSection); EditSectionsActiveSectionOpsRebuildQuadTree = new QPushButton(root->tr("Rebuild QuadTree"), EditSectionsActiveSectionOps); vboxLayout->addWidget(EditSectionsActiveSectionOpsRebuildQuadTree); EditSectionsActiveSectionOpsRebuildSplatMap = new QPushButton(root->tr("Rebuild Splat Map"), EditSectionsActiveSectionOps); vboxLayout->addWidget(EditSectionsActiveSectionOpsRebuildSplatMap); EditSectionsActiveSectionOps->setLayout(vboxLayout); EditSectionsActiveSectionOps->hide(); editSectionsLayout->addWidget(EditSectionsActiveSectionOps); } // inactive selection create options { EditSectionsInactiveSection = new QGroupBox(root->tr("Section Contents"), EditSectionsPanel); formLayout = new QFormLayout(EditSectionsInactiveSection); EditSectionsInactiveSectionCreateLayer = new QComboBox(EditSectionsInactiveSection); formLayout->addRow(new QLabel(root->tr("Create Layer: "), EditSectionsInactiveSection)); formLayout->addRow(EditSectionsInactiveSectionCreateLayer); EditSectionsInactiveSectionCreateHeight = new QDoubleSpinBox(EditSectionsInactiveSection); formLayout->addRow(new QLabel(root->tr("Create Height: "), EditSectionsInactiveSection)); formLayout->addRow(EditSectionsInactiveSectionCreateHeight); EditSectionsInactiveSection->setLayout(formLayout); EditSectionsInactiveSection->hide(); editSectionsLayout->addWidget(EditSectionsInactiveSection); } // inactive selection ops { EditSectionsInactiveSectionOps = new QGroupBox(root->tr("Operations"), EditSectionsPanel); QVBoxLayout *vboxLayout = new QVBoxLayout(EditSectionsInactiveSectionOps); EditSectionsInactiveSectionOpsCreateSection = new QPushButton(root->tr("Create Section"), EditSectionsInactiveSectionOps); vboxLayout->addWidget(EditSectionsInactiveSectionOpsCreateSection); EditSectionsInactiveSectionOps->setLayout(vboxLayout); EditSectionsInactiveSectionOps->hide(); editSectionsLayout->addWidget(EditSectionsInactiveSectionOps); } EditSectionsPanel->setLayout(editSectionsLayout); EditSectionsPanel->hide(); rootLayout->addWidget(EditSectionsPanel); } // heightmap import panel { HeightmapImportPanel = new QWidget(root); QVBoxLayout *heightmapImportLayout = new QVBoxLayout(HeightmapImportPanel); heightmapImportLayout->setContentsMargins(0, 0, 0, 0); // source { QGroupBox *heightmapImportSourceGroupBox = new QGroupBox(root->tr("Source"), HeightmapImportPanel); QFormLayout *heightmapImportSourceFormLayout = new QFormLayout(heightmapImportSourceGroupBox); QButtonGroup *heightmapImportSourceTypeButtonGroup = new QButtonGroup(heightmapImportSourceGroupBox); HeightmapImportPanelSourceTypeRaw8 = new QRadioButton(root->tr("Raw 8-bit Heightmap"), heightmapImportSourceGroupBox); heightmapImportSourceTypeButtonGroup->addButton(HeightmapImportPanelSourceTypeRaw8); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSourceTypeRaw8); HeightmapImportPanelSourceTypeRaw16 = new QRadioButton(root->tr("Raw 16-bit Heightmap"), heightmapImportSourceGroupBox); heightmapImportSourceTypeButtonGroup->addButton(HeightmapImportPanelSourceTypeRaw16); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSourceTypeRaw16); HeightmapImportPanelSourceTypeRawFloat = new QRadioButton(root->tr("Raw Float Heightmap"), heightmapImportSourceGroupBox); heightmapImportSourceTypeButtonGroup->addButton(HeightmapImportPanelSourceTypeRawFloat); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSourceTypeRawFloat); HeightmapImportPanelSourceTypeImage = new QRadioButton(root->tr("Image"), heightmapImportSourceGroupBox); heightmapImportSourceTypeButtonGroup->addButton(HeightmapImportPanelSourceTypeImage); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSourceTypeImage); HeightmapImportPanelSource = new QPushButton(heightmapImportSourceGroupBox); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSource); HeightmapImportPanelSourceWidth = new QLabel(heightmapImportSourceGroupBox); HeightmapImportPanelSourceWidth->setText(QStringLiteral("0")); heightmapImportSourceFormLayout->addRow(root->tr("Source Width: "), HeightmapImportPanelSourceWidth); HeightmapImportPanelSourceHeight = new QLabel(heightmapImportSourceGroupBox); HeightmapImportPanelSourceHeight->setText(QStringLiteral("0")); heightmapImportSourceFormLayout->addRow(root->tr("Source Height: "), HeightmapImportPanelSourceHeight); HeightmapImportPanelSourcePreview = new QLabel(heightmapImportSourceGroupBox); HeightmapImportPanelSourcePreview->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); HeightmapImportPanelSourcePreview->setFixedSize(128, 128); HeightmapImportPanelSourcePreview->setBackgroundRole(QPalette::Dark); heightmapImportSourceFormLayout->addRow(HeightmapImportPanelSourcePreview); heightmapImportSourceGroupBox->setLayout(heightmapImportSourceFormLayout); heightmapImportLayout->addWidget(heightmapImportSourceGroupBox); } // destination { QGroupBox *heightmapImportDestinationGroupBox = new QGroupBox(root->tr("Destination"), HeightmapImportPanel); QFormLayout *heightmapImportDestinationFormLayout = new QFormLayout(heightmapImportDestinationGroupBox); HeightmapImportPanelDestinationStartSectionX = new QSpinBox(heightmapImportDestinationGroupBox); heightmapImportDestinationFormLayout->addRow(root->tr("Start Section X: "), HeightmapImportPanelDestinationStartSectionX); HeightmapImportPanelDestinationStartSectionY = new QSpinBox(heightmapImportDestinationGroupBox); heightmapImportDestinationFormLayout->addRow(root->tr("Start Section Y: "), HeightmapImportPanelDestinationStartSectionY); HeightmapImportPanelDestinationMinHeight = new QDoubleSpinBox(heightmapImportDestinationGroupBox); HeightmapImportPanelDestinationMinHeight->setMinimum(-65536.0); HeightmapImportPanelDestinationMinHeight->setMaximum(65536.0); HeightmapImportPanelDestinationMinHeight->setSingleStep(0.1); HeightmapImportPanelDestinationMinHeight->setValue(0); heightmapImportDestinationFormLayout->addRow(root->tr("Min Height: "), HeightmapImportPanelDestinationMinHeight); HeightmapImportPanelDestinationMaxHeight = new QDoubleSpinBox(heightmapImportDestinationGroupBox); HeightmapImportPanelDestinationMaxHeight->setMinimum(-65536.0); HeightmapImportPanelDestinationMaxHeight->setMaximum(65536.0); HeightmapImportPanelDestinationMaxHeight->setSingleStep(0.1); HeightmapImportPanelDestinationMaxHeight->setValue(32.0); heightmapImportDestinationFormLayout->addRow(root->tr("Max Height: "), HeightmapImportPanelDestinationMaxHeight); heightmapImportDestinationGroupBox->setLayout(heightmapImportDestinationFormLayout); heightmapImportLayout->addWidget(heightmapImportDestinationGroupBox); } // scale { QGroupBox *heightmapImportScaleGroupBox = new QGroupBox(root->tr("Scale"), HeightmapImportPanel); QFormLayout *heightmapImportScaleFormLayout = new QFormLayout(heightmapImportScaleGroupBox); HeightmapImportPanelScaleType = new QButtonGroup(heightmapImportScaleGroupBox); HeightmapImportPanelScaleTypeNone = new QRadioButton(root->tr("None"), heightmapImportScaleGroupBox); heightmapImportScaleFormLayout->addRow(HeightmapImportPanelScaleTypeNone); HeightmapImportPanelScaleTypeDownscale = new QRadioButton(root->tr("Downscale"), heightmapImportScaleGroupBox); heightmapImportScaleFormLayout->addRow(HeightmapImportPanelScaleTypeDownscale); HeightmapImportPanelScaleTypeUpscale = new QRadioButton(root->tr("Upscale"), heightmapImportScaleGroupBox); heightmapImportScaleFormLayout->addRow(HeightmapImportPanelScaleTypeUpscale); HeightmapImportPanelScaleAmount = new QSpinBox(heightmapImportScaleGroupBox); HeightmapImportPanelScaleAmount->setMinimum(1); HeightmapImportPanelScaleAmount->setMaximum(128); heightmapImportScaleFormLayout->addRow(root->tr("Scale Amount: "), HeightmapImportPanelScaleAmount); heightmapImportScaleGroupBox->setLayout(heightmapImportScaleFormLayout); heightmapImportLayout->addWidget(heightmapImportScaleGroupBox); } // result { QGroupBox *heightmapImportResultGroupBox = new QGroupBox(root->tr("Result"), HeightmapImportPanel); QFormLayout *heightmapImportResultFormLayout = new QFormLayout(heightmapImportResultGroupBox); HeightmapImportPanelResultSizeX = new QLabel(heightmapImportResultGroupBox); HeightmapImportPanelResultSizeX->setText(QStringLiteral("0")); heightmapImportResultFormLayout->addRow(root->tr("X Points: "), HeightmapImportPanelResultSizeX); HeightmapImportPanelResultSizeY = new QLabel(heightmapImportResultGroupBox); HeightmapImportPanelResultSizeY->setText(QStringLiteral("0")); heightmapImportResultFormLayout->addRow(root->tr("Y Points: "), HeightmapImportPanelResultSizeY); HeightmapImportPanelImport = new QPushButton(heightmapImportResultGroupBox); HeightmapImportPanelImport->setText(root->tr("Import...")); heightmapImportResultFormLayout->addRow(HeightmapImportPanelImport); heightmapImportResultGroupBox->setLayout(heightmapImportResultFormLayout); heightmapImportLayout->addWidget(heightmapImportResultGroupBox); } HeightmapImportPanel->setLayout(heightmapImportLayout); HeightmapImportPanel->hide(); rootLayout->addWidget(HeightmapImportPanel); } // terrain settings panel { SettingsPanel = new QWidget(root); SettingsPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); verticalLayout2 = new QVBoxLayout(SettingsPanel); verticalLayout2->setSizeConstraint(QLayout::SetMaximumSize); verticalLayout2->setSpacing(0); verticalLayout2->setMargin(0); verticalLayout2->setContentsMargins(4, 4, 4, 4); label = new QLabel(SettingsPanel); label->setText(root->tr("View Distance: ")); label->setMaximumSize(QSize(16777215, 24)); verticalLayout2->addWidget(label); SettingsPanelViewDistance = new QSpinBox(SettingsPanel); SettingsPanelViewDistance->setRange(16, 65535); SettingsPanelViewDistance->setSingleStep(16); SettingsPanelViewDistance->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); SettingsPanelViewDistance->setMaximumSize(QSize(16777215, 24)); SettingsPanelViewDistance->setValue(CVars::r_terrain_view_distance.GetInt()); verticalLayout2->addWidget(SettingsPanelViewDistance); label = new QLabel(SettingsPanel); label->setText(root->tr("Render Resolution Multiplier: ")); label->setMaximumSize(QSize(16777215, 24)); verticalLayout2->addWidget(label); SettingsPanelRenderResolutionMultiplier = new QSpinBox(SettingsPanel); SettingsPanelRenderResolutionMultiplier->setRange(1, 10); SettingsPanelRenderResolutionMultiplier->setSingleStep(1); SettingsPanelRenderResolutionMultiplier->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); SettingsPanelRenderResolutionMultiplier->setMaximumSize(QSize(16777215, 24)); SettingsPanelRenderResolutionMultiplier->setValue(CVars::r_terrain_render_resolution_multiplier.GetInt()); verticalLayout2->addWidget(SettingsPanelRenderResolutionMultiplier); label = new QLabel(SettingsPanel); label->setText(root->tr("LOD Distance Ratio: ")); label->setMaximumSize(QSize(16777215, 24)); verticalLayout2->addWidget(label); SettingsPanelLODDistanceRatio = new QDoubleSpinBox(SettingsPanel); SettingsPanelLODDistanceRatio->setRange(1.0, 10.0); SettingsPanelLODDistanceRatio->setSingleStep(0.5); SettingsPanelLODDistanceRatio->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); SettingsPanelLODDistanceRatio->setMaximumSize(QSize(16777215, 24)); SettingsPanelLODDistanceRatio->setValue(CVars::r_terrain_lod_distance_ratio.GetFloat()); verticalLayout2->addWidget(SettingsPanelLODDistanceRatio); SettingsPanelRebuildQuadtree = new QPushButton(root->tr("Rebuild QuadTrees"), SettingsPanel); verticalLayout2->addWidget(SettingsPanelRebuildQuadtree); SettingsPanelRebuildSplatMaps = new QPushButton(root->tr("Rebuild Splat Maps"), SettingsPanel); verticalLayout2->addWidget(SettingsPanelRebuildSplatMaps); SettingsPanel->setLayout(verticalLayout2); SettingsPanel->hide(); rootLayout->addWidget(SettingsPanel); } // complete widget setup rootLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding)); root->setLayout(rootLayout); } void OnWidgetChanged(EDITOR_TERRAIN_EDIT_MODE_WIDGET currentWidget) { buttonEditHeight->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT)); buttonEditLayers->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS)); buttonEditDetails->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS)); buttonEditHoles->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES)); buttonEditSections->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS)); buttonImportHeightmap->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_IMPORT_HEIGHTMAP)); buttonSettings->setChecked((currentWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_SETTINGS)); BrushPanel->hide(); EditHeightPanel->hide(); EditLayersPanel->hide(); EditDetailsPanel->hide(); EditHolesPanel->hide(); EditSectionsPanel->hide(); HeightmapImportPanel->hide(); SettingsPanel->hide(); ResetHeightmapImport(); switch (currentWidget) { case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT: BrushPanel->show(); EditHeightPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS: BrushPanel->show(); EditLayersPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS: BrushPanel->show(); EditDetailsPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES: EditHolesPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS: EditSectionsPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_IMPORT_HEIGHTMAP: HeightmapImportPanel->show(); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_SETTINGS: SettingsPanel->show(); break; } } void ResetHeightmapImport(bool clearType = true) { if (clearType) HeightmapImportPanelSourceTypeRaw8->setChecked(true); HeightmapImportPanelSourceFileName.clear(); HeightmapImportPanelSourceWidth->setText(QStringLiteral("0")); HeightmapImportPanelSourceHeight->setText(QStringLiteral("0")); HeightmapImportPanelSourcePreview->setPixmap(QPixmap()); HeightmapImportPanelDestinationStartSectionX->setValue(0); HeightmapImportPanelDestinationStartSectionY->setValue(0); HeightmapImportPanelScaleTypeNone->setChecked(true); HeightmapImportPanelScaleAmount->setValue(1); UpdateHeightmapImport(); } void UpdateHeightmapImport() { bool allow = true; uint32 pointsX = 0; uint32 pointsY = 0; if (HeightmapImportPanelSourceFileName.length() > 0) { HeightmapImportPanelSource->setText(HeightmapImportPanelSourceFileName); uint32 imageSizeX = StringConverter::StringToUInt32(ConvertQStringToString(HeightmapImportPanelSourceWidth->text())); uint32 imageSizeY = StringConverter::StringToUInt32(ConvertQStringToString(HeightmapImportPanelSourceHeight->text())); uint32 scale = (uint32)HeightmapImportPanelScaleAmount->value(); if (HeightmapImportPanelScaleTypeDownscale->isChecked()) { pointsX = imageSizeX / scale; pointsY = imageSizeY / scale; } else if (HeightmapImportPanelScaleTypeUpscale->isChecked()) { pointsX = imageSizeX * scale; pointsY = imageSizeY * scale; } else { pointsX = imageSizeX; pointsY = imageSizeY; } } else { HeightmapImportPanelSource->setText(QStringLiteral("Select Source...")); allow = false; } if (HeightmapImportPanelScaleTypeNone->isChecked()) { HeightmapImportPanelScaleAmount->setValue(1); HeightmapImportPanelScaleAmount->setEnabled(false); } else { HeightmapImportPanelScaleAmount->setEnabled(true); } HeightmapImportPanelResultSizeX->setText(QString::number(pointsX)); HeightmapImportPanelResultSizeY->setText(QString::number(pointsY)); HeightmapImportPanelImport->setEnabled(allow); } }; QWidget *EditorTerrainEditMode::CreateUI(QWidget *parentWidget) { DebugAssert(m_ui == nullptr); m_ui = new ui_EditorTerrainEditMode(); m_ui->CreateUI(parentWidget); connect(m_ui->buttonEditHeight, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetEditTerrainClicked(bool))); connect(m_ui->buttonEditDetails, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetEditDetailsClicked(bool))); connect(m_ui->buttonEditHoles, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetEditHolesClicked(bool))); connect(m_ui->buttonEditSections, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetEditSectionsClicked(bool))); connect(m_ui->buttonEditLayers, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetEditLayersClicked(bool))); connect(m_ui->buttonImportHeightmap, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetImportHeightmapClicked(bool))); connect(m_ui->buttonSettings, SIGNAL(clicked(bool)), this, SLOT(OnUIWidgetSettingsClicked(bool))); connect(m_ui->BrushPanelBrushRadius, SIGNAL(valueChanged(double)), this, SLOT(OnUIBrushRadiusChanged(double))); connect(m_ui->BrushPanelBrushFalloff, SIGNAL(valueChanged(double)), this, SLOT(OnUIBrushFalloffChanged(double))); connect(m_ui->BrushPanelBrushInvert, SIGNAL(clicked(bool)), this, SLOT(OnUIBrushInvertChanged(bool))); connect(m_ui->EditHeightPanelStepHeight, SIGNAL(valueChanged(double)), this, SLOT(OnUITerrainStepHeightChanged(double))); connect(m_ui->EditLayersPanelStepWeight, SIGNAL(valueChanged(double)), this, SLOT(OnUILayersStepWeightChanged(double))); connect(m_ui->EditLayersPanelLayerList, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(OnUILayersLayerListItemClicked(QListWidgetItem *))); connect(m_ui->EditLayersPanelEditLayers, SIGNAL(clicked()), this, SLOT(OnUILayersEditLayerListClicked())); connect(m_ui->EditSectionsActiveSectionOpsDeleteLayers, SIGNAL(clicked()), this, SLOT(OnUISectionsActiveSectionDeleteLayersClicked())); connect(m_ui->EditSectionsActiveSectionOpsDeleteSection, SIGNAL(clicked()), this, SLOT(OnUISectionsActiveSectionDeleteSectionClicked())); connect(m_ui->EditSectionsInactiveSectionOpsCreateSection, SIGNAL(clicked()), this, SLOT(OnUISectionsInactiveSectionCreateSectionClicked())); connect(m_ui->HeightmapImportPanelSourceTypeRaw8, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelSourceTypeClicked(bool))); connect(m_ui->HeightmapImportPanelSourceTypeRaw16, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelSourceTypeClicked(bool))); connect(m_ui->HeightmapImportPanelSourceTypeRawFloat, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelSourceTypeClicked(bool))); connect(m_ui->HeightmapImportPanelSource, SIGNAL(clicked()), this, SLOT(OnUIHeightmapImportPanelSelectSourceImageClicked())); connect(m_ui->HeightmapImportPanelScaleTypeNone, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelScaleTypeClicked(bool))); connect(m_ui->HeightmapImportPanelScaleTypeDownscale, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelScaleTypeClicked(bool))); connect(m_ui->HeightmapImportPanelScaleTypeUpscale, SIGNAL(clicked(bool)), this, SLOT(OnUIHeightmapImportPanelScaleTypeClicked(bool))); connect(m_ui->HeightmapImportPanelScaleAmount, SIGNAL(valueChanged(int)), this, SLOT(OnUIHeightmapImportPanelScaleAmountChanged(int))); connect(m_ui->HeightmapImportPanelImport, SIGNAL(clicked()), this, SLOT(OnUIHeightmapImportPanelImportClicked())); connect(m_ui->SettingsPanelViewDistance, SIGNAL(valueChanged(int)), this, SLOT(OnUISettingsPanelViewDistanceValueChanged(int))); connect(m_ui->SettingsPanelRenderResolutionMultiplier, SIGNAL(valueChanged(int)), this, SLOT(OnUISettingsPanelRenderResolutionMultiplierChanged(int))); connect(m_ui->SettingsPanelLODDistanceRatio, SIGNAL(valueChanged(double)), this, SLOT(OnUISettingsPanelLODDistanceRatioChanged(double))); connect(m_ui->SettingsPanelRebuildQuadtree, SIGNAL(clicked()), this, SLOT(OnUISettingsPanelRebuildQuadtreeClicked())); // create the layer list view UpdateDetailLayerList(); // update ui m_ui->OnWidgetChanged(m_eActiveWidget); // one-time filling of data BlockSignalsForCall(m_ui->BrushPanelBrushRadius)->setValue(m_brushRadius); BlockSignalsForCall(m_ui->BrushPanelBrushFalloff)->setValue(m_brushFalloff); BlockSignalsForCall(m_ui->EditHeightPanelStepHeight)->setValue(m_brushTerrainStep); BlockSignalsForCall(m_ui->EditLayersPanelStepWeight)->setValue(m_brushLayerStep); UpdateUIForSelectedSection(); return m_ui->root; } void EditorTerrainEditMode::OnUIWidgetEditTerrainClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT); } void EditorTerrainEditMode::OnUIWidgetEditDetailsClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS); } void EditorTerrainEditMode::OnUIWidgetEditHolesClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES); } void EditorTerrainEditMode::OnUIWidgetEditSectionsClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS); } void EditorTerrainEditMode::OnUIWidgetEditLayersClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS); } void EditorTerrainEditMode::OnUIWidgetImportHeightmapClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_IMPORT_HEIGHTMAP); } void EditorTerrainEditMode::OnUIWidgetSettingsClicked(bool checked) { SetActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_SETTINGS); } void EditorTerrainEditMode::OnUIBrushRadiusChanged(double value) { SetBrushRadius((float)value); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUIBrushFalloffChanged(double value) { SetBrushFalloff((float)value); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUIBrushInvertChanged(bool checked) { } void EditorTerrainEditMode::OnUITerrainStepHeightChanged(double value) { SetBrushHeightStep((float)value); } void EditorTerrainEditMode::OnUILayersStepWeightChanged(double value) { SetBrushLayerStep((float)value); } void EditorTerrainEditMode::OnUILayersLayerListItemClicked(QListWidgetItem *pListItem) { const TerrainLayerListBaseLayer *pBaseLayer = m_pTerrainData->GetLayerList()->GetBaseLayerByName(ConvertQStringToString(pListItem->text())); SetBrushLayerSelectedLayer((pBaseLayer != nullptr) ? pBaseLayer->Index : -1); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUILayersEditLayerListClicked() { } void EditorTerrainEditMode::OnUISectionsActiveSectionDeleteLayersClicked() { } void EditorTerrainEditMode::OnUISectionsActiveSectionDeleteSectionClicked() { } void EditorTerrainEditMode::OnUISectionsInactiveSectionCreateSectionClicked() { // skip if nothing we can create if (!m_validSelectedSection || m_pTerrainData->IsSectionAvailable(m_selectedSection.x, m_selectedSection.y)) return; // read the create layer and height float createHeight = 0.0f; uint8 createLayer = 0; // invoke the creation if (CreateSection(m_selectedSection.x, m_selectedSection.y, createHeight, createLayer)) { // update ui UpdateUIForSelectedSection(); } } void EditorTerrainEditMode::OnUIHeightmapImportPanelSourceTypeClicked(bool checked) { if (checked) m_ui->ResetHeightmapImport(false); } void EditorTerrainEditMode::OnUIHeightmapImportPanelSelectSourceImageClicked() { if (m_ui->HeightmapImportPanelSourceTypeImage->isChecked()) { QString filename = QFileDialog::getOpenFileName(m_pMap->GetMapWindow(), tr("Select Image..."), QStringLiteral(""), tr("Image Files (*.bmp *.jpg *.jpeg *.png)"), NULL, 0); if (filename.isEmpty()) return; QImage loadedImage; if (!loadedImage.load(filename)) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Failed to load image at ") + filename); return; } m_ui->HeightmapImportPanelSourceFileName = filename; m_ui->HeightmapImportPanelSourceWidth->setText(QString::number(loadedImage.width())); m_ui->HeightmapImportPanelSourceHeight->setText(QString::number(loadedImage.height())); QPixmap loadedImagePixmap(QPixmap::fromImage(loadedImage)); m_ui->HeightmapImportPanelSourcePreview->setPixmap(loadedImagePixmap.scaled(128, 128)); } else { QString filename = QFileDialog::getOpenFileName(m_pMap->GetMapWindow(), tr("Select Raw File..."), QStringLiteral(""), tr("Any File (*.*)"), NULL, 0); if (filename.isEmpty()) return; // calculate bytes per pixel uint32 bytesPerPixel = 1; if (m_ui->HeightmapImportPanelSourceTypeRaw16->isChecked()) bytesPerPixel = 2; else if (m_ui->HeightmapImportPanelSourceTypeRawFloat->isChecked()) bytesPerPixel = 4; // open file AutoReleasePtr<ByteStream> pStream = FileSystem::OpenFile(ConvertQStringToString(filename), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Failed to load image at ") + filename); return; } // work out dimensions, if the heightmap is >4gb we are in trouble uint32 fileSize = (uint32)pStream->GetSize(); float imageSizeF = Y_sqrtf(static_cast<float>(fileSize / bytesPerPixel)); uint32 imageSize = Math::Truncate(imageSizeF); if (Math::FractionalPart(imageSizeF) != 0.0f) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Heightmap is unacceptable or not square: ") + filename); return; } // create the image byte *pInRow = new byte[imageSize * bytesPerPixel]; QImage previewImage(imageSize, imageSize, QImage::Format_RGB32); for (uint32 y = 0; y < imageSize; y++) { // read the row if (!pStream->Read2(pInRow, imageSize * bytesPerPixel)) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Read error in heightmap: ") + filename); delete[] pInRow; return; } // process it if (m_ui->HeightmapImportPanelSourceTypeRawFloat->isChecked()) { const float *pRowPointer = reinterpret_cast<const float *>(pInRow); float minHeight = (float)m_ui->HeightmapImportPanelDestinationMinHeight->value(); float maxHeight = (float)m_ui->HeightmapImportPanelDestinationMaxHeight->value(); for (uint32 x = 0; x < imageSize; x++) { float value = (*pRowPointer - minHeight) / maxHeight; pRowPointer++; uint8 byteValue = (uint8)Math::Truncate(Math::Clamp(value * 255.0f, 0.0f, 255.0f)); previewImage.setPixel(x, y, qRgb(byteValue, byteValue, byteValue)); } } else if (m_ui->HeightmapImportPanelSourceTypeRaw16->isChecked()) { const uint16 *pRowPointer = reinterpret_cast<const uint16 *>(pInRow); for (uint32 x = 0; x < imageSize; x++) { float value = *pRowPointer / 65535.0f; pRowPointer++; uint8 byteValue = (uint8)Math::Truncate(Math::Clamp(value * 255.0f, 0.0f, 255.0f)); previewImage.setPixel(x, y, qRgb(byteValue, byteValue, byteValue)); } } else { const uint8 *pRowPointer = reinterpret_cast<const uint8 *>(pInRow); for (uint32 x = 0; x < imageSize; x++) { float value = *pRowPointer / 255.0f; pRowPointer++; uint8 byteValue = (uint8)Math::Truncate(Math::Clamp(value * 255.0f, 0.0f, 255.0f)); previewImage.setPixel(x, y, qRgb(byteValue, byteValue, byteValue)); } } } m_ui->HeightmapImportPanelSourceFileName = filename; m_ui->HeightmapImportPanelSourceWidth->setText(QString::number(previewImage.width())); m_ui->HeightmapImportPanelSourceHeight->setText(QString::number(previewImage.height())); QPixmap loadedImagePixmap(QPixmap::fromImage(previewImage.scaled(128, 128))); m_ui->HeightmapImportPanelSourcePreview->setPixmap(loadedImagePixmap); } m_ui->UpdateHeightmapImport(); } void EditorTerrainEditMode::OnUIHeightmapImportPanelScaleAmountChanged(int value) { m_ui->UpdateHeightmapImport(); } void EditorTerrainEditMode::OnUIHeightmapImportPanelScaleTypeClicked(bool checked) { if (checked) m_ui->UpdateHeightmapImport(); } void EditorTerrainEditMode::OnUIHeightmapImportPanelImportClicked() { EditorProgressDialog progressDialog(m_pMap->GetMapWindow()); progressDialog.show(); // read parameters int32 startSectionX = (int32)m_ui->HeightmapImportPanelDestinationStartSectionX->value(); int32 startSectionY = (int32)m_ui->HeightmapImportPanelDestinationStartSectionY->value(); float minHeight = (float)m_ui->HeightmapImportPanelDestinationMinHeight->value(); float maxHeight = (float)m_ui->HeightmapImportPanelDestinationMaxHeight->value(); MapSourceTerrainData::HeightmapImportScaleType scaleType = MapSourceTerrainData::HeightmapImportScaleType_None; uint32 scaleAmount = (uint32)m_ui->HeightmapImportPanelScaleAmount->value(); // fix up scale if (m_ui->HeightmapImportPanelScaleTypeDownscale->isChecked()) scaleType = MapSourceTerrainData::HeightmapImportScaleType_Downscale; else if (m_ui->HeightmapImportPanelScaleTypeUpscale->isChecked()) scaleType = MapSourceTerrainData::HeightmapImportScaleType_Upscale; else scaleAmount = 1; // load up heightmap Image heightmapImage; progressDialog.SetStatusText("Loading Heightmap..."); // for images. if (m_ui->HeightmapImportPanelSourceTypeImage->isChecked()) { QImage loadedImage; if (!loadedImage.load(m_ui->HeightmapImportPanelSourceFileName)) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Failed to load image at ") + m_ui->HeightmapImportPanelSourceFileName); return; } if (!EditorHelpers::ConvertQImageToImage(&loadedImage, &heightmapImage, PIXEL_FORMAT_R8_UNORM)) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Failed to convert image at ") + m_ui->HeightmapImportPanelSourceFileName); return; } } else { // calculate bytes per pixel uint32 bytesPerPixel = 1; if (m_ui->HeightmapImportPanelSourceTypeRaw16->isChecked()) bytesPerPixel = 2; else if (m_ui->HeightmapImportPanelSourceTypeRawFloat->isChecked()) bytesPerPixel = 4; // open file AutoReleasePtr<ByteStream> pStream = FileSystem::OpenFile(ConvertQStringToString(m_ui->HeightmapImportPanelSourceFileName), BYTESTREAM_OPEN_READ | BYTESTREAM_OPEN_STREAMED); if (pStream == nullptr) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Failed to load image at ") + m_ui->HeightmapImportPanelSourceFileName); return; } // work out dimensions, if the heightmap is >4gb we are in trouble uint32 fileSize = (uint32)pStream->GetSize(); float imageSizeF = Y_sqrtf(static_cast<float>(fileSize / bytesPerPixel)); uint32 imageSize = Math::Truncate(imageSizeF); if (Math::FractionalPart(imageSizeF) != 0.0f) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Heightmap is unacceptable or not square: ") + m_ui->HeightmapImportPanelSourceFileName); return; } // create the image if (m_ui->HeightmapImportPanelSourceTypeRawFloat->isChecked()) heightmapImage.Create(PIXEL_FORMAT_R32_FLOAT, imageSize, imageSize, 1); else if (m_ui->HeightmapImportPanelSourceTypeRaw16->isChecked()) heightmapImage.Create(PIXEL_FORMAT_R16_UNORM, imageSize, imageSize, 1); else heightmapImage.Create(PIXEL_FORMAT_R8_UNORM, imageSize, imageSize, 1); // read in image rows byte *pWritePointer = reinterpret_cast<byte *>(heightmapImage.GetData()); for (uint32 y = 0; y < imageSize; y++) { // read the row if (!pStream->Read2(pWritePointer, imageSize * bytesPerPixel)) { QMessageBox::critical(m_pMap->GetMapWindow(), tr("Image Load Error"), tr("Read error in heightmap: ") + m_ui->HeightmapImportPanelSourceFileName); return; } // increment write pointer pWritePointer += heightmapImage.GetDataRowPitch(); } } // run the import ImportHeightmap(&heightmapImage, startSectionX, startSectionY, minHeight, maxHeight, scaleType, scaleAmount, &progressDialog); // redraw m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUISettingsPanelViewDistanceValueChanged(int value) { g_pConsole->SetCVar(&CVars::r_terrain_view_distance, (int32)value); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUISettingsPanelRenderResolutionMultiplierChanged(int value) { g_pConsole->SetCVar(&CVars::r_terrain_render_resolution_multiplier, (int32)value); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUISettingsPanelLODDistanceRatioChanged(double value) { g_pConsole->SetCVar(&CVars::r_terrain_lod_distance_ratio, (float)value); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::OnUISettingsPanelRebuildQuadtreeClicked() { EditorProgressDialog progressDialog(m_pMap->GetMapWindow()); progressDialog.show(); RebuildQuadTree(m_pTerrainData->GetParameters()->LODCount, &progressDialog); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EditorTerrainEditMode::EditorTerrainEditMode(EditorMap *pMap) : EditorEditMode(pMap), m_ui(nullptr), m_pTerrainData(nullptr), m_pTerrainRenderer(nullptr), m_pBrushOverlayMaterial(nullptr), m_eActiveWidget(EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT), m_brushColor(1.0f, 1.0f, 1.0f), m_brushRadius(2.0f), m_brushFalloff(0.2f), m_brushTerrainStep(1.0f), m_brushTerrainMinHeight(0.0f), m_brushTerrainMaxHeight(0.0f), m_brushLayerStep(1.0f), m_brushLayerSelectedBaseLayer(-1), m_eCurrentState(STATE_NONE), m_mouseRayHitLocation(float3::Infinite), m_mouseOverClosestPoint(int2::Zero), m_mouseOverClosestPointPosition(float3::Zero), m_validMouseOverPosition(false), m_mouseOverSection(int2::Zero), m_validMouseOverSection(false), m_selectedSection(int2::Zero), m_validSelectedSection(false) { } EditorTerrainEditMode::~EditorTerrainEditMode() { delete m_ui; // clear the callbacks m_pTerrainData->SetEditCallbacks(nullptr); DeleteSectionRenderProxies(); SAFE_RELEASE(m_pBrushOverlayMaterial); } void EditorTerrainEditMode::SetActiveWidget(EDITOR_TERRAIN_EDIT_MODE_WIDGET widget) { if (m_eActiveWidget == widget) { // ensure the widget stays active m_ui->OnWidgetChanged(m_eActiveWidget); return; } ClearState(); m_eActiveWidget = widget; m_ui->OnWidgetChanged(m_eActiveWidget); m_pMap->GetMapWindow()->RedrawAllViewports(); } void EditorTerrainEditMode::SetBrushColor(const float3 &color) { m_brushColor = color; m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushColor", SHADER_PARAMETER_TYPE_FLOAT3, &m_brushColor); m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::SetBrushRadius(float radius) { m_brushRadius = radius; m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushRadius", SHADER_PARAMETER_TYPE_FLOAT, &m_brushRadius); UpdateBrushVisual(); m_pMap->RedrawAllViewports(); Log_InfoPrintf("Terrain brush radius now %s", StringConverter::FloatToString(radius).GetCharArray()); } void EditorTerrainEditMode::SetBrushFalloff(float falloff) { m_brushFalloff = falloff; m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushFalloff", SHADER_PARAMETER_TYPE_FLOAT, &m_brushFalloff); UpdateBrushVisual(); m_pMap->RedrawAllViewports(); Log_InfoPrintf("Terrain brush falloff now %s", StringConverter::FloatToString(falloff).GetCharArray()); } void EditorTerrainEditMode::SetBrushLayerSelectedLayer(int32 selectedLayer) { m_brushLayerSelectedBaseLayer = selectedLayer; if (m_brushLayerSelectedBaseLayer >= 0) { const TerrainLayerListGenerator::BaseLayer *pBaseLayer = m_pMap->GetMapSource()->GetTerrainData()->GetLayerListGenerator()->GetBaseLayer(selectedLayer); if (pBaseLayer != nullptr) Log_InfoPrintf("Terrain brush is now painting base layer '%s'", pBaseLayer->Name.GetCharArray()); else m_brushLayerSelectedBaseLayer = -1; } } bool EditorTerrainEditMode::Initialize(ProgressCallbacks *pProgressCallbacks) { if (!EditorEditMode::Initialize(pProgressCallbacks)) return false; // get data handle m_pTerrainData = m_pMap->GetMapSource()->GetTerrainData(); DebugAssert(m_pTerrainData != nullptr); // create renderer m_pTerrainRenderer = TerrainRenderer::CreateTerrainRenderer(m_pTerrainData->GetParameters(), m_pTerrainData->GetLayerList()); DebugAssert(m_pTerrainRenderer != nullptr); // create overlay material { AutoReleasePtr<const MaterialShader> pBrushOverlayMaterialShader = g_pResourceManager->GetMaterialShader("materials/editor/terrain_brush_overlay"); if (pBrushOverlayMaterialShader == NULL) return false; m_pBrushOverlayMaterial = new Material(); m_pBrushOverlayMaterial->Create("materials/editor/terrain_brush_overlay", pBrushOverlayMaterialShader); m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushCenter", SHADER_PARAMETER_TYPE_FLOAT3, &m_mouseOverClosestPointPosition); m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushRadius", SHADER_PARAMETER_TYPE_FLOAT, &m_brushRadius); m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushFalloff", SHADER_PARAMETER_TYPE_FLOAT, &m_brushFalloff); m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushColor", SHADER_PARAMETER_TYPE_FLOAT3, &m_brushColor); float brushRadiusForShader = m_brushRadius * (float)m_pTerrainData->GetParameters()->Scale; m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushRadius", SHADER_PARAMETER_TYPE_FLOAT, &brushRadiusForShader); } // set the callbacks and create any proxies for currently-loaded sections CreateSectionRenderProxies(); m_pTerrainData->SetEditCallbacks(static_cast<MapSourceTerrainData::EditCallbacks *>(this)); // load all sections [just for now until streaming] // this will also create the section render proxies if (!m_pTerrainData->LoadAllSections(pProgressCallbacks)) return false; return true; } void EditorTerrainEditMode::Activate() { EditorEditMode::Activate(); } void EditorTerrainEditMode::Deactivate() { // clear state variables ClearState(); EditorEditMode::Deactivate(); } void EditorTerrainEditMode::Update(const float timeSinceLastUpdate) { EditorEditMode::Update(timeSinceLastUpdate); } void EditorTerrainEditMode::OnActiveViewportChanged(EditorMapViewport *pOldActiveViewport, EditorMapViewport *pNewActiveViewport) { EditorEditMode::OnActiveViewportChanged(pOldActiveViewport, pNewActiveViewport); } bool EditorTerrainEditMode::HandleViewportKeyboardInputEvent(EditorMapViewport *pViewport, const QKeyEvent *pKeyboardEvent) { // pass to camera if (pViewport->GetViewController().HandleKeyboardEvent(pKeyboardEvent)) return true; return EditorEditMode::HandleViewportKeyboardInputEvent(pViewport, pKeyboardEvent); } bool EditorTerrainEditMode::HandleViewportMouseInputEvent(EditorMapViewport *pViewport, const QMouseEvent *pMouseEvent) { if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::LeftButton) { if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS) { BeginPaint(); return true; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::LeftButton) { if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS) { EndPaint(); return true; } else if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS) { // update the selected section m_selectedSection = m_mouseOverSection; m_validSelectedSection = m_validMouseOverSection; pViewport->FlagForRedraw(); UpdateUIForSelectedSection(); return true; } } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::MiddleButton) { } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::MiddleButton) { SmallString message; if (!m_validMouseOverPosition) message.Format("invalid mouse over position"); else message.Format("ray hit = [%f, %f, %f]\nclosest point = [%i, %i]\nposition = [%f, %f, %f]", m_mouseRayHitLocation.x, m_mouseRayHitLocation.y, m_mouseRayHitLocation.z, m_mouseOverClosestPoint.x, m_mouseOverClosestPoint.y, m_mouseOverClosestPointPosition.x, m_mouseOverClosestPointPosition.y, m_mouseOverClosestPointPosition.z); QMessageBox::information(m_pMap->GetMapWindow(), QStringLiteral("Hit information"), ConvertStringToQString(message)); } else if (pMouseEvent->type() == QEvent::MouseButtonPress && pMouseEvent->button() == Qt::RightButton) { // right mouse button can enter a viewport state. if we are not in a state, determine which state to enter. if (m_eCurrentState == STATE_NONE) { // right mouse button enters camera rotation state m_eCurrentState = STATE_CAMERA_ROTATION; // lock cursor, set cursor, and redraw pViewport->LockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_CROSS); pViewport->FlagForRedraw(); return true; } } else if (pMouseEvent->type() == QEvent::MouseButtonRelease && pMouseEvent->button() == Qt::RightButton) { // if in camera rotation state, exit it if (m_eCurrentState == STATE_CAMERA_ROTATION) { // exit the state m_eCurrentState = STATE_NONE; // reset viewport state pViewport->UnlockMouseCursor(); pViewport->SetMouseCursor(EDITOR_CURSOR_TYPE_ARROW); pViewport->FlagForRedraw(); return true; } } else if (pMouseEvent->type() == QEvent::MouseMove) { // handle mouse movement based on state switch (m_eCurrentState) { case STATE_NONE: { if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS || m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES) { // update position UpdateTerrainCoordinates(pViewport, pViewport->GetMousePosition(), false); } if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS) { // update section UpdateTerrainCoordinates(pViewport, pViewport->GetMousePosition(), true); } } break; case STATE_PAINT_TERRAIN_HEIGHT: case STATE_PAINT_TERRAIN_LAYER: { // update position, then paint it UpdateTerrainCoordinates(pViewport, pViewport->GetMousePosition(), false); UpdatePaint(); pViewport->FlagForRedraw(); return true; } break; case STATE_CAMERA_ROTATION: { // pass difference through to camera pViewport->GetViewController().RotateFromMousePosition(pViewport->GetMouseDelta()); pViewport->FlagForRedraw(); } break; } } return EditorEditMode::HandleViewportMouseInputEvent(pViewport, pMouseEvent); } bool EditorTerrainEditMode::HandleViewportWheelInputEvent(EditorMapViewport *pViewport, const QWheelEvent *pWheelEvent) { return EditorEditMode::HandleViewportWheelInputEvent(pViewport, pWheelEvent); } void EditorTerrainEditMode::ClearState() { m_eCurrentState = STATE_NONE; m_mouseRayHitLocation = float3::Infinite; m_mouseOverClosestPoint.SetZero(); m_mouseOverClosestPointPosition = float3::Infinite; m_validMouseOverPosition = false; m_mouseOverSection.SetZero(); m_validMouseOverSection = false; m_selectedSection.SetZero(); m_validSelectedSection = false; } void EditorTerrainEditMode::OnViewportDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterWorld(pViewport); switch (m_eActiveWidget) { case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT: case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS: case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_DETAILS: case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HOLES: DrawPostWorldOverlaysTerrainWidget(pViewport); break; case EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_SECTIONS: DrawPostWorldOverlaysSectionWidget(pViewport); break; } } void EditorTerrainEditMode::OnViewportDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawBeforeWorld(pViewport); } void EditorTerrainEditMode::OnViewportDrawAfterPost(EditorMapViewport *pViewport) { EditorEditMode::OnViewportDrawAfterPost(pViewport); } void EditorTerrainEditMode::OnPickingTextureDrawAfterWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawAfterWorld(pViewport); } void EditorTerrainEditMode::OnPickingTextureDrawBeforeWorld(EditorMapViewport *pViewport) { EditorEditMode::OnPickingTextureDrawBeforeWorld(pViewport); } void EditorTerrainEditMode::UpdateDetailLayerList() { // preview image size static const uint32 PREVIEW_IMAGE_SIZE = 48; // clear it to begin with m_ui->EditLayersPanelLayerList->clear(); m_ui->EditLayersPanelLayerList->setIconSize(QSize(PREVIEW_IMAGE_SIZE, PREVIEW_IMAGE_SIZE)); // reset the layer to paint m_brushLayerSelectedBaseLayer = -1; // iterate over layers const TerrainLayerListGenerator *pLayerListGenerator = m_pMap->GetMapSource()->GetTerrainData()->GetLayerListGenerator(); for (uint32 i = 0; i < TERRAIN_MAX_LAYERS; i++) { const TerrainLayerListGenerator::BaseLayer *pBaseLayer = pLayerListGenerator->GetBaseLayer(i); if (pBaseLayer == nullptr) continue; // paint this layer if it's the first one if (m_brushLayerSelectedBaseLayer < 0) m_brushLayerSelectedBaseLayer = (int32)i; // should have a base map DebugAssert(pBaseLayer->pBaseMap != nullptr); // convert it to the preview size Image resizedImage; if (!resizedImage.CopyAndResize(*pBaseLayer->pBaseMap, IMAGE_RESIZE_FILTER_LANCZOS3, PREVIEW_IMAGE_SIZE, PREVIEW_IMAGE_SIZE, 1)) { resizedImage.Create(PIXEL_FORMAT_R8G8B8_UNORM, PREVIEW_IMAGE_SIZE, PREVIEW_IMAGE_SIZE, 1); Y_memset(resizedImage.GetData(), 0xFF, resizedImage.GetDataSize()); } // load it into qt QPixmap layerPixmap; EditorHelpers::ConvertImageToQPixmap(resizedImage, &layerPixmap); // create an icon QIcon layerIcon; layerIcon.addPixmap(layerPixmap); // add it to the list m_ui->EditLayersPanelLayerList->addItem(new QListWidgetItem(layerIcon, ConvertStringToQString(pBaseLayer->Name))); } // set to first in the list if (m_ui->EditLayersPanelLayerList->count() > 0) m_ui->EditLayersPanelLayerList->setCurrentRow(0); } void EditorTerrainEditMode::UpdateTerrainCoordinates(EditorMapViewport *pViewport, const int2 &mousePosition, bool sectionOnly) { //Timer ut; // get world pick ray Ray worldRay(pViewport->GetViewController().GetPickRay(mousePosition.x, mousePosition.y)); // fastpath? if (!sectionOnly) { // issue raycast float3 contactPoint, contactNormal; if (m_pTerrainData->RayCast(worldRay, contactNormal, contactPoint)) { // transform back to world coordinates if (!m_validMouseOverPosition || !m_validMouseOverSection || contactPoint != m_mouseRayHitLocation) { // derive section from point // calculate indexed position //Log_DevPrintf("world over pos: %f %f %f", contactPoint.x, contactPoint.y, contactPoint.z); m_mouseRayHitLocation = contactPoint; m_mouseOverClosestPoint = m_pTerrainData->CalculatePointForPosition(contactPoint); m_mouseOverClosestPointPosition = m_pTerrainData->CalculatePositionForPoint(m_mouseOverClosestPoint.x, m_mouseOverClosestPoint.y); m_validMouseOverPosition = true; // update overlay material m_pBrushOverlayMaterial->SetShaderUniformParameterByName("BrushCenter", SHADER_PARAMETER_TYPE_FLOAT3, &m_mouseRayHitLocation); UpdateBrushVisual(); // redraw pViewport->FlagForRedraw(); } // is valid //Log_ProfilePrintf("terrain intersection took %.4f msec", ut.GetTimeMilliseconds()); return; } } else { float3 bestContactPoint, bestContactNormal; float3 contactPoint, contactNormal; float bestContactDistance = Y_FLT_INFINITE; float contactDistance; // null the position vars m_brushVertices.Clear(); // issue raycast against the terrain if (m_pTerrainData->RayCast(worldRay, contactNormal, contactPoint)) { // store this contact bestContactDistance = (contactPoint - worldRay.GetOrigin()).SquaredLength(); bestContactPoint = contactPoint; bestContactNormal = contactNormal; } // intersect the ground plane with the camera ray, then use these coordinates to determine the section the mouse is under Plane groundPlane(float3::UnitZ, (float)m_pTerrainData->GetParameters()->BaseHeight); if (worldRay.PlaneIntersection(groundPlane, contactNormal, contactPoint)) { contactDistance = (contactPoint - worldRay.GetOrigin()).SquaredLength(); if (contactDistance < bestContactDistance) { bestContactDistance = contactDistance; bestContactPoint = contactPoint; bestContactNormal = contactNormal; } } // the camera could be under the terrain, try a plane in the opposite direction Plane reversedPlane(-groundPlane.GetNormal(), -groundPlane.GetDistance()); if (worldRay.PlaneIntersection(reversedPlane, contactNormal, contactPoint)) { contactDistance = (contactPoint - worldRay.GetOrigin()).SquaredLength(); if (contactDistance < bestContactDistance) { bestContactDistance = contactDistance; bestContactPoint = contactPoint; bestContactNormal = contactNormal; } } // hit anything? if (bestContactDistance != Y_FLT_INFINITE) { // set the position if (!m_validMouseOverPosition || !m_validMouseOverSection || contactPoint != m_mouseRayHitLocation) { m_mouseRayHitLocation = contactPoint; m_mouseOverClosestPoint = m_pTerrainData->CalculatePointForPosition(contactPoint); m_mouseOverClosestPointPosition = m_pTerrainData->CalculatePositionForPoint(m_mouseOverClosestPoint.x, m_mouseOverClosestPoint.y); m_validMouseOverPosition = true; pViewport->FlagForRedraw(); } // set the section int2 mouseUnderSection(m_pTerrainData->CalculateSectionForPosition(contactPoint)); if (!m_validMouseOverSection || m_mouseOverSection != mouseUnderSection) { m_mouseOverSection = mouseUnderSection; m_validMouseOverSection = true; pViewport->FlagForRedraw(); UpdateUIForSelectedSection(); } // hit something //Log_ProfilePrintf("terrain intersection took %.4f msec", ut.GetTimeMilliseconds()); return; } } if (m_validMouseOverPosition || m_validMouseOverSection) { m_mouseRayHitLocation = float3::Infinite; m_mouseOverClosestPoint.SetZero(); m_validMouseOverPosition = false; m_mouseOverSection.SetZero(); m_validMouseOverSection = false; UpdateBrushVisual(); pViewport->FlagForRedraw(); UpdateUIForSelectedSection(); } //Log_ProfilePrintf("terrain intersection took %.4f msec", ut.GetTimeMilliseconds()); } void EditorTerrainEditMode::UpdateBrushVisual() { m_brushVertices.Clear(); if (!m_validMouseOverPosition) return; float3 brushCenter(m_mouseRayHitLocation); float3 brushMinBounds(brushCenter - m_brushRadius); float3 brushMaxBounds(brushCenter + m_brushRadius); AABox brushBoundingBox(brushMinBounds, brushMaxBounds); m_pTerrainData->EnumerateSectionsOverlappingBox(brushBoundingBox, [this, &brushBoundingBox](const TerrainSection *pSection) { pSection->EnumerateTrianglesIntersectingBox(brushBoundingBox, [this](const float3 vertices[3]) { PlainVertexFactory::Vertex vertex; for (uint32 i = 0; i < 3; i++) { vertex.Position = vertices[i]; vertex.TexCoord.SetZero(); vertex.Color = MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255); m_brushVertices.Add(vertex); } }); }); m_pMap->RedrawAllViewports(); } float EditorTerrainEditMode::GetBrushPaintAmount(int32 pointX, int32 pointY) const { // calculate weight float2 fClosestPoint((float)m_mouseOverClosestPoint.x, (float)m_mouseOverClosestPoint.y); float2 pointPosition(TerrainUtilities::CalculatePositionForPoint(m_pTerrainData->GetParameters(), pointX, pointY).xy()); float2 weightVector((fClosestPoint - pointPosition) / m_brushRadius); float weight = Math::Pow(1.0f - Math::Clamp(weightVector.SquaredLength(), 0.0f, 1.0f), m_brushFalloff); //Log_DevPrintf("p[%i,%i] weight = %f", pointX, pointY, weight); return weight; } bool EditorTerrainEditMode::BeginPaint() { if (!m_validMouseOverPosition) return false; // depending on widget if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_HEIGHT) { // get the height of the closest point, this becomes the 'low' height range float closestPointHeight = GetPointHeight(m_mouseOverClosestPoint.x, m_mouseOverClosestPoint.y); m_brushTerrainMinHeight = closestPointHeight; // low + step = high m_brushTerrainMaxHeight = closestPointHeight + m_brushTerrainStep; // set state m_eCurrentState = STATE_PAINT_TERRAIN_HEIGHT; // bring up the current mouse position's height UpdatePaint(); // ok! m_pMap->RedrawAllViewports(); return true; } else if (m_eActiveWidget == EDITOR_HEIGHTFIELD_TERRAIN_EDIT_MODE_WIDGET_EDIT_LAYERS) { // has a layer selected if (m_brushLayerSelectedBaseLayer < 0) return false; // start it m_eCurrentState = STATE_PAINT_TERRAIN_LAYER; UpdatePaint(); // ok! m_pMap->RedrawAllViewports(); return true; } return false; } void EditorTerrainEditMode::UpdatePaint() { if (!m_validMouseOverPosition) return; float brushRadiusInPoints = m_brushRadius / (float)m_pTerrainData->GetParameters()->Scale; int32 iBrushRadiusInPoints = (int32)Math::Ceil(brushRadiusInPoints); // find points in range of cursor int2 startPoint = m_mouseOverClosestPoint - iBrushRadiusInPoints; int2 endPoint = m_mouseOverClosestPoint + iBrushRadiusInPoints; // depending on widget if (m_eCurrentState == STATE_PAINT_TERRAIN_HEIGHT) { // use the brush paint height float heightLow = m_brushTerrainMinHeight; float heightHigh = m_brushTerrainMaxHeight; float heightRange = heightHigh - heightLow; // iterate over points for (int32 pointY = startPoint.y; pointY <= endPoint.y; pointY++) { for (int32 pointX = startPoint.x; pointX <= endPoint.x; pointX++) { // is height in range to be modified float currentHeight = GetPointHeight(pointX, pointY); //if (currentHeight > m_brushTerrainMinHeight) //continue; // calculate weight float weight = GetBrushPaintAmount(pointX, pointY); float newHeight = heightLow + weight * heightRange; //Log_DevPrintf("p[%i,%i] weight = %f, height = %f", pointX, pointY, weight, newHeight); // apply height if (currentHeight < newHeight) SetPointHeight(pointX, pointY, newHeight); } } // update brush since the height changed UpdateBrushVisual(); } else if (m_eCurrentState == STATE_PAINT_TERRAIN_LAYER) { DebugAssert(m_brushLayerSelectedBaseLayer >= 0); // iterate over points for (int32 pointY = startPoint.y; pointY <= endPoint.y; pointY++) { for (int32 pointX = startPoint.x; pointX <= endPoint.x; pointX++) { float weight = GetBrushPaintAmount(pointX, pointY); //Log_DevPrintf("p[%i,%i] weight = %f", pointX, pointY, weight); // is height in range to be modified float currentWeight = GetPointLayerWeight(pointX, pointY, (uint8)m_brushLayerSelectedBaseLayer); if (currentWeight < weight) SetPointLayerWeight(pointX, pointY, (uint8)m_brushLayerSelectedBaseLayer, m_brushLayerStep * weight); } } } } void EditorTerrainEditMode::EndPaint() { m_brushTerrainMinHeight = 0.0f; m_brushTerrainMaxHeight = 0.0f; m_eCurrentState = STATE_NONE; m_pMap->RedrawAllViewports(); } void EditorTerrainEditMode::DrawPostWorldOverlaysSectionWidget(EditorMapViewport *pViewport) { MiniGUIContext &guiContext = pViewport->GetGUIContext(); // draw the bounding box of the section with the mouse over if (m_validMouseOverSection && (!m_validSelectedSection || m_selectedSection != m_mouseOverSection)) { AABox sectionBounds(TerrainUtilities::CalculateSectionBoundingBox(m_pTerrainData->GetParameters(), m_mouseOverSection.x, m_mouseOverSection.y)); const float3 &sectionMinBounds = sectionBounds.GetMinBounds(); const float3 &sectionMaxBounds = sectionBounds.GetMaxBounds(); float baseZ = (float)m_pTerrainData->GetParameters()->BaseHeight; guiContext.SetDepthTestingEnabled(false); guiContext.SetAlphaBlendingEnabled(false); guiContext.Draw3DRect(float3(sectionMinBounds.x, sectionMaxBounds.y, baseZ), float3(sectionMinBounds.x, sectionMinBounds.y, baseZ), float3(sectionMaxBounds.x, sectionMinBounds.y, baseZ), float3(sectionMaxBounds.x, sectionMaxBounds.y, baseZ), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 255, 255)); } // and the selected section if (m_validSelectedSection) { AABox sectionBounds(TerrainUtilities::CalculateSectionBoundingBox(m_pTerrainData->GetParameters(), m_selectedSection.x, m_selectedSection.y)); const float3 &sectionMinBounds = sectionBounds.GetMinBounds(); const float3 &sectionMaxBounds = sectionBounds.GetMaxBounds(); float baseZ = (float)m_pTerrainData->GetParameters()->BaseHeight; guiContext.SetDepthTestingEnabled(false); guiContext.SetAlphaBlendingEnabled(false); guiContext.Draw3DRect(float3(sectionMinBounds.x, sectionMaxBounds.y, baseZ), float3(sectionMinBounds.x, sectionMinBounds.y, baseZ), float3(sectionMaxBounds.x, sectionMinBounds.y, baseZ), float3(sectionMaxBounds.x, sectionMaxBounds.y, baseZ), MAKE_COLOR_R8G8B8A8_UNORM(255, 255, 0, 255)); } } void EditorTerrainEditMode::DrawPostWorldOverlaysTerrainWidget(EditorMapViewport *pViewport) { if (m_brushVertices.GetSize() > 0) { GPUContext *pContext = g_pRenderer->GetGPUContext(); pContext->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pContext->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); pContext->GetConstants()->SetLocalToWorldMatrix(float4x4::Identity, true); //g_pRenderer->DrawPlainColored(pContext, m_brushVertices.GetBasePointer(), m_brushVertices.GetSize()); //g_pRenderer->DrawMaterialPlainUserPointer(pContext, m_pBrushOverlayMaterial, m_brushVertices.GetBasePointer(), m_brushVertices.GetSize()); } } void EditorTerrainEditMode::UpdateUIForSelectedSection() { if (m_validSelectedSection) { m_ui->EditSectionsNoSelection->hide(); m_ui->EditSectionsSectionInfo->show(); m_ui->EditSectionsSectionInfoSectionX->setText(ConvertStringToQString(StringConverter::Int32ToString(m_selectedSection.x))); m_ui->EditSectionsSectionInfoSectionY->setText(ConvertStringToQString(StringConverter::Int32ToString(m_selectedSection.y))); if (m_pTerrainData->IsSectionAvailable(m_selectedSection.x, m_selectedSection.y)) { m_ui->EditSectionsActiveSection->show(); m_ui->EditSectionsActiveSectionOps->show(); m_ui->EditSectionsInactiveSection->hide(); m_ui->EditSectionsInactiveSectionOps->hide(); const TerrainSection *pSection = m_pTerrainData->GetSection(m_selectedSection.x, m_selectedSection.y); if (pSection != nullptr) { m_ui->EditSectionsActiveSectionNodeCount->setText(ConvertStringToQString(StringConverter::Int32ToString(pSection->GetQuadTree()->GetNodeCount()))); m_ui->EditSectionsActiveSectionSplatMapCount->setText(ConvertStringToQString(StringConverter::Int32ToString(pSection->GetSplatMapCount()))); } } else { m_ui->EditSectionsActiveSection->hide(); m_ui->EditSectionsActiveSectionOps->hide(); m_ui->EditSectionsInactiveSection->show(); m_ui->EditSectionsInactiveSectionOps->show(); } } else { // mouse over? if (m_validMouseOverSection) { m_ui->EditSectionsNoSelection->hide(); m_ui->EditSectionsSectionInfo->show(); m_ui->EditSectionsSectionInfoSectionX->setText(ConvertStringToQString(StringConverter::Int32ToString(m_mouseOverSection.x))); m_ui->EditSectionsSectionInfoSectionY->setText(ConvertStringToQString(StringConverter::Int32ToString(m_mouseOverSection.y))); } else { m_ui->EditSectionsNoSelection->show(); m_ui->EditSectionsSectionInfo->hide(); } m_ui->EditSectionsActiveSection->hide(); m_ui->EditSectionsActiveSectionOps->hide(); m_ui->EditSectionsInactiveSection->hide(); m_ui->EditSectionsInactiveSectionOps->hide(); } } bool EditorTerrainEditMode::CreateSection(int32 sectionX, int32 sectionY, float createHeight, uint8 createLayer) { if (m_pTerrainData->IsSectionAvailable(sectionX, sectionY)) return false; EditorProgressDialog progressDialog(m_pMap->GetMapWindow()); progressDialog.show(); if (!m_pTerrainData->CreateSection(sectionX, sectionY, createHeight, createLayer, &progressDialog)) return false; // update bounding box of map m_pMap->MergeMapBoundingBox(m_pTerrainData->CalculateTerrainBoundingBox()); return true; } bool EditorTerrainEditMode::DeleteSection(int32 sectionX, int32 sectionY) { if (!m_pTerrainData->IsSectionAvailable(sectionX, sectionY)) return false; EditorProgressDialog progressDialog(m_pMap->GetMapWindow()); progressDialog.show(); m_pTerrainData->DeleteSection(sectionX, sectionY, &progressDialog); return true; } bool EditorTerrainEditMode::ImportHeightmap(const Image *pHeightmap, int32 startSectionX, int32 startSectionY, float minHeight, float maxHeight, MapSourceTerrainData::HeightmapImportScaleType scaleType, uint32 scaleAmount, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // delete all section render proxies, and unset the callback interface. this way it'll be a lot faster. DeleteSectionRenderProxies(); m_pTerrainData->SetEditCallbacks(nullptr); // run the import bool importResult = m_pTerrainData->ImportHeightmap(pHeightmap, startSectionX, startSectionY, minHeight, maxHeight, scaleType, scaleAmount, pProgressCallbacks); // re-create section render proxies, and the callback interface CreateSectionRenderProxies(); m_pTerrainData->SetEditCallbacks(static_cast<MapSourceTerrainData::EditCallbacks *>(this)); // update bounding box of map if (importResult) m_pMap->MergeMapBoundingBox(m_pTerrainData->CalculateTerrainBoundingBox()); // done return importResult; } bool EditorTerrainEditMode::RebuildQuadTree(uint32 newLodCount, ProgressCallbacks *pProgressCallbacks /* = ProgressCallbacks::NullProgressCallback */) { // delete all section render proxies, and unset the callback interface. this way it'll be a lot faster. DeleteSectionRenderProxies(); m_pTerrainData->SetEditCallbacks(nullptr); // run the rebuild bool rebuildResult = m_pTerrainData->RebuildQuadTree(newLodCount, pProgressCallbacks); // re-create section render proxies, and the callback interface CreateSectionRenderProxies(); m_pTerrainData->SetEditCallbacks(static_cast<MapSourceTerrainData::EditCallbacks *>(this)); // done return rebuildResult; } void EditorTerrainEditMode::OnSectionCreated(int32 sectionX, int32 sectionY) { Log_DevPrintf("EditorTerrainEditMode::OnSectionCreated: Section created: [%i, %i]", sectionX, sectionY); } void EditorTerrainEditMode::OnSectionDeleted(int32 sectionX, int32 sectionY) { Log_DevPrintf("EditorTerrainEditMode::OnSectionDeleted: Section deleted: [%i, %i]", sectionX, sectionY); } void EditorTerrainEditMode::OnSectionLoaded(const TerrainSection *pSection) { Log_DevPrintf("EditorTerrainEditMode::OnSectionLoaded: Section loaded: [%i, %i]", pSection->GetSectionX(), pSection->GetSectionY()); // shouldn't have a render proxy for it DebugAssert(GetSectionRenderProxy(pSection->GetSectionX(), pSection->GetSectionY()) == nullptr); // so create one TerrainSectionRenderProxy *pRenderProxy = m_pTerrainRenderer->CreateSectionRenderProxy(0, pSection); DebugAssert(pRenderProxy != nullptr); // and add it to the world m_pMap->GetRenderWorld()->AddRenderable(pRenderProxy); m_sectionRenderProxies.Add(pRenderProxy); } void EditorTerrainEditMode::OnSectionUnloaded(const TerrainSection *pSection) { Log_DevPrintf("EditorTerrainEditMode::OnSectionUnloaded: Section unloaded: [%i, %i]", pSection->GetSectionX(), pSection->GetSectionY()); // do we have a render proxy for it? for (uint32 i = 0; i < m_sectionRenderProxies.GetSize(); i++) { TerrainSectionRenderProxy *pRenderProxy = m_sectionRenderProxies[i]; if (pRenderProxy->GetSection() == pSection) { // remove it m_sectionRenderProxies.OrderedRemove(i); m_pMap->GetRenderWorld()->RemoveRenderable(pRenderProxy); pRenderProxy->Release(); break; } } // shouldn't have any other proxies DebugAssert(GetSectionRenderProxy(pSection->GetSectionX(), pSection->GetSectionY())); } void EditorTerrainEditMode::OnSectionLayersModified(const TerrainSection *pSection) { // have a proxy? TerrainSectionRenderProxy *pRenderProxy = GetSectionRenderProxy(pSection); if (pRenderProxy != nullptr) pRenderProxy->OnLayersModified(); } void EditorTerrainEditMode::OnSectionPointHeightModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY) { // have a proxy? TerrainSectionRenderProxy *pRenderProxy = GetSectionRenderProxy(pSection); if (pRenderProxy != nullptr) pRenderProxy->OnPointHeightModified(offsetX, offsetY); } void EditorTerrainEditMode::OnSectionPointLayersModified(const TerrainSection *pSection, uint32 offsetX, uint32 offsetY) { // have a proxy? TerrainSectionRenderProxy *pRenderProxy = GetSectionRenderProxy(pSection); if (pRenderProxy != nullptr) pRenderProxy->OnPointLayersModified(offsetX, offsetY); } TerrainSectionRenderProxy *EditorTerrainEditMode::GetSectionRenderProxy(const TerrainSection *pSection) { for (uint32 i = 0; i < m_sectionRenderProxies.GetSize(); i++) { if (m_sectionRenderProxies[i]->GetSection() == pSection) return m_sectionRenderProxies[i]; } return nullptr; } TerrainSectionRenderProxy *EditorTerrainEditMode::GetSectionRenderProxy(int32 sectionX, int32 sectionY) { for (uint32 i = 0; i < m_sectionRenderProxies.GetSize(); i++) { if (m_sectionRenderProxies[i]->GetSectionX() == sectionX && m_sectionRenderProxies[i]->GetSectionY() == sectionY) return m_sectionRenderProxies[i]; } return nullptr; } bool EditorTerrainEditMode::CreateSectionRenderProxy(int32 sectionX, int32 sectionY) { DebugAssert(GetSectionRenderProxy(sectionX, sectionY) == nullptr); const TerrainSection *pSection = m_pTerrainData->GetSection(sectionX, sectionY); DebugAssert(pSection != nullptr); TerrainSectionRenderProxy *pRenderProxy = m_pTerrainRenderer->CreateSectionRenderProxy(0, pSection); if (pRenderProxy == nullptr) return false; m_pMap->GetRenderWorld()->AddRenderable(pRenderProxy); m_sectionRenderProxies.Add(pRenderProxy); return true; } void EditorTerrainEditMode::DeleteSectionRenderProxy(int32 sectionX, int32 sectionY) { for (uint32 i = 0; i < m_sectionRenderProxies.GetSize(); i++) { TerrainSectionRenderProxy *pRenderProxy = m_sectionRenderProxies[i]; if (pRenderProxy->GetSectionX() == sectionX && pRenderProxy->GetSectionY() == sectionY) { m_sectionRenderProxies.OrderedRemove(i); m_pMap->GetRenderWorld()->RemoveRenderable(pRenderProxy); pRenderProxy->Release(); return; } } } bool EditorTerrainEditMode::CreateSectionRenderProxies() { bool result = true; m_pTerrainData->EnumerateLoadedSections([this, &result](const TerrainSection *pSection) { if (GetSectionRenderProxy(pSection->GetSectionX(), pSection->GetSectionY()) != nullptr) return; TerrainSectionRenderProxy *pRenderProxy = m_pTerrainRenderer->CreateSectionRenderProxy(0, pSection); if (pRenderProxy == nullptr) { result = false; return; } m_pMap->GetRenderWorld()->AddRenderable(pRenderProxy); m_sectionRenderProxies.Add(pRenderProxy); }); return result; } void EditorTerrainEditMode::DeleteSectionRenderProxies() { for (uint32 i = 0; i < m_sectionRenderProxies.GetSize(); i++) { TerrainSectionRenderProxy *pRenderProxy = m_sectionRenderProxies[i]; m_pMap->GetRenderWorld()->RemoveRenderable(pRenderProxy); pRenderProxy->Release(); } m_sectionRenderProxies.Obliterate(); } <file_sep>/Editor/Source/Editor/MapEditor/EditorEntityIdWorldRenderer.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/MapEditor/EditorEntityIdWorldRenderer.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderQueue.h" #include "Renderer/Renderer.h" #include "Renderer/ShaderProgram.h" #include "Renderer/Shaders/OneColorShader.h" #include "Engine/Material.h" EditorEntityIdWorldRenderer::EditorEntityIdWorldRenderer(GPUContext *pGPUContext, const Options *pOptions) : SingleShaderWorldRenderer(pGPUContext, pOptions) { const uint32 availableRenderPassMask = RENDER_PASS_LIGHTMAP | RENDER_PASS_EMISSIVE | RENDER_PASS_STATIC_LIGHTING | RENDER_PASS_DYNAMIC_LIGHTING | RENDER_PASS_SHADOWED_LIGHTING | RENDER_PASS_TINT; m_renderQueue.SetAcceptingLights(false); m_renderQueue.SetAcceptingRenderPassMask(availableRenderPassMask); m_renderQueue.SetAcceptingOccluders(false); m_renderQueue.SetAcceptingDebugObjects(false); } EditorEntityIdWorldRenderer::~EditorEntityIdWorldRenderer() { } void EditorEntityIdWorldRenderer::DrawQueueEntry(const ViewParameters *pViewParameters, RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry) { ShaderProgram *pShaderProgram; if ((pShaderProgram = GetShaderProgram(OBJECT_TYPEINFO(OneColorShader), 0, pQueueEntry)) == NULL) return; m_pGPUContext->SetShaderProgram(pShaderProgram->GetGPUProgram()); m_pGPUContext->SetRasterizerState(pQueueEntry->pMaterial->GetShader()->SelectRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK, false, false)); m_pGPUContext->SetDepthStencilState(pQueueEntry->pMaterial->GetShader()->SelectDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); SetBlendingModeForMaterial(m_pGPUContext, pQueueEntry); SetCommonShaderProgramParameters(pViewParameters, pQueueEntry, pShaderProgram); OneColorShader::SetColor(m_pGPUContext, pShaderProgram, PixelFormatHelpers::ConvertRGBAToFloat4(pQueueEntry->pRenderProxy->GetEntityId())); pQueueEntry->pRenderProxy->DrawQueueEntry(&pViewParameters->ViewCamera, pQueueEntry, m_pGPUContext); } <file_sep>/Engine/Source/Renderer/WorldRenderers/CSMShadowMapRenderer.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/WorldRenderers/CSMShadowMapRenderer.h" #include "Renderer/Shaders/ShadowMapShader.h" #include "Renderer/ShaderProgramSelector.h" #include "Renderer/RenderWorld.h" #include "Renderer/RenderQueue.h" #include "Renderer/RenderProfiler.h" #include "Renderer/Renderer.h" #include "Engine/Material.h" #include "Engine/EngineCVars.h" #include "Engine/Profiling.h" Log_SetChannel(CSMShadowMapRenderer); CSMShadowMapRenderer::CSMShadowMapRenderer(uint32 shadowMapResolution /* = 256 */, PIXEL_FORMAT shadowMapFormat /* = PIXEL_FORMAT_D16_UNORM */, uint32 cascadeCount /* = 3 */, float splitLambda /* = 0.95f */) : m_shadowMapResolution(shadowMapResolution), m_shadowMapFormat(shadowMapFormat), m_cascadeCount(cascadeCount), m_splitLambda(splitLambda) { Y_memzero(m_splitDepths, sizeof(m_splitDepths)); m_renderQueue.SetAcceptingLights(false); m_renderQueue.SetAcceptingRenderPassMask(RENDER_PASS_SHADOW_MAP); m_renderQueue.SetAcceptingOccluders(false); m_renderQueue.SetAcceptingDebugObjects(false); } CSMShadowMapRenderer::~CSMShadowMapRenderer() { } bool CSMShadowMapRenderer::AllocateShadowMap(ShadowMapData *pShadowMapData) { // store vars pShadowMapData->IsActive = false; pShadowMapData->CascadeCount = m_cascadeCount; Y_memzero(pShadowMapData->ViewProjectionMatrices, sizeof(pShadowMapData->ViewProjectionMatrices)); Y_memzero(pShadowMapData->CascadeFrustumEyeSpaceDepths, sizeof(pShadowMapData->CascadeFrustumEyeSpaceDepths)); // create descriptor GPU_TEXTURE2D_DESC textureDesc(m_shadowMapResolution * m_cascadeCount, m_shadowMapResolution, m_shadowMapFormat, GPU_TEXTURE_FLAG_SHADER_BINDABLE | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER, 1); GPU_SAMPLER_STATE_DESC samplerStateDesc(TEXTURE_FILTER_MIN_MAG_MIP_POINT, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_BORDER, TEXTURE_ADDRESS_MODE_CLAMP, float4::One, 0, 0, 0, 0, GPU_COMPARISON_FUNC_NEVER); // hardware pcf? if (CVars::r_shadow_use_hardware_pcf.GetBool()) { samplerStateDesc.Filter = TEXTURE_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; samplerStateDesc.ComparisonFunc = GPU_COMPARISON_FUNC_LESS; } // create it Log_PerfPrintf("CSMShadowMapRenderer::AllocateShadowMap: Allocating new %u x %u x %s texture", textureDesc.Width, textureDesc.Height, NameTable_GetNameString(NameTables::PixelFormat, m_shadowMapFormat)); pShadowMapData->pShadowMapTexture = g_pRenderer->CreateTexture2D(&textureDesc, &samplerStateDesc); if (pShadowMapData->pShadowMapTexture == nullptr) return false; // create views GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC dbvDesc(pShadowMapData->pShadowMapTexture, 0); if ((pShadowMapData->pShadowMapDSV = g_pRenderer->CreateDepthStencilBufferView(pShadowMapData->pShadowMapTexture, &dbvDesc)) == nullptr) { pShadowMapData->pShadowMapTexture->Release(); pShadowMapData->pShadowMapTexture = nullptr; return false; } // ok return true; } void CSMShadowMapRenderer::FreeShadowMap(ShadowMapData *pShadowMapData) { pShadowMapData->pShadowMapDSV->Release(); pShadowMapData->pShadowMapTexture->Release(); } void CSMShadowMapRenderer::CalculateSplitDepths(const Camera *pViewCamera, float shadowDistance) { // far distance is max of camera far and shadow distance float nearDistance = pViewCamera->GetNearPlaneDistance(); float farDistance = shadowDistance; // calculate each split depth for (uint32 splitIndex = 0; splitIndex <= m_cascadeCount; splitIndex++) { float fLog = nearDistance * Y_powf((farDistance / nearDistance), (float)splitIndex / (float)m_cascadeCount); float fLinear = nearDistance + (farDistance - nearDistance) * ((float)splitIndex / (float)m_cascadeCount); m_splitDepths[splitIndex] = fLog * m_splitLambda + fLinear * (1.0f - m_splitLambda); } // // calculate for far // float farDistance = viewFarDistance; // float fLog = viewNearDistance * Y_powf((farDistance / viewNearDistance), (float)(splitIndex + 1) / (float)splitCount); // float fLinear = viewNearDistance + (farDistance - viewNearDistance) * ((float)(splitIndex + 1) / (float)splitCount); // *pFarDistance = fLog * lambda + fLinear * (1.0f - lambda); } static void GetViewCameraFrustumCorners(float3 *pOutPoints, const Camera *pViewCamera, float overrideNearPlaneDistance, float overrideFarPlaneDistance) { if (pViewCamera->GetProjectionType() == CAMERA_PROJECTION_TYPE_PERSPECTIVE) { // get forward vector float3 forwardVector((-pViewCamera->GetViewMatrix().GetRow(2).xyz()).Normalize()); float3 upVector(pViewCamera->GetViewMatrix().GetRow(1).xyz().Normalize()); float3 leftVector((-pViewCamera->GetViewMatrix().GetRow(0).xyz()).Normalize()); // get near/far plane centers float3 nearPlaneCenter(pViewCamera->GetPosition() + forwardVector * overrideNearPlaneDistance); float3 farPlaneCenter(pViewCamera->GetPosition() + forwardVector * overrideFarPlaneDistance); // get v/h extent locations from center float viewAngle = Math::DegreesToRadians(pViewCamera->GetPerspectiveFieldOfView()); float nearExtentDistance = Y_tanf(viewAngle / 2.0f) * overrideNearPlaneDistance; float3 nearExtentY = upVector * nearExtentDistance; float3 nearExtentX = leftVector * (pViewCamera->GetPerspectiveAspect() * nearExtentDistance); float farExtentDistance = Y_tanf(viewAngle / 2.0f) * overrideFarPlaneDistance; float3 farExtentY = upVector * farExtentDistance; float3 farExtentX = leftVector * (pViewCamera->GetPerspectiveAspect() * farExtentDistance); // find corners by adding/subtracting extents pOutPoints[0] = nearPlaneCenter + nearExtentY - nearExtentX; pOutPoints[1] = nearPlaneCenter + nearExtentY + nearExtentX; pOutPoints[2] = nearPlaneCenter - nearExtentY + nearExtentX; pOutPoints[3] = nearPlaneCenter - nearExtentY - nearExtentX; pOutPoints[4] = farPlaneCenter + farExtentY - farExtentX; pOutPoints[5] = farPlaneCenter + farExtentY + farExtentX; pOutPoints[6] = farPlaneCenter - farExtentY + farExtentX; pOutPoints[7] = farPlaneCenter - farExtentY - farExtentX; } else { Camera cloneCamera(*pViewCamera); cloneCamera.SetNearFarPlaneDistances(overrideNearPlaneDistance, overrideFarPlaneDistance); cloneCamera.GetFrustum().GetCornerVertices(pOutPoints); } } void CSMShadowMapRenderer::CalculateViewDependantVariables(const Camera *pViewCamera) { // get world-space corners of view camera //float3 frustumCornersWS[8]; float3 *frustumCornersWS = m_frustumCornersVS; GetViewCameraFrustumCorners(frustumCornersWS, pViewCamera, pViewCamera->GetNearPlaneDistance(), pViewCamera->GetFarPlaneDistance()); // transform world-space corners of view camera to view space for (uint32 i = 0; i < 8; i++) m_frustumCornersVS[i] = pViewCamera->GetViewMatrix().TransformPoint(frustumCornersWS[i]); } void CSMShadowMapRenderer::BuildCascadeCamera(Camera *pOutCascadeCamera, const Camera *pViewCamera, const float3 &lightDirection, uint32 splitIndex, uint32 splitCount, float lambda, float shadowDrawDistance, const RenderWorld *pRenderWorld) { // bring the nearZ back to 80%, for better results at split point float nearZ = (splitIndex > 0) ? m_splitDepths[splitIndex] * 0.8f : m_splitDepths[splitIndex]; float farZ = m_splitDepths[splitIndex + 1]; // shorten view frustum according to shadow view distance float3 splitFrustumCornersVS[8]; for (uint32 i = 0; i < 4; i++) splitFrustumCornersVS[i] = m_frustumCornersVS[i + 4] * (nearZ / pViewCamera->GetFarPlaneDistance()); for (uint32 i = 4; i < 8; i++) splitFrustumCornersVS[i] = m_frustumCornersVS[i] * (farZ / pViewCamera->GetFarPlaneDistance()); // transform back to world-space float3 frustumCornersWS[8]; for (uint32 i = 0; i < 8; i++) frustumCornersWS[i] = pViewCamera->GetInverseViewMatrix().TransformPoint(splitFrustumCornersVS[i]); // find the centroid float3 frustumCentroid(float3::Zero); for (uint32 i = 0; i < 8; i++) frustumCentroid += frustumCornersWS[i]; frustumCentroid /= 8.0f; // position shadow-caster camera so that it's looking at the centroid, backed up direction of light float distFromCentroid = Max((farZ - nearZ), splitFrustumCornersVS[4].Distance(splitFrustumCornersVS[5])) + 100.0f; pOutCascadeCamera->SetPosition(frustumCentroid - (lightDirection * distFromCentroid)); pOutCascadeCamera->SetRotation((Quaternion::FromTwoUnitVectors(float3::NegativeUnitZ, lightDirection) * Quaternion::FromEulerAngles(-90.0f, 0.0f, 0.0f)).Normalize()); // determine position of frustum corners in light space float3 frustumCornersLS[8]; for (uint32 i = 0; i < 8; i++) frustumCornersLS[i] = pOutCascadeCamera->GetViewMatrix().TransformPoint(frustumCornersWS[i]); // create orthographic projection by sizing bounding box to frustum coordinates in light space float3 minBounds(frustumCornersLS[0]); float3 maxBounds(frustumCornersLS[0]); for (uint32 i = 1; i < 8; i++) { minBounds = minBounds.Min(frustumCornersLS[i]); maxBounds = maxBounds.Max(frustumCornersLS[i]); } // snap camera in one texel increments float diagonalLength = (frustumCornersWS[0] - frustumCornersWS[6]).Length() + 2.0f; float worldUnitsPerTexel = diagonalLength / (float)m_shadowMapResolution; float3 borderOffset((float3(diagonalLength) - (maxBounds - minBounds)) * 0.5f); maxBounds += borderOffset; minBounds -= borderOffset; minBounds /= worldUnitsPerTexel; minBounds = minBounds.Floor(); minBounds *= worldUnitsPerTexel; maxBounds /= worldUnitsPerTexel; maxBounds = maxBounds.Floor(); maxBounds *= worldUnitsPerTexel; // create orthographic camera const float nearClipOffset = 100.0f; pOutCascadeCamera->SetProjectionType(CAMERA_PROJECTION_TYPE_ORTHOGRAPHIC); pOutCascadeCamera->SetOrthographicWindow(minBounds.x, maxBounds.x, minBounds.y, maxBounds.y); pOutCascadeCamera->SetNearFarPlaneDistances(-maxBounds.z - nearClipOffset, -minBounds.z); pOutCascadeCamera->SetObjectCullDistance(shadowDrawDistance); // align to texels { float halfShadowMapSize = (float)m_shadowMapResolution * 0.5f; float2 shadowOrigin(pOutCascadeCamera->GetViewProjectionMatrix().TransformPoint(float3::Zero).xy() * halfShadowMapSize); float2 roundedOrigin(shadowOrigin.Round()); float2 rounding = (roundedOrigin - shadowOrigin) / halfShadowMapSize; float4x4 roundingMatrix = float4x4::MakeTranslationMatrix(rounding.x, rounding.y, 0.0f); // apply after projection pOutCascadeCamera->SetProjectionMatrix(roundingMatrix * pOutCascadeCamera->GetProjectionMatrix()); } } void CSMShadowMapRenderer::DrawShadowMap(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { // draw using multipass technique DrawMultiPass(pCommandList, pShadowMapData, pViewCamera, shadowDistance, pRenderWorld, pLight); } void CSMShadowMapRenderer::DrawMultiPass(GPUCommandList *pCommandList, ShadowMapData *pShadowMapData, const Camera *pViewCamera, float shadowDistance, const RenderWorld *pRenderWorld, const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLight) { MICROPROFILE_SCOPEI("CSMShadowMapRenderer", "DrawMultiPass", MICROPROFILE_COLOR(200, 47, 85)); // work out shadow draw distance float shadowDrawDistance = Min(shadowDistance, pViewCamera->GetFarPlaneDistance() - pViewCamera->GetNearPlaneDistance()); // set common states pCommandList->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); pCommandList->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(true, true, GPU_COMPARISON_FUNC_LESS), 0); pCommandList->SetRenderTargets(0, nullptr, pShadowMapData->pShadowMapDSV); pCommandList->ClearTargets(false, true, false, float4::Zero, 1.0f); // calculate split depths CalculateSplitDepths(pViewCamera, shadowDrawDistance); // calculate scene-dependant variables CalculateViewDependantVariables(pViewCamera); // draw each cascade individually for (uint32 i = 0; i < m_cascadeCount; i++) { // calculate viewport for this cascade RENDERER_VIEWPORT shadowMapViewport(i * m_shadowMapResolution, 0, m_shadowMapResolution, m_shadowMapResolution, 0.0f, 1.0f); pCommandList->SetViewport(&shadowMapViewport); // get camera Camera lightCamera; BuildCascadeCamera(&lightCamera, pViewCamera, pLight->Direction, i, m_cascadeCount, m_splitLambda, shadowDrawDistance, pRenderWorld); // add cascade camera //RENDER_PROFILER_ADD_CAMERA(pRenderProfiler, &lightCamera, String::FromFormat("PSSM cascade %u camera", i)); // store vp matrix pShadowMapData->CascadeFrustumEyeSpaceDepths[i] = m_splitDepths[i + 1]; pShadowMapData->ViewProjectionMatrices[i] = lightCamera.GetViewProjectionMatrix(); g_pRenderer->GetGPUDevice()->CorrectProjectionMatrix(pShadowMapData->ViewProjectionMatrices[i]); // follow the normal process... clear queue m_renderQueue.Clear(); // find renderables { MICROPROFILE_SCOPEI("CSMShadowMapRenderer", "EnumerateRenderables", MICROPROFILE_COLOR(47, 200, 85)); // find everything in this cascade's frustum pRenderWorld->EnumerateRenderablesInFrustum(lightCamera.GetFrustum(), [this, &lightCamera](const RenderProxy *pRenderProxy) { // add to render queue pRenderProxy->QueueForRender(&lightCamera, &m_renderQueue); }); // sort queue m_renderQueue.Sort(); } // got any? if (!m_renderQueue.GetQueueSize()) continue; // set constants pCommandList->GetConstants()->SetFromCamera(lightCamera, true); // draw opaque objects { MICROPROFILE_SCOPEI("CSMShadowMapRenderer", "DrawOpaqueObjects", MICROPROFILE_COLOR(47, 85, 200)); // initialize selector -- fixme for global flags? ShaderProgramSelector shaderSelector(0); shaderSelector.SetBaseShader(OBJECT_TYPEINFO(ShadowMapShader), 0); // loop renderables RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetOpaqueRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetOpaqueRenderables().GetBasePointer() + m_renderQueue.GetOpaqueRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { DebugAssert(pQueueEntry->RenderPassMask & RENDER_PASS_SHADOW_MAP); // For now, only masked materials are drawn with clipping shaderSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); shaderSelector.SetMaterial((pQueueEntry->pMaterial->GetShader()->GetBlendMode() == MATERIAL_BLENDING_MODE_MASKED) ? pQueueEntry->pMaterial : nullptr); // only continue with shader ShaderProgram *pShaderProgram = shaderSelector.MakeActive(pCommandList); if (pShaderProgram != nullptr) { pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pCommandList); } } } // draw transparent objects { MICROPROFILE_SCOPEI("CSMShadowMapRenderer", "DrawTransparentObjects", MICROPROFILE_COLOR(200, 85, 47)); // initialize selector ShaderProgramSelector shaderSelector(0); shaderSelector.SetBaseShader(OBJECT_TYPEINFO(ShadowMapShader), 0); // loop renderables RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry = m_renderQueue.GetTranslucentRenderables().GetBasePointer(); RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntryEnd = m_renderQueue.GetTranslucentRenderables().GetBasePointer() + m_renderQueue.GetTranslucentRenderables().GetSize(); for (; pQueueEntry != pQueueEntryEnd; pQueueEntry++) { DebugAssert(pQueueEntry->RenderPassMask & RENDER_PASS_SHADOW_MAP); // For now, only masked materials are drawn with clipping shaderSelector.SetVertexFactory(pQueueEntry->pVertexFactoryTypeInfo, pQueueEntry->VertexFactoryFlags); shaderSelector.SetMaterial((pQueueEntry->pMaterial->GetShader()->GetBlendMode() != MATERIAL_BLENDING_MODE_NONE) ? pQueueEntry->pMaterial : nullptr); // only continue with shader ShaderProgram *pShaderProgram = shaderSelector.MakeActive(pCommandList); if (pShaderProgram != nullptr) { pQueueEntry->pRenderProxy->SetupForDraw(&lightCamera, pQueueEntry, pCommandList, pShaderProgram); pQueueEntry->pRenderProxy->DrawQueueEntry(&lightCamera, pQueueEntry, pCommandList); } } } } // set everything else to infinte as not to break it for (uint32 i = m_cascadeCount; i < MaxCascadeCount; i++) pShadowMapData->CascadeFrustumEyeSpaceDepths[i] = Y_FLT_INFINITE; } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunkCollisionShape.cpp #include "BlockEngine/PrecompiledHeader.h" #include "BlockEngine/BlockWorldChunkCollisionShape.h" #include "BlockEngine/BlockWorldChunk.h" #include "Engine/BlockPalette.h" #include "Engine/Physics/BulletHeaders.h" Log_SetChannel(BlockWorldChunkCollisionShape); ATTRIBUTE_ALIGNED16(class) btBlockWorldChunkCollisionShape : public btConcaveShape { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btBlockWorldChunkCollisionShape(const BlockPalette *pPalette, uint32 chunkSize, const BlockWorldChunk *pChunk) : btConcaveShape(), m_pPalette(pPalette), m_chunkSize(chunkSize), m_pChunk(pChunk), m_aabbMin(0.0f, 0.0f, 0.0f), m_aabbMax((float)chunkSize, (float)chunkSize, (float)chunkSize), m_localScaling(1.0f, 1.0f, 1.0f) { m_shapeType = CUSTOM_CONCAVE_SHAPE_TYPE; } virtual ~btBlockWorldChunkCollisionShape() { } virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const { aabbMin = t(m_aabbMin); aabbMax = t(m_aabbMax); } virtual void setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; } virtual const btVector3& getLocalScaling() const { return m_localScaling; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual const char* getName() const { return "btBlockTerrainCollisionShape"; } private: const BlockPalette *m_pPalette; uint32 m_chunkSize; const BlockWorldChunk *m_pChunk; btVector3 m_aabbMin; btVector3 m_aabbMax; btVector3 m_localScaling; }; BlockWorldChunkCollisionShape::BlockWorldChunkCollisionShape(const BlockPalette *pPalette, uint32 chunkSize, const BlockWorldChunk *pChunk) { // create bullet shape m_pBulletShape = new btBlockWorldChunkCollisionShape(pPalette, chunkSize, pChunk); m_boundingBox.SetBounds(float3::Zero, float3((float)chunkSize, (float)chunkSize, (float)chunkSize)); } BlockWorldChunkCollisionShape::~BlockWorldChunkCollisionShape() { delete m_pBulletShape; } const Physics::COLLISION_SHAPE_TYPE BlockWorldChunkCollisionShape::GetType() const { return Physics::COLLISION_SHAPE_TYPE_CUSTOM; } const AABox &BlockWorldChunkCollisionShape::GetLocalBoundingBox() const { return m_boundingBox; } bool BlockWorldChunkCollisionShape::LoadFromData(const void *pData, uint32 dataSize) { return false; } bool BlockWorldChunkCollisionShape::LoadFromStream(ByteStream *pStream, uint32 dataSize) { return false; } Physics::CollisionShape *BlockWorldChunkCollisionShape::CreateScaledShape(const float3 &scale) const { Panic("Should never be called."); return NULL; } void BlockWorldChunkCollisionShape::ApplyShapeTransform(btTransform &worldTransform) const { } void BlockWorldChunkCollisionShape::ApplyInverseShapeTransform(btTransform &worldTransform) const { } btCollisionShape *BlockWorldChunkCollisionShape::GetBulletShape() const { return static_cast<btCollisionShape *>(m_pBulletShape); } void btBlockWorldChunkCollisionShape::calculateLocalInertia(btScalar mass, btVector3& inertia) const { //moving concave objects not supported inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } static inline btVector3 GetBlockVertexPosition(const btVector3 &baseTranslation, const float blockSizeInWorldUnits, int32 x, int32 y, int32 z) { return btVector3((float)x, (float)y, (float)z) * blockSizeInWorldUnits + baseTranslation; } void btBlockWorldChunkCollisionShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const { // can't handle != lod 0 atm if (m_pChunk->GetLoadedLODLevel() != 0) return; // get chunk data const BlockWorldBlockType *pBlockValues = m_pChunk->GetBlockValues(0); const uint32 yStride = m_chunkSize; const uint32 zStride = m_chunkSize * yStride; const int32 chunkSizeMinusOne = (int32)m_chunkSize - 1; // clip the chunk to the specified aabb uint32 minBlockX = (uint32)Math::Clamp((int32)Math::Floor(aabbMin.x()), 0, chunkSizeMinusOne); uint32 minBlockY = (uint32)Math::Clamp((int32)Math::Floor(aabbMin.y()), 0, chunkSizeMinusOne); uint32 minBlockZ = (uint32)Math::Clamp((int32)Math::Floor(aabbMin.z()), 0, chunkSizeMinusOne); uint32 maxBlockX = (uint32)Math::Clamp((int32)Math::Floor(aabbMax.x()), 0, chunkSizeMinusOne); uint32 maxBlockY = (uint32)Math::Clamp((int32)Math::Floor(aabbMax.y()), 0, chunkSizeMinusOne); uint32 maxBlockZ = (uint32)Math::Clamp((int32)Math::Floor(aabbMax.z()), 0, chunkSizeMinusOne); // iterate over matched blocks for (uint32 blockZ = minBlockZ; blockZ <= maxBlockZ; blockZ++) { for (uint32 blockY = minBlockY; blockY <= maxBlockY; blockY++) { for (uint32 blockX = minBlockX; blockX <= maxBlockX; blockX++) { // get block type BlockWorldBlockType blockValue = pBlockValues[blockZ * zStride + blockY * yStride + blockX]; if (blockValue == 0) continue; // get type float blockHeight = 1.0f; if ((blockValue & BLOCK_WORLD_BLOCK_VALUE_COLORED_FLAG_BIT) == 0) { const BlockPalette::BlockType *pBlockType = m_pPalette->GetBlockType(blockValue); if ((pBlockType->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE) == 0) continue; if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_SLAB) { // adjust height blockHeight = pBlockType->SlabShapeSettings.Height; } else if (pBlockType->ShapeType == BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_MESH) { // lookup the mesh const StaticMesh *pStaticMesh = m_pPalette->GetMesh(pBlockType->MeshShapeSettings.MeshIndex); const Physics::CollisionShape *pCollisionShape = pStaticMesh->GetCollisionShape(); if (pCollisionShape == nullptr) continue; // only works for concave if (!pCollisionShape->GetBulletShape()->isConcave()) continue; // create a temporary transform btQuaternion rotation; rotation.setEuler(0.0f, 0.0f, 90.0f * (float)m_pChunk->GetBlockRotation(0, blockX, blockY, blockZ)); btTransform meshTransform(rotation, btVector3((float)blockX + 0.5f, (float)blockY + 0.5f, (float)blockZ) + Physics::Float3ToBulletVector(m_pChunk->GetBasePosition())); // create a temporary callback class MeshCallback : public btTriangleCallback { btTransform &meshTransform; btTriangleCallback *callback; public: MeshCallback(btTransform &meshTransform, btTriangleCallback *callback) : meshTransform(meshTransform), callback(callback) {} // these have to be here to shut up the stupid warnings, even deleting them still throws warnings.. // 1>BlockEngine\BlockWorldChunkCollisionShape.cpp(202): warning C4822: 'btBlockWorldChunkCollisionShape::processAllTriangles::MeshCallback::MeshCallback' : local class member function does not have a body MeshCallback(const MeshCallback &m) : meshTransform(m.meshTransform), callback(m.callback) {} MeshCallback &operator=(const MeshCallback &m) { meshTransform = m.meshTransform; callback = m.callback; return *this; } virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { btVector3 newTriangle[3]; newTriangle[0] = meshTransform(triangle[0]); newTriangle[1] = meshTransform(triangle[1]); newTriangle[2] = meshTransform(triangle[2]); callback->processTriangle(newTriangle, partId, triangleIndex); } }; MeshCallback meshCallback(meshTransform, callback); // invoke the mesh's collision shape process function static_cast<const btConcaveShape *>(pStaticMesh->GetCollisionShape()->GetBulletShape())->processAllTriangles(&meshCallback, meshTransform.invXform(aabbMin), meshTransform.invXform(aabbMax)); } else if (pBlockType->ShapeType != BLOCK_MESH_BLOCK_TYPE_SHAPE_TYPE_CUBE) { // can't handle yet continue; } } // is cube { // generate the vertex positions for this block float baseX = (float)blockX; float baseY = (float)blockY; float baseZ = (float)blockZ; // generate vertices btVector3 blockVertices[8] = { btVector3(baseX, baseY, baseZ), // bottom-front-left btVector3(baseX + 1.0f, baseY, baseZ), // bottom-front-right btVector3(baseX, baseY + 1.0f, baseZ), // bottom-back-left btVector3(baseX + 1.0f, baseY + 1.0f, baseZ), // bottom-back-right btVector3(baseX, baseY, baseZ + blockHeight), // top-front-left btVector3(baseX + 1.0f, baseY, baseZ + blockHeight), // top-front-right btVector3(baseX, baseY + 1.0f, baseZ + blockHeight), // top-back-left btVector3(baseX + 1.0f, baseY + 1.0f, baseZ + blockHeight) // top-back-right }; btVector3 triangleVerticesA[3]; btVector3 triangleVerticesB[3]; // right face triangleVerticesA[0] = blockVertices[5]; triangleVerticesA[1] = blockVertices[1]; triangleVerticesA[2] = blockVertices[3]; triangleVerticesB[0] = blockVertices[5]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[7]; callback->processTriangle(triangleVerticesA, CUBE_FACE_RIGHT, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_RIGHT, 1); // left face triangleVerticesA[0] = blockVertices[4]; triangleVerticesA[1] = blockVertices[0]; triangleVerticesA[2] = blockVertices[2]; triangleVerticesB[0] = blockVertices[2]; triangleVerticesB[1] = blockVertices[4]; triangleVerticesB[2] = blockVertices[6]; callback->processTriangle(triangleVerticesA, CUBE_FACE_LEFT, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_LEFT, 1); // back face triangleVerticesA[0] = blockVertices[6]; triangleVerticesA[1] = blockVertices[7]; triangleVerticesA[2] = blockVertices[2]; triangleVerticesB[0] = blockVertices[7]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[2]; callback->processTriangle(triangleVerticesA, CUBE_FACE_BACK, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_BACK, 1); // front face triangleVerticesA[0] = blockVertices[0]; triangleVerticesA[1] = blockVertices[5]; triangleVerticesA[2] = blockVertices[4]; triangleVerticesB[0] = blockVertices[4]; triangleVerticesB[1] = blockVertices[1]; triangleVerticesB[2] = blockVertices[5]; callback->processTriangle(triangleVerticesA, CUBE_FACE_FRONT, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_FRONT, 1); // top face triangleVerticesA[0] = blockVertices[6]; triangleVerticesA[1] = blockVertices[5]; triangleVerticesA[2] = blockVertices[7]; triangleVerticesB[0] = blockVertices[6]; triangleVerticesB[1] = blockVertices[4]; triangleVerticesB[2] = blockVertices[5]; callback->processTriangle(triangleVerticesA, CUBE_FACE_TOP, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_TOP, 1); // bottom face triangleVerticesA[0] = blockVertices[0]; triangleVerticesA[1] = blockVertices[2]; triangleVerticesA[2] = blockVertices[3]; triangleVerticesB[0] = blockVertices[2]; triangleVerticesB[1] = blockVertices[3]; triangleVerticesB[2] = blockVertices[1]; callback->processTriangle(triangleVerticesA, CUBE_FACE_BOTTOM, 0); callback->processTriangle(triangleVerticesB, CUBE_FACE_BOTTOM, 1); /* if (searchBounds.AABoxIntersection(AABox(float3(baseX, baseY, baseZ), float3(baseX + fBlockSizeInWorldUnits, baseY + fBlockSizeInWorldUnits, baseZ + fBlockSizeInWorldUnits)))) Log_DevPrintf("PASS! sect %i %i chunk %i %i %i block %u %u %u", pSection->GetSectionX(), pSection->GetSectionY(), pChunk->GetChunkX(), pChunk->GetChunkY(), pChunk->GetChunkZ(), blockX, blockY, blockZ); else Log_DevPrintf("FAIL! sect %i %i chunk %i %i %i block %u %u %u", pSection->GetSectionX(), pSection->GetSectionY(), pChunk->GetChunkX(), pChunk->GetChunkY(), pChunk->GetChunkZ(), blockX, blockY, blockZ); */ } } } } } <file_sep>/Editor/Source/Editor/EditorProgressDialog.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorProgressDialog.h" #include "Editor/Editor.h" #include "Editor/EditorHelpers.h" Log_SetChannel(EditorProgressDialog); EditorProgressDialog::EditorProgressDialog(QWidget *pParent, Qt::WindowFlags windowFlags /*= 0*/) : QDialog(pParent, windowFlags), EditorProgressCallbacks(pParent), m_ui(new Ui_EditorProgressDialog()) { m_ui->setupUi(this); setModal(true); } EditorProgressDialog::~EditorProgressDialog() { delete m_ui; } void EditorProgressDialog::SetCancellable(bool cancellable) { BaseProgressCallbacks::SetCancellable(cancellable); m_ui->m_cancelButton->setEnabled(false); g_pEditor->ProcessBackgroundEvents(); } void EditorProgressDialog::SetStatusText(const char *statusText) { BaseProgressCallbacks::SetStatusText(statusText); m_ui->m_status->setText(statusText); g_pEditor->ProcessBackgroundEvents(); } void EditorProgressDialog::SetProgressRange(uint32 range) { BaseProgressCallbacks::SetProgressRange(range); m_ui->m_progressBar->setRange(0, m_progressRange); m_ui->m_progressBar->setValue(m_progressValue); g_pEditor->ProcessBackgroundEvents(); } void EditorProgressDialog::SetProgressValue(uint32 value) { #if 1 float oldPercent = (m_progressRange != 0) ? Math::Clamp((float)m_progressValue / (float)m_progressRange, 0.0f, 1.0f) : 0.0f; int32 oldWidthInPixels = Math::Truncate(oldPercent * (float)m_ui->m_progressBar->width()); BaseProgressCallbacks::SetProgressValue(value); float newPercent = (m_progressRange != 0) ? Math::Clamp((float)m_progressValue / (float)m_progressRange, 0.0f, 1.0f) : 0.0f; int32 newWidthInPixels = Math::Truncate(newPercent * (float)m_ui->m_progressBar->width()); if (oldWidthInPixels != newWidthInPixels) { m_ui->m_progressBar->setValue(m_progressValue); g_pEditor->ProcessBackgroundEvents(); } #else float oldPercent = (m_progressRange != 0) ? Math::Clamp((float)m_progressValue / (float)m_progressRange, 0.0f, 1.0f) : 0.0f; BaseProgressCallbacks::SetProgressValue(value); float newPercent = (m_progressRange != 0) ? Math::Clamp((float)m_progressValue / (float)m_progressRange, 0.0f, 1.0f) : 0.0f; if (Math::Truncate(oldPercent) != Math::Truncate(newPercent)) { m_ui->m_progressBar->setValue(m_progressValue); ProcessEvents(); } #endif } void EditorProgressDialog::DisplayError(const char *message) { // push to log for now, fix me later when the ui is updated Log_ErrorPrint(message); } void EditorProgressDialog::DisplayWarning(const char *message) { // push to log for now, fix me later when the ui is updated Log_WarningPrint(message); } void EditorProgressDialog::DisplayInformation(const char *message) { // push to log for now, fix me later when the ui is updated Log_InfoPrint(message); } void EditorProgressDialog::DisplayDebugMessage(const char *message) { // push to log for now, fix me later when the ui is updated Log_DevPrint(message); } <file_sep>/Engine/Source/Engine/BlockMeshUtilities.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/BlockMeshUtilities.h" #include "Engine/BlockPalette.h" //Log_SetChannel(BlockMeshUtilities); namespace BlockMeshUtilities { struct RayMeshIntersectionParameters { // in const BlockPalette *pBlockList; Vector3i MeshMinCoordinates; Vector3i MeshMaxCoordinates; int32 DataZStride, DataYStride; const byte *pBlockData; Ray TestRay; // out float ClosestDistance; Vector3i ClosestBlock; uint8 ClosestFace; }; inline static byte RayMeshIntersectionGetBlock(const RayMeshIntersectionParameters *pParameters, const Vector3i &blockPosition) { Vector3i local = blockPosition - pParameters->MeshMinCoordinates; return pParameters->pBlockData[local.z * pParameters->DataZStride + local.y * pParameters->DataYStride + local.x]; } static void RayMeshIntersectionInternal(RayMeshIntersectionParameters *pParameters, const SIMDVector3i &minNodeBounds, const SIMDVector3i &maxNodeBounds, const Vector3i &nodeSize) { float hitDistance; // if we can't subdivide the block any more, test everything inside the bounds if (nodeSize % 2 != Vector3i::Zero) { Vector3i currentBlock; for (currentBlock = minNodeBounds; currentBlock.z <= maxNodeBounds.z; currentBlock.z++) { for (currentBlock.y = minNodeBounds.y; currentBlock.y <= maxNodeBounds.y; currentBlock.y++) { for (currentBlock.x = minNodeBounds.x; currentBlock.x <= maxNodeBounds.x; currentBlock.x++) { if ((pParameters->pBlockList->GetBlockType(RayMeshIntersectionGetBlock(pParameters, currentBlock))->Flags & (BLOCK_MESH_BLOCK_TYPE_FLAG_VISIBLE | BLOCK_MESH_BLOCK_TYPE_FLAG_COLLIDABLE)) == 0) continue; SIMDVector3f blockMinBounds = SIMDVector3f(currentBlock); SIMDVector3f blockMaxBounds = blockMinBounds + 1.0f; // intersect the ray with it uint32 hitFace = 0; hitDistance = pParameters->TestRay.AABoxIntersectionTime(blockMinBounds, blockMaxBounds); if (hitDistance < pParameters->ClosestDistance) { pParameters->ClosestDistance = hitDistance; pParameters->ClosestBlock = currentBlock; pParameters->ClosestFace = (uint8)hitFace; } } } } // exit early return; } // split it up by half Vector3i halfNodeSize = nodeSize / 2; Vector3i childMinBounds, childMaxBounds; // front bottomleft block childMinBounds = (minNodeBounds).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // front bottomright block childMinBounds = (minNodeBounds + SIMDVector3i(halfNodeSize.x, 0, 0)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // front topleft block childMinBounds = (minNodeBounds + SIMDVector3i(0, 0, halfNodeSize.z)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // front topright block childMinBounds = (minNodeBounds + SIMDVector3i(halfNodeSize.x, 0, halfNodeSize.z)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // back bottomleft block childMinBounds = (minNodeBounds + SIMDVector3i(0, halfNodeSize.y, 0)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // back bottomright block childMinBounds = (minNodeBounds + SIMDVector3i(halfNodeSize.x, halfNodeSize.y, 0)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // back topleft block childMinBounds = (minNodeBounds + SIMDVector3i(0, halfNodeSize.y, halfNodeSize.z)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); // back topright block childMinBounds = (minNodeBounds + SIMDVector3i(halfNodeSize.x, halfNodeSize.y, halfNodeSize.z)).Max(pParameters->MeshMinCoordinates); childMaxBounds = (childMinBounds + halfNodeSize).Min(pParameters->MeshMaxCoordinates) + Vector3i::One; if (pParameters->TestRay.AABoxIntersection(SIMDVector3f(childMinBounds), SIMDVector3f(childMaxBounds))) RayMeshIntersectionInternal(pParameters, childMinBounds, childMaxBounds, halfNodeSize); } float RayMeshIntersection(int3 *pHitPosition, uint8 *pHitFace, const BlockPalette *pBlockList, const int3 &meshMinCoordinates, const int3 &meshMaxCoordinates, const BlockVolumeBlockType *pBlockData, const Ray &ray) { // get mesh size, then align it to powers of 2 for faster iteration Vector3i meshSize = meshMaxCoordinates - meshMinCoordinates + Vector3i::One; int32 nextPow2SmallestComponent = Y_nextpow2i(Min(meshSize.x, Min(meshSize.y, meshSize.z))); Vector3i alignedMeshSize = Vector3i(Max(nextPow2SmallestComponent, meshSize.x), Max(nextPow2SmallestComponent, meshSize.y), Max(nextPow2SmallestComponent, meshSize.z)); DebugAssert(!meshSize.AnyLessEqual(Vector3i::Zero)); // create query struct // ray origin is scaled down by each block size, so that each unit is equal to "one block" RayMeshIntersectionParameters query; query.pBlockList = pBlockList; query.MeshMinCoordinates = meshMinCoordinates; query.MeshMaxCoordinates = meshMaxCoordinates; query.DataYStride = sizeof(byte) * meshSize.x; query.DataZStride = query.DataYStride * meshSize.y; query.pBlockData = pBlockData; query.TestRay = Ray(ray.GetOrigin(), ray.GetDirection()); query.ClosestDistance = Y_FLT_INFINITE; // invoke it RayMeshIntersectionInternal(&query, query.MeshMinCoordinates, query.MeshMaxCoordinates, alignedMeshSize); // got a result? if (query.ClosestDistance != Y_FLT_INFINITE) { // store them *pHitPosition = query.ClosestBlock; if (pHitFace != NULL) *pHitFace = query.ClosestFace; } return query.ClosestDistance; } float RayMeshIntersection(int32 *pHitX, int32 *pHitY, int32 *pHitZ, uint8 *pHitFace, const BlockPalette *pBlockList, int32 meshMinX, int32 meshMinY, int32 meshMinZ, int32 meshMaxX, int32 meshMaxY, int32 meshMaxZ, const BlockVolumeBlockType *pBlockData, const Ray &ray) { // get mesh size, then align it to powers of 2 for faster iteration Vector3i meshMinCoordinates = Vector3i(meshMinX, meshMinY, meshMinZ); Vector3i meshMaxCoordinates = Vector3i(meshMaxX, meshMaxY, meshMaxZ); Vector3i meshSize = meshMaxCoordinates - meshMinCoordinates + Vector3i::One; int32 nextPow2SmallestComponent = Y_nextpow2i(Min(meshSize.x, Min(meshSize.y, meshSize.z))); Vector3i alignedMeshSize = Vector3i(Max(nextPow2SmallestComponent, meshSize.x), Max(nextPow2SmallestComponent, meshSize.y), Max(nextPow2SmallestComponent, meshSize.z)); DebugAssert(!meshSize.AnyLessEqual(Vector3i::Zero)); // create query struct // ray origin is scaled down by each block size, so that each unit is equal to "one block" RayMeshIntersectionParameters query; query.pBlockList = pBlockList; query.MeshMinCoordinates = meshMinCoordinates; query.MeshMaxCoordinates = meshMaxCoordinates; query.DataYStride = sizeof(byte) * meshSize.x; query.DataZStride = query.DataYStride * meshSize.y; query.pBlockData = pBlockData; query.TestRay = Ray(ray.GetOrigin(), ray.GetDirection()); query.ClosestDistance = Y_FLT_INFINITE; // invoke it RayMeshIntersectionInternal(&query, query.MeshMinCoordinates, query.MeshMaxCoordinates, alignedMeshSize); // store them if (query.ClosestDistance != Y_FLT_INFINITE) { *pHitX = query.ClosestBlock.x; *pHitY = query.ClosestBlock.y; *pHitZ = query.ClosestBlock.z; if (pHitFace != NULL) *pHitFace = query.ClosestFace; } return query.ClosestDistance; } void CreateMeshLOD(uint8 *pOutBlockData, uint32 lodLevel, const BlockPalette *pBlockList, const uint8 *pBlockData, uint32 meshSize) { uint8 blockValues[1024]; uint32 nBlockValues; Assert(lodLevel < 5); uint32 meshYPitch = (sizeof(uint8) * meshSize); uint32 meshZPitch = meshYPitch * meshSize; uint32 lodSize = meshSize >> lodLevel; uint32 lodYPitch = (sizeof(uint8) * lodSize); uint32 lodZPitch = lodYPitch * lodSize; uint32 collapseSize = (1 << lodLevel); uint32 i, j; uint32 x, y, z; uint32 x2, y2, z2; for (z = 0; z < lodSize; z++) { for (y = 0; y < lodSize; y++) { for (x = 0; x < lodSize; x++) { nBlockValues = 0; uint32 sx = x * collapseSize; uint32 sy = y * collapseSize; uint32 sz = z * collapseSize; for (z2 = 0; z2 < collapseSize; z2++) { for (y2 = 0; y2 < collapseSize; y2++) { for (x2 = 0; x2 < collapseSize; x2++) { DebugAssert(nBlockValues < countof(blockValues)); blockValues[nBlockValues++] = pBlockData[(sz + z2) * meshZPitch + (sy + y2) * meshYPitch + (sx + x2)]; } } } // find the most common block type uint8 mostCommonBlockType = 0; uint32 mostCommonBlockTypeCount = 0; uint8 mostCommonOpaqueBlockType = 0; uint32 mostCommonOpaqueBlockTypeCount = 0; for (i = 0; i < nBlockValues; i++) { uint8 blockType = blockValues[i]; if (blockType == mostCommonBlockType) continue; uint32 count = 0; for (j = 0; j < nBlockValues; j++) { if (blockValues[j] == blockType) count++; } if (count > mostCommonBlockTypeCount) { mostCommonBlockType = blockType; mostCommonBlockTypeCount = count; } if (count > mostCommonOpaqueBlockTypeCount) { if (blockType != 0 && pBlockList->GetBlockType(blockType)->Flags & BLOCK_MESH_BLOCK_TYPE_FLAG_BLOCKS_VISIBILITY) { mostCommonOpaqueBlockType = blockType; mostCommonOpaqueBlockTypeCount = count; } } } // use the most common transparent over a solid block uint8 collapsedBlockType = (mostCommonOpaqueBlockTypeCount > 0) ? mostCommonOpaqueBlockType : mostCommonBlockType; pOutBlockData[z * lodZPitch + y * lodYPitch + x] = collapsedBlockType; } } } } }; // namespace BlockMeshUtilities <file_sep>/Engine/Source/OpenGLES2Renderer/OpenGLES2GPUTexture.cpp #include "OpenGLES2Renderer/PrecompiledHeader.h" #include "OpenGLES2Renderer/OpenGLES2GPUTexture.h" #include "OpenGLES2Renderer/OpenGLES2GPUContext.h" #include "OpenGLES2Renderer/OpenGLES2GPUDevice.h" Log_SetChannel(OpenGLES2RenderBackend); static const GLenum s_GLCubeMapFaceEnums[CUBEMAP_FACE_COUNT] = { GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; static void SetOpenGLTextureState(GLenum textureTarget, uint32 mipLevels, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc) { glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, OpenGLES2TypeConversion::GetOpenGLTextureMinFilter(pSamplerStateDesc->Filter, (mipLevels > 1))); glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, OpenGLES2TypeConversion::GetOpenGLTextureMagFilter(pSamplerStateDesc->Filter)); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, OpenGLES2TypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressU)); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, OpenGLES2TypeConversion::GetOpenGLTextureWrap(pSamplerStateDesc->AddressV)); #ifdef GL_EXT_texture_filter_anisotropic if (GLAD_GL_EXT_texture_filter_anisotropic) { if (pSamplerStateDesc->Filter == TEXTURE_FILTER_ANISOTROPIC || pSamplerStateDesc->Filter == TEXTURE_FILTER_COMPARISON_ANISOTROPIC) glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)pSamplerStateDesc->MaxAnisotropy); else glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } #endif } static void SetDefaultOpenGLTextureState(GLenum textureTarget) { glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #ifdef GL_EXT_texture_filter_anisotropic if (GLAD_GL_EXT_texture_filter_anisotropic) glTexParameterf(textureTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); #endif } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLES2GPUTexture2D::OpenGLES2GPUTexture2D(const GPU_TEXTURE2D_DESC *pDesc, GLuint glTextureId) : GPUTexture2D(pDesc), m_glTextureId(glTextureId) { } OpenGLES2GPUTexture2D::~OpenGLES2GPUTexture2D() { glDeleteTextures(1, &m_glTextureId); } void OpenGLES2GPUTexture2D::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage; } } void OpenGLES2GPUTexture2D::SetDebugName(const char *name) { OpenGLES2Helpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTexture2D *OpenGLES2GPUDevice::CreateTexture2D(const GPU_TEXTURE2D_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // validate mip levels if using mipmapped sample filter if (pSamplerStateDesc != nullptr && Renderer::TextureFilterRequiresMips(pSamplerStateDesc->Filter) && pTextureDesc->MipLevels > 1 && pTextureDesc->MipLevels != Renderer::CalculateMipCount(pTextureDesc->Width, pTextureDesc->Height)) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture2D: GLES 2.0 requires a full texture mip chain if a mip filter is used."); return nullptr; } // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLES2TypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture2D: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateTexture2D: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_2D, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); uint32 imageSize = (hasInitialData) ? pInitialDataPitch[i] * blocksHigh : 0; const void *pInitialData = (hasInitialData) ? ppInitialData[i] : nullptr; glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, imageSize, pInitialData); } } else { // flip and upload mip levels for (uint32 i = 0; i < pTextureDesc->MipLevels; i++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> i); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> i); glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, (hasInitialData) ? ppInitialData[i] : nullptr); } } // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_2D, pTextureDesc->MipLevels, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_2D); } // restore mutator texture unit RestoreMutatorTextureUnit(); // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateTexture2D: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLES2GPUTexture2D(pTextureDesc, glTextureId); } bool OpenGLES2GPUContext::ReadTexture(GPUTexture2D *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLES2GPUTexture2D *pOpenGLTexture = static_cast<OpenGLES2GPUTexture2D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLES2TypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pOpenGLTexture->GetGLTextureId(), mipIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_FRAMEBUFFER, (m_usingFrameBufferObject) ? m_drawFrameBufferObjectId : 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLES2GPUContext::WriteTexture(GPUTexture2D *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLES2GPUTexture2D *pOpenGLTexture = static_cast<OpenGLES2GPUTexture2D *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLES2TypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_2D, pOpenGLTexture->GetGLTextureId()); glTexSubImage2D(GL_TEXTURE_2D, mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLES2GPUTextureCube::OpenGLES2GPUTextureCube(const GPU_TEXTURECUBE_DESC *pDesc, GLuint glTextureId) : GPUTextureCube(pDesc), m_glTextureId(glTextureId) { } OpenGLES2GPUTextureCube::~OpenGLES2GPUTextureCube() { glDeleteTextures(1, &m_glTextureId); } void OpenGLES2GPUTextureCube::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { uint32 memoryUsage = 0; for (uint32 j = 0; j < m_desc.MipLevels; j++) memoryUsage += PixelFormat_CalculateImageSize(m_desc.Format, Max(m_desc.Width >> j, (uint32)1), Max(m_desc.Height >> j, (uint32)1), 1); *gpuMemoryUsage = memoryUsage * CUBEMAP_FACE_COUNT; } } void OpenGLES2GPUTextureCube::SetDebugName(const char *name) { OpenGLES2Helpers::SetObjectDebugName(GL_TEXTURE, m_glTextureId, name); } GPUTextureCube *OpenGLES2GPUDevice::CreateTextureCube(const GPU_TEXTURECUBE_DESC *pTextureDesc, const GPU_SAMPLER_STATE_DESC *pSamplerStateDesc, const void **ppInitialData /* = nullptr */, const uint32 *pInitialDataPitch /* = nullptr */) { // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0 && pTextureDesc->MipLevels < TEXTURE_MAX_MIPMAP_COUNT); // validate mip levels if using mipmapped sample filter if (pSamplerStateDesc != nullptr && Renderer::TextureFilterRequiresMips(pSamplerStateDesc->Filter) && pTextureDesc->MipLevels > 1 && pTextureDesc->MipLevels != Renderer::CalculateMipCount(pTextureDesc->Width, pTextureDesc->Height)) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTexture2D: GLES 2.0 requires a full texture mip chain if a mip filter is used."); return nullptr; } // convert to opengl types GLint glInternalFormat; GLenum glFormat; GLenum glType; if (!OpenGLES2TypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, &glFormat, &glType)) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateTextureCube: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glTextureId; glGenTextures(1, &glTextureId); if (glTextureId == 0) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateTextureCube: glGenTextures failed: "); return nullptr; } // has data to upload? bool hasInitialData = (ppInitialData != nullptr && pInitialDataPitch != nullptr); // switch to the mutator texture unit BindMutatorTextureUnit(); // bind texture glBindTexture(GL_TEXTURE_CUBE_MAP, glTextureId); // texture is compressed? if (pPixelFormatInfo->IsBlockCompressed) { for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); uint32 blocksHigh = Max((uint32)1, mipHeight / pPixelFormatInfo->BlockSize); // upload each array texture if (hasInitialData) { // upload each face glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, pInitialDataPitch[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex] * blocksHigh, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } } } else { // upload mip levels for (uint32 mipIndex = 0; mipIndex < pTextureDesc->MipLevels; mipIndex++) { // calculate dimensions uint32 mipWidth = Max((uint32)1, pTextureDesc->Width >> mipIndex); uint32 mipHeight = Max((uint32)1, pTextureDesc->Height >> mipIndex); // upload array if (hasInitialData) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_X * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Y * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_POSITIVE_Z * pTextureDesc->MipLevels + mipIndex]); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, ppInitialData[CUBEMAP_FACE_NEGATIVE_Z * pTextureDesc->MipLevels + mipIndex]); } else { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, mipIndex, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, nullptr); } } } // setup sampler state if (pTextureDesc->Flags & GPU_TEXTURE_FLAG_SHADER_BINDABLE) { if (pSamplerStateDesc != nullptr) SetOpenGLTextureState(GL_TEXTURE_CUBE_MAP, pTextureDesc->MipLevels, pSamplerStateDesc); else SetDefaultOpenGLTextureState(GL_TEXTURE_CUBE_MAP); } // restore currently-bound texture RestoreMutatorTextureUnit(); // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateTextureCube: One or more GL errors occured: "); glDeleteTextures(1, &glTextureId); return nullptr; } // create texture class return new OpenGLES2GPUTextureCube(pTextureDesc, glTextureId); } bool OpenGLES2GPUContext::ReadTexture(GPUTextureCube *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLES2GPUTextureCube *pOpenGLTexture = static_cast<OpenGLES2GPUTextureCube *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. if (pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); } // get gl formats GLenum glFormat; GLenum glType; OpenGLES2TypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, s_GLCubeMapFaceEnums[face], pOpenGLTexture->GetGLTextureId(), mipIndex); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0, 0); // restore fbo state glBindFramebuffer(GL_FRAMEBUFFER, (m_usingFrameBufferObject) ? m_drawFrameBufferObjectId : 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1 && pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLES2GPUContext::WriteTexture(GPUTextureCube *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, CUBEMAP_FACE face, uint32 mipIndex, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLES2GPUTextureCube *pOpenGLTexture = static_cast<OpenGLES2GPUTextureCube *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_WRITABLE); DebugAssert(countX > 0 && countY > 0 && face < CUBEMAP_FACE_COUNT); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // calculate mip level uint32 mipWidth = Max(pOpenGLTexture->GetDesc()->Width >> mipIndex, (uint32)1); uint32 mipHeight = Max(pOpenGLTexture->GetDesc()->Height >> mipIndex, (uint32)1); if ((startX + countX) > mipWidth || (startY + countY) > mipHeight) return false; // check destination size if ((countY * sourceRowPitch) > cbSource) return false; // flip pixels if we have more than one row byte *pFlippedPixels = nullptr; if (countY > 0 && pOpenGLTexture->GetDesc()->Flags & (GPU_TEXTURE_FLAG_BIND_RENDER_TARGET | GPU_TEXTURE_FLAG_BIND_DEPTH_STENCIL_BUFFER)) { // flip y coordinate startY = mipHeight - startY - countY; DebugAssert(startY < mipHeight); // flip rows pFlippedPixels = new byte[cbSource]; PixelFormat_FlipImage(pFlippedPixels, pSource, sourceRowPitch, countY); pSource = pFlippedPixels; } // get gl formats GLenum glFormat; GLenum glType; OpenGLES2TypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // update the texture BindMutatorTextureUnit(); { glBindTexture(GL_TEXTURE_CUBE_MAP, pOpenGLTexture->GetGLTextureId()); glTexSubImage2D(s_GLCubeMapFaceEnums[face], mipIndex, startX, startY, countX, countY, glFormat, glType, pSource); } RestoreMutatorTextureUnit(); // free temporary buffer delete[] pFlippedPixels; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// OpenGLES2GPUDepthTexture::OpenGLES2GPUDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pDesc, GLuint glRenderBufferId) : GPUDepthTexture(pDesc), m_glRenderBufferId(glRenderBufferId) { } OpenGLES2GPUDepthTexture::~OpenGLES2GPUDepthTexture() { glDeleteRenderbuffers(1, &m_glRenderBufferId); } void OpenGLES2GPUDepthTexture::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) { *gpuMemoryUsage = PixelFormat_CalculateImageSize(m_desc.Format, m_desc.Width, m_desc.Height, 1); } } void OpenGLES2GPUDepthTexture::SetDebugName(const char *name) { OpenGLES2Helpers::SetObjectDebugName(GL_RENDERBUFFER, m_glRenderBufferId, name); } GPUDepthTexture *OpenGLES2GPUDevice::CreateDepthTexture(const GPU_DEPTH_TEXTURE_DESC *pTextureDesc) { // get pixel format info const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pTextureDesc->Format); DebugAssert(pPixelFormatInfo != nullptr); // validate descriptor. we shouldn't be creating invalid textures on the device, so just assert out. DebugAssert(pTextureDesc->Width > 0 && pTextureDesc->Height > 0); // convert to opengl types GLint glInternalFormat; if (!OpenGLES2TypeConversion::GetOpenGLTextureFormat(pTextureDesc->Format, &glInternalFormat, nullptr, nullptr)) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateDepthTexture: Could not get mapping of texture format for %s", pPixelFormatInfo->Name); return nullptr; } GL_CHECKED_SECTION_BEGIN(); // allocate object id GLuint glRenderBufferId; glGenRenderbuffers(1, &glRenderBufferId); if (glRenderBufferId == 0) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateDepthTexture: glGenTextures failed: "); return nullptr; } // bind texture, and allocate storage glBindRenderbuffer(GL_RENDERBUFFER, glRenderBufferId); glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, pTextureDesc->Width, pTextureDesc->Height); glBindRenderbuffer(GL_RENDERBUFFER, 0); // check state if (GL_CHECK_ERROR_STATE()) { GL_PRINT_ERROR("OpenGLES2GPUDevice::CreateDepthTexture: One or more GL errors occured: "); glDeleteTextures(1, &glRenderBufferId); return nullptr; } // create texture class return new OpenGLES2GPUDepthTexture(pTextureDesc, glRenderBufferId); } bool OpenGLES2GPUContext::ReadTexture(GPUDepthTexture *pTexture, void *pDestination, uint32 destinationRowPitch, uint32 cbDestination, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { OpenGLES2GPUDepthTexture *pOpenGLTexture = static_cast<OpenGLES2GPUDepthTexture *>(pTexture); DebugAssert(pOpenGLTexture->GetDesc()->Flags & GPU_TEXTURE_FLAG_READABLE); DebugAssert(countX > 0 && countY > 0); // not handling compressed textures at the moment if (PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format)->IsBlockCompressed) return false; // get pixel format const PIXEL_FORMAT_INFO *pPixelFormatInfo = PixelFormat_GetPixelFormatInfo(pOpenGLTexture->GetDesc()->Format); DebugAssert(!pPixelFormatInfo->IsBlockCompressed && ((pPixelFormatInfo->BitsPerPixel % 8) == 0)); UNREFERENCED_PARAMETER(pPixelFormatInfo); // calculate mip level if ((startX + countX) > pOpenGLTexture->GetDesc()->Width || (startY + countY) > pOpenGLTexture->GetDesc()->Height) return false; // check destination size if ((countY * destinationRowPitch) > cbDestination) return false; // flip the coordinates around, since opengl's origin is at the bottom-left. startY = pOpenGLTexture->GetDesc()->Height - startY - countY; DebugAssert(startY < pOpenGLTexture->GetDesc()->Height); // get gl formats GLenum glFormat; GLenum glType; OpenGLES2TypeConversion::GetOpenGLTextureFormat(pOpenGLTexture->GetDesc()->Format, nullptr, &glFormat, &glType); // bind fbo glBindFramebuffer(GL_FRAMEBUFFER, m_readFrameBufferObjectId); // bind to FBO if (glFormat == GL_DEPTH_COMPONENT) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, pOpenGLTexture->GetGLRenderBufferId()); //else if (glFormat == GL_DEPTH_STENCIL) //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, pOpenGLTexture->GetGLRenderBufferId()); // check fbo completeness DebugAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); // invoke the read glReadPixels(startX, startY, countX, countY, glFormat, glType, pDestination); // unbind texture if (glFormat == GL_DEPTH_COMPONENT) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); //else if (glFormat == GL_DEPTH_STENCIL) //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); // restore fbo state glBindFramebuffer(GL_FRAMEBUFFER, (m_usingFrameBufferObject) ? m_drawFrameBufferObjectId : 0); // flip the rows as opengl's coordinate system starts at the bottom not the top if (countY > 1) PixelFormat_FlipImageInPlace(pDestination, destinationRowPitch, countY); return true; } bool OpenGLES2GPUContext::WriteTexture(GPUDepthTexture *pTexture, const void *pSource, uint32 sourceRowPitch, uint32 cbSource, uint32 startX, uint32 startY, uint32 countX, uint32 countY) { // can't write to renderbuffers return false; } static GLenum GetTextureDepthStencilAttachmentPoint(PIXEL_FORMAT pixelFormat) { // todo: move to texture? switch (pixelFormat) { case PIXEL_FORMAT_D16_UNORM: case PIXEL_FORMAT_D32_FLOAT: return GL_DEPTH_ATTACHMENT; } UnreachableCode(); return (GLenum)0; } OpenGLES2GPURenderTargetView::OpenGLES2GPURenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLuint textureName) : GPURenderTargetView(pTexture, pDesc), m_textureType(textureType), m_textureName(textureName) { } OpenGLES2GPURenderTargetView::~OpenGLES2GPURenderTargetView() { } void OpenGLES2GPURenderTargetView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void OpenGLES2GPURenderTargetView::SetDebugName(const char *name) { } GPURenderTargetView *OpenGLES2GPUDevice::CreateRenderTargetView(GPUTexture *pTexture, const GPU_RENDER_TARGET_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // fill in DSV structure TEXTURE_TYPE textureType; PIXEL_FORMAT pixelFormat; GLuint textureName; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE2D: textureType = TEXTURE_TYPE_2D; pixelFormat = static_cast<OpenGLES2GPUTexture2D *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUTexture2D *>(pTexture)->GetGLTextureId(); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: textureType = TEXTURE_TYPE_CUBE; pixelFormat = static_cast<OpenGLES2GPUTextureCube *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUTextureCube *>(pTexture)->GetGLTextureId(); break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: textureType = TEXTURE_TYPE_DEPTH; pixelFormat = static_cast<OpenGLES2GPUDepthTexture *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUDepthTexture *>(pTexture)->GetGLRenderBufferId(); break; default: Log_ErrorPrintf("OpenGLES2GPUDevice::CreateRenderTargetView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } if (pixelFormat != pDesc->Format) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateRenderTargetView: Pixel format must match view format. (%u vs %u)", pixelFormat, pDesc->Format); return nullptr; } return new OpenGLES2GPURenderTargetView(pTexture, pDesc, textureType, textureName); } OpenGLES2GPUDepthStencilBufferView::OpenGLES2GPUDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc, TEXTURE_TYPE textureType, GLenum attachmentPoint, GLuint textureName) : GPUDepthStencilBufferView(pTexture, pDesc), m_textureType(textureType), m_attachmentPoint(attachmentPoint), m_textureName(textureName) { } OpenGLES2GPUDepthStencilBufferView::~OpenGLES2GPUDepthStencilBufferView() { } void OpenGLES2GPUDepthStencilBufferView::GetMemoryUsage(uint32 *cpuMemoryUsage, uint32 *gpuMemoryUsage) const { if (cpuMemoryUsage != nullptr) *cpuMemoryUsage = sizeof(*this); if (gpuMemoryUsage != nullptr) gpuMemoryUsage = 0; } void OpenGLES2GPUDepthStencilBufferView::SetDebugName(const char *name) { } GPUDepthStencilBufferView *OpenGLES2GPUDevice::CreateDepthStencilBufferView(GPUTexture *pTexture, const GPU_DEPTH_STENCIL_BUFFER_VIEW_DESC *pDesc) { DebugAssert(pTexture != nullptr); // fill in DSV structure TEXTURE_TYPE textureType; PIXEL_FORMAT pixelFormat; GLuint textureName; GLenum attachmentPoint; switch (pTexture->GetResourceType()) { case GPU_RESOURCE_TYPE_TEXTURE2D: textureType = TEXTURE_TYPE_2D; pixelFormat = static_cast<OpenGLES2GPUTexture2D *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUTexture2D *>(pTexture)->GetGLTextureId(); attachmentPoint = GetTextureDepthStencilAttachmentPoint(pixelFormat); break; case GPU_RESOURCE_TYPE_TEXTURECUBE: textureType = TEXTURE_TYPE_CUBE; pixelFormat = static_cast<OpenGLES2GPUTextureCube *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUTextureCube *>(pTexture)->GetGLTextureId(); attachmentPoint = GetTextureDepthStencilAttachmentPoint(pixelFormat); break; case GPU_RESOURCE_TYPE_DEPTH_TEXTURE: textureType = TEXTURE_TYPE_DEPTH; pixelFormat = static_cast<OpenGLES2GPUDepthTexture *>(pTexture)->GetDesc()->Format; textureName = static_cast<OpenGLES2GPUDepthTexture *>(pTexture)->GetGLRenderBufferId(); attachmentPoint = GetTextureDepthStencilAttachmentPoint(pixelFormat); break; default: Log_ErrorPrintf("OpenGLES2GPUDevice::CreateDepthBufferView: Invalid resource type %s", NameTable_GetNameString(NameTables::GPUResourceType, pTexture->GetResourceType())); return nullptr; } if (pixelFormat != pDesc->Format) { Log_ErrorPrintf("OpenGLES2GPUDevice::CreateDepthStencilBufferView: Pixel format must match view format. (%u vs %u)", pixelFormat, pDesc->Format); return nullptr; } return new OpenGLES2GPUDepthStencilBufferView(pTexture, pDesc, textureType, attachmentPoint, textureName); } <file_sep>/Engine/Source/Engine/SkeletalAnimation.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/SkeletalAnimation.h" #include "Engine/ResourceManager.h" #include "Engine/DataFormats.h" Log_SetChannel(SkeletalAnimation); DEFINE_RESOURCE_TYPE_INFO(SkeletalAnimation); DEFINE_RESOURCE_GENERIC_FACTORY(SkeletalAnimation); SkeletalAnimation::SkeletalAnimation(const ResourceTypeInfo *pResourceTypeInfo /*= &s_TypeInfo*/) : BaseClass(pResourceTypeInfo), m_pBoneTracks(nullptr), m_ppBoneIndexToBoneTrack(nullptr), m_boneTrackCount(0), m_pRootMotionTrack(nullptr) { } SkeletalAnimation::~SkeletalAnimation() { delete m_pRootMotionTrack; delete[] m_ppBoneIndexToBoneTrack; delete[] m_pBoneTracks; } void SkeletalAnimation::TransformTrack::GetKeyFrames(float time, const KeyFrame **ppStartKeyFrame, const KeyFrame **ppEndKeyFrame, float *pFactor) const { DebugAssert(time >= 0.0f); // only one key? if (m_keyFrames.GetSize() == 1) { *ppStartKeyFrame = &m_keyFrames[0]; *ppEndKeyFrame = nullptr; *pFactor = 0.0f; return; } // find the key that we reside in with a time of <= t uint32 keyIndex; for (keyIndex = 0; keyIndex < (m_keyFrames.GetSize() - 1); keyIndex++) { if (time < m_keyFrames[keyIndex + 1].Key) break; } // is this the last key? uint32 nextKeyIndex = keyIndex + 1; if (nextKeyIndex == m_keyFrames.GetSize()) { // use the last key *ppStartKeyFrame = &m_keyFrames[keyIndex]; *ppEndKeyFrame = nullptr; *pFactor = 0.0f; return; } // calculate factor const float thisKeyTime = m_keyFrames[keyIndex].Key; const float nextKeyTime = m_keyFrames[nextKeyIndex].Key; const float factor = (time - thisKeyTime) / (nextKeyTime - thisKeyTime); DebugAssert(factor >= 0.0f && factor <= 1.0f); // store values *ppStartKeyFrame = &m_keyFrames[keyIndex]; *ppEndKeyFrame = &m_keyFrames[nextKeyIndex]; *pFactor = factor; } void SkeletalAnimation::TransformTrack::GetBoneTransform(float time, Transform *pTransform, bool interpolate /* = true */) const { // find the keyframes for this time spec const KeyFrame *startKeyFrame; const KeyFrame *endKeyFrame; float factor; GetKeyFrames(time, &startKeyFrame, &endKeyFrame, &factor); // do we have to interpolate if (endKeyFrame != nullptr) { // handle cases where it is very close to zero/one if (Math::NearEqual(factor, 0.0f, Y_FLT_EPSILON)) { // use the start keyframe *pTransform = startKeyFrame->Value; } else if (Math::NearEqual(factor, 1.0f, Y_FLT_EPSILON)) { // use the end keyframe *pTransform = endKeyFrame->Value; } else { // allow interpolation? if (interpolate) { // linear interpolate between the two *pTransform = Transform::LinearInterpolate(startKeyFrame->Value, endKeyFrame->Value, factor); } else { // if factor >= 0.5, use end, otherwise start if (factor < 0.5f) *pTransform = startKeyFrame->Value; else *pTransform = endKeyFrame->Value; } } } else { // only have one keyframe reference DebugAssert(startKeyFrame != nullptr); *pTransform = startKeyFrame->Value; } } bool SkeletalAnimation::CalculateRelativeBoneTransform(uint32 boneIndex, float time, Transform *pTransform, bool interpolate /* = true */) const { DebugAssert(boneIndex < m_pSkeleton->GetBoneCount()); // find the track const TransformTrack *pBoneTrack = m_ppBoneIndexToBoneTrack[boneIndex]; if (pBoneTrack != nullptr) { // get the transform for the specified time pBoneTrack->GetBoneTransform(time, pTransform, interpolate); return true; } else { // we have no track for this bone return false; } } void SkeletalAnimation::CalculateAbsoluteBoneTransform(uint32 boneIndex, float time, Transform *pTransform, bool interpolate /* = true */) const { DebugAssert(boneIndex < m_pSkeleton->GetBoneCount()); // bone has parent? const Skeleton::Bone *pBone = m_pSkeleton->GetBoneByIndex(boneIndex); if (pBone->GetParentBone() == nullptr) { // no parent, this must be the root, so just return the relative transform of the root if (!CalculateRelativeBoneTransform(boneIndex, time, pTransform, interpolate)) *pTransform = m_pSkeleton->GetBoneByIndex(boneIndex)->GetRelativeBaseFrameTransform(); } else { // get the parent's absolute transform Transform parentTransform; CalculateAbsoluteBoneTransform(pBone->GetParentBone()->GetIndex(), time, &parentTransform, interpolate); // and this bone's relative transform Transform thisBoneTransform; if (!CalculateRelativeBoneTransform(boneIndex, time, &thisBoneTransform, interpolate)) *pTransform = m_pSkeleton->GetBoneByIndex(boneIndex)->GetRelativeBaseFrameTransform(); // apply parent after bone *pTransform = Transform::ConcatenateTransforms(thisBoneTransform, parentTransform); } } bool SkeletalAnimation::LoadFromStream(const char *name, ByteStream *pStream) { DF_SKELETALANIMATION_HEADER fileHeader; if (!pStream->Read2(&fileHeader, sizeof(fileHeader))) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Could not read header"); return false; } // verify header if (fileHeader.Magic != DF_SKELETALANIMATION_HEADER_MAGIC || fileHeader.HeaderSize != sizeof(fileHeader)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Invalid header"); return false; } // read skeleton name { String skeletonName; skeletonName.Resize(fileHeader.SkeletonNameLength); if (!pStream->SeekAbsolute(fileHeader.SkeletonNameOffset) || !pStream->Read2(skeletonName.GetWriteableCharArray(), fileHeader.SkeletonNameLength)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Invalid skeleton name"); return false; } // load skeleton if ((m_pSkeleton = g_pResourceManager->GetSkeleton(skeletonName)) == nullptr) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Could not load skeleton '%s'", skeletonName.GetCharArray()); return false; } } // verify skeleton matches if (m_pSkeleton->GetBoneCount() != fileHeader.SkeletonBoneCount) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Bone count in animation does not match skeleton (%u / %u)", fileHeader.SkeletonBoneCount, m_pSkeleton->GetBoneCount()); return false; } // allocate everything m_duration = fileHeader.Duration; m_strName = name; // read in bone tracks if (fileHeader.BoneTrackCount > 0) { // seek to start of bone track data if (!pStream->SeekAbsolute(fileHeader.BoneTrackOffset)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Failed to seek to bone track offset."); return false; } m_pBoneTracks = new BoneTrack[fileHeader.BoneTrackCount]; m_boneTrackCount = fileHeader.BoneTrackCount; for (uint32 i = 0; i < m_boneTrackCount; i++) { if (!m_pBoneTracks[i].LoadFromStream(pStream, m_pSkeleton)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Failed to load bone track %u.", i); return false; } } // bind bone tracks to bones uint32 skeletonBoneCount = m_pSkeleton->GetBoneCount(); m_ppBoneIndexToBoneTrack = new const BoneTrack *[skeletonBoneCount]; Y_memzero(m_ppBoneIndexToBoneTrack, sizeof(const BoneTrack *) * skeletonBoneCount); for (uint32 i = 0; i < m_boneTrackCount; i++) { uint32 boneIndex = m_pBoneTracks[i].GetBoneIndex(); if (boneIndex >= skeletonBoneCount || m_ppBoneIndexToBoneTrack[boneIndex] != nullptr) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Duplicate or invalid bone index %u in track %u", boneIndex, i); return false; } m_ppBoneIndexToBoneTrack[boneIndex] = &m_pBoneTracks[i]; } } // read in root motion track if (fileHeader.RootMotionOffset != 0) { // seek to start of track data if (!pStream->SeekAbsolute(fileHeader.RootMotionOffset)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Failed to seek to root motion track offset."); return false; } m_pRootMotionTrack = new RootMotionTrack(); if (!m_pRootMotionTrack->LoadFromStream(pStream, m_pSkeleton)) { Log_ErrorPrintf("SkeletalAnimation::LoadFromStream: Failed to load root motion track."); return false; } } // done return true; } bool SkeletalAnimation::TransformTrack::LoadKeyFramesFromStream(ByteStream *pStream, float duration, uint32 keyFrameCount) { DebugAssert(duration >= 0.0f && keyFrameCount > 0); m_duration = duration; m_keyFrames.Resize(keyFrameCount); // read in keyframes const uint32 READ_KEYFRAME_COUNT = 16; DF_SKELETALANIMATION_TRANSFORM_TRACK_KEYFRAME readKeyframes[READ_KEYFRAME_COUNT]; for (uint32 i = 0; i < keyFrameCount; i += READ_KEYFRAME_COUNT) { uint32 readCount = Min(READ_KEYFRAME_COUNT, keyFrameCount - i); if (!pStream->Read2(readKeyframes, sizeof(DF_SKELETALANIMATION_TRANSFORM_TRACK_KEYFRAME) * readCount)) return false; for (uint32 j = 0; j < readCount; j++) { DF_SKELETALANIMATION_TRANSFORM_TRACK_KEYFRAME &rkf = readKeyframes[j]; KeyFrame &kf = m_keyFrames[i + j]; kf.Key = rkf.Time; kf.Value = Transform(float3(rkf.Position), Quaternion(rkf.Rotation[0], rkf.Rotation[1], rkf.Rotation[2], rkf.Rotation[3]), float3(rkf.Scale)); } } return true; } bool SkeletalAnimation::BoneTrack::LoadFromStream(ByteStream *pStream, const Skeleton *pSkeleton) { // read in header DF_SKELETALANIMATION_BONE_TRACK_HEADER header; if (!pStream->Read2(&header, sizeof(header))) return false; // validate bone index if (header.BoneIndex >= pSkeleton->GetBoneCount()) { Log_ErrorPrintf("SkeletalAnimation::BoneTrack::LoadFromStream: Bone track contains invalid bone index: %u", header.BoneIndex); return false; } // set values m_boneIndex = header.BoneIndex; // read keyframes if (!LoadKeyFramesFromStream(pStream, header.Duration, header.KeyFrameCount)) return false; // done return true; } bool SkeletalAnimation::RootMotionTrack::LoadFromStream(ByteStream *pStream, const Skeleton *pSkeleton) { // read in header DF_SKELETALANIMATION_ROOT_MOTION_TRACK_HEADER header; if (!pStream->Read2(&header, sizeof(header))) return false; // read keyframes if (!LoadKeyFramesFromStream(pStream, header.Duration, header.KeyFrameCount)) return false; // done return true; } <file_sep>/Engine/Source/MathLib/Ray.h #pragma once #include "MathLib/Common.h" #include "MathLib/Vectorf.h" class AABox; class AABoxi; class Plane; class Sphere; class Ray { public: Ray() {} Ray(const Ray &copyRay); Ray(const Vector3f &orgin, const Vector3f &direction, float maxDistance); Ray(const Vector3f &start, const Vector3f &end); const Vector3f &GetOrigin() const { return m_Origin; } const Vector3f &GetEnd() const { return m_End; } const Vector3f &GetDirection() const { return m_Direction; } const Vector3f &GetInverseDirection() const { return m_InverseDirection; } const float GetDistance() const { return m_Distance; } //void SetOrigin(const float3 &newOrigin) { m_Origin = newOrigin; } //void SetDirection(const float3 &newDirection) { m_Direction = newDirection; m_InverseDirection = float3::One / newDirection; } AABox GetAABox() const; bool AABoxIntersection(const AABox &aaBox) const; bool AABoxIntersection(const AABox &aaBox, Vector3f &contactNormal, Vector3f &contactPoint) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds) const; bool AABoxIntersection(const Vector3f &minBounds, const Vector3f &maxBounds, Vector3f &contactNormal, Vector3f &contactPoint) const; float AABoxIntersectionTime(const AABox &aaBox) const; float AABoxIntersectionTime(const Vector3f &minBounds, const Vector3f &maxBounds) const; bool AABoxIntersectionTimeFace(const AABox &aaBox, float *pContactTime, CUBE_FACE *pContactFace) const; bool AABoxIntersectionTimeFace(const Vector3f &minBounds, const Vector3f &maxBounds, float *pContactTime, CUBE_FACE *pContactFace) const; bool PlaneIntersection(const Plane &intersectPlane); bool PlaneIntersection(const Plane &intersectPlane, Vector3f &contactNormal, Vector3f &contactPoint); float PlaneIntersectionTime(const Plane &intersectPlane); bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, Vector3f &contactNormal, Vector3f &contactPoint) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1) const; bool TriangleIntersection(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1, Vector3f &contactNormal, Vector3f &contactPoint) const; float TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2); float TriangleIntersectionTime(const Vector3f &v0, const Vector3f &v1, const Vector3f &v2, const Vector3f &e0, const Vector3f &e1); bool SphereIntersection(const Sphere &sphere); bool SphereIntersection(const Sphere &sphere, Vector3f &contactNormal, Vector3f &contactPoint); float SphereIntersectionTime(const Sphere &sphere); private: Vector3f m_Origin; Vector3f m_End; Vector3f m_Direction; Vector3f m_InverseDirection; float m_Distance; }; <file_sep>/DemoGame/Source/DemoGame/DrawCallStressDemo.cpp #include "DemoGame/PrecompiledHeader.h" #include "DemoGame/DrawCallStressDemo.h" #include "DemoGame/DemoUtilities.h" #include "BaseGame/LoadingScreenProgressCallbacks.h" #include "Engine/World.h" #include "Renderer/RenderWorld.h" #include "Renderer/ImGuiBridge.h" Log_SetChannel(SkeletalAnimationDemo); DrawCallStressDemo::DrawCallStressDemo(DemoGame *pDemoGame) : BaseDemoWorldGameState(pDemoGame) , m_pSunLightEntity(nullptr) , m_sunLightRotation(float3::Zero) , m_pMeshToRender(nullptr) , m_newObjectCount(10) { } DrawCallStressDemo::~DrawCallStressDemo() { SAFE_RELEASE(m_pMeshToRender); SAFE_RELEASE(m_pSunLightEntity); } bool DrawCallStressDemo::Initialize() { if (!BaseDemoWorldGameState::Initialize()) return false; if (!CreateDynamicWorld()) return false; // load mesh to render m_pMeshToRender = g_pResourceManager->GetStaticMesh("models/engine/unit_sphere"); if (m_pMeshToRender == nullptr) return false; // set model, this creates the renderable too LoadingScreenProgressCallbacks progressCallbacks; CreateObjects(m_newObjectCount, false, &progressCallbacks); // init view parameters m_viewParameters.MaximumShadowViewDistance = 500.0f; m_viewParameters.EnableBloom = false; m_viewParameters.EnableManualExposure = true; m_viewParameters.ManualExposure = 1.0f; m_camera.SetPosition(float3(-1.1f, -10.4f, 3.3f)); return true; } bool DrawCallStressDemo::OnWorldCreated(World *pWorld) { if (!BaseDemoWorldGameState::OnWorldCreated(pWorld)) return false; // sun entity //m_pSunLightEntity = DemoUtilities::CreateSunLight(m_pWorld, float3(1.0f, 1.0f, 1.0f), 1.2f, 0.4f); m_pSunLightEntity = DemoUtilities::CreateSunLight(m_pWorld, float3(1.0f, 0.992f, 0.8f), 1.2f, 0.4f); // ground plane AutoReleasePtr<const Material> pGroundPlaneMaterial = g_pResourceManager->GetDefaultMaterial(); AutoReleasePtr<Entity> pGroundPlaneEntity = DemoUtilities::CreatePlaneShape(m_pWorld, float3::UnitZ, float3(0.0f, 0.0f, 0.0f), 100.0f, pGroundPlaneMaterial, 10.0f); // done return true; } void DrawCallStressDemo::Shutdown() { while (!m_meshProxies.IsEmpty()) { StaticMeshRenderProxy *pRenderProxy = m_meshProxies.LastElement(); m_pWorld->GetRenderWorld()->RemoveRenderable(pRenderProxy); pRenderProxy->Release(); m_meshProxies.PopBack(); } BaseDemoWorldGameState::Shutdown(); } void DrawCallStressDemo::OnWorldDeleted(World *pWorld) { BaseDemoWorldGameState::OnWorldDeleted(pWorld); } void DrawCallStressDemo::OnMainThreadTick(float deltaTime) { BaseDemoWorldGameState::OnMainThreadTick(deltaTime); if (m_sunLightRotation.SquaredLength() > 0.0f) m_pSunLightEntity->SetRotation((m_pSunLightEntity->GetRotation() * Quaternion::FromEulerAngles(m_sunLightRotation.x * deltaTime, m_sunLightRotation.y * deltaTime, 0.0f)).Normalize()); } void DrawCallStressDemo::DrawOverlays(float deltaTime) { BaseDemoWorldGameState::DrawOverlays(deltaTime); //m_pDemoGame->GetGUIContext()->Draw3DBox(AABox(0.0f, 10.0f, 0.0f, 1.0f, 11.0f, 1.0f), MAKE_COLOR_R8G8B8_UNORM(255, 255, 255)); } void DrawCallStressDemo::DrawUI(float deltaTime) { BaseDemoWorldGameState::DrawUI(deltaTime); ImGui::SetNextWindowPos(ImVec2(10, float(m_viewParameters.Viewport.Height - 250)), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(320, 240), ImGuiSetCond_FirstUseEver); // annoyingly, everything is drawn on the UI thread yet commands have to be invoked on the main thread.. if (ImGui::Begin("Draw Call Stress Demo")) { int intValue; //float floatValue; //bool boolValue; ImGui::PushItemWidth(-140.0f); // @TODO intValue = 0; if (ImGui::Combo("Mesh", &intValue, "models/engine/unit_sphere\0\0")) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this, intValue]() { //SetModelIndex(intValue); }); } // count ImGui::SliderInt("Object count", reinterpret_cast<int *>(&m_newObjectCount), 0, 20000); // update if (ImGui::Button("Update")) { QUEUE_MAIN_THREAD_LAMBDA_COMMAND([this]() { LoadingScreenProgressCallbacks callbacks; CreateObjects(m_newObjectCount, false, &callbacks); }); } // @TODO model rotation/scale/etc ImGui::PopItemWidth(); } ImGui::End(); } bool DrawCallStressDemo::OnWindowEvent(const union SDL_Event *event) { if (event->type == SDL_KEYDOWN || event->type == SDL_KEYUP) { bool isKeyDownEvent = (event->type == SDL_KEYDOWN); switch (event->key.keysym.sym) { case SDLK_LEFT: m_sunLightRotation.x += (isKeyDownEvent) ? -1.0f : 1.0f; return true; case SDLK_RIGHT: m_sunLightRotation.x += (isKeyDownEvent) ? 1.0f : -1.0f; return true; case SDLK_UP: m_sunLightRotation.y += (isKeyDownEvent) ? 1.0f : -1.0f; return true; case SDLK_DOWN: m_sunLightRotation.y += (isKeyDownEvent) ? -1.0f : 1.0f; return true; } } return BaseDemoWorldGameState::OnWindowEvent(event); } void DrawCallStressDemo::CreateObjects(uint32 count, bool useInstancing, ProgressCallbacks *pProgressCallbacks) { const float SPACING = 1.5f; const float ZPOS = 1.0f; uint32 origCount = m_meshProxies.GetSize(); if (origCount > 0) { pProgressCallbacks->SetStatusText("Removing existing objects..."); pProgressCallbacks->SetProgressRange(m_meshProxies.GetSize()); while (!m_meshProxies.IsEmpty()) { StaticMeshRenderProxy *pRenderProxy = m_meshProxies.LastElement(); m_pWorld->GetRenderWorld()->RemoveRenderable(pRenderProxy); pRenderProxy->Release(); m_meshProxies.PopBack(); pProgressCallbacks->SetProgressValue(origCount - m_meshProxies.GetSize()); } } pProgressCallbacks->SetFormattedStatusText("Creating %u new objects...", count); pProgressCallbacks->SetProgressRange(count); pProgressCallbacks->SetProgressValue(0); uint32 rowsAndColumns = Math::Truncate(Math::Sqrt((float)count)); for (uint32 row = 0; row < rowsAndColumns; row++) { float posX = (-(float(rowsAndColumns) / 2.0f) + (float)row) * SPACING; for (uint32 col = 0; col < rowsAndColumns; col++) { float posY = (-(float(rowsAndColumns) / 2.0f) + (float)col) * SPACING; Transform xform(Vector3f(posX, posY, ZPOS), Quaternion::Identity, Vector3f::One); StaticMeshRenderProxy *pRenderProxy = new StaticMeshRenderProxy(0, m_pMeshToRender, xform, ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS | ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS); m_pWorld->GetRenderWorld()->AddRenderable(pRenderProxy); m_meshProxies.Add(pRenderProxy); pProgressCallbacks->IncrementProgressValue(); } } } bool LaunchpadGameState::InvokeDrawCallStressDemo() { return RunDemo(new DrawCallStressDemo(m_pDemoGame)); } <file_sep>/Editor/Source/Editor/MapEditor/moc_EditorTerrainEditMode.cpp /**************************************************************************** ** Meta object code from reading C++ file 'EditorTerrainEditMode.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "Editor/PrecompiledHeader.h" #include "EditorTerrainEditMode.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'EditorTerrainEditMode.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_EditorTerrainEditMode_t { QByteArrayData data[32]; char stringdata[981]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_EditorTerrainEditMode_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_EditorTerrainEditMode_t qt_meta_stringdata_EditorTerrainEditMode = { { QT_MOC_LITERAL(0, 0, 21), // "EditorTerrainEditMode" QT_MOC_LITERAL(1, 22, 28), // "OnUIWidgetEditTerrainClicked" QT_MOC_LITERAL(2, 51, 0), // "" QT_MOC_LITERAL(3, 52, 7), // "checked" QT_MOC_LITERAL(4, 60, 28), // "OnUIWidgetEditDetailsClicked" QT_MOC_LITERAL(5, 89, 26), // "OnUIWidgetEditHolesClicked" QT_MOC_LITERAL(6, 116, 29), // "OnUIWidgetEditSectionsClicked" QT_MOC_LITERAL(7, 146, 27), // "OnUIWidgetEditLayersClicked" QT_MOC_LITERAL(8, 174, 32), // "OnUIWidgetImportHeightmapClicked" QT_MOC_LITERAL(9, 207, 25), // "OnUIWidgetSettingsClicked" QT_MOC_LITERAL(10, 233, 22), // "OnUIBrushRadiusChanged" QT_MOC_LITERAL(11, 256, 5), // "value" QT_MOC_LITERAL(12, 262, 23), // "OnUIBrushFalloffChanged" QT_MOC_LITERAL(13, 286, 22), // "OnUIBrushInvertChanged" QT_MOC_LITERAL(14, 309, 28), // "OnUITerrainStepHeightChanged" QT_MOC_LITERAL(15, 338, 27), // "OnUILayersStepWeightChanged" QT_MOC_LITERAL(16, 366, 30), // "OnUILayersLayerListItemClicked" QT_MOC_LITERAL(17, 397, 16), // "QListWidgetItem*" QT_MOC_LITERAL(18, 414, 9), // "pListItem" QT_MOC_LITERAL(19, 424, 30), // "OnUILayersEditLayerListClicked" QT_MOC_LITERAL(20, 455, 44), // "OnUISectionsActiveSectionDele..." QT_MOC_LITERAL(21, 500, 45), // "OnUISectionsActiveSectionDele..." QT_MOC_LITERAL(22, 546, 47), // "OnUISectionsInactiveSectionCr..." QT_MOC_LITERAL(23, 594, 41), // "OnUIHeightmapImportPanelSourc..." QT_MOC_LITERAL(24, 636, 48), // "OnUIHeightmapImportPanelSelec..." QT_MOC_LITERAL(25, 685, 42), // "OnUIHeightmapImportPanelScale..." QT_MOC_LITERAL(26, 728, 40), // "OnUIHeightmapImportPanelScale..." QT_MOC_LITERAL(27, 769, 37), // "OnUIHeightmapImportPanelImpor..." QT_MOC_LITERAL(28, 807, 41), // "OnUISettingsPanelViewDistance..." QT_MOC_LITERAL(29, 849, 50), // "OnUISettingsPanelRenderResolu..." QT_MOC_LITERAL(30, 900, 40), // "OnUISettingsPanelLODDistanceR..." QT_MOC_LITERAL(31, 941, 39) // "OnUISettingsPanelRebuildQuadt..." }, "EditorTerrainEditMode\0" "OnUIWidgetEditTerrainClicked\0\0checked\0" "OnUIWidgetEditDetailsClicked\0" "OnUIWidgetEditHolesClicked\0" "OnUIWidgetEditSectionsClicked\0" "OnUIWidgetEditLayersClicked\0" "OnUIWidgetImportHeightmapClicked\0" "OnUIWidgetSettingsClicked\0" "OnUIBrushRadiusChanged\0value\0" "OnUIBrushFalloffChanged\0OnUIBrushInvertChanged\0" "OnUITerrainStepHeightChanged\0" "OnUILayersStepWeightChanged\0" "OnUILayersLayerListItemClicked\0" "QListWidgetItem*\0pListItem\0" "OnUILayersEditLayerListClicked\0" "OnUISectionsActiveSectionDeleteLayersClicked\0" "OnUISectionsActiveSectionDeleteSectionClicked\0" "OnUISectionsInactiveSectionCreateSectionClicked\0" "OnUIHeightmapImportPanelSourceTypeClicked\0" "OnUIHeightmapImportPanelSelectSourceImageClicked\0" "OnUIHeightmapImportPanelScaleAmountChanged\0" "OnUIHeightmapImportPanelScaleTypeClicked\0" "OnUIHeightmapImportPanelImportClicked\0" "OnUISettingsPanelViewDistanceValueChanged\0" "OnUISettingsPanelRenderResolutionMultiplierChanged\0" "OnUISettingsPanelLODDistanceRatioChanged\0" "OnUISettingsPanelRebuildQuadtreeClicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_EditorTerrainEditMode[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 26, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 144, 2, 0x08 /* Private */, 4, 1, 147, 2, 0x08 /* Private */, 5, 1, 150, 2, 0x08 /* Private */, 6, 1, 153, 2, 0x08 /* Private */, 7, 1, 156, 2, 0x08 /* Private */, 8, 1, 159, 2, 0x08 /* Private */, 9, 1, 162, 2, 0x08 /* Private */, 10, 1, 165, 2, 0x08 /* Private */, 12, 1, 168, 2, 0x08 /* Private */, 13, 1, 171, 2, 0x08 /* Private */, 14, 1, 174, 2, 0x08 /* Private */, 15, 1, 177, 2, 0x08 /* Private */, 16, 1, 180, 2, 0x08 /* Private */, 19, 0, 183, 2, 0x08 /* Private */, 20, 0, 184, 2, 0x08 /* Private */, 21, 0, 185, 2, 0x08 /* Private */, 22, 0, 186, 2, 0x08 /* Private */, 23, 1, 187, 2, 0x08 /* Private */, 24, 0, 190, 2, 0x08 /* Private */, 25, 1, 191, 2, 0x08 /* Private */, 26, 1, 194, 2, 0x08 /* Private */, 27, 0, 197, 2, 0x08 /* Private */, 28, 1, 198, 2, 0x08 /* Private */, 29, 1, 201, 2, 0x08 /* Private */, 30, 1, 204, 2, 0x08 /* Private */, 31, 0, 207, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Double, 11, QMetaType::Void, QMetaType::Double, 11, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Double, 11, QMetaType::Void, QMetaType::Double, 11, QMetaType::Void, 0x80000000 | 17, 18, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Void, QMetaType::Int, 11, QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Void, QMetaType::Int, 11, QMetaType::Void, QMetaType::Int, 11, QMetaType::Void, QMetaType::Double, 11, QMetaType::Void, 0 // eod }; void EditorTerrainEditMode::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { EditorTerrainEditMode *_t = static_cast<EditorTerrainEditMode *>(_o); switch (_id) { case 0: _t->OnUIWidgetEditTerrainClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->OnUIWidgetEditDetailsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: _t->OnUIWidgetEditHolesClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 3: _t->OnUIWidgetEditSectionsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 4: _t->OnUIWidgetEditLayersClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->OnUIWidgetImportHeightmapClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 6: _t->OnUIWidgetSettingsClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: _t->OnUIBrushRadiusChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 8: _t->OnUIBrushFalloffChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 9: _t->OnUIBrushInvertChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; case 10: _t->OnUITerrainStepHeightChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 11: _t->OnUILayersStepWeightChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 12: _t->OnUILayersLayerListItemClicked((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break; case 13: _t->OnUILayersEditLayerListClicked(); break; case 14: _t->OnUISectionsActiveSectionDeleteLayersClicked(); break; case 15: _t->OnUISectionsActiveSectionDeleteSectionClicked(); break; case 16: _t->OnUISectionsInactiveSectionCreateSectionClicked(); break; case 17: _t->OnUIHeightmapImportPanelSourceTypeClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 18: _t->OnUIHeightmapImportPanelSelectSourceImageClicked(); break; case 19: _t->OnUIHeightmapImportPanelScaleAmountChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 20: _t->OnUIHeightmapImportPanelScaleTypeClicked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 21: _t->OnUIHeightmapImportPanelImportClicked(); break; case 22: _t->OnUISettingsPanelViewDistanceValueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 23: _t->OnUISettingsPanelRenderResolutionMultiplierChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 24: _t->OnUISettingsPanelLODDistanceRatioChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 25: _t->OnUISettingsPanelRebuildQuadtreeClicked(); break; default: ; } } } const QMetaObject EditorTerrainEditMode::staticMetaObject = { { &EditorEditMode::staticMetaObject, qt_meta_stringdata_EditorTerrainEditMode.data, qt_meta_data_EditorTerrainEditMode, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *EditorTerrainEditMode::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *EditorTerrainEditMode::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_EditorTerrainEditMode.stringdata)) return static_cast<void*>(const_cast< EditorTerrainEditMode*>(this)); return EditorEditMode::qt_metacast(_clname); } int EditorTerrainEditMode::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = EditorEditMode::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 26) qt_static_metacall(this, _c, _id, _a); _id -= 26; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 26) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 26; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/Engine/Source/Engine/StaticMesh.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/StaticMesh.h" #include "Engine/DataFormats.h" #include "Engine/Material.h" #include "Engine/ResourceManager.h" #include "Engine/Physics/CollisionShape.h" #include "Renderer/Renderer.h" #include "Renderer/VertexBufferBindingArray.h" #include "Core/ChunkFileReader.h" #include "Core/MeshUtilties.h" Log_SetChannel(StaticMesh); DEFINE_RESOURCE_TYPE_INFO(StaticMesh); DEFINE_RESOURCE_GENERIC_FACTORY(StaticMesh); StaticMesh::StaticMesh(const ResourceTypeInfo *pResourceTypeInfo /* = &s_TypeInfo */) : BaseClass(pResourceTypeInfo), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_vertexFactoryFlags(0), m_pCollisionShape(nullptr), m_pLODs(nullptr), m_LODCount(0), m_GPUResourcesCreated(false) { } StaticMesh::LOD::LOD() : m_vertexFactoryFlags(0), m_pIndices(nullptr), m_indexCount(0), m_indexFormat(GPU_INDEX_FORMAT_COUNT), m_pIndexBuffer(nullptr), m_loaded(false) { } StaticMesh::~StaticMesh() { ReleaseGPUResources(); delete[] m_pLODs; for (uint32 materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { if (m_materials[materialIndex] != nullptr) m_materials[materialIndex]->Release(); } if (m_pCollisionShape != nullptr) m_pCollisionShape->Release(); } StaticMesh::LOD::~LOD() { ReleaseGPUResources(); Y_free(m_pIndices); } bool StaticMesh::Load(const char *FileName, ByteStream *pStream) { BinaryReader binaryReader(pStream); #define ABORTREASON(Reason) Log_ErrorPrintf("Could not load static mesh '%s': %s", FileName, Reason) // fix name m_strName = FileName; // read header DF_STATICMESH_HEADER meshHeader; if (!binaryReader.SafeReadBytes(&meshHeader, sizeof(meshHeader)) || meshHeader.Magic != DF_STATICMESH_HEADER_MAGIC || meshHeader.Size != sizeof(DF_STATICMESH_HEADER) || meshHeader.MaterialCount == 0 || meshHeader.LODCount == 0) { ABORTREASON("invalid file header."); return false; } // set data m_boundingBox = AABox(meshHeader.BoundingBoxMin, meshHeader.BoundingBoxMax); m_boundingSphere = Sphere(meshHeader.BoundingSphereCenter, meshHeader.BoundingSphereRadius); m_materials.Resize(meshHeader.MaterialCount); Y_memzero(m_materials.GetBasePointer(), sizeof(const Material *) * m_materials.GetSize()); m_pLODs = new LOD[meshHeader.LODCount]; m_LODCount = meshHeader.LODCount; m_LODOffsetTable.Resize(m_LODCount); m_LODOffsetTable.ZeroContents(); // figure out VF flags m_vertexFactoryFlags = LOCAL_VERTEX_FACTORY_FLAG_TANGENT_VECTORS; if (meshHeader.VertexFlags & DF_STATICMESH_VERTEX_FLAG_COLOR) m_vertexFactoryFlags |= LOCAL_VERTEX_FACTORY_FLAG_VERTEX_COLORS; if (meshHeader.VertexFlags & DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT2) m_vertexFactoryFlags |= LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT2_TEXCOORDS; else if (meshHeader.VertexFlags & DF_STATICMESH_VERTEX_FLAG_TEXCOORD_FLOAT3) m_vertexFactoryFlags |= LOCAL_VERTEX_FACTORY_FLAG_VERTEX_FLOAT3_TEXCOORDS; // load collision shape if (meshHeader.CollisionShapeType != Physics::COLLISION_SHAPE_TYPE_NONE) { if (!binaryReader.SafeSeekAbsolute(meshHeader.CollisionShapeOffset)) return false; m_pCollisionShape = Physics::CollisionShape::CreateFromStream(pStream, meshHeader.CollisionShapeSize); if (m_pCollisionShape == nullptr) { ABORTREASON("could not load collision shape"); return false; } } // load materials { if (!binaryReader.SafeSeekAbsolute(meshHeader.MaterialNamesOffset)) return false; SmallString materialName; for (uint32 materialIndex = 0; materialIndex < m_materials.GetSize(); materialIndex++) { if (!binaryReader.SafeReadCString(&materialName)) return false; if ((m_materials[materialIndex] = g_pResourceManager->GetMaterial(materialName)) == nullptr) { m_materials[materialIndex] = g_pResourceManager->GetDefaultMaterial(); DebugAssert(m_materials[materialIndex] != nullptr); } } } // load lods { if (!binaryReader.SafeSeekAbsolute(meshHeader.LODOffsetsOffset)) return false; // load the offsets for (uint32 lodIndex = 0; lodIndex < m_LODCount; lodIndex++) { if (!binaryReader.SafeReadUInt32(&m_LODOffsetTable[lodIndex])) return false; } // load the actual lods for (uint32 lodIndex = 0; lodIndex < m_LODCount; lodIndex++) { if (!binaryReader.SafeSeekAbsolute(m_LODOffsetTable[lodIndex]) || !m_pLODs[lodIndex].LoadFromStream(pStream, m_vertexFactoryFlags)) return false; } } // create on gpu if (g_pRenderer != nullptr && !CreateGPUResources()) { ABORTREASON("failed to create GPU resources"); return false; } return true; #undef ABORTREASON } bool StaticMesh::LOD::LoadFromStream(ByteStream *pStream, uint32 vertexFactoryFlags) { BinaryReader binaryReader(pStream); DF_STATICMESH_LOD_HEADER lodHeader; if (!binaryReader.SafeReadBytes(&lodHeader, sizeof(lodHeader))) return false; // allocate everything m_vertexFactoryFlags = vertexFactoryFlags; m_vertices.Resize(lodHeader.VertexCount); m_indexCount = lodHeader.IndexCount; m_indexFormat = (GPU_INDEX_FORMAT)lodHeader.IndexFormat; uint32 indicesSize = m_indexCount * ((m_indexFormat == GPU_INDEX_FORMAT_UINT32) ? sizeof(uint32) : sizeof(uint16)); m_pIndices = Y_malloc(indicesSize); m_batches.Resize(lodHeader.BatchCount); // load vertices { if (!binaryReader.SafeSeekAbsolute(lodHeader.VerticesOffset)) return false; // read them into a temporary memory block DF_STATICMESH_VERTEX *fileVertices = new DF_STATICMESH_VERTEX[m_vertices.GetSize()]; if (!binaryReader.SafeReadBytes(fileVertices, sizeof(DF_STATICMESH_VERTEX) * m_vertices.GetSize())) { delete[] fileVertices; return false; } // parse vertices const DF_STATICMESH_VERTEX *pSourceVertex = fileVertices; LocalVertexFactory::Vertex *pDestinationVertex = m_vertices.GetBasePointer(); for (uint32 vertexIndex = 0; vertexIndex < m_vertices.GetSize(); vertexIndex++) { pDestinationVertex->Position.Load(pSourceVertex->Position); pDestinationVertex->Tangent.Load(pSourceVertex->Tangent); pDestinationVertex->Binormal.Load(pSourceVertex->Binormal); pDestinationVertex->Normal.Load(pSourceVertex->Normal); pDestinationVertex->TexCoord.Load(pSourceVertex->TexCoord); pDestinationVertex->Color = pSourceVertex->Color; pSourceVertex++; pDestinationVertex++; } delete[] fileVertices; } // load indices { if (!binaryReader.SafeSeekAbsolute(lodHeader.IndicesOffset)) return false; // one read if (!binaryReader.SafeReadBytes(m_pIndices, indicesSize)) return false; } // load batches { if (!binaryReader.SafeSeekAbsolute(lodHeader.BatchesOffset)) return false; // read them into a temporary memory block DF_STATICMESH_BATCH *fileBatches = new DF_STATICMESH_BATCH[m_batches.GetSize()]; if (!binaryReader.SafeReadBytes(fileBatches, sizeof(DF_STATICMESH_BATCH) * m_batches.GetSize())) { delete[] fileBatches; return false; } // parse vertices const DF_STATICMESH_BATCH *pSourceBatch = fileBatches; Batch *pDestinationBatch = m_batches.GetBasePointer(); for (uint32 batchIndex = 0; batchIndex < m_batches.GetSize(); batchIndex++) { pDestinationBatch->MaterialIndex = pSourceBatch->MaterialIndex; pDestinationBatch->StartIndex = pSourceBatch->StartIndex; pDestinationBatch->NumIndices = pSourceBatch->NumIndices; pSourceBatch++; pDestinationBatch++; } delete[] fileBatches; } // create on gpu if (g_pRenderer != nullptr && !CreateGPUResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } m_loaded = true; return true; } void StaticMesh::LOD::Unload() { ReleaseGPUResources(); m_loaded = false; m_batches.Obliterate(); Y_free(m_pIndices); m_pIndices = nullptr; m_indexCount = 0; m_indexFormat = GPU_INDEX_FORMAT_COUNT; m_vertices.Obliterate(); } bool StaticMesh::CreateGPUResources() const { if (m_GPUResourcesCreated) return true; for (uint32 lodIndex = 0; lodIndex < m_LODCount; lodIndex++) { LOD *pLOD = &m_pLODs[lodIndex]; if (pLOD->IsLoaded() && !pLOD->CreateGPUResources()) return false; } m_GPUResourcesCreated = true; return true; } bool StaticMesh::LOD::CreateGPUResources() const { if (m_vertexBuffers.GetActiveBufferCount() == 0) { if (!LocalVertexFactory::CreateVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_vertexFactoryFlags, m_vertices.GetBasePointer(), m_vertices.GetSize(), &m_vertexBuffers)) return false; } if (m_pIndexBuffer == nullptr) { GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, m_indexCount * ((m_indexFormat == GPU_INDEX_FORMAT_UINT32) ? sizeof(uint32) : sizeof(uint16))); if ((m_pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, m_pIndices)) == NULL) return false; } return true; } void StaticMesh::ReleaseGPUResources() const { for (uint32 lodIndex = 0; lodIndex < m_LODCount; lodIndex++) { LOD *pLOD = &m_pLODs[lodIndex]; if (pLOD->IsLoaded()) pLOD->ReleaseGPUResources(); } m_GPUResourcesCreated = false; } void StaticMesh::LOD::ReleaseGPUResources() const { m_vertexBuffers.Clear(); SAFE_RELEASE(m_pIndexBuffer); } bool StaticMesh::CheckGPUResources() const { if (!m_GPUResourcesCreated && !CreateGPUResources()) return false; return true; } <file_sep>/Engine/Source/Engine/Defines.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/Common.h" Y_Define_NameTable(NameTables::MaterialBlendingMode) Y_NameTable_Entry("None", MATERIAL_BLENDING_MODE_NONE) Y_NameTable_Entry("Additive", MATERIAL_BLENDING_MODE_ADDITIVE) Y_NameTable_Entry("Straight", MATERIAL_BLENDING_MODE_STRAIGHT) Y_NameTable_Entry("Premultiplied", MATERIAL_BLENDING_MODE_PREMULTIPLIED) Y_NameTable_Entry("Masked", MATERIAL_BLENDING_MODE_MASKED) Y_NameTable_Entry("SoftMasked", MATERIAL_BLENDING_MODE_SOFTMASKED) Y_NameTable_End() Y_Define_NameTable(NameTables::MaterialLightingType) Y_NameTable_Entry("Emissive", MATERIAL_LIGHTING_TYPE_EMISSIVE) Y_NameTable_Entry("Reflective", MATERIAL_LIGHTING_TYPE_REFLECTIVE) Y_NameTable_Entry("ReflectiveEmissive", MATERIAL_LIGHTING_TYPE_REFLECTIVE_EMISSIVE) Y_NameTable_Entry("ReflectiveTwoSided", MATERIAL_LIGHTING_TYPE_REFLECTIVE_TWO_SIDED) Y_NameTable_End() Y_Define_NameTable(NameTables::MaterialLightingModel) Y_NameTable_Entry("Phong", MATERIAL_LIGHTING_MODEL_PHONG) Y_NameTable_Entry("BlinnPhong", MATERIAL_LIGHTING_MODEL_BLINN_PHONG) Y_NameTable_Entry("PhysicallyBased", MATERIAL_LIGHTING_MODEL_PHYSICALLY_BASED) Y_NameTable_Entry("Custom", MATERIAL_LIGHTING_MODEL_CUSTOM) Y_NameTable_End() Y_Define_NameTable(NameTables::MaterialLightingNormalSpace) Y_NameTable_Entry("World", MATERIAL_LIGHTING_NORMAL_SPACE_WORLD_SPACE) Y_NameTable_Entry("Tangent", MATERIAL_LIGHTING_NORMAL_SPACE_TANGENT_SPACE) Y_NameTable_End() Y_Define_NameTable(NameTables::MaterialRenderMode) Y_NameTable_Entry("Normal", MATERIAL_RENDER_MODE_NORMAL) Y_NameTable_Entry("Wireframe", MATERIAL_RENDER_MODE_WIREFRAME) Y_NameTable_Entry("PostProcess", MATERIAL_RENDER_MODE_POST_PROCESS) Y_NameTable_End() Y_Define_NameTable(NameTables::MaterialRenderLayer) Y_NameTable_Entry("SkyBox", MATERIAL_RENDER_LAYER_SKYBOX) Y_NameTable_Entry("Normal", MATERIAL_RENDER_LAYER_NORMAL) Y_NameTable_End() <file_sep>/Engine/Source/ContentConverterStandalone/OBJImporter.cpp #include "PrecompiledHeader.h" #include "ContentConverter.h" #include "ContentConverter/OBJImporter.h" #include "ResourceCompiler/StaticMeshGenerator.h" Log_SetChannel(OBJImporter); #define CHECK_ARG(str) !Y_strcmp(argv[i], str) #define CHECK_ARG_PARAM(str) !Y_strcmp(argv[i], str) && ((i + 1) < argc) static void PrintOBJImporterSyntax() { Log_InfoPrint("OBJ Importer options:"); Log_InfoPrint(" -h, -help: Displays this text."); Log_InfoPrint(" -i <filename>: Specify source file name."); Log_InfoPrint(" -basedir <name>: Output base directory."); Log_InfoPrint(" -name <name>: Output name. Required if -nogroupmeshes. A full path is required if you don't specify -meshpath."); Log_InfoPrint(" -meshpath <name>: Mesh path. Required if -groupmeshes or -genmap are specified."); Log_InfoPrint(" -materialpath <name>: Material output path. Defaults to mesh path."); Log_InfoPrint(" -texturepath <name>: Material output path. Defaults to mesh path."); Log_InfoPrint(" -[no]importmaterials: Generate materials for OBJ materials, default on"); Log_InfoPrint(" -[no]overwritematerials: Overwrite existing materials when importing, default off"); Log_InfoPrint(" -[no]importtextures: Convert textures for OBJ materials, default on"); Log_InfoPrint(" -[no]overwritetextures: Overwrite existing textures when importing materials, default off"); Log_InfoPrint(" -teximport [option] [option value]: Specify texture converter argument."); Log_InfoPrint(" -[no]groupmeshes: Use OBJ face groups as meshes, default off"); Log_InfoPrint(" -[no]center: Center mesh at (0, 0, 0), default off"); Log_InfoPrint(" -[no]genmap <name>: Generate a map with all meshes, default off. Implies -center."); Log_InfoPrint(" -[no]smoothinggroups: Generate normals using smoothing groups from obj, default on"); Log_InfoPrint(" -scale: Global uniform scale all vertices."); Log_InfoPrint(" -rotate(X|Y|Z) <amount>: Rotate around the axis as a post-transform."); Log_InfoPrint(" -translate(X|Y|Z) <degrees>: Translate along the axis as a post-transform."); Log_InfoPrint(" -scale[X|Y|Z] <amount>: Uniform or nonuniform scale on axis as a post-transform."); Log_InfoPrint(" -flipwinding: Flip the triangle winding order"); Log_InfoPrint(" -cs <(yup|zup)_(lh|rh)>: File uses specified coordinate system, convert if necessary."); Log_InfoPrint(" -collision: Defines collision shape type, defaults to none. (trianglemesh, convexhull)"); Log_InfoPrint(""); } bool ParseOBJConverterOption(OBJImporterOptions &Options, int &i, int argc, char *argv[]) { if (CHECK_ARG_PARAM("-i")) Options.InputFileName = argv[++i]; else if (CHECK_ARG_PARAM("-meshdir")) Options.MeshDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-meshprefix")) Options.MeshPrefix = argv[++i]; else if (CHECK_ARG_PARAM("-genmap")) Options.OutputMapName = argv[++i]; else if (CHECK_ARG("-nomaterials")) Options.ImportMaterials = false; else if (CHECK_ARG("-materials")) Options.ImportMaterials = true; else if (CHECK_ARG_PARAM("-materialdir")) Options.MaterialDirectory = argv[++i]; else if (CHECK_ARG_PARAM("-materialprefix")) Options.MaterialPrefix = argv[++i]; else if (CHECK_ARG_PARAM("-defaultmaterialname")) Options.DefaultMaterialName = argv[++i]; else if (CHECK_ARG_PARAM("-collision")) Options.BuildCollisionShapeType = argv[++i]; else if (CHECK_ARG_PARAM("-rotateX")) Options.TransformMatrix = float4x4::MakeRotationMatrixX(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateY")) Options.TransformMatrix = float4x4::MakeRotationMatrixY(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-rotateZ")) Options.TransformMatrix = float4x4::MakeRotationMatrixZ(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateX")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateY")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-translateZ")) Options.TransformMatrix = float4x4::MakeTranslationMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleX")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i]), 0.0f, 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleY")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, StringConverter::StringToFloat(argv[++i]), 0.0f) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scaleZ")) Options.TransformMatrix = float4x4::MakeScaleMatrix(0.0f, 0.0f, StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG_PARAM("-scale")) Options.TransformMatrix = float4x4::MakeScaleMatrix(StringConverter::StringToFloat(argv[++i])) * Options.TransformMatrix; else if (CHECK_ARG("-center")) Options.CenterMeshes = StaticMeshGenerator::CenterOrigin_Center; else if (CHECK_ARG("-centerbase")) Options.CenterMeshes = StaticMeshGenerator::CenterOrigin_CenterBottom; else if (CHECK_ARG_PARAM("-cs")) { ++i; if (!Y_stricmp(argv[i], "yup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_LH; else if (!Y_stricmp(argv[i], "yup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Y_UP_RH; else if (!Y_stricmp(argv[i], "zup_lh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_LH; else if (!Y_stricmp(argv[i], "zup_rh")) Options.CoordinateSystem = COORDINATE_SYSTEM_Z_UP_RH; else { Log_ErrorPrintf("Invalid coordinate system specified."); return false; } } else if (CHECK_ARG("-smoothinggroups")) Options.UseSmoothingGroups = true; else if (CHECK_ARG("-nosmoothinggroups")) Options.UseSmoothingGroups = false; else if (CHECK_ARG("-mergegroups")) Options.MergeGroups = true; else if (CHECK_ARG("-nomergegroups")) Options.MergeGroups = false; else if (CHECK_ARG_PARAM("-collision")) Options.BuildCollisionShapeType = argv[++i]; else if (CHECK_ARG("-h") || CHECK_ARG("-help")) { i = argc; PrintOBJImporterSyntax(); return false; } else { Log_ErrorPrintf("Unknown option: %s", argv[i]); return false; } return true; } int RunOBJImporter(int argc, char *argv[]) { int i; if (argc == 0) { PrintOBJImporterSyntax(); return 0; } OBJImporterOptions Options; OBJImporter::SetDefaultOptions(&Options); for (i = 0; i < argc; i++) { if (!ParseOBJConverterOption(Options, i, argc, argv)) return 1; } if (Options.InputFileName.IsEmpty()) { Log_ErrorPrintf("Missing input file name."); return 1; } { ConsoleProgressCallbacks progressCallbacks; OBJImporter Importer(&progressCallbacks); if (!Importer.Execute(&Options)) { Log_ErrorPrintf("Import process failed."); return 2; } } Log_InfoPrintf("Import process successful."); return 0; } <file_sep>/Engine/Source/Engine/TerrainRenderer.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/TerrainRenderer.h" #include "Engine/TerrainRendererNull.h" #include "Engine/TerrainRendererCDLOD.h" #include "Engine/EngineCVars.h" #include "Renderer/Renderer.h" #include "Core/MeshUtilties.h" Log_SetChannel(TerrainRenderer); TerrainRenderer::TerrainRenderer(TERRAIN_RENDERER_TYPE type, const TerrainParameters *pParameters, const TerrainLayerList *pLayerList) : m_type(type), m_parameters(*pParameters), m_pLayerList(pLayerList) { m_pLayerList->AddRef(); } TerrainRenderer::~TerrainRenderer() { } TerrainRenderer *TerrainRenderer::CreateTerrainRenderer(const TerrainParameters *pParameters, const TerrainLayerList *pLayerList) { // determine renderer TERRAIN_RENDERER_TYPE rendererType = TERRAIN_RENDERER_TYPE_NULL; if (g_pRenderer != NULL) { if (!NameTable_TranslateType(NameTables::TerrainRendererType, CVars::r_terrain_renderer.GetString(), &rendererType, true)) { Log_WarningPrintf("TerrainRenderer::CreateTerrainRenderer: Unknown terrain renderer type '%s'. Using CDLOD.", CVars::r_terrain_renderer.GetString().GetCharArray()); rendererType = TERRAIN_RENDERER_TYPE_CDLOD; } } switch (rendererType) { case TERRAIN_RENDERER_TYPE_NULL: return new TerrainRendererNull(pParameters, pLayerList); case TERRAIN_RENDERER_TYPE_CDLOD: return new TerrainRendererCDLOD(pParameters, pLayerList); } Panic("Unrecognized terrain renderer type"); return NULL; } // bool TerrainManager::IsSectionInVisibleRange(int32 sectionX, int32 sectionY) const // { // AABox sectionBounds = CalculateSectionBoundingBox(sectionX, sectionY); // return (sectionBounds.GetCenter() - Vector3(m_lastCameraPosition)).SquaredLength() <= Math::Square(m_loadDistance); // } TerrainSectionRenderProxy::TerrainSectionRenderProxy(uint32 entityId, const TerrainSection *pSection) : RenderProxy(entityId), m_pSection(pSection), m_sectionX(pSection->GetSectionX()), m_sectionY(pSection->GetSectionY()) { m_pSection->AddRef(); } TerrainSectionRenderProxy::~TerrainSectionRenderProxy() { m_pSection->Release(); } // void TerrainRenderProxy::UpdateBounds() // { // AABox boundingBox(m_pTerrainRenderer->GetTerrainManager()->CalculateTerrainBoundingBox()); // // if (GetBoundingBox() != boundingBox) // SetBounds(boundingBox, Sphere::FromAABox(boundingBox)); // } bool TerrainSectionRenderProxy::RayCast(const Ray &ray, float3 &contactNormal, float3 &contactPoint, bool exitAtFirstIntersection) const { return m_pSection->RayCast(ray, contactNormal, contactPoint, exitAtFirstIntersection); } uint32 TerrainSectionRenderProxy::GetIntersectingTriangles(const AABox &searchBox, IntersectingTriangleArray &intersectingTriangles) const { uint32 numAdded = 0; // optimize me later! enumerate triangles in box m_pSection->EnumerateTrianglesIntersectingBox(searchBox, [searchBox, &intersectingTriangles, &numAdded](const float3 vertices[3]) { // calculate the normal for these three vertices float3 normal(MeshUtilites::CalculateFaceNormal(vertices[0], vertices[1], vertices[2])); // add to list intersectingTriangles.Add(IntersectingTriangle(vertices[0], vertices[1], vertices[2], normal)); numAdded++; }); return numAdded; } <file_sep>/Editor/Source/Editor/ToolMenuWidget.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/ToolMenuWidget.h" ToolMenuWidget::ToolMenuWidget(QWidget *pParent, Qt::Orientation orientation /* = Qt::Vertical */, bool showLabels /* = true */) : m_orientation(orientation), m_showLabels(showLabels), m_iconSize(16, 16), m_buttonMargins(4) { if (orientation == Qt::Horizontal) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); m_layout = new QHBoxLayout(this); } else { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_layout = new QVBoxLayout(this); } m_layout->setSizeConstraint(QLayout::SetMaximumSize); m_layout->setSpacing(0); m_layout->setMargin(0); } ToolMenuWidget::~ToolMenuWidget() { } void ToolMenuWidget::recreateLayout() { QBoxLayout *newLayout; if (m_orientation == Qt::Horizontal) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); newLayout = new QHBoxLayout(this); } else { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); newLayout = new QVBoxLayout(this); } newLayout->setSizeConstraint(QLayout::SetMaximumSize); newLayout->setSpacing(0); newLayout->setMargin(0); for (Item &item : m_items) { m_layout->removeWidget(item.pWidget); if (item.pAction != nullptr) { delete item.pWidget; item.pWidget = createToolButtonForAction(item.pAction); } newLayout->addWidget(item.pWidget); } delete m_layout; m_layout = newLayout; } void ToolMenuWidget::clear() { for (Item &item : m_items) { m_layout->removeWidget(item.pWidget); if (item.pAction != nullptr) { delete item.pWidget; if (item.pAction->parent() == this) delete item.pAction; } } m_items.clear(); } void ToolMenuWidget::addAction(QAction *pAction) { Item *pExistingItem = findItemForAction(pAction); if (pExistingItem != nullptr) removeAction(pAction); if (pAction->isSeparator()) { QFrame *line = new QFrame(this); line->setFrameShape(QFrame::VLine); line->setFrameShadow(QFrame::Raised); //line->setFrameShadow(QFrame::Sunken); Item item; item.pAction = pAction; item.pWidget = line; m_items.append(item); m_layout->addWidget(line); } else { QToolButton *pToolButton = createToolButtonForAction(pAction); Item item; item.pAction = pAction; item.pWidget = pToolButton; m_items.append(item); m_layout->addWidget(pToolButton); } } void ToolMenuWidget::addWidget(QWidget *pWidget) { Item *pExistingItem = findItemForWidget(pWidget); if (pExistingItem != nullptr) removeWidget(pWidget); Item item; item.pAction = nullptr; item.pWidget = pWidget; m_items.append(item); m_layout->addWidget(pWidget); } void ToolMenuWidget::addSeperator() { QAction *action = new QAction(this); action->setSeparator(true); addAction(action); } void ToolMenuWidget::removeAction(QAction *pAction) { for (int i = 0; i < m_items.size(); i++) { if (m_items[i].pAction == pAction) { m_layout->removeWidget(m_items[i].pWidget); m_items.removeAt(i); return; } } } void ToolMenuWidget::removeWidget(QWidget *pWidget) { for (int i = 0; i < m_items.size(); i++) { if (m_items[i].pWidget == pWidget) { m_layout->removeWidget(pWidget); m_items.removeAt(i); return; } } } QToolButton *ToolMenuWidget::createToolButtonForAction(QAction *pAction) { QToolButton *pToolButton = new QToolButton(this); if (m_orientation == Qt::Horizontal) { pToolButton->setToolButtonStyle((m_showLabels) ? Qt::ToolButtonTextUnderIcon : Qt::ToolButtonIconOnly); pToolButton->setSizePolicy((m_showLabels) ? QSizePolicy::Expanding : QSizePolicy::Fixed, (m_showLabels) ? QSizePolicy::Expanding : QSizePolicy::Fixed); //pToolButton->setMinimumSize(QSize(m_iconSize.width() + m_buttonMargins * 2, m_iconSize.height() + m_buttonMargins * 2)); pToolButton->setMaximumSize(QSize(m_iconSize.width() + m_buttonMargins * 2, 16777215)); pToolButton->setFixedSize(QSize(m_iconSize.width() + m_buttonMargins * 2, m_iconSize.height() + m_buttonMargins * 2)); } else { pToolButton->setToolButtonStyle((m_showLabels) ? Qt::ToolButtonTextBesideIcon : Qt::ToolButtonIconOnly); pToolButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); pToolButton->setMaximumSize(QSize(16777215, m_iconSize.height() + m_buttonMargins * 2)); pToolButton->setFixedSize(QSize(16777215, m_iconSize.height() + m_buttonMargins * 2)); } pToolButton->setAutoRaise(true); // pToolButton->setText(pAction->text()); // pToolButton->setIcon(pAction->icon()); // pToolButton->setCheckable(pAction->isCheckable()); // pToolButton->setChecked(pAction->isChecked()); pToolButton->setDefaultAction(pAction); //connect(pToolButton, SIGNAL(clicked(bool)), this, SLOT(OnToolButtonClicked(bool))); return pToolButton; } ToolMenuWidget::Item *ToolMenuWidget::findItemForAction(QAction *pAction) { for (Item &item : m_items) { if (item.pAction == pAction) return &item; } return nullptr; } ToolMenuWidget::Item *ToolMenuWidget::findItemForWidget(QWidget *pWidget) { for (Item &item : m_items) { if (item.pWidget == pWidget) return &item; } return nullptr; } void ToolMenuWidget::OnToolButtonClicked(bool checked) { QObject *signalSender = sender(); if (signalSender == nullptr) return; for (Item &item : m_items) { if (item.pWidget == signalSender) { if (item.pAction->isCheckable()) item.pAction->setChecked(checked); item.pAction->triggered(checked); return; } } } <file_sep>/Editor/Source/Editor/EditorCVars.h #pragma once #include "Editor/Common.h" namespace CVars { extern CVar e_camera_max_speed; extern CVar e_camera_acceleration; extern CVar e_max_fps; extern CVar e_max_fps_unfocused; } <file_sep>/Engine/Source/Engine/ParticleSystemBuiltinEmitters.h #pragma once #include "Engine/ParticleSystemEmitter.h" class ParticleSystemEmitter_Sprite : public ParticleSystemEmitter { DECLARE_OBJECT_TYPE_INFO(ParticleSystemEmitter_Sprite, ParticleSystemEmitter); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemEmitter_Sprite); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemEmitter_Sprite); public: ParticleSystemEmitter_Sprite(); virtual ~ParticleSystemEmitter_Sprite(); // Material to draw. const Material *GetMaterial() const { return m_pMaterial; } void SetMaterial(const Material *pMaterial); virtual void InitializeInstance(InstanceData *pEmitterData) const override; virtual void CleanupInstance(InstanceData *pEmitterData) const override; virtual void UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const override; virtual void InitializeRenderData(InstanceRenderData *pEmitterRenderData) const override; virtual void CleanupRenderData(InstanceRenderData *pEmitterRenderData) const override; virtual void UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const override; virtual void QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; private: // Material to render. const Material *m_pMaterial; // property callbacks static bool PropertyCallbackGetMaterial(ThisClass *pParticleSystem, const void *pUserData, String *pValue); static bool PropertyCallbackSetMaterial(ThisClass *pParticleSystem, const void *pUserData, const String *pValue); }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class StaticMesh; class ParticleSystemEmitter_StaticMesh : public ParticleSystemEmitter { DECLARE_OBJECT_TYPE_INFO(ParticleSystemEmitter_Sprite, ParticleSystemEmitter); DECLARE_OBJECT_GENERIC_FACTORY(ParticleSystemEmitter_Sprite); DECLARE_OBJECT_PROPERTY_MAP(ParticleSystemEmitter_Sprite); public: ParticleSystemEmitter_StaticMesh(); virtual ~ParticleSystemEmitter_StaticMesh(); // Static mesh to instance. const StaticMesh *GetMesh(uint32 index) const { return m_meshes[index]; } void SetMesh(uint32 index, const StaticMesh *pMesh); void AddMesh(const StaticMesh *pMesh); void RemoveMesh(uint32 index); virtual void InitializeInstance(InstanceData *pEmitterData) const override; virtual void CleanupInstance(InstanceData *pEmitterData) const override; virtual void UpdateInstance(InstanceData *pEmitterData, const Transform *pBaseTransform, RandomNumberGenerator *pRNG, float deltaTime) const override; virtual void InitializeRenderData(InstanceRenderData *pEmitterRenderData) const override; virtual void CleanupRenderData(InstanceRenderData *pEmitterRenderData) const override; virtual void UpdateRenderData(const InstanceData *pEmitterData, InstanceRenderData *pEmitterRenderData) const override; virtual void QueueForRender(const RenderProxy *pRenderProxy, uint32 userData, const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, RenderQueue *pRenderQueue) const override; virtual void SetupForDraw(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const override; virtual void DrawQueueEntry(const InstanceRenderData *pEmitterRenderData, const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const override; private: // Meshes to render. PODArray<const StaticMesh *> m_meshes; }; <file_sep>/Engine/Source/Engine/Material.h #pragma once #include "Engine/Common.h" #include "Engine/MaterialShader.h" #include "Renderer/RendererTypes.h" class GPUTexture; class Texture; class GPUSamplerState; class ShaderProgram; class Material : public Resource { DECLARE_RESOURCE_TYPE_INFO(Material, Resource); DECLARE_RESOURCE_GENERIC_FACTORY(Material); public: Material(const ResourceTypeInfo *pResourceTypeInfo = &s_TypeInfo); ~Material(); const MaterialShader *GetShader() const { return m_pShader; } uint32 GetShaderStaticSwitchMask() const { return m_iShaderStaticSwitchMask; } // new void Create(const char *resourceName, const MaterialShader *pShader); // serialization bool Load(const char *resourceName, ByteStream *pStream); // device resource management bool CreateDeviceResources() const; bool BindDeviceResources(GPUCommandList *pCommandList, ShaderProgram *pProgram) const; void ReleaseDeviceResources() const; // wrappers to shader const MaterialShader::UniformParameter::Value *GetShaderUniformParameter(uint32 i) const { return &m_ShaderUniformParameters[i]; } const MaterialShader::TextureParameter::Value *GetShaderTextureParameter(uint32 i) const { return &m_ShaderTextureParameters[i]; } const bool GetShaderStaticSwitchParameter(uint32 i) const { return (m_iShaderStaticSwitchMask & m_pShader->GetStaticSwitchParameter(i)->Mask) != 0; } // shader parameters void SetShaderUniformParameter(uint32 Index, SHADER_PARAMETER_TYPE Type, const void *pNewValue); void SetShaderUniformParameterString(uint32 Index, const char *NewValue); bool SetShaderTextureParameter(uint32 Index, const Texture *pNewTexture); bool SetShaderTextureParameter(uint32 Index, GPUTexture *pNewTexture); bool SetShaderTextureParameterString(uint32 Index, const char *NewValue); void SetShaderStaticSwitchParameter(uint32 Index, bool On); // shader parameters by string bool SetShaderUniformParameterByName(const char *Name, SHADER_PARAMETER_TYPE Type, const void *pNewValue); bool SetShaderUniformParameterStringByName(const char *Name, const char *NewValue); bool SetShaderTextureParameterByName(const char *Name, const Texture *pNewTexture); bool SetShaderTextureParameterByName(const char *Name, GPUTexture *pNewTexture); bool SetShaderTextureParameterStringByName(const char *Name, const char *NewValue); bool SetShaderStaticSwitchParameterByName(const char *Name, bool On); // forwarders to material shader uint32 GetRenderPassMask(uint32 WantedPassMask) const { return m_pShader->SelectRenderPassMask(WantedPassMask); } GPUBlendState *SelectBlendState() const { return m_pShader->SelectBlendState(); } private: const MaterialShader *m_pShader; MemArray<MaterialShader::UniformParameter::Value> m_ShaderUniformParameters; MemArray<MaterialShader::TextureParameter::Value> m_ShaderTextureParameters; uint32 m_iShaderStaticSwitchMask; mutable bool m_bDeviceResourcesCreated; }; <file_sep>/Engine/Source/Renderer/RenderProxies/SkeletalMeshRenderProxy.cpp #include "Renderer/PrecompiledHeader.h" #include "Renderer/RenderProxies/SkeletalMeshRenderProxy.h" #include "Renderer/VertexFactories/SkeletalMeshVertexFactory.h" #include "Renderer/RenderWorld.h" #include "Renderer/Renderer.h" #include "Engine/EngineCVars.h" #include "Engine/Camera.h" #include "Engine/Material.h" SkeletalMeshRenderProxy::SkeletalMeshRenderProxy(uint32 entityId, const SkeletalMesh *pSkeletalMesh, const Transform &transform, uint32 shadowFlags) : RenderProxy(entityId), m_visibility(true), m_pSkeletalMesh(NULL), m_shadowFlags(shadowFlags), m_tintEnabled(false), m_tintColor(0xFFFFFFFF), m_bGPUResourcesCreated(false), m_pCPUSkinningVertexBuffer(nullptr), m_useGPUSkinning(CVars::r_gpu_skinning.GetBool()) { DebugAssert(pSkeletalMesh != NULL); m_pSkeletalMesh = pSkeletalMesh; m_pSkeletalMesh->AddRef(); // allocate materials m_materials.Resize(pSkeletalMesh->GetMaterialCount()); for (uint32 i = 0; i < pSkeletalMesh->GetMaterialCount(); i++) { m_materials[i] = pSkeletalMesh->GetMaterial(i); DebugAssert(m_materials[i] != NULL); m_materials[i]->AddRef(); } // update bounds SetTransform(transform); // init bone matrices InitializeBoneTransformArray(); } SkeletalMeshRenderProxy::~SkeletalMeshRenderProxy() { ReleaseDeviceResources(); m_pSkeletalMesh->Release(); for (uint32 i = 0; i < m_materials.GetSize(); i++) m_materials[i]->Release(); } void SkeletalMeshRenderProxy::SetSkeletalMesh(const SkeletalMesh *pSkeletalMesh) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetSkeletalMesh(pSkeletalMesh); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); ReferenceCountedHolder<const SkeletalMesh> pSkeletalMeshHolder(pSkeletalMesh); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, pSkeletalMeshHolder]() { pThisHolder->RealSetSkeletalMesh(pSkeletalMeshHolder); }); } } void SkeletalMeshRenderProxy::RealSetSkeletalMesh(const SkeletalMesh *pSkeletalMesh) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pSkeletalMesh != nullptr); if (m_pSkeletalMesh == pSkeletalMesh) return; // not yet owned by render thread, so no need to do async modifications ReleaseDeviceResources(); // release materials for (uint32 i = 0; i < m_materials.GetSize(); i++) { m_materials[i]->Release(); m_materials[i] = NULL; } // release mesh m_pSkeletalMesh->Release(); // set new mesh m_pSkeletalMesh = pSkeletalMesh; m_pSkeletalMesh->AddRef(); // reallocate materials m_materials.Resize(m_pSkeletalMesh->GetMaterialCount()); m_materials.Shrink(); for (uint32 i = 0; i < m_pSkeletalMesh->GetMaterialCount(); i++) { m_materials[i] = m_pSkeletalMesh->GetMaterial(i); DebugAssert(m_materials[i] != NULL); m_materials[i]->AddRef(); } // initialize bone transforms InitializeBoneTransformArray(); // fix up bounds SetBounds(m_transform.TransformBoundingBox(m_pSkeletalMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pSkeletalMesh->GetBoundingSphere())); } void SkeletalMeshRenderProxy::SetMaterial(uint32 i, const Material *pMaterialOverride) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetMaterial(i, pMaterialOverride); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); ReferenceCountedHolder<const Material> pMaterialHolder(pMaterialOverride); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, i, pMaterialHolder]() { pThisHolder->RealSetMaterial(i, pMaterialHolder); }); } } void SkeletalMeshRenderProxy::RealSetMaterial(uint32 i, const Material *pMaterialOverride) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); DebugAssert(pMaterialOverride != NULL); // not yet owned by render thread, so no need to do async modifications DebugAssert(i < m_materials.GetSize()); m_materials[i]->Release(); m_materials[i] = pMaterialOverride; m_materials[i]->AddRef(); } void SkeletalMeshRenderProxy::SetTransform(const Transform &transform) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTransform(transform); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, transform]() { pThisHolder->RealSetTransform(transform); }); } } void SkeletalMeshRenderProxy::RealSetTransform(const Transform &transform) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_transform = transform; m_localToWorldMatrix = m_transform.GetTransformMatrix4x4(); SetBounds(m_transform.TransformBoundingBox(m_pSkeletalMesh->GetBoundingBox()), m_transform.TransformBoundingSphere(m_pSkeletalMesh->GetBoundingSphere())); } void SkeletalMeshRenderProxy::SetTintColor(bool enabled, uint32 color /* = 0 */) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetTintColor(enabled, color); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, enabled, color]() { pThisHolder->RealSetTintColor(enabled, color); }); } } void SkeletalMeshRenderProxy::RealSetTintColor(bool enabled, uint32 color /*= 0*/) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_tintEnabled = enabled; m_tintColor = (enabled) ? color : 0xFFFFFFFF; } void SkeletalMeshRenderProxy::SetVisibility(bool visible) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetVisibility(visible); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, visible]() { pThisHolder->RealSetVisibility(visible); }); } } void SkeletalMeshRenderProxy::RealSetVisibility(bool visible) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_visibility = visible; } void SkeletalMeshRenderProxy::SetShadowFlags(uint32 shadowFlags) { if (!IsInWorld()) { // not yet in world so we can do it directly RealSetShadowFlags(shadowFlags); } else { ReferenceCountedHolder<SkeletalMeshRenderProxy> pThisHolder(this); QUEUE_RENDERER_LAMBDA_COMMAND([pThisHolder, shadowFlags]() { pThisHolder->RealSetShadowFlags(shadowFlags); }); } } void SkeletalMeshRenderProxy::RealSetShadowFlags(uint32 shadowFlags) { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); m_shadowFlags = shadowFlags; } void SkeletalMeshRenderProxy::QueueForRender(const Camera *pCamera, RenderQueue *pRenderQueue) const { if (!m_visibility) return; // check gpu resources if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; // skinning settings if (m_useGPUSkinning != CVars::r_gpu_skinning.GetBool()) { m_useGPUSkinning = CVars::r_gpu_skinning.GetBool(); ReleaseDeviceResources(); if (!CreateDeviceResources()) return; } // Store the requested render passes. uint32 wantedRenderPasses = RENDER_PASSES_DEFAULT; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_CAST_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOW_MAP; if (!(m_shadowFlags & ENTITY_SHADOW_FLAG_RECEIVE_DYNAMIC_SHADOWS)) wantedRenderPasses &= ~RENDER_PASS_SHADOWED_LIGHTING; // if (hasLightMaps && (availableRenderPassMask & RENDER_PASS_LIGHTMAP)) // wantedRenderPasses = (wantedRenderPasses & ~(RENDER_PASS_STATIC_OPAQUE_LIGHTING | RENDER_PASS_STATIC_TRANSPARENT_LIGHTING)) | RENDER_PASS_LIGHTMAP; if (m_tintEnabled) wantedRenderPasses |= RENDER_PASS_TINT; // Calculate view distance float viewDistance = pCamera->CalculateDepthToPoint(GetBoundingSphere().GetCenter()); // Draw this LOD. for (uint32 i = 0; i < m_pSkeletalMesh->GetBatchCount(); i++) { // Get batch info. const SkeletalMesh::Batch *pBatch = m_pSkeletalMesh->GetBatch(i); //if (pBatch->WeightCount != 1) //continue; // Get material. const Material *pMaterial = m_materials[pBatch->MaterialIndex]; // Determine render passes. There isn't really any passes that a static mesh can't handle, so we only remove the material ones. uint32 renderPassMask = pMaterial->GetShader()->SelectRenderPassMask(wantedRenderPasses); // Add to render queue if we have any render passes. if (renderPassMask != 0) { // vertex factory flags for weight count uint32 vertexFactoryFlags = m_pSkeletalMesh->GetBaseVertexFactoryFlags(); if (m_useGPUSkinning) { vertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING; switch (pBatch->WeightCount) { case 4: vertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_3_ENABLED; case 3: vertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_2_ENABLED; case 2: vertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_1_ENABLED; case 1: vertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_WEIGHT_0_ENABLED; } } RENDER_QUEUE_RENDERABLE_ENTRY queueEntry; queueEntry.RenderPassMask = renderPassMask; queueEntry.pRenderProxy = this; queueEntry.BoundingBox = GetBoundingBox(); queueEntry.pVertexFactoryTypeInfo = VERTEX_FACTORY_TYPE_INFO(SkeletalMeshVertexFactory); queueEntry.VertexFactoryFlags = vertexFactoryFlags; queueEntry.pMaterial = pMaterial; queueEntry.ViewDistance = viewDistance; queueEntry.UserData[0] = i; queueEntry.TintColor = m_tintColor; queueEntry.Layer = pMaterial->GetShader()->SelectRenderQueueLayer(); pRenderQueue->AddRenderable(&queueEntry); } } if (pRenderQueue->IsAcceptingDebugObjects()) { if (CVars::r_show_skeletons.GetBool()) { pRenderQueue->AddDebugInfoObject(this); } } } void SkeletalMeshRenderProxy::SetupForDraw(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList, ShaderProgram *pShaderProgram) const { const SkeletalMesh::Batch *pBatch = m_pSkeletalMesh->GetBatch(pQueueEntry->UserData[0]); SkeletalMeshVertexFactory::SetBoneMatrices(pCommandList, pShaderProgram, 0, pBatch->BoneRefCount, &m_boneTransforms[pBatch->BaseBoneRef]); pCommandList->GetConstants()->SetLocalToWorldMatrix(m_localToWorldMatrix, true); pCommandList->SetDrawTopology(DRAW_TOPOLOGY_TRIANGLE_LIST); m_VertexBuffers.BindBuffers(pCommandList); pCommandList->SetIndexBuffer(m_pSkeletalMesh->GetIndexBuffer(), GPU_INDEX_FORMAT_UINT16, 0); } void SkeletalMeshRenderProxy::DrawQueueEntry(const Camera *pCamera, const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry, GPUCommandList *pCommandList) const { const SkeletalMesh::Batch *pBatch = m_pSkeletalMesh->GetBatch(pQueueEntry->UserData[0]); pCommandList->DrawIndexed(pBatch->FirstIndex, pBatch->IndexCount, pBatch->BaseVertex); } bool SkeletalMeshRenderProxy::CreateDeviceResources() const { uint32 i; if (m_bGPUResourcesCreated) return true; if (!m_pSkeletalMesh->CreateGPUResources()) return false; for (i = 0; i < m_materials.GetSize(); i++) { if (!m_materials[i]->CreateDeviceResources()) return false; } if (CVars::r_gpu_skinning.GetBool()) { if (m_VertexBuffers.GetBuffer(0) == nullptr) SkeletalMeshVertexFactory::ShareVerticesBuffer(&m_VertexBuffers, m_pSkeletalMesh->GetVertexBuffers()); } else { if (m_cpuSkinnedVertices.GetSize() != m_pSkeletalMesh->GetVertexCount()) { m_cpuSkinnedVertices.Resize(m_pSkeletalMesh->GetVertexCount()); m_cpuSkinnedVertices.ZeroContents(); } if (m_pCPUSkinningVertexBuffer == nullptr) { uint32 vertexSize = SkeletalMeshVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_pSkeletalMesh->GetBaseVertexFactoryFlags()); GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_VERTEX_BUFFER | GPU_BUFFER_FLAG_MAPPABLE, vertexSize * m_pSkeletalMesh->GetVertexCount()); if ((m_pCPUSkinningVertexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, nullptr)) == nullptr) return false; m_VertexBuffers.SetBuffer(0, m_pCPUSkinningVertexBuffer, 0, vertexSize); } } m_bGPUResourcesCreated = true; return true; } void SkeletalMeshRenderProxy::ReleaseDeviceResources() const { m_VertexBuffers.Clear(); SAFE_RELEASE(m_pCPUSkinningVertexBuffer); m_cpuSkinnedVertices.Obliterate(); m_bGPUResourcesCreated = false; } void SkeletalMeshRenderProxy::InitializeBoneTransformArray() { const Skeleton *pSkeleton = m_pSkeletalMesh->GetSkeleton(); DebugAssert(pSkeleton->GetBoneCount() > 0 && m_pSkeletalMesh->GetBoneRefCount() > 0); m_boneTransforms.Resize(m_pSkeletalMesh->GetBoneRefCount()); for (uint32 i = 0; i < m_boneTransforms.GetSize(); i++) { const uint32 meshBoneIndex = (uint32)m_pSkeletalMesh->GetBoneRef(i); const SkeletalMesh::Bone *pMeshBone = m_pSkeletalMesh->GetBone(meshBoneIndex); // calculate base frame transform //m_boneTransforms[i] = pSkeleton->GetBoneByIndex(pMeshBone->SkeletonBoneIndex)->GetAbsoluteBaseFrameTransform().GetTransformMatrix3x4() * pMeshBone->LocalToBoneTransform.GetTransformMatrix3x4(); m_boneTransforms[i] = Transform::ConcatenateTransforms(pMeshBone->LocalToBoneTransform, pSkeleton->GetBoneByIndex(pMeshBone->SkeletonBoneIndex)->GetAbsoluteBaseFrameTransform()).GetTransformMatrix3x4(); } } void SkeletalMeshRenderProxy::SetBoneTransforms(uint32 firstTransform, uint32 transformCount, const float3x4 *pTransforms) { for (uint32 boneRefIndex = 0; boneRefIndex < m_boneTransforms.GetSize(); boneRefIndex++) { const uint32 meshBoneIndex = (uint32)m_pSkeletalMesh->GetBoneRef(boneRefIndex); const SkeletalMesh::Bone *pMeshBone = m_pSkeletalMesh->GetBone(meshBoneIndex); if (meshBoneIndex >= firstTransform && meshBoneIndex < (firstTransform + transformCount)) { uint32 transformArrayIndex = meshBoneIndex - firstTransform; m_boneTransforms[boneRefIndex] = Transform::ConcatenateTransforms(pMeshBone->LocalToBoneTransform, Transform(pTransforms[transformArrayIndex])).GetTransformMatrix3x4(); //m_boneTransforms[boneRefIndex] = pTransforms[transformArrayIndex]; } } if (!m_useGPUSkinning) { if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; TransformVerticesOnCPU(); } } void SkeletalMeshRenderProxy::SetBoneTransforms(uint32 firstTransform, uint32 transformCount, const Transform *pTransforms) { for (uint32 boneRefIndex = 0; boneRefIndex < m_boneTransforms.GetSize(); boneRefIndex++) { const uint32 meshBoneIndex = (uint32)m_pSkeletalMesh->GetBoneRef(boneRefIndex); const SkeletalMesh::Bone *pMeshBone = m_pSkeletalMesh->GetBone(meshBoneIndex); if (meshBoneIndex >= firstTransform && meshBoneIndex < (firstTransform + transformCount)) { uint32 transformArrayIndex = meshBoneIndex - firstTransform; m_boneTransforms[boneRefIndex] = Transform::ConcatenateTransforms(pMeshBone->LocalToBoneTransform, pTransforms[transformArrayIndex]).GetTransformMatrix3x4(); //m_boneTransforms[boneRefIndex] = pTransforms[transformArrayIndex].GetTransformMatrix3x4(); } } if (!m_useGPUSkinning) { if (!m_bGPUResourcesCreated && !CreateDeviceResources()) return; TransformVerticesOnCPU(); } } void SkeletalMeshRenderProxy::ResetToBaseFrameTransform() { DebugAssert(!IsInWorld() || Renderer::IsOnRenderThread()); const Skeleton *pSkeleton = m_pSkeletalMesh->GetSkeleton(); DebugAssert(pSkeleton->GetBoneCount() > 0 && m_pSkeletalMesh->GetBoneRefCount() > 0); for (uint32 i = 0; i < m_boneTransforms.GetSize(); i++) { const uint32 meshBoneIndex = (uint32)m_pSkeletalMesh->GetBoneRef(i); const SkeletalMesh::Bone *pMeshBone = m_pSkeletalMesh->GetBone(meshBoneIndex); // calculate base frame transform //m_boneTransforms[i] = pSkeleton->GetBoneByIndex(pMeshBone->SkeletonBoneIndex)->GetAbsoluteBaseFrameTransform().GetTransformMatrix3x4() * pMeshBone->LocalToBoneTransform.GetTransformMatrix3x4(); m_boneTransforms[i] = Transform::ConcatenateTransforms(pMeshBone->LocalToBoneTransform, pSkeleton->GetBoneByIndex(pMeshBone->SkeletonBoneIndex)->GetAbsoluteBaseFrameTransform()).GetTransformMatrix3x4(); } } void SkeletalMeshRenderProxy::DrawDebugInfo(const Camera *pCamera, GPUCommandList *pCommandList, MiniGUIContext *pGUIContext) const { if (CVars::r_show_skeletons.GetBool()) { const Skeleton *pSkeleton = m_pSkeletalMesh->GetSkeleton(); // for each bone for (uint32 i = 0; i < pSkeleton->GetBoneCount(); i++) { const Skeleton::Bone *pParentBone = pSkeleton->GetBoneByIndex(i); const float3x4 &parentBoneTransform = m_boneTransforms[i]; float3 lineSource(m_transform.TransformPoint(parentBoneTransform.TransformPoint(float3::Zero))); // for each bone that has this bone as a parent for (uint32 j = 0; j < pSkeleton->GetBoneCount(); j++) { const Skeleton::Bone *pChildBone = pSkeleton->GetBoneByIndex(j); if (pChildBone->GetParentBone() == pParentBone) { const float3x4 &childBoneTransform = m_boneTransforms[j]; // draw a line from source to destination float3 lineDestination(m_transform.TransformPoint(childBoneTransform.TransformPoint(float3::Zero))); pGUIContext->Draw3DLineWidth(lineSource, lineDestination, MAKE_COLOR_R8G8B8A8_UNORM(240, 240, 240, 255), 2.0f); // and the axes float3 axisOrigin(lineDestination); float3 xAxisPos(m_transform.TransformPoint(childBoneTransform.TransformPoint(float3::UnitX * 0.5f))); float3 yAxisPos(m_transform.TransformPoint(childBoneTransform.TransformPoint(float3::UnitY * 0.5f))); float3 zAxisPos(m_transform.TransformPoint(childBoneTransform.TransformPoint(float3::UnitZ * 0.5f))); pGUIContext->Draw3DLineWidth(axisOrigin, xAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(255, 0, 0, 255), 2.0f); pGUIContext->Draw3DLineWidth(axisOrigin, yAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(0, 255, 0, 255), 2.0f); pGUIContext->Draw3DLineWidth(axisOrigin, zAxisPos, MAKE_COLOR_R8G8B8A8_UNORM(0, 0, 255, 255), 2.0f); } } } } } void SkeletalMeshRenderProxy::TransformVerticesOnCPU() { DebugAssert(m_cpuSkinnedVertices.GetSize() == m_pSkeletalMesh->GetVertexCount()); for (uint32 batchIndex = 0; batchIndex < m_pSkeletalMesh->GetBatchCount(); batchIndex++) { const SkeletalMesh::Batch *pBatch = m_pSkeletalMesh->GetBatch(batchIndex); const SkeletalMeshVertexFactory::Vertex *pSourceVertex = m_pSkeletalMesh->GetVertex(pBatch->BaseVertex); SkeletalMeshVertexFactory::Vertex *pDestinationVertex = &m_cpuSkinnedVertices[pBatch->BaseVertex]; const uint32 weightCount = pBatch->WeightCount; const uint32 baseBoneRef = pBatch->BaseBoneRef; const uint32 vertexCount = pBatch->VertexCount; DebugAssert(pBatch->WeightCount > 0); for (uint32 vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++, pSourceVertex++, pDestinationVertex++) { // should always have at least one bone const float3x4 *pBoneTransform = &m_boneTransforms[baseBoneRef + (uint32)pSourceVertex->BoneIndices[0]]; float boneWeight = pSourceVertex->BoneWeights[0]; // transform the attributes pDestinationVertex->Position = pBoneTransform->TransformPoint(pSourceVertex->Position) * boneWeight; pDestinationVertex->TangentX = pBoneTransform->TransformNormal(pSourceVertex->TangentX) * boneWeight; pDestinationVertex->TangentY = pBoneTransform->TransformNormal(pSourceVertex->TangentY) * boneWeight; pDestinationVertex->TangentZ = pBoneTransform->TransformNormal(pSourceVertex->TangentZ) * boneWeight; // and any remaining bones switch (weightCount) { case 4: { pBoneTransform = &m_boneTransforms[baseBoneRef + (uint32)pSourceVertex->BoneIndices[3]]; boneWeight = pSourceVertex->BoneWeights[3]; pDestinationVertex->Position += pBoneTransform->TransformPoint(pSourceVertex->Position) * boneWeight; pDestinationVertex->TangentX += pBoneTransform->TransformNormal(pSourceVertex->TangentX) * boneWeight; pDestinationVertex->TangentY += pBoneTransform->TransformNormal(pSourceVertex->TangentY) * boneWeight; pDestinationVertex->TangentZ += pBoneTransform->TransformNormal(pSourceVertex->TangentZ) * boneWeight; } case 3: { pBoneTransform = &m_boneTransforms[baseBoneRef + (uint32)pSourceVertex->BoneIndices[2]]; boneWeight = pSourceVertex->BoneWeights[2]; pDestinationVertex->Position += pBoneTransform->TransformPoint(pSourceVertex->Position) * boneWeight; pDestinationVertex->TangentX += pBoneTransform->TransformNormal(pSourceVertex->TangentX) * boneWeight; pDestinationVertex->TangentY += pBoneTransform->TransformNormal(pSourceVertex->TangentY) * boneWeight; pDestinationVertex->TangentZ += pBoneTransform->TransformNormal(pSourceVertex->TangentZ) * boneWeight; } case 2: { pBoneTransform = &m_boneTransforms[baseBoneRef + (uint32)pSourceVertex->BoneIndices[1]]; boneWeight = pSourceVertex->BoneWeights[1]; pDestinationVertex->Position += pBoneTransform->TransformPoint(pSourceVertex->Position) * boneWeight; pDestinationVertex->TangentX += pBoneTransform->TransformNormal(pSourceVertex->TangentX) * boneWeight; pDestinationVertex->TangentY += pBoneTransform->TransformNormal(pSourceVertex->TangentY) * boneWeight; pDestinationVertex->TangentZ += pBoneTransform->TransformNormal(pSourceVertex->TangentZ) * boneWeight; } } // normalize tangents pDestinationVertex->TangentX.SafeNormalizeInPlace(); pDestinationVertex->TangentY.SafeNormalizeInPlace(); pDestinationVertex->TangentZ.SafeNormalizeInPlace(); // non-changing attributes pDestinationVertex->TexCoord = pSourceVertex->TexCoord; pDestinationVertex->Color = pSourceVertex->Color; } } // update the buffer void *pMappedBufferPointer; if (g_pRenderer->GetGPUContext()->MapBuffer(m_pCPUSkinningVertexBuffer, GPU_MAP_TYPE_WRITE_DISCARD, &pMappedBufferPointer)) { uint32 vertexSize = SkeletalMeshVertexFactory::GetVertexSize(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_pSkeletalMesh->GetBaseVertexFactoryFlags()); SkeletalMeshVertexFactory::FillVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_pSkeletalMesh->GetBaseVertexFactoryFlags(), m_cpuSkinnedVertices.GetBasePointer(), m_cpuSkinnedVertices.GetSize(), pMappedBufferPointer, vertexSize * m_pSkeletalMesh->GetVertexCount()); g_pRenderer->GetGPUContext()->Unmapbuffer(m_pCPUSkinningVertexBuffer, pMappedBufferPointer); } } <file_sep>/Editor/Source/Editor/EditorResourcePreviewWidget.h #pragma once #include "Editor/Common.h" #include "Editor/EditorRendererSwapChainWidget.h" #include "Editor/ui_EditorResourcePreviewWidget.h" #include "Engine/ArcBallCamera.h" #include "Renderer/WorldRenderer.h" #include "Renderer/MiniGUIContext.h" class Resource; class ResourceTypeInfo; class Material; class MaterialShader; class Texture; class StaticMesh; class BlockMesh; class RenderWorld; class RenderProxy; class EditorLightSimulator; class EditorResourcePreviewWidget : public QWidget { Q_OBJECT enum PREVIEW_TYPE { PREVIEW_TYPE_NONE, PREVIEW_TYPE_MATERIAL, PREVIEW_TYPE_MATERIALSHADER, PREVIEW_TYPE_TEXTURE2D, PREVIEW_TYPE_STATICMESH, PREVIEW_TYPE_STATICBLOCKMESH, }; enum STATE { STATE_NONE, STATE_ROTATE_CAMERA, STATE_COUNT, }; public: EditorResourcePreviewWidget(QWidget *pParent = NULL); ~EditorResourcePreviewWidget(); void ClearPreview(); bool SetPreviewResource(const Resource *pResource); bool SetPreviewResourceByName(const ResourceTypeInfo *pResourceTypeInfo, const char *resourceName); void SetPreviewMaterial(const Material *pMaterial); void SetPreviewMaterialShader(const MaterialShader *pMaterialShader); void SetPreviewTexture(const Texture *pTexture); void SetPreviewStaticMesh(const StaticMesh *pStaticMesh); void SetPreviewStaticBlockMesh(const BlockMesh *pStaticBlockMesh); void SetPreviewErrorMessage(const char *message); // render options const EDITOR_RENDER_MODE GetRenderMode() const { return m_renderMode; } void SetRenderMode(EDITOR_RENDER_MODE renderMode); void SetViewportFlag(uint32 flag); void ClearViewportFlag(uint32 flag); // gpu resources bool CreateGPUResources(); void ReleaseGPUResources(); // flag for redraw void FlagForRedraw() { m_bRedrawPending = true; } private: void SetupStaticMesh(const StaticMesh *pStaticMeshToRender, const Material *pMaterialOverride); void UpdateZoomScale(); void ResetCamera(); void Draw(); void DrawPreview(); void DrawPreviewOverlays(); // ui Ui_EditorResourcePreviewWidget *m_ui; // render settings EDITOR_RENDER_MODE m_renderMode; uint32 m_viewportFlags; // preview object PREVIEW_TYPE m_ePreviewType; union { const Resource *asResource; const Material *asMaterial; const MaterialShader *asMaterialShader; const Texture *asTexture; const StaticMesh *asStaticMesh; const BlockMesh *asStaticBlockMesh; } m_Resource; // redraw pending? bool m_bRedrawPending; // renderer stuff uint32 m_renderTargetWidth, m_renderTargetHeight; bool m_bHardwareResourcesCreated; // renderer objects GPUOutputBuffer *m_pSwapChain; WorldRenderer *m_pWorldRenderer; WorldRenderer::ViewParameters m_viewParameters; MiniGUIContext m_guiContext; // cameras ArcBallCamera m_ArcBallCamera; float m_fZoomScale; const Font *m_pOverlayTextFont; String m_errorMessage; RenderWorld *m_pRenderWorld; RenderProxy *m_pResourceRenderProxy; EditorLightSimulator *m_pLightSimulator; // --- key/button states --- STATE m_eCurrentState; uint32 m_iStateData; int2 m_LastMousePosition; //=================================================================================================================================================================== // UI Event Handlers //=================================================================================================================================================================== void ConnectUIEvents(); private Q_SLOTS: void OnFocusGained(); void OnFocusLost(); void OnToolbarViewWireframeClicked(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_WIREFRAME); } void OnToolbarViewUnlitClicked(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_FULLBRIGHT); } void OnToolbarViewLitClicked(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_LIT); } void OnToolbarViewLightingOnlyClicked(bool checked) { SetRenderMode(EDITOR_RENDER_MODE_LIGHTING_ONLY); } void OnToolbarFlagShadowsClicked(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS); } void OnToolbarFlagWireframeOverlayClicked(bool checked) { (checked) ? SetViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY) : ClearViewportFlag(EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY); } void OnSwapChainWidgetResized(); void OnSwapChainWidgetPaint(); void OnSwapChainWidgetKeyboardEvent(const QKeyEvent *pKeyboardEvent); void OnSwapChainWidgetMouseEvent(const QMouseEvent *pMouseEvent); void OnSwapChainWidgetWheelEvent(const QWheelEvent *pWheelEvent); void OnFrameExecutionTriggered(float timeSinceLastFrame); };<file_sep>/Engine/Source/ResourceCompiler/CollisionShapeGenerator.cpp #include "ResourceCompiler/PrecompiledHeader.h" #include "ResourceCompiler/CollisionShapeGenerator.h" #include "YBaseLib/BinaryWriteBuffer.h" #include "YBaseLib/XMLReader.h" #include "YBaseLib/XMLWriter.h" Log_SetChannel(CollisionShapeGenerator); // Import bullet headers #include "Engine/Physics/BulletHeaders.h" //#include "hacdCircularList.h" //#include "hacdVector.h" //#include "hacdICHull.h" //#include "hacdGraph.h" //#include "hacdHACD.h" namespace Physics { CollisionShapeGenerator::CollisionShapeGenerator(COLLISION_SHAPE_TYPE type /* = COLLISION_SHAPE_TYPE_TRIANGLE_MESH */) : m_type(type), m_boxCenter(float3::Zero), m_boxHalfExtents(float3::Zero), m_sphereCenter(float3::Zero), m_sphereRadius(0.0f) { } CollisionShapeGenerator::~CollisionShapeGenerator() { } void CollisionShapeGenerator::SetType(COLLISION_SHAPE_TYPE type) { m_type = type; m_boxCenter = float3::Zero; m_boxHalfExtents = float3::Zero; m_sphereCenter = float3::Zero; m_sphereRadius = 0.0f; m_triangleMeshTriangles.Clear(); m_convexHullVertices.Clear(); } void CollisionShapeGenerator::AddTriangle(const float3 &v0, const float3 &v1, const float3 &v2) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_TRIANGLE_MESH); TriangleMeshTriangle triangle; triangle.VertexPositions[0] = v0; triangle.VertexPositions[1] = v1; triangle.VertexPositions[2] = v2; m_triangleMeshTriangles.Add(triangle); } void CollisionShapeGenerator::AddConvexHullVertex(const float3 &v) { DebugAssert(m_type == COLLISION_SHAPE_TYPE_CONVEX_HULL); m_convexHullVertices.Add(v); } void CollisionShapeGenerator::ConvertToBox() { Assert(m_type == COLLISION_SHAPE_TYPE_TRIANGLE_MESH); m_type = COLLISION_SHAPE_TYPE_BOX; if (m_triangleMeshTriangles.GetSize() == 0) { m_boxHalfExtents.SetZero(); } else { // take the bounding box of all the vertices in the triangle mesh AABox boundingBox(m_triangleMeshTriangles[0].VertexPositions[0]); for (uint32 i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { for (uint32 j = 0; j < 3; j++) { boundingBox.Merge(m_triangleMeshTriangles[i].VertexPositions[j]); } } m_triangleMeshTriangles.Obliterate(); // get center and extents m_boxHalfExtents = boundingBox.GetExtents() * 0.5f; } } void CollisionShapeGenerator::ConvertToSphere() { Assert(m_type == COLLISION_SHAPE_TYPE_TRIANGLE_MESH); m_type = COLLISION_SHAPE_TYPE_SPHERE; if (m_triangleMeshTriangles.GetSize() == 0) { m_sphereRadius = Math::Epsilon<float>(); } else { // take the bounding sphere of all the vertices in the triangle mesh AABox boundingBox(m_triangleMeshTriangles[0].VertexPositions[0]); for (uint32 i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { for (uint32 j = 0; j < 3; j++) { boundingBox.Merge(m_triangleMeshTriangles[i].VertexPositions[j]); } } Sphere boundingSphere(boundingBox.GetCenter(), 0.0f); for (uint32 i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { for (uint32 j = 0; j < 3; j++) { boundingSphere.Merge(m_triangleMeshTriangles[i].VertexPositions[j]); } } m_triangleMeshTriangles.Obliterate(); // get center and extents m_sphereRadius = boundingSphere.GetRadius(); } } void CollisionShapeGenerator::ConvertToConvexHull() { Assert(m_type == COLLISION_SHAPE_TYPE_TRIANGLE_MESH); Panic("unimplemented"); } bool CollisionShapeGenerator::LoadFromXML(XMLReader &xmlReader) { // process xml nodes for (;;) { if (!xmlReader.NextToken()) break; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 shapeSelection = xmlReader.Select("box|sphere|triangle-mesh|convex-hull"); if (shapeSelection < 0) return false; switch (shapeSelection) { // box case 0: { SetType(COLLISION_SHAPE_TYPE_BOX); m_boxCenter = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("center", "0 0 0")); m_boxHalfExtents = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("half-extents", "0 0 0")); if (!xmlReader.SkipCurrentElement()) return false; } break; // sphere case 1: { SetType(COLLISION_SHAPE_TYPE_SPHERE); m_sphereCenter = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("center", "0 0 0")); m_sphereRadius = StringConverter::StringToFloat(xmlReader.FetchAttributeDefault("radius", "0")); if (!xmlReader.SkipCurrentElement()) return false; } break; // triangle-mesh case 2: { SetType(COLLISION_SHAPE_TYPE_TRIANGLE_MESH); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 triangleMeshSelection = xmlReader.Select("triangles"); if (triangleMeshSelection < 0) return false; switch (triangleMeshSelection) { // triangles case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 trianglesSelection = xmlReader.Select("triangle"); if (trianglesSelection < 0) return false; switch (triangleMeshSelection) { // triangle case 0: { TriangleMeshTriangle triangle; triangle.VertexPositions[0] = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("vertex1", "0 0 0")); triangle.VertexPositions[1] = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("vertex2", "0 0 0")); triangle.VertexPositions[2] = StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("vertex3", "0 0 0")); m_triangleMeshTriangles.Add(triangle); if (!xmlReader.SkipCurrentElement()) return false; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "triangles") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "triangle-mesh") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } } break; // convex-hull case 3: { SetType(COLLISION_SHAPE_TYPE_CONVEX_HULL); if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 convexHullSelection = xmlReader.Select("vertices"); if (convexHullSelection < 0) return false; switch (convexHullSelection) { // triangles case 0: { if (!xmlReader.IsEmptyElement()) { for (;;) { if (!xmlReader.NextToken()) return false; if (xmlReader.GetTokenType() == XMLREADER_TOKEN_ELEMENT) { int32 verticesSelection = xmlReader.Select("vertex"); if (verticesSelection < 0) return false; switch (convexHullSelection) { // triangle case 0: { m_convexHullVertices.Add(StringConverter::StringToFloat3(xmlReader.FetchAttributeDefault("position", "0 0 0"))); if (!xmlReader.SkipCurrentElement()) return false; } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "vertices") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { DebugAssert(Y_stricmp(xmlReader.GetNodeName(), "convex-hull") == 0); break; } else { xmlReader.PrintError("parse error"); return false; } } } } break; } } else if (xmlReader.GetTokenType() == XMLREADER_TOKEN_END_ELEMENT) { break; } else { xmlReader.PrintError("parse error"); return false; } } return true; } bool CollisionShapeGenerator::SaveToXML(XMLWriter &xmlWriter) const { uint32 i; SmallString tempString; switch (m_type) { case COLLISION_SHAPE_TYPE_BOX: { xmlWriter.StartElement("box"); { StringConverter::Float3ToString(tempString, m_boxCenter); xmlWriter.WriteAttribute("center", tempString); StringConverter::Float3ToString(tempString, m_boxHalfExtents); xmlWriter.WriteAttribute("half-extents", tempString); } xmlWriter.EndElement(); } break; case COLLISION_SHAPE_TYPE_SPHERE: { xmlWriter.StartElement("sphere"); { StringConverter::Float3ToString(tempString, m_sphereCenter); xmlWriter.WriteAttribute("center", tempString); StringConverter::FloatToString(tempString, m_sphereRadius); xmlWriter.WriteAttribute("radius", tempString); } xmlWriter.EndElement(); } break; case COLLISION_SHAPE_TYPE_TRIANGLE_MESH: { xmlWriter.StartElement("triangle-mesh"); { xmlWriter.StartElement("triangles"); { for (i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { xmlWriter.StartElement("triangle"); { const TriangleMeshTriangle &triangle = m_triangleMeshTriangles[i]; StringConverter::Float3ToString(tempString, triangle.VertexPositions[0]); xmlWriter.WriteAttribute("vertex1", tempString); StringConverter::Float3ToString(tempString, triangle.VertexPositions[1]); xmlWriter.WriteAttribute("vertex2", tempString); StringConverter::Float3ToString(tempString, triangle.VertexPositions[2]); xmlWriter.WriteAttribute("vertex3", tempString); } xmlWriter.EndElement(); } } xmlWriter.EndElement(); } xmlWriter.EndElement(); } break; case COLLISION_SHAPE_TYPE_CONVEX_HULL: { xmlWriter.StartElement("convex-hull"); { xmlWriter.StartElement("vertices"); { for (i = 0; i < m_convexHullVertices.GetSize(); i++) { xmlWriter.StartElement("vertex"); { StringConverter::Float3ToString(tempString, m_convexHullVertices[i]); xmlWriter.WriteAttribute("position", tempString); } xmlWriter.EndElement(); } } xmlWriter.EndElement(); } xmlWriter.EndElement(); } break; default: UnreachableCode(); break; } return (!xmlWriter.InErrorState()); } bool CollisionShapeGenerator::Compile(BinaryBlob **ppOutputBlob) const { switch (m_type) { case COLLISION_SHAPE_TYPE_BOX: { BinaryWriteBuffer binaryWriter; binaryWriter << uint8(COLLISION_SHAPE_TYPE_BOX); binaryWriter << m_boxCenter; binaryWriter << m_boxHalfExtents; *ppOutputBlob = BinaryBlob::CreateFromPointer(binaryWriter.GetBufferPointer(), binaryWriter.GetBufferSize()); return true; } break; case COLLISION_SHAPE_TYPE_SPHERE: { BinaryWriteBuffer binaryWriter; binaryWriter << uint8(COLLISION_SHAPE_TYPE_SPHERE); binaryWriter << m_sphereCenter; binaryWriter << m_sphereRadius; *ppOutputBlob = BinaryBlob::CreateFromPointer(binaryWriter.GetBufferPointer(), binaryWriter.GetBufferSize()); return true; } break; case COLLISION_SHAPE_TYPE_TRIANGLE_MESH: { // create triangle mesh btTriangleMesh *pBulletTriangleMesh = new btTriangleMesh(); #if 0 // pull in the triangles for (uint32 i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { const TriangleMeshTriangle &triangle = m_triangleMeshTriangles[i]; pBulletTriangleMesh->addTriangle(BulletHelpers::Float3ToBulletVector(triangle.VertexPositions[0]), BulletHelpers::Float3ToBulletVector(triangle.VertexPositions[1]), BulletHelpers::Float3ToBulletVector(triangle.VertexPositions[2]), true); } #elif 1 // extract vertices float3 *pVertices = new float3[m_triangleMeshTriangles.GetSize() * 3]; HashTable<float3, uint32> *pVerticesHashTable = new HashTable<float3, uint32>(); uint32 *pIndices = new uint32[m_triangleMeshTriangles.GetSize() * 3]; uint32 nVertices = 0; uint32 nIndices = 0; for (uint32 i = 0; i < m_triangleMeshTriangles.GetSize(); i++) { const TriangleMeshTriangle &triangle = m_triangleMeshTriangles[i]; for (uint32 j = 0; j < 3; j++) { const float3 &vertex = triangle.VertexPositions[j]; HashTable<float3, uint32>::Member *pMember = pVerticesHashTable->Find(vertex); if (pMember != NULL) { DebugAssert(pMember->Key == vertex && pVertices[pMember->Value] == vertex); } else { pVertices[nVertices] = vertex; pMember = pVerticesHashTable->Insert(vertex, nVertices); nVertices++; } pIndices[nIndices++] = pMember->Value; } } // add to bullet shape for (uint32 i = 0; i < nVertices; i++) pBulletTriangleMesh->findOrAddVertex(Float3ToBulletVector(pVertices[i]), false); for (uint32 i = 0; i < nIndices; i++) pBulletTriangleMesh->addIndex(pIndices[i]); pBulletTriangleMesh->getIndexedMeshArray()[0].m_numTriangles = nIndices / 3; // clean temp memory delete[] pIndices; delete pVerticesHashTable; delete[] pVertices; #endif // create the shape btBvhTriangleMeshShape *pShape = new btBvhTriangleMeshShape(pBulletTriangleMesh, true, true); // serialize it btDefaultSerializer serializer; serializer.startSerialization(); pShape->serializeSingleShape(&serializer); serializer.finishSerialization(); // create the blob BinaryBlob *pOutputBlob = BinaryBlob::Allocate(sizeof(uint8) + serializer.getCurrentBufferSize()); *(uint8 *)(pOutputBlob->GetDataPointer()) = COLLISION_SHAPE_TYPE_TRIANGLE_MESH; Y_memcpy(reinterpret_cast<byte *>(pOutputBlob->GetDataPointer()) + sizeof(uint8), serializer.getBufferPointer(), serializer.getCurrentBufferSize()); *ppOutputBlob = pOutputBlob; // clean up delete pShape; delete pBulletTriangleMesh; return true; } break; case COLLISION_SHAPE_TYPE_CONVEX_HULL: { //*ppOutputBlob = BinaryBlob::CreateFromPointer() *ppOutputBlob = NULL; //return true; return false; } break; default: UnreachableCode(); return false; } } void CollisionShapeGenerator::Copy(const CollisionShapeGenerator *pGenerator) { // just copy all vars, meh. m_type = pGenerator->m_type; m_boxCenter = pGenerator->m_boxCenter; m_boxHalfExtents = pGenerator->m_boxHalfExtents; m_sphereCenter = pGenerator->m_sphereCenter; m_sphereRadius = pGenerator->m_sphereRadius; m_triangleMeshTriangles.Assign(pGenerator->m_triangleMeshTriangles); m_convexHullVertices.Assign(pGenerator->m_convexHullVertices); } bool CollisionShapeGenerator::ApplyTransform(const Transform &transform) { switch (m_type) { case COLLISION_SHAPE_TYPE_BOX: { AABox tempBox(m_boxCenter - m_boxHalfExtents, m_boxCenter + m_boxHalfExtents); AABox transformedBox(transform.TransformBoundingBox(tempBox)); m_boxCenter = transformedBox.GetCenter(); m_boxHalfExtents = transformedBox.GetExtents() / 2.0f; return true; } case COLLISION_SHAPE_TYPE_SPHERE: { Sphere tempSphere(m_sphereCenter, m_sphereRadius); Sphere transformedSphere(transform.TransformBoundingSphere(tempSphere)); m_sphereCenter = transformedSphere.GetCenter(); m_sphereRadius = transformedSphere.GetRadius(); return true; } case COLLISION_SHAPE_TYPE_TRIANGLE_MESH: { for (TriangleMeshTriangle &tri : m_triangleMeshTriangles) { tri.VertexPositions[0] = transform.TransformPoint(tri.VertexPositions[0]); tri.VertexPositions[1] = transform.TransformPoint(tri.VertexPositions[1]); tri.VertexPositions[2] = transform.TransformPoint(tri.VertexPositions[2]); } return true; } case COLLISION_SHAPE_TYPE_CONVEX_HULL: { return false; } default: UnreachableCode(); return false; } } bool CollisionShapeGenerator::ApplyTransform(const float4x4 &transformMatrix) { switch (m_type) { case COLLISION_SHAPE_TYPE_BOX: { AABox tempBox(m_boxCenter - m_boxHalfExtents, m_boxCenter + m_boxHalfExtents); AABox transformedBox(tempBox.GetTransformed(transformMatrix)); m_boxCenter = transformedBox.GetCenter(); m_boxHalfExtents = transformedBox.GetExtents() / 2.0f; return true; } case COLLISION_SHAPE_TYPE_SPHERE: { Sphere tempSphere(m_sphereCenter, m_sphereRadius); Sphere transformedSphere(tempSphere.GetTransformed(transformMatrix)); m_sphereCenter = transformedSphere.GetCenter(); m_sphereRadius = transformedSphere.GetRadius(); return true; } case COLLISION_SHAPE_TYPE_TRIANGLE_MESH: { for (TriangleMeshTriangle &tri : m_triangleMeshTriangles) { tri.VertexPositions[0] = transformMatrix.TransformPoint(tri.VertexPositions[0]); tri.VertexPositions[1] = transformMatrix.TransformPoint(tri.VertexPositions[1]); tri.VertexPositions[2] = transformMatrix.TransformPoint(tri.VertexPositions[2]); } return true; } case COLLISION_SHAPE_TYPE_CONVEX_HULL: { return false; } default: UnreachableCode(); return false; } } } // namespace Physics <file_sep>/Engine/Source/ContentConverter/AssimpSkeletonImporter.h #pragma once #include "ContentConverter/BaseImporter.h" namespace Assimp { class Importer; } struct aiScene; struct aiNode; struct aiAnimation; namespace AssimpHelpers { class ProgressCallbacksLogStream; } class SkeletonGenerator; class AssimpSkeletonImporter : public BaseImporter { public: struct Options { String SourcePath; String OutputResourceName; COORDINATE_SYSTEM CoordinateSystem; float4x4 TransformMatrix; }; public: AssimpSkeletonImporter(const Options *pOptions, ProgressCallbacks *pProgressCallbacks); ~AssimpSkeletonImporter(); static void SetDefaultOptions(Options *pOptions); bool Execute(); private: bool LoadScene(); bool CreateBones(); bool ReadBoneInfoFromNode(const aiNode *pNode, int32 parentBoneIndex); bool WriteOutput(); const Options *m_pOptions; Assimp::Importer *m_pImporter; AssimpHelpers::ProgressCallbacksLogStream *m_pLogStream; const aiScene *m_pScene; float4x4 m_globalTransform; float4x4 m_inverseGlobalTransform; SkeletonGenerator *m_pOutputGenerator; }; <file_sep>/Editor/Source/Editor/EditorHelpers.cpp #include "Editor/PrecompiledHeader.h" #include "Editor/EditorHelpers.h" #include "Engine/Engine.h" #include "Engine/World.h" #include "Editor/MapEditor/EditorEntityIdWorldRenderer.h" #include "Editor/EditorVisual.h" #include "Editor/Editor.h" #include "Renderer/Renderer.h" #include "Renderer/WorldRenderer.h" #include "ResourceCompiler/ObjectTemplate.h" #include "ResourceCompiler/ObjectTemplateManager.h" #include "Core/Image.h" #include "Core/PixelFormat.h" Log_SetChannel(EditorHelpers); // void EditorHelpers::DrawGrid(const float &GridWidth, const float &GridHeight, const float &GridStep) // { // static const uint32 verticesPerDraw = 16384; // PlainVertexFactory::Vertex gridVertices[verticesPerDraw]; // float gridBoundsX = Min(65536.0f, GridWidth) * 0.5f; // float gridBoundsY = Min(65536.0f, GridHeight) * 0.5f; // float x, y; // uint32 i; // uint32 nVertices = 0; // // // cache device pointers // GPUContext *pGPUDevice = g_pRenderer->GetMainContext(); // GPUContextConstants *pGPUConstants = pGPUDevice->GetConstants(); // // // set constants // pGPUConstants->SetLocalToWorldMatrix(Matrix4::Identity, false); // pGPUConstants->CommitChanges(); // // // setup renderer // pGPUDevice->SetRasterizerState(g_pRenderer->GetFixedResources()->GetRasterizerState(RENDERER_FILL_SOLID, RENDERER_CULL_BACK)); // pGPUDevice->SetDepthStencilState(g_pRenderer->GetFixedResources()->GetDepthStencilState(false, false), 0); // pGPUDevice->SetBlendState(g_pRenderer->GetFixedResources()->GetBlendStateNoBlending()); // pGPUDevice->SetDrawTopology(DRAW_TOPOLOGY_LINE_LIST); // // // calc number of rows, columns // uint32 drawRows = (uint32)Y_ceilf(gridBoundsX * 2.0f / GridStep); // uint32 drawColumns = (uint32)Y_ceilf(gridBoundsY * 2.0f / GridStep); // // // fill in vertices common data // uint32 verticesToInitialize = Min(verticesPerDraw, (drawRows + drawColumns + 2) * 2); // for (i = 0; i < verticesToInitialize; i++) // { // gridVertices[i].TexCoord.SetZero(); // gridVertices[i].Color = MAKE_COLOR_R8G8B8A8_UNORM(102, 102, 102, 255); // } // // // draw columns // for (i = 0, x = 0.0f; i <= drawColumns; i++, x += GridStep) // { // gridVertices[nVertices++].Position.Set(-gridBoundsX + x, gridBoundsY, 0.0f); // gridVertices[nVertices++].Position.Set(-gridBoundsX + x, -gridBoundsY, 0.0f); // // if (nVertices == verticesPerDraw) // { // g_pRenderer->DrawPlainColored(pGPUDevice, gridVertices, nVertices); // nVertices = 0; // } // } // // // draw rows // for (i = 0, y = 0.0f; i <= drawRows; i++, y += GridStep) // { // gridVertices[nVertices++].Position.Set(-gridBoundsX, -gridBoundsY + y, 0.0f); // gridVertices[nVertices++].Position.Set(gridBoundsX, -gridBoundsY + y, 0.0f); // // if (nVertices == verticesPerDraw) // { // g_pRenderer->DrawPlainColored(pGPUDevice, gridVertices, nVertices); // nVertices = 0; // } // } // // // vertices still to draw? // if (nVertices > 0) // g_pRenderer->DrawPlainColored(pGPUDevice, gridVertices, nVertices); // } void EditorHelpers::ConvertQStringToString(String &dest, const QString &source) { dest.Clear(); uint32 sourceLength = (uint32)source.length(); if (sourceLength > 0) { QByteArray sourceUtf8(source.toUtf8()); dest.Resize(sourceLength); Y_memcpy(dest.GetWriteableCharArray(), sourceUtf8.data(), sourceLength); dest.GetWriteableCharArray()[sourceLength] = 0; } } String EditorHelpers::ConvertQStringToString(const QString &source) { String returnValue; ConvertQStringToString(returnValue, source); return returnValue; } QString EditorHelpers::ConvertStringToQString(const String &source) { QString returnValue(QString::fromUtf8(source.GetCharArray(), source.GetLength())); return returnValue; } bool EditorHelpers::ConvertImageToQImage(const Image &image, QImage *pDestinationImage, bool premultiplyAlpha /* = true */) { const PIXEL_FORMAT_INFO *pImagePixelFormatInfo = PixelFormat_GetPixelFormatInfo(image.GetPixelFormat()); if (pImagePixelFormatInfo->HasAlpha) { Image tempImage; const Image *pCopyImage = &image; if (image.GetPixelFormat() != PIXEL_FORMAT_B8G8R8A8_UNORM) { if (!tempImage.CopyAndConvertPixelFormat(image, PIXEL_FORMAT_B8G8R8A8_UNORM)) return false; pCopyImage = &tempImage; } QImage::Format qImageFormat = QImage::Format_ARGB32; if (premultiplyAlpha) { uint32 nPixels = pCopyImage->GetWidth() * pCopyImage->GetHeight(); uint32 *pPixelData = (uint32 *)pCopyImage->GetData(); for (uint32 i = 0; i < nPixels; i++) { byte *pPixelDataBytes = (byte *)pPixelData; // this doesn't actually match up with the ordering in the pixel data, but since // we are pulling and saving in the same order it doesn't actually matter float3 color((float)pPixelDataBytes[0], (float)pPixelDataBytes[1], (float)pPixelDataBytes[2]); color *= (float)pPixelDataBytes[3] / 255.0f; pPixelDataBytes[0] = (byte)Math::Clamp(Math::Truncate(color.r), 0, 255); pPixelDataBytes[1] = (byte)Math::Clamp(Math::Truncate(color.g), 0, 255); pPixelDataBytes[2] = (byte)Math::Clamp(Math::Truncate(color.b), 0, 255); pPixelData++; } qImageFormat = QImage::Format_ARGB32_Premultiplied; } *pDestinationImage = QImage(pCopyImage->GetData(), pCopyImage->GetWidth(), pCopyImage->GetHeight(), qImageFormat).copy(); return true; } else { Image tempImage; const Image *pCopyImage = &image; if (image.GetPixelFormat() != PIXEL_FORMAT_B8G8R8X8_UNORM) { if (!tempImage.CopyAndConvertPixelFormat(image, PIXEL_FORMAT_B8G8R8X8_UNORM)) return false; pCopyImage = &tempImage; } *pDestinationImage = QImage(pCopyImage->GetData(), pCopyImage->GetWidth(), pCopyImage->GetHeight(), QImage::Format_RGB32).copy(); return true; } } bool EditorHelpers::ConvertImageToQPixmap(const Image &image, QPixmap *pDestinationPixmap, bool premultiplyAlpha /* = true */) { QImage qImage; if (!ConvertImageToQImage(image, &qImage, premultiplyAlpha)) return false; *pDestinationPixmap = QPixmap::fromImage(qImage); return true; } bool EditorHelpers::ConvertQImageToImage(const QImage *pSourceImage, Image *pDestinationImage, PIXEL_FORMAT pixelFormat /*= PIXEL_FORMAT_UNKNOWN*/) { /*switch (pSourceImage->format()) { case QImage::Format_ARGB32: case QImage::Format_ARGB32_Premultiplied: { pDestinationImage->Create(PIXEL_FORMAT_R8G8B8A8_UNORM, pSourceImage->width(), pSourceImage->height(), 1); byte *pDataPointer = pDestinationImage->GetData(); for (uint32 y = 0; y < pDestinationImage->GetHeight(); y++) { byte *pDataRowPointer = pDataPointer; for (uint32 x = 0; x < pDestinationImage->GetWidth(); x++) { QRgb sourcePixelValue = pSourceImage->pixel(x, y); *(pDataRowPointer++) = qRed(sourcePixelValue); *(pDataRowPointer++) = qBlue(sourcePixelValue); *(pDataRowPointer++) = qGreen(sourcePixelValue); *(pDataRowPointer++) = qAlpha(sourcePixelValue); } pDataPointer += pDestinationImage->GetDataRowPitch(); } } break; }*/ if (pSourceImage->hasAlphaChannel()) { if (pSourceImage->format() != QImage::Format_ARGB32) { QImage imageCopy(pSourceImage->convertToFormat(QImage::Format_ARGB32)); pDestinationImage->Create(PIXEL_FORMAT_R8G8B8A8_UNORM, imageCopy.width(), imageCopy.height(), 1); byte *pDestinationPointer = pDestinationImage->GetData(); for (int scanline = 0; scanline < imageCopy.height(); scanline++) { Y_memcpy(pDestinationPointer, imageCopy.scanLine(scanline), Min(pDestinationImage->GetDataRowPitch(), (uint32)imageCopy.bytesPerLine())); pDestinationPointer += pDestinationImage->GetDataRowPitch(); } } else { pDestinationImage->Create(PIXEL_FORMAT_R8G8B8A8_UNORM, pSourceImage->width(), pSourceImage->height(), 1); byte *pDestinationPointer = pDestinationImage->GetData(); for (int scanline = 0; scanline < pSourceImage->height(); scanline++) { Y_memcpy(pDestinationPointer, pSourceImage->scanLine(scanline), Min(pDestinationImage->GetDataRowPitch(), (uint32)pSourceImage->bytesPerLine())); pDestinationPointer += pDestinationImage->GetDataRowPitch(); } } } else { if (pSourceImage->format() != QImage::Format_RGB32) { QImage imageCopy(pSourceImage->convertToFormat(QImage::Format_RGB32)); pDestinationImage->Create(PIXEL_FORMAT_R8G8B8A8_UNORM, imageCopy.width(), imageCopy.height(), 1); byte *pDestinationPointer = pDestinationImage->GetData(); for (int scanline = 0; scanline < imageCopy.height(); scanline++) { Y_memcpy(pDestinationPointer, imageCopy.scanLine(scanline), Min(pDestinationImage->GetDataRowPitch(), (uint32)imageCopy.bytesPerLine())); pDestinationPointer += pDestinationImage->GetDataRowPitch(); } } else { pDestinationImage->Create(PIXEL_FORMAT_R8G8B8A8_UNORM, pSourceImage->width(), pSourceImage->height(), 1); byte *pDestinationPointer = pDestinationImage->GetData(); for (int scanline = 0; scanline < pSourceImage->height(); scanline++) { Y_memcpy(pDestinationPointer, pSourceImage->scanLine(scanline), Min(pDestinationImage->GetDataRowPitch(), (uint32)pSourceImage->bytesPerLine())); pDestinationPointer += pDestinationImage->GetDataRowPitch(); } } } if (pixelFormat != PIXEL_FORMAT_UNKNOWN && !pDestinationImage->ConvertPixelFormat(pixelFormat)) return false; return true; } QString EditorHelpers::GetEditorResourcePath(const char *filename) { PathString sstr; sstr.Format("engine/resources/editor/%s", filename); FileSystem::BuildOSPath(sstr); return ConvertStringToQString(sstr); } WorldRenderer *EditorHelpers::CreateWorldRendererForRenderMode(EDITOR_RENDER_MODE renderMode, GPUContext *pGPUContext, uint32 viewportFlags, uint32 viewportWidth, uint32 viewportHeight) { WorldRenderer::Options options; options.InitFromCVars(); options.EnableShadows = (viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_SHADOWS); options.ShowDebugInfo = (viewportFlags & EDITOR_VIEWPORT_FLAG_ENABLE_DEBUG_INFO); options.ShowWireframeOverlay = (viewportFlags & EDITOR_VIEWPORT_FLAG_WIREFRAME_OVERLAY); options.RenderWidth = viewportWidth; options.RenderHeight = viewportHeight; switch (renderMode) { case EDITOR_RENDER_MODE_LIT: break; case EDITOR_RENDER_MODE_FULLBRIGHT: options.RenderModeFullbright = true; break; case EDITOR_RENDER_MODE_WIREFRAME: options.RenderModeNormals = true; break; case EDITOR_RENDER_MODE_LIGHTING_ONLY: options.RenderModeLightingOnly = true; break; } WorldRenderer *pWorldRenderer = WorldRenderer::Create(pGPUContext, &options); if (pWorldRenderer == nullptr) Panic("Failed to create world renderer"); return pWorldRenderer; } WorldRenderer *EditorHelpers::CreatePickingWorldRenderer(GPUContext *pGPUContext, uint32 viewportWidth, uint32 viewportHeight) { // use defaults, since most of them will be ignored anyway WorldRenderer::Options options; options.RenderWidth = viewportWidth; options.RenderHeight = viewportHeight; WorldRenderer *pWorldRenderer = new EditorEntityIdWorldRenderer(pGPUContext, &options); if (!pWorldRenderer->Initialize()) Panic("Failed to create picking world renderer"); return pWorldRenderer; } void EditorHelpers::CreateEntityTypeMenu(QMenu *pMenu, bool onlyCreatable /*= true*/) { // get the entity and static object types const ObjectTemplate *pStaticObjectTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("StaticObject"); const ObjectTemplate *pEntityTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("Entity"); DebugAssert(pStaticObjectTemplate != nullptr && pEntityTemplate != nullptr); PODArray<const ObjectTemplate *> items; ObjectTemplateManager::GetInstance().EnumerateObjectTemplates([onlyCreatable, pStaticObjectTemplate, pEntityTemplate, &items](const ObjectTemplate *pTemplate) { if (onlyCreatable && !pTemplate->CanCreate()) return; // has to either be parented to entity or static object if (!pTemplate->IsDerivedFrom(pStaticObjectTemplate) && !pTemplate->IsDerivedFrom(pEntityTemplate)) return; items.Add(pTemplate); }); // sort alphabetically items.SortCB([](const ObjectTemplate *pLeft, const ObjectTemplate *pRight) { return pLeft->GetTypeName().NumericCompare(pRight->GetTypeName()); }); // create menu for (uint32 i = 0; i < items.GetSize(); i++) { QAction *pAction = pMenu->addAction(ConvertStringToQString(items[i]->GetDisplayName())); pAction->setToolTip(ConvertStringToQString(items[i]->GetDescription())); pAction->setData(ConvertStringToQString(items[i]->GetTypeName())); } } void EditorHelpers::CreateComponentTypeMenu(QMenu *pMenu, bool onlyCreatable /*= true*/) { // get the entity and static object types const ObjectTemplate *pComponentTemplate = ObjectTemplateManager::GetInstance().GetObjectTemplate("Component"); DebugAssert(pComponentTemplate != nullptr); PODArray<const ObjectTemplate *> items; ObjectTemplateManager::GetInstance().EnumerateObjectTemplates([onlyCreatable, pComponentTemplate, &items](const ObjectTemplate *pTemplate) { if (onlyCreatable && !pTemplate->CanCreate() || !pTemplate->IsDerivedFrom(pComponentTemplate)) return; items.Add(pTemplate); }); // sort alphabetically items.SortCB([](const ObjectTemplate *pLeft, const ObjectTemplate *pRight) { return pLeft->GetTypeName().NumericCompare(pRight->GetTypeName()); }); // create menu for (uint32 i = 0; i < items.GetSize(); i++) { QAction *pAction = pMenu->addAction(ConvertStringToQString(items[i]->GetDisplayName())); pAction->setToolTip(ConvertStringToQString(items[i]->GetDescription())); pAction->setData(ConvertStringToQString(items[i]->GetTypeName())); } } <file_sep>/Engine/Source/Engine/SkeletalMesh.cpp #include "Engine/PrecompiledHeader.h" #include "Engine/SkeletalMesh.h" #include "Engine/DataFormats.h" #include "Engine/ResourceManager.h" #include "Engine/Material.h" #include "Engine/Physics/CollisionShape.h" #include "Renderer/VertexFactories/SkeletalMeshVertexFactory.h" #include "Renderer/Renderer.h" #include "Core/ChunkFileReader.h" Log_SetChannel(SkeletalMesh); DEFINE_RESOURCE_TYPE_INFO(SkeletalMesh); DEFINE_RESOURCE_GENERIC_FACTORY(SkeletalMesh); SkeletalMesh::SkeletalMesh(const ResourceTypeInfo *pResourceTypeInfo /*= &s_TypeInfo*/) : BaseClass(pResourceTypeInfo), m_pSkeleton(nullptr), m_boundingBox(AABox::Zero), m_boundingSphere(Sphere::Zero), m_baseVertexFactoryFlags(0), m_pCollisionShape(nullptr), m_bufferVertexFactoryFlags(0), m_pIndexBuffer(nullptr), m_GPUResourcesCreated(false) { } SkeletalMesh::~SkeletalMesh() { SkeletalMesh::ReleaseGPUResources(); // release material references for (uint32 i = 0; i < m_materials.GetSize(); i++) { const Material *pMaterial = m_materials[i]; if (pMaterial != nullptr) pMaterial->Release(); } if (m_pSkeleton != nullptr) m_pSkeleton->Release(); if (m_pCollisionShape != nullptr) m_pCollisionShape->Release(); } bool SkeletalMesh::LoadFromStream(const char *name, ByteStream *pStream) { DF_SKELETALMESH_HEADER fileHeader; if (!pStream->Read2(&fileHeader, sizeof(fileHeader))) return false; if (fileHeader.Magic != DF_SKELETALMESH_HEADER_MAGIC || fileHeader.HeaderSize != sizeof(fileHeader)) return false; ChunkFileReader chunkReader; if (!chunkReader.Initialize(pStream)) return false; // get skeleton { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_SKELETON) || chunkReader.GetCurrentChunkTypeCount<DF_SKELETALMESH_SKELETON>() != 1) return false; const DF_SKELETALMESH_SKELETON *pSkeletonChunk = chunkReader.GetCurrentChunkTypePointer<DF_SKELETALMESH_SKELETON>(); m_pSkeleton = g_pResourceManager->GetSkeleton(chunkReader.GetStringByIndex(pSkeletonChunk->SkeletonNameStringIndex)); if (m_pSkeleton == nullptr) { Log_ErrorPrintf("SkeletalMesh::LoadFromStream: Failed to load skeleton '%s'", chunkReader.GetStringByIndex(pSkeletonChunk->SkeletonNameStringIndex)); return false; } if (m_pSkeleton->GetBoneCount() != fileHeader.SkeletonBoneCount) { Log_ErrorPrintf("SkeletalMesh::LoadFromStream: Mismatched skeleton '%s' (%u vs %u bones)", chunkReader.GetStringByIndex(pSkeletonChunk->SkeletonNameStringIndex), fileHeader.BoneCount, m_pSkeleton->GetBoneCount()); return false; } } // allocate everything m_boundingBox.SetBounds(float3(fileHeader.BoundingBoxMin), float3(fileHeader.BoundingBoxMax)); m_boundingSphere.SetCenterAndRadius(float3(fileHeader.BoundingSphereCenter), fileHeader.BoundingSphereRadius); m_materials.Resize(fileHeader.MaterialCount); m_materials.ZeroContents(); m_bones.Resize(fileHeader.BoneCount); m_boneRefs.Resize(fileHeader.BoneRefCount); m_vertices.Resize(fileHeader.VertexCount); m_indices.Resize(fileHeader.IndexCount); m_batches.Resize(fileHeader.BatchCount); // bones { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_BONES) || chunkReader.GetCurrentChunkTypeCount<DF_SKELETALMESH_BONE>() != fileHeader.BoneCount) return false; const DF_SKELETALMESH_BONE *pSourceBone = chunkReader.GetCurrentChunkTypePointer<DF_SKELETALMESH_BONE>(); Bone *pDestinationBone = m_bones.GetBasePointer(); for (uint32 i = 0; i < m_bones.GetSize(); i++, pSourceBone++, pDestinationBone++) { if (pSourceBone->SkeletonBoneIndex >= m_pSkeleton->GetBoneCount()) return false; pDestinationBone->SkeletonBoneIndex = pSourceBone->SkeletonBoneIndex; pDestinationBone->LocalToBoneTransform = Transform(float3(pSourceBone->LocalToBonePosition), Quaternion(pSourceBone->LocalToBoneRotation), float3(pSourceBone->LocalToBoneScale)); } } // bone refs { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_BONE_REFS) || chunkReader.GetCurrentChunkTypeCount<uint16>() != fileHeader.BoneRefCount) return false; Y_memcpy(m_boneRefs.GetBasePointer(), chunkReader.GetCurrentChunkPointer(), sizeof(uint16) * fileHeader.BoneRefCount); } // read materials { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_MATERIALS) || chunkReader.GetCurrentChunkTypeCount<DF_SKELETALMESH_MATERIAL>() != m_materials.GetSize()) return false; const DF_SKELETALMESH_MATERIAL *pSourceMaterials = chunkReader.GetCurrentChunkTypePointer<DF_SKELETALMESH_MATERIAL>(); for (uint32 i = 0; i < m_materials.GetSize(); i++) { const char *materialName = chunkReader.GetStringByIndex(pSourceMaterials[i].MaterialNameStringIndex); const Material *pMaterial = g_pResourceManager->GetMaterial(materialName); if (pMaterial == nullptr) { Log_WarningPrintf("SkeletalMesh::LoadFromStream: Could not find material '%s', using default.", materialName); pMaterial = g_pResourceManager->GetDefaultMaterial(); } m_materials[i] = pMaterial; } } // read vertices { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_VERTICES) || chunkReader.GetCurrentChunkTypeCount<DF_SKELETALMESH_VERTEX>() != m_vertices.GetSize()) return false; const DF_SKELETALMESH_VERTEX *pSourceVertices = chunkReader.GetCurrentChunkTypePointer<DF_SKELETALMESH_VERTEX>(); for (uint32 i = 0; i < m_vertices.GetSize(); i++) { const DF_SKELETALMESH_VERTEX *pSourceVertex = &pSourceVertices[i]; SkeletalMeshVertexFactory::Vertex *pDestinationVertex = &m_vertices[i]; pDestinationVertex->Position.Load(pSourceVertex->Position); pDestinationVertex->TangentX.Load(pSourceVertex->Tangent); pDestinationVertex->TangentY.Load(pSourceVertex->Binormal); pDestinationVertex->TangentZ.Load(pSourceVertex->Normal); pDestinationVertex->TexCoord.Load(pSourceVertex->TextureCoordinates); pDestinationVertex->Color = pSourceVertex->Color; Y_memcpy(pDestinationVertex->BoneIndices, pSourceVertex->BoneIndices, sizeof(pDestinationVertex->BoneIndices)); Y_memcpy(pDestinationVertex->BoneWeights, pSourceVertex->BoneWeights, sizeof(pDestinationVertex->BoneWeights)); } } // read indices { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_INDICES) || chunkReader.GetCurrentChunkTypeCount<uint16>() != m_indices.GetSize()) return false; Y_memcpy(m_indices.GetBasePointer(), chunkReader.GetCurrentChunkPointer(), sizeof(uint16) * m_indices.GetSize()); } // read batches { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_BATCHES) || chunkReader.GetCurrentChunkTypeCount<DF_SKELETALMESH_BATCH>() != m_batches.GetSize()) return false; // determine base vertex factory flags m_baseVertexFactoryFlags = 0; if (fileHeader.Flags & DF_SKELETALMESH_FLAG_USE_TEXTURE_COORDINATES) m_baseVertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_TEXCOORDS; if (fileHeader.Flags & DF_SKELETALMESH_FLAG_USE_VERTEX_COLORS) m_baseVertexFactoryFlags |= SKELETAL_MESH_VERTEX_FACTORY_FLAG_VERTEX_COLORS; // add batches const DF_SKELETALMESH_BATCH *pSourceBatches = chunkReader.GetCurrentChunkTypePointer<DF_SKELETALMESH_BATCH>(); for (uint32 i = 0; i < m_batches.GetSize(); i++) { const DF_SKELETALMESH_BATCH *pSourceBatch = &pSourceBatches[i]; Batch *pDestinationBatch = &m_batches[i]; // set fields pDestinationBatch->MaterialIndex = pSourceBatch->MaterialIndex; pDestinationBatch->WeightCount = pSourceBatch->WeightCount; pDestinationBatch->BaseBoneRef = pSourceBatch->BaseBoneRef; pDestinationBatch->BoneRefCount = pSourceBatch->BoneRefCount; pDestinationBatch->BaseVertex = pSourceBatch->BaseVertex; pDestinationBatch->VertexCount = pSourceBatch->VertexCount; pDestinationBatch->FirstIndex = pSourceBatch->StartIndex; pDestinationBatch->IndexCount = pSourceBatch->IndexCount; } } // read collision shape if (fileHeader.CollisionShapeType != Physics::COLLISION_SHAPE_TYPE_NONE) { if (!chunkReader.LoadChunk(DF_SKELETALMESH_CHUNK_COLLISION_SHAPE)) return false; m_pCollisionShape = Physics::CollisionShape::CreateFromData(chunkReader.GetCurrentChunkPointer(), chunkReader.GetCurrentChunkSize()); if (m_pCollisionShape == nullptr) return false; } // done m_strName = name; // create on gpu if (!CreateGPUResources()) { Log_ErrorPrintf("GPU upload failed."); return false; } return true; } bool SkeletalMesh::CreateGPUResources() const { if (m_GPUResourcesCreated) return true; // todo: check constant buffer limits m_bufferVertexFactoryFlags = m_baseVertexFactoryFlags | SKELETAL_MESH_VERTEX_FACTORY_FLAG_GPU_SKINNING; if (m_vertexBuffers.GetBuffer(0) == nullptr) { if (!SkeletalMeshVertexFactory::CreateVerticesBuffer(g_pRenderer->GetPlatform(), g_pRenderer->GetFeatureLevel(), m_bufferVertexFactoryFlags, m_vertices.GetBasePointer(), m_vertices.GetSize(), &m_vertexBuffers)) return false; } if (m_pIndexBuffer == NULL) { GPU_BUFFER_DESC bufferDesc(GPU_BUFFER_FLAG_BIND_INDEX_BUFFER, m_indices.GetStorageSizeInBytes()); if ((m_pIndexBuffer = g_pRenderer->CreateBuffer(&bufferDesc, m_indices.GetBasePointer())) == nullptr) return false; } m_GPUResourcesCreated = true; return true; } void SkeletalMesh::ReleaseGPUResources() const { m_vertexBuffers.Clear(); SAFE_RELEASE(m_pIndexBuffer); m_GPUResourcesCreated = false; } bool SkeletalMesh::CheckGPUResources() const { if (m_vertexBuffers.GetBuffer(0) == nullptr) return false; if (m_pIndexBuffer == nullptr) return false; return true; } /* SkeletalMeshInstanceBoneData::SkeletalMeshInstanceBoneData(const SkeletalMesh *pSkeletalMesh) { InitializeForMesh(pSkeletalMesh); } SkeletalMeshInstanceBoneData::~SkeletalMeshInstanceBoneData() { } void SkeletalMeshInstanceBoneData::InitializeForMesh(const SkeletalMesh *pSkeletalMesh) { const Skeleton *pSkeleton = pSkeletalMesh->GetSkeleton(); if (pSkeleton->GetBoneCount() != m_boneTransforms.GetSize()) { m_boneTransforms.Obliterate(); m_boneTransforms.Resize(pSkeleton->GetBoneCount()); } ResetToBaseFrame(pSkeletalMesh); } void SkeletalMeshInstanceBoneData::ResetToBaseFrame(const SkeletalMesh *pSkeletalMesh) { const Skeleton *pSkeleton = pSkeletalMesh->GetSkeleton(); DebugAssert(pSkeleton->GetBoneCount() == m_boneTransforms.GetSize()); for (uint32 i = 0; i < m_boneTransforms.GetSize(); i++) m_boneTransforms[i] = pSkeleton->GetBoneByIndex(i)->GetAbsoluteBaseFrameTransform(); } */ <file_sep>/Engine/Source/D3D12Renderer/D3D12RenderBackend.cpp #include "D3D12Renderer/PrecompiledHeader.h" #include "D3D12Renderer/D3D12GPUDevice.h" #include "D3D12Renderer/D3D12GPUContext.h" #include "D3D12Renderer/D3D12GPUOutputBuffer.h" #include "D3D12Renderer/D3D12Helpers.h" #include "D3D12Renderer/D3D12CVars.h" #include "Engine/EngineCVars.h" Log_SetChannel(D3D12RenderBackend); bool D3D12RenderBackend_Create(const RendererInitializationParameters *pCreateParameters, SDL_Window *pSDLWindow, GPUDevice **ppDevice, GPUContext **ppImmediateContext, GPUOutputBuffer **ppOutputBuffer) { HRESULT hResult; // load d3d12 library HMODULE hD3D12Module = LoadLibraryA("d3d12.dll"); if (hD3D12Module == nullptr) { Log_ErrorPrintf("D3D12RenderBackend::Create: Failed to load d3d12.dll library."); return false; } // get function entry points PFN_D3D12_CREATE_DEVICE fnD3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(hD3D12Module, "D3D12CreateDevice"); PFN_D3D12_GET_DEBUG_INTERFACE fnD3D12GetDebugInterface = (PFN_D3D12_GET_DEBUG_INTERFACE)GetProcAddress(hD3D12Module, "D3D12GetDebugInterface"); PFN_D3D12_SERIALIZE_ROOT_SIGNATURE fnD3D12SerializeRootSignature = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)GetProcAddress(hD3D12Module, "D3D12SerializeRootSignature"); if (fnD3D12CreateDevice == nullptr || fnD3D12GetDebugInterface == nullptr || fnD3D12SerializeRootSignature == nullptr) { Log_ErrorPrintf("D3D12RenderBackend::Create: Missing D3D12 device entry points."); FreeLibrary(hD3D12Module); return false; } // acquire debug interface if (CVars::r_use_debug_device.GetBool()) { Log_PerfPrintf("Enabling Direct3D 12 debug layer, performance will suffer as a result."); ID3D12Debug *pD3D12Debug; hResult = fnD3D12GetDebugInterface(__uuidof(ID3D12Debug), (void **)&pD3D12Debug); if (SUCCEEDED(hResult)) { pD3D12Debug->EnableDebugLayer(); pD3D12Debug->Release(); } else { Log_WarningPrintf("D3D12GetDebugInterface failed with hResult %08X. Debug layer will not be enabled.", hResult); } } // create dxgi factory IDXGIFactory4 *pDXGIFactory; hResult = CreateDXGIFactory2((CVars::r_use_debug_device.GetBool()) ? DXGI_CREATE_FACTORY_DEBUG : 0, IID_PPV_ARGS(&pDXGIFactory)); //hResult = CreateDXGIFactory1(IID_PPV_ARGS(&m_pDXGIFactory)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12RenderBackend::Create: Failed to create DXGI factory with hResult %08X", hResult); FreeLibrary(hD3D12Module); return false; } // find adapter IDXGIAdapter3 *pDXGIAdapter = nullptr; if (CVars::r_d3d12_force_warp.GetBool()) { hResult = pDXGIFactory->EnumWarpAdapter(IID_PPV_ARGS(&pDXGIAdapter)); if (FAILED(hResult)) { Log_ErrorPrintf("IDXGIFactory::EnumWarpAdapter failed with hResult %08X", hResult); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } } #if 1 else { // iterate over adapters for (uint32 adapterIndex = 0; ; adapterIndex++) { IDXGIAdapter *pAdapter; hResult = pDXGIFactory->EnumAdapters(adapterIndex, &pAdapter); if (hResult == DXGI_ERROR_NOT_FOUND) break; if (SUCCEEDED(hResult)) { hResult = pAdapter->QueryInterface(__uuidof(IDXGIAdapter3), (void **)&pDXGIAdapter); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12RenderBackend::Create: IDXGIAdapter::QueryInterface(IDXGIAdapter3) failed."); pAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } pAdapter->Release(); break; } Log_WarningPrintf("IDXGIFactory::EnumAdapters(%u) failed with hResult %08X", adapterIndex, hResult); } } // found an adapter if (pDXGIAdapter == nullptr) { Log_ErrorPrintf("D3D12RenderBackend::Create: Failed to find an acceptable adapter.", hResult); pDXGIAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } // print device name { // get adapter desc DXGI_ADAPTER_DESC DXGIAdapterDesc; hResult = pDXGIAdapter->GetDesc(&DXGIAdapterDesc); DebugAssert(hResult == S_OK); char deviceName[128]; WideCharToMultiByte(CP_ACP, 0, DXGIAdapterDesc.Description, -1, deviceName, countof(deviceName), NULL, NULL); Log_InfoPrintf("D3D12 render backend using DXGI Adapter: %s.", deviceName); } #endif // create the device ID3D12Device *pD3DDevice; hResult = fnD3D12CreateDevice(pDXGIAdapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&pD3DDevice)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12RenderBackend::Create: Could not create D3D12 device: %08X.", hResult); pDXGIAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } // query feature levels static const D3D_FEATURE_LEVEL requestedFeatureLevels[] = { D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevelsData = { countof(requestedFeatureLevels), requestedFeatureLevels, D3D_FEATURE_LEVEL_11_0 }; hResult = pD3DDevice->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevelsData, sizeof(featureLevelsData)); if (FAILED(hResult)) { Log_ErrorPrintf("D3D12RenderBackend::Create: CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS) failed with hResult %08X", hResult); pD3DDevice->Release(); pDXGIAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } // print feature level D3D_FEATURE_LEVEL D3DFeatureLevel = featureLevelsData.MaxSupportedFeatureLevel; Log_DevPrintf("D3D12RenderBackend::Create: Driver supports feature level %s (%X)", NameTable_GetNameString(NameTables::D3DFeatureLevels, D3DFeatureLevel), D3DFeatureLevel); // map to our range RENDERER_FEATURE_LEVEL featureLevel; if (D3DFeatureLevel >= D3D_FEATURE_LEVEL_11_0) featureLevel = RENDERER_FEATURE_LEVEL_SM5; else { Log_ErrorPrintf("D3D12RenderBackend::Create: Feature level is insufficient"); pD3DDevice->Release(); pDXGIAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } // find texture platform TEXTURE_PLATFORM texturePlatform; { texturePlatform = TEXTURE_PLATFORM_DXTC; Log_InfoPrintf("Texture Platform: %s", NameTable_GetNameString(NameTables::TexturePlatform, texturePlatform)); } // other vars uint32 frameLatency = pCreateParameters->GPUFrameLatency; Log_DevPrintf("Frame latency: %u", frameLatency); // set default backbuffer formats if unspecified PIXEL_FORMAT outputBackBufferFormat = pCreateParameters->BackBufferFormat; PIXEL_FORMAT outputDepthStencilFormat = pCreateParameters->DepthStencilBufferFormat; if (outputBackBufferFormat == PIXEL_FORMAT_UNKNOWN) outputBackBufferFormat = PIXEL_FORMAT_R8G8B8A8_UNORM; // create device and context D3D12GPUDevice *pDevice = new D3D12GPUDevice(hD3D12Module, pDXGIFactory, pDXGIAdapter, pD3DDevice, D3DFeatureLevel, featureLevel, texturePlatform, outputBackBufferFormat, outputDepthStencilFormat, frameLatency); D3D12GPUContext *pImmediateContext = pDevice->InitializeAndCreateContext(); if (pImmediateContext == nullptr) { pDevice->Release(); pD3DDevice->Release(); pDXGIAdapter->Release(); pDXGIFactory->Release(); FreeLibrary(hD3D12Module); return false; } // release our d3d pointers pD3DDevice->Release(); pDXGIAdapter->Release(); pDXGIFactory->Release(); // create implicit swap chain GPUOutputBuffer *pOutputBuffer = nullptr; if (pSDLWindow != nullptr) { // pass through to normal method pOutputBuffer = pDevice->CreateOutputBuffer(pSDLWindow, pCreateParameters->ImplicitSwapChainVSyncType); if (pOutputBuffer == nullptr) { pImmediateContext->Release(); pDevice->Release(); return false; } // bind to context pImmediateContext->SetOutputBuffer(pOutputBuffer); } // set pointers *ppDevice = pDevice; *ppImmediateContext = pImmediateContext; *ppOutputBuffer = pOutputBuffer; Log_InfoPrint("D3D12 render backend creation successful."); return true; } <file_sep>/Engine/Source/D3D11Renderer/D3D11CVars.h #pragma once #include "Engine/Common.h" namespace CVars { // D3D11 CVars extern CVar r_d3d11_force_ref; extern CVar r_d3d11_force_warp; extern CVar r_d3d11_use_11_1; } <file_sep>/Engine/Source/BlockEngine/BlockWorldChunk.h #pragma once #include "BlockEngine/BlockWorldTypes.h" namespace Physics { class StaticObject; } class BlockWorldChunk { friend class BlockWorld; public: enum MeshState { MeshState_Idle, MeshState_Pending, MeshState_InProgress, MeshState_InProgressWithChanges }; public: BlockWorldChunk(BlockWorldSection *pSection, int32 relativeChunkX, int32 relativeChunkY, int32 relativeChunkZ); ~BlockWorldChunk(); BlockWorldSection *GetSection() { return m_pSection; } const BlockWorldSection *GetSection() const { return m_pSection; } const int32 GetChunkSize() const { return m_chunkSize; } const int32 GetLoadedLODLevel() const { return m_loadedLODLevel; } const int32 GetRenderLODLevel() const { return m_renderLODLevel; } const int32 GetRelativeChunkX() const { return m_relativeChunkX; } const int32 GetRelativeChunkY() const { return m_relativeChunkY; } const int32 GetRelativeChunkZ() const { return m_relativeChunkZ; } const int32 GetGlobalChunkX() const { return m_globalChunkX; } const int32 GetGlobalChunkY() const { return m_globalChunkY; } const int32 GetGlobalChunkZ() const { return m_globalChunkZ; } const float3 &GetBasePosition() const { return m_basePosition; } const AABox &GetBoundingBox() const { return m_boundingBox; } void SetRenderLODLevel(int32 lodLevel) { m_renderLODLevel = lodLevel; } // serialization void Create(); bool LoadFromStream(int32 lodLevel, ByteStream *pStream); bool SaveToStream(int32 lodLevel, ByteStream *pStream); void UnloadLODLevel(int32 lodLevel); // chunk data is indexed by (bz * CHUNKSIZE * CHUNKHEIGHT) + (by * CHUNKSIZE) + bx const BlockWorldBlockType *GetBlockValues(int32 lodLevel) const { return m_pBlockValues[lodLevel]; } const BlockWorldBlockDataType *GetBlockData(int32 lodLevel) const { return m_pBlockData[lodLevel]; } BlockWorldBlockType *GetBlockValues(int32 lodLevel) { return m_pBlockValues[lodLevel]; } BlockWorldBlockDataType *GetBlockData(int32 lodLevel) { return m_pBlockData[lodLevel]; } int32 GetZStride(int32 lodLevel) { return m_zStride[lodLevel]; } // check if the chunk is empty bool IsAirChunk() const; // manipulators BlockWorldBlockType GetBlock(int32 lodLevel, int32 bx, int32 by, int32 bz) const; void SetBlock(int32 lodLevel, int32 bx, int32 by, int32 bz, BlockWorldBlockType blockType); // data manipulators BlockWorldBlockDataType GetBlockData(int32 lodLevel, int32 bx, int32 by, int32 bz) const; void SetBlockData(int32 lodLevel, int32 bx, int32 by, int32 bz, BlockWorldBlockDataType blockType); // lighting manipulators uint8 GetBlockLight(int32 lodLevel, int32 bx, int32 by, int32 bz) const; void SetBlockLight(int32 lodLevel, int32 bx, int32 by, int32 bz, uint8 lightLevel); // rotation manipulators uint8 GetBlockRotation(int32 lodLevel, int32 bx, int32 by, int32 bz) const; void SetBlockRotation(int32 lodLevel, int32 bx, int32 by, int32 bz, uint8 rotation); // update the lods for a particular block void UpdateLODs(int32 lodLevel, int32 blockX, int32 blockY, int32 blockZ); // mesh pending flag MeshState GetMeshState() const { return m_meshState; } bool IsMeshPending() const { return (m_meshState != MeshState_Idle); } void SetMeshState(MeshState state) { DebugAssert(state <= MeshState_InProgress); m_meshState = state; } // collision object BlockWorldChunkCollisionShape *GetCollisionShape() { return m_pCollisionShape; } Physics::StaticObject *GetCollisionObject() { return m_pCollisionObject; } // render object, when setting this takes the reference BlockWorldChunkRenderProxy *GetRenderProxy() { return m_pRenderProxy; } void SetRenderProxy(BlockWorldChunkRenderProxy *pRenderProxy) { m_pRenderProxy = pRenderProxy; } private: BlockWorldSection *m_pSection; int32 m_chunkSize; int32 m_loadedLODLevel; int32 m_renderLODLevel; int32 m_relativeChunkX; int32 m_relativeChunkY; int32 m_relativeChunkZ; int32 m_globalChunkX; int32 m_globalChunkY; int32 m_globalChunkZ; float3 m_basePosition; AABox m_boundingBox; // chunk data is indexed by (bz * CHUNKSIZE * CHUNKHEIGHT) + (by * CHUNKSIZE) + bx BlockWorldBlockType *m_pBlockValues[BLOCK_WORLD_MAX_LOD_LEVELS]; BlockWorldBlockDataType *m_pBlockData[BLOCK_WORLD_MAX_LOD_LEVELS]; int32 m_zStride[BLOCK_WORLD_MAX_LOD_LEVELS]; // physics object for this chunk BlockWorldChunkCollisionShape *m_pCollisionShape; Physics::StaticObject *m_pCollisionObject; // render object for this chunk BlockWorldChunkRenderProxy *m_pRenderProxy; // mesh pending flag MeshState m_meshState; }; <file_sep>/Engine/Source/Engine/EntityTypeInfo.h #pragma once #include "Engine/ScriptObjectTypeInfo.h" class EntityTypeInfo : public ScriptObjectTypeInfo { public: EntityTypeInfo(const char *TypeName, const ObjectTypeInfo *pParentTypeInfo, const PROPERTY_DECLARATION *pPropertyDeclarations, ObjectFactory *pFactory, uint32 scriptFlags, const SCRIPT_FUNCTION_TABLE_ENTRY *pScriptFunctions); virtual ~EntityTypeInfo(); // type registration virtual void RegisterType() override; virtual void UnregisterType() override; }; // Macros #define DECLARE_ENTITY_TYPEINFO(Type, ParentType) \ private: \ static EntityTypeInfo s_typeInfo; \ static const PROPERTY_DECLARATION s_propertyDeclarations[]; \ static const SCRIPT_FUNCTION_TABLE_ENTRY *__TypeScriptFunctionTable(); \ public: \ typedef Type ThisClass; \ typedef ParentType BaseClass; \ static const EntityTypeInfo *StaticTypeInfo() { return &s_typeInfo; } \ static EntityTypeInfo *StaticMutableTypeInfo() { return &s_typeInfo; } #define DECLARE_ENTITY_GENERIC_FACTORY(Type) DECLARE_OBJECT_GENERIC_FACTORY(Type) #define DECLARE_ENTITY_NO_FACTORY(Type) DECLARE_OBJECT_NO_FACTORY(Type) #define DEFINE_ENTITY_TYPEINFO(Type, ScriptFlags) \ EntityTypeInfo Type::s_typeInfo = EntityTypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::s_propertyDeclarations, Type::StaticFactory(), ScriptFlags, Type::__TypeScriptFunctionTable()); \ DEFINE_SCRIPT_ARG_WRAPPERS(Type); #define DEFINE_ENTITY_TYPEINFO_NOSCRIPT(Type) \ EntityTypeInfo Type::s_typeInfo = EntityTypeInfo(#Type, Type::BaseClass::StaticTypeInfo(), Type::s_propertyDeclarations, Type::StaticFactory(), SCRIPT_OBJECT_FLAG_UNEXPOSED, nullptr); \ const SCRIPT_FUNCTION_TABLE_ENTRY *Type::__TypeScriptFunctionTable() { return nullptr; } #define DEFINE_ENTITY_GENERIC_FACTORY(Type) DEFINE_OBJECT_GENERIC_FACTORY(Type) #define BEGIN_ENTITY_PROPERTIES(Type) \ const PROPERTY_DECLARATION Type::s_propertyDeclarations[] = { #define END_ENTITY_PROPERTIES() \ PROPERTY_TABLE_MEMBER(NULL, PROPERTY_TYPE_COUNT, 0, NULL, NULL, NULL, NULL, NULL, NULL) \ }; #define BEGIN_ENTITY_SCRIPT_FUNCTIONS(Type) BEGIN_SCRIPT_OBJECT_FUNCTIONS(Type) #define DEFINE_ENTITY_SCRIPT_FUNCTION(FunctionName, FunctionPointer) DEFINE_SCRIPT_OBJECT_FUNCTION(FunctionName, FunctionPointer) #define END_ENTITY_SCRIPT_FUNCTIONS() END_SCRIPT_OBJECT_FUNCTIONS() #define ENTITY_TYPEINFO(Type) OBJECT_TYPEINFO(Type) #define ENTITY_TYPEINFO_PTR(Ptr) OBJECT_TYPEINFO_PTR(Type) #define ENTITY_MUTABLE_TYPEINFO(Type) OBJECT_MUTABLE_TYPEINFO(Type) #define ENTITY_MUTABLE_TYPEINFO_PTR(Type) OBJECT_MUTABLE_TYPEINFO_PTR(Type) <file_sep>/Engine/Source/BaseGame/InteractiveEntity.h #pragma once #include "BaseGame/GameEntity.h" class InteractiveEntity : public GameEntity { DECLARE_ENTITY_TYPEINFO(InteractiveEntity, GameEntity); DECLARE_ENTITY_NO_FACTORY(InteractiveEntity); public: InteractiveEntity(const EntityTypeInfo *pTypeInfo = &s_typeInfo); virtual ~InteractiveEntity(); }; <file_sep>/Engine/Source/Renderer/RenderQueue.h #pragma once #include "Renderer/Common.h" class RenderProxy; class VertexFactoryTypeInfo; class Material; class GPUTexture; class GPUQuery; enum RENDER_QUEUE_LAYER { RENDER_QUEUE_LAYER_SKYBOX = 0, // skybox RENDER_QUEUE_LAYER_NONE = 1, // everything else RENDER_QUEUE_LAYER_DECALS = 2, }; struct RENDER_QUEUE_RENDERABLE_ENTRY { uint64 SortKey; const RenderProxy *pRenderProxy; const VertexFactoryTypeInfo *pVertexFactoryTypeInfo; const Material *pMaterial; void *UserDataPointer[2]; AABox BoundingBox; uint32 RenderPassMask; uint32 VertexFactoryFlags; float ViewDistance; uint32 TintColor; uint32 UserData[4]; uint8 Layer; // predicate to apply when drawing GPUQuery *pPredicate; // align to 2 cache lines #if defined(Y_CPU_X86) //byte __padding__[32]; // 128-96 #elif defined(Y_CPU_X64) //byte __padding__[20]; // 128-108 #endif // start cleared inline RENDER_QUEUE_RENDERABLE_ENTRY() { Y_memzero(this, sizeof(RENDER_QUEUE_RENDERABLE_ENTRY)); } }; struct RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY { float3 LightColor; float3 AmbientColor; float3 Direction; uint32 ShadowFlags; int32 ShadowMapIndex; bool Static; }; struct RENDER_QUEUE_POINT_LIGHT_ENTRY { float3 Position; float Range; float InverseRange; float3 LightColor; float FalloffExponent; uint32 ShadowFlags; int32 ShadowMapIndex; bool Static; }; struct RENDER_QUEUE_SPOT_LIGHT_ENTRY { float3 Position; float Range; float InverseRange; float3 LightColor; float Theta; float Phi; float Falloff; uint32 ShadowFlags; int32 ShadowMapIndex; bool Static; }; struct RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY { float3 Position; float Range; float3 LightColor; VOLUMETRIC_LIGHT_PRIMITIVE Primitive; float FalloffRate; float3 BoxExtents; float SphereRadius; bool Static; }; struct RENDER_QUEUE_OCCLUDER_ENTRY { const RenderProxy *pRenderProxy; void *UserDataPointer[2]; uint32 UserData[4]; bool MatchUserData; // todo: provide a mesh? AABox BoundingBox; // start cleared inline RENDER_QUEUE_OCCLUDER_ENTRY() { Y_memzero(this, sizeof(RENDER_QUEUE_OCCLUDER_ENTRY)); } }; class RenderQueue { public: typedef MemArray<RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY> DirectionalLightArray; typedef MemArray<RENDER_QUEUE_POINT_LIGHT_ENTRY> PointLightArray; typedef MemArray<RENDER_QUEUE_SPOT_LIGHT_ENTRY> SpotLightArray; typedef MemArray<RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY> VolumetricLightArray; typedef MemArray<RENDER_QUEUE_RENDERABLE_ENTRY> RenderableArray; typedef MemArray<RENDER_QUEUE_OCCLUDER_ENTRY> OccluderArray; typedef PODArray<const RenderProxy *> DebugDrawRenderableArray; public: RenderQueue(); ~RenderQueue(); // accepted object draw mask const bool IsAcceptingLights() const { return m_acceptingLights; } const uint32 GetAcceptingRenderPassMask() const { return m_acceptingRenderPassMask; } const bool IsAcceptingDebugObjects() const { return m_acceptingDebugObjects; } const bool IsAcceptingOccluders() const { return m_acceptingOccluders; } void SetAcceptingLights(bool enabled) { m_acceptingLights = enabled; } void SetAcceptingRenderPassMask(uint32 mask) { m_acceptingRenderPassMask = mask; } void SetAcceptingOccluders(bool enabled) { m_acceptingOccluders = enabled; } void SetAcceptingDebugObjects(bool enabled) { m_acceptingDebugObjects = enabled; } // Adds a batch to the draw queue. // Does not perform sorting. void AddLight(const RENDER_QUEUE_DIRECTIONAL_LIGHT_ENTRY *pLightEntry); void AddLight(const RENDER_QUEUE_POINT_LIGHT_ENTRY *pLightEntry); void AddLight(const RENDER_QUEUE_SPOT_LIGHT_ENTRY *pLightEntry); void AddLight(const RENDER_QUEUE_VOLUMETRIC_LIGHT_ENTRY *pLightEntry); void AddRenderable(const RENDER_QUEUE_RENDERABLE_ENTRY *pQueueEntry); void AddOccluder(const RENDER_QUEUE_OCCLUDER_ENTRY *pOccluderEntry); void AddOccluder(const RenderProxy *pRenderProxy, const AABox &boundingBox); void AddOccluder(const RenderProxy *pRenderProxy, const AABox &boundingBox, const uint32 userData[], const void *const userDataPointer[]); void AddDebugInfoObject(const RenderProxy *pRenderProxy); // remove a render proxy from the queue void InvalidateOpaqueRenderProxy(const RenderProxy *pRenderProxy); void InvalidateOpaqueRenderProxy(const RenderProxy *pRenderProxy, const uint32 userData[], const void *const userDataPointer[]); // mark queue entries with a query result void MarkRenderProxyWithPredicate(const RenderProxy *pRenderProxy, GPUQuery *pPredicate); void MarkRenderProxyWithPredicate(const RenderProxy *pRenderProxy, const uint32 userData[], const void *const userDataPointer[], GPUQuery *pPredicate); // Re-sorts the render queue for optimal performance. void Sort(); // Clears the render queue. void Clear(); // External Access const uint32 GetQueueSize() const { return m_queueSize; } const uint32 GetNumObjectsInvalidatedByOcclusion() const { return m_numObjectsInvalidatedByOcclusion; } // lights DirectionalLightArray &GetDirectionalLightArray() { return m_directionalLightArray; } const uint32 GetDirectionalLightCount() const { return m_directionalLightArray.GetSize(); } PointLightArray &GetPointLightArray() { return m_pointLightArray; } const uint32 GetPointLightCount() const { return m_pointLightArray.GetSize(); } SpotLightArray &GetSpotLightArray() { return m_spotLightArray; } const uint32 GetSpotLightCount() const { return m_spotLightArray.GetSize(); } VolumetricLightArray &GetVolumetricLightArray() { return m_volumetricLightArray; } const uint32 GetVolumetricLightCount() const { return m_volumetricLightArray.GetSize(); } // opaque objects (both unlit and lit) RenderableArray &GetOpaqueRenderables() { return m_opaqueRenderables; } const uint32 GetOpaqueRenderableCount() const { return m_opaqueRenderables.GetSize(); } // translucent objects (both unlit and lit) RenderableArray &GetTranslucentRenderables() { return m_translucentRenderables; } const uint32 GetTranslucentRenderableCount() const { return m_translucentRenderables.GetSize(); } // post process renderables RenderableArray &GetPostProcessRenderables() { return m_postProcessRenderables; } const uint32 GetPostProcessRenderableCount() const { return m_postProcessRenderables.GetSize(); } // occlusion culling occluders OccluderArray &GetOccluders() { return m_occluders; } // debug draw objects DebugDrawRenderableArray &GetDebugObjects() { return m_debugDrawObjects; } private: // accepting lights? bool m_acceptingLights; // accepting draw mask? uint32 m_acceptingRenderPassMask; // accepting occluders? bool m_acceptingOccluders; // accepting debug info? bool m_acceptingDebugObjects; // total objects added uint32 m_queueSize; uint32 m_numObjectsInvalidatedByOcclusion; // list of lights DirectionalLightArray m_directionalLightArray; PointLightArray m_pointLightArray; SpotLightArray m_spotLightArray; VolumetricLightArray m_volumetricLightArray; // opaque objects with light interactions // todo in the future: split this into z prepass, lightmap/emissive, lit buckets and examine impact on perf RenderableArray m_opaqueRenderables; // unlit translucent objects, also those with light interactions, since this is sorted by distance RenderableArray m_translucentRenderables; // post process renderables RenderableArray m_postProcessRenderables; // occlusion culling occluders OccluderArray m_occluders; // objects with debug draw callbacks DebugDrawRenderableArray m_debugDrawObjects; }; <file_sep>/Editor/Source/Editor/EditorHelpers.h #pragma once #include "Editor/Common.h" class Image; class WorldRenderer; //================================================================================================================= // helper functions //================================================================================================================= namespace EditorHelpers { // grid drawing // the grid is generated on the x/y plane, if another plane is desired, provide a matrix parameter. // the grid will be translated to the specified base position, so it 'appears' to be infinite. // this method assumes that the render target and depth stencil buffer are already set. //void DrawGrid(const float &GridWidth, const float &GridHeight, const float &GridStep); // convert a qstring to our string class void ConvertQStringToString(String &dest, const QString &source); String ConvertQStringToString(const QString &source); QString ConvertStringToQString(const String &source); // convert a image to qimage bool ConvertImageToQImage(const Image &image, QImage *pDestinationImage, bool premultiplyAlpha = true); bool ConvertImageToQPixmap(const Image &image, QPixmap *pDestinationPixmap, bool premultiplyAlpha = true); // convert a qimage to an image bool ConvertQImageToImage(const QImage *pSourceImage, Image *pDestinationImage, PIXEL_FORMAT pixelFormat = PIXEL_FORMAT_UNKNOWN); // build the full path to an editor resource QString GetEditorResourcePath(const char *filename); // create a world renderer for the specified view mode WorldRenderer *CreateWorldRendererForRenderMode(EDITOR_RENDER_MODE renderMode, GPUContext *pGPUContext, uint32 viewportFlags, uint32 viewportWidth, uint32 viewportHeight); // create a picking/entity id world renderer WorldRenderer *CreatePickingWorldRenderer(GPUContext *pGPUContext, uint32 viewportWidth, uint32 viewportHeight); // create a menu containing entity types void CreateEntityTypeMenu(QMenu *pMenu, bool onlyCreatable = true); // create a menu containing component types void CreateComponentTypeMenu(QMenu *pMenu, bool onlyCreatable = true); }; // Use shorthand for the string functions using EditorHelpers::ConvertStringToQString; using EditorHelpers::ConvertQStringToString;
4aca6e0da325098e72791349bea4dad0d79d3674
[ "CMake", "Makefile", "C", "C++", "Shell" ]
803
C++
stenzek/YGameEngine
833e0dceee8f7d87c311624776344dde4ffa1c83
9e1d42cc01cba1ea40030776df401ec4ed2bc4cb
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2017-12-17 12:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('list', '0001_initial'), ] operations = [ migrations.AddField( model_name='post', name='image', field=models.ImageField(default='ímages/None/no-img.jpg', upload_to='images/'), ), migrations.AddField( model_name='post', name='preview_text', field=models.CharField(blank=True, max_length=50), ), ] <file_sep>{% extends 'list/base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-12 col-md-10 mx-auto"> <div class="post"> <h1>Recipes ({{ posts.count }})</h1> <hr> {% for post in posts %} <a href="{% url 'post_detail' pk=post.pk %}"><img src="{{ post.image.url }}" class="post-image"/></a> <hr> <i class="fa fa-clock-o" style="font-size:20px">&nbsp;{{ post.prepare_time }}&nbsp;</i> <i class="fa fa-user" style="font-size:20px">&nbsp;{{ post.portions }}</i> <hr> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <h4>{{ post.preview_text }}</h4> <div class="info"> Posted by <strong>{{ post.author }}</strong> on {{ post.published_date }} <br><br> <a href="{% url 'post_detail' pk=post.pk %}"><span class="glyphicon glyphicon-envelope"></span> Comments: {{ post.comments.count }}</a> </div> <hr> {% endfor %} </div> </div> </div> </div> {% endblock %} <file_sep>from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ('image', 'title', 'prepare_time', 'portions', 'preview_text', 'ingredients', 'preperation') class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) content = forms.CharField( required=True, widget=forms.Textarea ) <file_sep>from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') image = models.ImageField(upload_to = 'recipe_images') title = models.CharField(max_length=200) prepare_time = models.CharField(max_length = 20, blank=True) portions = models.CharField(max_length = 20, blank=True) preview_text = models.CharField(max_length = 100, blank=True) ingredients = models.TextField() preperation = models.TextField(blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('list.Post', related_name='comments') author = models.ForeignKey('auth.User') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text <file_sep>from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^signup/$', views.signup, name='signup'), url(r'^login/$', auth_views.login, {'template_name': 'list/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'list/logout.html'}, name='logout'), url(r'^post/recipes/$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), url(r'^post/contact/$', views.contact, name='contact'), url(r'^post/recieved/$', views.message_recieved, name='message_recieved'), url(r'^post/(?P<pk>\d+)/delete/$', views.post_delete, name='post_delete'), url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
c2bb32679573b040ee6503a6f405bdce1e93e52b
[ "Python", "HTML" ]
5
Python
Carmen99/sharecipe
4bc93c587bf71ce3acb9185fa31c9f16f772497f
467ff060aaabd014b310a8d483150ec143166b53
refs/heads/master
<repo_name>sudahiroshi/signal_example<file_sep>/test.rb trap(:SIGHUP) do puts "SIGHUP !!" end trap(:SIGTERM) do puts "SIGTERM !!" end trap(:SIGKILL) do puts "SIGKILL !!" end loop do (Math.sqrt(rand(44)) ** 8).floor sleep 1 end <file_sep>/test3.rb class Sigtest attr_accessor :interval def initialize @interval = 1 trap(:SIGTERM) do @interval += 0.1 end trap(:SIGINT) do @interval -= 0.1 end end end sig = Sigtest.new loop do sleep sig.interval print "." end <file_sep>/README.md # signal_example UNIXのシグナルを確認するためのプログラムです。 Rubyで書いていますが、他の言語でも同じことができると思います。 下記のページを参考にしました。 https://blog.a-know.me/entry/2016/10/17/070111 ## プログラムの説明 ### test.rb シグナルが送られるとメッセージを表示するプログラムです。 対応しているシグナルはSIGHUPとSIGINTです。 ``` $ ruby test.rb ``` で実行します。 別のターミナルでPIDを調べ、以下のようにシグナルを送るとメッセージが表示されます。 (以下はPIDが9990の場合の例です) ``` $ kill 9990 $ kill -1 9990 $ kill -9 9990 ``` 上記のようにシグナルを送ると、下記のように順番にメッセージが表示されます。 なお、SIGKILLについては捕捉できずにプログラムが終了します。 ``` SIGTERM !! SIGHUP !! 強制終了 $ ``` ### test2.rb シグナルが送られた回数を表示するプログラムです。 なお、5秒に1回、回数を表示します。 ``` $ ruby test2.rb ``` で実行します。 その後、別のターミナルからシグナルを送ります。 (以下の例はPIDが9991の場合の例です) ``` $ kill 9991 $ kill 9991 $ kill 9991 ``` 上記のようにシグナルを送ると、下記のように順番にメッセージが表示されます。 ``` 0 0 1 1 2 2 2 2 2 3 3 ``` ### test3.rb インターバルにしたがって「.」を表示するプログラムです。 インターバルはシグナルで長くしたり短くしたりできます。 ``` $ ruby test3.rb ``` で実行します。 その後、別のターミナルからシグナルを送ります。 (以下の例はPIDが9992の場合の例です) ``` $ kill 9992 $ kill -2 9992 $ kill 9992 ``` 実際に動かさないと体感できませんが、以下のように表示されます。 ``` ..................... ``` <file_sep>/test2.rb class Sigtest attr_accessor :num def initialize @num = 0 trap(:SIGTERM) do @num += 1 end end end sig = Sigtest.new loop do sleep 5 puts "-> " + sig.num.to_s end
e1a40248d1e58c54c079b59cd1f21f244c29c8d7
[ "Markdown", "Ruby" ]
4
Ruby
sudahiroshi/signal_example
c8da35f0c5894876fd50f155b8a997eaadcbd526
9b09df17370cd82670206731121eb21866576759
refs/heads/master
<repo_name>vaibhaw2731/dataStructures<file_sep>/Queue/README.md Queue works on the principle of FIFO i.e. First in First Out. The code is the implementation of Queue having functions to perform following operations: 1) Insert an element in the queue 2) Delete an element from the queue 3) Display the elements of the queue <file_sep>/Queue/Queue.cpp #include<iostream> using namespace std; struct QueueNode //Node of queue { int data; struct QueueNode *next; }*front,*rear; //front and rear node reference of the queue void initialize() //intializing front and rear { front=NULL; rear=NULL; } void menu() //menu to select an action to perform { cout<<"Enter 1 to insert an element to the queue"<<endl; cout<<"Enter 2 to remove an item from the queue"<<endl; cout<<"Enter 3 to display the queue"<<endl; cout<<"Enter 4 to exit"<<endl; cout<<"Enter your choice: "; } void insert(int key) //insert an element in the queue { QueueNode *temp=new QueueNode(); //temporary node to store the given element temp->data=key; temp->next=NULL; if(front==NULL) { front =temp; rear=temp; } else { rear->next=temp; rear=temp; } } void remove() //remove the first element from the queue { QueueNode *temp; if(front==NULL) { cout<<"Queue Underflow"<<endl; } else { temp=front; cout<<"Element Deleted: "<<temp->data<<endl; front=front->next; free(temp); //free up memory occupied by the deleted element } } void display() //display all elements of the queue { QueueNode *temp; if(front==NULL) cout<<"Queue is empty"<<endl; else { temp=front; cout<<"Queue elements: "; while(temp!=NULL) { if(temp->next!=NULL) cout<<temp->data<<"->"; else cout<<temp->data<<endl; temp=temp->next; } } } int main() //driver function { initialize(); menu(); int ch; cin>>ch; cout<<endl; while(ch!=4) { switch(ch) { case 1: int key; cout<<"Enter an element to insert: "; cin>>key; insert(key); cout<<endl; break; case 2: remove(); break; case 3: display(); break; default: cout<<"Wrong choice, Try again"<<endl; } menu(); cin>>ch; cout<<endl; } }
134afc3b78855f11c6b3f8208cab442419571a68
[ "Markdown", "C++" ]
2
Markdown
vaibhaw2731/dataStructures
1f7528806fc129e37e986b5ef78a7ee210c076b0
f1f79cfd00215d30fd25c78541fa1b4e2489448d
refs/heads/master
<repo_name>Giampierospec/semaforoITLA<file_sep>/config.php <?php if($_POST){ file_put_contents('config.txt', json_encode($_POST)); header("Location:index.php"); } $datos = json_decode(file_get_contents('config.txt'),true); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Indie+Flower|Russo+One" rel="stylesheet"> <script src="https://use.fontawesome.com/01d9e54a7d.js"></script> <meta charset="utf-8"> <title>Interfaz de Admin</title> <link rel="stylesheet" href="css/semaforo.css"> <link rel="stylesheet" href="css/config.css"> </head> <body> <div class="container-fluid text-center"> <div class="jumbotron bg-dark-blue"> <h1>Escriba el intervalo para los semáforos</h1> <form class="form-horizontal" action="" method="post"> <div class="form-group input group"> <div class="row"> <div class="col-sm-6"> <label for="Green"><p>Introduzca el intervalo para el Verde </p></label> </div> <div class="col-sm-6"> <input type="number" name="Green" class="form-control" value="<?php echo $datos['Green']; ?>" required/> </div> </div> </div> <div class="form-group input-group"> <div class="row"> <div class="col-sm-6"> <label for="Red"><p>Introduzca el intervalo para el Rojo</p> </label> </div> <div class="col-sm-6"> <input type="number" name="Red" class="form-control" value="<?php echo $datos['Red']; ?>" /> </div> </div> </div> <div class="form-group input-group"> <div class="row"> <div class="col-sm-6"> <label for="Yellow"><p>Introduzca el intervalo para el Amarillo</p> </label> </div> <div class="col-sm-6"> <input type="number" name="Yellow" class="form-control" value="<?php echo $datos['Yellow']; ?>" /> </div> </div> </div> <button type="submit" class="btn btn-default"><i class="fa fa-paper-plane"></i> Guardar</button> </form> </div> </div> </body> </html> <file_sep>/index.php <?php if(!isset($_GET['calle'])){ header("Location:elegir.php"); } $calle = $_GET['calle']; $datos = json_decode(file_get_contents('config.txt'),true); $data_retrieved = (empty($datos['Red']))?0:'E'; ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Indie+Flower|Russo+One" rel="stylesheet"> <script src="https://use.fontawesome.com/01d9e54a7d.js"></script> <meta charset="utf-8"> <title>Semaforo Calle | <?php echo $calle ?></title> <link rel="stylesheet" href="css/semaforo.css"> </head> <body> <div class="container-fluid text-center"> <div class="jumbotron bg-dark-blue"> <h1>Semaforo Calle | <?php echo $calle ?></h1> <p class="caption">Este es el semáforo corriendo</p> <div id="traffic-light"> <div id="Red" class="bulb"></div> <div id="Yellow" class="bulb"></div> <div id="Green" class="bulb"></div> </div> <div id="message"> </div> </div> </div> <?php if($calle =='A'): ?> <script type="text/javascript"> var datos = '<?php echo $data_retrieved?>'; var tiempoRed = 0; var tiempoGreen = 0; var tiempoYellow = 0; if(datos == 0){ tiempoRed = datos; tiempoGreen = datos; tiempoYellow = datos; } else{ tiempoRed = <?php echo (empty($datos))?0:$datos['Red'];?> * 1000; tiempoGreen = <?php echo (empty($datos))?0:$datos['Green'];?> *1000; tiempoYellow = <?php echo (empty($datos))?0:$datos['Yellow'];?> *1000; } </script> <script src="js/semaforoa.js"></script> <?php endif;?> <?php if($calle =='B'): ?> <script src="js/semaforob.js"></script> <?php endif;?> </body> </html> <file_sep>/js/semaforob.js var red = document.getElementById("Red"); var yellow = document.getElementById("Yellow"); var green = document.getElementById("Green"); var color = "Red"; function ciclo(){ $.ajax({ url: 'server.php', method: 'get', success: function(info){ color = info; } }); if(color == 'Red'){ color = 'Green'; } else if(color == 'Green'){ color = 'Yellow'; } else if(color == 'Yellow'){ color = 'Red'; } clearLights(); $("#"+color).css("background-color",color.toLowerCase()); setTimeout(ciclo, 200); } function clearLights(){ red.style.backgroundColor = "#111"; yellow.style.backgroundColor = "#111"; green.style.backgroundColor = "#111"; } window.addEventListener("load", ciclo); <file_sep>/README.md # semaforo | ITLA Aqui subo el codigo en su mayoria que hizo posible que este semaforo funcionase
fae15b35fd55fae0b42f2dea20b894c19137906f
[ "JavaScript", "Markdown", "PHP" ]
4
PHP
Giampierospec/semaforoITLA
1705fa0c49811487b61d754386492b2d4ae82c3b
86841d1bf74704cf04f3c2e4ff116ea2ba43a99d
refs/heads/master
<repo_name>souflam/exampledata<file_sep>/exampleData.sql -- phpMyAdmin SQL Dump -- version 4.6.6 -- https://www.phpmyadmin.net/ -- -- Client : localhost:3306 -- Généré le : Ven 03 Novembre 2017 à 18:50 -- Version du serveur : 5.6.35 -- Version de PHP : 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Base de données : `exampleData` -- -- -------------------------------------------------------- -- -- Structure de la table `markers` -- CREATE TABLE `markers` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `lat` varchar(255) NOT NULL, `lng` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Contenu de la table `markers` -- INSERT INTO `markers` (`id`, `name`, `address`, `lat`, `lng`) VALUES (1, '<NAME> & <NAME>', '939 W El Camino Real, Mountain View, CA', '37.386339', '-122.085823'), (2, 'Amici\'s East Coast Pizzeria', '790 Castro St, Mountain View, CA', '37.38714', '-122.083235'), (3, 'Kapp\'s Pizza Bar & Grill', '191 Castro St, Mountain View, CA', '37.393885', '-122.078916'), (4, 'Round Table Pizza: Mountain View', '570 N Shoreline Blvd, Mountain View, CA', '37.402653', '-122.079354'), (5, 'Tony & Alba\'s Pizza & Pasta', '619 Escuela Ave, Mountain View, CA', '37.394011', '-122.095528'), (6, 'Oregano\'s Wood-Fired Pizza', '4546 El Camino Real, Los Altos, CA', '37.401724', '-122.114646'), (7, 'Round Table Pizza: Sunnyvale-Mary-Central Expy', '415 N Mary Ave, Sunnyvale, CA', '37.390038', '-122.042034'), (8, 'Giordano\'s', '730 N Rush St, Chicago, IL', '41.895729', '-87.625411'), (9, 'Filippi\'s Pizza Grotto', '1747 India St, San Diego, CA', '32.723831', '-117.168326'), (10, '<NAME>zeria', '439 N Wells St, Chicago, IL', '41.890346', '-87.633927'), (11, 'Sammy\'s Woodfired Pizza', '770 4th Ave, San Diego, CA', '32.713382', '-117.16118'), (12, 'Casa Bianca Pizza Pie', '1650 Colorado Blvd, Los Angeles, CA', '34.139159', '-118.204608'), (13, '<NAME>', '510 S Arroyo Pkwy, Pasadena, CA', '34.137003', '-118.147303'), (14, 'Pizzeria Paradiso', '2029 P St NW, Washington, DC', '38.90965', '-77.0459'), (15, 'Star Pizza', '2111 Norfolk St, Houston, TX', '29.732452', '-95.411058'), (16, 'Tutta Bella Neapolitan Pizzera', '4918 Rainier Ave S, Seattle, WA', '47.557704', '-122.284985'), (17, 'Touche Pasta Pizza Pool', '1425 NW Glisan St, Portland, OR', '45.526465', '-122.68558'), (18, 'Piecora\'s New York Pizza', '1401 E Madison St, Seattle, WA', '47.614005', '-122.313985'), (19, 'Pagliacci Pizza', '550 Queen Anne Ave N, Seattle, WA', '47.623942', '-122.356719'), (20, 'Zeeks Pizza - Phinney Ridge', '6000 Phinney Ave N, Seattle, WA', '47.67267', '-122.354092'), (21, 'Old Town Pizza', '226 NW Davis St, Portland, OR', '45.524557', '-122.67268'), (22, 'Zeeks Pizza - Belltown', '419 Denny Way, Seattle, WA', '47.618314', '-122.347998'), (23, 'Escape From New York Pizza', '622 NW 23rd Ave, Portland, OR', '45.527105', '-122.698509'), (24, 'Big Fred\'s Pizza Garden', '1101 S 119th St, Omaha, NE', '41.248662', '-96.09876'), (25, 'Old Chicago', '1111 Harney St, Omaha, NE', '41.25652', '-95.930683'), (26, 'Sgt Peffer\'s Cafe Italian', '1501 N Saddle Creek Rd, Omaha, NE', '41.273084', '-95.987816'), (27, 'Mama\'s Pizza', '715 N Saddle Creek Rd, Omaha, NE', '41.265883', '-95.980682'), (28, 'Zio\'s New York Style Pizzeria', '1213 Howard St, Omaha, NE', '41.25545', '-95.932022'), (29, 'Boston\'s Restaurant & Sports', '620 E Disk Dr, Rapid City, SD', '44.106938', '-103.205226'), (30, 'Zio\'s New York Style Pizzeria', '7834 W Dodge Rd, Omaha, NE', '41.26325', '-96.0564'), (31, 'La Casa Pizzaria', '4432 Leavenworth St, Omaha, NE', '41.2524', '-95.979578'), (32, 'Giordano\'s', '730 N Rush St, Chicago, IL', '41.895729', '-87.625411'), (33, '<NAME>\'s Pizzeria', '439 N Wells St, Chicago, IL', '41.890346', '-87.633927'), (34, 'Piece Restaurant', '1927 W North Ave, Chicago, IL', '41.910493', '-87.676127'), (35, 'Connie\'s Pizza Inc', '2373 S Archer Ave, Chicago, IL', '41.849213', '-87.641681'), (36, 'Exchequer Restaurant', '226 S Wabash Ave, Chicago, IL', '41.879189', '-87.626079'), (37, 'Coco\'s By The Falls', '5339 Murray Street, Niagara Falls, Ontario', '43.083555', '-79.082706'), (38, 'Pompei', '1531 W Taylor St, Chicago, IL', '41.869301', '-87.664779'), (39, 'Lynn\'s Paradise Cafe', '984 Barret Ave, Louisville, KY', '38.23693', '-85.72854'), (40, 'Otto Restaurant Enoteca Pizza', '1 5th Ave, New York, NY', '40.732161', '-73.996321'), (41, 'Grimaldi\'s', '19 Old Fulton St, Brooklyn, NY', '40.702515', '-73.993733'), (42, 'Lombardi\'s', '32 Spring St, New York, NY', '40.721675', '-73.995595'), (43, '<NAME>', '278 Bleecker St, New York, NY', '40.731706', '-74.003271'), (44, '<NAME>', '260 W 44th St, New York, NY', '40.758072', '-73.987736'), (45, 'Burger Joint', '2175 Broadway, New York, NY', '40.782398', '-73.981'), (46, '<NAME>', '157 Wooster St, New Haven, CT', '41.302803', '-72.917042'), (47, 'Adrianne\'s Pizza Bar', '54 Stone St, New York, NY', '40.70448', '-74.010137'), (48, 'Pizzeria Regina: Regina Pizza', '11 1/2 Thacher St, Boston, MA', '42.365338', '-71.056832'), (49, 'Upper Crust', '20 Charles St, Boston, MA', '42.356607', '-71.069681'), (50, 'Bertucci\'s Brick Oven Rstrnt', '4 Brookline Pl, Brookline, MA', '42.331917', '-71.115311'), (51, 'Aquitaine', '569 Tremont St, Boston, MA', '42.343637', '-71.072265'), (52, 'Bertucci\'s Brick Oven Rstrnt', '43 Stanhope St, Boston, MA', '42.348299', '-71.073249'), (53, 'Upper Crust', '286 Harvard St, Brookline, MA', '42.342856', '-71.122311'), (54, 'Bertucci\'s Brick Oven Rstrnt', '799 Main St, Cambridge, MA', '42.363259', '-71.09721'), (55, 'Bertucci\'s Brick Oven Rstrnt', '22 Merchants Row, Boston, MA', '42.359146', '-71.055477'), (56, '<NAME>', '317 W Bryan St, Savannah, GA', '32.081152', '-81.094992'), (57, 'Domino\'s Pizza: Myrtle Beach', '1706 S Kings Hwy # A, Myrtle Beach, SC', '33.67488', '-78.905143'), (58, 'East of Chicago Pizza Company', '3901 North Kings Highway Suite 1, Myrtle Beach, SC', '33.716097', '-78.855582'), (59, 'Villa Tronco Italian Rstrnt', '1213 Blanding St, Columbia, SC', '34.008048', '-81.036314'), (60, 'Mellow Mushroom Pizza Bakers', '11 W Liberty St, Savannah, GA', '32.074673', '-81.093699'), (61, 'Andolinis Pizza', '82 Wentworth St, Charleston, SC', '32.78233', '-79.934236'), (62, 'Mellow Mushroom Pizza Bakers', '259 E Broad St, Athens, GA', '33.9578', '-83.37466'), (63, 'Bucks Pizza of Edisto Beach Inc', '114 Jungle Rd, Edisto Island, SC', '32.503973', '-80.297947'), (64, 'Anthony\'s Coal Fired Pizza', '2203 S Federal Hwy, Fort Lauderdale, FL', '26.094671', '-80.136689'), (65, 'Giordano\'s', '12151 S Apopka Vineland Rd, Orlando, FL', '28.389367', '-81.506222'), (66, 'Pizza Rustica', '863 Washington Ave, Miami Beach, FL', '25.779059', '-80.133107'), (67, 'Mama Jennie\'s Italian Restaurant', '11720 Ne 2nd Ave, North Miami, FL', '25.882782', '-80.19429'), (68, 'Anthony\'s Coal Fired Pizza', '17901 Biscayne Blvd, Aventura, FL', '25.941116', '-80.148826'), (69, 'Anthony\'s Coal Fired Pizza', '4527 Weston Rd, Weston, FL', '26.065395', '-80.362442'), (70, 'Mario the Baker Pizza & Italian Restaurant', '13695 W Dixie Hwy, North Miami, FL', '25.92974', '-80.15609'), (71, 'Big Cheese Pizza', '8080 SW 67th Ave, Miami, FL', '25.696025', '-80.301113'), (72, 'Ingleside Village Pizza', '2396 Ingleside Ave, Macon, GA', '32.85376', '-83.657406'), (73, 'Ciao Bella Pizza Da Guglielmo', '29 Highway 98 E, Destin, FL', '30.395556', '-86.512093'), (74, 'Papa John\'s Pizza', '810 Russell Pkwy, Warner Robins, GA', '32.593911', '-83.637075'), (75, 'Papa John\'s Pizza: East Central Montgomery', '2525 Madison Ave, Montgomery, AL', '32.381121', '-86.273035'), (76, 'Cici\'s Pizza', '6268 Atlanta Hwy, Montgomery, AL', '32.382205', '-86.190675'), (77, 'Papa John\'s Pizza', '1210 E Jackson St, Thomasville, GA', '30.849129', '-83.963428'), (78, 'Papa John\'s Pizza', '711 N Westover Blvd # G, Albany, GA', '31.61397', '-84.22308'), (79, 'Mellow Mushroom Pizza Bakers', '6100 Veterans Pkwy, Columbus, GA', '32.532078', '-84.955894'), (80, 'Star Pizza', '2111 Norfolk St, Houston, TX', '29.732452', '-95.411058'), (81, 'Star Pizza II', '77 Harvard St, Houston, TX', '29.770751', '-95.396042'), (82, 'Brothers Pizzeria', '1029 Highway 6 N # 100, Houston, TX', '29.768337', '-95.643594'), (83, '11th Street Cafe Inc', '748 E 11th St, Houston, TX', '29.790794', '-95.388921'), (84, 'California Pizza Kitchen', '1705 Post Oak Blvd # A, Houston, TX', '29.750172', '-95.461199'), (85, 'Collina\'s Italian Cafe', '3835 Richmond Ave, Houston, TX', '29.73262', '-95.438964'), (86, 'Barry\'s Pizza & Italian Diner', '6003 Richmond Ave, Houston, TX', '29.73143', '-95.484382'), (87, 'Mario\'s Seawall Italian Restaurant', '628 Seawall Blvd, Galveston, TX', '29.304542', '-94.772598'), (88, 'Campisi\'s Egyptian Restaurant', '5610 E Mockingbird Ln, Dallas, TX', '32.83651', '-96.771781'), (89, 'Fat Joe\'s Pizza Pasta & Bar', '4721 W Park Blvd # 101, Plano, TX', '33.027055', '-96.788912'), (90, 'Saccone\'s Pizza', '13812 N Highway 183, Austin, TX', '29.569507', '-97.964663'), (91, 'Fireside Pies', '2820 N Henderson Ave, Dallas, TX', '32.819762', '-96.784148'), (92, 'Romeo\'s', '1500 Barton Springs Rd, Austin, TX', '30.261526', '-97.760022'), (93, 'Sandella\'s Cafe', '5910 N Macarthur Blvd, Irving, TX', '32.892002', '-96.961188'), (94, 'Mangia Chicago Stuffed Pizza', '3500 Guadalupe St, Austin, TX', '30.301543', '-97.739112'), (95, '<NAME>', '508 West Ave, Austin, TX', '30.269393', '-97.750889'), (96, 'Filippi\'s Pizza Grotto', '1747 India St, San Diego, CA', '32.723831', '-117.168326'), (97, 'Pizzeria Bianco', '623 E Adams St, Phoenix, AZ', '33.449377', '-112.065521'), (98, 'Sammy\'s Woodfired Pizza', '770 4th Ave, San Diego, CA', '32.713382', '-117.16118'), (99, 'Casa Bianca Pizza Pie', '1650 Colorado Blvd, Los Angeles, CA', '34.139159', '-118.204608'), (100, 'Park<NAME>', '510 S Arroyo Pkwy, Pasadena, CA', '34.137003', '-118.147303'), (101, 'California Pizza Kitchen', '330 S Hope St, Los Angeles, CA', '34.05333', '-118.252683'), (102, 'B J\'s Pizza & Grill', '200 Main St # 101, Huntington Beach, CA', '33.658058', '-118.001101'), (103, 'B J\'s Restaurant & Brewhouse', '280 S Coast Hwy, Laguna Beach, CA', '33.54209', '-117.783516'), (104, 'Giuseppe\'s Depot Restaurant', '10 S Sierra Madre St, Colorado Springs, CO', '38.834548', '-104.828297'), (105, 'Beau Jo\'s Pizza', '2710 S Colorado Blvd, Denver, CO', '39.667342', '-104.940708'), (106, 'Pasquini\'s Pizzeria', '1310 S Broadway, Denver, CO', '39.692824', '-104.987463'), (107, 'Fargos Pizza Co', '2910 E Platte Ave, Colorado Springs, CO', '38.839847', '-104.774423'), (108, 'Old Chicago', '1415 Market St, Denver, CO', '39.748177', '-105.000501'), (109, 'Sink', '1165 13th St, Boulder, CO', '40.00821', '-105.276236'), (110, 'Ligori\'s Pizza & Pasta', '4421 Harrison Blvd, Ogden, UT', '41.182732', '-111.949199'), (111, 'Old Chicago', '1102 Pearl St, Boulder, CO', '40.017591', '-105.28099'), (112, 'Boston\'s Restaurant & Sports', '620 E Disk Dr, Rapid City, SD', '44.106938', '-103.205226'), (113, 'Chuck E Cheese\'s Pizza', '100 24th St W # B, Billings, MT', '45.771355', '-108.57629'), (114, 'Space Aliens Grill & Bar', '1304 E Century Ave, Bismarck, ND', '46.83808', '-100.771734'), (115, '2nd Street Bistro', '123 North 2nd Street, Livingston, MT', '45.661014', '-110.561422'), (116, 'Domino\'s Pizza', '1524 S Broadway # 1, Minot, ND', '48.219657', '-101.296037'), (117, 'American Classic Pizzeria', '1744 Grand Ave, Billings, MT', '45.78412', '-108.560205'), (118, 'Godfather\'s Pizza', '905 Main St, Billings, MT', '45.81508', '-108.470758'), (119, 'Papa John\'s Pizza', '605 Main St, Billings, MT', '45.810222', '-108.472125'), (120, 'Aardvark Pizza & Sub', '304A Caribou St, Banff, AB', '51.176488', '-115.570751'), (121, 'Jasper Pizza Place', '402 Connaught Dr, Jasper, AB', '52.879085', '-118.079319'), (122, 'Odyssey Pizza & Steak House', '3-3814 Bow Trail SW, Calgary, AB', '51.045233', '-114.141249'), (123, 'Basil\'s Pizza', '2118 33 Avenue SW, Calgary, AB', '51.023981', '-114.109903'), (124, 'Castle Pizza & Donair', '7724 Elbow Drive SW, Calgary, AB', '50.984497', '-114.08315'), (125, 'Santa Lucia Italian Restaurant', '714 8 St, Canmore, AB', '51.089195', '-115.358733'), (126, 'Tops Pizza & Steak House No 3', '7-5602 4 Street NW, Calgary, AB', '51.101205', '-114.071458'), (127, 'Evvia Restaurant', '837 Main St, Canmore, AB', '51.089177', '-115.361767'), (128, 'D&#39;Bronx', '3904 Bell St, Kansas City, MO', '39.057182', '-94.606105'), (129, 'Cicero\'s Restaurant & Entrtnmt', '6691 Delmar Blvd, St Louis, MO', '38.656308', '-90.308439'), (130, 'Hideaway Pizza', '6616 N Western Ave, Oklahoma City, OK', '35.539114', '-97.52976'), (131, 'Fortel\'s Pizza Den', '7932 Mackenzie Rd, St Louis, MO', '38.566441', '-90.320792'), (132, 'Hideaway Pizza', '7877 E 51st St, Tulsa, OK', '36.089897', '-95.889241'), (133, 'Farotto\'s Catering', '9525 Manchester Rd, Webster Groves, MO', '38.609327', '-90.364435'), (134, 'California Pizza Kitchen', '1493 Saint Louis Galleria, St Louis, MO', '38.633613', '-90.345949'), (135, 'D\'Bronx', '2450 Grand Blvd # 124, Kansas City, MO', '39.082723', '-94.58178'), (136, 'Giuseppe\'s Depot Restaurant', '10 S Sierra Madre St, Colorado Springs, CO', '38.834548', '-104.828297'), (137, 'Beau Jo\'s Pizza', '2710 S Colorado Blvd, Denver, CO', '39.667342', '-104.940708'), (138, 'Pasquini\'s Pizzeria', '1310 S Broadway, Denver, CO', '39.692824', '-104.987463'), (139, 'Fargos Pizza Co', '2910 E Platte Ave, Colorado Springs, CO', '38.839847', '-104.774423'), (140, 'Old Chicago', '1415 Market St, Denver, CO', '39.748177', '-105.000501'), (141, 'Sink', '1165 13th St, Boulder, CO', '40.00821', '-105.276236'), (142, 'Old Chicago', '1102 Pearl St, Boulder, CO', '40.017591', '-105.28099'), (143, 'Gondolier', '1738 Pearl St, Boulder, CO', '40.019345', '-105.272946'), (144, 'Ligori\'s Pizza & Pasta', '4421 Harrison Blvd, Ogden, UT', '41.182732', '-111.949199'), (145, 'Brick Oven Restaurant', '111 E 800 N, Provo, UT', '40.244493', '-111.656322'), (146, 'Zachary\'s Chicago Pizza', '5801 College Ave, Oakland, CA', '37.846179', '-122.251951'), (147, 'Zachary\'s Chicago Pizza', '1853 Solano Ave, Berkeley, CA', '37.891407', '-122.27843'), (148, 'Cheese Board Pizza', '1512 Shattuck Ave, Berkeley, CA', '37.879976', '-122.269275'), (149, 'Goat Hill Pizza', '300 Connecticut St, San Francisco, CA', '37.762431', '-122.397617'), (150, '<NAME>', '1042 Kearny St, San Francisco, CA', '37.797388', '-122.405374'), (151, 'Little Star Pizza LLC', '846 Divisadero St, San Francisco, CA', '37.77752', '-122.438215'), (152, 'Pauline\'s Pizza', '260 Valencia, San Francisco, CA', '37.768725', '-122.422245'), (153, 'Villa Romana Pizzeria & Rstrnt', '731 Irving St, San Francisco, CA', '37.764074', '-122.465581'), (154, 'Amici\'s East Coast Pizzeria', '69 E 3rd Ave, San Mateo, CA', '37.563896', '-122.32472'), (155, 'Amici\'s East Coast Pizzeria', '226 Redwood Shores Pkwy, Redwood City, CA', '37.520516', '-122.252255'), (156, 'North Beach Pizza', '240 E 3rd Ave, San Mateo, CA', '37.565325', '-122.322643'), (157, 'Patxi\'s Chicago Pizza', '441 Emerson St, Palo Alto, CA', '37.445148', '-122.163553'), (158, 'Pizz\'a Chicago', '4115 El Camino Real, Palo Alto, CA', '37.414106', '-122.126223'), (159, 'California Pizza Kitchen', '531 Cowper St, Palo Alto, CA', '37.448075', '-122.158813'), (160, 'Windy City Pizza', '35 Bovet Rd, San Mateo, CA', '37.551562', '-122.314525'), (161, 'Applewood Pizza 2 Go', '1001 El Camino Real, Menlo Park, CA', '37.452966', '-122.181722'), (162, 'Pizza Antica', '334 Santana Row # 1065, San Jose, CA', '37.321792', '-121.947735'), (163, 'Pizz\'a Chicago', '155 W San Fernando St, San Jose, CA', '37.333277', '-121.891677'), (164, 'House of Pizza', '527 S Almaden Ave, San Jose, CA', '37.326353', '-121.888165'), (165, 'Amici\'s East Coast Pizzeria', '225 W Santa Clara St, San Jose, CA', '37.334702', '-121.894045'), (166, 'Fiorillo\'s Restaurant', '638 El Camino Real, Santa Clara, CA', '37.354603', '-121.942577'), (167, 'Tony & Alba\'s Pizza & Pasta', '3137 Stevens Creek Blvd, San Jose, CA', '37.323297', '-121.951646'), (168, 'Giorgio\'s', '1445 Foxworthy Ave, San Jose, CA', '37.274648', '-121.892893'), (169, 'Round Table Pizza', '4302 Moorpark Ave, San Jose, CA', '37.315903', '-121.977925'); -- -- Index pour les tables exportées -- -- -- Index pour la table `markers` -- ALTER TABLE `markers` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT pour les tables exportées -- -- -- AUTO_INCREMENT pour la table `markers` -- ALTER TABLE `markers` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=170;
026db937ae64dbfd57c0e0a6908e94f3c25cbdd6
[ "SQL" ]
1
SQL
souflam/exampledata
61b179e0669f98de217786df2449c9edd224c4ab
f3c1e49b4d2c565b59fa16d60ee039d392a8a8b8
refs/heads/master
<file_sep><?php namespace Overblog\ThriftBundle\Server; use Overblog\ThriftBundle\Server\Server; use Thrift\Server\TServerSocket; use Thrift\Factory\TTransportFactory; use Thrift\Factory\TBinaryProtocolFactory; /** * Socket Server class * @author <NAME> */ class SocketServer extends Server { /** * Run socket server * * @param string $host * @param int $port */ public function run($host = 'localhost', $port = 9090) { $transport = new TServerSocket($host, $port); $outputTransportFactory = $inputTransportFactory = new TTransportFactory($transport); $outputProtocolFactory = $inputProtocolFactory = new TBinaryProtocolFactory(); // Do we use fork ? $fork = 'Thrift\\Server\\' . ($this->config['fork'] ? 'TForkingServer' : 'TSimpleServer'); $server = new $fork( $this->processor, $transport, $inputTransportFactory, $outputTransportFactory, $inputProtocolFactory, $outputProtocolFactory ); $server->serve(); } }<file_sep><?php namespace Overblog\ThriftBundle\Server; /** * Abstract class to create a server * @author <NAME> */ abstract class Server { /** * Thrift Processor */ protected $processor; /** * Configuration * @var array */ protected $config; /** * Load dependencies * @param mixed $processor * @param array $config */ public function __construct($processor, Array $config) { $this->processor = $processor; $this->config = $config; } /** * Return thrif header */ public function getHeader() { header('Content-Type: application/x-thrift'); } /** * Run the server */ abstract public function run(); }<file_sep><?php /** * UNIT TEST * * @author <NAME> */ namespace Overblog\ThriftBundle\Tests\Command; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernelMock extends Kernel { public function registerBundles() { } public function registerContainerConfiguration(LoaderInterface $loader) { } }<file_sep><?php namespace Overblog\ThriftBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Overblog\ThriftBundle\CacheWarmer\ThriftCompileCacheWarmer; use Overblog\ThriftBundle\Listener\ClassLoaderListener; /** * Description of FactoryPass * * @author xavier */ class FactoryPass implements CompilerPassInterface { /** * You can modify the container here before it is dumped to PHP code. * * @param ContainerBuilder $container * * @return void * * @api */ function process(ContainerBuilder $container) { $cacheDir = $container->getParameter('kernel.cache_dir'); $warmer = new ThriftCompileCacheWarmer( $cacheDir, $container->getParameter('kernel.root_dir'), $container->getParameter('thrift.config.compiler.path'), $container->getParameter('thrift.config.services') ); $warmer->compile(); // Init Class Loader ClassLoaderListener::registerClassLoader($cacheDir); } } <file_sep><?php namespace Overblog\ThriftBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Overblog\ThriftBundle\Server\HttpServer; use Symfony\Component\HttpFoundation\Request; /** * Http Server controller * @author <NAME> */ class ThriftController extends Controller { /** * HTTP Entry point */ public function serverAction(Request $request) { if(!($extensionName = $request->get('extensionName'))) { throw $this->createNotFoundException('Unable to get config name'); } $servers = $this->container->getParameter('thrift.config.servers'); if(!isset($servers[$extensionName])) { throw $this->createNotFoundException(sprintf('Unknown config "%s"', $extensionName)); } $server = $servers[$extensionName]; $server = new HttpServer( $this->container->get('thrift.factory')->getProcessorInstance( $server['service'], $this->container->get($server['handler']) ), $server['service_config'] ); $server->getHeader(); $server->run(); // Much faster than return a Symfony Response exit(0); } } <file_sep><?php namespace Overblog\ThriftBundle\Tests\Factory; use Overblog\ThriftBundle\Tests\ThriftBundleTestCase; use Overblog\ThriftBundle\Factory\ThriftFactory; /** * UNIT TEST * * @author <NAME> */ class ThriftFactoryTest extends ThriftBundleTestCase { protected function setUp() { parent::setUp(); parent::compile(); } public function testFactory() { $factory = new ThriftFactory(array( 'test' => array( 'definition' => 'Test', 'className' => 'TestService', 'namespace' => 'ThriftModel\Test' ) )); $this->assertInstanceOf( 'ThriftModel\Test\Test', $factory->getInstance('ThriftModel\Test\Test') ); $this->assertInstanceOf( 'ThriftModel\Test\Test', $factory->getInstance('ThriftModel\Test\Test', array()) ); $this->assertInstanceOf( 'ThriftModel\Test\State', $factory->getInstance('ThriftModel\Test\State') ); $this->assertInstanceOf( 'ThriftModel\Test\InvalidValueException', $factory->getInstance('ThriftModel\Test\InvalidValueException') ); $this->assertInstanceOf( 'ThriftModel\Test\TestServiceProcessor', $factory->getProcessorInstance('test', null) ); $this->assertInstanceOf( 'ThriftModel\Test\TestServiceClient', $factory->getClientInstance('test', null) ); } } <file_sep><?php namespace Overblog\ThriftBundle\Exception; /** * Configuration Exception * @author <NAME> */ class ConfigurationException extends \Exception { /** * Create exception and set message * @param string $message */ public function __construct($message) { parent::__construct($message, null, null); } /** * Return the message * @return String */ public function __toString() { return $this->message; } }<file_sep><?php namespace Overblog\ThriftBundle\Tests; use Overblog\ThriftBundle\Compiler\ThriftCompiler; use Symfony\Component\ClassLoader\MapClassLoader; use Symfony\Component\ClassLoader\ClassMapGenerator; class ThriftBundleTestCase extends \PHPUnit_Framework_TestCase { protected $modelPath; protected $definitionPath; protected $namespace = 'Overblog\ThriftBundle\Tests'; protected $compiler; protected function setUp() { $this->modelPath = __DIR__ . '/thrift'; $this->definitionPath = __DIR__ . '/ThriftDefinition/Test.thrift'; } protected function compile() { //Build cache $this->compiler = new ThriftCompiler(); $this->compiler->setModelPath($this->modelPath); $this->compiler->compile($this->definitionPath, true); // Init Loader $l = new MapClassLoader(ClassMapGenerator::createMap($this->modelPath)); $l->register(); } protected function tearDown() { exec(sprintf('rm -rf %s 2>&1 > /dev/null', $this->modelPath)); } protected function onNotSuccessfulTest($e) { exec(sprintf('rm -rf %s 2>&1 > /dev/null', $this->modelPath)); parent::onNotSuccessfulTest($e); } }<file_sep><?php namespace Overblog\ThriftBundle\Client; use Overblog\ThriftBundle\Client\Client; use Thrift\Transport\THttpClient; /** * HTTP Client * @author <NAME> */ class HttpClient extends Client { /** * Instanciate Socket Client * * @return Thrift\Transport\THttpClient */ protected function createSocket() { $host = current($this->config['hosts']); $url = parse_url($this->config['type'] . '://' . $host['host']); $socket = new THttpClient($url['host'], $host['port'], $url['path']); if (!empty($host['httpTimeoutSecs'])) { $socket->setTimeoutSecs($host['httpTimeoutSecs']); } return $socket; } }<file_sep><?php namespace Overblog\ThriftBundle\Exception; /** * This exception is throw when a compilation error is encountered * * @author <NAME> <<EMAIL>> */ class CompilerException extends \Exception {} <file_sep><?php namespace Overblog\ThriftBundle\Factory; /** * Thrift factory * * @author <NAME> */ class ThriftFactory { protected $services; /** * Inject dependencies * @param array $services */ public function __construct(Array $services) { $this->services = $services; } /** * Return an instance of a Thrift Model Class * * @param string $classe * @param mixed $param * @return Object */ public function getInstance($classe, $param = null) { if(is_null($param)) { return new $classe(); } else { return new $classe($param); } } /** * Return a processor instance * * @param string $service * @param mixed $handler * @return Object */ public function getProcessorInstance($service, $handler) { $classe = sprintf('%s\%sProcessor', $this->services[$service]['namespace'], $this->services[$service]['className']); return new $classe($handler); } /** * Return a client instance * * @param string $service * @param Thrift\Protocol\TProtocol $protocol * @return Object */ public function getClientInstance($service, $protocol) { $classe = sprintf('%s\%sClient', $this->services[$service]['namespace'], $this->services[$service]['className']); return new $classe($protocol); } }<file_sep><?php namespace Overblog\ThriftBundle\Tests\Client; use ThriftModel\Test\Test; use Overblog\ThriftBundle\Factory\ThriftFactory; class TestHandler { protected $factory; public function __construct(ThriftFactory $factory) { $this->factory = $factory; } public function ping() { } public function get($id) { if($id == -1) { $e = $this->factory->getInstance('ThriftModel\Test\InvalidValueException', array( 'error_code' => 100, 'error_msg' => 'ERROR' )); throw $e; } $test = $this->factory->getInstance('ThriftModel\Test\Test', array( 'id' => $id, 'content' => 'TEST' )); return $test; } public function getList($id) { $test = $this->get($id); $test1 = clone $test; $test1->content = 'TEST2'; return array($test, $test1); } public function create($test) { if(empty($test->content)) { $e = $this->factory->getInstance('ThriftModel\Test\InvalidValueException', array( 'error_code' => 100, 'error_msg' => 'ERROR' )); throw $e; } return true; } }<file_sep><?php namespace Overblog\ThriftBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Overblog\ThriftBundle\DependencyInjection\Compiler\FactoryPass; /** * Overblog Thrift Bundle * @author <NAME> */ class OverblogThriftBundle extends Bundle { /** * Builds the bundle. * * It is only ever called once when the cache is empty. * * This method can be overridden to register compilation passes, * other extensions, ... * * @param ContainerBuilder $container A ContainerBuilder instance */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new FactoryPass()); } } <file_sep><?php namespace Overblog\ThriftBundle\Client; /** * PHPUnit Mock of a Thrift Client * * @author <NAME> <<EMAIL>> */ class ThriftTestClientPhpunit extends \PHPUnit_Framework_TestCase {} <file_sep><?php namespace Overblog\ThriftBundle\Server; use Overblog\ThriftBundle\Server\Server; use Thrift\Transport\TBufferedTransport; use Thrift\Transport\TPhpStream; /** * HTTP Server class * @author <NAME> */ class HttpServer extends Server { /** * Run server */ public function run() { $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W)); $protocol = new $this->config['protocol']($transport, true, true); $transport->open(); $this->processor->process($protocol, $protocol); $transport->close(); } }<file_sep><?php namespace Overblog\ThriftBundle\Compiler; use Overblog\ThriftBundle\Exception\ConfigurationException; /** * Thrift compiler * @author <NAME> */ class ThriftCompiler { /** * Thrift Executable name * @var string */ protected $thriftExec = 'thrift'; /** * Thrift Executable path * @var string */ protected $thriftPath = '/usr/local/bin/'; /** * Model Path * @var string */ protected $modelPath; /** * Included dirs * @var string[] */ protected $includeDirs = array(); /** * Base compiler options * @var array */ protected $options = array('oop' => null); /** * Last compiler output * @var string */ protected $lastOutput; /** * Return Thrift path * @return string */ protected function getExecPath() { return $this->thriftPath . $this->thriftExec; } /** * Set exec path * @param string $path * @return bool */ public function setExecPath($path) { if('/' !== substr($path, -1)) { $path .= '/'; } $this->thriftPath = $path; return $this->checkExec(); } /** * Check if Thrift exec is installed * @throws \Overblog\ThriftBundle\Exception\ConfigurationException * @return boolean */ protected function checkExec() { if(!file_exists($this->getExecPath())) { throw new ConfigurationException('Unable to find Thrift executable'); } return true; } /** * Set model path and create it if needed * @param string $path */ public function setModelPath($path) { if(!is_null($path) && !file_exists($path)) { mkdir($path); } $this->modelPath = $path; } /** * Add a directory to the list of directories searched for include directives * @param string[] $includeDirs */ public function setIncludeDirs($includeDirs) { $this->includeDirs = (array)$includeDirs; } /** * Set namespace prefix * @param string $namespace */ public function setNamespacePrefix($namespace) { $this->options['nsglobal'] = escapeshellarg($namespace); } /** * Generate PHP validator methods */ public function addValidate() { $this->options['validate'] = null; } /** * Compile server files too (processor) */ protected function addServerCompile() { if(!isset($this->options['server'])) { $this->options['server'] = null; } } /** * Compile the thrift options * @return string */ protected function compileOptions() { $return = array(); foreach($this->options as $option => $value) { $return[] = $option . (!empty($value) ? '=' . $value : ''); } return implode(',', $return); } /** * Compile the Thrift definition * @param string $definition * @param boolean $serverCompile * @throws \Overblog\ThriftBundle\Exception\ConfigurationException * @return boolean */ public function compile($definition, $serverCompile = false) { // Check if definition file exists if(!file_exists($definition)) { throw new ConfigurationException(sprintf('Unable to find Thrift definition at path "%s"', $definition)); } if(true === $serverCompile) { $this->addServerCompile(); } // prepare includeDirs $includeDirs = ''; foreach ($this->includeDirs as $includeDir) { $includeDirs .= ' -I '. $includeDir; } //Reset output $this->lastOutput = null; $cmd = sprintf( '%s -r -v --gen php:%s --out %s %s %s 2>&1', $this->getExecPath(), $this->compileOptions(), $this->modelPath, $includeDirs, $definition ); exec($cmd, $this->lastOutput, $return); return (0 === $return) ? true : false; } /** * Return the last compiler output * @return string */ public function getLastOutput() { return $this->lastOutput; } }<file_sep><?php /** * UNIT TEST * * @author <NAME> */ namespace Overblog\ThriftBundle\Tests\Command; class ServerTest extends \PHPUnit_Framework_TestCase { protected function setUp() { } public function testServer() { } }<file_sep><?php namespace Overblog\ThriftBundle\Routing; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; class ThriftRoutingLoader extends Loader { protected $services; public function __construct($services) { $this->services = $services; } /** * Loads a resource. * * @param mixed $resource The resource * @param string|null $type The resource type or null if unknown * * @throws \Exception If something went wrong */ public function load($resource, $type = null) { $coll = new RouteCollection(); foreach ($this->services as $path => $service) { $route = new Route( '/'.$path, array('_controller' => 'ThriftBundle:Thrift:server', 'extensionName' => $path), array(), array(), null, array(), array('post') ); $coll->add('thrift.' . $service['service'], $route); } return $coll; } /** * Returns whether this class supports the given resource. * * @param mixed $resource A resource * @param string|null $type The resource type or null if unknown * * @return bool True if this class supports the given resource, false otherwise */ public function supports($resource, $type = null) { return 'thrift' == $type; } } <file_sep><?php namespace Overblog\ThriftBundle\Client; use Overblog\ThriftBundle\Client\ThriftClient; use Overblog\ThriftBundle\Client\ThriftTestClientPhpunit; /** * ThriftTestClient is used to replace Thrift Client by a PhpUnit Mocked version * * @author <NAME> <<EMAIL>> */ class ThriftTestClient extends ThriftClient { /** * @inheritdoc */ public function getClient() { if(is_null($this->client)) { $className = sprintf( '%s\%sClient', $this->config['service_config']['namespace'], $this->config['service_config']['className'] ); // Init Mock $phpunit = new ThriftTestClientPhpunit(); $this->client = $phpunit->getMockBuilder($className) ->disableOriginalConstructor() ->getMock(); } return $this->client; } } <file_sep><?php namespace Overblog\ThriftBundle\Client; /** * Abstract class for create a client * @author <NAME> */ abstract class Client { /** * Config handler * @var array */ protected $config; /** * Socket instance * @var Thrift\Transport\TSocket */ protected $socket; /** * Register dependencies * @param array $config */ public function __construct(Array $config) { $this->config = $config; } /** * Return socket * * @return Thrift\Transport\TSocket */ public function getSocket() { if(is_null($this->socket)) { $this->socket = $this->createSocket(); } return $this->socket; } /** * Insctanciate socket * * @return Thrift\Transport\TSocket */ abstract protected function createSocket(); }<file_sep><?php namespace Overblog\ThriftBundle\Client; use Overblog\ThriftBundle\Client\Client; use Thrift\Transport\TSocket; use Thrift\Transport\TSocketPool; /** * Socket Client * @author <NAME> */ class SocketClient extends Client { /** * Instanciate Socket Client * * @return Thrift\Transport\TSocket */ protected function createSocket() { $nbHosts = count($this->config['hosts']); if($nbHosts == 1) { $host = current($this->config['hosts']); $socket = new TSocket($host['host'], $host['port']); if (!empty($host['recvTimeout'])) $socket->setRecvTimeout($host['recvTimeout']); if (!empty($host['sendTimeout'])) $socket->setSendTimeout($host['sendTimeout']); } else { $hosts = array(); $ports = array(); foreach($this->config['hosts'] as $host) { $hosts[] = $host['host']; $ports[] = $host['port']; } $socket = new TSocketPool($hosts, $ports); if (!empty($host['recvTimeout'])) $socket->setRecvTimeout($host['recvTimeout']); if (!empty($host['sendTimeout'])) $socket->setSendTimeout($host['sendTimeout']); } return $socket; } }
0766c5615c676d4560ed170bfeb54b824c1bb2f8
[ "PHP" ]
21
PHP
mcg-web/ThriftBundle
480a0e60811062d4b54c0688973c5c6be226ef30
4f20db60b2326006bcf8a648e3ba25231b5f6a26
refs/heads/master
<repo_name>dzzy/RelayGreenHouse<file_sep>/relaytest.py import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # init list with pin numbers relays = {1:17,2:27,3:22,4:23} #outlet:gpio mapping # loop through relays and set mode and state to 'high' for i in relays: GPIO.setup(relays[i], GPIO.OUT) GPIO.output(relays[i], GPIO.HIGH) # time to sleep between operations in the main loop SleepTimeL = 1 while True: try: for i in relays: GPIO.output(relays[i], GPIO.LOW) time.sleep(5) for i in relays: GPIO.output(relays[i], GPIO.HIGH) time.sleep(5) except KeyboardInterrupt: # turn the relay off set_relay(False) # Reset GPIO settings GPIO.cleanup() print("\nExiting\n") # exit the application sys.exit(0)<file_sep>/sensortest.py import Adafruit_DHT import time DHT_SENSOR = Adafruit_DHT.DHT22 SENSOR_PIN_1=9 SENSOR_PIN_2=10 while True: humidity1, temperature1 = Adafruit_DHT.read_retry(DHT_SENSOR, SENSOR_PIN_1) humidity2, temperature2 = Adafruit_DHT.read_retry(DHT_SENSOR, SENSOR_PIN_2) if humidity1 is None or temperature1 is None: print("Failed to retrieve data from humidity sensor 1") if humidity2 is None or temperature2 is None: print("Failed to retrieve data from humidity sensor 2") if humidity1 is not None and temperature1 is not None: print("Sensor 1: Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature1, humidity1)) if humidity2 is not None and temperature2 is not None: print("Sensor 2: Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature2, humidity2)) else: print("Failed to retrieve data from humidity sensor 2") time.sleep(2)<file_sep>/README.md # RASPBERRY PI GREENHOUSE # This project uses a raspberry pi, a 4 channel relay, and ac power sockets to create controllable power. # Run time of relay is controlled by value of sensors and/or time of day. <file_sep>/program.py import RPi.GPIO as GPIO import Adafruit_DHT as DHT import time import datetime # config values HUMIDITY_ON = 95 HUMIDITY_OFF = 98 SLEEPTIME = 3 errorResetRate = 180 / SLEEPTIME # divide by SLEEPTIME # if we dont get a value from one sensor for 3 minutes the average will reset to the other sensor # all relay pins RELAYPINS = [17, 27, 22, 23] # relay GPIO pins UNUSED = 17 HUMIDIFIER = 27 LIGHT = 22 FAN = 23 #all sensor pins SENSORPINS = [9,10] # sensor GPIO pins SENSOR = DHT.DHT22 SENSOR1 = 9 SENSOR2 = 10 # set up GPIO as BCM GPIO.setmode(GPIO.BCM) # loop through relay pins and set mode and state to 'high' print("Program Start: All Relays Off") for i in RELAYPINS: GPIO.setup(i, GPIO.OUT) GPIO.output(i, GPIO.HIGH) print("Program Start: Setting up sensors") for i in SENSORPINS: GPIO.setup(i, GPIO.IN) time.sleep(SLEEPTIME) timeString = time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time())) # initialize variables humidity1 = 0 humidity2 = 0 temperature1 = 0 temperature2 = 0 error1 = 0 error2 = 0 loopCount = 0 humidityState = "OFF" fanState = "OFF" lightState = "OFF" humidifierChange = timeString # start fan GPIO.output(FAN, GPIO.LOW) print("**** Enabling FAN ****") fanState = "ON" # turn on light GPIO.output(LIGHT, GPIO.LOW) print("**** Enabling Light ****") lightState = "ON" try: while True: # sleepyTime time.sleep(SLEEPTIME) # loopCount loopCount += 1 # get the current time timeString = time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time())) # read the sensor values to temp variables humidity1a, temperature1a = DHT.read(SENSOR, SENSOR1) humidity2a, temperature2a = DHT.read(SENSOR, SENSOR2) if humidity1a is None or temperature1a is None: print("**** Failed to retrieve data from humidity sensor 1 ****") error1 += 1 if error1 > errorResetRate: # if we get more than errorResetRate sensor read errors on sensor 1 humidity1 = humidity2 # store the current value of sensor 2 into humidity1 to get a more accurate average error1 = 0 # and reset the error rate print("**** Resetting sensor 1 errors to sensor 2 ****") else: # we got a good reading, set working variables for averaging humidity1 = humidity1a temperature1 = temperature1a if humidity2a is None or temperature2a is None: print("**** Failed to retrieve data from humidity sensor 2 ****") error2 += 1 if error2 > errorResetRate: # if we get more than errorResetRate sensor read errors on sensor 2 humidity2 = humidity1 # store the current value of sensor 1 into humidity2 to get a more accurate average error2 = 0 # and reset the error rate print("**** Resetting sensor 1 errors to sensor 2 ****") else: # we got a good reading, set working variables for averaging humidity2 = humidity2a temperature2 = temperature2a if loopCount == errorResetRate: error1 = 0 error2 = 0 print("**** Resetting Error Rate ****") # calculate average humidity humidityAvg = (humidity1 + humidity2) / 2 # calculate average temperature temperatureAvg = (temperature1 + temperature2) / 2 # output the status print("Current Time: ",timeString) print("Sensor 1 Temp: {0:0.1f}*C Humidity={1:0.1f}%".format(temperature1, humidity1)) print("Sensor 2 Temp: {0:0.1f}*C Humidity={1:0.1f}%".format(temperature2, humidity2)) print("Humidity average: {0:0.1f}%".format(humidityAvg)) print("Temperature average: {0:1.2f}*C".format(temperatureAvg)) print("Humidifier state: ",humidityState) print("Humidifier last change:",humidifierChange) print("Fan state: ",fanState) print("Light state: ",lightState) if humidityAvg < HUMIDITY_ON and humidityState is not "ON": # if humidity is less than the on trigger, enable humidifier GPIO.output(HUMIDIFIER, GPIO.LOW) print("**** Enabling Humidifier ****") humidityState = "ON" humidifierChange = timeString if humidityAvg > HUMIDITY_OFF and humidityState is not "OFF": # if humidity is more than the cutoff, turn off. GPIO.output(HUMIDIFIER, GPIO.HIGH) print("**** Disabling Humidifier ****") humidityState = "OFF" humidifierChange = timeString if humidity1 == 0 and humidity2 == 0: # both sensors are 0. turn off and exit. print("**** Sensor failure, powering down ****") GPIO.output(HUMIDIFIER, GPIO.HIGH) GPIO.output(FAN, GPIO.HIGH) humidityState = "OFF" fanState = "OFF" break print("................................................................") except KeyboardInterrupt: # turn the relay off print("Cleanup") for i in relayPins: GPIO.setmode(GPIO.BCM) GPIO.output(i, GPIO.HIGH) GPIO.cleanup() for i in sensorPins: GPIO.cleanup() # Reset GPIO settings print("\nExiting\n") # exit the application sys.exit(0)<file_sep>/allon.py import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # init list with pin numbers pinList = [17, 27, 22, 23] # loop through pins and set mode and state to 'high' for i in pinList: GPIO.setup(i, GPIO.OUT) GPIO.output(i, GPIO.HIGH) # time to sleep between operations in the main loop SleepTimeL = 1 try: print ("ONE ON") time.sleep(SleepTimeL) GPIO.output(27, GPIO.LOW) print ("TWO ON") time.sleep(SleepTimeL) GPIO.output(22, GPIO.LOW) print ("THREE ON") time.sleep(SleepTimeL) GPIO.output(23, GPIO.LOW) print ("FOUR ON") time.sleep(SleepTimeL) GPIO.output(17, GPIO.LOW) except KeyboardInterrupt: # turn the relay off set_relay(False) # Reset GPIO settings GPIO.cleanup() print("\nExiting\n") # exit the application sys.exit(0)
e7e0f4973d37814316d0c01e7a81bc5d8fcc4eba
[ "Markdown", "Python" ]
5
Python
dzzy/RelayGreenHouse
23fa7c4e316040f9b6954981dad546153cd5df6e
aa47b4e8d354c945bcb8f4a091d4c05430b8aa48
refs/heads/master
<repo_name>WestTorranceRobotics/InfiniteRechargeCameraServer<file_sep>/src/main/java/Main.java import java.lang.reflect.Field; import java.lang.reflect.Modifier; import edu.wpi.cscore.HttpCamera; import edu.wpi.cscore.MjpegServer; import edu.wpi.cscore.VideoCamera; import edu.wpi.cscore.VideoSource.ConnectionStrategy; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.networktables.EntryListenerFlags; import edu.wpi.first.networktables.NetworkTable; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.shuffleboard.BuiltInWidgets; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ public final class Main { private static final int[] cameraPorts = {0, 2, 4}; public static final int NUMBER_CAMERAS = cameraPorts.length; private Main() { } /** * Main. */ public static void main(String... args) { System.out.println("Starting network tables"); NetworkTableInstance.getDefault().startClientTeam(5124); try { Thread.sleep(5000); } catch (InterruptedException ex) { System.out.println("Program not allowed to wait: network tables may not be started."); } CameraServer server = CameraServer.getInstance(); VideoCamera[] cameras = new VideoCamera[NUMBER_CAMERAS + 1]; for (int i = 0; i < NUMBER_CAMERAS; i++) { cameras[i] = server.startAutomaticCapture(cameraPorts[i]); cameras[i].setConnectionStrategy(ConnectionStrategy.kAutoManage); cameras[i].setFPS(30); cameras[i].setResolution(320, 240); cameras[i].setExposureManual(50); server.addCamera(cameras[i]); } cameras[NUMBER_CAMERAS] = new HttpCamera("limelight", "http://limelight.local:5800"); server.addCamera(cameras[NUMBER_CAMERAS]); MjpegServer output = (MjpegServer) server.getServer(); output.setSource(cameras[0]); output.setResolution(320, 240); output.setCompression(50); output.setDefaultCompression(50); output.setFPS(30); NetworkTable table = NetworkTableInstance.getDefault().getTable("rpi"); NetworkTableEntry aimbot = table.getEntry("aimbot"); aimbot.setDouble(0); NetworkTableEntry camera = table.getEntry("camera"); camera.setDouble(0); NetworkTableEntry cameraSelection = NetworkTableInstance.getDefault().getTable("").getEntry("CameraSelection"); cameraSelection.setString(cameras[0].getName()); NetworkTableEntry pipeline = NetworkTableInstance.getDefault() .getTable("limelight").getEntry("pipeline"); camera.addListener((change) -> { int selected = (int) change.value.getDouble(); output.setSource(cameras[selected]); cameraSelection.setString(cameras[selected].getName()); if (aimbot.getDouble(0) != 1 && selected == NUMBER_CAMERAS) { pipeline.setDouble(1); } if (aimbot.getDouble(0) == 1 && pipeline.getDouble(0) != 0) { pipeline.setDouble(0); } }, generateAllFlagsMask()); System.out.println("Adding view to Shuffleboard"); Shuffleboard.getTab("Driving Display").add("Selected Camera View", output.getSource()) .withSize(8, 4).withPosition(1, 0).withWidget(BuiltInWidgets.kCameraStream); int i = 0; while (true) { try { SmartDashboard.putNumber("Heartbeat", ++i); Thread.sleep(1000); } catch (InterruptedException ex) { return; } } } /** * Iterates through the fields in {@link EntryListenerFlags} to find all * public, static, final integers and mask them together. It is assumed that * no other integers will exist in the class than those denoting possible flags, * and that only public, static, and final integers may represent flag masks. * All non-integer fields or fields without the correct modifiers are skipped, * while those found are masked together with a bitwise OR. * * @return A mask representing all possible entry listener change flags */ private static int generateAllFlagsMask() { int mask = 0; for (Field f : EntryListenerFlags.class.getDeclaredFields()) { if (f.getType() == Integer.TYPE) { int mods = f.getModifiers(); if ((mods & Modifier.PUBLIC) == 0 || (mods & Modifier.STATIC) == 0 || (mods & Modifier.FINAL) == 0) { continue; } try { mask |= f.getInt(new EntryListenerFlags(){}); } catch (ReflectiveOperationException ex) { // ignore constants that we can't get, because // they must not be intended as flag bit masks } } } return mask; } } <file_sep>/README.txt ================== Programming the Pi ================== -------- Building -------- Java 11 is required to build. Set your path and/or JAVA_HOME environment variable appropriately. Then run the build function of gradlew. These two steps have been combined for most FRC-enabled Windows systems in the file BUILDJAR.bat. --------- Deploying --------- On the rPi web dashboard: 1) Make the rPi writable by selecting the "Writable" tab 2) In the rPi web dashboard Application tab, select the "Uploaded Java jar" option for Application 3) Click "Browse..." and select the "java-multiCameraServer-all.jar" file in your desktop project directory in the build/libs subdirectory 4) Click Save The application will be automatically started. Console output can be seen by enabling console output in the Vision Status tab. ==================== Features and Updates ==================== === 2 March 2020: First Functional Version === Rewriting the camera switcher from the top to the bottom has proved successful. Although there likely exist potential optimizations and cleanings in the code, and even potential feature enhancements, this version is being merged for its completeness of vital functionality. Documentation of interface to first completed camera server version: Network tables: It uses the table "rpi" and has two keys "aimbot" which is 1 or 0, depending on whether or not we want the vision tracking to be running. This is just to make sure the rpi knows when vision is running so that if the driver requests limelight camera view, it won't overwrite the network table settings that turn on the limelight. If "aimbot" is set to zero, or if it doesn't exist, the rpi assumes it is allowed to turn off the limelight. "camera" which is a number between 0 and the NUMBER_CAMERAS code constant (which is equal to the number of cameras plugged into the pi by usb). Allowed range is inclusive. This number chooses which camera will be displayed on the shuffleboard. Viewing: Open SmartDashboard. Add a new Camera Server Stream Viewer Widget to the dashboard. Set the view to be editable, and set the stream to a reasonable size in the context of the rest of the SmartDashboard display. Return the view to its uneditable mode. The stream is not currently known to be accessible from Shuffleboard.
66a199d99f47d3bd5104dda911a9e993a58e079c
[ "Java", "Text" ]
2
Java
WestTorranceRobotics/InfiniteRechargeCameraServer
e236ece3d51991a02bee99ef34c81fb4aca132b7
b8fb7dbc5996a072bd7914f1b29034c740a78002
refs/heads/master
<file_sep>window.onresize = function() { var height = Math.max(document.documentElement.clientHeight,document.body.offsetHeight); document.getElementById('container').style.height = height - 180 + 'px'; $(".content").css('height',height-220+'px') } $(function(){ var height = Math.max(document.documentElement.clientHeight,document.body.offsetHeight); document.getElementById('container').style.height = height - 180 + 'px'; $(".content").css('height',height-220+'px'); $("#box").css('margin-top') }) <file_sep> window.onresize = function() { var height = Math.max(document.documentElement.clientHeight,document.body.offsetHeight); document.getElementById('container').style.height = height - 142 + 'px'; } $(function(){ var height = Math.max(document.documentElement.clientHeight,document.body.offsetHeight); document.getElementById('container').style.height = height - 142 + 'px'; var url = "container.html"; $("#centerFrame").attr("src", url); $('#M').hover(function() { $('#ullM').show(); }, function() { $('#ullM').hide(); }); $('#ullM').hover(function() { $('#ullM').show(); }, function() { $('#ullM').hide(); }); $('#D').hover(function() { $('#ullD').show(); }, function() { $('#ullD').hide(); }); $('#ullD').hover(function() { $('#ullD').show(); }, function() { $('#ullD').hide(); }); $('#E').hover(function() { $('#ullE').show(); }, function() { $('#ullE').hide(); }); $('#ullE').hover(function() { $('#ullE').show(); }, function() { $('#ullE').hide(); }); $('#F').hover(function() { $('#ullF').show(); }, function() { $('#ullF').hide(); }); $('#ullF').hover(function() { $('#ullF').show(); }, function() { $('#ullF').hide(); }); $('#Score').hover(function(){ $(this).css('background','#EEEEEE') $('#ullScore').show() },function(){ $(this).css('background','white') $('#ullScore').hide(); }) $('#ullScore').hover(function(){ $('#ullScore').show() $('#Score').css('background','#EEEEEE') },function(){ $('#ullScore').hide(); $('#Score').css('background','white') }) $('#Competitive').hover(function(){ $(this).css('background','#EEEEEE') $('#ullCompetitive').show() },function(){ $(this).css('background','white') $('#ullCompetitive').hide(); }) $('#ullCompetitive').hover(function(){ $('#ullCompetitive').show() $('#Competitive').css('background','#EEEEEE') },function(){ $('#ullCompetitive').hide(); $('#Competitive').css('background','white') }) $('#Intelligence').hover(function(){ $(this).css('background','#EEEEEE') $('#ullIntelligence').show() },function(){ $(this).css('background','white') $('#ullIntelligence').hide(); }) $('#ullIntelligence').hover(function(){ $('#ullIntelligence').show() $('#Intelligence').css('background','#EEEEEE') },function(){ $('#ullIntelligence').hide(); $('#Intelligence').css('background','white') }) $('#Delivery').hover(function(){ $(this).css('background','#EEEEEE') $('#ullDelivery').show() },function(){ $(this).css('background','white') $('#ullDelivery').hide(); }) $('#ullDelivery').hover(function(){ $('#ullDelivery').show() $('#Delivery').css('background','#EEEEEE') },function(){ $('#ullDelivery').hide(); $('#Delivery').css('background','white') }) }) var net = "https://www.starcompass.net" function setData(menu, obj) { $(".nav_hq_s").attr("class", "nav_hq_s"); obj.attr("class", "nav_hq_s nav_hq_on"); /* var ip = "192.168.1.20"; var port = "8080"; */ if (menu == 1) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!01_Market Intelligence!2f!01_01 Corporate Topline.db" $("#centerFrame").attr("src", url); } else if (menu == 2) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!01_Market Intelligence!2f!01_02 One Report_by Brand.db"; $("#centerFrame").attr("src", url); } else if (menu == 3) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!01_Market Intelligence!2f!01_03 Business Market Performance.db"; $("#centerFrame").attr("src", url); } else if (menu == 4) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_01 Category Landscape.db"; $("#centerFrame").attr("src", url); } else if (menu == 5) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_02 Brand Scorecard!2f!BrandSCHC.db"; $("#centerFrame").attr("src", url); } else if (menu == 6) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_02 Brand Scorecard!2f!BrandSCBC.db"; $("#centerFrame").attr("src", url); } else if (menu == 7) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_02 Brand Scorecard!2f!Laundry scorecard!2f!BrandSCLC.db"; $("#centerFrame").attr("src", url); } else if (menu == 8) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_02 Brand Scorecard!2f!Oralcare scorecard!2f!BrandSCOC.db"; $("#centerFrame").attr("src", url); } else if (menu == 9) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_03 Competitive Analytics!2f!02_03_01 Competitive Performance.db"; $("#centerFrame").attr("src", url); } else if (menu == 10) { // var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=ABI^2f^Data^20^Bank^2f^03_3^20^OOH^20^Detail.db"; $("#centerFrame").attr("src", url); } else if (menu == 11) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_04 Intelligence!2f!02_04_01 Newsletter.db"; $("#centerFrame").attr("src", url); } else if (menu == 12) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!02_Brand Analytics!2f!02_04 Intelligence!2f!02_04_02 Sharing Studies.db"; $("#centerFrame").attr("src", url); } else if (menu == 13) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!03_ISP Performance!2f!03_01 TV Delivery.db"; $("#centerFrame").attr("src", url); }else if (menu == 14) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!03_ISP Performance!2f!03_02 OTT Delivery.db"; $("#centerFrame").attr("src", url); }else if (menu == 15) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!03_ISP Performance!2f!03_03 Digital Delivery!2f!03_03_01 Daily Tracking.db"; $("#centerFrame").attr("src", url); }else if (menu == 16) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!03_ISP Performance!2f!03_03 Digital Delivery!2f!03_03_02 Monthly Tracking.db"; $("#centerFrame").attr("src", url); }else if (menu == 17) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!03_ISP Performance!2f!03_03 Digital Delivery!2f!03_03_03 Digital Post buy.db"; $("#centerFrame").attr("src", url); }else if (menu == 18) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!04_Media Detail!2f!04_01 TV GRP SOV.db"; $("#centerFrame").attr("src", url); }else if (menu == 19) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!04_Media Detail!2f!04_02 ISP Media Reach.db"; $("#centerFrame").attr("src", url); }else if (menu == 20) { var url = net + "/bi/Viewer?proc=1&action=viewer&hback=true&db=PGCI-2017!2f!04_Media Detail!2f!04_03 Media Monitor Spending.db"; $("#centerFrame").attr("src", url); } };
c8dcafbcf9324068e3613280e88dabb5088a68c0
[ "JavaScript" ]
2
JavaScript
DD21207/PGCI
9b474492018cc595f2489e7bd3f63b63228e000a
1f02bd65f22d343f517153b99ecf810ed2a7e72d
refs/heads/master
<file_sep>my_first_name = "Mhaventhan" # puts my_first_name # # my_first_name = :Mhaventhan # puts my_first_name # number_array = [1,2,3,4,5] # puts number_array name_array = ['Mhaventhan','Viren','Logaraj','Hanad','Ivor'] # puts name_array.shift # puts '-----=-=-=-=--------=-==-' # puts name_array # person = { # :name => 'Mhaventhan', # :age => 23 # } # person = { # name: 'Mhaventhan', # age: 23 # } # # puts person[:name] # puts person[:age] my_string = 'some string value' puts my_string.upcase mystery_variable = 'Mhaventhan' puts mystery_variable.class alphabet = 'abcdefgh' # puts alphabet.reverse! puts alphabet.start_with?('a') # method is a function within a method <file_sep># while loop # i = 0 # while i <= 10 do # puts "while #{i}" # i+=1 # end # do while # i = 11 # begin # puts"Do while: #{[i]}" # i+=1 # end while i < 10 # inverse loops # i = 0 # until i > 10 do # puts "until: #{i}" # i +=1 # end # array = ["sring1","string2"] # for i in array # puts "for loops are great #{i}" # end # each loop words = ["Mav","Gav","dan"] # (words).each_with_index do |word, index| # puts "value of local variable is #{word}, the index is #{index}" # end # reversed_words = words.map do |word| # word.reverse # end # puts reversed_words numbers = [1,4,5,2,3,1,2,4] sum = numbers.reduce 0 do |total, number| puts "---------" puts total puts number puts "---------" total + number end puts "sum #{sum}" quick_sum = numbers.reduce(0, :+) puts quick_sum <file_sep># def say_hello # puts "say hello" # end # say_hello # # def add_numbers num1,num2 # num1+num2 # end # # puts add_numbers 1,2 # def create_user(name, course="SDET") # "#{name} is in #{course}" # end # # puts create_user("Richard", "DevOps") # def say_words(*words) # puts words # end # # say_words("word1","word2","word3","word4","word5") # def say(what, *people) # people.each do |person| # puts "Hey, #{person},#{what}" # end # end # # say("Hello","Mav","dave" def add_numbers(num1,num2) return num1 + num2 end puts add_numbers(1,2) <file_sep># if statement # if true # puts 'this works' # end # # if false # puts 'if true this will work' # else # puts 'if false' # # end # if true # puts 'string' # elsif true # puts 'string2' # else # puts 'string3' # end # val =1 # if(val ==1) then puts "1" else puts "not 1" end # tunary # val ==1? (puts'1'):(puts'2') # comparison # == # != # > # < # <= # >= # .eql? checking the type and the value # .equal? if the object is same # logical operators # and # or # && # || # ! # not <file_sep>require 'mac/say' Mac::Say.say('')
99c852d1a4f9cdb59099404e534397e43e1ad59b
[ "Ruby" ]
5
Ruby
Mhaventhan/Sparta_Ruby
0a7c6087123b6fdeaceba03628a5fffcc4a5065b
820c20b4d4555a5ee8d979a0cdce54cea94d3f59
refs/heads/master
<file_sep>let database = firebase.database(); let currentUser; let currentUserKey; let currentUserDetail; let currentSearchFriendIDForInvitation; //ID 就是 Email let currentSearchFriendKeyForInvitation; // // 登入功能 登入後,開啟即時偵測 getElement('.confirmToLogin').addEventListener('click', (e)=>{ currentUser = getElement('#loginUser').value; getMemberInfoByChild('user_email', currentUser, (list, key) =>{ currentUserKey = key; if ( key === undefined ) { getElement('.loginRemind').innerHTML = "如果沒有帳號,不要隨便開玩笑"; } else { detectChange(); getElement('.login').style.display = "none"; getElement('.memberFrame').style.display = "block"; } }); }) //尋找好友點擊確認 getElement('.confirmToAdd').addEventListener('click', (e)=> { currentSearchFriendIDForInvitation = getElement('#friendId').value; getMemberInfoByChild('user_email', currentSearchFriendIDForInvitation, showFriendSearchResult).then(function(snapshot){ if ( snapshot != null ) { getElement(".yes").style.display = "inline-block" getElement(".no").style.display = "inline-block" } }); }) //確認加入好友 getElement('.yes').addEventListener('click', (e)=>{ sendFriendRequest(currentUserKey, currentSearchFriendKeyForInvitation,"pending_send","pending_cofirm"); }) //取消加入好友 getElement('.no').addEventListener('click', (e)=>{ getElement("#friendId").value = ""; getElement('.result>.resultUserEmail').innerHTML = ""; getElement('.result>.resultUserName').innerHTML = ""; getElement(".yes").style.display = "none" getElement(".no").style.display = "none" console.log('你在戲弄我?'); }) /////////////////////////////////////////////////////////////////////////////////////////////////////////// ////更新好友狀態區域//// //主程式:共有 pending_confirm, pending_send, valid三種狀態,如為null則與remove效果相同 function sendFriendRequest(currentUserKey, currentSearchFriendKeyForInvitation,invite_status, confirm_status){ database.ref('member'+ '/' + currentUserKey + '/' + 'friend' + '/' + currentSearchFriendKeyForInvitation ).set({ invite_status: invite_status, }); database.ref('member'+ '/' + currentSearchFriendKeyForInvitation + '/' + 'friend' + '/' + currentUserKey ).set({ invite_status: confirm_status, }); // getMemberInfoByChild('user_email', currentUser, getFriendsList); } //更新好友狀態,由接受邀請人接受邀請。 onclick事件寫在getFriendList的動態生成裡面 function confirmFriendRequest() { console.log(this.index); getMemberInfoByChild('user_email', this.index, (list, key) =>{ let confirmUserKey = key; sendFriendRequest(currentUserKey, confirmUserKey, "valid", "valid"); }) } function rejectFriendRequest() { console.log(this.index); getMemberInfoByChild('user_email', this.index, (list, key) =>{ let confirmUserKey = key; sendFriendRequest(currentUserKey, confirmUserKey, null , null ); }) } //顯示朋友清冊 //偵測朋友清冊更新 function detectChange() { console.log('detectChange'); database.ref("/member/" + currentUserKey + "/friend").on("value", function(snapshot) { getMemberInfoByChild('user_email', currentUser, getFriendsList); }); } //取得好友名單並顯示 function getFriendsList(list) { if (list === false || list.friend === undefined || list.friend === null) { getElement('.friendList').innerHTML = "您,沒朋友"; } else { let friendList =[]; getElement('.friendList').innerHTML= ""; for (let i =0 ; i <Object.keys(list.friend).length; i++){ let currentSearchFriendStatus = list.friend[Object.keys(list.friend)[i]].invite_status; console.log(currentSearchFriendStatus); getMemberInfoByKey(Object.keys(list.friend)[i], (fullList)=> { let friendListItem = document.createElement('div'); let friendName = document.createElement('h2'); friendName.innerHTML = fullList.user_name; let friendEmail = document.createElement('h4'); friendEmail.innerHTML = fullList.user_email; let confirmStatus = document.createElement('h5'); confirmStatus.innerHTML = currentSearchFriendStatus; getElement('.friendList').appendChild(friendListItem); friendListItem.append(friendName, friendEmail,confirmStatus); if (currentSearchFriendStatus === "pending_confirm") { let confirmButton = document.createElement('button'); let rejectButton = document.createElement('button'); confirmButton.innerHTML = "確認"; rejectButton.innerHTML = "拒絕"; friendListItem.append(confirmButton, rejectButton); confirmButton.index = fullList.user_email; confirmButton.onclick = confirmFriendRequest; rejectButton.index = fullList.user_email; rejectButton.onclick = rejectFriendRequest; } } ); } } } //顯示朋友清冊^^^^^ //確認是否有這個人,如果沒有資料 function showFriendSearchResult(list, key) { if ( list === false ) { getElement('.result>.resultUserEmail').innerHTML = ""; getElement('.result>.resultUserEmail').innerHTML = "查無此人,不要隨便開玩笑"; } else { getElement('.result>.resultUserEmail').innerHTML = ""; getElement('.result>.resultUserName').innerHTML = ""; getElement('.result>.resultUserEmail').innerHTML = list.user_email; getElement('.result>.resultUserName').innerHTML = list.user_name; currentSearchFriendKeyForInvitation = key; } } // 用key取得會員相關資料 function getMemberInfoByKey(keyforSearch, callback) { return database.ref('member/').orderByKey().equalTo(keyforSearch).once('value').then(function(snapshot){ snapshot.forEach(function(childSnapshot) { // console.log(childSnapshot.val()); callback(childSnapshot.val()); }); }) } // 用特定欄位取得相關資料 function getMemberInfoByChild(child, keyforSearch, callback) { return database.ref('member/').orderByChild(child).equalTo(keyforSearch).once('value').then(function(snapshot){ if (snapshot.val() === null) { callback(false); } else { snapshot.forEach(function(childSnapshot) { console.log(childSnapshot.val(),childSnapshot.key); callback(childSnapshot.val(), childSnapshot.key); }); return snapshot.val(); } }) } <file_sep># Post-and-Friends ## https://pkypeter.github.io/Post-and-Friends/index.html ### Features 1. Write articles and Post 2. Invite and Add new friends ### Stack Firebase Realtime Database: use to deal with membership list, friends status control, articles storage,
1c741d39abb5c4b857db55e021643ee1bb7433db
[ "JavaScript", "Markdown" ]
2
JavaScript
pkyPeter/appworks_PTT
4213262f4502e2980b09937ef2ffb18517614e8b
b9ad849085d2bcf59cfc7a83bb7d6f6c49bc91e4
refs/heads/master
<file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { public class OrganizacijaRepozitorijum : IOrganizacijaRepozitorijum { private VoziloContext context; public OrganizacijaRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Organizacija organizacija) { context.Organizacije.Add(organizacija); } public void Obrisi(Organizacija organizacija) { context.Organizacije.Remove(organizacija); } public Organizacija VratiPoId(int id) { return context.Organizacije.Find(id); } public IEnumerable<Organizacija> VratiSve() { return context.Organizacije.ToList(); } public IEnumerable<Radnik> radniciOrg(int orgId) { return context.Radnici.Where(r => r.OrganizacijaId == orgId).ToList(); } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { class RegistracijaRepozitorijum : IRegistracijaRepozitorijum { private VoziloContext context; public RegistracijaRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Registracija registracija) { context.Registracije.Add(registracija); } public void Obrisi(Registracija registracija) { context.Registracije.Remove(registracija); } public Registracija VratiPoId(int id) { return context.Registracije.Find(id); } public IEnumerable<Registracija> VratiSve() { return context.Registracije.ToList(); } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Modeli; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class VlasnikForm : MetroFramework.Forms.MetroForm { private UnitOfWork unit; int idSelekt = 0; public VlasnikForm() { InitializeComponent(); var context = new VoziloContext(); unit = new UnitOfWork(context); dgvVlasnici.DataSource = unit.Vlasnici.VratiSve(); } private void VlasnikForm_Load(object sender, EventArgs e) { } private void lblBrisanje_Click(object sender, EventArgs e) { } private void btnDodaj_Click(object sender, EventArgs e) { try { var ime = txtIme.Text; var prezime = txtPrezime.Text; var novi = new Vlasnik(); novi.Ime = ime; novi.Prezime = prezime; this.unit.Vlasnici.Dodaj(novi); this.unit.Sacuvaj(); MessageBox.Show("Vlasnik dodat"); dgvVlasnici.DataSource = this.unit.Vlasnici.VratiSve(); } catch(Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void btnBrisanje_Click(object sender, EventArgs e) { try { var vlasnik = unit.Vlasnici.VratiPoId(idSelekt); unit.Vlasnici.Obrisi(vlasnik); unit.Sacuvaj(); dgvVlasnici.DataSource = unit.Vlasnici.VratiSve(); MessageBox.Show("Vlasnik obrisan."); } catch(Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void dgvVlasnici_CellClick(object sender, DataGridViewCellEventArgs e) { var ind = e.RowIndex; idSelekt = int.Parse(dgvVlasnici[0, ind].Value.ToString()); lblBrisanje.Text = "Vlasnik za brisanje (ID):"; lblBrisanje.Text = "Vlasnik za brisanje (ID):" + idSelekt.ToString(); } private void btnVozila_Click(object sender, EventArgs e) { try { dgvVozilaV.DataSource = unit.Vlasnici.MojaPutnicka(idSelekt); } catch (Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void btnTeretna_Click(object sender, EventArgs e) { try { dgvVozilaV.DataSource = unit.Vlasnici.MojaTeretna(idSelekt); } catch (Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { public class PutnickoRepozitorijum : IPutnickoRepozitorijum { private VoziloContext context; public PutnickoRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Putnicko vozilo) { context.Putnicka.Add(vozilo); } public void Obrisi(Putnicko vozilo) { context.Putnicka.Remove(vozilo); } public Putnicko VratiPoId(int id) { return context.Putnicka.Find(id); } public IEnumerable<Putnicko> VratiSva() { return context.Putnicka.ToList(); } } } <file_sep>namespace RegistracijaVozila.Migrations { using System; using System.Data.Entity.Migrations; public partial class Prva : DbMigration { public override void Up() { CreateTable( "dbo.Organizacijas", c => new { OrganizacijaId = c.Int(nullable: false, identity: true), Naziv = c.String(nullable: false, maxLength: 30), Grad = c.String(nullable: false, maxLength: 15), Ulica = c.String(nullable: false, maxLength: 20), }) .PrimaryKey(t => t.OrganizacijaId); CreateTable( "dbo.Radniks", c => new { RadnikId = c.Int(nullable: false, identity: true), Ime = c.String(nullable: false, maxLength: 20), Prezime = c.String(nullable: false, maxLength: 20), Godine = c.Int(), OrganizacijaId = c.Int(nullable: false), }) .PrimaryKey(t => t.RadnikId) .ForeignKey("dbo.Organizacijas", t => t.OrganizacijaId, cascadeDelete: true) .Index(t => t.OrganizacijaId); CreateTable( "dbo.Putnickoes", c => new { PutnickoId = c.Int(nullable: false, identity: true), Proizvodjac = c.String(nullable: false, maxLength: 20), Tip = c.String(nullable: false, maxLength: 20), GodProizvodnje = c.Int(nullable: false), Snaga = c.Single(nullable: false), Boja = c.String(nullable: false, maxLength: 20), VlasnikId = c.Int(nullable: false), Registracija_RegistracijaId = c.Int(), }) .PrimaryKey(t => t.PutnickoId) .ForeignKey("dbo.Registracijas", t => t.Registracija_RegistracijaId) .ForeignKey("dbo.Vlasniks", t => t.VlasnikId, cascadeDelete: true) .Index(t => t.VlasnikId) .Index(t => t.Registracija_RegistracijaId); CreateTable( "dbo.Registracijas", c => new { RegistracijaId = c.Int(nullable: false, identity: true), Cena = c.Int(nullable: false), Datum = c.String(nullable: false), RadnikId = c.Int(nullable: false), VoziloId = c.Int(nullable: false), tipVozila = c.String(nullable: false), }) .PrimaryKey(t => t.RegistracijaId) .ForeignKey("dbo.Radniks", t => t.RadnikId, cascadeDelete: true) .Index(t => t.RadnikId); CreateTable( "dbo.Vlasniks", c => new { VlasnikId = c.Int(nullable: false, identity: true), Ime = c.String(nullable: false, maxLength: 20), Prezime = c.String(nullable: false, maxLength: 20), }) .PrimaryKey(t => t.VlasnikId); CreateTable( "dbo.Voziloes", c => new { VoziloId = c.Int(nullable: false, identity: true), Proizvodjac = c.String(), Tip = c.String(), GodProizvodnje = c.Int(nullable: false), Boja = c.String(), VlasnikId = c.Int(nullable: false), Registracija_RegistracijaId = c.Int(), }) .PrimaryKey(t => t.VoziloId) .ForeignKey("dbo.Registracijas", t => t.Registracija_RegistracijaId) .ForeignKey("dbo.Vlasniks", t => t.VlasnikId, cascadeDelete: true) .Index(t => t.VlasnikId) .Index(t => t.Registracija_RegistracijaId); CreateTable( "dbo.Teretnoes", c => new { TeretnoId = c.Int(nullable: false, identity: true), Proizvodjac = c.String(nullable: false, maxLength: 20), Tip = c.String(nullable: false, maxLength: 20), GodProizvodnje = c.Int(nullable: false), Nosivost = c.Single(nullable: false), Boja = c.String(nullable: false, maxLength: 20), VlasnikId = c.Int(nullable: false), Registracija_RegistracijaId = c.Int(), }) .PrimaryKey(t => t.TeretnoId) .ForeignKey("dbo.Registracijas", t => t.Registracija_RegistracijaId) .ForeignKey("dbo.Vlasniks", t => t.VlasnikId, cascadeDelete: true) .Index(t => t.VlasnikId) .Index(t => t.Registracija_RegistracijaId); } public override void Down() { DropForeignKey("dbo.Teretnoes", "VlasnikId", "dbo.Vlasniks"); DropForeignKey("dbo.Teretnoes", "Registracija_RegistracijaId", "dbo.Registracijas"); DropForeignKey("dbo.Putnickoes", "VlasnikId", "dbo.Vlasniks"); DropForeignKey("dbo.Voziloes", "VlasnikId", "dbo.Vlasniks"); DropForeignKey("dbo.Voziloes", "Registracija_RegistracijaId", "dbo.Registracijas"); DropForeignKey("dbo.Putnickoes", "Registracija_RegistracijaId", "dbo.Registracijas"); DropForeignKey("dbo.Registracijas", "RadnikId", "dbo.Radniks"); DropForeignKey("dbo.Radniks", "OrganizacijaId", "dbo.Organizacijas"); DropIndex("dbo.Teretnoes", new[] { "Registracija_RegistracijaId" }); DropIndex("dbo.Teretnoes", new[] { "VlasnikId" }); DropIndex("dbo.Voziloes", new[] { "Registracija_RegistracijaId" }); DropIndex("dbo.Voziloes", new[] { "VlasnikId" }); DropIndex("dbo.Registracijas", new[] { "RadnikId" }); DropIndex("dbo.Putnickoes", new[] { "Registracija_RegistracijaId" }); DropIndex("dbo.Putnickoes", new[] { "VlasnikId" }); DropIndex("dbo.Radniks", new[] { "OrganizacijaId" }); DropTable("dbo.Teretnoes"); DropTable("dbo.Voziloes"); DropTable("dbo.Vlasniks"); DropTable("dbo.Registracijas"); DropTable("dbo.Putnickoes"); DropTable("dbo.Radniks"); DropTable("dbo.Organizacijas"); } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class Form1 : MetroFramework.Forms.MetroForm { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { pbVozilo.SizeMode = PictureBoxSizeMode.StretchImage; pbVlasnik.SizeMode = PictureBoxSizeMode.StretchImage; pbOrg.SizeMode = PictureBoxSizeMode.StretchImage; pbRad.SizeMode = PictureBoxSizeMode.StretchImage; pbReg.SizeMode = PictureBoxSizeMode.StretchImage; pbVozilo.BackColor = Color.Transparent; pbVlasnik.BackColor = Color.Transparent; pbOrg.BackColor = Color.Transparent; pbRad.BackColor = Color.Transparent; pbReg.BackColor = Color.Transparent; mlbOrg.BackColor = Color.Transparent; mlbReg.BackColor = Color.Transparent; mlbRad.BackColor = Color.Transparent; mlbVoz.BackColor = Color.Transparent; mlbVlas.BackColor = Color.Transparent; } private void pbVozilo_Click(object sender, EventArgs e) { VozilaForm vozila = new VozilaForm(); vozila.Show(); } private void pbRad_Click_1(object sender, EventArgs e) { RadnikForm radnik = new RadnikForm(); radnik.Show(); } private void pbOrg_Click_1(object sender, EventArgs e) { OrganizacijaForm organizacija = new OrganizacijaForm(); organizacija.Show(); } private void pbVlasnik_Click_1(object sender, EventArgs e) { VlasnikForm vlasnik = new VlasnikForm(); vlasnik.Show(); } private void pbReg_Click(object sender, EventArgs e) { RegistracijaForm registracija = new RegistracijaForm(); registracija.Show(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Organizacija { public Organizacija() { Radnici = new List<Radnik>(); } public int OrganizacijaId { set; get; } public string Naziv { set; get; } public string Grad { set; get; } public string Ulica { set; get; } public ICollection<Radnik> Radnici { set; get; } public override string ToString() { return OrganizacijaId.ToString() + " " + Naziv; } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Modeli; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class OrganizacijaForm : MetroFramework.Forms.MetroForm { private UnitOfWork unit; private int idSelekt; public OrganizacijaForm() { InitializeComponent(); var context = new VoziloContext(); unit = new UnitOfWork(context); dgvOrganizacije.DataSource = unit.Organizacije.VratiSve(); } private void OrganizacijaForm_Load(object sender, EventArgs e) { } private void btnDodaj_Click(object sender, EventArgs e) { try { var naziv = txtNaziv.Text; var grad = txtGrad.Text; var ulica = txtUlica.Text; var nova = new Organizacija(); nova.Naziv = naziv; nova.Grad = grad; nova.Ulica = ulica; unit.Organizacije.Dodaj(nova); unit.Sacuvaj(); MessageBox.Show("Organizacija dodata."); dgvOrganizacije.DataSource = this.unit.Organizacije.VratiSve(); } catch (Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void btnBrisanje_Click(object sender, EventArgs e) { try { var organizacija = unit.Organizacije.VratiPoId(idSelekt); unit.Organizacije.Obrisi(organizacija); unit.Sacuvaj(); dgvOrganizacije.DataSource = unit.Organizacije.VratiSve(); MessageBox.Show("Organizacija obrisana."); } catch (Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void dgvOrganizacije_CellClick(object sender, DataGridViewCellEventArgs e) { var ind = e.RowIndex; idSelekt = int.Parse(dgvOrganizacije[0, ind].Value.ToString()); lblBrisanje.Text = "Organizacija za brisanje (ID):"; lblBrisanje.Text = "Organizacija za brisanje (ID):" + idSelekt.ToString(); } private void btnRadnici_Click(object sender, EventArgs e) { try { dgvRadnici.DataSource = unit.Organizacije.radniciOrg(idSelekt); } catch(Exception ex) { MessageBox.Show("Doslo je do greske."); } } private void dgvRadnici_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { public class RadnikRepozitorijum : IRadnikRepozitorijum { private VoziloContext context; public RadnikRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Radnik radnik) { context.Radnici.Add(radnik); } public void Obrisi(Radnik radnik) { context.Radnici.Remove(radnik); } public Radnik VratiPoId(int id) { return context.Radnici.Find(id); } public IEnumerable<Radnik> VratiSve() { return context.Radnici.ToList(); } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IPutnickoRepozitorijum { IEnumerable<Putnicko> VratiSva(); Putnicko VratiPoId(int id); void Dodaj(Putnicko vozilo); void Obrisi(Putnicko vozilo); } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Modeli; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class RegistracijaForm : MetroFramework.Forms.MetroForm { private UnitOfWork unit; private int idSelekt; private int idV; private List<string> radnici = new List<string>(); private List<string> vozilaP = new List<string>(); private List<string> vozilaT = new List<string>(); private string tip = "Putnicko"; public RegistracijaForm() { InitializeComponent(); var context = new VoziloContext(); unit = new UnitOfWork(context); dgvRegistracije.DataSource = unit.Registracije.VratiSve(); var radSvi = unit.Radnici.VratiSve(); var vozSva = unit.Vozila.VratiSva(); var vozTSva = unit.Teretna.VratiSva(); foreach(var p in vozSva) { vozilaP.Add(p.ToString()); } foreach (var t in vozTSva) { vozilaT.Add(t.ToString()); } foreach (var r in radSvi) { radnici.Add(r.ToString()); } cmbVozila.DataSource = vozSva; cmbRadnici.DataSource = radnici; } private void RegistracijaForm_Load(object sender, EventArgs e) { } private void btnDodaj_Click(object sender, EventArgs e) { try { var nova = new Registracija(); nova.RadnikId = int.Parse(cmbRadnici.Text.Split(' ')[0]); nova.VoziloId = int.Parse(cmbVozila.Text.Split(' ')[0]); nova.Cena = int.Parse(txtCena.Text); nova.Datum = dtpDatum.Value.Date.ToString(); nova.tipVozila = tip; // Console.WriteLine(nova.ToString()); unit.Registracije.Dodaj(nova); unit.Sacuvaj(); MessageBox.Show("Registracija dodata."); dgvRegistracije.DataSource = unit.Registracije.VratiSve(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnP_Click(object sender, EventArgs e) { cmbVozila.DataSource = vozilaP; tip = "Putnicko"; } private void btnV_Click(object sender, EventArgs e) { cmbVozila.DataSource = vozilaT; tip = "Teretno"; } private void dgvRegistracije_CellClick(object sender, DataGridViewCellEventArgs e) { try { var ind = e.RowIndex; idSelekt = int.Parse(dgvRegistracije[5, ind].Value.ToString()); var tipN = dgvRegistracije[6, ind].Value.ToString(); var vlasnik = unit.Vlasnici.VratiPoId(idSelekt); Putnicko p; Teretno t; if (tipN == "Putnicko") { p = unit.Vozila.VratiPoId(idSelekt); lblVoz.Text = "Selektovano vozilo:"; lblVoz.Text = "Selektovano vozilo: " + p.ToString(); var vid = p.VlasnikId; var vl = unit.Vlasnici.VratiPoId(vid); lblVlasnik.Text = "Vlasnik odabranog automobila:"; lblVlasnik.Text = "Vlasnik odabranog automobila:" + vl.ToString(); } else { t = unit.Teretna.VratiPoId(idSelekt); lblVoz.Text = "Selektovano vozilo:"; lblVoz.Text = "Selektovano vozilo: " + t.ToString(); var vid = t.VlasnikId; var vl = unit.Vlasnici.VratiPoId(vid); lblVlasnik.Text = "Vlasnik odabranog automobila:"; lblVlasnik.Text = "Vlasnik odabranog automobila:" + vl.ToString(); } } catch (Exception ex) { MessageBox.Show("Greska."); } } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IOrganizacijaRepozitorijum { IEnumerable<Organizacija> VratiSve(); Organizacija VratiPoId(int id); void Dodaj(Organizacija organizacija); void Obrisi(Organizacija organizacija); IEnumerable<Radnik> radniciOrg(int orgId); } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { public class UnitOfWork : IUnitOfWork { private VoziloContext context; private RadnikRepozitorijum radnici; private PutnickoRepozitorijum vozila; private VlasnikRepozitorijum vlasnici; private OrganizacijaRepozitorijum organizacije; private RegistracijaRepozitorijum registracije; private TeretnoRepozitorijum teretna; public UnitOfWork(VoziloContext context) { this.context = context; } public IPutnickoRepozitorijum Vozila { get { return vozila ?? (vozila = new PutnickoRepozitorijum(context)); } } public ITeretnaRepozitorijum Teretna { get { return teretna ?? (teretna = new TeretnoRepozitorijum(context)); } } public IVlasnikRepozitorijum Vlasnici { get { return vlasnici ?? (vlasnici = new VlasnikRepozitorijum(context)); } } public IRadnikRepozitorijum Radnici { get { return radnici ?? (radnici = new RadnikRepozitorijum(context)); } } public IOrganizacijaRepozitorijum Organizacije { get { return organizacije ?? (organizacije = new OrganizacijaRepozitorijum(context)); } } public IRegistracijaRepozitorijum Registracije { get { return registracije ?? (registracije = new RegistracijaRepozitorijum(context)); } } public void Sacuvaj() { context.SaveChanges(); } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IRadnikRepozitorijum { IEnumerable<Radnik> VratiSve(); Radnik VratiPoId(int id); void Dodaj(Radnik radnik); void Obrisi(Radnik radnik); } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Modeli; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class RadnikForm : MetroFramework.Forms.MetroForm { private UnitOfWork unit; private int idSelekt; private List<string> orgs = new List<string>(); public RadnikForm() { InitializeComponent(); var context = new VoziloContext(); unit = new UnitOfWork(context); dgvRadnici.DataSource = unit.Radnici.VratiSve(); var sveOrg = unit.Organizacije.VratiSve(); foreach(var org in sveOrg) { orgs.Add(org.ToString()); } cmbOrganizacija.DataSource = orgs; } private void RadnikForm_Load(object sender, EventArgs e) { } private void metroTextBox1_Click(object sender, EventArgs e) { } private void lbOrganizacija_Click(object sender, EventArgs e) { } private void dgvRadnici_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void btnDodaj_Click(object sender, EventArgs e) { try { var novi = new Radnik(); novi.Ime = txtIme.Text; novi.Prezime = txtPrezime.Text; novi.Godine = int.Parse(txtGod.Text); novi.OrganizacijaId = int.Parse(cmbOrganizacija.Text.Split(' ')[0]); unit.Radnici.Dodaj(novi); unit.Sacuvaj(); MessageBox.Show("Radnik dodat."); dgvRadnici.DataSource = unit.Radnici.VratiSve(); } catch (Exception ex) { MessageBox.Show("Uneti podaci nisu validni."); } } private void dgvRadnici_CellClick(object sender, DataGridViewCellEventArgs e) { try { var ind = e.RowIndex; idSelekt = int.Parse(dgvRadnici[0, ind].Value.ToString()); lblBrisanje.Text = "Radnik za brisanje (ID):"; lblBrisanje.Text = "Radnik za brisanje (ID):" + idSelekt.ToString(); var odabran = unit.Radnici.VratiPoId(idSelekt); txtIme.Text = odabran.Ime; txtPrezime.Text = odabran.Prezime; txtGod.Text = odabran.Godine.ToString(); cmbOrganizacija.Text = odabran.OrganizacijaId.ToString(); } catch(Exception ex) { MessageBox.Show("Greska."); } } private void btnBrisanje_Click(object sender, EventArgs e) { try { var radnik = unit.Radnici.VratiPoId(idSelekt); unit.Radnici.Obrisi(radnik); unit.Sacuvaj(); dgvRadnici.DataSource = unit.Radnici.VratiSve(); MessageBox.Show("Radnik obrisan."); } catch (Exception ex) { MessageBox.Show("Radnik obrisan."); } } private void btnIzmeni_Click(object sender, EventArgs e) { try { var radnik = unit.Radnici.VratiPoId(idSelekt); radnik.Ime = txtIme.Text; radnik.Prezime = txtPrezime.Text; radnik.Godine = int.Parse(txtGod.Text); radnik.OrganizacijaId = int.Parse(cmbOrganizacija.Text.Split(' ')[0]); unit.Sacuvaj(); dgvRadnici.Refresh(); // dgvRadnici.DataSource = unit.Radnici.VratiSve(); MessageBox.Show("Radnik izmenjen."); } catch (Exception ex) { MessageBox.Show("Radnik obrisan."); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Vlasnik { public Vlasnik() { Vozila = new List<Vozilo>(); } public int VlasnikId { set; get; } public string Ime { set; get; } public string Prezime { set; get;} public ICollection<Vozilo> Vozila { set; get; } public override String ToString() { return VlasnikId.ToString() + ' ' + Ime + ' ' + Prezime; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Putnicko { public int PutnickoId { set; get; } public string Proizvodjac { set; get; } public string Tip { set; get; } public int GodProizvodnje { set; get; } public float Snaga { set; get; } public string Boja { set; get; } public Registracija Registracija { set; get; } public Vlasnik Vlasnik { set; get; } public int VlasnikId { set; get; } public override string ToString() { return PutnickoId.ToString() + " " + Proizvodjac; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Teretno { public int TeretnoId { set; get; } public string Proizvodjac { set; get; } public string Tip { set; get; } public int GodProizvodnje { set; get; } public float Nosivost { set; get; } public string Boja { set; get; } public Registracija Registracija { set; get; } public Vlasnik Vlasnik { set; get; } public int VlasnikId { set; get; } public override string ToString() { return TeretnoId.ToString() + " " + Proizvodjac; } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IVlasnikRepozitorijum { IEnumerable<Vlasnik> VratiSve(); Vlasnik VratiPoId(int id); void Dodaj(Vlasnik vlasnik); void Obrisi(Vlasnik vlasnik); IEnumerable<Putnicko> MojaPutnicka(int vlasnikId); IEnumerable<Teretno> MojaTeretna(int vlasnikId); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Registracija { public int RegistracijaId { set; get; } public int Cena { set; get; } public string Datum { set; get; } public Radnik Radnik { set; get; } public int RadnikId { set; get; } public int VoziloId { set; get; } public string tipVozila { set; get; } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { class TeretnoRepozitorijum : ITeretnaRepozitorijum { private VoziloContext context; public TeretnoRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Teretno vozilo) { context.Teretna.Add(vozilo); } public void Obrisi(Teretno vozilo) { context.Teretna.Remove(vozilo); } public Teretno VratiPoId(int id) { return context.Teretna.Find(id); } public IEnumerable<Teretno> VratiSva() { return context.Teretna.ToList(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Modeli { public class Radnik { public int RadnikId { set; get; } public string Ime { set; get; } public string Prezime { set; get; } public int Godine { set; get; } public Organizacija Organizacija { set; get; } public int OrganizacijaId { set; get; } public override string ToString() { return RadnikId.ToString() + " " + Ime + " " + Prezime; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IUnitOfWork { IPutnickoRepozitorijum Vozila { get;} ITeretnaRepozitorijum Teretna { get; } IVlasnikRepozitorijum Vlasnici { get; } IRadnikRepozitorijum Radnici { get; } IOrganizacijaRepozitorijum Organizacije { get; } IRegistracijaRepozitorijum Registracije { get; } void Sacuvaj(); } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface ITeretnaRepozitorijum { IEnumerable<Teretno> VratiSva(); Teretno VratiPoId(int id); void Dodaj(Teretno vozilo); void Obrisi(Teretno vozilo); } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.IRepozitorijumi; using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Repozitorijumi { public class VlasnikRepozitorijum : IVlasnikRepozitorijum { private VoziloContext context; public VlasnikRepozitorijum(VoziloContext context) { this.context = context; } public void Dodaj(Vlasnik vlasnik) { context.Vlasnici.Add(vlasnik); } public void Obrisi(Vlasnik vlasnik) { context.Vlasnici.Remove(vlasnik); } public Vlasnik VratiPoId(int id) { return context.Vlasnici.Find(id); } public IEnumerable<Vlasnik> VratiSve() { return context.Vlasnici.ToList(); } public IEnumerable<Putnicko> MojaPutnicka(int vlasnikId) { return context.Putnicka.Where(v => v.VlasnikId == vlasnikId).ToList(); } public IEnumerable<Teretno> MojaTeretna(int vlasnikId) { return context.Teretna.Where(v => v.VlasnikId == vlasnikId).ToList(); } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.Baza { public class VoziloContext : DbContext { public virtual DbSet<Putnicko> Putnicka { set; get; } public virtual DbSet<Teretno> Teretna { set; get; } public virtual DbSet<Radnik> Radnici { set; get; } public virtual DbSet<Vlasnik> Vlasnici { set; get; } public virtual DbSet<Organizacija> Organizacije { set; get; } public virtual DbSet<Registracija> Registracije { set; get; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Modeli.Registracija>().HasKey(r => r.RegistracijaId); modelBuilder.Entity<Radnik>().HasKey(ra => ra.RadnikId); modelBuilder.Entity<Vlasnik>().HasKey(v => v.VlasnikId); modelBuilder.Entity<Putnicko>().HasKey(vz => vz.PutnickoId); modelBuilder.Entity<Teretno>().HasKey(vz => vz.TeretnoId); modelBuilder.Entity<Organizacija>().HasKey(o => o.OrganizacijaId); // modelBuilder.Entity<Modeli.Registracija>().HasRequired(r => r.Radnik).WithOptional(ra => ra.Registracija); modelBuilder.Entity<Vlasnik>().Property(v => v.Ime).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Vlasnik>().Property(v => v.Prezime).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Radnik>().Property(ra => ra.Ime).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Radnik>().Property(ra => ra.Prezime).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Radnik>().Property(ra => ra.Godine).IsOptional(); modelBuilder.Entity<Organizacija>().Property(o => o.Naziv).HasMaxLength(30).IsRequired(); modelBuilder.Entity<Organizacija>().Property(o => o.Grad).HasMaxLength(15).IsRequired(); modelBuilder.Entity<Organizacija>().Property(o => o.Ulica).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Modeli.Registracija>().Property(r => r.Cena).IsRequired(); modelBuilder.Entity<Modeli.Registracija>().Property(r => r.tipVozila).IsRequired(); modelBuilder.Entity<Modeli.Registracija>().Property(r => r.Datum).IsRequired(); modelBuilder.Entity<Putnicko>().Property(vz => vz.Proizvodjac).HasMaxLength(20).IsRequired(); modelBuilder.Entity <Putnicko> ().Property(vz => vz.Tip).HasMaxLength(20).IsRequired(); modelBuilder.Entity < Putnicko > ().Property(vz => vz.GodProizvodnje).IsRequired(); modelBuilder.Entity<Putnicko>().Property(vz => vz.Boja).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Teretno>().Property(vz => vz.Proizvodjac).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Teretno>().Property(vz => vz.Tip).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Teretno>().Property(vz => vz.GodProizvodnje).IsRequired(); modelBuilder.Entity<Teretno>().Property(vz => vz.Boja).HasMaxLength(20).IsRequired(); modelBuilder.Entity<Teretno>().Property(vz => vz.Nosivost).IsRequired(); modelBuilder.Entity<Putnicko>().Property(vz => vz.Snaga).IsRequired(); } } } <file_sep>using RegistracijaVozila.Baza; using RegistracijaVozila.Modeli; using RegistracijaVozila.Repozitorijumi; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RegistracijaVozila { public partial class VozilaForm : MetroFramework.Forms.MetroForm { private UnitOfWork unit; private List<string> boje; private List<Putnicko> putnickaSva; private List<Teretno> teretnaSva; private bool putnickoIliNe = true; private int idIzmena = 0; public VozilaForm() { InitializeComponent(); var context = new VoziloContext(); unit = new UnitOfWork(context); putnickaSva = unit.Vozila.VratiSva().ToList(); teretnaSva = unit.Teretna.VratiSva().ToList(); dgvVozila.DataSource = putnickaSva; // dgvVozila.DataSource = context.Vozila.ToList(); boje = new List<string>(); boje.Add("Crna"); boje.Add("Siva"); boje.Add("Bela"); boje.Add("Crvena"); boje.Add("Zuta"); boje.Add("Plava"); boje.Add("Zelena"); cmbBoja.DataSource = boje; var tipovi = new List<string>(); tipovi.Add("Putnicko"); tipovi.Add("Teretno"); cmbTip.DataSource = tipovi; var vlasnici = unit.Vlasnici.VratiSve(); List<string> vlasniciBiraj = new List<string>(); foreach (var v in vlasnici) { vlasniciBiraj.Add(v.ToString()); } cmbVlasnik.DataSource = vlasniciBiraj; } private void dgvVozila_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void metroTextBox3_Click(object sender, EventArgs e) { } private void metroLabel1_Click(object sender, EventArgs e) { } private void metroLabel7_Click(object sender, EventArgs e) { } private void metroLabel3_Click(object sender, EventArgs e) { } private void metroButton1_Click(object sender, EventArgs e) { try { var proizvodjac = txtPro.Text; var tip = cmbTip.Text; var godina = int.Parse(txtGodina.Text); var boja = cmbBoja.Text; var razdvoj = cmbVlasnik.Text.Split(' '); var vlasnik = unit.Vlasnici.VratiPoId(int.Parse(razdvoj[0])); var snaga = txtSnaga.Text != ""? float.Parse(txtSnaga.Text) : 100; var nosivost = txtTeret.Text != "" ? float.Parse(txtTeret.Text) : 100; if(tip=="Putnicko") { var novo = new Putnicko(); novo.Boja = boja; novo.Proizvodjac = proizvodjac; novo.Vlasnik = vlasnik; novo.Snaga = snaga; novo.GodProizvodnje = godina; novo.Tip = tip; unit.Vozila.Dodaj(novo); unit.Sacuvaj(); dgvVozila.DataSource = unit.Vozila.VratiSva(); } else { var novo = new Teretno(); novo.Boja = boja; novo.Proizvodjac = proizvodjac; novo.Vlasnik = vlasnik; novo.Nosivost = nosivost; novo.GodProizvodnje = godina; novo.Tip = tip; unit.Teretna.Dodaj(novo); unit.Sacuvaj(); dgvVozila.DataSource = unit.Teretna.VratiSva(); } MessageBox.Show("Dodat auto"); } catch(Exception ex) { MessageBox.Show("Uneti podaci nisu ispravni."); } } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { } private void metroButton2_Click(object sender, EventArgs e) { dgvVozila.DataSource = putnickaSva; putnickoIliNe = true; dgvVozila.Refresh(); } private void metroButton3_Click(object sender, EventArgs e) { dgvVozila.DataSource = teretnaSva; putnickoIliNe = false; dgvVozila.Refresh(); } private void dgvVozila_CellClick(object sender, DataGridViewCellEventArgs e) { try { Putnicko vozilo = null; Teretno vozilo2 = null; var ind = e.RowIndex; idIzmena = int.Parse(dgvVozila[0, ind].Value.ToString()); if(putnickoIliNe) { vozilo = unit.Vozila.VratiPoId(idIzmena); txtGodina.Text = vozilo.GodProizvodnje.ToString(); txtPro.Text = vozilo.Proizvodjac.ToString(); txtSnaga.Text = vozilo.Snaga.ToString(); cmbBoja.Text = vozilo.Boja.ToString(); cmbVlasnik.Text = vozilo.VlasnikId.ToString(); lblBrisanje.Text = "Vozilo za brisanje (ID):"; lblBrisanje.Text = lblBrisanje.Text + "Putnicko " + vozilo.PutnickoId.ToString(); } else { vozilo2 = unit.Teretna.VratiPoId(idIzmena); txtGodina.Text = vozilo2.GodProizvodnje.ToString(); txtPro.Text = vozilo2.Proizvodjac.ToString(); txtTeret.Text = vozilo2.Nosivost.ToString(); cmbBoja.Text = vozilo2.Boja.ToString(); cmbVlasnik.Text = vozilo2.VlasnikId.ToString(); lblBrisanje.Text = "Vozilo za brisanje (ID):"; lblBrisanje.Text = lblBrisanje.Text + "Teretno " + vozilo2.TeretnoId.ToString(); } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnIzmeni_Click(object sender, EventArgs e) { try { Putnicko vozilo = null; Teretno vozilo2 = null; if (putnickoIliNe) { vozilo = unit.Vozila.VratiPoId(idIzmena); var proizvodjac = txtPro.Text; var godina = int.Parse(txtGodina.Text); var boja = cmbBoja.Text; var razdvoj = cmbVlasnik.Text.Split(' '); var vlasnik = unit.Vlasnici.VratiPoId(int.Parse(razdvoj[0])); var snaga = txtSnaga.Text != "" ? float.Parse(txtSnaga.Text) : 100; vozilo.Proizvodjac = proizvodjac; vozilo.GodProizvodnje = godina; vozilo.Boja = boja; vozilo.Vlasnik = vlasnik; vozilo.Snaga = snaga; unit.Sacuvaj(); dgvVozila.Refresh(); MessageBox.Show("Izmene uspesne."); } else { vozilo2 = unit.Teretna.VratiPoId(idIzmena); var proizvodjac = txtPro.Text; var godina = int.Parse(txtGodina.Text); var boja = cmbBoja.Text; var razdvoj = cmbVlasnik.Text.Split(' '); var vlasnik = unit.Vlasnici.VratiPoId(int.Parse(razdvoj[0])); var teret = txtTeret.Text != "" ? float.Parse(txtTeret.Text) : 100; vozilo2.Proizvodjac = proizvodjac; vozilo2.GodProizvodnje = godina; vozilo2.Boja = boja; vozilo2.Vlasnik = vlasnik; vozilo2.Nosivost = teret; unit.Sacuvaj(); dgvVozila.Refresh(); MessageBox.Show("Izmene uspesne."); } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void btnBrisanje_Click(object sender, EventArgs e) { try { if(putnickoIliNe) { var vozilo = unit.Vozila.VratiPoId(idIzmena); unit.Vozila.Obrisi(vozilo); unit.Sacuvaj(); dgvVozila.DataSource = unit.Vozila.VratiSva(); lblBrisanje.Text = "Vozilo za brisanje (ID):"; MessageBox.Show("Vozilo obrisano."); } else { var vozilo2 = unit.Teretna.VratiPoId(idIzmena); unit.Teretna.Obrisi(vozilo2); unit.Sacuvaj(); dgvVozila.DataSource = unit.Teretna.VratiSva(); lblBrisanje.Text = "Vozilo za brisanje (ID):"; MessageBox.Show("Vozilo obrisano."); } } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void VozilaForm_Load(object sender, EventArgs e) { } } } <file_sep>using RegistracijaVozila.Modeli; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RegistracijaVozila.IRepozitorijumi { public interface IRegistracijaRepozitorijum { IEnumerable<Registracija> VratiSve(); Registracija VratiPoId(int id); void Dodaj(Registracija registracija); void Obrisi(Registracija registracija); } }
096ccfee4497c4565ad07a63aa490ab3c248db9a
[ "C#" ]
28
C#
VahidM98/Registracija-vozila-Desktop-app
8fd28fa331efeac0be13c933dc4fbba8f138646a
536049f8270beeded2e7fc9cf2485454517bf5c4
refs/heads/master
<repo_name>trayvonc/course_scheduling<file_sep>/src/com/view/About.java package com.view; import static com.mytools.MyFont.f0; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.imageio.*; import javax.swing.*; import javax.swing.plaf.FontUIResource; public class About extends JDialog implements ActionListener,MouseListener{ /** * @param args */ JLabel jlclose; // public static void main(String[] args) { // // TODO 自动生成的方法存根 // About ul = new About(); // } int xOld = 0; int yOld = 0; public About() { // 设置文本显示效果 UIManager.put("OptionPane.messageFont", new FontUIResource(f0)); Container ct = this.getContentPane(); this.setLayout(null); jlclose = new JLabel("", new ImageIcon("image/999.png"), 0); jlclose.setBounds(455,4,25,25); jlclose.addMouseListener(this); jlclose.addMouseListener(this); jlclose.setToolTipText("关闭"); ct.add(jlclose); BackImage bi = new BackImage(); bi.setBounds(0, 0, 484,341); //this.add(bi); ct.add(bi); this.setUndecorated(true); this.setSize(484,341); int width = Toolkit.getDefaultToolkit().getScreenSize().width; int height = Toolkit.getDefaultToolkit().getScreenSize().height; this.setLocation(width / 2 - 200, height / 2 - 200); this.setVisible(true); //清除输入法控制 this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { xOld = e.getX();//记录鼠标按下时的坐标 yOld = e.getY(); } }); this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { int xOnScreen = e.getXOnScreen(); int yOnScreen = e.getYOnScreen(); int xx = xOnScreen - xOld; int yy = yOnScreen - yOld; About.this.setLocation(xx, yy);//设置拖拽后,窗口的位置 } }); } // 内部类 放图片 @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == jlclose) { this.dispose(); } // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseReleased(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. if (e.getSource() == jlclose) { java.net.URL imageUrl1=Windows1.class.getResource("/com/image/close-square.png"); this.jlclose.setIcon( new ImageIcon(imageUrl1)); } } @Override public void mouseExited(MouseEvent e) { if (e.getSource() == jlclose) { this.jlclose.setIcon( new ImageIcon("image/999.png")); } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public class BackImage extends JPanel { Image img; public BackImage() { try { java.net.URL imageUrl2=Windows1.class.getResource("/com/image/About.png"); img = ImageIO.read(imageUrl2); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public void paintComponent(Graphics g) { g.drawImage(img, 0, 0,484,341, this); } } //响应登录请求 @Override public void actionPerformed(ActionEvent e) { // TODO 自动生成的方法存根 // else if (e.getSource() == jcancel) { // // //当点击取消按钮时,关闭登陆框,退出系统 // this.dispose(); // } } } <file_sep>/src/com/view/Windows1.java package com.view; import com.model.EmpModel; import com.mytools.MyFont; import com.mytools.*; import static com.mytools.MyFont.f0; import static com.mytools.MyFont.f1; import java.util.*; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import javax.imageio.*; import java.io.*; import javax.swing.plaf.FontUIResource; public class Windows1 extends JFrame implements ActionListener, MouseListener,Runnable,MouseMotionListener { //定义需要的组件 Image titleIcon, timeBg, p1_bg, p3Icon, chart; ImagePanel p1_bgImage, jp3Image, ct; BackgroundMenuBar jmb; JSplitPane jsp; JMenu jm1, jm2, jm3, jm4, jm5, jm6; JMenuItem jmi1, jmi2, jmi3, jmi4, jmi5, jmi6, jmi7, jmi8, jmi9, jmi10, jmi11, jmi12; ImageIcon jmi1_icon1, jmi2_icon2, jmi3_icon3, jmi4_icon4, jmi5_icon5, jmi6_icon6, jmi7_icon7, jmi8_icon8, jmi9_icon9, jmi10_icon10, jmi11_icon11, jmi12_icon12; JToolBar jtb; JButton jb1, jb2, jb3, jb4, jb5, jb6, jb7, jb8, jb9, jb10; JPanel jp1, jp2, jp3, jp4, jp5; JLabel showTime;//显示时间 JLabel p2_jl1, p2_jl2,jl1,jl2,username; JLabel p1_jl1, p1_jl2, p1_jl3, p1_jl4, p1_jl5, p1_jl6, p1_jl7, p1_jl8; CardLayout myCard, myCard1; Timer t;//可定时触发Action事件 Vector<String> ss=null; EmpInfo ei=null; int bright=0; showTimeTable st=null; JTable showTable=null; SearchTimeTable st1=null; public static void main(String[] args) { //管理员测试登录 Vector<String> s=new Vector<String>(); s.add("1"); s.add("gm"); s.add("gm"); Windows1 w1 = new Windows1(s); } //菜单 public void initMenu() { //一级菜单 java.net.URL imageUrl1=Windows1.class.getResource("/com/image/toolBar_image/form1.png"); java.net.URL imageUrl2=Windows1.class.getResource("/com/image/toolBar_image/profile1.png"); java.net.URL imageUrl3=Windows1.class.getResource("/com/image/toolBar_image/settings1.png"); java.net.URL imageUrl4=Windows1.class.getResource("/com/image/toolBar_image/same1.png"); java.net.URL imageUrl5=Windows1.class.getResource("/com/image/toolBar_image/exit1.png"); jmi1_icon1 = new ImageIcon(imageUrl1); jmi2_icon2 = new ImageIcon(imageUrl2); jmi3_icon3 = new ImageIcon(imageUrl3); jmi4_icon4 = new ImageIcon(imageUrl4); jmi5_icon5 = new ImageIcon(imageUrl5); jm1 = new JMenu("系统管理"); jm1.setFont(MyFont.f3); //创建其二级菜单 // jmi1=new JMenuItem("切换用户",jmi1_icon1); // jmi1.setFont(MyFont.f2); jmi2 = new JMenuItem("个人管理", jmi2_icon2); jmi2.addActionListener(this); jmi2.setActionCommand("me"); jmi2.setFont(MyFont.f2); jmi3 = new JMenuItem("系统设置", jmi3_icon3); jmi3.addActionListener(this); jmi3.setActionCommand("tools"); jmi3.setFont(MyFont.f2); // jmi4=new JMenuItem("NULL",jmi4_icon4); // jmi4.setFont(MyFont.f2); jmi5 = new JMenuItem("安全退出", jmi5_icon5); jmi5.addActionListener(this); jmi5.setActionCommand("Exit"); jmi5.setFont(MyFont.f2); //jm1.add(jmi1); jm1.add(jmi2); jm1.add(jmi3); //jm1.add(jmi4); jm1.add(jmi5); java.net.URL imageUrl6=Windows1.class.getResource("/com/image/toolBar_image/group1.png"); jmi6_icon6 = new ImageIcon(imageUrl6); jm2 = new JMenu("人事记录"); jm2.setFont(MyFont.f3); jmi6 = new JMenuItem("人事管理", jmi6_icon6); jmi6.setFont(MyFont.f2); jmi6.addActionListener(this); jmi6.setActionCommand("Emp"); jm2.add(jmi6); java.net.URL imageUrl7=Windows1.class.getResource("/com/image/toolBar_image/sort1.png"); jmi7_icon7 = new ImageIcon(imageUrl7); jm3 = new JMenu("录入信息"); jm3.setFont(MyFont.f3); jmi7 = new JMenuItem("录入实验室", jmi7_icon7); jmi7.setFont(MyFont.f2); jmi7.addActionListener(this); jmi7.setActionCommand("Addlab"); jm3.add(jmi7); jmi8 = new JMenuItem("录入申请", jmi1_icon1); jmi8.setFont(MyFont.f2); jmi8.addActionListener(this); jmi8.setActionCommand("Addapp"); jm3.add(jmi8); java.net.URL imageUrl8=Windows1.class.getResource("/com/image/toolBar_image/punch1.png"); jmi8_icon8 = new ImageIcon(imageUrl8); jm4 = new JMenu("课表服务"); jm4.setFont(MyFont.f3); jmi9 = new JMenuItem("课表生成", jmi8_icon8); jmi9.setFont(MyFont.f2); jm4.add(jmi9); jmi9.addActionListener(this); jmi9.setActionCommand("create"); // jmi9.addActionListener( e-> { // new Thread(() -> { // try { // // Thread.sleep(3000); // SwingUtilities.invokeLater(() -> new NQueens()); // //Thread.sleep(3000); // SwingUtilities.invokeLater(() -> jl2.setText("课表生成成功,快去查看课表吧!")); // // SwingUtilities.invokeLater(() -> jl2.setText("1.检查数据合法性...")); // //Thread.sleep(3000);//模仿检测数据合法性 // //SwingUtilities.invokeLater(()-> jl2.setText("2.正在导入数据...")); // //Thread.sleep(4000);//模仿导入数据 // //SwingUtilities.invokeLater(() -> jl2.setText("3.导入成功!")); // } catch (Exception e1) { // e1.printStackTrace(); // } // }).start(); // }); jmi10 = new JMenuItem("课表查询", jmi4_icon4); jmi10.setFont(MyFont.f2); jm4.add(jmi10); jmi10.addActionListener(this); jmi10.setActionCommand("timetable"); java.net.URL imageUrl10=Windows1.class.getResource("/com/image/toolBar_image/info1.png"); //java.net.URL imageUrl11=Windows1.class.getResource("/com/image/toolBar_image/jb10.jpg"); java.net.URL imageUrl12=Windows1.class.getResource("/com/image/toolBar_image/emoji1.png"); jmi10_icon10 = new ImageIcon(imageUrl10); //jmi11_icon11 = new ImageIcon(imageUrl11); jmi12_icon12 = new ImageIcon(imageUrl12); jm6 = new JMenu("帮助"); jm6.setFont(MyFont.f3); jmi11 = new JMenuItem("文本帮助", jmi10_icon10); jmi11.setFont(MyFont.f2); jmi12 = new JMenuItem("关于我们", jmi12_icon12); jmi12.setFont(MyFont.f2); jmi11.setFont(MyFont.f2); jm6.add(jmi11); jm6.add(jmi12); jmi11.addActionListener(this); jmi11.setActionCommand("info"); jmi12.addActionListener(this); jmi12.setActionCommand("About"); jmb = new BackgroundMenuBar(); jmb.add(jm1); jmb.add(jm2); jmb.add(jm3); jmb.add(jm4); jmb.add(jm6); int width = Toolkit.getDefaultToolkit().getScreenSize().width; int height = Toolkit.getDefaultToolkit().getScreenSize().height; this.setJMenuBar(jmb); } //工具栏1111 // public void initToolBar() // { // jtb=new JToolBar(); // jtb.setFloatable(false); // jb1=new JButton(new ImageIcon("image/jm1_icon1.jpg")); // jb2=new JButton(new ImageIcon("image/jm1_icon2.jpg")); // jb3=new JButton(new ImageIcon("image/jm1_icon3.jpg")); // jb4=new JButton(new ImageIcon("image/jm1_icon4.jpg")); // jb5=new JButton(new ImageIcon("image/toolBar_image/jb5.jpg")); // jb6=new JButton(new ImageIcon("image/toolBar_image/jb6.jpg")); // jb7=new JButton(new ImageIcon("image/toolBar_image/jb7.jpg")); // jb8=new JButton(new ImageIcon("image/toolBar_image/jb8.jpg")); // jb9=new JButton(new ImageIcon("image/toolBar_image/jb9.jpg")); // jb10=new JButton(new ImageIcon("image/toolBar_image/jb10.jpg")); // jtb.add(jb1); // jtb.add(jb2); // jtb.add(jb3); // jtb.add(jb4); // jtb.add(jb5); // jtb.add(jb6); // jtb.add(jb7); // jtb.add(jb8); // jtb.add(jb9); // jtb.add(jb10); // // } public void initCenter(Vector<String> s) { //存放头像和昵称 JPanel jp_user=new JPanel(); //jp1 jp1 = new JPanel(new BorderLayout()); try { java.net.URL imageUrl13=Windows1.class.getResource("/com/image/center_image/jp1_bg.jpg"); p1_bg = ImageIO.read(imageUrl13); } catch (IOException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } Cursor myCursor = new Cursor(HAND_CURSOR); p1_bgImage = new ImagePanel(p1_bg); p1_bgImage.setLayout(new GridLayout(8, 1)); if(s.get(2).equals("gm")){ java.net.URL imageUrl14=Windows1.class.getResource("/com/image/center_image/gm.png"); p1_jl1 = new JLabel(new ImageIcon(imageUrl14)); }else if(s.get(2).equals("student")){ java.net.URL imageUrl15=Windows1.class.getResource("/com/image/center_image/student.png"); p1_jl1 = new JLabel(new ImageIcon(imageUrl15)); }else if(s.get(2).equals("teacher")){ java.net.URL imageUrl16=Windows1.class.getResource("/com/image/center_image/teacher.png"); p1_jl1 = new JLabel(new ImageIcon(imageUrl16)); } jp_user.setLayout(null); jp_user.setOpaque(false); jp_user.add(p1_jl1); p1_jl1.setBounds(10,20,64,64); username = new JLabel(s.get(1)+""); username.setFont(MyFont.f3); username.setForeground(Color.lightGray); username.setBounds(80,40,64,20); jp_user.add(username); p1_bgImage.add(jp_user); java.net.URL imageUrl17=Windows1.class.getResource("/com/image/center_image/group.png"); p1_jl2 = new JLabel("人 事 管 理", new ImageIcon(imageUrl17), 0); p1_jl2.setFont(MyFont.f3); p1_jl2.setForeground(Color.lightGray); //让label 初始不可用 p1_jl2.setCursor(myCursor); //p1_jl2.setEnabled(false); p1_jl2.addMouseListener(this); p1_bgImage.add(p1_jl2); // p1_jl3=new JLabel("登 陆 管 理",new ImageIcon("image/center_image/label_3.jpg"),0); // p1_jl3.setFont(MyFont.f4); // p1_jl3.setCursor(myCursor); // p1_jl3.setEnabled(false); // p1_jl3.addMouseListener(this); // p1_bgImage.add(p1_jl3); java.net.URL imageUrl18=Windows1.class.getResource("/com/image/center_image/sort.png"); p1_jl4 = new JLabel("录入 实验室", new ImageIcon(imageUrl18), 0); p1_jl4.setFont(MyFont.f3); p1_jl4.setForeground(Color.lightGray); p1_jl4.setCursor(myCursor); //p1_jl4.setEnabled(false); p1_jl4.addMouseListener(this); p1_bgImage.add(p1_jl4); java.net.URL imageUrl19=Windows1.class.getResource("/com/image/center_image/form.png"); p1_jl5 = new JLabel("录 入 申 请", new ImageIcon(imageUrl19), 0); p1_jl5.setFont(MyFont.f3); p1_jl5.setForeground(Color.lightGray); p1_jl5.setCursor(myCursor); //p1_jl5.setEnabled(false); p1_jl5.addMouseListener(this); p1_bgImage.add(p1_jl5); java.net.URL imageUrl20=Windows1.class.getResource("/com/image/center_image/punch.png"); p1_jl6 = new JLabel("课 表 生 成", new ImageIcon(imageUrl20), 0); p1_jl6.setFont(MyFont.f3); p1_jl6.setForeground(Color.lightGray); p1_jl6.setCursor(myCursor); //p1_jl6.setEnabled(false); p1_jl6.addMouseListener(this); p1_bgImage.add(p1_jl6); java.net.URL imageUrl21=Windows1.class.getResource("/com/image/center_image/same.png"); p1_jl7 = new JLabel("课 表 查 询", new ImageIcon(imageUrl21), 0); p1_jl7.setFont(MyFont.f3); p1_jl7.setForeground(Color.lightGray); p1_jl7.setCursor(myCursor); // p1_jl7.setEnabled(false); p1_jl7.addMouseListener(this); p1_bgImage.add(p1_jl7); java.net.URL imageUrl22=Windows1.class.getResource("/com/image/center_image/settings.png"); p1_jl8 = new JLabel("系 统 设 置", new ImageIcon(imageUrl22), 0); p1_jl8.setFont(MyFont.f3); p1_jl8.setForeground(Color.lightGray); p1_jl8.setCursor(myCursor); //p1_jl8.setEnabled(false); p1_jl8.addMouseListener(this); p1_bgImage.add(p1_jl8); jp1.add(p1_bgImage); //jp4,jp2,jp3 myCard = new CardLayout(); myCard1 = new CardLayout(); jp4 = new JPanel(new BorderLayout()); jp2 = new JPanel(myCard1); java.net.URL imageUrl23=Windows1.class.getResource("/com/image/center_image/jp2_left.jpg"); p2_jl1 = new JLabel(new ImageIcon(imageUrl23)); p2_jl1.setToolTipText("折叠"); //图标切换 p2_jl1.addMouseListener(this); java.net.URL imageUrl24=Windows1.class.getResource("/com/image/center_image/jp2_right.jpg"); p2_jl2 = new JLabel(new ImageIcon(imageUrl24)); p2_jl2.setToolTipText("展开"); p2_jl2.addMouseListener(this); jp2.add(p2_jl1, "0"); jp2.add(p2_jl2, "1"); jp3 = new JPanel(myCard); //先给jp3加入主界面卡片 try { java.net.URL imageUrl25=Windows1.class.getResource("/com/image/center_image/jp3_bg.jpg"); p3Icon = ImageIO.read(imageUrl25); } catch (IOException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } jp3Image = new ImagePanel(p3Icon); jp3.add(jp3Image, "0"); //人事管理 ei = new EmpInfo(s); jp3.add(ei, "1"); //实验室界面 LabInfo li = new LabInfo(); jp3.add(li, "3"); //申请界面 AppInfo ai = new AppInfo(); jp3.add(ai, "4"); //线程查询太耗费资源了 // Thread t=new Thread(ai); // t.start(); //生成表界面 //ImageIcon p3Icon1 =new ImageIcon("image/center_image/loading.gif"); java.net.URL imageUrl26=Windows1.class.getResource("/com/image/center_image/loading.gif"); jl1=new JLabel(new ImageIcon(imageUrl26)); jl2=new JLabel("哈哈哈"); jl2.setFont(f1); JPanel jp=new JPanel(); jp.setLayout(null); jl1.setBounds(430,100, 256,256); jl2.setBounds(430,250, 256,256); jp.add(jl1); jp.add(jl2); jp3.add(jp, "5"); //课表查询界面 st=new showTimeTable(); // String tname=null; // try{ // st1=new SearchTimeTable(tname); // }catch(Exception e){ // e.printStackTrace(); // } jp3.add(st, "6"); //系统设置 Image p3Icon1=null; try { java.net.URL imageUrl27=Windows1.class.getResource("/com/image/center_image/jp3_bg.jpg"); p3Icon1 = ImageIO.read(imageUrl27); } catch (IOException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } ImagePanel jp3Image1 = new ImagePanel(p3Icon1); jp3.add(jp3Image1, "7"); // //报表统计 // try { // chart=ImageIO.read(new File("image/chart.jpg")); // } catch (IOException e) { // // TODO 自动生成的 catch 块 // e.printStackTrace(); // } // ct=new ImagePanel(chart); // //ct.setBounds(0, 0, this.getWidth()-50, this.getHeight()-10); // jp3.add(ct,"4"); //系统设置 // OperatChoose oc=new OperatChoose(); // jp3.add(oc,"6"); jp4.add(jp2, "West"); jp4.add(jp3, "Center"); jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jp1, jp4); jsp.setDividerLocation(150); jsp.setDividerSize(0); } //状态栏 public void initEnd() { jp5 = new JPanel(new BorderLayout()); //t = new Timer(1000, this);//每隔一秒触发ActonEvent Thread t = new Thread(this); showTime = new JLabel(Calendar.getInstance().getTime().toLocaleString() + " "); java.net.URL imageUrl28=Windows1.class.getResource("/com/image/时间.png"); showTime.setIcon(new ImageIcon(imageUrl28)); showTime.setFont(MyFont.f1); showTime.setForeground(Color.PINK); t.start(); try { java.net.URL imageUrl29=Windows1.class.getResource("/com/image/time_bg.jpg"); timeBg = ImageIO.read(imageUrl29); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } ImagePanel ip1 = new ImagePanel(timeBg); ip1.setLayout(new BorderLayout()); ip1.add(showTime, "East"); jp5.add(ip1); } public Windows1(Vector<String> s) { // 设置文本显示效果 UIManager.put("OptionPane.messageFont", new FontUIResource(f0)); try { java.net.URL imageUrl30=Windows1.class.getResource("/com/image/center_image/"+s.get(2)+".png"); titleIcon = ImageIO.read(imageUrl30); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } this.ss=s; //菜单 this.initMenu(); //工具栏 //this.initToolBar(); //中间 this.initCenter(s); //状态栏 this.initEnd(); Container ct = this.getContentPane(); // ct.add(jtb,"North"); ct.add(jp5, "South"); ct.add(jsp, "Center"); int width = Toolkit.getDefaultToolkit().getScreenSize().width; int height = Toolkit.getDefaultToolkit().getScreenSize().height; this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(width - 600, height - 300); this.setLocation(400, 200); this.setIconImage(titleIcon); this.setTitle("实验室安排系统"); //this.getContentPane().add(new GetFilePathSingle().getPanel()); //测试读取 //List<GetApp> list = new ArrayList<GetApp>(); //list=new ExcelOperationUtil().readExcelData(); //去掉上边框 // this.addMouseListener(this); // this.addMouseMotionListener(this); // this.setUndecorated(true); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO 自动生成的方法存根 if (e.getActionCommand().equals("Emp")) { this.myCard.show(jp3, "1"); this.setTitle("人事管理-实验室安排系统"); //颜色控制 this.p1_jl2.setForeground(Color.white); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); }else if (e.getActionCommand().equals("Addlab")) { this.myCard.show(jp3, "3"); this.setTitle("录入实验室-实验室安排系统"); bright=2; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.white); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); }else if (e.getActionCommand().equals("Addapp")) { this.myCard.show(jp3, "4"); this.setTitle("录入申请-实验室安排系统"); bright=3; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.white); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); }else if (e.getActionCommand().equals("Exit")) { System.exit(0); }else if (e.getActionCommand().equals("create")) { this.myCard.show(jp3, "5"); this.setTitle("课表生成-实验室安排系统"); jl2.setText(" 正在为您生成课表,请稍后。。。"); bright=4; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.white); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); //运行排课程序 NQueens nQueens=new NQueens(jl2); Thread t=new Thread(nQueens); t.start(); showTable=st.returnjJTable(); //全部删除以前的表 String sql = "delete from general_table"; EmpModel em = new EmpModel(); em.deleteModel(sql); }else if (e.getActionCommand().equals("me")) { //更改个人信息 String empId =ss.get(0); String sql = "select * from login where id=?"; String[] params = {empId}; EmpModel emme = new EmpModel(); emme.query(sql, params); new UpdEmpDialog(ei, "修改个人信息", true, emme, 0, ei.jtable,username); //下面两句执行的时间过早 // System.out.println(emme.getValueAt(0, 1)+""); // username.setText(emme.getValueAt(0, 1)+""); }else if (e.getActionCommand().equals("timetable")) { this.myCard.show(jp3, "6"); this.setTitle("课表查询-实验室安排系统"); bright=5; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.white); this.p1_jl8.setForeground(Color.lightGray); //刷新课表 st.flashTable(); }else if (e.getActionCommand().equals("About")) { About about = new About(); }else if (e.getActionCommand().equals("info")) { final JDialog dialog = new JDialog(this, "提示", true); Font f1 = new Font("宋体", Font.BOLD, 18); JPanel jp = new JPanel(); jp.setLayout(new GridLayout(1, 1)); JTextArea jta = new JTextArea("*人事管理可以增加人员,只有管理员可以删改\r\n*修改个人信息请使用左上角个人管理\r\n*可以录入实验室地址和座位数\r\n*录入申请支持增删改查\r\n*录入申请支持批量导入和拖拽导入\r\n*录入申请支持一键清空\r\n*课表生成尽量满足老师的上课选择期望\r\n*课表生成按照先申请优先满足的原则\r\n*课表查询支持按老师查询和按班级查询\r\n*此软件纯属娱乐,版权问题概不负责", 20, 10); jta.setFont(f1); jp.add(jta); dialog.add(jp); dialog.setSize(410, 240); dialog.setResizable(false); dialog.setLocation(800, 430); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setVisible(true); }else if (e.getActionCommand().equals("tools")) { this.myCard.show(jp3, "7"); this.setTitle("系统设置-实验室安排系统"); bright=6; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.white); } } @Override public void mouseClicked(MouseEvent arg0) { // TODO 自动生成的方法存根 if (arg0.getSource() == p1_jl2) { this.myCard.show(jp3, "1"); this.setTitle("人事管理-实验室安排系统"); //颜色控制 bright=1; this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl4) { this.myCard.show(jp3, "3"); this.setTitle("录入实验室-实验室安排系统"); bright=2; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl5) { this.myCard.show(jp3, "4"); this.setTitle("录入申请-实验室安排系统"); bright=3; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl6) { this.myCard.show(jp3, "5"); this.setTitle("课表生成-实验室安排系统"); jl2.setText(" 正在为您生成课表,请稍后。。。"); bright=4; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); //全部删除以前的表 String sql = "delete from general_table"; EmpModel em = new EmpModel(); em.deleteModel(sql); //不能在这里运行排课程序,要调用线程 NQueens nQueens=new NQueens(jl2); Thread t=new Thread(nQueens); t.start(); } else if (arg0.getSource() == p1_jl7) { this.myCard.show(jp3, "6"); this.setTitle("课表查询-实验室安排系统"); bright=5; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl8.setForeground(Color.lightGray); st.flashTable(); } else if (arg0.getSource() == p1_jl8) { //MediaHelp mh=new MediaHelp(); this.myCard.show(jp3, "7"); this.setTitle("系统设置-实验室安排系统"); bright=6; this.p1_jl2.setForeground(Color.lightGray); this.p1_jl4.setForeground(Color.lightGray); this.p1_jl5.setForeground(Color.lightGray); this.p1_jl6.setForeground(Color.lightGray); this.p1_jl7.setForeground(Color.lightGray); } else if (arg0.getSource() == p2_jl1) { //把显示各种操作的界面隐藏起来(jp1),同时显示jp2卡片布局中的jp2_lab2(向右的箭头) //把拆分面板的左边隐藏起来,即隐藏jp1 this.jsp.setDividerLocation(0);//设置拆分面板的左边面板的大小为0像素,即不可见 //同时显示向右的箭头 this.myCard1.show(jp2, "1"); } else if (arg0.getSource() == p2_jl2) { //System.out.println("111111111"); //把隐藏的jp1面板展开,即设置左边面板拆分大小 this.jsp.setDividerLocation(150);//由于前面定义拆分面板时,左边占150像素,此时应显示150像素 //同时显示向左的箭头 this.myCard1.show(jp2, "0"); //this.jsp.setDividerLocation(Toolkit.getDefaultToolkit().getScreenSize().width); }else if (arg0.getSource() == jm2) { this.myCard.show(jp3, "1"); } else if (arg0.getSource() == jmi7) { this.myCard.show(jp3, "2"); } else if (arg0.getSource() == jmi8) { this.myCard.show(jp3, "3"); } else if (arg0.getSource() == jmi5) { System.exit(0); } } @Override public void mouseEntered(MouseEvent arg0) { // TODO 自动生成的方法存根 if (arg0.getSource() == p1_jl2) { this.p1_jl2.setForeground(Color.white); } else if (arg0.getSource() == p1_jl4) { this.p1_jl4.setForeground(Color.white); } else if (arg0.getSource() == p1_jl5) { this.p1_jl5.setForeground(Color.white); } else if (arg0.getSource() == p1_jl6) { this.p1_jl6.setForeground(Color.white); } else if (arg0.getSource() == p1_jl7) { this.p1_jl7.setForeground(Color.white); } else if (arg0.getSource() == p1_jl8) { this.p1_jl8.setForeground(Color.white); } } @Override public void mouseExited(MouseEvent arg0) { // TODO 自动生成的方法存根 if (arg0.getSource() == p1_jl2) { if(bright!=1) this.p1_jl2.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl4) { if(bright!=2) this.p1_jl4.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl5) { if(bright!=3) this.p1_jl5.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl6) { if(bright!=4) this.p1_jl6.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl7) { if(bright!=5) this.p1_jl7.setForeground(Color.lightGray); } else if (arg0.getSource() == p1_jl8) { if(bright!=6) this.p1_jl8.setForeground(Color.lightGray); } } // int xOld = 0; // int yOld = 0; @Override public void mousePressed(MouseEvent arg0) { // TODO 自动生成的方法存根 // xOld = arg0.getX();//记录鼠标按下时的坐标 // yOld = arg0.getY(); } @Override public void mouseReleased(MouseEvent arg0) { // TODO 自动生成的方法存根 } @Override public void run() { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. while (true) { //休眠 try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } //重画时间 this.showTime.setText(Calendar.getInstance().getTime().toLocaleString()+" "); } } @Override public void mouseDragged(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // int xOnScreen = e.getXOnScreen(); // int yOnScreen = e.getYOnScreen(); // int xx = xOnScreen - xOld; // int yy = yOnScreen - yOld; // Windows1.this.setLocation(xx, yy);//设置拖拽后,窗口的位置 } @Override public void mouseMoved(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } //创建JMenuBar对象修改内容 class BackgroundMenuBar extends JMenuBar { Color bgColor=Color.lightGray; public void setColor(Color color) { bgColor=color; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(bgColor); g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1); //Image img = new Image("image/toolBar_image/label_7.jpg"); // BufferedImage image = new BufferedImage(150, 150,BufferedImage.TYPE_3BYTE_BGR); // g2d.drawImage(img, 20, 0, 20, 20, this); } } <file_sep>/src/com/db/SqlHelper.java /* * 对数据库操作的类 * 对数据库的操作,就是crud * 调用存储过程 * *注意:如果连接数据库时出现如下异常则表示未引入三个JAR驱动包,另外一个原因就是SQL语句有语法错误 *java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDviver * */ package com.db; import java.sql.*; public class SqlHelper { //定义需要的对象 Connection ct=null; PreparedStatement ps=null; ResultSet rs=null; String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/time_table?characterEncoding=utf8&useSSL=false"; String user="root"; String passwd="<PASSWORD>"; int sum=0; //构造函数,初始化ct public SqlHelper() { try { //加载驱动 Class.forName(driver); System.out.println("Connecting to a selected database..."); //得到连接 ct=DriverManager.getConnection(url,user,passwd); System.out.println("Connected database successfully!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //[]paras,通过?赋值方式可以防止漏洞注入方式,保证安全性 public ResultSet query(String sql,String []paras) { try { ps=ct.prepareStatement(sql); //对sql的参数赋值 for(int i=0;i<paras.length;i++) { ps.setString(i+1, paras[i]); } //执行查询 rs=ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } //返回结果集 return rs; } public int queryExecute(String sql) { try { ps=ct.prepareStatement(sql); rs=ps.executeQuery(); if(rs.next()) { sum=rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } //返回结果集 return sum; } public void Delete(String sql) { try { Statement stmt=ct.createStatement();//创建Statement对象 stmt.executeUpdate(sql);//执行sql语句 } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } public boolean updateExecete(String sql,String []params) { //System.out.println("com.db.SqlHelper.updateExecete()"); boolean b=true; try { ps=ct.prepareStatement(sql); //对sql的参数赋值 for(int i=0;i<params.length;i++) { ps.setString(i+1, params[i]); } //执行查询 if(ps.executeUpdate()!=1) { b=false; } } catch (Exception e) { b=false; e.printStackTrace(); // TODO: handle exception } finally { this.close(); } //返回结果集 return b; } //关闭资源的方法 public void close() { try { if(rs!=null) rs.close(); if(ps!=null) ps.close(); if(ct!=null) ct.close(); } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } } <file_sep>/README.md ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/0.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/1.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/2.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/3.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/5.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/6.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/7.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/8.png) ![Image text](https://github.com/trayvonc/course_scheduling/blob/master/resimg/9.png) <file_sep>/src/com/mytools/addExcel.java package com.mytools; import java.awt.*; import com.view.*; import javax.swing.*; import javax.swing.JDialog; import java.util.List; import com.model.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Locale; //批量添加 public class addExcel extends JDialog{ JTable jtable; List<GetApp> list = null; public void doAddExcle(boolean model, JTable jtable,List<GetApp> list,int tmp){ this.jtable = jtable; this.list=list; String[] params = null; String sql = "insert into application(class,stu_num,address,teacher,week,time,Monday,Tuesday,Wednesday,Thurday,Friday) values(?,?,?,?,?,?,?,?,?,?,?)"; String[] tmplist = {list.get(tmp).getClasses(),list.get(tmp).getStu_num(),list.get(tmp).getAddress(),list.get(tmp).getTeacher(),list.get(tmp).getWeek(),list.get(tmp).getTime(),list.get(tmp).getMonday(),list.get(tmp).getTuesday(),list.get(tmp).getWednseday(),list.get(tmp).getThurday(),list.get(tmp).getFriday()}; params = tmplist; EmpModel em = new EmpModel(); boolean b=em.UpdateModel(sql, params); if (!b&&tmp==list.size()-1) { JOptionPane.showMessageDialog(null, "添加失败,请输入正确数据类型!"); } else if(b&&tmp==list.size()-1) { JOptionPane.showMessageDialog(null, "恭喜!添加成功!"); AppInfo.sum+=list.size(); AppInfo. p3_l1.setText("总记录是" + AppInfo.sum + "条"); //EmpInfo tmpEmpInfo=new EmpInfo(); this.showAll(jtable); this.dispose(); } //this.dispose(); } public void showAll(JTable jtable){ String sql="select * from application where 1=?"; String[]params={"1"}; EmpModel em=new EmpModel(); em.query(sql, params); //jtable=new JTable(em); jtable.setModel(em); } } <file_sep>/src/com/model/EmpModel.java /** * 这是人事管理的操作 */ package com.model; import com.db.*; import java.sql.*; import java.util.*; import javax.swing.table.*; public class EmpModel extends AbstractTableModel { public Vector<String> colums; public Vector<Vector> rows; public boolean UpdateModel(String sql, String[] params) { SqlHelper hp = new SqlHelper(); return hp.updateExecete(sql, params); } public void deleteModel(String sql) { SqlHelper hp = new SqlHelper(); hp.Delete(sql); } public int getNum(String sql) { SqlHelper hp = new SqlHelper(); int sum = hp.queryExecute(sql); return sum; } public void query(String sql, String[] params) { //初始化 colums = new Vector<String>(); rows = new Vector<Vector>(); // this.colums.add("员工号"); // this.colums.add("姓名"); // this.colums.add("性别"); // this.colums.add("职位"); SqlHelper hp = new SqlHelper(); ResultSet rs = hp.query(sql, params); try { ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < rsmd.getColumnCount(); i++) { this.colums.add(rsmd.getColumnName(i + 1)); } while (rs.next()) { Vector<String> temp = new Vector<String>(); for (int i = 0; i < rsmd.getColumnCount(); i++) { temp.add(rs.getString(i + 1)); } rows.add(temp); // temp.add(rs.getString(1)); // temp.add(rs.getString(2)); // temp.add(rs.getString(3)); // temp.add(rs.getString(4)); } } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { hp.close(); } } @Override public int getColumnCount() { // TODO 自动生成的方法存根 return this.colums.size(); } @Override public int getRowCount() { // TODO 自动生成的方法存根 return this.rows.size(); } @Override public String getColumnName(int arg0) { // TODO 自动生成的方法存根 return this.colums.get(arg0).toString(); } @Override public Object getValueAt(int arg0, int arg1) { // TODO 自动生成的方法存根 //System.out.println(arg0+","+ arg1); return ((Vector) rows.get(arg0)).get(arg1); } // public Object getValueFromIdObject(int id, int arg1) { // // TODO 自动生成的方法存根 // for (int i = 0; i < rows.size() - 1; i++) { // if (id == Integer.parseInt(((Vector) rows.get(i)).get(0)+"")) { // return ((Vector) rows.get(i)).get(arg1); // } // } // return -1; // } } <file_sep>/src/com/excel/ExcelOperationUtil.java package com.excel; import java.io.File; import java.io.FileInputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import jxl.Sheet; import jxl.Workbook; import com.model.GetApp; import javax.swing.JOptionPane; public class ExcelOperationUtil { public List<GetApp> readExcelData(String filePath) { List<GetApp> list = new ArrayList<GetApp>(); try { String path = filePath; //String path = "C:\\Users\\<NAME>\\Desktop\\查询结果.xls"; File xlsFile = new File(path); FileInputStream fs = new FileInputStream(xlsFile); Workbook book = Workbook.getWorkbook(fs);//获取工作簿对象 Sheet sheet = book.getSheet(0);//获取工作表对象,第一个sheet int rows = sheet.getRows();//获取工作表中的数据行数 for (int i = 1; i <= rows - 1; i++) {//循环Excel工作表的行,并读取单元格数据 GetApp g = new GetApp(); int application_id = Integer.parseInt(sheet.getCell(0, i).getContents()); String classes = sheet.getCell(1, i).getContents(); String stu_num = sheet.getCell(2, i).getContents(); //空值判断 if (sheet.getCell(3, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setAddress(null); } else { String address = sheet.getCell(3, i).getContents(); g.setAddress(address); } String teacher = sheet.getCell(4, i).getContents(); String week = sheet.getCell(5, i).getContents(); String time = sheet.getCell(6, i).getContents(); if (sheet.getCell(7, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setMonday(null); } else { String Monday = sheet.getCell(7, i).getContents(); g.setMonday(Monday); } if (sheet.getCell(8, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setTuesday(null); } else { String Thuesday = sheet.getCell(8, i).getContents(); g.setTuesday(Thuesday); } if (sheet.getCell(9, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setWednseday(null); } else { String Wednesday = sheet.getCell(9, i).getContents(); g.setWednseday(Wednesday); } if (sheet.getCell(10, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setThurday(null); } else { String Thurday = sheet.getCell(10, i).getContents(); g.setThurday(Thurday); } if (sheet.getCell(11, i).getContents().equals(null)) { //不知道怎么处理,暂时先告诉程序无穷大就是空值 g.setFriday(null); } else { String Friday = sheet.getCell(11, i).getContents(); g.setFriday(Friday); } g.setApplication_id(application_id); g.setClasses(classes); g.setStu_num(stu_num); g.setTeacher(teacher); g.setWeek(week); g.setTime(time); list.add(g); } System.out.println("------获取Excel中的数据【成功】------"); return list; } catch (Exception e) { System.out.println("获取Excel中的数据【异常】,异常信息:" + e.getMessage()); JOptionPane.showMessageDialog(null, "获取Excel中的数据【异常】,异常信息:" + e.getMessage()); e.printStackTrace(); return null; } } }
7b55a074aea08f971a57f902c4e07e20e859b4c2
[ "Markdown", "Java" ]
7
Java
trayvonc/course_scheduling
6fb69ff20cca47eee7982ffe8f3d7838b2d1a200
99214318bd1afa0e82f9a711dba69190d3a5ac1c
refs/heads/master
<repo_name>kabir02091999/prueva<file_sep>/tareas1.js document.getElementById("even").addEventListener("click",prueva); getTarea(); function prueva(){ var conte = document.getElementById("cont").value; //alert(conte); var tarea = { conte }; if(localStorage.getItem("tareas") === null){ var ta = []; ta.push(tarea); localStorage.setItem("tareas", JSON.stringify(ta)); }else{ var ta= JSON.parse(localStorage.getItem("tareas")); ta.push(tarea); localStorage.setItem("tareas",JSON.stringify(ta)); } //console.log(localStorage.getItem("tareas")); getTarea(); } function getTarea(){ var tarea = JSON.parse(localStorage.getItem("tareas")); var di = document.getElementById("tareas"); di.innerHTML=''; for (var i = 0; i < tarea.length; i++) { var nom = tarea[i].conte; di.innerHTML += `<div class ="hola"> <p>${nom}</p> <input type="button" name="" value="borrar" onclick="del('${nom}')"> </div>` } } function del(nom){ var tarea = JSON.parse(localStorage.getItem("tareas")); for (var i = 0; i < tarea.length; i++) { if(tarea[i].conte == nom){ tarea.splice(i,1); } } localStorage.setItem("tareas", JSON.stringify(tarea)); getTarea(); }
9008c6bedefb1260fae366af27fa0bc92f68d75d
[ "JavaScript" ]
1
JavaScript
kabir02091999/prueva
a9ff10e85e83dc1fae7292fbac5fd0be9064850c
23adb78500265565aad39b78b6675500012f89b0
refs/heads/master
<repo_name>cmcconnell1/k8s-build-deploy-ingress-nginx-for-aws<file_sep>/delete #!/usr/bin/env bash set -e shopt -s extglob TFVARS="$1" MANIFEST_PATH=./manifests/ingress-nginx KUARD_DEMO_PATH=./test testpath() { local path=$1 if ! test -d $path then echo "!!! Not found: ${path}" && exit 1 fi } testpath $MANIFEST_PATH testpath $KUARD_DEMO_PATH # printf "\nDelete kuard TLS demo resources first\n" kubectl delete --recursive -f $KUARD_DEMO_PATH& # printf "\nDeleting ingress-nginx global cluster ingress.\n" for i in `seq 1 10`; do \ kubectl delete --recursive -f $MANIFEST_PATH && break || \ sleep 10; \ done; \<file_sep>/build #!/usr/bin/env bash # ref: https://kubernetes.github.io/ingress-nginx/deploy/#aws TFVARS="$1" # ref: https://github.com/kubernetes/ingress-nginx # Notes: # - in the ingress-nginx project naming is inconsistent (similar to the helm chart being called nginx-ingress) # - the versions in the kube manifest files dont match the version tags # i.e.: ref: https://github.com/kubernetes/ingress-nginx/blob/nginx-0.25.1/docs/deploy/index.md#aws # note in the 'nginx-0.25.1' tag version, the deployment uses nginx-ingress-controller:0.25.0 #INGRESS_NGINX_K8S_CONTROLLER=$(awk -F "= " '/ingress_nginx_k8s_controller/ {print $2}' ${TFVARS} | sed 's/"//g') #INGRESS_NGINX_K8S_WILDCARD_CERT_ARN=$(awk -F "= " '/ingress_nginx_k8s_wildcard_cert_arn/ {print $2}' ${TFVARS} | sed 's/"//g') # the above vars fetching s like this for our ENV using a global tfvars file for IAC, so you can omit and use plain old shell vars INGRESS_NGINX_K8S_CONTROLLER="0.28.0" INGRESS_NGINX_K8S_WILDCARD_CERT_ARN="arn:aws:acm:us-west-2:001234567890:certificate/your-aws-cert-arn-goes-here" MANIFEST_PATH=./manifests/ingress-nginx echo $INGRESS_NGINX_K8S_CONTROLLER echo $INGRESS_NGINX_K8S_WILDCARD_CERT_ARN rm -rf $MANIFEST_PATH && mkdir $MANIFEST_PATH # update our ingress-nginx controller image version in the 'mandatory' manifest file. # ref: https://kubernetes.github.io/ingress-nginx/deploy/#prerequisite-generic-deployment-command # https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.28.0/deploy/static/mandatory.yaml sed -e "s#__INGRESS_NGINX_K8S_CONTROLLER__#${INGRESS_NGINX_K8S_CONTROLLER}#g" ./templates/00-mandatory.yaml.tpl > "$MANIFEST_PATH/00-mandatory.yaml" # update our AWS cert ARN in the 'service-l7' manifest file. sed -e "s#__INGRESS_NGINX_K8S_WILDCARD_CERT_ARN__#${INGRESS_NGINX_K8S_WILDCARD_CERT_ARN}#g" ./templates/01-service-l7.yaml.tpl > "$MANIFEST_PATH/01-service-l7.yaml" # no mods needed for the 'patch-configmap-l7' file cp ./templates/02-patch-configmap-l7.yaml.tpl "$MANIFEST_PATH/02-patch-configmap-l7.yaml" <file_sep>/apply #!/usr/bin/env bash set -e shopt -s extglob TFVARS="$1" MANIFEST_PATH=./manifests/ingress-nginx KUARD_DEMO_PATH=./test testpath() { local path=$1 if ! test -d $path then echo "!!! Not found: ${path}, did you forget to run k8s-build?" && exit 1 fi } testpath $MANIFEST_PATH for i in `seq 1 10`; do \ kubectl apply --recursive -f $MANIFEST_PATH && break || \ sleep 10; \ done; \ # deploy 'kuard' our TLS valiation service printf "\nSleeping for 5 then deploying kuard TLS demo 'https://kuard.dev.mycompany.com'" printf "\nAllow a few minutes for External-DNS Route53 to update the requisite A/ALIAS for kuard.dev.mycompany.com\n\n" sleep 5 kubectl apply -f $KUARD_DEMO_PATH/kuard-test-ingress.yaml <file_sep>/README.md # NGINX Ingress Controller ## Overview Built around the Kubernetes Ingress resource that uses ConfigMap to store the NGINX configuration. #### Docs https://kubernetes.github.io/ingress-nginx/ https://kubernetes.github.io/ingress-nginx/how-it-works/ #### Configuration https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/nginx-configuration/annotations.md ## Building and Deploying - `./build` - `./apply` - Validate all the components that ingress-nginx deploys into the ingress-nginx namespace: ```console kubectl get all -n ingress-nginx NAME READY STATUS RESTARTS AGE pod/nginx-ingress-controller-748cd7b559-rgk5p 1/1 Running 0 100m NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/ingress-nginx LoadBalancer 172.20.34.160 your-hex-aws-external-ip-address-goes-here-1492918777.us-west-2.elb.amazonaws.com 80:31487/TCP,443:30073/TCP 100m NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/nginx-ingress-controller 1/1 1 1 100m NAME DESIRED CURRENT READY AGE replicaset.apps/nginx-ingress-controller-748cd7b559 1 1 1 100m ``` - Notes: - The service must get and publish its external-ip address--for AWS it should look like this: ```console kubectl get service/ingress-nginx -n ingress-nginx -o jsonpath='{.status.loadBalancer.ingress[0].hostname}' your-hex-aws-external-ip-address-goes-here-1492918777.us-west-2.elb.amazonaws.com ``` - This can sometimes take up to 15 minutes when AWS backend queues are high. ## Testing and Validation Ingress with a Demo Service We also Deploy a kuard demo service configuted to terminate L7 TLS at the AWS ELB using the below kuard kube manifest files. You can get the address of your NLB via--if you don't see the status as shown below either more time is needed on AWS backend or there is an error--see the EKS cluster's control-plane logs <https://us-west-2.console.aws.amazon.com/cloudwatch/home?region=us-west-2#logs:> for further troubleshooting.: ```console k logs -f deployment.apps/nginx-ingress-controller -n ingress-nginx | grep $service ``` ```console kubectl get ing/kuard -n kuard -o yaml | grep -A 5 'status' status: loadBalancer: ingress: - hostname: your-hex-aws-external-ip-address-goes-here-1492918777.us-west-2.elb.amazonaws.com ``` Our Kuard demo TLS service deploys the following components for kuard to the current kube cluster (per your KUBECONFIG ENV variable). * kind: Namespace * kind: Deployment * kind: Service * kind: Ingress - Note it also configures requisite Route53 resource records for our kuard.dev.terradatum service due to our annotations in the Ingress manifest in the above noted manifest file. #### Validate that External-DNS creates requisite A/ALIAS and TXT records for demo service. ```console export HOST=kuard.dev.mycompany.com ; aws route53 list-resource-record-sets --hosted-zone-id Z3L41146DZNXKA | grep -A 5 $HOST | egrep "(Value|Name)" "Name": "kuard.dev.mycompany.com.", "DNSName": "your-hex-aws-external-ip-address-goes-here-1492918777.us-west-2.elb.amazonaws.com.", "Name": "kuard.dev.mycompany.com.", "Value": "\"heritage=external-dns,external-dns/owner=Z3L41146DZNXKA,external-dns/resource=ingress/kuard/kuard\"" ``` #### Test with curl or browser ```console curl https://kuard.dev.mycompany.com | grep 'Demo' % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1754 100 1754 0 0 8323 0 --:--:-- --:--:-- --:--:-- 8312 <title>KUAR Demo</title> ``` ```console open https://kuard.dev.mycompany.com ```
0ce94670766aa671cdf0f5eae8df32fa460a9f44
[ "Markdown", "Shell" ]
4
Shell
cmcconnell1/k8s-build-deploy-ingress-nginx-for-aws
dacc9944ca4df7609652c7894cbf1aaab4973840
6c70e61ee6c41e43f49aac133cc399f52d8f1956
refs/heads/master
<repo_name>irxess/IT-3105_AI_Programming_Modules_2015<file_sep>/Common/GAC/cnet.py import itertools from constraintInstance import * from variableInstance import * class CNET(): """CNET is a representation of constraints with components (variabels, domain, constraints) Domain is a function. domain(x) returns the domain of given variable x Each variable x is a vertex""" def __init__(self, variables, domains, expression): self.variables = variables self.constraints = [] self.domains = domains for e in expression: (args, func) = e constraint = self.makeConstraint(args, func) self.constraints.append(constraint) def getConstraints(self): return self.constraints def getDomains(self): return self.domains def makeConstraint(self, variables, expression, envir=globals()): function = "(lambda " + variables + ": " + expression + ")" return eval(function, envir) <file_sep>/Module 1, A-star/grid.py import pygame import node from graph import Graph class Grid(Graph): def __init__(self, width, height, rows, columns, display): self.display = display self.width = width self.height = height self.rows = rows self.columns = columns self.cellheight = self.height // self.rows self.cellwidth = self.width // self.columns self.celltype = {} for i in ['start', 'goal', 'unvisited', 'closed', 'open', 'blocked', 'path']: icon = pygame.image.load(i + '.png').convert() icon = pygame.transform.scale(icon, (self.cellwidth, self.cellheight)) self.celltype[i] = icon self.grid = [] for row in range(rows): self.grid.append([]) for column in range(columns): self.grid[row].append( node.Node(row,column) ) def draw(self): for row in range(self.rows): for column in range(self.columns): icon = self.celltype[ self.grid[row][column].state ] self.display.blit( icon, (self.cellwidth*column, self.cellheight*row) ) def drawPath(self, x, y): self.display.blit( self.celltype['path'], (self.cellwidth*y, self.cellheight*x)) def update_cell(self, row, column, state): self.grid[row][column].update(state) if state=='start': self.startNode = self.grid[row][column] if state=='goal': self.goalNode = self.grid[row][column] super(Grid, self).update_cell(state) def getNode(self, position): (x,y) = position if x >= 0 and y >= 0: if x < self.rows and y < self.columns: return self.grid[x][y] else: return None def generateSucc(self, node): listToCheck = [] ((x,y), s) = node.getID() directions = [[-1, 0], [0,-1], [1,0], [0,1]] for i in range(len(directions)): k = x + directions[i][0] l = y + directions[i][1] if k < self.rows and l < self.columns: neighbornode = self.getNode( (k,l) ) listToCheck.append( neighbornode ) neighbors = [] for neighbornode in listToCheck: if neighbornode and neighbornode.getState()!= 'blocked': if neighbornode.getG() > node.getG() + 1 : neighbornode.setG( node.getG() + 1 ) neighbors.append( neighbornode ) # else: # neighbornode.setG(100) # neighbors.append( neighbornode ) return neighbors <file_sep>/Module 3, Nonograms/nonogramSolver.py from AStarGAC import Astar_GAC from nstate import NonogramState class NonogramSolver(Astar_GAC): """NonogramSolver is a specializesd Astar_GAC""" #both def __init__(self, variables, domains, expressions): super(NonogramSolver, self).__init__(variables, domains, expressions) def createNewState( self, variables, constraints): return NonogramState(variables, constraints) <file_sep>/Common/GAC/AStarGAC.py import os import sys current_directory = sys.path[0] sys.path.append( os.path.abspath('../Common/AStar') ) sys.path.append( os.path.abspath('../Common/GAC') ) from astar import AStar from cnet import CNET from gac import GAC from graph import Graph from variableInstance import VI from constraintInstance import CI import itertools from abc import ABCMeta, abstractmethod class Astar_GAC(Graph): """Astar_GAC integrates Astar and GAC""" #both def __init__(self, variables, domains, expressions): super(Astar_GAC, self).__init__() self.cnet = CNET(variables, domains, expressions) self.currentState = self.initializeState(self.cnet) self.gac = GAC(self.currentState) self.Astar = AStar(self) @abstractmethod def createNewState( self, variables, constraints): pass def initializeState(self, cnet): """in initState each variable has its full domain. It will be set as root node initilizes cnet""" s = self.createNewState( cnet.variables, cnet.constraints ) s.update('start') self.startNode = s self.stateCounter = 0 self.nofAssumption = 0 self.nofExpanded = 0 return s def search(self): self.currentState = self.gac.domainFiltering(self.currentState) self.stateCounter += 1 if self.currentState.isSolution(): self.printStatistics(self.currentState) return self.currentState return self.iterateSearch() def iterateSearch(self): prev = self.currentState if prev.isSolution(): return prev self.currentState = self.Astar.iterateAStar() # self.currentState.updateColors() self.stateCounter += 1 self.currentState.parent = prev #used for backtracking to find 'shortest path' for statistics self.nofExpanded = self.Astar.nofExpandedNodes if self.currentState.isSolution(): self.printStatistics(self.currentState) return self.currentState self.currentState = self.gac.domainFiltering(self.currentState) return self.currentState def makeAssumption(self, newVI, parentState): """Generate one successor, and make sure all pointers are correct""" newVertices = {} newVIList = [] for vi in parentState.viList: viID = vi.getID() tmpVI = VI(viID, vi.domain.copy()) newVertices[viID] = tmpVI newVIList.append( tmpVI ) for vi in parentState.viList: viID = vi.getID() for neighbor in vi.neighbors: n = newVertices[ neighbor.getID() ] newVertices[viID].add_neighbor( n ) for vi in newVIList: if vi.getID() == newVI.getID(): newVIList.remove(vi) newVIList.append(newVI) else: for vi_n in vi.neighbors: if vi_n.getID() == newVI.getID(): vi.neighbors.remove(vi_n) vi.neighbors.append(newVI) succ = self.createNewState(newVIList, parentState.constraintList) succ.parent = parentState succ.updateUndecided() # maybe not needed succ.ciList = [] constraints = self.cnet.getConstraints() for v in succ.undecidedVariables: for n in v.neighbors: for c in constraints: succ.ciList.append( CI(c,[v,n]) ) return succ def generateSucc(self, state): """ make a guess. start gussing value for variables with min. domain length""" succStates = [] finishedVIs = [] varsCopy = state.undecidedVariables.copy() if not len(varsCopy): return [] otherVIs = sorted(varsCopy, key=lambda v: len(v.domain), reverse=True) betterVI = otherVIs.pop() if betterVI.domain: initID = betterVI.getID() for d in betterVI.domain: newVI = VI( initID, [d]) newVI.neighbors = betterVI.neighbors.copy() successor = self.makeAssumption(newVI, state) succStates.append( self.gac.rerun(successor) ) return succStates else: return [] # Not complete : TODO def printStatistics(self, state): print ( 'The number of unsatisfied constraints = ', self.countUnsatisfiedConstraints(state), '\n' ) print ( 'The total number of verticies without color assignment = ', self.countColorLess(state), '\n' ) print ( 'The total number of nodes in search tree = ', self.stateCounter, '\n' ) print ( 'The total number of nodes poped from agenda and expanded = ', self.nofExpanded, '\n' ) print ( 'The length of the path = ', self.nofAssumption ,'\n') def countColorLess(self, state): nofColorLess = 0 for vi in state.viList: if len(vi.domain) != 1: nofColorLess += 1 return nofColorLess # def countUnsatisfiedConstraints(self, state): # unsatisfied = 0 # varList = state.viList # for c in state.ciList: # for var in varList: # if var in c.variables: # if self.countInconsistentDomainValues(var, c) or not len(var.domain): # unsatisfied += 1 # return unsatisfied def countUnsatisfiedConstraints(self, state): unsatisfied = 0 varList = state.viList for var in varList: if len(var.domain) != 1: unsatisfied += 1 return unsatisfied # Needed for Graph def getGoal(self): return None def countInconsistentDomainValues(self, x, c): pairs = [] nofInconsistency = 0 for k in c.variables: for value in x.domain: pairs.extend( list(itertools.product([value], k.domain)) ) for p in pairs : if not c.constraint( p[0], p[1] ): nofInconsistency += 1 return nofInconsistency <file_sep>/Module 4, 2048/state.py from abc import ABCMeta, abstractmethod import boardcontroller as bc from copy import deepcopy, copy import random from math import * import numpy as np import settings as s import operator # from collection import deque def calculateHeuristic(board, nofMerges, maxMerging, highestMerg): """ Inspired by the method on stack overflow factors: 1. The location of the (current) largest tile on the board. Is it in a corner/edge? 2. The number of free cells 3. Are the high numbers in a "snake-pattern" 4. How many merges occur in this move 5. Consecutive chain. If score diff. is a fixed value """ heuristic = 0 heuristic += s.edgeWeight * edgeScore(board) heuristic += s.openCellWeigth * openCellScore(board) heuristic += s.snakeWeight * snake(board) heuristic += s.mergeWeight * mergeScore(nofMerges, maxMerging, highestMerg, max(board)) heuristic += s.gradientWeight * gradient(board) heuristic += s.smoothnessWeigth * smoothness(board) heuristic += s.nearWeight * nearness(board) # spaceAround2Tiles() # edge around highest # distance between two largest tiles return heuristic directions = ('up', 'down', 'left', 'right') def generateMAXSuccessors(board): """ Generate the boards that happen when pressing arrow up, down, left, right. Do not insert a new tile, only merge. """ successors = [] merges = [] maxMergings = [] highestMerges = [] #directions = ['up', 'down', 'left', 'right'] for direction in directions: succ = deepcopy(board) succ, nofMerges, maxMerging, highestMerg = bc.slide(direction, succ) # if succ == parent means no move, no changes after sliding therfore don't append as successor if succ != board: successors.append(succ) merges.append(nofMerges) maxMergings.append(maxMerging) highestMerges.append(highestMerg) return successors, merges, maxMergings, highestMerges def generateCHANCESuccessors(board): """ Generate new boards by inserting a new tile in all possible locations. Maybe two tiles(2C), with values 2 and 4. Try with only C later """ successors = [] probabilities = [] for i in xrange( len(board) ): if board[i] == 0: succ1 = deepcopy(board) succ2 = deepcopy(board) succ1[i] = 1 successors.append(succ1) probabilities.append(1.0) # succ2[i] = 2 # successors.append(succ2) # probabilities.append(0.1) outcomes = len(probabilities) for i in xrange(outcomes): # probabilities[i] /= (outcomes/2) probabilities[i] /= (outcomes) return successors, probabilities def generateSuccessorsBiased(board): # Using biased stochastics successors = [] probabilities = [] for i in xrange( len(board) ): succ = deepcopy(board) if board[i] == 0: succ[i] = flip() probabilities.append( (succ[i] == 1) and 0.9 or 0.1 ) successors.append(succ) nofSuccs = float( len(probabilities) ) for i in xrange(len(probabilities)-1): p = probabilities[i] probabilities[i] = p * (1/nofSuccs) # probabilities = [(p*(1/nofSuccs)) for p in probabilities] return successors, probabilities def flip(): # choice of 2 or 4 with p = {0.9, 0.1} if random.random() < 0.9 : return 1 return 2 def edgeScore(grid): scoreCorner = 0 scoreEdge = 0 score = 0 corner = frozenset([0, 3, 12, 15]) center = frozenset([5, 6, 9, 10]) edge = frozenset(grid).difference(center) # edge cells = (all cells) - (center cells) maxTile = max(grid) if maxTile in (grid[i] for i in corner): return 1 # highest tile in corner is good if maxTile in (grid[i] for i in edge): return 0.6 # highest tile on edge is not that bad else: return 0 def mergeScore(nofMerges, maxMerging, highestMerge, maxTile): if maxMerging > 0: return 1 # we always want to merge the highest tile if highestMerge + 1>= maxTile: return 0.9 x = nofMerges / 8.0 # max 8 merges possible highestScore = highestMerge/maxTile h = x/3 + highestScore/3*2 if h < 0.9: return h return 0.9 def openCellScore(board): count = 0 for cell in board: if cell == 0: count += 1 return count/16.0 def gradient(board): b = copy(board) maxScore = 0 # grad = [10, 9, 8, 7, 9, 6, 5, 4, 8, 5, 3, 2, 7, 4, 2, 1] grad = [8, 5, 2, 1, 5, 3, -1, -2, 2, -1, -3, -5, 1, -2, -5, -8] # [ 8, 5, 2, 1, # 5, 3, -1, -2, # 2, -1, -3, -5, # 1, -2, -5, -8 ] grad[:] = [x / 8.0 for x in grad] maxTile = max(board) for j in xrange(4): for i in xrange( len(board)-1 ): b[i] = grad[i] * b[i] / maxTile maxScore = max(sum(b), maxScore) b = rotateLeft(b) # 2.6 is awesome, 1 is bad return maxScore/2.8 # return maxScore def smoothness(board): score = 0 for rotation in xrange(2): for i in xrange(4): for j in xrange(3): val1 = board[4*i + j] val2 = board[4*i + j+1] diff = (abs(val1 - val2) ) if diff > 1: score -= diff board = rotateLeft(board) scoreInRange = 1 + (score/100.0) return scoreInRange def snake(board): b = copy(board) maxScore = 0 for j in xrange(4): # left to right snake pattern score = 0 importance = 256 broke = False for i in [0,1,2]: if b[i] >= b[i+1]: score += importance else: broke = True break importance /= 2 if broke == False: for i in [7,6,5]: if b[i] >= b[i-1]: score += importance else: break importance /= 2 maxScore = max(score, maxScore) # up-down snake pattern score = 0 importance = 256 broke = False for i in [0,4,8]: if b[i] >= b[i+4]: score += importance else: broke = True break importance /= 2 if broke == False: for i in [13,9,5]: if b[i] >= b[i-4]: score += importance else: break importance /= 2 maxScore = max(score, maxScore) b = rotateLeft(b) x = maxScore/504.0 # 504 is the max score possible return 2**x - 1 def evalBestCorner(board): # i: corner0, corner1, corner2, corner3 maxMonotScore = 0 b = deepcopy(board) for i in xrange(4): score = monotonicityScore(b) maxMonotScore = max(score, maxMonotScore) b = rotateLeft(b) return maxMonotScore def rotateLeft(board): rotated = [] l = 16 for i in xrange(3, -1, -1): rotated.extend( board[i:l:4] ) l -= 1 return rotated def nearness(board): # positions with two larges tiles largest, secLargest = second_largest(board) lX = largest % 4 lY = largest / 4 sX = secLargest % 4 sY = secLargest / 4 distance = abs(lX - sX) + abs(lY - sY) return 1 - distance/6.0 def second_largest(numbers): count = 0 m1 = m2 = float('-inf') p1 = p2 = 0 for x in numbers: count += 1 if x > m2: if x >= m1: m1, m2 = x, m1 p1, p2 = count-1, p1 else: m2 = x p2 = count-1 return p1, p2 if count >= 2 else None # def smoothness(board): # score = 0 # highestDiff = 0.0 # for i in xrange( len(board) -1 ): # difference = abs(board[i] - board[i+1]) # score -= ( difference ) # highestDiff = max(highestDiff, difference) # return score/highestDiff # def snake(board): # b = copy(board) # maxScore = 0 # maxTile = max(board) # pattern = [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] # # pattern = [16, 15, 14, 13, 9, 10, 11, 12, 5, 6, 7, 8, 4, 3, 2, 1] # pattern[:] = [x / 16.0 for x in pattern] # for j in xrange(4): # for i in xrange( len(board)-1 ): # b[i] = pattern[i] * b[i] / maxTile # # maxScore = max(sum(x for x in b), maxScore) # maxScore = max(sum(b), maxScore) # b = rotateLeft(b) # return maxScore <file_sep>/Common/GAC/state.py import os, sys current_directory = sys.path[0] sys.path.append( os.path.abspath('../Common/AStar') ) import itertools from abstractnode import AbstractNode import uuid from constraintInstance import * from variableInstance import * from abc import ABCMeta, abstractmethod class State(AbstractNode): __metaclass__ = ABCMeta def __init__(self, variables, constraints): super(State, self).__init__() self.constraintList = constraints self.viList = variables self.id = uuid.uuid4() self.g = 0 # we don't care about the distance walked self.parent = None self.state = 'unvisited' self.undecidedVariables = [] self.updateCIList() def __repr__(self): string = 'State: ID:%s, f:%s, constraints:%s, variables:\n%s\n' %(self.id, self.f, len(self.ciList), len(self.viList)) for vi in self.viList: string += vi.__repr__() + '\n' return string def updateUndecided(self): self.undecidedVariables = [] for v in self.viList: if len(v.domain) != 1: self.undecidedVariables.append(v) def updateCIList(self): self.updateUndecided() self.ciList = [] for c in self.constraintList: for v in self.undecidedVariables: for n in v.neighbors: self.ciList.append( CI(c, [v,n]) ) def estimateDistance(self, goal): self.h = 0 for v in self.viList: self.h += len(v.domain) - 1 super(State, self).estimateDistance() def getID(self): return self.id @abstractmethod def isContradictory(self): pass @abstractmethod def isSolution(self): pass def tieBreaking(self, goal): countVarLowestDomainLength = 0 for variable in self.viList: if len(variable.domain) == 1: countVarLowestDomainLength += 1 return countVarLowestDomainLength <file_sep>/Module 1, A-star/buttonPgu.py import pygame from pgu import gui class Gui(object): def __init__(self, width=500, height=250): self.width = width self.height = height app = gui.App() container = gui.container(self.width, self.height) def drawButton(self, text): button = gui.Button(text) # app.connect(gui.CLICK) button.connect(gui.CLICK, app.click, None) container.add(button, 60, 30)<file_sep>/Common/AStar/astar.py from collections import * from heapq import * # import node # import grid import pdb from math import sqrt, pow class AStar: def __init__(self, graph, method='Best first'): self.graph = graph self.startNode = graph.getStart() self.goalNode = graph.getGoal() self.method = method #BFS, DFS or AStar self.limit = 1000 self.openList = deque() self.closed = set() self.newNode = self.startNode self.newNode.estimateDistance(self.goalNode) self.openNode(self.newNode) self.countNodes = 1 self.solution = 'The solution is ' self.pathLength = 1 self.nofExpandedNodes = 0 self.failed = False def getStats(self): if self.failed == True: if self.countNodes > self.limit: return self.method + ": Nodes opened: " + str(self.countNodes) + " Search failed, went over limit." else: return self.method + ": Nodes opened: " + str(self.countNodes) + " Search failed, no path found." return self.method + ": Nodes opened: " + str(self.countNodes) + " Path length: " + str(self.pathLength) def extractMin(self): if self.method == 'BFS': return self.openList.popleft() elif self.method == 'DFS': return self.openList.pop() else: li = self.openList sortedlist = sorted(list(li), key=lambda x: x.f, reverse=True) n = sortedlist[ len(sortedlist) - 1 ] nodesLowesF = [ n ] tie_n = n.tieBreaking(self.goalNode) for node in sortedlist: if node.f == n.f: nodesLowesF.append(node) if len(nodesLowesF) == 1: self.openList.remove(n) return n for x in nodesLowesF: tie_x = x.tieBreaking(self.goalNode) if tie_x < tie_n: n = x tie_n = tie_x self.openList.remove(n) return n def openNode(self, node): self.openList.append(node) node.update('open') # self.countNodes += 1 def closeNode(self, node): self.closed.add(node) node.update('closed') def isOpen(self, node): for n in self.openList: if n.getID() == node.getID(): return True return False def isClosed(self, node): for n in self.closed: if n.getID() == node.getID() : return True return False def updatePath(self): for node in self.bestPath: node.update('path') def attachAndEval(self, child, parent): child.setParent(parent) child.estimateDistance(self.goalNode) def backtrackPath(self): self.bestPath = [] pathNode = self.newNode self.pathLength = 1 while pathNode.getParent() != None: self.pathLength += 1 self.bestPath.append(pathNode) pathNode = pathNode.getParent() self.bestPath.append(pathNode) # self.updatePath() return self.goalNode def betterPathFound(self, new, old): if new.getG() + 1 < old.getG(): return True else: return False def iterateAStar(self): if self.newNode.state != 'goal': if len(self.openList) == 0: self.failed = True return self.newNode if self.countNodes > self.limit: self.failed = True return self.newNode self.newNode = self.extractMin() self.closeNode(self.newNode) # self.nofExpandedNodes += 1 if self.newNode.getState() == 'goal': # r = self.newNode # self.backtrackPath() return self.backtrackPath() succ = self.graph.generateSucc(self.newNode) for s in succ: if self.isClosed(s): if self.betterPathFound(self.newNode, s): self.newNode.improvePath(s) elif self.isOpen(s): if self.betterPathFound(self.newNode, s): self.attachAndEval(s, self.newNode) else: self.attachAndEval(s, self.newNode) self.openNode(s) self.countNodes += 1 self.newNode.addChild(s) self.nofExpandedNodes += 1 return self.newNode <file_sep>/README.md # IT-3105_AI_Programming_Modules_2015 <file_sep>/Module 6, 2048 ANN/heuristic.py from abc import ABCMeta, abstractmethod import boardcontroller as bc from copy import deepcopy, copy import sys, random from math import * import numpy as np import settings as s import operator if (sys.version_info > (3, 0)): xrange = range directions = ('up', 'down', 'left', 'right') def calculate_heuristics(board, mergeCount, maxMerging, highestMerg): h_index = 0 heuristics = np.empty(19, dtype=float) heuristics[h_index] = edgeScore(board) h_index += 1 merges = mergeScore(mergeCount) for i in range(len(merges)): heuristics[h_index] = merges[i] h_index += 1 openCells = openCellScore(board) for i in range(len(openCells)): heuristics[h_index] = openCells[i] h_index += 1 heuristics[h_index] = gradient(board) h_index += 1 snakeLength = snake(board) for i in range(len(snakeLength)): heuristics[h_index] = snakeLength[i] h_index += 1 heuristics[h_index] = nearness(board) h_index+=1 heuristics[h_index] = smoothness(board) heuristics[h_index+1] = monotonicity(board) return heuristics def edgeScore(grid): scoreCorner = 0 scoreEdge = 0 score = 0 corner = frozenset([0, 3, 12, 15]) center = frozenset([5, 6, 9, 10]) edge = frozenset(grid).difference(center) # edge cells = (all cells) - (center cells) maxTile = max(grid) if maxTile in (grid[i] for i in corner): return 1.0 # highest tile in corner is good if maxTile in (grid[i] for i in edge): return 0.4 # highest tile on edge is not that bad else: return 0.0 def mergeScore(nofMerges): if nofMerges > 5: return [1., 1., 1., 1., 1., 1.] elif nofMerges > 4: return [1., 1., 1., 1., 1., 0.] elif nofMerges > 3: return [1., 1., 1., 1., 0., 0.] elif nofMerges > 2: return [1., 1., 1., 0., 0., 0.] elif nofMerges > 1: return [1., 1., 0., 0., 0., 0.] elif nofMerges > 0: return [1., 0., 0., 0., 0., 0.] else: return [0., 0., 0., 0., 0., 0.] def openCellScore(board): count = 0 for cell in board: if cell == 0: count += 1 if count > 12: return [1, 1, 1, 1] elif count > 8: return [1, 1, 1, 0] elif count > 5: return [1, 1, 0, 0] elif count > 2: return [1, 0, 0, 0] else: return [0, 0, 0, 0] # rotated = [] # l = 16 # for i in xrange(3, -1, -1): # rotated.extend( board[i:l:4] ) # l -= 1 # return rotated def smoothness(board): diff = 0 for col in range(4): for row in range(3): i = row + 4*col diff -= abs(board[i]-board[i+1]) / 15. for row in range(4): for col in range(3): j = col + 4*row diff -= abs(board[j]-board[j+1]) / 15. return diff def monotonicity(board): score=0 for j in range(4): i = 4*j if board[i] < board[i+1] < board[i+2] < board[i+3]: score += 1 elif board[i] > board[i+1] > board[i+2] > board[i+3]: score +=1 if board[j] < board[j+4] < board[j+2*4] < board[j+3*4]: score +=1 elif board[j] > board[j+4] > board[j+2*4] > board[j+3*4]: score +=1 return score/8. def gradient(board): b = copy(board) maxScore = 0 grad = [8, 5, 2, 1, 5, 3, -1, -2, 2, -1, -3, -5, 1, -2, -5, -8] # [ 8, 5, 2, 1, # 5, 3, -1, -2, # 2, -1, -3, -5, # 1, -2, -5, -8 ] grad[:] = [x / 8.0 for x in grad] maxTile = max(board) for j in xrange(4): for i in xrange( len(board)-1 ): b[i] = grad[i] * b[i] / maxTile maxScore = max(sum(b), maxScore) b = rotateLeft(b) # 2.6 is awesome, 1 is bad r = maxScore/2.8 if r > 1: r = 1. return r # def smoothness(board): # score = 0 # for rotation in xrange(2): # for i in xrange(4): # for j in xrange(3): # val1 = board[4*i + j] # val2 = board[4*i + j+1] # diff = (abs(val1 - val2) ) # if diff > 1: # score -= diff # board = rotateLeft(board) # scoreInRange = 1 + (score/100.0) # return scoreInRange # should test if this calculates score correctly def snake(board): b = copy(board) maxScore = 0 for j in xrange(4): # left to right snake pattern score = 0 broke = False for i in [0,1,2]: if b[i] >= b[i+1]: score += 1 else: broke = True break if broke == False: if b[3] >= b[7]: score += 1 for i in [7,6,5]: if b[i] >= b[i-1]: score += 1 else: break maxScore = max(score, maxScore) # up-down snake pattern score = 0 broke = False for i in [0,4,8]: if b[i] >= b[i+4]: score += 1 else: broke = True break if broke == False: if b[12] >= b[13]: score += 1 for i in [13,9,5]: if b[i] >= b[i-4]: score += 1 else: break maxScore = max(score, maxScore) b = rotateLeft(b) if score > 6: return [1., 1., 1., 1.] elif score > 4: return [1., 1., 1., 0.] elif score > 3: return [1., 1., 0., 0.] elif score > 2: return [1., 0., 0., 0.] else: return [0., 0., 0., 0.] # x = maxScore/504.0 # 504 is the max score possible # return 2**x - 1 # def evalBestCorner(board): # # i: corner0, corner1, corner2, corner3 # maxMonotScore = 0 # b = deepcopy(board) # for i in xrange(4): # score = monotonicityScore(b) # maxMonotScore = max(score, maxMonotScore) # b = rotateLeft(b) # return maxMonotScore def rotateLeft(board): rotated = [] l = 16 for i in xrange(3, -1, -1): rotated.extend( board[i:l:4] ) l -= 1 return rotated def nearness(board): # positions with two larges tiles largest, secLargest = second_largest(board) lX = largest % 4 lY = largest / 4 sX = secLargest % 4 sY = secLargest / 4 distance = abs(lX - sX) + abs(lY - sY) return 1 - distance/6.0 def second_largest(numbers): count = 0 m1 = m2 = float('-inf') p1 = p2 = 0 for x in numbers: count += 1 if x > m2: if x >= m1: m1, m2 = x, m1 p1, p2 = count-1, p1 else: m2 = x p2 = count-1 return p1, p2 if count >= 2 else None # def smoothness(board): # score = 0 # highestDiff = 0.0 # for i in xrange( len(board) -1 ): # difference = abs(board[i] - board[i+1]) # score -= ( difference ) # highestDiff = max(highestDiff, difference) # return score/highestDiff <file_sep>/Common/AStar/graph.py from abc import ABCMeta, abstractmethod class Graph: __metaclass__ = ABCMeta def __init__(self): self.startNode = None self.goalNode = None self.limit = 2000 def update_cell(self, state): if state=='start': self.startNode.g = 0 def getStart(self): return self.startNode def getGoal(self): return self.goalNode @abstractmethod def isGoal(self, node): pass @abstractmethod def generateSucc(self, node): pass <file_sep>/Module 4, 2048/settings.py def init(near, smooth, merge, grad, edge, op, snake): global nearWeight global smoothnessWeigth global mergeWeight global gradientWeight global edgeWeight global openCellWeigth global snakeWeight nearWeight = float(near) smoothnessWeigth = float(smooth) mergeWeight = float(merge) gradientWeight = float(grad) edgeWeight = float(edge) openCellWeigth = float(op) snakeWeight = float(snake) <file_sep>/Module 4, 2048/boardcontroller.py import visuals import random from copy import copy import sys if (sys.version_info < (3, 0)): from expectimax import * else: xrange = range class BoardController(): def __init__(self): self.window = visuals.GameWindow() self.start_new_game() def start_new_game(self): random.seed() self.board = [0] * 4*4 spawnRandomTile(self.board) self.window.update_view(self.board) def move(self, direction): """ Actually move. Slide first, then insertTile. Update GUI """ slide(direction, self.board) spawnRandomTile(self.board) self.window.update_view(self.board) def grid(self, x, y): """ Get the value of a position of the board. 0,0 is the top left corner. """ return self.board[x * 4 + y] def setGrid(self, x, y, v): """ Update the value of a position of the board. 0,0 is the top left corner. """ self.board[x * 4 + y] = v def slide(direction, board): """ Move all tiles as far in direction as possible. Use merge() if needed. """ if direction == 'up': return slideUp(board) elif direction == 'down': return slideDown(board) elif direction == 'right': return slideRight(board) elif direction == 'left': return slideLeft(board) def slideUp(board): merged = [False] * 4*4 mergeCount = 0 maxMerging = highestMerg = 0 maxTile = max(board) moves = 0 for i in xrange(3): # move as much as possible for pos in xrange(4,16): if board[pos-4] == 0: board[pos-4] = board[pos] board[pos] = 0 moves += 1 elif board[pos-4] == board[pos]: if not merged[pos] and not merged[pos-4]: # merge tiles if board[pos] == maxTile: maxMerging = board[pos]+1 board[pos-4] += 1 highestMerg = max( board[pos-4] , highestMerg) board[pos] = 0 mergeCount += 1 merged[pos-4] = True return board, mergeCount, maxMerging, highestMerg, moves def slideDown(board): merged = [False] * 4*4 mergeCount = 0 maxMerging = highestMerg= 0 maxTile = max(board) moves = 0 for i in xrange(3): for pos in range(11,-1,-1): if board[pos+4] == 0: board[pos+4] = board[pos] board[pos] = 0 moves += 1 elif board[pos+4] == board[pos]: if not merged[pos] and not merged[pos+4]: # merge tiles if board[pos] == maxTile: maxMerging = board[pos]+1 board[pos+4] += 1 highestMerg = max( board[pos+4] , highestMerg) board[pos] = 0 mergeCount += 1 merged[pos+4] = True return board, mergeCount, maxMerging, highestMerg, moves def slideLeft(board): merged = [False] * 4*4 mergeCount = 0 maxMerging = highestMerg = 0 maxTile = max(board) moves = 0 for i in xrange(3): for pos in [1,2,3,5,6,7,9,10,11,13,14,15]: if board[pos-1] == 0: board[pos-1] = board[pos] board[pos] = 0 moves += 1 elif board[pos-1] == board[pos]: if not merged[pos] and not merged[pos-1]: # merge tiles if board[pos] == maxTile: maxMerging = board[pos]+1 board[pos-1] += 1 highestMerg = max( board[pos-4] , highestMerg) board[pos] = 0 mergeCount += 1 merged[pos-1] = True return board, mergeCount, maxMerging, highestMerg, moves def slideRight(board): merged = [False] * 4*4 mergeCount = 0 maxMerging = highestMerg=0 maxTile = max(board) moves = 0 for i in xrange(3): for pos in [2,1,0,6,5,4,10,9,8,14,13,12]: if board[pos+1] == 0: board[pos+1] = board[pos] board[pos] = 0 moves += 1 elif board[pos+1] == board[pos]: if not merged[pos] and not merged[pos+1]: # merge tiles if board[pos] == maxTile: maxMerging = board[pos]+1 board[pos+1] += 1 highestMerg = max( board[pos+1] , highestMerg) board[pos] = 0 mergeCount += 1 merged[pos+1] = True return board, mergeCount, maxMerging, highestMerg, moves def findEmptyTiles(board): #return np.array(np.where(board == 0)) empty = [] for i in xrange( len(board) ): if board[i] == 0: empty.append(i) return empty #def createAllPossibleNeighbors(board): # emptyList = findEmptyTiles() # neighbors = [] # for pos in emptyList: # neighbor = board.copy() # insertTile(pos, 2, neighbor) # neighbors.append(neighbor) def spawnRandomTile(board): listWithEmptyTiles = findEmptyTiles(board) randomPosition = random.choice( listWithEmptyTiles ) #randomPosition = tuple(listWithEmptyTiles.T[np.random.randint(0, listWithEmptyTiles.shape[1])]) randomValue = 1 if random.random() > 0.9: randomValue = 2 insertTile( randomPosition, randomValue, board ) def insertTile( position, value, board ): board[position] = value <file_sep>/Module 6, 2048 ANN/play2048.py import sys sys.path.append("../Module 4, 2048/") sys.path.append("../Module 5, deeplearning/") import boardcontroller as bc import construct_ann from copy import copy import random, time, pickle import theano from theano import tensor as T from heuristic import calculate_heuristics from heuristic2 import calculate_heuristics2 from heuristic3 import calculate_heuristics3 import numpy as np import requests import time def playRandom(times_to_play=1): b = bc.BoardController() games_played = 0 results = [] while games_played < times_to_play: old_board = copy(b.board) result = moveRandom(b) b.window.update_view(b.board) if result > 0: # game over games_played += 1 results.append(result) b.start_new_game() return results def moveRandom(b): bestDirection = 'none' valid_moves = [] for direction in ['up', 'down', 'left', 'right']: nextBoard, nofMerges, maxMerging, highestMerg, moves = bc.slide( direction, copy(b.board) ) # count = bc.slide( direction, copy(b.board) ) if nextBoard != b.board: bestHeuristic = 1 valid_moves.append(direction) if len(valid_moves)!=0: b.move( random.choice(valid_moves) ) return 0 else: # game_over(b) score = 2**max(b.board) print(score) return score def playANN(functions, layer_sizes, learning_rate, epochs=1, training_size=21760, times_to_play=1, prep=1): with open('training_data.pkl', 'rb') as f: tr_data, tr_labels = pickle.load(f) # find input size: if prep == 1: preprocess_function = preprocess elif prep == 2: preprocess_function = preprocess2 else: preprocess_function = preprocess3 input_size = len(preprocess_function(tr_data[0])) ann = construct_ann.Construct_ANN(layer_sizes, functions, learning_rate, input_units=input_size, output_units=4, max_of_outputs=False) tr_sig = np.zeros([training_size, input_size]) tr_lbl = np.empty([training_size, 4]) for i in range(training_size): boardstate = tr_data[i] label = tr_labels[i] input_layer = preprocess_function(boardstate) correct_output = generate_output_layer(label) for j in range(len(input_layer)): tr_sig[i][j] = input_layer[j] for j in range(len(correct_output)): tr_lbl[i][j] = correct_output[j] # tr_sig is a numpy array with inputs as numpy arrays # tr_lbl is a numpy array with correct outputs as numpy arrays for i in range(epochs): for start, end in zip(range(0, len(tr_sig), 128), range(128, len(tr_sig), 128)): ann.train(tr_sig[start:end], tr_lbl[start:end]) # start game b = bc.BoardController() games_played = 0 results = [] while games_played < times_to_play: old_board = copy(b.board) result = moveANN(ann, b, prep) if result > 0: # game over games_played += 1 results.append(result) if games_played < times_to_play: b.start_new_game() return results def moveANN(ann, b, prep): # change max_of_outputs to False is we want to see # the rating of all 4 directions if prep == 1: input_layer = preprocess(b.board) elif prep == 2: input_layer = preprocess2(b.board) else: input_layer = preprocess3(b.board) weights = ann.predict([input_layer]) directions = ['up', 'down', 'left', 'right'] weighted_moves = [] for i in range(len(directions)): weighted_moves.append( (weights[i], directions[i]) ) # sorted_moves.sort(key = lambda t: t[1]) weighted_moves.sort(reverse=True) for weighted_move in weighted_moves: move = weighted_move[1] old_board = copy(b.board) try: # print('Trying to move') b.move(move) # print(old_board) # print(b.board) if old_board != b.board: return 0 else: b.board = old_board print('invalid move') except(ValueError, IndexError): b.board = old_board pass # invalid move, try next value # no moves left at this point score = 2**max(b.board) print(score) return score def preprocess(state): input_layer = np.zeros([4, 19], dtype=float) i = 0 for direction in ['up', 'down', 'left', 'right']: board, mergeCount, maxMerging, highestMerg, moves = bc.slide(direction, copy(state)) if board != state: input_layer[i] = calculate_heuristics(board, mergeCount, maxMerging, highestMerg) # else: keep these values at 0 i += 1 return input_layer.flatten() def preprocess2(state): input_layer = calculate_heuristics2(state) return input_layer def preprocess3(state): input_layer = np.zeros([4, 14], dtype=float) i = 0 for direction in ['up', 'down', 'left', 'right']: board, mergeCount, maxMerging, highestMerg, moves = bc.slide(direction, copy(state)) if board != state: input_layer[i] = calculate_heuristics(board, mergeCount, maxMerging, highestMerg, moves) # else: keep these values at 0 i += 1 return input_layer.flatten() def generate_output_layer(label): if label == 'up': return np.array([1.,0.,0.,0.]) if label == 'down': return np.array([0.,1.,0.,0.]) if label == 'left': return np.array([0.,0.,1.,0.]) if label == 'right': return np.array([0.,0.,0.,1.]) print(label) sys.exit(0) def game_over(b): print(2**max(b.board)) while True: b.window.update_view(b.board) def welch(list1, list2): params = {"results": str(list1) + " " + str(list2), "raw": "1"} resp = requests.post('http://folk.ntnu.no/valerijf/6/', data=params) return resp.text def parse_input(envir=globals()): functions = eval('[' + sys.argv[2] + ']', envir) layer_sizes = eval('[' + sys.argv[3] + ']', envir) learning_rate = eval(sys.argv[4], envir) return functions, layer_sizes, learning_rate if __name__ == "__main__": # python3 play2048.py ai "T.tanh, T.tanh, T.nnet.softmax" "100,40" "0.03" # python3 play2048.py ai "T.nnet.relu, T.nnet.sigmoid, T.nnet.softmax" "100,40" "0.01" # python3 play2048.py both "T.nnet.relu, T.nnet.sigmoid, T.nnet.softmax" "100, 40" "0.01" if (sys.argv[1] == 'ai'): func, layers, lr = parse_input() # results = playANN(func, layers, lr, epochs=10, times_to_play=50, prep=2) results = playANN(func, layers, lr, epochs=10, times_to_play=50) print('Average: ', sum(results) / float(len(results))) # playANN([T.tanh, T.nnet.sigmoid, T.nnet.softmax], [80, 70], 0.006) # playANN([T.nnet.relu, T.nnet.softmax], [100], 0.004) elif (sys.argv[1] == 'random'): playRandom(times_to_play=10) elif (sys.argv[1] == 'both'): func, layers, lr = parse_input() ann_list = playANN(func, layers, lr, 30, times_to_play=50) random_list = playRandom(times_to_play=50) print(random_list) print(ann_list) print(welch(random_list, ann_list)) else: print("Argument one should be 'ai', 'random' or 'both'.") <file_sep>/Module 6, 2048 ANN/heuristic3.py from abc import ABCMeta, abstractmethod import boardcontroller as bc from copy import deepcopy, copy import sys, random from math import * import numpy as np import settings as s import operator if (sys.version_info > (3, 0)): xrange = range directions = ('up', 'down', 'left', 'right') def calculate_heuristics3(board, mergeCount, maxMerging, highestMerg, nof_moves): # only look at merges, moved tiles, amount of neighbors near 2's and same tiles near each other h_index = 0 heuristics = np.empty(14, dtype=float) merges = mergeScore(mergeCount) for i in range(len(merges)): heuristics[h_index] = merges[i] h_index += 1 heuristics[h_index] = gradient(board) h_index += 1 snakeLength = snake(board) for i in range(len(snakeLength)): heuristics[h_index] = snakeLength[i] h_index += 1 heuristics[h_index] = nearness(board) return heuristics def mergeScore(nofMerges): if nofMerges > 5: return [1., 1., 1., 1., 1., 1.] elif nofMerges > 4: return [1., 1., 1., 1., 1., 0.] elif nofMerges > 3: return [1., 1., 1., 1., 0., 0.] elif nofMerges > 2: return [1., 1., 1., 0., 0., 0.] elif nofMerges > 1: return [1., 1., 0., 0., 0., 0.] elif nofMerges > 0: return [1., 0., 0., 0., 0., 0.] else: return [0., 0., 0., 0., 0., 0.] def moveScore(moves): if nofMerges == 0: return [1., 1., 1., 1., 1., 1.] elif nofMerges == 1 : return [1., 1., 1., 1., 1., 0.] elif nofMerges == 2: return [1., 1., 1., 1., 0., 0.] elif nofMerges == 3: return [1., 1., 1., 0., 0., 0.] elif nofMerges <= 5: return [1., 1., 0., 0., 0., 0.] elif nofMerges <= 7: return [1., 0., 0., 0., 0., 0.] else: return [0., 0., 0., 0., 0., 0.] def rotateLeft(board): rotated = [] l = 16 for i in xrange(3, -1, -1): rotated.extend( board[i:l:4] ) l -= 1 return rotated def second_largest(numbers): count = 0 m1 = m2 = float('-inf') p1 = p2 = 0 for x in numbers: count += 1 if x > m2: if x >= m1: m1, m2 = x, m1 p1, p2 = count-1, p1 else: m2 = x p2 = count-1 return p1, p2 if count >= 2 else None <file_sep>/Module 2, CSP/vertexColoring.py from AStarGAC import Astar_GAC from coloringState import ColoringState class VertexColoring(Astar_GAC): """Astar_GAC integrates Astar and GAC""" #both def __init__(self, variables, domains, expressions): super(VertexColoring, self).__init__(variables, domains, expressions) def createNewState( self, variables, constraints): return ColoringState(variables, constraints) <file_sep>/Module 4, 2048/test.py import subprocess from copy import copy def testrange(index, h): while h[index] > 0.05: h[index] -= 0.05 h[index+1] += 0.05 # print h[0], h[1], h[2], h[3], h[4], h[5] for i in range(3): subprocess.call(['python', 'main.py', str(h[0]), str(h[1]), str(h[2]), str(h[3]), str(h[4]), str(h[5])]) if index+2<len(h): testrange(index+1, copy(h)) def test(index, h): h[index] -= 0.05 h[index+1] += 0.05 # print h[0], h[1], h[2], h[3], h[4], h[5] for i in range(3): subprocess.call(['python', 'main.py', str(h[0]), str(h[1]), str(h[2]), str(h[3]), str(h[4]), str(h[5])]) if index+2<len(h): testrange(index+1, copy(h)) l = [0.30, 0.0, 0.2, 0.2, 0.15, 0.15] test(0, l) <file_sep>/Module 2, CSP/vertex.py class Vertex: def __init__(self, x, y): self.x = x self.y = y self.neighbors = [] self.color = (0,0,0) self.domain = [] # list of colors self.initialVI = None self.currentVI = None # self.constraints = [] # list of functions def __repr__(self): return 'vertex(x=%s, y=%s, color=%s)' %(self.x, self.y, self.color) def setDomain(self, value): self.domain = value def add_neighbor(self, vertex): self.neighbors.append(vertex) def getNeighbors(self): return self.neighbors def setColor(self, color): self.color = color def getColor(self): return self.color def getPosition(self): return (self.x,self.y) def addConstraint(self, expression): self.constraints.append(expression) <file_sep>/Module 2, CSP/coloringState.py import itertools from abstractnode import AbstractNode import uuid from constraintInstance import * from variableInstance import * from state import State class ColoringState(State): def __init__(self, variables, constraints): super(ColoringState, self).__init__(variables, constraints) def __repr__(self): string = 'State: ID:%s, f:%s, constraints:%s, variables:\n%s\n' %(self.id, self.f, len(self.ciList), len(self.viList)) for vi in self.viList: string += vi.__repr__() + '\n' return string def getVerticesToDraw(self): self.updateColors() return self.viList def updateColors(self): for vi in self.viList: if len(vi.domain) == 1: vi.color = vi.domain[0] else: vi.color = (0,0,0) def isContradictory(self): for vi in self.viList: if len( vi.domain ) == 0: return True if len( vi.domain ) == 1: for nb in vi.neighbors: if vi.color == nb.color and vi.color != (0,0,0): return True return False def isSolution(self): for vi in self.viList: if len( vi.domain ) != 1: return False for nb in vi.neighbors: if vi.color == nb.color: return False return True <file_sep>/Module 1, A-star/window.py import pygame import sys from grid import Grid import pygbutton import time from astar import AStar class Window: def create_grid(self, rows, columns): self.bfs_grid = Grid(self.width, self.height*2//3, rows, columns, self.screen) self.dfs_grid = Grid(self.width, self.height*2//3, rows, columns, self.screen) self.astar_grid = Grid(self.width, self.height*2//3, rows, columns, self.screen) def update_cell(self, row, column, state): self.bfs_grid.update_cell(row, column, state) self.dfs_grid.update_cell(row, column, state) self.astar_grid.update_cell(row, column, state) def create_astar(self): self.bfs = AStar(self.bfs_grid, 'BFS') self.dfs = AStar(self.dfs_grid, 'DFS') self.astar = AStar(self.astar_grid, 'AStar') self.active_search = self.bfs self.active_grid = self.bfs_grid def create_buttons(self): l = 10 h = 25 t = self.height*2//3 + 10 w = (self.width-l*4)//3 p = [(l,t,w,h),(l*2 + w,t, w,h),(l*3 + w*2, t,w, h)] self.buttons = [pygbutton.PygButton(p[0], "BFS"), pygbutton.PygButton(p[1], "DFS"), pygbutton.PygButton(p[2], "A*")] def __init__(self, width=500,height=750): pygame.init() self.width = width self.height = height self.screen = pygame.display.set_mode((self.width, self.height)) self.create_buttons() # self.font = pygame.font.SysFont('Arial', 25) self.font = pygame.font.Font('freesansbold.ttf', 16) self.WHITE = (255, 255, 255) self.BLACK = (0, 0, 0) def show_text(self): x = 10 y = self.height*2//3 + 50 text = self.bfs.getStats() self.screen.blit(self.font.render(text, True, self.BLACK), (x, y)) y += 25 text = self.dfs.getStats() self.screen.blit(self.font.render(text, True, self.BLACK), (x, y)) y += 25 text = self.astar.getStats() self.screen.blit(self.font.render(text, True, self.BLACK), (x, y)) def drawPath(self): self.active_search.backtrackPath() pathNodes = self.active_search.bestPath for node in pathNodes[:-1]: ((x,y),s) = node.getID() if node.state != 'goal': self.active_grid.drawPath(x, y) def loop(self): clock = pygame.time.Clock() results = [None, None, None] active_result_index = 0 active_result = results[active_result_index] while True: pygame.event.pump() active_result = results[active_result_index] if active_result == None or active_result.state != 'goal': active_result = self.active_search.iterateAStar() results[active_result_index] = active_result self.screen.fill(self.WHITE) self.active_grid.draw() self.drawPath() self.show_text() for event in pygame.event.get(): if 'click' in self.buttons[0].handleEvent(event): self.active_search = self.bfs self.active_grid = self.bfs_grid active_result_index = 0 if 'click' in self.buttons[1].handleEvent(event): self.active_search = self.dfs self.active_grid = self.dfs_grid active_result_index = 1 if 'click' in self.buttons[2].handleEvent(event): self.active_search = self.astar self.active_grid = self.astar_grid active_result_index = 2 if event.type == pygame.QUIT: sys.exit() for button in self.buttons: button.draw(self.screen) # pygame.display.update(changed_rectangles) is faster pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # time.sleep(3) <file_sep>/Common/AStar/abstractnode.py from abc import ABCMeta, abstractmethod class AbstractNode: __metaclass__ = ABCMeta def __init__(self): # super(Node, self).__init__() self.g = float('inf') self.f = float('inf') self.h = float('inf') self.parent = None #pointer to best parent node self.children = [] #list of succesors self.state = 'unvisited' def __repr__(self): return 'node(id=%s, fValue=%s, h=%s, g=%s state=%s)' %(self.getID(), self.f, self.h, self.g, self.state) def update(self, state): if self.state is not 'goal' and self.state is not 'start': self.state = state @abstractmethod def getID(self): pass def getF(self): self.f = self.g + self.h return self.f def getG(self): return self.g def setG(self, gValue): self.g = gValue self.f = self.g + self.h def getState(self): return self.state def setParent(self, parentNode): parentG = parentNode.getG() if self.g + self.cost(parentNode) > parentG: self.setG(parentG + self.cost(parentNode)) self.parent = parentNode def getParent(self): return self.parent def getChildren(self): return self.children def addChild(self, node): self.children.append(node) def improvePath(self, node): cost = self.cost(node) for child in self.children: gNew = self.g + cost if gNew < child.g: child.setParent(self) # child.setG(gNew) child.improvePath(node) @abstractmethod def tieBreaking(self, goal=None): pass def cost(self, node): nodeID = node.getID() if self.getID() == nodeID: return 0 return 1 @abstractmethod def estimateDistance(self): self.f = self.g + self.h <file_sep>/Module 4, 2048/expectimax.py import state, pdb def expectimax( node, depth, nextPlayer, nofMerges, maxMerging, highestMerg ): if depth == 0: h = state.calculateHeuristic(node, nofMerges, maxMerging, highestMerg) return h if nextPlayer == 'ai': return findBestSuccessor( node, depth, nofMerges, maxMerging, highestMerg) if nextPlayer == 'board': return findBestAverageSuccessor( node, depth, nofMerges, maxMerging, highestMerg) def findBestSuccessor( node, depth, nofMerges, maxMerging, highestMerg): bestHeuristic = float('-inf') successors, merges, maxMergings, highestMerges = state.generateMAXSuccessors(node) if len(successors) == 0: return state.calculateHeuristic(node, nofMerges, maxMerging, highestMerg) for i in xrange( len(successors) ): succHeuristic = expectimax( successors[i], depth-1, 'board', merges[i], maxMergings[i], highestMerges[i]) if succHeuristic > bestHeuristic: bestHeuristic = succHeuristic return bestHeuristic def findBestAverageSuccessor( node, depth, nofMerges, maxMerging, highestMerg): weightedAverage = 0 # successors, probabilities = state.generateSuccessorsBiased(node) #C successors, probabilities = state.generateCHANCESuccessors(node) #2C if len(successors) == 0: return state.calculateHeuristic(node, nofMerges, maxMerging, highestMerg) for i in xrange(len(successors)): if probabilities[i] < 0.0001: continue successorH = expectimax( successors[i], depth-1, 'ai', nofMerges , maxMerging, highestMerg) weightedAverage += (probabilities[i] * successorH) return weightedAverage <file_sep>/Common/GAC/constraintInstance.py class CI(object): def __init__(self, constraint, variables): self.constraint = constraint self.variables = variables # list of variableInstances that the constraint function needs def __repr__(self): return '(constraint:=%s, dependentVariables:=%s)' %(self.constraint, self.variables) <file_sep>/Module 3, Nonograms/main.py import sys import os import window def pairwise(iterable): a = iter(iterable) return zip(a, a) def find_segment_index( array, segment_nr ): i = 0 while i < len(array): if array[i] == 'black': segment_nr -= 1 if segment_nr == 0: start = i end = i i += 1 while i < len(array): if array[i] == 'black': if segment_nr == 0: end = i i += 1 else: break else: i += 1 if segment_nr == 0: return (start,end) def generateDomain( array, segment_nr ): r = [] (i,j) = find_segment_index( array, segment_nr ) while j < len(array): if segment_nr > 1: r += ( generateDomain( array.copy(), segment_nr-1 )) if (j<len(array)-1 and array[j+1] == 'white') and ((j < len(array) - 2 and array[j+2] == 'white') or j==len(array)-2): array[i] = 'white' array[j+1] = 'black' r.append(array.copy()) i += 1 j += 1 else: return r return r def main(): inputFile = sys.argv[1] f = open(inputFile, 'r') (rows_domain, columns_domain) = readInputFile(f) constraints = [] for variables,expression in pairwise( sys.argv[2:] ): constraints.append( (variables,expression) ) # TODO: None should be variables w = window.Window(500, 750) w.initialize_problem(rows_domain, columns_domain, constraints) # w.create_astar() w.loop() def readInputFile(inputFile): stdin = [] for line in inputFile: stdin.append(line.split(' ')) stdin[-1] = [ int(x) for x in stdin[-1] ] row_length = stdin[0][0] column_length = stdin[0][1] row_count = column_length column_count = row_length rows = [] columns = [] for r in range(row_count): row = ['white']*row_length row_offset = 0 for block in stdin[r+1]: for cell in range(block): row[row_offset] = 'black' row_offset += 1 row_offset += 1 rows.append(row.copy()) for c in range(column_count): column = ['white']*column_length col_offset = 0 for block in stdin[c+1+row_count]: for cell in range(block): column[col_offset] = 'black' col_offset += 1 col_offset += 1 # columns.append(column.copy()) columns.append( column.copy()) rows_domain = [] for i,r in enumerate(rows): l = [] l.append(r) l += generateDomain( r.copy(), len(stdin[i+1])) rows_domain.append(l.copy()) column_domain = [] for i,c in enumerate(columns): l = [] l.append(c) l += generateDomain( c.copy(), len(stdin[i+1+row_count]) ) column_domain.append(l.copy()) for i,c in enumerate(columns): columns[i] = list(reversed(c)) return (list(reversed(rows_domain)), column_domain) if __name__ == "__main__": main() <file_sep>/Module 2, CSP/variableInstance.py from abstractVariable import AbstractVariable class VI(AbstractVariable): def __init__(self, position, domain): self.x,self.y = position self.color = (0,0,0) super(VI, self).__init__(domain) def __repr__(self): return 'vertex(x=%s, y=%s, color=%s, domain=%s)' %(self.x, self.y, self.color,self.domain) def getID(self): return (self.x,self.y) def getColor(self): if len(self.domain) == 1: self.color = self.domain[0] return self.color def getPosition(self): return self.getID() <file_sep>/Module 1, A-star/main.py import sys import os current_directory = sys.path[0] sys.path.append( os.path.abspath('../Common/AStar') ) import window def main(): w = window.Window() stdin = [] translation_table = dict.fromkeys(map(ord, '() \n'), None) for line in sys.stdin: # translate )( to , line = line.replace(') (', ',') line = line.replace(')(', ',') stdin.append(line.translate(translation_table).split(',')) stdin[-1] = [ int(x) for x in stdin[-1] ] rows = stdin[0][0] columns = stdin[0][1] w.create_grid(rows, columns) w.update_cell(stdin[1][0], stdin[1][1], 'start') w.update_cell(stdin[2][0], stdin[2][1], 'goal') # for each wall for i in range(0, len(stdin[3])-1, 4): # for each piece in row for row_offset in range(stdin[3][i+2]): # for each piece in column for col_offset in range(stdin[3][i+3]): x = stdin[3][i] + row_offset y = stdin[3][i + 1] + col_offset w.update_cell(x, y, 'blocked') w.create_astar() w.loop() if __name__ == "__main__": main() <file_sep>/Module 4, 2048/main.py from boardcontroller import BoardController as window import boardcontroller as bc from expectimax import * from copy import copy import time import settings, sys depth = 7 # measure process time t0 = time.clock() stop = minutes = seconds = 0 nearness = 0.0 smooth = 0.0 merge = 0.4 gradient = 0.1 edge = 0.0 opencell = 0.5 snake = 0.0 # settings.init( nearness, smooth, merge, gradient, edge, opencell, snake ) settings.init(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]) # b = bc.BoardController() b = window() b.window.update_view(b.board) def emptyTiles(board): count = 0 for cell in board: if cell == 0: count += 1 return count def logic(): bestHeuristic = -1 bestDirection = 'none' for direction in ['up', 'down', 'left', 'right']: # for direction in ['down', 'left', 'right']: nextBoard, nofMerges, maxMerging, highestMerg = bc.slide( direction, copy(b.board) ) if nextBoard != b.board: # heuristic = expectimax( nextBoard, 6, 'board', nofMerges, maxMerging, highestMerg) nofEmpty = emptyTiles(nextBoard) if nofEmpty >= 10: heuristic = expectimax( nextBoard, 4, 'board', nofMerges, maxMerging, highestMerg) elif nofEmpty >= 5: heuristic = expectimax( nextBoard, 5, 'board', nofMerges, maxMerging, highestMerg) else: heuristic = expectimax( nextBoard, 5, 'board', nofMerges, maxMerging, highestMerg) if heuristic > bestHeuristic: bestHeuristic = heuristic bestDirection = direction if bestHeuristic != -1: b.move(bestDirection) else: # orig_stdout = sys.stdout # f = file('testResults.txt', 'w') # sys.stdout = f print '----------------------------------' print 'game over' # stop = float(time.clock()) # minutes = (stop - t0)/60 # seconds = (stop - t0)%60 print 'Running time: ', time.clock() print 'depth = ', depth print 2**max(b.board) print nearness, smooth, merge, gradient, edge, opencell # sys.stdout = orig_stdout # f.close() while True: b.window.update_view(b.board) # sys.exit(0) print nearness, smooth, merge, gradient, edge, opencell, snake while True: logic() <file_sep>/Module 3, Nonograms/variableInstance.py from abstractVariable import AbstractVariable class VI(AbstractVariable): def __init__(self, ID, domain): (isRow, index) = ID self.isRow = isRow self.index = index self.length = len(domain[0]) super(VI, self).__init__(domain) def __repr__(self): if self.isRow: r = 'Row:' else: r = 'Column:' return 'vertex(%s, index=%s, domain=%s)' %(r, self.index, self.domain) def drawColorsToGUI(self, gui): if len(self.domain)==1: if self.isRow: for i in range( self.length ): gui.grid[self.index][i] = self.domain[0][i] else: # is column for i in range( self.length ): gui.grid[i][self.index] = self.domain[0][i] def getID(self): return (self.isRow, self.index) def isSatisfied(self, pair, neighbor, constraint): viCell = pair[0][neighbor.index] nCell = pair[1][self.index] return constraint(viCell, nCell) <file_sep>/Module 6, 2048 ANN/heuristic2.py import numpy as np from copy import copy def calculate_heuristics2(board): h_index = 0 heuristics = np.empty(24, dtype=float) score = snakeUpDown(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 score = snakeLeftRight(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 score = mergeLeftRight(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 score = mergeUpDown(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 score = edgeScore(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 score = downFilled(board) for i in range(len(score)): heuristics[h_index] = score[i] h_index += 1 return heuristics def snakeUpDown(board): b = copy(board) maxScore = 0 for j in range(2): # up-down snake pattern score = 0 broke = False for i in [0,4,8]: if b[i] >= b[i+4]: score += 1 else: broke = True break if broke == False: if b[12] >= b[13]: score += 1 for i in [13,9,5]: if b[i] >= b[i-4]: score += 1 else: break maxScore = max(score, maxScore) b = rotateLeft(b) if score > 6: return [1., 1., 1., 1.] elif score > 4: return [1., 1., 1., 0.] elif score > 3: return [1., 1., 0., 0.] elif score > 2: return [1., 0., 0., 0.] else: return [0., 0., 0., 0.] def snakeLeftRight(board): b = copy(board) maxScore = 0 for j in range(2): # left to right snake pattern score = 0 broke = False for i in [0,1,2]: if b[i] >= b[i+1]: score += 1 else: broke = True break if broke == False: if b[3] >= b[7]: score += 1 for i in [7,6,5]: if b[i] >= b[i-1]: score += 1 else: break maxScore = max(score, maxScore) b = rotateLeft(b) if score > 6: return [1., 1., 1., 1.] elif score > 4: return [1., 1., 1., 0.] elif score > 3: return [1., 1., 0., 0.] elif score > 2: return [1., 0., 0., 0.] else: return [0., 0., 0., 0.] def mergeLeftRight(board): score = 0 for i in [0,1,2,4,5,6,8,9,10,12,13,14]: if board[i] == board[i+1]: score += 1 if score >= 4: return [1., 1., 1., 1.] elif score == 3: return [1., 1., 1., 0.] elif score == 2: return [1., 1., 0., 0.] elif score == 1: return [1., 0., 0., 0.] else: return [0., 0., 0., 0.] def mergeUpDown(board): score = 0 for i in [0,1,2,3,4,5,6,7,8,9,10]: if board[i] == board[i+4]: score += 1 if score >= 4: return [1., 1., 1., 1.] elif score == 3: return [1., 1., 1., 0.] elif score == 2: return [1., 1., 0., 0.] elif score == 1: return [1., 0., 0., 0.] else: return [0., 0., 0., 0.] def edgeScore(grid): score = [0.,0.,0.,0.] maxTile = max(grid) if maxTile == grid[0]: score[0] = 1. if maxTile == grid[3]: score[1] = 1. if maxTile == grid[12]: score[2] = 1. if maxTile == grid[15]: score[3] = 1. return score def downFilled(board): score = [0.,0.,0.,0.] if board[12]!=0: score[0] = 1 if board[13]!=0: score[1] = 1 if board[14]!=0: score[2] = 1 if board[15]!=0: score[3] = 1 return score def rotateLeft(board): rotated = [] l = 16 for i in range(3, -1, -1): rotated.extend( board[i:l:4] ) l -= 1 return rotated <file_sep>/Common/GAC/abstractVariable.py from abc import ABCMeta, abstractmethod class AbstractVariable(): __metaclass__ = ABCMeta def __init__(self, domain): self.domain = domain self.neighbors = [] def __eq__(self, vi): return (self.getID() == vi.getID()) @abstractmethod def __repr__(self): return 'vertex(x=%s, y=%s, color=%s, domain=%s)' %(self.getID, self.domain) def add_neighbor(self, vertex): self.neighbors.append(vertex) def getNeighbors(self): return self.neighbors @abstractmethod def getID(self): pass def isSatisfied(self, args, n, constraint): return constraint(*args) # def isSatisfied(self, pair, n, constraint): # return constraint(pair[0], pair[1]) <file_sep>/Module 2, CSP/main.py import window import sys from variableInstance import VI def pairwise(iterable): a = iter(iterable) return zip(a, a) def main(): w = window.Window(700,700) input_constraint = "" # lamba x: return (x.1 == x.2) # lambda v1, v2: v1.color != v2.color number_of_colors = int(sys.argv[1]) colorList = [ (255,107,107), # red (216,107,255), # purple (107,255,110), # green (107,228,255), # light blue (255,169,107), # orange (255,208,107), # light orange (107,255,188), # cyan (107,124,255), # blue (255,107,186), # pink (223,255,107)] # yellow green colors = colorList[:number_of_colors] inputFile = sys.argv[2] f = open(inputFile, 'r') vertexList = [] for line in f: vertexList.append(line.rstrip().split(' ')) vertexList[-1] = [ float(x) for x in vertexList[-1] ] number_of_vertices = int(vertexList[0][0]) number_of_edges = int(vertexList[0][1]) vertices = [0]*number_of_vertices highest_x = float("-inf") highest_y = float("-inf") lowest_x = float("inf") lowest_y = float("inf") for v in range(number_of_vertices): line = vertexList[v+1] vertices[ int(line[0]) ] = VI( (line[1], line[2]), []) if line[1] > highest_x: highest_x = line[1] if line[2] > highest_y: highest_y = line[2] if line[1] < lowest_x: lowest_x = line[1] if line[2] < lowest_y: lowest_y = line[2] for e in range(number_of_edges): line = vertexList[e+1+number_of_vertices] vertex1 = vertices[ int(line[0]) ] vertex2 = vertices[ int(line[1]) ] vertex2.add_neighbor( vertex1 ) vertex1.add_neighbor( vertex2 ) w.set_coordinates( highest_x, highest_y, lowest_x, lowest_y ) constraints = [] for variables,expression in pairwise( sys.argv[3:] ): constraints.append( (variables,expression) ) w.initialize_problem( vertices, constraints, colors ) w.loop() if __name__ == "__main__": main() <file_sep>/Module 3, Nonograms/window.py import pygame import os, sys import time current_directory = sys.path[0] sys.path.append( os.path.abspath('../Common/GAC') ) from gui_grid import GUIGrid from nonogramSolver import NonogramSolver from variableInstance import VI class Window: def update_cell(self, row, column, state): self.grid.update_cell(row, column, state) def __init__(self, width=500, height=750): pygame.init() self.WHITE = (255,255,255) self.width = width self.height = height self.screen = pygame.display.set_mode((self.width, self.height)) self.prevState = None def initialize_problem(self, row_domains, column_domains, constraints): rows = len(row_domains) columns = len(column_domains) self.guigrid = GUIGrid(self.width, self.height*2//3, rows, columns, self.screen) rowVIs = [] for i in range(rows): v = VI((True,i), row_domains[i]) rowVIs.append(v) colVIs = [] for i in range(columns): v = VI((False,i), column_domains[i]) v.neighbors = rowVIs colVIs.append(v) for vi in rowVIs: vi.neighbors = colVIs self.astarGAC = NonogramSolver(rowVIs + colVIs, row_domains + column_domains, constraints) self.currentState = self.astarGAC.search() self.screen.fill(self.WHITE) self.guigrid.reset() if self.currentState: for var in self.currentState.viList: var.drawColorsToGUI(self.guigrid) self.guigrid.draw() pygame.display.flip() def loop(self): clock = pygame.time.Clock() results = [None, None, None] active_result_index = 0 active_result = results[active_result_index] while True: pygame.event.pump() time.sleep(0.3) if not self.currentState.isSolution(): self.prevState = self.currentState self.currentState = self.astarGAC.iterateSearch() if self.currentState is not None: self.screen.fill(self.WHITE) self.guigrid.reset() if self.currentState: for var in self.currentState.viList: var.drawColorsToGUI(self.guigrid) self.guigrid.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.flip() clock.tick(60) <file_sep>/Module 3, Nonograms/nstate.py import itertools from abstractnode import AbstractNode import uuid from constraintInstance import * from variableInstance import * from state import State class NonogramState(State): def __init__(self, variables, constraints): super(NonogramState, self).__init__(variables, constraints) def __repr__(self): string = 'State: ID:%s, f:%s, constraints:%s, variables:\n%s\n' %(self.id, self.f, len(self.ciList), len(self.viList)) for vi in self.viList: string += vi.__repr__() + '\n' return string def isContradictory(self): for vi in self.viList: if len( vi.domain ) == 0: return True if len( vi.domain ) == 1: for nb in vi.neighbors: if nb.domain[0][vi.index] != vi.domain[0][nb.index]: return True return False def isSolution(self): for vi in self.viList: if len( vi.domain ) != 1: return False return True <file_sep>/Module 1, A-star/node.py from abstractnode import AbstractNode from math import sqrt class Node(AbstractNode): def __init__(self, x, y): super(Node, self).__init__() self.x = x self.y = y def getID(self): return ((self.x, self.y), self.state) # def cost(self, node): # (nodeX,nodeY,s) = node.getID() # if self.x == nodeX and self.y == nodeY: # return 0 # return 1 def tieBreaking(self, goal): ((goalX,goalY),s) = goal.getID() return sqrt( pow((self.x - goalX), 2) + pow((self.y - goalY), 2) ) def estimateDistance(self, goal): # (goalX,goalY,s) = goal.getID() # Manhatan distance # self.h = (abs(goalX - self.x) + abs(goalY - self.y)) self.tieBreaking(goal) super(Node, self).estimateDistance() <file_sep>/Module 3, Nonograms/gui_grid.py import pygame class GUIGrid(): def __init__(self, w, h, r, c, screen): self.height = h self.width = w self.rows = r self.columns = c self.display = screen self.cellheight = self.height // self.rows self.cellwidth = self.width // self.columns self.celltype = {} for i in ['white', 'black']: icon = pygame.image.load(i + '.png').convert() icon = pygame.transform.scale(icon, (self.cellwidth, self.cellheight)) self.celltype[i] = icon self.grid = [] for x in range(self.rows): self.grid.append([]) for y in range(self.columns): self.grid[x].append('white') def draw(self): for row in range(self.rows): for column in range(self.columns): icon = self.celltype[ self.grid[row][column] ] self.display.blit( icon, (self.cellwidth*column, self.cellheight*row) ) def updateCell(self, x, y, state): if x >= 0 and x < self.rows: if y >= 0 and y < self.columns: self.grid[x][y] = state def reset(self): for x in range(self.rows): for y in range(self.columns): self.grid[x][y] = 'white' <file_sep>/Module 2, CSP/window.py import pygame import os, sys current_directory = sys.path[0] sys.path.append( os.path.abspath('../Common/GAC') ) from vertexColoring import VertexColoring class Window: def __init__(self, width=600,height=600): pygame.init() self.width = width self.height = height self.screen = pygame.display.set_mode((self.width, self.height)) self.WHITE = (255, 255, 255) self.screen.fill(self.WHITE) self.prevState = None def initialize_problem(self, vertices, constraints, colors): self.set_vertices(vertices) self.draw_state(vertices) domains = colors for vertex in vertices: vertex.domain = colors self.astarGAC = VertexColoring( vertices, domains, constraints ) self.currentState = self.astarGAC.search() self.vertices = self.currentState.getVerticesToDraw() self.draw_vertices( self.vertices ) def set_coordinates( self, max_x, max_y, min_x, min_y ): self.x_diff = min_x self.y_diff = min_y self.scale_x = (self.width - 20) / (max_x - min_x) self.scale_y = (self.height - 20) / (max_y - min_y) def draw_state(self, vertices): for v in vertices: start_pos = self.getAndFitPosition(v) for n in v.neighbors: end_pos = self.getAndFitPosition(n) pygame.draw.line(self.screen, (90,90,90), start_pos, end_pos, 1) color = v.getColor() pygame.draw.circle(self.screen, color, start_pos, 5) def draw_vertices(self, vertices): for v in vertices: start_pos = self.getAndFitPosition(v) color = v.getColor() pygame.draw.circle(self.screen, color, start_pos, 5) def getAndFitPosition(self, vertex): (x,y) = vertex.getPosition() x = int((x - self.x_diff) * self.scale_x) + 10 y = int((y - self.y_diff) * self.scale_y) + 10 return (x,y) def set_vertices( self, v ): self.vertices = v def loop(self): clock = pygame.time.Clock() printedStatistics = False while True: pygame.event.pump() if not self.currentState.isSolution(): self.prevState = self.currentState self.currentState = self.astarGAC.iterateSearch() self.currentState.updateColors() self.vertices = self.currentState.getVerticesToDraw() self.draw_vertices( self.vertices ) else: if not printedStatistics: self.astarGAC.printStatistics( self.currentState ) printedStatistics = True for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # pygame.display.update(changed_rectangles) is faster pygame.display.flip() pygame.display.update() # --- Limit to 60 frames per second clock.tick(60) <file_sep>/Module 5, deeplearning/construct_ann.py """ construct_ann.py Created by <NAME> on 05/11/15. References: http://cs231n.github.io/neural-networks-2 """ import sys import theano from theano import tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import numpy as np from mnist_basics import * import sys, time from math import ceil, floor, sqrt # Numpy printing options np.set_printoptions(threshold=1000, edgeitems=38, linewidth=159) theano.config.exception_verbosity='high' # prints out the error message and what caused the error. class Construct_ANN(object): """docstring for Construct_ANN""" def __init__(self, hidden_nodes, functions, lr, input_units=784, output_units=10, max_of_outputs=True): super(Construct_ANN, self).__init__() self.hidden_nodes = hidden_nodes self.learning_rate = lr self.functions = functions self.build_ann(hidden_nodes, self.learning_rate, input_units, output_units, max_of_outputs) def build_ann(self, hidden_nodes, lr, input_units, output_units, max_of_outputs): ann_weights, biases = get_net_weights(hidden_nodes, input_units, output_units) signals = T.fmatrix() # input signals labels = T.fmatrix() # input labels params = [] for i in range(len(biases)): params.append(ann_weights[i]) params.append(biases[i]) p_outputs = model(signals, ann_weights, biases, self.functions)# probability outputs given input signals # p_outputs = model2(signals, ann_weights, biases, self.functions) #w/dropout if max_of_outputs: max_predict = T.argmax(p_outputs, axis=1) # chooses the maximum prediction over the probabilities else: max_predict = p_outputs[0] # classification metric to optimize # cost = T.mean(T.nnet.categorical_crossentropy(p_outputs, labels)) # without dropout cost = T.mean(T.nnet.categorical_crossentropy(p_outputs, labels)) # with dropout, but doesn't work :/ # cost = T.sum((signals - p_outputs)**2)#different cost function # updates = sgd(cost, params, lr) # sgd:model1 without dropout updates = acc_sgd(cost, params, lr) #accelerated w/ momentum self.train = theano.function(inputs=[signals, labels], outputs=cost, updates=updates, allow_input_downcast=True) self.predict = theano.function(inputs=[signals], outputs=max_predict, allow_input_downcast=True) def blind_test(self, test_input): test_cases = np.array(test_input)/255.0 test_count = len(test_input) predictions = [] pred_index = 0 prediction = self.predict(test_cases) for ele in prediction: predictions.append( int(ele) ) pred_index += 1 # return predictions return predictions[:pred_index] def softmax(X): # numerically more stable than tensor.nnet.softmax # suggested in theano doc. e_x = T.exp(X - X.max(axis=1, keepdims=True)) return e_x / e_x.sum(axis=1, keepdims=True) def get_func_names(funcs): names=[] for f in funcs: if f==T.tanh: names.append('tanh') elif f==T.nnet.relu: names.append('relu') elif f==T.nnet.softmax or f==softmax: names.append('softmax') else: names.append(f.name) return names # Stochastic Gradient Descent def sgd(cost, params, lr, momentum=0.8): grads = T.grad(cost=cost, wrt=params) # computes gradient of loss w/respect to params updates = [] # Back propagation act for p, g in zip(params, grads): updates.append([p, p - g * lr]) return updates def model(X, weights, biases, functions): """ Calculate the activation function for each layer. """ # w/ sgd h = X for i in range(len(weights)): if functions[i] == T.nnet.sigmoid: weights[i] *= 4 h = functions[i](T.dot(h, weights[i])+biases[i]) return h def acc_sgd(cost, params, lr=0.001, momentum=0.9, epsilon=1e-6): # this function accelerates convergence by momentum grads = T.grad(cost=cost, wrt=params) # computes gradient of loss w/respect to params updates = [] # Back propagation act for p, g in zip(params, grads): accumulator = theano.shared(p.get_value()*0., broadcastable=p.broadcastable) acc_new = momentum * accumulator + (1 - momentum) * g ** 2 gradient_scaling = T.sqrt(acc_new + epsilon) g = g / gradient_scaling updates.append((p, p - g * lr)) updates.append((accumulator, acc_new)) return updates # with dropout regularization, not regulizes biases def model2(X, weights, biases, functions, p_drop_in=0.2, p_drop_out=0.5): h = functions[0]( T.dot(dropout(X, p_drop_in), weights[0])+biases[0] ) for i in range(1,len(weights)): if functions[i] == T.nnet.sigmoid: weights[i] *= 4 h = dropout(h, p_drop_out) h = functions[i](T.dot(h, weights[i])+biases[i]) return h def dropout(X, p=0.0): # X: input data # p: probability of keeping a unit active. higher = less dropout if p > 0: retain_prob = 1 - p noise = RandomStreams().binomial(X.shape, p=retain_prob, dtype=theano.config.floatX) X = X * (noise/retain_prob) return X # converts labels to a 2D numpy array of 0's & 1's def one_hot_encoding(x,n): if type(x) == list: x = np.array(x) x = x.flatten() lbls = np.zeros((len(x),n)) lbls[np.arange(len(x)),x] = 1 return lbls def get_functions(length, funcs=[T.tanh, T.nnet.sigmoid]): if len(funcs) == length: return funcs print('Length not matching function list length') return False def floatX(X): return np.asarray(X, dtype=theano.config.floatX) #ReLU units will have a positive mean. def init_weights(shape, n): return theano.shared(floatX(np.random.uniform( -.1, .1, size=shape) * (sqrt(2.0/n)) )) def init_bias(shape): return theano.shared(floatX(np.random.uniform( -.1, .1, size=shape))) def get_net_weights(hidden_nodes, input_units, output_units): network_weights = [] biases = [] if len(hidden_nodes)==0: network_weights.append(init_weights((input_units, output_units), n=input_units)) biases.append(init_bias(output_units)) return network_weights, biases n0 = hidden_nodes[0] # append first hidden layer network_weights.append(init_weights((input_units, n0), n=input_units)) biases.append( init_bias(n0) ) for n_next in hidden_nodes[1:]: network_weights.append(init_weights((n0, n_next), n=n0)) biases.append(init_bias(n_next)) n0 = n_next # append output layer network_weights.append(init_weights((hidden_nodes[-1], output_units), n=hidden_nodes[-1])) biases.append(init_bias(output_units)) # returns weights for all layers in the network return network_weights, biases def load_cases(): # load both training & testing cases # training_cases = load_all_flat_cases('training') # testing_cases = load_all_flat_cases('testing') training_cases = load_flat_text_cases('all_flat_mnist_training_cases_text.txt') testing_cases = load_flat_text_cases('all_flat_mnist_testing_cases_text.txt') # seperate cases into images and their labels training_signals = np.array(training_cases[0])/255.0 training_labels = training_cases[1] testing_signals = np.array(testing_cases[0])/255.0 testing_labels = testing_cases[1] # Modify to 2D(lable arrays)numpy arrays of zeros & ones of length 10 testing_labels = one_hot_encoding(testing_labels, 10) training_labels = one_hot_encoding(training_labels, 10) return training_signals, training_labels, testing_signals, testing_labels def train_on_batches(epochs, hidden_nodes, funcs, lr, batch_size=128): ann = Construct_ANN(hidden_nodes, funcs, lr) # traning_signals, training_labels, testing_signals, testing_labels = load_cases() tr_sig, tr_lbl, te_sig, te_lbl = load_cases() # Write results and statistics to a file # orig_stdout = sys.stdout # f = open('testResults2.txt', 'a') # sys.stdout = f # print('***********************************************************************') # print('functions = ', get_func_names(ann.functions), '\nlearning rate = ', ann.learning_rate) # print('hidden nodes = ',ann.hidden_nodes) # print ('epoch', '|',' occuracy', '\n---------------------') for i in range(epochs): for start, end in zip(range(0, len(tr_sig), 128), range(128, len(tr_sig), 128)): cost = ann.train(tr_sig[start:end], tr_lbl[start:end]) # sys.exit(0) occuracy = np.mean(np.argmax(te_lbl, axis=1) == ann.predict(te_sig)) # print(occuracy) answers = np.argmax(te_lbl, axis=1) predictions = ann.predict(te_sig) total = int(te_sig.size/784) # print(sum(answers==predictions), 'out of', total, 'correct.') print('functions = ', get_func_names(ann.functions), '\nlearning rate = ', ann.learning_rate) print(hidden_nodes) # sys.stdout = orig_stdout # f.close() return ann def parse_input(envir=globals()): functions = eval('[' + sys.argv[1] + ']', envir) layer_sizes = eval('[' + sys.argv[2] + ']', envir) learning_rate = eval(sys.argv[3], envir) return (functions, layer_sizes, learning_rate) # only run this if we're not being imported if __name__ == "__main__": # train 20 times, 2 hidden layers with 625 nodes funct, layrs, lrt = parse_input() trained_ann = train_on_batches(epochs=20, hidden_nodes=layrs, funcs=funct, lr=lrt) # trained_ann = train_on_batches(epochs=20, hidden_nodes=[625, 625], \ # funcs=[T.nnet.relu, T.nnet.relu, softmax], lr=0.001) minor_demo(trained_ann) <file_sep>/Common/GAC/gac.py from copy import deepcopy import itertools from state import * from constraintInstance import CI class GAC(): def __init__(self, state): """ Push all valid combinations of x,c onto the queue """ state.updateCIList() self.queue = [] for ci in state.ciList: self.queue.append( (0, ci) ) self.state = state self.unSatisfied = 0 def revise(self, x, c): """ Retain all x in the domain if there exists an y in the other domain that satisfies the constraint. Remove all others. """ revised = False toBeRemovedFromDomain = [] vi = c.variables[x] for value_i in vi.domain: satisfied = False if len(vi.neighbors)==0: satisfied = True for y in c.variables[1:]: satisfied = False for value_j in y.domain: if vi.isSatisfied( (value_i, value_j), y, c.constraint ): satisfied = True else: self.unSatisfied += 1 if not satisfied: revised = True toBeRemovedFromDomain.append( value_i ) for ele in toBeRemovedFromDomain: if ele in vi.domain: vi.domain.remove(ele) return revised def domainFiltering(self, state): """ Queue masse sjekker. Kjør revise på alle i queue i rekkefølge. Hvis revise fjernet noe: queue alle komboer hvor naboene er hovedvariabelen """ self.state = state while len(self.queue) > 0: index, ci = self.queue.pop() revised = self.revise(index, ci) if revised: # assume all variables are in all constraints for c in state.constraintList: for vi in ci.variables[index].neighbors: newCI = CI(c, [vi, ci.variables[index]]) self.queue.append( (0,newCI) ) return state def rerun(self, state): # assume all variables are in all constraints self.state = state self.queue = [] for vi in state.viList: for vi_n in vi.neighbors: for c in state.constraintList: newCI = CI( c, [vi,vi_n] ) self.queue.append( (0,newCI) ) return self.domainFiltering( state )
a1ae4c8cdbf7c13b5b5b00e512a62b2aff3798aa
[ "Markdown", "Python" ]
38
Python
irxess/IT-3105_AI_Programming_Modules_2015
f076fab754e0780fe19577586e1ffd6456d6dc7e
31c72a6d30fed212ab562842b3630a9469dbb583
refs/heads/master
<repo_name>traal-devel/udacity-p01-spring-boot-helloworld<file_sep>/spring-boot-helloworld/src/main/java/ch/traal/demo/servlet/HelloServlet.java package ch.traal.demo.servlet; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name="helloServlet", urlPatterns ="/helloServlet") public class HelloServlet extends HttpServlet { /** Auto generated serial-version by eclipse */ private static final long serialVersionUID = 2177556473029818793L; /* methods */ @Override protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException{ System.out.println("Running Hello Servlet doGet method."); response.getOutputStream().println("Running Hello Servlet doGet method"); } } <file_sep>/spring-boot-helloworld/src/main/java/ch/traal/demo/servlet/HelloFilter.java package ch.traal.demo.servlet; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; @WebFilter( filterName="helloFilter", urlPatterns="/helloServlet" ) public class HelloFilter implements Filter { /* member variables */ /* constructors */ /* methods */ @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { System.out.println("Executing doFilter method"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("Done executing doFilter method"); } }
18f41a98bd93419243607497717e8e105d72174b
[ "Java" ]
2
Java
traal-devel/udacity-p01-spring-boot-helloworld
913d3b54cceb3d05e7b412e0dbbb3012e36c71d3
55c1597f17ec50c0d13a523ee98bb79da8837435
refs/heads/master
<repo_name>monitorjbl/vault-commons-config<file_sep>/src/main/java/com/monitorjbl/VaultConfiguration.java package com.monitorjbl; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.configuration2.AbstractConfiguration; import org.apache.commons.configuration2.Configuration; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import java.io.IOException; import java.util.Iterator; import java.util.Map; public class VaultConfiguration extends AbstractConfiguration implements Configuration { private final ObjectMapper mapper; private final PoolingHttpClientConnectionManager cm; private final CloseableHttpClient httpClient; private final String vaultUrl; private final String vaultToken; private final String vaultBackend; private final String configName; public VaultConfiguration(String vaultUrl, String vaultToken, String vaultBackend, String configName) { this.vaultUrl = vaultUrl; this.vaultToken = vaultToken; this.vaultBackend = vaultBackend; this.configName = configName; this.cm = new PoolingHttpClientConnectionManager(); this.httpClient = HttpClients.custom() .setConnectionManager(cm) .build(); this.mapper = new ObjectMapper(); } @SuppressWarnings("unchecked") private Map<String, Object> loadFromVault() { HttpGet get = new HttpGet(vaultUrl + "/v1/" + vaultBackend + "/" + configName); get.addHeader("X-Vault-Token", vaultToken); try(CloseableHttpResponse response = httpClient.execute(get)) { if(response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Could not read from Vault (" + response.getStatusLine().getStatusCode() + ")"); } Map map = mapper.readValue(response.getEntity().getContent(), Map.class); return (Map<String, Object>) map.get("data"); } catch(IOException e) { throw new RuntimeException(e); } } @Override protected void addPropertyDirect(String key, Object value) { throw new UnsupportedOperationException(); } @Override protected void clearPropertyDirect(String key) { throw new UnsupportedOperationException(); } @Override protected boolean isEmptyInternal() { return loadFromVault().isEmpty(); } @Override protected boolean containsKeyInternal(String key) { return loadFromVault().containsKey(key); } @Override protected Object getPropertyInternal(String key) { return loadFromVault().get(key); } @Override protected Iterator<String> getKeysInternal() { return loadFromVault().keySet().iterator(); } public static void main(String[] args) { VaultConfiguration config = new VaultConfiguration( "http://127.0.0.1:8200", "26a78c5a-9d72-e020-493a-20ab39dd5136", "secret", "account-management"); config.getString("excited"); } }
7ef982147058c2feb9e39a7ae73b8f9359686db5
[ "Java" ]
1
Java
monitorjbl/vault-commons-config
ab59a8360b1d35e0509d7a0c95a96ba825ee988e
a9ee987a3d4f77bff467a9dae3f698447c226dd8
refs/heads/master
<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Authorize Request */ class AuthorizeRequest extends AbstractVerifiRequest { public function getData() { // An amount parameter is required. $this->validate('amount', 'transactionReference'); $data = array( 'amount' => $this->getAmount(), 'orderid' => $this->getTransactionReference(), 'ipaddress' => $this->getClientIp(), 'orderdescription' => '', 'type' => 'authorize' ); // A card token can be provided if the card has been stored // in the gateway. if ($this->getCardReference()) { $data['transactionid'] = $this->getCardReference(); // If no card token is provided then there must be a valid // card presented. } else { $this->validate('card'); $card = $this->getCard(); $card->validate(); $data['firstname'] = $card->getBillingFirstName(); $data['lastname'] = $card->getBillingLastName(); $data['company'] = $card->getBillingCompany(); $data['ccnumber'] = $card->getNumber(); $data['ccexp'] = $card->getExpiryDate('m/Y'); $data['cvv'] = $card->getCvv(); $data['address1'] = $card->getBillingAddress1(); $data['address2'] = $card->getBillingAddress2(); $data['city'] = $card->getBillingCity(); $data['state'] = $card->getBillingState(); $data['zip'] = $card->getBillingPostcode(); $data['country'] = $card->getBillingCountry(); $data['phone'] = $card->getBillingPhone(); $data['email'] = $card->getEmail(); } return $data; } /** * Get transaction endpoint. * * Purchases are created using the "sale" type. * * @return string */ protected function getEndpoint() { return parent::getEndpoint(); } }<file_sep><?php /** * Verifi Response */ namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractResponse; /** * Verifi Response * * This is the response class for all Verifi requests. * * @see \Omnipay\Verifi\Gateway */ class Response extends AbstractResponse { /** * Is the transaction successful? * * @return bool */ public function isSuccessful() { if ( isset($this->data['response']) && isset($this->data['response_code']) ) { return (bool)($this->data['response'] == '1' && $this->data['response_code'] == '100'); } return false; } /** * Get the transaction reference. * * @return string|null */ public function getTransactionReference() { if (isset($this->data['transactionid'])) { return $this->data['transactionid']; } return null; } /** * Get a card reference, for createCard or createCustomer requests. * * @return string|null */ public function getCardReference() { return null; } /** * Get a token, for createCard requests. * * @return string|null */ public function getToken() { if ( $this->isSuccessful() ) { return $this->data['transactionid']; } return null; } /** * Get the card data from the response. * * @return array|null */ public function getCard() { if (isset($this->data['card'])) { return $this->data['card']; } return null; } /** * Get the error message from the response. * * Returns null if the request was successful. * * @return string|null */ public function getMessage() { if ( ! $this->isSuccessful() ) { return $this->data['responsetext']; } return null; } /** * Check if subscription was successfull * * Returns null if the request was unsuccessful. * * @return string|null */ public function isSubscribed() { if ( $this->isSuccessful() && isset($this->data['subscription_id']) ) { return (bool)$this->data['subscription_id']; } return null; } /** * Get subscription id * * Returns null if the request was unsuccessful. * * @return string|null */ public function getSubscriptionId() { if ( $this->isSuccessful() && isset($this->data['subscription_id']) ) { return $this->data['subscription_id']; } return null; } }<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Create Custom Subscription Request */ class CreateCustomSubscriptionRequest extends AbstractVerifiRequest { public function getData() { $plan_amount = ( $this->getPlanAmount() ) ? $this->getPlanAmount() : $this->getAmount(); $plan_payments = ( $this->getPlanPayments() ) ? $this->getPlanPayments() : 0; $start_date = ( $this->getStartDate() ) ? $this->getStartDate() : date("Ymd"); $data = array( 'recurring' => 'add_subscription', 'plan_amount' => $this->getAmount(), 'start_date' => $start_date, 'plan_payments' => $plan_payments, 'payment' => 'creditcard', 'orderid' => $this->getTransactionReference(), ); if ( $this->getDayFrequency() && is_null($this->getMonthFrequency()) ) { $data['day_frequency'] = $this->getDayFrequency(); } if ( $this->getMonthFrequency() && $this->getDayOfMonth() ) { $data['month_frequency'] = $this->getMonthFrequency(); $data['day_of_month'] = $this->getDayOfMonth(); } if ( $this->getCustomerReceipt() ) { $data['customer_receipt'] = $this->getCustomerReceipt(); } $this->validate('card'); $card = $this->getCard(); $card->validate(); $data['first_name'] = $card->getBillingFirstName(); $data['last_name'] = $card->getBillingLastName(); $data['company'] = $card->getBillingCompany(); $data['ccnumber'] = $card->getNumber(); $data['ccexp'] = $card->getExpiryDate('m/Y'); $data['cvv'] = $card->getCvv(); $data['address1'] = $card->getBillingAddress1(); $data['address2'] = $card->getBillingAddress2(); $data['city'] = $card->getBillingCity(); $data['state'] = $card->getBillingState(); $data['zip'] = $card->getBillingPostcode(); $data['country'] = $card->getBillingCountry(); $data['phone'] = $card->getBillingPhone(); $data['email'] = $card->getEmail(); return $data; } }<file_sep><?php namespace Omnipay\Verifi; use Omnipay\Common\AbstractGateway; use Omnipay\Verifi\Message\AuthorizeRequest; /** * Verifi Gateway * * This gateway is useful for testing. It simply authorizes any payment made using a valid * credit card number and expiry. * * Any card number which passes the Luhn algorithm and ends in an even number is authorized, * for example: 4242424242424242 * * Any card number which passes the Luhn algorithm and ends in an odd number is declined, * for example: 4111111111111111 */ class Gateway extends AbstractGateway { /** * Get the gateway display name * * @return string */ public function getName() { return 'Verifi v1.0'; } /** * Get the gateway default parameters * * @return array */ public function getDefaultParameters() { return array( 'username' => '', 'password' => '', 'type' => '', 'testMode' => false ); } /** * Get the gateway username * * @return string */ public function getUsername() { return $this->getParameter('username'); } /** * Set the gateway username * * @return VerifiGateway provides a fluent interface. */ public function setUsername($value) { return $this->setParameter('username', $value); } /** * Set the getway password * * @param string password * @return string */ public function setPassword($value) { return $this->setParameter('password', $value); } /** * Get the gateway password * * @return string */ public function getPassword() { return $this->getParameter('password'); } /** * Create a authorize request. * * @param array $parameters * @return \Omnipay\Verifi\Message\AuthorizeRequest */ public function authorize(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\AuthorizeRequest', $parameters); } /** * Create a capture request. * * @param array $parameters * @return \Omnipay\Verifi\Message\CaptureRequest */ public function capture(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CaptureRequest', $parameters); } /** * Create a purchase request. * * @param array $parameters * @return \Omnipay\Verifi\Message\PurchaseRequest */ public function purchase(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\PurchaseRequest', $parameters); } /** * Refund a purchase * * @param array $parameters * @return \Omnipay\Verifi\Message\RefundRequest */ public function refund(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\RefundRequest', $parameters); } /** * Tokenize a card * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateCardRequest */ public function createCard(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CreateCardRequest', $parameters); } /** * Tokenize a card * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateCardRequest */ public function updateCard(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CreateCardRequest', $parameters); } /** * Tokenize a card * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateCardRequest */ public function void(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\VoidRequest', $parameters); } /** * Create a customer * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateCustomerRequest */ public function createCustomer(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CreateCustomerRequest', $parameters); } /** * Fetch details of a customer * * @param array $parameters * @return \Omnipay\Verifi\Message\FetchCustomerRequest */ public function fetchCustomer(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\FetchCustomerRequest', $parameters); } /** * Delete a customer * * @param array $parameters * @return \Omnipay\Verifi\Message\DeleteCustomerRequest */ public function deleteCustomer(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\DeleteCustomerRequest', $parameters); } /** * Create a subscription * * A subscription is an instance of a customer subscribing to a plan. * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateSubscriptionRequest */ public function createSubscription(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CreateSubscriptionRequest', $parameters); } /** * Create a custom subscription * * A subscription is an instance of a customer subscribing to a plan. * * @param array $parameters * @return \Omnipay\Verifi\Message\CreateCustomSubscriptionRequest */ public function createCustomSubscription(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\CreateCustomSubscriptionRequest', $parameters); } /** * Update billing information of a subscription * * @param array $parameters * @return \Omnipay\Verifi\Message\UpdateSubscriptionRequest */ public function updateSubscription(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\UpdateSubscriptionRequest', $parameters); } /** * Update billing information of a subscription * * @param array $parameters * @return \Omnipay\Verifi\Message\UpdateSubscriptionRequest */ public function deleteSubscription(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\DeleteSubscriptionRequest', $parameters); } /** * Fetch details of a customer * * @param array $parameters * @return \Omnipay\Verifi\Message\FetchCustomerRequest */ public function fetchTransaction(array $parameters = array()) { return $this->createRequest('\Omnipay\Verifi\Message\FetchTransactionRequest', $parameters); } }<file_sep># Omnipay: Verifi **Verifi driver for the Omnipay PHP payment processing library** [![Latest Stable Version](https://poser.pugx.org/pickupman/omnipay-verifi/version.png)](https://packagist.org/packages/pickupman/omnipay-verifi) [![Total Downloads](https://poser.pugx.org/pickupman/omnipay-verifi/d/total.png)](https://packagist.org/packages/pickupman/omnipay-verifi) [Omnipay](https://github.com/thephpleague/omnipay) is a framework agnostic, multi-gateway payment processing library for PHP 5.3+. This package implements Verifi support for Omnipay. ## Installation Omnipay is installed via [Composer](http://getcomposer.org/). To install, simply add it to your `composer.json` file: ```json { "require": { "pickupman/omnipay-verifi": "~1.0" } } ``` And run composer to update your dependencies: $ curl -s http://getcomposer.org/installer | php $ php composer.phar update ## Basic Usage The following gateways are provided by this package: * Verifi For general usage instructions, please see the main [Omnipay](https://github.com/thephpleague/omnipay) repository. ## Purchase / Sale For charging a card you may do the following ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); $response = $gateway->purchase( [ 'card' => $card, 'amount' => '10.00', 'clientIp' => $_SERVER['REMOTE_ADDR'], 'transactionReference' => '1', ] )->send(); if ( $response->isSuccessful() ) { // Continue processing $transactionID = $response->getTransactionReference(); } ``` ## Refund / Credit In order to process a refund, you must pass the originating transaction id returned by the gateway ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); $response = $gateway->refund( [ 'amount' => '10.00', 'transactionReference' => 'original transactionid', ] )->send(); if ( $response->isSuccessful() ) { // Continue processing $transactionID = $response->getTransactionReference(); } ``` ## Void To void an existing transaction, you must pass the originating transaction id returned by the gateway ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); $response = $gateway->void( [ 'transactionReference' => 'original transactionid', ] )->send(); if ( $response->isSuccessful() ) { // Continue processing $transactionID = $response->getTransactionReference(); } ``` ## Authorize You can authorize a credit card to verify funds, and then process the amount later. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); $response = $gateway->authorize( [ 'card' => $card, 'amount' => '10.00', 'transactionReference' => 'order id or other unique value', ] )->send(); if ( $response->isSuccessful() ) { // Continue processing $transactionID = $response->getTransactionReference(); // Use this value later to capture } ``` ## Capture Use a capture, to charge a card after retrieving an authorization ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); $response = $gateway->capture( [ 'amount' => '10.00', 'transactionReference' => 'order id or other unique value', ] )->send(); if ( $response->isSuccessful() ) { // Continue processing $transactionID = $response->getTransactionReference(); // Use this value later to capture } ``` ## Creating a Recurring Billing Subscription You can create a custom billing cycle without any plans. You will need to define the amount, and billing intervals. See Verifi documentation for supported values. All API values are supported. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); //Create a subscription $subscription = $gateway->createCustomSubscription([ 'start_date' => 'YYYYMMDD', // Defaults to current date if not passed 'plan_id' => 'valid plan id from control panel', 'card' => $card ])->send(); if ( $subscription->isSuccessful() ) { $subscriptionID = $subscription->getSubscriptionId(); // Save for later } ``` ## Create a Recurring Billing Custom Subscription You can create a custom billing cycle without any plans. You will need to define the amount, and billing intervals. See Verifi documentation for supported values. All API values are supported. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); //Create a subscription $subscription = $gateway->createCustomSubscription([ 'amount' => '25.00', 'month_frequency' => 1, // Billed monthly 'day_of_month' => 1, // on first of the month 'plan_payments' => 0, // indefinitely or cancelled 'card' => $card ])->send(); if ( $subscription->isSuccessful() ) { $subscriptionID = $subscription->getSubscriptionId(); // Save for later } ``` ## Delete a Subscription You may delete / cancel a subscription by passing the originating subscription id. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); $subscription = $gateway->deleteSubscription([ 'subscription_id' => 'subscription id here' ])->send(); ``` ## Add Customer to Vault You may add a customer and their billing information to be saved in your Verifi vault. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); $response = $gateway->createCard([ 'card' => $card ]); if ( $response->isSuccessful() ) { $vaultId = $response->getToken(); } ``` ## Update a subscription You can update the billing information for customer by passing the originating transaction id. ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setUsername('username'); $gateway->setPassword('<PASSWORD>'); // Example card data $card = new Omnipay\Common\CreditCard([ 'firstName' => 'John', 'lastName' => 'Doe', 'billingAddress1' => '888 Main', 'billingZip' => '77777', 'billingCity' => 'City', 'billingState' => 'State', 'billingPostcode' => 'Zip', 'number' => '4111111111111111', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]); $subscription = $gateway->updateSubscription([ 'subscription_id' => 'subscription id here', 'card' => $card ]); if ( $subscription->isSuccessful() ) { $subscriptionID = $subscription->getSubscriptionId(); } ``` ## Test Mode This feature will *NOT* turn on test mode for your account. Test mode must be enabled or disabled from your Verifi control panel. All transactions processed on a live account will be charged. If you would like to use the default testing credentials from Verifi, please initialize the gateway with ```php $gateway = Omnipay\Omnipay::create('Verifi'); $gateway->setTestMode(true); // Automatically sets default testing gateway username and password ``` Any transactions processed with testMode(true) will not be charged, *OR* shown in your control panel. This method will automatically apply the testing username and password for the Verifi gateway. ## Support If you are having general issues with Omnipay, we suggest posting on [Stack Overflow](http://stackoverflow.com/). Be sure to add the [omnipay tag](http://stackoverflow.com/questions/tagged/omnipay) so it can be easily found. If you want to keep up to date with release anouncements, discuss ideas for the project, or ask more detailed questions, there is also a [mailing list](https://groups.google.com/forum/#!forum/omnipay) which you can subscribe to. If you believe you have found a bug, please report it using the [GitHub issue tracker](https://github.com/pickupman/omnipay-verifi/issues), or better yet, fork the library and submit a pull request.<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Delete Subscription Request */ class FetchTransactionRequest extends AbstractVerifiRequest { public function getData() { $this->liveEndpoint = $this->queryEndpoint; // An amount parameter is required. $this->validate('transactionReference'); $data = array( 'transaction_id' => $this->getTransactionReference() ); if ( $this->getCustomerReceipt() ) { $data['customer_receipt'] = $this->getCustomerReceipt(); } return $data; } }<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Delete Subscription Request */ class DeleteSubscriptionRequest extends AbstractVerifiRequest { public function getData() { // An amount parameter is required. $this->validate('subscription_id'); $data = array( 'recurring' => 'delete_subscription', 'subscription_id' => $this->getSubscriptionId() ); if ( $this->getCustomerReceipt() ) { $data['customer_receipt'] = $this->getCustomerReceipt(); } return $data; } }<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Update Subscription Request */ class UpdateSubscriptionRequest extends AbstractVerifiRequest { public function getData() { // An amount parameter is required. $this->validate('subscription_id'); $data = array( 'recurring' => 'update_subscription', 'subscription_id' => $this->getSubscriptionId(), 'start_date' => $this->getStartDate(), 'payment' => 'creditcard', 'orderid' => $this->getTransactionReference(), ); if ( $this->getCustomerReceipt() ) { $data['customer_receipt'] = $this->getCustomerReceipt(); } if ( $this->getCard() ) { $this->validate('card'); $card = $this->getCard(); $card->validate(); $data['first_name'] = $card->getBillingFirstName(); $data['last_name'] = $card->getBillingLastName(); $data['company'] = $card->getBillingCompany(); $data['ccnumber'] = $card->getNumber(); $data['ccexp'] = $card->getExpiryDate('m/Y'); $data['cvv'] = $card->getCvv(); $data['address1'] = $card->getBillingAddress1(); $data['address2'] = $card->getBillingAddress2(); $data['city'] = $card->getBillingCity(); $data['state'] = $card->getBillingState(); $data['zip'] = $card->getBillingPostcode(); $data['country'] = $card->getBillingCountry(); $data['phone'] = $card->getBillingPhone(); $data['email'] = $card->getEmail(); } return $data; } }<file_sep><?php /** * Verifi Refund Request */ namespace Omnipay\Verifi\Message; /** * Fat Zebra REST Purchase Request * * In order to create a purchase you must submit the following details: * * * Amount (numerical) * * Reference (string - maximum 30 characters) -- this must be unique. More * than one transaction using the same Reference value will raise an error. * * * Card Token (String) * * Example: * * <code> * // Create a gateway for the Verifi Gateway * // (routes to GatewayFactory::create) * $gateway = Omnipay::create('Verifi'); * * // Initialise the gateway * $gateway->initialize(array( * 'username' => 'TEST', * 'password' => '<PASSWORD>', * 'testMode' => true, // Or false when you are ready for live transactions * )); * * // Do a purchase transaction on the gateway * $transaction = $gateway->refund(array( * 'amount' => '10.00', * 'transactionReference' => 'TestPurchaseTransaction' * )); * $response = $transaction->send(); * if ($response->isSuccessful()) { * echo "Refund transaction was successful!\n"; * $sale_id = $response->getTransactionReference(); * echo "Transaction reference = " . $sale_id . "\n"; * } * </code> * * @see Omnipay\Verifi\VerifiGateway */ class RefundRequest extends AbstractVerifiRequest { public function getData() { // An amount parameter is required. $this->validate('amount', 'transactionReference'); $data = array( 'amount' => $this->getAmount(), 'transactionid' => $this->getTransactionReference(), 'type' => 'refund', ); return $data; } /** * Get transaction endpoint. * * Purchases are created using the "sale" type. * * @return string */ protected function getEndpoint() { return parent::getEndpoint(); } }<file_sep><?php /** * Verifi Abstract XML Request */ namespace Omnipay\Verifi\Message; use Guzzle\Http\EntityBody; use Guzzle\Stream\PhpStreamRequestFactory; /** * Verifi Abstract XML Request * * This is the parent class for all Fat Zebra REST requests. * * Test modes: * * There are two test modes in the Paystream system - one is a * sandbox environment and the other is a test mode flag. * * The Sandbox Environment is an identical copy of the live environment * which is 100% functional except for communicating with the banks. * * The Test Mode Flag is used to switch the live environment into * test mode. If test: true is sent with your request your transactions * will be executed in the live environment, but not communicate with * the bank backends. This mode is useful for testing changes to your * live website. * * Currently this class makes the assumption that if the testMode * flag is set then the Sandbox Environment is being used. * * @see \Omnipay\Verifi\VerifiGateway */ abstract class AbstractVerifiRequest extends \Omnipay\Common\Message\AbstractRequest { const API_VERSION = 'v1.0'; /** * Sandbox Endpoint URL * * @var string URL */ protected $testEndpoint = 'https://secure.verifi.com/gw/api/transact.php'; /** * Live Endpoint URL * * @var string URL */ protected $liveEndpoint = 'https://secure.verifi.com/gw/api/transact.php'; /** * Query API Endpoint URL * * @var string URL */ protected $queryEndpoint = 'https://secure.verifi.com/api/query.php'; /** * Get HTTP Method. * * This is nearly always POST but can be over-ridden in sub classes. * * @return string */ protected function getHttpMethod() { return 'POST'; } /** * Get API endpoint URL * * @return string */ protected function getEndpoint() { $base = $this->getTestMode() ? $this->testEndpoint : $this->liveEndpoint; return $base; } protected function setEndpoint($value) { } /** * Get the gateway username * * @return string */ public function getUsername() { return $this->getParameter('username'); } /** * Set the gateway username * * @return AbstractRestRequest provides a fluent interface. */ public function setUsername($value) { return $this->setParameter('username', $value); } /** * Get the gateway password * * @return string */ public function getPassword() { return $this->getParameter('password'); } /** * Set the gateway password * * @return string */ public function setPassword($value) { return $this->setParameter('password', $value); } /** * Get the level of continuity for recurring billing * * @return string */ public function getLevelOfContinuity() { return $this->getParameter('level_of_continuity'); } /** * Set the level of continuity for recurring billing * * @param string */ public function setLevelOfContinuity($value) { return $this->setParameter('level_of_continuity', $value); } /** * Get the subscription plan id * * @param string */ public function getPlanId($value) { return $this->getParameter('plan_id'); } /** * Set the subscription plan id * * @param string */ public function setPlanId($value) { return $this->setParameter('plan_id', $value); } /** * Get the start date for a subscription * * @param string YYYYMMDD */ public function getStartDate() { return $this->getParameter('start_date', date("Ymd")); } /** * Set the start date for a subscription * * @param string YYYYMMDD */ public function setStartDate($value) { return $this->setParameter('start_date', $value); } /** * Get the send customer receipt flag * * @param string */ public function getCustomerReceipt() { return $this->getParameter('customer_receipt'); } /** * Set the send customer receipt flag * * @param string */ public function setCustomerReceipt($value) { return $this->setParameter('customer_receipt', $value); } /** * Get the number of plan payments * Defaults to 0 = billed until cancelled * * @param string */ public function getPlanPayments() { return $this->getParameter('plan_payments', '0'); } /** * Set the number of payments the customer will be bill * Passing "0" will bill customer until canceled. * * @param string */ public function setPlanPayments($value) { return $this->setParameter('plan_payments', $value); } /** * Get the plan amount that will be billed * * @param string */ public function getPlanAmount() { return $this->getParameter('plan_amount'); } /** * Set the plan amount customer will be billed each cycle * * @param string */ public function setPlanAmount($value) { return $this->setParameter('plan_amount', $value); } /** * Get the daily frequency billing option * * @param string */ public function getDayFrequency() { return $this->getParameter('day_frequency'); } /** * Set the billing frequency on a daily schedule * NOT to be used with month_frequency * * @param string */ public function setDayFrequency($value) { return $this->setParameter('day_frequency', $value); } /** * Get the monthly billing frequency * * @param string */ public function getMonthFrequency() { return $this->getParameter('month_frequency'); } /** * Set the monthly billing frequency * NOT to be used with day_frequency * Valid values are 1 - 24 * * @param string */ public function setMonthFrequency($value) { return $this->setParameter('month_frequency', $value); } /** * Get the day of the month billing will occur on * * @param string */ public function getDayOfMonth() { return $this->getParameter('day_of_month'); } /** * Set the day of the month billing will occur on * USED with month_frequency * Valid values are 1 - 31. If value is greater than the number * of days in a month, billing will occur on last day of that month * * @param string */ public function setDayOfMonth($value) { return $this->setParameter('day_of_month', $value); } /** * Get the subscription id * * @param string */ public function getSubscriptionId() { return $this->getParameter('subscription_id'); } /** * Set the subscription id * * @param string */ public function setSubscriptionId($value) { return $this->setParameter('subscription_id', $value); } public function getTransactionId() { return $this->getParameter('transactionReference'); } /** * Process request * * @return mixed */ public function sendData($data) { if ( true == $this->getParameter('testMode') ) { $data['username'] = 'demo'; $data['password'] = '<PASSWORD>'; } else { $data['username'] = $this->getUsername(); $data['password'] = $<PASSWORD>(); } // don't throw exceptions for 4xx errors $this->httpClient->getEventDispatcher()->addListener( 'request.error', function ($event) { if ($event['response']->isClientError()) { $event->stopPropagation(); } } ); $httpRequest = $this->httpClient->createRequest( $this->getHttpMethod(), $this->getEndpoint(), null, $data ); // Might be useful to have some debug code here. Perhaps hook to whatever // logging engine is being used. // echo "Data == " . json_encode($data) . "\n"; //$httpResponse = $httpRequest->send(); $factory = new PhpStreamRequestFactory(); $stream = $factory->fromRequest($httpRequest); // Read until the stream is closed while (!$stream->feof()) { // Read a line from the stream $line = $stream->readLine(); // JSON decode the line of data } parse_str($line, $output); return $this->response = new Response($this, $output, $factory->getLastResponseHeaders()); } }<file_sep><?php namespace Omnipay\Verifi\Message; use Omnipay\Common\Message\AbstractRequest; /** * Verifi Capture Request */ class CaptureRequest extends AbstractVerifiRequest { public function getData() { // An amount parameter is required. $this->validate('amount', 'transactionReference'); $data = array( 'amount' => $this->getAmount(), 'transactionid' => $this->getTransactionReference(), 'type' => 'capture' ); return $data; } /** * Get transaction endpoint. * * Purchases are created using the "sale" type. * * @return string */ protected function getEndpoint() { return parent::getEndpoint(); } }
f0a7992d8c2dcb6b087c2d982ac3552883f0ce35
[ "Markdown", "PHP" ]
11
PHP
pickupman/omnipay-verifi
4b2da03c721853a0a19b91f9375f46de82efac0a
e721e3a61a33af0d1738de6ca78ecff79149cb37